Linux 4.1.18
[linux/fpc-iii.git] / arch / x86 / kvm / vmx.c
blob945f9e13f1aa6e641aa32b06b5093e759bf92af0
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"
23 #include <linux/kvm_host.h>
24 #include <linux/module.h>
25 #include <linux/kernel.h>
26 #include <linux/mm.h>
27 #include <linux/highmem.h>
28 #include <linux/sched.h>
29 #include <linux/moduleparam.h>
30 #include <linux/mod_devicetable.h>
31 #include <linux/ftrace_event.h>
32 #include <linux/slab.h>
33 #include <linux/tboot.h>
34 #include <linux/hrtimer.h>
35 #include "kvm_cache_regs.h"
36 #include "x86.h"
38 #include <asm/io.h>
39 #include <asm/desc.h>
40 #include <asm/vmx.h>
41 #include <asm/virtext.h>
42 #include <asm/mce.h>
43 #include <asm/i387.h>
44 #include <asm/xcr.h>
45 #include <asm/perf_event.h>
46 #include <asm/debugreg.h>
47 #include <asm/kexec.h>
48 #include <asm/apic.h>
50 #include "trace.h"
52 #define __ex(x) __kvm_handle_fault_on_reboot(x)
53 #define __ex_clear(x, reg) \
54 ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
56 MODULE_AUTHOR("Qumranet");
57 MODULE_LICENSE("GPL");
59 static const struct x86_cpu_id vmx_cpu_id[] = {
60 X86_FEATURE_MATCH(X86_FEATURE_VMX),
63 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
65 static bool __read_mostly enable_vpid = 1;
66 module_param_named(vpid, enable_vpid, bool, 0444);
68 static bool __read_mostly flexpriority_enabled = 1;
69 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
71 static bool __read_mostly enable_ept = 1;
72 module_param_named(ept, enable_ept, bool, S_IRUGO);
74 static bool __read_mostly enable_unrestricted_guest = 1;
75 module_param_named(unrestricted_guest,
76 enable_unrestricted_guest, bool, S_IRUGO);
78 static bool __read_mostly enable_ept_ad_bits = 1;
79 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
81 static bool __read_mostly emulate_invalid_guest_state = true;
82 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
84 static bool __read_mostly vmm_exclusive = 1;
85 module_param(vmm_exclusive, bool, S_IRUGO);
87 static bool __read_mostly fasteoi = 1;
88 module_param(fasteoi, bool, S_IRUGO);
90 static bool __read_mostly enable_apicv = 1;
91 module_param(enable_apicv, bool, S_IRUGO);
93 static bool __read_mostly enable_shadow_vmcs = 1;
94 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
96 * If nested=1, nested virtualization is supported, i.e., guests may use
97 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
98 * use VMX instructions.
100 static bool __read_mostly nested = 0;
101 module_param(nested, bool, S_IRUGO);
103 static u64 __read_mostly host_xss;
105 static bool __read_mostly enable_pml = 1;
106 module_param_named(pml, enable_pml, bool, S_IRUGO);
108 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
109 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
110 #define KVM_VM_CR0_ALWAYS_ON \
111 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
112 #define KVM_CR4_GUEST_OWNED_BITS \
113 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
114 | X86_CR4_OSXMMEXCPT | X86_CR4_TSD)
116 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
117 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
119 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
121 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
124 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
125 * ple_gap: upper bound on the amount of time between two successive
126 * executions of PAUSE in a loop. Also indicate if ple enabled.
127 * According to test, this time is usually smaller than 128 cycles.
128 * ple_window: upper bound on the amount of time a guest is allowed to execute
129 * in a PAUSE loop. Tests indicate that most spinlocks are held for
130 * less than 2^12 cycles
131 * Time is measured based on a counter that runs at the same rate as the TSC,
132 * refer SDM volume 3b section 21.6.13 & 22.1.3.
134 #define KVM_VMX_DEFAULT_PLE_GAP 128
135 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
136 #define KVM_VMX_DEFAULT_PLE_WINDOW_GROW 2
137 #define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
138 #define KVM_VMX_DEFAULT_PLE_WINDOW_MAX \
139 INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
141 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
142 module_param(ple_gap, int, S_IRUGO);
144 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
145 module_param(ple_window, int, S_IRUGO);
147 /* Default doubles per-vcpu window every exit. */
148 static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
149 module_param(ple_window_grow, int, S_IRUGO);
151 /* Default resets per-vcpu window every exit to ple_window. */
152 static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
153 module_param(ple_window_shrink, int, S_IRUGO);
155 /* Default is to compute the maximum so we can never overflow. */
156 static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
157 static int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
158 module_param(ple_window_max, int, S_IRUGO);
160 extern const ulong vmx_return;
162 #define NR_AUTOLOAD_MSRS 8
163 #define VMCS02_POOL_SIZE 1
165 struct vmcs {
166 u32 revision_id;
167 u32 abort;
168 char data[0];
172 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
173 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
174 * loaded on this CPU (so we can clear them if the CPU goes down).
176 struct loaded_vmcs {
177 struct vmcs *vmcs;
178 int cpu;
179 int launched;
180 struct list_head loaded_vmcss_on_cpu_link;
183 struct shared_msr_entry {
184 unsigned index;
185 u64 data;
186 u64 mask;
190 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
191 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
192 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
193 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
194 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
195 * More than one of these structures may exist, if L1 runs multiple L2 guests.
196 * nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
197 * underlying hardware which will be used to run L2.
198 * This structure is packed to ensure that its layout is identical across
199 * machines (necessary for live migration).
200 * If there are changes in this struct, VMCS12_REVISION must be changed.
202 typedef u64 natural_width;
203 struct __packed vmcs12 {
204 /* According to the Intel spec, a VMCS region must start with the
205 * following two fields. Then follow implementation-specific data.
207 u32 revision_id;
208 u32 abort;
210 u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
211 u32 padding[7]; /* room for future expansion */
213 u64 io_bitmap_a;
214 u64 io_bitmap_b;
215 u64 msr_bitmap;
216 u64 vm_exit_msr_store_addr;
217 u64 vm_exit_msr_load_addr;
218 u64 vm_entry_msr_load_addr;
219 u64 tsc_offset;
220 u64 virtual_apic_page_addr;
221 u64 apic_access_addr;
222 u64 posted_intr_desc_addr;
223 u64 ept_pointer;
224 u64 eoi_exit_bitmap0;
225 u64 eoi_exit_bitmap1;
226 u64 eoi_exit_bitmap2;
227 u64 eoi_exit_bitmap3;
228 u64 xss_exit_bitmap;
229 u64 guest_physical_address;
230 u64 vmcs_link_pointer;
231 u64 guest_ia32_debugctl;
232 u64 guest_ia32_pat;
233 u64 guest_ia32_efer;
234 u64 guest_ia32_perf_global_ctrl;
235 u64 guest_pdptr0;
236 u64 guest_pdptr1;
237 u64 guest_pdptr2;
238 u64 guest_pdptr3;
239 u64 guest_bndcfgs;
240 u64 host_ia32_pat;
241 u64 host_ia32_efer;
242 u64 host_ia32_perf_global_ctrl;
243 u64 padding64[8]; /* room for future expansion */
245 * To allow migration of L1 (complete with its L2 guests) between
246 * machines of different natural widths (32 or 64 bit), we cannot have
247 * unsigned long fields with no explict size. We use u64 (aliased
248 * natural_width) instead. Luckily, x86 is little-endian.
250 natural_width cr0_guest_host_mask;
251 natural_width cr4_guest_host_mask;
252 natural_width cr0_read_shadow;
253 natural_width cr4_read_shadow;
254 natural_width cr3_target_value0;
255 natural_width cr3_target_value1;
256 natural_width cr3_target_value2;
257 natural_width cr3_target_value3;
258 natural_width exit_qualification;
259 natural_width guest_linear_address;
260 natural_width guest_cr0;
261 natural_width guest_cr3;
262 natural_width guest_cr4;
263 natural_width guest_es_base;
264 natural_width guest_cs_base;
265 natural_width guest_ss_base;
266 natural_width guest_ds_base;
267 natural_width guest_fs_base;
268 natural_width guest_gs_base;
269 natural_width guest_ldtr_base;
270 natural_width guest_tr_base;
271 natural_width guest_gdtr_base;
272 natural_width guest_idtr_base;
273 natural_width guest_dr7;
274 natural_width guest_rsp;
275 natural_width guest_rip;
276 natural_width guest_rflags;
277 natural_width guest_pending_dbg_exceptions;
278 natural_width guest_sysenter_esp;
279 natural_width guest_sysenter_eip;
280 natural_width host_cr0;
281 natural_width host_cr3;
282 natural_width host_cr4;
283 natural_width host_fs_base;
284 natural_width host_gs_base;
285 natural_width host_tr_base;
286 natural_width host_gdtr_base;
287 natural_width host_idtr_base;
288 natural_width host_ia32_sysenter_esp;
289 natural_width host_ia32_sysenter_eip;
290 natural_width host_rsp;
291 natural_width host_rip;
292 natural_width paddingl[8]; /* room for future expansion */
293 u32 pin_based_vm_exec_control;
294 u32 cpu_based_vm_exec_control;
295 u32 exception_bitmap;
296 u32 page_fault_error_code_mask;
297 u32 page_fault_error_code_match;
298 u32 cr3_target_count;
299 u32 vm_exit_controls;
300 u32 vm_exit_msr_store_count;
301 u32 vm_exit_msr_load_count;
302 u32 vm_entry_controls;
303 u32 vm_entry_msr_load_count;
304 u32 vm_entry_intr_info_field;
305 u32 vm_entry_exception_error_code;
306 u32 vm_entry_instruction_len;
307 u32 tpr_threshold;
308 u32 secondary_vm_exec_control;
309 u32 vm_instruction_error;
310 u32 vm_exit_reason;
311 u32 vm_exit_intr_info;
312 u32 vm_exit_intr_error_code;
313 u32 idt_vectoring_info_field;
314 u32 idt_vectoring_error_code;
315 u32 vm_exit_instruction_len;
316 u32 vmx_instruction_info;
317 u32 guest_es_limit;
318 u32 guest_cs_limit;
319 u32 guest_ss_limit;
320 u32 guest_ds_limit;
321 u32 guest_fs_limit;
322 u32 guest_gs_limit;
323 u32 guest_ldtr_limit;
324 u32 guest_tr_limit;
325 u32 guest_gdtr_limit;
326 u32 guest_idtr_limit;
327 u32 guest_es_ar_bytes;
328 u32 guest_cs_ar_bytes;
329 u32 guest_ss_ar_bytes;
330 u32 guest_ds_ar_bytes;
331 u32 guest_fs_ar_bytes;
332 u32 guest_gs_ar_bytes;
333 u32 guest_ldtr_ar_bytes;
334 u32 guest_tr_ar_bytes;
335 u32 guest_interruptibility_info;
336 u32 guest_activity_state;
337 u32 guest_sysenter_cs;
338 u32 host_ia32_sysenter_cs;
339 u32 vmx_preemption_timer_value;
340 u32 padding32[7]; /* room for future expansion */
341 u16 virtual_processor_id;
342 u16 posted_intr_nv;
343 u16 guest_es_selector;
344 u16 guest_cs_selector;
345 u16 guest_ss_selector;
346 u16 guest_ds_selector;
347 u16 guest_fs_selector;
348 u16 guest_gs_selector;
349 u16 guest_ldtr_selector;
350 u16 guest_tr_selector;
351 u16 guest_intr_status;
352 u16 host_es_selector;
353 u16 host_cs_selector;
354 u16 host_ss_selector;
355 u16 host_ds_selector;
356 u16 host_fs_selector;
357 u16 host_gs_selector;
358 u16 host_tr_selector;
362 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
363 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
364 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
366 #define VMCS12_REVISION 0x11e57ed0
369 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
370 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
371 * current implementation, 4K are reserved to avoid future complications.
373 #define VMCS12_SIZE 0x1000
375 /* Used to remember the last vmcs02 used for some recently used vmcs12s */
376 struct vmcs02_list {
377 struct list_head list;
378 gpa_t vmptr;
379 struct loaded_vmcs vmcs02;
383 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
384 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
386 struct nested_vmx {
387 /* Has the level1 guest done vmxon? */
388 bool vmxon;
389 gpa_t vmxon_ptr;
391 /* The guest-physical address of the current VMCS L1 keeps for L2 */
392 gpa_t current_vmptr;
393 /* The host-usable pointer to the above */
394 struct page *current_vmcs12_page;
395 struct vmcs12 *current_vmcs12;
396 struct vmcs *current_shadow_vmcs;
398 * Indicates if the shadow vmcs must be updated with the
399 * data hold by vmcs12
401 bool sync_shadow_vmcs;
403 /* vmcs02_list cache of VMCSs recently used to run L2 guests */
404 struct list_head vmcs02_pool;
405 int vmcs02_num;
406 u64 vmcs01_tsc_offset;
407 /* L2 must run next, and mustn't decide to exit to L1. */
408 bool nested_run_pending;
410 * Guest pages referred to in vmcs02 with host-physical pointers, so
411 * we must keep them pinned while L2 runs.
413 struct page *apic_access_page;
414 struct page *virtual_apic_page;
415 struct page *pi_desc_page;
416 struct pi_desc *pi_desc;
417 bool pi_pending;
418 u16 posted_intr_nv;
419 u64 msr_ia32_feature_control;
421 struct hrtimer preemption_timer;
422 bool preemption_timer_expired;
424 /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
425 u64 vmcs01_debugctl;
427 u32 nested_vmx_procbased_ctls_low;
428 u32 nested_vmx_procbased_ctls_high;
429 u32 nested_vmx_true_procbased_ctls_low;
430 u32 nested_vmx_secondary_ctls_low;
431 u32 nested_vmx_secondary_ctls_high;
432 u32 nested_vmx_pinbased_ctls_low;
433 u32 nested_vmx_pinbased_ctls_high;
434 u32 nested_vmx_exit_ctls_low;
435 u32 nested_vmx_exit_ctls_high;
436 u32 nested_vmx_true_exit_ctls_low;
437 u32 nested_vmx_entry_ctls_low;
438 u32 nested_vmx_entry_ctls_high;
439 u32 nested_vmx_true_entry_ctls_low;
440 u32 nested_vmx_misc_low;
441 u32 nested_vmx_misc_high;
442 u32 nested_vmx_ept_caps;
445 #define POSTED_INTR_ON 0
446 /* Posted-Interrupt Descriptor */
447 struct pi_desc {
448 u32 pir[8]; /* Posted interrupt requested */
449 u32 control; /* bit 0 of control is outstanding notification bit */
450 u32 rsvd[7];
451 } __aligned(64);
453 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
455 return test_and_set_bit(POSTED_INTR_ON,
456 (unsigned long *)&pi_desc->control);
459 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
461 return test_and_clear_bit(POSTED_INTR_ON,
462 (unsigned long *)&pi_desc->control);
465 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
467 return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
470 struct vcpu_vmx {
471 struct kvm_vcpu vcpu;
472 unsigned long host_rsp;
473 u8 fail;
474 bool nmi_known_unmasked;
475 u32 exit_intr_info;
476 u32 idt_vectoring_info;
477 ulong rflags;
478 struct shared_msr_entry *guest_msrs;
479 int nmsrs;
480 int save_nmsrs;
481 unsigned long host_idt_base;
482 #ifdef CONFIG_X86_64
483 u64 msr_host_kernel_gs_base;
484 u64 msr_guest_kernel_gs_base;
485 #endif
486 u32 vm_entry_controls_shadow;
487 u32 vm_exit_controls_shadow;
489 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
490 * non-nested (L1) guest, it always points to vmcs01. For a nested
491 * guest (L2), it points to a different VMCS.
493 struct loaded_vmcs vmcs01;
494 struct loaded_vmcs *loaded_vmcs;
495 bool __launched; /* temporary, used in vmx_vcpu_run */
496 struct msr_autoload {
497 unsigned nr;
498 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
499 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
500 } msr_autoload;
501 struct {
502 int loaded;
503 u16 fs_sel, gs_sel, ldt_sel;
504 #ifdef CONFIG_X86_64
505 u16 ds_sel, es_sel;
506 #endif
507 int gs_ldt_reload_needed;
508 int fs_reload_needed;
509 u64 msr_host_bndcfgs;
510 unsigned long vmcs_host_cr4; /* May not match real cr4 */
511 } host_state;
512 struct {
513 int vm86_active;
514 ulong save_rflags;
515 struct kvm_segment segs[8];
516 } rmode;
517 struct {
518 u32 bitmask; /* 4 bits per segment (1 bit per field) */
519 struct kvm_save_segment {
520 u16 selector;
521 unsigned long base;
522 u32 limit;
523 u32 ar;
524 } seg[8];
525 } segment_cache;
526 int vpid;
527 bool emulation_required;
529 /* Support for vnmi-less CPUs */
530 int soft_vnmi_blocked;
531 ktime_t entry_time;
532 s64 vnmi_blocked_time;
533 u32 exit_reason;
535 bool rdtscp_enabled;
537 /* Posted interrupt descriptor */
538 struct pi_desc pi_desc;
540 /* Support for a guest hypervisor (nested VMX) */
541 struct nested_vmx nested;
543 /* Dynamic PLE window. */
544 int ple_window;
545 bool ple_window_dirty;
547 /* Support for PML */
548 #define PML_ENTITY_NUM 512
549 struct page *pml_pg;
552 enum segment_cache_field {
553 SEG_FIELD_SEL = 0,
554 SEG_FIELD_BASE = 1,
555 SEG_FIELD_LIMIT = 2,
556 SEG_FIELD_AR = 3,
558 SEG_FIELD_NR = 4
561 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
563 return container_of(vcpu, struct vcpu_vmx, vcpu);
566 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
567 #define FIELD(number, name) [number] = VMCS12_OFFSET(name)
568 #define FIELD64(number, name) [number] = VMCS12_OFFSET(name), \
569 [number##_HIGH] = VMCS12_OFFSET(name)+4
572 static unsigned long shadow_read_only_fields[] = {
574 * We do NOT shadow fields that are modified when L0
575 * traps and emulates any vmx instruction (e.g. VMPTRLD,
576 * VMXON...) executed by L1.
577 * For example, VM_INSTRUCTION_ERROR is read
578 * by L1 if a vmx instruction fails (part of the error path).
579 * Note the code assumes this logic. If for some reason
580 * we start shadowing these fields then we need to
581 * force a shadow sync when L0 emulates vmx instructions
582 * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
583 * by nested_vmx_failValid)
585 VM_EXIT_REASON,
586 VM_EXIT_INTR_INFO,
587 VM_EXIT_INSTRUCTION_LEN,
588 IDT_VECTORING_INFO_FIELD,
589 IDT_VECTORING_ERROR_CODE,
590 VM_EXIT_INTR_ERROR_CODE,
591 EXIT_QUALIFICATION,
592 GUEST_LINEAR_ADDRESS,
593 GUEST_PHYSICAL_ADDRESS
595 static int max_shadow_read_only_fields =
596 ARRAY_SIZE(shadow_read_only_fields);
598 static unsigned long shadow_read_write_fields[] = {
599 TPR_THRESHOLD,
600 GUEST_RIP,
601 GUEST_RSP,
602 GUEST_CR0,
603 GUEST_CR3,
604 GUEST_CR4,
605 GUEST_INTERRUPTIBILITY_INFO,
606 GUEST_RFLAGS,
607 GUEST_CS_SELECTOR,
608 GUEST_CS_AR_BYTES,
609 GUEST_CS_LIMIT,
610 GUEST_CS_BASE,
611 GUEST_ES_BASE,
612 GUEST_BNDCFGS,
613 CR0_GUEST_HOST_MASK,
614 CR0_READ_SHADOW,
615 CR4_READ_SHADOW,
616 TSC_OFFSET,
617 EXCEPTION_BITMAP,
618 CPU_BASED_VM_EXEC_CONTROL,
619 VM_ENTRY_EXCEPTION_ERROR_CODE,
620 VM_ENTRY_INTR_INFO_FIELD,
621 VM_ENTRY_INSTRUCTION_LEN,
622 VM_ENTRY_EXCEPTION_ERROR_CODE,
623 HOST_FS_BASE,
624 HOST_GS_BASE,
625 HOST_FS_SELECTOR,
626 HOST_GS_SELECTOR
628 static int max_shadow_read_write_fields =
629 ARRAY_SIZE(shadow_read_write_fields);
631 static const unsigned short vmcs_field_to_offset_table[] = {
632 FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
633 FIELD(POSTED_INTR_NV, posted_intr_nv),
634 FIELD(GUEST_ES_SELECTOR, guest_es_selector),
635 FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
636 FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
637 FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
638 FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
639 FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
640 FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
641 FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
642 FIELD(GUEST_INTR_STATUS, guest_intr_status),
643 FIELD(HOST_ES_SELECTOR, host_es_selector),
644 FIELD(HOST_CS_SELECTOR, host_cs_selector),
645 FIELD(HOST_SS_SELECTOR, host_ss_selector),
646 FIELD(HOST_DS_SELECTOR, host_ds_selector),
647 FIELD(HOST_FS_SELECTOR, host_fs_selector),
648 FIELD(HOST_GS_SELECTOR, host_gs_selector),
649 FIELD(HOST_TR_SELECTOR, host_tr_selector),
650 FIELD64(IO_BITMAP_A, io_bitmap_a),
651 FIELD64(IO_BITMAP_B, io_bitmap_b),
652 FIELD64(MSR_BITMAP, msr_bitmap),
653 FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
654 FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
655 FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
656 FIELD64(TSC_OFFSET, tsc_offset),
657 FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
658 FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
659 FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
660 FIELD64(EPT_POINTER, ept_pointer),
661 FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
662 FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
663 FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
664 FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
665 FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
666 FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
667 FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
668 FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
669 FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
670 FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
671 FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
672 FIELD64(GUEST_PDPTR0, guest_pdptr0),
673 FIELD64(GUEST_PDPTR1, guest_pdptr1),
674 FIELD64(GUEST_PDPTR2, guest_pdptr2),
675 FIELD64(GUEST_PDPTR3, guest_pdptr3),
676 FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
677 FIELD64(HOST_IA32_PAT, host_ia32_pat),
678 FIELD64(HOST_IA32_EFER, host_ia32_efer),
679 FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
680 FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
681 FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
682 FIELD(EXCEPTION_BITMAP, exception_bitmap),
683 FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
684 FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
685 FIELD(CR3_TARGET_COUNT, cr3_target_count),
686 FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
687 FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
688 FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
689 FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
690 FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
691 FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
692 FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
693 FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
694 FIELD(TPR_THRESHOLD, tpr_threshold),
695 FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
696 FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
697 FIELD(VM_EXIT_REASON, vm_exit_reason),
698 FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
699 FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
700 FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
701 FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
702 FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
703 FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
704 FIELD(GUEST_ES_LIMIT, guest_es_limit),
705 FIELD(GUEST_CS_LIMIT, guest_cs_limit),
706 FIELD(GUEST_SS_LIMIT, guest_ss_limit),
707 FIELD(GUEST_DS_LIMIT, guest_ds_limit),
708 FIELD(GUEST_FS_LIMIT, guest_fs_limit),
709 FIELD(GUEST_GS_LIMIT, guest_gs_limit),
710 FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
711 FIELD(GUEST_TR_LIMIT, guest_tr_limit),
712 FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
713 FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
714 FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
715 FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
716 FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
717 FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
718 FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
719 FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
720 FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
721 FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
722 FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
723 FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
724 FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
725 FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
726 FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
727 FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
728 FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
729 FIELD(CR0_READ_SHADOW, cr0_read_shadow),
730 FIELD(CR4_READ_SHADOW, cr4_read_shadow),
731 FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
732 FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
733 FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
734 FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
735 FIELD(EXIT_QUALIFICATION, exit_qualification),
736 FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
737 FIELD(GUEST_CR0, guest_cr0),
738 FIELD(GUEST_CR3, guest_cr3),
739 FIELD(GUEST_CR4, guest_cr4),
740 FIELD(GUEST_ES_BASE, guest_es_base),
741 FIELD(GUEST_CS_BASE, guest_cs_base),
742 FIELD(GUEST_SS_BASE, guest_ss_base),
743 FIELD(GUEST_DS_BASE, guest_ds_base),
744 FIELD(GUEST_FS_BASE, guest_fs_base),
745 FIELD(GUEST_GS_BASE, guest_gs_base),
746 FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
747 FIELD(GUEST_TR_BASE, guest_tr_base),
748 FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
749 FIELD(GUEST_IDTR_BASE, guest_idtr_base),
750 FIELD(GUEST_DR7, guest_dr7),
751 FIELD(GUEST_RSP, guest_rsp),
752 FIELD(GUEST_RIP, guest_rip),
753 FIELD(GUEST_RFLAGS, guest_rflags),
754 FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
755 FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
756 FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
757 FIELD(HOST_CR0, host_cr0),
758 FIELD(HOST_CR3, host_cr3),
759 FIELD(HOST_CR4, host_cr4),
760 FIELD(HOST_FS_BASE, host_fs_base),
761 FIELD(HOST_GS_BASE, host_gs_base),
762 FIELD(HOST_TR_BASE, host_tr_base),
763 FIELD(HOST_GDTR_BASE, host_gdtr_base),
764 FIELD(HOST_IDTR_BASE, host_idtr_base),
765 FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
766 FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
767 FIELD(HOST_RSP, host_rsp),
768 FIELD(HOST_RIP, host_rip),
771 static inline short vmcs_field_to_offset(unsigned long field)
773 BUILD_BUG_ON(ARRAY_SIZE(vmcs_field_to_offset_table) > SHRT_MAX);
775 if (field >= ARRAY_SIZE(vmcs_field_to_offset_table) ||
776 vmcs_field_to_offset_table[field] == 0)
777 return -ENOENT;
779 return vmcs_field_to_offset_table[field];
782 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
784 return to_vmx(vcpu)->nested.current_vmcs12;
787 static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
789 struct page *page = gfn_to_page(vcpu->kvm, addr >> PAGE_SHIFT);
790 if (is_error_page(page))
791 return NULL;
793 return page;
796 static void nested_release_page(struct page *page)
798 kvm_release_page_dirty(page);
801 static void nested_release_page_clean(struct page *page)
803 kvm_release_page_clean(page);
806 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
807 static u64 construct_eptp(unsigned long root_hpa);
808 static void kvm_cpu_vmxon(u64 addr);
809 static void kvm_cpu_vmxoff(void);
810 static bool vmx_mpx_supported(void);
811 static bool vmx_xsaves_supported(void);
812 static int vmx_vm_has_apicv(struct kvm *kvm);
813 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
814 static void vmx_set_segment(struct kvm_vcpu *vcpu,
815 struct kvm_segment *var, int seg);
816 static void vmx_get_segment(struct kvm_vcpu *vcpu,
817 struct kvm_segment *var, int seg);
818 static bool guest_state_valid(struct kvm_vcpu *vcpu);
819 static u32 vmx_segment_access_rights(struct kvm_segment *var);
820 static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu);
821 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
822 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
823 static int alloc_identity_pagetable(struct kvm *kvm);
825 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
826 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
828 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
829 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
831 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
832 static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
834 static unsigned long *vmx_io_bitmap_a;
835 static unsigned long *vmx_io_bitmap_b;
836 static unsigned long *vmx_msr_bitmap_legacy;
837 static unsigned long *vmx_msr_bitmap_longmode;
838 static unsigned long *vmx_msr_bitmap_legacy_x2apic;
839 static unsigned long *vmx_msr_bitmap_longmode_x2apic;
840 static unsigned long *vmx_msr_bitmap_nested;
841 static unsigned long *vmx_vmread_bitmap;
842 static unsigned long *vmx_vmwrite_bitmap;
844 static bool cpu_has_load_ia32_efer;
845 static bool cpu_has_load_perf_global_ctrl;
847 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
848 static DEFINE_SPINLOCK(vmx_vpid_lock);
850 static struct vmcs_config {
851 int size;
852 int order;
853 u32 revision_id;
854 u32 pin_based_exec_ctrl;
855 u32 cpu_based_exec_ctrl;
856 u32 cpu_based_2nd_exec_ctrl;
857 u32 vmexit_ctrl;
858 u32 vmentry_ctrl;
859 } vmcs_config;
861 static struct vmx_capability {
862 u32 ept;
863 u32 vpid;
864 } vmx_capability;
866 #define VMX_SEGMENT_FIELD(seg) \
867 [VCPU_SREG_##seg] = { \
868 .selector = GUEST_##seg##_SELECTOR, \
869 .base = GUEST_##seg##_BASE, \
870 .limit = GUEST_##seg##_LIMIT, \
871 .ar_bytes = GUEST_##seg##_AR_BYTES, \
874 static const struct kvm_vmx_segment_field {
875 unsigned selector;
876 unsigned base;
877 unsigned limit;
878 unsigned ar_bytes;
879 } kvm_vmx_segment_fields[] = {
880 VMX_SEGMENT_FIELD(CS),
881 VMX_SEGMENT_FIELD(DS),
882 VMX_SEGMENT_FIELD(ES),
883 VMX_SEGMENT_FIELD(FS),
884 VMX_SEGMENT_FIELD(GS),
885 VMX_SEGMENT_FIELD(SS),
886 VMX_SEGMENT_FIELD(TR),
887 VMX_SEGMENT_FIELD(LDTR),
890 static u64 host_efer;
892 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
895 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
896 * away by decrementing the array size.
898 static const u32 vmx_msr_index[] = {
899 #ifdef CONFIG_X86_64
900 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
901 #endif
902 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
905 static inline bool is_page_fault(u32 intr_info)
907 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
908 INTR_INFO_VALID_MASK)) ==
909 (INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
912 static inline bool is_no_device(u32 intr_info)
914 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
915 INTR_INFO_VALID_MASK)) ==
916 (INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
919 static inline bool is_invalid_opcode(u32 intr_info)
921 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
922 INTR_INFO_VALID_MASK)) ==
923 (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK);
926 static inline bool is_external_interrupt(u32 intr_info)
928 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
929 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
932 static inline bool is_machine_check(u32 intr_info)
934 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
935 INTR_INFO_VALID_MASK)) ==
936 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
939 static inline bool cpu_has_vmx_msr_bitmap(void)
941 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
944 static inline bool cpu_has_vmx_tpr_shadow(void)
946 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
949 static inline bool vm_need_tpr_shadow(struct kvm *kvm)
951 return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm));
954 static inline bool cpu_has_secondary_exec_ctrls(void)
956 return vmcs_config.cpu_based_exec_ctrl &
957 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
960 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
962 return vmcs_config.cpu_based_2nd_exec_ctrl &
963 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
966 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
968 return vmcs_config.cpu_based_2nd_exec_ctrl &
969 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
972 static inline bool cpu_has_vmx_apic_register_virt(void)
974 return vmcs_config.cpu_based_2nd_exec_ctrl &
975 SECONDARY_EXEC_APIC_REGISTER_VIRT;
978 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
980 return vmcs_config.cpu_based_2nd_exec_ctrl &
981 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
984 static inline bool cpu_has_vmx_posted_intr(void)
986 return vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
989 static inline bool cpu_has_vmx_apicv(void)
991 return cpu_has_vmx_apic_register_virt() &&
992 cpu_has_vmx_virtual_intr_delivery() &&
993 cpu_has_vmx_posted_intr();
996 static inline bool cpu_has_vmx_flexpriority(void)
998 return cpu_has_vmx_tpr_shadow() &&
999 cpu_has_vmx_virtualize_apic_accesses();
1002 static inline bool cpu_has_vmx_ept_execute_only(void)
1004 return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1007 static inline bool cpu_has_vmx_ept_2m_page(void)
1009 return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1012 static inline bool cpu_has_vmx_ept_1g_page(void)
1014 return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1017 static inline bool cpu_has_vmx_ept_4levels(void)
1019 return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1022 static inline bool cpu_has_vmx_ept_ad_bits(void)
1024 return vmx_capability.ept & VMX_EPT_AD_BIT;
1027 static inline bool cpu_has_vmx_invept_context(void)
1029 return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1032 static inline bool cpu_has_vmx_invept_global(void)
1034 return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1037 static inline bool cpu_has_vmx_invvpid_single(void)
1039 return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1042 static inline bool cpu_has_vmx_invvpid_global(void)
1044 return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1047 static inline bool cpu_has_vmx_ept(void)
1049 return vmcs_config.cpu_based_2nd_exec_ctrl &
1050 SECONDARY_EXEC_ENABLE_EPT;
1053 static inline bool cpu_has_vmx_unrestricted_guest(void)
1055 return vmcs_config.cpu_based_2nd_exec_ctrl &
1056 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1059 static inline bool cpu_has_vmx_ple(void)
1061 return vmcs_config.cpu_based_2nd_exec_ctrl &
1062 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1065 static inline bool vm_need_virtualize_apic_accesses(struct kvm *kvm)
1067 return flexpriority_enabled && irqchip_in_kernel(kvm);
1070 static inline bool cpu_has_vmx_vpid(void)
1072 return vmcs_config.cpu_based_2nd_exec_ctrl &
1073 SECONDARY_EXEC_ENABLE_VPID;
1076 static inline bool cpu_has_vmx_rdtscp(void)
1078 return vmcs_config.cpu_based_2nd_exec_ctrl &
1079 SECONDARY_EXEC_RDTSCP;
1082 static inline bool cpu_has_vmx_invpcid(void)
1084 return vmcs_config.cpu_based_2nd_exec_ctrl &
1085 SECONDARY_EXEC_ENABLE_INVPCID;
1088 static inline bool cpu_has_virtual_nmis(void)
1090 return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1093 static inline bool cpu_has_vmx_wbinvd_exit(void)
1095 return vmcs_config.cpu_based_2nd_exec_ctrl &
1096 SECONDARY_EXEC_WBINVD_EXITING;
1099 static inline bool cpu_has_vmx_shadow_vmcs(void)
1101 u64 vmx_msr;
1102 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1103 /* check if the cpu supports writing r/o exit information fields */
1104 if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1105 return false;
1107 return vmcs_config.cpu_based_2nd_exec_ctrl &
1108 SECONDARY_EXEC_SHADOW_VMCS;
1111 static inline bool cpu_has_vmx_pml(void)
1113 return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1116 static inline bool report_flexpriority(void)
1118 return flexpriority_enabled;
1121 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1123 return vmcs12->cpu_based_vm_exec_control & bit;
1126 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1128 return (vmcs12->cpu_based_vm_exec_control &
1129 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1130 (vmcs12->secondary_vm_exec_control & bit);
1133 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1135 return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1138 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1140 return vmcs12->pin_based_vm_exec_control &
1141 PIN_BASED_VMX_PREEMPTION_TIMER;
1144 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1146 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1149 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1151 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES) &&
1152 vmx_xsaves_supported();
1155 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1157 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1160 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1162 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1165 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1167 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1170 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1172 return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1175 static inline bool is_exception(u32 intr_info)
1177 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1178 == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
1181 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1182 u32 exit_intr_info,
1183 unsigned long exit_qualification);
1184 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1185 struct vmcs12 *vmcs12,
1186 u32 reason, unsigned long qualification);
1188 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1190 int i;
1192 for (i = 0; i < vmx->nmsrs; ++i)
1193 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1194 return i;
1195 return -1;
1198 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1200 struct {
1201 u64 vpid : 16;
1202 u64 rsvd : 48;
1203 u64 gva;
1204 } operand = { vpid, 0, gva };
1206 asm volatile (__ex(ASM_VMX_INVVPID)
1207 /* CF==1 or ZF==1 --> rc = -1 */
1208 "; ja 1f ; ud2 ; 1:"
1209 : : "a"(&operand), "c"(ext) : "cc", "memory");
1212 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1214 struct {
1215 u64 eptp, gpa;
1216 } operand = {eptp, gpa};
1218 asm volatile (__ex(ASM_VMX_INVEPT)
1219 /* CF==1 or ZF==1 --> rc = -1 */
1220 "; ja 1f ; ud2 ; 1:\n"
1221 : : "a" (&operand), "c" (ext) : "cc", "memory");
1224 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1226 int i;
1228 i = __find_msr_index(vmx, msr);
1229 if (i >= 0)
1230 return &vmx->guest_msrs[i];
1231 return NULL;
1234 static void vmcs_clear(struct vmcs *vmcs)
1236 u64 phys_addr = __pa(vmcs);
1237 u8 error;
1239 asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1240 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1241 : "cc", "memory");
1242 if (error)
1243 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1244 vmcs, phys_addr);
1247 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1249 vmcs_clear(loaded_vmcs->vmcs);
1250 loaded_vmcs->cpu = -1;
1251 loaded_vmcs->launched = 0;
1254 static void vmcs_load(struct vmcs *vmcs)
1256 u64 phys_addr = __pa(vmcs);
1257 u8 error;
1259 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1260 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1261 : "cc", "memory");
1262 if (error)
1263 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1264 vmcs, phys_addr);
1267 #ifdef CONFIG_KEXEC
1269 * This bitmap is used to indicate whether the vmclear
1270 * operation is enabled on all cpus. All disabled by
1271 * default.
1273 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1275 static inline void crash_enable_local_vmclear(int cpu)
1277 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1280 static inline void crash_disable_local_vmclear(int cpu)
1282 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1285 static inline int crash_local_vmclear_enabled(int cpu)
1287 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1290 static void crash_vmclear_local_loaded_vmcss(void)
1292 int cpu = raw_smp_processor_id();
1293 struct loaded_vmcs *v;
1295 if (!crash_local_vmclear_enabled(cpu))
1296 return;
1298 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1299 loaded_vmcss_on_cpu_link)
1300 vmcs_clear(v->vmcs);
1302 #else
1303 static inline void crash_enable_local_vmclear(int cpu) { }
1304 static inline void crash_disable_local_vmclear(int cpu) { }
1305 #endif /* CONFIG_KEXEC */
1307 static void __loaded_vmcs_clear(void *arg)
1309 struct loaded_vmcs *loaded_vmcs = arg;
1310 int cpu = raw_smp_processor_id();
1312 if (loaded_vmcs->cpu != cpu)
1313 return; /* vcpu migration can race with cpu offline */
1314 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1315 per_cpu(current_vmcs, cpu) = NULL;
1316 crash_disable_local_vmclear(cpu);
1317 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1320 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1321 * is before setting loaded_vmcs->vcpu to -1 which is done in
1322 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1323 * then adds the vmcs into percpu list before it is deleted.
1325 smp_wmb();
1327 loaded_vmcs_init(loaded_vmcs);
1328 crash_enable_local_vmclear(cpu);
1331 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1333 int cpu = loaded_vmcs->cpu;
1335 if (cpu != -1)
1336 smp_call_function_single(cpu,
1337 __loaded_vmcs_clear, loaded_vmcs, 1);
1340 static inline void vpid_sync_vcpu_single(struct vcpu_vmx *vmx)
1342 if (vmx->vpid == 0)
1343 return;
1345 if (cpu_has_vmx_invvpid_single())
1346 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0);
1349 static inline void vpid_sync_vcpu_global(void)
1351 if (cpu_has_vmx_invvpid_global())
1352 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1355 static inline void vpid_sync_context(struct vcpu_vmx *vmx)
1357 if (cpu_has_vmx_invvpid_single())
1358 vpid_sync_vcpu_single(vmx);
1359 else
1360 vpid_sync_vcpu_global();
1363 static inline void ept_sync_global(void)
1365 if (cpu_has_vmx_invept_global())
1366 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1369 static inline void ept_sync_context(u64 eptp)
1371 if (enable_ept) {
1372 if (cpu_has_vmx_invept_context())
1373 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1374 else
1375 ept_sync_global();
1379 static __always_inline unsigned long vmcs_readl(unsigned long field)
1381 unsigned long value;
1383 asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1384 : "=a"(value) : "d"(field) : "cc");
1385 return value;
1388 static __always_inline u16 vmcs_read16(unsigned long field)
1390 return vmcs_readl(field);
1393 static __always_inline u32 vmcs_read32(unsigned long field)
1395 return vmcs_readl(field);
1398 static __always_inline u64 vmcs_read64(unsigned long field)
1400 #ifdef CONFIG_X86_64
1401 return vmcs_readl(field);
1402 #else
1403 return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
1404 #endif
1407 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1409 printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1410 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1411 dump_stack();
1414 static void vmcs_writel(unsigned long field, unsigned long value)
1416 u8 error;
1418 asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1419 : "=q"(error) : "a"(value), "d"(field) : "cc");
1420 if (unlikely(error))
1421 vmwrite_error(field, value);
1424 static void vmcs_write16(unsigned long field, u16 value)
1426 vmcs_writel(field, value);
1429 static void vmcs_write32(unsigned long field, u32 value)
1431 vmcs_writel(field, value);
1434 static void vmcs_write64(unsigned long field, u64 value)
1436 vmcs_writel(field, value);
1437 #ifndef CONFIG_X86_64
1438 asm volatile ("");
1439 vmcs_writel(field+1, value >> 32);
1440 #endif
1443 static void vmcs_clear_bits(unsigned long field, u32 mask)
1445 vmcs_writel(field, vmcs_readl(field) & ~mask);
1448 static void vmcs_set_bits(unsigned long field, u32 mask)
1450 vmcs_writel(field, vmcs_readl(field) | mask);
1453 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1455 vmcs_write32(VM_ENTRY_CONTROLS, val);
1456 vmx->vm_entry_controls_shadow = val;
1459 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1461 if (vmx->vm_entry_controls_shadow != val)
1462 vm_entry_controls_init(vmx, val);
1465 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1467 return vmx->vm_entry_controls_shadow;
1471 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1473 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1476 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1478 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1481 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1483 vmcs_write32(VM_EXIT_CONTROLS, val);
1484 vmx->vm_exit_controls_shadow = val;
1487 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1489 if (vmx->vm_exit_controls_shadow != val)
1490 vm_exit_controls_init(vmx, val);
1493 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1495 return vmx->vm_exit_controls_shadow;
1499 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1501 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1504 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1506 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1509 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1511 vmx->segment_cache.bitmask = 0;
1514 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1515 unsigned field)
1517 bool ret;
1518 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1520 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1521 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1522 vmx->segment_cache.bitmask = 0;
1524 ret = vmx->segment_cache.bitmask & mask;
1525 vmx->segment_cache.bitmask |= mask;
1526 return ret;
1529 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1531 u16 *p = &vmx->segment_cache.seg[seg].selector;
1533 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1534 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1535 return *p;
1538 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1540 ulong *p = &vmx->segment_cache.seg[seg].base;
1542 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1543 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1544 return *p;
1547 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1549 u32 *p = &vmx->segment_cache.seg[seg].limit;
1551 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1552 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1553 return *p;
1556 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1558 u32 *p = &vmx->segment_cache.seg[seg].ar;
1560 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1561 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1562 return *p;
1565 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1567 u32 eb;
1569 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1570 (1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR);
1571 if ((vcpu->guest_debug &
1572 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1573 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1574 eb |= 1u << BP_VECTOR;
1575 if (to_vmx(vcpu)->rmode.vm86_active)
1576 eb = ~0;
1577 if (enable_ept)
1578 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1579 if (vcpu->fpu_active)
1580 eb &= ~(1u << NM_VECTOR);
1582 /* When we are running a nested L2 guest and L1 specified for it a
1583 * certain exception bitmap, we must trap the same exceptions and pass
1584 * them to L1. When running L2, we will only handle the exceptions
1585 * specified above if L1 did not want them.
1587 if (is_guest_mode(vcpu))
1588 eb |= get_vmcs12(vcpu)->exception_bitmap;
1590 vmcs_write32(EXCEPTION_BITMAP, eb);
1593 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1594 unsigned long entry, unsigned long exit)
1596 vm_entry_controls_clearbit(vmx, entry);
1597 vm_exit_controls_clearbit(vmx, exit);
1600 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1602 unsigned i;
1603 struct msr_autoload *m = &vmx->msr_autoload;
1605 switch (msr) {
1606 case MSR_EFER:
1607 if (cpu_has_load_ia32_efer) {
1608 clear_atomic_switch_msr_special(vmx,
1609 VM_ENTRY_LOAD_IA32_EFER,
1610 VM_EXIT_LOAD_IA32_EFER);
1611 return;
1613 break;
1614 case MSR_CORE_PERF_GLOBAL_CTRL:
1615 if (cpu_has_load_perf_global_ctrl) {
1616 clear_atomic_switch_msr_special(vmx,
1617 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1618 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1619 return;
1621 break;
1624 for (i = 0; i < m->nr; ++i)
1625 if (m->guest[i].index == msr)
1626 break;
1628 if (i == m->nr)
1629 return;
1630 --m->nr;
1631 m->guest[i] = m->guest[m->nr];
1632 m->host[i] = m->host[m->nr];
1633 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1634 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1637 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1638 unsigned long entry, unsigned long exit,
1639 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
1640 u64 guest_val, u64 host_val)
1642 vmcs_write64(guest_val_vmcs, guest_val);
1643 vmcs_write64(host_val_vmcs, host_val);
1644 vm_entry_controls_setbit(vmx, entry);
1645 vm_exit_controls_setbit(vmx, exit);
1648 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1649 u64 guest_val, u64 host_val)
1651 unsigned i;
1652 struct msr_autoload *m = &vmx->msr_autoload;
1654 switch (msr) {
1655 case MSR_EFER:
1656 if (cpu_has_load_ia32_efer) {
1657 add_atomic_switch_msr_special(vmx,
1658 VM_ENTRY_LOAD_IA32_EFER,
1659 VM_EXIT_LOAD_IA32_EFER,
1660 GUEST_IA32_EFER,
1661 HOST_IA32_EFER,
1662 guest_val, host_val);
1663 return;
1665 break;
1666 case MSR_CORE_PERF_GLOBAL_CTRL:
1667 if (cpu_has_load_perf_global_ctrl) {
1668 add_atomic_switch_msr_special(vmx,
1669 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1670 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1671 GUEST_IA32_PERF_GLOBAL_CTRL,
1672 HOST_IA32_PERF_GLOBAL_CTRL,
1673 guest_val, host_val);
1674 return;
1676 break;
1679 for (i = 0; i < m->nr; ++i)
1680 if (m->guest[i].index == msr)
1681 break;
1683 if (i == NR_AUTOLOAD_MSRS) {
1684 printk_once(KERN_WARNING "Not enough msr switch entries. "
1685 "Can't add msr %x\n", msr);
1686 return;
1687 } else if (i == m->nr) {
1688 ++m->nr;
1689 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1690 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1693 m->guest[i].index = msr;
1694 m->guest[i].value = guest_val;
1695 m->host[i].index = msr;
1696 m->host[i].value = host_val;
1699 static void reload_tss(void)
1702 * VT restores TR but not its size. Useless.
1704 struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
1705 struct desc_struct *descs;
1707 descs = (void *)gdt->address;
1708 descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
1709 load_TR_desc();
1712 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
1714 u64 guest_efer;
1715 u64 ignore_bits;
1717 guest_efer = vmx->vcpu.arch.efer;
1720 * NX is emulated; LMA and LME handled by hardware; SCE meaningless
1721 * outside long mode
1723 ignore_bits = EFER_NX | EFER_SCE;
1724 #ifdef CONFIG_X86_64
1725 ignore_bits |= EFER_LMA | EFER_LME;
1726 /* SCE is meaningful only in long mode on Intel */
1727 if (guest_efer & EFER_LMA)
1728 ignore_bits &= ~(u64)EFER_SCE;
1729 #endif
1730 guest_efer &= ~ignore_bits;
1731 guest_efer |= host_efer & ignore_bits;
1732 vmx->guest_msrs[efer_offset].data = guest_efer;
1733 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1735 clear_atomic_switch_msr(vmx, MSR_EFER);
1738 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1739 * On CPUs that support "load IA32_EFER", always switch EFER
1740 * atomically, since it's faster than switching it manually.
1742 if (cpu_has_load_ia32_efer ||
1743 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1744 guest_efer = vmx->vcpu.arch.efer;
1745 if (!(guest_efer & EFER_LMA))
1746 guest_efer &= ~EFER_LME;
1747 if (guest_efer != host_efer)
1748 add_atomic_switch_msr(vmx, MSR_EFER,
1749 guest_efer, host_efer);
1750 return false;
1753 return true;
1756 static unsigned long segment_base(u16 selector)
1758 struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
1759 struct desc_struct *d;
1760 unsigned long table_base;
1761 unsigned long v;
1763 if (!(selector & ~3))
1764 return 0;
1766 table_base = gdt->address;
1768 if (selector & 4) { /* from ldt */
1769 u16 ldt_selector = kvm_read_ldt();
1771 if (!(ldt_selector & ~3))
1772 return 0;
1774 table_base = segment_base(ldt_selector);
1776 d = (struct desc_struct *)(table_base + (selector & ~7));
1777 v = get_desc_base(d);
1778 #ifdef CONFIG_X86_64
1779 if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
1780 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
1781 #endif
1782 return v;
1785 static inline unsigned long kvm_read_tr_base(void)
1787 u16 tr;
1788 asm("str %0" : "=g"(tr));
1789 return segment_base(tr);
1792 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
1794 struct vcpu_vmx *vmx = to_vmx(vcpu);
1795 int i;
1797 if (vmx->host_state.loaded)
1798 return;
1800 vmx->host_state.loaded = 1;
1802 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1803 * allow segment selectors with cpl > 0 or ti == 1.
1805 vmx->host_state.ldt_sel = kvm_read_ldt();
1806 vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
1807 savesegment(fs, vmx->host_state.fs_sel);
1808 if (!(vmx->host_state.fs_sel & 7)) {
1809 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
1810 vmx->host_state.fs_reload_needed = 0;
1811 } else {
1812 vmcs_write16(HOST_FS_SELECTOR, 0);
1813 vmx->host_state.fs_reload_needed = 1;
1815 savesegment(gs, vmx->host_state.gs_sel);
1816 if (!(vmx->host_state.gs_sel & 7))
1817 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
1818 else {
1819 vmcs_write16(HOST_GS_SELECTOR, 0);
1820 vmx->host_state.gs_ldt_reload_needed = 1;
1823 #ifdef CONFIG_X86_64
1824 savesegment(ds, vmx->host_state.ds_sel);
1825 savesegment(es, vmx->host_state.es_sel);
1826 #endif
1828 #ifdef CONFIG_X86_64
1829 vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
1830 vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
1831 #else
1832 vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
1833 vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
1834 #endif
1836 #ifdef CONFIG_X86_64
1837 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1838 if (is_long_mode(&vmx->vcpu))
1839 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1840 #endif
1841 if (boot_cpu_has(X86_FEATURE_MPX))
1842 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
1843 for (i = 0; i < vmx->save_nmsrs; ++i)
1844 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1845 vmx->guest_msrs[i].data,
1846 vmx->guest_msrs[i].mask);
1849 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
1851 if (!vmx->host_state.loaded)
1852 return;
1854 ++vmx->vcpu.stat.host_state_reload;
1855 vmx->host_state.loaded = 0;
1856 #ifdef CONFIG_X86_64
1857 if (is_long_mode(&vmx->vcpu))
1858 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1859 #endif
1860 if (vmx->host_state.gs_ldt_reload_needed) {
1861 kvm_load_ldt(vmx->host_state.ldt_sel);
1862 #ifdef CONFIG_X86_64
1863 load_gs_index(vmx->host_state.gs_sel);
1864 #else
1865 loadsegment(gs, vmx->host_state.gs_sel);
1866 #endif
1868 if (vmx->host_state.fs_reload_needed)
1869 loadsegment(fs, vmx->host_state.fs_sel);
1870 #ifdef CONFIG_X86_64
1871 if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
1872 loadsegment(ds, vmx->host_state.ds_sel);
1873 loadsegment(es, vmx->host_state.es_sel);
1875 #endif
1876 reload_tss();
1877 #ifdef CONFIG_X86_64
1878 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1879 #endif
1880 if (vmx->host_state.msr_host_bndcfgs)
1881 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
1883 * If the FPU is not active (through the host task or
1884 * the guest vcpu), then restore the cr0.TS bit.
1886 if (!user_has_fpu() && !vmx->vcpu.guest_fpu_loaded)
1887 stts();
1888 load_gdt(this_cpu_ptr(&host_gdt));
1891 static void vmx_load_host_state(struct vcpu_vmx *vmx)
1893 preempt_disable();
1894 __vmx_load_host_state(vmx);
1895 preempt_enable();
1899 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1900 * vcpu mutex is already taken.
1902 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1904 struct vcpu_vmx *vmx = to_vmx(vcpu);
1905 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1907 if (!vmm_exclusive)
1908 kvm_cpu_vmxon(phys_addr);
1909 else if (vmx->loaded_vmcs->cpu != cpu)
1910 loaded_vmcs_clear(vmx->loaded_vmcs);
1912 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1913 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1914 vmcs_load(vmx->loaded_vmcs->vmcs);
1917 if (vmx->loaded_vmcs->cpu != cpu) {
1918 struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
1919 unsigned long sysenter_esp;
1921 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1922 local_irq_disable();
1923 crash_disable_local_vmclear(cpu);
1926 * Read loaded_vmcs->cpu should be before fetching
1927 * loaded_vmcs->loaded_vmcss_on_cpu_link.
1928 * See the comments in __loaded_vmcs_clear().
1930 smp_rmb();
1932 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1933 &per_cpu(loaded_vmcss_on_cpu, cpu));
1934 crash_enable_local_vmclear(cpu);
1935 local_irq_enable();
1938 * Linux uses per-cpu TSS and GDT, so set these when switching
1939 * processors.
1941 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
1942 vmcs_writel(HOST_GDTR_BASE, gdt->address); /* 22.2.4 */
1944 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1945 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1946 vmx->loaded_vmcs->cpu = cpu;
1950 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1952 __vmx_load_host_state(to_vmx(vcpu));
1953 if (!vmm_exclusive) {
1954 __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
1955 vcpu->cpu = -1;
1956 kvm_cpu_vmxoff();
1960 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
1962 ulong cr0;
1964 if (vcpu->fpu_active)
1965 return;
1966 vcpu->fpu_active = 1;
1967 cr0 = vmcs_readl(GUEST_CR0);
1968 cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
1969 cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
1970 vmcs_writel(GUEST_CR0, cr0);
1971 update_exception_bitmap(vcpu);
1972 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
1973 if (is_guest_mode(vcpu))
1974 vcpu->arch.cr0_guest_owned_bits &=
1975 ~get_vmcs12(vcpu)->cr0_guest_host_mask;
1976 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1979 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1982 * Return the cr0 value that a nested guest would read. This is a combination
1983 * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
1984 * its hypervisor (cr0_read_shadow).
1986 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
1988 return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
1989 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
1991 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
1993 return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
1994 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
1997 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
1999 /* Note that there is no vcpu->fpu_active = 0 here. The caller must
2000 * set this *before* calling this function.
2002 vmx_decache_cr0_guest_bits(vcpu);
2003 vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
2004 update_exception_bitmap(vcpu);
2005 vcpu->arch.cr0_guest_owned_bits = 0;
2006 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2007 if (is_guest_mode(vcpu)) {
2009 * L1's specified read shadow might not contain the TS bit,
2010 * so now that we turned on shadowing of this bit, we need to
2011 * set this bit of the shadow. Like in nested_vmx_run we need
2012 * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
2013 * up-to-date here because we just decached cr0.TS (and we'll
2014 * only update vmcs12->guest_cr0 on nested exit).
2016 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2017 vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
2018 (vcpu->arch.cr0 & X86_CR0_TS);
2019 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
2020 } else
2021 vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
2024 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2026 unsigned long rflags, save_rflags;
2028 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2029 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2030 rflags = vmcs_readl(GUEST_RFLAGS);
2031 if (to_vmx(vcpu)->rmode.vm86_active) {
2032 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2033 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2034 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2036 to_vmx(vcpu)->rflags = rflags;
2038 return to_vmx(vcpu)->rflags;
2041 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2043 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2044 to_vmx(vcpu)->rflags = rflags;
2045 if (to_vmx(vcpu)->rmode.vm86_active) {
2046 to_vmx(vcpu)->rmode.save_rflags = rflags;
2047 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2049 vmcs_writel(GUEST_RFLAGS, rflags);
2052 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2054 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2055 int ret = 0;
2057 if (interruptibility & GUEST_INTR_STATE_STI)
2058 ret |= KVM_X86_SHADOW_INT_STI;
2059 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2060 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2062 return ret;
2065 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2067 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2068 u32 interruptibility = interruptibility_old;
2070 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2072 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2073 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2074 else if (mask & KVM_X86_SHADOW_INT_STI)
2075 interruptibility |= GUEST_INTR_STATE_STI;
2077 if ((interruptibility != interruptibility_old))
2078 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2081 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2083 unsigned long rip;
2085 rip = kvm_rip_read(vcpu);
2086 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2087 kvm_rip_write(vcpu, rip);
2089 /* skipping an emulated instruction also counts */
2090 vmx_set_interrupt_shadow(vcpu, 0);
2094 * KVM wants to inject page-faults which it got to the guest. This function
2095 * checks whether in a nested guest, we need to inject them to L1 or L2.
2097 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned nr)
2099 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2101 if (!(vmcs12->exception_bitmap & (1u << nr)))
2102 return 0;
2104 nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
2105 vmcs_read32(VM_EXIT_INTR_INFO),
2106 vmcs_readl(EXIT_QUALIFICATION));
2107 return 1;
2110 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
2111 bool has_error_code, u32 error_code,
2112 bool reinject)
2114 struct vcpu_vmx *vmx = to_vmx(vcpu);
2115 u32 intr_info = nr | INTR_INFO_VALID_MASK;
2117 if (!reinject && is_guest_mode(vcpu) &&
2118 nested_vmx_check_exception(vcpu, nr))
2119 return;
2121 if (has_error_code) {
2122 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2123 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2126 if (vmx->rmode.vm86_active) {
2127 int inc_eip = 0;
2128 if (kvm_exception_is_soft(nr))
2129 inc_eip = vcpu->arch.event_exit_inst_len;
2130 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2131 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2132 return;
2135 if (kvm_exception_is_soft(nr)) {
2136 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2137 vmx->vcpu.arch.event_exit_inst_len);
2138 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2139 } else
2140 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2142 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2145 static bool vmx_rdtscp_supported(void)
2147 return cpu_has_vmx_rdtscp();
2150 static bool vmx_invpcid_supported(void)
2152 return cpu_has_vmx_invpcid() && enable_ept;
2156 * Swap MSR entry in host/guest MSR entry array.
2158 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2160 struct shared_msr_entry tmp;
2162 tmp = vmx->guest_msrs[to];
2163 vmx->guest_msrs[to] = vmx->guest_msrs[from];
2164 vmx->guest_msrs[from] = tmp;
2167 static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
2169 unsigned long *msr_bitmap;
2171 if (is_guest_mode(vcpu))
2172 msr_bitmap = vmx_msr_bitmap_nested;
2173 else if (irqchip_in_kernel(vcpu->kvm) &&
2174 apic_x2apic_mode(vcpu->arch.apic)) {
2175 if (is_long_mode(vcpu))
2176 msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
2177 else
2178 msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
2179 } else {
2180 if (is_long_mode(vcpu))
2181 msr_bitmap = vmx_msr_bitmap_longmode;
2182 else
2183 msr_bitmap = vmx_msr_bitmap_legacy;
2186 vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
2190 * Set up the vmcs to automatically save and restore system
2191 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
2192 * mode, as fiddling with msrs is very expensive.
2194 static void setup_msrs(struct vcpu_vmx *vmx)
2196 int save_nmsrs, index;
2198 save_nmsrs = 0;
2199 #ifdef CONFIG_X86_64
2200 if (is_long_mode(&vmx->vcpu)) {
2201 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2202 if (index >= 0)
2203 move_msr_up(vmx, index, save_nmsrs++);
2204 index = __find_msr_index(vmx, MSR_LSTAR);
2205 if (index >= 0)
2206 move_msr_up(vmx, index, save_nmsrs++);
2207 index = __find_msr_index(vmx, MSR_CSTAR);
2208 if (index >= 0)
2209 move_msr_up(vmx, index, save_nmsrs++);
2210 index = __find_msr_index(vmx, MSR_TSC_AUX);
2211 if (index >= 0 && vmx->rdtscp_enabled)
2212 move_msr_up(vmx, index, save_nmsrs++);
2214 * MSR_STAR is only needed on long mode guests, and only
2215 * if efer.sce is enabled.
2217 index = __find_msr_index(vmx, MSR_STAR);
2218 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2219 move_msr_up(vmx, index, save_nmsrs++);
2221 #endif
2222 index = __find_msr_index(vmx, MSR_EFER);
2223 if (index >= 0 && update_transition_efer(vmx, index))
2224 move_msr_up(vmx, index, save_nmsrs++);
2226 vmx->save_nmsrs = save_nmsrs;
2228 if (cpu_has_vmx_msr_bitmap())
2229 vmx_set_msr_bitmap(&vmx->vcpu);
2233 * reads and returns guest's timestamp counter "register"
2234 * guest_tsc = host_tsc + tsc_offset -- 21.3
2236 static u64 guest_read_tsc(void)
2238 u64 host_tsc, tsc_offset;
2240 rdtscll(host_tsc);
2241 tsc_offset = vmcs_read64(TSC_OFFSET);
2242 return host_tsc + tsc_offset;
2246 * Like guest_read_tsc, but always returns L1's notion of the timestamp
2247 * counter, even if a nested guest (L2) is currently running.
2249 static u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2251 u64 tsc_offset;
2253 tsc_offset = is_guest_mode(vcpu) ?
2254 to_vmx(vcpu)->nested.vmcs01_tsc_offset :
2255 vmcs_read64(TSC_OFFSET);
2256 return host_tsc + tsc_offset;
2260 * Engage any workarounds for mis-matched TSC rates. Currently limited to
2261 * software catchup for faster rates on slower CPUs.
2263 static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2265 if (!scale)
2266 return;
2268 if (user_tsc_khz > tsc_khz) {
2269 vcpu->arch.tsc_catchup = 1;
2270 vcpu->arch.tsc_always_catchup = 1;
2271 } else
2272 WARN(1, "user requested TSC rate below hardware speed\n");
2275 static u64 vmx_read_tsc_offset(struct kvm_vcpu *vcpu)
2277 return vmcs_read64(TSC_OFFSET);
2281 * writes 'offset' into guest's timestamp counter offset register
2283 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2285 if (is_guest_mode(vcpu)) {
2287 * We're here if L1 chose not to trap WRMSR to TSC. According
2288 * to the spec, this should set L1's TSC; The offset that L1
2289 * set for L2 remains unchanged, and still needs to be added
2290 * to the newly set TSC to get L2's TSC.
2292 struct vmcs12 *vmcs12;
2293 to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset;
2294 /* recalculate vmcs02.TSC_OFFSET: */
2295 vmcs12 = get_vmcs12(vcpu);
2296 vmcs_write64(TSC_OFFSET, offset +
2297 (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2298 vmcs12->tsc_offset : 0));
2299 } else {
2300 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2301 vmcs_read64(TSC_OFFSET), offset);
2302 vmcs_write64(TSC_OFFSET, offset);
2306 static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment, bool host)
2308 u64 offset = vmcs_read64(TSC_OFFSET);
2310 vmcs_write64(TSC_OFFSET, offset + adjustment);
2311 if (is_guest_mode(vcpu)) {
2312 /* Even when running L2, the adjustment needs to apply to L1 */
2313 to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment;
2314 } else
2315 trace_kvm_write_tsc_offset(vcpu->vcpu_id, offset,
2316 offset + adjustment);
2319 static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2321 return target_tsc - native_read_tsc();
2324 static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
2326 struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
2327 return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
2331 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2332 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2333 * all guests if the "nested" module option is off, and can also be disabled
2334 * for a single guest by disabling its VMX cpuid bit.
2336 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2338 return nested && guest_cpuid_has_vmx(vcpu);
2342 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2343 * returned for the various VMX controls MSRs when nested VMX is enabled.
2344 * The same values should also be used to verify that vmcs12 control fields are
2345 * valid during nested entry from L1 to L2.
2346 * Each of these control msrs has a low and high 32-bit half: A low bit is on
2347 * if the corresponding bit in the (32-bit) control field *must* be on, and a
2348 * bit in the high half is on if the corresponding bit in the control field
2349 * may be on. See also vmx_control_verify().
2351 static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
2354 * Note that as a general rule, the high half of the MSRs (bits in
2355 * the control fields which may be 1) should be initialized by the
2356 * intersection of the underlying hardware's MSR (i.e., features which
2357 * can be supported) and the list of features we want to expose -
2358 * because they are known to be properly supported in our code.
2359 * Also, usually, the low half of the MSRs (bits which must be 1) can
2360 * be set to 0, meaning that L1 may turn off any of these bits. The
2361 * reason is that if one of these bits is necessary, it will appear
2362 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2363 * fields of vmcs01 and vmcs02, will turn these bits off - and
2364 * nested_vmx_exit_handled() will not pass related exits to L1.
2365 * These rules have exceptions below.
2368 /* pin-based controls */
2369 rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2370 vmx->nested.nested_vmx_pinbased_ctls_low,
2371 vmx->nested.nested_vmx_pinbased_ctls_high);
2372 vmx->nested.nested_vmx_pinbased_ctls_low |=
2373 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2374 vmx->nested.nested_vmx_pinbased_ctls_high &=
2375 PIN_BASED_EXT_INTR_MASK |
2376 PIN_BASED_NMI_EXITING |
2377 PIN_BASED_VIRTUAL_NMIS;
2378 vmx->nested.nested_vmx_pinbased_ctls_high |=
2379 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2380 PIN_BASED_VMX_PREEMPTION_TIMER;
2381 if (vmx_vm_has_apicv(vmx->vcpu.kvm))
2382 vmx->nested.nested_vmx_pinbased_ctls_high |=
2383 PIN_BASED_POSTED_INTR;
2385 /* exit controls */
2386 rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2387 vmx->nested.nested_vmx_exit_ctls_low,
2388 vmx->nested.nested_vmx_exit_ctls_high);
2389 vmx->nested.nested_vmx_exit_ctls_low =
2390 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2392 vmx->nested.nested_vmx_exit_ctls_high &=
2393 #ifdef CONFIG_X86_64
2394 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2395 #endif
2396 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2397 vmx->nested.nested_vmx_exit_ctls_high |=
2398 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2399 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2400 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2402 if (vmx_mpx_supported())
2403 vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2405 /* We support free control of debug control saving. */
2406 vmx->nested.nested_vmx_true_exit_ctls_low =
2407 vmx->nested.nested_vmx_exit_ctls_low &
2408 ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2410 /* entry controls */
2411 rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2412 vmx->nested.nested_vmx_entry_ctls_low,
2413 vmx->nested.nested_vmx_entry_ctls_high);
2414 vmx->nested.nested_vmx_entry_ctls_low =
2415 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2416 vmx->nested.nested_vmx_entry_ctls_high &=
2417 #ifdef CONFIG_X86_64
2418 VM_ENTRY_IA32E_MODE |
2419 #endif
2420 VM_ENTRY_LOAD_IA32_PAT;
2421 vmx->nested.nested_vmx_entry_ctls_high |=
2422 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
2423 if (vmx_mpx_supported())
2424 vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2426 /* We support free control of debug control loading. */
2427 vmx->nested.nested_vmx_true_entry_ctls_low =
2428 vmx->nested.nested_vmx_entry_ctls_low &
2429 ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2431 /* cpu-based controls */
2432 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2433 vmx->nested.nested_vmx_procbased_ctls_low,
2434 vmx->nested.nested_vmx_procbased_ctls_high);
2435 vmx->nested.nested_vmx_procbased_ctls_low =
2436 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2437 vmx->nested.nested_vmx_procbased_ctls_high &=
2438 CPU_BASED_VIRTUAL_INTR_PENDING |
2439 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2440 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2441 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2442 CPU_BASED_CR3_STORE_EXITING |
2443 #ifdef CONFIG_X86_64
2444 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2445 #endif
2446 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2447 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_EXITING |
2448 CPU_BASED_RDPMC_EXITING | CPU_BASED_RDTSC_EXITING |
2449 CPU_BASED_PAUSE_EXITING | CPU_BASED_TPR_SHADOW |
2450 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2452 * We can allow some features even when not supported by the
2453 * hardware. For example, L1 can specify an MSR bitmap - and we
2454 * can use it to avoid exits to L1 - even when L0 runs L2
2455 * without MSR bitmaps.
2457 vmx->nested.nested_vmx_procbased_ctls_high |=
2458 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2459 CPU_BASED_USE_MSR_BITMAPS;
2461 /* We support free control of CR3 access interception. */
2462 vmx->nested.nested_vmx_true_procbased_ctls_low =
2463 vmx->nested.nested_vmx_procbased_ctls_low &
2464 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2466 /* secondary cpu-based controls */
2467 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2468 vmx->nested.nested_vmx_secondary_ctls_low,
2469 vmx->nested.nested_vmx_secondary_ctls_high);
2470 vmx->nested.nested_vmx_secondary_ctls_low = 0;
2471 vmx->nested.nested_vmx_secondary_ctls_high &=
2472 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2473 SECONDARY_EXEC_RDTSCP |
2474 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2475 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2476 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2477 SECONDARY_EXEC_WBINVD_EXITING |
2478 SECONDARY_EXEC_XSAVES;
2480 if (enable_ept) {
2481 /* nested EPT: emulate EPT also to L1 */
2482 vmx->nested.nested_vmx_secondary_ctls_high |=
2483 SECONDARY_EXEC_ENABLE_EPT;
2484 vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
2485 VMX_EPTP_WB_BIT | VMX_EPT_2MB_PAGE_BIT |
2486 VMX_EPT_INVEPT_BIT;
2487 vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
2489 * For nested guests, we don't do anything specific
2490 * for single context invalidation. Hence, only advertise
2491 * support for global context invalidation.
2493 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT;
2494 } else
2495 vmx->nested.nested_vmx_ept_caps = 0;
2497 if (enable_unrestricted_guest)
2498 vmx->nested.nested_vmx_secondary_ctls_high |=
2499 SECONDARY_EXEC_UNRESTRICTED_GUEST;
2501 /* miscellaneous data */
2502 rdmsr(MSR_IA32_VMX_MISC,
2503 vmx->nested.nested_vmx_misc_low,
2504 vmx->nested.nested_vmx_misc_high);
2505 vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
2506 vmx->nested.nested_vmx_misc_low |=
2507 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
2508 VMX_MISC_ACTIVITY_HLT;
2509 vmx->nested.nested_vmx_misc_high = 0;
2512 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2515 * Bits 0 in high must be 0, and bits 1 in low must be 1.
2517 return ((control & high) | low) == control;
2520 static inline u64 vmx_control_msr(u32 low, u32 high)
2522 return low | ((u64)high << 32);
2525 /* Returns 0 on success, non-0 otherwise. */
2526 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2528 struct vcpu_vmx *vmx = to_vmx(vcpu);
2530 switch (msr_index) {
2531 case MSR_IA32_VMX_BASIC:
2533 * This MSR reports some information about VMX support. We
2534 * should return information about the VMX we emulate for the
2535 * guest, and the VMCS structure we give it - not about the
2536 * VMX support of the underlying hardware.
2538 *pdata = VMCS12_REVISION | VMX_BASIC_TRUE_CTLS |
2539 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2540 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2541 break;
2542 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2543 case MSR_IA32_VMX_PINBASED_CTLS:
2544 *pdata = vmx_control_msr(
2545 vmx->nested.nested_vmx_pinbased_ctls_low,
2546 vmx->nested.nested_vmx_pinbased_ctls_high);
2547 break;
2548 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2549 *pdata = vmx_control_msr(
2550 vmx->nested.nested_vmx_true_procbased_ctls_low,
2551 vmx->nested.nested_vmx_procbased_ctls_high);
2552 break;
2553 case MSR_IA32_VMX_PROCBASED_CTLS:
2554 *pdata = vmx_control_msr(
2555 vmx->nested.nested_vmx_procbased_ctls_low,
2556 vmx->nested.nested_vmx_procbased_ctls_high);
2557 break;
2558 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2559 *pdata = vmx_control_msr(
2560 vmx->nested.nested_vmx_true_exit_ctls_low,
2561 vmx->nested.nested_vmx_exit_ctls_high);
2562 break;
2563 case MSR_IA32_VMX_EXIT_CTLS:
2564 *pdata = vmx_control_msr(
2565 vmx->nested.nested_vmx_exit_ctls_low,
2566 vmx->nested.nested_vmx_exit_ctls_high);
2567 break;
2568 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2569 *pdata = vmx_control_msr(
2570 vmx->nested.nested_vmx_true_entry_ctls_low,
2571 vmx->nested.nested_vmx_entry_ctls_high);
2572 break;
2573 case MSR_IA32_VMX_ENTRY_CTLS:
2574 *pdata = vmx_control_msr(
2575 vmx->nested.nested_vmx_entry_ctls_low,
2576 vmx->nested.nested_vmx_entry_ctls_high);
2577 break;
2578 case MSR_IA32_VMX_MISC:
2579 *pdata = vmx_control_msr(
2580 vmx->nested.nested_vmx_misc_low,
2581 vmx->nested.nested_vmx_misc_high);
2582 break;
2584 * These MSRs specify bits which the guest must keep fixed (on or off)
2585 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2586 * We picked the standard core2 setting.
2588 #define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2589 #define VMXON_CR4_ALWAYSON X86_CR4_VMXE
2590 case MSR_IA32_VMX_CR0_FIXED0:
2591 *pdata = VMXON_CR0_ALWAYSON;
2592 break;
2593 case MSR_IA32_VMX_CR0_FIXED1:
2594 *pdata = -1ULL;
2595 break;
2596 case MSR_IA32_VMX_CR4_FIXED0:
2597 *pdata = VMXON_CR4_ALWAYSON;
2598 break;
2599 case MSR_IA32_VMX_CR4_FIXED1:
2600 *pdata = -1ULL;
2601 break;
2602 case MSR_IA32_VMX_VMCS_ENUM:
2603 *pdata = 0x2e; /* highest index: VMX_PREEMPTION_TIMER_VALUE */
2604 break;
2605 case MSR_IA32_VMX_PROCBASED_CTLS2:
2606 *pdata = vmx_control_msr(
2607 vmx->nested.nested_vmx_secondary_ctls_low,
2608 vmx->nested.nested_vmx_secondary_ctls_high);
2609 break;
2610 case MSR_IA32_VMX_EPT_VPID_CAP:
2611 /* Currently, no nested vpid support */
2612 *pdata = vmx->nested.nested_vmx_ept_caps;
2613 break;
2614 default:
2615 return 1;
2618 return 0;
2622 * Reads an msr value (of 'msr_index') into 'pdata'.
2623 * Returns 0 on success, non-0 otherwise.
2624 * Assumes vcpu_load() was already called.
2626 static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2628 u64 data;
2629 struct shared_msr_entry *msr;
2631 if (!pdata) {
2632 printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
2633 return -EINVAL;
2636 switch (msr_index) {
2637 #ifdef CONFIG_X86_64
2638 case MSR_FS_BASE:
2639 data = vmcs_readl(GUEST_FS_BASE);
2640 break;
2641 case MSR_GS_BASE:
2642 data = vmcs_readl(GUEST_GS_BASE);
2643 break;
2644 case MSR_KERNEL_GS_BASE:
2645 vmx_load_host_state(to_vmx(vcpu));
2646 data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
2647 break;
2648 #endif
2649 case MSR_EFER:
2650 return kvm_get_msr_common(vcpu, msr_index, pdata);
2651 case MSR_IA32_TSC:
2652 data = guest_read_tsc();
2653 break;
2654 case MSR_IA32_SYSENTER_CS:
2655 data = vmcs_read32(GUEST_SYSENTER_CS);
2656 break;
2657 case MSR_IA32_SYSENTER_EIP:
2658 data = vmcs_readl(GUEST_SYSENTER_EIP);
2659 break;
2660 case MSR_IA32_SYSENTER_ESP:
2661 data = vmcs_readl(GUEST_SYSENTER_ESP);
2662 break;
2663 case MSR_IA32_BNDCFGS:
2664 if (!vmx_mpx_supported())
2665 return 1;
2666 data = vmcs_read64(GUEST_BNDCFGS);
2667 break;
2668 case MSR_IA32_FEATURE_CONTROL:
2669 if (!nested_vmx_allowed(vcpu))
2670 return 1;
2671 data = to_vmx(vcpu)->nested.msr_ia32_feature_control;
2672 break;
2673 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2674 if (!nested_vmx_allowed(vcpu))
2675 return 1;
2676 return vmx_get_vmx_msr(vcpu, msr_index, pdata);
2677 case MSR_IA32_XSS:
2678 if (!vmx_xsaves_supported())
2679 return 1;
2680 data = vcpu->arch.ia32_xss;
2681 break;
2682 case MSR_TSC_AUX:
2683 if (!to_vmx(vcpu)->rdtscp_enabled)
2684 return 1;
2685 /* Otherwise falls through */
2686 default:
2687 msr = find_msr_entry(to_vmx(vcpu), msr_index);
2688 if (msr) {
2689 data = msr->data;
2690 break;
2692 return kvm_get_msr_common(vcpu, msr_index, pdata);
2695 *pdata = data;
2696 return 0;
2699 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
2702 * Writes msr value into into the appropriate "register".
2703 * Returns 0 on success, non-0 otherwise.
2704 * Assumes vcpu_load() was already called.
2706 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2708 struct vcpu_vmx *vmx = to_vmx(vcpu);
2709 struct shared_msr_entry *msr;
2710 int ret = 0;
2711 u32 msr_index = msr_info->index;
2712 u64 data = msr_info->data;
2714 switch (msr_index) {
2715 case MSR_EFER:
2716 ret = kvm_set_msr_common(vcpu, msr_info);
2717 break;
2718 #ifdef CONFIG_X86_64
2719 case MSR_FS_BASE:
2720 vmx_segment_cache_clear(vmx);
2721 vmcs_writel(GUEST_FS_BASE, data);
2722 break;
2723 case MSR_GS_BASE:
2724 vmx_segment_cache_clear(vmx);
2725 vmcs_writel(GUEST_GS_BASE, data);
2726 break;
2727 case MSR_KERNEL_GS_BASE:
2728 vmx_load_host_state(vmx);
2729 vmx->msr_guest_kernel_gs_base = data;
2730 break;
2731 #endif
2732 case MSR_IA32_SYSENTER_CS:
2733 vmcs_write32(GUEST_SYSENTER_CS, data);
2734 break;
2735 case MSR_IA32_SYSENTER_EIP:
2736 vmcs_writel(GUEST_SYSENTER_EIP, data);
2737 break;
2738 case MSR_IA32_SYSENTER_ESP:
2739 vmcs_writel(GUEST_SYSENTER_ESP, data);
2740 break;
2741 case MSR_IA32_BNDCFGS:
2742 if (!vmx_mpx_supported())
2743 return 1;
2744 vmcs_write64(GUEST_BNDCFGS, data);
2745 break;
2746 case MSR_IA32_TSC:
2747 kvm_write_tsc(vcpu, msr_info);
2748 break;
2749 case MSR_IA32_CR_PAT:
2750 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2751 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
2752 return 1;
2753 vmcs_write64(GUEST_IA32_PAT, data);
2754 vcpu->arch.pat = data;
2755 break;
2757 ret = kvm_set_msr_common(vcpu, msr_info);
2758 break;
2759 case MSR_IA32_TSC_ADJUST:
2760 ret = kvm_set_msr_common(vcpu, msr_info);
2761 break;
2762 case MSR_IA32_FEATURE_CONTROL:
2763 if (!nested_vmx_allowed(vcpu) ||
2764 (to_vmx(vcpu)->nested.msr_ia32_feature_control &
2765 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
2766 return 1;
2767 vmx->nested.msr_ia32_feature_control = data;
2768 if (msr_info->host_initiated && data == 0)
2769 vmx_leave_nested(vcpu);
2770 break;
2771 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2772 return 1; /* they are read-only */
2773 case MSR_IA32_XSS:
2774 if (!vmx_xsaves_supported())
2775 return 1;
2777 * The only supported bit as of Skylake is bit 8, but
2778 * it is not supported on KVM.
2780 if (data != 0)
2781 return 1;
2782 vcpu->arch.ia32_xss = data;
2783 if (vcpu->arch.ia32_xss != host_xss)
2784 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
2785 vcpu->arch.ia32_xss, host_xss);
2786 else
2787 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
2788 break;
2789 case MSR_TSC_AUX:
2790 if (!vmx->rdtscp_enabled)
2791 return 1;
2792 /* Check reserved bit, higher 32 bits should be zero */
2793 if ((data >> 32) != 0)
2794 return 1;
2795 /* Otherwise falls through */
2796 default:
2797 msr = find_msr_entry(vmx, msr_index);
2798 if (msr) {
2799 u64 old_msr_data = msr->data;
2800 msr->data = data;
2801 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2802 preempt_disable();
2803 ret = kvm_set_shared_msr(msr->index, msr->data,
2804 msr->mask);
2805 preempt_enable();
2806 if (ret)
2807 msr->data = old_msr_data;
2809 break;
2811 ret = kvm_set_msr_common(vcpu, msr_info);
2814 return ret;
2817 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2819 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2820 switch (reg) {
2821 case VCPU_REGS_RSP:
2822 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2823 break;
2824 case VCPU_REGS_RIP:
2825 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2826 break;
2827 case VCPU_EXREG_PDPTR:
2828 if (enable_ept)
2829 ept_save_pdptrs(vcpu);
2830 break;
2831 default:
2832 break;
2836 static __init int cpu_has_kvm_support(void)
2838 return cpu_has_vmx();
2841 static __init int vmx_disabled_by_bios(void)
2843 u64 msr;
2845 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2846 if (msr & FEATURE_CONTROL_LOCKED) {
2847 /* launched w/ TXT and VMX disabled */
2848 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2849 && tboot_enabled())
2850 return 1;
2851 /* launched w/o TXT and VMX only enabled w/ TXT */
2852 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2853 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2854 && !tboot_enabled()) {
2855 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2856 "activate TXT before enabling KVM\n");
2857 return 1;
2859 /* launched w/o TXT and VMX disabled */
2860 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2861 && !tboot_enabled())
2862 return 1;
2865 return 0;
2868 static void kvm_cpu_vmxon(u64 addr)
2870 asm volatile (ASM_VMX_VMXON_RAX
2871 : : "a"(&addr), "m"(addr)
2872 : "memory", "cc");
2875 static int hardware_enable(void)
2877 int cpu = raw_smp_processor_id();
2878 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2879 u64 old, test_bits;
2881 if (cr4_read_shadow() & X86_CR4_VMXE)
2882 return -EBUSY;
2884 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2887 * Now we can enable the vmclear operation in kdump
2888 * since the loaded_vmcss_on_cpu list on this cpu
2889 * has been initialized.
2891 * Though the cpu is not in VMX operation now, there
2892 * is no problem to enable the vmclear operation
2893 * for the loaded_vmcss_on_cpu list is empty!
2895 crash_enable_local_vmclear(cpu);
2897 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2899 test_bits = FEATURE_CONTROL_LOCKED;
2900 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2901 if (tboot_enabled())
2902 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2904 if ((old & test_bits) != test_bits) {
2905 /* enable and lock */
2906 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2908 cr4_set_bits(X86_CR4_VMXE);
2910 if (vmm_exclusive) {
2911 kvm_cpu_vmxon(phys_addr);
2912 ept_sync_global();
2915 native_store_gdt(this_cpu_ptr(&host_gdt));
2917 return 0;
2920 static void vmclear_local_loaded_vmcss(void)
2922 int cpu = raw_smp_processor_id();
2923 struct loaded_vmcs *v, *n;
2925 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2926 loaded_vmcss_on_cpu_link)
2927 __loaded_vmcs_clear(v);
2931 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2932 * tricks.
2934 static void kvm_cpu_vmxoff(void)
2936 asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
2939 static void hardware_disable(void)
2941 if (vmm_exclusive) {
2942 vmclear_local_loaded_vmcss();
2943 kvm_cpu_vmxoff();
2945 cr4_clear_bits(X86_CR4_VMXE);
2948 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2949 u32 msr, u32 *result)
2951 u32 vmx_msr_low, vmx_msr_high;
2952 u32 ctl = ctl_min | ctl_opt;
2954 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2956 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2957 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2959 /* Ensure minimum (required) set of control bits are supported. */
2960 if (ctl_min & ~ctl)
2961 return -EIO;
2963 *result = ctl;
2964 return 0;
2967 static __init bool allow_1_setting(u32 msr, u32 ctl)
2969 u32 vmx_msr_low, vmx_msr_high;
2971 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2972 return vmx_msr_high & ctl;
2975 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
2977 u32 vmx_msr_low, vmx_msr_high;
2978 u32 min, opt, min2, opt2;
2979 u32 _pin_based_exec_control = 0;
2980 u32 _cpu_based_exec_control = 0;
2981 u32 _cpu_based_2nd_exec_control = 0;
2982 u32 _vmexit_control = 0;
2983 u32 _vmentry_control = 0;
2985 min = CPU_BASED_HLT_EXITING |
2986 #ifdef CONFIG_X86_64
2987 CPU_BASED_CR8_LOAD_EXITING |
2988 CPU_BASED_CR8_STORE_EXITING |
2989 #endif
2990 CPU_BASED_CR3_LOAD_EXITING |
2991 CPU_BASED_CR3_STORE_EXITING |
2992 CPU_BASED_USE_IO_BITMAPS |
2993 CPU_BASED_MOV_DR_EXITING |
2994 CPU_BASED_USE_TSC_OFFSETING |
2995 CPU_BASED_MWAIT_EXITING |
2996 CPU_BASED_MONITOR_EXITING |
2997 CPU_BASED_INVLPG_EXITING |
2998 CPU_BASED_RDPMC_EXITING;
3000 opt = CPU_BASED_TPR_SHADOW |
3001 CPU_BASED_USE_MSR_BITMAPS |
3002 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3003 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
3004 &_cpu_based_exec_control) < 0)
3005 return -EIO;
3006 #ifdef CONFIG_X86_64
3007 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3008 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
3009 ~CPU_BASED_CR8_STORE_EXITING;
3010 #endif
3011 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
3012 min2 = 0;
3013 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3014 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3015 SECONDARY_EXEC_WBINVD_EXITING |
3016 SECONDARY_EXEC_ENABLE_VPID |
3017 SECONDARY_EXEC_ENABLE_EPT |
3018 SECONDARY_EXEC_UNRESTRICTED_GUEST |
3019 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
3020 SECONDARY_EXEC_RDTSCP |
3021 SECONDARY_EXEC_ENABLE_INVPCID |
3022 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3023 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3024 SECONDARY_EXEC_SHADOW_VMCS |
3025 SECONDARY_EXEC_XSAVES |
3026 SECONDARY_EXEC_ENABLE_PML;
3027 if (adjust_vmx_controls(min2, opt2,
3028 MSR_IA32_VMX_PROCBASED_CTLS2,
3029 &_cpu_based_2nd_exec_control) < 0)
3030 return -EIO;
3032 #ifndef CONFIG_X86_64
3033 if (!(_cpu_based_2nd_exec_control &
3034 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
3035 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
3036 #endif
3038 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3039 _cpu_based_2nd_exec_control &= ~(
3040 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3041 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3042 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3044 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
3045 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
3046 enabled */
3047 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
3048 CPU_BASED_CR3_STORE_EXITING |
3049 CPU_BASED_INVLPG_EXITING);
3050 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
3051 vmx_capability.ept, vmx_capability.vpid);
3054 min = VM_EXIT_SAVE_DEBUG_CONTROLS;
3055 #ifdef CONFIG_X86_64
3056 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
3057 #endif
3058 opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
3059 VM_EXIT_ACK_INTR_ON_EXIT | VM_EXIT_CLEAR_BNDCFGS;
3060 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
3061 &_vmexit_control) < 0)
3062 return -EIO;
3064 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
3065 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR;
3066 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
3067 &_pin_based_exec_control) < 0)
3068 return -EIO;
3070 if (!(_cpu_based_2nd_exec_control &
3071 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) ||
3072 !(_vmexit_control & VM_EXIT_ACK_INTR_ON_EXIT))
3073 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
3075 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
3076 opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
3077 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
3078 &_vmentry_control) < 0)
3079 return -EIO;
3081 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
3083 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
3084 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
3085 return -EIO;
3087 #ifdef CONFIG_X86_64
3088 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
3089 if (vmx_msr_high & (1u<<16))
3090 return -EIO;
3091 #endif
3093 /* Require Write-Back (WB) memory type for VMCS accesses. */
3094 if (((vmx_msr_high >> 18) & 15) != 6)
3095 return -EIO;
3097 vmcs_conf->size = vmx_msr_high & 0x1fff;
3098 vmcs_conf->order = get_order(vmcs_config.size);
3099 vmcs_conf->revision_id = vmx_msr_low;
3101 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
3102 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
3103 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
3104 vmcs_conf->vmexit_ctrl = _vmexit_control;
3105 vmcs_conf->vmentry_ctrl = _vmentry_control;
3107 cpu_has_load_ia32_efer =
3108 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3109 VM_ENTRY_LOAD_IA32_EFER)
3110 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3111 VM_EXIT_LOAD_IA32_EFER);
3113 cpu_has_load_perf_global_ctrl =
3114 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3115 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
3116 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3117 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
3120 * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
3121 * but due to arrata below it can't be used. Workaround is to use
3122 * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
3124 * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
3126 * AAK155 (model 26)
3127 * AAP115 (model 30)
3128 * AAT100 (model 37)
3129 * BC86,AAY89,BD102 (model 44)
3130 * BA97 (model 46)
3133 if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
3134 switch (boot_cpu_data.x86_model) {
3135 case 26:
3136 case 30:
3137 case 37:
3138 case 44:
3139 case 46:
3140 cpu_has_load_perf_global_ctrl = false;
3141 printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
3142 "does not work properly. Using workaround\n");
3143 break;
3144 default:
3145 break;
3149 if (cpu_has_xsaves)
3150 rdmsrl(MSR_IA32_XSS, host_xss);
3152 return 0;
3155 static struct vmcs *alloc_vmcs_cpu(int cpu)
3157 int node = cpu_to_node(cpu);
3158 struct page *pages;
3159 struct vmcs *vmcs;
3161 pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order);
3162 if (!pages)
3163 return NULL;
3164 vmcs = page_address(pages);
3165 memset(vmcs, 0, vmcs_config.size);
3166 vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
3167 return vmcs;
3170 static struct vmcs *alloc_vmcs(void)
3172 return alloc_vmcs_cpu(raw_smp_processor_id());
3175 static void free_vmcs(struct vmcs *vmcs)
3177 free_pages((unsigned long)vmcs, vmcs_config.order);
3181 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
3183 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3185 if (!loaded_vmcs->vmcs)
3186 return;
3187 loaded_vmcs_clear(loaded_vmcs);
3188 free_vmcs(loaded_vmcs->vmcs);
3189 loaded_vmcs->vmcs = NULL;
3192 static void free_kvm_area(void)
3194 int cpu;
3196 for_each_possible_cpu(cpu) {
3197 free_vmcs(per_cpu(vmxarea, cpu));
3198 per_cpu(vmxarea, cpu) = NULL;
3202 static void init_vmcs_shadow_fields(void)
3204 int i, j;
3206 /* No checks for read only fields yet */
3208 for (i = j = 0; i < max_shadow_read_write_fields; i++) {
3209 switch (shadow_read_write_fields[i]) {
3210 case GUEST_BNDCFGS:
3211 if (!vmx_mpx_supported())
3212 continue;
3213 break;
3214 default:
3215 break;
3218 if (j < i)
3219 shadow_read_write_fields[j] =
3220 shadow_read_write_fields[i];
3221 j++;
3223 max_shadow_read_write_fields = j;
3225 /* shadowed fields guest access without vmexit */
3226 for (i = 0; i < max_shadow_read_write_fields; i++) {
3227 clear_bit(shadow_read_write_fields[i],
3228 vmx_vmwrite_bitmap);
3229 clear_bit(shadow_read_write_fields[i],
3230 vmx_vmread_bitmap);
3232 for (i = 0; i < max_shadow_read_only_fields; i++)
3233 clear_bit(shadow_read_only_fields[i],
3234 vmx_vmread_bitmap);
3237 static __init int alloc_kvm_area(void)
3239 int cpu;
3241 for_each_possible_cpu(cpu) {
3242 struct vmcs *vmcs;
3244 vmcs = alloc_vmcs_cpu(cpu);
3245 if (!vmcs) {
3246 free_kvm_area();
3247 return -ENOMEM;
3250 per_cpu(vmxarea, cpu) = vmcs;
3252 return 0;
3255 static bool emulation_required(struct kvm_vcpu *vcpu)
3257 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3260 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
3261 struct kvm_segment *save)
3263 if (!emulate_invalid_guest_state) {
3265 * CS and SS RPL should be equal during guest entry according
3266 * to VMX spec, but in reality it is not always so. Since vcpu
3267 * is in the middle of the transition from real mode to
3268 * protected mode it is safe to assume that RPL 0 is a good
3269 * default value.
3271 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
3272 save->selector &= ~SEGMENT_RPL_MASK;
3273 save->dpl = save->selector & SEGMENT_RPL_MASK;
3274 save->s = 1;
3276 vmx_set_segment(vcpu, save, seg);
3279 static void enter_pmode(struct kvm_vcpu *vcpu)
3281 unsigned long flags;
3282 struct vcpu_vmx *vmx = to_vmx(vcpu);
3285 * Update real mode segment cache. It may be not up-to-date if sement
3286 * register was written while vcpu was in a guest mode.
3288 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3289 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3290 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3291 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3292 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3293 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3295 vmx->rmode.vm86_active = 0;
3297 vmx_segment_cache_clear(vmx);
3299 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3301 flags = vmcs_readl(GUEST_RFLAGS);
3302 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3303 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3304 vmcs_writel(GUEST_RFLAGS, flags);
3306 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
3307 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
3309 update_exception_bitmap(vcpu);
3311 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3312 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3313 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3314 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3315 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3316 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3319 static void fix_rmode_seg(int seg, struct kvm_segment *save)
3321 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3322 struct kvm_segment var = *save;
3324 var.dpl = 0x3;
3325 if (seg == VCPU_SREG_CS)
3326 var.type = 0x3;
3328 if (!emulate_invalid_guest_state) {
3329 var.selector = var.base >> 4;
3330 var.base = var.base & 0xffff0;
3331 var.limit = 0xffff;
3332 var.g = 0;
3333 var.db = 0;
3334 var.present = 1;
3335 var.s = 1;
3336 var.l = 0;
3337 var.unusable = 0;
3338 var.type = 0x3;
3339 var.avl = 0;
3340 if (save->base & 0xf)
3341 printk_once(KERN_WARNING "kvm: segment base is not "
3342 "paragraph aligned when entering "
3343 "protected mode (seg=%d)", seg);
3346 vmcs_write16(sf->selector, var.selector);
3347 vmcs_write32(sf->base, var.base);
3348 vmcs_write32(sf->limit, var.limit);
3349 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
3352 static void enter_rmode(struct kvm_vcpu *vcpu)
3354 unsigned long flags;
3355 struct vcpu_vmx *vmx = to_vmx(vcpu);
3357 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3358 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3359 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3360 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3361 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3362 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3363 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3365 vmx->rmode.vm86_active = 1;
3368 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
3369 * vcpu. Warn the user that an update is overdue.
3371 if (!vcpu->kvm->arch.tss_addr)
3372 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
3373 "called before entering vcpu\n");
3375 vmx_segment_cache_clear(vmx);
3377 vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
3378 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
3379 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3381 flags = vmcs_readl(GUEST_RFLAGS);
3382 vmx->rmode.save_rflags = flags;
3384 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3386 vmcs_writel(GUEST_RFLAGS, flags);
3387 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
3388 update_exception_bitmap(vcpu);
3390 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3391 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3392 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3393 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3394 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3395 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3397 kvm_mmu_reset_context(vcpu);
3400 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
3402 struct vcpu_vmx *vmx = to_vmx(vcpu);
3403 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
3405 if (!msr)
3406 return;
3409 * Force kernel_gs_base reloading before EFER changes, as control
3410 * of this msr depends on is_long_mode().
3412 vmx_load_host_state(to_vmx(vcpu));
3413 vcpu->arch.efer = efer;
3414 if (efer & EFER_LMA) {
3415 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3416 msr->data = efer;
3417 } else {
3418 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3420 msr->data = efer & ~EFER_LME;
3422 setup_msrs(vmx);
3425 #ifdef CONFIG_X86_64
3427 static void enter_lmode(struct kvm_vcpu *vcpu)
3429 u32 guest_tr_ar;
3431 vmx_segment_cache_clear(to_vmx(vcpu));
3433 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3434 if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
3435 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3436 __func__);
3437 vmcs_write32(GUEST_TR_AR_BYTES,
3438 (guest_tr_ar & ~AR_TYPE_MASK)
3439 | AR_TYPE_BUSY_64_TSS);
3441 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3444 static void exit_lmode(struct kvm_vcpu *vcpu)
3446 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3447 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3450 #endif
3452 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
3454 vpid_sync_context(to_vmx(vcpu));
3455 if (enable_ept) {
3456 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3457 return;
3458 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
3462 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
3464 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
3466 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
3467 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
3470 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
3472 if (enable_ept && is_paging(vcpu))
3473 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
3474 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
3477 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
3479 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
3481 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
3482 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
3485 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
3487 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3489 if (!test_bit(VCPU_EXREG_PDPTR,
3490 (unsigned long *)&vcpu->arch.regs_dirty))
3491 return;
3493 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3494 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3495 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3496 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3497 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3501 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3503 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3505 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3506 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3507 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3508 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3509 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3512 __set_bit(VCPU_EXREG_PDPTR,
3513 (unsigned long *)&vcpu->arch.regs_avail);
3514 __set_bit(VCPU_EXREG_PDPTR,
3515 (unsigned long *)&vcpu->arch.regs_dirty);
3518 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
3520 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3521 unsigned long cr0,
3522 struct kvm_vcpu *vcpu)
3524 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3525 vmx_decache_cr3(vcpu);
3526 if (!(cr0 & X86_CR0_PG)) {
3527 /* From paging/starting to nonpaging */
3528 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3529 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
3530 (CPU_BASED_CR3_LOAD_EXITING |
3531 CPU_BASED_CR3_STORE_EXITING));
3532 vcpu->arch.cr0 = cr0;
3533 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3534 } else if (!is_paging(vcpu)) {
3535 /* From nonpaging to paging */
3536 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3537 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
3538 ~(CPU_BASED_CR3_LOAD_EXITING |
3539 CPU_BASED_CR3_STORE_EXITING));
3540 vcpu->arch.cr0 = cr0;
3541 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3544 if (!(cr0 & X86_CR0_WP))
3545 *hw_cr0 &= ~X86_CR0_WP;
3548 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3550 struct vcpu_vmx *vmx = to_vmx(vcpu);
3551 unsigned long hw_cr0;
3553 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
3554 if (enable_unrestricted_guest)
3555 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3556 else {
3557 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3559 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3560 enter_pmode(vcpu);
3562 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3563 enter_rmode(vcpu);
3566 #ifdef CONFIG_X86_64
3567 if (vcpu->arch.efer & EFER_LME) {
3568 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3569 enter_lmode(vcpu);
3570 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3571 exit_lmode(vcpu);
3573 #endif
3575 if (enable_ept)
3576 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3578 if (!vcpu->fpu_active)
3579 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
3581 vmcs_writel(CR0_READ_SHADOW, cr0);
3582 vmcs_writel(GUEST_CR0, hw_cr0);
3583 vcpu->arch.cr0 = cr0;
3585 /* depends on vcpu->arch.cr0 to be set to a new value */
3586 vmx->emulation_required = emulation_required(vcpu);
3589 static u64 construct_eptp(unsigned long root_hpa)
3591 u64 eptp;
3593 /* TODO write the value reading from MSR */
3594 eptp = VMX_EPT_DEFAULT_MT |
3595 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
3596 if (enable_ept_ad_bits)
3597 eptp |= VMX_EPT_AD_ENABLE_BIT;
3598 eptp |= (root_hpa & PAGE_MASK);
3600 return eptp;
3603 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
3605 unsigned long guest_cr3;
3606 u64 eptp;
3608 guest_cr3 = cr3;
3609 if (enable_ept) {
3610 eptp = construct_eptp(cr3);
3611 vmcs_write64(EPT_POINTER, eptp);
3612 if (is_paging(vcpu) || is_guest_mode(vcpu))
3613 guest_cr3 = kvm_read_cr3(vcpu);
3614 else
3615 guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
3616 ept_load_pdptrs(vcpu);
3619 vmx_flush_tlb(vcpu);
3620 vmcs_writel(GUEST_CR3, guest_cr3);
3623 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3626 * Pass through host's Machine Check Enable value to hw_cr4, which
3627 * is in force while we are in guest mode. Do not let guests control
3628 * this bit, even if host CR4.MCE == 0.
3630 unsigned long hw_cr4 =
3631 (cr4_read_shadow() & X86_CR4_MCE) |
3632 (cr4 & ~X86_CR4_MCE) |
3633 (to_vmx(vcpu)->rmode.vm86_active ?
3634 KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
3636 if (cr4 & X86_CR4_VMXE) {
3638 * To use VMXON (and later other VMX instructions), a guest
3639 * must first be able to turn on cr4.VMXE (see handle_vmon()).
3640 * So basically the check on whether to allow nested VMX
3641 * is here.
3643 if (!nested_vmx_allowed(vcpu))
3644 return 1;
3646 if (to_vmx(vcpu)->nested.vmxon &&
3647 ((cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON))
3648 return 1;
3650 vcpu->arch.cr4 = cr4;
3651 if (enable_ept) {
3652 if (!is_paging(vcpu)) {
3653 hw_cr4 &= ~X86_CR4_PAE;
3654 hw_cr4 |= X86_CR4_PSE;
3655 } else if (!(cr4 & X86_CR4_PAE)) {
3656 hw_cr4 &= ~X86_CR4_PAE;
3660 if (!enable_unrestricted_guest && !is_paging(vcpu))
3662 * SMEP/SMAP is disabled if CPU is in non-paging mode in
3663 * hardware. However KVM always uses paging mode without
3664 * unrestricted guest.
3665 * To emulate this behavior, SMEP/SMAP needs to be manually
3666 * disabled when guest switches to non-paging mode.
3668 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP);
3670 vmcs_writel(CR4_READ_SHADOW, cr4);
3671 vmcs_writel(GUEST_CR4, hw_cr4);
3672 return 0;
3675 static void vmx_get_segment(struct kvm_vcpu *vcpu,
3676 struct kvm_segment *var, int seg)
3678 struct vcpu_vmx *vmx = to_vmx(vcpu);
3679 u32 ar;
3681 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3682 *var = vmx->rmode.segs[seg];
3683 if (seg == VCPU_SREG_TR
3684 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3685 return;
3686 var->base = vmx_read_guest_seg_base(vmx, seg);
3687 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3688 return;
3690 var->base = vmx_read_guest_seg_base(vmx, seg);
3691 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3692 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3693 ar = vmx_read_guest_seg_ar(vmx, seg);
3694 var->unusable = (ar >> 16) & 1;
3695 var->type = ar & 15;
3696 var->s = (ar >> 4) & 1;
3697 var->dpl = (ar >> 5) & 3;
3699 * Some userspaces do not preserve unusable property. Since usable
3700 * segment has to be present according to VMX spec we can use present
3701 * property to amend userspace bug by making unusable segment always
3702 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3703 * segment as unusable.
3705 var->present = !var->unusable;
3706 var->avl = (ar >> 12) & 1;
3707 var->l = (ar >> 13) & 1;
3708 var->db = (ar >> 14) & 1;
3709 var->g = (ar >> 15) & 1;
3712 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3714 struct kvm_segment s;
3716 if (to_vmx(vcpu)->rmode.vm86_active) {
3717 vmx_get_segment(vcpu, &s, seg);
3718 return s.base;
3720 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3723 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
3725 struct vcpu_vmx *vmx = to_vmx(vcpu);
3727 if (unlikely(vmx->rmode.vm86_active))
3728 return 0;
3729 else {
3730 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3731 return AR_DPL(ar);
3735 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3737 u32 ar;
3739 if (var->unusable || !var->present)
3740 ar = 1 << 16;
3741 else {
3742 ar = var->type & 15;
3743 ar |= (var->s & 1) << 4;
3744 ar |= (var->dpl & 3) << 5;
3745 ar |= (var->present & 1) << 7;
3746 ar |= (var->avl & 1) << 12;
3747 ar |= (var->l & 1) << 13;
3748 ar |= (var->db & 1) << 14;
3749 ar |= (var->g & 1) << 15;
3752 return ar;
3755 static void vmx_set_segment(struct kvm_vcpu *vcpu,
3756 struct kvm_segment *var, int seg)
3758 struct vcpu_vmx *vmx = to_vmx(vcpu);
3759 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3761 vmx_segment_cache_clear(vmx);
3763 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3764 vmx->rmode.segs[seg] = *var;
3765 if (seg == VCPU_SREG_TR)
3766 vmcs_write16(sf->selector, var->selector);
3767 else if (var->s)
3768 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3769 goto out;
3772 vmcs_writel(sf->base, var->base);
3773 vmcs_write32(sf->limit, var->limit);
3774 vmcs_write16(sf->selector, var->selector);
3777 * Fix the "Accessed" bit in AR field of segment registers for older
3778 * qemu binaries.
3779 * IA32 arch specifies that at the time of processor reset the
3780 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3781 * is setting it to 0 in the userland code. This causes invalid guest
3782 * state vmexit when "unrestricted guest" mode is turned on.
3783 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3784 * tree. Newer qemu binaries with that qemu fix would not need this
3785 * kvm hack.
3787 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3788 var->type |= 0x1; /* Accessed */
3790 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3792 out:
3793 vmx->emulation_required = emulation_required(vcpu);
3796 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3798 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3800 *db = (ar >> 14) & 1;
3801 *l = (ar >> 13) & 1;
3804 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3806 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3807 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3810 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3812 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3813 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3816 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3818 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3819 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3822 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3824 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3825 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3828 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3830 struct kvm_segment var;
3831 u32 ar;
3833 vmx_get_segment(vcpu, &var, seg);
3834 var.dpl = 0x3;
3835 if (seg == VCPU_SREG_CS)
3836 var.type = 0x3;
3837 ar = vmx_segment_access_rights(&var);
3839 if (var.base != (var.selector << 4))
3840 return false;
3841 if (var.limit != 0xffff)
3842 return false;
3843 if (ar != 0xf3)
3844 return false;
3846 return true;
3849 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3851 struct kvm_segment cs;
3852 unsigned int cs_rpl;
3854 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3855 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3857 if (cs.unusable)
3858 return false;
3859 if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK))
3860 return false;
3861 if (!cs.s)
3862 return false;
3863 if (cs.type & AR_TYPE_WRITEABLE_MASK) {
3864 if (cs.dpl > cs_rpl)
3865 return false;
3866 } else {
3867 if (cs.dpl != cs_rpl)
3868 return false;
3870 if (!cs.present)
3871 return false;
3873 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3874 return true;
3877 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3879 struct kvm_segment ss;
3880 unsigned int ss_rpl;
3882 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3883 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3885 if (ss.unusable)
3886 return true;
3887 if (ss.type != 3 && ss.type != 7)
3888 return false;
3889 if (!ss.s)
3890 return false;
3891 if (ss.dpl != ss_rpl) /* DPL != RPL */
3892 return false;
3893 if (!ss.present)
3894 return false;
3896 return true;
3899 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3901 struct kvm_segment var;
3902 unsigned int rpl;
3904 vmx_get_segment(vcpu, &var, seg);
3905 rpl = var.selector & SEGMENT_RPL_MASK;
3907 if (var.unusable)
3908 return true;
3909 if (!var.s)
3910 return false;
3911 if (!var.present)
3912 return false;
3913 if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) {
3914 if (var.dpl < rpl) /* DPL < RPL */
3915 return false;
3918 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3919 * rights flags
3921 return true;
3924 static bool tr_valid(struct kvm_vcpu *vcpu)
3926 struct kvm_segment tr;
3928 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3930 if (tr.unusable)
3931 return false;
3932 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3933 return false;
3934 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3935 return false;
3936 if (!tr.present)
3937 return false;
3939 return true;
3942 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3944 struct kvm_segment ldtr;
3946 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3948 if (ldtr.unusable)
3949 return true;
3950 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3951 return false;
3952 if (ldtr.type != 2)
3953 return false;
3954 if (!ldtr.present)
3955 return false;
3957 return true;
3960 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3962 struct kvm_segment cs, ss;
3964 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3965 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3967 return ((cs.selector & SEGMENT_RPL_MASK) ==
3968 (ss.selector & SEGMENT_RPL_MASK));
3972 * Check if guest state is valid. Returns true if valid, false if
3973 * not.
3974 * We assume that registers are always usable
3976 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3978 if (enable_unrestricted_guest)
3979 return true;
3981 /* real mode guest state checks */
3982 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3983 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3984 return false;
3985 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3986 return false;
3987 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3988 return false;
3989 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3990 return false;
3991 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3992 return false;
3993 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3994 return false;
3995 } else {
3996 /* protected mode guest state checks */
3997 if (!cs_ss_rpl_check(vcpu))
3998 return false;
3999 if (!code_segment_valid(vcpu))
4000 return false;
4001 if (!stack_segment_valid(vcpu))
4002 return false;
4003 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
4004 return false;
4005 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
4006 return false;
4007 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
4008 return false;
4009 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
4010 return false;
4011 if (!tr_valid(vcpu))
4012 return false;
4013 if (!ldtr_valid(vcpu))
4014 return false;
4016 /* TODO:
4017 * - Add checks on RIP
4018 * - Add checks on RFLAGS
4021 return true;
4024 static int init_rmode_tss(struct kvm *kvm)
4026 gfn_t fn;
4027 u16 data = 0;
4028 int idx, r;
4030 idx = srcu_read_lock(&kvm->srcu);
4031 fn = kvm->arch.tss_addr >> PAGE_SHIFT;
4032 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4033 if (r < 0)
4034 goto out;
4035 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
4036 r = kvm_write_guest_page(kvm, fn++, &data,
4037 TSS_IOPB_BASE_OFFSET, sizeof(u16));
4038 if (r < 0)
4039 goto out;
4040 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
4041 if (r < 0)
4042 goto out;
4043 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4044 if (r < 0)
4045 goto out;
4046 data = ~0;
4047 r = kvm_write_guest_page(kvm, fn, &data,
4048 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
4049 sizeof(u8));
4050 out:
4051 srcu_read_unlock(&kvm->srcu, idx);
4052 return r;
4055 static int init_rmode_identity_map(struct kvm *kvm)
4057 int i, idx, r = 0;
4058 pfn_t identity_map_pfn;
4059 u32 tmp;
4061 if (!enable_ept)
4062 return 0;
4064 /* Protect kvm->arch.ept_identity_pagetable_done. */
4065 mutex_lock(&kvm->slots_lock);
4067 if (likely(kvm->arch.ept_identity_pagetable_done))
4068 goto out2;
4070 identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
4072 r = alloc_identity_pagetable(kvm);
4073 if (r < 0)
4074 goto out2;
4076 idx = srcu_read_lock(&kvm->srcu);
4077 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
4078 if (r < 0)
4079 goto out;
4080 /* Set up identity-mapping pagetable for EPT in real mode */
4081 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
4082 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
4083 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
4084 r = kvm_write_guest_page(kvm, identity_map_pfn,
4085 &tmp, i * sizeof(tmp), sizeof(tmp));
4086 if (r < 0)
4087 goto out;
4089 kvm->arch.ept_identity_pagetable_done = true;
4091 out:
4092 srcu_read_unlock(&kvm->srcu, idx);
4094 out2:
4095 mutex_unlock(&kvm->slots_lock);
4096 return r;
4099 static void seg_setup(int seg)
4101 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4102 unsigned int ar;
4104 vmcs_write16(sf->selector, 0);
4105 vmcs_writel(sf->base, 0);
4106 vmcs_write32(sf->limit, 0xffff);
4107 ar = 0x93;
4108 if (seg == VCPU_SREG_CS)
4109 ar |= 0x08; /* code segment */
4111 vmcs_write32(sf->ar_bytes, ar);
4114 static int alloc_apic_access_page(struct kvm *kvm)
4116 struct page *page;
4117 struct kvm_userspace_memory_region kvm_userspace_mem;
4118 int r = 0;
4120 mutex_lock(&kvm->slots_lock);
4121 if (kvm->arch.apic_access_page_done)
4122 goto out;
4123 kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
4124 kvm_userspace_mem.flags = 0;
4125 kvm_userspace_mem.guest_phys_addr = APIC_DEFAULT_PHYS_BASE;
4126 kvm_userspace_mem.memory_size = PAGE_SIZE;
4127 r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
4128 if (r)
4129 goto out;
4131 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
4132 if (is_error_page(page)) {
4133 r = -EFAULT;
4134 goto out;
4138 * Do not pin the page in memory, so that memory hot-unplug
4139 * is able to migrate it.
4141 put_page(page);
4142 kvm->arch.apic_access_page_done = true;
4143 out:
4144 mutex_unlock(&kvm->slots_lock);
4145 return r;
4148 static int alloc_identity_pagetable(struct kvm *kvm)
4150 /* Called with kvm->slots_lock held. */
4152 struct kvm_userspace_memory_region kvm_userspace_mem;
4153 int r = 0;
4155 BUG_ON(kvm->arch.ept_identity_pagetable_done);
4157 kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
4158 kvm_userspace_mem.flags = 0;
4159 kvm_userspace_mem.guest_phys_addr =
4160 kvm->arch.ept_identity_map_addr;
4161 kvm_userspace_mem.memory_size = PAGE_SIZE;
4162 r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
4164 return r;
4167 static void allocate_vpid(struct vcpu_vmx *vmx)
4169 int vpid;
4171 vmx->vpid = 0;
4172 if (!enable_vpid)
4173 return;
4174 spin_lock(&vmx_vpid_lock);
4175 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
4176 if (vpid < VMX_NR_VPIDS) {
4177 vmx->vpid = vpid;
4178 __set_bit(vpid, vmx_vpid_bitmap);
4180 spin_unlock(&vmx_vpid_lock);
4183 static void free_vpid(struct vcpu_vmx *vmx)
4185 if (!enable_vpid)
4186 return;
4187 spin_lock(&vmx_vpid_lock);
4188 if (vmx->vpid != 0)
4189 __clear_bit(vmx->vpid, vmx_vpid_bitmap);
4190 spin_unlock(&vmx_vpid_lock);
4193 #define MSR_TYPE_R 1
4194 #define MSR_TYPE_W 2
4195 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
4196 u32 msr, int type)
4198 int f = sizeof(unsigned long);
4200 if (!cpu_has_vmx_msr_bitmap())
4201 return;
4204 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4205 * have the write-low and read-high bitmap offsets the wrong way round.
4206 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4208 if (msr <= 0x1fff) {
4209 if (type & MSR_TYPE_R)
4210 /* read-low */
4211 __clear_bit(msr, msr_bitmap + 0x000 / f);
4213 if (type & MSR_TYPE_W)
4214 /* write-low */
4215 __clear_bit(msr, msr_bitmap + 0x800 / f);
4217 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4218 msr &= 0x1fff;
4219 if (type & MSR_TYPE_R)
4220 /* read-high */
4221 __clear_bit(msr, msr_bitmap + 0x400 / f);
4223 if (type & MSR_TYPE_W)
4224 /* write-high */
4225 __clear_bit(msr, msr_bitmap + 0xc00 / f);
4230 static void __vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
4231 u32 msr, int type)
4233 int f = sizeof(unsigned long);
4235 if (!cpu_has_vmx_msr_bitmap())
4236 return;
4239 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4240 * have the write-low and read-high bitmap offsets the wrong way round.
4241 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4243 if (msr <= 0x1fff) {
4244 if (type & MSR_TYPE_R)
4245 /* read-low */
4246 __set_bit(msr, msr_bitmap + 0x000 / f);
4248 if (type & MSR_TYPE_W)
4249 /* write-low */
4250 __set_bit(msr, msr_bitmap + 0x800 / f);
4252 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4253 msr &= 0x1fff;
4254 if (type & MSR_TYPE_R)
4255 /* read-high */
4256 __set_bit(msr, msr_bitmap + 0x400 / f);
4258 if (type & MSR_TYPE_W)
4259 /* write-high */
4260 __set_bit(msr, msr_bitmap + 0xc00 / f);
4266 * If a msr is allowed by L0, we should check whether it is allowed by L1.
4267 * The corresponding bit will be cleared unless both of L0 and L1 allow it.
4269 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
4270 unsigned long *msr_bitmap_nested,
4271 u32 msr, int type)
4273 int f = sizeof(unsigned long);
4275 if (!cpu_has_vmx_msr_bitmap()) {
4276 WARN_ON(1);
4277 return;
4281 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4282 * have the write-low and read-high bitmap offsets the wrong way round.
4283 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4285 if (msr <= 0x1fff) {
4286 if (type & MSR_TYPE_R &&
4287 !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
4288 /* read-low */
4289 __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
4291 if (type & MSR_TYPE_W &&
4292 !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
4293 /* write-low */
4294 __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
4296 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4297 msr &= 0x1fff;
4298 if (type & MSR_TYPE_R &&
4299 !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
4300 /* read-high */
4301 __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
4303 if (type & MSR_TYPE_W &&
4304 !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
4305 /* write-high */
4306 __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
4311 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
4313 if (!longmode_only)
4314 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
4315 msr, MSR_TYPE_R | MSR_TYPE_W);
4316 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
4317 msr, MSR_TYPE_R | MSR_TYPE_W);
4320 static void vmx_enable_intercept_msr_read_x2apic(u32 msr)
4322 __vmx_enable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4323 msr, MSR_TYPE_R);
4324 __vmx_enable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4325 msr, MSR_TYPE_R);
4328 static void vmx_disable_intercept_msr_read_x2apic(u32 msr)
4330 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4331 msr, MSR_TYPE_R);
4332 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4333 msr, MSR_TYPE_R);
4336 static void vmx_disable_intercept_msr_write_x2apic(u32 msr)
4338 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4339 msr, MSR_TYPE_W);
4340 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4341 msr, MSR_TYPE_W);
4344 static int vmx_vm_has_apicv(struct kvm *kvm)
4346 return enable_apicv && irqchip_in_kernel(kvm);
4349 static int vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
4351 struct vcpu_vmx *vmx = to_vmx(vcpu);
4352 int max_irr;
4353 void *vapic_page;
4354 u16 status;
4356 if (vmx->nested.pi_desc &&
4357 vmx->nested.pi_pending) {
4358 vmx->nested.pi_pending = false;
4359 if (!pi_test_and_clear_on(vmx->nested.pi_desc))
4360 return 0;
4362 max_irr = find_last_bit(
4363 (unsigned long *)vmx->nested.pi_desc->pir, 256);
4365 if (max_irr == 256)
4366 return 0;
4368 vapic_page = kmap(vmx->nested.virtual_apic_page);
4369 if (!vapic_page) {
4370 WARN_ON(1);
4371 return -ENOMEM;
4373 __kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page);
4374 kunmap(vmx->nested.virtual_apic_page);
4376 status = vmcs_read16(GUEST_INTR_STATUS);
4377 if ((u8)max_irr > ((u8)status & 0xff)) {
4378 status &= ~0xff;
4379 status |= (u8)max_irr;
4380 vmcs_write16(GUEST_INTR_STATUS, status);
4383 return 0;
4386 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu)
4388 #ifdef CONFIG_SMP
4389 if (vcpu->mode == IN_GUEST_MODE) {
4390 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
4391 POSTED_INTR_VECTOR);
4392 return true;
4394 #endif
4395 return false;
4398 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4399 int vector)
4401 struct vcpu_vmx *vmx = to_vmx(vcpu);
4403 if (is_guest_mode(vcpu) &&
4404 vector == vmx->nested.posted_intr_nv) {
4405 /* the PIR and ON have been set by L1. */
4406 kvm_vcpu_trigger_posted_interrupt(vcpu);
4408 * If a posted intr is not recognized by hardware,
4409 * we will accomplish it in the next vmentry.
4411 vmx->nested.pi_pending = true;
4412 kvm_make_request(KVM_REQ_EVENT, vcpu);
4413 return 0;
4415 return -1;
4418 * Send interrupt to vcpu via posted interrupt way.
4419 * 1. If target vcpu is running(non-root mode), send posted interrupt
4420 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4421 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4422 * interrupt from PIR in next vmentry.
4424 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4426 struct vcpu_vmx *vmx = to_vmx(vcpu);
4427 int r;
4429 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4430 if (!r)
4431 return;
4433 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4434 return;
4436 r = pi_test_and_set_on(&vmx->pi_desc);
4437 kvm_make_request(KVM_REQ_EVENT, vcpu);
4438 if (r || !kvm_vcpu_trigger_posted_interrupt(vcpu))
4439 kvm_vcpu_kick(vcpu);
4442 static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
4444 struct vcpu_vmx *vmx = to_vmx(vcpu);
4446 if (!pi_test_and_clear_on(&vmx->pi_desc))
4447 return;
4449 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
4452 static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu)
4454 return;
4458 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4459 * will not change in the lifetime of the guest.
4460 * Note that host-state that does change is set elsewhere. E.g., host-state
4461 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4463 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4465 u32 low32, high32;
4466 unsigned long tmpl;
4467 struct desc_ptr dt;
4468 unsigned long cr4;
4470 vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */
4471 vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */
4473 /* Save the most likely value for this task's CR4 in the VMCS. */
4474 cr4 = cr4_read_shadow();
4475 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4476 vmx->host_state.vmcs_host_cr4 = cr4;
4478 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4479 #ifdef CONFIG_X86_64
4481 * Load null selectors, so we can avoid reloading them in
4482 * __vmx_load_host_state(), in case userspace uses the null selectors
4483 * too (the expected case).
4485 vmcs_write16(HOST_DS_SELECTOR, 0);
4486 vmcs_write16(HOST_ES_SELECTOR, 0);
4487 #else
4488 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4489 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4490 #endif
4491 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4492 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4494 native_store_idt(&dt);
4495 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
4496 vmx->host_idt_base = dt.address;
4498 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
4500 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4501 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4502 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4503 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4505 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4506 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4507 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4511 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4513 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
4514 if (enable_ept)
4515 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
4516 if (is_guest_mode(&vmx->vcpu))
4517 vmx->vcpu.arch.cr4_guest_owned_bits &=
4518 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
4519 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
4522 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4524 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4526 if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
4527 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4528 return pin_based_exec_ctrl;
4531 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4533 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4535 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4536 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4538 if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
4539 exec_control &= ~CPU_BASED_TPR_SHADOW;
4540 #ifdef CONFIG_X86_64
4541 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4542 CPU_BASED_CR8_LOAD_EXITING;
4543 #endif
4545 if (!enable_ept)
4546 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4547 CPU_BASED_CR3_LOAD_EXITING |
4548 CPU_BASED_INVLPG_EXITING;
4549 return exec_control;
4552 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4554 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4555 if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
4556 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4557 if (vmx->vpid == 0)
4558 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4559 if (!enable_ept) {
4560 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4561 enable_unrestricted_guest = 0;
4562 /* Enable INVPCID for non-ept guests may cause performance regression. */
4563 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
4565 if (!enable_unrestricted_guest)
4566 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4567 if (!ple_gap)
4568 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4569 if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
4570 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4571 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4572 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4573 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4574 (handle_vmptrld).
4575 We can NOT enable shadow_vmcs here because we don't have yet
4576 a current VMCS12
4578 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4579 /* PML is enabled/disabled in creating/destorying vcpu */
4580 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4582 return exec_control;
4585 static void ept_set_mmio_spte_mask(void)
4588 * EPT Misconfigurations can be generated if the value of bits 2:0
4589 * of an EPT paging-structure entry is 110b (write/execute).
4590 * Also, magic bits (0x3ull << 62) is set to quickly identify mmio
4591 * spte.
4593 kvm_mmu_set_mmio_spte_mask((0x3ull << 62) | 0x6ull);
4596 #define VMX_XSS_EXIT_BITMAP 0
4598 * Sets up the vmcs for emulated real mode.
4600 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
4602 #ifdef CONFIG_X86_64
4603 unsigned long a;
4604 #endif
4605 int i;
4607 /* I/O */
4608 vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
4609 vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
4611 if (enable_shadow_vmcs) {
4612 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
4613 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
4615 if (cpu_has_vmx_msr_bitmap())
4616 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
4618 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4620 /* Control */
4621 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
4623 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
4625 if (cpu_has_secondary_exec_ctrls()) {
4626 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4627 vmx_secondary_exec_control(vmx));
4630 if (vmx_vm_has_apicv(vmx->vcpu.kvm)) {
4631 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4632 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4633 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4634 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4636 vmcs_write16(GUEST_INTR_STATUS, 0);
4638 vmcs_write64(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4639 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4642 if (ple_gap) {
4643 vmcs_write32(PLE_GAP, ple_gap);
4644 vmx->ple_window = ple_window;
4645 vmx->ple_window_dirty = true;
4648 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4649 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4650 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4652 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4653 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4654 vmx_set_constant_host_state(vmx);
4655 #ifdef CONFIG_X86_64
4656 rdmsrl(MSR_FS_BASE, a);
4657 vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
4658 rdmsrl(MSR_GS_BASE, a);
4659 vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
4660 #else
4661 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4662 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4663 #endif
4665 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4666 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4667 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
4668 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4669 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
4671 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4672 u32 msr_low, msr_high;
4673 u64 host_pat;
4674 rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
4675 host_pat = msr_low | ((u64) msr_high << 32);
4676 /* Write the default value follow host pat */
4677 vmcs_write64(GUEST_IA32_PAT, host_pat);
4678 /* Keep arch.pat sync with GUEST_IA32_PAT */
4679 vmx->vcpu.arch.pat = host_pat;
4682 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
4683 u32 index = vmx_msr_index[i];
4684 u32 data_low, data_high;
4685 int j = vmx->nmsrs;
4687 if (rdmsr_safe(index, &data_low, &data_high) < 0)
4688 continue;
4689 if (wrmsr_safe(index, data_low, data_high) < 0)
4690 continue;
4691 vmx->guest_msrs[j].index = i;
4692 vmx->guest_msrs[j].data = 0;
4693 vmx->guest_msrs[j].mask = -1ull;
4694 ++vmx->nmsrs;
4698 vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
4700 /* 22.2.1, 20.8.1 */
4701 vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
4703 vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
4704 set_cr4_guest_host_mask(vmx);
4706 if (vmx_xsaves_supported())
4707 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4709 return 0;
4712 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4714 struct vcpu_vmx *vmx = to_vmx(vcpu);
4715 struct msr_data apic_base_msr;
4717 vmx->rmode.vm86_active = 0;
4719 vmx->soft_vnmi_blocked = 0;
4721 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4722 kvm_set_cr8(&vmx->vcpu, 0);
4723 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE;
4724 if (kvm_vcpu_is_reset_bsp(&vmx->vcpu))
4725 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4726 apic_base_msr.host_initiated = true;
4727 kvm_set_apic_base(&vmx->vcpu, &apic_base_msr);
4729 vmx_segment_cache_clear(vmx);
4731 seg_setup(VCPU_SREG_CS);
4732 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4733 vmcs_write32(GUEST_CS_BASE, 0xffff0000);
4735 seg_setup(VCPU_SREG_DS);
4736 seg_setup(VCPU_SREG_ES);
4737 seg_setup(VCPU_SREG_FS);
4738 seg_setup(VCPU_SREG_GS);
4739 seg_setup(VCPU_SREG_SS);
4741 vmcs_write16(GUEST_TR_SELECTOR, 0);
4742 vmcs_writel(GUEST_TR_BASE, 0);
4743 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4744 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4746 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4747 vmcs_writel(GUEST_LDTR_BASE, 0);
4748 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4749 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4751 vmcs_write32(GUEST_SYSENTER_CS, 0);
4752 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4753 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4755 vmcs_writel(GUEST_RFLAGS, 0x02);
4756 kvm_rip_write(vcpu, 0xfff0);
4758 vmcs_writel(GUEST_GDTR_BASE, 0);
4759 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4761 vmcs_writel(GUEST_IDTR_BASE, 0);
4762 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4764 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4765 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4766 vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4768 /* Special registers */
4769 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4771 setup_msrs(vmx);
4773 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4775 if (cpu_has_vmx_tpr_shadow()) {
4776 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4777 if (vm_need_tpr_shadow(vmx->vcpu.kvm))
4778 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4779 __pa(vmx->vcpu.arch.apic->regs));
4780 vmcs_write32(TPR_THRESHOLD, 0);
4783 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4785 if (vmx_vm_has_apicv(vcpu->kvm))
4786 memset(&vmx->pi_desc, 0, sizeof(struct pi_desc));
4788 if (vmx->vpid != 0)
4789 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4791 vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4792 vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */
4793 vmx_set_cr4(&vmx->vcpu, 0);
4794 vmx_set_efer(&vmx->vcpu, 0);
4795 vmx_fpu_activate(&vmx->vcpu);
4796 update_exception_bitmap(&vmx->vcpu);
4798 vpid_sync_context(vmx);
4802 * In nested virtualization, check if L1 asked to exit on external interrupts.
4803 * For most existing hypervisors, this will always return true.
4805 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
4807 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
4808 PIN_BASED_EXT_INTR_MASK;
4812 * In nested virtualization, check if L1 has set
4813 * VM_EXIT_ACK_INTR_ON_EXIT
4815 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
4817 return get_vmcs12(vcpu)->vm_exit_controls &
4818 VM_EXIT_ACK_INTR_ON_EXIT;
4821 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
4823 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
4824 PIN_BASED_NMI_EXITING;
4827 static void enable_irq_window(struct kvm_vcpu *vcpu)
4829 u32 cpu_based_vm_exec_control;
4831 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4832 cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
4833 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4836 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4838 u32 cpu_based_vm_exec_control;
4840 if (!cpu_has_virtual_nmis() ||
4841 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4842 enable_irq_window(vcpu);
4843 return;
4846 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4847 cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
4848 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4851 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4853 struct vcpu_vmx *vmx = to_vmx(vcpu);
4854 uint32_t intr;
4855 int irq = vcpu->arch.interrupt.nr;
4857 trace_kvm_inj_virq(irq);
4859 ++vcpu->stat.irq_injections;
4860 if (vmx->rmode.vm86_active) {
4861 int inc_eip = 0;
4862 if (vcpu->arch.interrupt.soft)
4863 inc_eip = vcpu->arch.event_exit_inst_len;
4864 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
4865 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4866 return;
4868 intr = irq | INTR_INFO_VALID_MASK;
4869 if (vcpu->arch.interrupt.soft) {
4870 intr |= INTR_TYPE_SOFT_INTR;
4871 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4872 vmx->vcpu.arch.event_exit_inst_len);
4873 } else
4874 intr |= INTR_TYPE_EXT_INTR;
4875 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4878 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4880 struct vcpu_vmx *vmx = to_vmx(vcpu);
4882 if (is_guest_mode(vcpu))
4883 return;
4885 if (!cpu_has_virtual_nmis()) {
4887 * Tracking the NMI-blocked state in software is built upon
4888 * finding the next open IRQ window. This, in turn, depends on
4889 * well-behaving guests: They have to keep IRQs disabled at
4890 * least as long as the NMI handler runs. Otherwise we may
4891 * cause NMI nesting, maybe breaking the guest. But as this is
4892 * highly unlikely, we can live with the residual risk.
4894 vmx->soft_vnmi_blocked = 1;
4895 vmx->vnmi_blocked_time = 0;
4898 ++vcpu->stat.nmi_injections;
4899 vmx->nmi_known_unmasked = false;
4900 if (vmx->rmode.vm86_active) {
4901 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
4902 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4903 return;
4905 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4906 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4909 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4911 if (!cpu_has_virtual_nmis())
4912 return to_vmx(vcpu)->soft_vnmi_blocked;
4913 if (to_vmx(vcpu)->nmi_known_unmasked)
4914 return false;
4915 return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4918 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4920 struct vcpu_vmx *vmx = to_vmx(vcpu);
4922 if (!cpu_has_virtual_nmis()) {
4923 if (vmx->soft_vnmi_blocked != masked) {
4924 vmx->soft_vnmi_blocked = masked;
4925 vmx->vnmi_blocked_time = 0;
4927 } else {
4928 vmx->nmi_known_unmasked = !masked;
4929 if (masked)
4930 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4931 GUEST_INTR_STATE_NMI);
4932 else
4933 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4934 GUEST_INTR_STATE_NMI);
4938 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4940 if (to_vmx(vcpu)->nested.nested_run_pending)
4941 return 0;
4943 if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
4944 return 0;
4946 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4947 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4948 | GUEST_INTR_STATE_NMI));
4951 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4953 return (!to_vmx(vcpu)->nested.nested_run_pending &&
4954 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4955 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4956 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4959 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4961 int ret;
4962 struct kvm_userspace_memory_region tss_mem = {
4963 .slot = TSS_PRIVATE_MEMSLOT,
4964 .guest_phys_addr = addr,
4965 .memory_size = PAGE_SIZE * 3,
4966 .flags = 0,
4969 ret = kvm_set_memory_region(kvm, &tss_mem);
4970 if (ret)
4971 return ret;
4972 kvm->arch.tss_addr = addr;
4973 return init_rmode_tss(kvm);
4976 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4978 switch (vec) {
4979 case BP_VECTOR:
4981 * Update instruction length as we may reinject the exception
4982 * from user space while in guest debugging mode.
4984 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4985 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4986 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4987 return false;
4988 /* fall through */
4989 case DB_VECTOR:
4990 if (vcpu->guest_debug &
4991 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4992 return false;
4993 /* fall through */
4994 case DE_VECTOR:
4995 case OF_VECTOR:
4996 case BR_VECTOR:
4997 case UD_VECTOR:
4998 case DF_VECTOR:
4999 case SS_VECTOR:
5000 case GP_VECTOR:
5001 case MF_VECTOR:
5002 return true;
5003 break;
5005 return false;
5008 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
5009 int vec, u32 err_code)
5012 * Instruction with address size override prefix opcode 0x67
5013 * Cause the #SS fault with 0 error code in VM86 mode.
5015 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5016 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
5017 if (vcpu->arch.halt_request) {
5018 vcpu->arch.halt_request = 0;
5019 return kvm_vcpu_halt(vcpu);
5021 return 1;
5023 return 0;
5027 * Forward all other exceptions that are valid in real mode.
5028 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5029 * the required debugging infrastructure rework.
5031 kvm_queue_exception(vcpu, vec);
5032 return 1;
5036 * Trigger machine check on the host. We assume all the MSRs are already set up
5037 * by the CPU and that we still run on the same CPU as the MCE occurred on.
5038 * We pass a fake environment to the machine check handler because we want
5039 * the guest to be always treated like user space, no matter what context
5040 * it used internally.
5042 static void kvm_machine_check(void)
5044 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
5045 struct pt_regs regs = {
5046 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
5047 .flags = X86_EFLAGS_IF,
5050 do_machine_check(&regs, 0);
5051 #endif
5054 static int handle_machine_check(struct kvm_vcpu *vcpu)
5056 /* already handled by vcpu_run */
5057 return 1;
5060 static int handle_exception(struct kvm_vcpu *vcpu)
5062 struct vcpu_vmx *vmx = to_vmx(vcpu);
5063 struct kvm_run *kvm_run = vcpu->run;
5064 u32 intr_info, ex_no, error_code;
5065 unsigned long cr2, rip, dr6;
5066 u32 vect_info;
5067 enum emulation_result er;
5069 vect_info = vmx->idt_vectoring_info;
5070 intr_info = vmx->exit_intr_info;
5072 if (is_machine_check(intr_info))
5073 return handle_machine_check(vcpu);
5075 if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
5076 return 1; /* already handled by vmx_vcpu_run() */
5078 if (is_no_device(intr_info)) {
5079 vmx_fpu_activate(vcpu);
5080 return 1;
5083 if (is_invalid_opcode(intr_info)) {
5084 if (is_guest_mode(vcpu)) {
5085 kvm_queue_exception(vcpu, UD_VECTOR);
5086 return 1;
5088 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
5089 if (er != EMULATE_DONE)
5090 kvm_queue_exception(vcpu, UD_VECTOR);
5091 return 1;
5094 error_code = 0;
5095 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5096 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5099 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5100 * MMIO, it is better to report an internal error.
5101 * See the comments in vmx_handle_exit.
5103 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5104 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5105 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5106 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5107 vcpu->run->internal.ndata = 3;
5108 vcpu->run->internal.data[0] = vect_info;
5109 vcpu->run->internal.data[1] = intr_info;
5110 vcpu->run->internal.data[2] = error_code;
5111 return 0;
5114 if (is_page_fault(intr_info)) {
5115 /* EPT won't cause page fault directly */
5116 BUG_ON(enable_ept);
5117 cr2 = vmcs_readl(EXIT_QUALIFICATION);
5118 trace_kvm_page_fault(cr2, error_code);
5120 if (kvm_event_needs_reinjection(vcpu))
5121 kvm_mmu_unprotect_page_virt(vcpu, cr2);
5122 return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
5125 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5127 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5128 return handle_rmode_exception(vcpu, ex_no, error_code);
5130 switch (ex_no) {
5131 case AC_VECTOR:
5132 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5133 return 1;
5134 case DB_VECTOR:
5135 dr6 = vmcs_readl(EXIT_QUALIFICATION);
5136 if (!(vcpu->guest_debug &
5137 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5138 vcpu->arch.dr6 &= ~15;
5139 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5140 if (!(dr6 & ~DR6_RESERVED)) /* icebp */
5141 skip_emulated_instruction(vcpu);
5143 kvm_queue_exception(vcpu, DB_VECTOR);
5144 return 1;
5146 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
5147 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5148 /* fall through */
5149 case BP_VECTOR:
5151 * Update instruction length as we may reinject #BP from
5152 * user space while in guest debugging mode. Reading it for
5153 * #DB as well causes no harm, it is not used in that case.
5155 vmx->vcpu.arch.event_exit_inst_len =
5156 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5157 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5158 rip = kvm_rip_read(vcpu);
5159 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
5160 kvm_run->debug.arch.exception = ex_no;
5161 break;
5162 default:
5163 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5164 kvm_run->ex.exception = ex_no;
5165 kvm_run->ex.error_code = error_code;
5166 break;
5168 return 0;
5171 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
5173 ++vcpu->stat.irq_exits;
5174 return 1;
5177 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5179 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5180 return 0;
5183 static int handle_io(struct kvm_vcpu *vcpu)
5185 unsigned long exit_qualification;
5186 int size, in, string;
5187 unsigned port;
5189 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5190 string = (exit_qualification & 16) != 0;
5191 in = (exit_qualification & 8) != 0;
5193 ++vcpu->stat.io_exits;
5195 if (string || in)
5196 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5198 port = exit_qualification >> 16;
5199 size = (exit_qualification & 7) + 1;
5200 skip_emulated_instruction(vcpu);
5202 return kvm_fast_pio_out(vcpu, size, port);
5205 static void
5206 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5209 * Patch in the VMCALL instruction:
5211 hypercall[0] = 0x0f;
5212 hypercall[1] = 0x01;
5213 hypercall[2] = 0xc1;
5216 static bool nested_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5218 unsigned long always_on = VMXON_CR0_ALWAYSON;
5219 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5221 if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
5222 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
5223 nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
5224 always_on &= ~(X86_CR0_PE | X86_CR0_PG);
5225 return (val & always_on) == always_on;
5228 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5229 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5231 if (is_guest_mode(vcpu)) {
5232 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5233 unsigned long orig_val = val;
5236 * We get here when L2 changed cr0 in a way that did not change
5237 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5238 * but did change L0 shadowed bits. So we first calculate the
5239 * effective cr0 value that L1 would like to write into the
5240 * hardware. It consists of the L2-owned bits from the new
5241 * value combined with the L1-owned bits from L1's guest_cr0.
5243 val = (val & ~vmcs12->cr0_guest_host_mask) |
5244 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5246 if (!nested_cr0_valid(vcpu, val))
5247 return 1;
5249 if (kvm_set_cr0(vcpu, val))
5250 return 1;
5251 vmcs_writel(CR0_READ_SHADOW, orig_val);
5252 return 0;
5253 } else {
5254 if (to_vmx(vcpu)->nested.vmxon &&
5255 ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
5256 return 1;
5257 return kvm_set_cr0(vcpu, val);
5261 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5263 if (is_guest_mode(vcpu)) {
5264 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5265 unsigned long orig_val = val;
5267 /* analogously to handle_set_cr0 */
5268 val = (val & ~vmcs12->cr4_guest_host_mask) |
5269 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5270 if (kvm_set_cr4(vcpu, val))
5271 return 1;
5272 vmcs_writel(CR4_READ_SHADOW, orig_val);
5273 return 0;
5274 } else
5275 return kvm_set_cr4(vcpu, val);
5278 /* called to set cr0 as approriate for clts instruction exit. */
5279 static void handle_clts(struct kvm_vcpu *vcpu)
5281 if (is_guest_mode(vcpu)) {
5283 * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
5284 * but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
5285 * just pretend it's off (also in arch.cr0 for fpu_activate).
5287 vmcs_writel(CR0_READ_SHADOW,
5288 vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
5289 vcpu->arch.cr0 &= ~X86_CR0_TS;
5290 } else
5291 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5294 static int handle_cr(struct kvm_vcpu *vcpu)
5296 unsigned long exit_qualification, val;
5297 int cr;
5298 int reg;
5299 int err;
5301 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5302 cr = exit_qualification & 15;
5303 reg = (exit_qualification >> 8) & 15;
5304 switch ((exit_qualification >> 4) & 3) {
5305 case 0: /* mov to cr */
5306 val = kvm_register_readl(vcpu, reg);
5307 trace_kvm_cr_write(cr, val);
5308 switch (cr) {
5309 case 0:
5310 err = handle_set_cr0(vcpu, val);
5311 kvm_complete_insn_gp(vcpu, err);
5312 return 1;
5313 case 3:
5314 err = kvm_set_cr3(vcpu, val);
5315 kvm_complete_insn_gp(vcpu, err);
5316 return 1;
5317 case 4:
5318 err = handle_set_cr4(vcpu, val);
5319 kvm_complete_insn_gp(vcpu, err);
5320 return 1;
5321 case 8: {
5322 u8 cr8_prev = kvm_get_cr8(vcpu);
5323 u8 cr8 = (u8)val;
5324 err = kvm_set_cr8(vcpu, cr8);
5325 kvm_complete_insn_gp(vcpu, err);
5326 if (irqchip_in_kernel(vcpu->kvm))
5327 return 1;
5328 if (cr8_prev <= cr8)
5329 return 1;
5330 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5331 return 0;
5334 break;
5335 case 2: /* clts */
5336 handle_clts(vcpu);
5337 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5338 skip_emulated_instruction(vcpu);
5339 vmx_fpu_activate(vcpu);
5340 return 1;
5341 case 1: /*mov from cr*/
5342 switch (cr) {
5343 case 3:
5344 val = kvm_read_cr3(vcpu);
5345 kvm_register_write(vcpu, reg, val);
5346 trace_kvm_cr_read(cr, val);
5347 skip_emulated_instruction(vcpu);
5348 return 1;
5349 case 8:
5350 val = kvm_get_cr8(vcpu);
5351 kvm_register_write(vcpu, reg, val);
5352 trace_kvm_cr_read(cr, val);
5353 skip_emulated_instruction(vcpu);
5354 return 1;
5356 break;
5357 case 3: /* lmsw */
5358 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5359 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5360 kvm_lmsw(vcpu, val);
5362 skip_emulated_instruction(vcpu);
5363 return 1;
5364 default:
5365 break;
5367 vcpu->run->exit_reason = 0;
5368 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5369 (int)(exit_qualification >> 4) & 3, cr);
5370 return 0;
5373 static int handle_dr(struct kvm_vcpu *vcpu)
5375 unsigned long exit_qualification;
5376 int dr, dr7, reg;
5378 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5379 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5381 /* First, if DR does not exist, trigger UD */
5382 if (!kvm_require_dr(vcpu, dr))
5383 return 1;
5385 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
5386 if (!kvm_require_cpl(vcpu, 0))
5387 return 1;
5388 dr7 = vmcs_readl(GUEST_DR7);
5389 if (dr7 & DR7_GD) {
5391 * As the vm-exit takes precedence over the debug trap, we
5392 * need to emulate the latter, either for the host or the
5393 * guest debugging itself.
5395 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5396 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
5397 vcpu->run->debug.arch.dr7 = dr7;
5398 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5399 vcpu->run->debug.arch.exception = DB_VECTOR;
5400 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5401 return 0;
5402 } else {
5403 vcpu->arch.dr6 &= ~15;
5404 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
5405 kvm_queue_exception(vcpu, DB_VECTOR);
5406 return 1;
5410 if (vcpu->guest_debug == 0) {
5411 u32 cpu_based_vm_exec_control;
5413 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5414 cpu_based_vm_exec_control &= ~CPU_BASED_MOV_DR_EXITING;
5415 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5418 * No more DR vmexits; force a reload of the debug registers
5419 * and reenter on this instruction. The next vmexit will
5420 * retrieve the full state of the debug registers.
5422 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5423 return 1;
5426 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5427 if (exit_qualification & TYPE_MOV_FROM_DR) {
5428 unsigned long val;
5430 if (kvm_get_dr(vcpu, dr, &val))
5431 return 1;
5432 kvm_register_write(vcpu, reg, val);
5433 } else
5434 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
5435 return 1;
5437 skip_emulated_instruction(vcpu);
5438 return 1;
5441 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
5443 return vcpu->arch.dr6;
5446 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
5450 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5452 u32 cpu_based_vm_exec_control;
5454 get_debugreg(vcpu->arch.db[0], 0);
5455 get_debugreg(vcpu->arch.db[1], 1);
5456 get_debugreg(vcpu->arch.db[2], 2);
5457 get_debugreg(vcpu->arch.db[3], 3);
5458 get_debugreg(vcpu->arch.dr6, 6);
5459 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5461 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5463 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5464 cpu_based_vm_exec_control |= CPU_BASED_MOV_DR_EXITING;
5465 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5468 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5470 vmcs_writel(GUEST_DR7, val);
5473 static int handle_cpuid(struct kvm_vcpu *vcpu)
5475 kvm_emulate_cpuid(vcpu);
5476 return 1;
5479 static int handle_rdmsr(struct kvm_vcpu *vcpu)
5481 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
5482 u64 data;
5484 if (vmx_get_msr(vcpu, ecx, &data)) {
5485 trace_kvm_msr_read_ex(ecx);
5486 kvm_inject_gp(vcpu, 0);
5487 return 1;
5490 trace_kvm_msr_read(ecx, data);
5492 /* FIXME: handling of bits 32:63 of rax, rdx */
5493 vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u;
5494 vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
5495 skip_emulated_instruction(vcpu);
5496 return 1;
5499 static int handle_wrmsr(struct kvm_vcpu *vcpu)
5501 struct msr_data msr;
5502 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
5503 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
5504 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
5506 msr.data = data;
5507 msr.index = ecx;
5508 msr.host_initiated = false;
5509 if (kvm_set_msr(vcpu, &msr) != 0) {
5510 trace_kvm_msr_write_ex(ecx, data);
5511 kvm_inject_gp(vcpu, 0);
5512 return 1;
5515 trace_kvm_msr_write(ecx, data);
5516 skip_emulated_instruction(vcpu);
5517 return 1;
5520 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5522 kvm_make_request(KVM_REQ_EVENT, vcpu);
5523 return 1;
5526 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5528 u32 cpu_based_vm_exec_control;
5530 /* clear pending irq */
5531 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5532 cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
5533 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5535 kvm_make_request(KVM_REQ_EVENT, vcpu);
5537 ++vcpu->stat.irq_window_exits;
5540 * If the user space waits to inject interrupts, exit as soon as
5541 * possible
5543 if (!irqchip_in_kernel(vcpu->kvm) &&
5544 vcpu->run->request_interrupt_window &&
5545 !kvm_cpu_has_interrupt(vcpu)) {
5546 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
5547 return 0;
5549 return 1;
5552 static int handle_halt(struct kvm_vcpu *vcpu)
5554 return kvm_emulate_halt(vcpu);
5557 static int handle_vmcall(struct kvm_vcpu *vcpu)
5559 kvm_emulate_hypercall(vcpu);
5560 return 1;
5563 static int handle_invd(struct kvm_vcpu *vcpu)
5565 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5568 static int handle_invlpg(struct kvm_vcpu *vcpu)
5570 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5572 kvm_mmu_invlpg(vcpu, exit_qualification);
5573 skip_emulated_instruction(vcpu);
5574 return 1;
5577 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5579 int err;
5581 err = kvm_rdpmc(vcpu);
5582 kvm_complete_insn_gp(vcpu, err);
5584 return 1;
5587 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5589 kvm_emulate_wbinvd(vcpu);
5590 return 1;
5593 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5595 u64 new_bv = kvm_read_edx_eax(vcpu);
5596 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
5598 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5599 skip_emulated_instruction(vcpu);
5600 return 1;
5603 static int handle_xsaves(struct kvm_vcpu *vcpu)
5605 skip_emulated_instruction(vcpu);
5606 WARN(1, "this should never happen\n");
5607 return 1;
5610 static int handle_xrstors(struct kvm_vcpu *vcpu)
5612 skip_emulated_instruction(vcpu);
5613 WARN(1, "this should never happen\n");
5614 return 1;
5617 static int handle_apic_access(struct kvm_vcpu *vcpu)
5619 if (likely(fasteoi)) {
5620 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5621 int access_type, offset;
5623 access_type = exit_qualification & APIC_ACCESS_TYPE;
5624 offset = exit_qualification & APIC_ACCESS_OFFSET;
5626 * Sane guest uses MOV to write EOI, with written value
5627 * not cared. So make a short-circuit here by avoiding
5628 * heavy instruction emulation.
5630 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5631 (offset == APIC_EOI)) {
5632 kvm_lapic_set_eoi(vcpu);
5633 skip_emulated_instruction(vcpu);
5634 return 1;
5637 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5640 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5642 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5643 int vector = exit_qualification & 0xff;
5645 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5646 kvm_apic_set_eoi_accelerated(vcpu, vector);
5647 return 1;
5650 static int handle_apic_write(struct kvm_vcpu *vcpu)
5652 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5653 u32 offset = exit_qualification & 0xfff;
5655 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5656 kvm_apic_write_nodecode(vcpu, offset);
5657 return 1;
5660 static int handle_task_switch(struct kvm_vcpu *vcpu)
5662 struct vcpu_vmx *vmx = to_vmx(vcpu);
5663 unsigned long exit_qualification;
5664 bool has_error_code = false;
5665 u32 error_code = 0;
5666 u16 tss_selector;
5667 int reason, type, idt_v, idt_index;
5669 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5670 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5671 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5673 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5675 reason = (u32)exit_qualification >> 30;
5676 if (reason == TASK_SWITCH_GATE && idt_v) {
5677 switch (type) {
5678 case INTR_TYPE_NMI_INTR:
5679 vcpu->arch.nmi_injected = false;
5680 vmx_set_nmi_mask(vcpu, true);
5681 break;
5682 case INTR_TYPE_EXT_INTR:
5683 case INTR_TYPE_SOFT_INTR:
5684 kvm_clear_interrupt_queue(vcpu);
5685 break;
5686 case INTR_TYPE_HARD_EXCEPTION:
5687 if (vmx->idt_vectoring_info &
5688 VECTORING_INFO_DELIVER_CODE_MASK) {
5689 has_error_code = true;
5690 error_code =
5691 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5693 /* fall through */
5694 case INTR_TYPE_SOFT_EXCEPTION:
5695 kvm_clear_exception_queue(vcpu);
5696 break;
5697 default:
5698 break;
5701 tss_selector = exit_qualification;
5703 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5704 type != INTR_TYPE_EXT_INTR &&
5705 type != INTR_TYPE_NMI_INTR))
5706 skip_emulated_instruction(vcpu);
5708 if (kvm_task_switch(vcpu, tss_selector,
5709 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
5710 has_error_code, error_code) == EMULATE_FAIL) {
5711 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5712 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5713 vcpu->run->internal.ndata = 0;
5714 return 0;
5717 /* clear all local breakpoint enable flags */
5718 vmcs_writel(GUEST_DR7, vmcs_readl(GUEST_DR7) & ~0x155);
5721 * TODO: What about debug traps on tss switch?
5722 * Are we supposed to inject them and update dr6?
5725 return 1;
5728 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5730 unsigned long exit_qualification;
5731 gpa_t gpa;
5732 u32 error_code;
5733 int gla_validity;
5735 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5737 gla_validity = (exit_qualification >> 7) & 0x3;
5738 if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) {
5739 printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
5740 printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
5741 (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
5742 vmcs_readl(GUEST_LINEAR_ADDRESS));
5743 printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
5744 (long unsigned int)exit_qualification);
5745 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5746 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
5747 return 0;
5751 * EPT violation happened while executing iret from NMI,
5752 * "blocked by NMI" bit has to be set before next VM entry.
5753 * There are errata that may cause this bit to not be set:
5754 * AAK134, BY25.
5756 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5757 cpu_has_virtual_nmis() &&
5758 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5759 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5761 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5762 trace_kvm_page_fault(gpa, exit_qualification);
5764 /* It is a write fault? */
5765 error_code = exit_qualification & PFERR_WRITE_MASK;
5766 /* It is a fetch fault? */
5767 error_code |= (exit_qualification << 2) & PFERR_FETCH_MASK;
5768 /* ept page table is present? */
5769 error_code |= (exit_qualification >> 3) & PFERR_PRESENT_MASK;
5771 vcpu->arch.exit_qualification = exit_qualification;
5773 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5776 static u64 ept_rsvd_mask(u64 spte, int level)
5778 int i;
5779 u64 mask = 0;
5781 for (i = 51; i > boot_cpu_data.x86_phys_bits; i--)
5782 mask |= (1ULL << i);
5784 if (level == 4)
5785 /* bits 7:3 reserved */
5786 mask |= 0xf8;
5787 else if (spte & (1ULL << 7))
5789 * 1GB/2MB page, bits 29:12 or 20:12 reserved respectively,
5790 * level == 1 if the hypervisor is using the ignored bit 7.
5792 mask |= (PAGE_SIZE << ((level - 1) * 9)) - PAGE_SIZE;
5793 else if (level > 1)
5794 /* bits 6:3 reserved */
5795 mask |= 0x78;
5797 return mask;
5800 static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
5801 int level)
5803 printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level);
5805 /* 010b (write-only) */
5806 WARN_ON((spte & 0x7) == 0x2);
5808 /* 110b (write/execute) */
5809 WARN_ON((spte & 0x7) == 0x6);
5811 /* 100b (execute-only) and value not supported by logical processor */
5812 if (!cpu_has_vmx_ept_execute_only())
5813 WARN_ON((spte & 0x7) == 0x4);
5815 /* not 000b */
5816 if ((spte & 0x7)) {
5817 u64 rsvd_bits = spte & ept_rsvd_mask(spte, level);
5819 if (rsvd_bits != 0) {
5820 printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n",
5821 __func__, rsvd_bits);
5822 WARN_ON(1);
5825 /* bits 5:3 are _not_ reserved for large page or leaf page */
5826 if ((rsvd_bits & 0x38) == 0) {
5827 u64 ept_mem_type = (spte & 0x38) >> 3;
5829 if (ept_mem_type == 2 || ept_mem_type == 3 ||
5830 ept_mem_type == 7) {
5831 printk(KERN_ERR "%s: ept_mem_type=0x%llx\n",
5832 __func__, ept_mem_type);
5833 WARN_ON(1);
5839 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5841 u64 sptes[4];
5842 int nr_sptes, i, ret;
5843 gpa_t gpa;
5845 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5846 if (!kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5847 skip_emulated_instruction(vcpu);
5848 return 1;
5851 ret = handle_mmio_page_fault_common(vcpu, gpa, true);
5852 if (likely(ret == RET_MMIO_PF_EMULATE))
5853 return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
5854 EMULATE_DONE;
5856 if (unlikely(ret == RET_MMIO_PF_INVALID))
5857 return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0);
5859 if (unlikely(ret == RET_MMIO_PF_RETRY))
5860 return 1;
5862 /* It is the real ept misconfig */
5863 printk(KERN_ERR "EPT: Misconfiguration.\n");
5864 printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa);
5866 nr_sptes = kvm_mmu_get_spte_hierarchy(vcpu, gpa, sptes);
5868 for (i = PT64_ROOT_LEVEL; i > PT64_ROOT_LEVEL - nr_sptes; --i)
5869 ept_misconfig_inspect_spte(vcpu, sptes[i-1], i);
5871 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5872 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
5874 return 0;
5877 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5879 u32 cpu_based_vm_exec_control;
5881 /* clear pending NMI */
5882 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5883 cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
5884 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5885 ++vcpu->stat.nmi_window_exits;
5886 kvm_make_request(KVM_REQ_EVENT, vcpu);
5888 return 1;
5891 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5893 struct vcpu_vmx *vmx = to_vmx(vcpu);
5894 enum emulation_result err = EMULATE_DONE;
5895 int ret = 1;
5896 u32 cpu_exec_ctrl;
5897 bool intr_window_requested;
5898 unsigned count = 130;
5900 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5901 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
5903 while (vmx->emulation_required && count-- != 0) {
5904 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5905 return handle_interrupt_window(&vmx->vcpu);
5907 if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
5908 return 1;
5910 err = emulate_instruction(vcpu, EMULTYPE_NO_REEXECUTE);
5912 if (err == EMULATE_USER_EXIT) {
5913 ++vcpu->stat.mmio_exits;
5914 ret = 0;
5915 goto out;
5918 if (err != EMULATE_DONE) {
5919 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5920 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5921 vcpu->run->internal.ndata = 0;
5922 return 0;
5925 if (vcpu->arch.halt_request) {
5926 vcpu->arch.halt_request = 0;
5927 ret = kvm_vcpu_halt(vcpu);
5928 goto out;
5931 if (signal_pending(current))
5932 goto out;
5933 if (need_resched())
5934 schedule();
5937 out:
5938 return ret;
5941 static int __grow_ple_window(int val)
5943 if (ple_window_grow < 1)
5944 return ple_window;
5946 val = min(val, ple_window_actual_max);
5948 if (ple_window_grow < ple_window)
5949 val *= ple_window_grow;
5950 else
5951 val += ple_window_grow;
5953 return val;
5956 static int __shrink_ple_window(int val, int modifier, int minimum)
5958 if (modifier < 1)
5959 return ple_window;
5961 if (modifier < ple_window)
5962 val /= modifier;
5963 else
5964 val -= modifier;
5966 return max(val, minimum);
5969 static void grow_ple_window(struct kvm_vcpu *vcpu)
5971 struct vcpu_vmx *vmx = to_vmx(vcpu);
5972 int old = vmx->ple_window;
5974 vmx->ple_window = __grow_ple_window(old);
5976 if (vmx->ple_window != old)
5977 vmx->ple_window_dirty = true;
5979 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
5982 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5984 struct vcpu_vmx *vmx = to_vmx(vcpu);
5985 int old = vmx->ple_window;
5987 vmx->ple_window = __shrink_ple_window(old,
5988 ple_window_shrink, ple_window);
5990 if (vmx->ple_window != old)
5991 vmx->ple_window_dirty = true;
5993 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
5997 * ple_window_actual_max is computed to be one grow_ple_window() below
5998 * ple_window_max. (See __grow_ple_window for the reason.)
5999 * This prevents overflows, because ple_window_max is int.
6000 * ple_window_max effectively rounded down to a multiple of ple_window_grow in
6001 * this process.
6002 * ple_window_max is also prevented from setting vmx->ple_window < ple_window.
6004 static void update_ple_window_actual_max(void)
6006 ple_window_actual_max =
6007 __shrink_ple_window(max(ple_window_max, ple_window),
6008 ple_window_grow, INT_MIN);
6011 static __init int hardware_setup(void)
6013 int r = -ENOMEM, i, msr;
6015 rdmsrl_safe(MSR_EFER, &host_efer);
6017 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
6018 kvm_define_shared_msr(i, vmx_msr_index[i]);
6020 vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
6021 if (!vmx_io_bitmap_a)
6022 return r;
6024 vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
6025 if (!vmx_io_bitmap_b)
6026 goto out;
6028 vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);
6029 if (!vmx_msr_bitmap_legacy)
6030 goto out1;
6032 vmx_msr_bitmap_legacy_x2apic =
6033 (unsigned long *)__get_free_page(GFP_KERNEL);
6034 if (!vmx_msr_bitmap_legacy_x2apic)
6035 goto out2;
6037 vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);
6038 if (!vmx_msr_bitmap_longmode)
6039 goto out3;
6041 vmx_msr_bitmap_longmode_x2apic =
6042 (unsigned long *)__get_free_page(GFP_KERNEL);
6043 if (!vmx_msr_bitmap_longmode_x2apic)
6044 goto out4;
6046 if (nested) {
6047 vmx_msr_bitmap_nested =
6048 (unsigned long *)__get_free_page(GFP_KERNEL);
6049 if (!vmx_msr_bitmap_nested)
6050 goto out5;
6053 vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
6054 if (!vmx_vmread_bitmap)
6055 goto out6;
6057 vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
6058 if (!vmx_vmwrite_bitmap)
6059 goto out7;
6061 memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
6062 memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
6065 * Allow direct access to the PC debug port (it is often used for I/O
6066 * delays, but the vmexits simply slow things down).
6068 memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
6069 clear_bit(0x80, vmx_io_bitmap_a);
6071 memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
6073 memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
6074 memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
6075 if (nested)
6076 memset(vmx_msr_bitmap_nested, 0xff, PAGE_SIZE);
6078 if (setup_vmcs_config(&vmcs_config) < 0) {
6079 r = -EIO;
6080 goto out8;
6083 if (boot_cpu_has(X86_FEATURE_NX))
6084 kvm_enable_efer_bits(EFER_NX);
6086 if (!cpu_has_vmx_vpid())
6087 enable_vpid = 0;
6088 if (!cpu_has_vmx_shadow_vmcs())
6089 enable_shadow_vmcs = 0;
6090 if (enable_shadow_vmcs)
6091 init_vmcs_shadow_fields();
6093 if (!cpu_has_vmx_ept() ||
6094 !cpu_has_vmx_ept_4levels()) {
6095 enable_ept = 0;
6096 enable_unrestricted_guest = 0;
6097 enable_ept_ad_bits = 0;
6100 if (!cpu_has_vmx_ept_ad_bits())
6101 enable_ept_ad_bits = 0;
6103 if (!cpu_has_vmx_unrestricted_guest())
6104 enable_unrestricted_guest = 0;
6106 if (!cpu_has_vmx_flexpriority())
6107 flexpriority_enabled = 0;
6110 * set_apic_access_page_addr() is used to reload apic access
6111 * page upon invalidation. No need to do anything if not
6112 * using the APIC_ACCESS_ADDR VMCS field.
6114 if (!flexpriority_enabled)
6115 kvm_x86_ops->set_apic_access_page_addr = NULL;
6117 if (!cpu_has_vmx_tpr_shadow())
6118 kvm_x86_ops->update_cr8_intercept = NULL;
6120 if (enable_ept && !cpu_has_vmx_ept_2m_page())
6121 kvm_disable_largepages();
6123 if (!cpu_has_vmx_ple())
6124 ple_gap = 0;
6126 if (!cpu_has_vmx_apicv())
6127 enable_apicv = 0;
6129 if (enable_apicv)
6130 kvm_x86_ops->update_cr8_intercept = NULL;
6131 else {
6132 kvm_x86_ops->hwapic_irr_update = NULL;
6133 kvm_x86_ops->hwapic_isr_update = NULL;
6134 kvm_x86_ops->deliver_posted_interrupt = NULL;
6135 kvm_x86_ops->sync_pir_to_irr = vmx_sync_pir_to_irr_dummy;
6138 vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
6139 vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
6140 vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
6141 vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
6142 vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
6143 vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
6144 vmx_disable_intercept_for_msr(MSR_IA32_BNDCFGS, true);
6146 memcpy(vmx_msr_bitmap_legacy_x2apic,
6147 vmx_msr_bitmap_legacy, PAGE_SIZE);
6148 memcpy(vmx_msr_bitmap_longmode_x2apic,
6149 vmx_msr_bitmap_longmode, PAGE_SIZE);
6151 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
6153 if (enable_apicv) {
6154 for (msr = 0x800; msr <= 0x8ff; msr++)
6155 vmx_disable_intercept_msr_read_x2apic(msr);
6157 /* According SDM, in x2apic mode, the whole id reg is used.
6158 * But in KVM, it only use the highest eight bits. Need to
6159 * intercept it */
6160 vmx_enable_intercept_msr_read_x2apic(0x802);
6161 /* TMCCT */
6162 vmx_enable_intercept_msr_read_x2apic(0x839);
6163 /* TPR */
6164 vmx_disable_intercept_msr_write_x2apic(0x808);
6165 /* EOI */
6166 vmx_disable_intercept_msr_write_x2apic(0x80b);
6167 /* SELF-IPI */
6168 vmx_disable_intercept_msr_write_x2apic(0x83f);
6171 if (enable_ept) {
6172 kvm_mmu_set_mask_ptes(0ull,
6173 (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
6174 (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
6175 0ull, VMX_EPT_EXECUTABLE_MASK);
6176 ept_set_mmio_spte_mask();
6177 kvm_enable_tdp();
6178 } else
6179 kvm_disable_tdp();
6181 update_ple_window_actual_max();
6184 * Only enable PML when hardware supports PML feature, and both EPT
6185 * and EPT A/D bit features are enabled -- PML depends on them to work.
6187 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
6188 enable_pml = 0;
6190 if (!enable_pml) {
6191 kvm_x86_ops->slot_enable_log_dirty = NULL;
6192 kvm_x86_ops->slot_disable_log_dirty = NULL;
6193 kvm_x86_ops->flush_log_dirty = NULL;
6194 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
6197 return alloc_kvm_area();
6199 out8:
6200 free_page((unsigned long)vmx_vmwrite_bitmap);
6201 out7:
6202 free_page((unsigned long)vmx_vmread_bitmap);
6203 out6:
6204 if (nested)
6205 free_page((unsigned long)vmx_msr_bitmap_nested);
6206 out5:
6207 free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
6208 out4:
6209 free_page((unsigned long)vmx_msr_bitmap_longmode);
6210 out3:
6211 free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
6212 out2:
6213 free_page((unsigned long)vmx_msr_bitmap_legacy);
6214 out1:
6215 free_page((unsigned long)vmx_io_bitmap_b);
6216 out:
6217 free_page((unsigned long)vmx_io_bitmap_a);
6219 return r;
6222 static __exit void hardware_unsetup(void)
6224 free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
6225 free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
6226 free_page((unsigned long)vmx_msr_bitmap_legacy);
6227 free_page((unsigned long)vmx_msr_bitmap_longmode);
6228 free_page((unsigned long)vmx_io_bitmap_b);
6229 free_page((unsigned long)vmx_io_bitmap_a);
6230 free_page((unsigned long)vmx_vmwrite_bitmap);
6231 free_page((unsigned long)vmx_vmread_bitmap);
6232 if (nested)
6233 free_page((unsigned long)vmx_msr_bitmap_nested);
6235 free_kvm_area();
6239 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
6240 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
6242 static int handle_pause(struct kvm_vcpu *vcpu)
6244 if (ple_gap)
6245 grow_ple_window(vcpu);
6247 skip_emulated_instruction(vcpu);
6248 kvm_vcpu_on_spin(vcpu);
6250 return 1;
6253 static int handle_nop(struct kvm_vcpu *vcpu)
6255 skip_emulated_instruction(vcpu);
6256 return 1;
6259 static int handle_mwait(struct kvm_vcpu *vcpu)
6261 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
6262 return handle_nop(vcpu);
6265 static int handle_monitor(struct kvm_vcpu *vcpu)
6267 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
6268 return handle_nop(vcpu);
6272 * To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
6273 * We could reuse a single VMCS for all the L2 guests, but we also want the
6274 * option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
6275 * allows keeping them loaded on the processor, and in the future will allow
6276 * optimizations where prepare_vmcs02 doesn't need to set all the fields on
6277 * every entry if they never change.
6278 * So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
6279 * (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
6281 * The following functions allocate and free a vmcs02 in this pool.
6284 /* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
6285 static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
6287 struct vmcs02_list *item;
6288 list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
6289 if (item->vmptr == vmx->nested.current_vmptr) {
6290 list_move(&item->list, &vmx->nested.vmcs02_pool);
6291 return &item->vmcs02;
6294 if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
6295 /* Recycle the least recently used VMCS. */
6296 item = list_entry(vmx->nested.vmcs02_pool.prev,
6297 struct vmcs02_list, list);
6298 item->vmptr = vmx->nested.current_vmptr;
6299 list_move(&item->list, &vmx->nested.vmcs02_pool);
6300 return &item->vmcs02;
6303 /* Create a new VMCS */
6304 item = kmalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
6305 if (!item)
6306 return NULL;
6307 item->vmcs02.vmcs = alloc_vmcs();
6308 if (!item->vmcs02.vmcs) {
6309 kfree(item);
6310 return NULL;
6312 loaded_vmcs_init(&item->vmcs02);
6313 item->vmptr = vmx->nested.current_vmptr;
6314 list_add(&(item->list), &(vmx->nested.vmcs02_pool));
6315 vmx->nested.vmcs02_num++;
6316 return &item->vmcs02;
6319 /* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
6320 static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
6322 struct vmcs02_list *item;
6323 list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
6324 if (item->vmptr == vmptr) {
6325 free_loaded_vmcs(&item->vmcs02);
6326 list_del(&item->list);
6327 kfree(item);
6328 vmx->nested.vmcs02_num--;
6329 return;
6334 * Free all VMCSs saved for this vcpu, except the one pointed by
6335 * vmx->loaded_vmcs. We must be running L1, so vmx->loaded_vmcs
6336 * must be &vmx->vmcs01.
6338 static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
6340 struct vmcs02_list *item, *n;
6342 WARN_ON(vmx->loaded_vmcs != &vmx->vmcs01);
6343 list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
6345 * Something will leak if the above WARN triggers. Better than
6346 * a use-after-free.
6348 if (vmx->loaded_vmcs == &item->vmcs02)
6349 continue;
6351 free_loaded_vmcs(&item->vmcs02);
6352 list_del(&item->list);
6353 kfree(item);
6354 vmx->nested.vmcs02_num--;
6359 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
6360 * set the success or error code of an emulated VMX instruction, as specified
6361 * by Vol 2B, VMX Instruction Reference, "Conventions".
6363 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
6365 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
6366 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
6367 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
6370 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
6372 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
6373 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
6374 X86_EFLAGS_SF | X86_EFLAGS_OF))
6375 | X86_EFLAGS_CF);
6378 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
6379 u32 vm_instruction_error)
6381 if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
6383 * failValid writes the error number to the current VMCS, which
6384 * can't be done there isn't a current VMCS.
6386 nested_vmx_failInvalid(vcpu);
6387 return;
6389 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
6390 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
6391 X86_EFLAGS_SF | X86_EFLAGS_OF))
6392 | X86_EFLAGS_ZF);
6393 get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
6395 * We don't need to force a shadow sync because
6396 * VM_INSTRUCTION_ERROR is not shadowed
6400 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
6402 /* TODO: not to reset guest simply here. */
6403 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6404 pr_warn("kvm: nested vmx abort, indicator %d\n", indicator);
6407 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
6409 struct vcpu_vmx *vmx =
6410 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
6412 vmx->nested.preemption_timer_expired = true;
6413 kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
6414 kvm_vcpu_kick(&vmx->vcpu);
6416 return HRTIMER_NORESTART;
6420 * Decode the memory-address operand of a vmx instruction, as recorded on an
6421 * exit caused by such an instruction (run by a guest hypervisor).
6422 * On success, returns 0. When the operand is invalid, returns 1 and throws
6423 * #UD or #GP.
6425 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
6426 unsigned long exit_qualification,
6427 u32 vmx_instruction_info, gva_t *ret)
6430 * According to Vol. 3B, "Information for VM Exits Due to Instruction
6431 * Execution", on an exit, vmx_instruction_info holds most of the
6432 * addressing components of the operand. Only the displacement part
6433 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
6434 * For how an actual address is calculated from all these components,
6435 * refer to Vol. 1, "Operand Addressing".
6437 int scaling = vmx_instruction_info & 3;
6438 int addr_size = (vmx_instruction_info >> 7) & 7;
6439 bool is_reg = vmx_instruction_info & (1u << 10);
6440 int seg_reg = (vmx_instruction_info >> 15) & 7;
6441 int index_reg = (vmx_instruction_info >> 18) & 0xf;
6442 bool index_is_valid = !(vmx_instruction_info & (1u << 22));
6443 int base_reg = (vmx_instruction_info >> 23) & 0xf;
6444 bool base_is_valid = !(vmx_instruction_info & (1u << 27));
6446 if (is_reg) {
6447 kvm_queue_exception(vcpu, UD_VECTOR);
6448 return 1;
6451 /* Addr = segment_base + offset */
6452 /* offset = base + [index * scale] + displacement */
6453 *ret = vmx_get_segment_base(vcpu, seg_reg);
6454 if (base_is_valid)
6455 *ret += kvm_register_read(vcpu, base_reg);
6456 if (index_is_valid)
6457 *ret += kvm_register_read(vcpu, index_reg)<<scaling;
6458 *ret += exit_qualification; /* holds the displacement */
6460 if (addr_size == 1) /* 32 bit */
6461 *ret &= 0xffffffff;
6464 * TODO: throw #GP (and return 1) in various cases that the VM*
6465 * instructions require it - e.g., offset beyond segment limit,
6466 * unusable or unreadable/unwritable segment, non-canonical 64-bit
6467 * address, and so on. Currently these are not checked.
6469 return 0;
6473 * This function performs the various checks including
6474 * - if it's 4KB aligned
6475 * - No bits beyond the physical address width are set
6476 * - Returns 0 on success or else 1
6477 * (Intel SDM Section 30.3)
6479 static int nested_vmx_check_vmptr(struct kvm_vcpu *vcpu, int exit_reason,
6480 gpa_t *vmpointer)
6482 gva_t gva;
6483 gpa_t vmptr;
6484 struct x86_exception e;
6485 struct page *page;
6486 struct vcpu_vmx *vmx = to_vmx(vcpu);
6487 int maxphyaddr = cpuid_maxphyaddr(vcpu);
6489 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
6490 vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
6491 return 1;
6493 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
6494 sizeof(vmptr), &e)) {
6495 kvm_inject_page_fault(vcpu, &e);
6496 return 1;
6499 switch (exit_reason) {
6500 case EXIT_REASON_VMON:
6502 * SDM 3: 24.11.5
6503 * The first 4 bytes of VMXON region contain the supported
6504 * VMCS revision identifier
6506 * Note - IA32_VMX_BASIC[48] will never be 1
6507 * for the nested case;
6508 * which replaces physical address width with 32
6511 if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
6512 nested_vmx_failInvalid(vcpu);
6513 skip_emulated_instruction(vcpu);
6514 return 1;
6517 page = nested_get_page(vcpu, vmptr);
6518 if (page == NULL ||
6519 *(u32 *)kmap(page) != VMCS12_REVISION) {
6520 nested_vmx_failInvalid(vcpu);
6521 kunmap(page);
6522 skip_emulated_instruction(vcpu);
6523 return 1;
6525 kunmap(page);
6526 vmx->nested.vmxon_ptr = vmptr;
6527 break;
6528 case EXIT_REASON_VMCLEAR:
6529 if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
6530 nested_vmx_failValid(vcpu,
6531 VMXERR_VMCLEAR_INVALID_ADDRESS);
6532 skip_emulated_instruction(vcpu);
6533 return 1;
6536 if (vmptr == vmx->nested.vmxon_ptr) {
6537 nested_vmx_failValid(vcpu,
6538 VMXERR_VMCLEAR_VMXON_POINTER);
6539 skip_emulated_instruction(vcpu);
6540 return 1;
6542 break;
6543 case EXIT_REASON_VMPTRLD:
6544 if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
6545 nested_vmx_failValid(vcpu,
6546 VMXERR_VMPTRLD_INVALID_ADDRESS);
6547 skip_emulated_instruction(vcpu);
6548 return 1;
6551 if (vmptr == vmx->nested.vmxon_ptr) {
6552 nested_vmx_failValid(vcpu,
6553 VMXERR_VMCLEAR_VMXON_POINTER);
6554 skip_emulated_instruction(vcpu);
6555 return 1;
6557 break;
6558 default:
6559 return 1; /* shouldn't happen */
6562 if (vmpointer)
6563 *vmpointer = vmptr;
6564 return 0;
6568 * Emulate the VMXON instruction.
6569 * Currently, we just remember that VMX is active, and do not save or even
6570 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
6571 * do not currently need to store anything in that guest-allocated memory
6572 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
6573 * argument is different from the VMXON pointer (which the spec says they do).
6575 static int handle_vmon(struct kvm_vcpu *vcpu)
6577 struct kvm_segment cs;
6578 struct vcpu_vmx *vmx = to_vmx(vcpu);
6579 struct vmcs *shadow_vmcs;
6580 const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
6581 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
6583 /* The Intel VMX Instruction Reference lists a bunch of bits that
6584 * are prerequisite to running VMXON, most notably cr4.VMXE must be
6585 * set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
6586 * Otherwise, we should fail with #UD. We test these now:
6588 if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
6589 !kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
6590 (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
6591 kvm_queue_exception(vcpu, UD_VECTOR);
6592 return 1;
6595 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
6596 if (is_long_mode(vcpu) && !cs.l) {
6597 kvm_queue_exception(vcpu, UD_VECTOR);
6598 return 1;
6601 if (vmx_get_cpl(vcpu)) {
6602 kvm_inject_gp(vcpu, 0);
6603 return 1;
6606 if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMON, NULL))
6607 return 1;
6609 if (vmx->nested.vmxon) {
6610 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
6611 skip_emulated_instruction(vcpu);
6612 return 1;
6615 if ((vmx->nested.msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
6616 != VMXON_NEEDED_FEATURES) {
6617 kvm_inject_gp(vcpu, 0);
6618 return 1;
6621 if (enable_shadow_vmcs) {
6622 shadow_vmcs = alloc_vmcs();
6623 if (!shadow_vmcs)
6624 return -ENOMEM;
6625 /* mark vmcs as shadow */
6626 shadow_vmcs->revision_id |= (1u << 31);
6627 /* init shadow vmcs */
6628 vmcs_clear(shadow_vmcs);
6629 vmx->nested.current_shadow_vmcs = shadow_vmcs;
6632 INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
6633 vmx->nested.vmcs02_num = 0;
6635 hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
6636 HRTIMER_MODE_REL);
6637 vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
6639 vmx->nested.vmxon = true;
6641 skip_emulated_instruction(vcpu);
6642 nested_vmx_succeed(vcpu);
6643 return 1;
6647 * Intel's VMX Instruction Reference specifies a common set of prerequisites
6648 * for running VMX instructions (except VMXON, whose prerequisites are
6649 * slightly different). It also specifies what exception to inject otherwise.
6651 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
6653 struct kvm_segment cs;
6654 struct vcpu_vmx *vmx = to_vmx(vcpu);
6656 if (!vmx->nested.vmxon) {
6657 kvm_queue_exception(vcpu, UD_VECTOR);
6658 return 0;
6661 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
6662 if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
6663 (is_long_mode(vcpu) && !cs.l)) {
6664 kvm_queue_exception(vcpu, UD_VECTOR);
6665 return 0;
6668 if (vmx_get_cpl(vcpu)) {
6669 kvm_inject_gp(vcpu, 0);
6670 return 0;
6673 return 1;
6676 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
6678 u32 exec_control;
6679 if (vmx->nested.current_vmptr == -1ull)
6680 return;
6682 /* current_vmptr and current_vmcs12 are always set/reset together */
6683 if (WARN_ON(vmx->nested.current_vmcs12 == NULL))
6684 return;
6686 if (enable_shadow_vmcs) {
6687 /* copy to memory all shadowed fields in case
6688 they were modified */
6689 copy_shadow_to_vmcs12(vmx);
6690 vmx->nested.sync_shadow_vmcs = false;
6691 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6692 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
6693 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
6694 vmcs_write64(VMCS_LINK_POINTER, -1ull);
6696 vmx->nested.posted_intr_nv = -1;
6697 kunmap(vmx->nested.current_vmcs12_page);
6698 nested_release_page(vmx->nested.current_vmcs12_page);
6699 vmx->nested.current_vmptr = -1ull;
6700 vmx->nested.current_vmcs12 = NULL;
6704 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
6705 * just stops using VMX.
6707 static void free_nested(struct vcpu_vmx *vmx)
6709 if (!vmx->nested.vmxon)
6710 return;
6712 vmx->nested.vmxon = false;
6713 nested_release_vmcs12(vmx);
6714 if (enable_shadow_vmcs)
6715 free_vmcs(vmx->nested.current_shadow_vmcs);
6716 /* Unpin physical memory we referred to in current vmcs02 */
6717 if (vmx->nested.apic_access_page) {
6718 nested_release_page(vmx->nested.apic_access_page);
6719 vmx->nested.apic_access_page = NULL;
6721 if (vmx->nested.virtual_apic_page) {
6722 nested_release_page(vmx->nested.virtual_apic_page);
6723 vmx->nested.virtual_apic_page = NULL;
6725 if (vmx->nested.pi_desc_page) {
6726 kunmap(vmx->nested.pi_desc_page);
6727 nested_release_page(vmx->nested.pi_desc_page);
6728 vmx->nested.pi_desc_page = NULL;
6729 vmx->nested.pi_desc = NULL;
6732 nested_free_all_saved_vmcss(vmx);
6735 /* Emulate the VMXOFF instruction */
6736 static int handle_vmoff(struct kvm_vcpu *vcpu)
6738 if (!nested_vmx_check_permission(vcpu))
6739 return 1;
6740 free_nested(to_vmx(vcpu));
6741 skip_emulated_instruction(vcpu);
6742 nested_vmx_succeed(vcpu);
6743 return 1;
6746 /* Emulate the VMCLEAR instruction */
6747 static int handle_vmclear(struct kvm_vcpu *vcpu)
6749 struct vcpu_vmx *vmx = to_vmx(vcpu);
6750 gpa_t vmptr;
6751 struct vmcs12 *vmcs12;
6752 struct page *page;
6754 if (!nested_vmx_check_permission(vcpu))
6755 return 1;
6757 if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMCLEAR, &vmptr))
6758 return 1;
6760 if (vmptr == vmx->nested.current_vmptr)
6761 nested_release_vmcs12(vmx);
6763 page = nested_get_page(vcpu, vmptr);
6764 if (page == NULL) {
6766 * For accurate processor emulation, VMCLEAR beyond available
6767 * physical memory should do nothing at all. However, it is
6768 * possible that a nested vmx bug, not a guest hypervisor bug,
6769 * resulted in this case, so let's shut down before doing any
6770 * more damage:
6772 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6773 return 1;
6775 vmcs12 = kmap(page);
6776 vmcs12->launch_state = 0;
6777 kunmap(page);
6778 nested_release_page(page);
6780 nested_free_vmcs02(vmx, vmptr);
6782 skip_emulated_instruction(vcpu);
6783 nested_vmx_succeed(vcpu);
6784 return 1;
6787 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
6789 /* Emulate the VMLAUNCH instruction */
6790 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
6792 return nested_vmx_run(vcpu, true);
6795 /* Emulate the VMRESUME instruction */
6796 static int handle_vmresume(struct kvm_vcpu *vcpu)
6799 return nested_vmx_run(vcpu, false);
6802 enum vmcs_field_type {
6803 VMCS_FIELD_TYPE_U16 = 0,
6804 VMCS_FIELD_TYPE_U64 = 1,
6805 VMCS_FIELD_TYPE_U32 = 2,
6806 VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
6809 static inline int vmcs_field_type(unsigned long field)
6811 if (0x1 & field) /* the *_HIGH fields are all 32 bit */
6812 return VMCS_FIELD_TYPE_U32;
6813 return (field >> 13) & 0x3 ;
6816 static inline int vmcs_field_readonly(unsigned long field)
6818 return (((field >> 10) & 0x3) == 1);
6822 * Read a vmcs12 field. Since these can have varying lengths and we return
6823 * one type, we chose the biggest type (u64) and zero-extend the return value
6824 * to that size. Note that the caller, handle_vmread, might need to use only
6825 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
6826 * 64-bit fields are to be returned).
6828 static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
6829 unsigned long field, u64 *ret)
6831 short offset = vmcs_field_to_offset(field);
6832 char *p;
6834 if (offset < 0)
6835 return offset;
6837 p = ((char *)(get_vmcs12(vcpu))) + offset;
6839 switch (vmcs_field_type(field)) {
6840 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6841 *ret = *((natural_width *)p);
6842 return 0;
6843 case VMCS_FIELD_TYPE_U16:
6844 *ret = *((u16 *)p);
6845 return 0;
6846 case VMCS_FIELD_TYPE_U32:
6847 *ret = *((u32 *)p);
6848 return 0;
6849 case VMCS_FIELD_TYPE_U64:
6850 *ret = *((u64 *)p);
6851 return 0;
6852 default:
6853 WARN_ON(1);
6854 return -ENOENT;
6859 static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
6860 unsigned long field, u64 field_value){
6861 short offset = vmcs_field_to_offset(field);
6862 char *p = ((char *) get_vmcs12(vcpu)) + offset;
6863 if (offset < 0)
6864 return offset;
6866 switch (vmcs_field_type(field)) {
6867 case VMCS_FIELD_TYPE_U16:
6868 *(u16 *)p = field_value;
6869 return 0;
6870 case VMCS_FIELD_TYPE_U32:
6871 *(u32 *)p = field_value;
6872 return 0;
6873 case VMCS_FIELD_TYPE_U64:
6874 *(u64 *)p = field_value;
6875 return 0;
6876 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6877 *(natural_width *)p = field_value;
6878 return 0;
6879 default:
6880 WARN_ON(1);
6881 return -ENOENT;
6886 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
6888 int i;
6889 unsigned long field;
6890 u64 field_value;
6891 struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs;
6892 const unsigned long *fields = shadow_read_write_fields;
6893 const int num_fields = max_shadow_read_write_fields;
6895 preempt_disable();
6897 vmcs_load(shadow_vmcs);
6899 for (i = 0; i < num_fields; i++) {
6900 field = fields[i];
6901 switch (vmcs_field_type(field)) {
6902 case VMCS_FIELD_TYPE_U16:
6903 field_value = vmcs_read16(field);
6904 break;
6905 case VMCS_FIELD_TYPE_U32:
6906 field_value = vmcs_read32(field);
6907 break;
6908 case VMCS_FIELD_TYPE_U64:
6909 field_value = vmcs_read64(field);
6910 break;
6911 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6912 field_value = vmcs_readl(field);
6913 break;
6914 default:
6915 WARN_ON(1);
6916 continue;
6918 vmcs12_write_any(&vmx->vcpu, field, field_value);
6921 vmcs_clear(shadow_vmcs);
6922 vmcs_load(vmx->loaded_vmcs->vmcs);
6924 preempt_enable();
6927 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
6929 const unsigned long *fields[] = {
6930 shadow_read_write_fields,
6931 shadow_read_only_fields
6933 const int max_fields[] = {
6934 max_shadow_read_write_fields,
6935 max_shadow_read_only_fields
6937 int i, q;
6938 unsigned long field;
6939 u64 field_value = 0;
6940 struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs;
6942 vmcs_load(shadow_vmcs);
6944 for (q = 0; q < ARRAY_SIZE(fields); q++) {
6945 for (i = 0; i < max_fields[q]; i++) {
6946 field = fields[q][i];
6947 vmcs12_read_any(&vmx->vcpu, field, &field_value);
6949 switch (vmcs_field_type(field)) {
6950 case VMCS_FIELD_TYPE_U16:
6951 vmcs_write16(field, (u16)field_value);
6952 break;
6953 case VMCS_FIELD_TYPE_U32:
6954 vmcs_write32(field, (u32)field_value);
6955 break;
6956 case VMCS_FIELD_TYPE_U64:
6957 vmcs_write64(field, (u64)field_value);
6958 break;
6959 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6960 vmcs_writel(field, (long)field_value);
6961 break;
6962 default:
6963 WARN_ON(1);
6964 break;
6969 vmcs_clear(shadow_vmcs);
6970 vmcs_load(vmx->loaded_vmcs->vmcs);
6974 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
6975 * used before) all generate the same failure when it is missing.
6977 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
6979 struct vcpu_vmx *vmx = to_vmx(vcpu);
6980 if (vmx->nested.current_vmptr == -1ull) {
6981 nested_vmx_failInvalid(vcpu);
6982 skip_emulated_instruction(vcpu);
6983 return 0;
6985 return 1;
6988 static int handle_vmread(struct kvm_vcpu *vcpu)
6990 unsigned long field;
6991 u64 field_value;
6992 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6993 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6994 gva_t gva = 0;
6996 if (!nested_vmx_check_permission(vcpu) ||
6997 !nested_vmx_check_vmcs12(vcpu))
6998 return 1;
7000 /* Decode instruction info and find the field to read */
7001 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7002 /* Read the field, zero-extended to a u64 field_value */
7003 if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
7004 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7005 skip_emulated_instruction(vcpu);
7006 return 1;
7009 * Now copy part of this value to register or memory, as requested.
7010 * Note that the number of bits actually copied is 32 or 64 depending
7011 * on the guest's mode (32 or 64 bit), not on the given field's length.
7013 if (vmx_instruction_info & (1u << 10)) {
7014 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
7015 field_value);
7016 } else {
7017 if (get_vmx_mem_address(vcpu, exit_qualification,
7018 vmx_instruction_info, &gva))
7019 return 1;
7020 /* _system ok, as nested_vmx_check_permission verified cpl=0 */
7021 kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
7022 &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
7025 nested_vmx_succeed(vcpu);
7026 skip_emulated_instruction(vcpu);
7027 return 1;
7031 static int handle_vmwrite(struct kvm_vcpu *vcpu)
7033 unsigned long field;
7034 gva_t gva;
7035 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7036 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7037 /* The value to write might be 32 or 64 bits, depending on L1's long
7038 * mode, and eventually we need to write that into a field of several
7039 * possible lengths. The code below first zero-extends the value to 64
7040 * bit (field_value), and then copies only the approriate number of
7041 * bits into the vmcs12 field.
7043 u64 field_value = 0;
7044 struct x86_exception e;
7046 if (!nested_vmx_check_permission(vcpu) ||
7047 !nested_vmx_check_vmcs12(vcpu))
7048 return 1;
7050 if (vmx_instruction_info & (1u << 10))
7051 field_value = kvm_register_readl(vcpu,
7052 (((vmx_instruction_info) >> 3) & 0xf));
7053 else {
7054 if (get_vmx_mem_address(vcpu, exit_qualification,
7055 vmx_instruction_info, &gva))
7056 return 1;
7057 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
7058 &field_value, (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
7059 kvm_inject_page_fault(vcpu, &e);
7060 return 1;
7065 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7066 if (vmcs_field_readonly(field)) {
7067 nested_vmx_failValid(vcpu,
7068 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
7069 skip_emulated_instruction(vcpu);
7070 return 1;
7073 if (vmcs12_write_any(vcpu, field, field_value) < 0) {
7074 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7075 skip_emulated_instruction(vcpu);
7076 return 1;
7079 nested_vmx_succeed(vcpu);
7080 skip_emulated_instruction(vcpu);
7081 return 1;
7084 /* Emulate the VMPTRLD instruction */
7085 static int handle_vmptrld(struct kvm_vcpu *vcpu)
7087 struct vcpu_vmx *vmx = to_vmx(vcpu);
7088 gpa_t vmptr;
7089 u32 exec_control;
7091 if (!nested_vmx_check_permission(vcpu))
7092 return 1;
7094 if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMPTRLD, &vmptr))
7095 return 1;
7097 if (vmx->nested.current_vmptr != vmptr) {
7098 struct vmcs12 *new_vmcs12;
7099 struct page *page;
7100 page = nested_get_page(vcpu, vmptr);
7101 if (page == NULL) {
7102 nested_vmx_failInvalid(vcpu);
7103 skip_emulated_instruction(vcpu);
7104 return 1;
7106 new_vmcs12 = kmap(page);
7107 if (new_vmcs12->revision_id != VMCS12_REVISION) {
7108 kunmap(page);
7109 nested_release_page_clean(page);
7110 nested_vmx_failValid(vcpu,
7111 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
7112 skip_emulated_instruction(vcpu);
7113 return 1;
7116 nested_release_vmcs12(vmx);
7117 vmx->nested.current_vmptr = vmptr;
7118 vmx->nested.current_vmcs12 = new_vmcs12;
7119 vmx->nested.current_vmcs12_page = page;
7120 if (enable_shadow_vmcs) {
7121 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7122 exec_control |= SECONDARY_EXEC_SHADOW_VMCS;
7123 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
7124 vmcs_write64(VMCS_LINK_POINTER,
7125 __pa(vmx->nested.current_shadow_vmcs));
7126 vmx->nested.sync_shadow_vmcs = true;
7130 nested_vmx_succeed(vcpu);
7131 skip_emulated_instruction(vcpu);
7132 return 1;
7135 /* Emulate the VMPTRST instruction */
7136 static int handle_vmptrst(struct kvm_vcpu *vcpu)
7138 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7139 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7140 gva_t vmcs_gva;
7141 struct x86_exception e;
7143 if (!nested_vmx_check_permission(vcpu))
7144 return 1;
7146 if (get_vmx_mem_address(vcpu, exit_qualification,
7147 vmx_instruction_info, &vmcs_gva))
7148 return 1;
7149 /* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
7150 if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
7151 (void *)&to_vmx(vcpu)->nested.current_vmptr,
7152 sizeof(u64), &e)) {
7153 kvm_inject_page_fault(vcpu, &e);
7154 return 1;
7156 nested_vmx_succeed(vcpu);
7157 skip_emulated_instruction(vcpu);
7158 return 1;
7161 /* Emulate the INVEPT instruction */
7162 static int handle_invept(struct kvm_vcpu *vcpu)
7164 struct vcpu_vmx *vmx = to_vmx(vcpu);
7165 u32 vmx_instruction_info, types;
7166 unsigned long type;
7167 gva_t gva;
7168 struct x86_exception e;
7169 struct {
7170 u64 eptp, gpa;
7171 } operand;
7173 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7174 SECONDARY_EXEC_ENABLE_EPT) ||
7175 !(vmx->nested.nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
7176 kvm_queue_exception(vcpu, UD_VECTOR);
7177 return 1;
7180 if (!nested_vmx_check_permission(vcpu))
7181 return 1;
7183 if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) {
7184 kvm_queue_exception(vcpu, UD_VECTOR);
7185 return 1;
7188 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7189 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7191 types = (vmx->nested.nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
7193 if (!(types & (1UL << type))) {
7194 nested_vmx_failValid(vcpu,
7195 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7196 return 1;
7199 /* According to the Intel VMX instruction reference, the memory
7200 * operand is read even if it isn't needed (e.g., for type==global)
7202 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7203 vmx_instruction_info, &gva))
7204 return 1;
7205 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
7206 sizeof(operand), &e)) {
7207 kvm_inject_page_fault(vcpu, &e);
7208 return 1;
7211 switch (type) {
7212 case VMX_EPT_EXTENT_GLOBAL:
7213 kvm_mmu_sync_roots(vcpu);
7214 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
7215 nested_vmx_succeed(vcpu);
7216 break;
7217 default:
7218 /* Trap single context invalidation invept calls */
7219 BUG_ON(1);
7220 break;
7223 skip_emulated_instruction(vcpu);
7224 return 1;
7227 static int handle_invvpid(struct kvm_vcpu *vcpu)
7229 kvm_queue_exception(vcpu, UD_VECTOR);
7230 return 1;
7233 static int handle_pml_full(struct kvm_vcpu *vcpu)
7235 unsigned long exit_qualification;
7237 trace_kvm_pml_full(vcpu->vcpu_id);
7239 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7242 * PML buffer FULL happened while executing iret from NMI,
7243 * "blocked by NMI" bit has to be set before next VM entry.
7245 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
7246 cpu_has_virtual_nmis() &&
7247 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
7248 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
7249 GUEST_INTR_STATE_NMI);
7252 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
7253 * here.., and there's no userspace involvement needed for PML.
7255 return 1;
7259 * The exit handlers return 1 if the exit was handled fully and guest execution
7260 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
7261 * to be done to userspace and return 0.
7263 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
7264 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
7265 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
7266 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
7267 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
7268 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
7269 [EXIT_REASON_CR_ACCESS] = handle_cr,
7270 [EXIT_REASON_DR_ACCESS] = handle_dr,
7271 [EXIT_REASON_CPUID] = handle_cpuid,
7272 [EXIT_REASON_MSR_READ] = handle_rdmsr,
7273 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
7274 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
7275 [EXIT_REASON_HLT] = handle_halt,
7276 [EXIT_REASON_INVD] = handle_invd,
7277 [EXIT_REASON_INVLPG] = handle_invlpg,
7278 [EXIT_REASON_RDPMC] = handle_rdpmc,
7279 [EXIT_REASON_VMCALL] = handle_vmcall,
7280 [EXIT_REASON_VMCLEAR] = handle_vmclear,
7281 [EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
7282 [EXIT_REASON_VMPTRLD] = handle_vmptrld,
7283 [EXIT_REASON_VMPTRST] = handle_vmptrst,
7284 [EXIT_REASON_VMREAD] = handle_vmread,
7285 [EXIT_REASON_VMRESUME] = handle_vmresume,
7286 [EXIT_REASON_VMWRITE] = handle_vmwrite,
7287 [EXIT_REASON_VMOFF] = handle_vmoff,
7288 [EXIT_REASON_VMON] = handle_vmon,
7289 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
7290 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
7291 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
7292 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
7293 [EXIT_REASON_WBINVD] = handle_wbinvd,
7294 [EXIT_REASON_XSETBV] = handle_xsetbv,
7295 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
7296 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
7297 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
7298 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
7299 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
7300 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
7301 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
7302 [EXIT_REASON_INVEPT] = handle_invept,
7303 [EXIT_REASON_INVVPID] = handle_invvpid,
7304 [EXIT_REASON_XSAVES] = handle_xsaves,
7305 [EXIT_REASON_XRSTORS] = handle_xrstors,
7306 [EXIT_REASON_PML_FULL] = handle_pml_full,
7309 static const int kvm_vmx_max_exit_handlers =
7310 ARRAY_SIZE(kvm_vmx_exit_handlers);
7312 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
7313 struct vmcs12 *vmcs12)
7315 unsigned long exit_qualification;
7316 gpa_t bitmap, last_bitmap;
7317 unsigned int port;
7318 int size;
7319 u8 b;
7321 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7322 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
7324 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7326 port = exit_qualification >> 16;
7327 size = (exit_qualification & 7) + 1;
7329 last_bitmap = (gpa_t)-1;
7330 b = -1;
7332 while (size > 0) {
7333 if (port < 0x8000)
7334 bitmap = vmcs12->io_bitmap_a;
7335 else if (port < 0x10000)
7336 bitmap = vmcs12->io_bitmap_b;
7337 else
7338 return true;
7339 bitmap += (port & 0x7fff) / 8;
7341 if (last_bitmap != bitmap)
7342 if (kvm_read_guest(vcpu->kvm, bitmap, &b, 1))
7343 return true;
7344 if (b & (1 << (port & 7)))
7345 return true;
7347 port++;
7348 size--;
7349 last_bitmap = bitmap;
7352 return false;
7356 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
7357 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
7358 * disinterest in the current event (read or write a specific MSR) by using an
7359 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
7361 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
7362 struct vmcs12 *vmcs12, u32 exit_reason)
7364 u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
7365 gpa_t bitmap;
7367 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
7368 return true;
7371 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
7372 * for the four combinations of read/write and low/high MSR numbers.
7373 * First we need to figure out which of the four to use:
7375 bitmap = vmcs12->msr_bitmap;
7376 if (exit_reason == EXIT_REASON_MSR_WRITE)
7377 bitmap += 2048;
7378 if (msr_index >= 0xc0000000) {
7379 msr_index -= 0xc0000000;
7380 bitmap += 1024;
7383 /* Then read the msr_index'th bit from this bitmap: */
7384 if (msr_index < 1024*8) {
7385 unsigned char b;
7386 if (kvm_read_guest(vcpu->kvm, bitmap + msr_index/8, &b, 1))
7387 return true;
7388 return 1 & (b >> (msr_index & 7));
7389 } else
7390 return true; /* let L1 handle the wrong parameter */
7394 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
7395 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
7396 * intercept (via guest_host_mask etc.) the current event.
7398 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
7399 struct vmcs12 *vmcs12)
7401 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7402 int cr = exit_qualification & 15;
7403 int reg = (exit_qualification >> 8) & 15;
7404 unsigned long val = kvm_register_readl(vcpu, reg);
7406 switch ((exit_qualification >> 4) & 3) {
7407 case 0: /* mov to cr */
7408 switch (cr) {
7409 case 0:
7410 if (vmcs12->cr0_guest_host_mask &
7411 (val ^ vmcs12->cr0_read_shadow))
7412 return true;
7413 break;
7414 case 3:
7415 if ((vmcs12->cr3_target_count >= 1 &&
7416 vmcs12->cr3_target_value0 == val) ||
7417 (vmcs12->cr3_target_count >= 2 &&
7418 vmcs12->cr3_target_value1 == val) ||
7419 (vmcs12->cr3_target_count >= 3 &&
7420 vmcs12->cr3_target_value2 == val) ||
7421 (vmcs12->cr3_target_count >= 4 &&
7422 vmcs12->cr3_target_value3 == val))
7423 return false;
7424 if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
7425 return true;
7426 break;
7427 case 4:
7428 if (vmcs12->cr4_guest_host_mask &
7429 (vmcs12->cr4_read_shadow ^ val))
7430 return true;
7431 break;
7432 case 8:
7433 if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
7434 return true;
7435 break;
7437 break;
7438 case 2: /* clts */
7439 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
7440 (vmcs12->cr0_read_shadow & X86_CR0_TS))
7441 return true;
7442 break;
7443 case 1: /* mov from cr */
7444 switch (cr) {
7445 case 3:
7446 if (vmcs12->cpu_based_vm_exec_control &
7447 CPU_BASED_CR3_STORE_EXITING)
7448 return true;
7449 break;
7450 case 8:
7451 if (vmcs12->cpu_based_vm_exec_control &
7452 CPU_BASED_CR8_STORE_EXITING)
7453 return true;
7454 break;
7456 break;
7457 case 3: /* lmsw */
7459 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
7460 * cr0. Other attempted changes are ignored, with no exit.
7462 if (vmcs12->cr0_guest_host_mask & 0xe &
7463 (val ^ vmcs12->cr0_read_shadow))
7464 return true;
7465 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
7466 !(vmcs12->cr0_read_shadow & 0x1) &&
7467 (val & 0x1))
7468 return true;
7469 break;
7471 return false;
7475 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
7476 * should handle it ourselves in L0 (and then continue L2). Only call this
7477 * when in is_guest_mode (L2).
7479 static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
7481 u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
7482 struct vcpu_vmx *vmx = to_vmx(vcpu);
7483 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7484 u32 exit_reason = vmx->exit_reason;
7486 trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
7487 vmcs_readl(EXIT_QUALIFICATION),
7488 vmx->idt_vectoring_info,
7489 intr_info,
7490 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
7491 KVM_ISA_VMX);
7493 if (vmx->nested.nested_run_pending)
7494 return false;
7496 if (unlikely(vmx->fail)) {
7497 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
7498 vmcs_read32(VM_INSTRUCTION_ERROR));
7499 return true;
7502 switch (exit_reason) {
7503 case EXIT_REASON_EXCEPTION_NMI:
7504 if (!is_exception(intr_info))
7505 return false;
7506 else if (is_page_fault(intr_info))
7507 return enable_ept;
7508 else if (is_no_device(intr_info) &&
7509 !(vmcs12->guest_cr0 & X86_CR0_TS))
7510 return false;
7511 return vmcs12->exception_bitmap &
7512 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
7513 case EXIT_REASON_EXTERNAL_INTERRUPT:
7514 return false;
7515 case EXIT_REASON_TRIPLE_FAULT:
7516 return true;
7517 case EXIT_REASON_PENDING_INTERRUPT:
7518 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
7519 case EXIT_REASON_NMI_WINDOW:
7520 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
7521 case EXIT_REASON_TASK_SWITCH:
7522 return true;
7523 case EXIT_REASON_CPUID:
7524 if (kvm_register_read(vcpu, VCPU_REGS_RAX) == 0xa)
7525 return false;
7526 return true;
7527 case EXIT_REASON_HLT:
7528 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
7529 case EXIT_REASON_INVD:
7530 return true;
7531 case EXIT_REASON_INVLPG:
7532 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
7533 case EXIT_REASON_RDPMC:
7534 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
7535 case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
7536 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
7537 case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
7538 case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
7539 case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
7540 case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
7541 case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
7542 case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
7544 * VMX instructions trap unconditionally. This allows L1 to
7545 * emulate them for its L2 guest, i.e., allows 3-level nesting!
7547 return true;
7548 case EXIT_REASON_CR_ACCESS:
7549 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
7550 case EXIT_REASON_DR_ACCESS:
7551 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
7552 case EXIT_REASON_IO_INSTRUCTION:
7553 return nested_vmx_exit_handled_io(vcpu, vmcs12);
7554 case EXIT_REASON_MSR_READ:
7555 case EXIT_REASON_MSR_WRITE:
7556 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
7557 case EXIT_REASON_INVALID_STATE:
7558 return true;
7559 case EXIT_REASON_MWAIT_INSTRUCTION:
7560 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
7561 case EXIT_REASON_MONITOR_INSTRUCTION:
7562 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
7563 case EXIT_REASON_PAUSE_INSTRUCTION:
7564 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
7565 nested_cpu_has2(vmcs12,
7566 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
7567 case EXIT_REASON_MCE_DURING_VMENTRY:
7568 return false;
7569 case EXIT_REASON_TPR_BELOW_THRESHOLD:
7570 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
7571 case EXIT_REASON_APIC_ACCESS:
7572 return nested_cpu_has2(vmcs12,
7573 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
7574 case EXIT_REASON_APIC_WRITE:
7575 case EXIT_REASON_EOI_INDUCED:
7576 /* apic_write and eoi_induced should exit unconditionally. */
7577 return true;
7578 case EXIT_REASON_EPT_VIOLATION:
7580 * L0 always deals with the EPT violation. If nested EPT is
7581 * used, and the nested mmu code discovers that the address is
7582 * missing in the guest EPT table (EPT12), the EPT violation
7583 * will be injected with nested_ept_inject_page_fault()
7585 return false;
7586 case EXIT_REASON_EPT_MISCONFIG:
7588 * L2 never uses directly L1's EPT, but rather L0's own EPT
7589 * table (shadow on EPT) or a merged EPT table that L0 built
7590 * (EPT on EPT). So any problems with the structure of the
7591 * table is L0's fault.
7593 return false;
7594 case EXIT_REASON_WBINVD:
7595 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
7596 case EXIT_REASON_XSETBV:
7597 return true;
7598 case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
7600 * This should never happen, since it is not possible to
7601 * set XSS to a non-zero value---neither in L1 nor in L2.
7602 * If if it were, XSS would have to be checked against
7603 * the XSS exit bitmap in vmcs12.
7605 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
7606 default:
7607 return true;
7611 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
7613 *info1 = vmcs_readl(EXIT_QUALIFICATION);
7614 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
7617 static int vmx_enable_pml(struct vcpu_vmx *vmx)
7619 struct page *pml_pg;
7620 u32 exec_control;
7622 pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
7623 if (!pml_pg)
7624 return -ENOMEM;
7626 vmx->pml_pg = pml_pg;
7628 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
7629 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
7631 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7632 exec_control |= SECONDARY_EXEC_ENABLE_PML;
7633 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
7635 return 0;
7638 static void vmx_disable_pml(struct vcpu_vmx *vmx)
7640 u32 exec_control;
7642 ASSERT(vmx->pml_pg);
7643 __free_page(vmx->pml_pg);
7644 vmx->pml_pg = NULL;
7646 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7647 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
7648 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
7651 static void vmx_flush_pml_buffer(struct vcpu_vmx *vmx)
7653 struct kvm *kvm = vmx->vcpu.kvm;
7654 u64 *pml_buf;
7655 u16 pml_idx;
7657 pml_idx = vmcs_read16(GUEST_PML_INDEX);
7659 /* Do nothing if PML buffer is empty */
7660 if (pml_idx == (PML_ENTITY_NUM - 1))
7661 return;
7663 /* PML index always points to next available PML buffer entity */
7664 if (pml_idx >= PML_ENTITY_NUM)
7665 pml_idx = 0;
7666 else
7667 pml_idx++;
7669 pml_buf = page_address(vmx->pml_pg);
7670 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
7671 u64 gpa;
7673 gpa = pml_buf[pml_idx];
7674 WARN_ON(gpa & (PAGE_SIZE - 1));
7675 mark_page_dirty(kvm, gpa >> PAGE_SHIFT);
7678 /* reset PML index */
7679 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
7683 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
7684 * Called before reporting dirty_bitmap to userspace.
7686 static void kvm_flush_pml_buffers(struct kvm *kvm)
7688 int i;
7689 struct kvm_vcpu *vcpu;
7691 * We only need to kick vcpu out of guest mode here, as PML buffer
7692 * is flushed at beginning of all VMEXITs, and it's obvious that only
7693 * vcpus running in guest are possible to have unflushed GPAs in PML
7694 * buffer.
7696 kvm_for_each_vcpu(i, vcpu, kvm)
7697 kvm_vcpu_kick(vcpu);
7701 * The guest has exited. See if we can fix it or if we need userspace
7702 * assistance.
7704 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
7706 struct vcpu_vmx *vmx = to_vmx(vcpu);
7707 u32 exit_reason = vmx->exit_reason;
7708 u32 vectoring_info = vmx->idt_vectoring_info;
7711 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
7712 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
7713 * querying dirty_bitmap, we only need to kick all vcpus out of guest
7714 * mode as if vcpus is in root mode, the PML buffer must has been
7715 * flushed already.
7717 if (enable_pml)
7718 vmx_flush_pml_buffer(vmx);
7720 /* If guest state is invalid, start emulating */
7721 if (vmx->emulation_required)
7722 return handle_invalid_guest_state(vcpu);
7724 if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
7725 nested_vmx_vmexit(vcpu, exit_reason,
7726 vmcs_read32(VM_EXIT_INTR_INFO),
7727 vmcs_readl(EXIT_QUALIFICATION));
7728 return 1;
7731 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
7732 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
7733 vcpu->run->fail_entry.hardware_entry_failure_reason
7734 = exit_reason;
7735 return 0;
7738 if (unlikely(vmx->fail)) {
7739 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
7740 vcpu->run->fail_entry.hardware_entry_failure_reason
7741 = vmcs_read32(VM_INSTRUCTION_ERROR);
7742 return 0;
7746 * Note:
7747 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
7748 * delivery event since it indicates guest is accessing MMIO.
7749 * The vm-exit can be triggered again after return to guest that
7750 * will cause infinite loop.
7752 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
7753 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
7754 exit_reason != EXIT_REASON_EPT_VIOLATION &&
7755 exit_reason != EXIT_REASON_TASK_SWITCH)) {
7756 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7757 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
7758 vcpu->run->internal.ndata = 2;
7759 vcpu->run->internal.data[0] = vectoring_info;
7760 vcpu->run->internal.data[1] = exit_reason;
7761 return 0;
7764 if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
7765 !(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
7766 get_vmcs12(vcpu))))) {
7767 if (vmx_interrupt_allowed(vcpu)) {
7768 vmx->soft_vnmi_blocked = 0;
7769 } else if (vmx->vnmi_blocked_time > 1000000000LL &&
7770 vcpu->arch.nmi_pending) {
7772 * This CPU don't support us in finding the end of an
7773 * NMI-blocked window if the guest runs with IRQs
7774 * disabled. So we pull the trigger after 1 s of
7775 * futile waiting, but inform the user about this.
7777 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
7778 "state on VCPU %d after 1 s timeout\n",
7779 __func__, vcpu->vcpu_id);
7780 vmx->soft_vnmi_blocked = 0;
7784 if (exit_reason < kvm_vmx_max_exit_handlers
7785 && kvm_vmx_exit_handlers[exit_reason])
7786 return kvm_vmx_exit_handlers[exit_reason](vcpu);
7787 else {
7788 WARN_ONCE(1, "vmx: unexpected exit reason 0x%x\n", exit_reason);
7789 kvm_queue_exception(vcpu, UD_VECTOR);
7790 return 1;
7794 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
7796 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7798 if (is_guest_mode(vcpu) &&
7799 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
7800 return;
7802 if (irr == -1 || tpr < irr) {
7803 vmcs_write32(TPR_THRESHOLD, 0);
7804 return;
7807 vmcs_write32(TPR_THRESHOLD, irr);
7810 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
7812 u32 sec_exec_control;
7815 * There is not point to enable virtualize x2apic without enable
7816 * apicv
7818 if (!cpu_has_vmx_virtualize_x2apic_mode() ||
7819 !vmx_vm_has_apicv(vcpu->kvm))
7820 return;
7822 if (!vm_need_tpr_shadow(vcpu->kvm))
7823 return;
7825 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7827 if (set) {
7828 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7829 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
7830 } else {
7831 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
7832 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7834 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
7836 vmx_set_msr_bitmap(vcpu);
7839 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
7841 struct vcpu_vmx *vmx = to_vmx(vcpu);
7844 * Currently we do not handle the nested case where L2 has an
7845 * APIC access page of its own; that page is still pinned.
7846 * Hence, we skip the case where the VCPU is in guest mode _and_
7847 * L1 prepared an APIC access page for L2.
7849 * For the case where L1 and L2 share the same APIC access page
7850 * (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
7851 * in the vmcs12), this function will only update either the vmcs01
7852 * or the vmcs02. If the former, the vmcs02 will be updated by
7853 * prepare_vmcs02. If the latter, the vmcs01 will be updated in
7854 * the next L2->L1 exit.
7856 if (!is_guest_mode(vcpu) ||
7857 !nested_cpu_has2(vmx->nested.current_vmcs12,
7858 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
7859 vmcs_write64(APIC_ACCESS_ADDR, hpa);
7862 static void vmx_hwapic_isr_update(struct kvm *kvm, int isr)
7864 u16 status;
7865 u8 old;
7867 if (isr == -1)
7868 isr = 0;
7870 status = vmcs_read16(GUEST_INTR_STATUS);
7871 old = status >> 8;
7872 if (isr != old) {
7873 status &= 0xff;
7874 status |= isr << 8;
7875 vmcs_write16(GUEST_INTR_STATUS, status);
7879 static void vmx_set_rvi(int vector)
7881 u16 status;
7882 u8 old;
7884 if (vector == -1)
7885 vector = 0;
7887 status = vmcs_read16(GUEST_INTR_STATUS);
7888 old = (u8)status & 0xff;
7889 if ((u8)vector != old) {
7890 status &= ~0xff;
7891 status |= (u8)vector;
7892 vmcs_write16(GUEST_INTR_STATUS, status);
7896 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
7898 if (!is_guest_mode(vcpu)) {
7899 vmx_set_rvi(max_irr);
7900 return;
7903 if (max_irr == -1)
7904 return;
7907 * In guest mode. If a vmexit is needed, vmx_check_nested_events
7908 * handles it.
7910 if (nested_exit_on_intr(vcpu))
7911 return;
7914 * Else, fall back to pre-APICv interrupt injection since L2
7915 * is run without virtual interrupt delivery.
7917 if (!kvm_event_needs_reinjection(vcpu) &&
7918 vmx_interrupt_allowed(vcpu)) {
7919 kvm_queue_interrupt(vcpu, max_irr, false);
7920 vmx_inject_irq(vcpu);
7924 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
7926 if (!vmx_vm_has_apicv(vcpu->kvm))
7927 return;
7929 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
7930 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
7931 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
7932 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
7935 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
7937 u32 exit_intr_info;
7939 if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
7940 || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
7941 return;
7943 vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
7944 exit_intr_info = vmx->exit_intr_info;
7946 /* Handle machine checks before interrupts are enabled */
7947 if (is_machine_check(exit_intr_info))
7948 kvm_machine_check();
7950 /* We need to handle NMIs before interrupts are enabled */
7951 if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
7952 (exit_intr_info & INTR_INFO_VALID_MASK)) {
7953 kvm_before_handle_nmi(&vmx->vcpu);
7954 asm("int $2");
7955 kvm_after_handle_nmi(&vmx->vcpu);
7959 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
7961 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
7964 * If external interrupt exists, IF bit is set in rflags/eflags on the
7965 * interrupt stack frame, and interrupt will be enabled on a return
7966 * from interrupt handler.
7968 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
7969 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
7970 unsigned int vector;
7971 unsigned long entry;
7972 gate_desc *desc;
7973 struct vcpu_vmx *vmx = to_vmx(vcpu);
7974 #ifdef CONFIG_X86_64
7975 unsigned long tmp;
7976 #endif
7978 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
7979 desc = (gate_desc *)vmx->host_idt_base + vector;
7980 entry = gate_offset(*desc);
7981 asm volatile(
7982 #ifdef CONFIG_X86_64
7983 "mov %%" _ASM_SP ", %[sp]\n\t"
7984 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
7985 "push $%c[ss]\n\t"
7986 "push %[sp]\n\t"
7987 #endif
7988 "pushf\n\t"
7989 "orl $0x200, (%%" _ASM_SP ")\n\t"
7990 __ASM_SIZE(push) " $%c[cs]\n\t"
7991 "call *%[entry]\n\t"
7993 #ifdef CONFIG_X86_64
7994 [sp]"=&r"(tmp)
7995 #endif
7997 [entry]"r"(entry),
7998 [ss]"i"(__KERNEL_DS),
7999 [cs]"i"(__KERNEL_CS)
8001 } else
8002 local_irq_enable();
8005 static bool vmx_mpx_supported(void)
8007 return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
8008 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
8011 static bool vmx_xsaves_supported(void)
8013 return vmcs_config.cpu_based_2nd_exec_ctrl &
8014 SECONDARY_EXEC_XSAVES;
8017 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
8019 u32 exit_intr_info;
8020 bool unblock_nmi;
8021 u8 vector;
8022 bool idtv_info_valid;
8024 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
8026 if (cpu_has_virtual_nmis()) {
8027 if (vmx->nmi_known_unmasked)
8028 return;
8030 * Can't use vmx->exit_intr_info since we're not sure what
8031 * the exit reason is.
8033 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8034 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
8035 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
8037 * SDM 3: 27.7.1.2 (September 2008)
8038 * Re-set bit "block by NMI" before VM entry if vmexit caused by
8039 * a guest IRET fault.
8040 * SDM 3: 23.2.2 (September 2008)
8041 * Bit 12 is undefined in any of the following cases:
8042 * If the VM exit sets the valid bit in the IDT-vectoring
8043 * information field.
8044 * If the VM exit is due to a double fault.
8046 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
8047 vector != DF_VECTOR && !idtv_info_valid)
8048 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
8049 GUEST_INTR_STATE_NMI);
8050 else
8051 vmx->nmi_known_unmasked =
8052 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
8053 & GUEST_INTR_STATE_NMI);
8054 } else if (unlikely(vmx->soft_vnmi_blocked))
8055 vmx->vnmi_blocked_time +=
8056 ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
8059 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
8060 u32 idt_vectoring_info,
8061 int instr_len_field,
8062 int error_code_field)
8064 u8 vector;
8065 int type;
8066 bool idtv_info_valid;
8068 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
8070 vcpu->arch.nmi_injected = false;
8071 kvm_clear_exception_queue(vcpu);
8072 kvm_clear_interrupt_queue(vcpu);
8074 if (!idtv_info_valid)
8075 return;
8077 kvm_make_request(KVM_REQ_EVENT, vcpu);
8079 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
8080 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
8082 switch (type) {
8083 case INTR_TYPE_NMI_INTR:
8084 vcpu->arch.nmi_injected = true;
8086 * SDM 3: 27.7.1.2 (September 2008)
8087 * Clear bit "block by NMI" before VM entry if a NMI
8088 * delivery faulted.
8090 vmx_set_nmi_mask(vcpu, false);
8091 break;
8092 case INTR_TYPE_SOFT_EXCEPTION:
8093 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
8094 /* fall through */
8095 case INTR_TYPE_HARD_EXCEPTION:
8096 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
8097 u32 err = vmcs_read32(error_code_field);
8098 kvm_requeue_exception_e(vcpu, vector, err);
8099 } else
8100 kvm_requeue_exception(vcpu, vector);
8101 break;
8102 case INTR_TYPE_SOFT_INTR:
8103 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
8104 /* fall through */
8105 case INTR_TYPE_EXT_INTR:
8106 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
8107 break;
8108 default:
8109 break;
8113 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
8115 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
8116 VM_EXIT_INSTRUCTION_LEN,
8117 IDT_VECTORING_ERROR_CODE);
8120 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
8122 __vmx_complete_interrupts(vcpu,
8123 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
8124 VM_ENTRY_INSTRUCTION_LEN,
8125 VM_ENTRY_EXCEPTION_ERROR_CODE);
8127 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
8130 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
8132 int i, nr_msrs;
8133 struct perf_guest_switch_msr *msrs;
8135 msrs = perf_guest_get_msrs(&nr_msrs);
8137 if (!msrs)
8138 return;
8140 for (i = 0; i < nr_msrs; i++)
8141 if (msrs[i].host == msrs[i].guest)
8142 clear_atomic_switch_msr(vmx, msrs[i].msr);
8143 else
8144 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
8145 msrs[i].host);
8148 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
8150 struct vcpu_vmx *vmx = to_vmx(vcpu);
8151 unsigned long debugctlmsr, cr4;
8153 /* Record the guest's net vcpu time for enforced NMI injections. */
8154 if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
8155 vmx->entry_time = ktime_get();
8157 /* Don't enter VMX if guest state is invalid, let the exit handler
8158 start emulation until we arrive back to a valid state */
8159 if (vmx->emulation_required)
8160 return;
8162 if (vmx->ple_window_dirty) {
8163 vmx->ple_window_dirty = false;
8164 vmcs_write32(PLE_WINDOW, vmx->ple_window);
8167 if (vmx->nested.sync_shadow_vmcs) {
8168 copy_vmcs12_to_shadow(vmx);
8169 vmx->nested.sync_shadow_vmcs = false;
8172 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
8173 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
8174 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
8175 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
8177 cr4 = cr4_read_shadow();
8178 if (unlikely(cr4 != vmx->host_state.vmcs_host_cr4)) {
8179 vmcs_writel(HOST_CR4, cr4);
8180 vmx->host_state.vmcs_host_cr4 = cr4;
8183 /* When single-stepping over STI and MOV SS, we must clear the
8184 * corresponding interruptibility bits in the guest state. Otherwise
8185 * vmentry fails as it then expects bit 14 (BS) in pending debug
8186 * exceptions being set, but that's not correct for the guest debugging
8187 * case. */
8188 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8189 vmx_set_interrupt_shadow(vcpu, 0);
8191 atomic_switch_perf_msrs(vmx);
8192 debugctlmsr = get_debugctlmsr();
8194 vmx->__launched = vmx->loaded_vmcs->launched;
8195 asm(
8196 /* Store host registers */
8197 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
8198 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
8199 "push %%" _ASM_CX " \n\t"
8200 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
8201 "je 1f \n\t"
8202 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
8203 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
8204 "1: \n\t"
8205 /* Reload cr2 if changed */
8206 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
8207 "mov %%cr2, %%" _ASM_DX " \n\t"
8208 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
8209 "je 2f \n\t"
8210 "mov %%" _ASM_AX", %%cr2 \n\t"
8211 "2: \n\t"
8212 /* Check if vmlaunch of vmresume is needed */
8213 "cmpl $0, %c[launched](%0) \n\t"
8214 /* Load guest registers. Don't clobber flags. */
8215 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
8216 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
8217 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
8218 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
8219 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
8220 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
8221 #ifdef CONFIG_X86_64
8222 "mov %c[r8](%0), %%r8 \n\t"
8223 "mov %c[r9](%0), %%r9 \n\t"
8224 "mov %c[r10](%0), %%r10 \n\t"
8225 "mov %c[r11](%0), %%r11 \n\t"
8226 "mov %c[r12](%0), %%r12 \n\t"
8227 "mov %c[r13](%0), %%r13 \n\t"
8228 "mov %c[r14](%0), %%r14 \n\t"
8229 "mov %c[r15](%0), %%r15 \n\t"
8230 #endif
8231 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
8233 /* Enter guest mode */
8234 "jne 1f \n\t"
8235 __ex(ASM_VMX_VMLAUNCH) "\n\t"
8236 "jmp 2f \n\t"
8237 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
8238 "2: "
8239 /* Save guest registers, load host registers, keep flags */
8240 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
8241 "pop %0 \n\t"
8242 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
8243 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
8244 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
8245 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
8246 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
8247 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
8248 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
8249 #ifdef CONFIG_X86_64
8250 "mov %%r8, %c[r8](%0) \n\t"
8251 "mov %%r9, %c[r9](%0) \n\t"
8252 "mov %%r10, %c[r10](%0) \n\t"
8253 "mov %%r11, %c[r11](%0) \n\t"
8254 "mov %%r12, %c[r12](%0) \n\t"
8255 "mov %%r13, %c[r13](%0) \n\t"
8256 "mov %%r14, %c[r14](%0) \n\t"
8257 "mov %%r15, %c[r15](%0) \n\t"
8258 #endif
8259 "mov %%cr2, %%" _ASM_AX " \n\t"
8260 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
8262 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
8263 "setbe %c[fail](%0) \n\t"
8264 ".pushsection .rodata \n\t"
8265 ".global vmx_return \n\t"
8266 "vmx_return: " _ASM_PTR " 2b \n\t"
8267 ".popsection"
8268 : : "c"(vmx), "d"((unsigned long)HOST_RSP),
8269 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
8270 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
8271 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
8272 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
8273 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
8274 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
8275 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
8276 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
8277 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
8278 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
8279 #ifdef CONFIG_X86_64
8280 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
8281 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
8282 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
8283 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
8284 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
8285 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
8286 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
8287 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
8288 #endif
8289 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
8290 [wordsize]"i"(sizeof(ulong))
8291 : "cc", "memory"
8292 #ifdef CONFIG_X86_64
8293 , "rax", "rbx", "rdi", "rsi"
8294 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
8295 #else
8296 , "eax", "ebx", "edi", "esi"
8297 #endif
8300 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
8301 if (debugctlmsr)
8302 update_debugctlmsr(debugctlmsr);
8304 #ifndef CONFIG_X86_64
8306 * The sysexit path does not restore ds/es, so we must set them to
8307 * a reasonable value ourselves.
8309 * We can't defer this to vmx_load_host_state() since that function
8310 * may be executed in interrupt context, which saves and restore segments
8311 * around it, nullifying its effect.
8313 loadsegment(ds, __USER_DS);
8314 loadsegment(es, __USER_DS);
8315 #endif
8317 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
8318 | (1 << VCPU_EXREG_RFLAGS)
8319 | (1 << VCPU_EXREG_PDPTR)
8320 | (1 << VCPU_EXREG_SEGMENTS)
8321 | (1 << VCPU_EXREG_CR3));
8322 vcpu->arch.regs_dirty = 0;
8324 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
8326 vmx->loaded_vmcs->launched = 1;
8328 vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
8329 trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
8332 * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
8333 * we did not inject a still-pending event to L1 now because of
8334 * nested_run_pending, we need to re-enable this bit.
8336 if (vmx->nested.nested_run_pending)
8337 kvm_make_request(KVM_REQ_EVENT, vcpu);
8339 vmx->nested.nested_run_pending = 0;
8341 vmx_complete_atomic_exit(vmx);
8342 vmx_recover_nmi_blocking(vmx);
8343 vmx_complete_interrupts(vmx);
8346 static void vmx_load_vmcs01(struct kvm_vcpu *vcpu)
8348 struct vcpu_vmx *vmx = to_vmx(vcpu);
8349 int cpu;
8351 if (vmx->loaded_vmcs == &vmx->vmcs01)
8352 return;
8354 cpu = get_cpu();
8355 vmx->loaded_vmcs = &vmx->vmcs01;
8356 vmx_vcpu_put(vcpu);
8357 vmx_vcpu_load(vcpu, cpu);
8358 vcpu->cpu = cpu;
8359 put_cpu();
8362 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
8364 struct vcpu_vmx *vmx = to_vmx(vcpu);
8366 if (enable_pml)
8367 vmx_disable_pml(vmx);
8368 free_vpid(vmx);
8369 leave_guest_mode(vcpu);
8370 vmx_load_vmcs01(vcpu);
8371 free_nested(vmx);
8372 free_loaded_vmcs(vmx->loaded_vmcs);
8373 kfree(vmx->guest_msrs);
8374 kvm_vcpu_uninit(vcpu);
8375 kmem_cache_free(kvm_vcpu_cache, vmx);
8378 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
8380 int err;
8381 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
8382 int cpu;
8384 if (!vmx)
8385 return ERR_PTR(-ENOMEM);
8387 allocate_vpid(vmx);
8389 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
8390 if (err)
8391 goto free_vcpu;
8393 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
8394 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
8395 > PAGE_SIZE);
8397 err = -ENOMEM;
8398 if (!vmx->guest_msrs) {
8399 goto uninit_vcpu;
8402 vmx->loaded_vmcs = &vmx->vmcs01;
8403 vmx->loaded_vmcs->vmcs = alloc_vmcs();
8404 if (!vmx->loaded_vmcs->vmcs)
8405 goto free_msrs;
8406 if (!vmm_exclusive)
8407 kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
8408 loaded_vmcs_init(vmx->loaded_vmcs);
8409 if (!vmm_exclusive)
8410 kvm_cpu_vmxoff();
8412 cpu = get_cpu();
8413 vmx_vcpu_load(&vmx->vcpu, cpu);
8414 vmx->vcpu.cpu = cpu;
8415 err = vmx_vcpu_setup(vmx);
8416 vmx_vcpu_put(&vmx->vcpu);
8417 put_cpu();
8418 if (err)
8419 goto free_vmcs;
8420 if (vm_need_virtualize_apic_accesses(kvm)) {
8421 err = alloc_apic_access_page(kvm);
8422 if (err)
8423 goto free_vmcs;
8426 if (enable_ept) {
8427 if (!kvm->arch.ept_identity_map_addr)
8428 kvm->arch.ept_identity_map_addr =
8429 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
8430 err = init_rmode_identity_map(kvm);
8431 if (err)
8432 goto free_vmcs;
8435 if (nested)
8436 nested_vmx_setup_ctls_msrs(vmx);
8438 vmx->nested.posted_intr_nv = -1;
8439 vmx->nested.current_vmptr = -1ull;
8440 vmx->nested.current_vmcs12 = NULL;
8443 * If PML is turned on, failure on enabling PML just results in failure
8444 * of creating the vcpu, therefore we can simplify PML logic (by
8445 * avoiding dealing with cases, such as enabling PML partially on vcpus
8446 * for the guest, etc.
8448 if (enable_pml) {
8449 err = vmx_enable_pml(vmx);
8450 if (err)
8451 goto free_vmcs;
8454 return &vmx->vcpu;
8456 free_vmcs:
8457 free_loaded_vmcs(vmx->loaded_vmcs);
8458 free_msrs:
8459 kfree(vmx->guest_msrs);
8460 uninit_vcpu:
8461 kvm_vcpu_uninit(&vmx->vcpu);
8462 free_vcpu:
8463 free_vpid(vmx);
8464 kmem_cache_free(kvm_vcpu_cache, vmx);
8465 return ERR_PTR(err);
8468 static void __init vmx_check_processor_compat(void *rtn)
8470 struct vmcs_config vmcs_conf;
8472 *(int *)rtn = 0;
8473 if (setup_vmcs_config(&vmcs_conf) < 0)
8474 *(int *)rtn = -EIO;
8475 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
8476 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
8477 smp_processor_id());
8478 *(int *)rtn = -EIO;
8482 static int get_ept_level(void)
8484 return VMX_EPT_DEFAULT_GAW + 1;
8487 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
8489 u64 ret;
8491 /* For VT-d and EPT combination
8492 * 1. MMIO: always map as UC
8493 * 2. EPT with VT-d:
8494 * a. VT-d without snooping control feature: can't guarantee the
8495 * result, try to trust guest.
8496 * b. VT-d with snooping control feature: snooping control feature of
8497 * VT-d engine can guarantee the cache correctness. Just set it
8498 * to WB to keep consistent with host. So the same as item 3.
8499 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
8500 * consistent with host MTRR
8502 if (is_mmio)
8503 ret = MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
8504 else if (kvm_arch_has_noncoherent_dma(vcpu->kvm))
8505 ret = kvm_get_guest_memory_type(vcpu, gfn) <<
8506 VMX_EPT_MT_EPTE_SHIFT;
8507 else
8508 ret = (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT)
8509 | VMX_EPT_IPAT_BIT;
8511 return ret;
8514 static int vmx_get_lpage_level(void)
8516 if (enable_ept && !cpu_has_vmx_ept_1g_page())
8517 return PT_DIRECTORY_LEVEL;
8518 else
8519 /* For shadow and EPT supported 1GB page */
8520 return PT_PDPE_LEVEL;
8523 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
8525 struct kvm_cpuid_entry2 *best;
8526 struct vcpu_vmx *vmx = to_vmx(vcpu);
8527 u32 exec_control;
8529 vmx->rdtscp_enabled = false;
8530 if (vmx_rdtscp_supported()) {
8531 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8532 if (exec_control & SECONDARY_EXEC_RDTSCP) {
8533 best = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
8534 if (best && (best->edx & bit(X86_FEATURE_RDTSCP)))
8535 vmx->rdtscp_enabled = true;
8536 else {
8537 exec_control &= ~SECONDARY_EXEC_RDTSCP;
8538 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
8539 exec_control);
8542 if (nested && !vmx->rdtscp_enabled)
8543 vmx->nested.nested_vmx_secondary_ctls_high &=
8544 ~SECONDARY_EXEC_RDTSCP;
8547 /* Exposing INVPCID only when PCID is exposed */
8548 best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
8549 if (vmx_invpcid_supported() &&
8550 best && (best->ebx & bit(X86_FEATURE_INVPCID)) &&
8551 guest_cpuid_has_pcid(vcpu)) {
8552 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8553 exec_control |= SECONDARY_EXEC_ENABLE_INVPCID;
8554 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
8555 exec_control);
8556 } else {
8557 if (cpu_has_secondary_exec_ctrls()) {
8558 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8559 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
8560 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
8561 exec_control);
8563 if (best)
8564 best->ebx &= ~bit(X86_FEATURE_INVPCID);
8568 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
8570 if (func == 1 && nested)
8571 entry->ecx |= bit(X86_FEATURE_VMX);
8574 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
8575 struct x86_exception *fault)
8577 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8578 u32 exit_reason;
8580 if (fault->error_code & PFERR_RSVD_MASK)
8581 exit_reason = EXIT_REASON_EPT_MISCONFIG;
8582 else
8583 exit_reason = EXIT_REASON_EPT_VIOLATION;
8584 nested_vmx_vmexit(vcpu, exit_reason, 0, vcpu->arch.exit_qualification);
8585 vmcs12->guest_physical_address = fault->address;
8588 /* Callbacks for nested_ept_init_mmu_context: */
8590 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
8592 /* return the page table to be shadowed - in our case, EPT12 */
8593 return get_vmcs12(vcpu)->ept_pointer;
8596 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
8598 WARN_ON(mmu_is_nested(vcpu));
8599 kvm_init_shadow_ept_mmu(vcpu,
8600 to_vmx(vcpu)->nested.nested_vmx_ept_caps &
8601 VMX_EPT_EXECUTE_ONLY_BIT);
8602 vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
8603 vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
8604 vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
8606 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
8609 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
8611 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
8614 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
8615 u16 error_code)
8617 bool inequality, bit;
8619 bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
8620 inequality =
8621 (error_code & vmcs12->page_fault_error_code_mask) !=
8622 vmcs12->page_fault_error_code_match;
8623 return inequality ^ bit;
8626 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
8627 struct x86_exception *fault)
8629 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8631 WARN_ON(!is_guest_mode(vcpu));
8633 if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code))
8634 nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
8635 vmcs_read32(VM_EXIT_INTR_INFO),
8636 vmcs_readl(EXIT_QUALIFICATION));
8637 else
8638 kvm_inject_page_fault(vcpu, fault);
8641 static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
8642 struct vmcs12 *vmcs12)
8644 struct vcpu_vmx *vmx = to_vmx(vcpu);
8645 int maxphyaddr = cpuid_maxphyaddr(vcpu);
8647 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
8648 if (!PAGE_ALIGNED(vmcs12->apic_access_addr) ||
8649 vmcs12->apic_access_addr >> maxphyaddr)
8650 return false;
8653 * Translate L1 physical address to host physical
8654 * address for vmcs02. Keep the page pinned, so this
8655 * physical address remains valid. We keep a reference
8656 * to it so we can release it later.
8658 if (vmx->nested.apic_access_page) /* shouldn't happen */
8659 nested_release_page(vmx->nested.apic_access_page);
8660 vmx->nested.apic_access_page =
8661 nested_get_page(vcpu, vmcs12->apic_access_addr);
8664 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
8665 if (!PAGE_ALIGNED(vmcs12->virtual_apic_page_addr) ||
8666 vmcs12->virtual_apic_page_addr >> maxphyaddr)
8667 return false;
8669 if (vmx->nested.virtual_apic_page) /* shouldn't happen */
8670 nested_release_page(vmx->nested.virtual_apic_page);
8671 vmx->nested.virtual_apic_page =
8672 nested_get_page(vcpu, vmcs12->virtual_apic_page_addr);
8675 * Failing the vm entry is _not_ what the processor does
8676 * but it's basically the only possibility we have.
8677 * We could still enter the guest if CR8 load exits are
8678 * enabled, CR8 store exits are enabled, and virtualize APIC
8679 * access is disabled; in this case the processor would never
8680 * use the TPR shadow and we could simply clear the bit from
8681 * the execution control. But such a configuration is useless,
8682 * so let's keep the code simple.
8684 if (!vmx->nested.virtual_apic_page)
8685 return false;
8688 if (nested_cpu_has_posted_intr(vmcs12)) {
8689 if (!IS_ALIGNED(vmcs12->posted_intr_desc_addr, 64) ||
8690 vmcs12->posted_intr_desc_addr >> maxphyaddr)
8691 return false;
8693 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
8694 kunmap(vmx->nested.pi_desc_page);
8695 nested_release_page(vmx->nested.pi_desc_page);
8697 vmx->nested.pi_desc_page =
8698 nested_get_page(vcpu, vmcs12->posted_intr_desc_addr);
8699 if (!vmx->nested.pi_desc_page)
8700 return false;
8702 vmx->nested.pi_desc =
8703 (struct pi_desc *)kmap(vmx->nested.pi_desc_page);
8704 if (!vmx->nested.pi_desc) {
8705 nested_release_page_clean(vmx->nested.pi_desc_page);
8706 return false;
8708 vmx->nested.pi_desc =
8709 (struct pi_desc *)((void *)vmx->nested.pi_desc +
8710 (unsigned long)(vmcs12->posted_intr_desc_addr &
8711 (PAGE_SIZE - 1)));
8714 return true;
8717 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
8719 u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
8720 struct vcpu_vmx *vmx = to_vmx(vcpu);
8722 if (vcpu->arch.virtual_tsc_khz == 0)
8723 return;
8725 /* Make sure short timeouts reliably trigger an immediate vmexit.
8726 * hrtimer_start does not guarantee this. */
8727 if (preemption_timeout <= 1) {
8728 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
8729 return;
8732 preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
8733 preemption_timeout *= 1000000;
8734 do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
8735 hrtimer_start(&vmx->nested.preemption_timer,
8736 ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
8739 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
8740 struct vmcs12 *vmcs12)
8742 int maxphyaddr;
8743 u64 addr;
8745 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
8746 return 0;
8748 if (vmcs12_read_any(vcpu, MSR_BITMAP, &addr)) {
8749 WARN_ON(1);
8750 return -EINVAL;
8752 maxphyaddr = cpuid_maxphyaddr(vcpu);
8754 if (!PAGE_ALIGNED(vmcs12->msr_bitmap) ||
8755 ((addr + PAGE_SIZE) >> maxphyaddr))
8756 return -EINVAL;
8758 return 0;
8762 * Merge L0's and L1's MSR bitmap, return false to indicate that
8763 * we do not use the hardware.
8765 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
8766 struct vmcs12 *vmcs12)
8768 int msr;
8769 struct page *page;
8770 unsigned long *msr_bitmap;
8772 if (!nested_cpu_has_virt_x2apic_mode(vmcs12))
8773 return false;
8775 page = nested_get_page(vcpu, vmcs12->msr_bitmap);
8776 if (!page) {
8777 WARN_ON(1);
8778 return false;
8780 msr_bitmap = (unsigned long *)kmap(page);
8781 if (!msr_bitmap) {
8782 nested_release_page_clean(page);
8783 WARN_ON(1);
8784 return false;
8787 if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
8788 if (nested_cpu_has_apic_reg_virt(vmcs12))
8789 for (msr = 0x800; msr <= 0x8ff; msr++)
8790 nested_vmx_disable_intercept_for_msr(
8791 msr_bitmap,
8792 vmx_msr_bitmap_nested,
8793 msr, MSR_TYPE_R);
8794 /* TPR is allowed */
8795 nested_vmx_disable_intercept_for_msr(msr_bitmap,
8796 vmx_msr_bitmap_nested,
8797 APIC_BASE_MSR + (APIC_TASKPRI >> 4),
8798 MSR_TYPE_R | MSR_TYPE_W);
8799 if (nested_cpu_has_vid(vmcs12)) {
8800 /* EOI and self-IPI are allowed */
8801 nested_vmx_disable_intercept_for_msr(
8802 msr_bitmap,
8803 vmx_msr_bitmap_nested,
8804 APIC_BASE_MSR + (APIC_EOI >> 4),
8805 MSR_TYPE_W);
8806 nested_vmx_disable_intercept_for_msr(
8807 msr_bitmap,
8808 vmx_msr_bitmap_nested,
8809 APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
8810 MSR_TYPE_W);
8812 } else {
8814 * Enable reading intercept of all the x2apic
8815 * MSRs. We should not rely on vmcs12 to do any
8816 * optimizations here, it may have been modified
8817 * by L1.
8819 for (msr = 0x800; msr <= 0x8ff; msr++)
8820 __vmx_enable_intercept_for_msr(
8821 vmx_msr_bitmap_nested,
8822 msr,
8823 MSR_TYPE_R);
8825 __vmx_enable_intercept_for_msr(
8826 vmx_msr_bitmap_nested,
8827 APIC_BASE_MSR + (APIC_TASKPRI >> 4),
8828 MSR_TYPE_W);
8829 __vmx_enable_intercept_for_msr(
8830 vmx_msr_bitmap_nested,
8831 APIC_BASE_MSR + (APIC_EOI >> 4),
8832 MSR_TYPE_W);
8833 __vmx_enable_intercept_for_msr(
8834 vmx_msr_bitmap_nested,
8835 APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
8836 MSR_TYPE_W);
8838 kunmap(page);
8839 nested_release_page_clean(page);
8841 return true;
8844 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
8845 struct vmcs12 *vmcs12)
8847 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
8848 !nested_cpu_has_apic_reg_virt(vmcs12) &&
8849 !nested_cpu_has_vid(vmcs12) &&
8850 !nested_cpu_has_posted_intr(vmcs12))
8851 return 0;
8854 * If virtualize x2apic mode is enabled,
8855 * virtualize apic access must be disabled.
8857 if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
8858 nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
8859 return -EINVAL;
8862 * If virtual interrupt delivery is enabled,
8863 * we must exit on external interrupts.
8865 if (nested_cpu_has_vid(vmcs12) &&
8866 !nested_exit_on_intr(vcpu))
8867 return -EINVAL;
8870 * bits 15:8 should be zero in posted_intr_nv,
8871 * the descriptor address has been already checked
8872 * in nested_get_vmcs12_pages.
8874 if (nested_cpu_has_posted_intr(vmcs12) &&
8875 (!nested_cpu_has_vid(vmcs12) ||
8876 !nested_exit_intr_ack_set(vcpu) ||
8877 vmcs12->posted_intr_nv & 0xff00))
8878 return -EINVAL;
8880 /* tpr shadow is needed by all apicv features. */
8881 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
8882 return -EINVAL;
8884 return 0;
8887 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
8888 unsigned long count_field,
8889 unsigned long addr_field)
8891 int maxphyaddr;
8892 u64 count, addr;
8894 if (vmcs12_read_any(vcpu, count_field, &count) ||
8895 vmcs12_read_any(vcpu, addr_field, &addr)) {
8896 WARN_ON(1);
8897 return -EINVAL;
8899 if (count == 0)
8900 return 0;
8901 maxphyaddr = cpuid_maxphyaddr(vcpu);
8902 if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
8903 (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
8904 pr_warn_ratelimited(
8905 "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
8906 addr_field, maxphyaddr, count, addr);
8907 return -EINVAL;
8909 return 0;
8912 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
8913 struct vmcs12 *vmcs12)
8915 if (vmcs12->vm_exit_msr_load_count == 0 &&
8916 vmcs12->vm_exit_msr_store_count == 0 &&
8917 vmcs12->vm_entry_msr_load_count == 0)
8918 return 0; /* Fast path */
8919 if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
8920 VM_EXIT_MSR_LOAD_ADDR) ||
8921 nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
8922 VM_EXIT_MSR_STORE_ADDR) ||
8923 nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
8924 VM_ENTRY_MSR_LOAD_ADDR))
8925 return -EINVAL;
8926 return 0;
8929 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
8930 struct vmx_msr_entry *e)
8932 /* x2APIC MSR accesses are not allowed */
8933 if (apic_x2apic_mode(vcpu->arch.apic) && e->index >> 8 == 0x8)
8934 return -EINVAL;
8935 if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
8936 e->index == MSR_IA32_UCODE_REV)
8937 return -EINVAL;
8938 if (e->reserved != 0)
8939 return -EINVAL;
8940 return 0;
8943 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
8944 struct vmx_msr_entry *e)
8946 if (e->index == MSR_FS_BASE ||
8947 e->index == MSR_GS_BASE ||
8948 e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
8949 nested_vmx_msr_check_common(vcpu, e))
8950 return -EINVAL;
8951 return 0;
8954 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
8955 struct vmx_msr_entry *e)
8957 if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
8958 nested_vmx_msr_check_common(vcpu, e))
8959 return -EINVAL;
8960 return 0;
8964 * Load guest's/host's msr at nested entry/exit.
8965 * return 0 for success, entry index for failure.
8967 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
8969 u32 i;
8970 struct vmx_msr_entry e;
8971 struct msr_data msr;
8973 msr.host_initiated = false;
8974 for (i = 0; i < count; i++) {
8975 if (kvm_read_guest(vcpu->kvm, gpa + i * sizeof(e),
8976 &e, sizeof(e))) {
8977 pr_warn_ratelimited(
8978 "%s cannot read MSR entry (%u, 0x%08llx)\n",
8979 __func__, i, gpa + i * sizeof(e));
8980 goto fail;
8982 if (nested_vmx_load_msr_check(vcpu, &e)) {
8983 pr_warn_ratelimited(
8984 "%s check failed (%u, 0x%x, 0x%x)\n",
8985 __func__, i, e.index, e.reserved);
8986 goto fail;
8988 msr.index = e.index;
8989 msr.data = e.value;
8990 if (kvm_set_msr(vcpu, &msr)) {
8991 pr_warn_ratelimited(
8992 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
8993 __func__, i, e.index, e.value);
8994 goto fail;
8997 return 0;
8998 fail:
8999 return i + 1;
9002 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
9004 u32 i;
9005 struct vmx_msr_entry e;
9007 for (i = 0; i < count; i++) {
9008 if (kvm_read_guest(vcpu->kvm,
9009 gpa + i * sizeof(e),
9010 &e, 2 * sizeof(u32))) {
9011 pr_warn_ratelimited(
9012 "%s cannot read MSR entry (%u, 0x%08llx)\n",
9013 __func__, i, gpa + i * sizeof(e));
9014 return -EINVAL;
9016 if (nested_vmx_store_msr_check(vcpu, &e)) {
9017 pr_warn_ratelimited(
9018 "%s check failed (%u, 0x%x, 0x%x)\n",
9019 __func__, i, e.index, e.reserved);
9020 return -EINVAL;
9022 if (kvm_get_msr(vcpu, e.index, &e.value)) {
9023 pr_warn_ratelimited(
9024 "%s cannot read MSR (%u, 0x%x)\n",
9025 __func__, i, e.index);
9026 return -EINVAL;
9028 if (kvm_write_guest(vcpu->kvm,
9029 gpa + i * sizeof(e) +
9030 offsetof(struct vmx_msr_entry, value),
9031 &e.value, sizeof(e.value))) {
9032 pr_warn_ratelimited(
9033 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
9034 __func__, i, e.index, e.value);
9035 return -EINVAL;
9038 return 0;
9042 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
9043 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
9044 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
9045 * guest in a way that will both be appropriate to L1's requests, and our
9046 * needs. In addition to modifying the active vmcs (which is vmcs02), this
9047 * function also has additional necessary side-effects, like setting various
9048 * vcpu->arch fields.
9050 static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
9052 struct vcpu_vmx *vmx = to_vmx(vcpu);
9053 u32 exec_control;
9055 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
9056 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
9057 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
9058 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
9059 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
9060 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
9061 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
9062 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
9063 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
9064 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
9065 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
9066 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
9067 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
9068 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
9069 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
9070 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
9071 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
9072 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
9073 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
9074 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
9075 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
9076 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
9077 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
9078 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
9079 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
9080 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
9081 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
9082 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
9083 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
9084 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
9085 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
9086 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
9087 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
9088 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
9089 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
9090 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
9092 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
9093 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
9094 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
9095 } else {
9096 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
9097 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
9099 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
9100 vmcs12->vm_entry_intr_info_field);
9101 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
9102 vmcs12->vm_entry_exception_error_code);
9103 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
9104 vmcs12->vm_entry_instruction_len);
9105 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
9106 vmcs12->guest_interruptibility_info);
9107 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
9108 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
9109 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
9110 vmcs12->guest_pending_dbg_exceptions);
9111 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
9112 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
9114 if (nested_cpu_has_xsaves(vmcs12))
9115 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
9116 vmcs_write64(VMCS_LINK_POINTER, -1ull);
9118 exec_control = vmcs12->pin_based_vm_exec_control;
9119 exec_control |= vmcs_config.pin_based_exec_ctrl;
9120 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
9122 if (nested_cpu_has_posted_intr(vmcs12)) {
9124 * Note that we use L0's vector here and in
9125 * vmx_deliver_nested_posted_interrupt.
9127 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
9128 vmx->nested.pi_pending = false;
9129 vmcs_write64(POSTED_INTR_NV, POSTED_INTR_VECTOR);
9130 vmcs_write64(POSTED_INTR_DESC_ADDR,
9131 page_to_phys(vmx->nested.pi_desc_page) +
9132 (unsigned long)(vmcs12->posted_intr_desc_addr &
9133 (PAGE_SIZE - 1)));
9134 } else
9135 exec_control &= ~PIN_BASED_POSTED_INTR;
9137 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
9139 vmx->nested.preemption_timer_expired = false;
9140 if (nested_cpu_has_preemption_timer(vmcs12))
9141 vmx_start_preemption_timer(vcpu);
9144 * Whether page-faults are trapped is determined by a combination of
9145 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
9146 * If enable_ept, L0 doesn't care about page faults and we should
9147 * set all of these to L1's desires. However, if !enable_ept, L0 does
9148 * care about (at least some) page faults, and because it is not easy
9149 * (if at all possible?) to merge L0 and L1's desires, we simply ask
9150 * to exit on each and every L2 page fault. This is done by setting
9151 * MASK=MATCH=0 and (see below) EB.PF=1.
9152 * Note that below we don't need special code to set EB.PF beyond the
9153 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
9154 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
9155 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
9157 * A problem with this approach (when !enable_ept) is that L1 may be
9158 * injected with more page faults than it asked for. This could have
9159 * caused problems, but in practice existing hypervisors don't care.
9160 * To fix this, we will need to emulate the PFEC checking (on the L1
9161 * page tables), using walk_addr(), when injecting PFs to L1.
9163 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
9164 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
9165 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
9166 enable_ept ? vmcs12->page_fault_error_code_match : 0);
9168 if (cpu_has_secondary_exec_ctrls()) {
9169 exec_control = vmx_secondary_exec_control(vmx);
9170 if (!vmx->rdtscp_enabled)
9171 exec_control &= ~SECONDARY_EXEC_RDTSCP;
9172 /* Take the following fields only from vmcs12 */
9173 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
9174 SECONDARY_EXEC_RDTSCP |
9175 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
9176 SECONDARY_EXEC_APIC_REGISTER_VIRT);
9177 if (nested_cpu_has(vmcs12,
9178 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
9179 exec_control |= vmcs12->secondary_vm_exec_control;
9181 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
9183 * If translation failed, no matter: This feature asks
9184 * to exit when accessing the given address, and if it
9185 * can never be accessed, this feature won't do
9186 * anything anyway.
9188 if (!vmx->nested.apic_access_page)
9189 exec_control &=
9190 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9191 else
9192 vmcs_write64(APIC_ACCESS_ADDR,
9193 page_to_phys(vmx->nested.apic_access_page));
9194 } else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
9195 (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))) {
9196 exec_control |=
9197 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9198 kvm_vcpu_reload_apic_access_page(vcpu);
9201 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
9202 vmcs_write64(EOI_EXIT_BITMAP0,
9203 vmcs12->eoi_exit_bitmap0);
9204 vmcs_write64(EOI_EXIT_BITMAP1,
9205 vmcs12->eoi_exit_bitmap1);
9206 vmcs_write64(EOI_EXIT_BITMAP2,
9207 vmcs12->eoi_exit_bitmap2);
9208 vmcs_write64(EOI_EXIT_BITMAP3,
9209 vmcs12->eoi_exit_bitmap3);
9210 vmcs_write16(GUEST_INTR_STATUS,
9211 vmcs12->guest_intr_status);
9214 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
9219 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
9220 * Some constant fields are set here by vmx_set_constant_host_state().
9221 * Other fields are different per CPU, and will be set later when
9222 * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
9224 vmx_set_constant_host_state(vmx);
9227 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
9228 * entry, but only if the current (host) sp changed from the value
9229 * we wrote last (vmx->host_rsp). This cache is no longer relevant
9230 * if we switch vmcs, and rather than hold a separate cache per vmcs,
9231 * here we just force the write to happen on entry.
9233 vmx->host_rsp = 0;
9235 exec_control = vmx_exec_control(vmx); /* L0's desires */
9236 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
9237 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
9238 exec_control &= ~CPU_BASED_TPR_SHADOW;
9239 exec_control |= vmcs12->cpu_based_vm_exec_control;
9241 if (exec_control & CPU_BASED_TPR_SHADOW) {
9242 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
9243 page_to_phys(vmx->nested.virtual_apic_page));
9244 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
9247 if (cpu_has_vmx_msr_bitmap() &&
9248 exec_control & CPU_BASED_USE_MSR_BITMAPS) {
9249 nested_vmx_merge_msr_bitmap(vcpu, vmcs12);
9250 /* MSR_BITMAP will be set by following vmx_set_efer. */
9251 } else
9252 exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
9255 * Merging of IO bitmap not currently supported.
9256 * Rather, exit every time.
9258 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
9259 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
9261 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
9263 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
9264 * bitwise-or of what L1 wants to trap for L2, and what we want to
9265 * trap. Note that CR0.TS also needs updating - we do this later.
9267 update_exception_bitmap(vcpu);
9268 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
9269 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
9271 /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
9272 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
9273 * bits are further modified by vmx_set_efer() below.
9275 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
9277 /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
9278 * emulated by vmx_set_efer(), below.
9280 vm_entry_controls_init(vmx,
9281 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
9282 ~VM_ENTRY_IA32E_MODE) |
9283 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
9285 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) {
9286 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
9287 vcpu->arch.pat = vmcs12->guest_ia32_pat;
9288 } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
9289 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
9292 set_cr4_guest_host_mask(vmx);
9294 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
9295 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
9297 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
9298 vmcs_write64(TSC_OFFSET,
9299 vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset);
9300 else
9301 vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
9303 if (enable_vpid) {
9305 * Trivially support vpid by letting L2s share their parent
9306 * L1's vpid. TODO: move to a more elaborate solution, giving
9307 * each L2 its own vpid and exposing the vpid feature to L1.
9309 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
9310 vmx_flush_tlb(vcpu);
9313 if (nested_cpu_has_ept(vmcs12)) {
9314 kvm_mmu_unload(vcpu);
9315 nested_ept_init_mmu_context(vcpu);
9318 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
9319 vcpu->arch.efer = vmcs12->guest_ia32_efer;
9320 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
9321 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
9322 else
9323 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
9324 /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
9325 vmx_set_efer(vcpu, vcpu->arch.efer);
9328 * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
9329 * TS bit (for lazy fpu) and bits which we consider mandatory enabled.
9330 * The CR0_READ_SHADOW is what L2 should have expected to read given
9331 * the specifications by L1; It's not enough to take
9332 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
9333 * have more bits than L1 expected.
9335 vmx_set_cr0(vcpu, vmcs12->guest_cr0);
9336 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
9338 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
9339 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
9341 /* shadow page tables on either EPT or shadow page tables */
9342 kvm_set_cr3(vcpu, vmcs12->guest_cr3);
9343 kvm_mmu_reset_context(vcpu);
9345 if (!enable_ept)
9346 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
9349 * L1 may access the L2's PDPTR, so save them to construct vmcs12
9351 if (enable_ept) {
9352 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
9353 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
9354 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
9355 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
9358 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
9359 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
9363 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
9364 * for running an L2 nested guest.
9366 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
9368 struct vmcs12 *vmcs12;
9369 struct vcpu_vmx *vmx = to_vmx(vcpu);
9370 int cpu;
9371 struct loaded_vmcs *vmcs02;
9372 bool ia32e;
9373 u32 msr_entry_idx;
9375 if (!nested_vmx_check_permission(vcpu) ||
9376 !nested_vmx_check_vmcs12(vcpu))
9377 return 1;
9379 skip_emulated_instruction(vcpu);
9380 vmcs12 = get_vmcs12(vcpu);
9382 if (enable_shadow_vmcs)
9383 copy_shadow_to_vmcs12(vmx);
9386 * The nested entry process starts with enforcing various prerequisites
9387 * on vmcs12 as required by the Intel SDM, and act appropriately when
9388 * they fail: As the SDM explains, some conditions should cause the
9389 * instruction to fail, while others will cause the instruction to seem
9390 * to succeed, but return an EXIT_REASON_INVALID_STATE.
9391 * To speed up the normal (success) code path, we should avoid checking
9392 * for misconfigurations which will anyway be caught by the processor
9393 * when using the merged vmcs02.
9395 if (vmcs12->launch_state == launch) {
9396 nested_vmx_failValid(vcpu,
9397 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
9398 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
9399 return 1;
9402 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
9403 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT) {
9404 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
9405 return 1;
9408 if (!nested_get_vmcs12_pages(vcpu, vmcs12)) {
9409 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
9410 return 1;
9413 if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12)) {
9414 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
9415 return 1;
9418 if (nested_vmx_check_apicv_controls(vcpu, vmcs12)) {
9419 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
9420 return 1;
9423 if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12)) {
9424 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
9425 return 1;
9428 if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
9429 vmx->nested.nested_vmx_true_procbased_ctls_low,
9430 vmx->nested.nested_vmx_procbased_ctls_high) ||
9431 !vmx_control_verify(vmcs12->secondary_vm_exec_control,
9432 vmx->nested.nested_vmx_secondary_ctls_low,
9433 vmx->nested.nested_vmx_secondary_ctls_high) ||
9434 !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
9435 vmx->nested.nested_vmx_pinbased_ctls_low,
9436 vmx->nested.nested_vmx_pinbased_ctls_high) ||
9437 !vmx_control_verify(vmcs12->vm_exit_controls,
9438 vmx->nested.nested_vmx_true_exit_ctls_low,
9439 vmx->nested.nested_vmx_exit_ctls_high) ||
9440 !vmx_control_verify(vmcs12->vm_entry_controls,
9441 vmx->nested.nested_vmx_true_entry_ctls_low,
9442 vmx->nested.nested_vmx_entry_ctls_high))
9444 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
9445 return 1;
9448 if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
9449 ((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
9450 nested_vmx_failValid(vcpu,
9451 VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
9452 return 1;
9455 if (!nested_cr0_valid(vcpu, vmcs12->guest_cr0) ||
9456 ((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
9457 nested_vmx_entry_failure(vcpu, vmcs12,
9458 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
9459 return 1;
9461 if (vmcs12->vmcs_link_pointer != -1ull) {
9462 nested_vmx_entry_failure(vcpu, vmcs12,
9463 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
9464 return 1;
9468 * If the load IA32_EFER VM-entry control is 1, the following checks
9469 * are performed on the field for the IA32_EFER MSR:
9470 * - Bits reserved in the IA32_EFER MSR must be 0.
9471 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
9472 * the IA-32e mode guest VM-exit control. It must also be identical
9473 * to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
9474 * CR0.PG) is 1.
9476 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) {
9477 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
9478 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
9479 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
9480 ((vmcs12->guest_cr0 & X86_CR0_PG) &&
9481 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))) {
9482 nested_vmx_entry_failure(vcpu, vmcs12,
9483 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
9484 return 1;
9489 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
9490 * IA32_EFER MSR must be 0 in the field for that register. In addition,
9491 * the values of the LMA and LME bits in the field must each be that of
9492 * the host address-space size VM-exit control.
9494 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
9495 ia32e = (vmcs12->vm_exit_controls &
9496 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
9497 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
9498 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
9499 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)) {
9500 nested_vmx_entry_failure(vcpu, vmcs12,
9501 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
9502 return 1;
9507 * We're finally done with prerequisite checking, and can start with
9508 * the nested entry.
9511 vmcs02 = nested_get_current_vmcs02(vmx);
9512 if (!vmcs02)
9513 return -ENOMEM;
9515 enter_guest_mode(vcpu);
9517 vmx->nested.vmcs01_tsc_offset = vmcs_read64(TSC_OFFSET);
9519 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
9520 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
9522 cpu = get_cpu();
9523 vmx->loaded_vmcs = vmcs02;
9524 vmx_vcpu_put(vcpu);
9525 vmx_vcpu_load(vcpu, cpu);
9526 vcpu->cpu = cpu;
9527 put_cpu();
9529 vmx_segment_cache_clear(vmx);
9531 prepare_vmcs02(vcpu, vmcs12);
9533 msr_entry_idx = nested_vmx_load_msr(vcpu,
9534 vmcs12->vm_entry_msr_load_addr,
9535 vmcs12->vm_entry_msr_load_count);
9536 if (msr_entry_idx) {
9537 leave_guest_mode(vcpu);
9538 vmx_load_vmcs01(vcpu);
9539 nested_vmx_entry_failure(vcpu, vmcs12,
9540 EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
9541 return 1;
9544 vmcs12->launch_state = 1;
9546 if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
9547 return kvm_vcpu_halt(vcpu);
9549 vmx->nested.nested_run_pending = 1;
9552 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
9553 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
9554 * returned as far as L1 is concerned. It will only return (and set
9555 * the success flag) when L2 exits (see nested_vmx_vmexit()).
9557 return 1;
9561 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
9562 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
9563 * This function returns the new value we should put in vmcs12.guest_cr0.
9564 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
9565 * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
9566 * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
9567 * didn't trap the bit, because if L1 did, so would L0).
9568 * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
9569 * been modified by L2, and L1 knows it. So just leave the old value of
9570 * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
9571 * isn't relevant, because if L0 traps this bit it can set it to anything.
9572 * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
9573 * changed these bits, and therefore they need to be updated, but L0
9574 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather
9575 * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
9577 static inline unsigned long
9578 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
9580 return
9581 /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
9582 /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
9583 /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
9584 vcpu->arch.cr0_guest_owned_bits));
9587 static inline unsigned long
9588 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
9590 return
9591 /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
9592 /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
9593 /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
9594 vcpu->arch.cr4_guest_owned_bits));
9597 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
9598 struct vmcs12 *vmcs12)
9600 u32 idt_vectoring;
9601 unsigned int nr;
9603 if (vcpu->arch.exception.pending && vcpu->arch.exception.reinject) {
9604 nr = vcpu->arch.exception.nr;
9605 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
9607 if (kvm_exception_is_soft(nr)) {
9608 vmcs12->vm_exit_instruction_len =
9609 vcpu->arch.event_exit_inst_len;
9610 idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
9611 } else
9612 idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
9614 if (vcpu->arch.exception.has_error_code) {
9615 idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
9616 vmcs12->idt_vectoring_error_code =
9617 vcpu->arch.exception.error_code;
9620 vmcs12->idt_vectoring_info_field = idt_vectoring;
9621 } else if (vcpu->arch.nmi_injected) {
9622 vmcs12->idt_vectoring_info_field =
9623 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
9624 } else if (vcpu->arch.interrupt.pending) {
9625 nr = vcpu->arch.interrupt.nr;
9626 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
9628 if (vcpu->arch.interrupt.soft) {
9629 idt_vectoring |= INTR_TYPE_SOFT_INTR;
9630 vmcs12->vm_entry_instruction_len =
9631 vcpu->arch.event_exit_inst_len;
9632 } else
9633 idt_vectoring |= INTR_TYPE_EXT_INTR;
9635 vmcs12->idt_vectoring_info_field = idt_vectoring;
9639 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
9641 struct vcpu_vmx *vmx = to_vmx(vcpu);
9643 if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
9644 vmx->nested.preemption_timer_expired) {
9645 if (vmx->nested.nested_run_pending)
9646 return -EBUSY;
9647 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
9648 return 0;
9651 if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
9652 if (vmx->nested.nested_run_pending ||
9653 vcpu->arch.interrupt.pending)
9654 return -EBUSY;
9655 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
9656 NMI_VECTOR | INTR_TYPE_NMI_INTR |
9657 INTR_INFO_VALID_MASK, 0);
9659 * The NMI-triggered VM exit counts as injection:
9660 * clear this one and block further NMIs.
9662 vcpu->arch.nmi_pending = 0;
9663 vmx_set_nmi_mask(vcpu, true);
9664 return 0;
9667 if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
9668 nested_exit_on_intr(vcpu)) {
9669 if (vmx->nested.nested_run_pending)
9670 return -EBUSY;
9671 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
9672 return 0;
9675 return vmx_complete_nested_posted_interrupt(vcpu);
9678 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
9680 ktime_t remaining =
9681 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
9682 u64 value;
9684 if (ktime_to_ns(remaining) <= 0)
9685 return 0;
9687 value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
9688 do_div(value, 1000000);
9689 return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
9693 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
9694 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
9695 * and this function updates it to reflect the changes to the guest state while
9696 * L2 was running (and perhaps made some exits which were handled directly by L0
9697 * without going back to L1), and to reflect the exit reason.
9698 * Note that we do not have to copy here all VMCS fields, just those that
9699 * could have changed by the L2 guest or the exit - i.e., the guest-state and
9700 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
9701 * which already writes to vmcs12 directly.
9703 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
9704 u32 exit_reason, u32 exit_intr_info,
9705 unsigned long exit_qualification)
9707 /* update guest state fields: */
9708 vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
9709 vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
9711 vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
9712 vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
9713 vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
9715 vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
9716 vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
9717 vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
9718 vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
9719 vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
9720 vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
9721 vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
9722 vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
9723 vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
9724 vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
9725 vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
9726 vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
9727 vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
9728 vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
9729 vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
9730 vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
9731 vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
9732 vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
9733 vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
9734 vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
9735 vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
9736 vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
9737 vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
9738 vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
9739 vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
9740 vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
9741 vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
9742 vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
9743 vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
9744 vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
9745 vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
9746 vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
9747 vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
9748 vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
9749 vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
9750 vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
9752 vmcs12->guest_interruptibility_info =
9753 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
9754 vmcs12->guest_pending_dbg_exceptions =
9755 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
9756 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
9757 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
9758 else
9759 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
9761 if (nested_cpu_has_preemption_timer(vmcs12)) {
9762 if (vmcs12->vm_exit_controls &
9763 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
9764 vmcs12->vmx_preemption_timer_value =
9765 vmx_get_preemption_timer_value(vcpu);
9766 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
9770 * In some cases (usually, nested EPT), L2 is allowed to change its
9771 * own CR3 without exiting. If it has changed it, we must keep it.
9772 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
9773 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
9775 * Additionally, restore L2's PDPTR to vmcs12.
9777 if (enable_ept) {
9778 vmcs12->guest_cr3 = vmcs_read64(GUEST_CR3);
9779 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
9780 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
9781 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
9782 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
9785 if (nested_cpu_has_vid(vmcs12))
9786 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
9788 vmcs12->vm_entry_controls =
9789 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
9790 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
9792 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
9793 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
9794 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
9797 /* TODO: These cannot have changed unless we have MSR bitmaps and
9798 * the relevant bit asks not to trap the change */
9799 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
9800 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
9801 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
9802 vmcs12->guest_ia32_efer = vcpu->arch.efer;
9803 vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
9804 vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
9805 vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
9806 if (vmx_mpx_supported())
9807 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
9808 if (nested_cpu_has_xsaves(vmcs12))
9809 vmcs12->xss_exit_bitmap = vmcs_read64(XSS_EXIT_BITMAP);
9811 /* update exit information fields: */
9813 vmcs12->vm_exit_reason = exit_reason;
9814 vmcs12->exit_qualification = exit_qualification;
9816 vmcs12->vm_exit_intr_info = exit_intr_info;
9817 if ((vmcs12->vm_exit_intr_info &
9818 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
9819 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK))
9820 vmcs12->vm_exit_intr_error_code =
9821 vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
9822 vmcs12->idt_vectoring_info_field = 0;
9823 vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
9824 vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9826 if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
9827 /* vm_entry_intr_info_field is cleared on exit. Emulate this
9828 * instead of reading the real value. */
9829 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
9832 * Transfer the event that L0 or L1 may wanted to inject into
9833 * L2 to IDT_VECTORING_INFO_FIELD.
9835 vmcs12_save_pending_event(vcpu, vmcs12);
9839 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
9840 * preserved above and would only end up incorrectly in L1.
9842 vcpu->arch.nmi_injected = false;
9843 kvm_clear_exception_queue(vcpu);
9844 kvm_clear_interrupt_queue(vcpu);
9848 * A part of what we need to when the nested L2 guest exits and we want to
9849 * run its L1 parent, is to reset L1's guest state to the host state specified
9850 * in vmcs12.
9851 * This function is to be called not only on normal nested exit, but also on
9852 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
9853 * Failures During or After Loading Guest State").
9854 * This function should be called when the active VMCS is L1's (vmcs01).
9856 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
9857 struct vmcs12 *vmcs12)
9859 struct kvm_segment seg;
9861 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
9862 vcpu->arch.efer = vmcs12->host_ia32_efer;
9863 else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
9864 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
9865 else
9866 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
9867 vmx_set_efer(vcpu, vcpu->arch.efer);
9869 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
9870 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
9871 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
9873 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
9874 * actually changed, because it depends on the current state of
9875 * fpu_active (which may have changed).
9876 * Note that vmx_set_cr0 refers to efer set above.
9878 vmx_set_cr0(vcpu, vmcs12->host_cr0);
9880 * If we did fpu_activate()/fpu_deactivate() during L2's run, we need
9881 * to apply the same changes to L1's vmcs. We just set cr0 correctly,
9882 * but we also need to update cr0_guest_host_mask and exception_bitmap.
9884 update_exception_bitmap(vcpu);
9885 vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
9886 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
9889 * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
9890 * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
9892 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
9893 kvm_set_cr4(vcpu, vmcs12->host_cr4);
9895 nested_ept_uninit_mmu_context(vcpu);
9897 kvm_set_cr3(vcpu, vmcs12->host_cr3);
9898 kvm_mmu_reset_context(vcpu);
9900 if (!enable_ept)
9901 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
9903 if (enable_vpid) {
9905 * Trivially support vpid by letting L2s share their parent
9906 * L1's vpid. TODO: move to a more elaborate solution, giving
9907 * each L2 its own vpid and exposing the vpid feature to L1.
9909 vmx_flush_tlb(vcpu);
9913 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
9914 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
9915 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
9916 vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
9917 vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
9919 /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
9920 if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
9921 vmcs_write64(GUEST_BNDCFGS, 0);
9923 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
9924 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
9925 vcpu->arch.pat = vmcs12->host_ia32_pat;
9927 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
9928 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
9929 vmcs12->host_ia32_perf_global_ctrl);
9931 /* Set L1 segment info according to Intel SDM
9932 27.5.2 Loading Host Segment and Descriptor-Table Registers */
9933 seg = (struct kvm_segment) {
9934 .base = 0,
9935 .limit = 0xFFFFFFFF,
9936 .selector = vmcs12->host_cs_selector,
9937 .type = 11,
9938 .present = 1,
9939 .s = 1,
9940 .g = 1
9942 if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
9943 seg.l = 1;
9944 else
9945 seg.db = 1;
9946 vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
9947 seg = (struct kvm_segment) {
9948 .base = 0,
9949 .limit = 0xFFFFFFFF,
9950 .type = 3,
9951 .present = 1,
9952 .s = 1,
9953 .db = 1,
9954 .g = 1
9956 seg.selector = vmcs12->host_ds_selector;
9957 vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
9958 seg.selector = vmcs12->host_es_selector;
9959 vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
9960 seg.selector = vmcs12->host_ss_selector;
9961 vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
9962 seg.selector = vmcs12->host_fs_selector;
9963 seg.base = vmcs12->host_fs_base;
9964 vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
9965 seg.selector = vmcs12->host_gs_selector;
9966 seg.base = vmcs12->host_gs_base;
9967 vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
9968 seg = (struct kvm_segment) {
9969 .base = vmcs12->host_tr_base,
9970 .limit = 0x67,
9971 .selector = vmcs12->host_tr_selector,
9972 .type = 11,
9973 .present = 1
9975 vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
9977 kvm_set_dr(vcpu, 7, 0x400);
9978 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
9980 if (cpu_has_vmx_msr_bitmap())
9981 vmx_set_msr_bitmap(vcpu);
9983 if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
9984 vmcs12->vm_exit_msr_load_count))
9985 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
9989 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
9990 * and modify vmcs12 to make it see what it would expect to see there if
9991 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
9993 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
9994 u32 exit_intr_info,
9995 unsigned long exit_qualification)
9997 struct vcpu_vmx *vmx = to_vmx(vcpu);
9998 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10000 /* trying to cancel vmlaunch/vmresume is a bug */
10001 WARN_ON_ONCE(vmx->nested.nested_run_pending);
10003 leave_guest_mode(vcpu);
10004 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
10005 exit_qualification);
10007 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
10008 vmcs12->vm_exit_msr_store_count))
10009 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
10011 vmx_load_vmcs01(vcpu);
10013 if ((exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
10014 && nested_exit_intr_ack_set(vcpu)) {
10015 int irq = kvm_cpu_get_interrupt(vcpu);
10016 WARN_ON(irq < 0);
10017 vmcs12->vm_exit_intr_info = irq |
10018 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
10021 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
10022 vmcs12->exit_qualification,
10023 vmcs12->idt_vectoring_info_field,
10024 vmcs12->vm_exit_intr_info,
10025 vmcs12->vm_exit_intr_error_code,
10026 KVM_ISA_VMX);
10028 vm_entry_controls_init(vmx, vmcs_read32(VM_ENTRY_CONTROLS));
10029 vm_exit_controls_init(vmx, vmcs_read32(VM_EXIT_CONTROLS));
10030 vmx_segment_cache_clear(vmx);
10032 /* if no vmcs02 cache requested, remove the one we used */
10033 if (VMCS02_POOL_SIZE == 0)
10034 nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
10036 load_vmcs12_host_state(vcpu, vmcs12);
10038 /* Update TSC_OFFSET if TSC was changed while L2 ran */
10039 vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
10041 /* This is needed for same reason as it was needed in prepare_vmcs02 */
10042 vmx->host_rsp = 0;
10044 /* Unpin physical memory we referred to in vmcs02 */
10045 if (vmx->nested.apic_access_page) {
10046 nested_release_page(vmx->nested.apic_access_page);
10047 vmx->nested.apic_access_page = NULL;
10049 if (vmx->nested.virtual_apic_page) {
10050 nested_release_page(vmx->nested.virtual_apic_page);
10051 vmx->nested.virtual_apic_page = NULL;
10053 if (vmx->nested.pi_desc_page) {
10054 kunmap(vmx->nested.pi_desc_page);
10055 nested_release_page(vmx->nested.pi_desc_page);
10056 vmx->nested.pi_desc_page = NULL;
10057 vmx->nested.pi_desc = NULL;
10061 * We are now running in L2, mmu_notifier will force to reload the
10062 * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
10064 kvm_vcpu_reload_apic_access_page(vcpu);
10067 * Exiting from L2 to L1, we're now back to L1 which thinks it just
10068 * finished a VMLAUNCH or VMRESUME instruction, so we need to set the
10069 * success or failure flag accordingly.
10071 if (unlikely(vmx->fail)) {
10072 vmx->fail = 0;
10073 nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR));
10074 } else
10075 nested_vmx_succeed(vcpu);
10076 if (enable_shadow_vmcs)
10077 vmx->nested.sync_shadow_vmcs = true;
10079 /* in case we halted in L2 */
10080 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10084 * Forcibly leave nested mode in order to be able to reset the VCPU later on.
10086 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
10088 if (is_guest_mode(vcpu))
10089 nested_vmx_vmexit(vcpu, -1, 0, 0);
10090 free_nested(to_vmx(vcpu));
10094 * L1's failure to enter L2 is a subset of a normal exit, as explained in
10095 * 23.7 "VM-entry failures during or after loading guest state" (this also
10096 * lists the acceptable exit-reason and exit-qualification parameters).
10097 * It should only be called before L2 actually succeeded to run, and when
10098 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
10100 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
10101 struct vmcs12 *vmcs12,
10102 u32 reason, unsigned long qualification)
10104 load_vmcs12_host_state(vcpu, vmcs12);
10105 vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
10106 vmcs12->exit_qualification = qualification;
10107 nested_vmx_succeed(vcpu);
10108 if (enable_shadow_vmcs)
10109 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
10112 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
10113 struct x86_instruction_info *info,
10114 enum x86_intercept_stage stage)
10116 return X86EMUL_CONTINUE;
10119 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
10121 if (ple_gap)
10122 shrink_ple_window(vcpu);
10125 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
10126 struct kvm_memory_slot *slot)
10128 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
10129 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
10132 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
10133 struct kvm_memory_slot *slot)
10135 kvm_mmu_slot_set_dirty(kvm, slot);
10138 static void vmx_flush_log_dirty(struct kvm *kvm)
10140 kvm_flush_pml_buffers(kvm);
10143 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
10144 struct kvm_memory_slot *memslot,
10145 gfn_t offset, unsigned long mask)
10147 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
10150 static struct kvm_x86_ops vmx_x86_ops = {
10151 .cpu_has_kvm_support = cpu_has_kvm_support,
10152 .disabled_by_bios = vmx_disabled_by_bios,
10153 .hardware_setup = hardware_setup,
10154 .hardware_unsetup = hardware_unsetup,
10155 .check_processor_compatibility = vmx_check_processor_compat,
10156 .hardware_enable = hardware_enable,
10157 .hardware_disable = hardware_disable,
10158 .cpu_has_accelerated_tpr = report_flexpriority,
10160 .vcpu_create = vmx_create_vcpu,
10161 .vcpu_free = vmx_free_vcpu,
10162 .vcpu_reset = vmx_vcpu_reset,
10164 .prepare_guest_switch = vmx_save_host_state,
10165 .vcpu_load = vmx_vcpu_load,
10166 .vcpu_put = vmx_vcpu_put,
10168 .update_db_bp_intercept = update_exception_bitmap,
10169 .get_msr = vmx_get_msr,
10170 .set_msr = vmx_set_msr,
10171 .get_segment_base = vmx_get_segment_base,
10172 .get_segment = vmx_get_segment,
10173 .set_segment = vmx_set_segment,
10174 .get_cpl = vmx_get_cpl,
10175 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
10176 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
10177 .decache_cr3 = vmx_decache_cr3,
10178 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
10179 .set_cr0 = vmx_set_cr0,
10180 .set_cr3 = vmx_set_cr3,
10181 .set_cr4 = vmx_set_cr4,
10182 .set_efer = vmx_set_efer,
10183 .get_idt = vmx_get_idt,
10184 .set_idt = vmx_set_idt,
10185 .get_gdt = vmx_get_gdt,
10186 .set_gdt = vmx_set_gdt,
10187 .get_dr6 = vmx_get_dr6,
10188 .set_dr6 = vmx_set_dr6,
10189 .set_dr7 = vmx_set_dr7,
10190 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
10191 .cache_reg = vmx_cache_reg,
10192 .get_rflags = vmx_get_rflags,
10193 .set_rflags = vmx_set_rflags,
10194 .fpu_activate = vmx_fpu_activate,
10195 .fpu_deactivate = vmx_fpu_deactivate,
10197 .tlb_flush = vmx_flush_tlb,
10199 .run = vmx_vcpu_run,
10200 .handle_exit = vmx_handle_exit,
10201 .skip_emulated_instruction = skip_emulated_instruction,
10202 .set_interrupt_shadow = vmx_set_interrupt_shadow,
10203 .get_interrupt_shadow = vmx_get_interrupt_shadow,
10204 .patch_hypercall = vmx_patch_hypercall,
10205 .set_irq = vmx_inject_irq,
10206 .set_nmi = vmx_inject_nmi,
10207 .queue_exception = vmx_queue_exception,
10208 .cancel_injection = vmx_cancel_injection,
10209 .interrupt_allowed = vmx_interrupt_allowed,
10210 .nmi_allowed = vmx_nmi_allowed,
10211 .get_nmi_mask = vmx_get_nmi_mask,
10212 .set_nmi_mask = vmx_set_nmi_mask,
10213 .enable_nmi_window = enable_nmi_window,
10214 .enable_irq_window = enable_irq_window,
10215 .update_cr8_intercept = update_cr8_intercept,
10216 .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
10217 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
10218 .vm_has_apicv = vmx_vm_has_apicv,
10219 .load_eoi_exitmap = vmx_load_eoi_exitmap,
10220 .hwapic_irr_update = vmx_hwapic_irr_update,
10221 .hwapic_isr_update = vmx_hwapic_isr_update,
10222 .sync_pir_to_irr = vmx_sync_pir_to_irr,
10223 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
10225 .set_tss_addr = vmx_set_tss_addr,
10226 .get_tdp_level = get_ept_level,
10227 .get_mt_mask = vmx_get_mt_mask,
10229 .get_exit_info = vmx_get_exit_info,
10231 .get_lpage_level = vmx_get_lpage_level,
10233 .cpuid_update = vmx_cpuid_update,
10235 .rdtscp_supported = vmx_rdtscp_supported,
10236 .invpcid_supported = vmx_invpcid_supported,
10238 .set_supported_cpuid = vmx_set_supported_cpuid,
10240 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
10242 .set_tsc_khz = vmx_set_tsc_khz,
10243 .read_tsc_offset = vmx_read_tsc_offset,
10244 .write_tsc_offset = vmx_write_tsc_offset,
10245 .adjust_tsc_offset = vmx_adjust_tsc_offset,
10246 .compute_tsc_offset = vmx_compute_tsc_offset,
10247 .read_l1_tsc = vmx_read_l1_tsc,
10249 .set_tdp_cr3 = vmx_set_cr3,
10251 .check_intercept = vmx_check_intercept,
10252 .handle_external_intr = vmx_handle_external_intr,
10253 .mpx_supported = vmx_mpx_supported,
10254 .xsaves_supported = vmx_xsaves_supported,
10256 .check_nested_events = vmx_check_nested_events,
10258 .sched_in = vmx_sched_in,
10260 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
10261 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
10262 .flush_log_dirty = vmx_flush_log_dirty,
10263 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
10266 static int __init vmx_init(void)
10268 int r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
10269 __alignof__(struct vcpu_vmx), THIS_MODULE);
10270 if (r)
10271 return r;
10273 #ifdef CONFIG_KEXEC
10274 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
10275 crash_vmclear_local_loaded_vmcss);
10276 #endif
10278 return 0;
10281 static void __exit vmx_exit(void)
10283 #ifdef CONFIG_KEXEC
10284 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
10285 synchronize_rcu();
10286 #endif
10288 kvm_exit();
10291 module_init(vmx_init)
10292 module_exit(vmx_exit)