Merge tag 'for_linus' of git://git.kernel.org/pub/scm/linux/kernel/git/mst/vhost
[cris-mirror.git] / arch / x86 / kvm / vmx.c
blob051dab74e4e928ac7bf90598c0b9a9a8d8855f13
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/moduleparam.h>
31 #include <linux/mod_devicetable.h>
32 #include <linux/trace_events.h>
33 #include <linux/slab.h>
34 #include <linux/tboot.h>
35 #include <linux/hrtimer.h>
36 #include <linux/frame.h>
37 #include <linux/nospec.h>
38 #include "kvm_cache_regs.h"
39 #include "x86.h"
41 #include <asm/cpu.h>
42 #include <asm/io.h>
43 #include <asm/desc.h>
44 #include <asm/vmx.h>
45 #include <asm/virtext.h>
46 #include <asm/mce.h>
47 #include <asm/fpu/internal.h>
48 #include <asm/perf_event.h>
49 #include <asm/debugreg.h>
50 #include <asm/kexec.h>
51 #include <asm/apic.h>
52 #include <asm/irq_remapping.h>
53 #include <asm/mmu_context.h>
54 #include <asm/microcode.h>
55 #include <asm/nospec-branch.h>
57 #include "trace.h"
58 #include "pmu.h"
60 #define __ex(x) __kvm_handle_fault_on_reboot(x)
61 #define __ex_clear(x, reg) \
62 ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
64 MODULE_AUTHOR("Qumranet");
65 MODULE_LICENSE("GPL");
67 static const struct x86_cpu_id vmx_cpu_id[] = {
68 X86_FEATURE_MATCH(X86_FEATURE_VMX),
71 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
73 static bool __read_mostly enable_vpid = 1;
74 module_param_named(vpid, enable_vpid, bool, 0444);
76 static bool __read_mostly enable_vnmi = 1;
77 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
79 static bool __read_mostly flexpriority_enabled = 1;
80 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
82 static bool __read_mostly enable_ept = 1;
83 module_param_named(ept, enable_ept, bool, S_IRUGO);
85 static bool __read_mostly enable_unrestricted_guest = 1;
86 module_param_named(unrestricted_guest,
87 enable_unrestricted_guest, bool, S_IRUGO);
89 static bool __read_mostly enable_ept_ad_bits = 1;
90 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
92 static bool __read_mostly emulate_invalid_guest_state = true;
93 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
95 static bool __read_mostly fasteoi = 1;
96 module_param(fasteoi, bool, S_IRUGO);
98 static bool __read_mostly enable_apicv = 1;
99 module_param(enable_apicv, bool, S_IRUGO);
101 static bool __read_mostly enable_shadow_vmcs = 1;
102 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
104 * If nested=1, nested virtualization is supported, i.e., guests may use
105 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
106 * use VMX instructions.
108 static bool __read_mostly nested = 0;
109 module_param(nested, bool, S_IRUGO);
111 static u64 __read_mostly host_xss;
113 static bool __read_mostly enable_pml = 1;
114 module_param_named(pml, enable_pml, bool, S_IRUGO);
116 #define MSR_TYPE_R 1
117 #define MSR_TYPE_W 2
118 #define MSR_TYPE_RW 3
120 #define MSR_BITMAP_MODE_X2APIC 1
121 #define MSR_BITMAP_MODE_X2APIC_APICV 2
122 #define MSR_BITMAP_MODE_LM 4
124 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
126 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
127 static int __read_mostly cpu_preemption_timer_multi;
128 static bool __read_mostly enable_preemption_timer = 1;
129 #ifdef CONFIG_X86_64
130 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
131 #endif
133 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
134 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
135 #define KVM_VM_CR0_ALWAYS_ON \
136 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
137 #define KVM_CR4_GUEST_OWNED_BITS \
138 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
139 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
141 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
142 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
144 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
146 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
149 * Hyper-V requires all of these, so mark them as supported even though
150 * they are just treated the same as all-context.
152 #define VMX_VPID_EXTENT_SUPPORTED_MASK \
153 (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
154 VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
155 VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
156 VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
159 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
160 * ple_gap: upper bound on the amount of time between two successive
161 * executions of PAUSE in a loop. Also indicate if ple enabled.
162 * According to test, this time is usually smaller than 128 cycles.
163 * ple_window: upper bound on the amount of time a guest is allowed to execute
164 * in a PAUSE loop. Tests indicate that most spinlocks are held for
165 * less than 2^12 cycles
166 * Time is measured based on a counter that runs at the same rate as the TSC,
167 * refer SDM volume 3b section 21.6.13 & 22.1.3.
169 #define KVM_VMX_DEFAULT_PLE_GAP 128
170 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
171 #define KVM_VMX_DEFAULT_PLE_WINDOW_GROW 2
172 #define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
173 #define KVM_VMX_DEFAULT_PLE_WINDOW_MAX \
174 INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
176 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
177 module_param(ple_gap, int, S_IRUGO);
179 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
180 module_param(ple_window, int, S_IRUGO);
182 /* Default doubles per-vcpu window every exit. */
183 static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
184 module_param(ple_window_grow, int, S_IRUGO);
186 /* Default resets per-vcpu window every exit to ple_window. */
187 static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
188 module_param(ple_window_shrink, int, S_IRUGO);
190 /* Default is to compute the maximum so we can never overflow. */
191 static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
192 static int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
193 module_param(ple_window_max, int, S_IRUGO);
195 extern const ulong vmx_return;
197 #define NR_AUTOLOAD_MSRS 8
199 struct vmcs {
200 u32 revision_id;
201 u32 abort;
202 char data[0];
206 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
207 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
208 * loaded on this CPU (so we can clear them if the CPU goes down).
210 struct loaded_vmcs {
211 struct vmcs *vmcs;
212 struct vmcs *shadow_vmcs;
213 int cpu;
214 bool launched;
215 bool nmi_known_unmasked;
216 unsigned long vmcs_host_cr3; /* May not match real cr3 */
217 unsigned long vmcs_host_cr4; /* May not match real cr4 */
218 /* Support for vnmi-less CPUs */
219 int soft_vnmi_blocked;
220 ktime_t entry_time;
221 s64 vnmi_blocked_time;
222 unsigned long *msr_bitmap;
223 struct list_head loaded_vmcss_on_cpu_link;
226 struct shared_msr_entry {
227 unsigned index;
228 u64 data;
229 u64 mask;
233 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
234 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
235 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
236 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
237 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
238 * More than one of these structures may exist, if L1 runs multiple L2 guests.
239 * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
240 * underlying hardware which will be used to run L2.
241 * This structure is packed to ensure that its layout is identical across
242 * machines (necessary for live migration).
243 * If there are changes in this struct, VMCS12_REVISION must be changed.
245 typedef u64 natural_width;
246 struct __packed vmcs12 {
247 /* According to the Intel spec, a VMCS region must start with the
248 * following two fields. Then follow implementation-specific data.
250 u32 revision_id;
251 u32 abort;
253 u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
254 u32 padding[7]; /* room for future expansion */
256 u64 io_bitmap_a;
257 u64 io_bitmap_b;
258 u64 msr_bitmap;
259 u64 vm_exit_msr_store_addr;
260 u64 vm_exit_msr_load_addr;
261 u64 vm_entry_msr_load_addr;
262 u64 tsc_offset;
263 u64 virtual_apic_page_addr;
264 u64 apic_access_addr;
265 u64 posted_intr_desc_addr;
266 u64 vm_function_control;
267 u64 ept_pointer;
268 u64 eoi_exit_bitmap0;
269 u64 eoi_exit_bitmap1;
270 u64 eoi_exit_bitmap2;
271 u64 eoi_exit_bitmap3;
272 u64 eptp_list_address;
273 u64 xss_exit_bitmap;
274 u64 guest_physical_address;
275 u64 vmcs_link_pointer;
276 u64 pml_address;
277 u64 guest_ia32_debugctl;
278 u64 guest_ia32_pat;
279 u64 guest_ia32_efer;
280 u64 guest_ia32_perf_global_ctrl;
281 u64 guest_pdptr0;
282 u64 guest_pdptr1;
283 u64 guest_pdptr2;
284 u64 guest_pdptr3;
285 u64 guest_bndcfgs;
286 u64 host_ia32_pat;
287 u64 host_ia32_efer;
288 u64 host_ia32_perf_global_ctrl;
289 u64 padding64[8]; /* room for future expansion */
291 * To allow migration of L1 (complete with its L2 guests) between
292 * machines of different natural widths (32 or 64 bit), we cannot have
293 * unsigned long fields with no explict size. We use u64 (aliased
294 * natural_width) instead. Luckily, x86 is little-endian.
296 natural_width cr0_guest_host_mask;
297 natural_width cr4_guest_host_mask;
298 natural_width cr0_read_shadow;
299 natural_width cr4_read_shadow;
300 natural_width cr3_target_value0;
301 natural_width cr3_target_value1;
302 natural_width cr3_target_value2;
303 natural_width cr3_target_value3;
304 natural_width exit_qualification;
305 natural_width guest_linear_address;
306 natural_width guest_cr0;
307 natural_width guest_cr3;
308 natural_width guest_cr4;
309 natural_width guest_es_base;
310 natural_width guest_cs_base;
311 natural_width guest_ss_base;
312 natural_width guest_ds_base;
313 natural_width guest_fs_base;
314 natural_width guest_gs_base;
315 natural_width guest_ldtr_base;
316 natural_width guest_tr_base;
317 natural_width guest_gdtr_base;
318 natural_width guest_idtr_base;
319 natural_width guest_dr7;
320 natural_width guest_rsp;
321 natural_width guest_rip;
322 natural_width guest_rflags;
323 natural_width guest_pending_dbg_exceptions;
324 natural_width guest_sysenter_esp;
325 natural_width guest_sysenter_eip;
326 natural_width host_cr0;
327 natural_width host_cr3;
328 natural_width host_cr4;
329 natural_width host_fs_base;
330 natural_width host_gs_base;
331 natural_width host_tr_base;
332 natural_width host_gdtr_base;
333 natural_width host_idtr_base;
334 natural_width host_ia32_sysenter_esp;
335 natural_width host_ia32_sysenter_eip;
336 natural_width host_rsp;
337 natural_width host_rip;
338 natural_width paddingl[8]; /* room for future expansion */
339 u32 pin_based_vm_exec_control;
340 u32 cpu_based_vm_exec_control;
341 u32 exception_bitmap;
342 u32 page_fault_error_code_mask;
343 u32 page_fault_error_code_match;
344 u32 cr3_target_count;
345 u32 vm_exit_controls;
346 u32 vm_exit_msr_store_count;
347 u32 vm_exit_msr_load_count;
348 u32 vm_entry_controls;
349 u32 vm_entry_msr_load_count;
350 u32 vm_entry_intr_info_field;
351 u32 vm_entry_exception_error_code;
352 u32 vm_entry_instruction_len;
353 u32 tpr_threshold;
354 u32 secondary_vm_exec_control;
355 u32 vm_instruction_error;
356 u32 vm_exit_reason;
357 u32 vm_exit_intr_info;
358 u32 vm_exit_intr_error_code;
359 u32 idt_vectoring_info_field;
360 u32 idt_vectoring_error_code;
361 u32 vm_exit_instruction_len;
362 u32 vmx_instruction_info;
363 u32 guest_es_limit;
364 u32 guest_cs_limit;
365 u32 guest_ss_limit;
366 u32 guest_ds_limit;
367 u32 guest_fs_limit;
368 u32 guest_gs_limit;
369 u32 guest_ldtr_limit;
370 u32 guest_tr_limit;
371 u32 guest_gdtr_limit;
372 u32 guest_idtr_limit;
373 u32 guest_es_ar_bytes;
374 u32 guest_cs_ar_bytes;
375 u32 guest_ss_ar_bytes;
376 u32 guest_ds_ar_bytes;
377 u32 guest_fs_ar_bytes;
378 u32 guest_gs_ar_bytes;
379 u32 guest_ldtr_ar_bytes;
380 u32 guest_tr_ar_bytes;
381 u32 guest_interruptibility_info;
382 u32 guest_activity_state;
383 u32 guest_sysenter_cs;
384 u32 host_ia32_sysenter_cs;
385 u32 vmx_preemption_timer_value;
386 u32 padding32[7]; /* room for future expansion */
387 u16 virtual_processor_id;
388 u16 posted_intr_nv;
389 u16 guest_es_selector;
390 u16 guest_cs_selector;
391 u16 guest_ss_selector;
392 u16 guest_ds_selector;
393 u16 guest_fs_selector;
394 u16 guest_gs_selector;
395 u16 guest_ldtr_selector;
396 u16 guest_tr_selector;
397 u16 guest_intr_status;
398 u16 guest_pml_index;
399 u16 host_es_selector;
400 u16 host_cs_selector;
401 u16 host_ss_selector;
402 u16 host_ds_selector;
403 u16 host_fs_selector;
404 u16 host_gs_selector;
405 u16 host_tr_selector;
409 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
410 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
411 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
413 #define VMCS12_REVISION 0x11e57ed0
416 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
417 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
418 * current implementation, 4K are reserved to avoid future complications.
420 #define VMCS12_SIZE 0x1000
423 * VMCS12_MAX_FIELD_INDEX is the highest index value used in any
424 * supported VMCS12 field encoding.
426 #define VMCS12_MAX_FIELD_INDEX 0x17
429 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
430 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
432 struct nested_vmx {
433 /* Has the level1 guest done vmxon? */
434 bool vmxon;
435 gpa_t vmxon_ptr;
436 bool pml_full;
438 /* The guest-physical address of the current VMCS L1 keeps for L2 */
439 gpa_t current_vmptr;
441 * Cache of the guest's VMCS, existing outside of guest memory.
442 * Loaded from guest memory during VMPTRLD. Flushed to guest
443 * memory during VMCLEAR and VMPTRLD.
445 struct vmcs12 *cached_vmcs12;
447 * Indicates if the shadow vmcs must be updated with the
448 * data hold by vmcs12
450 bool sync_shadow_vmcs;
451 bool dirty_vmcs12;
453 bool change_vmcs01_virtual_x2apic_mode;
454 /* L2 must run next, and mustn't decide to exit to L1. */
455 bool nested_run_pending;
457 struct loaded_vmcs vmcs02;
460 * Guest pages referred to in the vmcs02 with host-physical
461 * pointers, so we must keep them pinned while L2 runs.
463 struct page *apic_access_page;
464 struct page *virtual_apic_page;
465 struct page *pi_desc_page;
466 struct pi_desc *pi_desc;
467 bool pi_pending;
468 u16 posted_intr_nv;
470 struct hrtimer preemption_timer;
471 bool preemption_timer_expired;
473 /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
474 u64 vmcs01_debugctl;
476 u16 vpid02;
477 u16 last_vpid;
480 * We only store the "true" versions of the VMX capability MSRs. We
481 * generate the "non-true" versions by setting the must-be-1 bits
482 * according to the SDM.
484 u32 nested_vmx_procbased_ctls_low;
485 u32 nested_vmx_procbased_ctls_high;
486 u32 nested_vmx_secondary_ctls_low;
487 u32 nested_vmx_secondary_ctls_high;
488 u32 nested_vmx_pinbased_ctls_low;
489 u32 nested_vmx_pinbased_ctls_high;
490 u32 nested_vmx_exit_ctls_low;
491 u32 nested_vmx_exit_ctls_high;
492 u32 nested_vmx_entry_ctls_low;
493 u32 nested_vmx_entry_ctls_high;
494 u32 nested_vmx_misc_low;
495 u32 nested_vmx_misc_high;
496 u32 nested_vmx_ept_caps;
497 u32 nested_vmx_vpid_caps;
498 u64 nested_vmx_basic;
499 u64 nested_vmx_cr0_fixed0;
500 u64 nested_vmx_cr0_fixed1;
501 u64 nested_vmx_cr4_fixed0;
502 u64 nested_vmx_cr4_fixed1;
503 u64 nested_vmx_vmcs_enum;
504 u64 nested_vmx_vmfunc_controls;
506 /* SMM related state */
507 struct {
508 /* in VMX operation on SMM entry? */
509 bool vmxon;
510 /* in guest mode on SMM entry? */
511 bool guest_mode;
512 } smm;
515 #define POSTED_INTR_ON 0
516 #define POSTED_INTR_SN 1
518 /* Posted-Interrupt Descriptor */
519 struct pi_desc {
520 u32 pir[8]; /* Posted interrupt requested */
521 union {
522 struct {
523 /* bit 256 - Outstanding Notification */
524 u16 on : 1,
525 /* bit 257 - Suppress Notification */
526 sn : 1,
527 /* bit 271:258 - Reserved */
528 rsvd_1 : 14;
529 /* bit 279:272 - Notification Vector */
530 u8 nv;
531 /* bit 287:280 - Reserved */
532 u8 rsvd_2;
533 /* bit 319:288 - Notification Destination */
534 u32 ndst;
536 u64 control;
538 u32 rsvd[6];
539 } __aligned(64);
541 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
543 return test_and_set_bit(POSTED_INTR_ON,
544 (unsigned long *)&pi_desc->control);
547 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
549 return test_and_clear_bit(POSTED_INTR_ON,
550 (unsigned long *)&pi_desc->control);
553 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
555 return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
558 static inline void pi_clear_sn(struct pi_desc *pi_desc)
560 return clear_bit(POSTED_INTR_SN,
561 (unsigned long *)&pi_desc->control);
564 static inline void pi_set_sn(struct pi_desc *pi_desc)
566 return set_bit(POSTED_INTR_SN,
567 (unsigned long *)&pi_desc->control);
570 static inline void pi_clear_on(struct pi_desc *pi_desc)
572 clear_bit(POSTED_INTR_ON,
573 (unsigned long *)&pi_desc->control);
576 static inline int pi_test_on(struct pi_desc *pi_desc)
578 return test_bit(POSTED_INTR_ON,
579 (unsigned long *)&pi_desc->control);
582 static inline int pi_test_sn(struct pi_desc *pi_desc)
584 return test_bit(POSTED_INTR_SN,
585 (unsigned long *)&pi_desc->control);
588 struct vcpu_vmx {
589 struct kvm_vcpu vcpu;
590 unsigned long host_rsp;
591 u8 fail;
592 u8 msr_bitmap_mode;
593 u32 exit_intr_info;
594 u32 idt_vectoring_info;
595 ulong rflags;
596 struct shared_msr_entry *guest_msrs;
597 int nmsrs;
598 int save_nmsrs;
599 unsigned long host_idt_base;
600 #ifdef CONFIG_X86_64
601 u64 msr_host_kernel_gs_base;
602 u64 msr_guest_kernel_gs_base;
603 #endif
605 u64 arch_capabilities;
606 u64 spec_ctrl;
608 u32 vm_entry_controls_shadow;
609 u32 vm_exit_controls_shadow;
610 u32 secondary_exec_control;
613 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
614 * non-nested (L1) guest, it always points to vmcs01. For a nested
615 * guest (L2), it points to a different VMCS.
617 struct loaded_vmcs vmcs01;
618 struct loaded_vmcs *loaded_vmcs;
619 bool __launched; /* temporary, used in vmx_vcpu_run */
620 struct msr_autoload {
621 unsigned nr;
622 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
623 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
624 } msr_autoload;
625 struct {
626 int loaded;
627 u16 fs_sel, gs_sel, ldt_sel;
628 #ifdef CONFIG_X86_64
629 u16 ds_sel, es_sel;
630 #endif
631 int gs_ldt_reload_needed;
632 int fs_reload_needed;
633 u64 msr_host_bndcfgs;
634 } host_state;
635 struct {
636 int vm86_active;
637 ulong save_rflags;
638 struct kvm_segment segs[8];
639 } rmode;
640 struct {
641 u32 bitmask; /* 4 bits per segment (1 bit per field) */
642 struct kvm_save_segment {
643 u16 selector;
644 unsigned long base;
645 u32 limit;
646 u32 ar;
647 } seg[8];
648 } segment_cache;
649 int vpid;
650 bool emulation_required;
652 u32 exit_reason;
654 /* Posted interrupt descriptor */
655 struct pi_desc pi_desc;
657 /* Support for a guest hypervisor (nested VMX) */
658 struct nested_vmx nested;
660 /* Dynamic PLE window. */
661 int ple_window;
662 bool ple_window_dirty;
664 /* Support for PML */
665 #define PML_ENTITY_NUM 512
666 struct page *pml_pg;
668 /* apic deadline value in host tsc */
669 u64 hv_deadline_tsc;
671 u64 current_tsc_ratio;
673 u32 host_pkru;
675 unsigned long host_debugctlmsr;
678 * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
679 * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
680 * in msr_ia32_feature_control_valid_bits.
682 u64 msr_ia32_feature_control;
683 u64 msr_ia32_feature_control_valid_bits;
686 enum segment_cache_field {
687 SEG_FIELD_SEL = 0,
688 SEG_FIELD_BASE = 1,
689 SEG_FIELD_LIMIT = 2,
690 SEG_FIELD_AR = 3,
692 SEG_FIELD_NR = 4
695 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
697 return container_of(vcpu, struct vcpu_vmx, vcpu);
700 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
702 return &(to_vmx(vcpu)->pi_desc);
705 #define ROL16(val, n) ((u16)(((u16)(val) << (n)) | ((u16)(val) >> (16 - (n)))))
706 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
707 #define FIELD(number, name) [ROL16(number, 6)] = VMCS12_OFFSET(name)
708 #define FIELD64(number, name) \
709 FIELD(number, name), \
710 [ROL16(number##_HIGH, 6)] = VMCS12_OFFSET(name) + sizeof(u32)
713 static u16 shadow_read_only_fields[] = {
714 #define SHADOW_FIELD_RO(x) x,
715 #include "vmx_shadow_fields.h"
717 static int max_shadow_read_only_fields =
718 ARRAY_SIZE(shadow_read_only_fields);
720 static u16 shadow_read_write_fields[] = {
721 #define SHADOW_FIELD_RW(x) x,
722 #include "vmx_shadow_fields.h"
724 static int max_shadow_read_write_fields =
725 ARRAY_SIZE(shadow_read_write_fields);
727 static const unsigned short vmcs_field_to_offset_table[] = {
728 FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
729 FIELD(POSTED_INTR_NV, posted_intr_nv),
730 FIELD(GUEST_ES_SELECTOR, guest_es_selector),
731 FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
732 FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
733 FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
734 FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
735 FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
736 FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
737 FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
738 FIELD(GUEST_INTR_STATUS, guest_intr_status),
739 FIELD(GUEST_PML_INDEX, guest_pml_index),
740 FIELD(HOST_ES_SELECTOR, host_es_selector),
741 FIELD(HOST_CS_SELECTOR, host_cs_selector),
742 FIELD(HOST_SS_SELECTOR, host_ss_selector),
743 FIELD(HOST_DS_SELECTOR, host_ds_selector),
744 FIELD(HOST_FS_SELECTOR, host_fs_selector),
745 FIELD(HOST_GS_SELECTOR, host_gs_selector),
746 FIELD(HOST_TR_SELECTOR, host_tr_selector),
747 FIELD64(IO_BITMAP_A, io_bitmap_a),
748 FIELD64(IO_BITMAP_B, io_bitmap_b),
749 FIELD64(MSR_BITMAP, msr_bitmap),
750 FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
751 FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
752 FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
753 FIELD64(TSC_OFFSET, tsc_offset),
754 FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
755 FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
756 FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
757 FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
758 FIELD64(EPT_POINTER, ept_pointer),
759 FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
760 FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
761 FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
762 FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
763 FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
764 FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
765 FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
766 FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
767 FIELD64(PML_ADDRESS, pml_address),
768 FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
769 FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
770 FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
771 FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
772 FIELD64(GUEST_PDPTR0, guest_pdptr0),
773 FIELD64(GUEST_PDPTR1, guest_pdptr1),
774 FIELD64(GUEST_PDPTR2, guest_pdptr2),
775 FIELD64(GUEST_PDPTR3, guest_pdptr3),
776 FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
777 FIELD64(HOST_IA32_PAT, host_ia32_pat),
778 FIELD64(HOST_IA32_EFER, host_ia32_efer),
779 FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
780 FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
781 FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
782 FIELD(EXCEPTION_BITMAP, exception_bitmap),
783 FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
784 FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
785 FIELD(CR3_TARGET_COUNT, cr3_target_count),
786 FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
787 FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
788 FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
789 FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
790 FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
791 FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
792 FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
793 FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
794 FIELD(TPR_THRESHOLD, tpr_threshold),
795 FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
796 FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
797 FIELD(VM_EXIT_REASON, vm_exit_reason),
798 FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
799 FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
800 FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
801 FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
802 FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
803 FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
804 FIELD(GUEST_ES_LIMIT, guest_es_limit),
805 FIELD(GUEST_CS_LIMIT, guest_cs_limit),
806 FIELD(GUEST_SS_LIMIT, guest_ss_limit),
807 FIELD(GUEST_DS_LIMIT, guest_ds_limit),
808 FIELD(GUEST_FS_LIMIT, guest_fs_limit),
809 FIELD(GUEST_GS_LIMIT, guest_gs_limit),
810 FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
811 FIELD(GUEST_TR_LIMIT, guest_tr_limit),
812 FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
813 FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
814 FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
815 FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
816 FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
817 FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
818 FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
819 FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
820 FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
821 FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
822 FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
823 FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
824 FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
825 FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
826 FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
827 FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
828 FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
829 FIELD(CR0_READ_SHADOW, cr0_read_shadow),
830 FIELD(CR4_READ_SHADOW, cr4_read_shadow),
831 FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
832 FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
833 FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
834 FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
835 FIELD(EXIT_QUALIFICATION, exit_qualification),
836 FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
837 FIELD(GUEST_CR0, guest_cr0),
838 FIELD(GUEST_CR3, guest_cr3),
839 FIELD(GUEST_CR4, guest_cr4),
840 FIELD(GUEST_ES_BASE, guest_es_base),
841 FIELD(GUEST_CS_BASE, guest_cs_base),
842 FIELD(GUEST_SS_BASE, guest_ss_base),
843 FIELD(GUEST_DS_BASE, guest_ds_base),
844 FIELD(GUEST_FS_BASE, guest_fs_base),
845 FIELD(GUEST_GS_BASE, guest_gs_base),
846 FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
847 FIELD(GUEST_TR_BASE, guest_tr_base),
848 FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
849 FIELD(GUEST_IDTR_BASE, guest_idtr_base),
850 FIELD(GUEST_DR7, guest_dr7),
851 FIELD(GUEST_RSP, guest_rsp),
852 FIELD(GUEST_RIP, guest_rip),
853 FIELD(GUEST_RFLAGS, guest_rflags),
854 FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
855 FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
856 FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
857 FIELD(HOST_CR0, host_cr0),
858 FIELD(HOST_CR3, host_cr3),
859 FIELD(HOST_CR4, host_cr4),
860 FIELD(HOST_FS_BASE, host_fs_base),
861 FIELD(HOST_GS_BASE, host_gs_base),
862 FIELD(HOST_TR_BASE, host_tr_base),
863 FIELD(HOST_GDTR_BASE, host_gdtr_base),
864 FIELD(HOST_IDTR_BASE, host_idtr_base),
865 FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
866 FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
867 FIELD(HOST_RSP, host_rsp),
868 FIELD(HOST_RIP, host_rip),
871 static inline short vmcs_field_to_offset(unsigned long field)
873 const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
874 unsigned short offset;
875 unsigned index;
877 if (field >> 15)
878 return -ENOENT;
880 index = ROL16(field, 6);
881 if (index >= size)
882 return -ENOENT;
884 index = array_index_nospec(index, size);
885 offset = vmcs_field_to_offset_table[index];
886 if (offset == 0)
887 return -ENOENT;
888 return offset;
891 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
893 return to_vmx(vcpu)->nested.cached_vmcs12;
896 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
897 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
898 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
899 static bool vmx_xsaves_supported(void);
900 static void vmx_set_segment(struct kvm_vcpu *vcpu,
901 struct kvm_segment *var, int seg);
902 static void vmx_get_segment(struct kvm_vcpu *vcpu,
903 struct kvm_segment *var, int seg);
904 static bool guest_state_valid(struct kvm_vcpu *vcpu);
905 static u32 vmx_segment_access_rights(struct kvm_segment *var);
906 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
907 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
908 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
909 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
910 u16 error_code);
911 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
912 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
913 u32 msr, int type);
915 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
916 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
918 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
919 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
921 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
924 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
925 * can find which vCPU should be waken up.
927 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
928 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
930 enum {
931 VMX_VMREAD_BITMAP,
932 VMX_VMWRITE_BITMAP,
933 VMX_BITMAP_NR
936 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
938 #define vmx_vmread_bitmap (vmx_bitmap[VMX_VMREAD_BITMAP])
939 #define vmx_vmwrite_bitmap (vmx_bitmap[VMX_VMWRITE_BITMAP])
941 static bool cpu_has_load_ia32_efer;
942 static bool cpu_has_load_perf_global_ctrl;
944 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
945 static DEFINE_SPINLOCK(vmx_vpid_lock);
947 static struct vmcs_config {
948 int size;
949 int order;
950 u32 basic_cap;
951 u32 revision_id;
952 u32 pin_based_exec_ctrl;
953 u32 cpu_based_exec_ctrl;
954 u32 cpu_based_2nd_exec_ctrl;
955 u32 vmexit_ctrl;
956 u32 vmentry_ctrl;
957 } vmcs_config;
959 static struct vmx_capability {
960 u32 ept;
961 u32 vpid;
962 } vmx_capability;
964 #define VMX_SEGMENT_FIELD(seg) \
965 [VCPU_SREG_##seg] = { \
966 .selector = GUEST_##seg##_SELECTOR, \
967 .base = GUEST_##seg##_BASE, \
968 .limit = GUEST_##seg##_LIMIT, \
969 .ar_bytes = GUEST_##seg##_AR_BYTES, \
972 static const struct kvm_vmx_segment_field {
973 unsigned selector;
974 unsigned base;
975 unsigned limit;
976 unsigned ar_bytes;
977 } kvm_vmx_segment_fields[] = {
978 VMX_SEGMENT_FIELD(CS),
979 VMX_SEGMENT_FIELD(DS),
980 VMX_SEGMENT_FIELD(ES),
981 VMX_SEGMENT_FIELD(FS),
982 VMX_SEGMENT_FIELD(GS),
983 VMX_SEGMENT_FIELD(SS),
984 VMX_SEGMENT_FIELD(TR),
985 VMX_SEGMENT_FIELD(LDTR),
988 static u64 host_efer;
990 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
993 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
994 * away by decrementing the array size.
996 static const u32 vmx_msr_index[] = {
997 #ifdef CONFIG_X86_64
998 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
999 #endif
1000 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1003 static inline bool is_exception_n(u32 intr_info, u8 vector)
1005 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1006 INTR_INFO_VALID_MASK)) ==
1007 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1010 static inline bool is_debug(u32 intr_info)
1012 return is_exception_n(intr_info, DB_VECTOR);
1015 static inline bool is_breakpoint(u32 intr_info)
1017 return is_exception_n(intr_info, BP_VECTOR);
1020 static inline bool is_page_fault(u32 intr_info)
1022 return is_exception_n(intr_info, PF_VECTOR);
1025 static inline bool is_no_device(u32 intr_info)
1027 return is_exception_n(intr_info, NM_VECTOR);
1030 static inline bool is_invalid_opcode(u32 intr_info)
1032 return is_exception_n(intr_info, UD_VECTOR);
1035 static inline bool is_external_interrupt(u32 intr_info)
1037 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1038 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1041 static inline bool is_machine_check(u32 intr_info)
1043 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1044 INTR_INFO_VALID_MASK)) ==
1045 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1048 static inline bool cpu_has_vmx_msr_bitmap(void)
1050 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1053 static inline bool cpu_has_vmx_tpr_shadow(void)
1055 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1058 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1060 return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1063 static inline bool cpu_has_secondary_exec_ctrls(void)
1065 return vmcs_config.cpu_based_exec_ctrl &
1066 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1069 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1071 return vmcs_config.cpu_based_2nd_exec_ctrl &
1072 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1075 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1077 return vmcs_config.cpu_based_2nd_exec_ctrl &
1078 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1081 static inline bool cpu_has_vmx_apic_register_virt(void)
1083 return vmcs_config.cpu_based_2nd_exec_ctrl &
1084 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1087 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1089 return vmcs_config.cpu_based_2nd_exec_ctrl &
1090 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1094 * Comment's format: document - errata name - stepping - processor name.
1095 * Refer from
1096 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1098 static u32 vmx_preemption_cpu_tfms[] = {
1099 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
1100 0x000206E6,
1101 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
1102 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1103 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1104 0x00020652,
1105 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1106 0x00020655,
1107 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
1108 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
1110 * 320767.pdf - AAP86 - B1 -
1111 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1113 0x000106E5,
1114 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1115 0x000106A0,
1116 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1117 0x000106A1,
1118 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1119 0x000106A4,
1120 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1121 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1122 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1123 0x000106A5,
1126 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1128 u32 eax = cpuid_eax(0x00000001), i;
1130 /* Clear the reserved bits */
1131 eax &= ~(0x3U << 14 | 0xfU << 28);
1132 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1133 if (eax == vmx_preemption_cpu_tfms[i])
1134 return true;
1136 return false;
1139 static inline bool cpu_has_vmx_preemption_timer(void)
1141 return vmcs_config.pin_based_exec_ctrl &
1142 PIN_BASED_VMX_PREEMPTION_TIMER;
1145 static inline bool cpu_has_vmx_posted_intr(void)
1147 return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1148 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1151 static inline bool cpu_has_vmx_apicv(void)
1153 return cpu_has_vmx_apic_register_virt() &&
1154 cpu_has_vmx_virtual_intr_delivery() &&
1155 cpu_has_vmx_posted_intr();
1158 static inline bool cpu_has_vmx_flexpriority(void)
1160 return cpu_has_vmx_tpr_shadow() &&
1161 cpu_has_vmx_virtualize_apic_accesses();
1164 static inline bool cpu_has_vmx_ept_execute_only(void)
1166 return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1169 static inline bool cpu_has_vmx_ept_2m_page(void)
1171 return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1174 static inline bool cpu_has_vmx_ept_1g_page(void)
1176 return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1179 static inline bool cpu_has_vmx_ept_4levels(void)
1181 return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1184 static inline bool cpu_has_vmx_ept_mt_wb(void)
1186 return vmx_capability.ept & VMX_EPTP_WB_BIT;
1189 static inline bool cpu_has_vmx_ept_5levels(void)
1191 return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1194 static inline bool cpu_has_vmx_ept_ad_bits(void)
1196 return vmx_capability.ept & VMX_EPT_AD_BIT;
1199 static inline bool cpu_has_vmx_invept_context(void)
1201 return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1204 static inline bool cpu_has_vmx_invept_global(void)
1206 return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1209 static inline bool cpu_has_vmx_invvpid_single(void)
1211 return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1214 static inline bool cpu_has_vmx_invvpid_global(void)
1216 return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1219 static inline bool cpu_has_vmx_invvpid(void)
1221 return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1224 static inline bool cpu_has_vmx_ept(void)
1226 return vmcs_config.cpu_based_2nd_exec_ctrl &
1227 SECONDARY_EXEC_ENABLE_EPT;
1230 static inline bool cpu_has_vmx_unrestricted_guest(void)
1232 return vmcs_config.cpu_based_2nd_exec_ctrl &
1233 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1236 static inline bool cpu_has_vmx_ple(void)
1238 return vmcs_config.cpu_based_2nd_exec_ctrl &
1239 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1242 static inline bool cpu_has_vmx_basic_inout(void)
1244 return (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1247 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1249 return flexpriority_enabled && lapic_in_kernel(vcpu);
1252 static inline bool cpu_has_vmx_vpid(void)
1254 return vmcs_config.cpu_based_2nd_exec_ctrl &
1255 SECONDARY_EXEC_ENABLE_VPID;
1258 static inline bool cpu_has_vmx_rdtscp(void)
1260 return vmcs_config.cpu_based_2nd_exec_ctrl &
1261 SECONDARY_EXEC_RDTSCP;
1264 static inline bool cpu_has_vmx_invpcid(void)
1266 return vmcs_config.cpu_based_2nd_exec_ctrl &
1267 SECONDARY_EXEC_ENABLE_INVPCID;
1270 static inline bool cpu_has_virtual_nmis(void)
1272 return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1275 static inline bool cpu_has_vmx_wbinvd_exit(void)
1277 return vmcs_config.cpu_based_2nd_exec_ctrl &
1278 SECONDARY_EXEC_WBINVD_EXITING;
1281 static inline bool cpu_has_vmx_shadow_vmcs(void)
1283 u64 vmx_msr;
1284 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1285 /* check if the cpu supports writing r/o exit information fields */
1286 if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1287 return false;
1289 return vmcs_config.cpu_based_2nd_exec_ctrl &
1290 SECONDARY_EXEC_SHADOW_VMCS;
1293 static inline bool cpu_has_vmx_pml(void)
1295 return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1298 static inline bool cpu_has_vmx_tsc_scaling(void)
1300 return vmcs_config.cpu_based_2nd_exec_ctrl &
1301 SECONDARY_EXEC_TSC_SCALING;
1304 static inline bool cpu_has_vmx_vmfunc(void)
1306 return vmcs_config.cpu_based_2nd_exec_ctrl &
1307 SECONDARY_EXEC_ENABLE_VMFUNC;
1310 static inline bool report_flexpriority(void)
1312 return flexpriority_enabled;
1315 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1317 return vmx_misc_cr3_count(to_vmx(vcpu)->nested.nested_vmx_misc_low);
1320 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1322 return vmcs12->cpu_based_vm_exec_control & bit;
1325 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1327 return (vmcs12->cpu_based_vm_exec_control &
1328 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1329 (vmcs12->secondary_vm_exec_control & bit);
1332 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1334 return vmcs12->pin_based_vm_exec_control &
1335 PIN_BASED_VMX_PREEMPTION_TIMER;
1338 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1340 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1343 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1345 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
1348 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
1350 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
1353 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1355 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1358 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1360 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1363 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1365 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1368 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1370 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1373 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1375 return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1378 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
1380 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
1383 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
1385 return nested_cpu_has_vmfunc(vmcs12) &&
1386 (vmcs12->vm_function_control &
1387 VMX_VMFUNC_EPTP_SWITCHING);
1390 static inline bool is_nmi(u32 intr_info)
1392 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1393 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1396 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1397 u32 exit_intr_info,
1398 unsigned long exit_qualification);
1399 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1400 struct vmcs12 *vmcs12,
1401 u32 reason, unsigned long qualification);
1403 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1405 int i;
1407 for (i = 0; i < vmx->nmsrs; ++i)
1408 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1409 return i;
1410 return -1;
1413 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1415 struct {
1416 u64 vpid : 16;
1417 u64 rsvd : 48;
1418 u64 gva;
1419 } operand = { vpid, 0, gva };
1421 asm volatile (__ex(ASM_VMX_INVVPID)
1422 /* CF==1 or ZF==1 --> rc = -1 */
1423 "; ja 1f ; ud2 ; 1:"
1424 : : "a"(&operand), "c"(ext) : "cc", "memory");
1427 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1429 struct {
1430 u64 eptp, gpa;
1431 } operand = {eptp, gpa};
1433 asm volatile (__ex(ASM_VMX_INVEPT)
1434 /* CF==1 or ZF==1 --> rc = -1 */
1435 "; ja 1f ; ud2 ; 1:\n"
1436 : : "a" (&operand), "c" (ext) : "cc", "memory");
1439 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1441 int i;
1443 i = __find_msr_index(vmx, msr);
1444 if (i >= 0)
1445 return &vmx->guest_msrs[i];
1446 return NULL;
1449 static void vmcs_clear(struct vmcs *vmcs)
1451 u64 phys_addr = __pa(vmcs);
1452 u8 error;
1454 asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1455 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1456 : "cc", "memory");
1457 if (error)
1458 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1459 vmcs, phys_addr);
1462 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1464 vmcs_clear(loaded_vmcs->vmcs);
1465 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1466 vmcs_clear(loaded_vmcs->shadow_vmcs);
1467 loaded_vmcs->cpu = -1;
1468 loaded_vmcs->launched = 0;
1471 static void vmcs_load(struct vmcs *vmcs)
1473 u64 phys_addr = __pa(vmcs);
1474 u8 error;
1476 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1477 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1478 : "cc", "memory");
1479 if (error)
1480 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1481 vmcs, phys_addr);
1484 #ifdef CONFIG_KEXEC_CORE
1486 * This bitmap is used to indicate whether the vmclear
1487 * operation is enabled on all cpus. All disabled by
1488 * default.
1490 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1492 static inline void crash_enable_local_vmclear(int cpu)
1494 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1497 static inline void crash_disable_local_vmclear(int cpu)
1499 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1502 static inline int crash_local_vmclear_enabled(int cpu)
1504 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1507 static void crash_vmclear_local_loaded_vmcss(void)
1509 int cpu = raw_smp_processor_id();
1510 struct loaded_vmcs *v;
1512 if (!crash_local_vmclear_enabled(cpu))
1513 return;
1515 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1516 loaded_vmcss_on_cpu_link)
1517 vmcs_clear(v->vmcs);
1519 #else
1520 static inline void crash_enable_local_vmclear(int cpu) { }
1521 static inline void crash_disable_local_vmclear(int cpu) { }
1522 #endif /* CONFIG_KEXEC_CORE */
1524 static void __loaded_vmcs_clear(void *arg)
1526 struct loaded_vmcs *loaded_vmcs = arg;
1527 int cpu = raw_smp_processor_id();
1529 if (loaded_vmcs->cpu != cpu)
1530 return; /* vcpu migration can race with cpu offline */
1531 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1532 per_cpu(current_vmcs, cpu) = NULL;
1533 crash_disable_local_vmclear(cpu);
1534 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1537 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1538 * is before setting loaded_vmcs->vcpu to -1 which is done in
1539 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1540 * then adds the vmcs into percpu list before it is deleted.
1542 smp_wmb();
1544 loaded_vmcs_init(loaded_vmcs);
1545 crash_enable_local_vmclear(cpu);
1548 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1550 int cpu = loaded_vmcs->cpu;
1552 if (cpu != -1)
1553 smp_call_function_single(cpu,
1554 __loaded_vmcs_clear, loaded_vmcs, 1);
1557 static inline void vpid_sync_vcpu_single(int vpid)
1559 if (vpid == 0)
1560 return;
1562 if (cpu_has_vmx_invvpid_single())
1563 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
1566 static inline void vpid_sync_vcpu_global(void)
1568 if (cpu_has_vmx_invvpid_global())
1569 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1572 static inline void vpid_sync_context(int vpid)
1574 if (cpu_has_vmx_invvpid_single())
1575 vpid_sync_vcpu_single(vpid);
1576 else
1577 vpid_sync_vcpu_global();
1580 static inline void ept_sync_global(void)
1582 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1585 static inline void ept_sync_context(u64 eptp)
1587 if (cpu_has_vmx_invept_context())
1588 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1589 else
1590 ept_sync_global();
1593 static __always_inline void vmcs_check16(unsigned long field)
1595 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1596 "16-bit accessor invalid for 64-bit field");
1597 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1598 "16-bit accessor invalid for 64-bit high field");
1599 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1600 "16-bit accessor invalid for 32-bit high field");
1601 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1602 "16-bit accessor invalid for natural width field");
1605 static __always_inline void vmcs_check32(unsigned long field)
1607 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1608 "32-bit accessor invalid for 16-bit field");
1609 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1610 "32-bit accessor invalid for natural width field");
1613 static __always_inline void vmcs_check64(unsigned long field)
1615 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1616 "64-bit accessor invalid for 16-bit field");
1617 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1618 "64-bit accessor invalid for 64-bit high field");
1619 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1620 "64-bit accessor invalid for 32-bit field");
1621 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1622 "64-bit accessor invalid for natural width field");
1625 static __always_inline void vmcs_checkl(unsigned long field)
1627 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1628 "Natural width accessor invalid for 16-bit field");
1629 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1630 "Natural width accessor invalid for 64-bit field");
1631 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1632 "Natural width accessor invalid for 64-bit high field");
1633 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1634 "Natural width accessor invalid for 32-bit field");
1637 static __always_inline unsigned long __vmcs_readl(unsigned long field)
1639 unsigned long value;
1641 asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1642 : "=a"(value) : "d"(field) : "cc");
1643 return value;
1646 static __always_inline u16 vmcs_read16(unsigned long field)
1648 vmcs_check16(field);
1649 return __vmcs_readl(field);
1652 static __always_inline u32 vmcs_read32(unsigned long field)
1654 vmcs_check32(field);
1655 return __vmcs_readl(field);
1658 static __always_inline u64 vmcs_read64(unsigned long field)
1660 vmcs_check64(field);
1661 #ifdef CONFIG_X86_64
1662 return __vmcs_readl(field);
1663 #else
1664 return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
1665 #endif
1668 static __always_inline unsigned long vmcs_readl(unsigned long field)
1670 vmcs_checkl(field);
1671 return __vmcs_readl(field);
1674 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1676 printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1677 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1678 dump_stack();
1681 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
1683 u8 error;
1685 asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1686 : "=q"(error) : "a"(value), "d"(field) : "cc");
1687 if (unlikely(error))
1688 vmwrite_error(field, value);
1691 static __always_inline void vmcs_write16(unsigned long field, u16 value)
1693 vmcs_check16(field);
1694 __vmcs_writel(field, value);
1697 static __always_inline void vmcs_write32(unsigned long field, u32 value)
1699 vmcs_check32(field);
1700 __vmcs_writel(field, value);
1703 static __always_inline void vmcs_write64(unsigned long field, u64 value)
1705 vmcs_check64(field);
1706 __vmcs_writel(field, value);
1707 #ifndef CONFIG_X86_64
1708 asm volatile ("");
1709 __vmcs_writel(field+1, value >> 32);
1710 #endif
1713 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
1715 vmcs_checkl(field);
1716 __vmcs_writel(field, value);
1719 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
1721 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1722 "vmcs_clear_bits does not support 64-bit fields");
1723 __vmcs_writel(field, __vmcs_readl(field) & ~mask);
1726 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
1728 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1729 "vmcs_set_bits does not support 64-bit fields");
1730 __vmcs_writel(field, __vmcs_readl(field) | mask);
1733 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
1735 vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
1738 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1740 vmcs_write32(VM_ENTRY_CONTROLS, val);
1741 vmx->vm_entry_controls_shadow = val;
1744 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1746 if (vmx->vm_entry_controls_shadow != val)
1747 vm_entry_controls_init(vmx, val);
1750 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1752 return vmx->vm_entry_controls_shadow;
1756 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1758 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1761 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1763 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1766 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
1768 vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
1771 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1773 vmcs_write32(VM_EXIT_CONTROLS, val);
1774 vmx->vm_exit_controls_shadow = val;
1777 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1779 if (vmx->vm_exit_controls_shadow != val)
1780 vm_exit_controls_init(vmx, val);
1783 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1785 return vmx->vm_exit_controls_shadow;
1789 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1791 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1794 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1796 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1799 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1801 vmx->segment_cache.bitmask = 0;
1804 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1805 unsigned field)
1807 bool ret;
1808 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1810 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1811 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1812 vmx->segment_cache.bitmask = 0;
1814 ret = vmx->segment_cache.bitmask & mask;
1815 vmx->segment_cache.bitmask |= mask;
1816 return ret;
1819 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1821 u16 *p = &vmx->segment_cache.seg[seg].selector;
1823 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1824 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1825 return *p;
1828 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1830 ulong *p = &vmx->segment_cache.seg[seg].base;
1832 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1833 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1834 return *p;
1837 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1839 u32 *p = &vmx->segment_cache.seg[seg].limit;
1841 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1842 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1843 return *p;
1846 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1848 u32 *p = &vmx->segment_cache.seg[seg].ar;
1850 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1851 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1852 return *p;
1855 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1857 u32 eb;
1859 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1860 (1u << DB_VECTOR) | (1u << AC_VECTOR);
1861 if ((vcpu->guest_debug &
1862 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1863 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1864 eb |= 1u << BP_VECTOR;
1865 if (to_vmx(vcpu)->rmode.vm86_active)
1866 eb = ~0;
1867 if (enable_ept)
1868 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1870 /* When we are running a nested L2 guest and L1 specified for it a
1871 * certain exception bitmap, we must trap the same exceptions and pass
1872 * them to L1. When running L2, we will only handle the exceptions
1873 * specified above if L1 did not want them.
1875 if (is_guest_mode(vcpu))
1876 eb |= get_vmcs12(vcpu)->exception_bitmap;
1878 vmcs_write32(EXCEPTION_BITMAP, eb);
1882 * Check if MSR is intercepted for currently loaded MSR bitmap.
1884 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
1886 unsigned long *msr_bitmap;
1887 int f = sizeof(unsigned long);
1889 if (!cpu_has_vmx_msr_bitmap())
1890 return true;
1892 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
1894 if (msr <= 0x1fff) {
1895 return !!test_bit(msr, msr_bitmap + 0x800 / f);
1896 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
1897 msr &= 0x1fff;
1898 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
1901 return true;
1905 * Check if MSR is intercepted for L01 MSR bitmap.
1907 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
1909 unsigned long *msr_bitmap;
1910 int f = sizeof(unsigned long);
1912 if (!cpu_has_vmx_msr_bitmap())
1913 return true;
1915 msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
1917 if (msr <= 0x1fff) {
1918 return !!test_bit(msr, msr_bitmap + 0x800 / f);
1919 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
1920 msr &= 0x1fff;
1921 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
1924 return true;
1927 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1928 unsigned long entry, unsigned long exit)
1930 vm_entry_controls_clearbit(vmx, entry);
1931 vm_exit_controls_clearbit(vmx, exit);
1934 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1936 unsigned i;
1937 struct msr_autoload *m = &vmx->msr_autoload;
1939 switch (msr) {
1940 case MSR_EFER:
1941 if (cpu_has_load_ia32_efer) {
1942 clear_atomic_switch_msr_special(vmx,
1943 VM_ENTRY_LOAD_IA32_EFER,
1944 VM_EXIT_LOAD_IA32_EFER);
1945 return;
1947 break;
1948 case MSR_CORE_PERF_GLOBAL_CTRL:
1949 if (cpu_has_load_perf_global_ctrl) {
1950 clear_atomic_switch_msr_special(vmx,
1951 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1952 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1953 return;
1955 break;
1958 for (i = 0; i < m->nr; ++i)
1959 if (m->guest[i].index == msr)
1960 break;
1962 if (i == m->nr)
1963 return;
1964 --m->nr;
1965 m->guest[i] = m->guest[m->nr];
1966 m->host[i] = m->host[m->nr];
1967 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1968 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1971 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1972 unsigned long entry, unsigned long exit,
1973 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
1974 u64 guest_val, u64 host_val)
1976 vmcs_write64(guest_val_vmcs, guest_val);
1977 vmcs_write64(host_val_vmcs, host_val);
1978 vm_entry_controls_setbit(vmx, entry);
1979 vm_exit_controls_setbit(vmx, exit);
1982 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1983 u64 guest_val, u64 host_val)
1985 unsigned i;
1986 struct msr_autoload *m = &vmx->msr_autoload;
1988 switch (msr) {
1989 case MSR_EFER:
1990 if (cpu_has_load_ia32_efer) {
1991 add_atomic_switch_msr_special(vmx,
1992 VM_ENTRY_LOAD_IA32_EFER,
1993 VM_EXIT_LOAD_IA32_EFER,
1994 GUEST_IA32_EFER,
1995 HOST_IA32_EFER,
1996 guest_val, host_val);
1997 return;
1999 break;
2000 case MSR_CORE_PERF_GLOBAL_CTRL:
2001 if (cpu_has_load_perf_global_ctrl) {
2002 add_atomic_switch_msr_special(vmx,
2003 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2004 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2005 GUEST_IA32_PERF_GLOBAL_CTRL,
2006 HOST_IA32_PERF_GLOBAL_CTRL,
2007 guest_val, host_val);
2008 return;
2010 break;
2011 case MSR_IA32_PEBS_ENABLE:
2012 /* PEBS needs a quiescent period after being disabled (to write
2013 * a record). Disabling PEBS through VMX MSR swapping doesn't
2014 * provide that period, so a CPU could write host's record into
2015 * guest's memory.
2017 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2020 for (i = 0; i < m->nr; ++i)
2021 if (m->guest[i].index == msr)
2022 break;
2024 if (i == NR_AUTOLOAD_MSRS) {
2025 printk_once(KERN_WARNING "Not enough msr switch entries. "
2026 "Can't add msr %x\n", msr);
2027 return;
2028 } else if (i == m->nr) {
2029 ++m->nr;
2030 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
2031 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
2034 m->guest[i].index = msr;
2035 m->guest[i].value = guest_val;
2036 m->host[i].index = msr;
2037 m->host[i].value = host_val;
2040 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2042 u64 guest_efer = vmx->vcpu.arch.efer;
2043 u64 ignore_bits = 0;
2045 if (!enable_ept) {
2047 * NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
2048 * host CPUID is more efficient than testing guest CPUID
2049 * or CR4. Host SMEP is anyway a requirement for guest SMEP.
2051 if (boot_cpu_has(X86_FEATURE_SMEP))
2052 guest_efer |= EFER_NX;
2053 else if (!(guest_efer & EFER_NX))
2054 ignore_bits |= EFER_NX;
2058 * LMA and LME handled by hardware; SCE meaningless outside long mode.
2060 ignore_bits |= EFER_SCE;
2061 #ifdef CONFIG_X86_64
2062 ignore_bits |= EFER_LMA | EFER_LME;
2063 /* SCE is meaningful only in long mode on Intel */
2064 if (guest_efer & EFER_LMA)
2065 ignore_bits &= ~(u64)EFER_SCE;
2066 #endif
2068 clear_atomic_switch_msr(vmx, MSR_EFER);
2071 * On EPT, we can't emulate NX, so we must switch EFER atomically.
2072 * On CPUs that support "load IA32_EFER", always switch EFER
2073 * atomically, since it's faster than switching it manually.
2075 if (cpu_has_load_ia32_efer ||
2076 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2077 if (!(guest_efer & EFER_LMA))
2078 guest_efer &= ~EFER_LME;
2079 if (guest_efer != host_efer)
2080 add_atomic_switch_msr(vmx, MSR_EFER,
2081 guest_efer, host_efer);
2082 return false;
2083 } else {
2084 guest_efer &= ~ignore_bits;
2085 guest_efer |= host_efer & ignore_bits;
2087 vmx->guest_msrs[efer_offset].data = guest_efer;
2088 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2090 return true;
2094 #ifdef CONFIG_X86_32
2096 * On 32-bit kernels, VM exits still load the FS and GS bases from the
2097 * VMCS rather than the segment table. KVM uses this helper to figure
2098 * out the current bases to poke them into the VMCS before entry.
2100 static unsigned long segment_base(u16 selector)
2102 struct desc_struct *table;
2103 unsigned long v;
2105 if (!(selector & ~SEGMENT_RPL_MASK))
2106 return 0;
2108 table = get_current_gdt_ro();
2110 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2111 u16 ldt_selector = kvm_read_ldt();
2113 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2114 return 0;
2116 table = (struct desc_struct *)segment_base(ldt_selector);
2118 v = get_desc_base(&table[selector >> 3]);
2119 return v;
2121 #endif
2123 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
2125 struct vcpu_vmx *vmx = to_vmx(vcpu);
2126 int i;
2128 if (vmx->host_state.loaded)
2129 return;
2131 vmx->host_state.loaded = 1;
2133 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
2134 * allow segment selectors with cpl > 0 or ti == 1.
2136 vmx->host_state.ldt_sel = kvm_read_ldt();
2137 vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
2138 savesegment(fs, vmx->host_state.fs_sel);
2139 if (!(vmx->host_state.fs_sel & 7)) {
2140 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
2141 vmx->host_state.fs_reload_needed = 0;
2142 } else {
2143 vmcs_write16(HOST_FS_SELECTOR, 0);
2144 vmx->host_state.fs_reload_needed = 1;
2146 savesegment(gs, vmx->host_state.gs_sel);
2147 if (!(vmx->host_state.gs_sel & 7))
2148 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
2149 else {
2150 vmcs_write16(HOST_GS_SELECTOR, 0);
2151 vmx->host_state.gs_ldt_reload_needed = 1;
2154 #ifdef CONFIG_X86_64
2155 savesegment(ds, vmx->host_state.ds_sel);
2156 savesegment(es, vmx->host_state.es_sel);
2157 #endif
2159 #ifdef CONFIG_X86_64
2160 vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
2161 vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
2162 #else
2163 vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
2164 vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
2165 #endif
2167 #ifdef CONFIG_X86_64
2168 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2169 if (is_long_mode(&vmx->vcpu))
2170 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2171 #endif
2172 if (boot_cpu_has(X86_FEATURE_MPX))
2173 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2174 for (i = 0; i < vmx->save_nmsrs; ++i)
2175 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2176 vmx->guest_msrs[i].data,
2177 vmx->guest_msrs[i].mask);
2180 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
2182 if (!vmx->host_state.loaded)
2183 return;
2185 ++vmx->vcpu.stat.host_state_reload;
2186 vmx->host_state.loaded = 0;
2187 #ifdef CONFIG_X86_64
2188 if (is_long_mode(&vmx->vcpu))
2189 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2190 #endif
2191 if (vmx->host_state.gs_ldt_reload_needed) {
2192 kvm_load_ldt(vmx->host_state.ldt_sel);
2193 #ifdef CONFIG_X86_64
2194 load_gs_index(vmx->host_state.gs_sel);
2195 #else
2196 loadsegment(gs, vmx->host_state.gs_sel);
2197 #endif
2199 if (vmx->host_state.fs_reload_needed)
2200 loadsegment(fs, vmx->host_state.fs_sel);
2201 #ifdef CONFIG_X86_64
2202 if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
2203 loadsegment(ds, vmx->host_state.ds_sel);
2204 loadsegment(es, vmx->host_state.es_sel);
2206 #endif
2207 invalidate_tss_limit();
2208 #ifdef CONFIG_X86_64
2209 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2210 #endif
2211 if (vmx->host_state.msr_host_bndcfgs)
2212 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2213 load_fixmap_gdt(raw_smp_processor_id());
2216 static void vmx_load_host_state(struct vcpu_vmx *vmx)
2218 preempt_disable();
2219 __vmx_load_host_state(vmx);
2220 preempt_enable();
2223 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2225 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2226 struct pi_desc old, new;
2227 unsigned int dest;
2230 * In case of hot-plug or hot-unplug, we may have to undo
2231 * vmx_vcpu_pi_put even if there is no assigned device. And we
2232 * always keep PI.NDST up to date for simplicity: it makes the
2233 * code easier, and CPU migration is not a fast path.
2235 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
2236 return;
2239 * First handle the simple case where no cmpxchg is necessary; just
2240 * allow posting non-urgent interrupts.
2242 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
2243 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
2244 * expects the VCPU to be on the blocked_vcpu_list that matches
2245 * PI.NDST.
2247 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
2248 vcpu->cpu == cpu) {
2249 pi_clear_sn(pi_desc);
2250 return;
2253 /* The full case. */
2254 do {
2255 old.control = new.control = pi_desc->control;
2257 dest = cpu_physical_id(cpu);
2259 if (x2apic_enabled())
2260 new.ndst = dest;
2261 else
2262 new.ndst = (dest << 8) & 0xFF00;
2264 new.sn = 0;
2265 } while (cmpxchg64(&pi_desc->control, old.control,
2266 new.control) != old.control);
2269 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2271 vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2272 vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2276 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2277 * vcpu mutex is already taken.
2279 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2281 struct vcpu_vmx *vmx = to_vmx(vcpu);
2282 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2284 if (!already_loaded) {
2285 loaded_vmcs_clear(vmx->loaded_vmcs);
2286 local_irq_disable();
2287 crash_disable_local_vmclear(cpu);
2290 * Read loaded_vmcs->cpu should be before fetching
2291 * loaded_vmcs->loaded_vmcss_on_cpu_link.
2292 * See the comments in __loaded_vmcs_clear().
2294 smp_rmb();
2296 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2297 &per_cpu(loaded_vmcss_on_cpu, cpu));
2298 crash_enable_local_vmclear(cpu);
2299 local_irq_enable();
2302 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2303 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2304 vmcs_load(vmx->loaded_vmcs->vmcs);
2305 indirect_branch_prediction_barrier();
2308 if (!already_loaded) {
2309 void *gdt = get_current_gdt_ro();
2310 unsigned long sysenter_esp;
2312 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2315 * Linux uses per-cpu TSS and GDT, so set these when switching
2316 * processors. See 22.2.4.
2318 vmcs_writel(HOST_TR_BASE,
2319 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
2320 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
2323 * VM exits change the host TR limit to 0x67 after a VM
2324 * exit. This is okay, since 0x67 covers everything except
2325 * the IO bitmap and have have code to handle the IO bitmap
2326 * being lost after a VM exit.
2328 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
2330 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2331 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2333 vmx->loaded_vmcs->cpu = cpu;
2336 /* Setup TSC multiplier */
2337 if (kvm_has_tsc_control &&
2338 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2339 decache_tsc_multiplier(vmx);
2341 vmx_vcpu_pi_load(vcpu, cpu);
2342 vmx->host_pkru = read_pkru();
2343 vmx->host_debugctlmsr = get_debugctlmsr();
2346 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2348 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2350 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2351 !irq_remapping_cap(IRQ_POSTING_CAP) ||
2352 !kvm_vcpu_apicv_active(vcpu))
2353 return;
2355 /* Set SN when the vCPU is preempted */
2356 if (vcpu->preempted)
2357 pi_set_sn(pi_desc);
2360 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2362 vmx_vcpu_pi_put(vcpu);
2364 __vmx_load_host_state(to_vmx(vcpu));
2367 static bool emulation_required(struct kvm_vcpu *vcpu)
2369 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
2372 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
2375 * Return the cr0 value that a nested guest would read. This is a combination
2376 * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
2377 * its hypervisor (cr0_read_shadow).
2379 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
2381 return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
2382 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
2384 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
2386 return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
2387 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
2390 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2392 unsigned long rflags, save_rflags;
2394 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2395 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2396 rflags = vmcs_readl(GUEST_RFLAGS);
2397 if (to_vmx(vcpu)->rmode.vm86_active) {
2398 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2399 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2400 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2402 to_vmx(vcpu)->rflags = rflags;
2404 return to_vmx(vcpu)->rflags;
2407 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2409 unsigned long old_rflags = vmx_get_rflags(vcpu);
2411 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2412 to_vmx(vcpu)->rflags = rflags;
2413 if (to_vmx(vcpu)->rmode.vm86_active) {
2414 to_vmx(vcpu)->rmode.save_rflags = rflags;
2415 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2417 vmcs_writel(GUEST_RFLAGS, rflags);
2419 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
2420 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
2423 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2425 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2426 int ret = 0;
2428 if (interruptibility & GUEST_INTR_STATE_STI)
2429 ret |= KVM_X86_SHADOW_INT_STI;
2430 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2431 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2433 return ret;
2436 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2438 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2439 u32 interruptibility = interruptibility_old;
2441 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2443 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2444 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2445 else if (mask & KVM_X86_SHADOW_INT_STI)
2446 interruptibility |= GUEST_INTR_STATE_STI;
2448 if ((interruptibility != interruptibility_old))
2449 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2452 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2454 unsigned long rip;
2456 rip = kvm_rip_read(vcpu);
2457 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2458 kvm_rip_write(vcpu, rip);
2460 /* skipping an emulated instruction also counts */
2461 vmx_set_interrupt_shadow(vcpu, 0);
2464 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
2465 unsigned long exit_qual)
2467 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2468 unsigned int nr = vcpu->arch.exception.nr;
2469 u32 intr_info = nr | INTR_INFO_VALID_MASK;
2471 if (vcpu->arch.exception.has_error_code) {
2472 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
2473 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2476 if (kvm_exception_is_soft(nr))
2477 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2478 else
2479 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2481 if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
2482 vmx_get_nmi_mask(vcpu))
2483 intr_info |= INTR_INFO_UNBLOCK_NMI;
2485 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
2489 * KVM wants to inject page-faults which it got to the guest. This function
2490 * checks whether in a nested guest, we need to inject them to L1 or L2.
2492 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
2494 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2495 unsigned int nr = vcpu->arch.exception.nr;
2497 if (nr == PF_VECTOR) {
2498 if (vcpu->arch.exception.nested_apf) {
2499 *exit_qual = vcpu->arch.apf.nested_apf_token;
2500 return 1;
2503 * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
2504 * The fix is to add the ancillary datum (CR2 or DR6) to structs
2505 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
2506 * can be written only when inject_pending_event runs. This should be
2507 * conditional on a new capability---if the capability is disabled,
2508 * kvm_multiple_exception would write the ancillary information to
2509 * CR2 or DR6, for backwards ABI-compatibility.
2511 if (nested_vmx_is_page_fault_vmexit(vmcs12,
2512 vcpu->arch.exception.error_code)) {
2513 *exit_qual = vcpu->arch.cr2;
2514 return 1;
2516 } else {
2517 if (vmcs12->exception_bitmap & (1u << nr)) {
2518 if (nr == DB_VECTOR)
2519 *exit_qual = vcpu->arch.dr6;
2520 else
2521 *exit_qual = 0;
2522 return 1;
2526 return 0;
2529 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
2531 struct vcpu_vmx *vmx = to_vmx(vcpu);
2532 unsigned nr = vcpu->arch.exception.nr;
2533 bool has_error_code = vcpu->arch.exception.has_error_code;
2534 u32 error_code = vcpu->arch.exception.error_code;
2535 u32 intr_info = nr | INTR_INFO_VALID_MASK;
2537 if (has_error_code) {
2538 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2539 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2542 if (vmx->rmode.vm86_active) {
2543 int inc_eip = 0;
2544 if (kvm_exception_is_soft(nr))
2545 inc_eip = vcpu->arch.event_exit_inst_len;
2546 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2547 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2548 return;
2551 if (kvm_exception_is_soft(nr)) {
2552 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2553 vmx->vcpu.arch.event_exit_inst_len);
2554 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2555 } else
2556 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2558 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2561 static bool vmx_rdtscp_supported(void)
2563 return cpu_has_vmx_rdtscp();
2566 static bool vmx_invpcid_supported(void)
2568 return cpu_has_vmx_invpcid() && enable_ept;
2572 * Swap MSR entry in host/guest MSR entry array.
2574 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2576 struct shared_msr_entry tmp;
2578 tmp = vmx->guest_msrs[to];
2579 vmx->guest_msrs[to] = vmx->guest_msrs[from];
2580 vmx->guest_msrs[from] = tmp;
2584 * Set up the vmcs to automatically save and restore system
2585 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
2586 * mode, as fiddling with msrs is very expensive.
2588 static void setup_msrs(struct vcpu_vmx *vmx)
2590 int save_nmsrs, index;
2592 save_nmsrs = 0;
2593 #ifdef CONFIG_X86_64
2594 if (is_long_mode(&vmx->vcpu)) {
2595 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2596 if (index >= 0)
2597 move_msr_up(vmx, index, save_nmsrs++);
2598 index = __find_msr_index(vmx, MSR_LSTAR);
2599 if (index >= 0)
2600 move_msr_up(vmx, index, save_nmsrs++);
2601 index = __find_msr_index(vmx, MSR_CSTAR);
2602 if (index >= 0)
2603 move_msr_up(vmx, index, save_nmsrs++);
2604 index = __find_msr_index(vmx, MSR_TSC_AUX);
2605 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
2606 move_msr_up(vmx, index, save_nmsrs++);
2608 * MSR_STAR is only needed on long mode guests, and only
2609 * if efer.sce is enabled.
2611 index = __find_msr_index(vmx, MSR_STAR);
2612 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2613 move_msr_up(vmx, index, save_nmsrs++);
2615 #endif
2616 index = __find_msr_index(vmx, MSR_EFER);
2617 if (index >= 0 && update_transition_efer(vmx, index))
2618 move_msr_up(vmx, index, save_nmsrs++);
2620 vmx->save_nmsrs = save_nmsrs;
2622 if (cpu_has_vmx_msr_bitmap())
2623 vmx_update_msr_bitmap(&vmx->vcpu);
2627 * reads and returns guest's timestamp counter "register"
2628 * guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
2629 * -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
2631 static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
2633 u64 host_tsc, tsc_offset;
2635 host_tsc = rdtsc();
2636 tsc_offset = vmcs_read64(TSC_OFFSET);
2637 return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
2641 * writes 'offset' into guest's timestamp counter offset register
2643 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2645 if (is_guest_mode(vcpu)) {
2647 * We're here if L1 chose not to trap WRMSR to TSC. According
2648 * to the spec, this should set L1's TSC; The offset that L1
2649 * set for L2 remains unchanged, and still needs to be added
2650 * to the newly set TSC to get L2's TSC.
2652 struct vmcs12 *vmcs12;
2653 /* recalculate vmcs02.TSC_OFFSET: */
2654 vmcs12 = get_vmcs12(vcpu);
2655 vmcs_write64(TSC_OFFSET, offset +
2656 (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2657 vmcs12->tsc_offset : 0));
2658 } else {
2659 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2660 vmcs_read64(TSC_OFFSET), offset);
2661 vmcs_write64(TSC_OFFSET, offset);
2666 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2667 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2668 * all guests if the "nested" module option is off, and can also be disabled
2669 * for a single guest by disabling its VMX cpuid bit.
2671 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2673 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
2677 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2678 * returned for the various VMX controls MSRs when nested VMX is enabled.
2679 * The same values should also be used to verify that vmcs12 control fields are
2680 * valid during nested entry from L1 to L2.
2681 * Each of these control msrs has a low and high 32-bit half: A low bit is on
2682 * if the corresponding bit in the (32-bit) control field *must* be on, and a
2683 * bit in the high half is on if the corresponding bit in the control field
2684 * may be on. See also vmx_control_verify().
2686 static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
2689 * Note that as a general rule, the high half of the MSRs (bits in
2690 * the control fields which may be 1) should be initialized by the
2691 * intersection of the underlying hardware's MSR (i.e., features which
2692 * can be supported) and the list of features we want to expose -
2693 * because they are known to be properly supported in our code.
2694 * Also, usually, the low half of the MSRs (bits which must be 1) can
2695 * be set to 0, meaning that L1 may turn off any of these bits. The
2696 * reason is that if one of these bits is necessary, it will appear
2697 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2698 * fields of vmcs01 and vmcs02, will turn these bits off - and
2699 * nested_vmx_exit_reflected() will not pass related exits to L1.
2700 * These rules have exceptions below.
2703 /* pin-based controls */
2704 rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2705 vmx->nested.nested_vmx_pinbased_ctls_low,
2706 vmx->nested.nested_vmx_pinbased_ctls_high);
2707 vmx->nested.nested_vmx_pinbased_ctls_low |=
2708 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2709 vmx->nested.nested_vmx_pinbased_ctls_high &=
2710 PIN_BASED_EXT_INTR_MASK |
2711 PIN_BASED_NMI_EXITING |
2712 PIN_BASED_VIRTUAL_NMIS;
2713 vmx->nested.nested_vmx_pinbased_ctls_high |=
2714 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2715 PIN_BASED_VMX_PREEMPTION_TIMER;
2716 if (kvm_vcpu_apicv_active(&vmx->vcpu))
2717 vmx->nested.nested_vmx_pinbased_ctls_high |=
2718 PIN_BASED_POSTED_INTR;
2720 /* exit controls */
2721 rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2722 vmx->nested.nested_vmx_exit_ctls_low,
2723 vmx->nested.nested_vmx_exit_ctls_high);
2724 vmx->nested.nested_vmx_exit_ctls_low =
2725 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2727 vmx->nested.nested_vmx_exit_ctls_high &=
2728 #ifdef CONFIG_X86_64
2729 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2730 #endif
2731 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2732 vmx->nested.nested_vmx_exit_ctls_high |=
2733 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2734 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2735 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2737 if (kvm_mpx_supported())
2738 vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2740 /* We support free control of debug control saving. */
2741 vmx->nested.nested_vmx_exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2743 /* entry controls */
2744 rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2745 vmx->nested.nested_vmx_entry_ctls_low,
2746 vmx->nested.nested_vmx_entry_ctls_high);
2747 vmx->nested.nested_vmx_entry_ctls_low =
2748 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2749 vmx->nested.nested_vmx_entry_ctls_high &=
2750 #ifdef CONFIG_X86_64
2751 VM_ENTRY_IA32E_MODE |
2752 #endif
2753 VM_ENTRY_LOAD_IA32_PAT;
2754 vmx->nested.nested_vmx_entry_ctls_high |=
2755 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
2756 if (kvm_mpx_supported())
2757 vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2759 /* We support free control of debug control loading. */
2760 vmx->nested.nested_vmx_entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2762 /* cpu-based controls */
2763 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2764 vmx->nested.nested_vmx_procbased_ctls_low,
2765 vmx->nested.nested_vmx_procbased_ctls_high);
2766 vmx->nested.nested_vmx_procbased_ctls_low =
2767 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2768 vmx->nested.nested_vmx_procbased_ctls_high &=
2769 CPU_BASED_VIRTUAL_INTR_PENDING |
2770 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2771 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2772 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2773 CPU_BASED_CR3_STORE_EXITING |
2774 #ifdef CONFIG_X86_64
2775 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2776 #endif
2777 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2778 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
2779 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
2780 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
2781 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2783 * We can allow some features even when not supported by the
2784 * hardware. For example, L1 can specify an MSR bitmap - and we
2785 * can use it to avoid exits to L1 - even when L0 runs L2
2786 * without MSR bitmaps.
2788 vmx->nested.nested_vmx_procbased_ctls_high |=
2789 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2790 CPU_BASED_USE_MSR_BITMAPS;
2792 /* We support free control of CR3 access interception. */
2793 vmx->nested.nested_vmx_procbased_ctls_low &=
2794 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2797 * secondary cpu-based controls. Do not include those that
2798 * depend on CPUID bits, they are added later by vmx_cpuid_update.
2800 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2801 vmx->nested.nested_vmx_secondary_ctls_low,
2802 vmx->nested.nested_vmx_secondary_ctls_high);
2803 vmx->nested.nested_vmx_secondary_ctls_low = 0;
2804 vmx->nested.nested_vmx_secondary_ctls_high &=
2805 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2806 SECONDARY_EXEC_DESC |
2807 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2808 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2809 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2810 SECONDARY_EXEC_WBINVD_EXITING;
2812 if (enable_ept) {
2813 /* nested EPT: emulate EPT also to L1 */
2814 vmx->nested.nested_vmx_secondary_ctls_high |=
2815 SECONDARY_EXEC_ENABLE_EPT;
2816 vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
2817 VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
2818 if (cpu_has_vmx_ept_execute_only())
2819 vmx->nested.nested_vmx_ept_caps |=
2820 VMX_EPT_EXECUTE_ONLY_BIT;
2821 vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
2822 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
2823 VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
2824 VMX_EPT_1GB_PAGE_BIT;
2825 if (enable_ept_ad_bits) {
2826 vmx->nested.nested_vmx_secondary_ctls_high |=
2827 SECONDARY_EXEC_ENABLE_PML;
2828 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_AD_BIT;
2832 if (cpu_has_vmx_vmfunc()) {
2833 vmx->nested.nested_vmx_secondary_ctls_high |=
2834 SECONDARY_EXEC_ENABLE_VMFUNC;
2836 * Advertise EPTP switching unconditionally
2837 * since we emulate it
2839 if (enable_ept)
2840 vmx->nested.nested_vmx_vmfunc_controls =
2841 VMX_VMFUNC_EPTP_SWITCHING;
2845 * Old versions of KVM use the single-context version without
2846 * checking for support, so declare that it is supported even
2847 * though it is treated as global context. The alternative is
2848 * not failing the single-context invvpid, and it is worse.
2850 if (enable_vpid) {
2851 vmx->nested.nested_vmx_secondary_ctls_high |=
2852 SECONDARY_EXEC_ENABLE_VPID;
2853 vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
2854 VMX_VPID_EXTENT_SUPPORTED_MASK;
2857 if (enable_unrestricted_guest)
2858 vmx->nested.nested_vmx_secondary_ctls_high |=
2859 SECONDARY_EXEC_UNRESTRICTED_GUEST;
2861 /* miscellaneous data */
2862 rdmsr(MSR_IA32_VMX_MISC,
2863 vmx->nested.nested_vmx_misc_low,
2864 vmx->nested.nested_vmx_misc_high);
2865 vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
2866 vmx->nested.nested_vmx_misc_low |=
2867 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
2868 VMX_MISC_ACTIVITY_HLT;
2869 vmx->nested.nested_vmx_misc_high = 0;
2872 * This MSR reports some information about VMX support. We
2873 * should return information about the VMX we emulate for the
2874 * guest, and the VMCS structure we give it - not about the
2875 * VMX support of the underlying hardware.
2877 vmx->nested.nested_vmx_basic =
2878 VMCS12_REVISION |
2879 VMX_BASIC_TRUE_CTLS |
2880 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2881 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2883 if (cpu_has_vmx_basic_inout())
2884 vmx->nested.nested_vmx_basic |= VMX_BASIC_INOUT;
2887 * These MSRs specify bits which the guest must keep fixed on
2888 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2889 * We picked the standard core2 setting.
2891 #define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2892 #define VMXON_CR4_ALWAYSON X86_CR4_VMXE
2893 vmx->nested.nested_vmx_cr0_fixed0 = VMXON_CR0_ALWAYSON;
2894 vmx->nested.nested_vmx_cr4_fixed0 = VMXON_CR4_ALWAYSON;
2896 /* These MSRs specify bits which the guest must keep fixed off. */
2897 rdmsrl(MSR_IA32_VMX_CR0_FIXED1, vmx->nested.nested_vmx_cr0_fixed1);
2898 rdmsrl(MSR_IA32_VMX_CR4_FIXED1, vmx->nested.nested_vmx_cr4_fixed1);
2900 /* highest index: VMX_PREEMPTION_TIMER_VALUE */
2901 vmx->nested.nested_vmx_vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
2905 * if fixed0[i] == 1: val[i] must be 1
2906 * if fixed1[i] == 0: val[i] must be 0
2908 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
2910 return ((val & fixed1) | fixed0) == val;
2913 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2915 return fixed_bits_valid(control, low, high);
2918 static inline u64 vmx_control_msr(u32 low, u32 high)
2920 return low | ((u64)high << 32);
2923 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
2925 superset &= mask;
2926 subset &= mask;
2928 return (superset | subset) == superset;
2931 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
2933 const u64 feature_and_reserved =
2934 /* feature (except bit 48; see below) */
2935 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
2936 /* reserved */
2937 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
2938 u64 vmx_basic = vmx->nested.nested_vmx_basic;
2940 if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
2941 return -EINVAL;
2944 * KVM does not emulate a version of VMX that constrains physical
2945 * addresses of VMX structures (e.g. VMCS) to 32-bits.
2947 if (data & BIT_ULL(48))
2948 return -EINVAL;
2950 if (vmx_basic_vmcs_revision_id(vmx_basic) !=
2951 vmx_basic_vmcs_revision_id(data))
2952 return -EINVAL;
2954 if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
2955 return -EINVAL;
2957 vmx->nested.nested_vmx_basic = data;
2958 return 0;
2961 static int
2962 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
2964 u64 supported;
2965 u32 *lowp, *highp;
2967 switch (msr_index) {
2968 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2969 lowp = &vmx->nested.nested_vmx_pinbased_ctls_low;
2970 highp = &vmx->nested.nested_vmx_pinbased_ctls_high;
2971 break;
2972 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2973 lowp = &vmx->nested.nested_vmx_procbased_ctls_low;
2974 highp = &vmx->nested.nested_vmx_procbased_ctls_high;
2975 break;
2976 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2977 lowp = &vmx->nested.nested_vmx_exit_ctls_low;
2978 highp = &vmx->nested.nested_vmx_exit_ctls_high;
2979 break;
2980 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2981 lowp = &vmx->nested.nested_vmx_entry_ctls_low;
2982 highp = &vmx->nested.nested_vmx_entry_ctls_high;
2983 break;
2984 case MSR_IA32_VMX_PROCBASED_CTLS2:
2985 lowp = &vmx->nested.nested_vmx_secondary_ctls_low;
2986 highp = &vmx->nested.nested_vmx_secondary_ctls_high;
2987 break;
2988 default:
2989 BUG();
2992 supported = vmx_control_msr(*lowp, *highp);
2994 /* Check must-be-1 bits are still 1. */
2995 if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
2996 return -EINVAL;
2998 /* Check must-be-0 bits are still 0. */
2999 if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3000 return -EINVAL;
3002 *lowp = data;
3003 *highp = data >> 32;
3004 return 0;
3007 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3009 const u64 feature_and_reserved_bits =
3010 /* feature */
3011 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3012 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3013 /* reserved */
3014 GENMASK_ULL(13, 9) | BIT_ULL(31);
3015 u64 vmx_misc;
3017 vmx_misc = vmx_control_msr(vmx->nested.nested_vmx_misc_low,
3018 vmx->nested.nested_vmx_misc_high);
3020 if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3021 return -EINVAL;
3023 if ((vmx->nested.nested_vmx_pinbased_ctls_high &
3024 PIN_BASED_VMX_PREEMPTION_TIMER) &&
3025 vmx_misc_preemption_timer_rate(data) !=
3026 vmx_misc_preemption_timer_rate(vmx_misc))
3027 return -EINVAL;
3029 if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3030 return -EINVAL;
3032 if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3033 return -EINVAL;
3035 if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3036 return -EINVAL;
3038 vmx->nested.nested_vmx_misc_low = data;
3039 vmx->nested.nested_vmx_misc_high = data >> 32;
3040 return 0;
3043 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3045 u64 vmx_ept_vpid_cap;
3047 vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.nested_vmx_ept_caps,
3048 vmx->nested.nested_vmx_vpid_caps);
3050 /* Every bit is either reserved or a feature bit. */
3051 if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3052 return -EINVAL;
3054 vmx->nested.nested_vmx_ept_caps = data;
3055 vmx->nested.nested_vmx_vpid_caps = data >> 32;
3056 return 0;
3059 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3061 u64 *msr;
3063 switch (msr_index) {
3064 case MSR_IA32_VMX_CR0_FIXED0:
3065 msr = &vmx->nested.nested_vmx_cr0_fixed0;
3066 break;
3067 case MSR_IA32_VMX_CR4_FIXED0:
3068 msr = &vmx->nested.nested_vmx_cr4_fixed0;
3069 break;
3070 default:
3071 BUG();
3075 * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3076 * must be 1 in the restored value.
3078 if (!is_bitwise_subset(data, *msr, -1ULL))
3079 return -EINVAL;
3081 *msr = data;
3082 return 0;
3086 * Called when userspace is restoring VMX MSRs.
3088 * Returns 0 on success, non-0 otherwise.
3090 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3092 struct vcpu_vmx *vmx = to_vmx(vcpu);
3094 switch (msr_index) {
3095 case MSR_IA32_VMX_BASIC:
3096 return vmx_restore_vmx_basic(vmx, data);
3097 case MSR_IA32_VMX_PINBASED_CTLS:
3098 case MSR_IA32_VMX_PROCBASED_CTLS:
3099 case MSR_IA32_VMX_EXIT_CTLS:
3100 case MSR_IA32_VMX_ENTRY_CTLS:
3102 * The "non-true" VMX capability MSRs are generated from the
3103 * "true" MSRs, so we do not support restoring them directly.
3105 * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3106 * should restore the "true" MSRs with the must-be-1 bits
3107 * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3108 * DEFAULT SETTINGS".
3110 return -EINVAL;
3111 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3112 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3113 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3114 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3115 case MSR_IA32_VMX_PROCBASED_CTLS2:
3116 return vmx_restore_control_msr(vmx, msr_index, data);
3117 case MSR_IA32_VMX_MISC:
3118 return vmx_restore_vmx_misc(vmx, data);
3119 case MSR_IA32_VMX_CR0_FIXED0:
3120 case MSR_IA32_VMX_CR4_FIXED0:
3121 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3122 case MSR_IA32_VMX_CR0_FIXED1:
3123 case MSR_IA32_VMX_CR4_FIXED1:
3125 * These MSRs are generated based on the vCPU's CPUID, so we
3126 * do not support restoring them directly.
3128 return -EINVAL;
3129 case MSR_IA32_VMX_EPT_VPID_CAP:
3130 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3131 case MSR_IA32_VMX_VMCS_ENUM:
3132 vmx->nested.nested_vmx_vmcs_enum = data;
3133 return 0;
3134 default:
3136 * The rest of the VMX capability MSRs do not support restore.
3138 return -EINVAL;
3142 /* Returns 0 on success, non-0 otherwise. */
3143 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
3145 struct vcpu_vmx *vmx = to_vmx(vcpu);
3147 switch (msr_index) {
3148 case MSR_IA32_VMX_BASIC:
3149 *pdata = vmx->nested.nested_vmx_basic;
3150 break;
3151 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3152 case MSR_IA32_VMX_PINBASED_CTLS:
3153 *pdata = vmx_control_msr(
3154 vmx->nested.nested_vmx_pinbased_ctls_low,
3155 vmx->nested.nested_vmx_pinbased_ctls_high);
3156 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3157 *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3158 break;
3159 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3160 case MSR_IA32_VMX_PROCBASED_CTLS:
3161 *pdata = vmx_control_msr(
3162 vmx->nested.nested_vmx_procbased_ctls_low,
3163 vmx->nested.nested_vmx_procbased_ctls_high);
3164 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3165 *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3166 break;
3167 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3168 case MSR_IA32_VMX_EXIT_CTLS:
3169 *pdata = vmx_control_msr(
3170 vmx->nested.nested_vmx_exit_ctls_low,
3171 vmx->nested.nested_vmx_exit_ctls_high);
3172 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3173 *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3174 break;
3175 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3176 case MSR_IA32_VMX_ENTRY_CTLS:
3177 *pdata = vmx_control_msr(
3178 vmx->nested.nested_vmx_entry_ctls_low,
3179 vmx->nested.nested_vmx_entry_ctls_high);
3180 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
3181 *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3182 break;
3183 case MSR_IA32_VMX_MISC:
3184 *pdata = vmx_control_msr(
3185 vmx->nested.nested_vmx_misc_low,
3186 vmx->nested.nested_vmx_misc_high);
3187 break;
3188 case MSR_IA32_VMX_CR0_FIXED0:
3189 *pdata = vmx->nested.nested_vmx_cr0_fixed0;
3190 break;
3191 case MSR_IA32_VMX_CR0_FIXED1:
3192 *pdata = vmx->nested.nested_vmx_cr0_fixed1;
3193 break;
3194 case MSR_IA32_VMX_CR4_FIXED0:
3195 *pdata = vmx->nested.nested_vmx_cr4_fixed0;
3196 break;
3197 case MSR_IA32_VMX_CR4_FIXED1:
3198 *pdata = vmx->nested.nested_vmx_cr4_fixed1;
3199 break;
3200 case MSR_IA32_VMX_VMCS_ENUM:
3201 *pdata = vmx->nested.nested_vmx_vmcs_enum;
3202 break;
3203 case MSR_IA32_VMX_PROCBASED_CTLS2:
3204 *pdata = vmx_control_msr(
3205 vmx->nested.nested_vmx_secondary_ctls_low,
3206 vmx->nested.nested_vmx_secondary_ctls_high);
3207 break;
3208 case MSR_IA32_VMX_EPT_VPID_CAP:
3209 *pdata = vmx->nested.nested_vmx_ept_caps |
3210 ((u64)vmx->nested.nested_vmx_vpid_caps << 32);
3211 break;
3212 case MSR_IA32_VMX_VMFUNC:
3213 *pdata = vmx->nested.nested_vmx_vmfunc_controls;
3214 break;
3215 default:
3216 return 1;
3219 return 0;
3222 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3223 uint64_t val)
3225 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3227 return !(val & ~valid_bits);
3230 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
3232 return 1;
3236 * Reads an msr value (of 'msr_index') into 'pdata'.
3237 * Returns 0 on success, non-0 otherwise.
3238 * Assumes vcpu_load() was already called.
3240 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3242 struct vcpu_vmx *vmx = to_vmx(vcpu);
3243 struct shared_msr_entry *msr;
3245 switch (msr_info->index) {
3246 #ifdef CONFIG_X86_64
3247 case MSR_FS_BASE:
3248 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3249 break;
3250 case MSR_GS_BASE:
3251 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3252 break;
3253 case MSR_KERNEL_GS_BASE:
3254 vmx_load_host_state(vmx);
3255 msr_info->data = vmx->msr_guest_kernel_gs_base;
3256 break;
3257 #endif
3258 case MSR_EFER:
3259 return kvm_get_msr_common(vcpu, msr_info);
3260 case MSR_IA32_TSC:
3261 msr_info->data = guest_read_tsc(vcpu);
3262 break;
3263 case MSR_IA32_SPEC_CTRL:
3264 if (!msr_info->host_initiated &&
3265 !guest_cpuid_has(vcpu, X86_FEATURE_IBRS) &&
3266 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3267 return 1;
3269 msr_info->data = to_vmx(vcpu)->spec_ctrl;
3270 break;
3271 case MSR_IA32_ARCH_CAPABILITIES:
3272 if (!msr_info->host_initiated &&
3273 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3274 return 1;
3275 msr_info->data = to_vmx(vcpu)->arch_capabilities;
3276 break;
3277 case MSR_IA32_SYSENTER_CS:
3278 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3279 break;
3280 case MSR_IA32_SYSENTER_EIP:
3281 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3282 break;
3283 case MSR_IA32_SYSENTER_ESP:
3284 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3285 break;
3286 case MSR_IA32_BNDCFGS:
3287 if (!kvm_mpx_supported() ||
3288 (!msr_info->host_initiated &&
3289 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3290 return 1;
3291 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3292 break;
3293 case MSR_IA32_MCG_EXT_CTL:
3294 if (!msr_info->host_initiated &&
3295 !(vmx->msr_ia32_feature_control &
3296 FEATURE_CONTROL_LMCE))
3297 return 1;
3298 msr_info->data = vcpu->arch.mcg_ext_ctl;
3299 break;
3300 case MSR_IA32_FEATURE_CONTROL:
3301 msr_info->data = vmx->msr_ia32_feature_control;
3302 break;
3303 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3304 if (!nested_vmx_allowed(vcpu))
3305 return 1;
3306 return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
3307 case MSR_IA32_XSS:
3308 if (!vmx_xsaves_supported())
3309 return 1;
3310 msr_info->data = vcpu->arch.ia32_xss;
3311 break;
3312 case MSR_TSC_AUX:
3313 if (!msr_info->host_initiated &&
3314 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3315 return 1;
3316 /* Otherwise falls through */
3317 default:
3318 msr = find_msr_entry(vmx, msr_info->index);
3319 if (msr) {
3320 msr_info->data = msr->data;
3321 break;
3323 return kvm_get_msr_common(vcpu, msr_info);
3326 return 0;
3329 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3332 * Writes msr value into into the appropriate "register".
3333 * Returns 0 on success, non-0 otherwise.
3334 * Assumes vcpu_load() was already called.
3336 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3338 struct vcpu_vmx *vmx = to_vmx(vcpu);
3339 struct shared_msr_entry *msr;
3340 int ret = 0;
3341 u32 msr_index = msr_info->index;
3342 u64 data = msr_info->data;
3344 switch (msr_index) {
3345 case MSR_EFER:
3346 ret = kvm_set_msr_common(vcpu, msr_info);
3347 break;
3348 #ifdef CONFIG_X86_64
3349 case MSR_FS_BASE:
3350 vmx_segment_cache_clear(vmx);
3351 vmcs_writel(GUEST_FS_BASE, data);
3352 break;
3353 case MSR_GS_BASE:
3354 vmx_segment_cache_clear(vmx);
3355 vmcs_writel(GUEST_GS_BASE, data);
3356 break;
3357 case MSR_KERNEL_GS_BASE:
3358 vmx_load_host_state(vmx);
3359 vmx->msr_guest_kernel_gs_base = data;
3360 break;
3361 #endif
3362 case MSR_IA32_SYSENTER_CS:
3363 vmcs_write32(GUEST_SYSENTER_CS, data);
3364 break;
3365 case MSR_IA32_SYSENTER_EIP:
3366 vmcs_writel(GUEST_SYSENTER_EIP, data);
3367 break;
3368 case MSR_IA32_SYSENTER_ESP:
3369 vmcs_writel(GUEST_SYSENTER_ESP, data);
3370 break;
3371 case MSR_IA32_BNDCFGS:
3372 if (!kvm_mpx_supported() ||
3373 (!msr_info->host_initiated &&
3374 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3375 return 1;
3376 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
3377 (data & MSR_IA32_BNDCFGS_RSVD))
3378 return 1;
3379 vmcs_write64(GUEST_BNDCFGS, data);
3380 break;
3381 case MSR_IA32_TSC:
3382 kvm_write_tsc(vcpu, msr_info);
3383 break;
3384 case MSR_IA32_SPEC_CTRL:
3385 if (!msr_info->host_initiated &&
3386 !guest_cpuid_has(vcpu, X86_FEATURE_IBRS) &&
3387 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3388 return 1;
3390 /* The STIBP bit doesn't fault even if it's not advertised */
3391 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP))
3392 return 1;
3394 vmx->spec_ctrl = data;
3396 if (!data)
3397 break;
3400 * For non-nested:
3401 * When it's written (to non-zero) for the first time, pass
3402 * it through.
3404 * For nested:
3405 * The handling of the MSR bitmap for L2 guests is done in
3406 * nested_vmx_merge_msr_bitmap. We should not touch the
3407 * vmcs02.msr_bitmap here since it gets completely overwritten
3408 * in the merging. We update the vmcs01 here for L1 as well
3409 * since it will end up touching the MSR anyway now.
3411 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
3412 MSR_IA32_SPEC_CTRL,
3413 MSR_TYPE_RW);
3414 break;
3415 case MSR_IA32_PRED_CMD:
3416 if (!msr_info->host_initiated &&
3417 !guest_cpuid_has(vcpu, X86_FEATURE_IBPB) &&
3418 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3419 return 1;
3421 if (data & ~PRED_CMD_IBPB)
3422 return 1;
3424 if (!data)
3425 break;
3427 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
3430 * For non-nested:
3431 * When it's written (to non-zero) for the first time, pass
3432 * it through.
3434 * For nested:
3435 * The handling of the MSR bitmap for L2 guests is done in
3436 * nested_vmx_merge_msr_bitmap. We should not touch the
3437 * vmcs02.msr_bitmap here since it gets completely overwritten
3438 * in the merging.
3440 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
3441 MSR_TYPE_W);
3442 break;
3443 case MSR_IA32_ARCH_CAPABILITIES:
3444 if (!msr_info->host_initiated)
3445 return 1;
3446 vmx->arch_capabilities = data;
3447 break;
3448 case MSR_IA32_CR_PAT:
3449 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3450 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3451 return 1;
3452 vmcs_write64(GUEST_IA32_PAT, data);
3453 vcpu->arch.pat = data;
3454 break;
3456 ret = kvm_set_msr_common(vcpu, msr_info);
3457 break;
3458 case MSR_IA32_TSC_ADJUST:
3459 ret = kvm_set_msr_common(vcpu, msr_info);
3460 break;
3461 case MSR_IA32_MCG_EXT_CTL:
3462 if ((!msr_info->host_initiated &&
3463 !(to_vmx(vcpu)->msr_ia32_feature_control &
3464 FEATURE_CONTROL_LMCE)) ||
3465 (data & ~MCG_EXT_CTL_LMCE_EN))
3466 return 1;
3467 vcpu->arch.mcg_ext_ctl = data;
3468 break;
3469 case MSR_IA32_FEATURE_CONTROL:
3470 if (!vmx_feature_control_msr_valid(vcpu, data) ||
3471 (to_vmx(vcpu)->msr_ia32_feature_control &
3472 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
3473 return 1;
3474 vmx->msr_ia32_feature_control = data;
3475 if (msr_info->host_initiated && data == 0)
3476 vmx_leave_nested(vcpu);
3477 break;
3478 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3479 if (!msr_info->host_initiated)
3480 return 1; /* they are read-only */
3481 if (!nested_vmx_allowed(vcpu))
3482 return 1;
3483 return vmx_set_vmx_msr(vcpu, msr_index, data);
3484 case MSR_IA32_XSS:
3485 if (!vmx_xsaves_supported())
3486 return 1;
3488 * The only supported bit as of Skylake is bit 8, but
3489 * it is not supported on KVM.
3491 if (data != 0)
3492 return 1;
3493 vcpu->arch.ia32_xss = data;
3494 if (vcpu->arch.ia32_xss != host_xss)
3495 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
3496 vcpu->arch.ia32_xss, host_xss);
3497 else
3498 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
3499 break;
3500 case MSR_TSC_AUX:
3501 if (!msr_info->host_initiated &&
3502 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3503 return 1;
3504 /* Check reserved bit, higher 32 bits should be zero */
3505 if ((data >> 32) != 0)
3506 return 1;
3507 /* Otherwise falls through */
3508 default:
3509 msr = find_msr_entry(vmx, msr_index);
3510 if (msr) {
3511 u64 old_msr_data = msr->data;
3512 msr->data = data;
3513 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
3514 preempt_disable();
3515 ret = kvm_set_shared_msr(msr->index, msr->data,
3516 msr->mask);
3517 preempt_enable();
3518 if (ret)
3519 msr->data = old_msr_data;
3521 break;
3523 ret = kvm_set_msr_common(vcpu, msr_info);
3526 return ret;
3529 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
3531 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
3532 switch (reg) {
3533 case VCPU_REGS_RSP:
3534 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
3535 break;
3536 case VCPU_REGS_RIP:
3537 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
3538 break;
3539 case VCPU_EXREG_PDPTR:
3540 if (enable_ept)
3541 ept_save_pdptrs(vcpu);
3542 break;
3543 default:
3544 break;
3548 static __init int cpu_has_kvm_support(void)
3550 return cpu_has_vmx();
3553 static __init int vmx_disabled_by_bios(void)
3555 u64 msr;
3557 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
3558 if (msr & FEATURE_CONTROL_LOCKED) {
3559 /* launched w/ TXT and VMX disabled */
3560 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3561 && tboot_enabled())
3562 return 1;
3563 /* launched w/o TXT and VMX only enabled w/ TXT */
3564 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3565 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3566 && !tboot_enabled()) {
3567 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
3568 "activate TXT before enabling KVM\n");
3569 return 1;
3571 /* launched w/o TXT and VMX disabled */
3572 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3573 && !tboot_enabled())
3574 return 1;
3577 return 0;
3580 static void kvm_cpu_vmxon(u64 addr)
3582 cr4_set_bits(X86_CR4_VMXE);
3583 intel_pt_handle_vmx(1);
3585 asm volatile (ASM_VMX_VMXON_RAX
3586 : : "a"(&addr), "m"(addr)
3587 : "memory", "cc");
3590 static int hardware_enable(void)
3592 int cpu = raw_smp_processor_id();
3593 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
3594 u64 old, test_bits;
3596 if (cr4_read_shadow() & X86_CR4_VMXE)
3597 return -EBUSY;
3599 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
3600 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
3601 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
3604 * Now we can enable the vmclear operation in kdump
3605 * since the loaded_vmcss_on_cpu list on this cpu
3606 * has been initialized.
3608 * Though the cpu is not in VMX operation now, there
3609 * is no problem to enable the vmclear operation
3610 * for the loaded_vmcss_on_cpu list is empty!
3612 crash_enable_local_vmclear(cpu);
3614 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
3616 test_bits = FEATURE_CONTROL_LOCKED;
3617 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
3618 if (tboot_enabled())
3619 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
3621 if ((old & test_bits) != test_bits) {
3622 /* enable and lock */
3623 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
3625 kvm_cpu_vmxon(phys_addr);
3626 if (enable_ept)
3627 ept_sync_global();
3629 return 0;
3632 static void vmclear_local_loaded_vmcss(void)
3634 int cpu = raw_smp_processor_id();
3635 struct loaded_vmcs *v, *n;
3637 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
3638 loaded_vmcss_on_cpu_link)
3639 __loaded_vmcs_clear(v);
3643 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
3644 * tricks.
3646 static void kvm_cpu_vmxoff(void)
3648 asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
3650 intel_pt_handle_vmx(0);
3651 cr4_clear_bits(X86_CR4_VMXE);
3654 static void hardware_disable(void)
3656 vmclear_local_loaded_vmcss();
3657 kvm_cpu_vmxoff();
3660 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
3661 u32 msr, u32 *result)
3663 u32 vmx_msr_low, vmx_msr_high;
3664 u32 ctl = ctl_min | ctl_opt;
3666 rdmsr(msr, vmx_msr_low, vmx_msr_high);
3668 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
3669 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
3671 /* Ensure minimum (required) set of control bits are supported. */
3672 if (ctl_min & ~ctl)
3673 return -EIO;
3675 *result = ctl;
3676 return 0;
3679 static __init bool allow_1_setting(u32 msr, u32 ctl)
3681 u32 vmx_msr_low, vmx_msr_high;
3683 rdmsr(msr, vmx_msr_low, vmx_msr_high);
3684 return vmx_msr_high & ctl;
3687 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
3689 u32 vmx_msr_low, vmx_msr_high;
3690 u32 min, opt, min2, opt2;
3691 u32 _pin_based_exec_control = 0;
3692 u32 _cpu_based_exec_control = 0;
3693 u32 _cpu_based_2nd_exec_control = 0;
3694 u32 _vmexit_control = 0;
3695 u32 _vmentry_control = 0;
3697 min = CPU_BASED_HLT_EXITING |
3698 #ifdef CONFIG_X86_64
3699 CPU_BASED_CR8_LOAD_EXITING |
3700 CPU_BASED_CR8_STORE_EXITING |
3701 #endif
3702 CPU_BASED_CR3_LOAD_EXITING |
3703 CPU_BASED_CR3_STORE_EXITING |
3704 CPU_BASED_UNCOND_IO_EXITING |
3705 CPU_BASED_MOV_DR_EXITING |
3706 CPU_BASED_USE_TSC_OFFSETING |
3707 CPU_BASED_INVLPG_EXITING |
3708 CPU_BASED_RDPMC_EXITING;
3710 if (!kvm_mwait_in_guest())
3711 min |= CPU_BASED_MWAIT_EXITING |
3712 CPU_BASED_MONITOR_EXITING;
3714 opt = CPU_BASED_TPR_SHADOW |
3715 CPU_BASED_USE_MSR_BITMAPS |
3716 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3717 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
3718 &_cpu_based_exec_control) < 0)
3719 return -EIO;
3720 #ifdef CONFIG_X86_64
3721 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3722 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
3723 ~CPU_BASED_CR8_STORE_EXITING;
3724 #endif
3725 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
3726 min2 = 0;
3727 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3728 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3729 SECONDARY_EXEC_WBINVD_EXITING |
3730 SECONDARY_EXEC_ENABLE_VPID |
3731 SECONDARY_EXEC_ENABLE_EPT |
3732 SECONDARY_EXEC_UNRESTRICTED_GUEST |
3733 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
3734 SECONDARY_EXEC_DESC |
3735 SECONDARY_EXEC_RDTSCP |
3736 SECONDARY_EXEC_ENABLE_INVPCID |
3737 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3738 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3739 SECONDARY_EXEC_SHADOW_VMCS |
3740 SECONDARY_EXEC_XSAVES |
3741 SECONDARY_EXEC_RDSEED_EXITING |
3742 SECONDARY_EXEC_RDRAND_EXITING |
3743 SECONDARY_EXEC_ENABLE_PML |
3744 SECONDARY_EXEC_TSC_SCALING |
3745 SECONDARY_EXEC_ENABLE_VMFUNC;
3746 if (adjust_vmx_controls(min2, opt2,
3747 MSR_IA32_VMX_PROCBASED_CTLS2,
3748 &_cpu_based_2nd_exec_control) < 0)
3749 return -EIO;
3751 #ifndef CONFIG_X86_64
3752 if (!(_cpu_based_2nd_exec_control &
3753 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
3754 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
3755 #endif
3757 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3758 _cpu_based_2nd_exec_control &= ~(
3759 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3760 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3761 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3763 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
3764 &vmx_capability.ept, &vmx_capability.vpid);
3766 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
3767 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
3768 enabled */
3769 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
3770 CPU_BASED_CR3_STORE_EXITING |
3771 CPU_BASED_INVLPG_EXITING);
3772 } else if (vmx_capability.ept) {
3773 vmx_capability.ept = 0;
3774 pr_warn_once("EPT CAP should not exist if not support "
3775 "1-setting enable EPT VM-execution control\n");
3777 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
3778 vmx_capability.vpid) {
3779 vmx_capability.vpid = 0;
3780 pr_warn_once("VPID CAP should not exist if not support "
3781 "1-setting enable VPID VM-execution control\n");
3784 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
3785 #ifdef CONFIG_X86_64
3786 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
3787 #endif
3788 opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
3789 VM_EXIT_CLEAR_BNDCFGS;
3790 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
3791 &_vmexit_control) < 0)
3792 return -EIO;
3794 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
3795 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
3796 PIN_BASED_VMX_PREEMPTION_TIMER;
3797 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
3798 &_pin_based_exec_control) < 0)
3799 return -EIO;
3801 if (cpu_has_broken_vmx_preemption_timer())
3802 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3803 if (!(_cpu_based_2nd_exec_control &
3804 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
3805 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
3807 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
3808 opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
3809 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
3810 &_vmentry_control) < 0)
3811 return -EIO;
3813 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
3815 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
3816 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
3817 return -EIO;
3819 #ifdef CONFIG_X86_64
3820 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
3821 if (vmx_msr_high & (1u<<16))
3822 return -EIO;
3823 #endif
3825 /* Require Write-Back (WB) memory type for VMCS accesses. */
3826 if (((vmx_msr_high >> 18) & 15) != 6)
3827 return -EIO;
3829 vmcs_conf->size = vmx_msr_high & 0x1fff;
3830 vmcs_conf->order = get_order(vmcs_conf->size);
3831 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
3832 vmcs_conf->revision_id = vmx_msr_low;
3834 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
3835 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
3836 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
3837 vmcs_conf->vmexit_ctrl = _vmexit_control;
3838 vmcs_conf->vmentry_ctrl = _vmentry_control;
3840 cpu_has_load_ia32_efer =
3841 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3842 VM_ENTRY_LOAD_IA32_EFER)
3843 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3844 VM_EXIT_LOAD_IA32_EFER);
3846 cpu_has_load_perf_global_ctrl =
3847 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3848 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
3849 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3850 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
3853 * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
3854 * but due to errata below it can't be used. Workaround is to use
3855 * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
3857 * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
3859 * AAK155 (model 26)
3860 * AAP115 (model 30)
3861 * AAT100 (model 37)
3862 * BC86,AAY89,BD102 (model 44)
3863 * BA97 (model 46)
3866 if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
3867 switch (boot_cpu_data.x86_model) {
3868 case 26:
3869 case 30:
3870 case 37:
3871 case 44:
3872 case 46:
3873 cpu_has_load_perf_global_ctrl = false;
3874 printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
3875 "does not work properly. Using workaround\n");
3876 break;
3877 default:
3878 break;
3882 if (boot_cpu_has(X86_FEATURE_XSAVES))
3883 rdmsrl(MSR_IA32_XSS, host_xss);
3885 return 0;
3888 static struct vmcs *alloc_vmcs_cpu(int cpu)
3890 int node = cpu_to_node(cpu);
3891 struct page *pages;
3892 struct vmcs *vmcs;
3894 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
3895 if (!pages)
3896 return NULL;
3897 vmcs = page_address(pages);
3898 memset(vmcs, 0, vmcs_config.size);
3899 vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
3900 return vmcs;
3903 static void free_vmcs(struct vmcs *vmcs)
3905 free_pages((unsigned long)vmcs, vmcs_config.order);
3909 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
3911 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3913 if (!loaded_vmcs->vmcs)
3914 return;
3915 loaded_vmcs_clear(loaded_vmcs);
3916 free_vmcs(loaded_vmcs->vmcs);
3917 loaded_vmcs->vmcs = NULL;
3918 if (loaded_vmcs->msr_bitmap)
3919 free_page((unsigned long)loaded_vmcs->msr_bitmap);
3920 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
3923 static struct vmcs *alloc_vmcs(void)
3925 return alloc_vmcs_cpu(raw_smp_processor_id());
3928 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3930 loaded_vmcs->vmcs = alloc_vmcs();
3931 if (!loaded_vmcs->vmcs)
3932 return -ENOMEM;
3934 loaded_vmcs->shadow_vmcs = NULL;
3935 loaded_vmcs_init(loaded_vmcs);
3937 if (cpu_has_vmx_msr_bitmap()) {
3938 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
3939 if (!loaded_vmcs->msr_bitmap)
3940 goto out_vmcs;
3941 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
3943 return 0;
3945 out_vmcs:
3946 free_loaded_vmcs(loaded_vmcs);
3947 return -ENOMEM;
3950 static void free_kvm_area(void)
3952 int cpu;
3954 for_each_possible_cpu(cpu) {
3955 free_vmcs(per_cpu(vmxarea, cpu));
3956 per_cpu(vmxarea, cpu) = NULL;
3960 enum vmcs_field_width {
3961 VMCS_FIELD_WIDTH_U16 = 0,
3962 VMCS_FIELD_WIDTH_U64 = 1,
3963 VMCS_FIELD_WIDTH_U32 = 2,
3964 VMCS_FIELD_WIDTH_NATURAL_WIDTH = 3
3967 static inline int vmcs_field_width(unsigned long field)
3969 if (0x1 & field) /* the *_HIGH fields are all 32 bit */
3970 return VMCS_FIELD_WIDTH_U32;
3971 return (field >> 13) & 0x3 ;
3974 static inline int vmcs_field_readonly(unsigned long field)
3976 return (((field >> 10) & 0x3) == 1);
3979 static void init_vmcs_shadow_fields(void)
3981 int i, j;
3983 for (i = j = 0; i < max_shadow_read_only_fields; i++) {
3984 u16 field = shadow_read_only_fields[i];
3985 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
3986 (i + 1 == max_shadow_read_only_fields ||
3987 shadow_read_only_fields[i + 1] != field + 1))
3988 pr_err("Missing field from shadow_read_only_field %x\n",
3989 field + 1);
3991 clear_bit(field, vmx_vmread_bitmap);
3992 #ifdef CONFIG_X86_64
3993 if (field & 1)
3994 continue;
3995 #endif
3996 if (j < i)
3997 shadow_read_only_fields[j] = field;
3998 j++;
4000 max_shadow_read_only_fields = j;
4002 for (i = j = 0; i < max_shadow_read_write_fields; i++) {
4003 u16 field = shadow_read_write_fields[i];
4004 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4005 (i + 1 == max_shadow_read_write_fields ||
4006 shadow_read_write_fields[i + 1] != field + 1))
4007 pr_err("Missing field from shadow_read_write_field %x\n",
4008 field + 1);
4011 * PML and the preemption timer can be emulated, but the
4012 * processor cannot vmwrite to fields that don't exist
4013 * on bare metal.
4015 switch (field) {
4016 case GUEST_PML_INDEX:
4017 if (!cpu_has_vmx_pml())
4018 continue;
4019 break;
4020 case VMX_PREEMPTION_TIMER_VALUE:
4021 if (!cpu_has_vmx_preemption_timer())
4022 continue;
4023 break;
4024 case GUEST_INTR_STATUS:
4025 if (!cpu_has_vmx_apicv())
4026 continue;
4027 break;
4028 default:
4029 break;
4032 clear_bit(field, vmx_vmwrite_bitmap);
4033 clear_bit(field, vmx_vmread_bitmap);
4034 #ifdef CONFIG_X86_64
4035 if (field & 1)
4036 continue;
4037 #endif
4038 if (j < i)
4039 shadow_read_write_fields[j] = field;
4040 j++;
4042 max_shadow_read_write_fields = j;
4045 static __init int alloc_kvm_area(void)
4047 int cpu;
4049 for_each_possible_cpu(cpu) {
4050 struct vmcs *vmcs;
4052 vmcs = alloc_vmcs_cpu(cpu);
4053 if (!vmcs) {
4054 free_kvm_area();
4055 return -ENOMEM;
4058 per_cpu(vmxarea, cpu) = vmcs;
4060 return 0;
4063 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4064 struct kvm_segment *save)
4066 if (!emulate_invalid_guest_state) {
4068 * CS and SS RPL should be equal during guest entry according
4069 * to VMX spec, but in reality it is not always so. Since vcpu
4070 * is in the middle of the transition from real mode to
4071 * protected mode it is safe to assume that RPL 0 is a good
4072 * default value.
4074 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4075 save->selector &= ~SEGMENT_RPL_MASK;
4076 save->dpl = save->selector & SEGMENT_RPL_MASK;
4077 save->s = 1;
4079 vmx_set_segment(vcpu, save, seg);
4082 static void enter_pmode(struct kvm_vcpu *vcpu)
4084 unsigned long flags;
4085 struct vcpu_vmx *vmx = to_vmx(vcpu);
4088 * Update real mode segment cache. It may be not up-to-date if sement
4089 * register was written while vcpu was in a guest mode.
4091 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4092 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4093 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4094 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4095 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4096 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4098 vmx->rmode.vm86_active = 0;
4100 vmx_segment_cache_clear(vmx);
4102 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4104 flags = vmcs_readl(GUEST_RFLAGS);
4105 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4106 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4107 vmcs_writel(GUEST_RFLAGS, flags);
4109 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4110 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4112 update_exception_bitmap(vcpu);
4114 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4115 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4116 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4117 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4118 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4119 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4122 static void fix_rmode_seg(int seg, struct kvm_segment *save)
4124 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4125 struct kvm_segment var = *save;
4127 var.dpl = 0x3;
4128 if (seg == VCPU_SREG_CS)
4129 var.type = 0x3;
4131 if (!emulate_invalid_guest_state) {
4132 var.selector = var.base >> 4;
4133 var.base = var.base & 0xffff0;
4134 var.limit = 0xffff;
4135 var.g = 0;
4136 var.db = 0;
4137 var.present = 1;
4138 var.s = 1;
4139 var.l = 0;
4140 var.unusable = 0;
4141 var.type = 0x3;
4142 var.avl = 0;
4143 if (save->base & 0xf)
4144 printk_once(KERN_WARNING "kvm: segment base is not "
4145 "paragraph aligned when entering "
4146 "protected mode (seg=%d)", seg);
4149 vmcs_write16(sf->selector, var.selector);
4150 vmcs_writel(sf->base, var.base);
4151 vmcs_write32(sf->limit, var.limit);
4152 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
4155 static void enter_rmode(struct kvm_vcpu *vcpu)
4157 unsigned long flags;
4158 struct vcpu_vmx *vmx = to_vmx(vcpu);
4160 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4161 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4162 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4163 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4164 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4165 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4166 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4168 vmx->rmode.vm86_active = 1;
4171 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4172 * vcpu. Warn the user that an update is overdue.
4174 if (!vcpu->kvm->arch.tss_addr)
4175 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
4176 "called before entering vcpu\n");
4178 vmx_segment_cache_clear(vmx);
4180 vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
4181 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
4182 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4184 flags = vmcs_readl(GUEST_RFLAGS);
4185 vmx->rmode.save_rflags = flags;
4187 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
4189 vmcs_writel(GUEST_RFLAGS, flags);
4190 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
4191 update_exception_bitmap(vcpu);
4193 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4194 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4195 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4196 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4197 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4198 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4200 kvm_mmu_reset_context(vcpu);
4203 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
4205 struct vcpu_vmx *vmx = to_vmx(vcpu);
4206 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
4208 if (!msr)
4209 return;
4212 * Force kernel_gs_base reloading before EFER changes, as control
4213 * of this msr depends on is_long_mode().
4215 vmx_load_host_state(to_vmx(vcpu));
4216 vcpu->arch.efer = efer;
4217 if (efer & EFER_LMA) {
4218 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4219 msr->data = efer;
4220 } else {
4221 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4223 msr->data = efer & ~EFER_LME;
4225 setup_msrs(vmx);
4228 #ifdef CONFIG_X86_64
4230 static void enter_lmode(struct kvm_vcpu *vcpu)
4232 u32 guest_tr_ar;
4234 vmx_segment_cache_clear(to_vmx(vcpu));
4236 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4237 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
4238 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
4239 __func__);
4240 vmcs_write32(GUEST_TR_AR_BYTES,
4241 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
4242 | VMX_AR_TYPE_BUSY_64_TSS);
4244 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
4247 static void exit_lmode(struct kvm_vcpu *vcpu)
4249 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4250 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
4253 #endif
4255 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
4256 bool invalidate_gpa)
4258 if (enable_ept && (invalidate_gpa || !enable_vpid)) {
4259 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4260 return;
4261 ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa));
4262 } else {
4263 vpid_sync_context(vpid);
4267 static void vmx_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
4269 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid, invalidate_gpa);
4272 static void vmx_flush_tlb_ept_only(struct kvm_vcpu *vcpu)
4274 if (enable_ept)
4275 vmx_flush_tlb(vcpu, true);
4278 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
4280 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
4282 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
4283 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
4286 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
4288 if (enable_ept && is_paging(vcpu))
4289 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4290 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
4293 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
4295 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
4297 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
4298 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
4301 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
4303 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4305 if (!test_bit(VCPU_EXREG_PDPTR,
4306 (unsigned long *)&vcpu->arch.regs_dirty))
4307 return;
4309 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4310 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
4311 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
4312 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
4313 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
4317 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
4319 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4321 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4322 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
4323 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
4324 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
4325 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
4328 __set_bit(VCPU_EXREG_PDPTR,
4329 (unsigned long *)&vcpu->arch.regs_avail);
4330 __set_bit(VCPU_EXREG_PDPTR,
4331 (unsigned long *)&vcpu->arch.regs_dirty);
4334 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4336 u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
4337 u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
4338 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4340 if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
4341 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
4342 nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
4343 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
4345 return fixed_bits_valid(val, fixed0, fixed1);
4348 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4350 u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
4351 u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
4353 return fixed_bits_valid(val, fixed0, fixed1);
4356 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
4358 u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed0;
4359 u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed1;
4361 return fixed_bits_valid(val, fixed0, fixed1);
4364 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
4365 #define nested_guest_cr4_valid nested_cr4_valid
4366 #define nested_host_cr4_valid nested_cr4_valid
4368 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
4370 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
4371 unsigned long cr0,
4372 struct kvm_vcpu *vcpu)
4374 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
4375 vmx_decache_cr3(vcpu);
4376 if (!(cr0 & X86_CR0_PG)) {
4377 /* From paging/starting to nonpaging */
4378 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4379 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
4380 (CPU_BASED_CR3_LOAD_EXITING |
4381 CPU_BASED_CR3_STORE_EXITING));
4382 vcpu->arch.cr0 = cr0;
4383 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4384 } else if (!is_paging(vcpu)) {
4385 /* From nonpaging to paging */
4386 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4387 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
4388 ~(CPU_BASED_CR3_LOAD_EXITING |
4389 CPU_BASED_CR3_STORE_EXITING));
4390 vcpu->arch.cr0 = cr0;
4391 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4394 if (!(cr0 & X86_CR0_WP))
4395 *hw_cr0 &= ~X86_CR0_WP;
4398 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
4400 struct vcpu_vmx *vmx = to_vmx(vcpu);
4401 unsigned long hw_cr0;
4403 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
4404 if (enable_unrestricted_guest)
4405 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
4406 else {
4407 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
4409 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
4410 enter_pmode(vcpu);
4412 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
4413 enter_rmode(vcpu);
4416 #ifdef CONFIG_X86_64
4417 if (vcpu->arch.efer & EFER_LME) {
4418 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
4419 enter_lmode(vcpu);
4420 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
4421 exit_lmode(vcpu);
4423 #endif
4425 if (enable_ept)
4426 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
4428 vmcs_writel(CR0_READ_SHADOW, cr0);
4429 vmcs_writel(GUEST_CR0, hw_cr0);
4430 vcpu->arch.cr0 = cr0;
4432 /* depends on vcpu->arch.cr0 to be set to a new value */
4433 vmx->emulation_required = emulation_required(vcpu);
4436 static int get_ept_level(struct kvm_vcpu *vcpu)
4438 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
4439 return 5;
4440 return 4;
4443 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
4445 u64 eptp = VMX_EPTP_MT_WB;
4447 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
4449 if (enable_ept_ad_bits &&
4450 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
4451 eptp |= VMX_EPTP_AD_ENABLE_BIT;
4452 eptp |= (root_hpa & PAGE_MASK);
4454 return eptp;
4457 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
4459 unsigned long guest_cr3;
4460 u64 eptp;
4462 guest_cr3 = cr3;
4463 if (enable_ept) {
4464 eptp = construct_eptp(vcpu, cr3);
4465 vmcs_write64(EPT_POINTER, eptp);
4466 if (is_paging(vcpu) || is_guest_mode(vcpu))
4467 guest_cr3 = kvm_read_cr3(vcpu);
4468 else
4469 guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
4470 ept_load_pdptrs(vcpu);
4473 vmx_flush_tlb(vcpu, true);
4474 vmcs_writel(GUEST_CR3, guest_cr3);
4477 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
4480 * Pass through host's Machine Check Enable value to hw_cr4, which
4481 * is in force while we are in guest mode. Do not let guests control
4482 * this bit, even if host CR4.MCE == 0.
4484 unsigned long hw_cr4 =
4485 (cr4_read_shadow() & X86_CR4_MCE) |
4486 (cr4 & ~X86_CR4_MCE) |
4487 (to_vmx(vcpu)->rmode.vm86_active ?
4488 KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
4490 if ((cr4 & X86_CR4_UMIP) && !boot_cpu_has(X86_FEATURE_UMIP)) {
4491 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
4492 SECONDARY_EXEC_DESC);
4493 hw_cr4 &= ~X86_CR4_UMIP;
4494 } else if (!is_guest_mode(vcpu) ||
4495 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
4496 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
4497 SECONDARY_EXEC_DESC);
4499 if (cr4 & X86_CR4_VMXE) {
4501 * To use VMXON (and later other VMX instructions), a guest
4502 * must first be able to turn on cr4.VMXE (see handle_vmon()).
4503 * So basically the check on whether to allow nested VMX
4504 * is here.
4506 if (!nested_vmx_allowed(vcpu))
4507 return 1;
4510 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
4511 return 1;
4513 vcpu->arch.cr4 = cr4;
4514 if (enable_ept) {
4515 if (!is_paging(vcpu)) {
4516 hw_cr4 &= ~X86_CR4_PAE;
4517 hw_cr4 |= X86_CR4_PSE;
4518 } else if (!(cr4 & X86_CR4_PAE)) {
4519 hw_cr4 &= ~X86_CR4_PAE;
4523 if (!enable_unrestricted_guest && !is_paging(vcpu))
4525 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
4526 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
4527 * to be manually disabled when guest switches to non-paging
4528 * mode.
4530 * If !enable_unrestricted_guest, the CPU is always running
4531 * with CR0.PG=1 and CR4 needs to be modified.
4532 * If enable_unrestricted_guest, the CPU automatically
4533 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
4535 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
4537 vmcs_writel(CR4_READ_SHADOW, cr4);
4538 vmcs_writel(GUEST_CR4, hw_cr4);
4539 return 0;
4542 static void vmx_get_segment(struct kvm_vcpu *vcpu,
4543 struct kvm_segment *var, int seg)
4545 struct vcpu_vmx *vmx = to_vmx(vcpu);
4546 u32 ar;
4548 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4549 *var = vmx->rmode.segs[seg];
4550 if (seg == VCPU_SREG_TR
4551 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
4552 return;
4553 var->base = vmx_read_guest_seg_base(vmx, seg);
4554 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4555 return;
4557 var->base = vmx_read_guest_seg_base(vmx, seg);
4558 var->limit = vmx_read_guest_seg_limit(vmx, seg);
4559 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4560 ar = vmx_read_guest_seg_ar(vmx, seg);
4561 var->unusable = (ar >> 16) & 1;
4562 var->type = ar & 15;
4563 var->s = (ar >> 4) & 1;
4564 var->dpl = (ar >> 5) & 3;
4566 * Some userspaces do not preserve unusable property. Since usable
4567 * segment has to be present according to VMX spec we can use present
4568 * property to amend userspace bug by making unusable segment always
4569 * nonpresent. vmx_segment_access_rights() already marks nonpresent
4570 * segment as unusable.
4572 var->present = !var->unusable;
4573 var->avl = (ar >> 12) & 1;
4574 var->l = (ar >> 13) & 1;
4575 var->db = (ar >> 14) & 1;
4576 var->g = (ar >> 15) & 1;
4579 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
4581 struct kvm_segment s;
4583 if (to_vmx(vcpu)->rmode.vm86_active) {
4584 vmx_get_segment(vcpu, &s, seg);
4585 return s.base;
4587 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
4590 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
4592 struct vcpu_vmx *vmx = to_vmx(vcpu);
4594 if (unlikely(vmx->rmode.vm86_active))
4595 return 0;
4596 else {
4597 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
4598 return VMX_AR_DPL(ar);
4602 static u32 vmx_segment_access_rights(struct kvm_segment *var)
4604 u32 ar;
4606 if (var->unusable || !var->present)
4607 ar = 1 << 16;
4608 else {
4609 ar = var->type & 15;
4610 ar |= (var->s & 1) << 4;
4611 ar |= (var->dpl & 3) << 5;
4612 ar |= (var->present & 1) << 7;
4613 ar |= (var->avl & 1) << 12;
4614 ar |= (var->l & 1) << 13;
4615 ar |= (var->db & 1) << 14;
4616 ar |= (var->g & 1) << 15;
4619 return ar;
4622 static void vmx_set_segment(struct kvm_vcpu *vcpu,
4623 struct kvm_segment *var, int seg)
4625 struct vcpu_vmx *vmx = to_vmx(vcpu);
4626 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4628 vmx_segment_cache_clear(vmx);
4630 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4631 vmx->rmode.segs[seg] = *var;
4632 if (seg == VCPU_SREG_TR)
4633 vmcs_write16(sf->selector, var->selector);
4634 else if (var->s)
4635 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
4636 goto out;
4639 vmcs_writel(sf->base, var->base);
4640 vmcs_write32(sf->limit, var->limit);
4641 vmcs_write16(sf->selector, var->selector);
4644 * Fix the "Accessed" bit in AR field of segment registers for older
4645 * qemu binaries.
4646 * IA32 arch specifies that at the time of processor reset the
4647 * "Accessed" bit in the AR field of segment registers is 1. And qemu
4648 * is setting it to 0 in the userland code. This causes invalid guest
4649 * state vmexit when "unrestricted guest" mode is turned on.
4650 * Fix for this setup issue in cpu_reset is being pushed in the qemu
4651 * tree. Newer qemu binaries with that qemu fix would not need this
4652 * kvm hack.
4654 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
4655 var->type |= 0x1; /* Accessed */
4657 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
4659 out:
4660 vmx->emulation_required = emulation_required(vcpu);
4663 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4665 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
4667 *db = (ar >> 14) & 1;
4668 *l = (ar >> 13) & 1;
4671 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4673 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
4674 dt->address = vmcs_readl(GUEST_IDTR_BASE);
4677 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4679 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
4680 vmcs_writel(GUEST_IDTR_BASE, dt->address);
4683 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4685 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
4686 dt->address = vmcs_readl(GUEST_GDTR_BASE);
4689 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4691 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
4692 vmcs_writel(GUEST_GDTR_BASE, dt->address);
4695 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
4697 struct kvm_segment var;
4698 u32 ar;
4700 vmx_get_segment(vcpu, &var, seg);
4701 var.dpl = 0x3;
4702 if (seg == VCPU_SREG_CS)
4703 var.type = 0x3;
4704 ar = vmx_segment_access_rights(&var);
4706 if (var.base != (var.selector << 4))
4707 return false;
4708 if (var.limit != 0xffff)
4709 return false;
4710 if (ar != 0xf3)
4711 return false;
4713 return true;
4716 static bool code_segment_valid(struct kvm_vcpu *vcpu)
4718 struct kvm_segment cs;
4719 unsigned int cs_rpl;
4721 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4722 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
4724 if (cs.unusable)
4725 return false;
4726 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
4727 return false;
4728 if (!cs.s)
4729 return false;
4730 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
4731 if (cs.dpl > cs_rpl)
4732 return false;
4733 } else {
4734 if (cs.dpl != cs_rpl)
4735 return false;
4737 if (!cs.present)
4738 return false;
4740 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
4741 return true;
4744 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
4746 struct kvm_segment ss;
4747 unsigned int ss_rpl;
4749 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4750 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
4752 if (ss.unusable)
4753 return true;
4754 if (ss.type != 3 && ss.type != 7)
4755 return false;
4756 if (!ss.s)
4757 return false;
4758 if (ss.dpl != ss_rpl) /* DPL != RPL */
4759 return false;
4760 if (!ss.present)
4761 return false;
4763 return true;
4766 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
4768 struct kvm_segment var;
4769 unsigned int rpl;
4771 vmx_get_segment(vcpu, &var, seg);
4772 rpl = var.selector & SEGMENT_RPL_MASK;
4774 if (var.unusable)
4775 return true;
4776 if (!var.s)
4777 return false;
4778 if (!var.present)
4779 return false;
4780 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
4781 if (var.dpl < rpl) /* DPL < RPL */
4782 return false;
4785 /* TODO: Add other members to kvm_segment_field to allow checking for other access
4786 * rights flags
4788 return true;
4791 static bool tr_valid(struct kvm_vcpu *vcpu)
4793 struct kvm_segment tr;
4795 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
4797 if (tr.unusable)
4798 return false;
4799 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
4800 return false;
4801 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
4802 return false;
4803 if (!tr.present)
4804 return false;
4806 return true;
4809 static bool ldtr_valid(struct kvm_vcpu *vcpu)
4811 struct kvm_segment ldtr;
4813 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
4815 if (ldtr.unusable)
4816 return true;
4817 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
4818 return false;
4819 if (ldtr.type != 2)
4820 return false;
4821 if (!ldtr.present)
4822 return false;
4824 return true;
4827 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
4829 struct kvm_segment cs, ss;
4831 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4832 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4834 return ((cs.selector & SEGMENT_RPL_MASK) ==
4835 (ss.selector & SEGMENT_RPL_MASK));
4839 * Check if guest state is valid. Returns true if valid, false if
4840 * not.
4841 * We assume that registers are always usable
4843 static bool guest_state_valid(struct kvm_vcpu *vcpu)
4845 if (enable_unrestricted_guest)
4846 return true;
4848 /* real mode guest state checks */
4849 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
4850 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
4851 return false;
4852 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
4853 return false;
4854 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
4855 return false;
4856 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
4857 return false;
4858 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
4859 return false;
4860 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
4861 return false;
4862 } else {
4863 /* protected mode guest state checks */
4864 if (!cs_ss_rpl_check(vcpu))
4865 return false;
4866 if (!code_segment_valid(vcpu))
4867 return false;
4868 if (!stack_segment_valid(vcpu))
4869 return false;
4870 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
4871 return false;
4872 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
4873 return false;
4874 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
4875 return false;
4876 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
4877 return false;
4878 if (!tr_valid(vcpu))
4879 return false;
4880 if (!ldtr_valid(vcpu))
4881 return false;
4883 /* TODO:
4884 * - Add checks on RIP
4885 * - Add checks on RFLAGS
4888 return true;
4891 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
4893 return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
4896 static int init_rmode_tss(struct kvm *kvm)
4898 gfn_t fn;
4899 u16 data = 0;
4900 int idx, r;
4902 idx = srcu_read_lock(&kvm->srcu);
4903 fn = kvm->arch.tss_addr >> PAGE_SHIFT;
4904 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4905 if (r < 0)
4906 goto out;
4907 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
4908 r = kvm_write_guest_page(kvm, fn++, &data,
4909 TSS_IOPB_BASE_OFFSET, sizeof(u16));
4910 if (r < 0)
4911 goto out;
4912 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
4913 if (r < 0)
4914 goto out;
4915 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4916 if (r < 0)
4917 goto out;
4918 data = ~0;
4919 r = kvm_write_guest_page(kvm, fn, &data,
4920 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
4921 sizeof(u8));
4922 out:
4923 srcu_read_unlock(&kvm->srcu, idx);
4924 return r;
4927 static int init_rmode_identity_map(struct kvm *kvm)
4929 int i, idx, r = 0;
4930 kvm_pfn_t identity_map_pfn;
4931 u32 tmp;
4933 /* Protect kvm->arch.ept_identity_pagetable_done. */
4934 mutex_lock(&kvm->slots_lock);
4936 if (likely(kvm->arch.ept_identity_pagetable_done))
4937 goto out2;
4939 if (!kvm->arch.ept_identity_map_addr)
4940 kvm->arch.ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
4941 identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
4943 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
4944 kvm->arch.ept_identity_map_addr, PAGE_SIZE);
4945 if (r < 0)
4946 goto out2;
4948 idx = srcu_read_lock(&kvm->srcu);
4949 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
4950 if (r < 0)
4951 goto out;
4952 /* Set up identity-mapping pagetable for EPT in real mode */
4953 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
4954 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
4955 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
4956 r = kvm_write_guest_page(kvm, identity_map_pfn,
4957 &tmp, i * sizeof(tmp), sizeof(tmp));
4958 if (r < 0)
4959 goto out;
4961 kvm->arch.ept_identity_pagetable_done = true;
4963 out:
4964 srcu_read_unlock(&kvm->srcu, idx);
4966 out2:
4967 mutex_unlock(&kvm->slots_lock);
4968 return r;
4971 static void seg_setup(int seg)
4973 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4974 unsigned int ar;
4976 vmcs_write16(sf->selector, 0);
4977 vmcs_writel(sf->base, 0);
4978 vmcs_write32(sf->limit, 0xffff);
4979 ar = 0x93;
4980 if (seg == VCPU_SREG_CS)
4981 ar |= 0x08; /* code segment */
4983 vmcs_write32(sf->ar_bytes, ar);
4986 static int alloc_apic_access_page(struct kvm *kvm)
4988 struct page *page;
4989 int r = 0;
4991 mutex_lock(&kvm->slots_lock);
4992 if (kvm->arch.apic_access_page_done)
4993 goto out;
4994 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
4995 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
4996 if (r)
4997 goto out;
4999 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
5000 if (is_error_page(page)) {
5001 r = -EFAULT;
5002 goto out;
5006 * Do not pin the page in memory, so that memory hot-unplug
5007 * is able to migrate it.
5009 put_page(page);
5010 kvm->arch.apic_access_page_done = true;
5011 out:
5012 mutex_unlock(&kvm->slots_lock);
5013 return r;
5016 static int allocate_vpid(void)
5018 int vpid;
5020 if (!enable_vpid)
5021 return 0;
5022 spin_lock(&vmx_vpid_lock);
5023 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5024 if (vpid < VMX_NR_VPIDS)
5025 __set_bit(vpid, vmx_vpid_bitmap);
5026 else
5027 vpid = 0;
5028 spin_unlock(&vmx_vpid_lock);
5029 return vpid;
5032 static void free_vpid(int vpid)
5034 if (!enable_vpid || vpid == 0)
5035 return;
5036 spin_lock(&vmx_vpid_lock);
5037 __clear_bit(vpid, vmx_vpid_bitmap);
5038 spin_unlock(&vmx_vpid_lock);
5041 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5042 u32 msr, int type)
5044 int f = sizeof(unsigned long);
5046 if (!cpu_has_vmx_msr_bitmap())
5047 return;
5050 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5051 * have the write-low and read-high bitmap offsets the wrong way round.
5052 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5054 if (msr <= 0x1fff) {
5055 if (type & MSR_TYPE_R)
5056 /* read-low */
5057 __clear_bit(msr, msr_bitmap + 0x000 / f);
5059 if (type & MSR_TYPE_W)
5060 /* write-low */
5061 __clear_bit(msr, msr_bitmap + 0x800 / f);
5063 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5064 msr &= 0x1fff;
5065 if (type & MSR_TYPE_R)
5066 /* read-high */
5067 __clear_bit(msr, msr_bitmap + 0x400 / f);
5069 if (type & MSR_TYPE_W)
5070 /* write-high */
5071 __clear_bit(msr, msr_bitmap + 0xc00 / f);
5076 static void __always_inline vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5077 u32 msr, int type)
5079 int f = sizeof(unsigned long);
5081 if (!cpu_has_vmx_msr_bitmap())
5082 return;
5085 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5086 * have the write-low and read-high bitmap offsets the wrong way round.
5087 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5089 if (msr <= 0x1fff) {
5090 if (type & MSR_TYPE_R)
5091 /* read-low */
5092 __set_bit(msr, msr_bitmap + 0x000 / f);
5094 if (type & MSR_TYPE_W)
5095 /* write-low */
5096 __set_bit(msr, msr_bitmap + 0x800 / f);
5098 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5099 msr &= 0x1fff;
5100 if (type & MSR_TYPE_R)
5101 /* read-high */
5102 __set_bit(msr, msr_bitmap + 0x400 / f);
5104 if (type & MSR_TYPE_W)
5105 /* write-high */
5106 __set_bit(msr, msr_bitmap + 0xc00 / f);
5111 static void __always_inline vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
5112 u32 msr, int type, bool value)
5114 if (value)
5115 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
5116 else
5117 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
5121 * If a msr is allowed by L0, we should check whether it is allowed by L1.
5122 * The corresponding bit will be cleared unless both of L0 and L1 allow it.
5124 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
5125 unsigned long *msr_bitmap_nested,
5126 u32 msr, int type)
5128 int f = sizeof(unsigned long);
5131 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5132 * have the write-low and read-high bitmap offsets the wrong way round.
5133 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5135 if (msr <= 0x1fff) {
5136 if (type & MSR_TYPE_R &&
5137 !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
5138 /* read-low */
5139 __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
5141 if (type & MSR_TYPE_W &&
5142 !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
5143 /* write-low */
5144 __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
5146 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5147 msr &= 0x1fff;
5148 if (type & MSR_TYPE_R &&
5149 !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
5150 /* read-high */
5151 __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
5153 if (type & MSR_TYPE_W &&
5154 !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
5155 /* write-high */
5156 __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
5161 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
5163 u8 mode = 0;
5165 if (cpu_has_secondary_exec_ctrls() &&
5166 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
5167 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
5168 mode |= MSR_BITMAP_MODE_X2APIC;
5169 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
5170 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
5173 if (is_long_mode(vcpu))
5174 mode |= MSR_BITMAP_MODE_LM;
5176 return mode;
5179 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
5181 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
5182 u8 mode)
5184 int msr;
5186 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
5187 unsigned word = msr / BITS_PER_LONG;
5188 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
5189 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
5192 if (mode & MSR_BITMAP_MODE_X2APIC) {
5194 * TPR reads and writes can be virtualized even if virtual interrupt
5195 * delivery is not in use.
5197 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
5198 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
5199 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
5200 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
5201 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
5206 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
5208 struct vcpu_vmx *vmx = to_vmx(vcpu);
5209 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
5210 u8 mode = vmx_msr_bitmap_mode(vcpu);
5211 u8 changed = mode ^ vmx->msr_bitmap_mode;
5213 if (!changed)
5214 return;
5216 vmx_set_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW,
5217 !(mode & MSR_BITMAP_MODE_LM));
5219 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
5220 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
5222 vmx->msr_bitmap_mode = mode;
5225 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
5227 return enable_apicv;
5230 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
5232 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5233 gfn_t gfn;
5236 * Don't need to mark the APIC access page dirty; it is never
5237 * written to by the CPU during APIC virtualization.
5240 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
5241 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
5242 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5245 if (nested_cpu_has_posted_intr(vmcs12)) {
5246 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
5247 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5252 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
5254 struct vcpu_vmx *vmx = to_vmx(vcpu);
5255 int max_irr;
5256 void *vapic_page;
5257 u16 status;
5259 if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
5260 return;
5262 vmx->nested.pi_pending = false;
5263 if (!pi_test_and_clear_on(vmx->nested.pi_desc))
5264 return;
5266 max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
5267 if (max_irr != 256) {
5268 vapic_page = kmap(vmx->nested.virtual_apic_page);
5269 __kvm_apic_update_irr(vmx->nested.pi_desc->pir,
5270 vapic_page, &max_irr);
5271 kunmap(vmx->nested.virtual_apic_page);
5273 status = vmcs_read16(GUEST_INTR_STATUS);
5274 if ((u8)max_irr > ((u8)status & 0xff)) {
5275 status &= ~0xff;
5276 status |= (u8)max_irr;
5277 vmcs_write16(GUEST_INTR_STATUS, status);
5281 nested_mark_vmcs12_pages_dirty(vcpu);
5284 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
5285 bool nested)
5287 #ifdef CONFIG_SMP
5288 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
5290 if (vcpu->mode == IN_GUEST_MODE) {
5292 * The vector of interrupt to be delivered to vcpu had
5293 * been set in PIR before this function.
5295 * Following cases will be reached in this block, and
5296 * we always send a notification event in all cases as
5297 * explained below.
5299 * Case 1: vcpu keeps in non-root mode. Sending a
5300 * notification event posts the interrupt to vcpu.
5302 * Case 2: vcpu exits to root mode and is still
5303 * runnable. PIR will be synced to vIRR before the
5304 * next vcpu entry. Sending a notification event in
5305 * this case has no effect, as vcpu is not in root
5306 * mode.
5308 * Case 3: vcpu exits to root mode and is blocked.
5309 * vcpu_block() has already synced PIR to vIRR and
5310 * never blocks vcpu if vIRR is not cleared. Therefore,
5311 * a blocked vcpu here does not wait for any requested
5312 * interrupts in PIR, and sending a notification event
5313 * which has no effect is safe here.
5316 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
5317 return true;
5319 #endif
5320 return false;
5323 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
5324 int vector)
5326 struct vcpu_vmx *vmx = to_vmx(vcpu);
5328 if (is_guest_mode(vcpu) &&
5329 vector == vmx->nested.posted_intr_nv) {
5331 * If a posted intr is not recognized by hardware,
5332 * we will accomplish it in the next vmentry.
5334 vmx->nested.pi_pending = true;
5335 kvm_make_request(KVM_REQ_EVENT, vcpu);
5336 /* the PIR and ON have been set by L1. */
5337 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
5338 kvm_vcpu_kick(vcpu);
5339 return 0;
5341 return -1;
5344 * Send interrupt to vcpu via posted interrupt way.
5345 * 1. If target vcpu is running(non-root mode), send posted interrupt
5346 * notification to vcpu and hardware will sync PIR to vIRR atomically.
5347 * 2. If target vcpu isn't running(root mode), kick it to pick up the
5348 * interrupt from PIR in next vmentry.
5350 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
5352 struct vcpu_vmx *vmx = to_vmx(vcpu);
5353 int r;
5355 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
5356 if (!r)
5357 return;
5359 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
5360 return;
5362 /* If a previous notification has sent the IPI, nothing to do. */
5363 if (pi_test_and_set_on(&vmx->pi_desc))
5364 return;
5366 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
5367 kvm_vcpu_kick(vcpu);
5371 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
5372 * will not change in the lifetime of the guest.
5373 * Note that host-state that does change is set elsewhere. E.g., host-state
5374 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
5376 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
5378 u32 low32, high32;
5379 unsigned long tmpl;
5380 struct desc_ptr dt;
5381 unsigned long cr0, cr3, cr4;
5383 cr0 = read_cr0();
5384 WARN_ON(cr0 & X86_CR0_TS);
5385 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
5388 * Save the most likely value for this task's CR3 in the VMCS.
5389 * We can't use __get_current_cr3_fast() because we're not atomic.
5391 cr3 = __read_cr3();
5392 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
5393 vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
5395 /* Save the most likely value for this task's CR4 in the VMCS. */
5396 cr4 = cr4_read_shadow();
5397 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
5398 vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
5400 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
5401 #ifdef CONFIG_X86_64
5403 * Load null selectors, so we can avoid reloading them in
5404 * __vmx_load_host_state(), in case userspace uses the null selectors
5405 * too (the expected case).
5407 vmcs_write16(HOST_DS_SELECTOR, 0);
5408 vmcs_write16(HOST_ES_SELECTOR, 0);
5409 #else
5410 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5411 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5412 #endif
5413 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5414 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
5416 store_idt(&dt);
5417 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
5418 vmx->host_idt_base = dt.address;
5420 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
5422 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
5423 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
5424 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
5425 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
5427 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
5428 rdmsr(MSR_IA32_CR_PAT, low32, high32);
5429 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
5433 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
5435 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
5436 if (enable_ept)
5437 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
5438 if (is_guest_mode(&vmx->vcpu))
5439 vmx->vcpu.arch.cr4_guest_owned_bits &=
5440 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
5441 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
5444 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
5446 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
5448 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
5449 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
5451 if (!enable_vnmi)
5452 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
5454 /* Enable the preemption timer dynamically */
5455 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
5456 return pin_based_exec_ctrl;
5459 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5461 struct vcpu_vmx *vmx = to_vmx(vcpu);
5463 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5464 if (cpu_has_secondary_exec_ctrls()) {
5465 if (kvm_vcpu_apicv_active(vcpu))
5466 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5467 SECONDARY_EXEC_APIC_REGISTER_VIRT |
5468 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5469 else
5470 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5471 SECONDARY_EXEC_APIC_REGISTER_VIRT |
5472 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5475 if (cpu_has_vmx_msr_bitmap())
5476 vmx_update_msr_bitmap(vcpu);
5479 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
5481 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
5483 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
5484 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
5486 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
5487 exec_control &= ~CPU_BASED_TPR_SHADOW;
5488 #ifdef CONFIG_X86_64
5489 exec_control |= CPU_BASED_CR8_STORE_EXITING |
5490 CPU_BASED_CR8_LOAD_EXITING;
5491 #endif
5493 if (!enable_ept)
5494 exec_control |= CPU_BASED_CR3_STORE_EXITING |
5495 CPU_BASED_CR3_LOAD_EXITING |
5496 CPU_BASED_INVLPG_EXITING;
5497 return exec_control;
5500 static bool vmx_rdrand_supported(void)
5502 return vmcs_config.cpu_based_2nd_exec_ctrl &
5503 SECONDARY_EXEC_RDRAND_EXITING;
5506 static bool vmx_rdseed_supported(void)
5508 return vmcs_config.cpu_based_2nd_exec_ctrl &
5509 SECONDARY_EXEC_RDSEED_EXITING;
5512 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
5514 struct kvm_vcpu *vcpu = &vmx->vcpu;
5516 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
5518 if (!cpu_need_virtualize_apic_accesses(vcpu))
5519 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5520 if (vmx->vpid == 0)
5521 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
5522 if (!enable_ept) {
5523 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
5524 enable_unrestricted_guest = 0;
5525 /* Enable INVPCID for non-ept guests may cause performance regression. */
5526 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5528 if (!enable_unrestricted_guest)
5529 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
5530 if (!ple_gap)
5531 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
5532 if (!kvm_vcpu_apicv_active(vcpu))
5533 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
5534 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5535 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5537 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
5538 * in vmx_set_cr4. */
5539 exec_control &= ~SECONDARY_EXEC_DESC;
5541 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
5542 (handle_vmptrld).
5543 We can NOT enable shadow_vmcs here because we don't have yet
5544 a current VMCS12
5546 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
5548 if (!enable_pml)
5549 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
5551 if (vmx_xsaves_supported()) {
5552 /* Exposing XSAVES only when XSAVE is exposed */
5553 bool xsaves_enabled =
5554 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
5555 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
5557 if (!xsaves_enabled)
5558 exec_control &= ~SECONDARY_EXEC_XSAVES;
5560 if (nested) {
5561 if (xsaves_enabled)
5562 vmx->nested.nested_vmx_secondary_ctls_high |=
5563 SECONDARY_EXEC_XSAVES;
5564 else
5565 vmx->nested.nested_vmx_secondary_ctls_high &=
5566 ~SECONDARY_EXEC_XSAVES;
5570 if (vmx_rdtscp_supported()) {
5571 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
5572 if (!rdtscp_enabled)
5573 exec_control &= ~SECONDARY_EXEC_RDTSCP;
5575 if (nested) {
5576 if (rdtscp_enabled)
5577 vmx->nested.nested_vmx_secondary_ctls_high |=
5578 SECONDARY_EXEC_RDTSCP;
5579 else
5580 vmx->nested.nested_vmx_secondary_ctls_high &=
5581 ~SECONDARY_EXEC_RDTSCP;
5585 if (vmx_invpcid_supported()) {
5586 /* Exposing INVPCID only when PCID is exposed */
5587 bool invpcid_enabled =
5588 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
5589 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
5591 if (!invpcid_enabled) {
5592 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5593 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
5596 if (nested) {
5597 if (invpcid_enabled)
5598 vmx->nested.nested_vmx_secondary_ctls_high |=
5599 SECONDARY_EXEC_ENABLE_INVPCID;
5600 else
5601 vmx->nested.nested_vmx_secondary_ctls_high &=
5602 ~SECONDARY_EXEC_ENABLE_INVPCID;
5606 if (vmx_rdrand_supported()) {
5607 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
5608 if (rdrand_enabled)
5609 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
5611 if (nested) {
5612 if (rdrand_enabled)
5613 vmx->nested.nested_vmx_secondary_ctls_high |=
5614 SECONDARY_EXEC_RDRAND_EXITING;
5615 else
5616 vmx->nested.nested_vmx_secondary_ctls_high &=
5617 ~SECONDARY_EXEC_RDRAND_EXITING;
5621 if (vmx_rdseed_supported()) {
5622 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
5623 if (rdseed_enabled)
5624 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
5626 if (nested) {
5627 if (rdseed_enabled)
5628 vmx->nested.nested_vmx_secondary_ctls_high |=
5629 SECONDARY_EXEC_RDSEED_EXITING;
5630 else
5631 vmx->nested.nested_vmx_secondary_ctls_high &=
5632 ~SECONDARY_EXEC_RDSEED_EXITING;
5636 vmx->secondary_exec_control = exec_control;
5639 static void ept_set_mmio_spte_mask(void)
5642 * EPT Misconfigurations can be generated if the value of bits 2:0
5643 * of an EPT paging-structure entry is 110b (write/execute).
5645 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
5646 VMX_EPT_MISCONFIG_WX_VALUE);
5649 #define VMX_XSS_EXIT_BITMAP 0
5651 * Sets up the vmcs for emulated real mode.
5653 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
5655 #ifdef CONFIG_X86_64
5656 unsigned long a;
5657 #endif
5658 int i;
5660 if (enable_shadow_vmcs) {
5661 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
5662 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
5664 if (cpu_has_vmx_msr_bitmap())
5665 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
5667 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
5669 /* Control */
5670 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5671 vmx->hv_deadline_tsc = -1;
5673 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
5675 if (cpu_has_secondary_exec_ctrls()) {
5676 vmx_compute_secondary_exec_control(vmx);
5677 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
5678 vmx->secondary_exec_control);
5681 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
5682 vmcs_write64(EOI_EXIT_BITMAP0, 0);
5683 vmcs_write64(EOI_EXIT_BITMAP1, 0);
5684 vmcs_write64(EOI_EXIT_BITMAP2, 0);
5685 vmcs_write64(EOI_EXIT_BITMAP3, 0);
5687 vmcs_write16(GUEST_INTR_STATUS, 0);
5689 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
5690 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
5693 if (ple_gap) {
5694 vmcs_write32(PLE_GAP, ple_gap);
5695 vmx->ple_window = ple_window;
5696 vmx->ple_window_dirty = true;
5699 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
5700 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
5701 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
5703 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
5704 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
5705 vmx_set_constant_host_state(vmx);
5706 #ifdef CONFIG_X86_64
5707 rdmsrl(MSR_FS_BASE, a);
5708 vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
5709 rdmsrl(MSR_GS_BASE, a);
5710 vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
5711 #else
5712 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
5713 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
5714 #endif
5716 if (cpu_has_vmx_vmfunc())
5717 vmcs_write64(VM_FUNCTION_CONTROL, 0);
5719 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
5720 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
5721 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
5722 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
5723 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
5725 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
5726 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
5728 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
5729 u32 index = vmx_msr_index[i];
5730 u32 data_low, data_high;
5731 int j = vmx->nmsrs;
5733 if (rdmsr_safe(index, &data_low, &data_high) < 0)
5734 continue;
5735 if (wrmsr_safe(index, data_low, data_high) < 0)
5736 continue;
5737 vmx->guest_msrs[j].index = i;
5738 vmx->guest_msrs[j].data = 0;
5739 vmx->guest_msrs[j].mask = -1ull;
5740 ++vmx->nmsrs;
5743 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
5744 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, vmx->arch_capabilities);
5746 vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
5748 /* 22.2.1, 20.8.1 */
5749 vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
5751 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
5752 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
5754 set_cr4_guest_host_mask(vmx);
5756 if (vmx_xsaves_supported())
5757 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
5759 if (enable_pml) {
5760 ASSERT(vmx->pml_pg);
5761 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
5762 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5766 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
5768 struct vcpu_vmx *vmx = to_vmx(vcpu);
5769 struct msr_data apic_base_msr;
5770 u64 cr0;
5772 vmx->rmode.vm86_active = 0;
5773 vmx->spec_ctrl = 0;
5775 vcpu->arch.microcode_version = 0x100000000ULL;
5776 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
5777 kvm_set_cr8(vcpu, 0);
5779 if (!init_event) {
5780 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
5781 MSR_IA32_APICBASE_ENABLE;
5782 if (kvm_vcpu_is_reset_bsp(vcpu))
5783 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
5784 apic_base_msr.host_initiated = true;
5785 kvm_set_apic_base(vcpu, &apic_base_msr);
5788 vmx_segment_cache_clear(vmx);
5790 seg_setup(VCPU_SREG_CS);
5791 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
5792 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
5794 seg_setup(VCPU_SREG_DS);
5795 seg_setup(VCPU_SREG_ES);
5796 seg_setup(VCPU_SREG_FS);
5797 seg_setup(VCPU_SREG_GS);
5798 seg_setup(VCPU_SREG_SS);
5800 vmcs_write16(GUEST_TR_SELECTOR, 0);
5801 vmcs_writel(GUEST_TR_BASE, 0);
5802 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
5803 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5805 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
5806 vmcs_writel(GUEST_LDTR_BASE, 0);
5807 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
5808 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
5810 if (!init_event) {
5811 vmcs_write32(GUEST_SYSENTER_CS, 0);
5812 vmcs_writel(GUEST_SYSENTER_ESP, 0);
5813 vmcs_writel(GUEST_SYSENTER_EIP, 0);
5814 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
5817 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
5818 kvm_rip_write(vcpu, 0xfff0);
5820 vmcs_writel(GUEST_GDTR_BASE, 0);
5821 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
5823 vmcs_writel(GUEST_IDTR_BASE, 0);
5824 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
5826 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
5827 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
5828 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
5829 if (kvm_mpx_supported())
5830 vmcs_write64(GUEST_BNDCFGS, 0);
5832 setup_msrs(vmx);
5834 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
5836 if (cpu_has_vmx_tpr_shadow() && !init_event) {
5837 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
5838 if (cpu_need_tpr_shadow(vcpu))
5839 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
5840 __pa(vcpu->arch.apic->regs));
5841 vmcs_write32(TPR_THRESHOLD, 0);
5844 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
5846 if (vmx->vpid != 0)
5847 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
5849 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
5850 vmx->vcpu.arch.cr0 = cr0;
5851 vmx_set_cr0(vcpu, cr0); /* enter rmode */
5852 vmx_set_cr4(vcpu, 0);
5853 vmx_set_efer(vcpu, 0);
5855 update_exception_bitmap(vcpu);
5857 vpid_sync_context(vmx->vpid);
5861 * In nested virtualization, check if L1 asked to exit on external interrupts.
5862 * For most existing hypervisors, this will always return true.
5864 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
5866 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5867 PIN_BASED_EXT_INTR_MASK;
5871 * In nested virtualization, check if L1 has set
5872 * VM_EXIT_ACK_INTR_ON_EXIT
5874 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
5876 return get_vmcs12(vcpu)->vm_exit_controls &
5877 VM_EXIT_ACK_INTR_ON_EXIT;
5880 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
5882 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5883 PIN_BASED_NMI_EXITING;
5886 static void enable_irq_window(struct kvm_vcpu *vcpu)
5888 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
5889 CPU_BASED_VIRTUAL_INTR_PENDING);
5892 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5894 if (!enable_vnmi ||
5895 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
5896 enable_irq_window(vcpu);
5897 return;
5900 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
5901 CPU_BASED_VIRTUAL_NMI_PENDING);
5904 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
5906 struct vcpu_vmx *vmx = to_vmx(vcpu);
5907 uint32_t intr;
5908 int irq = vcpu->arch.interrupt.nr;
5910 trace_kvm_inj_virq(irq);
5912 ++vcpu->stat.irq_injections;
5913 if (vmx->rmode.vm86_active) {
5914 int inc_eip = 0;
5915 if (vcpu->arch.interrupt.soft)
5916 inc_eip = vcpu->arch.event_exit_inst_len;
5917 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
5918 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5919 return;
5921 intr = irq | INTR_INFO_VALID_MASK;
5922 if (vcpu->arch.interrupt.soft) {
5923 intr |= INTR_TYPE_SOFT_INTR;
5924 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
5925 vmx->vcpu.arch.event_exit_inst_len);
5926 } else
5927 intr |= INTR_TYPE_EXT_INTR;
5928 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
5931 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
5933 struct vcpu_vmx *vmx = to_vmx(vcpu);
5935 if (!enable_vnmi) {
5937 * Tracking the NMI-blocked state in software is built upon
5938 * finding the next open IRQ window. This, in turn, depends on
5939 * well-behaving guests: They have to keep IRQs disabled at
5940 * least as long as the NMI handler runs. Otherwise we may
5941 * cause NMI nesting, maybe breaking the guest. But as this is
5942 * highly unlikely, we can live with the residual risk.
5944 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
5945 vmx->loaded_vmcs->vnmi_blocked_time = 0;
5948 ++vcpu->stat.nmi_injections;
5949 vmx->loaded_vmcs->nmi_known_unmasked = false;
5951 if (vmx->rmode.vm86_active) {
5952 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
5953 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5954 return;
5957 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
5958 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
5961 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
5963 struct vcpu_vmx *vmx = to_vmx(vcpu);
5964 bool masked;
5966 if (!enable_vnmi)
5967 return vmx->loaded_vmcs->soft_vnmi_blocked;
5968 if (vmx->loaded_vmcs->nmi_known_unmasked)
5969 return false;
5970 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
5971 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5972 return masked;
5975 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5977 struct vcpu_vmx *vmx = to_vmx(vcpu);
5979 if (!enable_vnmi) {
5980 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
5981 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
5982 vmx->loaded_vmcs->vnmi_blocked_time = 0;
5984 } else {
5985 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5986 if (masked)
5987 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5988 GUEST_INTR_STATE_NMI);
5989 else
5990 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
5991 GUEST_INTR_STATE_NMI);
5995 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
5997 if (to_vmx(vcpu)->nested.nested_run_pending)
5998 return 0;
6000 if (!enable_vnmi &&
6001 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
6002 return 0;
6004 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6005 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
6006 | GUEST_INTR_STATE_NMI));
6009 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
6011 return (!to_vmx(vcpu)->nested.nested_run_pending &&
6012 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6013 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6014 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6017 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6019 int ret;
6021 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6022 PAGE_SIZE * 3);
6023 if (ret)
6024 return ret;
6025 kvm->arch.tss_addr = addr;
6026 return init_rmode_tss(kvm);
6029 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6031 switch (vec) {
6032 case BP_VECTOR:
6034 * Update instruction length as we may reinject the exception
6035 * from user space while in guest debugging mode.
6037 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6038 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6039 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6040 return false;
6041 /* fall through */
6042 case DB_VECTOR:
6043 if (vcpu->guest_debug &
6044 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6045 return false;
6046 /* fall through */
6047 case DE_VECTOR:
6048 case OF_VECTOR:
6049 case BR_VECTOR:
6050 case UD_VECTOR:
6051 case DF_VECTOR:
6052 case SS_VECTOR:
6053 case GP_VECTOR:
6054 case MF_VECTOR:
6055 return true;
6056 break;
6058 return false;
6061 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
6062 int vec, u32 err_code)
6065 * Instruction with address size override prefix opcode 0x67
6066 * Cause the #SS fault with 0 error code in VM86 mode.
6068 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
6069 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
6070 if (vcpu->arch.halt_request) {
6071 vcpu->arch.halt_request = 0;
6072 return kvm_vcpu_halt(vcpu);
6074 return 1;
6076 return 0;
6080 * Forward all other exceptions that are valid in real mode.
6081 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
6082 * the required debugging infrastructure rework.
6084 kvm_queue_exception(vcpu, vec);
6085 return 1;
6089 * Trigger machine check on the host. We assume all the MSRs are already set up
6090 * by the CPU and that we still run on the same CPU as the MCE occurred on.
6091 * We pass a fake environment to the machine check handler because we want
6092 * the guest to be always treated like user space, no matter what context
6093 * it used internally.
6095 static void kvm_machine_check(void)
6097 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
6098 struct pt_regs regs = {
6099 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
6100 .flags = X86_EFLAGS_IF,
6103 do_machine_check(&regs, 0);
6104 #endif
6107 static int handle_machine_check(struct kvm_vcpu *vcpu)
6109 /* already handled by vcpu_run */
6110 return 1;
6113 static int handle_exception(struct kvm_vcpu *vcpu)
6115 struct vcpu_vmx *vmx = to_vmx(vcpu);
6116 struct kvm_run *kvm_run = vcpu->run;
6117 u32 intr_info, ex_no, error_code;
6118 unsigned long cr2, rip, dr6;
6119 u32 vect_info;
6120 enum emulation_result er;
6122 vect_info = vmx->idt_vectoring_info;
6123 intr_info = vmx->exit_intr_info;
6125 if (is_machine_check(intr_info))
6126 return handle_machine_check(vcpu);
6128 if (is_nmi(intr_info))
6129 return 1; /* already handled by vmx_vcpu_run() */
6131 if (is_invalid_opcode(intr_info)) {
6132 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
6133 if (er == EMULATE_USER_EXIT)
6134 return 0;
6135 if (er != EMULATE_DONE)
6136 kvm_queue_exception(vcpu, UD_VECTOR);
6137 return 1;
6140 error_code = 0;
6141 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
6142 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6145 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
6146 * MMIO, it is better to report an internal error.
6147 * See the comments in vmx_handle_exit.
6149 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
6150 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
6151 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6152 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
6153 vcpu->run->internal.ndata = 3;
6154 vcpu->run->internal.data[0] = vect_info;
6155 vcpu->run->internal.data[1] = intr_info;
6156 vcpu->run->internal.data[2] = error_code;
6157 return 0;
6160 if (is_page_fault(intr_info)) {
6161 cr2 = vmcs_readl(EXIT_QUALIFICATION);
6162 /* EPT won't cause page fault directly */
6163 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
6164 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
6167 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
6169 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
6170 return handle_rmode_exception(vcpu, ex_no, error_code);
6172 switch (ex_no) {
6173 case AC_VECTOR:
6174 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
6175 return 1;
6176 case DB_VECTOR:
6177 dr6 = vmcs_readl(EXIT_QUALIFICATION);
6178 if (!(vcpu->guest_debug &
6179 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
6180 vcpu->arch.dr6 &= ~15;
6181 vcpu->arch.dr6 |= dr6 | DR6_RTM;
6182 if (!(dr6 & ~DR6_RESERVED)) /* icebp */
6183 skip_emulated_instruction(vcpu);
6185 kvm_queue_exception(vcpu, DB_VECTOR);
6186 return 1;
6188 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
6189 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
6190 /* fall through */
6191 case BP_VECTOR:
6193 * Update instruction length as we may reinject #BP from
6194 * user space while in guest debugging mode. Reading it for
6195 * #DB as well causes no harm, it is not used in that case.
6197 vmx->vcpu.arch.event_exit_inst_len =
6198 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6199 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6200 rip = kvm_rip_read(vcpu);
6201 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
6202 kvm_run->debug.arch.exception = ex_no;
6203 break;
6204 default:
6205 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
6206 kvm_run->ex.exception = ex_no;
6207 kvm_run->ex.error_code = error_code;
6208 break;
6210 return 0;
6213 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
6215 ++vcpu->stat.irq_exits;
6216 return 1;
6219 static int handle_triple_fault(struct kvm_vcpu *vcpu)
6221 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6222 vcpu->mmio_needed = 0;
6223 return 0;
6226 static int handle_io(struct kvm_vcpu *vcpu)
6228 unsigned long exit_qualification;
6229 int size, in, string, ret;
6230 unsigned port;
6232 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6233 string = (exit_qualification & 16) != 0;
6234 in = (exit_qualification & 8) != 0;
6236 ++vcpu->stat.io_exits;
6238 if (string || in)
6239 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6241 port = exit_qualification >> 16;
6242 size = (exit_qualification & 7) + 1;
6244 ret = kvm_skip_emulated_instruction(vcpu);
6247 * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
6248 * KVM_EXIT_DEBUG here.
6250 return kvm_fast_pio_out(vcpu, size, port) && ret;
6253 static void
6254 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
6257 * Patch in the VMCALL instruction:
6259 hypercall[0] = 0x0f;
6260 hypercall[1] = 0x01;
6261 hypercall[2] = 0xc1;
6264 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
6265 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
6267 if (is_guest_mode(vcpu)) {
6268 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6269 unsigned long orig_val = val;
6272 * We get here when L2 changed cr0 in a way that did not change
6273 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6274 * but did change L0 shadowed bits. So we first calculate the
6275 * effective cr0 value that L1 would like to write into the
6276 * hardware. It consists of the L2-owned bits from the new
6277 * value combined with the L1-owned bits from L1's guest_cr0.
6279 val = (val & ~vmcs12->cr0_guest_host_mask) |
6280 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6282 if (!nested_guest_cr0_valid(vcpu, val))
6283 return 1;
6285 if (kvm_set_cr0(vcpu, val))
6286 return 1;
6287 vmcs_writel(CR0_READ_SHADOW, orig_val);
6288 return 0;
6289 } else {
6290 if (to_vmx(vcpu)->nested.vmxon &&
6291 !nested_host_cr0_valid(vcpu, val))
6292 return 1;
6294 return kvm_set_cr0(vcpu, val);
6298 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6300 if (is_guest_mode(vcpu)) {
6301 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6302 unsigned long orig_val = val;
6304 /* analogously to handle_set_cr0 */
6305 val = (val & ~vmcs12->cr4_guest_host_mask) |
6306 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6307 if (kvm_set_cr4(vcpu, val))
6308 return 1;
6309 vmcs_writel(CR4_READ_SHADOW, orig_val);
6310 return 0;
6311 } else
6312 return kvm_set_cr4(vcpu, val);
6315 static int handle_desc(struct kvm_vcpu *vcpu)
6317 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
6318 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6321 static int handle_cr(struct kvm_vcpu *vcpu)
6323 unsigned long exit_qualification, val;
6324 int cr;
6325 int reg;
6326 int err;
6327 int ret;
6329 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6330 cr = exit_qualification & 15;
6331 reg = (exit_qualification >> 8) & 15;
6332 switch ((exit_qualification >> 4) & 3) {
6333 case 0: /* mov to cr */
6334 val = kvm_register_readl(vcpu, reg);
6335 trace_kvm_cr_write(cr, val);
6336 switch (cr) {
6337 case 0:
6338 err = handle_set_cr0(vcpu, val);
6339 return kvm_complete_insn_gp(vcpu, err);
6340 case 3:
6341 err = kvm_set_cr3(vcpu, val);
6342 return kvm_complete_insn_gp(vcpu, err);
6343 case 4:
6344 err = handle_set_cr4(vcpu, val);
6345 return kvm_complete_insn_gp(vcpu, err);
6346 case 8: {
6347 u8 cr8_prev = kvm_get_cr8(vcpu);
6348 u8 cr8 = (u8)val;
6349 err = kvm_set_cr8(vcpu, cr8);
6350 ret = kvm_complete_insn_gp(vcpu, err);
6351 if (lapic_in_kernel(vcpu))
6352 return ret;
6353 if (cr8_prev <= cr8)
6354 return ret;
6356 * TODO: we might be squashing a
6357 * KVM_GUESTDBG_SINGLESTEP-triggered
6358 * KVM_EXIT_DEBUG here.
6360 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
6361 return 0;
6364 break;
6365 case 2: /* clts */
6366 WARN_ONCE(1, "Guest should always own CR0.TS");
6367 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
6368 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
6369 return kvm_skip_emulated_instruction(vcpu);
6370 case 1: /*mov from cr*/
6371 switch (cr) {
6372 case 3:
6373 val = kvm_read_cr3(vcpu);
6374 kvm_register_write(vcpu, reg, val);
6375 trace_kvm_cr_read(cr, val);
6376 return kvm_skip_emulated_instruction(vcpu);
6377 case 8:
6378 val = kvm_get_cr8(vcpu);
6379 kvm_register_write(vcpu, reg, val);
6380 trace_kvm_cr_read(cr, val);
6381 return kvm_skip_emulated_instruction(vcpu);
6383 break;
6384 case 3: /* lmsw */
6385 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6386 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
6387 kvm_lmsw(vcpu, val);
6389 return kvm_skip_emulated_instruction(vcpu);
6390 default:
6391 break;
6393 vcpu->run->exit_reason = 0;
6394 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
6395 (int)(exit_qualification >> 4) & 3, cr);
6396 return 0;
6399 static int handle_dr(struct kvm_vcpu *vcpu)
6401 unsigned long exit_qualification;
6402 int dr, dr7, reg;
6404 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6405 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
6407 /* First, if DR does not exist, trigger UD */
6408 if (!kvm_require_dr(vcpu, dr))
6409 return 1;
6411 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
6412 if (!kvm_require_cpl(vcpu, 0))
6413 return 1;
6414 dr7 = vmcs_readl(GUEST_DR7);
6415 if (dr7 & DR7_GD) {
6417 * As the vm-exit takes precedence over the debug trap, we
6418 * need to emulate the latter, either for the host or the
6419 * guest debugging itself.
6421 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6422 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
6423 vcpu->run->debug.arch.dr7 = dr7;
6424 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6425 vcpu->run->debug.arch.exception = DB_VECTOR;
6426 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
6427 return 0;
6428 } else {
6429 vcpu->arch.dr6 &= ~15;
6430 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
6431 kvm_queue_exception(vcpu, DB_VECTOR);
6432 return 1;
6436 if (vcpu->guest_debug == 0) {
6437 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6438 CPU_BASED_MOV_DR_EXITING);
6441 * No more DR vmexits; force a reload of the debug registers
6442 * and reenter on this instruction. The next vmexit will
6443 * retrieve the full state of the debug registers.
6445 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
6446 return 1;
6449 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
6450 if (exit_qualification & TYPE_MOV_FROM_DR) {
6451 unsigned long val;
6453 if (kvm_get_dr(vcpu, dr, &val))
6454 return 1;
6455 kvm_register_write(vcpu, reg, val);
6456 } else
6457 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
6458 return 1;
6460 return kvm_skip_emulated_instruction(vcpu);
6463 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
6465 return vcpu->arch.dr6;
6468 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
6472 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
6474 get_debugreg(vcpu->arch.db[0], 0);
6475 get_debugreg(vcpu->arch.db[1], 1);
6476 get_debugreg(vcpu->arch.db[2], 2);
6477 get_debugreg(vcpu->arch.db[3], 3);
6478 get_debugreg(vcpu->arch.dr6, 6);
6479 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
6481 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
6482 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
6485 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
6487 vmcs_writel(GUEST_DR7, val);
6490 static int handle_cpuid(struct kvm_vcpu *vcpu)
6492 return kvm_emulate_cpuid(vcpu);
6495 static int handle_rdmsr(struct kvm_vcpu *vcpu)
6497 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6498 struct msr_data msr_info;
6500 msr_info.index = ecx;
6501 msr_info.host_initiated = false;
6502 if (vmx_get_msr(vcpu, &msr_info)) {
6503 trace_kvm_msr_read_ex(ecx);
6504 kvm_inject_gp(vcpu, 0);
6505 return 1;
6508 trace_kvm_msr_read(ecx, msr_info.data);
6510 /* FIXME: handling of bits 32:63 of rax, rdx */
6511 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
6512 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
6513 return kvm_skip_emulated_instruction(vcpu);
6516 static int handle_wrmsr(struct kvm_vcpu *vcpu)
6518 struct msr_data msr;
6519 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6520 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
6521 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
6523 msr.data = data;
6524 msr.index = ecx;
6525 msr.host_initiated = false;
6526 if (kvm_set_msr(vcpu, &msr) != 0) {
6527 trace_kvm_msr_write_ex(ecx, data);
6528 kvm_inject_gp(vcpu, 0);
6529 return 1;
6532 trace_kvm_msr_write(ecx, data);
6533 return kvm_skip_emulated_instruction(vcpu);
6536 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
6538 kvm_apic_update_ppr(vcpu);
6539 return 1;
6542 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
6544 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6545 CPU_BASED_VIRTUAL_INTR_PENDING);
6547 kvm_make_request(KVM_REQ_EVENT, vcpu);
6549 ++vcpu->stat.irq_window_exits;
6550 return 1;
6553 static int handle_halt(struct kvm_vcpu *vcpu)
6555 return kvm_emulate_halt(vcpu);
6558 static int handle_vmcall(struct kvm_vcpu *vcpu)
6560 return kvm_emulate_hypercall(vcpu);
6563 static int handle_invd(struct kvm_vcpu *vcpu)
6565 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6568 static int handle_invlpg(struct kvm_vcpu *vcpu)
6570 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6572 kvm_mmu_invlpg(vcpu, exit_qualification);
6573 return kvm_skip_emulated_instruction(vcpu);
6576 static int handle_rdpmc(struct kvm_vcpu *vcpu)
6578 int err;
6580 err = kvm_rdpmc(vcpu);
6581 return kvm_complete_insn_gp(vcpu, err);
6584 static int handle_wbinvd(struct kvm_vcpu *vcpu)
6586 return kvm_emulate_wbinvd(vcpu);
6589 static int handle_xsetbv(struct kvm_vcpu *vcpu)
6591 u64 new_bv = kvm_read_edx_eax(vcpu);
6592 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
6594 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
6595 return kvm_skip_emulated_instruction(vcpu);
6596 return 1;
6599 static int handle_xsaves(struct kvm_vcpu *vcpu)
6601 kvm_skip_emulated_instruction(vcpu);
6602 WARN(1, "this should never happen\n");
6603 return 1;
6606 static int handle_xrstors(struct kvm_vcpu *vcpu)
6608 kvm_skip_emulated_instruction(vcpu);
6609 WARN(1, "this should never happen\n");
6610 return 1;
6613 static int handle_apic_access(struct kvm_vcpu *vcpu)
6615 if (likely(fasteoi)) {
6616 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6617 int access_type, offset;
6619 access_type = exit_qualification & APIC_ACCESS_TYPE;
6620 offset = exit_qualification & APIC_ACCESS_OFFSET;
6622 * Sane guest uses MOV to write EOI, with written value
6623 * not cared. So make a short-circuit here by avoiding
6624 * heavy instruction emulation.
6626 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
6627 (offset == APIC_EOI)) {
6628 kvm_lapic_set_eoi(vcpu);
6629 return kvm_skip_emulated_instruction(vcpu);
6632 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6635 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
6637 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6638 int vector = exit_qualification & 0xff;
6640 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
6641 kvm_apic_set_eoi_accelerated(vcpu, vector);
6642 return 1;
6645 static int handle_apic_write(struct kvm_vcpu *vcpu)
6647 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6648 u32 offset = exit_qualification & 0xfff;
6650 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
6651 kvm_apic_write_nodecode(vcpu, offset);
6652 return 1;
6655 static int handle_task_switch(struct kvm_vcpu *vcpu)
6657 struct vcpu_vmx *vmx = to_vmx(vcpu);
6658 unsigned long exit_qualification;
6659 bool has_error_code = false;
6660 u32 error_code = 0;
6661 u16 tss_selector;
6662 int reason, type, idt_v, idt_index;
6664 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
6665 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
6666 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
6668 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6670 reason = (u32)exit_qualification >> 30;
6671 if (reason == TASK_SWITCH_GATE && idt_v) {
6672 switch (type) {
6673 case INTR_TYPE_NMI_INTR:
6674 vcpu->arch.nmi_injected = false;
6675 vmx_set_nmi_mask(vcpu, true);
6676 break;
6677 case INTR_TYPE_EXT_INTR:
6678 case INTR_TYPE_SOFT_INTR:
6679 kvm_clear_interrupt_queue(vcpu);
6680 break;
6681 case INTR_TYPE_HARD_EXCEPTION:
6682 if (vmx->idt_vectoring_info &
6683 VECTORING_INFO_DELIVER_CODE_MASK) {
6684 has_error_code = true;
6685 error_code =
6686 vmcs_read32(IDT_VECTORING_ERROR_CODE);
6688 /* fall through */
6689 case INTR_TYPE_SOFT_EXCEPTION:
6690 kvm_clear_exception_queue(vcpu);
6691 break;
6692 default:
6693 break;
6696 tss_selector = exit_qualification;
6698 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
6699 type != INTR_TYPE_EXT_INTR &&
6700 type != INTR_TYPE_NMI_INTR))
6701 skip_emulated_instruction(vcpu);
6703 if (kvm_task_switch(vcpu, tss_selector,
6704 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
6705 has_error_code, error_code) == EMULATE_FAIL) {
6706 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6707 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6708 vcpu->run->internal.ndata = 0;
6709 return 0;
6713 * TODO: What about debug traps on tss switch?
6714 * Are we supposed to inject them and update dr6?
6717 return 1;
6720 static int handle_ept_violation(struct kvm_vcpu *vcpu)
6722 unsigned long exit_qualification;
6723 gpa_t gpa;
6724 u64 error_code;
6726 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6729 * EPT violation happened while executing iret from NMI,
6730 * "blocked by NMI" bit has to be set before next VM entry.
6731 * There are errata that may cause this bit to not be set:
6732 * AAK134, BY25.
6734 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
6735 enable_vnmi &&
6736 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
6737 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
6739 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6740 trace_kvm_page_fault(gpa, exit_qualification);
6742 /* Is it a read fault? */
6743 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
6744 ? PFERR_USER_MASK : 0;
6745 /* Is it a write fault? */
6746 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
6747 ? PFERR_WRITE_MASK : 0;
6748 /* Is it a fetch fault? */
6749 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
6750 ? PFERR_FETCH_MASK : 0;
6751 /* ept page table entry is present? */
6752 error_code |= (exit_qualification &
6753 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
6754 EPT_VIOLATION_EXECUTABLE))
6755 ? PFERR_PRESENT_MASK : 0;
6757 error_code |= (exit_qualification & 0x100) != 0 ?
6758 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
6760 vcpu->arch.exit_qualification = exit_qualification;
6761 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
6764 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
6766 int ret;
6767 gpa_t gpa;
6770 * A nested guest cannot optimize MMIO vmexits, because we have an
6771 * nGPA here instead of the required GPA.
6773 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6774 if (!is_guest_mode(vcpu) &&
6775 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
6776 trace_kvm_fast_mmio(gpa);
6778 * Doing kvm_skip_emulated_instruction() depends on undefined
6779 * behavior: Intel's manual doesn't mandate
6780 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
6781 * occurs and while on real hardware it was observed to be set,
6782 * other hypervisors (namely Hyper-V) don't set it, we end up
6783 * advancing IP with some random value. Disable fast mmio when
6784 * running nested and keep it for real hardware in hope that
6785 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
6787 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
6788 return kvm_skip_emulated_instruction(vcpu);
6789 else
6790 return x86_emulate_instruction(vcpu, gpa, EMULTYPE_SKIP,
6791 NULL, 0) == EMULATE_DONE;
6794 ret = kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
6795 if (ret >= 0)
6796 return ret;
6798 /* It is the real ept misconfig */
6799 WARN_ON(1);
6801 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6802 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
6804 return 0;
6807 static int handle_nmi_window(struct kvm_vcpu *vcpu)
6809 WARN_ON_ONCE(!enable_vnmi);
6810 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6811 CPU_BASED_VIRTUAL_NMI_PENDING);
6812 ++vcpu->stat.nmi_window_exits;
6813 kvm_make_request(KVM_REQ_EVENT, vcpu);
6815 return 1;
6818 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
6820 struct vcpu_vmx *vmx = to_vmx(vcpu);
6821 enum emulation_result err = EMULATE_DONE;
6822 int ret = 1;
6823 u32 cpu_exec_ctrl;
6824 bool intr_window_requested;
6825 unsigned count = 130;
6827 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6828 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
6830 while (vmx->emulation_required && count-- != 0) {
6831 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
6832 return handle_interrupt_window(&vmx->vcpu);
6834 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
6835 return 1;
6837 err = emulate_instruction(vcpu, 0);
6839 if (err == EMULATE_USER_EXIT) {
6840 ++vcpu->stat.mmio_exits;
6841 ret = 0;
6842 goto out;
6845 if (err != EMULATE_DONE) {
6846 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6847 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6848 vcpu->run->internal.ndata = 0;
6849 return 0;
6852 if (vcpu->arch.halt_request) {
6853 vcpu->arch.halt_request = 0;
6854 ret = kvm_vcpu_halt(vcpu);
6855 goto out;
6858 if (signal_pending(current))
6859 goto out;
6860 if (need_resched())
6861 schedule();
6864 out:
6865 return ret;
6868 static int __grow_ple_window(int val)
6870 if (ple_window_grow < 1)
6871 return ple_window;
6873 val = min(val, ple_window_actual_max);
6875 if (ple_window_grow < ple_window)
6876 val *= ple_window_grow;
6877 else
6878 val += ple_window_grow;
6880 return val;
6883 static int __shrink_ple_window(int val, int modifier, int minimum)
6885 if (modifier < 1)
6886 return ple_window;
6888 if (modifier < ple_window)
6889 val /= modifier;
6890 else
6891 val -= modifier;
6893 return max(val, minimum);
6896 static void grow_ple_window(struct kvm_vcpu *vcpu)
6898 struct vcpu_vmx *vmx = to_vmx(vcpu);
6899 int old = vmx->ple_window;
6901 vmx->ple_window = __grow_ple_window(old);
6903 if (vmx->ple_window != old)
6904 vmx->ple_window_dirty = true;
6906 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
6909 static void shrink_ple_window(struct kvm_vcpu *vcpu)
6911 struct vcpu_vmx *vmx = to_vmx(vcpu);
6912 int old = vmx->ple_window;
6914 vmx->ple_window = __shrink_ple_window(old,
6915 ple_window_shrink, ple_window);
6917 if (vmx->ple_window != old)
6918 vmx->ple_window_dirty = true;
6920 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
6924 * ple_window_actual_max is computed to be one grow_ple_window() below
6925 * ple_window_max. (See __grow_ple_window for the reason.)
6926 * This prevents overflows, because ple_window_max is int.
6927 * ple_window_max effectively rounded down to a multiple of ple_window_grow in
6928 * this process.
6929 * ple_window_max is also prevented from setting vmx->ple_window < ple_window.
6931 static void update_ple_window_actual_max(void)
6933 ple_window_actual_max =
6934 __shrink_ple_window(max(ple_window_max, ple_window),
6935 ple_window_grow, INT_MIN);
6939 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
6941 static void wakeup_handler(void)
6943 struct kvm_vcpu *vcpu;
6944 int cpu = smp_processor_id();
6946 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6947 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
6948 blocked_vcpu_list) {
6949 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6951 if (pi_test_on(pi_desc) == 1)
6952 kvm_vcpu_kick(vcpu);
6954 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6957 void vmx_enable_tdp(void)
6959 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
6960 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
6961 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
6962 0ull, VMX_EPT_EXECUTABLE_MASK,
6963 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
6964 VMX_EPT_RWX_MASK, 0ull);
6966 ept_set_mmio_spte_mask();
6967 kvm_enable_tdp();
6970 static __init int hardware_setup(void)
6972 int r = -ENOMEM, i;
6974 rdmsrl_safe(MSR_EFER, &host_efer);
6976 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
6977 kvm_define_shared_msr(i, vmx_msr_index[i]);
6979 for (i = 0; i < VMX_BITMAP_NR; i++) {
6980 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
6981 if (!vmx_bitmap[i])
6982 goto out;
6985 memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
6986 memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
6988 if (setup_vmcs_config(&vmcs_config) < 0) {
6989 r = -EIO;
6990 goto out;
6993 if (boot_cpu_has(X86_FEATURE_NX))
6994 kvm_enable_efer_bits(EFER_NX);
6996 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
6997 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
6998 enable_vpid = 0;
7000 if (!cpu_has_vmx_ept() ||
7001 !cpu_has_vmx_ept_4levels() ||
7002 !cpu_has_vmx_ept_mt_wb() ||
7003 !cpu_has_vmx_invept_global())
7004 enable_ept = 0;
7006 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7007 enable_ept_ad_bits = 0;
7009 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7010 enable_unrestricted_guest = 0;
7012 if (!cpu_has_vmx_flexpriority())
7013 flexpriority_enabled = 0;
7015 if (!cpu_has_virtual_nmis())
7016 enable_vnmi = 0;
7019 * set_apic_access_page_addr() is used to reload apic access
7020 * page upon invalidation. No need to do anything if not
7021 * using the APIC_ACCESS_ADDR VMCS field.
7023 if (!flexpriority_enabled)
7024 kvm_x86_ops->set_apic_access_page_addr = NULL;
7026 if (!cpu_has_vmx_tpr_shadow())
7027 kvm_x86_ops->update_cr8_intercept = NULL;
7029 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7030 kvm_disable_largepages();
7032 if (!cpu_has_vmx_ple()) {
7033 ple_gap = 0;
7034 ple_window = 0;
7035 ple_window_grow = 0;
7036 ple_window_max = 0;
7037 ple_window_shrink = 0;
7040 if (!cpu_has_vmx_apicv()) {
7041 enable_apicv = 0;
7042 kvm_x86_ops->sync_pir_to_irr = NULL;
7045 if (cpu_has_vmx_tsc_scaling()) {
7046 kvm_has_tsc_control = true;
7047 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7048 kvm_tsc_scaling_ratio_frac_bits = 48;
7051 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7053 if (enable_ept)
7054 vmx_enable_tdp();
7055 else
7056 kvm_disable_tdp();
7058 update_ple_window_actual_max();
7061 * Only enable PML when hardware supports PML feature, and both EPT
7062 * and EPT A/D bit features are enabled -- PML depends on them to work.
7064 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7065 enable_pml = 0;
7067 if (!enable_pml) {
7068 kvm_x86_ops->slot_enable_log_dirty = NULL;
7069 kvm_x86_ops->slot_disable_log_dirty = NULL;
7070 kvm_x86_ops->flush_log_dirty = NULL;
7071 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7074 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7075 u64 vmx_msr;
7077 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7078 cpu_preemption_timer_multi =
7079 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7080 } else {
7081 kvm_x86_ops->set_hv_timer = NULL;
7082 kvm_x86_ops->cancel_hv_timer = NULL;
7085 if (!cpu_has_vmx_shadow_vmcs())
7086 enable_shadow_vmcs = 0;
7087 if (enable_shadow_vmcs)
7088 init_vmcs_shadow_fields();
7090 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7092 kvm_mce_cap_supported |= MCG_LMCE_P;
7094 return alloc_kvm_area();
7096 out:
7097 for (i = 0; i < VMX_BITMAP_NR; i++)
7098 free_page((unsigned long)vmx_bitmap[i]);
7100 return r;
7103 static __exit void hardware_unsetup(void)
7105 int i;
7107 for (i = 0; i < VMX_BITMAP_NR; i++)
7108 free_page((unsigned long)vmx_bitmap[i]);
7110 free_kvm_area();
7114 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
7115 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
7117 static int handle_pause(struct kvm_vcpu *vcpu)
7119 if (ple_gap)
7120 grow_ple_window(vcpu);
7123 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
7124 * VM-execution control is ignored if CPL > 0. OTOH, KVM
7125 * never set PAUSE_EXITING and just set PLE if supported,
7126 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
7128 kvm_vcpu_on_spin(vcpu, true);
7129 return kvm_skip_emulated_instruction(vcpu);
7132 static int handle_nop(struct kvm_vcpu *vcpu)
7134 return kvm_skip_emulated_instruction(vcpu);
7137 static int handle_mwait(struct kvm_vcpu *vcpu)
7139 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
7140 return handle_nop(vcpu);
7143 static int handle_invalid_op(struct kvm_vcpu *vcpu)
7145 kvm_queue_exception(vcpu, UD_VECTOR);
7146 return 1;
7149 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
7151 return 1;
7154 static int handle_monitor(struct kvm_vcpu *vcpu)
7156 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
7157 return handle_nop(vcpu);
7161 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
7162 * set the success or error code of an emulated VMX instruction, as specified
7163 * by Vol 2B, VMX Instruction Reference, "Conventions".
7165 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
7167 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
7168 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7169 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
7172 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
7174 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7175 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
7176 X86_EFLAGS_SF | X86_EFLAGS_OF))
7177 | X86_EFLAGS_CF);
7180 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
7181 u32 vm_instruction_error)
7183 if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
7185 * failValid writes the error number to the current VMCS, which
7186 * can't be done there isn't a current VMCS.
7188 nested_vmx_failInvalid(vcpu);
7189 return;
7191 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7192 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7193 X86_EFLAGS_SF | X86_EFLAGS_OF))
7194 | X86_EFLAGS_ZF);
7195 get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
7197 * We don't need to force a shadow sync because
7198 * VM_INSTRUCTION_ERROR is not shadowed
7202 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
7204 /* TODO: not to reset guest simply here. */
7205 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7206 pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
7209 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
7211 struct vcpu_vmx *vmx =
7212 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
7214 vmx->nested.preemption_timer_expired = true;
7215 kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
7216 kvm_vcpu_kick(&vmx->vcpu);
7218 return HRTIMER_NORESTART;
7222 * Decode the memory-address operand of a vmx instruction, as recorded on an
7223 * exit caused by such an instruction (run by a guest hypervisor).
7224 * On success, returns 0. When the operand is invalid, returns 1 and throws
7225 * #UD or #GP.
7227 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
7228 unsigned long exit_qualification,
7229 u32 vmx_instruction_info, bool wr, gva_t *ret)
7231 gva_t off;
7232 bool exn;
7233 struct kvm_segment s;
7236 * According to Vol. 3B, "Information for VM Exits Due to Instruction
7237 * Execution", on an exit, vmx_instruction_info holds most of the
7238 * addressing components of the operand. Only the displacement part
7239 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
7240 * For how an actual address is calculated from all these components,
7241 * refer to Vol. 1, "Operand Addressing".
7243 int scaling = vmx_instruction_info & 3;
7244 int addr_size = (vmx_instruction_info >> 7) & 7;
7245 bool is_reg = vmx_instruction_info & (1u << 10);
7246 int seg_reg = (vmx_instruction_info >> 15) & 7;
7247 int index_reg = (vmx_instruction_info >> 18) & 0xf;
7248 bool index_is_valid = !(vmx_instruction_info & (1u << 22));
7249 int base_reg = (vmx_instruction_info >> 23) & 0xf;
7250 bool base_is_valid = !(vmx_instruction_info & (1u << 27));
7252 if (is_reg) {
7253 kvm_queue_exception(vcpu, UD_VECTOR);
7254 return 1;
7257 /* Addr = segment_base + offset */
7258 /* offset = base + [index * scale] + displacement */
7259 off = exit_qualification; /* holds the displacement */
7260 if (base_is_valid)
7261 off += kvm_register_read(vcpu, base_reg);
7262 if (index_is_valid)
7263 off += kvm_register_read(vcpu, index_reg)<<scaling;
7264 vmx_get_segment(vcpu, &s, seg_reg);
7265 *ret = s.base + off;
7267 if (addr_size == 1) /* 32 bit */
7268 *ret &= 0xffffffff;
7270 /* Checks for #GP/#SS exceptions. */
7271 exn = false;
7272 if (is_long_mode(vcpu)) {
7273 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
7274 * non-canonical form. This is the only check on the memory
7275 * destination for long mode!
7277 exn = is_noncanonical_address(*ret, vcpu);
7278 } else if (is_protmode(vcpu)) {
7279 /* Protected mode: apply checks for segment validity in the
7280 * following order:
7281 * - segment type check (#GP(0) may be thrown)
7282 * - usability check (#GP(0)/#SS(0))
7283 * - limit check (#GP(0)/#SS(0))
7285 if (wr)
7286 /* #GP(0) if the destination operand is located in a
7287 * read-only data segment or any code segment.
7289 exn = ((s.type & 0xa) == 0 || (s.type & 8));
7290 else
7291 /* #GP(0) if the source operand is located in an
7292 * execute-only code segment
7294 exn = ((s.type & 0xa) == 8);
7295 if (exn) {
7296 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7297 return 1;
7299 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
7301 exn = (s.unusable != 0);
7302 /* Protected mode: #GP(0)/#SS(0) if the memory
7303 * operand is outside the segment limit.
7305 exn = exn || (off + sizeof(u64) > s.limit);
7307 if (exn) {
7308 kvm_queue_exception_e(vcpu,
7309 seg_reg == VCPU_SREG_SS ?
7310 SS_VECTOR : GP_VECTOR,
7312 return 1;
7315 return 0;
7318 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
7320 gva_t gva;
7321 struct x86_exception e;
7323 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7324 vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
7325 return 1;
7327 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, vmpointer,
7328 sizeof(*vmpointer), &e)) {
7329 kvm_inject_page_fault(vcpu, &e);
7330 return 1;
7333 return 0;
7336 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
7338 struct vcpu_vmx *vmx = to_vmx(vcpu);
7339 struct vmcs *shadow_vmcs;
7340 int r;
7342 r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
7343 if (r < 0)
7344 goto out_vmcs02;
7346 vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
7347 if (!vmx->nested.cached_vmcs12)
7348 goto out_cached_vmcs12;
7350 if (enable_shadow_vmcs) {
7351 shadow_vmcs = alloc_vmcs();
7352 if (!shadow_vmcs)
7353 goto out_shadow_vmcs;
7354 /* mark vmcs as shadow */
7355 shadow_vmcs->revision_id |= (1u << 31);
7356 /* init shadow vmcs */
7357 vmcs_clear(shadow_vmcs);
7358 vmx->vmcs01.shadow_vmcs = shadow_vmcs;
7361 hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
7362 HRTIMER_MODE_REL_PINNED);
7363 vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
7365 vmx->nested.vmxon = true;
7366 return 0;
7368 out_shadow_vmcs:
7369 kfree(vmx->nested.cached_vmcs12);
7371 out_cached_vmcs12:
7372 free_loaded_vmcs(&vmx->nested.vmcs02);
7374 out_vmcs02:
7375 return -ENOMEM;
7379 * Emulate the VMXON instruction.
7380 * Currently, we just remember that VMX is active, and do not save or even
7381 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
7382 * do not currently need to store anything in that guest-allocated memory
7383 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
7384 * argument is different from the VMXON pointer (which the spec says they do).
7386 static int handle_vmon(struct kvm_vcpu *vcpu)
7388 int ret;
7389 gpa_t vmptr;
7390 struct page *page;
7391 struct vcpu_vmx *vmx = to_vmx(vcpu);
7392 const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
7393 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7396 * The Intel VMX Instruction Reference lists a bunch of bits that are
7397 * prerequisite to running VMXON, most notably cr4.VMXE must be set to
7398 * 1 (see vmx_set_cr4() for when we allow the guest to set this).
7399 * Otherwise, we should fail with #UD. But most faulting conditions
7400 * have already been checked by hardware, prior to the VM-exit for
7401 * VMXON. We do test guest cr4.VMXE because processor CR4 always has
7402 * that bit set to 1 in non-root mode.
7404 if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
7405 kvm_queue_exception(vcpu, UD_VECTOR);
7406 return 1;
7409 if (vmx->nested.vmxon) {
7410 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
7411 return kvm_skip_emulated_instruction(vcpu);
7414 if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
7415 != VMXON_NEEDED_FEATURES) {
7416 kvm_inject_gp(vcpu, 0);
7417 return 1;
7420 if (nested_vmx_get_vmptr(vcpu, &vmptr))
7421 return 1;
7424 * SDM 3: 24.11.5
7425 * The first 4 bytes of VMXON region contain the supported
7426 * VMCS revision identifier
7428 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
7429 * which replaces physical address width with 32
7431 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7432 nested_vmx_failInvalid(vcpu);
7433 return kvm_skip_emulated_instruction(vcpu);
7436 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7437 if (is_error_page(page)) {
7438 nested_vmx_failInvalid(vcpu);
7439 return kvm_skip_emulated_instruction(vcpu);
7441 if (*(u32 *)kmap(page) != VMCS12_REVISION) {
7442 kunmap(page);
7443 kvm_release_page_clean(page);
7444 nested_vmx_failInvalid(vcpu);
7445 return kvm_skip_emulated_instruction(vcpu);
7447 kunmap(page);
7448 kvm_release_page_clean(page);
7450 vmx->nested.vmxon_ptr = vmptr;
7451 ret = enter_vmx_operation(vcpu);
7452 if (ret)
7453 return ret;
7455 nested_vmx_succeed(vcpu);
7456 return kvm_skip_emulated_instruction(vcpu);
7460 * Intel's VMX Instruction Reference specifies a common set of prerequisites
7461 * for running VMX instructions (except VMXON, whose prerequisites are
7462 * slightly different). It also specifies what exception to inject otherwise.
7463 * Note that many of these exceptions have priority over VM exits, so they
7464 * don't have to be checked again here.
7466 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
7468 if (!to_vmx(vcpu)->nested.vmxon) {
7469 kvm_queue_exception(vcpu, UD_VECTOR);
7470 return 0;
7472 return 1;
7475 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
7477 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
7478 vmcs_write64(VMCS_LINK_POINTER, -1ull);
7481 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
7483 if (vmx->nested.current_vmptr == -1ull)
7484 return;
7486 if (enable_shadow_vmcs) {
7487 /* copy to memory all shadowed fields in case
7488 they were modified */
7489 copy_shadow_to_vmcs12(vmx);
7490 vmx->nested.sync_shadow_vmcs = false;
7491 vmx_disable_shadow_vmcs(vmx);
7493 vmx->nested.posted_intr_nv = -1;
7495 /* Flush VMCS12 to guest memory */
7496 kvm_vcpu_write_guest_page(&vmx->vcpu,
7497 vmx->nested.current_vmptr >> PAGE_SHIFT,
7498 vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
7500 vmx->nested.current_vmptr = -1ull;
7504 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
7505 * just stops using VMX.
7507 static void free_nested(struct vcpu_vmx *vmx)
7509 if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
7510 return;
7512 vmx->nested.vmxon = false;
7513 vmx->nested.smm.vmxon = false;
7514 free_vpid(vmx->nested.vpid02);
7515 vmx->nested.posted_intr_nv = -1;
7516 vmx->nested.current_vmptr = -1ull;
7517 if (enable_shadow_vmcs) {
7518 vmx_disable_shadow_vmcs(vmx);
7519 vmcs_clear(vmx->vmcs01.shadow_vmcs);
7520 free_vmcs(vmx->vmcs01.shadow_vmcs);
7521 vmx->vmcs01.shadow_vmcs = NULL;
7523 kfree(vmx->nested.cached_vmcs12);
7524 /* Unpin physical memory we referred to in the vmcs02 */
7525 if (vmx->nested.apic_access_page) {
7526 kvm_release_page_dirty(vmx->nested.apic_access_page);
7527 vmx->nested.apic_access_page = NULL;
7529 if (vmx->nested.virtual_apic_page) {
7530 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
7531 vmx->nested.virtual_apic_page = NULL;
7533 if (vmx->nested.pi_desc_page) {
7534 kunmap(vmx->nested.pi_desc_page);
7535 kvm_release_page_dirty(vmx->nested.pi_desc_page);
7536 vmx->nested.pi_desc_page = NULL;
7537 vmx->nested.pi_desc = NULL;
7540 free_loaded_vmcs(&vmx->nested.vmcs02);
7543 /* Emulate the VMXOFF instruction */
7544 static int handle_vmoff(struct kvm_vcpu *vcpu)
7546 if (!nested_vmx_check_permission(vcpu))
7547 return 1;
7548 free_nested(to_vmx(vcpu));
7549 nested_vmx_succeed(vcpu);
7550 return kvm_skip_emulated_instruction(vcpu);
7553 /* Emulate the VMCLEAR instruction */
7554 static int handle_vmclear(struct kvm_vcpu *vcpu)
7556 struct vcpu_vmx *vmx = to_vmx(vcpu);
7557 u32 zero = 0;
7558 gpa_t vmptr;
7560 if (!nested_vmx_check_permission(vcpu))
7561 return 1;
7563 if (nested_vmx_get_vmptr(vcpu, &vmptr))
7564 return 1;
7566 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7567 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
7568 return kvm_skip_emulated_instruction(vcpu);
7571 if (vmptr == vmx->nested.vmxon_ptr) {
7572 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
7573 return kvm_skip_emulated_instruction(vcpu);
7576 if (vmptr == vmx->nested.current_vmptr)
7577 nested_release_vmcs12(vmx);
7579 kvm_vcpu_write_guest(vcpu,
7580 vmptr + offsetof(struct vmcs12, launch_state),
7581 &zero, sizeof(zero));
7583 nested_vmx_succeed(vcpu);
7584 return kvm_skip_emulated_instruction(vcpu);
7587 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
7589 /* Emulate the VMLAUNCH instruction */
7590 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
7592 return nested_vmx_run(vcpu, true);
7595 /* Emulate the VMRESUME instruction */
7596 static int handle_vmresume(struct kvm_vcpu *vcpu)
7599 return nested_vmx_run(vcpu, false);
7603 * Read a vmcs12 field. Since these can have varying lengths and we return
7604 * one type, we chose the biggest type (u64) and zero-extend the return value
7605 * to that size. Note that the caller, handle_vmread, might need to use only
7606 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
7607 * 64-bit fields are to be returned).
7609 static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
7610 unsigned long field, u64 *ret)
7612 short offset = vmcs_field_to_offset(field);
7613 char *p;
7615 if (offset < 0)
7616 return offset;
7618 p = ((char *)(get_vmcs12(vcpu))) + offset;
7620 switch (vmcs_field_width(field)) {
7621 case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
7622 *ret = *((natural_width *)p);
7623 return 0;
7624 case VMCS_FIELD_WIDTH_U16:
7625 *ret = *((u16 *)p);
7626 return 0;
7627 case VMCS_FIELD_WIDTH_U32:
7628 *ret = *((u32 *)p);
7629 return 0;
7630 case VMCS_FIELD_WIDTH_U64:
7631 *ret = *((u64 *)p);
7632 return 0;
7633 default:
7634 WARN_ON(1);
7635 return -ENOENT;
7640 static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
7641 unsigned long field, u64 field_value){
7642 short offset = vmcs_field_to_offset(field);
7643 char *p = ((char *) get_vmcs12(vcpu)) + offset;
7644 if (offset < 0)
7645 return offset;
7647 switch (vmcs_field_width(field)) {
7648 case VMCS_FIELD_WIDTH_U16:
7649 *(u16 *)p = field_value;
7650 return 0;
7651 case VMCS_FIELD_WIDTH_U32:
7652 *(u32 *)p = field_value;
7653 return 0;
7654 case VMCS_FIELD_WIDTH_U64:
7655 *(u64 *)p = field_value;
7656 return 0;
7657 case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
7658 *(natural_width *)p = field_value;
7659 return 0;
7660 default:
7661 WARN_ON(1);
7662 return -ENOENT;
7667 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
7669 int i;
7670 unsigned long field;
7671 u64 field_value;
7672 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7673 const u16 *fields = shadow_read_write_fields;
7674 const int num_fields = max_shadow_read_write_fields;
7676 preempt_disable();
7678 vmcs_load(shadow_vmcs);
7680 for (i = 0; i < num_fields; i++) {
7681 field = fields[i];
7682 field_value = __vmcs_readl(field);
7683 vmcs12_write_any(&vmx->vcpu, field, field_value);
7686 vmcs_clear(shadow_vmcs);
7687 vmcs_load(vmx->loaded_vmcs->vmcs);
7689 preempt_enable();
7692 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
7694 const u16 *fields[] = {
7695 shadow_read_write_fields,
7696 shadow_read_only_fields
7698 const int max_fields[] = {
7699 max_shadow_read_write_fields,
7700 max_shadow_read_only_fields
7702 int i, q;
7703 unsigned long field;
7704 u64 field_value = 0;
7705 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7707 vmcs_load(shadow_vmcs);
7709 for (q = 0; q < ARRAY_SIZE(fields); q++) {
7710 for (i = 0; i < max_fields[q]; i++) {
7711 field = fields[q][i];
7712 vmcs12_read_any(&vmx->vcpu, field, &field_value);
7713 __vmcs_writel(field, field_value);
7717 vmcs_clear(shadow_vmcs);
7718 vmcs_load(vmx->loaded_vmcs->vmcs);
7722 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
7723 * used before) all generate the same failure when it is missing.
7725 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
7727 struct vcpu_vmx *vmx = to_vmx(vcpu);
7728 if (vmx->nested.current_vmptr == -1ull) {
7729 nested_vmx_failInvalid(vcpu);
7730 return 0;
7732 return 1;
7735 static int handle_vmread(struct kvm_vcpu *vcpu)
7737 unsigned long field;
7738 u64 field_value;
7739 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7740 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7741 gva_t gva = 0;
7743 if (!nested_vmx_check_permission(vcpu))
7744 return 1;
7746 if (!nested_vmx_check_vmcs12(vcpu))
7747 return kvm_skip_emulated_instruction(vcpu);
7749 /* Decode instruction info and find the field to read */
7750 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7751 /* Read the field, zero-extended to a u64 field_value */
7752 if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
7753 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7754 return kvm_skip_emulated_instruction(vcpu);
7757 * Now copy part of this value to register or memory, as requested.
7758 * Note that the number of bits actually copied is 32 or 64 depending
7759 * on the guest's mode (32 or 64 bit), not on the given field's length.
7761 if (vmx_instruction_info & (1u << 10)) {
7762 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
7763 field_value);
7764 } else {
7765 if (get_vmx_mem_address(vcpu, exit_qualification,
7766 vmx_instruction_info, true, &gva))
7767 return 1;
7768 /* _system ok, as hardware has verified cpl=0 */
7769 kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
7770 &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
7773 nested_vmx_succeed(vcpu);
7774 return kvm_skip_emulated_instruction(vcpu);
7778 static int handle_vmwrite(struct kvm_vcpu *vcpu)
7780 unsigned long field;
7781 gva_t gva;
7782 struct vcpu_vmx *vmx = to_vmx(vcpu);
7783 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7784 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7786 /* The value to write might be 32 or 64 bits, depending on L1's long
7787 * mode, and eventually we need to write that into a field of several
7788 * possible lengths. The code below first zero-extends the value to 64
7789 * bit (field_value), and then copies only the appropriate number of
7790 * bits into the vmcs12 field.
7792 u64 field_value = 0;
7793 struct x86_exception e;
7795 if (!nested_vmx_check_permission(vcpu))
7796 return 1;
7798 if (!nested_vmx_check_vmcs12(vcpu))
7799 return kvm_skip_emulated_instruction(vcpu);
7801 if (vmx_instruction_info & (1u << 10))
7802 field_value = kvm_register_readl(vcpu,
7803 (((vmx_instruction_info) >> 3) & 0xf));
7804 else {
7805 if (get_vmx_mem_address(vcpu, exit_qualification,
7806 vmx_instruction_info, false, &gva))
7807 return 1;
7808 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
7809 &field_value, (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
7810 kvm_inject_page_fault(vcpu, &e);
7811 return 1;
7816 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7817 if (vmcs_field_readonly(field)) {
7818 nested_vmx_failValid(vcpu,
7819 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
7820 return kvm_skip_emulated_instruction(vcpu);
7823 if (vmcs12_write_any(vcpu, field, field_value) < 0) {
7824 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7825 return kvm_skip_emulated_instruction(vcpu);
7828 switch (field) {
7829 #define SHADOW_FIELD_RW(x) case x:
7830 #include "vmx_shadow_fields.h"
7832 * The fields that can be updated by L1 without a vmexit are
7833 * always updated in the vmcs02, the others go down the slow
7834 * path of prepare_vmcs02.
7836 break;
7837 default:
7838 vmx->nested.dirty_vmcs12 = true;
7839 break;
7842 nested_vmx_succeed(vcpu);
7843 return kvm_skip_emulated_instruction(vcpu);
7846 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
7848 vmx->nested.current_vmptr = vmptr;
7849 if (enable_shadow_vmcs) {
7850 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
7851 SECONDARY_EXEC_SHADOW_VMCS);
7852 vmcs_write64(VMCS_LINK_POINTER,
7853 __pa(vmx->vmcs01.shadow_vmcs));
7854 vmx->nested.sync_shadow_vmcs = true;
7856 vmx->nested.dirty_vmcs12 = true;
7859 /* Emulate the VMPTRLD instruction */
7860 static int handle_vmptrld(struct kvm_vcpu *vcpu)
7862 struct vcpu_vmx *vmx = to_vmx(vcpu);
7863 gpa_t vmptr;
7865 if (!nested_vmx_check_permission(vcpu))
7866 return 1;
7868 if (nested_vmx_get_vmptr(vcpu, &vmptr))
7869 return 1;
7871 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7872 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
7873 return kvm_skip_emulated_instruction(vcpu);
7876 if (vmptr == vmx->nested.vmxon_ptr) {
7877 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
7878 return kvm_skip_emulated_instruction(vcpu);
7881 if (vmx->nested.current_vmptr != vmptr) {
7882 struct vmcs12 *new_vmcs12;
7883 struct page *page;
7884 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7885 if (is_error_page(page)) {
7886 nested_vmx_failInvalid(vcpu);
7887 return kvm_skip_emulated_instruction(vcpu);
7889 new_vmcs12 = kmap(page);
7890 if (new_vmcs12->revision_id != VMCS12_REVISION) {
7891 kunmap(page);
7892 kvm_release_page_clean(page);
7893 nested_vmx_failValid(vcpu,
7894 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
7895 return kvm_skip_emulated_instruction(vcpu);
7898 nested_release_vmcs12(vmx);
7900 * Load VMCS12 from guest memory since it is not already
7901 * cached.
7903 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
7904 kunmap(page);
7905 kvm_release_page_clean(page);
7907 set_current_vmptr(vmx, vmptr);
7910 nested_vmx_succeed(vcpu);
7911 return kvm_skip_emulated_instruction(vcpu);
7914 /* Emulate the VMPTRST instruction */
7915 static int handle_vmptrst(struct kvm_vcpu *vcpu)
7917 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7918 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7919 gva_t vmcs_gva;
7920 struct x86_exception e;
7922 if (!nested_vmx_check_permission(vcpu))
7923 return 1;
7925 if (get_vmx_mem_address(vcpu, exit_qualification,
7926 vmx_instruction_info, true, &vmcs_gva))
7927 return 1;
7928 /* ok to use *_system, as hardware has verified cpl=0 */
7929 if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
7930 (void *)&to_vmx(vcpu)->nested.current_vmptr,
7931 sizeof(u64), &e)) {
7932 kvm_inject_page_fault(vcpu, &e);
7933 return 1;
7935 nested_vmx_succeed(vcpu);
7936 return kvm_skip_emulated_instruction(vcpu);
7939 /* Emulate the INVEPT instruction */
7940 static int handle_invept(struct kvm_vcpu *vcpu)
7942 struct vcpu_vmx *vmx = to_vmx(vcpu);
7943 u32 vmx_instruction_info, types;
7944 unsigned long type;
7945 gva_t gva;
7946 struct x86_exception e;
7947 struct {
7948 u64 eptp, gpa;
7949 } operand;
7951 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7952 SECONDARY_EXEC_ENABLE_EPT) ||
7953 !(vmx->nested.nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
7954 kvm_queue_exception(vcpu, UD_VECTOR);
7955 return 1;
7958 if (!nested_vmx_check_permission(vcpu))
7959 return 1;
7961 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7962 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7964 types = (vmx->nested.nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
7966 if (type >= 32 || !(types & (1 << type))) {
7967 nested_vmx_failValid(vcpu,
7968 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7969 return kvm_skip_emulated_instruction(vcpu);
7972 /* According to the Intel VMX instruction reference, the memory
7973 * operand is read even if it isn't needed (e.g., for type==global)
7975 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7976 vmx_instruction_info, false, &gva))
7977 return 1;
7978 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
7979 sizeof(operand), &e)) {
7980 kvm_inject_page_fault(vcpu, &e);
7981 return 1;
7984 switch (type) {
7985 case VMX_EPT_EXTENT_GLOBAL:
7987 * TODO: track mappings and invalidate
7988 * single context requests appropriately
7990 case VMX_EPT_EXTENT_CONTEXT:
7991 kvm_mmu_sync_roots(vcpu);
7992 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
7993 nested_vmx_succeed(vcpu);
7994 break;
7995 default:
7996 BUG_ON(1);
7997 break;
8000 return kvm_skip_emulated_instruction(vcpu);
8003 static int handle_invvpid(struct kvm_vcpu *vcpu)
8005 struct vcpu_vmx *vmx = to_vmx(vcpu);
8006 u32 vmx_instruction_info;
8007 unsigned long type, types;
8008 gva_t gva;
8009 struct x86_exception e;
8010 struct {
8011 u64 vpid;
8012 u64 gla;
8013 } operand;
8015 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
8016 SECONDARY_EXEC_ENABLE_VPID) ||
8017 !(vmx->nested.nested_vmx_vpid_caps & VMX_VPID_INVVPID_BIT)) {
8018 kvm_queue_exception(vcpu, UD_VECTOR);
8019 return 1;
8022 if (!nested_vmx_check_permission(vcpu))
8023 return 1;
8025 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8026 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
8028 types = (vmx->nested.nested_vmx_vpid_caps &
8029 VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
8031 if (type >= 32 || !(types & (1 << type))) {
8032 nested_vmx_failValid(vcpu,
8033 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8034 return kvm_skip_emulated_instruction(vcpu);
8037 /* according to the intel vmx instruction reference, the memory
8038 * operand is read even if it isn't needed (e.g., for type==global)
8040 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8041 vmx_instruction_info, false, &gva))
8042 return 1;
8043 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
8044 sizeof(operand), &e)) {
8045 kvm_inject_page_fault(vcpu, &e);
8046 return 1;
8048 if (operand.vpid >> 16) {
8049 nested_vmx_failValid(vcpu,
8050 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8051 return kvm_skip_emulated_instruction(vcpu);
8054 switch (type) {
8055 case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
8056 if (is_noncanonical_address(operand.gla, vcpu)) {
8057 nested_vmx_failValid(vcpu,
8058 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8059 return kvm_skip_emulated_instruction(vcpu);
8061 /* fall through */
8062 case VMX_VPID_EXTENT_SINGLE_CONTEXT:
8063 case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
8064 if (!operand.vpid) {
8065 nested_vmx_failValid(vcpu,
8066 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8067 return kvm_skip_emulated_instruction(vcpu);
8069 break;
8070 case VMX_VPID_EXTENT_ALL_CONTEXT:
8071 break;
8072 default:
8073 WARN_ON_ONCE(1);
8074 return kvm_skip_emulated_instruction(vcpu);
8077 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
8078 nested_vmx_succeed(vcpu);
8080 return kvm_skip_emulated_instruction(vcpu);
8083 static int handle_pml_full(struct kvm_vcpu *vcpu)
8085 unsigned long exit_qualification;
8087 trace_kvm_pml_full(vcpu->vcpu_id);
8089 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8092 * PML buffer FULL happened while executing iret from NMI,
8093 * "blocked by NMI" bit has to be set before next VM entry.
8095 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
8096 enable_vnmi &&
8097 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
8098 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
8099 GUEST_INTR_STATE_NMI);
8102 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
8103 * here.., and there's no userspace involvement needed for PML.
8105 return 1;
8108 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
8110 kvm_lapic_expired_hv_timer(vcpu);
8111 return 1;
8114 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
8116 struct vcpu_vmx *vmx = to_vmx(vcpu);
8117 int maxphyaddr = cpuid_maxphyaddr(vcpu);
8119 /* Check for memory type validity */
8120 switch (address & VMX_EPTP_MT_MASK) {
8121 case VMX_EPTP_MT_UC:
8122 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPTP_UC_BIT))
8123 return false;
8124 break;
8125 case VMX_EPTP_MT_WB:
8126 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPTP_WB_BIT))
8127 return false;
8128 break;
8129 default:
8130 return false;
8133 /* only 4 levels page-walk length are valid */
8134 if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
8135 return false;
8137 /* Reserved bits should not be set */
8138 if (address >> maxphyaddr || ((address >> 7) & 0x1f))
8139 return false;
8141 /* AD, if set, should be supported */
8142 if (address & VMX_EPTP_AD_ENABLE_BIT) {
8143 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPT_AD_BIT))
8144 return false;
8147 return true;
8150 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
8151 struct vmcs12 *vmcs12)
8153 u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
8154 u64 address;
8155 bool accessed_dirty;
8156 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8158 if (!nested_cpu_has_eptp_switching(vmcs12) ||
8159 !nested_cpu_has_ept(vmcs12))
8160 return 1;
8162 if (index >= VMFUNC_EPTP_ENTRIES)
8163 return 1;
8166 if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
8167 &address, index * 8, 8))
8168 return 1;
8170 accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
8173 * If the (L2) guest does a vmfunc to the currently
8174 * active ept pointer, we don't have to do anything else
8176 if (vmcs12->ept_pointer != address) {
8177 if (!valid_ept_address(vcpu, address))
8178 return 1;
8180 kvm_mmu_unload(vcpu);
8181 mmu->ept_ad = accessed_dirty;
8182 mmu->base_role.ad_disabled = !accessed_dirty;
8183 vmcs12->ept_pointer = address;
8185 * TODO: Check what's the correct approach in case
8186 * mmu reload fails. Currently, we just let the next
8187 * reload potentially fail
8189 kvm_mmu_reload(vcpu);
8192 return 0;
8195 static int handle_vmfunc(struct kvm_vcpu *vcpu)
8197 struct vcpu_vmx *vmx = to_vmx(vcpu);
8198 struct vmcs12 *vmcs12;
8199 u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
8202 * VMFUNC is only supported for nested guests, but we always enable the
8203 * secondary control for simplicity; for non-nested mode, fake that we
8204 * didn't by injecting #UD.
8206 if (!is_guest_mode(vcpu)) {
8207 kvm_queue_exception(vcpu, UD_VECTOR);
8208 return 1;
8211 vmcs12 = get_vmcs12(vcpu);
8212 if ((vmcs12->vm_function_control & (1 << function)) == 0)
8213 goto fail;
8215 switch (function) {
8216 case 0:
8217 if (nested_vmx_eptp_switching(vcpu, vmcs12))
8218 goto fail;
8219 break;
8220 default:
8221 goto fail;
8223 return kvm_skip_emulated_instruction(vcpu);
8225 fail:
8226 nested_vmx_vmexit(vcpu, vmx->exit_reason,
8227 vmcs_read32(VM_EXIT_INTR_INFO),
8228 vmcs_readl(EXIT_QUALIFICATION));
8229 return 1;
8233 * The exit handlers return 1 if the exit was handled fully and guest execution
8234 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
8235 * to be done to userspace and return 0.
8237 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
8238 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
8239 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
8240 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
8241 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
8242 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
8243 [EXIT_REASON_CR_ACCESS] = handle_cr,
8244 [EXIT_REASON_DR_ACCESS] = handle_dr,
8245 [EXIT_REASON_CPUID] = handle_cpuid,
8246 [EXIT_REASON_MSR_READ] = handle_rdmsr,
8247 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
8248 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
8249 [EXIT_REASON_HLT] = handle_halt,
8250 [EXIT_REASON_INVD] = handle_invd,
8251 [EXIT_REASON_INVLPG] = handle_invlpg,
8252 [EXIT_REASON_RDPMC] = handle_rdpmc,
8253 [EXIT_REASON_VMCALL] = handle_vmcall,
8254 [EXIT_REASON_VMCLEAR] = handle_vmclear,
8255 [EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
8256 [EXIT_REASON_VMPTRLD] = handle_vmptrld,
8257 [EXIT_REASON_VMPTRST] = handle_vmptrst,
8258 [EXIT_REASON_VMREAD] = handle_vmread,
8259 [EXIT_REASON_VMRESUME] = handle_vmresume,
8260 [EXIT_REASON_VMWRITE] = handle_vmwrite,
8261 [EXIT_REASON_VMOFF] = handle_vmoff,
8262 [EXIT_REASON_VMON] = handle_vmon,
8263 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
8264 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
8265 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
8266 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
8267 [EXIT_REASON_WBINVD] = handle_wbinvd,
8268 [EXIT_REASON_XSETBV] = handle_xsetbv,
8269 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
8270 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
8271 [EXIT_REASON_GDTR_IDTR] = handle_desc,
8272 [EXIT_REASON_LDTR_TR] = handle_desc,
8273 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
8274 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
8275 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
8276 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
8277 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
8278 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
8279 [EXIT_REASON_INVEPT] = handle_invept,
8280 [EXIT_REASON_INVVPID] = handle_invvpid,
8281 [EXIT_REASON_RDRAND] = handle_invalid_op,
8282 [EXIT_REASON_RDSEED] = handle_invalid_op,
8283 [EXIT_REASON_XSAVES] = handle_xsaves,
8284 [EXIT_REASON_XRSTORS] = handle_xrstors,
8285 [EXIT_REASON_PML_FULL] = handle_pml_full,
8286 [EXIT_REASON_VMFUNC] = handle_vmfunc,
8287 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
8290 static const int kvm_vmx_max_exit_handlers =
8291 ARRAY_SIZE(kvm_vmx_exit_handlers);
8293 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
8294 struct vmcs12 *vmcs12)
8296 unsigned long exit_qualification;
8297 gpa_t bitmap, last_bitmap;
8298 unsigned int port;
8299 int size;
8300 u8 b;
8302 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
8303 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
8305 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8307 port = exit_qualification >> 16;
8308 size = (exit_qualification & 7) + 1;
8310 last_bitmap = (gpa_t)-1;
8311 b = -1;
8313 while (size > 0) {
8314 if (port < 0x8000)
8315 bitmap = vmcs12->io_bitmap_a;
8316 else if (port < 0x10000)
8317 bitmap = vmcs12->io_bitmap_b;
8318 else
8319 return true;
8320 bitmap += (port & 0x7fff) / 8;
8322 if (last_bitmap != bitmap)
8323 if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
8324 return true;
8325 if (b & (1 << (port & 7)))
8326 return true;
8328 port++;
8329 size--;
8330 last_bitmap = bitmap;
8333 return false;
8337 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
8338 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
8339 * disinterest in the current event (read or write a specific MSR) by using an
8340 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
8342 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
8343 struct vmcs12 *vmcs12, u32 exit_reason)
8345 u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
8346 gpa_t bitmap;
8348 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
8349 return true;
8352 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
8353 * for the four combinations of read/write and low/high MSR numbers.
8354 * First we need to figure out which of the four to use:
8356 bitmap = vmcs12->msr_bitmap;
8357 if (exit_reason == EXIT_REASON_MSR_WRITE)
8358 bitmap += 2048;
8359 if (msr_index >= 0xc0000000) {
8360 msr_index -= 0xc0000000;
8361 bitmap += 1024;
8364 /* Then read the msr_index'th bit from this bitmap: */
8365 if (msr_index < 1024*8) {
8366 unsigned char b;
8367 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
8368 return true;
8369 return 1 & (b >> (msr_index & 7));
8370 } else
8371 return true; /* let L1 handle the wrong parameter */
8375 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
8376 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
8377 * intercept (via guest_host_mask etc.) the current event.
8379 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
8380 struct vmcs12 *vmcs12)
8382 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8383 int cr = exit_qualification & 15;
8384 int reg;
8385 unsigned long val;
8387 switch ((exit_qualification >> 4) & 3) {
8388 case 0: /* mov to cr */
8389 reg = (exit_qualification >> 8) & 15;
8390 val = kvm_register_readl(vcpu, reg);
8391 switch (cr) {
8392 case 0:
8393 if (vmcs12->cr0_guest_host_mask &
8394 (val ^ vmcs12->cr0_read_shadow))
8395 return true;
8396 break;
8397 case 3:
8398 if ((vmcs12->cr3_target_count >= 1 &&
8399 vmcs12->cr3_target_value0 == val) ||
8400 (vmcs12->cr3_target_count >= 2 &&
8401 vmcs12->cr3_target_value1 == val) ||
8402 (vmcs12->cr3_target_count >= 3 &&
8403 vmcs12->cr3_target_value2 == val) ||
8404 (vmcs12->cr3_target_count >= 4 &&
8405 vmcs12->cr3_target_value3 == val))
8406 return false;
8407 if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
8408 return true;
8409 break;
8410 case 4:
8411 if (vmcs12->cr4_guest_host_mask &
8412 (vmcs12->cr4_read_shadow ^ val))
8413 return true;
8414 break;
8415 case 8:
8416 if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
8417 return true;
8418 break;
8420 break;
8421 case 2: /* clts */
8422 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
8423 (vmcs12->cr0_read_shadow & X86_CR0_TS))
8424 return true;
8425 break;
8426 case 1: /* mov from cr */
8427 switch (cr) {
8428 case 3:
8429 if (vmcs12->cpu_based_vm_exec_control &
8430 CPU_BASED_CR3_STORE_EXITING)
8431 return true;
8432 break;
8433 case 8:
8434 if (vmcs12->cpu_based_vm_exec_control &
8435 CPU_BASED_CR8_STORE_EXITING)
8436 return true;
8437 break;
8439 break;
8440 case 3: /* lmsw */
8442 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
8443 * cr0. Other attempted changes are ignored, with no exit.
8445 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
8446 if (vmcs12->cr0_guest_host_mask & 0xe &
8447 (val ^ vmcs12->cr0_read_shadow))
8448 return true;
8449 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
8450 !(vmcs12->cr0_read_shadow & 0x1) &&
8451 (val & 0x1))
8452 return true;
8453 break;
8455 return false;
8459 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
8460 * should handle it ourselves in L0 (and then continue L2). Only call this
8461 * when in is_guest_mode (L2).
8463 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
8465 u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8466 struct vcpu_vmx *vmx = to_vmx(vcpu);
8467 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8469 if (vmx->nested.nested_run_pending)
8470 return false;
8472 if (unlikely(vmx->fail)) {
8473 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
8474 vmcs_read32(VM_INSTRUCTION_ERROR));
8475 return true;
8479 * The host physical addresses of some pages of guest memory
8480 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
8481 * Page). The CPU may write to these pages via their host
8482 * physical address while L2 is running, bypassing any
8483 * address-translation-based dirty tracking (e.g. EPT write
8484 * protection).
8486 * Mark them dirty on every exit from L2 to prevent them from
8487 * getting out of sync with dirty tracking.
8489 nested_mark_vmcs12_pages_dirty(vcpu);
8491 trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
8492 vmcs_readl(EXIT_QUALIFICATION),
8493 vmx->idt_vectoring_info,
8494 intr_info,
8495 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8496 KVM_ISA_VMX);
8498 switch (exit_reason) {
8499 case EXIT_REASON_EXCEPTION_NMI:
8500 if (is_nmi(intr_info))
8501 return false;
8502 else if (is_page_fault(intr_info))
8503 return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
8504 else if (is_no_device(intr_info) &&
8505 !(vmcs12->guest_cr0 & X86_CR0_TS))
8506 return false;
8507 else if (is_debug(intr_info) &&
8508 vcpu->guest_debug &
8509 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
8510 return false;
8511 else if (is_breakpoint(intr_info) &&
8512 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
8513 return false;
8514 return vmcs12->exception_bitmap &
8515 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
8516 case EXIT_REASON_EXTERNAL_INTERRUPT:
8517 return false;
8518 case EXIT_REASON_TRIPLE_FAULT:
8519 return true;
8520 case EXIT_REASON_PENDING_INTERRUPT:
8521 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
8522 case EXIT_REASON_NMI_WINDOW:
8523 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
8524 case EXIT_REASON_TASK_SWITCH:
8525 return true;
8526 case EXIT_REASON_CPUID:
8527 return true;
8528 case EXIT_REASON_HLT:
8529 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
8530 case EXIT_REASON_INVD:
8531 return true;
8532 case EXIT_REASON_INVLPG:
8533 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8534 case EXIT_REASON_RDPMC:
8535 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
8536 case EXIT_REASON_RDRAND:
8537 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
8538 case EXIT_REASON_RDSEED:
8539 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
8540 case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
8541 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
8542 case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
8543 case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
8544 case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
8545 case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
8546 case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
8547 case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
8549 * VMX instructions trap unconditionally. This allows L1 to
8550 * emulate them for its L2 guest, i.e., allows 3-level nesting!
8552 return true;
8553 case EXIT_REASON_CR_ACCESS:
8554 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
8555 case EXIT_REASON_DR_ACCESS:
8556 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
8557 case EXIT_REASON_IO_INSTRUCTION:
8558 return nested_vmx_exit_handled_io(vcpu, vmcs12);
8559 case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
8560 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
8561 case EXIT_REASON_MSR_READ:
8562 case EXIT_REASON_MSR_WRITE:
8563 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
8564 case EXIT_REASON_INVALID_STATE:
8565 return true;
8566 case EXIT_REASON_MWAIT_INSTRUCTION:
8567 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
8568 case EXIT_REASON_MONITOR_TRAP_FLAG:
8569 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
8570 case EXIT_REASON_MONITOR_INSTRUCTION:
8571 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
8572 case EXIT_REASON_PAUSE_INSTRUCTION:
8573 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
8574 nested_cpu_has2(vmcs12,
8575 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
8576 case EXIT_REASON_MCE_DURING_VMENTRY:
8577 return false;
8578 case EXIT_REASON_TPR_BELOW_THRESHOLD:
8579 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
8580 case EXIT_REASON_APIC_ACCESS:
8581 return nested_cpu_has2(vmcs12,
8582 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
8583 case EXIT_REASON_APIC_WRITE:
8584 case EXIT_REASON_EOI_INDUCED:
8585 /* apic_write and eoi_induced should exit unconditionally. */
8586 return true;
8587 case EXIT_REASON_EPT_VIOLATION:
8589 * L0 always deals with the EPT violation. If nested EPT is
8590 * used, and the nested mmu code discovers that the address is
8591 * missing in the guest EPT table (EPT12), the EPT violation
8592 * will be injected with nested_ept_inject_page_fault()
8594 return false;
8595 case EXIT_REASON_EPT_MISCONFIG:
8597 * L2 never uses directly L1's EPT, but rather L0's own EPT
8598 * table (shadow on EPT) or a merged EPT table that L0 built
8599 * (EPT on EPT). So any problems with the structure of the
8600 * table is L0's fault.
8602 return false;
8603 case EXIT_REASON_INVPCID:
8604 return
8605 nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
8606 nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8607 case EXIT_REASON_WBINVD:
8608 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
8609 case EXIT_REASON_XSETBV:
8610 return true;
8611 case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
8613 * This should never happen, since it is not possible to
8614 * set XSS to a non-zero value---neither in L1 nor in L2.
8615 * If if it were, XSS would have to be checked against
8616 * the XSS exit bitmap in vmcs12.
8618 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
8619 case EXIT_REASON_PREEMPTION_TIMER:
8620 return false;
8621 case EXIT_REASON_PML_FULL:
8622 /* We emulate PML support to L1. */
8623 return false;
8624 case EXIT_REASON_VMFUNC:
8625 /* VM functions are emulated through L2->L0 vmexits. */
8626 return false;
8627 default:
8628 return true;
8632 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
8634 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8637 * At this point, the exit interruption info in exit_intr_info
8638 * is only valid for EXCEPTION_NMI exits. For EXTERNAL_INTERRUPT
8639 * we need to query the in-kernel LAPIC.
8641 WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
8642 if ((exit_intr_info &
8643 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
8644 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
8645 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8646 vmcs12->vm_exit_intr_error_code =
8647 vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
8650 nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
8651 vmcs_readl(EXIT_QUALIFICATION));
8652 return 1;
8655 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
8657 *info1 = vmcs_readl(EXIT_QUALIFICATION);
8658 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
8661 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
8663 if (vmx->pml_pg) {
8664 __free_page(vmx->pml_pg);
8665 vmx->pml_pg = NULL;
8669 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
8671 struct vcpu_vmx *vmx = to_vmx(vcpu);
8672 u64 *pml_buf;
8673 u16 pml_idx;
8675 pml_idx = vmcs_read16(GUEST_PML_INDEX);
8677 /* Do nothing if PML buffer is empty */
8678 if (pml_idx == (PML_ENTITY_NUM - 1))
8679 return;
8681 /* PML index always points to next available PML buffer entity */
8682 if (pml_idx >= PML_ENTITY_NUM)
8683 pml_idx = 0;
8684 else
8685 pml_idx++;
8687 pml_buf = page_address(vmx->pml_pg);
8688 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
8689 u64 gpa;
8691 gpa = pml_buf[pml_idx];
8692 WARN_ON(gpa & (PAGE_SIZE - 1));
8693 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
8696 /* reset PML index */
8697 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
8701 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
8702 * Called before reporting dirty_bitmap to userspace.
8704 static void kvm_flush_pml_buffers(struct kvm *kvm)
8706 int i;
8707 struct kvm_vcpu *vcpu;
8709 * We only need to kick vcpu out of guest mode here, as PML buffer
8710 * is flushed at beginning of all VMEXITs, and it's obvious that only
8711 * vcpus running in guest are possible to have unflushed GPAs in PML
8712 * buffer.
8714 kvm_for_each_vcpu(i, vcpu, kvm)
8715 kvm_vcpu_kick(vcpu);
8718 static void vmx_dump_sel(char *name, uint32_t sel)
8720 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
8721 name, vmcs_read16(sel),
8722 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
8723 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
8724 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
8727 static void vmx_dump_dtsel(char *name, uint32_t limit)
8729 pr_err("%s limit=0x%08x, base=0x%016lx\n",
8730 name, vmcs_read32(limit),
8731 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
8734 static void dump_vmcs(void)
8736 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
8737 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
8738 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
8739 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
8740 u32 secondary_exec_control = 0;
8741 unsigned long cr4 = vmcs_readl(GUEST_CR4);
8742 u64 efer = vmcs_read64(GUEST_IA32_EFER);
8743 int i, n;
8745 if (cpu_has_secondary_exec_ctrls())
8746 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8748 pr_err("*** Guest State ***\n");
8749 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8750 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
8751 vmcs_readl(CR0_GUEST_HOST_MASK));
8752 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8753 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
8754 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
8755 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
8756 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
8758 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
8759 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
8760 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
8761 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
8763 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
8764 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
8765 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
8766 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
8767 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8768 vmcs_readl(GUEST_SYSENTER_ESP),
8769 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
8770 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
8771 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
8772 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
8773 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
8774 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
8775 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
8776 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
8777 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
8778 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
8779 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
8780 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
8781 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
8782 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
8783 efer, vmcs_read64(GUEST_IA32_PAT));
8784 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
8785 vmcs_read64(GUEST_IA32_DEBUGCTL),
8786 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
8787 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
8788 pr_err("PerfGlobCtl = 0x%016llx\n",
8789 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
8790 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
8791 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
8792 pr_err("Interruptibility = %08x ActivityState = %08x\n",
8793 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
8794 vmcs_read32(GUEST_ACTIVITY_STATE));
8795 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
8796 pr_err("InterruptStatus = %04x\n",
8797 vmcs_read16(GUEST_INTR_STATUS));
8799 pr_err("*** Host State ***\n");
8800 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
8801 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
8802 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
8803 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
8804 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
8805 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
8806 vmcs_read16(HOST_TR_SELECTOR));
8807 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
8808 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
8809 vmcs_readl(HOST_TR_BASE));
8810 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
8811 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
8812 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
8813 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
8814 vmcs_readl(HOST_CR4));
8815 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8816 vmcs_readl(HOST_IA32_SYSENTER_ESP),
8817 vmcs_read32(HOST_IA32_SYSENTER_CS),
8818 vmcs_readl(HOST_IA32_SYSENTER_EIP));
8819 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
8820 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
8821 vmcs_read64(HOST_IA32_EFER),
8822 vmcs_read64(HOST_IA32_PAT));
8823 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
8824 pr_err("PerfGlobCtl = 0x%016llx\n",
8825 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
8827 pr_err("*** Control State ***\n");
8828 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
8829 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
8830 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
8831 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
8832 vmcs_read32(EXCEPTION_BITMAP),
8833 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
8834 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
8835 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
8836 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
8837 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
8838 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
8839 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
8840 vmcs_read32(VM_EXIT_INTR_INFO),
8841 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8842 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
8843 pr_err(" reason=%08x qualification=%016lx\n",
8844 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
8845 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
8846 vmcs_read32(IDT_VECTORING_INFO_FIELD),
8847 vmcs_read32(IDT_VECTORING_ERROR_CODE));
8848 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
8849 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
8850 pr_err("TSC Multiplier = 0x%016llx\n",
8851 vmcs_read64(TSC_MULTIPLIER));
8852 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
8853 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
8854 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
8855 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
8856 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
8857 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
8858 n = vmcs_read32(CR3_TARGET_COUNT);
8859 for (i = 0; i + 1 < n; i += 4)
8860 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
8861 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
8862 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
8863 if (i < n)
8864 pr_err("CR3 target%u=%016lx\n",
8865 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
8866 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
8867 pr_err("PLE Gap=%08x Window=%08x\n",
8868 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
8869 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
8870 pr_err("Virtual processor ID = 0x%04x\n",
8871 vmcs_read16(VIRTUAL_PROCESSOR_ID));
8875 * The guest has exited. See if we can fix it or if we need userspace
8876 * assistance.
8878 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
8880 struct vcpu_vmx *vmx = to_vmx(vcpu);
8881 u32 exit_reason = vmx->exit_reason;
8882 u32 vectoring_info = vmx->idt_vectoring_info;
8884 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
8887 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
8888 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
8889 * querying dirty_bitmap, we only need to kick all vcpus out of guest
8890 * mode as if vcpus is in root mode, the PML buffer must has been
8891 * flushed already.
8893 if (enable_pml)
8894 vmx_flush_pml_buffer(vcpu);
8896 /* If guest state is invalid, start emulating */
8897 if (vmx->emulation_required)
8898 return handle_invalid_guest_state(vcpu);
8900 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
8901 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
8903 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
8904 dump_vmcs();
8905 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8906 vcpu->run->fail_entry.hardware_entry_failure_reason
8907 = exit_reason;
8908 return 0;
8911 if (unlikely(vmx->fail)) {
8912 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8913 vcpu->run->fail_entry.hardware_entry_failure_reason
8914 = vmcs_read32(VM_INSTRUCTION_ERROR);
8915 return 0;
8919 * Note:
8920 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
8921 * delivery event since it indicates guest is accessing MMIO.
8922 * The vm-exit can be triggered again after return to guest that
8923 * will cause infinite loop.
8925 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
8926 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
8927 exit_reason != EXIT_REASON_EPT_VIOLATION &&
8928 exit_reason != EXIT_REASON_PML_FULL &&
8929 exit_reason != EXIT_REASON_TASK_SWITCH)) {
8930 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8931 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8932 vcpu->run->internal.ndata = 3;
8933 vcpu->run->internal.data[0] = vectoring_info;
8934 vcpu->run->internal.data[1] = exit_reason;
8935 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
8936 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
8937 vcpu->run->internal.ndata++;
8938 vcpu->run->internal.data[3] =
8939 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
8941 return 0;
8944 if (unlikely(!enable_vnmi &&
8945 vmx->loaded_vmcs->soft_vnmi_blocked)) {
8946 if (vmx_interrupt_allowed(vcpu)) {
8947 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
8948 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
8949 vcpu->arch.nmi_pending) {
8951 * This CPU don't support us in finding the end of an
8952 * NMI-blocked window if the guest runs with IRQs
8953 * disabled. So we pull the trigger after 1 s of
8954 * futile waiting, but inform the user about this.
8956 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
8957 "state on VCPU %d after 1 s timeout\n",
8958 __func__, vcpu->vcpu_id);
8959 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
8963 if (exit_reason < kvm_vmx_max_exit_handlers
8964 && kvm_vmx_exit_handlers[exit_reason])
8965 return kvm_vmx_exit_handlers[exit_reason](vcpu);
8966 else {
8967 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
8968 exit_reason);
8969 kvm_queue_exception(vcpu, UD_VECTOR);
8970 return 1;
8974 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
8976 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8978 if (is_guest_mode(vcpu) &&
8979 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
8980 return;
8982 if (irr == -1 || tpr < irr) {
8983 vmcs_write32(TPR_THRESHOLD, 0);
8984 return;
8987 vmcs_write32(TPR_THRESHOLD, irr);
8990 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
8992 u32 sec_exec_control;
8994 /* Postpone execution until vmcs01 is the current VMCS. */
8995 if (is_guest_mode(vcpu)) {
8996 to_vmx(vcpu)->nested.change_vmcs01_virtual_x2apic_mode = true;
8997 return;
9000 if (!cpu_has_vmx_virtualize_x2apic_mode())
9001 return;
9003 if (!cpu_need_tpr_shadow(vcpu))
9004 return;
9006 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9008 if (set) {
9009 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9010 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
9011 } else {
9012 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
9013 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9014 vmx_flush_tlb_ept_only(vcpu);
9016 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
9018 vmx_update_msr_bitmap(vcpu);
9021 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
9023 struct vcpu_vmx *vmx = to_vmx(vcpu);
9026 * Currently we do not handle the nested case where L2 has an
9027 * APIC access page of its own; that page is still pinned.
9028 * Hence, we skip the case where the VCPU is in guest mode _and_
9029 * L1 prepared an APIC access page for L2.
9031 * For the case where L1 and L2 share the same APIC access page
9032 * (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
9033 * in the vmcs12), this function will only update either the vmcs01
9034 * or the vmcs02. If the former, the vmcs02 will be updated by
9035 * prepare_vmcs02. If the latter, the vmcs01 will be updated in
9036 * the next L2->L1 exit.
9038 if (!is_guest_mode(vcpu) ||
9039 !nested_cpu_has2(get_vmcs12(&vmx->vcpu),
9040 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
9041 vmcs_write64(APIC_ACCESS_ADDR, hpa);
9042 vmx_flush_tlb_ept_only(vcpu);
9046 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
9048 u16 status;
9049 u8 old;
9051 if (max_isr == -1)
9052 max_isr = 0;
9054 status = vmcs_read16(GUEST_INTR_STATUS);
9055 old = status >> 8;
9056 if (max_isr != old) {
9057 status &= 0xff;
9058 status |= max_isr << 8;
9059 vmcs_write16(GUEST_INTR_STATUS, status);
9063 static void vmx_set_rvi(int vector)
9065 u16 status;
9066 u8 old;
9068 if (vector == -1)
9069 vector = 0;
9071 status = vmcs_read16(GUEST_INTR_STATUS);
9072 old = (u8)status & 0xff;
9073 if ((u8)vector != old) {
9074 status &= ~0xff;
9075 status |= (u8)vector;
9076 vmcs_write16(GUEST_INTR_STATUS, status);
9080 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
9083 * When running L2, updating RVI is only relevant when
9084 * vmcs12 virtual-interrupt-delivery enabled.
9085 * However, it can be enabled only when L1 also
9086 * intercepts external-interrupts and in that case
9087 * we should not update vmcs02 RVI but instead intercept
9088 * interrupt. Therefore, do nothing when running L2.
9090 if (!is_guest_mode(vcpu))
9091 vmx_set_rvi(max_irr);
9094 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
9096 struct vcpu_vmx *vmx = to_vmx(vcpu);
9097 int max_irr;
9098 bool max_irr_updated;
9100 WARN_ON(!vcpu->arch.apicv_active);
9101 if (pi_test_on(&vmx->pi_desc)) {
9102 pi_clear_on(&vmx->pi_desc);
9104 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
9105 * But on x86 this is just a compiler barrier anyway.
9107 smp_mb__after_atomic();
9108 max_irr_updated =
9109 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
9112 * If we are running L2 and L1 has a new pending interrupt
9113 * which can be injected, we should re-evaluate
9114 * what should be done with this new L1 interrupt.
9115 * If L1 intercepts external-interrupts, we should
9116 * exit from L2 to L1. Otherwise, interrupt should be
9117 * delivered directly to L2.
9119 if (is_guest_mode(vcpu) && max_irr_updated) {
9120 if (nested_exit_on_intr(vcpu))
9121 kvm_vcpu_exiting_guest_mode(vcpu);
9122 else
9123 kvm_make_request(KVM_REQ_EVENT, vcpu);
9125 } else {
9126 max_irr = kvm_lapic_find_highest_irr(vcpu);
9128 vmx_hwapic_irr_update(vcpu, max_irr);
9129 return max_irr;
9132 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
9134 if (!kvm_vcpu_apicv_active(vcpu))
9135 return;
9137 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
9138 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
9139 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
9140 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
9143 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
9145 struct vcpu_vmx *vmx = to_vmx(vcpu);
9147 pi_clear_on(&vmx->pi_desc);
9148 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
9151 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
9153 u32 exit_intr_info = 0;
9154 u16 basic_exit_reason = (u16)vmx->exit_reason;
9156 if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
9157 || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
9158 return;
9160 if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9161 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9162 vmx->exit_intr_info = exit_intr_info;
9164 /* if exit due to PF check for async PF */
9165 if (is_page_fault(exit_intr_info))
9166 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
9168 /* Handle machine checks before interrupts are enabled */
9169 if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
9170 is_machine_check(exit_intr_info))
9171 kvm_machine_check();
9173 /* We need to handle NMIs before interrupts are enabled */
9174 if (is_nmi(exit_intr_info)) {
9175 kvm_before_handle_nmi(&vmx->vcpu);
9176 asm("int $2");
9177 kvm_after_handle_nmi(&vmx->vcpu);
9181 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
9183 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9185 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
9186 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
9187 unsigned int vector;
9188 unsigned long entry;
9189 gate_desc *desc;
9190 struct vcpu_vmx *vmx = to_vmx(vcpu);
9191 #ifdef CONFIG_X86_64
9192 unsigned long tmp;
9193 #endif
9195 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
9196 desc = (gate_desc *)vmx->host_idt_base + vector;
9197 entry = gate_offset(desc);
9198 asm volatile(
9199 #ifdef CONFIG_X86_64
9200 "mov %%" _ASM_SP ", %[sp]\n\t"
9201 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
9202 "push $%c[ss]\n\t"
9203 "push %[sp]\n\t"
9204 #endif
9205 "pushf\n\t"
9206 __ASM_SIZE(push) " $%c[cs]\n\t"
9207 CALL_NOSPEC
9209 #ifdef CONFIG_X86_64
9210 [sp]"=&r"(tmp),
9211 #endif
9212 ASM_CALL_CONSTRAINT
9214 THUNK_TARGET(entry),
9215 [ss]"i"(__KERNEL_DS),
9216 [cs]"i"(__KERNEL_CS)
9220 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
9222 static bool vmx_has_high_real_mode_segbase(void)
9224 return enable_unrestricted_guest || emulate_invalid_guest_state;
9227 static bool vmx_mpx_supported(void)
9229 return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
9230 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
9233 static bool vmx_xsaves_supported(void)
9235 return vmcs_config.cpu_based_2nd_exec_ctrl &
9236 SECONDARY_EXEC_XSAVES;
9239 static bool vmx_umip_emulated(void)
9241 return vmcs_config.cpu_based_2nd_exec_ctrl &
9242 SECONDARY_EXEC_DESC;
9245 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
9247 u32 exit_intr_info;
9248 bool unblock_nmi;
9249 u8 vector;
9250 bool idtv_info_valid;
9252 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9254 if (enable_vnmi) {
9255 if (vmx->loaded_vmcs->nmi_known_unmasked)
9256 return;
9258 * Can't use vmx->exit_intr_info since we're not sure what
9259 * the exit reason is.
9261 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9262 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
9263 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
9265 * SDM 3: 27.7.1.2 (September 2008)
9266 * Re-set bit "block by NMI" before VM entry if vmexit caused by
9267 * a guest IRET fault.
9268 * SDM 3: 23.2.2 (September 2008)
9269 * Bit 12 is undefined in any of the following cases:
9270 * If the VM exit sets the valid bit in the IDT-vectoring
9271 * information field.
9272 * If the VM exit is due to a double fault.
9274 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
9275 vector != DF_VECTOR && !idtv_info_valid)
9276 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9277 GUEST_INTR_STATE_NMI);
9278 else
9279 vmx->loaded_vmcs->nmi_known_unmasked =
9280 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
9281 & GUEST_INTR_STATE_NMI);
9282 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
9283 vmx->loaded_vmcs->vnmi_blocked_time +=
9284 ktime_to_ns(ktime_sub(ktime_get(),
9285 vmx->loaded_vmcs->entry_time));
9288 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
9289 u32 idt_vectoring_info,
9290 int instr_len_field,
9291 int error_code_field)
9293 u8 vector;
9294 int type;
9295 bool idtv_info_valid;
9297 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9299 vcpu->arch.nmi_injected = false;
9300 kvm_clear_exception_queue(vcpu);
9301 kvm_clear_interrupt_queue(vcpu);
9303 if (!idtv_info_valid)
9304 return;
9306 kvm_make_request(KVM_REQ_EVENT, vcpu);
9308 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
9309 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
9311 switch (type) {
9312 case INTR_TYPE_NMI_INTR:
9313 vcpu->arch.nmi_injected = true;
9315 * SDM 3: 27.7.1.2 (September 2008)
9316 * Clear bit "block by NMI" before VM entry if a NMI
9317 * delivery faulted.
9319 vmx_set_nmi_mask(vcpu, false);
9320 break;
9321 case INTR_TYPE_SOFT_EXCEPTION:
9322 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9323 /* fall through */
9324 case INTR_TYPE_HARD_EXCEPTION:
9325 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
9326 u32 err = vmcs_read32(error_code_field);
9327 kvm_requeue_exception_e(vcpu, vector, err);
9328 } else
9329 kvm_requeue_exception(vcpu, vector);
9330 break;
9331 case INTR_TYPE_SOFT_INTR:
9332 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9333 /* fall through */
9334 case INTR_TYPE_EXT_INTR:
9335 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
9336 break;
9337 default:
9338 break;
9342 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
9344 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
9345 VM_EXIT_INSTRUCTION_LEN,
9346 IDT_VECTORING_ERROR_CODE);
9349 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
9351 __vmx_complete_interrupts(vcpu,
9352 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
9353 VM_ENTRY_INSTRUCTION_LEN,
9354 VM_ENTRY_EXCEPTION_ERROR_CODE);
9356 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
9359 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
9361 int i, nr_msrs;
9362 struct perf_guest_switch_msr *msrs;
9364 msrs = perf_guest_get_msrs(&nr_msrs);
9366 if (!msrs)
9367 return;
9369 for (i = 0; i < nr_msrs; i++)
9370 if (msrs[i].host == msrs[i].guest)
9371 clear_atomic_switch_msr(vmx, msrs[i].msr);
9372 else
9373 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
9374 msrs[i].host);
9377 static void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
9379 struct vcpu_vmx *vmx = to_vmx(vcpu);
9380 u64 tscl;
9381 u32 delta_tsc;
9383 if (vmx->hv_deadline_tsc == -1)
9384 return;
9386 tscl = rdtsc();
9387 if (vmx->hv_deadline_tsc > tscl)
9388 /* sure to be 32 bit only because checked on set_hv_timer */
9389 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
9390 cpu_preemption_timer_multi);
9391 else
9392 delta_tsc = 0;
9394 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
9397 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
9399 struct vcpu_vmx *vmx = to_vmx(vcpu);
9400 unsigned long cr3, cr4;
9402 /* Record the guest's net vcpu time for enforced NMI injections. */
9403 if (unlikely(!enable_vnmi &&
9404 vmx->loaded_vmcs->soft_vnmi_blocked))
9405 vmx->loaded_vmcs->entry_time = ktime_get();
9407 /* Don't enter VMX if guest state is invalid, let the exit handler
9408 start emulation until we arrive back to a valid state */
9409 if (vmx->emulation_required)
9410 return;
9412 if (vmx->ple_window_dirty) {
9413 vmx->ple_window_dirty = false;
9414 vmcs_write32(PLE_WINDOW, vmx->ple_window);
9417 if (vmx->nested.sync_shadow_vmcs) {
9418 copy_vmcs12_to_shadow(vmx);
9419 vmx->nested.sync_shadow_vmcs = false;
9422 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
9423 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
9424 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
9425 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
9427 cr3 = __get_current_cr3_fast();
9428 if (unlikely(cr3 != vmx->loaded_vmcs->vmcs_host_cr3)) {
9429 vmcs_writel(HOST_CR3, cr3);
9430 vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
9433 cr4 = cr4_read_shadow();
9434 if (unlikely(cr4 != vmx->loaded_vmcs->vmcs_host_cr4)) {
9435 vmcs_writel(HOST_CR4, cr4);
9436 vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
9439 /* When single-stepping over STI and MOV SS, we must clear the
9440 * corresponding interruptibility bits in the guest state. Otherwise
9441 * vmentry fails as it then expects bit 14 (BS) in pending debug
9442 * exceptions being set, but that's not correct for the guest debugging
9443 * case. */
9444 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9445 vmx_set_interrupt_shadow(vcpu, 0);
9447 if (static_cpu_has(X86_FEATURE_PKU) &&
9448 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
9449 vcpu->arch.pkru != vmx->host_pkru)
9450 __write_pkru(vcpu->arch.pkru);
9452 atomic_switch_perf_msrs(vmx);
9454 vmx_arm_hv_timer(vcpu);
9457 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
9458 * it's non-zero. Since vmentry is serialising on affected CPUs, there
9459 * is no need to worry about the conditional branch over the wrmsr
9460 * being speculatively taken.
9462 if (vmx->spec_ctrl)
9463 native_wrmsrl(MSR_IA32_SPEC_CTRL, vmx->spec_ctrl);
9465 vmx->__launched = vmx->loaded_vmcs->launched;
9466 asm(
9467 /* Store host registers */
9468 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
9469 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
9470 "push %%" _ASM_CX " \n\t"
9471 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9472 "je 1f \n\t"
9473 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9474 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
9475 "1: \n\t"
9476 /* Reload cr2 if changed */
9477 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
9478 "mov %%cr2, %%" _ASM_DX " \n\t"
9479 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
9480 "je 2f \n\t"
9481 "mov %%" _ASM_AX", %%cr2 \n\t"
9482 "2: \n\t"
9483 /* Check if vmlaunch of vmresume is needed */
9484 "cmpl $0, %c[launched](%0) \n\t"
9485 /* Load guest registers. Don't clobber flags. */
9486 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
9487 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
9488 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
9489 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
9490 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
9491 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
9492 #ifdef CONFIG_X86_64
9493 "mov %c[r8](%0), %%r8 \n\t"
9494 "mov %c[r9](%0), %%r9 \n\t"
9495 "mov %c[r10](%0), %%r10 \n\t"
9496 "mov %c[r11](%0), %%r11 \n\t"
9497 "mov %c[r12](%0), %%r12 \n\t"
9498 "mov %c[r13](%0), %%r13 \n\t"
9499 "mov %c[r14](%0), %%r14 \n\t"
9500 "mov %c[r15](%0), %%r15 \n\t"
9501 #endif
9502 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
9504 /* Enter guest mode */
9505 "jne 1f \n\t"
9506 __ex(ASM_VMX_VMLAUNCH) "\n\t"
9507 "jmp 2f \n\t"
9508 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
9509 "2: "
9510 /* Save guest registers, load host registers, keep flags */
9511 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
9512 "pop %0 \n\t"
9513 "setbe %c[fail](%0)\n\t"
9514 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
9515 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
9516 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
9517 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
9518 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
9519 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
9520 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
9521 #ifdef CONFIG_X86_64
9522 "mov %%r8, %c[r8](%0) \n\t"
9523 "mov %%r9, %c[r9](%0) \n\t"
9524 "mov %%r10, %c[r10](%0) \n\t"
9525 "mov %%r11, %c[r11](%0) \n\t"
9526 "mov %%r12, %c[r12](%0) \n\t"
9527 "mov %%r13, %c[r13](%0) \n\t"
9528 "mov %%r14, %c[r14](%0) \n\t"
9529 "mov %%r15, %c[r15](%0) \n\t"
9530 "xor %%r8d, %%r8d \n\t"
9531 "xor %%r9d, %%r9d \n\t"
9532 "xor %%r10d, %%r10d \n\t"
9533 "xor %%r11d, %%r11d \n\t"
9534 "xor %%r12d, %%r12d \n\t"
9535 "xor %%r13d, %%r13d \n\t"
9536 "xor %%r14d, %%r14d \n\t"
9537 "xor %%r15d, %%r15d \n\t"
9538 #endif
9539 "mov %%cr2, %%" _ASM_AX " \n\t"
9540 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
9542 "xor %%eax, %%eax \n\t"
9543 "xor %%ebx, %%ebx \n\t"
9544 "xor %%esi, %%esi \n\t"
9545 "xor %%edi, %%edi \n\t"
9546 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
9547 ".pushsection .rodata \n\t"
9548 ".global vmx_return \n\t"
9549 "vmx_return: " _ASM_PTR " 2b \n\t"
9550 ".popsection"
9551 : : "c"(vmx), "d"((unsigned long)HOST_RSP),
9552 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
9553 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
9554 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
9555 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
9556 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
9557 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
9558 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
9559 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
9560 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
9561 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
9562 #ifdef CONFIG_X86_64
9563 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
9564 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
9565 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
9566 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
9567 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
9568 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
9569 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
9570 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
9571 #endif
9572 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
9573 [wordsize]"i"(sizeof(ulong))
9574 : "cc", "memory"
9575 #ifdef CONFIG_X86_64
9576 , "rax", "rbx", "rdi", "rsi"
9577 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
9578 #else
9579 , "eax", "ebx", "edi", "esi"
9580 #endif
9584 * We do not use IBRS in the kernel. If this vCPU has used the
9585 * SPEC_CTRL MSR it may have left it on; save the value and
9586 * turn it off. This is much more efficient than blindly adding
9587 * it to the atomic save/restore list. Especially as the former
9588 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
9590 * For non-nested case:
9591 * If the L01 MSR bitmap does not intercept the MSR, then we need to
9592 * save it.
9594 * For nested case:
9595 * If the L02 MSR bitmap does not intercept the MSR, then we need to
9596 * save it.
9598 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
9599 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
9601 if (vmx->spec_ctrl)
9602 native_wrmsrl(MSR_IA32_SPEC_CTRL, 0);
9604 /* Eliminate branch target predictions from guest mode */
9605 vmexit_fill_RSB();
9607 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
9608 if (vmx->host_debugctlmsr)
9609 update_debugctlmsr(vmx->host_debugctlmsr);
9611 #ifndef CONFIG_X86_64
9613 * The sysexit path does not restore ds/es, so we must set them to
9614 * a reasonable value ourselves.
9616 * We can't defer this to vmx_load_host_state() since that function
9617 * may be executed in interrupt context, which saves and restore segments
9618 * around it, nullifying its effect.
9620 loadsegment(ds, __USER_DS);
9621 loadsegment(es, __USER_DS);
9622 #endif
9624 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
9625 | (1 << VCPU_EXREG_RFLAGS)
9626 | (1 << VCPU_EXREG_PDPTR)
9627 | (1 << VCPU_EXREG_SEGMENTS)
9628 | (1 << VCPU_EXREG_CR3));
9629 vcpu->arch.regs_dirty = 0;
9632 * eager fpu is enabled if PKEY is supported and CR4 is switched
9633 * back on host, so it is safe to read guest PKRU from current
9634 * XSAVE.
9636 if (static_cpu_has(X86_FEATURE_PKU) &&
9637 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
9638 vcpu->arch.pkru = __read_pkru();
9639 if (vcpu->arch.pkru != vmx->host_pkru)
9640 __write_pkru(vmx->host_pkru);
9644 * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
9645 * we did not inject a still-pending event to L1 now because of
9646 * nested_run_pending, we need to re-enable this bit.
9648 if (vmx->nested.nested_run_pending)
9649 kvm_make_request(KVM_REQ_EVENT, vcpu);
9651 vmx->nested.nested_run_pending = 0;
9652 vmx->idt_vectoring_info = 0;
9654 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
9655 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9656 return;
9658 vmx->loaded_vmcs->launched = 1;
9659 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
9661 vmx_complete_atomic_exit(vmx);
9662 vmx_recover_nmi_blocking(vmx);
9663 vmx_complete_interrupts(vmx);
9665 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
9667 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
9669 struct vcpu_vmx *vmx = to_vmx(vcpu);
9670 int cpu;
9672 if (vmx->loaded_vmcs == vmcs)
9673 return;
9675 cpu = get_cpu();
9676 vmx->loaded_vmcs = vmcs;
9677 vmx_vcpu_put(vcpu);
9678 vmx_vcpu_load(vcpu, cpu);
9679 put_cpu();
9683 * Ensure that the current vmcs of the logical processor is the
9684 * vmcs01 of the vcpu before calling free_nested().
9686 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
9688 struct vcpu_vmx *vmx = to_vmx(vcpu);
9690 vcpu_load(vcpu);
9691 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
9692 free_nested(vmx);
9693 vcpu_put(vcpu);
9696 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
9698 struct vcpu_vmx *vmx = to_vmx(vcpu);
9700 if (enable_pml)
9701 vmx_destroy_pml_buffer(vmx);
9702 free_vpid(vmx->vpid);
9703 leave_guest_mode(vcpu);
9704 vmx_free_vcpu_nested(vcpu);
9705 free_loaded_vmcs(vmx->loaded_vmcs);
9706 kfree(vmx->guest_msrs);
9707 kvm_vcpu_uninit(vcpu);
9708 kmem_cache_free(kvm_vcpu_cache, vmx);
9711 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
9713 int err;
9714 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
9715 unsigned long *msr_bitmap;
9716 int cpu;
9718 if (!vmx)
9719 return ERR_PTR(-ENOMEM);
9721 vmx->vpid = allocate_vpid();
9723 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
9724 if (err)
9725 goto free_vcpu;
9727 err = -ENOMEM;
9730 * If PML is turned on, failure on enabling PML just results in failure
9731 * of creating the vcpu, therefore we can simplify PML logic (by
9732 * avoiding dealing with cases, such as enabling PML partially on vcpus
9733 * for the guest, etc.
9735 if (enable_pml) {
9736 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
9737 if (!vmx->pml_pg)
9738 goto uninit_vcpu;
9741 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
9742 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
9743 > PAGE_SIZE);
9745 if (!vmx->guest_msrs)
9746 goto free_pml;
9748 err = alloc_loaded_vmcs(&vmx->vmcs01);
9749 if (err < 0)
9750 goto free_msrs;
9752 msr_bitmap = vmx->vmcs01.msr_bitmap;
9753 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
9754 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
9755 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
9756 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
9757 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
9758 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
9759 vmx->msr_bitmap_mode = 0;
9761 vmx->loaded_vmcs = &vmx->vmcs01;
9762 cpu = get_cpu();
9763 vmx_vcpu_load(&vmx->vcpu, cpu);
9764 vmx->vcpu.cpu = cpu;
9765 vmx_vcpu_setup(vmx);
9766 vmx_vcpu_put(&vmx->vcpu);
9767 put_cpu();
9768 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
9769 err = alloc_apic_access_page(kvm);
9770 if (err)
9771 goto free_vmcs;
9774 if (enable_ept) {
9775 err = init_rmode_identity_map(kvm);
9776 if (err)
9777 goto free_vmcs;
9780 if (nested) {
9781 nested_vmx_setup_ctls_msrs(vmx);
9782 vmx->nested.vpid02 = allocate_vpid();
9785 vmx->nested.posted_intr_nv = -1;
9786 vmx->nested.current_vmptr = -1ull;
9788 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
9791 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
9792 * or POSTED_INTR_WAKEUP_VECTOR.
9794 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
9795 vmx->pi_desc.sn = 1;
9797 return &vmx->vcpu;
9799 free_vmcs:
9800 free_vpid(vmx->nested.vpid02);
9801 free_loaded_vmcs(vmx->loaded_vmcs);
9802 free_msrs:
9803 kfree(vmx->guest_msrs);
9804 free_pml:
9805 vmx_destroy_pml_buffer(vmx);
9806 uninit_vcpu:
9807 kvm_vcpu_uninit(&vmx->vcpu);
9808 free_vcpu:
9809 free_vpid(vmx->vpid);
9810 kmem_cache_free(kvm_vcpu_cache, vmx);
9811 return ERR_PTR(err);
9814 static void __init vmx_check_processor_compat(void *rtn)
9816 struct vmcs_config vmcs_conf;
9818 *(int *)rtn = 0;
9819 if (setup_vmcs_config(&vmcs_conf) < 0)
9820 *(int *)rtn = -EIO;
9821 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
9822 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
9823 smp_processor_id());
9824 *(int *)rtn = -EIO;
9828 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
9830 u8 cache;
9831 u64 ipat = 0;
9833 /* For VT-d and EPT combination
9834 * 1. MMIO: always map as UC
9835 * 2. EPT with VT-d:
9836 * a. VT-d without snooping control feature: can't guarantee the
9837 * result, try to trust guest.
9838 * b. VT-d with snooping control feature: snooping control feature of
9839 * VT-d engine can guarantee the cache correctness. Just set it
9840 * to WB to keep consistent with host. So the same as item 3.
9841 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
9842 * consistent with host MTRR
9844 if (is_mmio) {
9845 cache = MTRR_TYPE_UNCACHABLE;
9846 goto exit;
9849 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
9850 ipat = VMX_EPT_IPAT_BIT;
9851 cache = MTRR_TYPE_WRBACK;
9852 goto exit;
9855 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
9856 ipat = VMX_EPT_IPAT_BIT;
9857 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
9858 cache = MTRR_TYPE_WRBACK;
9859 else
9860 cache = MTRR_TYPE_UNCACHABLE;
9861 goto exit;
9864 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
9866 exit:
9867 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
9870 static int vmx_get_lpage_level(void)
9872 if (enable_ept && !cpu_has_vmx_ept_1g_page())
9873 return PT_DIRECTORY_LEVEL;
9874 else
9875 /* For shadow and EPT supported 1GB page */
9876 return PT_PDPE_LEVEL;
9879 static void vmcs_set_secondary_exec_control(u32 new_ctl)
9882 * These bits in the secondary execution controls field
9883 * are dynamic, the others are mostly based on the hypervisor
9884 * architecture and the guest's CPUID. Do not touch the
9885 * dynamic bits.
9887 u32 mask =
9888 SECONDARY_EXEC_SHADOW_VMCS |
9889 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
9890 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
9891 SECONDARY_EXEC_DESC;
9893 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9895 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
9896 (new_ctl & ~mask) | (cur_ctl & mask));
9900 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
9901 * (indicating "allowed-1") if they are supported in the guest's CPUID.
9903 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
9905 struct vcpu_vmx *vmx = to_vmx(vcpu);
9906 struct kvm_cpuid_entry2 *entry;
9908 vmx->nested.nested_vmx_cr0_fixed1 = 0xffffffff;
9909 vmx->nested.nested_vmx_cr4_fixed1 = X86_CR4_PCE;
9911 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
9912 if (entry && (entry->_reg & (_cpuid_mask))) \
9913 vmx->nested.nested_vmx_cr4_fixed1 |= (_cr4_mask); \
9914 } while (0)
9916 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
9917 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
9918 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
9919 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
9920 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
9921 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
9922 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
9923 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
9924 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
9925 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
9926 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
9927 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
9928 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
9929 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
9930 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
9932 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
9933 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
9934 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
9935 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
9936 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
9937 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
9939 #undef cr4_fixed1_update
9942 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
9944 struct vcpu_vmx *vmx = to_vmx(vcpu);
9946 if (cpu_has_secondary_exec_ctrls()) {
9947 vmx_compute_secondary_exec_control(vmx);
9948 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
9951 if (nested_vmx_allowed(vcpu))
9952 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
9953 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9954 else
9955 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
9956 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9958 if (nested_vmx_allowed(vcpu))
9959 nested_vmx_cr_fixed1_bits_update(vcpu);
9962 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
9964 if (func == 1 && nested)
9965 entry->ecx |= bit(X86_FEATURE_VMX);
9968 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
9969 struct x86_exception *fault)
9971 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9972 struct vcpu_vmx *vmx = to_vmx(vcpu);
9973 u32 exit_reason;
9974 unsigned long exit_qualification = vcpu->arch.exit_qualification;
9976 if (vmx->nested.pml_full) {
9977 exit_reason = EXIT_REASON_PML_FULL;
9978 vmx->nested.pml_full = false;
9979 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
9980 } else if (fault->error_code & PFERR_RSVD_MASK)
9981 exit_reason = EXIT_REASON_EPT_MISCONFIG;
9982 else
9983 exit_reason = EXIT_REASON_EPT_VIOLATION;
9985 nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
9986 vmcs12->guest_physical_address = fault->address;
9989 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
9991 return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
9994 /* Callbacks for nested_ept_init_mmu_context: */
9996 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
9998 /* return the page table to be shadowed - in our case, EPT12 */
9999 return get_vmcs12(vcpu)->ept_pointer;
10002 static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
10004 WARN_ON(mmu_is_nested(vcpu));
10005 if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
10006 return 1;
10008 kvm_mmu_unload(vcpu);
10009 kvm_init_shadow_ept_mmu(vcpu,
10010 to_vmx(vcpu)->nested.nested_vmx_ept_caps &
10011 VMX_EPT_EXECUTE_ONLY_BIT,
10012 nested_ept_ad_enabled(vcpu));
10013 vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
10014 vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
10015 vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
10017 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
10018 return 0;
10021 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
10023 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
10026 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
10027 u16 error_code)
10029 bool inequality, bit;
10031 bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
10032 inequality =
10033 (error_code & vmcs12->page_fault_error_code_mask) !=
10034 vmcs12->page_fault_error_code_match;
10035 return inequality ^ bit;
10038 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
10039 struct x86_exception *fault)
10041 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10043 WARN_ON(!is_guest_mode(vcpu));
10045 if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
10046 !to_vmx(vcpu)->nested.nested_run_pending) {
10047 vmcs12->vm_exit_intr_error_code = fault->error_code;
10048 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
10049 PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
10050 INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
10051 fault->address);
10052 } else {
10053 kvm_inject_page_fault(vcpu, fault);
10057 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
10058 struct vmcs12 *vmcs12);
10060 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
10061 struct vmcs12 *vmcs12)
10063 struct vcpu_vmx *vmx = to_vmx(vcpu);
10064 struct page *page;
10065 u64 hpa;
10067 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10069 * Translate L1 physical address to host physical
10070 * address for vmcs02. Keep the page pinned, so this
10071 * physical address remains valid. We keep a reference
10072 * to it so we can release it later.
10074 if (vmx->nested.apic_access_page) { /* shouldn't happen */
10075 kvm_release_page_dirty(vmx->nested.apic_access_page);
10076 vmx->nested.apic_access_page = NULL;
10078 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
10080 * If translation failed, no matter: This feature asks
10081 * to exit when accessing the given address, and if it
10082 * can never be accessed, this feature won't do
10083 * anything anyway.
10085 if (!is_error_page(page)) {
10086 vmx->nested.apic_access_page = page;
10087 hpa = page_to_phys(vmx->nested.apic_access_page);
10088 vmcs_write64(APIC_ACCESS_ADDR, hpa);
10089 } else {
10090 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
10091 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
10093 } else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
10094 cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
10095 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
10096 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
10097 kvm_vcpu_reload_apic_access_page(vcpu);
10100 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
10101 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
10102 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
10103 vmx->nested.virtual_apic_page = NULL;
10105 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
10108 * If translation failed, VM entry will fail because
10109 * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
10110 * Failing the vm entry is _not_ what the processor
10111 * does but it's basically the only possibility we
10112 * have. We could still enter the guest if CR8 load
10113 * exits are enabled, CR8 store exits are enabled, and
10114 * virtualize APIC access is disabled; in this case
10115 * the processor would never use the TPR shadow and we
10116 * could simply clear the bit from the execution
10117 * control. But such a configuration is useless, so
10118 * let's keep the code simple.
10120 if (!is_error_page(page)) {
10121 vmx->nested.virtual_apic_page = page;
10122 hpa = page_to_phys(vmx->nested.virtual_apic_page);
10123 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
10127 if (nested_cpu_has_posted_intr(vmcs12)) {
10128 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
10129 kunmap(vmx->nested.pi_desc_page);
10130 kvm_release_page_dirty(vmx->nested.pi_desc_page);
10131 vmx->nested.pi_desc_page = NULL;
10133 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
10134 if (is_error_page(page))
10135 return;
10136 vmx->nested.pi_desc_page = page;
10137 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
10138 vmx->nested.pi_desc =
10139 (struct pi_desc *)((void *)vmx->nested.pi_desc +
10140 (unsigned long)(vmcs12->posted_intr_desc_addr &
10141 (PAGE_SIZE - 1)));
10142 vmcs_write64(POSTED_INTR_DESC_ADDR,
10143 page_to_phys(vmx->nested.pi_desc_page) +
10144 (unsigned long)(vmcs12->posted_intr_desc_addr &
10145 (PAGE_SIZE - 1)));
10147 if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
10148 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
10149 CPU_BASED_USE_MSR_BITMAPS);
10150 else
10151 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
10152 CPU_BASED_USE_MSR_BITMAPS);
10155 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
10157 u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
10158 struct vcpu_vmx *vmx = to_vmx(vcpu);
10160 if (vcpu->arch.virtual_tsc_khz == 0)
10161 return;
10163 /* Make sure short timeouts reliably trigger an immediate vmexit.
10164 * hrtimer_start does not guarantee this. */
10165 if (preemption_timeout <= 1) {
10166 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
10167 return;
10170 preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
10171 preemption_timeout *= 1000000;
10172 do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
10173 hrtimer_start(&vmx->nested.preemption_timer,
10174 ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
10177 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
10178 struct vmcs12 *vmcs12)
10180 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
10181 return 0;
10183 if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
10184 !page_address_valid(vcpu, vmcs12->io_bitmap_b))
10185 return -EINVAL;
10187 return 0;
10190 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
10191 struct vmcs12 *vmcs12)
10193 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
10194 return 0;
10196 if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
10197 return -EINVAL;
10199 return 0;
10202 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
10203 struct vmcs12 *vmcs12)
10205 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10206 return 0;
10208 if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
10209 return -EINVAL;
10211 return 0;
10215 * Merge L0's and L1's MSR bitmap, return false to indicate that
10216 * we do not use the hardware.
10218 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
10219 struct vmcs12 *vmcs12)
10221 int msr;
10222 struct page *page;
10223 unsigned long *msr_bitmap_l1;
10224 unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
10226 * pred_cmd & spec_ctrl are trying to verify two things:
10228 * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
10229 * ensures that we do not accidentally generate an L02 MSR bitmap
10230 * from the L12 MSR bitmap that is too permissive.
10231 * 2. That L1 or L2s have actually used the MSR. This avoids
10232 * unnecessarily merging of the bitmap if the MSR is unused. This
10233 * works properly because we only update the L01 MSR bitmap lazily.
10234 * So even if L0 should pass L1 these MSRs, the L01 bitmap is only
10235 * updated to reflect this when L1 (or its L2s) actually write to
10236 * the MSR.
10238 bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
10239 bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
10241 /* Nothing to do if the MSR bitmap is not in use. */
10242 if (!cpu_has_vmx_msr_bitmap() ||
10243 !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
10244 return false;
10246 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10247 !pred_cmd && !spec_ctrl)
10248 return false;
10250 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
10251 if (is_error_page(page))
10252 return false;
10254 msr_bitmap_l1 = (unsigned long *)kmap(page);
10255 if (nested_cpu_has_apic_reg_virt(vmcs12)) {
10257 * L0 need not intercept reads for MSRs between 0x800 and 0x8ff, it
10258 * just lets the processor take the value from the virtual-APIC page;
10259 * take those 256 bits directly from the L1 bitmap.
10261 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
10262 unsigned word = msr / BITS_PER_LONG;
10263 msr_bitmap_l0[word] = msr_bitmap_l1[word];
10264 msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
10266 } else {
10267 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
10268 unsigned word = msr / BITS_PER_LONG;
10269 msr_bitmap_l0[word] = ~0;
10270 msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
10274 nested_vmx_disable_intercept_for_msr(
10275 msr_bitmap_l1, msr_bitmap_l0,
10276 X2APIC_MSR(APIC_TASKPRI),
10277 MSR_TYPE_W);
10279 if (nested_cpu_has_vid(vmcs12)) {
10280 nested_vmx_disable_intercept_for_msr(
10281 msr_bitmap_l1, msr_bitmap_l0,
10282 X2APIC_MSR(APIC_EOI),
10283 MSR_TYPE_W);
10284 nested_vmx_disable_intercept_for_msr(
10285 msr_bitmap_l1, msr_bitmap_l0,
10286 X2APIC_MSR(APIC_SELF_IPI),
10287 MSR_TYPE_W);
10290 if (spec_ctrl)
10291 nested_vmx_disable_intercept_for_msr(
10292 msr_bitmap_l1, msr_bitmap_l0,
10293 MSR_IA32_SPEC_CTRL,
10294 MSR_TYPE_R | MSR_TYPE_W);
10296 if (pred_cmd)
10297 nested_vmx_disable_intercept_for_msr(
10298 msr_bitmap_l1, msr_bitmap_l0,
10299 MSR_IA32_PRED_CMD,
10300 MSR_TYPE_W);
10302 kunmap(page);
10303 kvm_release_page_clean(page);
10305 return true;
10308 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
10309 struct vmcs12 *vmcs12)
10311 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10312 !nested_cpu_has_apic_reg_virt(vmcs12) &&
10313 !nested_cpu_has_vid(vmcs12) &&
10314 !nested_cpu_has_posted_intr(vmcs12))
10315 return 0;
10318 * If virtualize x2apic mode is enabled,
10319 * virtualize apic access must be disabled.
10321 if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10322 nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
10323 return -EINVAL;
10326 * If virtual interrupt delivery is enabled,
10327 * we must exit on external interrupts.
10329 if (nested_cpu_has_vid(vmcs12) &&
10330 !nested_exit_on_intr(vcpu))
10331 return -EINVAL;
10334 * bits 15:8 should be zero in posted_intr_nv,
10335 * the descriptor address has been already checked
10336 * in nested_get_vmcs12_pages.
10338 if (nested_cpu_has_posted_intr(vmcs12) &&
10339 (!nested_cpu_has_vid(vmcs12) ||
10340 !nested_exit_intr_ack_set(vcpu) ||
10341 vmcs12->posted_intr_nv & 0xff00))
10342 return -EINVAL;
10344 /* tpr shadow is needed by all apicv features. */
10345 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10346 return -EINVAL;
10348 return 0;
10351 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
10352 unsigned long count_field,
10353 unsigned long addr_field)
10355 int maxphyaddr;
10356 u64 count, addr;
10358 if (vmcs12_read_any(vcpu, count_field, &count) ||
10359 vmcs12_read_any(vcpu, addr_field, &addr)) {
10360 WARN_ON(1);
10361 return -EINVAL;
10363 if (count == 0)
10364 return 0;
10365 maxphyaddr = cpuid_maxphyaddr(vcpu);
10366 if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
10367 (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
10368 pr_debug_ratelimited(
10369 "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
10370 addr_field, maxphyaddr, count, addr);
10371 return -EINVAL;
10373 return 0;
10376 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
10377 struct vmcs12 *vmcs12)
10379 if (vmcs12->vm_exit_msr_load_count == 0 &&
10380 vmcs12->vm_exit_msr_store_count == 0 &&
10381 vmcs12->vm_entry_msr_load_count == 0)
10382 return 0; /* Fast path */
10383 if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
10384 VM_EXIT_MSR_LOAD_ADDR) ||
10385 nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
10386 VM_EXIT_MSR_STORE_ADDR) ||
10387 nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
10388 VM_ENTRY_MSR_LOAD_ADDR))
10389 return -EINVAL;
10390 return 0;
10393 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
10394 struct vmcs12 *vmcs12)
10396 u64 address = vmcs12->pml_address;
10397 int maxphyaddr = cpuid_maxphyaddr(vcpu);
10399 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
10400 if (!nested_cpu_has_ept(vmcs12) ||
10401 !IS_ALIGNED(address, 4096) ||
10402 address >> maxphyaddr)
10403 return -EINVAL;
10406 return 0;
10409 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
10410 struct vmx_msr_entry *e)
10412 /* x2APIC MSR accesses are not allowed */
10413 if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
10414 return -EINVAL;
10415 if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
10416 e->index == MSR_IA32_UCODE_REV)
10417 return -EINVAL;
10418 if (e->reserved != 0)
10419 return -EINVAL;
10420 return 0;
10423 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
10424 struct vmx_msr_entry *e)
10426 if (e->index == MSR_FS_BASE ||
10427 e->index == MSR_GS_BASE ||
10428 e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
10429 nested_vmx_msr_check_common(vcpu, e))
10430 return -EINVAL;
10431 return 0;
10434 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
10435 struct vmx_msr_entry *e)
10437 if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
10438 nested_vmx_msr_check_common(vcpu, e))
10439 return -EINVAL;
10440 return 0;
10444 * Load guest's/host's msr at nested entry/exit.
10445 * return 0 for success, entry index for failure.
10447 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10449 u32 i;
10450 struct vmx_msr_entry e;
10451 struct msr_data msr;
10453 msr.host_initiated = false;
10454 for (i = 0; i < count; i++) {
10455 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
10456 &e, sizeof(e))) {
10457 pr_debug_ratelimited(
10458 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10459 __func__, i, gpa + i * sizeof(e));
10460 goto fail;
10462 if (nested_vmx_load_msr_check(vcpu, &e)) {
10463 pr_debug_ratelimited(
10464 "%s check failed (%u, 0x%x, 0x%x)\n",
10465 __func__, i, e.index, e.reserved);
10466 goto fail;
10468 msr.index = e.index;
10469 msr.data = e.value;
10470 if (kvm_set_msr(vcpu, &msr)) {
10471 pr_debug_ratelimited(
10472 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10473 __func__, i, e.index, e.value);
10474 goto fail;
10477 return 0;
10478 fail:
10479 return i + 1;
10482 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10484 u32 i;
10485 struct vmx_msr_entry e;
10487 for (i = 0; i < count; i++) {
10488 struct msr_data msr_info;
10489 if (kvm_vcpu_read_guest(vcpu,
10490 gpa + i * sizeof(e),
10491 &e, 2 * sizeof(u32))) {
10492 pr_debug_ratelimited(
10493 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10494 __func__, i, gpa + i * sizeof(e));
10495 return -EINVAL;
10497 if (nested_vmx_store_msr_check(vcpu, &e)) {
10498 pr_debug_ratelimited(
10499 "%s check failed (%u, 0x%x, 0x%x)\n",
10500 __func__, i, e.index, e.reserved);
10501 return -EINVAL;
10503 msr_info.host_initiated = false;
10504 msr_info.index = e.index;
10505 if (kvm_get_msr(vcpu, &msr_info)) {
10506 pr_debug_ratelimited(
10507 "%s cannot read MSR (%u, 0x%x)\n",
10508 __func__, i, e.index);
10509 return -EINVAL;
10511 if (kvm_vcpu_write_guest(vcpu,
10512 gpa + i * sizeof(e) +
10513 offsetof(struct vmx_msr_entry, value),
10514 &msr_info.data, sizeof(msr_info.data))) {
10515 pr_debug_ratelimited(
10516 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10517 __func__, i, e.index, msr_info.data);
10518 return -EINVAL;
10521 return 0;
10524 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
10526 unsigned long invalid_mask;
10528 invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
10529 return (val & invalid_mask) == 0;
10533 * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
10534 * emulating VM entry into a guest with EPT enabled.
10535 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10536 * is assigned to entry_failure_code on failure.
10538 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
10539 u32 *entry_failure_code)
10541 if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
10542 if (!nested_cr3_valid(vcpu, cr3)) {
10543 *entry_failure_code = ENTRY_FAIL_DEFAULT;
10544 return 1;
10548 * If PAE paging and EPT are both on, CR3 is not used by the CPU and
10549 * must not be dereferenced.
10551 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
10552 !nested_ept) {
10553 if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
10554 *entry_failure_code = ENTRY_FAIL_PDPTE;
10555 return 1;
10559 vcpu->arch.cr3 = cr3;
10560 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
10563 kvm_mmu_reset_context(vcpu);
10564 return 0;
10567 static void prepare_vmcs02_full(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10568 bool from_vmentry)
10570 struct vcpu_vmx *vmx = to_vmx(vcpu);
10572 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
10573 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
10574 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
10575 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
10576 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
10577 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
10578 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
10579 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
10580 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
10581 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
10582 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
10583 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
10584 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
10585 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
10586 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
10587 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
10588 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
10589 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
10590 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
10591 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
10592 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
10593 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
10594 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
10595 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
10596 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
10597 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
10598 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
10599 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
10600 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
10601 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
10602 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
10604 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
10605 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
10606 vmcs12->guest_pending_dbg_exceptions);
10607 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
10608 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
10610 if (nested_cpu_has_xsaves(vmcs12))
10611 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
10612 vmcs_write64(VMCS_LINK_POINTER, -1ull);
10614 if (cpu_has_vmx_posted_intr())
10615 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
10618 * Whether page-faults are trapped is determined by a combination of
10619 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
10620 * If enable_ept, L0 doesn't care about page faults and we should
10621 * set all of these to L1's desires. However, if !enable_ept, L0 does
10622 * care about (at least some) page faults, and because it is not easy
10623 * (if at all possible?) to merge L0 and L1's desires, we simply ask
10624 * to exit on each and every L2 page fault. This is done by setting
10625 * MASK=MATCH=0 and (see below) EB.PF=1.
10626 * Note that below we don't need special code to set EB.PF beyond the
10627 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
10628 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
10629 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
10631 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
10632 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
10633 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
10634 enable_ept ? vmcs12->page_fault_error_code_match : 0);
10636 /* All VMFUNCs are currently emulated through L0 vmexits. */
10637 if (cpu_has_vmx_vmfunc())
10638 vmcs_write64(VM_FUNCTION_CONTROL, 0);
10640 if (cpu_has_vmx_apicv()) {
10641 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
10642 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
10643 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
10644 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
10648 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
10649 * Some constant fields are set here by vmx_set_constant_host_state().
10650 * Other fields are different per CPU, and will be set later when
10651 * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
10653 vmx_set_constant_host_state(vmx);
10656 * Set the MSR load/store lists to match L0's settings.
10658 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
10659 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10660 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
10661 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10662 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
10664 set_cr4_guest_host_mask(vmx);
10666 if (vmx_mpx_supported())
10667 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
10669 if (enable_vpid) {
10670 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
10671 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
10672 else
10673 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
10677 * L1 may access the L2's PDPTR, so save them to construct vmcs12
10679 if (enable_ept) {
10680 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
10681 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
10682 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
10683 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
10686 if (cpu_has_vmx_msr_bitmap())
10687 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
10691 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
10692 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
10693 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
10694 * guest in a way that will both be appropriate to L1's requests, and our
10695 * needs. In addition to modifying the active vmcs (which is vmcs02), this
10696 * function also has additional necessary side-effects, like setting various
10697 * vcpu->arch fields.
10698 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10699 * is assigned to entry_failure_code on failure.
10701 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10702 bool from_vmentry, u32 *entry_failure_code)
10704 struct vcpu_vmx *vmx = to_vmx(vcpu);
10705 u32 exec_control, vmcs12_exec_ctrl;
10708 * First, the fields that are shadowed. This must be kept in sync
10709 * with vmx_shadow_fields.h.
10712 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
10713 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
10714 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
10715 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
10716 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
10719 * Not in vmcs02: GUEST_PML_INDEX, HOST_FS_SELECTOR, HOST_GS_SELECTOR,
10720 * HOST_FS_BASE, HOST_GS_BASE.
10723 if (from_vmentry &&
10724 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
10725 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
10726 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
10727 } else {
10728 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
10729 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
10731 if (from_vmentry) {
10732 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
10733 vmcs12->vm_entry_intr_info_field);
10734 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
10735 vmcs12->vm_entry_exception_error_code);
10736 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
10737 vmcs12->vm_entry_instruction_len);
10738 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
10739 vmcs12->guest_interruptibility_info);
10740 vmx->loaded_vmcs->nmi_known_unmasked =
10741 !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
10742 } else {
10743 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10745 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
10747 exec_control = vmcs12->pin_based_vm_exec_control;
10749 /* Preemption timer setting is only taken from vmcs01. */
10750 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10751 exec_control |= vmcs_config.pin_based_exec_ctrl;
10752 if (vmx->hv_deadline_tsc == -1)
10753 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10755 /* Posted interrupts setting is only taken from vmcs12. */
10756 if (nested_cpu_has_posted_intr(vmcs12)) {
10757 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
10758 vmx->nested.pi_pending = false;
10759 } else {
10760 exec_control &= ~PIN_BASED_POSTED_INTR;
10763 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
10765 vmx->nested.preemption_timer_expired = false;
10766 if (nested_cpu_has_preemption_timer(vmcs12))
10767 vmx_start_preemption_timer(vcpu);
10769 if (cpu_has_secondary_exec_ctrls()) {
10770 exec_control = vmx->secondary_exec_control;
10772 /* Take the following fields only from vmcs12 */
10773 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10774 SECONDARY_EXEC_ENABLE_INVPCID |
10775 SECONDARY_EXEC_RDTSCP |
10776 SECONDARY_EXEC_XSAVES |
10777 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
10778 SECONDARY_EXEC_APIC_REGISTER_VIRT |
10779 SECONDARY_EXEC_ENABLE_VMFUNC);
10780 if (nested_cpu_has(vmcs12,
10781 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
10782 vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
10783 ~SECONDARY_EXEC_ENABLE_PML;
10784 exec_control |= vmcs12_exec_ctrl;
10787 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
10788 vmcs_write16(GUEST_INTR_STATUS,
10789 vmcs12->guest_intr_status);
10792 * Write an illegal value to APIC_ACCESS_ADDR. Later,
10793 * nested_get_vmcs12_pages will either fix it up or
10794 * remove the VM execution control.
10796 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
10797 vmcs_write64(APIC_ACCESS_ADDR, -1ull);
10799 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
10803 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
10804 * entry, but only if the current (host) sp changed from the value
10805 * we wrote last (vmx->host_rsp). This cache is no longer relevant
10806 * if we switch vmcs, and rather than hold a separate cache per vmcs,
10807 * here we just force the write to happen on entry.
10809 vmx->host_rsp = 0;
10811 exec_control = vmx_exec_control(vmx); /* L0's desires */
10812 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
10813 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
10814 exec_control &= ~CPU_BASED_TPR_SHADOW;
10815 exec_control |= vmcs12->cpu_based_vm_exec_control;
10818 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
10819 * nested_get_vmcs12_pages can't fix it up, the illegal value
10820 * will result in a VM entry failure.
10822 if (exec_control & CPU_BASED_TPR_SHADOW) {
10823 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
10824 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
10825 } else {
10826 #ifdef CONFIG_X86_64
10827 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
10828 CPU_BASED_CR8_STORE_EXITING;
10829 #endif
10833 * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
10834 * for I/O port accesses.
10836 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
10837 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
10839 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
10841 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
10842 * bitwise-or of what L1 wants to trap for L2, and what we want to
10843 * trap. Note that CR0.TS also needs updating - we do this later.
10845 update_exception_bitmap(vcpu);
10846 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
10847 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
10849 /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
10850 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
10851 * bits are further modified by vmx_set_efer() below.
10853 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
10855 /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
10856 * emulated by vmx_set_efer(), below.
10858 vm_entry_controls_init(vmx,
10859 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
10860 ~VM_ENTRY_IA32E_MODE) |
10861 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
10863 if (from_vmentry &&
10864 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
10865 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
10866 vcpu->arch.pat = vmcs12->guest_ia32_pat;
10867 } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
10868 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
10871 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
10872 vmcs_write64(TSC_OFFSET,
10873 vcpu->arch.tsc_offset + vmcs12->tsc_offset);
10874 else
10875 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
10876 if (kvm_has_tsc_control)
10877 decache_tsc_multiplier(vmx);
10879 if (enable_vpid) {
10881 * There is no direct mapping between vpid02 and vpid12, the
10882 * vpid02 is per-vCPU for L0 and reused while the value of
10883 * vpid12 is changed w/ one invvpid during nested vmentry.
10884 * The vpid12 is allocated by L1 for L2, so it will not
10885 * influence global bitmap(for vpid01 and vpid02 allocation)
10886 * even if spawn a lot of nested vCPUs.
10888 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
10889 if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
10890 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
10891 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02, true);
10893 } else {
10894 vmx_flush_tlb(vcpu, true);
10898 if (enable_pml) {
10900 * Conceptually we want to copy the PML address and index from
10901 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
10902 * since we always flush the log on each vmexit, this happens
10903 * to be equivalent to simply resetting the fields in vmcs02.
10905 ASSERT(vmx->pml_pg);
10906 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
10907 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10910 if (nested_cpu_has_ept(vmcs12)) {
10911 if (nested_ept_init_mmu_context(vcpu)) {
10912 *entry_failure_code = ENTRY_FAIL_DEFAULT;
10913 return 1;
10915 } else if (nested_cpu_has2(vmcs12,
10916 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10917 vmx_flush_tlb_ept_only(vcpu);
10921 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
10922 * bits which we consider mandatory enabled.
10923 * The CR0_READ_SHADOW is what L2 should have expected to read given
10924 * the specifications by L1; It's not enough to take
10925 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
10926 * have more bits than L1 expected.
10928 vmx_set_cr0(vcpu, vmcs12->guest_cr0);
10929 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
10931 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
10932 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
10934 if (from_vmentry &&
10935 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
10936 vcpu->arch.efer = vmcs12->guest_ia32_efer;
10937 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
10938 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
10939 else
10940 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
10941 /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
10942 vmx_set_efer(vcpu, vcpu->arch.efer);
10944 if (vmx->nested.dirty_vmcs12) {
10945 prepare_vmcs02_full(vcpu, vmcs12, from_vmentry);
10946 vmx->nested.dirty_vmcs12 = false;
10949 /* Shadow page tables on either EPT or shadow page tables. */
10950 if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
10951 entry_failure_code))
10952 return 1;
10954 if (!enable_ept)
10955 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
10957 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
10958 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
10959 return 0;
10962 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10964 struct vcpu_vmx *vmx = to_vmx(vcpu);
10966 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
10967 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
10968 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10970 if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
10971 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10973 if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
10974 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10976 if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
10977 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10979 if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
10980 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10982 if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
10983 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10985 if (nested_vmx_check_pml_controls(vcpu, vmcs12))
10986 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10988 if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
10989 vmx->nested.nested_vmx_procbased_ctls_low,
10990 vmx->nested.nested_vmx_procbased_ctls_high) ||
10991 (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
10992 !vmx_control_verify(vmcs12->secondary_vm_exec_control,
10993 vmx->nested.nested_vmx_secondary_ctls_low,
10994 vmx->nested.nested_vmx_secondary_ctls_high)) ||
10995 !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
10996 vmx->nested.nested_vmx_pinbased_ctls_low,
10997 vmx->nested.nested_vmx_pinbased_ctls_high) ||
10998 !vmx_control_verify(vmcs12->vm_exit_controls,
10999 vmx->nested.nested_vmx_exit_ctls_low,
11000 vmx->nested.nested_vmx_exit_ctls_high) ||
11001 !vmx_control_verify(vmcs12->vm_entry_controls,
11002 vmx->nested.nested_vmx_entry_ctls_low,
11003 vmx->nested.nested_vmx_entry_ctls_high))
11004 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11006 if (nested_cpu_has_vmfunc(vmcs12)) {
11007 if (vmcs12->vm_function_control &
11008 ~vmx->nested.nested_vmx_vmfunc_controls)
11009 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11011 if (nested_cpu_has_eptp_switching(vmcs12)) {
11012 if (!nested_cpu_has_ept(vmcs12) ||
11013 !page_address_valid(vcpu, vmcs12->eptp_list_address))
11014 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11018 if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
11019 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11021 if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
11022 !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
11023 !nested_cr3_valid(vcpu, vmcs12->host_cr3))
11024 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
11026 return 0;
11029 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11030 u32 *exit_qual)
11032 bool ia32e;
11034 *exit_qual = ENTRY_FAIL_DEFAULT;
11036 if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
11037 !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
11038 return 1;
11040 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS) &&
11041 vmcs12->vmcs_link_pointer != -1ull) {
11042 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
11043 return 1;
11047 * If the load IA32_EFER VM-entry control is 1, the following checks
11048 * are performed on the field for the IA32_EFER MSR:
11049 * - Bits reserved in the IA32_EFER MSR must be 0.
11050 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
11051 * the IA-32e mode guest VM-exit control. It must also be identical
11052 * to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
11053 * CR0.PG) is 1.
11055 if (to_vmx(vcpu)->nested.nested_run_pending &&
11056 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
11057 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
11058 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
11059 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
11060 ((vmcs12->guest_cr0 & X86_CR0_PG) &&
11061 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
11062 return 1;
11066 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
11067 * IA32_EFER MSR must be 0 in the field for that register. In addition,
11068 * the values of the LMA and LME bits in the field must each be that of
11069 * the host address-space size VM-exit control.
11071 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
11072 ia32e = (vmcs12->vm_exit_controls &
11073 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
11074 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
11075 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
11076 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
11077 return 1;
11080 if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
11081 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
11082 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
11083 return 1;
11085 return 0;
11088 static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, bool from_vmentry)
11090 struct vcpu_vmx *vmx = to_vmx(vcpu);
11091 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11092 u32 msr_entry_idx;
11093 u32 exit_qual;
11095 enter_guest_mode(vcpu);
11097 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
11098 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11100 vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
11101 vmx_segment_cache_clear(vmx);
11103 if (prepare_vmcs02(vcpu, vmcs12, from_vmentry, &exit_qual)) {
11104 leave_guest_mode(vcpu);
11105 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11106 nested_vmx_entry_failure(vcpu, vmcs12,
11107 EXIT_REASON_INVALID_STATE, exit_qual);
11108 return 1;
11111 nested_get_vmcs12_pages(vcpu, vmcs12);
11113 msr_entry_idx = nested_vmx_load_msr(vcpu,
11114 vmcs12->vm_entry_msr_load_addr,
11115 vmcs12->vm_entry_msr_load_count);
11116 if (msr_entry_idx) {
11117 leave_guest_mode(vcpu);
11118 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11119 nested_vmx_entry_failure(vcpu, vmcs12,
11120 EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
11121 return 1;
11125 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
11126 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
11127 * returned as far as L1 is concerned. It will only return (and set
11128 * the success flag) when L2 exits (see nested_vmx_vmexit()).
11130 return 0;
11134 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
11135 * for running an L2 nested guest.
11137 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
11139 struct vmcs12 *vmcs12;
11140 struct vcpu_vmx *vmx = to_vmx(vcpu);
11141 u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
11142 u32 exit_qual;
11143 int ret;
11145 if (!nested_vmx_check_permission(vcpu))
11146 return 1;
11148 if (!nested_vmx_check_vmcs12(vcpu))
11149 goto out;
11151 vmcs12 = get_vmcs12(vcpu);
11153 if (enable_shadow_vmcs)
11154 copy_shadow_to_vmcs12(vmx);
11157 * The nested entry process starts with enforcing various prerequisites
11158 * on vmcs12 as required by the Intel SDM, and act appropriately when
11159 * they fail: As the SDM explains, some conditions should cause the
11160 * instruction to fail, while others will cause the instruction to seem
11161 * to succeed, but return an EXIT_REASON_INVALID_STATE.
11162 * To speed up the normal (success) code path, we should avoid checking
11163 * for misconfigurations which will anyway be caught by the processor
11164 * when using the merged vmcs02.
11166 if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
11167 nested_vmx_failValid(vcpu,
11168 VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
11169 goto out;
11172 if (vmcs12->launch_state == launch) {
11173 nested_vmx_failValid(vcpu,
11174 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
11175 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
11176 goto out;
11179 ret = check_vmentry_prereqs(vcpu, vmcs12);
11180 if (ret) {
11181 nested_vmx_failValid(vcpu, ret);
11182 goto out;
11186 * After this point, the trap flag no longer triggers a singlestep trap
11187 * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
11188 * This is not 100% correct; for performance reasons, we delegate most
11189 * of the checks on host state to the processor. If those fail,
11190 * the singlestep trap is missed.
11192 skip_emulated_instruction(vcpu);
11194 ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
11195 if (ret) {
11196 nested_vmx_entry_failure(vcpu, vmcs12,
11197 EXIT_REASON_INVALID_STATE, exit_qual);
11198 return 1;
11202 * We're finally done with prerequisite checking, and can start with
11203 * the nested entry.
11206 ret = enter_vmx_non_root_mode(vcpu, true);
11207 if (ret)
11208 return ret;
11211 * If we're entering a halted L2 vcpu and the L2 vcpu won't be woken
11212 * by event injection, halt vcpu.
11214 if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
11215 !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK))
11216 return kvm_vcpu_halt(vcpu);
11218 vmx->nested.nested_run_pending = 1;
11220 return 1;
11222 out:
11223 return kvm_skip_emulated_instruction(vcpu);
11227 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
11228 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
11229 * This function returns the new value we should put in vmcs12.guest_cr0.
11230 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
11231 * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
11232 * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
11233 * didn't trap the bit, because if L1 did, so would L0).
11234 * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
11235 * been modified by L2, and L1 knows it. So just leave the old value of
11236 * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
11237 * isn't relevant, because if L0 traps this bit it can set it to anything.
11238 * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
11239 * changed these bits, and therefore they need to be updated, but L0
11240 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather
11241 * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
11243 static inline unsigned long
11244 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11246 return
11247 /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
11248 /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
11249 /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
11250 vcpu->arch.cr0_guest_owned_bits));
11253 static inline unsigned long
11254 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11256 return
11257 /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
11258 /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
11259 /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
11260 vcpu->arch.cr4_guest_owned_bits));
11263 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
11264 struct vmcs12 *vmcs12)
11266 u32 idt_vectoring;
11267 unsigned int nr;
11269 if (vcpu->arch.exception.injected) {
11270 nr = vcpu->arch.exception.nr;
11271 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11273 if (kvm_exception_is_soft(nr)) {
11274 vmcs12->vm_exit_instruction_len =
11275 vcpu->arch.event_exit_inst_len;
11276 idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
11277 } else
11278 idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
11280 if (vcpu->arch.exception.has_error_code) {
11281 idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
11282 vmcs12->idt_vectoring_error_code =
11283 vcpu->arch.exception.error_code;
11286 vmcs12->idt_vectoring_info_field = idt_vectoring;
11287 } else if (vcpu->arch.nmi_injected) {
11288 vmcs12->idt_vectoring_info_field =
11289 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
11290 } else if (vcpu->arch.interrupt.pending) {
11291 nr = vcpu->arch.interrupt.nr;
11292 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11294 if (vcpu->arch.interrupt.soft) {
11295 idt_vectoring |= INTR_TYPE_SOFT_INTR;
11296 vmcs12->vm_entry_instruction_len =
11297 vcpu->arch.event_exit_inst_len;
11298 } else
11299 idt_vectoring |= INTR_TYPE_EXT_INTR;
11301 vmcs12->idt_vectoring_info_field = idt_vectoring;
11305 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
11307 struct vcpu_vmx *vmx = to_vmx(vcpu);
11308 unsigned long exit_qual;
11309 bool block_nested_events =
11310 vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
11312 if (vcpu->arch.exception.pending &&
11313 nested_vmx_check_exception(vcpu, &exit_qual)) {
11314 if (block_nested_events)
11315 return -EBUSY;
11316 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
11317 return 0;
11320 if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
11321 vmx->nested.preemption_timer_expired) {
11322 if (block_nested_events)
11323 return -EBUSY;
11324 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
11325 return 0;
11328 if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
11329 if (block_nested_events)
11330 return -EBUSY;
11331 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11332 NMI_VECTOR | INTR_TYPE_NMI_INTR |
11333 INTR_INFO_VALID_MASK, 0);
11335 * The NMI-triggered VM exit counts as injection:
11336 * clear this one and block further NMIs.
11338 vcpu->arch.nmi_pending = 0;
11339 vmx_set_nmi_mask(vcpu, true);
11340 return 0;
11343 if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
11344 nested_exit_on_intr(vcpu)) {
11345 if (block_nested_events)
11346 return -EBUSY;
11347 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
11348 return 0;
11351 vmx_complete_nested_posted_interrupt(vcpu);
11352 return 0;
11355 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
11357 ktime_t remaining =
11358 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
11359 u64 value;
11361 if (ktime_to_ns(remaining) <= 0)
11362 return 0;
11364 value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
11365 do_div(value, 1000000);
11366 return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11370 * Update the guest state fields of vmcs12 to reflect changes that
11371 * occurred while L2 was running. (The "IA-32e mode guest" bit of the
11372 * VM-entry controls is also updated, since this is really a guest
11373 * state bit.)
11375 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11377 vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
11378 vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
11380 vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
11381 vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
11382 vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
11384 vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
11385 vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
11386 vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
11387 vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
11388 vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
11389 vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
11390 vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
11391 vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
11392 vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
11393 vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
11394 vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
11395 vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
11396 vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
11397 vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
11398 vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
11399 vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
11400 vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
11401 vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
11402 vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
11403 vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
11404 vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
11405 vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
11406 vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
11407 vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
11408 vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
11409 vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
11410 vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
11411 vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
11412 vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
11413 vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
11414 vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
11415 vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
11416 vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
11417 vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
11418 vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
11419 vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
11421 vmcs12->guest_interruptibility_info =
11422 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
11423 vmcs12->guest_pending_dbg_exceptions =
11424 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
11425 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11426 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
11427 else
11428 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
11430 if (nested_cpu_has_preemption_timer(vmcs12)) {
11431 if (vmcs12->vm_exit_controls &
11432 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
11433 vmcs12->vmx_preemption_timer_value =
11434 vmx_get_preemption_timer_value(vcpu);
11435 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
11439 * In some cases (usually, nested EPT), L2 is allowed to change its
11440 * own CR3 without exiting. If it has changed it, we must keep it.
11441 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
11442 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
11444 * Additionally, restore L2's PDPTR to vmcs12.
11446 if (enable_ept) {
11447 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
11448 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
11449 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
11450 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
11451 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
11454 vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
11456 if (nested_cpu_has_vid(vmcs12))
11457 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
11459 vmcs12->vm_entry_controls =
11460 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
11461 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
11463 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
11464 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
11465 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11468 /* TODO: These cannot have changed unless we have MSR bitmaps and
11469 * the relevant bit asks not to trap the change */
11470 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
11471 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
11472 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
11473 vmcs12->guest_ia32_efer = vcpu->arch.efer;
11474 vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
11475 vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
11476 vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
11477 if (kvm_mpx_supported())
11478 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
11482 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
11483 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
11484 * and this function updates it to reflect the changes to the guest state while
11485 * L2 was running (and perhaps made some exits which were handled directly by L0
11486 * without going back to L1), and to reflect the exit reason.
11487 * Note that we do not have to copy here all VMCS fields, just those that
11488 * could have changed by the L2 guest or the exit - i.e., the guest-state and
11489 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
11490 * which already writes to vmcs12 directly.
11492 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11493 u32 exit_reason, u32 exit_intr_info,
11494 unsigned long exit_qualification)
11496 /* update guest state fields: */
11497 sync_vmcs12(vcpu, vmcs12);
11499 /* update exit information fields: */
11501 vmcs12->vm_exit_reason = exit_reason;
11502 vmcs12->exit_qualification = exit_qualification;
11503 vmcs12->vm_exit_intr_info = exit_intr_info;
11505 vmcs12->idt_vectoring_info_field = 0;
11506 vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
11507 vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
11509 if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
11510 vmcs12->launch_state = 1;
11512 /* vm_entry_intr_info_field is cleared on exit. Emulate this
11513 * instead of reading the real value. */
11514 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
11517 * Transfer the event that L0 or L1 may wanted to inject into
11518 * L2 to IDT_VECTORING_INFO_FIELD.
11520 vmcs12_save_pending_event(vcpu, vmcs12);
11524 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
11525 * preserved above and would only end up incorrectly in L1.
11527 vcpu->arch.nmi_injected = false;
11528 kvm_clear_exception_queue(vcpu);
11529 kvm_clear_interrupt_queue(vcpu);
11532 static void load_vmcs12_mmu_host_state(struct kvm_vcpu *vcpu,
11533 struct vmcs12 *vmcs12)
11535 u32 entry_failure_code;
11537 nested_ept_uninit_mmu_context(vcpu);
11540 * Only PDPTE load can fail as the value of cr3 was checked on entry and
11541 * couldn't have changed.
11543 if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
11544 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
11546 if (!enable_ept)
11547 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
11551 * A part of what we need to when the nested L2 guest exits and we want to
11552 * run its L1 parent, is to reset L1's guest state to the host state specified
11553 * in vmcs12.
11554 * This function is to be called not only on normal nested exit, but also on
11555 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
11556 * Failures During or After Loading Guest State").
11557 * This function should be called when the active VMCS is L1's (vmcs01).
11559 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
11560 struct vmcs12 *vmcs12)
11562 struct kvm_segment seg;
11564 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
11565 vcpu->arch.efer = vmcs12->host_ia32_efer;
11566 else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11567 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11568 else
11569 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11570 vmx_set_efer(vcpu, vcpu->arch.efer);
11572 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
11573 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
11574 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
11576 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
11577 * actually changed, because vmx_set_cr0 refers to efer set above.
11579 * CR0_GUEST_HOST_MASK is already set in the original vmcs01
11580 * (KVM doesn't change it);
11582 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
11583 vmx_set_cr0(vcpu, vmcs12->host_cr0);
11585 /* Same as above - no reason to call set_cr4_guest_host_mask(). */
11586 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
11587 vmx_set_cr4(vcpu, vmcs12->host_cr4);
11589 load_vmcs12_mmu_host_state(vcpu, vmcs12);
11591 if (enable_vpid) {
11593 * Trivially support vpid by letting L2s share their parent
11594 * L1's vpid. TODO: move to a more elaborate solution, giving
11595 * each L2 its own vpid and exposing the vpid feature to L1.
11597 vmx_flush_tlb(vcpu, true);
11600 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
11601 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
11602 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
11603 vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
11604 vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
11605 vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
11606 vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
11608 /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
11609 if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
11610 vmcs_write64(GUEST_BNDCFGS, 0);
11612 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
11613 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
11614 vcpu->arch.pat = vmcs12->host_ia32_pat;
11616 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
11617 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
11618 vmcs12->host_ia32_perf_global_ctrl);
11620 /* Set L1 segment info according to Intel SDM
11621 27.5.2 Loading Host Segment and Descriptor-Table Registers */
11622 seg = (struct kvm_segment) {
11623 .base = 0,
11624 .limit = 0xFFFFFFFF,
11625 .selector = vmcs12->host_cs_selector,
11626 .type = 11,
11627 .present = 1,
11628 .s = 1,
11629 .g = 1
11631 if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11632 seg.l = 1;
11633 else
11634 seg.db = 1;
11635 vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
11636 seg = (struct kvm_segment) {
11637 .base = 0,
11638 .limit = 0xFFFFFFFF,
11639 .type = 3,
11640 .present = 1,
11641 .s = 1,
11642 .db = 1,
11643 .g = 1
11645 seg.selector = vmcs12->host_ds_selector;
11646 vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
11647 seg.selector = vmcs12->host_es_selector;
11648 vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
11649 seg.selector = vmcs12->host_ss_selector;
11650 vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
11651 seg.selector = vmcs12->host_fs_selector;
11652 seg.base = vmcs12->host_fs_base;
11653 vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
11654 seg.selector = vmcs12->host_gs_selector;
11655 seg.base = vmcs12->host_gs_base;
11656 vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
11657 seg = (struct kvm_segment) {
11658 .base = vmcs12->host_tr_base,
11659 .limit = 0x67,
11660 .selector = vmcs12->host_tr_selector,
11661 .type = 11,
11662 .present = 1
11664 vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
11666 kvm_set_dr(vcpu, 7, 0x400);
11667 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
11669 if (cpu_has_vmx_msr_bitmap())
11670 vmx_update_msr_bitmap(vcpu);
11672 if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
11673 vmcs12->vm_exit_msr_load_count))
11674 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
11678 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
11679 * and modify vmcs12 to make it see what it would expect to see there if
11680 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
11682 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
11683 u32 exit_intr_info,
11684 unsigned long exit_qualification)
11686 struct vcpu_vmx *vmx = to_vmx(vcpu);
11687 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11689 /* trying to cancel vmlaunch/vmresume is a bug */
11690 WARN_ON_ONCE(vmx->nested.nested_run_pending);
11693 * The only expected VM-instruction error is "VM entry with
11694 * invalid control field(s)." Anything else indicates a
11695 * problem with L0.
11697 WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
11698 VMXERR_ENTRY_INVALID_CONTROL_FIELD));
11700 leave_guest_mode(vcpu);
11702 if (likely(!vmx->fail)) {
11703 if (exit_reason == -1)
11704 sync_vmcs12(vcpu, vmcs12);
11705 else
11706 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
11707 exit_qualification);
11709 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
11710 vmcs12->vm_exit_msr_store_count))
11711 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
11714 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11715 vm_entry_controls_reset_shadow(vmx);
11716 vm_exit_controls_reset_shadow(vmx);
11717 vmx_segment_cache_clear(vmx);
11719 /* Update any VMCS fields that might have changed while L2 ran */
11720 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11721 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11722 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
11723 if (vmx->hv_deadline_tsc == -1)
11724 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11725 PIN_BASED_VMX_PREEMPTION_TIMER);
11726 else
11727 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11728 PIN_BASED_VMX_PREEMPTION_TIMER);
11729 if (kvm_has_tsc_control)
11730 decache_tsc_multiplier(vmx);
11732 if (vmx->nested.change_vmcs01_virtual_x2apic_mode) {
11733 vmx->nested.change_vmcs01_virtual_x2apic_mode = false;
11734 vmx_set_virtual_x2apic_mode(vcpu,
11735 vcpu->arch.apic_base & X2APIC_ENABLE);
11736 } else if (!nested_cpu_has_ept(vmcs12) &&
11737 nested_cpu_has2(vmcs12,
11738 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11739 vmx_flush_tlb_ept_only(vcpu);
11742 /* This is needed for same reason as it was needed in prepare_vmcs02 */
11743 vmx->host_rsp = 0;
11745 /* Unpin physical memory we referred to in vmcs02 */
11746 if (vmx->nested.apic_access_page) {
11747 kvm_release_page_dirty(vmx->nested.apic_access_page);
11748 vmx->nested.apic_access_page = NULL;
11750 if (vmx->nested.virtual_apic_page) {
11751 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11752 vmx->nested.virtual_apic_page = NULL;
11754 if (vmx->nested.pi_desc_page) {
11755 kunmap(vmx->nested.pi_desc_page);
11756 kvm_release_page_dirty(vmx->nested.pi_desc_page);
11757 vmx->nested.pi_desc_page = NULL;
11758 vmx->nested.pi_desc = NULL;
11762 * We are now running in L2, mmu_notifier will force to reload the
11763 * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
11765 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
11767 if (enable_shadow_vmcs && exit_reason != -1)
11768 vmx->nested.sync_shadow_vmcs = true;
11770 /* in case we halted in L2 */
11771 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11773 if (likely(!vmx->fail)) {
11775 * TODO: SDM says that with acknowledge interrupt on
11776 * exit, bit 31 of the VM-exit interrupt information
11777 * (valid interrupt) is always set to 1 on
11778 * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
11779 * need kvm_cpu_has_interrupt(). See the commit
11780 * message for details.
11782 if (nested_exit_intr_ack_set(vcpu) &&
11783 exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
11784 kvm_cpu_has_interrupt(vcpu)) {
11785 int irq = kvm_cpu_get_interrupt(vcpu);
11786 WARN_ON(irq < 0);
11787 vmcs12->vm_exit_intr_info = irq |
11788 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
11791 if (exit_reason != -1)
11792 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
11793 vmcs12->exit_qualification,
11794 vmcs12->idt_vectoring_info_field,
11795 vmcs12->vm_exit_intr_info,
11796 vmcs12->vm_exit_intr_error_code,
11797 KVM_ISA_VMX);
11799 load_vmcs12_host_state(vcpu, vmcs12);
11801 return;
11805 * After an early L2 VM-entry failure, we're now back
11806 * in L1 which thinks it just finished a VMLAUNCH or
11807 * VMRESUME instruction, so we need to set the failure
11808 * flag and the VM-instruction error field of the VMCS
11809 * accordingly.
11811 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
11813 load_vmcs12_mmu_host_state(vcpu, vmcs12);
11816 * The emulated instruction was already skipped in
11817 * nested_vmx_run, but the updated RIP was never
11818 * written back to the vmcs01.
11820 skip_emulated_instruction(vcpu);
11821 vmx->fail = 0;
11825 * Forcibly leave nested mode in order to be able to reset the VCPU later on.
11827 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
11829 if (is_guest_mode(vcpu)) {
11830 to_vmx(vcpu)->nested.nested_run_pending = 0;
11831 nested_vmx_vmexit(vcpu, -1, 0, 0);
11833 free_nested(to_vmx(vcpu));
11837 * L1's failure to enter L2 is a subset of a normal exit, as explained in
11838 * 23.7 "VM-entry failures during or after loading guest state" (this also
11839 * lists the acceptable exit-reason and exit-qualification parameters).
11840 * It should only be called before L2 actually succeeded to run, and when
11841 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
11843 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
11844 struct vmcs12 *vmcs12,
11845 u32 reason, unsigned long qualification)
11847 load_vmcs12_host_state(vcpu, vmcs12);
11848 vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
11849 vmcs12->exit_qualification = qualification;
11850 nested_vmx_succeed(vcpu);
11851 if (enable_shadow_vmcs)
11852 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
11855 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
11856 struct x86_instruction_info *info,
11857 enum x86_intercept_stage stage)
11859 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11860 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
11863 * RDPID causes #UD if disabled through secondary execution controls.
11864 * Because it is marked as EmulateOnUD, we need to intercept it here.
11866 if (info->intercept == x86_intercept_rdtscp &&
11867 !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
11868 ctxt->exception.vector = UD_VECTOR;
11869 ctxt->exception.error_code_valid = false;
11870 return X86EMUL_PROPAGATE_FAULT;
11873 /* TODO: check more intercepts... */
11874 return X86EMUL_CONTINUE;
11877 #ifdef CONFIG_X86_64
11878 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
11879 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
11880 u64 divisor, u64 *result)
11882 u64 low = a << shift, high = a >> (64 - shift);
11884 /* To avoid the overflow on divq */
11885 if (high >= divisor)
11886 return 1;
11888 /* Low hold the result, high hold rem which is discarded */
11889 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
11890 "rm" (divisor), "0" (low), "1" (high));
11891 *result = low;
11893 return 0;
11896 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
11898 struct vcpu_vmx *vmx = to_vmx(vcpu);
11899 u64 tscl = rdtsc();
11900 u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
11901 u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
11903 /* Convert to host delta tsc if tsc scaling is enabled */
11904 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
11905 u64_shl_div_u64(delta_tsc,
11906 kvm_tsc_scaling_ratio_frac_bits,
11907 vcpu->arch.tsc_scaling_ratio,
11908 &delta_tsc))
11909 return -ERANGE;
11912 * If the delta tsc can't fit in the 32 bit after the multi shift,
11913 * we can't use the preemption timer.
11914 * It's possible that it fits on later vmentries, but checking
11915 * on every vmentry is costly so we just use an hrtimer.
11917 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
11918 return -ERANGE;
11920 vmx->hv_deadline_tsc = tscl + delta_tsc;
11921 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11922 PIN_BASED_VMX_PREEMPTION_TIMER);
11924 return delta_tsc == 0;
11927 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
11929 struct vcpu_vmx *vmx = to_vmx(vcpu);
11930 vmx->hv_deadline_tsc = -1;
11931 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11932 PIN_BASED_VMX_PREEMPTION_TIMER);
11934 #endif
11936 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
11938 if (ple_gap)
11939 shrink_ple_window(vcpu);
11942 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
11943 struct kvm_memory_slot *slot)
11945 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
11946 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
11949 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
11950 struct kvm_memory_slot *slot)
11952 kvm_mmu_slot_set_dirty(kvm, slot);
11955 static void vmx_flush_log_dirty(struct kvm *kvm)
11957 kvm_flush_pml_buffers(kvm);
11960 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
11962 struct vmcs12 *vmcs12;
11963 struct vcpu_vmx *vmx = to_vmx(vcpu);
11964 gpa_t gpa;
11965 struct page *page = NULL;
11966 u64 *pml_address;
11968 if (is_guest_mode(vcpu)) {
11969 WARN_ON_ONCE(vmx->nested.pml_full);
11972 * Check if PML is enabled for the nested guest.
11973 * Whether eptp bit 6 is set is already checked
11974 * as part of A/D emulation.
11976 vmcs12 = get_vmcs12(vcpu);
11977 if (!nested_cpu_has_pml(vmcs12))
11978 return 0;
11980 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
11981 vmx->nested.pml_full = true;
11982 return 1;
11985 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
11987 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
11988 if (is_error_page(page))
11989 return 0;
11991 pml_address = kmap(page);
11992 pml_address[vmcs12->guest_pml_index--] = gpa;
11993 kunmap(page);
11994 kvm_release_page_clean(page);
11997 return 0;
12000 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
12001 struct kvm_memory_slot *memslot,
12002 gfn_t offset, unsigned long mask)
12004 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
12007 static void __pi_post_block(struct kvm_vcpu *vcpu)
12009 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
12010 struct pi_desc old, new;
12011 unsigned int dest;
12013 do {
12014 old.control = new.control = pi_desc->control;
12015 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
12016 "Wakeup handler not enabled while the VCPU is blocked\n");
12018 dest = cpu_physical_id(vcpu->cpu);
12020 if (x2apic_enabled())
12021 new.ndst = dest;
12022 else
12023 new.ndst = (dest << 8) & 0xFF00;
12025 /* set 'NV' to 'notification vector' */
12026 new.nv = POSTED_INTR_VECTOR;
12027 } while (cmpxchg64(&pi_desc->control, old.control,
12028 new.control) != old.control);
12030 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
12031 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12032 list_del(&vcpu->blocked_vcpu_list);
12033 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12034 vcpu->pre_pcpu = -1;
12039 * This routine does the following things for vCPU which is going
12040 * to be blocked if VT-d PI is enabled.
12041 * - Store the vCPU to the wakeup list, so when interrupts happen
12042 * we can find the right vCPU to wake up.
12043 * - Change the Posted-interrupt descriptor as below:
12044 * 'NDST' <-- vcpu->pre_pcpu
12045 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
12046 * - If 'ON' is set during this process, which means at least one
12047 * interrupt is posted for this vCPU, we cannot block it, in
12048 * this case, return 1, otherwise, return 0.
12051 static int pi_pre_block(struct kvm_vcpu *vcpu)
12053 unsigned int dest;
12054 struct pi_desc old, new;
12055 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
12057 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
12058 !irq_remapping_cap(IRQ_POSTING_CAP) ||
12059 !kvm_vcpu_apicv_active(vcpu))
12060 return 0;
12062 WARN_ON(irqs_disabled());
12063 local_irq_disable();
12064 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
12065 vcpu->pre_pcpu = vcpu->cpu;
12066 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12067 list_add_tail(&vcpu->blocked_vcpu_list,
12068 &per_cpu(blocked_vcpu_on_cpu,
12069 vcpu->pre_pcpu));
12070 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12073 do {
12074 old.control = new.control = pi_desc->control;
12076 WARN((pi_desc->sn == 1),
12077 "Warning: SN field of posted-interrupts "
12078 "is set before blocking\n");
12081 * Since vCPU can be preempted during this process,
12082 * vcpu->cpu could be different with pre_pcpu, we
12083 * need to set pre_pcpu as the destination of wakeup
12084 * notification event, then we can find the right vCPU
12085 * to wakeup in wakeup handler if interrupts happen
12086 * when the vCPU is in blocked state.
12088 dest = cpu_physical_id(vcpu->pre_pcpu);
12090 if (x2apic_enabled())
12091 new.ndst = dest;
12092 else
12093 new.ndst = (dest << 8) & 0xFF00;
12095 /* set 'NV' to 'wakeup vector' */
12096 new.nv = POSTED_INTR_WAKEUP_VECTOR;
12097 } while (cmpxchg64(&pi_desc->control, old.control,
12098 new.control) != old.control);
12100 /* We should not block the vCPU if an interrupt is posted for it. */
12101 if (pi_test_on(pi_desc) == 1)
12102 __pi_post_block(vcpu);
12104 local_irq_enable();
12105 return (vcpu->pre_pcpu == -1);
12108 static int vmx_pre_block(struct kvm_vcpu *vcpu)
12110 if (pi_pre_block(vcpu))
12111 return 1;
12113 if (kvm_lapic_hv_timer_in_use(vcpu))
12114 kvm_lapic_switch_to_sw_timer(vcpu);
12116 return 0;
12119 static void pi_post_block(struct kvm_vcpu *vcpu)
12121 if (vcpu->pre_pcpu == -1)
12122 return;
12124 WARN_ON(irqs_disabled());
12125 local_irq_disable();
12126 __pi_post_block(vcpu);
12127 local_irq_enable();
12130 static void vmx_post_block(struct kvm_vcpu *vcpu)
12132 if (kvm_x86_ops->set_hv_timer)
12133 kvm_lapic_switch_to_hv_timer(vcpu);
12135 pi_post_block(vcpu);
12139 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
12141 * @kvm: kvm
12142 * @host_irq: host irq of the interrupt
12143 * @guest_irq: gsi of the interrupt
12144 * @set: set or unset PI
12145 * returns 0 on success, < 0 on failure
12147 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
12148 uint32_t guest_irq, bool set)
12150 struct kvm_kernel_irq_routing_entry *e;
12151 struct kvm_irq_routing_table *irq_rt;
12152 struct kvm_lapic_irq irq;
12153 struct kvm_vcpu *vcpu;
12154 struct vcpu_data vcpu_info;
12155 int idx, ret = 0;
12157 if (!kvm_arch_has_assigned_device(kvm) ||
12158 !irq_remapping_cap(IRQ_POSTING_CAP) ||
12159 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
12160 return 0;
12162 idx = srcu_read_lock(&kvm->irq_srcu);
12163 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
12164 if (guest_irq >= irq_rt->nr_rt_entries ||
12165 hlist_empty(&irq_rt->map[guest_irq])) {
12166 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
12167 guest_irq, irq_rt->nr_rt_entries);
12168 goto out;
12171 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
12172 if (e->type != KVM_IRQ_ROUTING_MSI)
12173 continue;
12175 * VT-d PI cannot support posting multicast/broadcast
12176 * interrupts to a vCPU, we still use interrupt remapping
12177 * for these kind of interrupts.
12179 * For lowest-priority interrupts, we only support
12180 * those with single CPU as the destination, e.g. user
12181 * configures the interrupts via /proc/irq or uses
12182 * irqbalance to make the interrupts single-CPU.
12184 * We will support full lowest-priority interrupt later.
12187 kvm_set_msi_irq(kvm, e, &irq);
12188 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
12190 * Make sure the IRTE is in remapped mode if
12191 * we don't handle it in posted mode.
12193 ret = irq_set_vcpu_affinity(host_irq, NULL);
12194 if (ret < 0) {
12195 printk(KERN_INFO
12196 "failed to back to remapped mode, irq: %u\n",
12197 host_irq);
12198 goto out;
12201 continue;
12204 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
12205 vcpu_info.vector = irq.vector;
12207 trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
12208 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
12210 if (set)
12211 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
12212 else
12213 ret = irq_set_vcpu_affinity(host_irq, NULL);
12215 if (ret < 0) {
12216 printk(KERN_INFO "%s: failed to update PI IRTE\n",
12217 __func__);
12218 goto out;
12222 ret = 0;
12223 out:
12224 srcu_read_unlock(&kvm->irq_srcu, idx);
12225 return ret;
12228 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
12230 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
12231 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
12232 FEATURE_CONTROL_LMCE;
12233 else
12234 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
12235 ~FEATURE_CONTROL_LMCE;
12238 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
12240 /* we need a nested vmexit to enter SMM, postpone if run is pending */
12241 if (to_vmx(vcpu)->nested.nested_run_pending)
12242 return 0;
12243 return 1;
12246 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
12248 struct vcpu_vmx *vmx = to_vmx(vcpu);
12250 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
12251 if (vmx->nested.smm.guest_mode)
12252 nested_vmx_vmexit(vcpu, -1, 0, 0);
12254 vmx->nested.smm.vmxon = vmx->nested.vmxon;
12255 vmx->nested.vmxon = false;
12256 return 0;
12259 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
12261 struct vcpu_vmx *vmx = to_vmx(vcpu);
12262 int ret;
12264 if (vmx->nested.smm.vmxon) {
12265 vmx->nested.vmxon = true;
12266 vmx->nested.smm.vmxon = false;
12269 if (vmx->nested.smm.guest_mode) {
12270 vcpu->arch.hflags &= ~HF_SMM_MASK;
12271 ret = enter_vmx_non_root_mode(vcpu, false);
12272 vcpu->arch.hflags |= HF_SMM_MASK;
12273 if (ret)
12274 return ret;
12276 vmx->nested.smm.guest_mode = false;
12278 return 0;
12281 static int enable_smi_window(struct kvm_vcpu *vcpu)
12283 return 0;
12286 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
12287 .cpu_has_kvm_support = cpu_has_kvm_support,
12288 .disabled_by_bios = vmx_disabled_by_bios,
12289 .hardware_setup = hardware_setup,
12290 .hardware_unsetup = hardware_unsetup,
12291 .check_processor_compatibility = vmx_check_processor_compat,
12292 .hardware_enable = hardware_enable,
12293 .hardware_disable = hardware_disable,
12294 .cpu_has_accelerated_tpr = report_flexpriority,
12295 .cpu_has_high_real_mode_segbase = vmx_has_high_real_mode_segbase,
12297 .vcpu_create = vmx_create_vcpu,
12298 .vcpu_free = vmx_free_vcpu,
12299 .vcpu_reset = vmx_vcpu_reset,
12301 .prepare_guest_switch = vmx_save_host_state,
12302 .vcpu_load = vmx_vcpu_load,
12303 .vcpu_put = vmx_vcpu_put,
12305 .update_bp_intercept = update_exception_bitmap,
12306 .get_msr_feature = vmx_get_msr_feature,
12307 .get_msr = vmx_get_msr,
12308 .set_msr = vmx_set_msr,
12309 .get_segment_base = vmx_get_segment_base,
12310 .get_segment = vmx_get_segment,
12311 .set_segment = vmx_set_segment,
12312 .get_cpl = vmx_get_cpl,
12313 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
12314 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
12315 .decache_cr3 = vmx_decache_cr3,
12316 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
12317 .set_cr0 = vmx_set_cr0,
12318 .set_cr3 = vmx_set_cr3,
12319 .set_cr4 = vmx_set_cr4,
12320 .set_efer = vmx_set_efer,
12321 .get_idt = vmx_get_idt,
12322 .set_idt = vmx_set_idt,
12323 .get_gdt = vmx_get_gdt,
12324 .set_gdt = vmx_set_gdt,
12325 .get_dr6 = vmx_get_dr6,
12326 .set_dr6 = vmx_set_dr6,
12327 .set_dr7 = vmx_set_dr7,
12328 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
12329 .cache_reg = vmx_cache_reg,
12330 .get_rflags = vmx_get_rflags,
12331 .set_rflags = vmx_set_rflags,
12333 .tlb_flush = vmx_flush_tlb,
12335 .run = vmx_vcpu_run,
12336 .handle_exit = vmx_handle_exit,
12337 .skip_emulated_instruction = skip_emulated_instruction,
12338 .set_interrupt_shadow = vmx_set_interrupt_shadow,
12339 .get_interrupt_shadow = vmx_get_interrupt_shadow,
12340 .patch_hypercall = vmx_patch_hypercall,
12341 .set_irq = vmx_inject_irq,
12342 .set_nmi = vmx_inject_nmi,
12343 .queue_exception = vmx_queue_exception,
12344 .cancel_injection = vmx_cancel_injection,
12345 .interrupt_allowed = vmx_interrupt_allowed,
12346 .nmi_allowed = vmx_nmi_allowed,
12347 .get_nmi_mask = vmx_get_nmi_mask,
12348 .set_nmi_mask = vmx_set_nmi_mask,
12349 .enable_nmi_window = enable_nmi_window,
12350 .enable_irq_window = enable_irq_window,
12351 .update_cr8_intercept = update_cr8_intercept,
12352 .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
12353 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
12354 .get_enable_apicv = vmx_get_enable_apicv,
12355 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
12356 .load_eoi_exitmap = vmx_load_eoi_exitmap,
12357 .apicv_post_state_restore = vmx_apicv_post_state_restore,
12358 .hwapic_irr_update = vmx_hwapic_irr_update,
12359 .hwapic_isr_update = vmx_hwapic_isr_update,
12360 .sync_pir_to_irr = vmx_sync_pir_to_irr,
12361 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
12363 .set_tss_addr = vmx_set_tss_addr,
12364 .get_tdp_level = get_ept_level,
12365 .get_mt_mask = vmx_get_mt_mask,
12367 .get_exit_info = vmx_get_exit_info,
12369 .get_lpage_level = vmx_get_lpage_level,
12371 .cpuid_update = vmx_cpuid_update,
12373 .rdtscp_supported = vmx_rdtscp_supported,
12374 .invpcid_supported = vmx_invpcid_supported,
12376 .set_supported_cpuid = vmx_set_supported_cpuid,
12378 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
12380 .write_tsc_offset = vmx_write_tsc_offset,
12382 .set_tdp_cr3 = vmx_set_cr3,
12384 .check_intercept = vmx_check_intercept,
12385 .handle_external_intr = vmx_handle_external_intr,
12386 .mpx_supported = vmx_mpx_supported,
12387 .xsaves_supported = vmx_xsaves_supported,
12388 .umip_emulated = vmx_umip_emulated,
12390 .check_nested_events = vmx_check_nested_events,
12392 .sched_in = vmx_sched_in,
12394 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
12395 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
12396 .flush_log_dirty = vmx_flush_log_dirty,
12397 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
12398 .write_log_dirty = vmx_write_pml_buffer,
12400 .pre_block = vmx_pre_block,
12401 .post_block = vmx_post_block,
12403 .pmu_ops = &intel_pmu_ops,
12405 .update_pi_irte = vmx_update_pi_irte,
12407 #ifdef CONFIG_X86_64
12408 .set_hv_timer = vmx_set_hv_timer,
12409 .cancel_hv_timer = vmx_cancel_hv_timer,
12410 #endif
12412 .setup_mce = vmx_setup_mce,
12414 .smi_allowed = vmx_smi_allowed,
12415 .pre_enter_smm = vmx_pre_enter_smm,
12416 .pre_leave_smm = vmx_pre_leave_smm,
12417 .enable_smi_window = enable_smi_window,
12420 static int __init vmx_init(void)
12422 int r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
12423 __alignof__(struct vcpu_vmx), THIS_MODULE);
12424 if (r)
12425 return r;
12427 #ifdef CONFIG_KEXEC_CORE
12428 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
12429 crash_vmclear_local_loaded_vmcss);
12430 #endif
12432 return 0;
12435 static void __exit vmx_exit(void)
12437 #ifdef CONFIG_KEXEC_CORE
12438 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
12439 synchronize_rcu();
12440 #endif
12442 kvm_exit();
12445 module_init(vmx_init)
12446 module_exit(vmx_exit)