KVM: nVMX: Provide EFER.LMA saving support
[linux-2.6/btrfs-unstable.git] / arch / x86 / kvm / vmx.c
blob02f8c32b9b086189c72bf6fca58b33b1d16b970f
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 "kvm_cache_regs.h"
35 #include "x86.h"
37 #include <asm/io.h>
38 #include <asm/desc.h>
39 #include <asm/vmx.h>
40 #include <asm/virtext.h>
41 #include <asm/mce.h>
42 #include <asm/i387.h>
43 #include <asm/xcr.h>
44 #include <asm/perf_event.h>
45 #include <asm/kexec.h>
47 #include "trace.h"
49 #define __ex(x) __kvm_handle_fault_on_reboot(x)
50 #define __ex_clear(x, reg) \
51 ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
53 MODULE_AUTHOR("Qumranet");
54 MODULE_LICENSE("GPL");
56 static const struct x86_cpu_id vmx_cpu_id[] = {
57 X86_FEATURE_MATCH(X86_FEATURE_VMX),
60 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
62 static bool __read_mostly enable_vpid = 1;
63 module_param_named(vpid, enable_vpid, bool, 0444);
65 static bool __read_mostly flexpriority_enabled = 1;
66 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
68 static bool __read_mostly enable_ept = 1;
69 module_param_named(ept, enable_ept, bool, S_IRUGO);
71 static bool __read_mostly enable_unrestricted_guest = 1;
72 module_param_named(unrestricted_guest,
73 enable_unrestricted_guest, bool, S_IRUGO);
75 static bool __read_mostly enable_ept_ad_bits = 1;
76 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
78 static bool __read_mostly emulate_invalid_guest_state = true;
79 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
81 static bool __read_mostly vmm_exclusive = 1;
82 module_param(vmm_exclusive, bool, S_IRUGO);
84 static bool __read_mostly fasteoi = 1;
85 module_param(fasteoi, bool, S_IRUGO);
87 static bool __read_mostly enable_apicv_reg_vid;
90 * If nested=1, nested virtualization is supported, i.e., guests may use
91 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
92 * use VMX instructions.
94 static bool __read_mostly nested = 0;
95 module_param(nested, bool, S_IRUGO);
97 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
98 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
99 #define KVM_VM_CR0_ALWAYS_ON \
100 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
101 #define KVM_CR4_GUEST_OWNED_BITS \
102 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
103 | X86_CR4_OSXMMEXCPT)
105 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
106 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
108 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
111 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
112 * ple_gap: upper bound on the amount of time between two successive
113 * executions of PAUSE in a loop. Also indicate if ple enabled.
114 * According to test, this time is usually smaller than 128 cycles.
115 * ple_window: upper bound on the amount of time a guest is allowed to execute
116 * in a PAUSE loop. Tests indicate that most spinlocks are held for
117 * less than 2^12 cycles
118 * Time is measured based on a counter that runs at the same rate as the TSC,
119 * refer SDM volume 3b section 21.6.13 & 22.1.3.
121 #define KVM_VMX_DEFAULT_PLE_GAP 128
122 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
123 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
124 module_param(ple_gap, int, S_IRUGO);
126 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
127 module_param(ple_window, int, S_IRUGO);
129 extern const ulong vmx_return;
131 #define NR_AUTOLOAD_MSRS 8
132 #define VMCS02_POOL_SIZE 1
134 struct vmcs {
135 u32 revision_id;
136 u32 abort;
137 char data[0];
141 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
142 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
143 * loaded on this CPU (so we can clear them if the CPU goes down).
145 struct loaded_vmcs {
146 struct vmcs *vmcs;
147 int cpu;
148 int launched;
149 struct list_head loaded_vmcss_on_cpu_link;
152 struct shared_msr_entry {
153 unsigned index;
154 u64 data;
155 u64 mask;
159 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
160 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
161 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
162 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
163 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
164 * More than one of these structures may exist, if L1 runs multiple L2 guests.
165 * nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
166 * underlying hardware which will be used to run L2.
167 * This structure is packed to ensure that its layout is identical across
168 * machines (necessary for live migration).
169 * If there are changes in this struct, VMCS12_REVISION must be changed.
171 typedef u64 natural_width;
172 struct __packed vmcs12 {
173 /* According to the Intel spec, a VMCS region must start with the
174 * following two fields. Then follow implementation-specific data.
176 u32 revision_id;
177 u32 abort;
179 u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
180 u32 padding[7]; /* room for future expansion */
182 u64 io_bitmap_a;
183 u64 io_bitmap_b;
184 u64 msr_bitmap;
185 u64 vm_exit_msr_store_addr;
186 u64 vm_exit_msr_load_addr;
187 u64 vm_entry_msr_load_addr;
188 u64 tsc_offset;
189 u64 virtual_apic_page_addr;
190 u64 apic_access_addr;
191 u64 ept_pointer;
192 u64 guest_physical_address;
193 u64 vmcs_link_pointer;
194 u64 guest_ia32_debugctl;
195 u64 guest_ia32_pat;
196 u64 guest_ia32_efer;
197 u64 guest_ia32_perf_global_ctrl;
198 u64 guest_pdptr0;
199 u64 guest_pdptr1;
200 u64 guest_pdptr2;
201 u64 guest_pdptr3;
202 u64 host_ia32_pat;
203 u64 host_ia32_efer;
204 u64 host_ia32_perf_global_ctrl;
205 u64 padding64[8]; /* room for future expansion */
207 * To allow migration of L1 (complete with its L2 guests) between
208 * machines of different natural widths (32 or 64 bit), we cannot have
209 * unsigned long fields with no explict size. We use u64 (aliased
210 * natural_width) instead. Luckily, x86 is little-endian.
212 natural_width cr0_guest_host_mask;
213 natural_width cr4_guest_host_mask;
214 natural_width cr0_read_shadow;
215 natural_width cr4_read_shadow;
216 natural_width cr3_target_value0;
217 natural_width cr3_target_value1;
218 natural_width cr3_target_value2;
219 natural_width cr3_target_value3;
220 natural_width exit_qualification;
221 natural_width guest_linear_address;
222 natural_width guest_cr0;
223 natural_width guest_cr3;
224 natural_width guest_cr4;
225 natural_width guest_es_base;
226 natural_width guest_cs_base;
227 natural_width guest_ss_base;
228 natural_width guest_ds_base;
229 natural_width guest_fs_base;
230 natural_width guest_gs_base;
231 natural_width guest_ldtr_base;
232 natural_width guest_tr_base;
233 natural_width guest_gdtr_base;
234 natural_width guest_idtr_base;
235 natural_width guest_dr7;
236 natural_width guest_rsp;
237 natural_width guest_rip;
238 natural_width guest_rflags;
239 natural_width guest_pending_dbg_exceptions;
240 natural_width guest_sysenter_esp;
241 natural_width guest_sysenter_eip;
242 natural_width host_cr0;
243 natural_width host_cr3;
244 natural_width host_cr4;
245 natural_width host_fs_base;
246 natural_width host_gs_base;
247 natural_width host_tr_base;
248 natural_width host_gdtr_base;
249 natural_width host_idtr_base;
250 natural_width host_ia32_sysenter_esp;
251 natural_width host_ia32_sysenter_eip;
252 natural_width host_rsp;
253 natural_width host_rip;
254 natural_width paddingl[8]; /* room for future expansion */
255 u32 pin_based_vm_exec_control;
256 u32 cpu_based_vm_exec_control;
257 u32 exception_bitmap;
258 u32 page_fault_error_code_mask;
259 u32 page_fault_error_code_match;
260 u32 cr3_target_count;
261 u32 vm_exit_controls;
262 u32 vm_exit_msr_store_count;
263 u32 vm_exit_msr_load_count;
264 u32 vm_entry_controls;
265 u32 vm_entry_msr_load_count;
266 u32 vm_entry_intr_info_field;
267 u32 vm_entry_exception_error_code;
268 u32 vm_entry_instruction_len;
269 u32 tpr_threshold;
270 u32 secondary_vm_exec_control;
271 u32 vm_instruction_error;
272 u32 vm_exit_reason;
273 u32 vm_exit_intr_info;
274 u32 vm_exit_intr_error_code;
275 u32 idt_vectoring_info_field;
276 u32 idt_vectoring_error_code;
277 u32 vm_exit_instruction_len;
278 u32 vmx_instruction_info;
279 u32 guest_es_limit;
280 u32 guest_cs_limit;
281 u32 guest_ss_limit;
282 u32 guest_ds_limit;
283 u32 guest_fs_limit;
284 u32 guest_gs_limit;
285 u32 guest_ldtr_limit;
286 u32 guest_tr_limit;
287 u32 guest_gdtr_limit;
288 u32 guest_idtr_limit;
289 u32 guest_es_ar_bytes;
290 u32 guest_cs_ar_bytes;
291 u32 guest_ss_ar_bytes;
292 u32 guest_ds_ar_bytes;
293 u32 guest_fs_ar_bytes;
294 u32 guest_gs_ar_bytes;
295 u32 guest_ldtr_ar_bytes;
296 u32 guest_tr_ar_bytes;
297 u32 guest_interruptibility_info;
298 u32 guest_activity_state;
299 u32 guest_sysenter_cs;
300 u32 host_ia32_sysenter_cs;
301 u32 padding32[8]; /* room for future expansion */
302 u16 virtual_processor_id;
303 u16 guest_es_selector;
304 u16 guest_cs_selector;
305 u16 guest_ss_selector;
306 u16 guest_ds_selector;
307 u16 guest_fs_selector;
308 u16 guest_gs_selector;
309 u16 guest_ldtr_selector;
310 u16 guest_tr_selector;
311 u16 host_es_selector;
312 u16 host_cs_selector;
313 u16 host_ss_selector;
314 u16 host_ds_selector;
315 u16 host_fs_selector;
316 u16 host_gs_selector;
317 u16 host_tr_selector;
321 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
322 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
323 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
325 #define VMCS12_REVISION 0x11e57ed0
328 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
329 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
330 * current implementation, 4K are reserved to avoid future complications.
332 #define VMCS12_SIZE 0x1000
334 /* Used to remember the last vmcs02 used for some recently used vmcs12s */
335 struct vmcs02_list {
336 struct list_head list;
337 gpa_t vmptr;
338 struct loaded_vmcs vmcs02;
342 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
343 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
345 struct nested_vmx {
346 /* Has the level1 guest done vmxon? */
347 bool vmxon;
349 /* The guest-physical address of the current VMCS L1 keeps for L2 */
350 gpa_t current_vmptr;
351 /* The host-usable pointer to the above */
352 struct page *current_vmcs12_page;
353 struct vmcs12 *current_vmcs12;
355 /* vmcs02_list cache of VMCSs recently used to run L2 guests */
356 struct list_head vmcs02_pool;
357 int vmcs02_num;
358 u64 vmcs01_tsc_offset;
359 /* L2 must run next, and mustn't decide to exit to L1. */
360 bool nested_run_pending;
362 * Guest pages referred to in vmcs02 with host-physical pointers, so
363 * we must keep them pinned while L2 runs.
365 struct page *apic_access_page;
368 struct vcpu_vmx {
369 struct kvm_vcpu vcpu;
370 unsigned long host_rsp;
371 u8 fail;
372 u8 cpl;
373 bool nmi_known_unmasked;
374 u32 exit_intr_info;
375 u32 idt_vectoring_info;
376 ulong rflags;
377 struct shared_msr_entry *guest_msrs;
378 int nmsrs;
379 int save_nmsrs;
380 #ifdef CONFIG_X86_64
381 u64 msr_host_kernel_gs_base;
382 u64 msr_guest_kernel_gs_base;
383 #endif
385 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
386 * non-nested (L1) guest, it always points to vmcs01. For a nested
387 * guest (L2), it points to a different VMCS.
389 struct loaded_vmcs vmcs01;
390 struct loaded_vmcs *loaded_vmcs;
391 bool __launched; /* temporary, used in vmx_vcpu_run */
392 struct msr_autoload {
393 unsigned nr;
394 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
395 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
396 } msr_autoload;
397 struct {
398 int loaded;
399 u16 fs_sel, gs_sel, ldt_sel;
400 #ifdef CONFIG_X86_64
401 u16 ds_sel, es_sel;
402 #endif
403 int gs_ldt_reload_needed;
404 int fs_reload_needed;
405 } host_state;
406 struct {
407 int vm86_active;
408 ulong save_rflags;
409 struct kvm_segment segs[8];
410 } rmode;
411 struct {
412 u32 bitmask; /* 4 bits per segment (1 bit per field) */
413 struct kvm_save_segment {
414 u16 selector;
415 unsigned long base;
416 u32 limit;
417 u32 ar;
418 } seg[8];
419 } segment_cache;
420 int vpid;
421 bool emulation_required;
423 /* Support for vnmi-less CPUs */
424 int soft_vnmi_blocked;
425 ktime_t entry_time;
426 s64 vnmi_blocked_time;
427 u32 exit_reason;
429 bool rdtscp_enabled;
431 /* Support for a guest hypervisor (nested VMX) */
432 struct nested_vmx nested;
435 enum segment_cache_field {
436 SEG_FIELD_SEL = 0,
437 SEG_FIELD_BASE = 1,
438 SEG_FIELD_LIMIT = 2,
439 SEG_FIELD_AR = 3,
441 SEG_FIELD_NR = 4
444 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
446 return container_of(vcpu, struct vcpu_vmx, vcpu);
449 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
450 #define FIELD(number, name) [number] = VMCS12_OFFSET(name)
451 #define FIELD64(number, name) [number] = VMCS12_OFFSET(name), \
452 [number##_HIGH] = VMCS12_OFFSET(name)+4
454 static const unsigned short vmcs_field_to_offset_table[] = {
455 FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
456 FIELD(GUEST_ES_SELECTOR, guest_es_selector),
457 FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
458 FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
459 FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
460 FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
461 FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
462 FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
463 FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
464 FIELD(HOST_ES_SELECTOR, host_es_selector),
465 FIELD(HOST_CS_SELECTOR, host_cs_selector),
466 FIELD(HOST_SS_SELECTOR, host_ss_selector),
467 FIELD(HOST_DS_SELECTOR, host_ds_selector),
468 FIELD(HOST_FS_SELECTOR, host_fs_selector),
469 FIELD(HOST_GS_SELECTOR, host_gs_selector),
470 FIELD(HOST_TR_SELECTOR, host_tr_selector),
471 FIELD64(IO_BITMAP_A, io_bitmap_a),
472 FIELD64(IO_BITMAP_B, io_bitmap_b),
473 FIELD64(MSR_BITMAP, msr_bitmap),
474 FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
475 FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
476 FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
477 FIELD64(TSC_OFFSET, tsc_offset),
478 FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
479 FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
480 FIELD64(EPT_POINTER, ept_pointer),
481 FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
482 FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
483 FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
484 FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
485 FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
486 FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
487 FIELD64(GUEST_PDPTR0, guest_pdptr0),
488 FIELD64(GUEST_PDPTR1, guest_pdptr1),
489 FIELD64(GUEST_PDPTR2, guest_pdptr2),
490 FIELD64(GUEST_PDPTR3, guest_pdptr3),
491 FIELD64(HOST_IA32_PAT, host_ia32_pat),
492 FIELD64(HOST_IA32_EFER, host_ia32_efer),
493 FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
494 FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
495 FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
496 FIELD(EXCEPTION_BITMAP, exception_bitmap),
497 FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
498 FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
499 FIELD(CR3_TARGET_COUNT, cr3_target_count),
500 FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
501 FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
502 FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
503 FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
504 FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
505 FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
506 FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
507 FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
508 FIELD(TPR_THRESHOLD, tpr_threshold),
509 FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
510 FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
511 FIELD(VM_EXIT_REASON, vm_exit_reason),
512 FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
513 FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
514 FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
515 FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
516 FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
517 FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
518 FIELD(GUEST_ES_LIMIT, guest_es_limit),
519 FIELD(GUEST_CS_LIMIT, guest_cs_limit),
520 FIELD(GUEST_SS_LIMIT, guest_ss_limit),
521 FIELD(GUEST_DS_LIMIT, guest_ds_limit),
522 FIELD(GUEST_FS_LIMIT, guest_fs_limit),
523 FIELD(GUEST_GS_LIMIT, guest_gs_limit),
524 FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
525 FIELD(GUEST_TR_LIMIT, guest_tr_limit),
526 FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
527 FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
528 FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
529 FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
530 FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
531 FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
532 FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
533 FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
534 FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
535 FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
536 FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
537 FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
538 FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
539 FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
540 FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
541 FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
542 FIELD(CR0_READ_SHADOW, cr0_read_shadow),
543 FIELD(CR4_READ_SHADOW, cr4_read_shadow),
544 FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
545 FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
546 FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
547 FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
548 FIELD(EXIT_QUALIFICATION, exit_qualification),
549 FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
550 FIELD(GUEST_CR0, guest_cr0),
551 FIELD(GUEST_CR3, guest_cr3),
552 FIELD(GUEST_CR4, guest_cr4),
553 FIELD(GUEST_ES_BASE, guest_es_base),
554 FIELD(GUEST_CS_BASE, guest_cs_base),
555 FIELD(GUEST_SS_BASE, guest_ss_base),
556 FIELD(GUEST_DS_BASE, guest_ds_base),
557 FIELD(GUEST_FS_BASE, guest_fs_base),
558 FIELD(GUEST_GS_BASE, guest_gs_base),
559 FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
560 FIELD(GUEST_TR_BASE, guest_tr_base),
561 FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
562 FIELD(GUEST_IDTR_BASE, guest_idtr_base),
563 FIELD(GUEST_DR7, guest_dr7),
564 FIELD(GUEST_RSP, guest_rsp),
565 FIELD(GUEST_RIP, guest_rip),
566 FIELD(GUEST_RFLAGS, guest_rflags),
567 FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
568 FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
569 FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
570 FIELD(HOST_CR0, host_cr0),
571 FIELD(HOST_CR3, host_cr3),
572 FIELD(HOST_CR4, host_cr4),
573 FIELD(HOST_FS_BASE, host_fs_base),
574 FIELD(HOST_GS_BASE, host_gs_base),
575 FIELD(HOST_TR_BASE, host_tr_base),
576 FIELD(HOST_GDTR_BASE, host_gdtr_base),
577 FIELD(HOST_IDTR_BASE, host_idtr_base),
578 FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
579 FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
580 FIELD(HOST_RSP, host_rsp),
581 FIELD(HOST_RIP, host_rip),
583 static const int max_vmcs_field = ARRAY_SIZE(vmcs_field_to_offset_table);
585 static inline short vmcs_field_to_offset(unsigned long field)
587 if (field >= max_vmcs_field || vmcs_field_to_offset_table[field] == 0)
588 return -1;
589 return vmcs_field_to_offset_table[field];
592 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
594 return to_vmx(vcpu)->nested.current_vmcs12;
597 static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
599 struct page *page = gfn_to_page(vcpu->kvm, addr >> PAGE_SHIFT);
600 if (is_error_page(page))
601 return NULL;
603 return page;
606 static void nested_release_page(struct page *page)
608 kvm_release_page_dirty(page);
611 static void nested_release_page_clean(struct page *page)
613 kvm_release_page_clean(page);
616 static u64 construct_eptp(unsigned long root_hpa);
617 static void kvm_cpu_vmxon(u64 addr);
618 static void kvm_cpu_vmxoff(void);
619 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3);
620 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
621 static void vmx_set_segment(struct kvm_vcpu *vcpu,
622 struct kvm_segment *var, int seg);
623 static void vmx_get_segment(struct kvm_vcpu *vcpu,
624 struct kvm_segment *var, int seg);
625 static bool guest_state_valid(struct kvm_vcpu *vcpu);
626 static u32 vmx_segment_access_rights(struct kvm_segment *var);
628 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
629 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
631 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
632 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
634 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
635 static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
637 static unsigned long *vmx_io_bitmap_a;
638 static unsigned long *vmx_io_bitmap_b;
639 static unsigned long *vmx_msr_bitmap_legacy;
640 static unsigned long *vmx_msr_bitmap_longmode;
641 static unsigned long *vmx_msr_bitmap_legacy_x2apic;
642 static unsigned long *vmx_msr_bitmap_longmode_x2apic;
644 static bool cpu_has_load_ia32_efer;
645 static bool cpu_has_load_perf_global_ctrl;
647 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
648 static DEFINE_SPINLOCK(vmx_vpid_lock);
650 static struct vmcs_config {
651 int size;
652 int order;
653 u32 revision_id;
654 u32 pin_based_exec_ctrl;
655 u32 cpu_based_exec_ctrl;
656 u32 cpu_based_2nd_exec_ctrl;
657 u32 vmexit_ctrl;
658 u32 vmentry_ctrl;
659 } vmcs_config;
661 static struct vmx_capability {
662 u32 ept;
663 u32 vpid;
664 } vmx_capability;
666 #define VMX_SEGMENT_FIELD(seg) \
667 [VCPU_SREG_##seg] = { \
668 .selector = GUEST_##seg##_SELECTOR, \
669 .base = GUEST_##seg##_BASE, \
670 .limit = GUEST_##seg##_LIMIT, \
671 .ar_bytes = GUEST_##seg##_AR_BYTES, \
674 static const struct kvm_vmx_segment_field {
675 unsigned selector;
676 unsigned base;
677 unsigned limit;
678 unsigned ar_bytes;
679 } kvm_vmx_segment_fields[] = {
680 VMX_SEGMENT_FIELD(CS),
681 VMX_SEGMENT_FIELD(DS),
682 VMX_SEGMENT_FIELD(ES),
683 VMX_SEGMENT_FIELD(FS),
684 VMX_SEGMENT_FIELD(GS),
685 VMX_SEGMENT_FIELD(SS),
686 VMX_SEGMENT_FIELD(TR),
687 VMX_SEGMENT_FIELD(LDTR),
690 static u64 host_efer;
692 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
695 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
696 * away by decrementing the array size.
698 static const u32 vmx_msr_index[] = {
699 #ifdef CONFIG_X86_64
700 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
701 #endif
702 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
704 #define NR_VMX_MSR ARRAY_SIZE(vmx_msr_index)
706 static inline bool is_page_fault(u32 intr_info)
708 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
709 INTR_INFO_VALID_MASK)) ==
710 (INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
713 static inline bool is_no_device(u32 intr_info)
715 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
716 INTR_INFO_VALID_MASK)) ==
717 (INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
720 static inline bool is_invalid_opcode(u32 intr_info)
722 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
723 INTR_INFO_VALID_MASK)) ==
724 (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK);
727 static inline bool is_external_interrupt(u32 intr_info)
729 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
730 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
733 static inline bool is_machine_check(u32 intr_info)
735 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
736 INTR_INFO_VALID_MASK)) ==
737 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
740 static inline bool cpu_has_vmx_msr_bitmap(void)
742 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
745 static inline bool cpu_has_vmx_tpr_shadow(void)
747 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
750 static inline bool vm_need_tpr_shadow(struct kvm *kvm)
752 return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm));
755 static inline bool cpu_has_secondary_exec_ctrls(void)
757 return vmcs_config.cpu_based_exec_ctrl &
758 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
761 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
763 return vmcs_config.cpu_based_2nd_exec_ctrl &
764 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
767 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
769 return vmcs_config.cpu_based_2nd_exec_ctrl &
770 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
773 static inline bool cpu_has_vmx_apic_register_virt(void)
775 return vmcs_config.cpu_based_2nd_exec_ctrl &
776 SECONDARY_EXEC_APIC_REGISTER_VIRT;
779 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
781 return vmcs_config.cpu_based_2nd_exec_ctrl &
782 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
785 static inline bool cpu_has_vmx_flexpriority(void)
787 return cpu_has_vmx_tpr_shadow() &&
788 cpu_has_vmx_virtualize_apic_accesses();
791 static inline bool cpu_has_vmx_ept_execute_only(void)
793 return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
796 static inline bool cpu_has_vmx_eptp_uncacheable(void)
798 return vmx_capability.ept & VMX_EPTP_UC_BIT;
801 static inline bool cpu_has_vmx_eptp_writeback(void)
803 return vmx_capability.ept & VMX_EPTP_WB_BIT;
806 static inline bool cpu_has_vmx_ept_2m_page(void)
808 return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
811 static inline bool cpu_has_vmx_ept_1g_page(void)
813 return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
816 static inline bool cpu_has_vmx_ept_4levels(void)
818 return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
821 static inline bool cpu_has_vmx_ept_ad_bits(void)
823 return vmx_capability.ept & VMX_EPT_AD_BIT;
826 static inline bool cpu_has_vmx_invept_context(void)
828 return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
831 static inline bool cpu_has_vmx_invept_global(void)
833 return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
836 static inline bool cpu_has_vmx_invvpid_single(void)
838 return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
841 static inline bool cpu_has_vmx_invvpid_global(void)
843 return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
846 static inline bool cpu_has_vmx_ept(void)
848 return vmcs_config.cpu_based_2nd_exec_ctrl &
849 SECONDARY_EXEC_ENABLE_EPT;
852 static inline bool cpu_has_vmx_unrestricted_guest(void)
854 return vmcs_config.cpu_based_2nd_exec_ctrl &
855 SECONDARY_EXEC_UNRESTRICTED_GUEST;
858 static inline bool cpu_has_vmx_ple(void)
860 return vmcs_config.cpu_based_2nd_exec_ctrl &
861 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
864 static inline bool vm_need_virtualize_apic_accesses(struct kvm *kvm)
866 return flexpriority_enabled && irqchip_in_kernel(kvm);
869 static inline bool cpu_has_vmx_vpid(void)
871 return vmcs_config.cpu_based_2nd_exec_ctrl &
872 SECONDARY_EXEC_ENABLE_VPID;
875 static inline bool cpu_has_vmx_rdtscp(void)
877 return vmcs_config.cpu_based_2nd_exec_ctrl &
878 SECONDARY_EXEC_RDTSCP;
881 static inline bool cpu_has_vmx_invpcid(void)
883 return vmcs_config.cpu_based_2nd_exec_ctrl &
884 SECONDARY_EXEC_ENABLE_INVPCID;
887 static inline bool cpu_has_virtual_nmis(void)
889 return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
892 static inline bool cpu_has_vmx_wbinvd_exit(void)
894 return vmcs_config.cpu_based_2nd_exec_ctrl &
895 SECONDARY_EXEC_WBINVD_EXITING;
898 static inline bool report_flexpriority(void)
900 return flexpriority_enabled;
903 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
905 return vmcs12->cpu_based_vm_exec_control & bit;
908 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
910 return (vmcs12->cpu_based_vm_exec_control &
911 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
912 (vmcs12->secondary_vm_exec_control & bit);
915 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12,
916 struct kvm_vcpu *vcpu)
918 return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
921 static inline bool is_exception(u32 intr_info)
923 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
924 == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
927 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu);
928 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
929 struct vmcs12 *vmcs12,
930 u32 reason, unsigned long qualification);
932 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
934 int i;
936 for (i = 0; i < vmx->nmsrs; ++i)
937 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
938 return i;
939 return -1;
942 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
944 struct {
945 u64 vpid : 16;
946 u64 rsvd : 48;
947 u64 gva;
948 } operand = { vpid, 0, gva };
950 asm volatile (__ex(ASM_VMX_INVVPID)
951 /* CF==1 or ZF==1 --> rc = -1 */
952 "; ja 1f ; ud2 ; 1:"
953 : : "a"(&operand), "c"(ext) : "cc", "memory");
956 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
958 struct {
959 u64 eptp, gpa;
960 } operand = {eptp, gpa};
962 asm volatile (__ex(ASM_VMX_INVEPT)
963 /* CF==1 or ZF==1 --> rc = -1 */
964 "; ja 1f ; ud2 ; 1:\n"
965 : : "a" (&operand), "c" (ext) : "cc", "memory");
968 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
970 int i;
972 i = __find_msr_index(vmx, msr);
973 if (i >= 0)
974 return &vmx->guest_msrs[i];
975 return NULL;
978 static void vmcs_clear(struct vmcs *vmcs)
980 u64 phys_addr = __pa(vmcs);
981 u8 error;
983 asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
984 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
985 : "cc", "memory");
986 if (error)
987 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
988 vmcs, phys_addr);
991 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
993 vmcs_clear(loaded_vmcs->vmcs);
994 loaded_vmcs->cpu = -1;
995 loaded_vmcs->launched = 0;
998 static void vmcs_load(struct vmcs *vmcs)
1000 u64 phys_addr = __pa(vmcs);
1001 u8 error;
1003 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1004 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1005 : "cc", "memory");
1006 if (error)
1007 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1008 vmcs, phys_addr);
1011 #ifdef CONFIG_KEXEC
1013 * This bitmap is used to indicate whether the vmclear
1014 * operation is enabled on all cpus. All disabled by
1015 * default.
1017 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1019 static inline void crash_enable_local_vmclear(int cpu)
1021 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1024 static inline void crash_disable_local_vmclear(int cpu)
1026 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1029 static inline int crash_local_vmclear_enabled(int cpu)
1031 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1034 static void crash_vmclear_local_loaded_vmcss(void)
1036 int cpu = raw_smp_processor_id();
1037 struct loaded_vmcs *v;
1039 if (!crash_local_vmclear_enabled(cpu))
1040 return;
1042 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1043 loaded_vmcss_on_cpu_link)
1044 vmcs_clear(v->vmcs);
1046 #else
1047 static inline void crash_enable_local_vmclear(int cpu) { }
1048 static inline void crash_disable_local_vmclear(int cpu) { }
1049 #endif /* CONFIG_KEXEC */
1051 static void __loaded_vmcs_clear(void *arg)
1053 struct loaded_vmcs *loaded_vmcs = arg;
1054 int cpu = raw_smp_processor_id();
1056 if (loaded_vmcs->cpu != cpu)
1057 return; /* vcpu migration can race with cpu offline */
1058 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1059 per_cpu(current_vmcs, cpu) = NULL;
1060 crash_disable_local_vmclear(cpu);
1061 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1064 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1065 * is before setting loaded_vmcs->vcpu to -1 which is done in
1066 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1067 * then adds the vmcs into percpu list before it is deleted.
1069 smp_wmb();
1071 loaded_vmcs_init(loaded_vmcs);
1072 crash_enable_local_vmclear(cpu);
1075 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1077 int cpu = loaded_vmcs->cpu;
1079 if (cpu != -1)
1080 smp_call_function_single(cpu,
1081 __loaded_vmcs_clear, loaded_vmcs, 1);
1084 static inline void vpid_sync_vcpu_single(struct vcpu_vmx *vmx)
1086 if (vmx->vpid == 0)
1087 return;
1089 if (cpu_has_vmx_invvpid_single())
1090 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0);
1093 static inline void vpid_sync_vcpu_global(void)
1095 if (cpu_has_vmx_invvpid_global())
1096 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1099 static inline void vpid_sync_context(struct vcpu_vmx *vmx)
1101 if (cpu_has_vmx_invvpid_single())
1102 vpid_sync_vcpu_single(vmx);
1103 else
1104 vpid_sync_vcpu_global();
1107 static inline void ept_sync_global(void)
1109 if (cpu_has_vmx_invept_global())
1110 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1113 static inline void ept_sync_context(u64 eptp)
1115 if (enable_ept) {
1116 if (cpu_has_vmx_invept_context())
1117 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1118 else
1119 ept_sync_global();
1123 static __always_inline unsigned long vmcs_readl(unsigned long field)
1125 unsigned long value;
1127 asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1128 : "=a"(value) : "d"(field) : "cc");
1129 return value;
1132 static __always_inline u16 vmcs_read16(unsigned long field)
1134 return vmcs_readl(field);
1137 static __always_inline u32 vmcs_read32(unsigned long field)
1139 return vmcs_readl(field);
1142 static __always_inline u64 vmcs_read64(unsigned long field)
1144 #ifdef CONFIG_X86_64
1145 return vmcs_readl(field);
1146 #else
1147 return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
1148 #endif
1151 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1153 printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1154 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1155 dump_stack();
1158 static void vmcs_writel(unsigned long field, unsigned long value)
1160 u8 error;
1162 asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1163 : "=q"(error) : "a"(value), "d"(field) : "cc");
1164 if (unlikely(error))
1165 vmwrite_error(field, value);
1168 static void vmcs_write16(unsigned long field, u16 value)
1170 vmcs_writel(field, value);
1173 static void vmcs_write32(unsigned long field, u32 value)
1175 vmcs_writel(field, value);
1178 static void vmcs_write64(unsigned long field, u64 value)
1180 vmcs_writel(field, value);
1181 #ifndef CONFIG_X86_64
1182 asm volatile ("");
1183 vmcs_writel(field+1, value >> 32);
1184 #endif
1187 static void vmcs_clear_bits(unsigned long field, u32 mask)
1189 vmcs_writel(field, vmcs_readl(field) & ~mask);
1192 static void vmcs_set_bits(unsigned long field, u32 mask)
1194 vmcs_writel(field, vmcs_readl(field) | mask);
1197 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1199 vmx->segment_cache.bitmask = 0;
1202 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1203 unsigned field)
1205 bool ret;
1206 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1208 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1209 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1210 vmx->segment_cache.bitmask = 0;
1212 ret = vmx->segment_cache.bitmask & mask;
1213 vmx->segment_cache.bitmask |= mask;
1214 return ret;
1217 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1219 u16 *p = &vmx->segment_cache.seg[seg].selector;
1221 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1222 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1223 return *p;
1226 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1228 ulong *p = &vmx->segment_cache.seg[seg].base;
1230 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1231 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1232 return *p;
1235 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1237 u32 *p = &vmx->segment_cache.seg[seg].limit;
1239 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1240 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1241 return *p;
1244 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1246 u32 *p = &vmx->segment_cache.seg[seg].ar;
1248 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1249 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1250 return *p;
1253 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1255 u32 eb;
1257 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1258 (1u << NM_VECTOR) | (1u << DB_VECTOR);
1259 if ((vcpu->guest_debug &
1260 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1261 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1262 eb |= 1u << BP_VECTOR;
1263 if (to_vmx(vcpu)->rmode.vm86_active)
1264 eb = ~0;
1265 if (enable_ept)
1266 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1267 if (vcpu->fpu_active)
1268 eb &= ~(1u << NM_VECTOR);
1270 /* When we are running a nested L2 guest and L1 specified for it a
1271 * certain exception bitmap, we must trap the same exceptions and pass
1272 * them to L1. When running L2, we will only handle the exceptions
1273 * specified above if L1 did not want them.
1275 if (is_guest_mode(vcpu))
1276 eb |= get_vmcs12(vcpu)->exception_bitmap;
1278 vmcs_write32(EXCEPTION_BITMAP, eb);
1281 static void clear_atomic_switch_msr_special(unsigned long entry,
1282 unsigned long exit)
1284 vmcs_clear_bits(VM_ENTRY_CONTROLS, entry);
1285 vmcs_clear_bits(VM_EXIT_CONTROLS, exit);
1288 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1290 unsigned i;
1291 struct msr_autoload *m = &vmx->msr_autoload;
1293 switch (msr) {
1294 case MSR_EFER:
1295 if (cpu_has_load_ia32_efer) {
1296 clear_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
1297 VM_EXIT_LOAD_IA32_EFER);
1298 return;
1300 break;
1301 case MSR_CORE_PERF_GLOBAL_CTRL:
1302 if (cpu_has_load_perf_global_ctrl) {
1303 clear_atomic_switch_msr_special(
1304 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1305 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1306 return;
1308 break;
1311 for (i = 0; i < m->nr; ++i)
1312 if (m->guest[i].index == msr)
1313 break;
1315 if (i == m->nr)
1316 return;
1317 --m->nr;
1318 m->guest[i] = m->guest[m->nr];
1319 m->host[i] = m->host[m->nr];
1320 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1321 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1324 static void add_atomic_switch_msr_special(unsigned long entry,
1325 unsigned long exit, unsigned long guest_val_vmcs,
1326 unsigned long host_val_vmcs, u64 guest_val, u64 host_val)
1328 vmcs_write64(guest_val_vmcs, guest_val);
1329 vmcs_write64(host_val_vmcs, host_val);
1330 vmcs_set_bits(VM_ENTRY_CONTROLS, entry);
1331 vmcs_set_bits(VM_EXIT_CONTROLS, exit);
1334 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1335 u64 guest_val, u64 host_val)
1337 unsigned i;
1338 struct msr_autoload *m = &vmx->msr_autoload;
1340 switch (msr) {
1341 case MSR_EFER:
1342 if (cpu_has_load_ia32_efer) {
1343 add_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
1344 VM_EXIT_LOAD_IA32_EFER,
1345 GUEST_IA32_EFER,
1346 HOST_IA32_EFER,
1347 guest_val, host_val);
1348 return;
1350 break;
1351 case MSR_CORE_PERF_GLOBAL_CTRL:
1352 if (cpu_has_load_perf_global_ctrl) {
1353 add_atomic_switch_msr_special(
1354 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1355 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1356 GUEST_IA32_PERF_GLOBAL_CTRL,
1357 HOST_IA32_PERF_GLOBAL_CTRL,
1358 guest_val, host_val);
1359 return;
1361 break;
1364 for (i = 0; i < m->nr; ++i)
1365 if (m->guest[i].index == msr)
1366 break;
1368 if (i == NR_AUTOLOAD_MSRS) {
1369 printk_once(KERN_WARNING"Not enough mst switch entries. "
1370 "Can't add msr %x\n", msr);
1371 return;
1372 } else if (i == m->nr) {
1373 ++m->nr;
1374 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1375 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1378 m->guest[i].index = msr;
1379 m->guest[i].value = guest_val;
1380 m->host[i].index = msr;
1381 m->host[i].value = host_val;
1384 static void reload_tss(void)
1387 * VT restores TR but not its size. Useless.
1389 struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1390 struct desc_struct *descs;
1392 descs = (void *)gdt->address;
1393 descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
1394 load_TR_desc();
1397 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
1399 u64 guest_efer;
1400 u64 ignore_bits;
1402 guest_efer = vmx->vcpu.arch.efer;
1405 * NX is emulated; LMA and LME handled by hardware; SCE meaningless
1406 * outside long mode
1408 ignore_bits = EFER_NX | EFER_SCE;
1409 #ifdef CONFIG_X86_64
1410 ignore_bits |= EFER_LMA | EFER_LME;
1411 /* SCE is meaningful only in long mode on Intel */
1412 if (guest_efer & EFER_LMA)
1413 ignore_bits &= ~(u64)EFER_SCE;
1414 #endif
1415 guest_efer &= ~ignore_bits;
1416 guest_efer |= host_efer & ignore_bits;
1417 vmx->guest_msrs[efer_offset].data = guest_efer;
1418 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1420 clear_atomic_switch_msr(vmx, MSR_EFER);
1421 /* On ept, can't emulate nx, and must switch nx atomically */
1422 if (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX)) {
1423 guest_efer = vmx->vcpu.arch.efer;
1424 if (!(guest_efer & EFER_LMA))
1425 guest_efer &= ~EFER_LME;
1426 add_atomic_switch_msr(vmx, MSR_EFER, guest_efer, host_efer);
1427 return false;
1430 return true;
1433 static unsigned long segment_base(u16 selector)
1435 struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1436 struct desc_struct *d;
1437 unsigned long table_base;
1438 unsigned long v;
1440 if (!(selector & ~3))
1441 return 0;
1443 table_base = gdt->address;
1445 if (selector & 4) { /* from ldt */
1446 u16 ldt_selector = kvm_read_ldt();
1448 if (!(ldt_selector & ~3))
1449 return 0;
1451 table_base = segment_base(ldt_selector);
1453 d = (struct desc_struct *)(table_base + (selector & ~7));
1454 v = get_desc_base(d);
1455 #ifdef CONFIG_X86_64
1456 if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
1457 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
1458 #endif
1459 return v;
1462 static inline unsigned long kvm_read_tr_base(void)
1464 u16 tr;
1465 asm("str %0" : "=g"(tr));
1466 return segment_base(tr);
1469 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
1471 struct vcpu_vmx *vmx = to_vmx(vcpu);
1472 int i;
1474 if (vmx->host_state.loaded)
1475 return;
1477 vmx->host_state.loaded = 1;
1479 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1480 * allow segment selectors with cpl > 0 or ti == 1.
1482 vmx->host_state.ldt_sel = kvm_read_ldt();
1483 vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
1484 savesegment(fs, vmx->host_state.fs_sel);
1485 if (!(vmx->host_state.fs_sel & 7)) {
1486 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
1487 vmx->host_state.fs_reload_needed = 0;
1488 } else {
1489 vmcs_write16(HOST_FS_SELECTOR, 0);
1490 vmx->host_state.fs_reload_needed = 1;
1492 savesegment(gs, vmx->host_state.gs_sel);
1493 if (!(vmx->host_state.gs_sel & 7))
1494 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
1495 else {
1496 vmcs_write16(HOST_GS_SELECTOR, 0);
1497 vmx->host_state.gs_ldt_reload_needed = 1;
1500 #ifdef CONFIG_X86_64
1501 savesegment(ds, vmx->host_state.ds_sel);
1502 savesegment(es, vmx->host_state.es_sel);
1503 #endif
1505 #ifdef CONFIG_X86_64
1506 vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
1507 vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
1508 #else
1509 vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
1510 vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
1511 #endif
1513 #ifdef CONFIG_X86_64
1514 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1515 if (is_long_mode(&vmx->vcpu))
1516 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1517 #endif
1518 for (i = 0; i < vmx->save_nmsrs; ++i)
1519 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1520 vmx->guest_msrs[i].data,
1521 vmx->guest_msrs[i].mask);
1524 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
1526 if (!vmx->host_state.loaded)
1527 return;
1529 ++vmx->vcpu.stat.host_state_reload;
1530 vmx->host_state.loaded = 0;
1531 #ifdef CONFIG_X86_64
1532 if (is_long_mode(&vmx->vcpu))
1533 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1534 #endif
1535 if (vmx->host_state.gs_ldt_reload_needed) {
1536 kvm_load_ldt(vmx->host_state.ldt_sel);
1537 #ifdef CONFIG_X86_64
1538 load_gs_index(vmx->host_state.gs_sel);
1539 #else
1540 loadsegment(gs, vmx->host_state.gs_sel);
1541 #endif
1543 if (vmx->host_state.fs_reload_needed)
1544 loadsegment(fs, vmx->host_state.fs_sel);
1545 #ifdef CONFIG_X86_64
1546 if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
1547 loadsegment(ds, vmx->host_state.ds_sel);
1548 loadsegment(es, vmx->host_state.es_sel);
1550 #endif
1551 reload_tss();
1552 #ifdef CONFIG_X86_64
1553 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1554 #endif
1556 * If the FPU is not active (through the host task or
1557 * the guest vcpu), then restore the cr0.TS bit.
1559 if (!user_has_fpu() && !vmx->vcpu.guest_fpu_loaded)
1560 stts();
1561 load_gdt(&__get_cpu_var(host_gdt));
1564 static void vmx_load_host_state(struct vcpu_vmx *vmx)
1566 preempt_disable();
1567 __vmx_load_host_state(vmx);
1568 preempt_enable();
1572 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1573 * vcpu mutex is already taken.
1575 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1577 struct vcpu_vmx *vmx = to_vmx(vcpu);
1578 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1580 if (!vmm_exclusive)
1581 kvm_cpu_vmxon(phys_addr);
1582 else if (vmx->loaded_vmcs->cpu != cpu)
1583 loaded_vmcs_clear(vmx->loaded_vmcs);
1585 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1586 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1587 vmcs_load(vmx->loaded_vmcs->vmcs);
1590 if (vmx->loaded_vmcs->cpu != cpu) {
1591 struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1592 unsigned long sysenter_esp;
1594 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1595 local_irq_disable();
1596 crash_disable_local_vmclear(cpu);
1599 * Read loaded_vmcs->cpu should be before fetching
1600 * loaded_vmcs->loaded_vmcss_on_cpu_link.
1601 * See the comments in __loaded_vmcs_clear().
1603 smp_rmb();
1605 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1606 &per_cpu(loaded_vmcss_on_cpu, cpu));
1607 crash_enable_local_vmclear(cpu);
1608 local_irq_enable();
1611 * Linux uses per-cpu TSS and GDT, so set these when switching
1612 * processors.
1614 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
1615 vmcs_writel(HOST_GDTR_BASE, gdt->address); /* 22.2.4 */
1617 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1618 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1619 vmx->loaded_vmcs->cpu = cpu;
1623 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1625 __vmx_load_host_state(to_vmx(vcpu));
1626 if (!vmm_exclusive) {
1627 __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
1628 vcpu->cpu = -1;
1629 kvm_cpu_vmxoff();
1633 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
1635 ulong cr0;
1637 if (vcpu->fpu_active)
1638 return;
1639 vcpu->fpu_active = 1;
1640 cr0 = vmcs_readl(GUEST_CR0);
1641 cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
1642 cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
1643 vmcs_writel(GUEST_CR0, cr0);
1644 update_exception_bitmap(vcpu);
1645 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
1646 if (is_guest_mode(vcpu))
1647 vcpu->arch.cr0_guest_owned_bits &=
1648 ~get_vmcs12(vcpu)->cr0_guest_host_mask;
1649 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1652 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1655 * Return the cr0 value that a nested guest would read. This is a combination
1656 * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
1657 * its hypervisor (cr0_read_shadow).
1659 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
1661 return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
1662 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
1664 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
1666 return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
1667 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
1670 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
1672 /* Note that there is no vcpu->fpu_active = 0 here. The caller must
1673 * set this *before* calling this function.
1675 vmx_decache_cr0_guest_bits(vcpu);
1676 vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
1677 update_exception_bitmap(vcpu);
1678 vcpu->arch.cr0_guest_owned_bits = 0;
1679 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1680 if (is_guest_mode(vcpu)) {
1682 * L1's specified read shadow might not contain the TS bit,
1683 * so now that we turned on shadowing of this bit, we need to
1684 * set this bit of the shadow. Like in nested_vmx_run we need
1685 * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
1686 * up-to-date here because we just decached cr0.TS (and we'll
1687 * only update vmcs12->guest_cr0 on nested exit).
1689 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1690 vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
1691 (vcpu->arch.cr0 & X86_CR0_TS);
1692 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
1693 } else
1694 vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
1697 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1699 unsigned long rflags, save_rflags;
1701 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1702 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1703 rflags = vmcs_readl(GUEST_RFLAGS);
1704 if (to_vmx(vcpu)->rmode.vm86_active) {
1705 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1706 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1707 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1709 to_vmx(vcpu)->rflags = rflags;
1711 return to_vmx(vcpu)->rflags;
1714 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1716 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1717 to_vmx(vcpu)->rflags = rflags;
1718 if (to_vmx(vcpu)->rmode.vm86_active) {
1719 to_vmx(vcpu)->rmode.save_rflags = rflags;
1720 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1722 vmcs_writel(GUEST_RFLAGS, rflags);
1725 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1727 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1728 int ret = 0;
1730 if (interruptibility & GUEST_INTR_STATE_STI)
1731 ret |= KVM_X86_SHADOW_INT_STI;
1732 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1733 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1735 return ret & mask;
1738 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1740 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1741 u32 interruptibility = interruptibility_old;
1743 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1745 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1746 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1747 else if (mask & KVM_X86_SHADOW_INT_STI)
1748 interruptibility |= GUEST_INTR_STATE_STI;
1750 if ((interruptibility != interruptibility_old))
1751 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1754 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1756 unsigned long rip;
1758 rip = kvm_rip_read(vcpu);
1759 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1760 kvm_rip_write(vcpu, rip);
1762 /* skipping an emulated instruction also counts */
1763 vmx_set_interrupt_shadow(vcpu, 0);
1767 * KVM wants to inject page-faults which it got to the guest. This function
1768 * checks whether in a nested guest, we need to inject them to L1 or L2.
1769 * This function assumes it is called with the exit reason in vmcs02 being
1770 * a #PF exception (this is the only case in which KVM injects a #PF when L2
1771 * is running).
1773 static int nested_pf_handled(struct kvm_vcpu *vcpu)
1775 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1777 /* TODO: also check PFEC_MATCH/MASK, not just EB.PF. */
1778 if (!(vmcs12->exception_bitmap & (1u << PF_VECTOR)))
1779 return 0;
1781 nested_vmx_vmexit(vcpu);
1782 return 1;
1785 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
1786 bool has_error_code, u32 error_code,
1787 bool reinject)
1789 struct vcpu_vmx *vmx = to_vmx(vcpu);
1790 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1792 if (nr == PF_VECTOR && is_guest_mode(vcpu) &&
1793 nested_pf_handled(vcpu))
1794 return;
1796 if (has_error_code) {
1797 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1798 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1801 if (vmx->rmode.vm86_active) {
1802 int inc_eip = 0;
1803 if (kvm_exception_is_soft(nr))
1804 inc_eip = vcpu->arch.event_exit_inst_len;
1805 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1806 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1807 return;
1810 if (kvm_exception_is_soft(nr)) {
1811 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1812 vmx->vcpu.arch.event_exit_inst_len);
1813 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1814 } else
1815 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1817 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1820 static bool vmx_rdtscp_supported(void)
1822 return cpu_has_vmx_rdtscp();
1825 static bool vmx_invpcid_supported(void)
1827 return cpu_has_vmx_invpcid() && enable_ept;
1831 * Swap MSR entry in host/guest MSR entry array.
1833 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1835 struct shared_msr_entry tmp;
1837 tmp = vmx->guest_msrs[to];
1838 vmx->guest_msrs[to] = vmx->guest_msrs[from];
1839 vmx->guest_msrs[from] = tmp;
1842 static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
1844 unsigned long *msr_bitmap;
1846 if (irqchip_in_kernel(vcpu->kvm) && apic_x2apic_mode(vcpu->arch.apic)) {
1847 if (is_long_mode(vcpu))
1848 msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
1849 else
1850 msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
1851 } else {
1852 if (is_long_mode(vcpu))
1853 msr_bitmap = vmx_msr_bitmap_longmode;
1854 else
1855 msr_bitmap = vmx_msr_bitmap_legacy;
1858 vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
1862 * Set up the vmcs to automatically save and restore system
1863 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1864 * mode, as fiddling with msrs is very expensive.
1866 static void setup_msrs(struct vcpu_vmx *vmx)
1868 int save_nmsrs, index;
1870 save_nmsrs = 0;
1871 #ifdef CONFIG_X86_64
1872 if (is_long_mode(&vmx->vcpu)) {
1873 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1874 if (index >= 0)
1875 move_msr_up(vmx, index, save_nmsrs++);
1876 index = __find_msr_index(vmx, MSR_LSTAR);
1877 if (index >= 0)
1878 move_msr_up(vmx, index, save_nmsrs++);
1879 index = __find_msr_index(vmx, MSR_CSTAR);
1880 if (index >= 0)
1881 move_msr_up(vmx, index, save_nmsrs++);
1882 index = __find_msr_index(vmx, MSR_TSC_AUX);
1883 if (index >= 0 && vmx->rdtscp_enabled)
1884 move_msr_up(vmx, index, save_nmsrs++);
1886 * MSR_STAR is only needed on long mode guests, and only
1887 * if efer.sce is enabled.
1889 index = __find_msr_index(vmx, MSR_STAR);
1890 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
1891 move_msr_up(vmx, index, save_nmsrs++);
1893 #endif
1894 index = __find_msr_index(vmx, MSR_EFER);
1895 if (index >= 0 && update_transition_efer(vmx, index))
1896 move_msr_up(vmx, index, save_nmsrs++);
1898 vmx->save_nmsrs = save_nmsrs;
1900 if (cpu_has_vmx_msr_bitmap())
1901 vmx_set_msr_bitmap(&vmx->vcpu);
1905 * reads and returns guest's timestamp counter "register"
1906 * guest_tsc = host_tsc + tsc_offset -- 21.3
1908 static u64 guest_read_tsc(void)
1910 u64 host_tsc, tsc_offset;
1912 rdtscll(host_tsc);
1913 tsc_offset = vmcs_read64(TSC_OFFSET);
1914 return host_tsc + tsc_offset;
1918 * Like guest_read_tsc, but always returns L1's notion of the timestamp
1919 * counter, even if a nested guest (L2) is currently running.
1921 u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1923 u64 tsc_offset;
1925 tsc_offset = is_guest_mode(vcpu) ?
1926 to_vmx(vcpu)->nested.vmcs01_tsc_offset :
1927 vmcs_read64(TSC_OFFSET);
1928 return host_tsc + tsc_offset;
1932 * Engage any workarounds for mis-matched TSC rates. Currently limited to
1933 * software catchup for faster rates on slower CPUs.
1935 static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1937 if (!scale)
1938 return;
1940 if (user_tsc_khz > tsc_khz) {
1941 vcpu->arch.tsc_catchup = 1;
1942 vcpu->arch.tsc_always_catchup = 1;
1943 } else
1944 WARN(1, "user requested TSC rate below hardware speed\n");
1947 static u64 vmx_read_tsc_offset(struct kvm_vcpu *vcpu)
1949 return vmcs_read64(TSC_OFFSET);
1953 * writes 'offset' into guest's timestamp counter offset register
1955 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1957 if (is_guest_mode(vcpu)) {
1959 * We're here if L1 chose not to trap WRMSR to TSC. According
1960 * to the spec, this should set L1's TSC; The offset that L1
1961 * set for L2 remains unchanged, and still needs to be added
1962 * to the newly set TSC to get L2's TSC.
1964 struct vmcs12 *vmcs12;
1965 to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset;
1966 /* recalculate vmcs02.TSC_OFFSET: */
1967 vmcs12 = get_vmcs12(vcpu);
1968 vmcs_write64(TSC_OFFSET, offset +
1969 (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
1970 vmcs12->tsc_offset : 0));
1971 } else {
1972 vmcs_write64(TSC_OFFSET, offset);
1976 static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment, bool host)
1978 u64 offset = vmcs_read64(TSC_OFFSET);
1979 vmcs_write64(TSC_OFFSET, offset + adjustment);
1980 if (is_guest_mode(vcpu)) {
1981 /* Even when running L2, the adjustment needs to apply to L1 */
1982 to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment;
1986 static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1988 return target_tsc - native_read_tsc();
1991 static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
1993 struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
1994 return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
1998 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1999 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2000 * all guests if the "nested" module option is off, and can also be disabled
2001 * for a single guest by disabling its VMX cpuid bit.
2003 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2005 return nested && guest_cpuid_has_vmx(vcpu);
2009 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2010 * returned for the various VMX controls MSRs when nested VMX is enabled.
2011 * The same values should also be used to verify that vmcs12 control fields are
2012 * valid during nested entry from L1 to L2.
2013 * Each of these control msrs has a low and high 32-bit half: A low bit is on
2014 * if the corresponding bit in the (32-bit) control field *must* be on, and a
2015 * bit in the high half is on if the corresponding bit in the control field
2016 * may be on. See also vmx_control_verify().
2017 * TODO: allow these variables to be modified (downgraded) by module options
2018 * or other means.
2020 static u32 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high;
2021 static u32 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high;
2022 static u32 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high;
2023 static u32 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high;
2024 static u32 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high;
2025 static u32 nested_vmx_misc_low, nested_vmx_misc_high;
2026 static __init void nested_vmx_setup_ctls_msrs(void)
2029 * Note that as a general rule, the high half of the MSRs (bits in
2030 * the control fields which may be 1) should be initialized by the
2031 * intersection of the underlying hardware's MSR (i.e., features which
2032 * can be supported) and the list of features we want to expose -
2033 * because they are known to be properly supported in our code.
2034 * Also, usually, the low half of the MSRs (bits which must be 1) can
2035 * be set to 0, meaning that L1 may turn off any of these bits. The
2036 * reason is that if one of these bits is necessary, it will appear
2037 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2038 * fields of vmcs01 and vmcs02, will turn these bits off - and
2039 * nested_vmx_exit_handled() will not pass related exits to L1.
2040 * These rules have exceptions below.
2043 /* pin-based controls */
2044 rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2045 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high);
2047 * According to the Intel spec, if bit 55 of VMX_BASIC is off (as it is
2048 * in our case), bits 1, 2 and 4 (i.e., 0x16) must be 1 in this MSR.
2050 nested_vmx_pinbased_ctls_low |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2051 nested_vmx_pinbased_ctls_high &= PIN_BASED_EXT_INTR_MASK |
2052 PIN_BASED_NMI_EXITING | PIN_BASED_VIRTUAL_NMIS;
2053 nested_vmx_pinbased_ctls_high |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2056 * Exit controls
2057 * If bit 55 of VMX_BASIC is off, bits 0-8 and 10, 11, 13, 14, 16 and
2058 * 17 must be 1.
2060 nested_vmx_exit_ctls_low = VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2061 /* Note that guest use of VM_EXIT_ACK_INTR_ON_EXIT is not supported. */
2062 #ifdef CONFIG_X86_64
2063 nested_vmx_exit_ctls_high = VM_EXIT_HOST_ADDR_SPACE_SIZE;
2064 #else
2065 nested_vmx_exit_ctls_high = 0;
2066 #endif
2067 nested_vmx_exit_ctls_high |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2069 /* entry controls */
2070 rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2071 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high);
2072 /* If bit 55 of VMX_BASIC is off, bits 0-8 and 12 must be 1. */
2073 nested_vmx_entry_ctls_low = VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2074 nested_vmx_entry_ctls_high &=
2075 VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_IA32E_MODE;
2076 nested_vmx_entry_ctls_high |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2078 /* cpu-based controls */
2079 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2080 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high);
2081 nested_vmx_procbased_ctls_low = 0;
2082 nested_vmx_procbased_ctls_high &=
2083 CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2084 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2085 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2086 CPU_BASED_CR3_STORE_EXITING |
2087 #ifdef CONFIG_X86_64
2088 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2089 #endif
2090 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2091 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_EXITING |
2092 CPU_BASED_RDPMC_EXITING | CPU_BASED_RDTSC_EXITING |
2093 CPU_BASED_PAUSE_EXITING |
2094 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2096 * We can allow some features even when not supported by the
2097 * hardware. For example, L1 can specify an MSR bitmap - and we
2098 * can use it to avoid exits to L1 - even when L0 runs L2
2099 * without MSR bitmaps.
2101 nested_vmx_procbased_ctls_high |= CPU_BASED_USE_MSR_BITMAPS;
2103 /* secondary cpu-based controls */
2104 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2105 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high);
2106 nested_vmx_secondary_ctls_low = 0;
2107 nested_vmx_secondary_ctls_high &=
2108 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2109 SECONDARY_EXEC_WBINVD_EXITING;
2111 /* miscellaneous data */
2112 rdmsr(MSR_IA32_VMX_MISC, nested_vmx_misc_low, nested_vmx_misc_high);
2113 nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
2114 nested_vmx_misc_high = 0;
2117 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2120 * Bits 0 in high must be 0, and bits 1 in low must be 1.
2122 return ((control & high) | low) == control;
2125 static inline u64 vmx_control_msr(u32 low, u32 high)
2127 return low | ((u64)high << 32);
2131 * If we allow our guest to use VMX instructions (i.e., nested VMX), we should
2132 * also let it use VMX-specific MSRs.
2133 * vmx_get_vmx_msr() and vmx_set_vmx_msr() return 1 when we handled a
2134 * VMX-specific MSR, or 0 when we haven't (and the caller should handle it
2135 * like all other MSRs).
2137 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2139 if (!nested_vmx_allowed(vcpu) && msr_index >= MSR_IA32_VMX_BASIC &&
2140 msr_index <= MSR_IA32_VMX_TRUE_ENTRY_CTLS) {
2142 * According to the spec, processors which do not support VMX
2143 * should throw a #GP(0) when VMX capability MSRs are read.
2145 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
2146 return 1;
2149 switch (msr_index) {
2150 case MSR_IA32_FEATURE_CONTROL:
2151 *pdata = 0;
2152 break;
2153 case MSR_IA32_VMX_BASIC:
2155 * This MSR reports some information about VMX support. We
2156 * should return information about the VMX we emulate for the
2157 * guest, and the VMCS structure we give it - not about the
2158 * VMX support of the underlying hardware.
2160 *pdata = VMCS12_REVISION |
2161 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2162 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2163 break;
2164 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2165 case MSR_IA32_VMX_PINBASED_CTLS:
2166 *pdata = vmx_control_msr(nested_vmx_pinbased_ctls_low,
2167 nested_vmx_pinbased_ctls_high);
2168 break;
2169 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2170 case MSR_IA32_VMX_PROCBASED_CTLS:
2171 *pdata = vmx_control_msr(nested_vmx_procbased_ctls_low,
2172 nested_vmx_procbased_ctls_high);
2173 break;
2174 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2175 case MSR_IA32_VMX_EXIT_CTLS:
2176 *pdata = vmx_control_msr(nested_vmx_exit_ctls_low,
2177 nested_vmx_exit_ctls_high);
2178 break;
2179 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2180 case MSR_IA32_VMX_ENTRY_CTLS:
2181 *pdata = vmx_control_msr(nested_vmx_entry_ctls_low,
2182 nested_vmx_entry_ctls_high);
2183 break;
2184 case MSR_IA32_VMX_MISC:
2185 *pdata = vmx_control_msr(nested_vmx_misc_low,
2186 nested_vmx_misc_high);
2187 break;
2189 * These MSRs specify bits which the guest must keep fixed (on or off)
2190 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2191 * We picked the standard core2 setting.
2193 #define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2194 #define VMXON_CR4_ALWAYSON X86_CR4_VMXE
2195 case MSR_IA32_VMX_CR0_FIXED0:
2196 *pdata = VMXON_CR0_ALWAYSON;
2197 break;
2198 case MSR_IA32_VMX_CR0_FIXED1:
2199 *pdata = -1ULL;
2200 break;
2201 case MSR_IA32_VMX_CR4_FIXED0:
2202 *pdata = VMXON_CR4_ALWAYSON;
2203 break;
2204 case MSR_IA32_VMX_CR4_FIXED1:
2205 *pdata = -1ULL;
2206 break;
2207 case MSR_IA32_VMX_VMCS_ENUM:
2208 *pdata = 0x1f;
2209 break;
2210 case MSR_IA32_VMX_PROCBASED_CTLS2:
2211 *pdata = vmx_control_msr(nested_vmx_secondary_ctls_low,
2212 nested_vmx_secondary_ctls_high);
2213 break;
2214 case MSR_IA32_VMX_EPT_VPID_CAP:
2215 /* Currently, no nested ept or nested vpid */
2216 *pdata = 0;
2217 break;
2218 default:
2219 return 0;
2222 return 1;
2225 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
2227 if (!nested_vmx_allowed(vcpu))
2228 return 0;
2230 if (msr_index == MSR_IA32_FEATURE_CONTROL)
2231 /* TODO: the right thing. */
2232 return 1;
2234 * No need to treat VMX capability MSRs specially: If we don't handle
2235 * them, handle_wrmsr will #GP(0), which is correct (they are readonly)
2237 return 0;
2241 * Reads an msr value (of 'msr_index') into 'pdata'.
2242 * Returns 0 on success, non-0 otherwise.
2243 * Assumes vcpu_load() was already called.
2245 static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2247 u64 data;
2248 struct shared_msr_entry *msr;
2250 if (!pdata) {
2251 printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
2252 return -EINVAL;
2255 switch (msr_index) {
2256 #ifdef CONFIG_X86_64
2257 case MSR_FS_BASE:
2258 data = vmcs_readl(GUEST_FS_BASE);
2259 break;
2260 case MSR_GS_BASE:
2261 data = vmcs_readl(GUEST_GS_BASE);
2262 break;
2263 case MSR_KERNEL_GS_BASE:
2264 vmx_load_host_state(to_vmx(vcpu));
2265 data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
2266 break;
2267 #endif
2268 case MSR_EFER:
2269 return kvm_get_msr_common(vcpu, msr_index, pdata);
2270 case MSR_IA32_TSC:
2271 data = guest_read_tsc();
2272 break;
2273 case MSR_IA32_SYSENTER_CS:
2274 data = vmcs_read32(GUEST_SYSENTER_CS);
2275 break;
2276 case MSR_IA32_SYSENTER_EIP:
2277 data = vmcs_readl(GUEST_SYSENTER_EIP);
2278 break;
2279 case MSR_IA32_SYSENTER_ESP:
2280 data = vmcs_readl(GUEST_SYSENTER_ESP);
2281 break;
2282 case MSR_TSC_AUX:
2283 if (!to_vmx(vcpu)->rdtscp_enabled)
2284 return 1;
2285 /* Otherwise falls through */
2286 default:
2287 if (vmx_get_vmx_msr(vcpu, msr_index, pdata))
2288 return 0;
2289 msr = find_msr_entry(to_vmx(vcpu), msr_index);
2290 if (msr) {
2291 data = msr->data;
2292 break;
2294 return kvm_get_msr_common(vcpu, msr_index, pdata);
2297 *pdata = data;
2298 return 0;
2302 * Writes msr value into into the appropriate "register".
2303 * Returns 0 on success, non-0 otherwise.
2304 * Assumes vcpu_load() was already called.
2306 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2308 struct vcpu_vmx *vmx = to_vmx(vcpu);
2309 struct shared_msr_entry *msr;
2310 int ret = 0;
2311 u32 msr_index = msr_info->index;
2312 u64 data = msr_info->data;
2314 switch (msr_index) {
2315 case MSR_EFER:
2316 ret = kvm_set_msr_common(vcpu, msr_info);
2317 break;
2318 #ifdef CONFIG_X86_64
2319 case MSR_FS_BASE:
2320 vmx_segment_cache_clear(vmx);
2321 vmcs_writel(GUEST_FS_BASE, data);
2322 break;
2323 case MSR_GS_BASE:
2324 vmx_segment_cache_clear(vmx);
2325 vmcs_writel(GUEST_GS_BASE, data);
2326 break;
2327 case MSR_KERNEL_GS_BASE:
2328 vmx_load_host_state(vmx);
2329 vmx->msr_guest_kernel_gs_base = data;
2330 break;
2331 #endif
2332 case MSR_IA32_SYSENTER_CS:
2333 vmcs_write32(GUEST_SYSENTER_CS, data);
2334 break;
2335 case MSR_IA32_SYSENTER_EIP:
2336 vmcs_writel(GUEST_SYSENTER_EIP, data);
2337 break;
2338 case MSR_IA32_SYSENTER_ESP:
2339 vmcs_writel(GUEST_SYSENTER_ESP, data);
2340 break;
2341 case MSR_IA32_TSC:
2342 kvm_write_tsc(vcpu, msr_info);
2343 break;
2344 case MSR_IA32_CR_PAT:
2345 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2346 vmcs_write64(GUEST_IA32_PAT, data);
2347 vcpu->arch.pat = data;
2348 break;
2350 ret = kvm_set_msr_common(vcpu, msr_info);
2351 break;
2352 case MSR_IA32_TSC_ADJUST:
2353 ret = kvm_set_msr_common(vcpu, msr_info);
2354 break;
2355 case MSR_TSC_AUX:
2356 if (!vmx->rdtscp_enabled)
2357 return 1;
2358 /* Check reserved bit, higher 32 bits should be zero */
2359 if ((data >> 32) != 0)
2360 return 1;
2361 /* Otherwise falls through */
2362 default:
2363 if (vmx_set_vmx_msr(vcpu, msr_index, data))
2364 break;
2365 msr = find_msr_entry(vmx, msr_index);
2366 if (msr) {
2367 msr->data = data;
2368 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2369 preempt_disable();
2370 kvm_set_shared_msr(msr->index, msr->data,
2371 msr->mask);
2372 preempt_enable();
2374 break;
2376 ret = kvm_set_msr_common(vcpu, msr_info);
2379 return ret;
2382 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2384 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2385 switch (reg) {
2386 case VCPU_REGS_RSP:
2387 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2388 break;
2389 case VCPU_REGS_RIP:
2390 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2391 break;
2392 case VCPU_EXREG_PDPTR:
2393 if (enable_ept)
2394 ept_save_pdptrs(vcpu);
2395 break;
2396 default:
2397 break;
2401 static __init int cpu_has_kvm_support(void)
2403 return cpu_has_vmx();
2406 static __init int vmx_disabled_by_bios(void)
2408 u64 msr;
2410 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2411 if (msr & FEATURE_CONTROL_LOCKED) {
2412 /* launched w/ TXT and VMX disabled */
2413 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2414 && tboot_enabled())
2415 return 1;
2416 /* launched w/o TXT and VMX only enabled w/ TXT */
2417 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2418 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2419 && !tboot_enabled()) {
2420 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2421 "activate TXT before enabling KVM\n");
2422 return 1;
2424 /* launched w/o TXT and VMX disabled */
2425 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2426 && !tboot_enabled())
2427 return 1;
2430 return 0;
2433 static void kvm_cpu_vmxon(u64 addr)
2435 asm volatile (ASM_VMX_VMXON_RAX
2436 : : "a"(&addr), "m"(addr)
2437 : "memory", "cc");
2440 static int hardware_enable(void *garbage)
2442 int cpu = raw_smp_processor_id();
2443 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2444 u64 old, test_bits;
2446 if (read_cr4() & X86_CR4_VMXE)
2447 return -EBUSY;
2449 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2452 * Now we can enable the vmclear operation in kdump
2453 * since the loaded_vmcss_on_cpu list on this cpu
2454 * has been initialized.
2456 * Though the cpu is not in VMX operation now, there
2457 * is no problem to enable the vmclear operation
2458 * for the loaded_vmcss_on_cpu list is empty!
2460 crash_enable_local_vmclear(cpu);
2462 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2464 test_bits = FEATURE_CONTROL_LOCKED;
2465 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2466 if (tboot_enabled())
2467 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2469 if ((old & test_bits) != test_bits) {
2470 /* enable and lock */
2471 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2473 write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */
2475 if (vmm_exclusive) {
2476 kvm_cpu_vmxon(phys_addr);
2477 ept_sync_global();
2480 store_gdt(&__get_cpu_var(host_gdt));
2482 return 0;
2485 static void vmclear_local_loaded_vmcss(void)
2487 int cpu = raw_smp_processor_id();
2488 struct loaded_vmcs *v, *n;
2490 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2491 loaded_vmcss_on_cpu_link)
2492 __loaded_vmcs_clear(v);
2496 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2497 * tricks.
2499 static void kvm_cpu_vmxoff(void)
2501 asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
2504 static void hardware_disable(void *garbage)
2506 if (vmm_exclusive) {
2507 vmclear_local_loaded_vmcss();
2508 kvm_cpu_vmxoff();
2510 write_cr4(read_cr4() & ~X86_CR4_VMXE);
2513 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2514 u32 msr, u32 *result)
2516 u32 vmx_msr_low, vmx_msr_high;
2517 u32 ctl = ctl_min | ctl_opt;
2519 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2521 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2522 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2524 /* Ensure minimum (required) set of control bits are supported. */
2525 if (ctl_min & ~ctl)
2526 return -EIO;
2528 *result = ctl;
2529 return 0;
2532 static __init bool allow_1_setting(u32 msr, u32 ctl)
2534 u32 vmx_msr_low, vmx_msr_high;
2536 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2537 return vmx_msr_high & ctl;
2540 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
2542 u32 vmx_msr_low, vmx_msr_high;
2543 u32 min, opt, min2, opt2;
2544 u32 _pin_based_exec_control = 0;
2545 u32 _cpu_based_exec_control = 0;
2546 u32 _cpu_based_2nd_exec_control = 0;
2547 u32 _vmexit_control = 0;
2548 u32 _vmentry_control = 0;
2550 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2551 opt = PIN_BASED_VIRTUAL_NMIS;
2552 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2553 &_pin_based_exec_control) < 0)
2554 return -EIO;
2556 min = CPU_BASED_HLT_EXITING |
2557 #ifdef CONFIG_X86_64
2558 CPU_BASED_CR8_LOAD_EXITING |
2559 CPU_BASED_CR8_STORE_EXITING |
2560 #endif
2561 CPU_BASED_CR3_LOAD_EXITING |
2562 CPU_BASED_CR3_STORE_EXITING |
2563 CPU_BASED_USE_IO_BITMAPS |
2564 CPU_BASED_MOV_DR_EXITING |
2565 CPU_BASED_USE_TSC_OFFSETING |
2566 CPU_BASED_MWAIT_EXITING |
2567 CPU_BASED_MONITOR_EXITING |
2568 CPU_BASED_INVLPG_EXITING |
2569 CPU_BASED_RDPMC_EXITING;
2571 opt = CPU_BASED_TPR_SHADOW |
2572 CPU_BASED_USE_MSR_BITMAPS |
2573 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2574 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2575 &_cpu_based_exec_control) < 0)
2576 return -EIO;
2577 #ifdef CONFIG_X86_64
2578 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2579 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2580 ~CPU_BASED_CR8_STORE_EXITING;
2581 #endif
2582 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2583 min2 = 0;
2584 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2585 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2586 SECONDARY_EXEC_WBINVD_EXITING |
2587 SECONDARY_EXEC_ENABLE_VPID |
2588 SECONDARY_EXEC_ENABLE_EPT |
2589 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2590 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2591 SECONDARY_EXEC_RDTSCP |
2592 SECONDARY_EXEC_ENABLE_INVPCID |
2593 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2594 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
2595 if (adjust_vmx_controls(min2, opt2,
2596 MSR_IA32_VMX_PROCBASED_CTLS2,
2597 &_cpu_based_2nd_exec_control) < 0)
2598 return -EIO;
2600 #ifndef CONFIG_X86_64
2601 if (!(_cpu_based_2nd_exec_control &
2602 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2603 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2604 #endif
2606 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2607 _cpu_based_2nd_exec_control &= ~(
2608 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2609 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2610 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2612 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2613 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2614 enabled */
2615 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2616 CPU_BASED_CR3_STORE_EXITING |
2617 CPU_BASED_INVLPG_EXITING);
2618 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
2619 vmx_capability.ept, vmx_capability.vpid);
2622 min = 0;
2623 #ifdef CONFIG_X86_64
2624 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2625 #endif
2626 opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT;
2627 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2628 &_vmexit_control) < 0)
2629 return -EIO;
2631 min = 0;
2632 opt = VM_ENTRY_LOAD_IA32_PAT;
2633 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2634 &_vmentry_control) < 0)
2635 return -EIO;
2637 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2639 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2640 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2641 return -EIO;
2643 #ifdef CONFIG_X86_64
2644 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2645 if (vmx_msr_high & (1u<<16))
2646 return -EIO;
2647 #endif
2649 /* Require Write-Back (WB) memory type for VMCS accesses. */
2650 if (((vmx_msr_high >> 18) & 15) != 6)
2651 return -EIO;
2653 vmcs_conf->size = vmx_msr_high & 0x1fff;
2654 vmcs_conf->order = get_order(vmcs_config.size);
2655 vmcs_conf->revision_id = vmx_msr_low;
2657 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2658 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2659 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2660 vmcs_conf->vmexit_ctrl = _vmexit_control;
2661 vmcs_conf->vmentry_ctrl = _vmentry_control;
2663 cpu_has_load_ia32_efer =
2664 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2665 VM_ENTRY_LOAD_IA32_EFER)
2666 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2667 VM_EXIT_LOAD_IA32_EFER);
2669 cpu_has_load_perf_global_ctrl =
2670 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2671 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
2672 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2673 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2676 * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
2677 * but due to arrata below it can't be used. Workaround is to use
2678 * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2680 * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
2682 * AAK155 (model 26)
2683 * AAP115 (model 30)
2684 * AAT100 (model 37)
2685 * BC86,AAY89,BD102 (model 44)
2686 * BA97 (model 46)
2689 if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
2690 switch (boot_cpu_data.x86_model) {
2691 case 26:
2692 case 30:
2693 case 37:
2694 case 44:
2695 case 46:
2696 cpu_has_load_perf_global_ctrl = false;
2697 printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2698 "does not work properly. Using workaround\n");
2699 break;
2700 default:
2701 break;
2705 return 0;
2708 static struct vmcs *alloc_vmcs_cpu(int cpu)
2710 int node = cpu_to_node(cpu);
2711 struct page *pages;
2712 struct vmcs *vmcs;
2714 pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order);
2715 if (!pages)
2716 return NULL;
2717 vmcs = page_address(pages);
2718 memset(vmcs, 0, vmcs_config.size);
2719 vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
2720 return vmcs;
2723 static struct vmcs *alloc_vmcs(void)
2725 return alloc_vmcs_cpu(raw_smp_processor_id());
2728 static void free_vmcs(struct vmcs *vmcs)
2730 free_pages((unsigned long)vmcs, vmcs_config.order);
2734 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2736 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2738 if (!loaded_vmcs->vmcs)
2739 return;
2740 loaded_vmcs_clear(loaded_vmcs);
2741 free_vmcs(loaded_vmcs->vmcs);
2742 loaded_vmcs->vmcs = NULL;
2745 static void free_kvm_area(void)
2747 int cpu;
2749 for_each_possible_cpu(cpu) {
2750 free_vmcs(per_cpu(vmxarea, cpu));
2751 per_cpu(vmxarea, cpu) = NULL;
2755 static __init int alloc_kvm_area(void)
2757 int cpu;
2759 for_each_possible_cpu(cpu) {
2760 struct vmcs *vmcs;
2762 vmcs = alloc_vmcs_cpu(cpu);
2763 if (!vmcs) {
2764 free_kvm_area();
2765 return -ENOMEM;
2768 per_cpu(vmxarea, cpu) = vmcs;
2770 return 0;
2773 static __init int hardware_setup(void)
2775 if (setup_vmcs_config(&vmcs_config) < 0)
2776 return -EIO;
2778 if (boot_cpu_has(X86_FEATURE_NX))
2779 kvm_enable_efer_bits(EFER_NX);
2781 if (!cpu_has_vmx_vpid())
2782 enable_vpid = 0;
2784 if (!cpu_has_vmx_ept() ||
2785 !cpu_has_vmx_ept_4levels()) {
2786 enable_ept = 0;
2787 enable_unrestricted_guest = 0;
2788 enable_ept_ad_bits = 0;
2791 if (!cpu_has_vmx_ept_ad_bits())
2792 enable_ept_ad_bits = 0;
2794 if (!cpu_has_vmx_unrestricted_guest())
2795 enable_unrestricted_guest = 0;
2797 if (!cpu_has_vmx_flexpriority())
2798 flexpriority_enabled = 0;
2800 if (!cpu_has_vmx_tpr_shadow())
2801 kvm_x86_ops->update_cr8_intercept = NULL;
2803 if (enable_ept && !cpu_has_vmx_ept_2m_page())
2804 kvm_disable_largepages();
2806 if (!cpu_has_vmx_ple())
2807 ple_gap = 0;
2809 if (!cpu_has_vmx_apic_register_virt() ||
2810 !cpu_has_vmx_virtual_intr_delivery())
2811 enable_apicv_reg_vid = 0;
2813 if (enable_apicv_reg_vid)
2814 kvm_x86_ops->update_cr8_intercept = NULL;
2815 else
2816 kvm_x86_ops->hwapic_irr_update = NULL;
2818 if (nested)
2819 nested_vmx_setup_ctls_msrs();
2821 return alloc_kvm_area();
2824 static __exit void hardware_unsetup(void)
2826 free_kvm_area();
2829 static bool emulation_required(struct kvm_vcpu *vcpu)
2831 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
2834 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2835 struct kvm_segment *save)
2837 if (!emulate_invalid_guest_state) {
2839 * CS and SS RPL should be equal during guest entry according
2840 * to VMX spec, but in reality it is not always so. Since vcpu
2841 * is in the middle of the transition from real mode to
2842 * protected mode it is safe to assume that RPL 0 is a good
2843 * default value.
2845 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2846 save->selector &= ~SELECTOR_RPL_MASK;
2847 save->dpl = save->selector & SELECTOR_RPL_MASK;
2848 save->s = 1;
2850 vmx_set_segment(vcpu, save, seg);
2853 static void enter_pmode(struct kvm_vcpu *vcpu)
2855 unsigned long flags;
2856 struct vcpu_vmx *vmx = to_vmx(vcpu);
2859 * Update real mode segment cache. It may be not up-to-date if sement
2860 * register was written while vcpu was in a guest mode.
2862 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2863 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2864 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2865 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2866 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2867 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2869 vmx->rmode.vm86_active = 0;
2871 vmx_segment_cache_clear(vmx);
2873 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2875 flags = vmcs_readl(GUEST_RFLAGS);
2876 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2877 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2878 vmcs_writel(GUEST_RFLAGS, flags);
2880 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2881 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2883 update_exception_bitmap(vcpu);
2885 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2886 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2887 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2888 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2889 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2890 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2892 /* CPL is always 0 when CPU enters protected mode */
2893 __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
2894 vmx->cpl = 0;
2897 static gva_t rmode_tss_base(struct kvm *kvm)
2899 if (!kvm->arch.tss_addr) {
2900 struct kvm_memslots *slots;
2901 struct kvm_memory_slot *slot;
2902 gfn_t base_gfn;
2904 slots = kvm_memslots(kvm);
2905 slot = id_to_memslot(slots, 0);
2906 base_gfn = slot->base_gfn + slot->npages - 3;
2908 return base_gfn << PAGE_SHIFT;
2910 return kvm->arch.tss_addr;
2913 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2915 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2916 struct kvm_segment var = *save;
2918 var.dpl = 0x3;
2919 if (seg == VCPU_SREG_CS)
2920 var.type = 0x3;
2922 if (!emulate_invalid_guest_state) {
2923 var.selector = var.base >> 4;
2924 var.base = var.base & 0xffff0;
2925 var.limit = 0xffff;
2926 var.g = 0;
2927 var.db = 0;
2928 var.present = 1;
2929 var.s = 1;
2930 var.l = 0;
2931 var.unusable = 0;
2932 var.type = 0x3;
2933 var.avl = 0;
2934 if (save->base & 0xf)
2935 printk_once(KERN_WARNING "kvm: segment base is not "
2936 "paragraph aligned when entering "
2937 "protected mode (seg=%d)", seg);
2940 vmcs_write16(sf->selector, var.selector);
2941 vmcs_write32(sf->base, var.base);
2942 vmcs_write32(sf->limit, var.limit);
2943 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2946 static void enter_rmode(struct kvm_vcpu *vcpu)
2948 unsigned long flags;
2949 struct vcpu_vmx *vmx = to_vmx(vcpu);
2951 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2952 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2953 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2954 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2955 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2956 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2957 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2959 vmx->rmode.vm86_active = 1;
2962 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2963 * vcpu. Call it here with phys address pointing 16M below 4G.
2965 if (!vcpu->kvm->arch.tss_addr) {
2966 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2967 "called before entering vcpu\n");
2968 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
2969 vmx_set_tss_addr(vcpu->kvm, 0xfeffd000);
2970 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
2973 vmx_segment_cache_clear(vmx);
2975 vmcs_writel(GUEST_TR_BASE, rmode_tss_base(vcpu->kvm));
2976 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2977 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2979 flags = vmcs_readl(GUEST_RFLAGS);
2980 vmx->rmode.save_rflags = flags;
2982 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2984 vmcs_writel(GUEST_RFLAGS, flags);
2985 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2986 update_exception_bitmap(vcpu);
2988 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2989 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2990 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2991 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2992 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2993 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2995 kvm_mmu_reset_context(vcpu);
2998 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
3000 struct vcpu_vmx *vmx = to_vmx(vcpu);
3001 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
3003 if (!msr)
3004 return;
3007 * Force kernel_gs_base reloading before EFER changes, as control
3008 * of this msr depends on is_long_mode().
3010 vmx_load_host_state(to_vmx(vcpu));
3011 vcpu->arch.efer = efer;
3012 if (efer & EFER_LMA) {
3013 vmcs_write32(VM_ENTRY_CONTROLS,
3014 vmcs_read32(VM_ENTRY_CONTROLS) |
3015 VM_ENTRY_IA32E_MODE);
3016 msr->data = efer;
3017 } else {
3018 vmcs_write32(VM_ENTRY_CONTROLS,
3019 vmcs_read32(VM_ENTRY_CONTROLS) &
3020 ~VM_ENTRY_IA32E_MODE);
3022 msr->data = efer & ~EFER_LME;
3024 setup_msrs(vmx);
3027 #ifdef CONFIG_X86_64
3029 static void enter_lmode(struct kvm_vcpu *vcpu)
3031 u32 guest_tr_ar;
3033 vmx_segment_cache_clear(to_vmx(vcpu));
3035 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3036 if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
3037 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3038 __func__);
3039 vmcs_write32(GUEST_TR_AR_BYTES,
3040 (guest_tr_ar & ~AR_TYPE_MASK)
3041 | AR_TYPE_BUSY_64_TSS);
3043 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3046 static void exit_lmode(struct kvm_vcpu *vcpu)
3048 vmcs_write32(VM_ENTRY_CONTROLS,
3049 vmcs_read32(VM_ENTRY_CONTROLS)
3050 & ~VM_ENTRY_IA32E_MODE);
3051 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3054 #endif
3056 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
3058 vpid_sync_context(to_vmx(vcpu));
3059 if (enable_ept) {
3060 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3061 return;
3062 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
3066 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
3068 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
3070 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
3071 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
3074 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
3076 if (enable_ept && is_paging(vcpu))
3077 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
3078 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
3081 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
3083 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
3085 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
3086 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
3089 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
3091 if (!test_bit(VCPU_EXREG_PDPTR,
3092 (unsigned long *)&vcpu->arch.regs_dirty))
3093 return;
3095 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3096 vmcs_write64(GUEST_PDPTR0, vcpu->arch.mmu.pdptrs[0]);
3097 vmcs_write64(GUEST_PDPTR1, vcpu->arch.mmu.pdptrs[1]);
3098 vmcs_write64(GUEST_PDPTR2, vcpu->arch.mmu.pdptrs[2]);
3099 vmcs_write64(GUEST_PDPTR3, vcpu->arch.mmu.pdptrs[3]);
3103 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3105 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3106 vcpu->arch.mmu.pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3107 vcpu->arch.mmu.pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3108 vcpu->arch.mmu.pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3109 vcpu->arch.mmu.pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3112 __set_bit(VCPU_EXREG_PDPTR,
3113 (unsigned long *)&vcpu->arch.regs_avail);
3114 __set_bit(VCPU_EXREG_PDPTR,
3115 (unsigned long *)&vcpu->arch.regs_dirty);
3118 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
3120 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3121 unsigned long cr0,
3122 struct kvm_vcpu *vcpu)
3124 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3125 vmx_decache_cr3(vcpu);
3126 if (!(cr0 & X86_CR0_PG)) {
3127 /* From paging/starting to nonpaging */
3128 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3129 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
3130 (CPU_BASED_CR3_LOAD_EXITING |
3131 CPU_BASED_CR3_STORE_EXITING));
3132 vcpu->arch.cr0 = cr0;
3133 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3134 } else if (!is_paging(vcpu)) {
3135 /* From nonpaging to paging */
3136 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3137 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
3138 ~(CPU_BASED_CR3_LOAD_EXITING |
3139 CPU_BASED_CR3_STORE_EXITING));
3140 vcpu->arch.cr0 = cr0;
3141 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3144 if (!(cr0 & X86_CR0_WP))
3145 *hw_cr0 &= ~X86_CR0_WP;
3148 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3150 struct vcpu_vmx *vmx = to_vmx(vcpu);
3151 unsigned long hw_cr0;
3153 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
3154 if (enable_unrestricted_guest)
3155 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3156 else {
3157 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3159 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3160 enter_pmode(vcpu);
3162 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3163 enter_rmode(vcpu);
3166 #ifdef CONFIG_X86_64
3167 if (vcpu->arch.efer & EFER_LME) {
3168 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3169 enter_lmode(vcpu);
3170 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3171 exit_lmode(vcpu);
3173 #endif
3175 if (enable_ept)
3176 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3178 if (!vcpu->fpu_active)
3179 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
3181 vmcs_writel(CR0_READ_SHADOW, cr0);
3182 vmcs_writel(GUEST_CR0, hw_cr0);
3183 vcpu->arch.cr0 = cr0;
3185 /* depends on vcpu->arch.cr0 to be set to a new value */
3186 vmx->emulation_required = emulation_required(vcpu);
3189 static u64 construct_eptp(unsigned long root_hpa)
3191 u64 eptp;
3193 /* TODO write the value reading from MSR */
3194 eptp = VMX_EPT_DEFAULT_MT |
3195 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
3196 if (enable_ept_ad_bits)
3197 eptp |= VMX_EPT_AD_ENABLE_BIT;
3198 eptp |= (root_hpa & PAGE_MASK);
3200 return eptp;
3203 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
3205 unsigned long guest_cr3;
3206 u64 eptp;
3208 guest_cr3 = cr3;
3209 if (enable_ept) {
3210 eptp = construct_eptp(cr3);
3211 vmcs_write64(EPT_POINTER, eptp);
3212 guest_cr3 = is_paging(vcpu) ? kvm_read_cr3(vcpu) :
3213 vcpu->kvm->arch.ept_identity_map_addr;
3214 ept_load_pdptrs(vcpu);
3217 vmx_flush_tlb(vcpu);
3218 vmcs_writel(GUEST_CR3, guest_cr3);
3221 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3223 unsigned long hw_cr4 = cr4 | (to_vmx(vcpu)->rmode.vm86_active ?
3224 KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
3226 if (cr4 & X86_CR4_VMXE) {
3228 * To use VMXON (and later other VMX instructions), a guest
3229 * must first be able to turn on cr4.VMXE (see handle_vmon()).
3230 * So basically the check on whether to allow nested VMX
3231 * is here.
3233 if (!nested_vmx_allowed(vcpu))
3234 return 1;
3236 if (to_vmx(vcpu)->nested.vmxon &&
3237 ((cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON))
3238 return 1;
3240 vcpu->arch.cr4 = cr4;
3241 if (enable_ept) {
3242 if (!is_paging(vcpu)) {
3243 hw_cr4 &= ~X86_CR4_PAE;
3244 hw_cr4 |= X86_CR4_PSE;
3246 * SMEP is disabled if CPU is in non-paging mode in
3247 * hardware. However KVM always uses paging mode to
3248 * emulate guest non-paging mode with TDP.
3249 * To emulate this behavior, SMEP needs to be manually
3250 * disabled when guest switches to non-paging mode.
3252 hw_cr4 &= ~X86_CR4_SMEP;
3253 } else if (!(cr4 & X86_CR4_PAE)) {
3254 hw_cr4 &= ~X86_CR4_PAE;
3258 vmcs_writel(CR4_READ_SHADOW, cr4);
3259 vmcs_writel(GUEST_CR4, hw_cr4);
3260 return 0;
3263 static void vmx_get_segment(struct kvm_vcpu *vcpu,
3264 struct kvm_segment *var, int seg)
3266 struct vcpu_vmx *vmx = to_vmx(vcpu);
3267 u32 ar;
3269 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3270 *var = vmx->rmode.segs[seg];
3271 if (seg == VCPU_SREG_TR
3272 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3273 return;
3274 var->base = vmx_read_guest_seg_base(vmx, seg);
3275 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3276 return;
3278 var->base = vmx_read_guest_seg_base(vmx, seg);
3279 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3280 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3281 ar = vmx_read_guest_seg_ar(vmx, seg);
3282 var->type = ar & 15;
3283 var->s = (ar >> 4) & 1;
3284 var->dpl = (ar >> 5) & 3;
3285 var->present = (ar >> 7) & 1;
3286 var->avl = (ar >> 12) & 1;
3287 var->l = (ar >> 13) & 1;
3288 var->db = (ar >> 14) & 1;
3289 var->g = (ar >> 15) & 1;
3290 var->unusable = (ar >> 16) & 1;
3293 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3295 struct kvm_segment s;
3297 if (to_vmx(vcpu)->rmode.vm86_active) {
3298 vmx_get_segment(vcpu, &s, seg);
3299 return s.base;
3301 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3304 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
3306 struct vcpu_vmx *vmx = to_vmx(vcpu);
3308 if (!is_protmode(vcpu))
3309 return 0;
3311 if (!is_long_mode(vcpu)
3312 && (kvm_get_rflags(vcpu) & X86_EFLAGS_VM)) /* if virtual 8086 */
3313 return 3;
3315 if (!test_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail)) {
3316 __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3317 vmx->cpl = vmx_read_guest_seg_selector(vmx, VCPU_SREG_CS) & 3;
3320 return vmx->cpl;
3324 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3326 u32 ar;
3328 if (var->unusable || !var->present)
3329 ar = 1 << 16;
3330 else {
3331 ar = var->type & 15;
3332 ar |= (var->s & 1) << 4;
3333 ar |= (var->dpl & 3) << 5;
3334 ar |= (var->present & 1) << 7;
3335 ar |= (var->avl & 1) << 12;
3336 ar |= (var->l & 1) << 13;
3337 ar |= (var->db & 1) << 14;
3338 ar |= (var->g & 1) << 15;
3341 return ar;
3344 static void vmx_set_segment(struct kvm_vcpu *vcpu,
3345 struct kvm_segment *var, int seg)
3347 struct vcpu_vmx *vmx = to_vmx(vcpu);
3348 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3350 vmx_segment_cache_clear(vmx);
3351 if (seg == VCPU_SREG_CS)
3352 __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3354 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3355 vmx->rmode.segs[seg] = *var;
3356 if (seg == VCPU_SREG_TR)
3357 vmcs_write16(sf->selector, var->selector);
3358 else if (var->s)
3359 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3360 goto out;
3363 vmcs_writel(sf->base, var->base);
3364 vmcs_write32(sf->limit, var->limit);
3365 vmcs_write16(sf->selector, var->selector);
3368 * Fix the "Accessed" bit in AR field of segment registers for older
3369 * qemu binaries.
3370 * IA32 arch specifies that at the time of processor reset the
3371 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3372 * is setting it to 0 in the userland code. This causes invalid guest
3373 * state vmexit when "unrestricted guest" mode is turned on.
3374 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3375 * tree. Newer qemu binaries with that qemu fix would not need this
3376 * kvm hack.
3378 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3379 var->type |= 0x1; /* Accessed */
3381 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3383 out:
3384 vmx->emulation_required |= emulation_required(vcpu);
3387 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3389 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3391 *db = (ar >> 14) & 1;
3392 *l = (ar >> 13) & 1;
3395 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3397 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3398 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3401 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3403 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3404 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3407 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3409 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3410 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3413 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3415 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3416 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3419 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3421 struct kvm_segment var;
3422 u32 ar;
3424 vmx_get_segment(vcpu, &var, seg);
3425 var.dpl = 0x3;
3426 if (seg == VCPU_SREG_CS)
3427 var.type = 0x3;
3428 ar = vmx_segment_access_rights(&var);
3430 if (var.base != (var.selector << 4))
3431 return false;
3432 if (var.limit != 0xffff)
3433 return false;
3434 if (ar != 0xf3)
3435 return false;
3437 return true;
3440 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3442 struct kvm_segment cs;
3443 unsigned int cs_rpl;
3445 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3446 cs_rpl = cs.selector & SELECTOR_RPL_MASK;
3448 if (cs.unusable)
3449 return false;
3450 if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK))
3451 return false;
3452 if (!cs.s)
3453 return false;
3454 if (cs.type & AR_TYPE_WRITEABLE_MASK) {
3455 if (cs.dpl > cs_rpl)
3456 return false;
3457 } else {
3458 if (cs.dpl != cs_rpl)
3459 return false;
3461 if (!cs.present)
3462 return false;
3464 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3465 return true;
3468 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3470 struct kvm_segment ss;
3471 unsigned int ss_rpl;
3473 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3474 ss_rpl = ss.selector & SELECTOR_RPL_MASK;
3476 if (ss.unusable)
3477 return true;
3478 if (ss.type != 3 && ss.type != 7)
3479 return false;
3480 if (!ss.s)
3481 return false;
3482 if (ss.dpl != ss_rpl) /* DPL != RPL */
3483 return false;
3484 if (!ss.present)
3485 return false;
3487 return true;
3490 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3492 struct kvm_segment var;
3493 unsigned int rpl;
3495 vmx_get_segment(vcpu, &var, seg);
3496 rpl = var.selector & SELECTOR_RPL_MASK;
3498 if (var.unusable)
3499 return true;
3500 if (!var.s)
3501 return false;
3502 if (!var.present)
3503 return false;
3504 if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) {
3505 if (var.dpl < rpl) /* DPL < RPL */
3506 return false;
3509 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3510 * rights flags
3512 return true;
3515 static bool tr_valid(struct kvm_vcpu *vcpu)
3517 struct kvm_segment tr;
3519 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3521 if (tr.unusable)
3522 return false;
3523 if (tr.selector & SELECTOR_TI_MASK) /* TI = 1 */
3524 return false;
3525 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3526 return false;
3527 if (!tr.present)
3528 return false;
3530 return true;
3533 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3535 struct kvm_segment ldtr;
3537 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3539 if (ldtr.unusable)
3540 return true;
3541 if (ldtr.selector & SELECTOR_TI_MASK) /* TI = 1 */
3542 return false;
3543 if (ldtr.type != 2)
3544 return false;
3545 if (!ldtr.present)
3546 return false;
3548 return true;
3551 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3553 struct kvm_segment cs, ss;
3555 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3556 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3558 return ((cs.selector & SELECTOR_RPL_MASK) ==
3559 (ss.selector & SELECTOR_RPL_MASK));
3563 * Check if guest state is valid. Returns true if valid, false if
3564 * not.
3565 * We assume that registers are always usable
3567 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3569 if (enable_unrestricted_guest)
3570 return true;
3572 /* real mode guest state checks */
3573 if (!is_protmode(vcpu)) {
3574 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3575 return false;
3576 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3577 return false;
3578 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3579 return false;
3580 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3581 return false;
3582 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3583 return false;
3584 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3585 return false;
3586 } else {
3587 /* protected mode guest state checks */
3588 if (!cs_ss_rpl_check(vcpu))
3589 return false;
3590 if (!code_segment_valid(vcpu))
3591 return false;
3592 if (!stack_segment_valid(vcpu))
3593 return false;
3594 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3595 return false;
3596 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3597 return false;
3598 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3599 return false;
3600 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3601 return false;
3602 if (!tr_valid(vcpu))
3603 return false;
3604 if (!ldtr_valid(vcpu))
3605 return false;
3607 /* TODO:
3608 * - Add checks on RIP
3609 * - Add checks on RFLAGS
3612 return true;
3615 static int init_rmode_tss(struct kvm *kvm)
3617 gfn_t fn;
3618 u16 data = 0;
3619 int r, idx, ret = 0;
3621 idx = srcu_read_lock(&kvm->srcu);
3622 fn = rmode_tss_base(kvm) >> PAGE_SHIFT;
3623 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3624 if (r < 0)
3625 goto out;
3626 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3627 r = kvm_write_guest_page(kvm, fn++, &data,
3628 TSS_IOPB_BASE_OFFSET, sizeof(u16));
3629 if (r < 0)
3630 goto out;
3631 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3632 if (r < 0)
3633 goto out;
3634 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3635 if (r < 0)
3636 goto out;
3637 data = ~0;
3638 r = kvm_write_guest_page(kvm, fn, &data,
3639 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3640 sizeof(u8));
3641 if (r < 0)
3642 goto out;
3644 ret = 1;
3645 out:
3646 srcu_read_unlock(&kvm->srcu, idx);
3647 return ret;
3650 static int init_rmode_identity_map(struct kvm *kvm)
3652 int i, idx, r, ret;
3653 pfn_t identity_map_pfn;
3654 u32 tmp;
3656 if (!enable_ept)
3657 return 1;
3658 if (unlikely(!kvm->arch.ept_identity_pagetable)) {
3659 printk(KERN_ERR "EPT: identity-mapping pagetable "
3660 "haven't been allocated!\n");
3661 return 0;
3663 if (likely(kvm->arch.ept_identity_pagetable_done))
3664 return 1;
3665 ret = 0;
3666 identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
3667 idx = srcu_read_lock(&kvm->srcu);
3668 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3669 if (r < 0)
3670 goto out;
3671 /* Set up identity-mapping pagetable for EPT in real mode */
3672 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3673 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3674 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3675 r = kvm_write_guest_page(kvm, identity_map_pfn,
3676 &tmp, i * sizeof(tmp), sizeof(tmp));
3677 if (r < 0)
3678 goto out;
3680 kvm->arch.ept_identity_pagetable_done = true;
3681 ret = 1;
3682 out:
3683 srcu_read_unlock(&kvm->srcu, idx);
3684 return ret;
3687 static void seg_setup(int seg)
3689 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3690 unsigned int ar;
3692 vmcs_write16(sf->selector, 0);
3693 vmcs_writel(sf->base, 0);
3694 vmcs_write32(sf->limit, 0xffff);
3695 ar = 0x93;
3696 if (seg == VCPU_SREG_CS)
3697 ar |= 0x08; /* code segment */
3699 vmcs_write32(sf->ar_bytes, ar);
3702 static int alloc_apic_access_page(struct kvm *kvm)
3704 struct page *page;
3705 struct kvm_userspace_memory_region kvm_userspace_mem;
3706 int r = 0;
3708 mutex_lock(&kvm->slots_lock);
3709 if (kvm->arch.apic_access_page)
3710 goto out;
3711 kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
3712 kvm_userspace_mem.flags = 0;
3713 kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL;
3714 kvm_userspace_mem.memory_size = PAGE_SIZE;
3715 r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
3716 if (r)
3717 goto out;
3719 page = gfn_to_page(kvm, 0xfee00);
3720 if (is_error_page(page)) {
3721 r = -EFAULT;
3722 goto out;
3725 kvm->arch.apic_access_page = page;
3726 out:
3727 mutex_unlock(&kvm->slots_lock);
3728 return r;
3731 static int alloc_identity_pagetable(struct kvm *kvm)
3733 struct page *page;
3734 struct kvm_userspace_memory_region kvm_userspace_mem;
3735 int r = 0;
3737 mutex_lock(&kvm->slots_lock);
3738 if (kvm->arch.ept_identity_pagetable)
3739 goto out;
3740 kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
3741 kvm_userspace_mem.flags = 0;
3742 kvm_userspace_mem.guest_phys_addr =
3743 kvm->arch.ept_identity_map_addr;
3744 kvm_userspace_mem.memory_size = PAGE_SIZE;
3745 r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
3746 if (r)
3747 goto out;
3749 page = gfn_to_page(kvm, kvm->arch.ept_identity_map_addr >> PAGE_SHIFT);
3750 if (is_error_page(page)) {
3751 r = -EFAULT;
3752 goto out;
3755 kvm->arch.ept_identity_pagetable = page;
3756 out:
3757 mutex_unlock(&kvm->slots_lock);
3758 return r;
3761 static void allocate_vpid(struct vcpu_vmx *vmx)
3763 int vpid;
3765 vmx->vpid = 0;
3766 if (!enable_vpid)
3767 return;
3768 spin_lock(&vmx_vpid_lock);
3769 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3770 if (vpid < VMX_NR_VPIDS) {
3771 vmx->vpid = vpid;
3772 __set_bit(vpid, vmx_vpid_bitmap);
3774 spin_unlock(&vmx_vpid_lock);
3777 static void free_vpid(struct vcpu_vmx *vmx)
3779 if (!enable_vpid)
3780 return;
3781 spin_lock(&vmx_vpid_lock);
3782 if (vmx->vpid != 0)
3783 __clear_bit(vmx->vpid, vmx_vpid_bitmap);
3784 spin_unlock(&vmx_vpid_lock);
3787 #define MSR_TYPE_R 1
3788 #define MSR_TYPE_W 2
3789 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3790 u32 msr, int type)
3792 int f = sizeof(unsigned long);
3794 if (!cpu_has_vmx_msr_bitmap())
3795 return;
3798 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3799 * have the write-low and read-high bitmap offsets the wrong way round.
3800 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3802 if (msr <= 0x1fff) {
3803 if (type & MSR_TYPE_R)
3804 /* read-low */
3805 __clear_bit(msr, msr_bitmap + 0x000 / f);
3807 if (type & MSR_TYPE_W)
3808 /* write-low */
3809 __clear_bit(msr, msr_bitmap + 0x800 / f);
3811 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3812 msr &= 0x1fff;
3813 if (type & MSR_TYPE_R)
3814 /* read-high */
3815 __clear_bit(msr, msr_bitmap + 0x400 / f);
3817 if (type & MSR_TYPE_W)
3818 /* write-high */
3819 __clear_bit(msr, msr_bitmap + 0xc00 / f);
3824 static void __vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3825 u32 msr, int type)
3827 int f = sizeof(unsigned long);
3829 if (!cpu_has_vmx_msr_bitmap())
3830 return;
3833 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3834 * have the write-low and read-high bitmap offsets the wrong way round.
3835 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3837 if (msr <= 0x1fff) {
3838 if (type & MSR_TYPE_R)
3839 /* read-low */
3840 __set_bit(msr, msr_bitmap + 0x000 / f);
3842 if (type & MSR_TYPE_W)
3843 /* write-low */
3844 __set_bit(msr, msr_bitmap + 0x800 / f);
3846 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3847 msr &= 0x1fff;
3848 if (type & MSR_TYPE_R)
3849 /* read-high */
3850 __set_bit(msr, msr_bitmap + 0x400 / f);
3852 if (type & MSR_TYPE_W)
3853 /* write-high */
3854 __set_bit(msr, msr_bitmap + 0xc00 / f);
3859 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
3861 if (!longmode_only)
3862 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
3863 msr, MSR_TYPE_R | MSR_TYPE_W);
3864 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
3865 msr, MSR_TYPE_R | MSR_TYPE_W);
3868 static void vmx_enable_intercept_msr_read_x2apic(u32 msr)
3870 __vmx_enable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
3871 msr, MSR_TYPE_R);
3872 __vmx_enable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
3873 msr, MSR_TYPE_R);
3876 static void vmx_disable_intercept_msr_read_x2apic(u32 msr)
3878 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
3879 msr, MSR_TYPE_R);
3880 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
3881 msr, MSR_TYPE_R);
3884 static void vmx_disable_intercept_msr_write_x2apic(u32 msr)
3886 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
3887 msr, MSR_TYPE_W);
3888 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
3889 msr, MSR_TYPE_W);
3893 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3894 * will not change in the lifetime of the guest.
3895 * Note that host-state that does change is set elsewhere. E.g., host-state
3896 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3898 static void vmx_set_constant_host_state(void)
3900 u32 low32, high32;
3901 unsigned long tmpl;
3902 struct desc_ptr dt;
3904 vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */
3905 vmcs_writel(HOST_CR4, read_cr4()); /* 22.2.3, 22.2.5 */
3906 vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */
3908 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
3909 #ifdef CONFIG_X86_64
3911 * Load null selectors, so we can avoid reloading them in
3912 * __vmx_load_host_state(), in case userspace uses the null selectors
3913 * too (the expected case).
3915 vmcs_write16(HOST_DS_SELECTOR, 0);
3916 vmcs_write16(HOST_ES_SELECTOR, 0);
3917 #else
3918 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3919 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3920 #endif
3921 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3922 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
3924 native_store_idt(&dt);
3925 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
3927 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
3929 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3930 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3931 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
3932 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
3934 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
3935 rdmsr(MSR_IA32_CR_PAT, low32, high32);
3936 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
3940 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
3942 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
3943 if (enable_ept)
3944 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
3945 if (is_guest_mode(&vmx->vcpu))
3946 vmx->vcpu.arch.cr4_guest_owned_bits &=
3947 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
3948 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
3951 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
3953 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
3954 if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
3955 exec_control &= ~CPU_BASED_TPR_SHADOW;
3956 #ifdef CONFIG_X86_64
3957 exec_control |= CPU_BASED_CR8_STORE_EXITING |
3958 CPU_BASED_CR8_LOAD_EXITING;
3959 #endif
3961 if (!enable_ept)
3962 exec_control |= CPU_BASED_CR3_STORE_EXITING |
3963 CPU_BASED_CR3_LOAD_EXITING |
3964 CPU_BASED_INVLPG_EXITING;
3965 return exec_control;
3968 static int vmx_vm_has_apicv(struct kvm *kvm)
3970 return enable_apicv_reg_vid && irqchip_in_kernel(kvm);
3973 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
3975 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
3976 if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
3977 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3978 if (vmx->vpid == 0)
3979 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
3980 if (!enable_ept) {
3981 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
3982 enable_unrestricted_guest = 0;
3983 /* Enable INVPCID for non-ept guests may cause performance regression. */
3984 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
3986 if (!enable_unrestricted_guest)
3987 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
3988 if (!ple_gap)
3989 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
3990 if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
3991 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
3992 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3993 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
3994 return exec_control;
3997 static void ept_set_mmio_spte_mask(void)
4000 * EPT Misconfigurations can be generated if the value of bits 2:0
4001 * of an EPT paging-structure entry is 110b (write/execute).
4002 * Also, magic bits (0xffull << 49) is set to quickly identify mmio
4003 * spte.
4005 kvm_mmu_set_mmio_spte_mask(0xffull << 49 | 0x6ull);
4009 * Sets up the vmcs for emulated real mode.
4011 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
4013 #ifdef CONFIG_X86_64
4014 unsigned long a;
4015 #endif
4016 int i;
4018 /* I/O */
4019 vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
4020 vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
4022 if (cpu_has_vmx_msr_bitmap())
4023 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
4025 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4027 /* Control */
4028 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
4029 vmcs_config.pin_based_exec_ctrl);
4031 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
4033 if (cpu_has_secondary_exec_ctrls()) {
4034 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4035 vmx_secondary_exec_control(vmx));
4038 if (enable_apicv_reg_vid) {
4039 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4040 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4041 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4042 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4044 vmcs_write16(GUEST_INTR_STATUS, 0);
4047 if (ple_gap) {
4048 vmcs_write32(PLE_GAP, ple_gap);
4049 vmcs_write32(PLE_WINDOW, ple_window);
4052 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4053 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4054 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4056 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4057 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4058 vmx_set_constant_host_state();
4059 #ifdef CONFIG_X86_64
4060 rdmsrl(MSR_FS_BASE, a);
4061 vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
4062 rdmsrl(MSR_GS_BASE, a);
4063 vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
4064 #else
4065 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4066 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4067 #endif
4069 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4070 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4071 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
4072 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4073 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
4075 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4076 u32 msr_low, msr_high;
4077 u64 host_pat;
4078 rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
4079 host_pat = msr_low | ((u64) msr_high << 32);
4080 /* Write the default value follow host pat */
4081 vmcs_write64(GUEST_IA32_PAT, host_pat);
4082 /* Keep arch.pat sync with GUEST_IA32_PAT */
4083 vmx->vcpu.arch.pat = host_pat;
4086 for (i = 0; i < NR_VMX_MSR; ++i) {
4087 u32 index = vmx_msr_index[i];
4088 u32 data_low, data_high;
4089 int j = vmx->nmsrs;
4091 if (rdmsr_safe(index, &data_low, &data_high) < 0)
4092 continue;
4093 if (wrmsr_safe(index, data_low, data_high) < 0)
4094 continue;
4095 vmx->guest_msrs[j].index = i;
4096 vmx->guest_msrs[j].data = 0;
4097 vmx->guest_msrs[j].mask = -1ull;
4098 ++vmx->nmsrs;
4101 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
4103 /* 22.2.1, 20.8.1 */
4104 vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
4106 vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
4107 set_cr4_guest_host_mask(vmx);
4109 return 0;
4112 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4114 struct vcpu_vmx *vmx = to_vmx(vcpu);
4115 u64 msr;
4117 vmx->rmode.vm86_active = 0;
4119 vmx->soft_vnmi_blocked = 0;
4121 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4122 kvm_set_cr8(&vmx->vcpu, 0);
4123 msr = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
4124 if (kvm_vcpu_is_bsp(&vmx->vcpu))
4125 msr |= MSR_IA32_APICBASE_BSP;
4126 kvm_set_apic_base(&vmx->vcpu, msr);
4128 vmx_segment_cache_clear(vmx);
4130 seg_setup(VCPU_SREG_CS);
4131 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4133 seg_setup(VCPU_SREG_DS);
4134 seg_setup(VCPU_SREG_ES);
4135 seg_setup(VCPU_SREG_FS);
4136 seg_setup(VCPU_SREG_GS);
4137 seg_setup(VCPU_SREG_SS);
4139 vmcs_write16(GUEST_TR_SELECTOR, 0);
4140 vmcs_writel(GUEST_TR_BASE, 0);
4141 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4142 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4144 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4145 vmcs_writel(GUEST_LDTR_BASE, 0);
4146 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4147 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4149 vmcs_write32(GUEST_SYSENTER_CS, 0);
4150 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4151 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4153 vmcs_writel(GUEST_RFLAGS, 0x02);
4154 kvm_rip_write(vcpu, 0xfff0);
4156 vmcs_writel(GUEST_GDTR_BASE, 0);
4157 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4159 vmcs_writel(GUEST_IDTR_BASE, 0);
4160 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4162 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4163 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4164 vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4166 /* Special registers */
4167 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4169 setup_msrs(vmx);
4171 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4173 if (cpu_has_vmx_tpr_shadow()) {
4174 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4175 if (vm_need_tpr_shadow(vmx->vcpu.kvm))
4176 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4177 __pa(vmx->vcpu.arch.apic->regs));
4178 vmcs_write32(TPR_THRESHOLD, 0);
4181 if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
4182 vmcs_write64(APIC_ACCESS_ADDR,
4183 page_to_phys(vmx->vcpu.kvm->arch.apic_access_page));
4185 if (vmx->vpid != 0)
4186 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4188 vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4189 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
4190 vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */
4191 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
4192 vmx_set_cr4(&vmx->vcpu, 0);
4193 vmx_set_efer(&vmx->vcpu, 0);
4194 vmx_fpu_activate(&vmx->vcpu);
4195 update_exception_bitmap(&vmx->vcpu);
4197 vpid_sync_context(vmx);
4201 * In nested virtualization, check if L1 asked to exit on external interrupts.
4202 * For most existing hypervisors, this will always return true.
4204 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
4206 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
4207 PIN_BASED_EXT_INTR_MASK;
4210 static void enable_irq_window(struct kvm_vcpu *vcpu)
4212 u32 cpu_based_vm_exec_control;
4213 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu)) {
4215 * We get here if vmx_interrupt_allowed() said we can't
4216 * inject to L1 now because L2 must run. Ask L2 to exit
4217 * right after entry, so we can inject to L1 more promptly.
4219 kvm_make_request(KVM_REQ_IMMEDIATE_EXIT, vcpu);
4220 return;
4223 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4224 cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
4225 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4228 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4230 u32 cpu_based_vm_exec_control;
4232 if (!cpu_has_virtual_nmis()) {
4233 enable_irq_window(vcpu);
4234 return;
4237 if (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4238 enable_irq_window(vcpu);
4239 return;
4241 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4242 cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
4243 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4246 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4248 struct vcpu_vmx *vmx = to_vmx(vcpu);
4249 uint32_t intr;
4250 int irq = vcpu->arch.interrupt.nr;
4252 trace_kvm_inj_virq(irq);
4254 ++vcpu->stat.irq_injections;
4255 if (vmx->rmode.vm86_active) {
4256 int inc_eip = 0;
4257 if (vcpu->arch.interrupt.soft)
4258 inc_eip = vcpu->arch.event_exit_inst_len;
4259 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
4260 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4261 return;
4263 intr = irq | INTR_INFO_VALID_MASK;
4264 if (vcpu->arch.interrupt.soft) {
4265 intr |= INTR_TYPE_SOFT_INTR;
4266 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4267 vmx->vcpu.arch.event_exit_inst_len);
4268 } else
4269 intr |= INTR_TYPE_EXT_INTR;
4270 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4273 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4275 struct vcpu_vmx *vmx = to_vmx(vcpu);
4277 if (is_guest_mode(vcpu))
4278 return;
4280 if (!cpu_has_virtual_nmis()) {
4282 * Tracking the NMI-blocked state in software is built upon
4283 * finding the next open IRQ window. This, in turn, depends on
4284 * well-behaving guests: They have to keep IRQs disabled at
4285 * least as long as the NMI handler runs. Otherwise we may
4286 * cause NMI nesting, maybe breaking the guest. But as this is
4287 * highly unlikely, we can live with the residual risk.
4289 vmx->soft_vnmi_blocked = 1;
4290 vmx->vnmi_blocked_time = 0;
4293 ++vcpu->stat.nmi_injections;
4294 vmx->nmi_known_unmasked = false;
4295 if (vmx->rmode.vm86_active) {
4296 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
4297 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4298 return;
4300 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4301 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4304 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4306 if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
4307 return 0;
4309 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4310 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4311 | GUEST_INTR_STATE_NMI));
4314 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4316 if (!cpu_has_virtual_nmis())
4317 return to_vmx(vcpu)->soft_vnmi_blocked;
4318 if (to_vmx(vcpu)->nmi_known_unmasked)
4319 return false;
4320 return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4323 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4325 struct vcpu_vmx *vmx = to_vmx(vcpu);
4327 if (!cpu_has_virtual_nmis()) {
4328 if (vmx->soft_vnmi_blocked != masked) {
4329 vmx->soft_vnmi_blocked = masked;
4330 vmx->vnmi_blocked_time = 0;
4332 } else {
4333 vmx->nmi_known_unmasked = !masked;
4334 if (masked)
4335 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4336 GUEST_INTR_STATE_NMI);
4337 else
4338 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4339 GUEST_INTR_STATE_NMI);
4343 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4345 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu)) {
4346 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4347 if (to_vmx(vcpu)->nested.nested_run_pending ||
4348 (vmcs12->idt_vectoring_info_field &
4349 VECTORING_INFO_VALID_MASK))
4350 return 0;
4351 nested_vmx_vmexit(vcpu);
4352 vmcs12->vm_exit_reason = EXIT_REASON_EXTERNAL_INTERRUPT;
4353 vmcs12->vm_exit_intr_info = 0;
4354 /* fall through to normal code, but now in L1, not L2 */
4357 return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4358 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4359 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4362 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4364 int ret;
4365 struct kvm_userspace_memory_region tss_mem = {
4366 .slot = TSS_PRIVATE_MEMSLOT,
4367 .guest_phys_addr = addr,
4368 .memory_size = PAGE_SIZE * 3,
4369 .flags = 0,
4372 ret = kvm_set_memory_region(kvm, &tss_mem);
4373 if (ret)
4374 return ret;
4375 kvm->arch.tss_addr = addr;
4376 if (!init_rmode_tss(kvm))
4377 return -ENOMEM;
4379 return 0;
4382 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4384 switch (vec) {
4385 case BP_VECTOR:
4387 * Update instruction length as we may reinject the exception
4388 * from user space while in guest debugging mode.
4390 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4391 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4392 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4393 return false;
4394 /* fall through */
4395 case DB_VECTOR:
4396 if (vcpu->guest_debug &
4397 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4398 return false;
4399 /* fall through */
4400 case DE_VECTOR:
4401 case OF_VECTOR:
4402 case BR_VECTOR:
4403 case UD_VECTOR:
4404 case DF_VECTOR:
4405 case SS_VECTOR:
4406 case GP_VECTOR:
4407 case MF_VECTOR:
4408 return true;
4409 break;
4411 return false;
4414 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4415 int vec, u32 err_code)
4418 * Instruction with address size override prefix opcode 0x67
4419 * Cause the #SS fault with 0 error code in VM86 mode.
4421 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4422 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
4423 if (vcpu->arch.halt_request) {
4424 vcpu->arch.halt_request = 0;
4425 return kvm_emulate_halt(vcpu);
4427 return 1;
4429 return 0;
4433 * Forward all other exceptions that are valid in real mode.
4434 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4435 * the required debugging infrastructure rework.
4437 kvm_queue_exception(vcpu, vec);
4438 return 1;
4442 * Trigger machine check on the host. We assume all the MSRs are already set up
4443 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4444 * We pass a fake environment to the machine check handler because we want
4445 * the guest to be always treated like user space, no matter what context
4446 * it used internally.
4448 static void kvm_machine_check(void)
4450 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4451 struct pt_regs regs = {
4452 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4453 .flags = X86_EFLAGS_IF,
4456 do_machine_check(&regs, 0);
4457 #endif
4460 static int handle_machine_check(struct kvm_vcpu *vcpu)
4462 /* already handled by vcpu_run */
4463 return 1;
4466 static int handle_exception(struct kvm_vcpu *vcpu)
4468 struct vcpu_vmx *vmx = to_vmx(vcpu);
4469 struct kvm_run *kvm_run = vcpu->run;
4470 u32 intr_info, ex_no, error_code;
4471 unsigned long cr2, rip, dr6;
4472 u32 vect_info;
4473 enum emulation_result er;
4475 vect_info = vmx->idt_vectoring_info;
4476 intr_info = vmx->exit_intr_info;
4478 if (is_machine_check(intr_info))
4479 return handle_machine_check(vcpu);
4481 if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
4482 return 1; /* already handled by vmx_vcpu_run() */
4484 if (is_no_device(intr_info)) {
4485 vmx_fpu_activate(vcpu);
4486 return 1;
4489 if (is_invalid_opcode(intr_info)) {
4490 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
4491 if (er != EMULATE_DONE)
4492 kvm_queue_exception(vcpu, UD_VECTOR);
4493 return 1;
4496 error_code = 0;
4497 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4498 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4501 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4502 * MMIO, it is better to report an internal error.
4503 * See the comments in vmx_handle_exit.
4505 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4506 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4507 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4508 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4509 vcpu->run->internal.ndata = 2;
4510 vcpu->run->internal.data[0] = vect_info;
4511 vcpu->run->internal.data[1] = intr_info;
4512 return 0;
4515 if (is_page_fault(intr_info)) {
4516 /* EPT won't cause page fault directly */
4517 BUG_ON(enable_ept);
4518 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4519 trace_kvm_page_fault(cr2, error_code);
4521 if (kvm_event_needs_reinjection(vcpu))
4522 kvm_mmu_unprotect_page_virt(vcpu, cr2);
4523 return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
4526 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4528 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4529 return handle_rmode_exception(vcpu, ex_no, error_code);
4531 switch (ex_no) {
4532 case DB_VECTOR:
4533 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4534 if (!(vcpu->guest_debug &
4535 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4536 vcpu->arch.dr6 = dr6 | DR6_FIXED_1;
4537 kvm_queue_exception(vcpu, DB_VECTOR);
4538 return 1;
4540 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4541 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4542 /* fall through */
4543 case BP_VECTOR:
4545 * Update instruction length as we may reinject #BP from
4546 * user space while in guest debugging mode. Reading it for
4547 * #DB as well causes no harm, it is not used in that case.
4549 vmx->vcpu.arch.event_exit_inst_len =
4550 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4551 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4552 rip = kvm_rip_read(vcpu);
4553 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4554 kvm_run->debug.arch.exception = ex_no;
4555 break;
4556 default:
4557 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4558 kvm_run->ex.exception = ex_no;
4559 kvm_run->ex.error_code = error_code;
4560 break;
4562 return 0;
4565 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4567 ++vcpu->stat.irq_exits;
4568 return 1;
4571 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4573 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4574 return 0;
4577 static int handle_io(struct kvm_vcpu *vcpu)
4579 unsigned long exit_qualification;
4580 int size, in, string;
4581 unsigned port;
4583 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4584 string = (exit_qualification & 16) != 0;
4585 in = (exit_qualification & 8) != 0;
4587 ++vcpu->stat.io_exits;
4589 if (string || in)
4590 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
4592 port = exit_qualification >> 16;
4593 size = (exit_qualification & 7) + 1;
4594 skip_emulated_instruction(vcpu);
4596 return kvm_fast_pio_out(vcpu, size, port);
4599 static void
4600 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4603 * Patch in the VMCALL instruction:
4605 hypercall[0] = 0x0f;
4606 hypercall[1] = 0x01;
4607 hypercall[2] = 0xc1;
4610 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4611 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4613 if (is_guest_mode(vcpu)) {
4614 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4615 unsigned long orig_val = val;
4618 * We get here when L2 changed cr0 in a way that did not change
4619 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4620 * but did change L0 shadowed bits. So we first calculate the
4621 * effective cr0 value that L1 would like to write into the
4622 * hardware. It consists of the L2-owned bits from the new
4623 * value combined with the L1-owned bits from L1's guest_cr0.
4625 val = (val & ~vmcs12->cr0_guest_host_mask) |
4626 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4628 /* TODO: will have to take unrestricted guest mode into
4629 * account */
4630 if ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON)
4631 return 1;
4633 if (kvm_set_cr0(vcpu, val))
4634 return 1;
4635 vmcs_writel(CR0_READ_SHADOW, orig_val);
4636 return 0;
4637 } else {
4638 if (to_vmx(vcpu)->nested.vmxon &&
4639 ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
4640 return 1;
4641 return kvm_set_cr0(vcpu, val);
4645 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4647 if (is_guest_mode(vcpu)) {
4648 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4649 unsigned long orig_val = val;
4651 /* analogously to handle_set_cr0 */
4652 val = (val & ~vmcs12->cr4_guest_host_mask) |
4653 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4654 if (kvm_set_cr4(vcpu, val))
4655 return 1;
4656 vmcs_writel(CR4_READ_SHADOW, orig_val);
4657 return 0;
4658 } else
4659 return kvm_set_cr4(vcpu, val);
4662 /* called to set cr0 as approriate for clts instruction exit. */
4663 static void handle_clts(struct kvm_vcpu *vcpu)
4665 if (is_guest_mode(vcpu)) {
4667 * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
4668 * but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
4669 * just pretend it's off (also in arch.cr0 for fpu_activate).
4671 vmcs_writel(CR0_READ_SHADOW,
4672 vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
4673 vcpu->arch.cr0 &= ~X86_CR0_TS;
4674 } else
4675 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4678 static int handle_cr(struct kvm_vcpu *vcpu)
4680 unsigned long exit_qualification, val;
4681 int cr;
4682 int reg;
4683 int err;
4685 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4686 cr = exit_qualification & 15;
4687 reg = (exit_qualification >> 8) & 15;
4688 switch ((exit_qualification >> 4) & 3) {
4689 case 0: /* mov to cr */
4690 val = kvm_register_read(vcpu, reg);
4691 trace_kvm_cr_write(cr, val);
4692 switch (cr) {
4693 case 0:
4694 err = handle_set_cr0(vcpu, val);
4695 kvm_complete_insn_gp(vcpu, err);
4696 return 1;
4697 case 3:
4698 err = kvm_set_cr3(vcpu, val);
4699 kvm_complete_insn_gp(vcpu, err);
4700 return 1;
4701 case 4:
4702 err = handle_set_cr4(vcpu, val);
4703 kvm_complete_insn_gp(vcpu, err);
4704 return 1;
4705 case 8: {
4706 u8 cr8_prev = kvm_get_cr8(vcpu);
4707 u8 cr8 = kvm_register_read(vcpu, reg);
4708 err = kvm_set_cr8(vcpu, cr8);
4709 kvm_complete_insn_gp(vcpu, err);
4710 if (irqchip_in_kernel(vcpu->kvm))
4711 return 1;
4712 if (cr8_prev <= cr8)
4713 return 1;
4714 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4715 return 0;
4718 break;
4719 case 2: /* clts */
4720 handle_clts(vcpu);
4721 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4722 skip_emulated_instruction(vcpu);
4723 vmx_fpu_activate(vcpu);
4724 return 1;
4725 case 1: /*mov from cr*/
4726 switch (cr) {
4727 case 3:
4728 val = kvm_read_cr3(vcpu);
4729 kvm_register_write(vcpu, reg, val);
4730 trace_kvm_cr_read(cr, val);
4731 skip_emulated_instruction(vcpu);
4732 return 1;
4733 case 8:
4734 val = kvm_get_cr8(vcpu);
4735 kvm_register_write(vcpu, reg, val);
4736 trace_kvm_cr_read(cr, val);
4737 skip_emulated_instruction(vcpu);
4738 return 1;
4740 break;
4741 case 3: /* lmsw */
4742 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4743 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4744 kvm_lmsw(vcpu, val);
4746 skip_emulated_instruction(vcpu);
4747 return 1;
4748 default:
4749 break;
4751 vcpu->run->exit_reason = 0;
4752 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4753 (int)(exit_qualification >> 4) & 3, cr);
4754 return 0;
4757 static int handle_dr(struct kvm_vcpu *vcpu)
4759 unsigned long exit_qualification;
4760 int dr, reg;
4762 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
4763 if (!kvm_require_cpl(vcpu, 0))
4764 return 1;
4765 dr = vmcs_readl(GUEST_DR7);
4766 if (dr & DR7_GD) {
4768 * As the vm-exit takes precedence over the debug trap, we
4769 * need to emulate the latter, either for the host or the
4770 * guest debugging itself.
4772 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
4773 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
4774 vcpu->run->debug.arch.dr7 = dr;
4775 vcpu->run->debug.arch.pc =
4776 vmcs_readl(GUEST_CS_BASE) +
4777 vmcs_readl(GUEST_RIP);
4778 vcpu->run->debug.arch.exception = DB_VECTOR;
4779 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
4780 return 0;
4781 } else {
4782 vcpu->arch.dr7 &= ~DR7_GD;
4783 vcpu->arch.dr6 |= DR6_BD;
4784 vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
4785 kvm_queue_exception(vcpu, DB_VECTOR);
4786 return 1;
4790 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4791 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
4792 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
4793 if (exit_qualification & TYPE_MOV_FROM_DR) {
4794 unsigned long val;
4795 if (!kvm_get_dr(vcpu, dr, &val))
4796 kvm_register_write(vcpu, reg, val);
4797 } else
4798 kvm_set_dr(vcpu, dr, vcpu->arch.regs[reg]);
4799 skip_emulated_instruction(vcpu);
4800 return 1;
4803 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
4805 vmcs_writel(GUEST_DR7, val);
4808 static int handle_cpuid(struct kvm_vcpu *vcpu)
4810 kvm_emulate_cpuid(vcpu);
4811 return 1;
4814 static int handle_rdmsr(struct kvm_vcpu *vcpu)
4816 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4817 u64 data;
4819 if (vmx_get_msr(vcpu, ecx, &data)) {
4820 trace_kvm_msr_read_ex(ecx);
4821 kvm_inject_gp(vcpu, 0);
4822 return 1;
4825 trace_kvm_msr_read(ecx, data);
4827 /* FIXME: handling of bits 32:63 of rax, rdx */
4828 vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u;
4829 vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
4830 skip_emulated_instruction(vcpu);
4831 return 1;
4834 static int handle_wrmsr(struct kvm_vcpu *vcpu)
4836 struct msr_data msr;
4837 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4838 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
4839 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
4841 msr.data = data;
4842 msr.index = ecx;
4843 msr.host_initiated = false;
4844 if (vmx_set_msr(vcpu, &msr) != 0) {
4845 trace_kvm_msr_write_ex(ecx, data);
4846 kvm_inject_gp(vcpu, 0);
4847 return 1;
4850 trace_kvm_msr_write(ecx, data);
4851 skip_emulated_instruction(vcpu);
4852 return 1;
4855 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
4857 kvm_make_request(KVM_REQ_EVENT, vcpu);
4858 return 1;
4861 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
4863 u32 cpu_based_vm_exec_control;
4865 /* clear pending irq */
4866 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4867 cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
4868 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4870 kvm_make_request(KVM_REQ_EVENT, vcpu);
4872 ++vcpu->stat.irq_window_exits;
4875 * If the user space waits to inject interrupts, exit as soon as
4876 * possible
4878 if (!irqchip_in_kernel(vcpu->kvm) &&
4879 vcpu->run->request_interrupt_window &&
4880 !kvm_cpu_has_interrupt(vcpu)) {
4881 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
4882 return 0;
4884 return 1;
4887 static int handle_halt(struct kvm_vcpu *vcpu)
4889 skip_emulated_instruction(vcpu);
4890 return kvm_emulate_halt(vcpu);
4893 static int handle_vmcall(struct kvm_vcpu *vcpu)
4895 skip_emulated_instruction(vcpu);
4896 kvm_emulate_hypercall(vcpu);
4897 return 1;
4900 static int handle_invd(struct kvm_vcpu *vcpu)
4902 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
4905 static int handle_invlpg(struct kvm_vcpu *vcpu)
4907 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4909 kvm_mmu_invlpg(vcpu, exit_qualification);
4910 skip_emulated_instruction(vcpu);
4911 return 1;
4914 static int handle_rdpmc(struct kvm_vcpu *vcpu)
4916 int err;
4918 err = kvm_rdpmc(vcpu);
4919 kvm_complete_insn_gp(vcpu, err);
4921 return 1;
4924 static int handle_wbinvd(struct kvm_vcpu *vcpu)
4926 skip_emulated_instruction(vcpu);
4927 kvm_emulate_wbinvd(vcpu);
4928 return 1;
4931 static int handle_xsetbv(struct kvm_vcpu *vcpu)
4933 u64 new_bv = kvm_read_edx_eax(vcpu);
4934 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
4936 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
4937 skip_emulated_instruction(vcpu);
4938 return 1;
4941 static int handle_apic_access(struct kvm_vcpu *vcpu)
4943 if (likely(fasteoi)) {
4944 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4945 int access_type, offset;
4947 access_type = exit_qualification & APIC_ACCESS_TYPE;
4948 offset = exit_qualification & APIC_ACCESS_OFFSET;
4950 * Sane guest uses MOV to write EOI, with written value
4951 * not cared. So make a short-circuit here by avoiding
4952 * heavy instruction emulation.
4954 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
4955 (offset == APIC_EOI)) {
4956 kvm_lapic_set_eoi(vcpu);
4957 skip_emulated_instruction(vcpu);
4958 return 1;
4961 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
4964 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
4966 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4967 int vector = exit_qualification & 0xff;
4969 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
4970 kvm_apic_set_eoi_accelerated(vcpu, vector);
4971 return 1;
4974 static int handle_apic_write(struct kvm_vcpu *vcpu)
4976 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4977 u32 offset = exit_qualification & 0xfff;
4979 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
4980 kvm_apic_write_nodecode(vcpu, offset);
4981 return 1;
4984 static int handle_task_switch(struct kvm_vcpu *vcpu)
4986 struct vcpu_vmx *vmx = to_vmx(vcpu);
4987 unsigned long exit_qualification;
4988 bool has_error_code = false;
4989 u32 error_code = 0;
4990 u16 tss_selector;
4991 int reason, type, idt_v, idt_index;
4993 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
4994 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
4995 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
4997 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4999 reason = (u32)exit_qualification >> 30;
5000 if (reason == TASK_SWITCH_GATE && idt_v) {
5001 switch (type) {
5002 case INTR_TYPE_NMI_INTR:
5003 vcpu->arch.nmi_injected = false;
5004 vmx_set_nmi_mask(vcpu, true);
5005 break;
5006 case INTR_TYPE_EXT_INTR:
5007 case INTR_TYPE_SOFT_INTR:
5008 kvm_clear_interrupt_queue(vcpu);
5009 break;
5010 case INTR_TYPE_HARD_EXCEPTION:
5011 if (vmx->idt_vectoring_info &
5012 VECTORING_INFO_DELIVER_CODE_MASK) {
5013 has_error_code = true;
5014 error_code =
5015 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5017 /* fall through */
5018 case INTR_TYPE_SOFT_EXCEPTION:
5019 kvm_clear_exception_queue(vcpu);
5020 break;
5021 default:
5022 break;
5025 tss_selector = exit_qualification;
5027 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5028 type != INTR_TYPE_EXT_INTR &&
5029 type != INTR_TYPE_NMI_INTR))
5030 skip_emulated_instruction(vcpu);
5032 if (kvm_task_switch(vcpu, tss_selector,
5033 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
5034 has_error_code, error_code) == EMULATE_FAIL) {
5035 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5036 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5037 vcpu->run->internal.ndata = 0;
5038 return 0;
5041 /* clear all local breakpoint enable flags */
5042 vmcs_writel(GUEST_DR7, vmcs_readl(GUEST_DR7) & ~55);
5045 * TODO: What about debug traps on tss switch?
5046 * Are we supposed to inject them and update dr6?
5049 return 1;
5052 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5054 unsigned long exit_qualification;
5055 gpa_t gpa;
5056 u32 error_code;
5057 int gla_validity;
5059 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5061 gla_validity = (exit_qualification >> 7) & 0x3;
5062 if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) {
5063 printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
5064 printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
5065 (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
5066 vmcs_readl(GUEST_LINEAR_ADDRESS));
5067 printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
5068 (long unsigned int)exit_qualification);
5069 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5070 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
5071 return 0;
5074 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5075 trace_kvm_page_fault(gpa, exit_qualification);
5077 /* It is a write fault? */
5078 error_code = exit_qualification & (1U << 1);
5079 /* ept page table is present? */
5080 error_code |= (exit_qualification >> 3) & 0x1;
5082 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5085 static u64 ept_rsvd_mask(u64 spte, int level)
5087 int i;
5088 u64 mask = 0;
5090 for (i = 51; i > boot_cpu_data.x86_phys_bits; i--)
5091 mask |= (1ULL << i);
5093 if (level > 2)
5094 /* bits 7:3 reserved */
5095 mask |= 0xf8;
5096 else if (level == 2) {
5097 if (spte & (1ULL << 7))
5098 /* 2MB ref, bits 20:12 reserved */
5099 mask |= 0x1ff000;
5100 else
5101 /* bits 6:3 reserved */
5102 mask |= 0x78;
5105 return mask;
5108 static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
5109 int level)
5111 printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level);
5113 /* 010b (write-only) */
5114 WARN_ON((spte & 0x7) == 0x2);
5116 /* 110b (write/execute) */
5117 WARN_ON((spte & 0x7) == 0x6);
5119 /* 100b (execute-only) and value not supported by logical processor */
5120 if (!cpu_has_vmx_ept_execute_only())
5121 WARN_ON((spte & 0x7) == 0x4);
5123 /* not 000b */
5124 if ((spte & 0x7)) {
5125 u64 rsvd_bits = spte & ept_rsvd_mask(spte, level);
5127 if (rsvd_bits != 0) {
5128 printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n",
5129 __func__, rsvd_bits);
5130 WARN_ON(1);
5133 if (level == 1 || (level == 2 && (spte & (1ULL << 7)))) {
5134 u64 ept_mem_type = (spte & 0x38) >> 3;
5136 if (ept_mem_type == 2 || ept_mem_type == 3 ||
5137 ept_mem_type == 7) {
5138 printk(KERN_ERR "%s: ept_mem_type=0x%llx\n",
5139 __func__, ept_mem_type);
5140 WARN_ON(1);
5146 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5148 u64 sptes[4];
5149 int nr_sptes, i, ret;
5150 gpa_t gpa;
5152 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5154 ret = handle_mmio_page_fault_common(vcpu, gpa, true);
5155 if (likely(ret == 1))
5156 return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
5157 EMULATE_DONE;
5158 if (unlikely(!ret))
5159 return 1;
5161 /* It is the real ept misconfig */
5162 printk(KERN_ERR "EPT: Misconfiguration.\n");
5163 printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa);
5165 nr_sptes = kvm_mmu_get_spte_hierarchy(vcpu, gpa, sptes);
5167 for (i = PT64_ROOT_LEVEL; i > PT64_ROOT_LEVEL - nr_sptes; --i)
5168 ept_misconfig_inspect_spte(vcpu, sptes[i-1], i);
5170 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5171 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
5173 return 0;
5176 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5178 u32 cpu_based_vm_exec_control;
5180 /* clear pending NMI */
5181 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5182 cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
5183 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5184 ++vcpu->stat.nmi_window_exits;
5185 kvm_make_request(KVM_REQ_EVENT, vcpu);
5187 return 1;
5190 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5192 struct vcpu_vmx *vmx = to_vmx(vcpu);
5193 enum emulation_result err = EMULATE_DONE;
5194 int ret = 1;
5195 u32 cpu_exec_ctrl;
5196 bool intr_window_requested;
5197 unsigned count = 130;
5199 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5200 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
5202 while (!guest_state_valid(vcpu) && count-- != 0) {
5203 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5204 return handle_interrupt_window(&vmx->vcpu);
5206 if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
5207 return 1;
5209 err = emulate_instruction(vcpu, 0);
5211 if (err == EMULATE_DO_MMIO) {
5212 ret = 0;
5213 goto out;
5216 if (err != EMULATE_DONE) {
5217 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5218 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5219 vcpu->run->internal.ndata = 0;
5220 return 0;
5223 if (signal_pending(current))
5224 goto out;
5225 if (need_resched())
5226 schedule();
5229 vmx->emulation_required = emulation_required(vcpu);
5230 out:
5231 return ret;
5235 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5236 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5238 static int handle_pause(struct kvm_vcpu *vcpu)
5240 skip_emulated_instruction(vcpu);
5241 kvm_vcpu_on_spin(vcpu);
5243 return 1;
5246 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5248 kvm_queue_exception(vcpu, UD_VECTOR);
5249 return 1;
5253 * To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
5254 * We could reuse a single VMCS for all the L2 guests, but we also want the
5255 * option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
5256 * allows keeping them loaded on the processor, and in the future will allow
5257 * optimizations where prepare_vmcs02 doesn't need to set all the fields on
5258 * every entry if they never change.
5259 * So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
5260 * (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
5262 * The following functions allocate and free a vmcs02 in this pool.
5265 /* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
5266 static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
5268 struct vmcs02_list *item;
5269 list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
5270 if (item->vmptr == vmx->nested.current_vmptr) {
5271 list_move(&item->list, &vmx->nested.vmcs02_pool);
5272 return &item->vmcs02;
5275 if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
5276 /* Recycle the least recently used VMCS. */
5277 item = list_entry(vmx->nested.vmcs02_pool.prev,
5278 struct vmcs02_list, list);
5279 item->vmptr = vmx->nested.current_vmptr;
5280 list_move(&item->list, &vmx->nested.vmcs02_pool);
5281 return &item->vmcs02;
5284 /* Create a new VMCS */
5285 item = kmalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
5286 if (!item)
5287 return NULL;
5288 item->vmcs02.vmcs = alloc_vmcs();
5289 if (!item->vmcs02.vmcs) {
5290 kfree(item);
5291 return NULL;
5293 loaded_vmcs_init(&item->vmcs02);
5294 item->vmptr = vmx->nested.current_vmptr;
5295 list_add(&(item->list), &(vmx->nested.vmcs02_pool));
5296 vmx->nested.vmcs02_num++;
5297 return &item->vmcs02;
5300 /* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
5301 static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
5303 struct vmcs02_list *item;
5304 list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
5305 if (item->vmptr == vmptr) {
5306 free_loaded_vmcs(&item->vmcs02);
5307 list_del(&item->list);
5308 kfree(item);
5309 vmx->nested.vmcs02_num--;
5310 return;
5315 * Free all VMCSs saved for this vcpu, except the one pointed by
5316 * vmx->loaded_vmcs. These include the VMCSs in vmcs02_pool (except the one
5317 * currently used, if running L2), and vmcs01 when running L2.
5319 static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
5321 struct vmcs02_list *item, *n;
5322 list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
5323 if (vmx->loaded_vmcs != &item->vmcs02)
5324 free_loaded_vmcs(&item->vmcs02);
5325 list_del(&item->list);
5326 kfree(item);
5328 vmx->nested.vmcs02_num = 0;
5330 if (vmx->loaded_vmcs != &vmx->vmcs01)
5331 free_loaded_vmcs(&vmx->vmcs01);
5335 * Emulate the VMXON instruction.
5336 * Currently, we just remember that VMX is active, and do not save or even
5337 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
5338 * do not currently need to store anything in that guest-allocated memory
5339 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
5340 * argument is different from the VMXON pointer (which the spec says they do).
5342 static int handle_vmon(struct kvm_vcpu *vcpu)
5344 struct kvm_segment cs;
5345 struct vcpu_vmx *vmx = to_vmx(vcpu);
5347 /* The Intel VMX Instruction Reference lists a bunch of bits that
5348 * are prerequisite to running VMXON, most notably cr4.VMXE must be
5349 * set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
5350 * Otherwise, we should fail with #UD. We test these now:
5352 if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
5353 !kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
5354 (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5355 kvm_queue_exception(vcpu, UD_VECTOR);
5356 return 1;
5359 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5360 if (is_long_mode(vcpu) && !cs.l) {
5361 kvm_queue_exception(vcpu, UD_VECTOR);
5362 return 1;
5365 if (vmx_get_cpl(vcpu)) {
5366 kvm_inject_gp(vcpu, 0);
5367 return 1;
5370 INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
5371 vmx->nested.vmcs02_num = 0;
5373 vmx->nested.vmxon = true;
5375 skip_emulated_instruction(vcpu);
5376 return 1;
5380 * Intel's VMX Instruction Reference specifies a common set of prerequisites
5381 * for running VMX instructions (except VMXON, whose prerequisites are
5382 * slightly different). It also specifies what exception to inject otherwise.
5384 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
5386 struct kvm_segment cs;
5387 struct vcpu_vmx *vmx = to_vmx(vcpu);
5389 if (!vmx->nested.vmxon) {
5390 kvm_queue_exception(vcpu, UD_VECTOR);
5391 return 0;
5394 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5395 if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
5396 (is_long_mode(vcpu) && !cs.l)) {
5397 kvm_queue_exception(vcpu, UD_VECTOR);
5398 return 0;
5401 if (vmx_get_cpl(vcpu)) {
5402 kvm_inject_gp(vcpu, 0);
5403 return 0;
5406 return 1;
5410 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
5411 * just stops using VMX.
5413 static void free_nested(struct vcpu_vmx *vmx)
5415 if (!vmx->nested.vmxon)
5416 return;
5417 vmx->nested.vmxon = false;
5418 if (vmx->nested.current_vmptr != -1ull) {
5419 kunmap(vmx->nested.current_vmcs12_page);
5420 nested_release_page(vmx->nested.current_vmcs12_page);
5421 vmx->nested.current_vmptr = -1ull;
5422 vmx->nested.current_vmcs12 = NULL;
5424 /* Unpin physical memory we referred to in current vmcs02 */
5425 if (vmx->nested.apic_access_page) {
5426 nested_release_page(vmx->nested.apic_access_page);
5427 vmx->nested.apic_access_page = 0;
5430 nested_free_all_saved_vmcss(vmx);
5433 /* Emulate the VMXOFF instruction */
5434 static int handle_vmoff(struct kvm_vcpu *vcpu)
5436 if (!nested_vmx_check_permission(vcpu))
5437 return 1;
5438 free_nested(to_vmx(vcpu));
5439 skip_emulated_instruction(vcpu);
5440 return 1;
5444 * Decode the memory-address operand of a vmx instruction, as recorded on an
5445 * exit caused by such an instruction (run by a guest hypervisor).
5446 * On success, returns 0. When the operand is invalid, returns 1 and throws
5447 * #UD or #GP.
5449 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
5450 unsigned long exit_qualification,
5451 u32 vmx_instruction_info, gva_t *ret)
5454 * According to Vol. 3B, "Information for VM Exits Due to Instruction
5455 * Execution", on an exit, vmx_instruction_info holds most of the
5456 * addressing components of the operand. Only the displacement part
5457 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
5458 * For how an actual address is calculated from all these components,
5459 * refer to Vol. 1, "Operand Addressing".
5461 int scaling = vmx_instruction_info & 3;
5462 int addr_size = (vmx_instruction_info >> 7) & 7;
5463 bool is_reg = vmx_instruction_info & (1u << 10);
5464 int seg_reg = (vmx_instruction_info >> 15) & 7;
5465 int index_reg = (vmx_instruction_info >> 18) & 0xf;
5466 bool index_is_valid = !(vmx_instruction_info & (1u << 22));
5467 int base_reg = (vmx_instruction_info >> 23) & 0xf;
5468 bool base_is_valid = !(vmx_instruction_info & (1u << 27));
5470 if (is_reg) {
5471 kvm_queue_exception(vcpu, UD_VECTOR);
5472 return 1;
5475 /* Addr = segment_base + offset */
5476 /* offset = base + [index * scale] + displacement */
5477 *ret = vmx_get_segment_base(vcpu, seg_reg);
5478 if (base_is_valid)
5479 *ret += kvm_register_read(vcpu, base_reg);
5480 if (index_is_valid)
5481 *ret += kvm_register_read(vcpu, index_reg)<<scaling;
5482 *ret += exit_qualification; /* holds the displacement */
5484 if (addr_size == 1) /* 32 bit */
5485 *ret &= 0xffffffff;
5488 * TODO: throw #GP (and return 1) in various cases that the VM*
5489 * instructions require it - e.g., offset beyond segment limit,
5490 * unusable or unreadable/unwritable segment, non-canonical 64-bit
5491 * address, and so on. Currently these are not checked.
5493 return 0;
5497 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
5498 * set the success or error code of an emulated VMX instruction, as specified
5499 * by Vol 2B, VMX Instruction Reference, "Conventions".
5501 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
5503 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
5504 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
5505 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
5508 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
5510 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
5511 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
5512 X86_EFLAGS_SF | X86_EFLAGS_OF))
5513 | X86_EFLAGS_CF);
5516 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
5517 u32 vm_instruction_error)
5519 if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
5521 * failValid writes the error number to the current VMCS, which
5522 * can't be done there isn't a current VMCS.
5524 nested_vmx_failInvalid(vcpu);
5525 return;
5527 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
5528 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
5529 X86_EFLAGS_SF | X86_EFLAGS_OF))
5530 | X86_EFLAGS_ZF);
5531 get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
5534 /* Emulate the VMCLEAR instruction */
5535 static int handle_vmclear(struct kvm_vcpu *vcpu)
5537 struct vcpu_vmx *vmx = to_vmx(vcpu);
5538 gva_t gva;
5539 gpa_t vmptr;
5540 struct vmcs12 *vmcs12;
5541 struct page *page;
5542 struct x86_exception e;
5544 if (!nested_vmx_check_permission(vcpu))
5545 return 1;
5547 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5548 vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
5549 return 1;
5551 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
5552 sizeof(vmptr), &e)) {
5553 kvm_inject_page_fault(vcpu, &e);
5554 return 1;
5557 if (!IS_ALIGNED(vmptr, PAGE_SIZE)) {
5558 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
5559 skip_emulated_instruction(vcpu);
5560 return 1;
5563 if (vmptr == vmx->nested.current_vmptr) {
5564 kunmap(vmx->nested.current_vmcs12_page);
5565 nested_release_page(vmx->nested.current_vmcs12_page);
5566 vmx->nested.current_vmptr = -1ull;
5567 vmx->nested.current_vmcs12 = NULL;
5570 page = nested_get_page(vcpu, vmptr);
5571 if (page == NULL) {
5573 * For accurate processor emulation, VMCLEAR beyond available
5574 * physical memory should do nothing at all. However, it is
5575 * possible that a nested vmx bug, not a guest hypervisor bug,
5576 * resulted in this case, so let's shut down before doing any
5577 * more damage:
5579 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5580 return 1;
5582 vmcs12 = kmap(page);
5583 vmcs12->launch_state = 0;
5584 kunmap(page);
5585 nested_release_page(page);
5587 nested_free_vmcs02(vmx, vmptr);
5589 skip_emulated_instruction(vcpu);
5590 nested_vmx_succeed(vcpu);
5591 return 1;
5594 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
5596 /* Emulate the VMLAUNCH instruction */
5597 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
5599 return nested_vmx_run(vcpu, true);
5602 /* Emulate the VMRESUME instruction */
5603 static int handle_vmresume(struct kvm_vcpu *vcpu)
5606 return nested_vmx_run(vcpu, false);
5609 enum vmcs_field_type {
5610 VMCS_FIELD_TYPE_U16 = 0,
5611 VMCS_FIELD_TYPE_U64 = 1,
5612 VMCS_FIELD_TYPE_U32 = 2,
5613 VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
5616 static inline int vmcs_field_type(unsigned long field)
5618 if (0x1 & field) /* the *_HIGH fields are all 32 bit */
5619 return VMCS_FIELD_TYPE_U32;
5620 return (field >> 13) & 0x3 ;
5623 static inline int vmcs_field_readonly(unsigned long field)
5625 return (((field >> 10) & 0x3) == 1);
5629 * Read a vmcs12 field. Since these can have varying lengths and we return
5630 * one type, we chose the biggest type (u64) and zero-extend the return value
5631 * to that size. Note that the caller, handle_vmread, might need to use only
5632 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
5633 * 64-bit fields are to be returned).
5635 static inline bool vmcs12_read_any(struct kvm_vcpu *vcpu,
5636 unsigned long field, u64 *ret)
5638 short offset = vmcs_field_to_offset(field);
5639 char *p;
5641 if (offset < 0)
5642 return 0;
5644 p = ((char *)(get_vmcs12(vcpu))) + offset;
5646 switch (vmcs_field_type(field)) {
5647 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
5648 *ret = *((natural_width *)p);
5649 return 1;
5650 case VMCS_FIELD_TYPE_U16:
5651 *ret = *((u16 *)p);
5652 return 1;
5653 case VMCS_FIELD_TYPE_U32:
5654 *ret = *((u32 *)p);
5655 return 1;
5656 case VMCS_FIELD_TYPE_U64:
5657 *ret = *((u64 *)p);
5658 return 1;
5659 default:
5660 return 0; /* can never happen. */
5665 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
5666 * used before) all generate the same failure when it is missing.
5668 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
5670 struct vcpu_vmx *vmx = to_vmx(vcpu);
5671 if (vmx->nested.current_vmptr == -1ull) {
5672 nested_vmx_failInvalid(vcpu);
5673 skip_emulated_instruction(vcpu);
5674 return 0;
5676 return 1;
5679 static int handle_vmread(struct kvm_vcpu *vcpu)
5681 unsigned long field;
5682 u64 field_value;
5683 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5684 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5685 gva_t gva = 0;
5687 if (!nested_vmx_check_permission(vcpu) ||
5688 !nested_vmx_check_vmcs12(vcpu))
5689 return 1;
5691 /* Decode instruction info and find the field to read */
5692 field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
5693 /* Read the field, zero-extended to a u64 field_value */
5694 if (!vmcs12_read_any(vcpu, field, &field_value)) {
5695 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5696 skip_emulated_instruction(vcpu);
5697 return 1;
5700 * Now copy part of this value to register or memory, as requested.
5701 * Note that the number of bits actually copied is 32 or 64 depending
5702 * on the guest's mode (32 or 64 bit), not on the given field's length.
5704 if (vmx_instruction_info & (1u << 10)) {
5705 kvm_register_write(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
5706 field_value);
5707 } else {
5708 if (get_vmx_mem_address(vcpu, exit_qualification,
5709 vmx_instruction_info, &gva))
5710 return 1;
5711 /* _system ok, as nested_vmx_check_permission verified cpl=0 */
5712 kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
5713 &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
5716 nested_vmx_succeed(vcpu);
5717 skip_emulated_instruction(vcpu);
5718 return 1;
5722 static int handle_vmwrite(struct kvm_vcpu *vcpu)
5724 unsigned long field;
5725 gva_t gva;
5726 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5727 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5728 char *p;
5729 short offset;
5730 /* The value to write might be 32 or 64 bits, depending on L1's long
5731 * mode, and eventually we need to write that into a field of several
5732 * possible lengths. The code below first zero-extends the value to 64
5733 * bit (field_value), and then copies only the approriate number of
5734 * bits into the vmcs12 field.
5736 u64 field_value = 0;
5737 struct x86_exception e;
5739 if (!nested_vmx_check_permission(vcpu) ||
5740 !nested_vmx_check_vmcs12(vcpu))
5741 return 1;
5743 if (vmx_instruction_info & (1u << 10))
5744 field_value = kvm_register_read(vcpu,
5745 (((vmx_instruction_info) >> 3) & 0xf));
5746 else {
5747 if (get_vmx_mem_address(vcpu, exit_qualification,
5748 vmx_instruction_info, &gva))
5749 return 1;
5750 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
5751 &field_value, (is_long_mode(vcpu) ? 8 : 4), &e)) {
5752 kvm_inject_page_fault(vcpu, &e);
5753 return 1;
5758 field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
5759 if (vmcs_field_readonly(field)) {
5760 nested_vmx_failValid(vcpu,
5761 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
5762 skip_emulated_instruction(vcpu);
5763 return 1;
5766 offset = vmcs_field_to_offset(field);
5767 if (offset < 0) {
5768 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5769 skip_emulated_instruction(vcpu);
5770 return 1;
5772 p = ((char *) get_vmcs12(vcpu)) + offset;
5774 switch (vmcs_field_type(field)) {
5775 case VMCS_FIELD_TYPE_U16:
5776 *(u16 *)p = field_value;
5777 break;
5778 case VMCS_FIELD_TYPE_U32:
5779 *(u32 *)p = field_value;
5780 break;
5781 case VMCS_FIELD_TYPE_U64:
5782 *(u64 *)p = field_value;
5783 break;
5784 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
5785 *(natural_width *)p = field_value;
5786 break;
5787 default:
5788 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5789 skip_emulated_instruction(vcpu);
5790 return 1;
5793 nested_vmx_succeed(vcpu);
5794 skip_emulated_instruction(vcpu);
5795 return 1;
5798 /* Emulate the VMPTRLD instruction */
5799 static int handle_vmptrld(struct kvm_vcpu *vcpu)
5801 struct vcpu_vmx *vmx = to_vmx(vcpu);
5802 gva_t gva;
5803 gpa_t vmptr;
5804 struct x86_exception e;
5806 if (!nested_vmx_check_permission(vcpu))
5807 return 1;
5809 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5810 vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
5811 return 1;
5813 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
5814 sizeof(vmptr), &e)) {
5815 kvm_inject_page_fault(vcpu, &e);
5816 return 1;
5819 if (!IS_ALIGNED(vmptr, PAGE_SIZE)) {
5820 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
5821 skip_emulated_instruction(vcpu);
5822 return 1;
5825 if (vmx->nested.current_vmptr != vmptr) {
5826 struct vmcs12 *new_vmcs12;
5827 struct page *page;
5828 page = nested_get_page(vcpu, vmptr);
5829 if (page == NULL) {
5830 nested_vmx_failInvalid(vcpu);
5831 skip_emulated_instruction(vcpu);
5832 return 1;
5834 new_vmcs12 = kmap(page);
5835 if (new_vmcs12->revision_id != VMCS12_REVISION) {
5836 kunmap(page);
5837 nested_release_page_clean(page);
5838 nested_vmx_failValid(vcpu,
5839 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5840 skip_emulated_instruction(vcpu);
5841 return 1;
5843 if (vmx->nested.current_vmptr != -1ull) {
5844 kunmap(vmx->nested.current_vmcs12_page);
5845 nested_release_page(vmx->nested.current_vmcs12_page);
5848 vmx->nested.current_vmptr = vmptr;
5849 vmx->nested.current_vmcs12 = new_vmcs12;
5850 vmx->nested.current_vmcs12_page = page;
5853 nested_vmx_succeed(vcpu);
5854 skip_emulated_instruction(vcpu);
5855 return 1;
5858 /* Emulate the VMPTRST instruction */
5859 static int handle_vmptrst(struct kvm_vcpu *vcpu)
5861 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5862 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5863 gva_t vmcs_gva;
5864 struct x86_exception e;
5866 if (!nested_vmx_check_permission(vcpu))
5867 return 1;
5869 if (get_vmx_mem_address(vcpu, exit_qualification,
5870 vmx_instruction_info, &vmcs_gva))
5871 return 1;
5872 /* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
5873 if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
5874 (void *)&to_vmx(vcpu)->nested.current_vmptr,
5875 sizeof(u64), &e)) {
5876 kvm_inject_page_fault(vcpu, &e);
5877 return 1;
5879 nested_vmx_succeed(vcpu);
5880 skip_emulated_instruction(vcpu);
5881 return 1;
5885 * The exit handlers return 1 if the exit was handled fully and guest execution
5886 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5887 * to be done to userspace and return 0.
5889 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5890 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
5891 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5892 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5893 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5894 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5895 [EXIT_REASON_CR_ACCESS] = handle_cr,
5896 [EXIT_REASON_DR_ACCESS] = handle_dr,
5897 [EXIT_REASON_CPUID] = handle_cpuid,
5898 [EXIT_REASON_MSR_READ] = handle_rdmsr,
5899 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
5900 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
5901 [EXIT_REASON_HLT] = handle_halt,
5902 [EXIT_REASON_INVD] = handle_invd,
5903 [EXIT_REASON_INVLPG] = handle_invlpg,
5904 [EXIT_REASON_RDPMC] = handle_rdpmc,
5905 [EXIT_REASON_VMCALL] = handle_vmcall,
5906 [EXIT_REASON_VMCLEAR] = handle_vmclear,
5907 [EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
5908 [EXIT_REASON_VMPTRLD] = handle_vmptrld,
5909 [EXIT_REASON_VMPTRST] = handle_vmptrst,
5910 [EXIT_REASON_VMREAD] = handle_vmread,
5911 [EXIT_REASON_VMRESUME] = handle_vmresume,
5912 [EXIT_REASON_VMWRITE] = handle_vmwrite,
5913 [EXIT_REASON_VMOFF] = handle_vmoff,
5914 [EXIT_REASON_VMON] = handle_vmon,
5915 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5916 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5917 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5918 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5919 [EXIT_REASON_WBINVD] = handle_wbinvd,
5920 [EXIT_REASON_XSETBV] = handle_xsetbv,
5921 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5922 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5923 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5924 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5925 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5926 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_invalid_op,
5927 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_invalid_op,
5930 static const int kvm_vmx_max_exit_handlers =
5931 ARRAY_SIZE(kvm_vmx_exit_handlers);
5933 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
5934 struct vmcs12 *vmcs12)
5936 unsigned long exit_qualification;
5937 gpa_t bitmap, last_bitmap;
5938 unsigned int port;
5939 int size;
5940 u8 b;
5942 if (nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING))
5943 return 1;
5945 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
5946 return 0;
5948 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5950 port = exit_qualification >> 16;
5951 size = (exit_qualification & 7) + 1;
5953 last_bitmap = (gpa_t)-1;
5954 b = -1;
5956 while (size > 0) {
5957 if (port < 0x8000)
5958 bitmap = vmcs12->io_bitmap_a;
5959 else if (port < 0x10000)
5960 bitmap = vmcs12->io_bitmap_b;
5961 else
5962 return 1;
5963 bitmap += (port & 0x7fff) / 8;
5965 if (last_bitmap != bitmap)
5966 if (kvm_read_guest(vcpu->kvm, bitmap, &b, 1))
5967 return 1;
5968 if (b & (1 << (port & 7)))
5969 return 1;
5971 port++;
5972 size--;
5973 last_bitmap = bitmap;
5976 return 0;
5980 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
5981 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
5982 * disinterest in the current event (read or write a specific MSR) by using an
5983 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
5985 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
5986 struct vmcs12 *vmcs12, u32 exit_reason)
5988 u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
5989 gpa_t bitmap;
5991 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
5992 return 1;
5995 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
5996 * for the four combinations of read/write and low/high MSR numbers.
5997 * First we need to figure out which of the four to use:
5999 bitmap = vmcs12->msr_bitmap;
6000 if (exit_reason == EXIT_REASON_MSR_WRITE)
6001 bitmap += 2048;
6002 if (msr_index >= 0xc0000000) {
6003 msr_index -= 0xc0000000;
6004 bitmap += 1024;
6007 /* Then read the msr_index'th bit from this bitmap: */
6008 if (msr_index < 1024*8) {
6009 unsigned char b;
6010 if (kvm_read_guest(vcpu->kvm, bitmap + msr_index/8, &b, 1))
6011 return 1;
6012 return 1 & (b >> (msr_index & 7));
6013 } else
6014 return 1; /* let L1 handle the wrong parameter */
6018 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
6019 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
6020 * intercept (via guest_host_mask etc.) the current event.
6022 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
6023 struct vmcs12 *vmcs12)
6025 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6026 int cr = exit_qualification & 15;
6027 int reg = (exit_qualification >> 8) & 15;
6028 unsigned long val = kvm_register_read(vcpu, reg);
6030 switch ((exit_qualification >> 4) & 3) {
6031 case 0: /* mov to cr */
6032 switch (cr) {
6033 case 0:
6034 if (vmcs12->cr0_guest_host_mask &
6035 (val ^ vmcs12->cr0_read_shadow))
6036 return 1;
6037 break;
6038 case 3:
6039 if ((vmcs12->cr3_target_count >= 1 &&
6040 vmcs12->cr3_target_value0 == val) ||
6041 (vmcs12->cr3_target_count >= 2 &&
6042 vmcs12->cr3_target_value1 == val) ||
6043 (vmcs12->cr3_target_count >= 3 &&
6044 vmcs12->cr3_target_value2 == val) ||
6045 (vmcs12->cr3_target_count >= 4 &&
6046 vmcs12->cr3_target_value3 == val))
6047 return 0;
6048 if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
6049 return 1;
6050 break;
6051 case 4:
6052 if (vmcs12->cr4_guest_host_mask &
6053 (vmcs12->cr4_read_shadow ^ val))
6054 return 1;
6055 break;
6056 case 8:
6057 if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
6058 return 1;
6059 break;
6061 break;
6062 case 2: /* clts */
6063 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
6064 (vmcs12->cr0_read_shadow & X86_CR0_TS))
6065 return 1;
6066 break;
6067 case 1: /* mov from cr */
6068 switch (cr) {
6069 case 3:
6070 if (vmcs12->cpu_based_vm_exec_control &
6071 CPU_BASED_CR3_STORE_EXITING)
6072 return 1;
6073 break;
6074 case 8:
6075 if (vmcs12->cpu_based_vm_exec_control &
6076 CPU_BASED_CR8_STORE_EXITING)
6077 return 1;
6078 break;
6080 break;
6081 case 3: /* lmsw */
6083 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
6084 * cr0. Other attempted changes are ignored, with no exit.
6086 if (vmcs12->cr0_guest_host_mask & 0xe &
6087 (val ^ vmcs12->cr0_read_shadow))
6088 return 1;
6089 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
6090 !(vmcs12->cr0_read_shadow & 0x1) &&
6091 (val & 0x1))
6092 return 1;
6093 break;
6095 return 0;
6099 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
6100 * should handle it ourselves in L0 (and then continue L2). Only call this
6101 * when in is_guest_mode (L2).
6103 static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
6105 u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6106 struct vcpu_vmx *vmx = to_vmx(vcpu);
6107 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6108 u32 exit_reason = vmx->exit_reason;
6110 if (vmx->nested.nested_run_pending)
6111 return 0;
6113 if (unlikely(vmx->fail)) {
6114 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
6115 vmcs_read32(VM_INSTRUCTION_ERROR));
6116 return 1;
6119 switch (exit_reason) {
6120 case EXIT_REASON_EXCEPTION_NMI:
6121 if (!is_exception(intr_info))
6122 return 0;
6123 else if (is_page_fault(intr_info))
6124 return enable_ept;
6125 return vmcs12->exception_bitmap &
6126 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
6127 case EXIT_REASON_EXTERNAL_INTERRUPT:
6128 return 0;
6129 case EXIT_REASON_TRIPLE_FAULT:
6130 return 1;
6131 case EXIT_REASON_PENDING_INTERRUPT:
6132 case EXIT_REASON_NMI_WINDOW:
6134 * prepare_vmcs02() set the CPU_BASED_VIRTUAL_INTR_PENDING bit
6135 * (aka Interrupt Window Exiting) only when L1 turned it on,
6136 * so if we got a PENDING_INTERRUPT exit, this must be for L1.
6137 * Same for NMI Window Exiting.
6139 return 1;
6140 case EXIT_REASON_TASK_SWITCH:
6141 return 1;
6142 case EXIT_REASON_CPUID:
6143 return 1;
6144 case EXIT_REASON_HLT:
6145 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
6146 case EXIT_REASON_INVD:
6147 return 1;
6148 case EXIT_REASON_INVLPG:
6149 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
6150 case EXIT_REASON_RDPMC:
6151 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
6152 case EXIT_REASON_RDTSC:
6153 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
6154 case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
6155 case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
6156 case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
6157 case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
6158 case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
6160 * VMX instructions trap unconditionally. This allows L1 to
6161 * emulate them for its L2 guest, i.e., allows 3-level nesting!
6163 return 1;
6164 case EXIT_REASON_CR_ACCESS:
6165 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
6166 case EXIT_REASON_DR_ACCESS:
6167 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
6168 case EXIT_REASON_IO_INSTRUCTION:
6169 return nested_vmx_exit_handled_io(vcpu, vmcs12);
6170 case EXIT_REASON_MSR_READ:
6171 case EXIT_REASON_MSR_WRITE:
6172 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
6173 case EXIT_REASON_INVALID_STATE:
6174 return 1;
6175 case EXIT_REASON_MWAIT_INSTRUCTION:
6176 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
6177 case EXIT_REASON_MONITOR_INSTRUCTION:
6178 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
6179 case EXIT_REASON_PAUSE_INSTRUCTION:
6180 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
6181 nested_cpu_has2(vmcs12,
6182 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
6183 case EXIT_REASON_MCE_DURING_VMENTRY:
6184 return 0;
6185 case EXIT_REASON_TPR_BELOW_THRESHOLD:
6186 return 1;
6187 case EXIT_REASON_APIC_ACCESS:
6188 return nested_cpu_has2(vmcs12,
6189 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
6190 case EXIT_REASON_EPT_VIOLATION:
6191 case EXIT_REASON_EPT_MISCONFIG:
6192 return 0;
6193 case EXIT_REASON_WBINVD:
6194 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
6195 case EXIT_REASON_XSETBV:
6196 return 1;
6197 default:
6198 return 1;
6202 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
6204 *info1 = vmcs_readl(EXIT_QUALIFICATION);
6205 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
6209 * The guest has exited. See if we can fix it or if we need userspace
6210 * assistance.
6212 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
6214 struct vcpu_vmx *vmx = to_vmx(vcpu);
6215 u32 exit_reason = vmx->exit_reason;
6216 u32 vectoring_info = vmx->idt_vectoring_info;
6218 /* If guest state is invalid, start emulating */
6219 if (vmx->emulation_required)
6220 return handle_invalid_guest_state(vcpu);
6223 * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
6224 * we did not inject a still-pending event to L1 now because of
6225 * nested_run_pending, we need to re-enable this bit.
6227 if (vmx->nested.nested_run_pending)
6228 kvm_make_request(KVM_REQ_EVENT, vcpu);
6230 if (!is_guest_mode(vcpu) && (exit_reason == EXIT_REASON_VMLAUNCH ||
6231 exit_reason == EXIT_REASON_VMRESUME))
6232 vmx->nested.nested_run_pending = 1;
6233 else
6234 vmx->nested.nested_run_pending = 0;
6236 if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
6237 nested_vmx_vmexit(vcpu);
6238 return 1;
6241 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
6242 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6243 vcpu->run->fail_entry.hardware_entry_failure_reason
6244 = exit_reason;
6245 return 0;
6248 if (unlikely(vmx->fail)) {
6249 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6250 vcpu->run->fail_entry.hardware_entry_failure_reason
6251 = vmcs_read32(VM_INSTRUCTION_ERROR);
6252 return 0;
6256 * Note:
6257 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6258 * delivery event since it indicates guest is accessing MMIO.
6259 * The vm-exit can be triggered again after return to guest that
6260 * will cause infinite loop.
6262 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6263 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
6264 exit_reason != EXIT_REASON_EPT_VIOLATION &&
6265 exit_reason != EXIT_REASON_TASK_SWITCH)) {
6266 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6267 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6268 vcpu->run->internal.ndata = 2;
6269 vcpu->run->internal.data[0] = vectoring_info;
6270 vcpu->run->internal.data[1] = exit_reason;
6271 return 0;
6274 if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
6275 !(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
6276 get_vmcs12(vcpu), vcpu)))) {
6277 if (vmx_interrupt_allowed(vcpu)) {
6278 vmx->soft_vnmi_blocked = 0;
6279 } else if (vmx->vnmi_blocked_time > 1000000000LL &&
6280 vcpu->arch.nmi_pending) {
6282 * This CPU don't support us in finding the end of an
6283 * NMI-blocked window if the guest runs with IRQs
6284 * disabled. So we pull the trigger after 1 s of
6285 * futile waiting, but inform the user about this.
6287 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6288 "state on VCPU %d after 1 s timeout\n",
6289 __func__, vcpu->vcpu_id);
6290 vmx->soft_vnmi_blocked = 0;
6294 if (exit_reason < kvm_vmx_max_exit_handlers
6295 && kvm_vmx_exit_handlers[exit_reason])
6296 return kvm_vmx_exit_handlers[exit_reason](vcpu);
6297 else {
6298 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6299 vcpu->run->hw.hardware_exit_reason = exit_reason;
6301 return 0;
6304 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6306 if (irr == -1 || tpr < irr) {
6307 vmcs_write32(TPR_THRESHOLD, 0);
6308 return;
6311 vmcs_write32(TPR_THRESHOLD, irr);
6314 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
6316 u32 sec_exec_control;
6319 * There is not point to enable virtualize x2apic without enable
6320 * apicv
6322 if (!cpu_has_vmx_virtualize_x2apic_mode() ||
6323 !vmx_vm_has_apicv(vcpu->kvm))
6324 return;
6326 if (!vm_need_tpr_shadow(vcpu->kvm))
6327 return;
6329 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6331 if (set) {
6332 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6333 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6334 } else {
6335 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6336 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6338 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
6340 vmx_set_msr_bitmap(vcpu);
6343 static void vmx_hwapic_isr_update(struct kvm *kvm, int isr)
6345 u16 status;
6346 u8 old;
6348 if (!vmx_vm_has_apicv(kvm))
6349 return;
6351 if (isr == -1)
6352 isr = 0;
6354 status = vmcs_read16(GUEST_INTR_STATUS);
6355 old = status >> 8;
6356 if (isr != old) {
6357 status &= 0xff;
6358 status |= isr << 8;
6359 vmcs_write16(GUEST_INTR_STATUS, status);
6363 static void vmx_set_rvi(int vector)
6365 u16 status;
6366 u8 old;
6368 status = vmcs_read16(GUEST_INTR_STATUS);
6369 old = (u8)status & 0xff;
6370 if ((u8)vector != old) {
6371 status &= ~0xff;
6372 status |= (u8)vector;
6373 vmcs_write16(GUEST_INTR_STATUS, status);
6377 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6379 if (max_irr == -1)
6380 return;
6382 vmx_set_rvi(max_irr);
6385 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6387 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6388 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6389 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6390 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6393 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
6395 u32 exit_intr_info;
6397 if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
6398 || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
6399 return;
6401 vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6402 exit_intr_info = vmx->exit_intr_info;
6404 /* Handle machine checks before interrupts are enabled */
6405 if (is_machine_check(exit_intr_info))
6406 kvm_machine_check();
6408 /* We need to handle NMIs before interrupts are enabled */
6409 if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
6410 (exit_intr_info & INTR_INFO_VALID_MASK)) {
6411 kvm_before_handle_nmi(&vmx->vcpu);
6412 asm("int $2");
6413 kvm_after_handle_nmi(&vmx->vcpu);
6417 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6419 u32 exit_intr_info;
6420 bool unblock_nmi;
6421 u8 vector;
6422 bool idtv_info_valid;
6424 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6426 if (cpu_has_virtual_nmis()) {
6427 if (vmx->nmi_known_unmasked)
6428 return;
6430 * Can't use vmx->exit_intr_info since we're not sure what
6431 * the exit reason is.
6433 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6434 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6435 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6437 * SDM 3: 27.7.1.2 (September 2008)
6438 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6439 * a guest IRET fault.
6440 * SDM 3: 23.2.2 (September 2008)
6441 * Bit 12 is undefined in any of the following cases:
6442 * If the VM exit sets the valid bit in the IDT-vectoring
6443 * information field.
6444 * If the VM exit is due to a double fault.
6446 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6447 vector != DF_VECTOR && !idtv_info_valid)
6448 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6449 GUEST_INTR_STATE_NMI);
6450 else
6451 vmx->nmi_known_unmasked =
6452 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6453 & GUEST_INTR_STATE_NMI);
6454 } else if (unlikely(vmx->soft_vnmi_blocked))
6455 vmx->vnmi_blocked_time +=
6456 ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
6459 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6460 u32 idt_vectoring_info,
6461 int instr_len_field,
6462 int error_code_field)
6464 u8 vector;
6465 int type;
6466 bool idtv_info_valid;
6468 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6470 vcpu->arch.nmi_injected = false;
6471 kvm_clear_exception_queue(vcpu);
6472 kvm_clear_interrupt_queue(vcpu);
6474 if (!idtv_info_valid)
6475 return;
6477 kvm_make_request(KVM_REQ_EVENT, vcpu);
6479 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6480 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6482 switch (type) {
6483 case INTR_TYPE_NMI_INTR:
6484 vcpu->arch.nmi_injected = true;
6486 * SDM 3: 27.7.1.2 (September 2008)
6487 * Clear bit "block by NMI" before VM entry if a NMI
6488 * delivery faulted.
6490 vmx_set_nmi_mask(vcpu, false);
6491 break;
6492 case INTR_TYPE_SOFT_EXCEPTION:
6493 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6494 /* fall through */
6495 case INTR_TYPE_HARD_EXCEPTION:
6496 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6497 u32 err = vmcs_read32(error_code_field);
6498 kvm_queue_exception_e(vcpu, vector, err);
6499 } else
6500 kvm_queue_exception(vcpu, vector);
6501 break;
6502 case INTR_TYPE_SOFT_INTR:
6503 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6504 /* fall through */
6505 case INTR_TYPE_EXT_INTR:
6506 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6507 break;
6508 default:
6509 break;
6513 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6515 if (is_guest_mode(&vmx->vcpu))
6516 return;
6517 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6518 VM_EXIT_INSTRUCTION_LEN,
6519 IDT_VECTORING_ERROR_CODE);
6522 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6524 if (is_guest_mode(vcpu))
6525 return;
6526 __vmx_complete_interrupts(vcpu,
6527 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6528 VM_ENTRY_INSTRUCTION_LEN,
6529 VM_ENTRY_EXCEPTION_ERROR_CODE);
6531 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6534 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6536 int i, nr_msrs;
6537 struct perf_guest_switch_msr *msrs;
6539 msrs = perf_guest_get_msrs(&nr_msrs);
6541 if (!msrs)
6542 return;
6544 for (i = 0; i < nr_msrs; i++)
6545 if (msrs[i].host == msrs[i].guest)
6546 clear_atomic_switch_msr(vmx, msrs[i].msr);
6547 else
6548 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6549 msrs[i].host);
6552 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
6554 struct vcpu_vmx *vmx = to_vmx(vcpu);
6555 unsigned long debugctlmsr;
6557 if (is_guest_mode(vcpu) && !vmx->nested.nested_run_pending) {
6558 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6559 if (vmcs12->idt_vectoring_info_field &
6560 VECTORING_INFO_VALID_MASK) {
6561 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6562 vmcs12->idt_vectoring_info_field);
6563 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6564 vmcs12->vm_exit_instruction_len);
6565 if (vmcs12->idt_vectoring_info_field &
6566 VECTORING_INFO_DELIVER_CODE_MASK)
6567 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
6568 vmcs12->idt_vectoring_error_code);
6572 /* Record the guest's net vcpu time for enforced NMI injections. */
6573 if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
6574 vmx->entry_time = ktime_get();
6576 /* Don't enter VMX if guest state is invalid, let the exit handler
6577 start emulation until we arrive back to a valid state */
6578 if (vmx->emulation_required)
6579 return;
6581 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
6582 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6583 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
6584 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6586 /* When single-stepping over STI and MOV SS, we must clear the
6587 * corresponding interruptibility bits in the guest state. Otherwise
6588 * vmentry fails as it then expects bit 14 (BS) in pending debug
6589 * exceptions being set, but that's not correct for the guest debugging
6590 * case. */
6591 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6592 vmx_set_interrupt_shadow(vcpu, 0);
6594 atomic_switch_perf_msrs(vmx);
6595 debugctlmsr = get_debugctlmsr();
6597 vmx->__launched = vmx->loaded_vmcs->launched;
6598 asm(
6599 /* Store host registers */
6600 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
6601 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
6602 "push %%" _ASM_CX " \n\t"
6603 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
6604 "je 1f \n\t"
6605 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
6606 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
6607 "1: \n\t"
6608 /* Reload cr2 if changed */
6609 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
6610 "mov %%cr2, %%" _ASM_DX " \n\t"
6611 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
6612 "je 2f \n\t"
6613 "mov %%" _ASM_AX", %%cr2 \n\t"
6614 "2: \n\t"
6615 /* Check if vmlaunch of vmresume is needed */
6616 "cmpl $0, %c[launched](%0) \n\t"
6617 /* Load guest registers. Don't clobber flags. */
6618 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
6619 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
6620 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
6621 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
6622 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
6623 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
6624 #ifdef CONFIG_X86_64
6625 "mov %c[r8](%0), %%r8 \n\t"
6626 "mov %c[r9](%0), %%r9 \n\t"
6627 "mov %c[r10](%0), %%r10 \n\t"
6628 "mov %c[r11](%0), %%r11 \n\t"
6629 "mov %c[r12](%0), %%r12 \n\t"
6630 "mov %c[r13](%0), %%r13 \n\t"
6631 "mov %c[r14](%0), %%r14 \n\t"
6632 "mov %c[r15](%0), %%r15 \n\t"
6633 #endif
6634 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
6636 /* Enter guest mode */
6637 "jne 1f \n\t"
6638 __ex(ASM_VMX_VMLAUNCH) "\n\t"
6639 "jmp 2f \n\t"
6640 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
6641 "2: "
6642 /* Save guest registers, load host registers, keep flags */
6643 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
6644 "pop %0 \n\t"
6645 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
6646 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
6647 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
6648 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
6649 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
6650 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
6651 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
6652 #ifdef CONFIG_X86_64
6653 "mov %%r8, %c[r8](%0) \n\t"
6654 "mov %%r9, %c[r9](%0) \n\t"
6655 "mov %%r10, %c[r10](%0) \n\t"
6656 "mov %%r11, %c[r11](%0) \n\t"
6657 "mov %%r12, %c[r12](%0) \n\t"
6658 "mov %%r13, %c[r13](%0) \n\t"
6659 "mov %%r14, %c[r14](%0) \n\t"
6660 "mov %%r15, %c[r15](%0) \n\t"
6661 #endif
6662 "mov %%cr2, %%" _ASM_AX " \n\t"
6663 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
6665 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
6666 "setbe %c[fail](%0) \n\t"
6667 ".pushsection .rodata \n\t"
6668 ".global vmx_return \n\t"
6669 "vmx_return: " _ASM_PTR " 2b \n\t"
6670 ".popsection"
6671 : : "c"(vmx), "d"((unsigned long)HOST_RSP),
6672 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
6673 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
6674 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
6675 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
6676 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
6677 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
6678 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
6679 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
6680 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
6681 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
6682 #ifdef CONFIG_X86_64
6683 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
6684 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
6685 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
6686 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
6687 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
6688 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
6689 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
6690 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
6691 #endif
6692 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
6693 [wordsize]"i"(sizeof(ulong))
6694 : "cc", "memory"
6695 #ifdef CONFIG_X86_64
6696 , "rax", "rbx", "rdi", "rsi"
6697 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
6698 #else
6699 , "eax", "ebx", "edi", "esi"
6700 #endif
6703 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6704 if (debugctlmsr)
6705 update_debugctlmsr(debugctlmsr);
6707 #ifndef CONFIG_X86_64
6709 * The sysexit path does not restore ds/es, so we must set them to
6710 * a reasonable value ourselves.
6712 * We can't defer this to vmx_load_host_state() since that function
6713 * may be executed in interrupt context, which saves and restore segments
6714 * around it, nullifying its effect.
6716 loadsegment(ds, __USER_DS);
6717 loadsegment(es, __USER_DS);
6718 #endif
6720 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
6721 | (1 << VCPU_EXREG_RFLAGS)
6722 | (1 << VCPU_EXREG_CPL)
6723 | (1 << VCPU_EXREG_PDPTR)
6724 | (1 << VCPU_EXREG_SEGMENTS)
6725 | (1 << VCPU_EXREG_CR3));
6726 vcpu->arch.regs_dirty = 0;
6728 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6730 if (is_guest_mode(vcpu)) {
6731 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6732 vmcs12->idt_vectoring_info_field = vmx->idt_vectoring_info;
6733 if (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK) {
6734 vmcs12->idt_vectoring_error_code =
6735 vmcs_read32(IDT_VECTORING_ERROR_CODE);
6736 vmcs12->vm_exit_instruction_len =
6737 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6741 vmx->loaded_vmcs->launched = 1;
6743 vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
6744 trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
6746 vmx_complete_atomic_exit(vmx);
6747 vmx_recover_nmi_blocking(vmx);
6748 vmx_complete_interrupts(vmx);
6751 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6753 struct vcpu_vmx *vmx = to_vmx(vcpu);
6755 free_vpid(vmx);
6756 free_nested(vmx);
6757 free_loaded_vmcs(vmx->loaded_vmcs);
6758 kfree(vmx->guest_msrs);
6759 kvm_vcpu_uninit(vcpu);
6760 kmem_cache_free(kvm_vcpu_cache, vmx);
6763 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
6765 int err;
6766 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
6767 int cpu;
6769 if (!vmx)
6770 return ERR_PTR(-ENOMEM);
6772 allocate_vpid(vmx);
6774 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
6775 if (err)
6776 goto free_vcpu;
6778 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
6779 err = -ENOMEM;
6780 if (!vmx->guest_msrs) {
6781 goto uninit_vcpu;
6784 vmx->loaded_vmcs = &vmx->vmcs01;
6785 vmx->loaded_vmcs->vmcs = alloc_vmcs();
6786 if (!vmx->loaded_vmcs->vmcs)
6787 goto free_msrs;
6788 if (!vmm_exclusive)
6789 kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
6790 loaded_vmcs_init(vmx->loaded_vmcs);
6791 if (!vmm_exclusive)
6792 kvm_cpu_vmxoff();
6794 cpu = get_cpu();
6795 vmx_vcpu_load(&vmx->vcpu, cpu);
6796 vmx->vcpu.cpu = cpu;
6797 err = vmx_vcpu_setup(vmx);
6798 vmx_vcpu_put(&vmx->vcpu);
6799 put_cpu();
6800 if (err)
6801 goto free_vmcs;
6802 if (vm_need_virtualize_apic_accesses(kvm))
6803 err = alloc_apic_access_page(kvm);
6804 if (err)
6805 goto free_vmcs;
6807 if (enable_ept) {
6808 if (!kvm->arch.ept_identity_map_addr)
6809 kvm->arch.ept_identity_map_addr =
6810 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
6811 err = -ENOMEM;
6812 if (alloc_identity_pagetable(kvm) != 0)
6813 goto free_vmcs;
6814 if (!init_rmode_identity_map(kvm))
6815 goto free_vmcs;
6818 vmx->nested.current_vmptr = -1ull;
6819 vmx->nested.current_vmcs12 = NULL;
6821 return &vmx->vcpu;
6823 free_vmcs:
6824 free_loaded_vmcs(vmx->loaded_vmcs);
6825 free_msrs:
6826 kfree(vmx->guest_msrs);
6827 uninit_vcpu:
6828 kvm_vcpu_uninit(&vmx->vcpu);
6829 free_vcpu:
6830 free_vpid(vmx);
6831 kmem_cache_free(kvm_vcpu_cache, vmx);
6832 return ERR_PTR(err);
6835 static void __init vmx_check_processor_compat(void *rtn)
6837 struct vmcs_config vmcs_conf;
6839 *(int *)rtn = 0;
6840 if (setup_vmcs_config(&vmcs_conf) < 0)
6841 *(int *)rtn = -EIO;
6842 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6843 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6844 smp_processor_id());
6845 *(int *)rtn = -EIO;
6849 static int get_ept_level(void)
6851 return VMX_EPT_DEFAULT_GAW + 1;
6854 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6856 u64 ret;
6858 /* For VT-d and EPT combination
6859 * 1. MMIO: always map as UC
6860 * 2. EPT with VT-d:
6861 * a. VT-d without snooping control feature: can't guarantee the
6862 * result, try to trust guest.
6863 * b. VT-d with snooping control feature: snooping control feature of
6864 * VT-d engine can guarantee the cache correctness. Just set it
6865 * to WB to keep consistent with host. So the same as item 3.
6866 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
6867 * consistent with host MTRR
6869 if (is_mmio)
6870 ret = MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
6871 else if (vcpu->kvm->arch.iommu_domain &&
6872 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY))
6873 ret = kvm_get_guest_memory_type(vcpu, gfn) <<
6874 VMX_EPT_MT_EPTE_SHIFT;
6875 else
6876 ret = (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT)
6877 | VMX_EPT_IPAT_BIT;
6879 return ret;
6882 static int vmx_get_lpage_level(void)
6884 if (enable_ept && !cpu_has_vmx_ept_1g_page())
6885 return PT_DIRECTORY_LEVEL;
6886 else
6887 /* For shadow and EPT supported 1GB page */
6888 return PT_PDPE_LEVEL;
6891 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
6893 struct kvm_cpuid_entry2 *best;
6894 struct vcpu_vmx *vmx = to_vmx(vcpu);
6895 u32 exec_control;
6897 vmx->rdtscp_enabled = false;
6898 if (vmx_rdtscp_supported()) {
6899 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6900 if (exec_control & SECONDARY_EXEC_RDTSCP) {
6901 best = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
6902 if (best && (best->edx & bit(X86_FEATURE_RDTSCP)))
6903 vmx->rdtscp_enabled = true;
6904 else {
6905 exec_control &= ~SECONDARY_EXEC_RDTSCP;
6906 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6907 exec_control);
6912 /* Exposing INVPCID only when PCID is exposed */
6913 best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
6914 if (vmx_invpcid_supported() &&
6915 best && (best->ebx & bit(X86_FEATURE_INVPCID)) &&
6916 guest_cpuid_has_pcid(vcpu)) {
6917 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6918 exec_control |= SECONDARY_EXEC_ENABLE_INVPCID;
6919 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6920 exec_control);
6921 } else {
6922 if (cpu_has_secondary_exec_ctrls()) {
6923 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6924 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
6925 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6926 exec_control);
6928 if (best)
6929 best->ebx &= ~bit(X86_FEATURE_INVPCID);
6933 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
6935 if (func == 1 && nested)
6936 entry->ecx |= bit(X86_FEATURE_VMX);
6940 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
6941 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
6942 * with L0's requirements for its guest (a.k.a. vmsc01), so we can run the L2
6943 * guest in a way that will both be appropriate to L1's requests, and our
6944 * needs. In addition to modifying the active vmcs (which is vmcs02), this
6945 * function also has additional necessary side-effects, like setting various
6946 * vcpu->arch fields.
6948 static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
6950 struct vcpu_vmx *vmx = to_vmx(vcpu);
6951 u32 exec_control;
6953 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
6954 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
6955 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
6956 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
6957 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
6958 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
6959 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
6960 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
6961 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
6962 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
6963 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
6964 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
6965 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
6966 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
6967 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
6968 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
6969 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
6970 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
6971 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
6972 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
6973 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
6974 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
6975 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
6976 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
6977 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
6978 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
6979 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
6980 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
6981 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
6982 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
6983 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
6984 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
6985 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
6986 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
6987 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
6988 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
6990 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
6991 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6992 vmcs12->vm_entry_intr_info_field);
6993 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
6994 vmcs12->vm_entry_exception_error_code);
6995 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6996 vmcs12->vm_entry_instruction_len);
6997 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
6998 vmcs12->guest_interruptibility_info);
6999 vmcs_write32(GUEST_ACTIVITY_STATE, vmcs12->guest_activity_state);
7000 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
7001 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
7002 vmcs_writel(GUEST_RFLAGS, vmcs12->guest_rflags);
7003 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
7004 vmcs12->guest_pending_dbg_exceptions);
7005 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
7006 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
7008 vmcs_write64(VMCS_LINK_POINTER, -1ull);
7010 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
7011 (vmcs_config.pin_based_exec_ctrl |
7012 vmcs12->pin_based_vm_exec_control));
7015 * Whether page-faults are trapped is determined by a combination of
7016 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
7017 * If enable_ept, L0 doesn't care about page faults and we should
7018 * set all of these to L1's desires. However, if !enable_ept, L0 does
7019 * care about (at least some) page faults, and because it is not easy
7020 * (if at all possible?) to merge L0 and L1's desires, we simply ask
7021 * to exit on each and every L2 page fault. This is done by setting
7022 * MASK=MATCH=0 and (see below) EB.PF=1.
7023 * Note that below we don't need special code to set EB.PF beyond the
7024 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
7025 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
7026 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
7028 * A problem with this approach (when !enable_ept) is that L1 may be
7029 * injected with more page faults than it asked for. This could have
7030 * caused problems, but in practice existing hypervisors don't care.
7031 * To fix this, we will need to emulate the PFEC checking (on the L1
7032 * page tables), using walk_addr(), when injecting PFs to L1.
7034 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
7035 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
7036 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
7037 enable_ept ? vmcs12->page_fault_error_code_match : 0);
7039 if (cpu_has_secondary_exec_ctrls()) {
7040 u32 exec_control = vmx_secondary_exec_control(vmx);
7041 if (!vmx->rdtscp_enabled)
7042 exec_control &= ~SECONDARY_EXEC_RDTSCP;
7043 /* Take the following fields only from vmcs12 */
7044 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7045 if (nested_cpu_has(vmcs12,
7046 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
7047 exec_control |= vmcs12->secondary_vm_exec_control;
7049 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
7051 * Translate L1 physical address to host physical
7052 * address for vmcs02. Keep the page pinned, so this
7053 * physical address remains valid. We keep a reference
7054 * to it so we can release it later.
7056 if (vmx->nested.apic_access_page) /* shouldn't happen */
7057 nested_release_page(vmx->nested.apic_access_page);
7058 vmx->nested.apic_access_page =
7059 nested_get_page(vcpu, vmcs12->apic_access_addr);
7061 * If translation failed, no matter: This feature asks
7062 * to exit when accessing the given address, and if it
7063 * can never be accessed, this feature won't do
7064 * anything anyway.
7066 if (!vmx->nested.apic_access_page)
7067 exec_control &=
7068 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7069 else
7070 vmcs_write64(APIC_ACCESS_ADDR,
7071 page_to_phys(vmx->nested.apic_access_page));
7074 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
7079 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
7080 * Some constant fields are set here by vmx_set_constant_host_state().
7081 * Other fields are different per CPU, and will be set later when
7082 * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
7084 vmx_set_constant_host_state();
7087 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
7088 * entry, but only if the current (host) sp changed from the value
7089 * we wrote last (vmx->host_rsp). This cache is no longer relevant
7090 * if we switch vmcs, and rather than hold a separate cache per vmcs,
7091 * here we just force the write to happen on entry.
7093 vmx->host_rsp = 0;
7095 exec_control = vmx_exec_control(vmx); /* L0's desires */
7096 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
7097 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
7098 exec_control &= ~CPU_BASED_TPR_SHADOW;
7099 exec_control |= vmcs12->cpu_based_vm_exec_control;
7101 * Merging of IO and MSR bitmaps not currently supported.
7102 * Rather, exit every time.
7104 exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
7105 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
7106 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
7108 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
7110 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
7111 * bitwise-or of what L1 wants to trap for L2, and what we want to
7112 * trap. Note that CR0.TS also needs updating - we do this later.
7114 update_exception_bitmap(vcpu);
7115 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
7116 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
7118 /* Note: IA32_MODE, LOAD_IA32_EFER are modified by vmx_set_efer below */
7119 vmcs_write32(VM_EXIT_CONTROLS,
7120 vmcs12->vm_exit_controls | vmcs_config.vmexit_ctrl);
7121 vmcs_write32(VM_ENTRY_CONTROLS, vmcs12->vm_entry_controls |
7122 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
7124 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)
7125 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
7126 else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
7127 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
7130 set_cr4_guest_host_mask(vmx);
7132 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
7133 vmcs_write64(TSC_OFFSET,
7134 vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset);
7135 else
7136 vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
7138 if (enable_vpid) {
7140 * Trivially support vpid by letting L2s share their parent
7141 * L1's vpid. TODO: move to a more elaborate solution, giving
7142 * each L2 its own vpid and exposing the vpid feature to L1.
7144 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
7145 vmx_flush_tlb(vcpu);
7148 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
7149 vcpu->arch.efer = vmcs12->guest_ia32_efer;
7150 if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
7151 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
7152 else
7153 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
7154 /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
7155 vmx_set_efer(vcpu, vcpu->arch.efer);
7158 * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
7159 * TS bit (for lazy fpu) and bits which we consider mandatory enabled.
7160 * The CR0_READ_SHADOW is what L2 should have expected to read given
7161 * the specifications by L1; It's not enough to take
7162 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
7163 * have more bits than L1 expected.
7165 vmx_set_cr0(vcpu, vmcs12->guest_cr0);
7166 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
7168 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
7169 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
7171 /* shadow page tables on either EPT or shadow page tables */
7172 kvm_set_cr3(vcpu, vmcs12->guest_cr3);
7173 kvm_mmu_reset_context(vcpu);
7175 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
7176 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
7180 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
7181 * for running an L2 nested guest.
7183 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
7185 struct vmcs12 *vmcs12;
7186 struct vcpu_vmx *vmx = to_vmx(vcpu);
7187 int cpu;
7188 struct loaded_vmcs *vmcs02;
7190 if (!nested_vmx_check_permission(vcpu) ||
7191 !nested_vmx_check_vmcs12(vcpu))
7192 return 1;
7194 skip_emulated_instruction(vcpu);
7195 vmcs12 = get_vmcs12(vcpu);
7198 * The nested entry process starts with enforcing various prerequisites
7199 * on vmcs12 as required by the Intel SDM, and act appropriately when
7200 * they fail: As the SDM explains, some conditions should cause the
7201 * instruction to fail, while others will cause the instruction to seem
7202 * to succeed, but return an EXIT_REASON_INVALID_STATE.
7203 * To speed up the normal (success) code path, we should avoid checking
7204 * for misconfigurations which will anyway be caught by the processor
7205 * when using the merged vmcs02.
7207 if (vmcs12->launch_state == launch) {
7208 nested_vmx_failValid(vcpu,
7209 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
7210 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
7211 return 1;
7214 if ((vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_MSR_BITMAPS) &&
7215 !IS_ALIGNED(vmcs12->msr_bitmap, PAGE_SIZE)) {
7216 /*TODO: Also verify bits beyond physical address width are 0*/
7217 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7218 return 1;
7221 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
7222 !IS_ALIGNED(vmcs12->apic_access_addr, PAGE_SIZE)) {
7223 /*TODO: Also verify bits beyond physical address width are 0*/
7224 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7225 return 1;
7228 if (vmcs12->vm_entry_msr_load_count > 0 ||
7229 vmcs12->vm_exit_msr_load_count > 0 ||
7230 vmcs12->vm_exit_msr_store_count > 0) {
7231 pr_warn_ratelimited("%s: VMCS MSR_{LOAD,STORE} unsupported\n",
7232 __func__);
7233 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7234 return 1;
7237 if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
7238 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high) ||
7239 !vmx_control_verify(vmcs12->secondary_vm_exec_control,
7240 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high) ||
7241 !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
7242 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high) ||
7243 !vmx_control_verify(vmcs12->vm_exit_controls,
7244 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high) ||
7245 !vmx_control_verify(vmcs12->vm_entry_controls,
7246 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high))
7248 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7249 return 1;
7252 if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
7253 ((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
7254 nested_vmx_failValid(vcpu,
7255 VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7256 return 1;
7259 if (((vmcs12->guest_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
7260 ((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
7261 nested_vmx_entry_failure(vcpu, vmcs12,
7262 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
7263 return 1;
7265 if (vmcs12->vmcs_link_pointer != -1ull) {
7266 nested_vmx_entry_failure(vcpu, vmcs12,
7267 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
7268 return 1;
7272 * We're finally done with prerequisite checking, and can start with
7273 * the nested entry.
7276 vmcs02 = nested_get_current_vmcs02(vmx);
7277 if (!vmcs02)
7278 return -ENOMEM;
7280 enter_guest_mode(vcpu);
7282 vmx->nested.vmcs01_tsc_offset = vmcs_read64(TSC_OFFSET);
7284 cpu = get_cpu();
7285 vmx->loaded_vmcs = vmcs02;
7286 vmx_vcpu_put(vcpu);
7287 vmx_vcpu_load(vcpu, cpu);
7288 vcpu->cpu = cpu;
7289 put_cpu();
7291 vmx_segment_cache_clear(vmx);
7293 vmcs12->launch_state = 1;
7295 prepare_vmcs02(vcpu, vmcs12);
7298 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
7299 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
7300 * returned as far as L1 is concerned. It will only return (and set
7301 * the success flag) when L2 exits (see nested_vmx_vmexit()).
7303 return 1;
7307 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
7308 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
7309 * This function returns the new value we should put in vmcs12.guest_cr0.
7310 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
7311 * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
7312 * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
7313 * didn't trap the bit, because if L1 did, so would L0).
7314 * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
7315 * been modified by L2, and L1 knows it. So just leave the old value of
7316 * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
7317 * isn't relevant, because if L0 traps this bit it can set it to anything.
7318 * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
7319 * changed these bits, and therefore they need to be updated, but L0
7320 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather
7321 * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
7323 static inline unsigned long
7324 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
7326 return
7327 /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
7328 /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
7329 /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
7330 vcpu->arch.cr0_guest_owned_bits));
7333 static inline unsigned long
7334 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
7336 return
7337 /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
7338 /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
7339 /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
7340 vcpu->arch.cr4_guest_owned_bits));
7344 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
7345 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
7346 * and this function updates it to reflect the changes to the guest state while
7347 * L2 was running (and perhaps made some exits which were handled directly by L0
7348 * without going back to L1), and to reflect the exit reason.
7349 * Note that we do not have to copy here all VMCS fields, just those that
7350 * could have changed by the L2 guest or the exit - i.e., the guest-state and
7351 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
7352 * which already writes to vmcs12 directly.
7354 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
7356 /* update guest state fields: */
7357 vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
7358 vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
7360 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
7361 vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7362 vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
7363 vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
7365 vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
7366 vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
7367 vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
7368 vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
7369 vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
7370 vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
7371 vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
7372 vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
7373 vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
7374 vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
7375 vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
7376 vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
7377 vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
7378 vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
7379 vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
7380 vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
7381 vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
7382 vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
7383 vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
7384 vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
7385 vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
7386 vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
7387 vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
7388 vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
7389 vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
7390 vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
7391 vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
7392 vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
7393 vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
7394 vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
7395 vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
7396 vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
7397 vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
7398 vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
7399 vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
7400 vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
7402 vmcs12->guest_activity_state = vmcs_read32(GUEST_ACTIVITY_STATE);
7403 vmcs12->guest_interruptibility_info =
7404 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
7405 vmcs12->guest_pending_dbg_exceptions =
7406 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
7408 vmcs12->vm_entry_controls =
7409 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
7410 (vmcs_read32(VM_ENTRY_CONTROLS) & VM_ENTRY_IA32E_MODE);
7412 /* TODO: These cannot have changed unless we have MSR bitmaps and
7413 * the relevant bit asks not to trap the change */
7414 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
7415 if (vmcs12->vm_entry_controls & VM_EXIT_SAVE_IA32_PAT)
7416 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
7417 vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
7418 vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
7419 vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
7421 /* update exit information fields: */
7423 vmcs12->vm_exit_reason = to_vmx(vcpu)->exit_reason;
7424 vmcs12->exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7426 vmcs12->vm_exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
7427 vmcs12->vm_exit_intr_error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
7428 vmcs12->idt_vectoring_info_field = to_vmx(vcpu)->idt_vectoring_info;
7429 vmcs12->idt_vectoring_error_code =
7430 vmcs_read32(IDT_VECTORING_ERROR_CODE);
7431 vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
7432 vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7434 /* clear vm-entry fields which are to be cleared on exit */
7435 if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
7436 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
7440 * A part of what we need to when the nested L2 guest exits and we want to
7441 * run its L1 parent, is to reset L1's guest state to the host state specified
7442 * in vmcs12.
7443 * This function is to be called not only on normal nested exit, but also on
7444 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
7445 * Failures During or After Loading Guest State").
7446 * This function should be called when the active VMCS is L1's (vmcs01).
7448 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
7449 struct vmcs12 *vmcs12)
7451 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
7452 vcpu->arch.efer = vmcs12->host_ia32_efer;
7453 if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
7454 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
7455 else
7456 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
7457 vmx_set_efer(vcpu, vcpu->arch.efer);
7459 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
7460 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
7461 vmx_set_rflags(vcpu, X86_EFLAGS_BIT1);
7463 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
7464 * actually changed, because it depends on the current state of
7465 * fpu_active (which may have changed).
7466 * Note that vmx_set_cr0 refers to efer set above.
7468 kvm_set_cr0(vcpu, vmcs12->host_cr0);
7470 * If we did fpu_activate()/fpu_deactivate() during L2's run, we need
7471 * to apply the same changes to L1's vmcs. We just set cr0 correctly,
7472 * but we also need to update cr0_guest_host_mask and exception_bitmap.
7474 update_exception_bitmap(vcpu);
7475 vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
7476 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
7479 * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
7480 * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
7482 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
7483 kvm_set_cr4(vcpu, vmcs12->host_cr4);
7485 /* shadow page tables on either EPT or shadow page tables */
7486 kvm_set_cr3(vcpu, vmcs12->host_cr3);
7487 kvm_mmu_reset_context(vcpu);
7489 if (enable_vpid) {
7491 * Trivially support vpid by letting L2s share their parent
7492 * L1's vpid. TODO: move to a more elaborate solution, giving
7493 * each L2 its own vpid and exposing the vpid feature to L1.
7495 vmx_flush_tlb(vcpu);
7499 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
7500 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
7501 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
7502 vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
7503 vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
7504 vmcs_writel(GUEST_TR_BASE, vmcs12->host_tr_base);
7505 vmcs_writel(GUEST_GS_BASE, vmcs12->host_gs_base);
7506 vmcs_writel(GUEST_FS_BASE, vmcs12->host_fs_base);
7507 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->host_es_selector);
7508 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->host_cs_selector);
7509 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->host_ss_selector);
7510 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->host_ds_selector);
7511 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->host_fs_selector);
7512 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->host_gs_selector);
7513 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->host_tr_selector);
7515 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT)
7516 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
7517 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
7518 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
7519 vmcs12->host_ia32_perf_global_ctrl);
7521 kvm_set_dr(vcpu, 7, 0x400);
7522 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
7526 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
7527 * and modify vmcs12 to make it see what it would expect to see there if
7528 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
7530 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu)
7532 struct vcpu_vmx *vmx = to_vmx(vcpu);
7533 int cpu;
7534 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7536 leave_guest_mode(vcpu);
7537 prepare_vmcs12(vcpu, vmcs12);
7539 cpu = get_cpu();
7540 vmx->loaded_vmcs = &vmx->vmcs01;
7541 vmx_vcpu_put(vcpu);
7542 vmx_vcpu_load(vcpu, cpu);
7543 vcpu->cpu = cpu;
7544 put_cpu();
7546 vmx_segment_cache_clear(vmx);
7548 /* if no vmcs02 cache requested, remove the one we used */
7549 if (VMCS02_POOL_SIZE == 0)
7550 nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
7552 load_vmcs12_host_state(vcpu, vmcs12);
7554 /* Update TSC_OFFSET if TSC was changed while L2 ran */
7555 vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
7557 /* This is needed for same reason as it was needed in prepare_vmcs02 */
7558 vmx->host_rsp = 0;
7560 /* Unpin physical memory we referred to in vmcs02 */
7561 if (vmx->nested.apic_access_page) {
7562 nested_release_page(vmx->nested.apic_access_page);
7563 vmx->nested.apic_access_page = 0;
7567 * Exiting from L2 to L1, we're now back to L1 which thinks it just
7568 * finished a VMLAUNCH or VMRESUME instruction, so we need to set the
7569 * success or failure flag accordingly.
7571 if (unlikely(vmx->fail)) {
7572 vmx->fail = 0;
7573 nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR));
7574 } else
7575 nested_vmx_succeed(vcpu);
7579 * L1's failure to enter L2 is a subset of a normal exit, as explained in
7580 * 23.7 "VM-entry failures during or after loading guest state" (this also
7581 * lists the acceptable exit-reason and exit-qualification parameters).
7582 * It should only be called before L2 actually succeeded to run, and when
7583 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
7585 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
7586 struct vmcs12 *vmcs12,
7587 u32 reason, unsigned long qualification)
7589 load_vmcs12_host_state(vcpu, vmcs12);
7590 vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
7591 vmcs12->exit_qualification = qualification;
7592 nested_vmx_succeed(vcpu);
7595 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7596 struct x86_instruction_info *info,
7597 enum x86_intercept_stage stage)
7599 return X86EMUL_CONTINUE;
7602 static struct kvm_x86_ops vmx_x86_ops = {
7603 .cpu_has_kvm_support = cpu_has_kvm_support,
7604 .disabled_by_bios = vmx_disabled_by_bios,
7605 .hardware_setup = hardware_setup,
7606 .hardware_unsetup = hardware_unsetup,
7607 .check_processor_compatibility = vmx_check_processor_compat,
7608 .hardware_enable = hardware_enable,
7609 .hardware_disable = hardware_disable,
7610 .cpu_has_accelerated_tpr = report_flexpriority,
7612 .vcpu_create = vmx_create_vcpu,
7613 .vcpu_free = vmx_free_vcpu,
7614 .vcpu_reset = vmx_vcpu_reset,
7616 .prepare_guest_switch = vmx_save_host_state,
7617 .vcpu_load = vmx_vcpu_load,
7618 .vcpu_put = vmx_vcpu_put,
7620 .update_db_bp_intercept = update_exception_bitmap,
7621 .get_msr = vmx_get_msr,
7622 .set_msr = vmx_set_msr,
7623 .get_segment_base = vmx_get_segment_base,
7624 .get_segment = vmx_get_segment,
7625 .set_segment = vmx_set_segment,
7626 .get_cpl = vmx_get_cpl,
7627 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7628 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
7629 .decache_cr3 = vmx_decache_cr3,
7630 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
7631 .set_cr0 = vmx_set_cr0,
7632 .set_cr3 = vmx_set_cr3,
7633 .set_cr4 = vmx_set_cr4,
7634 .set_efer = vmx_set_efer,
7635 .get_idt = vmx_get_idt,
7636 .set_idt = vmx_set_idt,
7637 .get_gdt = vmx_get_gdt,
7638 .set_gdt = vmx_set_gdt,
7639 .set_dr7 = vmx_set_dr7,
7640 .cache_reg = vmx_cache_reg,
7641 .get_rflags = vmx_get_rflags,
7642 .set_rflags = vmx_set_rflags,
7643 .fpu_activate = vmx_fpu_activate,
7644 .fpu_deactivate = vmx_fpu_deactivate,
7646 .tlb_flush = vmx_flush_tlb,
7648 .run = vmx_vcpu_run,
7649 .handle_exit = vmx_handle_exit,
7650 .skip_emulated_instruction = skip_emulated_instruction,
7651 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7652 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7653 .patch_hypercall = vmx_patch_hypercall,
7654 .set_irq = vmx_inject_irq,
7655 .set_nmi = vmx_inject_nmi,
7656 .queue_exception = vmx_queue_exception,
7657 .cancel_injection = vmx_cancel_injection,
7658 .interrupt_allowed = vmx_interrupt_allowed,
7659 .nmi_allowed = vmx_nmi_allowed,
7660 .get_nmi_mask = vmx_get_nmi_mask,
7661 .set_nmi_mask = vmx_set_nmi_mask,
7662 .enable_nmi_window = enable_nmi_window,
7663 .enable_irq_window = enable_irq_window,
7664 .update_cr8_intercept = update_cr8_intercept,
7665 .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
7666 .vm_has_apicv = vmx_vm_has_apicv,
7667 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7668 .hwapic_irr_update = vmx_hwapic_irr_update,
7669 .hwapic_isr_update = vmx_hwapic_isr_update,
7671 .set_tss_addr = vmx_set_tss_addr,
7672 .get_tdp_level = get_ept_level,
7673 .get_mt_mask = vmx_get_mt_mask,
7675 .get_exit_info = vmx_get_exit_info,
7677 .get_lpage_level = vmx_get_lpage_level,
7679 .cpuid_update = vmx_cpuid_update,
7681 .rdtscp_supported = vmx_rdtscp_supported,
7682 .invpcid_supported = vmx_invpcid_supported,
7684 .set_supported_cpuid = vmx_set_supported_cpuid,
7686 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7688 .set_tsc_khz = vmx_set_tsc_khz,
7689 .read_tsc_offset = vmx_read_tsc_offset,
7690 .write_tsc_offset = vmx_write_tsc_offset,
7691 .adjust_tsc_offset = vmx_adjust_tsc_offset,
7692 .compute_tsc_offset = vmx_compute_tsc_offset,
7693 .read_l1_tsc = vmx_read_l1_tsc,
7695 .set_tdp_cr3 = vmx_set_cr3,
7697 .check_intercept = vmx_check_intercept,
7700 static int __init vmx_init(void)
7702 int r, i, msr;
7704 rdmsrl_safe(MSR_EFER, &host_efer);
7706 for (i = 0; i < NR_VMX_MSR; ++i)
7707 kvm_define_shared_msr(i, vmx_msr_index[i]);
7709 vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
7710 if (!vmx_io_bitmap_a)
7711 return -ENOMEM;
7713 r = -ENOMEM;
7715 vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
7716 if (!vmx_io_bitmap_b)
7717 goto out;
7719 vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);
7720 if (!vmx_msr_bitmap_legacy)
7721 goto out1;
7723 vmx_msr_bitmap_legacy_x2apic =
7724 (unsigned long *)__get_free_page(GFP_KERNEL);
7725 if (!vmx_msr_bitmap_legacy_x2apic)
7726 goto out2;
7728 vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);
7729 if (!vmx_msr_bitmap_longmode)
7730 goto out3;
7732 vmx_msr_bitmap_longmode_x2apic =
7733 (unsigned long *)__get_free_page(GFP_KERNEL);
7734 if (!vmx_msr_bitmap_longmode_x2apic)
7735 goto out4;
7738 * Allow direct access to the PC debug port (it is often used for I/O
7739 * delays, but the vmexits simply slow things down).
7741 memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
7742 clear_bit(0x80, vmx_io_bitmap_a);
7744 memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
7746 memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
7747 memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
7749 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7751 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
7752 __alignof__(struct vcpu_vmx), THIS_MODULE);
7753 if (r)
7754 goto out3;
7756 #ifdef CONFIG_KEXEC
7757 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
7758 crash_vmclear_local_loaded_vmcss);
7759 #endif
7761 vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
7762 vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
7763 vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
7764 vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
7765 vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
7766 vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
7767 memcpy(vmx_msr_bitmap_legacy_x2apic,
7768 vmx_msr_bitmap_legacy, PAGE_SIZE);
7769 memcpy(vmx_msr_bitmap_longmode_x2apic,
7770 vmx_msr_bitmap_longmode, PAGE_SIZE);
7772 if (enable_apicv_reg_vid) {
7773 for (msr = 0x800; msr <= 0x8ff; msr++)
7774 vmx_disable_intercept_msr_read_x2apic(msr);
7776 /* According SDM, in x2apic mode, the whole id reg is used.
7777 * But in KVM, it only use the highest eight bits. Need to
7778 * intercept it */
7779 vmx_enable_intercept_msr_read_x2apic(0x802);
7780 /* TMCCT */
7781 vmx_enable_intercept_msr_read_x2apic(0x839);
7782 /* TPR */
7783 vmx_disable_intercept_msr_write_x2apic(0x808);
7784 /* EOI */
7785 vmx_disable_intercept_msr_write_x2apic(0x80b);
7786 /* SELF-IPI */
7787 vmx_disable_intercept_msr_write_x2apic(0x83f);
7790 if (enable_ept) {
7791 kvm_mmu_set_mask_ptes(0ull,
7792 (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
7793 (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
7794 0ull, VMX_EPT_EXECUTABLE_MASK);
7795 ept_set_mmio_spte_mask();
7796 kvm_enable_tdp();
7797 } else
7798 kvm_disable_tdp();
7800 return 0;
7802 out4:
7803 free_page((unsigned long)vmx_msr_bitmap_longmode);
7804 out3:
7805 free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
7806 out2:
7807 free_page((unsigned long)vmx_msr_bitmap_legacy);
7808 out1:
7809 free_page((unsigned long)vmx_io_bitmap_b);
7810 out:
7811 free_page((unsigned long)vmx_io_bitmap_a);
7812 return r;
7815 static void __exit vmx_exit(void)
7817 free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
7818 free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
7819 free_page((unsigned long)vmx_msr_bitmap_legacy);
7820 free_page((unsigned long)vmx_msr_bitmap_longmode);
7821 free_page((unsigned long)vmx_io_bitmap_b);
7822 free_page((unsigned long)vmx_io_bitmap_a);
7824 #ifdef CONFIG_KEXEC
7825 rcu_assign_pointer(crash_vmclear_loaded_vmcss, NULL);
7826 synchronize_rcu();
7827 #endif
7829 kvm_exit();
7832 module_init(vmx_init)
7833 module_exit(vmx_exit)