]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - arch/x86/kvm/vmx.c
Merge branch 'x86-pti-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git...
[mirror_ubuntu-bionic-kernel.git] / arch / x86 / kvm / vmx.c
1 /*
2 * Kernel-based Virtual Machine driver for Linux
3 *
4 * This module enables machines with Intel VT-x extensions to run virtual
5 * machines without emulation or binary translation.
6 *
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9 *
10 * Authors:
11 * Avi Kivity <avi@qumranet.com>
12 * Yaniv Kamay <yaniv@qumranet.com>
13 *
14 * This work is licensed under the terms of the GNU GPL, version 2. See
15 * the COPYING file in the top-level directory.
16 *
17 */
18
19 #include "irq.h"
20 #include "mmu.h"
21 #include "cpuid.h"
22 #include "lapic.h"
23
24 #include <linux/kvm_host.h>
25 #include <linux/module.h>
26 #include <linux/kernel.h>
27 #include <linux/mm.h>
28 #include <linux/highmem.h>
29 #include <linux/sched.h>
30 #include <linux/moduleparam.h>
31 #include <linux/mod_devicetable.h>
32 #include <linux/trace_events.h>
33 #include <linux/slab.h>
34 #include <linux/tboot.h>
35 #include <linux/hrtimer.h>
36 #include <linux/frame.h>
37 #include "kvm_cache_regs.h"
38 #include "x86.h"
39
40 #include <asm/cpu.h>
41 #include <asm/io.h>
42 #include <asm/desc.h>
43 #include <asm/vmx.h>
44 #include <asm/virtext.h>
45 #include <asm/mce.h>
46 #include <asm/fpu/internal.h>
47 #include <asm/perf_event.h>
48 #include <asm/debugreg.h>
49 #include <asm/kexec.h>
50 #include <asm/apic.h>
51 #include <asm/irq_remapping.h>
52 #include <asm/mmu_context.h>
53 #include <asm/nospec-branch.h>
54
55 #include "trace.h"
56 #include "pmu.h"
57
58 #define __ex(x) __kvm_handle_fault_on_reboot(x)
59 #define __ex_clear(x, reg) \
60 ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
61
62 MODULE_AUTHOR("Qumranet");
63 MODULE_LICENSE("GPL");
64
65 static const struct x86_cpu_id vmx_cpu_id[] = {
66 X86_FEATURE_MATCH(X86_FEATURE_VMX),
67 {}
68 };
69 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
70
71 static bool __read_mostly enable_vpid = 1;
72 module_param_named(vpid, enable_vpid, bool, 0444);
73
74 static bool __read_mostly enable_vnmi = 1;
75 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
76
77 static bool __read_mostly flexpriority_enabled = 1;
78 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
79
80 static bool __read_mostly enable_ept = 1;
81 module_param_named(ept, enable_ept, bool, S_IRUGO);
82
83 static bool __read_mostly enable_unrestricted_guest = 1;
84 module_param_named(unrestricted_guest,
85 enable_unrestricted_guest, bool, S_IRUGO);
86
87 static bool __read_mostly enable_ept_ad_bits = 1;
88 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
89
90 static bool __read_mostly emulate_invalid_guest_state = true;
91 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
92
93 static bool __read_mostly fasteoi = 1;
94 module_param(fasteoi, bool, S_IRUGO);
95
96 static bool __read_mostly enable_apicv = 1;
97 module_param(enable_apicv, bool, S_IRUGO);
98
99 static bool __read_mostly enable_shadow_vmcs = 1;
100 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
101 /*
102 * If nested=1, nested virtualization is supported, i.e., guests may use
103 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
104 * use VMX instructions.
105 */
106 static bool __read_mostly nested = 0;
107 module_param(nested, bool, S_IRUGO);
108
109 static u64 __read_mostly host_xss;
110
111 static bool __read_mostly enable_pml = 1;
112 module_param_named(pml, enable_pml, bool, S_IRUGO);
113
114 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
115
116 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
117 static int __read_mostly cpu_preemption_timer_multi;
118 static bool __read_mostly enable_preemption_timer = 1;
119 #ifdef CONFIG_X86_64
120 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
121 #endif
122
123 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
124 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
125 #define KVM_VM_CR0_ALWAYS_ON \
126 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
127 #define KVM_CR4_GUEST_OWNED_BITS \
128 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
129 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
130
131 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
132 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
133
134 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
135
136 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
137
138 /*
139 * Hyper-V requires all of these, so mark them as supported even though
140 * they are just treated the same as all-context.
141 */
142 #define VMX_VPID_EXTENT_SUPPORTED_MASK \
143 (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
144 VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
145 VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
146 VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
147
148 /*
149 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
150 * ple_gap: upper bound on the amount of time between two successive
151 * executions of PAUSE in a loop. Also indicate if ple enabled.
152 * According to test, this time is usually smaller than 128 cycles.
153 * ple_window: upper bound on the amount of time a guest is allowed to execute
154 * in a PAUSE loop. Tests indicate that most spinlocks are held for
155 * less than 2^12 cycles
156 * Time is measured based on a counter that runs at the same rate as the TSC,
157 * refer SDM volume 3b section 21.6.13 & 22.1.3.
158 */
159 #define KVM_VMX_DEFAULT_PLE_GAP 128
160 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
161 #define KVM_VMX_DEFAULT_PLE_WINDOW_GROW 2
162 #define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
163 #define KVM_VMX_DEFAULT_PLE_WINDOW_MAX \
164 INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
165
166 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
167 module_param(ple_gap, int, S_IRUGO);
168
169 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
170 module_param(ple_window, int, S_IRUGO);
171
172 /* Default doubles per-vcpu window every exit. */
173 static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
174 module_param(ple_window_grow, int, S_IRUGO);
175
176 /* Default resets per-vcpu window every exit to ple_window. */
177 static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
178 module_param(ple_window_shrink, int, S_IRUGO);
179
180 /* Default is to compute the maximum so we can never overflow. */
181 static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
182 static int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
183 module_param(ple_window_max, int, S_IRUGO);
184
185 extern const ulong vmx_return;
186
187 #define NR_AUTOLOAD_MSRS 8
188 #define VMCS02_POOL_SIZE 1
189
190 struct vmcs {
191 u32 revision_id;
192 u32 abort;
193 char data[0];
194 };
195
196 /*
197 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
198 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
199 * loaded on this CPU (so we can clear them if the CPU goes down).
200 */
201 struct loaded_vmcs {
202 struct vmcs *vmcs;
203 struct vmcs *shadow_vmcs;
204 int cpu;
205 bool launched;
206 bool nmi_known_unmasked;
207 unsigned long vmcs_host_cr3; /* May not match real cr3 */
208 unsigned long vmcs_host_cr4; /* May not match real cr4 */
209 /* Support for vnmi-less CPUs */
210 int soft_vnmi_blocked;
211 ktime_t entry_time;
212 s64 vnmi_blocked_time;
213 struct list_head loaded_vmcss_on_cpu_link;
214 };
215
216 struct shared_msr_entry {
217 unsigned index;
218 u64 data;
219 u64 mask;
220 };
221
222 /*
223 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
224 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
225 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
226 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
227 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
228 * More than one of these structures may exist, if L1 runs multiple L2 guests.
229 * nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
230 * underlying hardware which will be used to run L2.
231 * This structure is packed to ensure that its layout is identical across
232 * machines (necessary for live migration).
233 * If there are changes in this struct, VMCS12_REVISION must be changed.
234 */
235 typedef u64 natural_width;
236 struct __packed vmcs12 {
237 /* According to the Intel spec, a VMCS region must start with the
238 * following two fields. Then follow implementation-specific data.
239 */
240 u32 revision_id;
241 u32 abort;
242
243 u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
244 u32 padding[7]; /* room for future expansion */
245
246 u64 io_bitmap_a;
247 u64 io_bitmap_b;
248 u64 msr_bitmap;
249 u64 vm_exit_msr_store_addr;
250 u64 vm_exit_msr_load_addr;
251 u64 vm_entry_msr_load_addr;
252 u64 tsc_offset;
253 u64 virtual_apic_page_addr;
254 u64 apic_access_addr;
255 u64 posted_intr_desc_addr;
256 u64 vm_function_control;
257 u64 ept_pointer;
258 u64 eoi_exit_bitmap0;
259 u64 eoi_exit_bitmap1;
260 u64 eoi_exit_bitmap2;
261 u64 eoi_exit_bitmap3;
262 u64 eptp_list_address;
263 u64 xss_exit_bitmap;
264 u64 guest_physical_address;
265 u64 vmcs_link_pointer;
266 u64 pml_address;
267 u64 guest_ia32_debugctl;
268 u64 guest_ia32_pat;
269 u64 guest_ia32_efer;
270 u64 guest_ia32_perf_global_ctrl;
271 u64 guest_pdptr0;
272 u64 guest_pdptr1;
273 u64 guest_pdptr2;
274 u64 guest_pdptr3;
275 u64 guest_bndcfgs;
276 u64 host_ia32_pat;
277 u64 host_ia32_efer;
278 u64 host_ia32_perf_global_ctrl;
279 u64 padding64[8]; /* room for future expansion */
280 /*
281 * To allow migration of L1 (complete with its L2 guests) between
282 * machines of different natural widths (32 or 64 bit), we cannot have
283 * unsigned long fields with no explict size. We use u64 (aliased
284 * natural_width) instead. Luckily, x86 is little-endian.
285 */
286 natural_width cr0_guest_host_mask;
287 natural_width cr4_guest_host_mask;
288 natural_width cr0_read_shadow;
289 natural_width cr4_read_shadow;
290 natural_width cr3_target_value0;
291 natural_width cr3_target_value1;
292 natural_width cr3_target_value2;
293 natural_width cr3_target_value3;
294 natural_width exit_qualification;
295 natural_width guest_linear_address;
296 natural_width guest_cr0;
297 natural_width guest_cr3;
298 natural_width guest_cr4;
299 natural_width guest_es_base;
300 natural_width guest_cs_base;
301 natural_width guest_ss_base;
302 natural_width guest_ds_base;
303 natural_width guest_fs_base;
304 natural_width guest_gs_base;
305 natural_width guest_ldtr_base;
306 natural_width guest_tr_base;
307 natural_width guest_gdtr_base;
308 natural_width guest_idtr_base;
309 natural_width guest_dr7;
310 natural_width guest_rsp;
311 natural_width guest_rip;
312 natural_width guest_rflags;
313 natural_width guest_pending_dbg_exceptions;
314 natural_width guest_sysenter_esp;
315 natural_width guest_sysenter_eip;
316 natural_width host_cr0;
317 natural_width host_cr3;
318 natural_width host_cr4;
319 natural_width host_fs_base;
320 natural_width host_gs_base;
321 natural_width host_tr_base;
322 natural_width host_gdtr_base;
323 natural_width host_idtr_base;
324 natural_width host_ia32_sysenter_esp;
325 natural_width host_ia32_sysenter_eip;
326 natural_width host_rsp;
327 natural_width host_rip;
328 natural_width paddingl[8]; /* room for future expansion */
329 u32 pin_based_vm_exec_control;
330 u32 cpu_based_vm_exec_control;
331 u32 exception_bitmap;
332 u32 page_fault_error_code_mask;
333 u32 page_fault_error_code_match;
334 u32 cr3_target_count;
335 u32 vm_exit_controls;
336 u32 vm_exit_msr_store_count;
337 u32 vm_exit_msr_load_count;
338 u32 vm_entry_controls;
339 u32 vm_entry_msr_load_count;
340 u32 vm_entry_intr_info_field;
341 u32 vm_entry_exception_error_code;
342 u32 vm_entry_instruction_len;
343 u32 tpr_threshold;
344 u32 secondary_vm_exec_control;
345 u32 vm_instruction_error;
346 u32 vm_exit_reason;
347 u32 vm_exit_intr_info;
348 u32 vm_exit_intr_error_code;
349 u32 idt_vectoring_info_field;
350 u32 idt_vectoring_error_code;
351 u32 vm_exit_instruction_len;
352 u32 vmx_instruction_info;
353 u32 guest_es_limit;
354 u32 guest_cs_limit;
355 u32 guest_ss_limit;
356 u32 guest_ds_limit;
357 u32 guest_fs_limit;
358 u32 guest_gs_limit;
359 u32 guest_ldtr_limit;
360 u32 guest_tr_limit;
361 u32 guest_gdtr_limit;
362 u32 guest_idtr_limit;
363 u32 guest_es_ar_bytes;
364 u32 guest_cs_ar_bytes;
365 u32 guest_ss_ar_bytes;
366 u32 guest_ds_ar_bytes;
367 u32 guest_fs_ar_bytes;
368 u32 guest_gs_ar_bytes;
369 u32 guest_ldtr_ar_bytes;
370 u32 guest_tr_ar_bytes;
371 u32 guest_interruptibility_info;
372 u32 guest_activity_state;
373 u32 guest_sysenter_cs;
374 u32 host_ia32_sysenter_cs;
375 u32 vmx_preemption_timer_value;
376 u32 padding32[7]; /* room for future expansion */
377 u16 virtual_processor_id;
378 u16 posted_intr_nv;
379 u16 guest_es_selector;
380 u16 guest_cs_selector;
381 u16 guest_ss_selector;
382 u16 guest_ds_selector;
383 u16 guest_fs_selector;
384 u16 guest_gs_selector;
385 u16 guest_ldtr_selector;
386 u16 guest_tr_selector;
387 u16 guest_intr_status;
388 u16 guest_pml_index;
389 u16 host_es_selector;
390 u16 host_cs_selector;
391 u16 host_ss_selector;
392 u16 host_ds_selector;
393 u16 host_fs_selector;
394 u16 host_gs_selector;
395 u16 host_tr_selector;
396 };
397
398 /*
399 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
400 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
401 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
402 */
403 #define VMCS12_REVISION 0x11e57ed0
404
405 /*
406 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
407 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
408 * current implementation, 4K are reserved to avoid future complications.
409 */
410 #define VMCS12_SIZE 0x1000
411
412 /* Used to remember the last vmcs02 used for some recently used vmcs12s */
413 struct vmcs02_list {
414 struct list_head list;
415 gpa_t vmptr;
416 struct loaded_vmcs vmcs02;
417 };
418
419 /*
420 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
421 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
422 */
423 struct nested_vmx {
424 /* Has the level1 guest done vmxon? */
425 bool vmxon;
426 gpa_t vmxon_ptr;
427 bool pml_full;
428
429 /* The guest-physical address of the current VMCS L1 keeps for L2 */
430 gpa_t current_vmptr;
431 /*
432 * Cache of the guest's VMCS, existing outside of guest memory.
433 * Loaded from guest memory during VMPTRLD. Flushed to guest
434 * memory during VMCLEAR and VMPTRLD.
435 */
436 struct vmcs12 *cached_vmcs12;
437 /*
438 * Indicates if the shadow vmcs must be updated with the
439 * data hold by vmcs12
440 */
441 bool sync_shadow_vmcs;
442
443 /* vmcs02_list cache of VMCSs recently used to run L2 guests */
444 struct list_head vmcs02_pool;
445 int vmcs02_num;
446 bool change_vmcs01_virtual_x2apic_mode;
447 /* L2 must run next, and mustn't decide to exit to L1. */
448 bool nested_run_pending;
449 /*
450 * Guest pages referred to in vmcs02 with host-physical pointers, so
451 * we must keep them pinned while L2 runs.
452 */
453 struct page *apic_access_page;
454 struct page *virtual_apic_page;
455 struct page *pi_desc_page;
456 struct pi_desc *pi_desc;
457 bool pi_pending;
458 u16 posted_intr_nv;
459
460 unsigned long *msr_bitmap;
461
462 struct hrtimer preemption_timer;
463 bool preemption_timer_expired;
464
465 /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
466 u64 vmcs01_debugctl;
467
468 u16 vpid02;
469 u16 last_vpid;
470
471 /*
472 * We only store the "true" versions of the VMX capability MSRs. We
473 * generate the "non-true" versions by setting the must-be-1 bits
474 * according to the SDM.
475 */
476 u32 nested_vmx_procbased_ctls_low;
477 u32 nested_vmx_procbased_ctls_high;
478 u32 nested_vmx_secondary_ctls_low;
479 u32 nested_vmx_secondary_ctls_high;
480 u32 nested_vmx_pinbased_ctls_low;
481 u32 nested_vmx_pinbased_ctls_high;
482 u32 nested_vmx_exit_ctls_low;
483 u32 nested_vmx_exit_ctls_high;
484 u32 nested_vmx_entry_ctls_low;
485 u32 nested_vmx_entry_ctls_high;
486 u32 nested_vmx_misc_low;
487 u32 nested_vmx_misc_high;
488 u32 nested_vmx_ept_caps;
489 u32 nested_vmx_vpid_caps;
490 u64 nested_vmx_basic;
491 u64 nested_vmx_cr0_fixed0;
492 u64 nested_vmx_cr0_fixed1;
493 u64 nested_vmx_cr4_fixed0;
494 u64 nested_vmx_cr4_fixed1;
495 u64 nested_vmx_vmcs_enum;
496 u64 nested_vmx_vmfunc_controls;
497
498 /* SMM related state */
499 struct {
500 /* in VMX operation on SMM entry? */
501 bool vmxon;
502 /* in guest mode on SMM entry? */
503 bool guest_mode;
504 } smm;
505 };
506
507 #define POSTED_INTR_ON 0
508 #define POSTED_INTR_SN 1
509
510 /* Posted-Interrupt Descriptor */
511 struct pi_desc {
512 u32 pir[8]; /* Posted interrupt requested */
513 union {
514 struct {
515 /* bit 256 - Outstanding Notification */
516 u16 on : 1,
517 /* bit 257 - Suppress Notification */
518 sn : 1,
519 /* bit 271:258 - Reserved */
520 rsvd_1 : 14;
521 /* bit 279:272 - Notification Vector */
522 u8 nv;
523 /* bit 287:280 - Reserved */
524 u8 rsvd_2;
525 /* bit 319:288 - Notification Destination */
526 u32 ndst;
527 };
528 u64 control;
529 };
530 u32 rsvd[6];
531 } __aligned(64);
532
533 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
534 {
535 return test_and_set_bit(POSTED_INTR_ON,
536 (unsigned long *)&pi_desc->control);
537 }
538
539 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
540 {
541 return test_and_clear_bit(POSTED_INTR_ON,
542 (unsigned long *)&pi_desc->control);
543 }
544
545 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
546 {
547 return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
548 }
549
550 static inline void pi_clear_sn(struct pi_desc *pi_desc)
551 {
552 return clear_bit(POSTED_INTR_SN,
553 (unsigned long *)&pi_desc->control);
554 }
555
556 static inline void pi_set_sn(struct pi_desc *pi_desc)
557 {
558 return set_bit(POSTED_INTR_SN,
559 (unsigned long *)&pi_desc->control);
560 }
561
562 static inline void pi_clear_on(struct pi_desc *pi_desc)
563 {
564 clear_bit(POSTED_INTR_ON,
565 (unsigned long *)&pi_desc->control);
566 }
567
568 static inline int pi_test_on(struct pi_desc *pi_desc)
569 {
570 return test_bit(POSTED_INTR_ON,
571 (unsigned long *)&pi_desc->control);
572 }
573
574 static inline int pi_test_sn(struct pi_desc *pi_desc)
575 {
576 return test_bit(POSTED_INTR_SN,
577 (unsigned long *)&pi_desc->control);
578 }
579
580 struct vcpu_vmx {
581 struct kvm_vcpu vcpu;
582 unsigned long host_rsp;
583 u8 fail;
584 u32 exit_intr_info;
585 u32 idt_vectoring_info;
586 ulong rflags;
587 struct shared_msr_entry *guest_msrs;
588 int nmsrs;
589 int save_nmsrs;
590 unsigned long host_idt_base;
591 #ifdef CONFIG_X86_64
592 u64 msr_host_kernel_gs_base;
593 u64 msr_guest_kernel_gs_base;
594 #endif
595 u32 vm_entry_controls_shadow;
596 u32 vm_exit_controls_shadow;
597 u32 secondary_exec_control;
598
599 /*
600 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
601 * non-nested (L1) guest, it always points to vmcs01. For a nested
602 * guest (L2), it points to a different VMCS.
603 */
604 struct loaded_vmcs vmcs01;
605 struct loaded_vmcs *loaded_vmcs;
606 bool __launched; /* temporary, used in vmx_vcpu_run */
607 struct msr_autoload {
608 unsigned nr;
609 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
610 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
611 } msr_autoload;
612 struct {
613 int loaded;
614 u16 fs_sel, gs_sel, ldt_sel;
615 #ifdef CONFIG_X86_64
616 u16 ds_sel, es_sel;
617 #endif
618 int gs_ldt_reload_needed;
619 int fs_reload_needed;
620 u64 msr_host_bndcfgs;
621 } host_state;
622 struct {
623 int vm86_active;
624 ulong save_rflags;
625 struct kvm_segment segs[8];
626 } rmode;
627 struct {
628 u32 bitmask; /* 4 bits per segment (1 bit per field) */
629 struct kvm_save_segment {
630 u16 selector;
631 unsigned long base;
632 u32 limit;
633 u32 ar;
634 } seg[8];
635 } segment_cache;
636 int vpid;
637 bool emulation_required;
638
639 u32 exit_reason;
640
641 /* Posted interrupt descriptor */
642 struct pi_desc pi_desc;
643
644 /* Support for a guest hypervisor (nested VMX) */
645 struct nested_vmx nested;
646
647 /* Dynamic PLE window. */
648 int ple_window;
649 bool ple_window_dirty;
650
651 /* Support for PML */
652 #define PML_ENTITY_NUM 512
653 struct page *pml_pg;
654
655 /* apic deadline value in host tsc */
656 u64 hv_deadline_tsc;
657
658 u64 current_tsc_ratio;
659
660 u32 host_pkru;
661
662 /*
663 * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
664 * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
665 * in msr_ia32_feature_control_valid_bits.
666 */
667 u64 msr_ia32_feature_control;
668 u64 msr_ia32_feature_control_valid_bits;
669 };
670
671 enum segment_cache_field {
672 SEG_FIELD_SEL = 0,
673 SEG_FIELD_BASE = 1,
674 SEG_FIELD_LIMIT = 2,
675 SEG_FIELD_AR = 3,
676
677 SEG_FIELD_NR = 4
678 };
679
680 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
681 {
682 return container_of(vcpu, struct vcpu_vmx, vcpu);
683 }
684
685 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
686 {
687 return &(to_vmx(vcpu)->pi_desc);
688 }
689
690 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
691 #define FIELD(number, name) [number] = VMCS12_OFFSET(name)
692 #define FIELD64(number, name) [number] = VMCS12_OFFSET(name), \
693 [number##_HIGH] = VMCS12_OFFSET(name)+4
694
695
696 static unsigned long shadow_read_only_fields[] = {
697 /*
698 * We do NOT shadow fields that are modified when L0
699 * traps and emulates any vmx instruction (e.g. VMPTRLD,
700 * VMXON...) executed by L1.
701 * For example, VM_INSTRUCTION_ERROR is read
702 * by L1 if a vmx instruction fails (part of the error path).
703 * Note the code assumes this logic. If for some reason
704 * we start shadowing these fields then we need to
705 * force a shadow sync when L0 emulates vmx instructions
706 * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
707 * by nested_vmx_failValid)
708 */
709 VM_EXIT_REASON,
710 VM_EXIT_INTR_INFO,
711 VM_EXIT_INSTRUCTION_LEN,
712 IDT_VECTORING_INFO_FIELD,
713 IDT_VECTORING_ERROR_CODE,
714 VM_EXIT_INTR_ERROR_CODE,
715 EXIT_QUALIFICATION,
716 GUEST_LINEAR_ADDRESS,
717 GUEST_PHYSICAL_ADDRESS
718 };
719 static int max_shadow_read_only_fields =
720 ARRAY_SIZE(shadow_read_only_fields);
721
722 static unsigned long shadow_read_write_fields[] = {
723 TPR_THRESHOLD,
724 GUEST_RIP,
725 GUEST_RSP,
726 GUEST_CR0,
727 GUEST_CR3,
728 GUEST_CR4,
729 GUEST_INTERRUPTIBILITY_INFO,
730 GUEST_RFLAGS,
731 GUEST_CS_SELECTOR,
732 GUEST_CS_AR_BYTES,
733 GUEST_CS_LIMIT,
734 GUEST_CS_BASE,
735 GUEST_ES_BASE,
736 GUEST_BNDCFGS,
737 CR0_GUEST_HOST_MASK,
738 CR0_READ_SHADOW,
739 CR4_READ_SHADOW,
740 TSC_OFFSET,
741 EXCEPTION_BITMAP,
742 CPU_BASED_VM_EXEC_CONTROL,
743 VM_ENTRY_EXCEPTION_ERROR_CODE,
744 VM_ENTRY_INTR_INFO_FIELD,
745 VM_ENTRY_INSTRUCTION_LEN,
746 VM_ENTRY_EXCEPTION_ERROR_CODE,
747 HOST_FS_BASE,
748 HOST_GS_BASE,
749 HOST_FS_SELECTOR,
750 HOST_GS_SELECTOR
751 };
752 static int max_shadow_read_write_fields =
753 ARRAY_SIZE(shadow_read_write_fields);
754
755 static const unsigned short vmcs_field_to_offset_table[] = {
756 FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
757 FIELD(POSTED_INTR_NV, posted_intr_nv),
758 FIELD(GUEST_ES_SELECTOR, guest_es_selector),
759 FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
760 FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
761 FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
762 FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
763 FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
764 FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
765 FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
766 FIELD(GUEST_INTR_STATUS, guest_intr_status),
767 FIELD(GUEST_PML_INDEX, guest_pml_index),
768 FIELD(HOST_ES_SELECTOR, host_es_selector),
769 FIELD(HOST_CS_SELECTOR, host_cs_selector),
770 FIELD(HOST_SS_SELECTOR, host_ss_selector),
771 FIELD(HOST_DS_SELECTOR, host_ds_selector),
772 FIELD(HOST_FS_SELECTOR, host_fs_selector),
773 FIELD(HOST_GS_SELECTOR, host_gs_selector),
774 FIELD(HOST_TR_SELECTOR, host_tr_selector),
775 FIELD64(IO_BITMAP_A, io_bitmap_a),
776 FIELD64(IO_BITMAP_B, io_bitmap_b),
777 FIELD64(MSR_BITMAP, msr_bitmap),
778 FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
779 FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
780 FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
781 FIELD64(TSC_OFFSET, tsc_offset),
782 FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
783 FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
784 FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
785 FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
786 FIELD64(EPT_POINTER, ept_pointer),
787 FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
788 FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
789 FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
790 FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
791 FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
792 FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
793 FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
794 FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
795 FIELD64(PML_ADDRESS, pml_address),
796 FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
797 FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
798 FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
799 FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
800 FIELD64(GUEST_PDPTR0, guest_pdptr0),
801 FIELD64(GUEST_PDPTR1, guest_pdptr1),
802 FIELD64(GUEST_PDPTR2, guest_pdptr2),
803 FIELD64(GUEST_PDPTR3, guest_pdptr3),
804 FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
805 FIELD64(HOST_IA32_PAT, host_ia32_pat),
806 FIELD64(HOST_IA32_EFER, host_ia32_efer),
807 FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
808 FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
809 FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
810 FIELD(EXCEPTION_BITMAP, exception_bitmap),
811 FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
812 FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
813 FIELD(CR3_TARGET_COUNT, cr3_target_count),
814 FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
815 FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
816 FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
817 FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
818 FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
819 FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
820 FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
821 FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
822 FIELD(TPR_THRESHOLD, tpr_threshold),
823 FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
824 FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
825 FIELD(VM_EXIT_REASON, vm_exit_reason),
826 FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
827 FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
828 FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
829 FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
830 FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
831 FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
832 FIELD(GUEST_ES_LIMIT, guest_es_limit),
833 FIELD(GUEST_CS_LIMIT, guest_cs_limit),
834 FIELD(GUEST_SS_LIMIT, guest_ss_limit),
835 FIELD(GUEST_DS_LIMIT, guest_ds_limit),
836 FIELD(GUEST_FS_LIMIT, guest_fs_limit),
837 FIELD(GUEST_GS_LIMIT, guest_gs_limit),
838 FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
839 FIELD(GUEST_TR_LIMIT, guest_tr_limit),
840 FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
841 FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
842 FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
843 FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
844 FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
845 FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
846 FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
847 FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
848 FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
849 FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
850 FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
851 FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
852 FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
853 FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
854 FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
855 FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
856 FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
857 FIELD(CR0_READ_SHADOW, cr0_read_shadow),
858 FIELD(CR4_READ_SHADOW, cr4_read_shadow),
859 FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
860 FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
861 FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
862 FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
863 FIELD(EXIT_QUALIFICATION, exit_qualification),
864 FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
865 FIELD(GUEST_CR0, guest_cr0),
866 FIELD(GUEST_CR3, guest_cr3),
867 FIELD(GUEST_CR4, guest_cr4),
868 FIELD(GUEST_ES_BASE, guest_es_base),
869 FIELD(GUEST_CS_BASE, guest_cs_base),
870 FIELD(GUEST_SS_BASE, guest_ss_base),
871 FIELD(GUEST_DS_BASE, guest_ds_base),
872 FIELD(GUEST_FS_BASE, guest_fs_base),
873 FIELD(GUEST_GS_BASE, guest_gs_base),
874 FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
875 FIELD(GUEST_TR_BASE, guest_tr_base),
876 FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
877 FIELD(GUEST_IDTR_BASE, guest_idtr_base),
878 FIELD(GUEST_DR7, guest_dr7),
879 FIELD(GUEST_RSP, guest_rsp),
880 FIELD(GUEST_RIP, guest_rip),
881 FIELD(GUEST_RFLAGS, guest_rflags),
882 FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
883 FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
884 FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
885 FIELD(HOST_CR0, host_cr0),
886 FIELD(HOST_CR3, host_cr3),
887 FIELD(HOST_CR4, host_cr4),
888 FIELD(HOST_FS_BASE, host_fs_base),
889 FIELD(HOST_GS_BASE, host_gs_base),
890 FIELD(HOST_TR_BASE, host_tr_base),
891 FIELD(HOST_GDTR_BASE, host_gdtr_base),
892 FIELD(HOST_IDTR_BASE, host_idtr_base),
893 FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
894 FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
895 FIELD(HOST_RSP, host_rsp),
896 FIELD(HOST_RIP, host_rip),
897 };
898
899 static inline short vmcs_field_to_offset(unsigned long field)
900 {
901 BUILD_BUG_ON(ARRAY_SIZE(vmcs_field_to_offset_table) > SHRT_MAX);
902
903 if (field >= ARRAY_SIZE(vmcs_field_to_offset_table))
904 return -ENOENT;
905
906 /*
907 * FIXME: Mitigation for CVE-2017-5753. To be replaced with a
908 * generic mechanism.
909 */
910 asm("lfence");
911
912 if (vmcs_field_to_offset_table[field] == 0)
913 return -ENOENT;
914
915 return vmcs_field_to_offset_table[field];
916 }
917
918 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
919 {
920 return to_vmx(vcpu)->nested.cached_vmcs12;
921 }
922
923 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
924 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
925 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
926 static bool vmx_xsaves_supported(void);
927 static void vmx_set_segment(struct kvm_vcpu *vcpu,
928 struct kvm_segment *var, int seg);
929 static void vmx_get_segment(struct kvm_vcpu *vcpu,
930 struct kvm_segment *var, int seg);
931 static bool guest_state_valid(struct kvm_vcpu *vcpu);
932 static u32 vmx_segment_access_rights(struct kvm_segment *var);
933 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
934 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
935 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
936 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
937 u16 error_code);
938
939 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
940 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
941 /*
942 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
943 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
944 */
945 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
946
947 /*
948 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
949 * can find which vCPU should be waken up.
950 */
951 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
952 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
953
954 enum {
955 VMX_IO_BITMAP_A,
956 VMX_IO_BITMAP_B,
957 VMX_MSR_BITMAP_LEGACY,
958 VMX_MSR_BITMAP_LONGMODE,
959 VMX_MSR_BITMAP_LEGACY_X2APIC_APICV,
960 VMX_MSR_BITMAP_LONGMODE_X2APIC_APICV,
961 VMX_MSR_BITMAP_LEGACY_X2APIC,
962 VMX_MSR_BITMAP_LONGMODE_X2APIC,
963 VMX_VMREAD_BITMAP,
964 VMX_VMWRITE_BITMAP,
965 VMX_BITMAP_NR
966 };
967
968 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
969
970 #define vmx_io_bitmap_a (vmx_bitmap[VMX_IO_BITMAP_A])
971 #define vmx_io_bitmap_b (vmx_bitmap[VMX_IO_BITMAP_B])
972 #define vmx_msr_bitmap_legacy (vmx_bitmap[VMX_MSR_BITMAP_LEGACY])
973 #define vmx_msr_bitmap_longmode (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE])
974 #define vmx_msr_bitmap_legacy_x2apic_apicv (vmx_bitmap[VMX_MSR_BITMAP_LEGACY_X2APIC_APICV])
975 #define vmx_msr_bitmap_longmode_x2apic_apicv (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE_X2APIC_APICV])
976 #define vmx_msr_bitmap_legacy_x2apic (vmx_bitmap[VMX_MSR_BITMAP_LEGACY_X2APIC])
977 #define vmx_msr_bitmap_longmode_x2apic (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE_X2APIC])
978 #define vmx_vmread_bitmap (vmx_bitmap[VMX_VMREAD_BITMAP])
979 #define vmx_vmwrite_bitmap (vmx_bitmap[VMX_VMWRITE_BITMAP])
980
981 static bool cpu_has_load_ia32_efer;
982 static bool cpu_has_load_perf_global_ctrl;
983
984 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
985 static DEFINE_SPINLOCK(vmx_vpid_lock);
986
987 static struct vmcs_config {
988 int size;
989 int order;
990 u32 basic_cap;
991 u32 revision_id;
992 u32 pin_based_exec_ctrl;
993 u32 cpu_based_exec_ctrl;
994 u32 cpu_based_2nd_exec_ctrl;
995 u32 vmexit_ctrl;
996 u32 vmentry_ctrl;
997 } vmcs_config;
998
999 static struct vmx_capability {
1000 u32 ept;
1001 u32 vpid;
1002 } vmx_capability;
1003
1004 #define VMX_SEGMENT_FIELD(seg) \
1005 [VCPU_SREG_##seg] = { \
1006 .selector = GUEST_##seg##_SELECTOR, \
1007 .base = GUEST_##seg##_BASE, \
1008 .limit = GUEST_##seg##_LIMIT, \
1009 .ar_bytes = GUEST_##seg##_AR_BYTES, \
1010 }
1011
1012 static const struct kvm_vmx_segment_field {
1013 unsigned selector;
1014 unsigned base;
1015 unsigned limit;
1016 unsigned ar_bytes;
1017 } kvm_vmx_segment_fields[] = {
1018 VMX_SEGMENT_FIELD(CS),
1019 VMX_SEGMENT_FIELD(DS),
1020 VMX_SEGMENT_FIELD(ES),
1021 VMX_SEGMENT_FIELD(FS),
1022 VMX_SEGMENT_FIELD(GS),
1023 VMX_SEGMENT_FIELD(SS),
1024 VMX_SEGMENT_FIELD(TR),
1025 VMX_SEGMENT_FIELD(LDTR),
1026 };
1027
1028 static u64 host_efer;
1029
1030 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1031
1032 /*
1033 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1034 * away by decrementing the array size.
1035 */
1036 static const u32 vmx_msr_index[] = {
1037 #ifdef CONFIG_X86_64
1038 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1039 #endif
1040 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1041 };
1042
1043 static inline bool is_exception_n(u32 intr_info, u8 vector)
1044 {
1045 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1046 INTR_INFO_VALID_MASK)) ==
1047 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1048 }
1049
1050 static inline bool is_debug(u32 intr_info)
1051 {
1052 return is_exception_n(intr_info, DB_VECTOR);
1053 }
1054
1055 static inline bool is_breakpoint(u32 intr_info)
1056 {
1057 return is_exception_n(intr_info, BP_VECTOR);
1058 }
1059
1060 static inline bool is_page_fault(u32 intr_info)
1061 {
1062 return is_exception_n(intr_info, PF_VECTOR);
1063 }
1064
1065 static inline bool is_no_device(u32 intr_info)
1066 {
1067 return is_exception_n(intr_info, NM_VECTOR);
1068 }
1069
1070 static inline bool is_invalid_opcode(u32 intr_info)
1071 {
1072 return is_exception_n(intr_info, UD_VECTOR);
1073 }
1074
1075 static inline bool is_external_interrupt(u32 intr_info)
1076 {
1077 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1078 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1079 }
1080
1081 static inline bool is_machine_check(u32 intr_info)
1082 {
1083 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1084 INTR_INFO_VALID_MASK)) ==
1085 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1086 }
1087
1088 static inline bool cpu_has_vmx_msr_bitmap(void)
1089 {
1090 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1091 }
1092
1093 static inline bool cpu_has_vmx_tpr_shadow(void)
1094 {
1095 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1096 }
1097
1098 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1099 {
1100 return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1101 }
1102
1103 static inline bool cpu_has_secondary_exec_ctrls(void)
1104 {
1105 return vmcs_config.cpu_based_exec_ctrl &
1106 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1107 }
1108
1109 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1110 {
1111 return vmcs_config.cpu_based_2nd_exec_ctrl &
1112 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1113 }
1114
1115 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1116 {
1117 return vmcs_config.cpu_based_2nd_exec_ctrl &
1118 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1119 }
1120
1121 static inline bool cpu_has_vmx_apic_register_virt(void)
1122 {
1123 return vmcs_config.cpu_based_2nd_exec_ctrl &
1124 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1125 }
1126
1127 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1128 {
1129 return vmcs_config.cpu_based_2nd_exec_ctrl &
1130 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1131 }
1132
1133 /*
1134 * Comment's format: document - errata name - stepping - processor name.
1135 * Refer from
1136 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1137 */
1138 static u32 vmx_preemption_cpu_tfms[] = {
1139 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
1140 0x000206E6,
1141 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
1142 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1143 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1144 0x00020652,
1145 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1146 0x00020655,
1147 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
1148 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
1149 /*
1150 * 320767.pdf - AAP86 - B1 -
1151 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1152 */
1153 0x000106E5,
1154 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1155 0x000106A0,
1156 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1157 0x000106A1,
1158 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1159 0x000106A4,
1160 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1161 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1162 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1163 0x000106A5,
1164 };
1165
1166 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1167 {
1168 u32 eax = cpuid_eax(0x00000001), i;
1169
1170 /* Clear the reserved bits */
1171 eax &= ~(0x3U << 14 | 0xfU << 28);
1172 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1173 if (eax == vmx_preemption_cpu_tfms[i])
1174 return true;
1175
1176 return false;
1177 }
1178
1179 static inline bool cpu_has_vmx_preemption_timer(void)
1180 {
1181 return vmcs_config.pin_based_exec_ctrl &
1182 PIN_BASED_VMX_PREEMPTION_TIMER;
1183 }
1184
1185 static inline bool cpu_has_vmx_posted_intr(void)
1186 {
1187 return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1188 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1189 }
1190
1191 static inline bool cpu_has_vmx_apicv(void)
1192 {
1193 return cpu_has_vmx_apic_register_virt() &&
1194 cpu_has_vmx_virtual_intr_delivery() &&
1195 cpu_has_vmx_posted_intr();
1196 }
1197
1198 static inline bool cpu_has_vmx_flexpriority(void)
1199 {
1200 return cpu_has_vmx_tpr_shadow() &&
1201 cpu_has_vmx_virtualize_apic_accesses();
1202 }
1203
1204 static inline bool cpu_has_vmx_ept_execute_only(void)
1205 {
1206 return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1207 }
1208
1209 static inline bool cpu_has_vmx_ept_2m_page(void)
1210 {
1211 return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1212 }
1213
1214 static inline bool cpu_has_vmx_ept_1g_page(void)
1215 {
1216 return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1217 }
1218
1219 static inline bool cpu_has_vmx_ept_4levels(void)
1220 {
1221 return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1222 }
1223
1224 static inline bool cpu_has_vmx_ept_mt_wb(void)
1225 {
1226 return vmx_capability.ept & VMX_EPTP_WB_BIT;
1227 }
1228
1229 static inline bool cpu_has_vmx_ept_5levels(void)
1230 {
1231 return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1232 }
1233
1234 static inline bool cpu_has_vmx_ept_ad_bits(void)
1235 {
1236 return vmx_capability.ept & VMX_EPT_AD_BIT;
1237 }
1238
1239 static inline bool cpu_has_vmx_invept_context(void)
1240 {
1241 return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1242 }
1243
1244 static inline bool cpu_has_vmx_invept_global(void)
1245 {
1246 return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1247 }
1248
1249 static inline bool cpu_has_vmx_invvpid_single(void)
1250 {
1251 return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1252 }
1253
1254 static inline bool cpu_has_vmx_invvpid_global(void)
1255 {
1256 return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1257 }
1258
1259 static inline bool cpu_has_vmx_invvpid(void)
1260 {
1261 return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1262 }
1263
1264 static inline bool cpu_has_vmx_ept(void)
1265 {
1266 return vmcs_config.cpu_based_2nd_exec_ctrl &
1267 SECONDARY_EXEC_ENABLE_EPT;
1268 }
1269
1270 static inline bool cpu_has_vmx_unrestricted_guest(void)
1271 {
1272 return vmcs_config.cpu_based_2nd_exec_ctrl &
1273 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1274 }
1275
1276 static inline bool cpu_has_vmx_ple(void)
1277 {
1278 return vmcs_config.cpu_based_2nd_exec_ctrl &
1279 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1280 }
1281
1282 static inline bool cpu_has_vmx_basic_inout(void)
1283 {
1284 return (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1285 }
1286
1287 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1288 {
1289 return flexpriority_enabled && lapic_in_kernel(vcpu);
1290 }
1291
1292 static inline bool cpu_has_vmx_vpid(void)
1293 {
1294 return vmcs_config.cpu_based_2nd_exec_ctrl &
1295 SECONDARY_EXEC_ENABLE_VPID;
1296 }
1297
1298 static inline bool cpu_has_vmx_rdtscp(void)
1299 {
1300 return vmcs_config.cpu_based_2nd_exec_ctrl &
1301 SECONDARY_EXEC_RDTSCP;
1302 }
1303
1304 static inline bool cpu_has_vmx_invpcid(void)
1305 {
1306 return vmcs_config.cpu_based_2nd_exec_ctrl &
1307 SECONDARY_EXEC_ENABLE_INVPCID;
1308 }
1309
1310 static inline bool cpu_has_virtual_nmis(void)
1311 {
1312 return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1313 }
1314
1315 static inline bool cpu_has_vmx_wbinvd_exit(void)
1316 {
1317 return vmcs_config.cpu_based_2nd_exec_ctrl &
1318 SECONDARY_EXEC_WBINVD_EXITING;
1319 }
1320
1321 static inline bool cpu_has_vmx_shadow_vmcs(void)
1322 {
1323 u64 vmx_msr;
1324 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1325 /* check if the cpu supports writing r/o exit information fields */
1326 if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1327 return false;
1328
1329 return vmcs_config.cpu_based_2nd_exec_ctrl &
1330 SECONDARY_EXEC_SHADOW_VMCS;
1331 }
1332
1333 static inline bool cpu_has_vmx_pml(void)
1334 {
1335 return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1336 }
1337
1338 static inline bool cpu_has_vmx_tsc_scaling(void)
1339 {
1340 return vmcs_config.cpu_based_2nd_exec_ctrl &
1341 SECONDARY_EXEC_TSC_SCALING;
1342 }
1343
1344 static inline bool cpu_has_vmx_vmfunc(void)
1345 {
1346 return vmcs_config.cpu_based_2nd_exec_ctrl &
1347 SECONDARY_EXEC_ENABLE_VMFUNC;
1348 }
1349
1350 static inline bool report_flexpriority(void)
1351 {
1352 return flexpriority_enabled;
1353 }
1354
1355 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1356 {
1357 return vmx_misc_cr3_count(to_vmx(vcpu)->nested.nested_vmx_misc_low);
1358 }
1359
1360 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1361 {
1362 return vmcs12->cpu_based_vm_exec_control & bit;
1363 }
1364
1365 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1366 {
1367 return (vmcs12->cpu_based_vm_exec_control &
1368 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1369 (vmcs12->secondary_vm_exec_control & bit);
1370 }
1371
1372 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1373 {
1374 return vmcs12->pin_based_vm_exec_control &
1375 PIN_BASED_VMX_PREEMPTION_TIMER;
1376 }
1377
1378 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1379 {
1380 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1381 }
1382
1383 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1384 {
1385 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
1386 }
1387
1388 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
1389 {
1390 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
1391 }
1392
1393 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1394 {
1395 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1396 }
1397
1398 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1399 {
1400 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1401 }
1402
1403 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1404 {
1405 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1406 }
1407
1408 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1409 {
1410 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1411 }
1412
1413 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1414 {
1415 return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1416 }
1417
1418 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
1419 {
1420 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
1421 }
1422
1423 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
1424 {
1425 return nested_cpu_has_vmfunc(vmcs12) &&
1426 (vmcs12->vm_function_control &
1427 VMX_VMFUNC_EPTP_SWITCHING);
1428 }
1429
1430 static inline bool is_nmi(u32 intr_info)
1431 {
1432 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1433 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1434 }
1435
1436 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1437 u32 exit_intr_info,
1438 unsigned long exit_qualification);
1439 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1440 struct vmcs12 *vmcs12,
1441 u32 reason, unsigned long qualification);
1442
1443 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1444 {
1445 int i;
1446
1447 for (i = 0; i < vmx->nmsrs; ++i)
1448 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1449 return i;
1450 return -1;
1451 }
1452
1453 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1454 {
1455 struct {
1456 u64 vpid : 16;
1457 u64 rsvd : 48;
1458 u64 gva;
1459 } operand = { vpid, 0, gva };
1460
1461 asm volatile (__ex(ASM_VMX_INVVPID)
1462 /* CF==1 or ZF==1 --> rc = -1 */
1463 "; ja 1f ; ud2 ; 1:"
1464 : : "a"(&operand), "c"(ext) : "cc", "memory");
1465 }
1466
1467 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1468 {
1469 struct {
1470 u64 eptp, gpa;
1471 } operand = {eptp, gpa};
1472
1473 asm volatile (__ex(ASM_VMX_INVEPT)
1474 /* CF==1 or ZF==1 --> rc = -1 */
1475 "; ja 1f ; ud2 ; 1:\n"
1476 : : "a" (&operand), "c" (ext) : "cc", "memory");
1477 }
1478
1479 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1480 {
1481 int i;
1482
1483 i = __find_msr_index(vmx, msr);
1484 if (i >= 0)
1485 return &vmx->guest_msrs[i];
1486 return NULL;
1487 }
1488
1489 static void vmcs_clear(struct vmcs *vmcs)
1490 {
1491 u64 phys_addr = __pa(vmcs);
1492 u8 error;
1493
1494 asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1495 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1496 : "cc", "memory");
1497 if (error)
1498 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1499 vmcs, phys_addr);
1500 }
1501
1502 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1503 {
1504 vmcs_clear(loaded_vmcs->vmcs);
1505 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1506 vmcs_clear(loaded_vmcs->shadow_vmcs);
1507 loaded_vmcs->cpu = -1;
1508 loaded_vmcs->launched = 0;
1509 }
1510
1511 static void vmcs_load(struct vmcs *vmcs)
1512 {
1513 u64 phys_addr = __pa(vmcs);
1514 u8 error;
1515
1516 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1517 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1518 : "cc", "memory");
1519 if (error)
1520 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1521 vmcs, phys_addr);
1522 }
1523
1524 #ifdef CONFIG_KEXEC_CORE
1525 /*
1526 * This bitmap is used to indicate whether the vmclear
1527 * operation is enabled on all cpus. All disabled by
1528 * default.
1529 */
1530 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1531
1532 static inline void crash_enable_local_vmclear(int cpu)
1533 {
1534 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1535 }
1536
1537 static inline void crash_disable_local_vmclear(int cpu)
1538 {
1539 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1540 }
1541
1542 static inline int crash_local_vmclear_enabled(int cpu)
1543 {
1544 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1545 }
1546
1547 static void crash_vmclear_local_loaded_vmcss(void)
1548 {
1549 int cpu = raw_smp_processor_id();
1550 struct loaded_vmcs *v;
1551
1552 if (!crash_local_vmclear_enabled(cpu))
1553 return;
1554
1555 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1556 loaded_vmcss_on_cpu_link)
1557 vmcs_clear(v->vmcs);
1558 }
1559 #else
1560 static inline void crash_enable_local_vmclear(int cpu) { }
1561 static inline void crash_disable_local_vmclear(int cpu) { }
1562 #endif /* CONFIG_KEXEC_CORE */
1563
1564 static void __loaded_vmcs_clear(void *arg)
1565 {
1566 struct loaded_vmcs *loaded_vmcs = arg;
1567 int cpu = raw_smp_processor_id();
1568
1569 if (loaded_vmcs->cpu != cpu)
1570 return; /* vcpu migration can race with cpu offline */
1571 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1572 per_cpu(current_vmcs, cpu) = NULL;
1573 crash_disable_local_vmclear(cpu);
1574 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1575
1576 /*
1577 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1578 * is before setting loaded_vmcs->vcpu to -1 which is done in
1579 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1580 * then adds the vmcs into percpu list before it is deleted.
1581 */
1582 smp_wmb();
1583
1584 loaded_vmcs_init(loaded_vmcs);
1585 crash_enable_local_vmclear(cpu);
1586 }
1587
1588 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1589 {
1590 int cpu = loaded_vmcs->cpu;
1591
1592 if (cpu != -1)
1593 smp_call_function_single(cpu,
1594 __loaded_vmcs_clear, loaded_vmcs, 1);
1595 }
1596
1597 static inline void vpid_sync_vcpu_single(int vpid)
1598 {
1599 if (vpid == 0)
1600 return;
1601
1602 if (cpu_has_vmx_invvpid_single())
1603 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
1604 }
1605
1606 static inline void vpid_sync_vcpu_global(void)
1607 {
1608 if (cpu_has_vmx_invvpid_global())
1609 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1610 }
1611
1612 static inline void vpid_sync_context(int vpid)
1613 {
1614 if (cpu_has_vmx_invvpid_single())
1615 vpid_sync_vcpu_single(vpid);
1616 else
1617 vpid_sync_vcpu_global();
1618 }
1619
1620 static inline void ept_sync_global(void)
1621 {
1622 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1623 }
1624
1625 static inline void ept_sync_context(u64 eptp)
1626 {
1627 if (cpu_has_vmx_invept_context())
1628 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1629 else
1630 ept_sync_global();
1631 }
1632
1633 static __always_inline void vmcs_check16(unsigned long field)
1634 {
1635 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1636 "16-bit accessor invalid for 64-bit field");
1637 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1638 "16-bit accessor invalid for 64-bit high field");
1639 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1640 "16-bit accessor invalid for 32-bit high field");
1641 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1642 "16-bit accessor invalid for natural width field");
1643 }
1644
1645 static __always_inline void vmcs_check32(unsigned long field)
1646 {
1647 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1648 "32-bit accessor invalid for 16-bit field");
1649 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1650 "32-bit accessor invalid for natural width field");
1651 }
1652
1653 static __always_inline void vmcs_check64(unsigned long field)
1654 {
1655 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1656 "64-bit accessor invalid for 16-bit field");
1657 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1658 "64-bit accessor invalid for 64-bit high field");
1659 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1660 "64-bit accessor invalid for 32-bit field");
1661 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1662 "64-bit accessor invalid for natural width field");
1663 }
1664
1665 static __always_inline void vmcs_checkl(unsigned long field)
1666 {
1667 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1668 "Natural width accessor invalid for 16-bit field");
1669 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1670 "Natural width accessor invalid for 64-bit field");
1671 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1672 "Natural width accessor invalid for 64-bit high field");
1673 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1674 "Natural width accessor invalid for 32-bit field");
1675 }
1676
1677 static __always_inline unsigned long __vmcs_readl(unsigned long field)
1678 {
1679 unsigned long value;
1680
1681 asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1682 : "=a"(value) : "d"(field) : "cc");
1683 return value;
1684 }
1685
1686 static __always_inline u16 vmcs_read16(unsigned long field)
1687 {
1688 vmcs_check16(field);
1689 return __vmcs_readl(field);
1690 }
1691
1692 static __always_inline u32 vmcs_read32(unsigned long field)
1693 {
1694 vmcs_check32(field);
1695 return __vmcs_readl(field);
1696 }
1697
1698 static __always_inline u64 vmcs_read64(unsigned long field)
1699 {
1700 vmcs_check64(field);
1701 #ifdef CONFIG_X86_64
1702 return __vmcs_readl(field);
1703 #else
1704 return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
1705 #endif
1706 }
1707
1708 static __always_inline unsigned long vmcs_readl(unsigned long field)
1709 {
1710 vmcs_checkl(field);
1711 return __vmcs_readl(field);
1712 }
1713
1714 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1715 {
1716 printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1717 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1718 dump_stack();
1719 }
1720
1721 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
1722 {
1723 u8 error;
1724
1725 asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1726 : "=q"(error) : "a"(value), "d"(field) : "cc");
1727 if (unlikely(error))
1728 vmwrite_error(field, value);
1729 }
1730
1731 static __always_inline void vmcs_write16(unsigned long field, u16 value)
1732 {
1733 vmcs_check16(field);
1734 __vmcs_writel(field, value);
1735 }
1736
1737 static __always_inline void vmcs_write32(unsigned long field, u32 value)
1738 {
1739 vmcs_check32(field);
1740 __vmcs_writel(field, value);
1741 }
1742
1743 static __always_inline void vmcs_write64(unsigned long field, u64 value)
1744 {
1745 vmcs_check64(field);
1746 __vmcs_writel(field, value);
1747 #ifndef CONFIG_X86_64
1748 asm volatile ("");
1749 __vmcs_writel(field+1, value >> 32);
1750 #endif
1751 }
1752
1753 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
1754 {
1755 vmcs_checkl(field);
1756 __vmcs_writel(field, value);
1757 }
1758
1759 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
1760 {
1761 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1762 "vmcs_clear_bits does not support 64-bit fields");
1763 __vmcs_writel(field, __vmcs_readl(field) & ~mask);
1764 }
1765
1766 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
1767 {
1768 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1769 "vmcs_set_bits does not support 64-bit fields");
1770 __vmcs_writel(field, __vmcs_readl(field) | mask);
1771 }
1772
1773 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
1774 {
1775 vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
1776 }
1777
1778 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1779 {
1780 vmcs_write32(VM_ENTRY_CONTROLS, val);
1781 vmx->vm_entry_controls_shadow = val;
1782 }
1783
1784 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1785 {
1786 if (vmx->vm_entry_controls_shadow != val)
1787 vm_entry_controls_init(vmx, val);
1788 }
1789
1790 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1791 {
1792 return vmx->vm_entry_controls_shadow;
1793 }
1794
1795
1796 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1797 {
1798 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1799 }
1800
1801 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1802 {
1803 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1804 }
1805
1806 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
1807 {
1808 vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
1809 }
1810
1811 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1812 {
1813 vmcs_write32(VM_EXIT_CONTROLS, val);
1814 vmx->vm_exit_controls_shadow = val;
1815 }
1816
1817 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1818 {
1819 if (vmx->vm_exit_controls_shadow != val)
1820 vm_exit_controls_init(vmx, val);
1821 }
1822
1823 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1824 {
1825 return vmx->vm_exit_controls_shadow;
1826 }
1827
1828
1829 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1830 {
1831 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1832 }
1833
1834 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1835 {
1836 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1837 }
1838
1839 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1840 {
1841 vmx->segment_cache.bitmask = 0;
1842 }
1843
1844 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1845 unsigned field)
1846 {
1847 bool ret;
1848 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1849
1850 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1851 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1852 vmx->segment_cache.bitmask = 0;
1853 }
1854 ret = vmx->segment_cache.bitmask & mask;
1855 vmx->segment_cache.bitmask |= mask;
1856 return ret;
1857 }
1858
1859 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1860 {
1861 u16 *p = &vmx->segment_cache.seg[seg].selector;
1862
1863 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1864 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1865 return *p;
1866 }
1867
1868 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1869 {
1870 ulong *p = &vmx->segment_cache.seg[seg].base;
1871
1872 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1873 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1874 return *p;
1875 }
1876
1877 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1878 {
1879 u32 *p = &vmx->segment_cache.seg[seg].limit;
1880
1881 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1882 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1883 return *p;
1884 }
1885
1886 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1887 {
1888 u32 *p = &vmx->segment_cache.seg[seg].ar;
1889
1890 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1891 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1892 return *p;
1893 }
1894
1895 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1896 {
1897 u32 eb;
1898
1899 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1900 (1u << DB_VECTOR) | (1u << AC_VECTOR);
1901 if ((vcpu->guest_debug &
1902 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1903 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1904 eb |= 1u << BP_VECTOR;
1905 if (to_vmx(vcpu)->rmode.vm86_active)
1906 eb = ~0;
1907 if (enable_ept)
1908 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1909
1910 /* When we are running a nested L2 guest and L1 specified for it a
1911 * certain exception bitmap, we must trap the same exceptions and pass
1912 * them to L1. When running L2, we will only handle the exceptions
1913 * specified above if L1 did not want them.
1914 */
1915 if (is_guest_mode(vcpu))
1916 eb |= get_vmcs12(vcpu)->exception_bitmap;
1917
1918 vmcs_write32(EXCEPTION_BITMAP, eb);
1919 }
1920
1921 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1922 unsigned long entry, unsigned long exit)
1923 {
1924 vm_entry_controls_clearbit(vmx, entry);
1925 vm_exit_controls_clearbit(vmx, exit);
1926 }
1927
1928 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1929 {
1930 unsigned i;
1931 struct msr_autoload *m = &vmx->msr_autoload;
1932
1933 switch (msr) {
1934 case MSR_EFER:
1935 if (cpu_has_load_ia32_efer) {
1936 clear_atomic_switch_msr_special(vmx,
1937 VM_ENTRY_LOAD_IA32_EFER,
1938 VM_EXIT_LOAD_IA32_EFER);
1939 return;
1940 }
1941 break;
1942 case MSR_CORE_PERF_GLOBAL_CTRL:
1943 if (cpu_has_load_perf_global_ctrl) {
1944 clear_atomic_switch_msr_special(vmx,
1945 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1946 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1947 return;
1948 }
1949 break;
1950 }
1951
1952 for (i = 0; i < m->nr; ++i)
1953 if (m->guest[i].index == msr)
1954 break;
1955
1956 if (i == m->nr)
1957 return;
1958 --m->nr;
1959 m->guest[i] = m->guest[m->nr];
1960 m->host[i] = m->host[m->nr];
1961 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1962 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1963 }
1964
1965 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1966 unsigned long entry, unsigned long exit,
1967 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
1968 u64 guest_val, u64 host_val)
1969 {
1970 vmcs_write64(guest_val_vmcs, guest_val);
1971 vmcs_write64(host_val_vmcs, host_val);
1972 vm_entry_controls_setbit(vmx, entry);
1973 vm_exit_controls_setbit(vmx, exit);
1974 }
1975
1976 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1977 u64 guest_val, u64 host_val)
1978 {
1979 unsigned i;
1980 struct msr_autoload *m = &vmx->msr_autoload;
1981
1982 switch (msr) {
1983 case MSR_EFER:
1984 if (cpu_has_load_ia32_efer) {
1985 add_atomic_switch_msr_special(vmx,
1986 VM_ENTRY_LOAD_IA32_EFER,
1987 VM_EXIT_LOAD_IA32_EFER,
1988 GUEST_IA32_EFER,
1989 HOST_IA32_EFER,
1990 guest_val, host_val);
1991 return;
1992 }
1993 break;
1994 case MSR_CORE_PERF_GLOBAL_CTRL:
1995 if (cpu_has_load_perf_global_ctrl) {
1996 add_atomic_switch_msr_special(vmx,
1997 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1998 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1999 GUEST_IA32_PERF_GLOBAL_CTRL,
2000 HOST_IA32_PERF_GLOBAL_CTRL,
2001 guest_val, host_val);
2002 return;
2003 }
2004 break;
2005 case MSR_IA32_PEBS_ENABLE:
2006 /* PEBS needs a quiescent period after being disabled (to write
2007 * a record). Disabling PEBS through VMX MSR swapping doesn't
2008 * provide that period, so a CPU could write host's record into
2009 * guest's memory.
2010 */
2011 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2012 }
2013
2014 for (i = 0; i < m->nr; ++i)
2015 if (m->guest[i].index == msr)
2016 break;
2017
2018 if (i == NR_AUTOLOAD_MSRS) {
2019 printk_once(KERN_WARNING "Not enough msr switch entries. "
2020 "Can't add msr %x\n", msr);
2021 return;
2022 } else if (i == m->nr) {
2023 ++m->nr;
2024 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
2025 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
2026 }
2027
2028 m->guest[i].index = msr;
2029 m->guest[i].value = guest_val;
2030 m->host[i].index = msr;
2031 m->host[i].value = host_val;
2032 }
2033
2034 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2035 {
2036 u64 guest_efer = vmx->vcpu.arch.efer;
2037 u64 ignore_bits = 0;
2038
2039 if (!enable_ept) {
2040 /*
2041 * NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
2042 * host CPUID is more efficient than testing guest CPUID
2043 * or CR4. Host SMEP is anyway a requirement for guest SMEP.
2044 */
2045 if (boot_cpu_has(X86_FEATURE_SMEP))
2046 guest_efer |= EFER_NX;
2047 else if (!(guest_efer & EFER_NX))
2048 ignore_bits |= EFER_NX;
2049 }
2050
2051 /*
2052 * LMA and LME handled by hardware; SCE meaningless outside long mode.
2053 */
2054 ignore_bits |= EFER_SCE;
2055 #ifdef CONFIG_X86_64
2056 ignore_bits |= EFER_LMA | EFER_LME;
2057 /* SCE is meaningful only in long mode on Intel */
2058 if (guest_efer & EFER_LMA)
2059 ignore_bits &= ~(u64)EFER_SCE;
2060 #endif
2061
2062 clear_atomic_switch_msr(vmx, MSR_EFER);
2063
2064 /*
2065 * On EPT, we can't emulate NX, so we must switch EFER atomically.
2066 * On CPUs that support "load IA32_EFER", always switch EFER
2067 * atomically, since it's faster than switching it manually.
2068 */
2069 if (cpu_has_load_ia32_efer ||
2070 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2071 if (!(guest_efer & EFER_LMA))
2072 guest_efer &= ~EFER_LME;
2073 if (guest_efer != host_efer)
2074 add_atomic_switch_msr(vmx, MSR_EFER,
2075 guest_efer, host_efer);
2076 return false;
2077 } else {
2078 guest_efer &= ~ignore_bits;
2079 guest_efer |= host_efer & ignore_bits;
2080
2081 vmx->guest_msrs[efer_offset].data = guest_efer;
2082 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2083
2084 return true;
2085 }
2086 }
2087
2088 #ifdef CONFIG_X86_32
2089 /*
2090 * On 32-bit kernels, VM exits still load the FS and GS bases from the
2091 * VMCS rather than the segment table. KVM uses this helper to figure
2092 * out the current bases to poke them into the VMCS before entry.
2093 */
2094 static unsigned long segment_base(u16 selector)
2095 {
2096 struct desc_struct *table;
2097 unsigned long v;
2098
2099 if (!(selector & ~SEGMENT_RPL_MASK))
2100 return 0;
2101
2102 table = get_current_gdt_ro();
2103
2104 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2105 u16 ldt_selector = kvm_read_ldt();
2106
2107 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2108 return 0;
2109
2110 table = (struct desc_struct *)segment_base(ldt_selector);
2111 }
2112 v = get_desc_base(&table[selector >> 3]);
2113 return v;
2114 }
2115 #endif
2116
2117 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
2118 {
2119 struct vcpu_vmx *vmx = to_vmx(vcpu);
2120 int i;
2121
2122 if (vmx->host_state.loaded)
2123 return;
2124
2125 vmx->host_state.loaded = 1;
2126 /*
2127 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
2128 * allow segment selectors with cpl > 0 or ti == 1.
2129 */
2130 vmx->host_state.ldt_sel = kvm_read_ldt();
2131 vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
2132 savesegment(fs, vmx->host_state.fs_sel);
2133 if (!(vmx->host_state.fs_sel & 7)) {
2134 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
2135 vmx->host_state.fs_reload_needed = 0;
2136 } else {
2137 vmcs_write16(HOST_FS_SELECTOR, 0);
2138 vmx->host_state.fs_reload_needed = 1;
2139 }
2140 savesegment(gs, vmx->host_state.gs_sel);
2141 if (!(vmx->host_state.gs_sel & 7))
2142 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
2143 else {
2144 vmcs_write16(HOST_GS_SELECTOR, 0);
2145 vmx->host_state.gs_ldt_reload_needed = 1;
2146 }
2147
2148 #ifdef CONFIG_X86_64
2149 savesegment(ds, vmx->host_state.ds_sel);
2150 savesegment(es, vmx->host_state.es_sel);
2151 #endif
2152
2153 #ifdef CONFIG_X86_64
2154 vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
2155 vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
2156 #else
2157 vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
2158 vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
2159 #endif
2160
2161 #ifdef CONFIG_X86_64
2162 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2163 if (is_long_mode(&vmx->vcpu))
2164 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2165 #endif
2166 if (boot_cpu_has(X86_FEATURE_MPX))
2167 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2168 for (i = 0; i < vmx->save_nmsrs; ++i)
2169 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2170 vmx->guest_msrs[i].data,
2171 vmx->guest_msrs[i].mask);
2172 }
2173
2174 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
2175 {
2176 if (!vmx->host_state.loaded)
2177 return;
2178
2179 ++vmx->vcpu.stat.host_state_reload;
2180 vmx->host_state.loaded = 0;
2181 #ifdef CONFIG_X86_64
2182 if (is_long_mode(&vmx->vcpu))
2183 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2184 #endif
2185 if (vmx->host_state.gs_ldt_reload_needed) {
2186 kvm_load_ldt(vmx->host_state.ldt_sel);
2187 #ifdef CONFIG_X86_64
2188 load_gs_index(vmx->host_state.gs_sel);
2189 #else
2190 loadsegment(gs, vmx->host_state.gs_sel);
2191 #endif
2192 }
2193 if (vmx->host_state.fs_reload_needed)
2194 loadsegment(fs, vmx->host_state.fs_sel);
2195 #ifdef CONFIG_X86_64
2196 if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
2197 loadsegment(ds, vmx->host_state.ds_sel);
2198 loadsegment(es, vmx->host_state.es_sel);
2199 }
2200 #endif
2201 invalidate_tss_limit();
2202 #ifdef CONFIG_X86_64
2203 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2204 #endif
2205 if (vmx->host_state.msr_host_bndcfgs)
2206 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2207 load_fixmap_gdt(raw_smp_processor_id());
2208 }
2209
2210 static void vmx_load_host_state(struct vcpu_vmx *vmx)
2211 {
2212 preempt_disable();
2213 __vmx_load_host_state(vmx);
2214 preempt_enable();
2215 }
2216
2217 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2218 {
2219 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2220 struct pi_desc old, new;
2221 unsigned int dest;
2222
2223 /*
2224 * In case of hot-plug or hot-unplug, we may have to undo
2225 * vmx_vcpu_pi_put even if there is no assigned device. And we
2226 * always keep PI.NDST up to date for simplicity: it makes the
2227 * code easier, and CPU migration is not a fast path.
2228 */
2229 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
2230 return;
2231
2232 /*
2233 * First handle the simple case where no cmpxchg is necessary; just
2234 * allow posting non-urgent interrupts.
2235 *
2236 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
2237 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
2238 * expects the VCPU to be on the blocked_vcpu_list that matches
2239 * PI.NDST.
2240 */
2241 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
2242 vcpu->cpu == cpu) {
2243 pi_clear_sn(pi_desc);
2244 return;
2245 }
2246
2247 /* The full case. */
2248 do {
2249 old.control = new.control = pi_desc->control;
2250
2251 dest = cpu_physical_id(cpu);
2252
2253 if (x2apic_enabled())
2254 new.ndst = dest;
2255 else
2256 new.ndst = (dest << 8) & 0xFF00;
2257
2258 new.sn = 0;
2259 } while (cmpxchg64(&pi_desc->control, old.control,
2260 new.control) != old.control);
2261 }
2262
2263 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2264 {
2265 vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2266 vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2267 }
2268
2269 /*
2270 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2271 * vcpu mutex is already taken.
2272 */
2273 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2274 {
2275 struct vcpu_vmx *vmx = to_vmx(vcpu);
2276 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2277
2278 if (!already_loaded) {
2279 loaded_vmcs_clear(vmx->loaded_vmcs);
2280 local_irq_disable();
2281 crash_disable_local_vmclear(cpu);
2282
2283 /*
2284 * Read loaded_vmcs->cpu should be before fetching
2285 * loaded_vmcs->loaded_vmcss_on_cpu_link.
2286 * See the comments in __loaded_vmcs_clear().
2287 */
2288 smp_rmb();
2289
2290 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2291 &per_cpu(loaded_vmcss_on_cpu, cpu));
2292 crash_enable_local_vmclear(cpu);
2293 local_irq_enable();
2294 }
2295
2296 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2297 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2298 vmcs_load(vmx->loaded_vmcs->vmcs);
2299 }
2300
2301 if (!already_loaded) {
2302 void *gdt = get_current_gdt_ro();
2303 unsigned long sysenter_esp;
2304
2305 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2306
2307 /*
2308 * Linux uses per-cpu TSS and GDT, so set these when switching
2309 * processors. See 22.2.4.
2310 */
2311 vmcs_writel(HOST_TR_BASE,
2312 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
2313 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
2314
2315 /*
2316 * VM exits change the host TR limit to 0x67 after a VM
2317 * exit. This is okay, since 0x67 covers everything except
2318 * the IO bitmap and have have code to handle the IO bitmap
2319 * being lost after a VM exit.
2320 */
2321 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
2322
2323 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2324 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2325
2326 vmx->loaded_vmcs->cpu = cpu;
2327 }
2328
2329 /* Setup TSC multiplier */
2330 if (kvm_has_tsc_control &&
2331 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2332 decache_tsc_multiplier(vmx);
2333
2334 vmx_vcpu_pi_load(vcpu, cpu);
2335 vmx->host_pkru = read_pkru();
2336 }
2337
2338 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2339 {
2340 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2341
2342 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2343 !irq_remapping_cap(IRQ_POSTING_CAP) ||
2344 !kvm_vcpu_apicv_active(vcpu))
2345 return;
2346
2347 /* Set SN when the vCPU is preempted */
2348 if (vcpu->preempted)
2349 pi_set_sn(pi_desc);
2350 }
2351
2352 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2353 {
2354 vmx_vcpu_pi_put(vcpu);
2355
2356 __vmx_load_host_state(to_vmx(vcpu));
2357 }
2358
2359 static bool emulation_required(struct kvm_vcpu *vcpu)
2360 {
2361 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
2362 }
2363
2364 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
2365
2366 /*
2367 * Return the cr0 value that a nested guest would read. This is a combination
2368 * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
2369 * its hypervisor (cr0_read_shadow).
2370 */
2371 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
2372 {
2373 return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
2374 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
2375 }
2376 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
2377 {
2378 return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
2379 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
2380 }
2381
2382 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2383 {
2384 unsigned long rflags, save_rflags;
2385
2386 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2387 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2388 rflags = vmcs_readl(GUEST_RFLAGS);
2389 if (to_vmx(vcpu)->rmode.vm86_active) {
2390 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2391 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2392 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2393 }
2394 to_vmx(vcpu)->rflags = rflags;
2395 }
2396 return to_vmx(vcpu)->rflags;
2397 }
2398
2399 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2400 {
2401 unsigned long old_rflags = vmx_get_rflags(vcpu);
2402
2403 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2404 to_vmx(vcpu)->rflags = rflags;
2405 if (to_vmx(vcpu)->rmode.vm86_active) {
2406 to_vmx(vcpu)->rmode.save_rflags = rflags;
2407 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2408 }
2409 vmcs_writel(GUEST_RFLAGS, rflags);
2410
2411 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
2412 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
2413 }
2414
2415 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2416 {
2417 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2418 int ret = 0;
2419
2420 if (interruptibility & GUEST_INTR_STATE_STI)
2421 ret |= KVM_X86_SHADOW_INT_STI;
2422 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2423 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2424
2425 return ret;
2426 }
2427
2428 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2429 {
2430 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2431 u32 interruptibility = interruptibility_old;
2432
2433 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2434
2435 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2436 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2437 else if (mask & KVM_X86_SHADOW_INT_STI)
2438 interruptibility |= GUEST_INTR_STATE_STI;
2439
2440 if ((interruptibility != interruptibility_old))
2441 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2442 }
2443
2444 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2445 {
2446 unsigned long rip;
2447
2448 rip = kvm_rip_read(vcpu);
2449 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2450 kvm_rip_write(vcpu, rip);
2451
2452 /* skipping an emulated instruction also counts */
2453 vmx_set_interrupt_shadow(vcpu, 0);
2454 }
2455
2456 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
2457 unsigned long exit_qual)
2458 {
2459 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2460 unsigned int nr = vcpu->arch.exception.nr;
2461 u32 intr_info = nr | INTR_INFO_VALID_MASK;
2462
2463 if (vcpu->arch.exception.has_error_code) {
2464 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
2465 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2466 }
2467
2468 if (kvm_exception_is_soft(nr))
2469 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2470 else
2471 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2472
2473 if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
2474 vmx_get_nmi_mask(vcpu))
2475 intr_info |= INTR_INFO_UNBLOCK_NMI;
2476
2477 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
2478 }
2479
2480 /*
2481 * KVM wants to inject page-faults which it got to the guest. This function
2482 * checks whether in a nested guest, we need to inject them to L1 or L2.
2483 */
2484 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
2485 {
2486 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2487 unsigned int nr = vcpu->arch.exception.nr;
2488
2489 if (nr == PF_VECTOR) {
2490 if (vcpu->arch.exception.nested_apf) {
2491 *exit_qual = vcpu->arch.apf.nested_apf_token;
2492 return 1;
2493 }
2494 /*
2495 * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
2496 * The fix is to add the ancillary datum (CR2 or DR6) to structs
2497 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
2498 * can be written only when inject_pending_event runs. This should be
2499 * conditional on a new capability---if the capability is disabled,
2500 * kvm_multiple_exception would write the ancillary information to
2501 * CR2 or DR6, for backwards ABI-compatibility.
2502 */
2503 if (nested_vmx_is_page_fault_vmexit(vmcs12,
2504 vcpu->arch.exception.error_code)) {
2505 *exit_qual = vcpu->arch.cr2;
2506 return 1;
2507 }
2508 } else {
2509 if (vmcs12->exception_bitmap & (1u << nr)) {
2510 if (nr == DB_VECTOR)
2511 *exit_qual = vcpu->arch.dr6;
2512 else
2513 *exit_qual = 0;
2514 return 1;
2515 }
2516 }
2517
2518 return 0;
2519 }
2520
2521 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
2522 {
2523 struct vcpu_vmx *vmx = to_vmx(vcpu);
2524 unsigned nr = vcpu->arch.exception.nr;
2525 bool has_error_code = vcpu->arch.exception.has_error_code;
2526 u32 error_code = vcpu->arch.exception.error_code;
2527 u32 intr_info = nr | INTR_INFO_VALID_MASK;
2528
2529 if (has_error_code) {
2530 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2531 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2532 }
2533
2534 if (vmx->rmode.vm86_active) {
2535 int inc_eip = 0;
2536 if (kvm_exception_is_soft(nr))
2537 inc_eip = vcpu->arch.event_exit_inst_len;
2538 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2539 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2540 return;
2541 }
2542
2543 if (kvm_exception_is_soft(nr)) {
2544 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2545 vmx->vcpu.arch.event_exit_inst_len);
2546 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2547 } else
2548 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2549
2550 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2551 }
2552
2553 static bool vmx_rdtscp_supported(void)
2554 {
2555 return cpu_has_vmx_rdtscp();
2556 }
2557
2558 static bool vmx_invpcid_supported(void)
2559 {
2560 return cpu_has_vmx_invpcid() && enable_ept;
2561 }
2562
2563 /*
2564 * Swap MSR entry in host/guest MSR entry array.
2565 */
2566 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2567 {
2568 struct shared_msr_entry tmp;
2569
2570 tmp = vmx->guest_msrs[to];
2571 vmx->guest_msrs[to] = vmx->guest_msrs[from];
2572 vmx->guest_msrs[from] = tmp;
2573 }
2574
2575 static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
2576 {
2577 unsigned long *msr_bitmap;
2578
2579 if (is_guest_mode(vcpu))
2580 msr_bitmap = to_vmx(vcpu)->nested.msr_bitmap;
2581 else if (cpu_has_secondary_exec_ctrls() &&
2582 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
2583 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
2584 if (enable_apicv && kvm_vcpu_apicv_active(vcpu)) {
2585 if (is_long_mode(vcpu))
2586 msr_bitmap = vmx_msr_bitmap_longmode_x2apic_apicv;
2587 else
2588 msr_bitmap = vmx_msr_bitmap_legacy_x2apic_apicv;
2589 } else {
2590 if (is_long_mode(vcpu))
2591 msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
2592 else
2593 msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
2594 }
2595 } else {
2596 if (is_long_mode(vcpu))
2597 msr_bitmap = vmx_msr_bitmap_longmode;
2598 else
2599 msr_bitmap = vmx_msr_bitmap_legacy;
2600 }
2601
2602 vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
2603 }
2604
2605 /*
2606 * Set up the vmcs to automatically save and restore system
2607 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
2608 * mode, as fiddling with msrs is very expensive.
2609 */
2610 static void setup_msrs(struct vcpu_vmx *vmx)
2611 {
2612 int save_nmsrs, index;
2613
2614 save_nmsrs = 0;
2615 #ifdef CONFIG_X86_64
2616 if (is_long_mode(&vmx->vcpu)) {
2617 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2618 if (index >= 0)
2619 move_msr_up(vmx, index, save_nmsrs++);
2620 index = __find_msr_index(vmx, MSR_LSTAR);
2621 if (index >= 0)
2622 move_msr_up(vmx, index, save_nmsrs++);
2623 index = __find_msr_index(vmx, MSR_CSTAR);
2624 if (index >= 0)
2625 move_msr_up(vmx, index, save_nmsrs++);
2626 index = __find_msr_index(vmx, MSR_TSC_AUX);
2627 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
2628 move_msr_up(vmx, index, save_nmsrs++);
2629 /*
2630 * MSR_STAR is only needed on long mode guests, and only
2631 * if efer.sce is enabled.
2632 */
2633 index = __find_msr_index(vmx, MSR_STAR);
2634 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2635 move_msr_up(vmx, index, save_nmsrs++);
2636 }
2637 #endif
2638 index = __find_msr_index(vmx, MSR_EFER);
2639 if (index >= 0 && update_transition_efer(vmx, index))
2640 move_msr_up(vmx, index, save_nmsrs++);
2641
2642 vmx->save_nmsrs = save_nmsrs;
2643
2644 if (cpu_has_vmx_msr_bitmap())
2645 vmx_set_msr_bitmap(&vmx->vcpu);
2646 }
2647
2648 /*
2649 * reads and returns guest's timestamp counter "register"
2650 * guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
2651 * -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
2652 */
2653 static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
2654 {
2655 u64 host_tsc, tsc_offset;
2656
2657 host_tsc = rdtsc();
2658 tsc_offset = vmcs_read64(TSC_OFFSET);
2659 return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
2660 }
2661
2662 /*
2663 * writes 'offset' into guest's timestamp counter offset register
2664 */
2665 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2666 {
2667 if (is_guest_mode(vcpu)) {
2668 /*
2669 * We're here if L1 chose not to trap WRMSR to TSC. According
2670 * to the spec, this should set L1's TSC; The offset that L1
2671 * set for L2 remains unchanged, and still needs to be added
2672 * to the newly set TSC to get L2's TSC.
2673 */
2674 struct vmcs12 *vmcs12;
2675 /* recalculate vmcs02.TSC_OFFSET: */
2676 vmcs12 = get_vmcs12(vcpu);
2677 vmcs_write64(TSC_OFFSET, offset +
2678 (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2679 vmcs12->tsc_offset : 0));
2680 } else {
2681 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2682 vmcs_read64(TSC_OFFSET), offset);
2683 vmcs_write64(TSC_OFFSET, offset);
2684 }
2685 }
2686
2687 /*
2688 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2689 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2690 * all guests if the "nested" module option is off, and can also be disabled
2691 * for a single guest by disabling its VMX cpuid bit.
2692 */
2693 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2694 {
2695 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
2696 }
2697
2698 /*
2699 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2700 * returned for the various VMX controls MSRs when nested VMX is enabled.
2701 * The same values should also be used to verify that vmcs12 control fields are
2702 * valid during nested entry from L1 to L2.
2703 * Each of these control msrs has a low and high 32-bit half: A low bit is on
2704 * if the corresponding bit in the (32-bit) control field *must* be on, and a
2705 * bit in the high half is on if the corresponding bit in the control field
2706 * may be on. See also vmx_control_verify().
2707 */
2708 static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
2709 {
2710 /*
2711 * Note that as a general rule, the high half of the MSRs (bits in
2712 * the control fields which may be 1) should be initialized by the
2713 * intersection of the underlying hardware's MSR (i.e., features which
2714 * can be supported) and the list of features we want to expose -
2715 * because they are known to be properly supported in our code.
2716 * Also, usually, the low half of the MSRs (bits which must be 1) can
2717 * be set to 0, meaning that L1 may turn off any of these bits. The
2718 * reason is that if one of these bits is necessary, it will appear
2719 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2720 * fields of vmcs01 and vmcs02, will turn these bits off - and
2721 * nested_vmx_exit_reflected() will not pass related exits to L1.
2722 * These rules have exceptions below.
2723 */
2724
2725 /* pin-based controls */
2726 rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2727 vmx->nested.nested_vmx_pinbased_ctls_low,
2728 vmx->nested.nested_vmx_pinbased_ctls_high);
2729 vmx->nested.nested_vmx_pinbased_ctls_low |=
2730 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2731 vmx->nested.nested_vmx_pinbased_ctls_high &=
2732 PIN_BASED_EXT_INTR_MASK |
2733 PIN_BASED_NMI_EXITING |
2734 PIN_BASED_VIRTUAL_NMIS;
2735 vmx->nested.nested_vmx_pinbased_ctls_high |=
2736 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2737 PIN_BASED_VMX_PREEMPTION_TIMER;
2738 if (kvm_vcpu_apicv_active(&vmx->vcpu))
2739 vmx->nested.nested_vmx_pinbased_ctls_high |=
2740 PIN_BASED_POSTED_INTR;
2741
2742 /* exit controls */
2743 rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2744 vmx->nested.nested_vmx_exit_ctls_low,
2745 vmx->nested.nested_vmx_exit_ctls_high);
2746 vmx->nested.nested_vmx_exit_ctls_low =
2747 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2748
2749 vmx->nested.nested_vmx_exit_ctls_high &=
2750 #ifdef CONFIG_X86_64
2751 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2752 #endif
2753 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2754 vmx->nested.nested_vmx_exit_ctls_high |=
2755 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2756 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2757 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2758
2759 if (kvm_mpx_supported())
2760 vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2761
2762 /* We support free control of debug control saving. */
2763 vmx->nested.nested_vmx_exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2764
2765 /* entry controls */
2766 rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2767 vmx->nested.nested_vmx_entry_ctls_low,
2768 vmx->nested.nested_vmx_entry_ctls_high);
2769 vmx->nested.nested_vmx_entry_ctls_low =
2770 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2771 vmx->nested.nested_vmx_entry_ctls_high &=
2772 #ifdef CONFIG_X86_64
2773 VM_ENTRY_IA32E_MODE |
2774 #endif
2775 VM_ENTRY_LOAD_IA32_PAT;
2776 vmx->nested.nested_vmx_entry_ctls_high |=
2777 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
2778 if (kvm_mpx_supported())
2779 vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2780
2781 /* We support free control of debug control loading. */
2782 vmx->nested.nested_vmx_entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2783
2784 /* cpu-based controls */
2785 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2786 vmx->nested.nested_vmx_procbased_ctls_low,
2787 vmx->nested.nested_vmx_procbased_ctls_high);
2788 vmx->nested.nested_vmx_procbased_ctls_low =
2789 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2790 vmx->nested.nested_vmx_procbased_ctls_high &=
2791 CPU_BASED_VIRTUAL_INTR_PENDING |
2792 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2793 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2794 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2795 CPU_BASED_CR3_STORE_EXITING |
2796 #ifdef CONFIG_X86_64
2797 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2798 #endif
2799 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2800 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
2801 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
2802 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
2803 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2804 /*
2805 * We can allow some features even when not supported by the
2806 * hardware. For example, L1 can specify an MSR bitmap - and we
2807 * can use it to avoid exits to L1 - even when L0 runs L2
2808 * without MSR bitmaps.
2809 */
2810 vmx->nested.nested_vmx_procbased_ctls_high |=
2811 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2812 CPU_BASED_USE_MSR_BITMAPS;
2813
2814 /* We support free control of CR3 access interception. */
2815 vmx->nested.nested_vmx_procbased_ctls_low &=
2816 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2817
2818 /*
2819 * secondary cpu-based controls. Do not include those that
2820 * depend on CPUID bits, they are added later by vmx_cpuid_update.
2821 */
2822 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2823 vmx->nested.nested_vmx_secondary_ctls_low,
2824 vmx->nested.nested_vmx_secondary_ctls_high);
2825 vmx->nested.nested_vmx_secondary_ctls_low = 0;
2826 vmx->nested.nested_vmx_secondary_ctls_high &=
2827 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2828 SECONDARY_EXEC_DESC |
2829 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2830 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2831 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2832 SECONDARY_EXEC_WBINVD_EXITING;
2833
2834 if (enable_ept) {
2835 /* nested EPT: emulate EPT also to L1 */
2836 vmx->nested.nested_vmx_secondary_ctls_high |=
2837 SECONDARY_EXEC_ENABLE_EPT;
2838 vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
2839 VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
2840 if (cpu_has_vmx_ept_execute_only())
2841 vmx->nested.nested_vmx_ept_caps |=
2842 VMX_EPT_EXECUTE_ONLY_BIT;
2843 vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
2844 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
2845 VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
2846 VMX_EPT_1GB_PAGE_BIT;
2847 if (enable_ept_ad_bits) {
2848 vmx->nested.nested_vmx_secondary_ctls_high |=
2849 SECONDARY_EXEC_ENABLE_PML;
2850 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_AD_BIT;
2851 }
2852 }
2853
2854 if (cpu_has_vmx_vmfunc()) {
2855 vmx->nested.nested_vmx_secondary_ctls_high |=
2856 SECONDARY_EXEC_ENABLE_VMFUNC;
2857 /*
2858 * Advertise EPTP switching unconditionally
2859 * since we emulate it
2860 */
2861 if (enable_ept)
2862 vmx->nested.nested_vmx_vmfunc_controls =
2863 VMX_VMFUNC_EPTP_SWITCHING;
2864 }
2865
2866 /*
2867 * Old versions of KVM use the single-context version without
2868 * checking for support, so declare that it is supported even
2869 * though it is treated as global context. The alternative is
2870 * not failing the single-context invvpid, and it is worse.
2871 */
2872 if (enable_vpid) {
2873 vmx->nested.nested_vmx_secondary_ctls_high |=
2874 SECONDARY_EXEC_ENABLE_VPID;
2875 vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
2876 VMX_VPID_EXTENT_SUPPORTED_MASK;
2877 }
2878
2879 if (enable_unrestricted_guest)
2880 vmx->nested.nested_vmx_secondary_ctls_high |=
2881 SECONDARY_EXEC_UNRESTRICTED_GUEST;
2882
2883 /* miscellaneous data */
2884 rdmsr(MSR_IA32_VMX_MISC,
2885 vmx->nested.nested_vmx_misc_low,
2886 vmx->nested.nested_vmx_misc_high);
2887 vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
2888 vmx->nested.nested_vmx_misc_low |=
2889 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
2890 VMX_MISC_ACTIVITY_HLT;
2891 vmx->nested.nested_vmx_misc_high = 0;
2892
2893 /*
2894 * This MSR reports some information about VMX support. We
2895 * should return information about the VMX we emulate for the
2896 * guest, and the VMCS structure we give it - not about the
2897 * VMX support of the underlying hardware.
2898 */
2899 vmx->nested.nested_vmx_basic =
2900 VMCS12_REVISION |
2901 VMX_BASIC_TRUE_CTLS |
2902 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2903 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2904
2905 if (cpu_has_vmx_basic_inout())
2906 vmx->nested.nested_vmx_basic |= VMX_BASIC_INOUT;
2907
2908 /*
2909 * These MSRs specify bits which the guest must keep fixed on
2910 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2911 * We picked the standard core2 setting.
2912 */
2913 #define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2914 #define VMXON_CR4_ALWAYSON X86_CR4_VMXE
2915 vmx->nested.nested_vmx_cr0_fixed0 = VMXON_CR0_ALWAYSON;
2916 vmx->nested.nested_vmx_cr4_fixed0 = VMXON_CR4_ALWAYSON;
2917
2918 /* These MSRs specify bits which the guest must keep fixed off. */
2919 rdmsrl(MSR_IA32_VMX_CR0_FIXED1, vmx->nested.nested_vmx_cr0_fixed1);
2920 rdmsrl(MSR_IA32_VMX_CR4_FIXED1, vmx->nested.nested_vmx_cr4_fixed1);
2921
2922 /* highest index: VMX_PREEMPTION_TIMER_VALUE */
2923 vmx->nested.nested_vmx_vmcs_enum = 0x2e;
2924 }
2925
2926 /*
2927 * if fixed0[i] == 1: val[i] must be 1
2928 * if fixed1[i] == 0: val[i] must be 0
2929 */
2930 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
2931 {
2932 return ((val & fixed1) | fixed0) == val;
2933 }
2934
2935 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2936 {
2937 return fixed_bits_valid(control, low, high);
2938 }
2939
2940 static inline u64 vmx_control_msr(u32 low, u32 high)
2941 {
2942 return low | ((u64)high << 32);
2943 }
2944
2945 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
2946 {
2947 superset &= mask;
2948 subset &= mask;
2949
2950 return (superset | subset) == superset;
2951 }
2952
2953 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
2954 {
2955 const u64 feature_and_reserved =
2956 /* feature (except bit 48; see below) */
2957 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
2958 /* reserved */
2959 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
2960 u64 vmx_basic = vmx->nested.nested_vmx_basic;
2961
2962 if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
2963 return -EINVAL;
2964
2965 /*
2966 * KVM does not emulate a version of VMX that constrains physical
2967 * addresses of VMX structures (e.g. VMCS) to 32-bits.
2968 */
2969 if (data & BIT_ULL(48))
2970 return -EINVAL;
2971
2972 if (vmx_basic_vmcs_revision_id(vmx_basic) !=
2973 vmx_basic_vmcs_revision_id(data))
2974 return -EINVAL;
2975
2976 if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
2977 return -EINVAL;
2978
2979 vmx->nested.nested_vmx_basic = data;
2980 return 0;
2981 }
2982
2983 static int
2984 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
2985 {
2986 u64 supported;
2987 u32 *lowp, *highp;
2988
2989 switch (msr_index) {
2990 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2991 lowp = &vmx->nested.nested_vmx_pinbased_ctls_low;
2992 highp = &vmx->nested.nested_vmx_pinbased_ctls_high;
2993 break;
2994 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2995 lowp = &vmx->nested.nested_vmx_procbased_ctls_low;
2996 highp = &vmx->nested.nested_vmx_procbased_ctls_high;
2997 break;
2998 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2999 lowp = &vmx->nested.nested_vmx_exit_ctls_low;
3000 highp = &vmx->nested.nested_vmx_exit_ctls_high;
3001 break;
3002 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3003 lowp = &vmx->nested.nested_vmx_entry_ctls_low;
3004 highp = &vmx->nested.nested_vmx_entry_ctls_high;
3005 break;
3006 case MSR_IA32_VMX_PROCBASED_CTLS2:
3007 lowp = &vmx->nested.nested_vmx_secondary_ctls_low;
3008 highp = &vmx->nested.nested_vmx_secondary_ctls_high;
3009 break;
3010 default:
3011 BUG();
3012 }
3013
3014 supported = vmx_control_msr(*lowp, *highp);
3015
3016 /* Check must-be-1 bits are still 1. */
3017 if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3018 return -EINVAL;
3019
3020 /* Check must-be-0 bits are still 0. */
3021 if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3022 return -EINVAL;
3023
3024 *lowp = data;
3025 *highp = data >> 32;
3026 return 0;
3027 }
3028
3029 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3030 {
3031 const u64 feature_and_reserved_bits =
3032 /* feature */
3033 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3034 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3035 /* reserved */
3036 GENMASK_ULL(13, 9) | BIT_ULL(31);
3037 u64 vmx_misc;
3038
3039 vmx_misc = vmx_control_msr(vmx->nested.nested_vmx_misc_low,
3040 vmx->nested.nested_vmx_misc_high);
3041
3042 if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3043 return -EINVAL;
3044
3045 if ((vmx->nested.nested_vmx_pinbased_ctls_high &
3046 PIN_BASED_VMX_PREEMPTION_TIMER) &&
3047 vmx_misc_preemption_timer_rate(data) !=
3048 vmx_misc_preemption_timer_rate(vmx_misc))
3049 return -EINVAL;
3050
3051 if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3052 return -EINVAL;
3053
3054 if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3055 return -EINVAL;
3056
3057 if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3058 return -EINVAL;
3059
3060 vmx->nested.nested_vmx_misc_low = data;
3061 vmx->nested.nested_vmx_misc_high = data >> 32;
3062 return 0;
3063 }
3064
3065 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3066 {
3067 u64 vmx_ept_vpid_cap;
3068
3069 vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.nested_vmx_ept_caps,
3070 vmx->nested.nested_vmx_vpid_caps);
3071
3072 /* Every bit is either reserved or a feature bit. */
3073 if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3074 return -EINVAL;
3075
3076 vmx->nested.nested_vmx_ept_caps = data;
3077 vmx->nested.nested_vmx_vpid_caps = data >> 32;
3078 return 0;
3079 }
3080
3081 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3082 {
3083 u64 *msr;
3084
3085 switch (msr_index) {
3086 case MSR_IA32_VMX_CR0_FIXED0:
3087 msr = &vmx->nested.nested_vmx_cr0_fixed0;
3088 break;
3089 case MSR_IA32_VMX_CR4_FIXED0:
3090 msr = &vmx->nested.nested_vmx_cr4_fixed0;
3091 break;
3092 default:
3093 BUG();
3094 }
3095
3096 /*
3097 * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3098 * must be 1 in the restored value.
3099 */
3100 if (!is_bitwise_subset(data, *msr, -1ULL))
3101 return -EINVAL;
3102
3103 *msr = data;
3104 return 0;
3105 }
3106
3107 /*
3108 * Called when userspace is restoring VMX MSRs.
3109 *
3110 * Returns 0 on success, non-0 otherwise.
3111 */
3112 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3113 {
3114 struct vcpu_vmx *vmx = to_vmx(vcpu);
3115
3116 switch (msr_index) {
3117 case MSR_IA32_VMX_BASIC:
3118 return vmx_restore_vmx_basic(vmx, data);
3119 case MSR_IA32_VMX_PINBASED_CTLS:
3120 case MSR_IA32_VMX_PROCBASED_CTLS:
3121 case MSR_IA32_VMX_EXIT_CTLS:
3122 case MSR_IA32_VMX_ENTRY_CTLS:
3123 /*
3124 * The "non-true" VMX capability MSRs are generated from the
3125 * "true" MSRs, so we do not support restoring them directly.
3126 *
3127 * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3128 * should restore the "true" MSRs with the must-be-1 bits
3129 * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3130 * DEFAULT SETTINGS".
3131 */
3132 return -EINVAL;
3133 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3134 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3135 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3136 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3137 case MSR_IA32_VMX_PROCBASED_CTLS2:
3138 return vmx_restore_control_msr(vmx, msr_index, data);
3139 case MSR_IA32_VMX_MISC:
3140 return vmx_restore_vmx_misc(vmx, data);
3141 case MSR_IA32_VMX_CR0_FIXED0:
3142 case MSR_IA32_VMX_CR4_FIXED0:
3143 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3144 case MSR_IA32_VMX_CR0_FIXED1:
3145 case MSR_IA32_VMX_CR4_FIXED1:
3146 /*
3147 * These MSRs are generated based on the vCPU's CPUID, so we
3148 * do not support restoring them directly.
3149 */
3150 return -EINVAL;
3151 case MSR_IA32_VMX_EPT_VPID_CAP:
3152 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3153 case MSR_IA32_VMX_VMCS_ENUM:
3154 vmx->nested.nested_vmx_vmcs_enum = data;
3155 return 0;
3156 default:
3157 /*
3158 * The rest of the VMX capability MSRs do not support restore.
3159 */
3160 return -EINVAL;
3161 }
3162 }
3163
3164 /* Returns 0 on success, non-0 otherwise. */
3165 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
3166 {
3167 struct vcpu_vmx *vmx = to_vmx(vcpu);
3168
3169 switch (msr_index) {
3170 case MSR_IA32_VMX_BASIC:
3171 *pdata = vmx->nested.nested_vmx_basic;
3172 break;
3173 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3174 case MSR_IA32_VMX_PINBASED_CTLS:
3175 *pdata = vmx_control_msr(
3176 vmx->nested.nested_vmx_pinbased_ctls_low,
3177 vmx->nested.nested_vmx_pinbased_ctls_high);
3178 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3179 *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3180 break;
3181 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3182 case MSR_IA32_VMX_PROCBASED_CTLS:
3183 *pdata = vmx_control_msr(
3184 vmx->nested.nested_vmx_procbased_ctls_low,
3185 vmx->nested.nested_vmx_procbased_ctls_high);
3186 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3187 *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3188 break;
3189 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3190 case MSR_IA32_VMX_EXIT_CTLS:
3191 *pdata = vmx_control_msr(
3192 vmx->nested.nested_vmx_exit_ctls_low,
3193 vmx->nested.nested_vmx_exit_ctls_high);
3194 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3195 *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3196 break;
3197 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3198 case MSR_IA32_VMX_ENTRY_CTLS:
3199 *pdata = vmx_control_msr(
3200 vmx->nested.nested_vmx_entry_ctls_low,
3201 vmx->nested.nested_vmx_entry_ctls_high);
3202 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
3203 *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3204 break;
3205 case MSR_IA32_VMX_MISC:
3206 *pdata = vmx_control_msr(
3207 vmx->nested.nested_vmx_misc_low,
3208 vmx->nested.nested_vmx_misc_high);
3209 break;
3210 case MSR_IA32_VMX_CR0_FIXED0:
3211 *pdata = vmx->nested.nested_vmx_cr0_fixed0;
3212 break;
3213 case MSR_IA32_VMX_CR0_FIXED1:
3214 *pdata = vmx->nested.nested_vmx_cr0_fixed1;
3215 break;
3216 case MSR_IA32_VMX_CR4_FIXED0:
3217 *pdata = vmx->nested.nested_vmx_cr4_fixed0;
3218 break;
3219 case MSR_IA32_VMX_CR4_FIXED1:
3220 *pdata = vmx->nested.nested_vmx_cr4_fixed1;
3221 break;
3222 case MSR_IA32_VMX_VMCS_ENUM:
3223 *pdata = vmx->nested.nested_vmx_vmcs_enum;
3224 break;
3225 case MSR_IA32_VMX_PROCBASED_CTLS2:
3226 *pdata = vmx_control_msr(
3227 vmx->nested.nested_vmx_secondary_ctls_low,
3228 vmx->nested.nested_vmx_secondary_ctls_high);
3229 break;
3230 case MSR_IA32_VMX_EPT_VPID_CAP:
3231 *pdata = vmx->nested.nested_vmx_ept_caps |
3232 ((u64)vmx->nested.nested_vmx_vpid_caps << 32);
3233 break;
3234 case MSR_IA32_VMX_VMFUNC:
3235 *pdata = vmx->nested.nested_vmx_vmfunc_controls;
3236 break;
3237 default:
3238 return 1;
3239 }
3240
3241 return 0;
3242 }
3243
3244 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3245 uint64_t val)
3246 {
3247 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3248
3249 return !(val & ~valid_bits);
3250 }
3251
3252 /*
3253 * Reads an msr value (of 'msr_index') into 'pdata'.
3254 * Returns 0 on success, non-0 otherwise.
3255 * Assumes vcpu_load() was already called.
3256 */
3257 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3258 {
3259 struct shared_msr_entry *msr;
3260
3261 switch (msr_info->index) {
3262 #ifdef CONFIG_X86_64
3263 case MSR_FS_BASE:
3264 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3265 break;
3266 case MSR_GS_BASE:
3267 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3268 break;
3269 case MSR_KERNEL_GS_BASE:
3270 vmx_load_host_state(to_vmx(vcpu));
3271 msr_info->data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
3272 break;
3273 #endif
3274 case MSR_EFER:
3275 return kvm_get_msr_common(vcpu, msr_info);
3276 case MSR_IA32_TSC:
3277 msr_info->data = guest_read_tsc(vcpu);
3278 break;
3279 case MSR_IA32_SYSENTER_CS:
3280 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3281 break;
3282 case MSR_IA32_SYSENTER_EIP:
3283 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3284 break;
3285 case MSR_IA32_SYSENTER_ESP:
3286 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3287 break;
3288 case MSR_IA32_BNDCFGS:
3289 if (!kvm_mpx_supported() ||
3290 (!msr_info->host_initiated &&
3291 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3292 return 1;
3293 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3294 break;
3295 case MSR_IA32_MCG_EXT_CTL:
3296 if (!msr_info->host_initiated &&
3297 !(to_vmx(vcpu)->msr_ia32_feature_control &
3298 FEATURE_CONTROL_LMCE))
3299 return 1;
3300 msr_info->data = vcpu->arch.mcg_ext_ctl;
3301 break;
3302 case MSR_IA32_FEATURE_CONTROL:
3303 msr_info->data = to_vmx(vcpu)->msr_ia32_feature_control;
3304 break;
3305 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3306 if (!nested_vmx_allowed(vcpu))
3307 return 1;
3308 return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
3309 case MSR_IA32_XSS:
3310 if (!vmx_xsaves_supported())
3311 return 1;
3312 msr_info->data = vcpu->arch.ia32_xss;
3313 break;
3314 case MSR_TSC_AUX:
3315 if (!msr_info->host_initiated &&
3316 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3317 return 1;
3318 /* Otherwise falls through */
3319 default:
3320 msr = find_msr_entry(to_vmx(vcpu), msr_info->index);
3321 if (msr) {
3322 msr_info->data = msr->data;
3323 break;
3324 }
3325 return kvm_get_msr_common(vcpu, msr_info);
3326 }
3327
3328 return 0;
3329 }
3330
3331 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3332
3333 /*
3334 * Writes msr value into into the appropriate "register".
3335 * Returns 0 on success, non-0 otherwise.
3336 * Assumes vcpu_load() was already called.
3337 */
3338 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3339 {
3340 struct vcpu_vmx *vmx = to_vmx(vcpu);
3341 struct shared_msr_entry *msr;
3342 int ret = 0;
3343 u32 msr_index = msr_info->index;
3344 u64 data = msr_info->data;
3345
3346 switch (msr_index) {
3347 case MSR_EFER:
3348 ret = kvm_set_msr_common(vcpu, msr_info);
3349 break;
3350 #ifdef CONFIG_X86_64
3351 case MSR_FS_BASE:
3352 vmx_segment_cache_clear(vmx);
3353 vmcs_writel(GUEST_FS_BASE, data);
3354 break;
3355 case MSR_GS_BASE:
3356 vmx_segment_cache_clear(vmx);
3357 vmcs_writel(GUEST_GS_BASE, data);
3358 break;
3359 case MSR_KERNEL_GS_BASE:
3360 vmx_load_host_state(vmx);
3361 vmx->msr_guest_kernel_gs_base = data;
3362 break;
3363 #endif
3364 case MSR_IA32_SYSENTER_CS:
3365 vmcs_write32(GUEST_SYSENTER_CS, data);
3366 break;
3367 case MSR_IA32_SYSENTER_EIP:
3368 vmcs_writel(GUEST_SYSENTER_EIP, data);
3369 break;
3370 case MSR_IA32_SYSENTER_ESP:
3371 vmcs_writel(GUEST_SYSENTER_ESP, data);
3372 break;
3373 case MSR_IA32_BNDCFGS:
3374 if (!kvm_mpx_supported() ||
3375 (!msr_info->host_initiated &&
3376 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3377 return 1;
3378 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
3379 (data & MSR_IA32_BNDCFGS_RSVD))
3380 return 1;
3381 vmcs_write64(GUEST_BNDCFGS, data);
3382 break;
3383 case MSR_IA32_TSC:
3384 kvm_write_tsc(vcpu, msr_info);
3385 break;
3386 case MSR_IA32_CR_PAT:
3387 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3388 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3389 return 1;
3390 vmcs_write64(GUEST_IA32_PAT, data);
3391 vcpu->arch.pat = data;
3392 break;
3393 }
3394 ret = kvm_set_msr_common(vcpu, msr_info);
3395 break;
3396 case MSR_IA32_TSC_ADJUST:
3397 ret = kvm_set_msr_common(vcpu, msr_info);
3398 break;
3399 case MSR_IA32_MCG_EXT_CTL:
3400 if ((!msr_info->host_initiated &&
3401 !(to_vmx(vcpu)->msr_ia32_feature_control &
3402 FEATURE_CONTROL_LMCE)) ||
3403 (data & ~MCG_EXT_CTL_LMCE_EN))
3404 return 1;
3405 vcpu->arch.mcg_ext_ctl = data;
3406 break;
3407 case MSR_IA32_FEATURE_CONTROL:
3408 if (!vmx_feature_control_msr_valid(vcpu, data) ||
3409 (to_vmx(vcpu)->msr_ia32_feature_control &
3410 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
3411 return 1;
3412 vmx->msr_ia32_feature_control = data;
3413 if (msr_info->host_initiated && data == 0)
3414 vmx_leave_nested(vcpu);
3415 break;
3416 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3417 if (!msr_info->host_initiated)
3418 return 1; /* they are read-only */
3419 if (!nested_vmx_allowed(vcpu))
3420 return 1;
3421 return vmx_set_vmx_msr(vcpu, msr_index, data);
3422 case MSR_IA32_XSS:
3423 if (!vmx_xsaves_supported())
3424 return 1;
3425 /*
3426 * The only supported bit as of Skylake is bit 8, but
3427 * it is not supported on KVM.
3428 */
3429 if (data != 0)
3430 return 1;
3431 vcpu->arch.ia32_xss = data;
3432 if (vcpu->arch.ia32_xss != host_xss)
3433 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
3434 vcpu->arch.ia32_xss, host_xss);
3435 else
3436 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
3437 break;
3438 case MSR_TSC_AUX:
3439 if (!msr_info->host_initiated &&
3440 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3441 return 1;
3442 /* Check reserved bit, higher 32 bits should be zero */
3443 if ((data >> 32) != 0)
3444 return 1;
3445 /* Otherwise falls through */
3446 default:
3447 msr = find_msr_entry(vmx, msr_index);
3448 if (msr) {
3449 u64 old_msr_data = msr->data;
3450 msr->data = data;
3451 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
3452 preempt_disable();
3453 ret = kvm_set_shared_msr(msr->index, msr->data,
3454 msr->mask);
3455 preempt_enable();
3456 if (ret)
3457 msr->data = old_msr_data;
3458 }
3459 break;
3460 }
3461 ret = kvm_set_msr_common(vcpu, msr_info);
3462 }
3463
3464 return ret;
3465 }
3466
3467 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
3468 {
3469 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
3470 switch (reg) {
3471 case VCPU_REGS_RSP:
3472 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
3473 break;
3474 case VCPU_REGS_RIP:
3475 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
3476 break;
3477 case VCPU_EXREG_PDPTR:
3478 if (enable_ept)
3479 ept_save_pdptrs(vcpu);
3480 break;
3481 default:
3482 break;
3483 }
3484 }
3485
3486 static __init int cpu_has_kvm_support(void)
3487 {
3488 return cpu_has_vmx();
3489 }
3490
3491 static __init int vmx_disabled_by_bios(void)
3492 {
3493 u64 msr;
3494
3495 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
3496 if (msr & FEATURE_CONTROL_LOCKED) {
3497 /* launched w/ TXT and VMX disabled */
3498 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3499 && tboot_enabled())
3500 return 1;
3501 /* launched w/o TXT and VMX only enabled w/ TXT */
3502 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3503 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3504 && !tboot_enabled()) {
3505 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
3506 "activate TXT before enabling KVM\n");
3507 return 1;
3508 }
3509 /* launched w/o TXT and VMX disabled */
3510 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3511 && !tboot_enabled())
3512 return 1;
3513 }
3514
3515 return 0;
3516 }
3517
3518 static void kvm_cpu_vmxon(u64 addr)
3519 {
3520 cr4_set_bits(X86_CR4_VMXE);
3521 intel_pt_handle_vmx(1);
3522
3523 asm volatile (ASM_VMX_VMXON_RAX
3524 : : "a"(&addr), "m"(addr)
3525 : "memory", "cc");
3526 }
3527
3528 static int hardware_enable(void)
3529 {
3530 int cpu = raw_smp_processor_id();
3531 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
3532 u64 old, test_bits;
3533
3534 if (cr4_read_shadow() & X86_CR4_VMXE)
3535 return -EBUSY;
3536
3537 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
3538 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
3539 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
3540
3541 /*
3542 * Now we can enable the vmclear operation in kdump
3543 * since the loaded_vmcss_on_cpu list on this cpu
3544 * has been initialized.
3545 *
3546 * Though the cpu is not in VMX operation now, there
3547 * is no problem to enable the vmclear operation
3548 * for the loaded_vmcss_on_cpu list is empty!
3549 */
3550 crash_enable_local_vmclear(cpu);
3551
3552 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
3553
3554 test_bits = FEATURE_CONTROL_LOCKED;
3555 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
3556 if (tboot_enabled())
3557 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
3558
3559 if ((old & test_bits) != test_bits) {
3560 /* enable and lock */
3561 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
3562 }
3563 kvm_cpu_vmxon(phys_addr);
3564 if (enable_ept)
3565 ept_sync_global();
3566
3567 return 0;
3568 }
3569
3570 static void vmclear_local_loaded_vmcss(void)
3571 {
3572 int cpu = raw_smp_processor_id();
3573 struct loaded_vmcs *v, *n;
3574
3575 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
3576 loaded_vmcss_on_cpu_link)
3577 __loaded_vmcs_clear(v);
3578 }
3579
3580
3581 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
3582 * tricks.
3583 */
3584 static void kvm_cpu_vmxoff(void)
3585 {
3586 asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
3587
3588 intel_pt_handle_vmx(0);
3589 cr4_clear_bits(X86_CR4_VMXE);
3590 }
3591
3592 static void hardware_disable(void)
3593 {
3594 vmclear_local_loaded_vmcss();
3595 kvm_cpu_vmxoff();
3596 }
3597
3598 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
3599 u32 msr, u32 *result)
3600 {
3601 u32 vmx_msr_low, vmx_msr_high;
3602 u32 ctl = ctl_min | ctl_opt;
3603
3604 rdmsr(msr, vmx_msr_low, vmx_msr_high);
3605
3606 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
3607 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
3608
3609 /* Ensure minimum (required) set of control bits are supported. */
3610 if (ctl_min & ~ctl)
3611 return -EIO;
3612
3613 *result = ctl;
3614 return 0;
3615 }
3616
3617 static __init bool allow_1_setting(u32 msr, u32 ctl)
3618 {
3619 u32 vmx_msr_low, vmx_msr_high;
3620
3621 rdmsr(msr, vmx_msr_low, vmx_msr_high);
3622 return vmx_msr_high & ctl;
3623 }
3624
3625 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
3626 {
3627 u32 vmx_msr_low, vmx_msr_high;
3628 u32 min, opt, min2, opt2;
3629 u32 _pin_based_exec_control = 0;
3630 u32 _cpu_based_exec_control = 0;
3631 u32 _cpu_based_2nd_exec_control = 0;
3632 u32 _vmexit_control = 0;
3633 u32 _vmentry_control = 0;
3634
3635 min = CPU_BASED_HLT_EXITING |
3636 #ifdef CONFIG_X86_64
3637 CPU_BASED_CR8_LOAD_EXITING |
3638 CPU_BASED_CR8_STORE_EXITING |
3639 #endif
3640 CPU_BASED_CR3_LOAD_EXITING |
3641 CPU_BASED_CR3_STORE_EXITING |
3642 CPU_BASED_USE_IO_BITMAPS |
3643 CPU_BASED_MOV_DR_EXITING |
3644 CPU_BASED_USE_TSC_OFFSETING |
3645 CPU_BASED_INVLPG_EXITING |
3646 CPU_BASED_RDPMC_EXITING;
3647
3648 if (!kvm_mwait_in_guest())
3649 min |= CPU_BASED_MWAIT_EXITING |
3650 CPU_BASED_MONITOR_EXITING;
3651
3652 opt = CPU_BASED_TPR_SHADOW |
3653 CPU_BASED_USE_MSR_BITMAPS |
3654 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3655 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
3656 &_cpu_based_exec_control) < 0)
3657 return -EIO;
3658 #ifdef CONFIG_X86_64
3659 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3660 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
3661 ~CPU_BASED_CR8_STORE_EXITING;
3662 #endif
3663 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
3664 min2 = 0;
3665 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3666 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3667 SECONDARY_EXEC_WBINVD_EXITING |
3668 SECONDARY_EXEC_ENABLE_VPID |
3669 SECONDARY_EXEC_ENABLE_EPT |
3670 SECONDARY_EXEC_UNRESTRICTED_GUEST |
3671 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
3672 SECONDARY_EXEC_RDTSCP |
3673 SECONDARY_EXEC_ENABLE_INVPCID |
3674 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3675 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3676 SECONDARY_EXEC_SHADOW_VMCS |
3677 SECONDARY_EXEC_XSAVES |
3678 SECONDARY_EXEC_RDSEED_EXITING |
3679 SECONDARY_EXEC_RDRAND_EXITING |
3680 SECONDARY_EXEC_ENABLE_PML |
3681 SECONDARY_EXEC_TSC_SCALING |
3682 SECONDARY_EXEC_ENABLE_VMFUNC;
3683 if (adjust_vmx_controls(min2, opt2,
3684 MSR_IA32_VMX_PROCBASED_CTLS2,
3685 &_cpu_based_2nd_exec_control) < 0)
3686 return -EIO;
3687 }
3688 #ifndef CONFIG_X86_64
3689 if (!(_cpu_based_2nd_exec_control &
3690 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
3691 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
3692 #endif
3693
3694 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3695 _cpu_based_2nd_exec_control &= ~(
3696 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3697 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3698 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3699
3700 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
3701 &vmx_capability.ept, &vmx_capability.vpid);
3702
3703 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
3704 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
3705 enabled */
3706 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
3707 CPU_BASED_CR3_STORE_EXITING |
3708 CPU_BASED_INVLPG_EXITING);
3709 } else if (vmx_capability.ept) {
3710 vmx_capability.ept = 0;
3711 pr_warn_once("EPT CAP should not exist if not support "
3712 "1-setting enable EPT VM-execution control\n");
3713 }
3714 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
3715 vmx_capability.vpid) {
3716 vmx_capability.vpid = 0;
3717 pr_warn_once("VPID CAP should not exist if not support "
3718 "1-setting enable VPID VM-execution control\n");
3719 }
3720
3721 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
3722 #ifdef CONFIG_X86_64
3723 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
3724 #endif
3725 opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
3726 VM_EXIT_CLEAR_BNDCFGS;
3727 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
3728 &_vmexit_control) < 0)
3729 return -EIO;
3730
3731 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
3732 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
3733 PIN_BASED_VMX_PREEMPTION_TIMER;
3734 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
3735 &_pin_based_exec_control) < 0)
3736 return -EIO;
3737
3738 if (cpu_has_broken_vmx_preemption_timer())
3739 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3740 if (!(_cpu_based_2nd_exec_control &
3741 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
3742 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
3743
3744 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
3745 opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
3746 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
3747 &_vmentry_control) < 0)
3748 return -EIO;
3749
3750 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
3751
3752 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
3753 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
3754 return -EIO;
3755
3756 #ifdef CONFIG_X86_64
3757 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
3758 if (vmx_msr_high & (1u<<16))
3759 return -EIO;
3760 #endif
3761
3762 /* Require Write-Back (WB) memory type for VMCS accesses. */
3763 if (((vmx_msr_high >> 18) & 15) != 6)
3764 return -EIO;
3765
3766 vmcs_conf->size = vmx_msr_high & 0x1fff;
3767 vmcs_conf->order = get_order(vmcs_conf->size);
3768 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
3769 vmcs_conf->revision_id = vmx_msr_low;
3770
3771 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
3772 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
3773 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
3774 vmcs_conf->vmexit_ctrl = _vmexit_control;
3775 vmcs_conf->vmentry_ctrl = _vmentry_control;
3776
3777 cpu_has_load_ia32_efer =
3778 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3779 VM_ENTRY_LOAD_IA32_EFER)
3780 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3781 VM_EXIT_LOAD_IA32_EFER);
3782
3783 cpu_has_load_perf_global_ctrl =
3784 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3785 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
3786 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3787 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
3788
3789 /*
3790 * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
3791 * but due to errata below it can't be used. Workaround is to use
3792 * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
3793 *
3794 * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
3795 *
3796 * AAK155 (model 26)
3797 * AAP115 (model 30)
3798 * AAT100 (model 37)
3799 * BC86,AAY89,BD102 (model 44)
3800 * BA97 (model 46)
3801 *
3802 */
3803 if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
3804 switch (boot_cpu_data.x86_model) {
3805 case 26:
3806 case 30:
3807 case 37:
3808 case 44:
3809 case 46:
3810 cpu_has_load_perf_global_ctrl = false;
3811 printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
3812 "does not work properly. Using workaround\n");
3813 break;
3814 default:
3815 break;
3816 }
3817 }
3818
3819 if (boot_cpu_has(X86_FEATURE_XSAVES))
3820 rdmsrl(MSR_IA32_XSS, host_xss);
3821
3822 return 0;
3823 }
3824
3825 static struct vmcs *alloc_vmcs_cpu(int cpu)
3826 {
3827 int node = cpu_to_node(cpu);
3828 struct page *pages;
3829 struct vmcs *vmcs;
3830
3831 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
3832 if (!pages)
3833 return NULL;
3834 vmcs = page_address(pages);
3835 memset(vmcs, 0, vmcs_config.size);
3836 vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
3837 return vmcs;
3838 }
3839
3840 static struct vmcs *alloc_vmcs(void)
3841 {
3842 return alloc_vmcs_cpu(raw_smp_processor_id());
3843 }
3844
3845 static void free_vmcs(struct vmcs *vmcs)
3846 {
3847 free_pages((unsigned long)vmcs, vmcs_config.order);
3848 }
3849
3850 /*
3851 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
3852 */
3853 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3854 {
3855 if (!loaded_vmcs->vmcs)
3856 return;
3857 loaded_vmcs_clear(loaded_vmcs);
3858 free_vmcs(loaded_vmcs->vmcs);
3859 loaded_vmcs->vmcs = NULL;
3860 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
3861 }
3862
3863 static void free_kvm_area(void)
3864 {
3865 int cpu;
3866
3867 for_each_possible_cpu(cpu) {
3868 free_vmcs(per_cpu(vmxarea, cpu));
3869 per_cpu(vmxarea, cpu) = NULL;
3870 }
3871 }
3872
3873 enum vmcs_field_type {
3874 VMCS_FIELD_TYPE_U16 = 0,
3875 VMCS_FIELD_TYPE_U64 = 1,
3876 VMCS_FIELD_TYPE_U32 = 2,
3877 VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
3878 };
3879
3880 static inline int vmcs_field_type(unsigned long field)
3881 {
3882 if (0x1 & field) /* the *_HIGH fields are all 32 bit */
3883 return VMCS_FIELD_TYPE_U32;
3884 return (field >> 13) & 0x3 ;
3885 }
3886
3887 static inline int vmcs_field_readonly(unsigned long field)
3888 {
3889 return (((field >> 10) & 0x3) == 1);
3890 }
3891
3892 static void init_vmcs_shadow_fields(void)
3893 {
3894 int i, j;
3895
3896 /* No checks for read only fields yet */
3897
3898 for (i = j = 0; i < max_shadow_read_write_fields; i++) {
3899 switch (shadow_read_write_fields[i]) {
3900 case GUEST_BNDCFGS:
3901 if (!kvm_mpx_supported())
3902 continue;
3903 break;
3904 default:
3905 break;
3906 }
3907
3908 if (j < i)
3909 shadow_read_write_fields[j] =
3910 shadow_read_write_fields[i];
3911 j++;
3912 }
3913 max_shadow_read_write_fields = j;
3914
3915 /* shadowed fields guest access without vmexit */
3916 for (i = 0; i < max_shadow_read_write_fields; i++) {
3917 unsigned long field = shadow_read_write_fields[i];
3918
3919 clear_bit(field, vmx_vmwrite_bitmap);
3920 clear_bit(field, vmx_vmread_bitmap);
3921 if (vmcs_field_type(field) == VMCS_FIELD_TYPE_U64) {
3922 clear_bit(field + 1, vmx_vmwrite_bitmap);
3923 clear_bit(field + 1, vmx_vmread_bitmap);
3924 }
3925 }
3926 for (i = 0; i < max_shadow_read_only_fields; i++) {
3927 unsigned long field = shadow_read_only_fields[i];
3928
3929 clear_bit(field, vmx_vmread_bitmap);
3930 if (vmcs_field_type(field) == VMCS_FIELD_TYPE_U64)
3931 clear_bit(field + 1, vmx_vmread_bitmap);
3932 }
3933 }
3934
3935 static __init int alloc_kvm_area(void)
3936 {
3937 int cpu;
3938
3939 for_each_possible_cpu(cpu) {
3940 struct vmcs *vmcs;
3941
3942 vmcs = alloc_vmcs_cpu(cpu);
3943 if (!vmcs) {
3944 free_kvm_area();
3945 return -ENOMEM;
3946 }
3947
3948 per_cpu(vmxarea, cpu) = vmcs;
3949 }
3950 return 0;
3951 }
3952
3953 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
3954 struct kvm_segment *save)
3955 {
3956 if (!emulate_invalid_guest_state) {
3957 /*
3958 * CS and SS RPL should be equal during guest entry according
3959 * to VMX spec, but in reality it is not always so. Since vcpu
3960 * is in the middle of the transition from real mode to
3961 * protected mode it is safe to assume that RPL 0 is a good
3962 * default value.
3963 */
3964 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
3965 save->selector &= ~SEGMENT_RPL_MASK;
3966 save->dpl = save->selector & SEGMENT_RPL_MASK;
3967 save->s = 1;
3968 }
3969 vmx_set_segment(vcpu, save, seg);
3970 }
3971
3972 static void enter_pmode(struct kvm_vcpu *vcpu)
3973 {
3974 unsigned long flags;
3975 struct vcpu_vmx *vmx = to_vmx(vcpu);
3976
3977 /*
3978 * Update real mode segment cache. It may be not up-to-date if sement
3979 * register was written while vcpu was in a guest mode.
3980 */
3981 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3982 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3983 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3984 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3985 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3986 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3987
3988 vmx->rmode.vm86_active = 0;
3989
3990 vmx_segment_cache_clear(vmx);
3991
3992 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3993
3994 flags = vmcs_readl(GUEST_RFLAGS);
3995 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3996 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3997 vmcs_writel(GUEST_RFLAGS, flags);
3998
3999 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4000 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4001
4002 update_exception_bitmap(vcpu);
4003
4004 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4005 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4006 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4007 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4008 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4009 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4010 }
4011
4012 static void fix_rmode_seg(int seg, struct kvm_segment *save)
4013 {
4014 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4015 struct kvm_segment var = *save;
4016
4017 var.dpl = 0x3;
4018 if (seg == VCPU_SREG_CS)
4019 var.type = 0x3;
4020
4021 if (!emulate_invalid_guest_state) {
4022 var.selector = var.base >> 4;
4023 var.base = var.base & 0xffff0;
4024 var.limit = 0xffff;
4025 var.g = 0;
4026 var.db = 0;
4027 var.present = 1;
4028 var.s = 1;
4029 var.l = 0;
4030 var.unusable = 0;
4031 var.type = 0x3;
4032 var.avl = 0;
4033 if (save->base & 0xf)
4034 printk_once(KERN_WARNING "kvm: segment base is not "
4035 "paragraph aligned when entering "
4036 "protected mode (seg=%d)", seg);
4037 }
4038
4039 vmcs_write16(sf->selector, var.selector);
4040 vmcs_writel(sf->base, var.base);
4041 vmcs_write32(sf->limit, var.limit);
4042 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
4043 }
4044
4045 static void enter_rmode(struct kvm_vcpu *vcpu)
4046 {
4047 unsigned long flags;
4048 struct vcpu_vmx *vmx = to_vmx(vcpu);
4049
4050 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4051 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4052 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4053 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4054 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4055 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4056 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4057
4058 vmx->rmode.vm86_active = 1;
4059
4060 /*
4061 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4062 * vcpu. Warn the user that an update is overdue.
4063 */
4064 if (!vcpu->kvm->arch.tss_addr)
4065 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
4066 "called before entering vcpu\n");
4067
4068 vmx_segment_cache_clear(vmx);
4069
4070 vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
4071 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
4072 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4073
4074 flags = vmcs_readl(GUEST_RFLAGS);
4075 vmx->rmode.save_rflags = flags;
4076
4077 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
4078
4079 vmcs_writel(GUEST_RFLAGS, flags);
4080 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
4081 update_exception_bitmap(vcpu);
4082
4083 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4084 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4085 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4086 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4087 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4088 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4089
4090 kvm_mmu_reset_context(vcpu);
4091 }
4092
4093 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
4094 {
4095 struct vcpu_vmx *vmx = to_vmx(vcpu);
4096 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
4097
4098 if (!msr)
4099 return;
4100
4101 /*
4102 * Force kernel_gs_base reloading before EFER changes, as control
4103 * of this msr depends on is_long_mode().
4104 */
4105 vmx_load_host_state(to_vmx(vcpu));
4106 vcpu->arch.efer = efer;
4107 if (efer & EFER_LMA) {
4108 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4109 msr->data = efer;
4110 } else {
4111 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4112
4113 msr->data = efer & ~EFER_LME;
4114 }
4115 setup_msrs(vmx);
4116 }
4117
4118 #ifdef CONFIG_X86_64
4119
4120 static void enter_lmode(struct kvm_vcpu *vcpu)
4121 {
4122 u32 guest_tr_ar;
4123
4124 vmx_segment_cache_clear(to_vmx(vcpu));
4125
4126 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4127 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
4128 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
4129 __func__);
4130 vmcs_write32(GUEST_TR_AR_BYTES,
4131 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
4132 | VMX_AR_TYPE_BUSY_64_TSS);
4133 }
4134 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
4135 }
4136
4137 static void exit_lmode(struct kvm_vcpu *vcpu)
4138 {
4139 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4140 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
4141 }
4142
4143 #endif
4144
4145 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid)
4146 {
4147 if (enable_ept) {
4148 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4149 return;
4150 ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa));
4151 } else {
4152 vpid_sync_context(vpid);
4153 }
4154 }
4155
4156 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
4157 {
4158 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid);
4159 }
4160
4161 static void vmx_flush_tlb_ept_only(struct kvm_vcpu *vcpu)
4162 {
4163 if (enable_ept)
4164 vmx_flush_tlb(vcpu);
4165 }
4166
4167 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
4168 {
4169 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
4170
4171 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
4172 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
4173 }
4174
4175 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
4176 {
4177 if (enable_ept && is_paging(vcpu))
4178 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4179 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
4180 }
4181
4182 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
4183 {
4184 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
4185
4186 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
4187 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
4188 }
4189
4190 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
4191 {
4192 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4193
4194 if (!test_bit(VCPU_EXREG_PDPTR,
4195 (unsigned long *)&vcpu->arch.regs_dirty))
4196 return;
4197
4198 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4199 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
4200 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
4201 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
4202 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
4203 }
4204 }
4205
4206 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
4207 {
4208 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4209
4210 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4211 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
4212 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
4213 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
4214 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
4215 }
4216
4217 __set_bit(VCPU_EXREG_PDPTR,
4218 (unsigned long *)&vcpu->arch.regs_avail);
4219 __set_bit(VCPU_EXREG_PDPTR,
4220 (unsigned long *)&vcpu->arch.regs_dirty);
4221 }
4222
4223 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4224 {
4225 u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
4226 u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
4227 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4228
4229 if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
4230 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
4231 nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
4232 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
4233
4234 return fixed_bits_valid(val, fixed0, fixed1);
4235 }
4236
4237 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4238 {
4239 u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
4240 u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
4241
4242 return fixed_bits_valid(val, fixed0, fixed1);
4243 }
4244
4245 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
4246 {
4247 u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed0;
4248 u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed1;
4249
4250 return fixed_bits_valid(val, fixed0, fixed1);
4251 }
4252
4253 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
4254 #define nested_guest_cr4_valid nested_cr4_valid
4255 #define nested_host_cr4_valid nested_cr4_valid
4256
4257 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
4258
4259 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
4260 unsigned long cr0,
4261 struct kvm_vcpu *vcpu)
4262 {
4263 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
4264 vmx_decache_cr3(vcpu);
4265 if (!(cr0 & X86_CR0_PG)) {
4266 /* From paging/starting to nonpaging */
4267 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4268 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
4269 (CPU_BASED_CR3_LOAD_EXITING |
4270 CPU_BASED_CR3_STORE_EXITING));
4271 vcpu->arch.cr0 = cr0;
4272 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4273 } else if (!is_paging(vcpu)) {
4274 /* From nonpaging to paging */
4275 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4276 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
4277 ~(CPU_BASED_CR3_LOAD_EXITING |
4278 CPU_BASED_CR3_STORE_EXITING));
4279 vcpu->arch.cr0 = cr0;
4280 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4281 }
4282
4283 if (!(cr0 & X86_CR0_WP))
4284 *hw_cr0 &= ~X86_CR0_WP;
4285 }
4286
4287 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
4288 {
4289 struct vcpu_vmx *vmx = to_vmx(vcpu);
4290 unsigned long hw_cr0;
4291
4292 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
4293 if (enable_unrestricted_guest)
4294 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
4295 else {
4296 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
4297
4298 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
4299 enter_pmode(vcpu);
4300
4301 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
4302 enter_rmode(vcpu);
4303 }
4304
4305 #ifdef CONFIG_X86_64
4306 if (vcpu->arch.efer & EFER_LME) {
4307 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
4308 enter_lmode(vcpu);
4309 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
4310 exit_lmode(vcpu);
4311 }
4312 #endif
4313
4314 if (enable_ept)
4315 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
4316
4317 vmcs_writel(CR0_READ_SHADOW, cr0);
4318 vmcs_writel(GUEST_CR0, hw_cr0);
4319 vcpu->arch.cr0 = cr0;
4320
4321 /* depends on vcpu->arch.cr0 to be set to a new value */
4322 vmx->emulation_required = emulation_required(vcpu);
4323 }
4324
4325 static int get_ept_level(struct kvm_vcpu *vcpu)
4326 {
4327 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
4328 return 5;
4329 return 4;
4330 }
4331
4332 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
4333 {
4334 u64 eptp = VMX_EPTP_MT_WB;
4335
4336 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
4337
4338 if (enable_ept_ad_bits &&
4339 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
4340 eptp |= VMX_EPTP_AD_ENABLE_BIT;
4341 eptp |= (root_hpa & PAGE_MASK);
4342
4343 return eptp;
4344 }
4345
4346 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
4347 {
4348 unsigned long guest_cr3;
4349 u64 eptp;
4350
4351 guest_cr3 = cr3;
4352 if (enable_ept) {
4353 eptp = construct_eptp(vcpu, cr3);
4354 vmcs_write64(EPT_POINTER, eptp);
4355 if (is_paging(vcpu) || is_guest_mode(vcpu))
4356 guest_cr3 = kvm_read_cr3(vcpu);
4357 else
4358 guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
4359 ept_load_pdptrs(vcpu);
4360 }
4361
4362 vmx_flush_tlb(vcpu);
4363 vmcs_writel(GUEST_CR3, guest_cr3);
4364 }
4365
4366 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
4367 {
4368 /*
4369 * Pass through host's Machine Check Enable value to hw_cr4, which
4370 * is in force while we are in guest mode. Do not let guests control
4371 * this bit, even if host CR4.MCE == 0.
4372 */
4373 unsigned long hw_cr4 =
4374 (cr4_read_shadow() & X86_CR4_MCE) |
4375 (cr4 & ~X86_CR4_MCE) |
4376 (to_vmx(vcpu)->rmode.vm86_active ?
4377 KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
4378
4379 if (cr4 & X86_CR4_VMXE) {
4380 /*
4381 * To use VMXON (and later other VMX instructions), a guest
4382 * must first be able to turn on cr4.VMXE (see handle_vmon()).
4383 * So basically the check on whether to allow nested VMX
4384 * is here.
4385 */
4386 if (!nested_vmx_allowed(vcpu))
4387 return 1;
4388 }
4389
4390 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
4391 return 1;
4392
4393 vcpu->arch.cr4 = cr4;
4394 if (enable_ept) {
4395 if (!is_paging(vcpu)) {
4396 hw_cr4 &= ~X86_CR4_PAE;
4397 hw_cr4 |= X86_CR4_PSE;
4398 } else if (!(cr4 & X86_CR4_PAE)) {
4399 hw_cr4 &= ~X86_CR4_PAE;
4400 }
4401 }
4402
4403 if (!enable_unrestricted_guest && !is_paging(vcpu))
4404 /*
4405 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
4406 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
4407 * to be manually disabled when guest switches to non-paging
4408 * mode.
4409 *
4410 * If !enable_unrestricted_guest, the CPU is always running
4411 * with CR0.PG=1 and CR4 needs to be modified.
4412 * If enable_unrestricted_guest, the CPU automatically
4413 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
4414 */
4415 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
4416
4417 vmcs_writel(CR4_READ_SHADOW, cr4);
4418 vmcs_writel(GUEST_CR4, hw_cr4);
4419 return 0;
4420 }
4421
4422 static void vmx_get_segment(struct kvm_vcpu *vcpu,
4423 struct kvm_segment *var, int seg)
4424 {
4425 struct vcpu_vmx *vmx = to_vmx(vcpu);
4426 u32 ar;
4427
4428 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4429 *var = vmx->rmode.segs[seg];
4430 if (seg == VCPU_SREG_TR
4431 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
4432 return;
4433 var->base = vmx_read_guest_seg_base(vmx, seg);
4434 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4435 return;
4436 }
4437 var->base = vmx_read_guest_seg_base(vmx, seg);
4438 var->limit = vmx_read_guest_seg_limit(vmx, seg);
4439 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4440 ar = vmx_read_guest_seg_ar(vmx, seg);
4441 var->unusable = (ar >> 16) & 1;
4442 var->type = ar & 15;
4443 var->s = (ar >> 4) & 1;
4444 var->dpl = (ar >> 5) & 3;
4445 /*
4446 * Some userspaces do not preserve unusable property. Since usable
4447 * segment has to be present according to VMX spec we can use present
4448 * property to amend userspace bug by making unusable segment always
4449 * nonpresent. vmx_segment_access_rights() already marks nonpresent
4450 * segment as unusable.
4451 */
4452 var->present = !var->unusable;
4453 var->avl = (ar >> 12) & 1;
4454 var->l = (ar >> 13) & 1;
4455 var->db = (ar >> 14) & 1;
4456 var->g = (ar >> 15) & 1;
4457 }
4458
4459 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
4460 {
4461 struct kvm_segment s;
4462
4463 if (to_vmx(vcpu)->rmode.vm86_active) {
4464 vmx_get_segment(vcpu, &s, seg);
4465 return s.base;
4466 }
4467 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
4468 }
4469
4470 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
4471 {
4472 struct vcpu_vmx *vmx = to_vmx(vcpu);
4473
4474 if (unlikely(vmx->rmode.vm86_active))
4475 return 0;
4476 else {
4477 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
4478 return VMX_AR_DPL(ar);
4479 }
4480 }
4481
4482 static u32 vmx_segment_access_rights(struct kvm_segment *var)
4483 {
4484 u32 ar;
4485
4486 if (var->unusable || !var->present)
4487 ar = 1 << 16;
4488 else {
4489 ar = var->type & 15;
4490 ar |= (var->s & 1) << 4;
4491 ar |= (var->dpl & 3) << 5;
4492 ar |= (var->present & 1) << 7;
4493 ar |= (var->avl & 1) << 12;
4494 ar |= (var->l & 1) << 13;
4495 ar |= (var->db & 1) << 14;
4496 ar |= (var->g & 1) << 15;
4497 }
4498
4499 return ar;
4500 }
4501
4502 static void vmx_set_segment(struct kvm_vcpu *vcpu,
4503 struct kvm_segment *var, int seg)
4504 {
4505 struct vcpu_vmx *vmx = to_vmx(vcpu);
4506 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4507
4508 vmx_segment_cache_clear(vmx);
4509
4510 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4511 vmx->rmode.segs[seg] = *var;
4512 if (seg == VCPU_SREG_TR)
4513 vmcs_write16(sf->selector, var->selector);
4514 else if (var->s)
4515 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
4516 goto out;
4517 }
4518
4519 vmcs_writel(sf->base, var->base);
4520 vmcs_write32(sf->limit, var->limit);
4521 vmcs_write16(sf->selector, var->selector);
4522
4523 /*
4524 * Fix the "Accessed" bit in AR field of segment registers for older
4525 * qemu binaries.
4526 * IA32 arch specifies that at the time of processor reset the
4527 * "Accessed" bit in the AR field of segment registers is 1. And qemu
4528 * is setting it to 0 in the userland code. This causes invalid guest
4529 * state vmexit when "unrestricted guest" mode is turned on.
4530 * Fix for this setup issue in cpu_reset is being pushed in the qemu
4531 * tree. Newer qemu binaries with that qemu fix would not need this
4532 * kvm hack.
4533 */
4534 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
4535 var->type |= 0x1; /* Accessed */
4536
4537 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
4538
4539 out:
4540 vmx->emulation_required = emulation_required(vcpu);
4541 }
4542
4543 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4544 {
4545 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
4546
4547 *db = (ar >> 14) & 1;
4548 *l = (ar >> 13) & 1;
4549 }
4550
4551 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4552 {
4553 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
4554 dt->address = vmcs_readl(GUEST_IDTR_BASE);
4555 }
4556
4557 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4558 {
4559 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
4560 vmcs_writel(GUEST_IDTR_BASE, dt->address);
4561 }
4562
4563 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4564 {
4565 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
4566 dt->address = vmcs_readl(GUEST_GDTR_BASE);
4567 }
4568
4569 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4570 {
4571 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
4572 vmcs_writel(GUEST_GDTR_BASE, dt->address);
4573 }
4574
4575 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
4576 {
4577 struct kvm_segment var;
4578 u32 ar;
4579
4580 vmx_get_segment(vcpu, &var, seg);
4581 var.dpl = 0x3;
4582 if (seg == VCPU_SREG_CS)
4583 var.type = 0x3;
4584 ar = vmx_segment_access_rights(&var);
4585
4586 if (var.base != (var.selector << 4))
4587 return false;
4588 if (var.limit != 0xffff)
4589 return false;
4590 if (ar != 0xf3)
4591 return false;
4592
4593 return true;
4594 }
4595
4596 static bool code_segment_valid(struct kvm_vcpu *vcpu)
4597 {
4598 struct kvm_segment cs;
4599 unsigned int cs_rpl;
4600
4601 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4602 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
4603
4604 if (cs.unusable)
4605 return false;
4606 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
4607 return false;
4608 if (!cs.s)
4609 return false;
4610 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
4611 if (cs.dpl > cs_rpl)
4612 return false;
4613 } else {
4614 if (cs.dpl != cs_rpl)
4615 return false;
4616 }
4617 if (!cs.present)
4618 return false;
4619
4620 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
4621 return true;
4622 }
4623
4624 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
4625 {
4626 struct kvm_segment ss;
4627 unsigned int ss_rpl;
4628
4629 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4630 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
4631
4632 if (ss.unusable)
4633 return true;
4634 if (ss.type != 3 && ss.type != 7)
4635 return false;
4636 if (!ss.s)
4637 return false;
4638 if (ss.dpl != ss_rpl) /* DPL != RPL */
4639 return false;
4640 if (!ss.present)
4641 return false;
4642
4643 return true;
4644 }
4645
4646 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
4647 {
4648 struct kvm_segment var;
4649 unsigned int rpl;
4650
4651 vmx_get_segment(vcpu, &var, seg);
4652 rpl = var.selector & SEGMENT_RPL_MASK;
4653
4654 if (var.unusable)
4655 return true;
4656 if (!var.s)
4657 return false;
4658 if (!var.present)
4659 return false;
4660 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
4661 if (var.dpl < rpl) /* DPL < RPL */
4662 return false;
4663 }
4664
4665 /* TODO: Add other members to kvm_segment_field to allow checking for other access
4666 * rights flags
4667 */
4668 return true;
4669 }
4670
4671 static bool tr_valid(struct kvm_vcpu *vcpu)
4672 {
4673 struct kvm_segment tr;
4674
4675 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
4676
4677 if (tr.unusable)
4678 return false;
4679 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
4680 return false;
4681 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
4682 return false;
4683 if (!tr.present)
4684 return false;
4685
4686 return true;
4687 }
4688
4689 static bool ldtr_valid(struct kvm_vcpu *vcpu)
4690 {
4691 struct kvm_segment ldtr;
4692
4693 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
4694
4695 if (ldtr.unusable)
4696 return true;
4697 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
4698 return false;
4699 if (ldtr.type != 2)
4700 return false;
4701 if (!ldtr.present)
4702 return false;
4703
4704 return true;
4705 }
4706
4707 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
4708 {
4709 struct kvm_segment cs, ss;
4710
4711 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4712 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4713
4714 return ((cs.selector & SEGMENT_RPL_MASK) ==
4715 (ss.selector & SEGMENT_RPL_MASK));
4716 }
4717
4718 /*
4719 * Check if guest state is valid. Returns true if valid, false if
4720 * not.
4721 * We assume that registers are always usable
4722 */
4723 static bool guest_state_valid(struct kvm_vcpu *vcpu)
4724 {
4725 if (enable_unrestricted_guest)
4726 return true;
4727
4728 /* real mode guest state checks */
4729 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
4730 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
4731 return false;
4732 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
4733 return false;
4734 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
4735 return false;
4736 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
4737 return false;
4738 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
4739 return false;
4740 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
4741 return false;
4742 } else {
4743 /* protected mode guest state checks */
4744 if (!cs_ss_rpl_check(vcpu))
4745 return false;
4746 if (!code_segment_valid(vcpu))
4747 return false;
4748 if (!stack_segment_valid(vcpu))
4749 return false;
4750 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
4751 return false;
4752 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
4753 return false;
4754 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
4755 return false;
4756 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
4757 return false;
4758 if (!tr_valid(vcpu))
4759 return false;
4760 if (!ldtr_valid(vcpu))
4761 return false;
4762 }
4763 /* TODO:
4764 * - Add checks on RIP
4765 * - Add checks on RFLAGS
4766 */
4767
4768 return true;
4769 }
4770
4771 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
4772 {
4773 return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
4774 }
4775
4776 static int init_rmode_tss(struct kvm *kvm)
4777 {
4778 gfn_t fn;
4779 u16 data = 0;
4780 int idx, r;
4781
4782 idx = srcu_read_lock(&kvm->srcu);
4783 fn = kvm->arch.tss_addr >> PAGE_SHIFT;
4784 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4785 if (r < 0)
4786 goto out;
4787 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
4788 r = kvm_write_guest_page(kvm, fn++, &data,
4789 TSS_IOPB_BASE_OFFSET, sizeof(u16));
4790 if (r < 0)
4791 goto out;
4792 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
4793 if (r < 0)
4794 goto out;
4795 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4796 if (r < 0)
4797 goto out;
4798 data = ~0;
4799 r = kvm_write_guest_page(kvm, fn, &data,
4800 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
4801 sizeof(u8));
4802 out:
4803 srcu_read_unlock(&kvm->srcu, idx);
4804 return r;
4805 }
4806
4807 static int init_rmode_identity_map(struct kvm *kvm)
4808 {
4809 int i, idx, r = 0;
4810 kvm_pfn_t identity_map_pfn;
4811 u32 tmp;
4812
4813 /* Protect kvm->arch.ept_identity_pagetable_done. */
4814 mutex_lock(&kvm->slots_lock);
4815
4816 if (likely(kvm->arch.ept_identity_pagetable_done))
4817 goto out2;
4818
4819 if (!kvm->arch.ept_identity_map_addr)
4820 kvm->arch.ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
4821 identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
4822
4823 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
4824 kvm->arch.ept_identity_map_addr, PAGE_SIZE);
4825 if (r < 0)
4826 goto out2;
4827
4828 idx = srcu_read_lock(&kvm->srcu);
4829 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
4830 if (r < 0)
4831 goto out;
4832 /* Set up identity-mapping pagetable for EPT in real mode */
4833 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
4834 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
4835 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
4836 r = kvm_write_guest_page(kvm, identity_map_pfn,
4837 &tmp, i * sizeof(tmp), sizeof(tmp));
4838 if (r < 0)
4839 goto out;
4840 }
4841 kvm->arch.ept_identity_pagetable_done = true;
4842
4843 out:
4844 srcu_read_unlock(&kvm->srcu, idx);
4845
4846 out2:
4847 mutex_unlock(&kvm->slots_lock);
4848 return r;
4849 }
4850
4851 static void seg_setup(int seg)
4852 {
4853 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4854 unsigned int ar;
4855
4856 vmcs_write16(sf->selector, 0);
4857 vmcs_writel(sf->base, 0);
4858 vmcs_write32(sf->limit, 0xffff);
4859 ar = 0x93;
4860 if (seg == VCPU_SREG_CS)
4861 ar |= 0x08; /* code segment */
4862
4863 vmcs_write32(sf->ar_bytes, ar);
4864 }
4865
4866 static int alloc_apic_access_page(struct kvm *kvm)
4867 {
4868 struct page *page;
4869 int r = 0;
4870
4871 mutex_lock(&kvm->slots_lock);
4872 if (kvm->arch.apic_access_page_done)
4873 goto out;
4874 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
4875 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
4876 if (r)
4877 goto out;
4878
4879 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
4880 if (is_error_page(page)) {
4881 r = -EFAULT;
4882 goto out;
4883 }
4884
4885 /*
4886 * Do not pin the page in memory, so that memory hot-unplug
4887 * is able to migrate it.
4888 */
4889 put_page(page);
4890 kvm->arch.apic_access_page_done = true;
4891 out:
4892 mutex_unlock(&kvm->slots_lock);
4893 return r;
4894 }
4895
4896 static int allocate_vpid(void)
4897 {
4898 int vpid;
4899
4900 if (!enable_vpid)
4901 return 0;
4902 spin_lock(&vmx_vpid_lock);
4903 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
4904 if (vpid < VMX_NR_VPIDS)
4905 __set_bit(vpid, vmx_vpid_bitmap);
4906 else
4907 vpid = 0;
4908 spin_unlock(&vmx_vpid_lock);
4909 return vpid;
4910 }
4911
4912 static void free_vpid(int vpid)
4913 {
4914 if (!enable_vpid || vpid == 0)
4915 return;
4916 spin_lock(&vmx_vpid_lock);
4917 __clear_bit(vpid, vmx_vpid_bitmap);
4918 spin_unlock(&vmx_vpid_lock);
4919 }
4920
4921 #define MSR_TYPE_R 1
4922 #define MSR_TYPE_W 2
4923 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
4924 u32 msr, int type)
4925 {
4926 int f = sizeof(unsigned long);
4927
4928 if (!cpu_has_vmx_msr_bitmap())
4929 return;
4930
4931 /*
4932 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4933 * have the write-low and read-high bitmap offsets the wrong way round.
4934 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4935 */
4936 if (msr <= 0x1fff) {
4937 if (type & MSR_TYPE_R)
4938 /* read-low */
4939 __clear_bit(msr, msr_bitmap + 0x000 / f);
4940
4941 if (type & MSR_TYPE_W)
4942 /* write-low */
4943 __clear_bit(msr, msr_bitmap + 0x800 / f);
4944
4945 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4946 msr &= 0x1fff;
4947 if (type & MSR_TYPE_R)
4948 /* read-high */
4949 __clear_bit(msr, msr_bitmap + 0x400 / f);
4950
4951 if (type & MSR_TYPE_W)
4952 /* write-high */
4953 __clear_bit(msr, msr_bitmap + 0xc00 / f);
4954
4955 }
4956 }
4957
4958 /*
4959 * If a msr is allowed by L0, we should check whether it is allowed by L1.
4960 * The corresponding bit will be cleared unless both of L0 and L1 allow it.
4961 */
4962 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
4963 unsigned long *msr_bitmap_nested,
4964 u32 msr, int type)
4965 {
4966 int f = sizeof(unsigned long);
4967
4968 if (!cpu_has_vmx_msr_bitmap()) {
4969 WARN_ON(1);
4970 return;
4971 }
4972
4973 /*
4974 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4975 * have the write-low and read-high bitmap offsets the wrong way round.
4976 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4977 */
4978 if (msr <= 0x1fff) {
4979 if (type & MSR_TYPE_R &&
4980 !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
4981 /* read-low */
4982 __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
4983
4984 if (type & MSR_TYPE_W &&
4985 !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
4986 /* write-low */
4987 __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
4988
4989 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4990 msr &= 0x1fff;
4991 if (type & MSR_TYPE_R &&
4992 !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
4993 /* read-high */
4994 __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
4995
4996 if (type & MSR_TYPE_W &&
4997 !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
4998 /* write-high */
4999 __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
5000
5001 }
5002 }
5003
5004 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
5005 {
5006 if (!longmode_only)
5007 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
5008 msr, MSR_TYPE_R | MSR_TYPE_W);
5009 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
5010 msr, MSR_TYPE_R | MSR_TYPE_W);
5011 }
5012
5013 static void vmx_disable_intercept_msr_x2apic(u32 msr, int type, bool apicv_active)
5014 {
5015 if (apicv_active) {
5016 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic_apicv,
5017 msr, type);
5018 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic_apicv,
5019 msr, type);
5020 } else {
5021 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
5022 msr, type);
5023 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
5024 msr, type);
5025 }
5026 }
5027
5028 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
5029 {
5030 return enable_apicv;
5031 }
5032
5033 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
5034 {
5035 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5036 gfn_t gfn;
5037
5038 /*
5039 * Don't need to mark the APIC access page dirty; it is never
5040 * written to by the CPU during APIC virtualization.
5041 */
5042
5043 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
5044 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
5045 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5046 }
5047
5048 if (nested_cpu_has_posted_intr(vmcs12)) {
5049 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
5050 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5051 }
5052 }
5053
5054
5055 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
5056 {
5057 struct vcpu_vmx *vmx = to_vmx(vcpu);
5058 int max_irr;
5059 void *vapic_page;
5060 u16 status;
5061
5062 if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
5063 return;
5064
5065 vmx->nested.pi_pending = false;
5066 if (!pi_test_and_clear_on(vmx->nested.pi_desc))
5067 return;
5068
5069 max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
5070 if (max_irr != 256) {
5071 vapic_page = kmap(vmx->nested.virtual_apic_page);
5072 __kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page);
5073 kunmap(vmx->nested.virtual_apic_page);
5074
5075 status = vmcs_read16(GUEST_INTR_STATUS);
5076 if ((u8)max_irr > ((u8)status & 0xff)) {
5077 status &= ~0xff;
5078 status |= (u8)max_irr;
5079 vmcs_write16(GUEST_INTR_STATUS, status);
5080 }
5081 }
5082
5083 nested_mark_vmcs12_pages_dirty(vcpu);
5084 }
5085
5086 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
5087 bool nested)
5088 {
5089 #ifdef CONFIG_SMP
5090 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
5091
5092 if (vcpu->mode == IN_GUEST_MODE) {
5093 /*
5094 * The vector of interrupt to be delivered to vcpu had
5095 * been set in PIR before this function.
5096 *
5097 * Following cases will be reached in this block, and
5098 * we always send a notification event in all cases as
5099 * explained below.
5100 *
5101 * Case 1: vcpu keeps in non-root mode. Sending a
5102 * notification event posts the interrupt to vcpu.
5103 *
5104 * Case 2: vcpu exits to root mode and is still
5105 * runnable. PIR will be synced to vIRR before the
5106 * next vcpu entry. Sending a notification event in
5107 * this case has no effect, as vcpu is not in root
5108 * mode.
5109 *
5110 * Case 3: vcpu exits to root mode and is blocked.
5111 * vcpu_block() has already synced PIR to vIRR and
5112 * never blocks vcpu if vIRR is not cleared. Therefore,
5113 * a blocked vcpu here does not wait for any requested
5114 * interrupts in PIR, and sending a notification event
5115 * which has no effect is safe here.
5116 */
5117
5118 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
5119 return true;
5120 }
5121 #endif
5122 return false;
5123 }
5124
5125 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
5126 int vector)
5127 {
5128 struct vcpu_vmx *vmx = to_vmx(vcpu);
5129
5130 if (is_guest_mode(vcpu) &&
5131 vector == vmx->nested.posted_intr_nv) {
5132 /* the PIR and ON have been set by L1. */
5133 kvm_vcpu_trigger_posted_interrupt(vcpu, true);
5134 /*
5135 * If a posted intr is not recognized by hardware,
5136 * we will accomplish it in the next vmentry.
5137 */
5138 vmx->nested.pi_pending = true;
5139 kvm_make_request(KVM_REQ_EVENT, vcpu);
5140 return 0;
5141 }
5142 return -1;
5143 }
5144 /*
5145 * Send interrupt to vcpu via posted interrupt way.
5146 * 1. If target vcpu is running(non-root mode), send posted interrupt
5147 * notification to vcpu and hardware will sync PIR to vIRR atomically.
5148 * 2. If target vcpu isn't running(root mode), kick it to pick up the
5149 * interrupt from PIR in next vmentry.
5150 */
5151 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
5152 {
5153 struct vcpu_vmx *vmx = to_vmx(vcpu);
5154 int r;
5155
5156 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
5157 if (!r)
5158 return;
5159
5160 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
5161 return;
5162
5163 /* If a previous notification has sent the IPI, nothing to do. */
5164 if (pi_test_and_set_on(&vmx->pi_desc))
5165 return;
5166
5167 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
5168 kvm_vcpu_kick(vcpu);
5169 }
5170
5171 /*
5172 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
5173 * will not change in the lifetime of the guest.
5174 * Note that host-state that does change is set elsewhere. E.g., host-state
5175 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
5176 */
5177 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
5178 {
5179 u32 low32, high32;
5180 unsigned long tmpl;
5181 struct desc_ptr dt;
5182 unsigned long cr0, cr3, cr4;
5183
5184 cr0 = read_cr0();
5185 WARN_ON(cr0 & X86_CR0_TS);
5186 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
5187
5188 /*
5189 * Save the most likely value for this task's CR3 in the VMCS.
5190 * We can't use __get_current_cr3_fast() because we're not atomic.
5191 */
5192 cr3 = __read_cr3();
5193 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
5194 vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
5195
5196 /* Save the most likely value for this task's CR4 in the VMCS. */
5197 cr4 = cr4_read_shadow();
5198 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
5199 vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
5200
5201 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
5202 #ifdef CONFIG_X86_64
5203 /*
5204 * Load null selectors, so we can avoid reloading them in
5205 * __vmx_load_host_state(), in case userspace uses the null selectors
5206 * too (the expected case).
5207 */
5208 vmcs_write16(HOST_DS_SELECTOR, 0);
5209 vmcs_write16(HOST_ES_SELECTOR, 0);
5210 #else
5211 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5212 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5213 #endif
5214 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5215 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
5216
5217 store_idt(&dt);
5218 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
5219 vmx->host_idt_base = dt.address;
5220
5221 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
5222
5223 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
5224 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
5225 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
5226 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
5227
5228 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
5229 rdmsr(MSR_IA32_CR_PAT, low32, high32);
5230 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
5231 }
5232 }
5233
5234 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
5235 {
5236 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
5237 if (enable_ept)
5238 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
5239 if (is_guest_mode(&vmx->vcpu))
5240 vmx->vcpu.arch.cr4_guest_owned_bits &=
5241 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
5242 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
5243 }
5244
5245 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
5246 {
5247 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
5248
5249 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
5250 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
5251
5252 if (!enable_vnmi)
5253 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
5254
5255 /* Enable the preemption timer dynamically */
5256 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
5257 return pin_based_exec_ctrl;
5258 }
5259
5260 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5261 {
5262 struct vcpu_vmx *vmx = to_vmx(vcpu);
5263
5264 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5265 if (cpu_has_secondary_exec_ctrls()) {
5266 if (kvm_vcpu_apicv_active(vcpu))
5267 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5268 SECONDARY_EXEC_APIC_REGISTER_VIRT |
5269 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5270 else
5271 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5272 SECONDARY_EXEC_APIC_REGISTER_VIRT |
5273 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5274 }
5275
5276 if (cpu_has_vmx_msr_bitmap())
5277 vmx_set_msr_bitmap(vcpu);
5278 }
5279
5280 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
5281 {
5282 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
5283
5284 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
5285 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
5286
5287 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
5288 exec_control &= ~CPU_BASED_TPR_SHADOW;
5289 #ifdef CONFIG_X86_64
5290 exec_control |= CPU_BASED_CR8_STORE_EXITING |
5291 CPU_BASED_CR8_LOAD_EXITING;
5292 #endif
5293 }
5294 if (!enable_ept)
5295 exec_control |= CPU_BASED_CR3_STORE_EXITING |
5296 CPU_BASED_CR3_LOAD_EXITING |
5297 CPU_BASED_INVLPG_EXITING;
5298 return exec_control;
5299 }
5300
5301 static bool vmx_rdrand_supported(void)
5302 {
5303 return vmcs_config.cpu_based_2nd_exec_ctrl &
5304 SECONDARY_EXEC_RDRAND_EXITING;
5305 }
5306
5307 static bool vmx_rdseed_supported(void)
5308 {
5309 return vmcs_config.cpu_based_2nd_exec_ctrl &
5310 SECONDARY_EXEC_RDSEED_EXITING;
5311 }
5312
5313 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
5314 {
5315 struct kvm_vcpu *vcpu = &vmx->vcpu;
5316
5317 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
5318 if (!cpu_need_virtualize_apic_accesses(vcpu))
5319 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5320 if (vmx->vpid == 0)
5321 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
5322 if (!enable_ept) {
5323 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
5324 enable_unrestricted_guest = 0;
5325 /* Enable INVPCID for non-ept guests may cause performance regression. */
5326 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5327 }
5328 if (!enable_unrestricted_guest)
5329 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
5330 if (!ple_gap)
5331 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
5332 if (!kvm_vcpu_apicv_active(vcpu))
5333 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
5334 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5335 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5336 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
5337 (handle_vmptrld).
5338 We can NOT enable shadow_vmcs here because we don't have yet
5339 a current VMCS12
5340 */
5341 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
5342
5343 if (!enable_pml)
5344 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
5345
5346 if (vmx_xsaves_supported()) {
5347 /* Exposing XSAVES only when XSAVE is exposed */
5348 bool xsaves_enabled =
5349 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
5350 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
5351
5352 if (!xsaves_enabled)
5353 exec_control &= ~SECONDARY_EXEC_XSAVES;
5354
5355 if (nested) {
5356 if (xsaves_enabled)
5357 vmx->nested.nested_vmx_secondary_ctls_high |=
5358 SECONDARY_EXEC_XSAVES;
5359 else
5360 vmx->nested.nested_vmx_secondary_ctls_high &=
5361 ~SECONDARY_EXEC_XSAVES;
5362 }
5363 }
5364
5365 if (vmx_rdtscp_supported()) {
5366 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
5367 if (!rdtscp_enabled)
5368 exec_control &= ~SECONDARY_EXEC_RDTSCP;
5369
5370 if (nested) {
5371 if (rdtscp_enabled)
5372 vmx->nested.nested_vmx_secondary_ctls_high |=
5373 SECONDARY_EXEC_RDTSCP;
5374 else
5375 vmx->nested.nested_vmx_secondary_ctls_high &=
5376 ~SECONDARY_EXEC_RDTSCP;
5377 }
5378 }
5379
5380 if (vmx_invpcid_supported()) {
5381 /* Exposing INVPCID only when PCID is exposed */
5382 bool invpcid_enabled =
5383 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
5384 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
5385
5386 if (!invpcid_enabled) {
5387 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5388 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
5389 }
5390
5391 if (nested) {
5392 if (invpcid_enabled)
5393 vmx->nested.nested_vmx_secondary_ctls_high |=
5394 SECONDARY_EXEC_ENABLE_INVPCID;
5395 else
5396 vmx->nested.nested_vmx_secondary_ctls_high &=
5397 ~SECONDARY_EXEC_ENABLE_INVPCID;
5398 }
5399 }
5400
5401 if (vmx_rdrand_supported()) {
5402 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
5403 if (rdrand_enabled)
5404 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
5405
5406 if (nested) {
5407 if (rdrand_enabled)
5408 vmx->nested.nested_vmx_secondary_ctls_high |=
5409 SECONDARY_EXEC_RDRAND_EXITING;
5410 else
5411 vmx->nested.nested_vmx_secondary_ctls_high &=
5412 ~SECONDARY_EXEC_RDRAND_EXITING;
5413 }
5414 }
5415
5416 if (vmx_rdseed_supported()) {
5417 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
5418 if (rdseed_enabled)
5419 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
5420
5421 if (nested) {
5422 if (rdseed_enabled)
5423 vmx->nested.nested_vmx_secondary_ctls_high |=
5424 SECONDARY_EXEC_RDSEED_EXITING;
5425 else
5426 vmx->nested.nested_vmx_secondary_ctls_high &=
5427 ~SECONDARY_EXEC_RDSEED_EXITING;
5428 }
5429 }
5430
5431 vmx->secondary_exec_control = exec_control;
5432 }
5433
5434 static void ept_set_mmio_spte_mask(void)
5435 {
5436 /*
5437 * EPT Misconfigurations can be generated if the value of bits 2:0
5438 * of an EPT paging-structure entry is 110b (write/execute).
5439 */
5440 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
5441 VMX_EPT_MISCONFIG_WX_VALUE);
5442 }
5443
5444 #define VMX_XSS_EXIT_BITMAP 0
5445 /*
5446 * Sets up the vmcs for emulated real mode.
5447 */
5448 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
5449 {
5450 #ifdef CONFIG_X86_64
5451 unsigned long a;
5452 #endif
5453 int i;
5454
5455 /* I/O */
5456 vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
5457 vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
5458
5459 if (enable_shadow_vmcs) {
5460 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
5461 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
5462 }
5463 if (cpu_has_vmx_msr_bitmap())
5464 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
5465
5466 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
5467
5468 /* Control */
5469 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5470 vmx->hv_deadline_tsc = -1;
5471
5472 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
5473
5474 if (cpu_has_secondary_exec_ctrls()) {
5475 vmx_compute_secondary_exec_control(vmx);
5476 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
5477 vmx->secondary_exec_control);
5478 }
5479
5480 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
5481 vmcs_write64(EOI_EXIT_BITMAP0, 0);
5482 vmcs_write64(EOI_EXIT_BITMAP1, 0);
5483 vmcs_write64(EOI_EXIT_BITMAP2, 0);
5484 vmcs_write64(EOI_EXIT_BITMAP3, 0);
5485
5486 vmcs_write16(GUEST_INTR_STATUS, 0);
5487
5488 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
5489 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
5490 }
5491
5492 if (ple_gap) {
5493 vmcs_write32(PLE_GAP, ple_gap);
5494 vmx->ple_window = ple_window;
5495 vmx->ple_window_dirty = true;
5496 }
5497
5498 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
5499 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
5500 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
5501
5502 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
5503 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
5504 vmx_set_constant_host_state(vmx);
5505 #ifdef CONFIG_X86_64
5506 rdmsrl(MSR_FS_BASE, a);
5507 vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
5508 rdmsrl(MSR_GS_BASE, a);
5509 vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
5510 #else
5511 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
5512 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
5513 #endif
5514
5515 if (cpu_has_vmx_vmfunc())
5516 vmcs_write64(VM_FUNCTION_CONTROL, 0);
5517
5518 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
5519 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
5520 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
5521 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
5522 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
5523
5524 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
5525 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
5526
5527 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
5528 u32 index = vmx_msr_index[i];
5529 u32 data_low, data_high;
5530 int j = vmx->nmsrs;
5531
5532 if (rdmsr_safe(index, &data_low, &data_high) < 0)
5533 continue;
5534 if (wrmsr_safe(index, data_low, data_high) < 0)
5535 continue;
5536 vmx->guest_msrs[j].index = i;
5537 vmx->guest_msrs[j].data = 0;
5538 vmx->guest_msrs[j].mask = -1ull;
5539 ++vmx->nmsrs;
5540 }
5541
5542
5543 vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
5544
5545 /* 22.2.1, 20.8.1 */
5546 vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
5547
5548 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
5549 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
5550
5551 set_cr4_guest_host_mask(vmx);
5552
5553 if (vmx_xsaves_supported())
5554 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
5555
5556 if (enable_pml) {
5557 ASSERT(vmx->pml_pg);
5558 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
5559 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5560 }
5561 }
5562
5563 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
5564 {
5565 struct vcpu_vmx *vmx = to_vmx(vcpu);
5566 struct msr_data apic_base_msr;
5567 u64 cr0;
5568
5569 vmx->rmode.vm86_active = 0;
5570
5571 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
5572 kvm_set_cr8(vcpu, 0);
5573
5574 if (!init_event) {
5575 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
5576 MSR_IA32_APICBASE_ENABLE;
5577 if (kvm_vcpu_is_reset_bsp(vcpu))
5578 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
5579 apic_base_msr.host_initiated = true;
5580 kvm_set_apic_base(vcpu, &apic_base_msr);
5581 }
5582
5583 vmx_segment_cache_clear(vmx);
5584
5585 seg_setup(VCPU_SREG_CS);
5586 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
5587 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
5588
5589 seg_setup(VCPU_SREG_DS);
5590 seg_setup(VCPU_SREG_ES);
5591 seg_setup(VCPU_SREG_FS);
5592 seg_setup(VCPU_SREG_GS);
5593 seg_setup(VCPU_SREG_SS);
5594
5595 vmcs_write16(GUEST_TR_SELECTOR, 0);
5596 vmcs_writel(GUEST_TR_BASE, 0);
5597 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
5598 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5599
5600 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
5601 vmcs_writel(GUEST_LDTR_BASE, 0);
5602 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
5603 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
5604
5605 if (!init_event) {
5606 vmcs_write32(GUEST_SYSENTER_CS, 0);
5607 vmcs_writel(GUEST_SYSENTER_ESP, 0);
5608 vmcs_writel(GUEST_SYSENTER_EIP, 0);
5609 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
5610 }
5611
5612 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
5613 kvm_rip_write(vcpu, 0xfff0);
5614
5615 vmcs_writel(GUEST_GDTR_BASE, 0);
5616 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
5617
5618 vmcs_writel(GUEST_IDTR_BASE, 0);
5619 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
5620
5621 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
5622 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
5623 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
5624 if (kvm_mpx_supported())
5625 vmcs_write64(GUEST_BNDCFGS, 0);
5626
5627 setup_msrs(vmx);
5628
5629 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
5630
5631 if (cpu_has_vmx_tpr_shadow() && !init_event) {
5632 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
5633 if (cpu_need_tpr_shadow(vcpu))
5634 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
5635 __pa(vcpu->arch.apic->regs));
5636 vmcs_write32(TPR_THRESHOLD, 0);
5637 }
5638
5639 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
5640
5641 if (vmx->vpid != 0)
5642 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
5643
5644 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
5645 vmx->vcpu.arch.cr0 = cr0;
5646 vmx_set_cr0(vcpu, cr0); /* enter rmode */
5647 vmx_set_cr4(vcpu, 0);
5648 vmx_set_efer(vcpu, 0);
5649
5650 update_exception_bitmap(vcpu);
5651
5652 vpid_sync_context(vmx->vpid);
5653 }
5654
5655 /*
5656 * In nested virtualization, check if L1 asked to exit on external interrupts.
5657 * For most existing hypervisors, this will always return true.
5658 */
5659 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
5660 {
5661 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5662 PIN_BASED_EXT_INTR_MASK;
5663 }
5664
5665 /*
5666 * In nested virtualization, check if L1 has set
5667 * VM_EXIT_ACK_INTR_ON_EXIT
5668 */
5669 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
5670 {
5671 return get_vmcs12(vcpu)->vm_exit_controls &
5672 VM_EXIT_ACK_INTR_ON_EXIT;
5673 }
5674
5675 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
5676 {
5677 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5678 PIN_BASED_NMI_EXITING;
5679 }
5680
5681 static void enable_irq_window(struct kvm_vcpu *vcpu)
5682 {
5683 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
5684 CPU_BASED_VIRTUAL_INTR_PENDING);
5685 }
5686
5687 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5688 {
5689 if (!enable_vnmi ||
5690 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
5691 enable_irq_window(vcpu);
5692 return;
5693 }
5694
5695 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
5696 CPU_BASED_VIRTUAL_NMI_PENDING);
5697 }
5698
5699 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
5700 {
5701 struct vcpu_vmx *vmx = to_vmx(vcpu);
5702 uint32_t intr;
5703 int irq = vcpu->arch.interrupt.nr;
5704
5705 trace_kvm_inj_virq(irq);
5706
5707 ++vcpu->stat.irq_injections;
5708 if (vmx->rmode.vm86_active) {
5709 int inc_eip = 0;
5710 if (vcpu->arch.interrupt.soft)
5711 inc_eip = vcpu->arch.event_exit_inst_len;
5712 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
5713 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5714 return;
5715 }
5716 intr = irq | INTR_INFO_VALID_MASK;
5717 if (vcpu->arch.interrupt.soft) {
5718 intr |= INTR_TYPE_SOFT_INTR;
5719 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
5720 vmx->vcpu.arch.event_exit_inst_len);
5721 } else
5722 intr |= INTR_TYPE_EXT_INTR;
5723 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
5724 }
5725
5726 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
5727 {
5728 struct vcpu_vmx *vmx = to_vmx(vcpu);
5729
5730 if (!enable_vnmi) {
5731 /*
5732 * Tracking the NMI-blocked state in software is built upon
5733 * finding the next open IRQ window. This, in turn, depends on
5734 * well-behaving guests: They have to keep IRQs disabled at
5735 * least as long as the NMI handler runs. Otherwise we may
5736 * cause NMI nesting, maybe breaking the guest. But as this is
5737 * highly unlikely, we can live with the residual risk.
5738 */
5739 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
5740 vmx->loaded_vmcs->vnmi_blocked_time = 0;
5741 }
5742
5743 ++vcpu->stat.nmi_injections;
5744 vmx->loaded_vmcs->nmi_known_unmasked = false;
5745
5746 if (vmx->rmode.vm86_active) {
5747 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
5748 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5749 return;
5750 }
5751
5752 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
5753 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
5754 }
5755
5756 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
5757 {
5758 struct vcpu_vmx *vmx = to_vmx(vcpu);
5759 bool masked;
5760
5761 if (!enable_vnmi)
5762 return vmx->loaded_vmcs->soft_vnmi_blocked;
5763 if (vmx->loaded_vmcs->nmi_known_unmasked)
5764 return false;
5765 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
5766 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5767 return masked;
5768 }
5769
5770 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5771 {
5772 struct vcpu_vmx *vmx = to_vmx(vcpu);
5773
5774 if (!enable_vnmi) {
5775 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
5776 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
5777 vmx->loaded_vmcs->vnmi_blocked_time = 0;
5778 }
5779 } else {
5780 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5781 if (masked)
5782 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5783 GUEST_INTR_STATE_NMI);
5784 else
5785 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
5786 GUEST_INTR_STATE_NMI);
5787 }
5788 }
5789
5790 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
5791 {
5792 if (to_vmx(vcpu)->nested.nested_run_pending)
5793 return 0;
5794
5795 if (!enable_vnmi &&
5796 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
5797 return 0;
5798
5799 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5800 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
5801 | GUEST_INTR_STATE_NMI));
5802 }
5803
5804 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
5805 {
5806 return (!to_vmx(vcpu)->nested.nested_run_pending &&
5807 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
5808 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5809 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
5810 }
5811
5812 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
5813 {
5814 int ret;
5815
5816 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
5817 PAGE_SIZE * 3);
5818 if (ret)
5819 return ret;
5820 kvm->arch.tss_addr = addr;
5821 return init_rmode_tss(kvm);
5822 }
5823
5824 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
5825 {
5826 switch (vec) {
5827 case BP_VECTOR:
5828 /*
5829 * Update instruction length as we may reinject the exception
5830 * from user space while in guest debugging mode.
5831 */
5832 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
5833 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5834 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5835 return false;
5836 /* fall through */
5837 case DB_VECTOR:
5838 if (vcpu->guest_debug &
5839 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
5840 return false;
5841 /* fall through */
5842 case DE_VECTOR:
5843 case OF_VECTOR:
5844 case BR_VECTOR:
5845 case UD_VECTOR:
5846 case DF_VECTOR:
5847 case SS_VECTOR:
5848 case GP_VECTOR:
5849 case MF_VECTOR:
5850 return true;
5851 break;
5852 }
5853 return false;
5854 }
5855
5856 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
5857 int vec, u32 err_code)
5858 {
5859 /*
5860 * Instruction with address size override prefix opcode 0x67
5861 * Cause the #SS fault with 0 error code in VM86 mode.
5862 */
5863 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5864 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
5865 if (vcpu->arch.halt_request) {
5866 vcpu->arch.halt_request = 0;
5867 return kvm_vcpu_halt(vcpu);
5868 }
5869 return 1;
5870 }
5871 return 0;
5872 }
5873
5874 /*
5875 * Forward all other exceptions that are valid in real mode.
5876 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5877 * the required debugging infrastructure rework.
5878 */
5879 kvm_queue_exception(vcpu, vec);
5880 return 1;
5881 }
5882
5883 /*
5884 * Trigger machine check on the host. We assume all the MSRs are already set up
5885 * by the CPU and that we still run on the same CPU as the MCE occurred on.
5886 * We pass a fake environment to the machine check handler because we want
5887 * the guest to be always treated like user space, no matter what context
5888 * it used internally.
5889 */
5890 static void kvm_machine_check(void)
5891 {
5892 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
5893 struct pt_regs regs = {
5894 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
5895 .flags = X86_EFLAGS_IF,
5896 };
5897
5898 do_machine_check(&regs, 0);
5899 #endif
5900 }
5901
5902 static int handle_machine_check(struct kvm_vcpu *vcpu)
5903 {
5904 /* already handled by vcpu_run */
5905 return 1;
5906 }
5907
5908 static int handle_exception(struct kvm_vcpu *vcpu)
5909 {
5910 struct vcpu_vmx *vmx = to_vmx(vcpu);
5911 struct kvm_run *kvm_run = vcpu->run;
5912 u32 intr_info, ex_no, error_code;
5913 unsigned long cr2, rip, dr6;
5914 u32 vect_info;
5915 enum emulation_result er;
5916
5917 vect_info = vmx->idt_vectoring_info;
5918 intr_info = vmx->exit_intr_info;
5919
5920 if (is_machine_check(intr_info))
5921 return handle_machine_check(vcpu);
5922
5923 if (is_nmi(intr_info))
5924 return 1; /* already handled by vmx_vcpu_run() */
5925
5926 if (is_invalid_opcode(intr_info)) {
5927 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
5928 if (er == EMULATE_USER_EXIT)
5929 return 0;
5930 if (er != EMULATE_DONE)
5931 kvm_queue_exception(vcpu, UD_VECTOR);
5932 return 1;
5933 }
5934
5935 error_code = 0;
5936 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5937 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5938
5939 /*
5940 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5941 * MMIO, it is better to report an internal error.
5942 * See the comments in vmx_handle_exit.
5943 */
5944 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5945 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5946 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5947 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5948 vcpu->run->internal.ndata = 3;
5949 vcpu->run->internal.data[0] = vect_info;
5950 vcpu->run->internal.data[1] = intr_info;
5951 vcpu->run->internal.data[2] = error_code;
5952 return 0;
5953 }
5954
5955 if (is_page_fault(intr_info)) {
5956 cr2 = vmcs_readl(EXIT_QUALIFICATION);
5957 /* EPT won't cause page fault directly */
5958 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
5959 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
5960 }
5961
5962 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5963
5964 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5965 return handle_rmode_exception(vcpu, ex_no, error_code);
5966
5967 switch (ex_no) {
5968 case AC_VECTOR:
5969 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5970 return 1;
5971 case DB_VECTOR:
5972 dr6 = vmcs_readl(EXIT_QUALIFICATION);
5973 if (!(vcpu->guest_debug &
5974 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5975 vcpu->arch.dr6 &= ~15;
5976 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5977 if (!(dr6 & ~DR6_RESERVED)) /* icebp */
5978 skip_emulated_instruction(vcpu);
5979
5980 kvm_queue_exception(vcpu, DB_VECTOR);
5981 return 1;
5982 }
5983 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
5984 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5985 /* fall through */
5986 case BP_VECTOR:
5987 /*
5988 * Update instruction length as we may reinject #BP from
5989 * user space while in guest debugging mode. Reading it for
5990 * #DB as well causes no harm, it is not used in that case.
5991 */
5992 vmx->vcpu.arch.event_exit_inst_len =
5993 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5994 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5995 rip = kvm_rip_read(vcpu);
5996 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
5997 kvm_run->debug.arch.exception = ex_no;
5998 break;
5999 default:
6000 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
6001 kvm_run->ex.exception = ex_no;
6002 kvm_run->ex.error_code = error_code;
6003 break;
6004 }
6005 return 0;
6006 }
6007
6008 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
6009 {
6010 ++vcpu->stat.irq_exits;
6011 return 1;
6012 }
6013
6014 static int handle_triple_fault(struct kvm_vcpu *vcpu)
6015 {
6016 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6017 vcpu->mmio_needed = 0;
6018 return 0;
6019 }
6020
6021 static int handle_io(struct kvm_vcpu *vcpu)
6022 {
6023 unsigned long exit_qualification;
6024 int size, in, string, ret;
6025 unsigned port;
6026
6027 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6028 string = (exit_qualification & 16) != 0;
6029 in = (exit_qualification & 8) != 0;
6030
6031 ++vcpu->stat.io_exits;
6032
6033 if (string || in)
6034 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6035
6036 port = exit_qualification >> 16;
6037 size = (exit_qualification & 7) + 1;
6038
6039 ret = kvm_skip_emulated_instruction(vcpu);
6040
6041 /*
6042 * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
6043 * KVM_EXIT_DEBUG here.
6044 */
6045 return kvm_fast_pio_out(vcpu, size, port) && ret;
6046 }
6047
6048 static void
6049 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
6050 {
6051 /*
6052 * Patch in the VMCALL instruction:
6053 */
6054 hypercall[0] = 0x0f;
6055 hypercall[1] = 0x01;
6056 hypercall[2] = 0xc1;
6057 }
6058
6059 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
6060 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
6061 {
6062 if (is_guest_mode(vcpu)) {
6063 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6064 unsigned long orig_val = val;
6065
6066 /*
6067 * We get here when L2 changed cr0 in a way that did not change
6068 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6069 * but did change L0 shadowed bits. So we first calculate the
6070 * effective cr0 value that L1 would like to write into the
6071 * hardware. It consists of the L2-owned bits from the new
6072 * value combined with the L1-owned bits from L1's guest_cr0.
6073 */
6074 val = (val & ~vmcs12->cr0_guest_host_mask) |
6075 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6076
6077 if (!nested_guest_cr0_valid(vcpu, val))
6078 return 1;
6079
6080 if (kvm_set_cr0(vcpu, val))
6081 return 1;
6082 vmcs_writel(CR0_READ_SHADOW, orig_val);
6083 return 0;
6084 } else {
6085 if (to_vmx(vcpu)->nested.vmxon &&
6086 !nested_host_cr0_valid(vcpu, val))
6087 return 1;
6088
6089 return kvm_set_cr0(vcpu, val);
6090 }
6091 }
6092
6093 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6094 {
6095 if (is_guest_mode(vcpu)) {
6096 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6097 unsigned long orig_val = val;
6098
6099 /* analogously to handle_set_cr0 */
6100 val = (val & ~vmcs12->cr4_guest_host_mask) |
6101 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6102 if (kvm_set_cr4(vcpu, val))
6103 return 1;
6104 vmcs_writel(CR4_READ_SHADOW, orig_val);
6105 return 0;
6106 } else
6107 return kvm_set_cr4(vcpu, val);
6108 }
6109
6110 static int handle_cr(struct kvm_vcpu *vcpu)
6111 {
6112 unsigned long exit_qualification, val;
6113 int cr;
6114 int reg;
6115 int err;
6116 int ret;
6117
6118 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6119 cr = exit_qualification & 15;
6120 reg = (exit_qualification >> 8) & 15;
6121 switch ((exit_qualification >> 4) & 3) {
6122 case 0: /* mov to cr */
6123 val = kvm_register_readl(vcpu, reg);
6124 trace_kvm_cr_write(cr, val);
6125 switch (cr) {
6126 case 0:
6127 err = handle_set_cr0(vcpu, val);
6128 return kvm_complete_insn_gp(vcpu, err);
6129 case 3:
6130 err = kvm_set_cr3(vcpu, val);
6131 return kvm_complete_insn_gp(vcpu, err);
6132 case 4:
6133 err = handle_set_cr4(vcpu, val);
6134 return kvm_complete_insn_gp(vcpu, err);
6135 case 8: {
6136 u8 cr8_prev = kvm_get_cr8(vcpu);
6137 u8 cr8 = (u8)val;
6138 err = kvm_set_cr8(vcpu, cr8);
6139 ret = kvm_complete_insn_gp(vcpu, err);
6140 if (lapic_in_kernel(vcpu))
6141 return ret;
6142 if (cr8_prev <= cr8)
6143 return ret;
6144 /*
6145 * TODO: we might be squashing a
6146 * KVM_GUESTDBG_SINGLESTEP-triggered
6147 * KVM_EXIT_DEBUG here.
6148 */
6149 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
6150 return 0;
6151 }
6152 }
6153 break;
6154 case 2: /* clts */
6155 WARN_ONCE(1, "Guest should always own CR0.TS");
6156 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
6157 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
6158 return kvm_skip_emulated_instruction(vcpu);
6159 case 1: /*mov from cr*/
6160 switch (cr) {
6161 case 3:
6162 val = kvm_read_cr3(vcpu);
6163 kvm_register_write(vcpu, reg, val);
6164 trace_kvm_cr_read(cr, val);
6165 return kvm_skip_emulated_instruction(vcpu);
6166 case 8:
6167 val = kvm_get_cr8(vcpu);
6168 kvm_register_write(vcpu, reg, val);
6169 trace_kvm_cr_read(cr, val);
6170 return kvm_skip_emulated_instruction(vcpu);
6171 }
6172 break;
6173 case 3: /* lmsw */
6174 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6175 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
6176 kvm_lmsw(vcpu, val);
6177
6178 return kvm_skip_emulated_instruction(vcpu);
6179 default:
6180 break;
6181 }
6182 vcpu->run->exit_reason = 0;
6183 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
6184 (int)(exit_qualification >> 4) & 3, cr);
6185 return 0;
6186 }
6187
6188 static int handle_dr(struct kvm_vcpu *vcpu)
6189 {
6190 unsigned long exit_qualification;
6191 int dr, dr7, reg;
6192
6193 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6194 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
6195
6196 /* First, if DR does not exist, trigger UD */
6197 if (!kvm_require_dr(vcpu, dr))
6198 return 1;
6199
6200 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
6201 if (!kvm_require_cpl(vcpu, 0))
6202 return 1;
6203 dr7 = vmcs_readl(GUEST_DR7);
6204 if (dr7 & DR7_GD) {
6205 /*
6206 * As the vm-exit takes precedence over the debug trap, we
6207 * need to emulate the latter, either for the host or the
6208 * guest debugging itself.
6209 */
6210 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6211 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
6212 vcpu->run->debug.arch.dr7 = dr7;
6213 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6214 vcpu->run->debug.arch.exception = DB_VECTOR;
6215 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
6216 return 0;
6217 } else {
6218 vcpu->arch.dr6 &= ~15;
6219 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
6220 kvm_queue_exception(vcpu, DB_VECTOR);
6221 return 1;
6222 }
6223 }
6224
6225 if (vcpu->guest_debug == 0) {
6226 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6227 CPU_BASED_MOV_DR_EXITING);
6228
6229 /*
6230 * No more DR vmexits; force a reload of the debug registers
6231 * and reenter on this instruction. The next vmexit will
6232 * retrieve the full state of the debug registers.
6233 */
6234 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
6235 return 1;
6236 }
6237
6238 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
6239 if (exit_qualification & TYPE_MOV_FROM_DR) {
6240 unsigned long val;
6241
6242 if (kvm_get_dr(vcpu, dr, &val))
6243 return 1;
6244 kvm_register_write(vcpu, reg, val);
6245 } else
6246 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
6247 return 1;
6248
6249 return kvm_skip_emulated_instruction(vcpu);
6250 }
6251
6252 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
6253 {
6254 return vcpu->arch.dr6;
6255 }
6256
6257 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
6258 {
6259 }
6260
6261 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
6262 {
6263 get_debugreg(vcpu->arch.db[0], 0);
6264 get_debugreg(vcpu->arch.db[1], 1);
6265 get_debugreg(vcpu->arch.db[2], 2);
6266 get_debugreg(vcpu->arch.db[3], 3);
6267 get_debugreg(vcpu->arch.dr6, 6);
6268 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
6269
6270 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
6271 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
6272 }
6273
6274 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
6275 {
6276 vmcs_writel(GUEST_DR7, val);
6277 }
6278
6279 static int handle_cpuid(struct kvm_vcpu *vcpu)
6280 {
6281 return kvm_emulate_cpuid(vcpu);
6282 }
6283
6284 static int handle_rdmsr(struct kvm_vcpu *vcpu)
6285 {
6286 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6287 struct msr_data msr_info;
6288
6289 msr_info.index = ecx;
6290 msr_info.host_initiated = false;
6291 if (vmx_get_msr(vcpu, &msr_info)) {
6292 trace_kvm_msr_read_ex(ecx);
6293 kvm_inject_gp(vcpu, 0);
6294 return 1;
6295 }
6296
6297 trace_kvm_msr_read(ecx, msr_info.data);
6298
6299 /* FIXME: handling of bits 32:63 of rax, rdx */
6300 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
6301 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
6302 return kvm_skip_emulated_instruction(vcpu);
6303 }
6304
6305 static int handle_wrmsr(struct kvm_vcpu *vcpu)
6306 {
6307 struct msr_data msr;
6308 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6309 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
6310 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
6311
6312 msr.data = data;
6313 msr.index = ecx;
6314 msr.host_initiated = false;
6315 if (kvm_set_msr(vcpu, &msr) != 0) {
6316 trace_kvm_msr_write_ex(ecx, data);
6317 kvm_inject_gp(vcpu, 0);
6318 return 1;
6319 }
6320
6321 trace_kvm_msr_write(ecx, data);
6322 return kvm_skip_emulated_instruction(vcpu);
6323 }
6324
6325 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
6326 {
6327 kvm_apic_update_ppr(vcpu);
6328 return 1;
6329 }
6330
6331 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
6332 {
6333 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6334 CPU_BASED_VIRTUAL_INTR_PENDING);
6335
6336 kvm_make_request(KVM_REQ_EVENT, vcpu);
6337
6338 ++vcpu->stat.irq_window_exits;
6339 return 1;
6340 }
6341
6342 static int handle_halt(struct kvm_vcpu *vcpu)
6343 {
6344 return kvm_emulate_halt(vcpu);
6345 }
6346
6347 static int handle_vmcall(struct kvm_vcpu *vcpu)
6348 {
6349 return kvm_emulate_hypercall(vcpu);
6350 }
6351
6352 static int handle_invd(struct kvm_vcpu *vcpu)
6353 {
6354 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6355 }
6356
6357 static int handle_invlpg(struct kvm_vcpu *vcpu)
6358 {
6359 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6360
6361 kvm_mmu_invlpg(vcpu, exit_qualification);
6362 return kvm_skip_emulated_instruction(vcpu);
6363 }
6364
6365 static int handle_rdpmc(struct kvm_vcpu *vcpu)
6366 {
6367 int err;
6368
6369 err = kvm_rdpmc(vcpu);
6370 return kvm_complete_insn_gp(vcpu, err);
6371 }
6372
6373 static int handle_wbinvd(struct kvm_vcpu *vcpu)
6374 {
6375 return kvm_emulate_wbinvd(vcpu);
6376 }
6377
6378 static int handle_xsetbv(struct kvm_vcpu *vcpu)
6379 {
6380 u64 new_bv = kvm_read_edx_eax(vcpu);
6381 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
6382
6383 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
6384 return kvm_skip_emulated_instruction(vcpu);
6385 return 1;
6386 }
6387
6388 static int handle_xsaves(struct kvm_vcpu *vcpu)
6389 {
6390 kvm_skip_emulated_instruction(vcpu);
6391 WARN(1, "this should never happen\n");
6392 return 1;
6393 }
6394
6395 static int handle_xrstors(struct kvm_vcpu *vcpu)
6396 {
6397 kvm_skip_emulated_instruction(vcpu);
6398 WARN(1, "this should never happen\n");
6399 return 1;
6400 }
6401
6402 static int handle_apic_access(struct kvm_vcpu *vcpu)
6403 {
6404 if (likely(fasteoi)) {
6405 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6406 int access_type, offset;
6407
6408 access_type = exit_qualification & APIC_ACCESS_TYPE;
6409 offset = exit_qualification & APIC_ACCESS_OFFSET;
6410 /*
6411 * Sane guest uses MOV to write EOI, with written value
6412 * not cared. So make a short-circuit here by avoiding
6413 * heavy instruction emulation.
6414 */
6415 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
6416 (offset == APIC_EOI)) {
6417 kvm_lapic_set_eoi(vcpu);
6418 return kvm_skip_emulated_instruction(vcpu);
6419 }
6420 }
6421 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6422 }
6423
6424 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
6425 {
6426 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6427 int vector = exit_qualification & 0xff;
6428
6429 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
6430 kvm_apic_set_eoi_accelerated(vcpu, vector);
6431 return 1;
6432 }
6433
6434 static int handle_apic_write(struct kvm_vcpu *vcpu)
6435 {
6436 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6437 u32 offset = exit_qualification & 0xfff;
6438
6439 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
6440 kvm_apic_write_nodecode(vcpu, offset);
6441 return 1;
6442 }
6443
6444 static int handle_task_switch(struct kvm_vcpu *vcpu)
6445 {
6446 struct vcpu_vmx *vmx = to_vmx(vcpu);
6447 unsigned long exit_qualification;
6448 bool has_error_code = false;
6449 u32 error_code = 0;
6450 u16 tss_selector;
6451 int reason, type, idt_v, idt_index;
6452
6453 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
6454 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
6455 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
6456
6457 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6458
6459 reason = (u32)exit_qualification >> 30;
6460 if (reason == TASK_SWITCH_GATE && idt_v) {
6461 switch (type) {
6462 case INTR_TYPE_NMI_INTR:
6463 vcpu->arch.nmi_injected = false;
6464 vmx_set_nmi_mask(vcpu, true);
6465 break;
6466 case INTR_TYPE_EXT_INTR:
6467 case INTR_TYPE_SOFT_INTR:
6468 kvm_clear_interrupt_queue(vcpu);
6469 break;
6470 case INTR_TYPE_HARD_EXCEPTION:
6471 if (vmx->idt_vectoring_info &
6472 VECTORING_INFO_DELIVER_CODE_MASK) {
6473 has_error_code = true;
6474 error_code =
6475 vmcs_read32(IDT_VECTORING_ERROR_CODE);
6476 }
6477 /* fall through */
6478 case INTR_TYPE_SOFT_EXCEPTION:
6479 kvm_clear_exception_queue(vcpu);
6480 break;
6481 default:
6482 break;
6483 }
6484 }
6485 tss_selector = exit_qualification;
6486
6487 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
6488 type != INTR_TYPE_EXT_INTR &&
6489 type != INTR_TYPE_NMI_INTR))
6490 skip_emulated_instruction(vcpu);
6491
6492 if (kvm_task_switch(vcpu, tss_selector,
6493 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
6494 has_error_code, error_code) == EMULATE_FAIL) {
6495 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6496 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6497 vcpu->run->internal.ndata = 0;
6498 return 0;
6499 }
6500
6501 /*
6502 * TODO: What about debug traps on tss switch?
6503 * Are we supposed to inject them and update dr6?
6504 */
6505
6506 return 1;
6507 }
6508
6509 static int handle_ept_violation(struct kvm_vcpu *vcpu)
6510 {
6511 unsigned long exit_qualification;
6512 gpa_t gpa;
6513 u64 error_code;
6514
6515 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6516
6517 /*
6518 * EPT violation happened while executing iret from NMI,
6519 * "blocked by NMI" bit has to be set before next VM entry.
6520 * There are errata that may cause this bit to not be set:
6521 * AAK134, BY25.
6522 */
6523 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
6524 enable_vnmi &&
6525 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
6526 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
6527
6528 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6529 trace_kvm_page_fault(gpa, exit_qualification);
6530
6531 /* Is it a read fault? */
6532 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
6533 ? PFERR_USER_MASK : 0;
6534 /* Is it a write fault? */
6535 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
6536 ? PFERR_WRITE_MASK : 0;
6537 /* Is it a fetch fault? */
6538 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
6539 ? PFERR_FETCH_MASK : 0;
6540 /* ept page table entry is present? */
6541 error_code |= (exit_qualification &
6542 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
6543 EPT_VIOLATION_EXECUTABLE))
6544 ? PFERR_PRESENT_MASK : 0;
6545
6546 error_code |= (exit_qualification & 0x100) != 0 ?
6547 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
6548
6549 vcpu->arch.exit_qualification = exit_qualification;
6550 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
6551 }
6552
6553 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
6554 {
6555 int ret;
6556 gpa_t gpa;
6557
6558 /*
6559 * A nested guest cannot optimize MMIO vmexits, because we have an
6560 * nGPA here instead of the required GPA.
6561 */
6562 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6563 if (!is_guest_mode(vcpu) &&
6564 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
6565 trace_kvm_fast_mmio(gpa);
6566 return kvm_skip_emulated_instruction(vcpu);
6567 }
6568
6569 ret = kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
6570 if (ret >= 0)
6571 return ret;
6572
6573 /* It is the real ept misconfig */
6574 WARN_ON(1);
6575
6576 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6577 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
6578
6579 return 0;
6580 }
6581
6582 static int handle_nmi_window(struct kvm_vcpu *vcpu)
6583 {
6584 WARN_ON_ONCE(!enable_vnmi);
6585 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6586 CPU_BASED_VIRTUAL_NMI_PENDING);
6587 ++vcpu->stat.nmi_window_exits;
6588 kvm_make_request(KVM_REQ_EVENT, vcpu);
6589
6590 return 1;
6591 }
6592
6593 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
6594 {
6595 struct vcpu_vmx *vmx = to_vmx(vcpu);
6596 enum emulation_result err = EMULATE_DONE;
6597 int ret = 1;
6598 u32 cpu_exec_ctrl;
6599 bool intr_window_requested;
6600 unsigned count = 130;
6601
6602 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6603 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
6604
6605 while (vmx->emulation_required && count-- != 0) {
6606 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
6607 return handle_interrupt_window(&vmx->vcpu);
6608
6609 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
6610 return 1;
6611
6612 err = emulate_instruction(vcpu, 0);
6613
6614 if (err == EMULATE_USER_EXIT) {
6615 ++vcpu->stat.mmio_exits;
6616 ret = 0;
6617 goto out;
6618 }
6619
6620 if (err != EMULATE_DONE) {
6621 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6622 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6623 vcpu->run->internal.ndata = 0;
6624 return 0;
6625 }
6626
6627 if (vcpu->arch.halt_request) {
6628 vcpu->arch.halt_request = 0;
6629 ret = kvm_vcpu_halt(vcpu);
6630 goto out;
6631 }
6632
6633 if (signal_pending(current))
6634 goto out;
6635 if (need_resched())
6636 schedule();
6637 }
6638
6639 out:
6640 return ret;
6641 }
6642
6643 static int __grow_ple_window(int val)
6644 {
6645 if (ple_window_grow < 1)
6646 return ple_window;
6647
6648 val = min(val, ple_window_actual_max);
6649
6650 if (ple_window_grow < ple_window)
6651 val *= ple_window_grow;
6652 else
6653 val += ple_window_grow;
6654
6655 return val;
6656 }
6657
6658 static int __shrink_ple_window(int val, int modifier, int minimum)
6659 {
6660 if (modifier < 1)
6661 return ple_window;
6662
6663 if (modifier < ple_window)
6664 val /= modifier;
6665 else
6666 val -= modifier;
6667
6668 return max(val, minimum);
6669 }
6670
6671 static void grow_ple_window(struct kvm_vcpu *vcpu)
6672 {
6673 struct vcpu_vmx *vmx = to_vmx(vcpu);
6674 int old = vmx->ple_window;
6675
6676 vmx->ple_window = __grow_ple_window(old);
6677
6678 if (vmx->ple_window != old)
6679 vmx->ple_window_dirty = true;
6680
6681 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
6682 }
6683
6684 static void shrink_ple_window(struct kvm_vcpu *vcpu)
6685 {
6686 struct vcpu_vmx *vmx = to_vmx(vcpu);
6687 int old = vmx->ple_window;
6688
6689 vmx->ple_window = __shrink_ple_window(old,
6690 ple_window_shrink, ple_window);
6691
6692 if (vmx->ple_window != old)
6693 vmx->ple_window_dirty = true;
6694
6695 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
6696 }
6697
6698 /*
6699 * ple_window_actual_max is computed to be one grow_ple_window() below
6700 * ple_window_max. (See __grow_ple_window for the reason.)
6701 * This prevents overflows, because ple_window_max is int.
6702 * ple_window_max effectively rounded down to a multiple of ple_window_grow in
6703 * this process.
6704 * ple_window_max is also prevented from setting vmx->ple_window < ple_window.
6705 */
6706 static void update_ple_window_actual_max(void)
6707 {
6708 ple_window_actual_max =
6709 __shrink_ple_window(max(ple_window_max, ple_window),
6710 ple_window_grow, INT_MIN);
6711 }
6712
6713 /*
6714 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
6715 */
6716 static void wakeup_handler(void)
6717 {
6718 struct kvm_vcpu *vcpu;
6719 int cpu = smp_processor_id();
6720
6721 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6722 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
6723 blocked_vcpu_list) {
6724 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6725
6726 if (pi_test_on(pi_desc) == 1)
6727 kvm_vcpu_kick(vcpu);
6728 }
6729 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6730 }
6731
6732 void vmx_enable_tdp(void)
6733 {
6734 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
6735 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
6736 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
6737 0ull, VMX_EPT_EXECUTABLE_MASK,
6738 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
6739 VMX_EPT_RWX_MASK, 0ull);
6740
6741 ept_set_mmio_spte_mask();
6742 kvm_enable_tdp();
6743 }
6744
6745 static __init int hardware_setup(void)
6746 {
6747 int r = -ENOMEM, i, msr;
6748
6749 rdmsrl_safe(MSR_EFER, &host_efer);
6750
6751 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
6752 kvm_define_shared_msr(i, vmx_msr_index[i]);
6753
6754 for (i = 0; i < VMX_BITMAP_NR; i++) {
6755 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
6756 if (!vmx_bitmap[i])
6757 goto out;
6758 }
6759
6760 memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
6761 memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
6762
6763 memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
6764
6765 memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
6766
6767 memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
6768 memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
6769
6770 if (setup_vmcs_config(&vmcs_config) < 0) {
6771 r = -EIO;
6772 goto out;
6773 }
6774
6775 if (boot_cpu_has(X86_FEATURE_NX))
6776 kvm_enable_efer_bits(EFER_NX);
6777
6778 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
6779 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
6780 enable_vpid = 0;
6781
6782 if (!cpu_has_vmx_shadow_vmcs())
6783 enable_shadow_vmcs = 0;
6784 if (enable_shadow_vmcs)
6785 init_vmcs_shadow_fields();
6786
6787 if (!cpu_has_vmx_ept() ||
6788 !cpu_has_vmx_ept_4levels() ||
6789 !cpu_has_vmx_ept_mt_wb() ||
6790 !cpu_has_vmx_invept_global())
6791 enable_ept = 0;
6792
6793 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
6794 enable_ept_ad_bits = 0;
6795
6796 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
6797 enable_unrestricted_guest = 0;
6798
6799 if (!cpu_has_vmx_flexpriority())
6800 flexpriority_enabled = 0;
6801
6802 if (!cpu_has_virtual_nmis())
6803 enable_vnmi = 0;
6804
6805 /*
6806 * set_apic_access_page_addr() is used to reload apic access
6807 * page upon invalidation. No need to do anything if not
6808 * using the APIC_ACCESS_ADDR VMCS field.
6809 */
6810 if (!flexpriority_enabled)
6811 kvm_x86_ops->set_apic_access_page_addr = NULL;
6812
6813 if (!cpu_has_vmx_tpr_shadow())
6814 kvm_x86_ops->update_cr8_intercept = NULL;
6815
6816 if (enable_ept && !cpu_has_vmx_ept_2m_page())
6817 kvm_disable_largepages();
6818
6819 if (!cpu_has_vmx_ple()) {
6820 ple_gap = 0;
6821 ple_window = 0;
6822 ple_window_grow = 0;
6823 ple_window_max = 0;
6824 ple_window_shrink = 0;
6825 }
6826
6827 if (!cpu_has_vmx_apicv()) {
6828 enable_apicv = 0;
6829 kvm_x86_ops->sync_pir_to_irr = NULL;
6830 }
6831
6832 if (cpu_has_vmx_tsc_scaling()) {
6833 kvm_has_tsc_control = true;
6834 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
6835 kvm_tsc_scaling_ratio_frac_bits = 48;
6836 }
6837
6838 vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
6839 vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
6840 vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
6841 vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
6842 vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
6843 vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
6844
6845 memcpy(vmx_msr_bitmap_legacy_x2apic_apicv,
6846 vmx_msr_bitmap_legacy, PAGE_SIZE);
6847 memcpy(vmx_msr_bitmap_longmode_x2apic_apicv,
6848 vmx_msr_bitmap_longmode, PAGE_SIZE);
6849 memcpy(vmx_msr_bitmap_legacy_x2apic,
6850 vmx_msr_bitmap_legacy, PAGE_SIZE);
6851 memcpy(vmx_msr_bitmap_longmode_x2apic,
6852 vmx_msr_bitmap_longmode, PAGE_SIZE);
6853
6854 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
6855
6856 for (msr = 0x800; msr <= 0x8ff; msr++) {
6857 if (msr == 0x839 /* TMCCT */)
6858 continue;
6859 vmx_disable_intercept_msr_x2apic(msr, MSR_TYPE_R, true);
6860 }
6861
6862 /*
6863 * TPR reads and writes can be virtualized even if virtual interrupt
6864 * delivery is not in use.
6865 */
6866 vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_W, true);
6867 vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_R | MSR_TYPE_W, false);
6868
6869 /* EOI */
6870 vmx_disable_intercept_msr_x2apic(0x80b, MSR_TYPE_W, true);
6871 /* SELF-IPI */
6872 vmx_disable_intercept_msr_x2apic(0x83f, MSR_TYPE_W, true);
6873
6874 if (enable_ept)
6875 vmx_enable_tdp();
6876 else
6877 kvm_disable_tdp();
6878
6879 update_ple_window_actual_max();
6880
6881 /*
6882 * Only enable PML when hardware supports PML feature, and both EPT
6883 * and EPT A/D bit features are enabled -- PML depends on them to work.
6884 */
6885 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
6886 enable_pml = 0;
6887
6888 if (!enable_pml) {
6889 kvm_x86_ops->slot_enable_log_dirty = NULL;
6890 kvm_x86_ops->slot_disable_log_dirty = NULL;
6891 kvm_x86_ops->flush_log_dirty = NULL;
6892 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
6893 }
6894
6895 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
6896 u64 vmx_msr;
6897
6898 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
6899 cpu_preemption_timer_multi =
6900 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
6901 } else {
6902 kvm_x86_ops->set_hv_timer = NULL;
6903 kvm_x86_ops->cancel_hv_timer = NULL;
6904 }
6905
6906 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
6907
6908 kvm_mce_cap_supported |= MCG_LMCE_P;
6909
6910 return alloc_kvm_area();
6911
6912 out:
6913 for (i = 0; i < VMX_BITMAP_NR; i++)
6914 free_page((unsigned long)vmx_bitmap[i]);
6915
6916 return r;
6917 }
6918
6919 static __exit void hardware_unsetup(void)
6920 {
6921 int i;
6922
6923 for (i = 0; i < VMX_BITMAP_NR; i++)
6924 free_page((unsigned long)vmx_bitmap[i]);
6925
6926 free_kvm_area();
6927 }
6928
6929 /*
6930 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
6931 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
6932 */
6933 static int handle_pause(struct kvm_vcpu *vcpu)
6934 {
6935 if (ple_gap)
6936 grow_ple_window(vcpu);
6937
6938 /*
6939 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
6940 * VM-execution control is ignored if CPL > 0. OTOH, KVM
6941 * never set PAUSE_EXITING and just set PLE if supported,
6942 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
6943 */
6944 kvm_vcpu_on_spin(vcpu, true);
6945 return kvm_skip_emulated_instruction(vcpu);
6946 }
6947
6948 static int handle_nop(struct kvm_vcpu *vcpu)
6949 {
6950 return kvm_skip_emulated_instruction(vcpu);
6951 }
6952
6953 static int handle_mwait(struct kvm_vcpu *vcpu)
6954 {
6955 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
6956 return handle_nop(vcpu);
6957 }
6958
6959 static int handle_invalid_op(struct kvm_vcpu *vcpu)
6960 {
6961 kvm_queue_exception(vcpu, UD_VECTOR);
6962 return 1;
6963 }
6964
6965 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
6966 {
6967 return 1;
6968 }
6969
6970 static int handle_monitor(struct kvm_vcpu *vcpu)
6971 {
6972 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
6973 return handle_nop(vcpu);
6974 }
6975
6976 /*
6977 * To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
6978 * We could reuse a single VMCS for all the L2 guests, but we also want the
6979 * option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
6980 * allows keeping them loaded on the processor, and in the future will allow
6981 * optimizations where prepare_vmcs02 doesn't need to set all the fields on
6982 * every entry if they never change.
6983 * So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
6984 * (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
6985 *
6986 * The following functions allocate and free a vmcs02 in this pool.
6987 */
6988
6989 /* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
6990 static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
6991 {
6992 struct vmcs02_list *item;
6993 list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
6994 if (item->vmptr == vmx->nested.current_vmptr) {
6995 list_move(&item->list, &vmx->nested.vmcs02_pool);
6996 return &item->vmcs02;
6997 }
6998
6999 if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
7000 /* Recycle the least recently used VMCS. */
7001 item = list_last_entry(&vmx->nested.vmcs02_pool,
7002 struct vmcs02_list, list);
7003 item->vmptr = vmx->nested.current_vmptr;
7004 list_move(&item->list, &vmx->nested.vmcs02_pool);
7005 return &item->vmcs02;
7006 }
7007
7008 /* Create a new VMCS */
7009 item = kzalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
7010 if (!item)
7011 return NULL;
7012 item->vmcs02.vmcs = alloc_vmcs();
7013 item->vmcs02.shadow_vmcs = NULL;
7014 if (!item->vmcs02.vmcs) {
7015 kfree(item);
7016 return NULL;
7017 }
7018 loaded_vmcs_init(&item->vmcs02);
7019 item->vmptr = vmx->nested.current_vmptr;
7020 list_add(&(item->list), &(vmx->nested.vmcs02_pool));
7021 vmx->nested.vmcs02_num++;
7022 return &item->vmcs02;
7023 }
7024
7025 /* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
7026 static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
7027 {
7028 struct vmcs02_list *item;
7029 list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
7030 if (item->vmptr == vmptr) {
7031 free_loaded_vmcs(&item->vmcs02);
7032 list_del(&item->list);
7033 kfree(item);
7034 vmx->nested.vmcs02_num--;
7035 return;
7036 }
7037 }
7038
7039 /*
7040 * Free all VMCSs saved for this vcpu, except the one pointed by
7041 * vmx->loaded_vmcs. We must be running L1, so vmx->loaded_vmcs
7042 * must be &vmx->vmcs01.
7043 */
7044 static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
7045 {
7046 struct vmcs02_list *item, *n;
7047
7048 WARN_ON(vmx->loaded_vmcs != &vmx->vmcs01);
7049 list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
7050 /*
7051 * Something will leak if the above WARN triggers. Better than
7052 * a use-after-free.
7053 */
7054 if (vmx->loaded_vmcs == &item->vmcs02)
7055 continue;
7056
7057 free_loaded_vmcs(&item->vmcs02);
7058 list_del(&item->list);
7059 kfree(item);
7060 vmx->nested.vmcs02_num--;
7061 }
7062 }
7063
7064 /*
7065 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
7066 * set the success or error code of an emulated VMX instruction, as specified
7067 * by Vol 2B, VMX Instruction Reference, "Conventions".
7068 */
7069 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
7070 {
7071 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
7072 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7073 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
7074 }
7075
7076 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
7077 {
7078 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7079 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
7080 X86_EFLAGS_SF | X86_EFLAGS_OF))
7081 | X86_EFLAGS_CF);
7082 }
7083
7084 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
7085 u32 vm_instruction_error)
7086 {
7087 if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
7088 /*
7089 * failValid writes the error number to the current VMCS, which
7090 * can't be done there isn't a current VMCS.
7091 */
7092 nested_vmx_failInvalid(vcpu);
7093 return;
7094 }
7095 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7096 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7097 X86_EFLAGS_SF | X86_EFLAGS_OF))
7098 | X86_EFLAGS_ZF);
7099 get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
7100 /*
7101 * We don't need to force a shadow sync because
7102 * VM_INSTRUCTION_ERROR is not shadowed
7103 */
7104 }
7105
7106 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
7107 {
7108 /* TODO: not to reset guest simply here. */
7109 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7110 pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
7111 }
7112
7113 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
7114 {
7115 struct vcpu_vmx *vmx =
7116 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
7117
7118 vmx->nested.preemption_timer_expired = true;
7119 kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
7120 kvm_vcpu_kick(&vmx->vcpu);
7121
7122 return HRTIMER_NORESTART;
7123 }
7124
7125 /*
7126 * Decode the memory-address operand of a vmx instruction, as recorded on an
7127 * exit caused by such an instruction (run by a guest hypervisor).
7128 * On success, returns 0. When the operand is invalid, returns 1 and throws
7129 * #UD or #GP.
7130 */
7131 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
7132 unsigned long exit_qualification,
7133 u32 vmx_instruction_info, bool wr, gva_t *ret)
7134 {
7135 gva_t off;
7136 bool exn;
7137 struct kvm_segment s;
7138
7139 /*
7140 * According to Vol. 3B, "Information for VM Exits Due to Instruction
7141 * Execution", on an exit, vmx_instruction_info holds most of the
7142 * addressing components of the operand. Only the displacement part
7143 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
7144 * For how an actual address is calculated from all these components,
7145 * refer to Vol. 1, "Operand Addressing".
7146 */
7147 int scaling = vmx_instruction_info & 3;
7148 int addr_size = (vmx_instruction_info >> 7) & 7;
7149 bool is_reg = vmx_instruction_info & (1u << 10);
7150 int seg_reg = (vmx_instruction_info >> 15) & 7;
7151 int index_reg = (vmx_instruction_info >> 18) & 0xf;
7152 bool index_is_valid = !(vmx_instruction_info & (1u << 22));
7153 int base_reg = (vmx_instruction_info >> 23) & 0xf;
7154 bool base_is_valid = !(vmx_instruction_info & (1u << 27));
7155
7156 if (is_reg) {
7157 kvm_queue_exception(vcpu, UD_VECTOR);
7158 return 1;
7159 }
7160
7161 /* Addr = segment_base + offset */
7162 /* offset = base + [index * scale] + displacement */
7163 off = exit_qualification; /* holds the displacement */
7164 if (base_is_valid)
7165 off += kvm_register_read(vcpu, base_reg);
7166 if (index_is_valid)
7167 off += kvm_register_read(vcpu, index_reg)<<scaling;
7168 vmx_get_segment(vcpu, &s, seg_reg);
7169 *ret = s.base + off;
7170
7171 if (addr_size == 1) /* 32 bit */
7172 *ret &= 0xffffffff;
7173
7174 /* Checks for #GP/#SS exceptions. */
7175 exn = false;
7176 if (is_long_mode(vcpu)) {
7177 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
7178 * non-canonical form. This is the only check on the memory
7179 * destination for long mode!
7180 */
7181 exn = is_noncanonical_address(*ret, vcpu);
7182 } else if (is_protmode(vcpu)) {
7183 /* Protected mode: apply checks for segment validity in the
7184 * following order:
7185 * - segment type check (#GP(0) may be thrown)
7186 * - usability check (#GP(0)/#SS(0))
7187 * - limit check (#GP(0)/#SS(0))
7188 */
7189 if (wr)
7190 /* #GP(0) if the destination operand is located in a
7191 * read-only data segment or any code segment.
7192 */
7193 exn = ((s.type & 0xa) == 0 || (s.type & 8));
7194 else
7195 /* #GP(0) if the source operand is located in an
7196 * execute-only code segment
7197 */
7198 exn = ((s.type & 0xa) == 8);
7199 if (exn) {
7200 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7201 return 1;
7202 }
7203 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
7204 */
7205 exn = (s.unusable != 0);
7206 /* Protected mode: #GP(0)/#SS(0) if the memory
7207 * operand is outside the segment limit.
7208 */
7209 exn = exn || (off + sizeof(u64) > s.limit);
7210 }
7211 if (exn) {
7212 kvm_queue_exception_e(vcpu,
7213 seg_reg == VCPU_SREG_SS ?
7214 SS_VECTOR : GP_VECTOR,
7215 0);
7216 return 1;
7217 }
7218
7219 return 0;
7220 }
7221
7222 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
7223 {
7224 gva_t gva;
7225 struct x86_exception e;
7226
7227 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7228 vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
7229 return 1;
7230
7231 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, vmpointer,
7232 sizeof(*vmpointer), &e)) {
7233 kvm_inject_page_fault(vcpu, &e);
7234 return 1;
7235 }
7236
7237 return 0;
7238 }
7239
7240 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
7241 {
7242 struct vcpu_vmx *vmx = to_vmx(vcpu);
7243 struct vmcs *shadow_vmcs;
7244
7245 if (cpu_has_vmx_msr_bitmap()) {
7246 vmx->nested.msr_bitmap =
7247 (unsigned long *)__get_free_page(GFP_KERNEL);
7248 if (!vmx->nested.msr_bitmap)
7249 goto out_msr_bitmap;
7250 }
7251
7252 vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
7253 if (!vmx->nested.cached_vmcs12)
7254 goto out_cached_vmcs12;
7255
7256 if (enable_shadow_vmcs) {
7257 shadow_vmcs = alloc_vmcs();
7258 if (!shadow_vmcs)
7259 goto out_shadow_vmcs;
7260 /* mark vmcs as shadow */
7261 shadow_vmcs->revision_id |= (1u << 31);
7262 /* init shadow vmcs */
7263 vmcs_clear(shadow_vmcs);
7264 vmx->vmcs01.shadow_vmcs = shadow_vmcs;
7265 }
7266
7267 INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
7268 vmx->nested.vmcs02_num = 0;
7269
7270 hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
7271 HRTIMER_MODE_REL_PINNED);
7272 vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
7273
7274 vmx->nested.vmxon = true;
7275 return 0;
7276
7277 out_shadow_vmcs:
7278 kfree(vmx->nested.cached_vmcs12);
7279
7280 out_cached_vmcs12:
7281 free_page((unsigned long)vmx->nested.msr_bitmap);
7282
7283 out_msr_bitmap:
7284 return -ENOMEM;
7285 }
7286
7287 /*
7288 * Emulate the VMXON instruction.
7289 * Currently, we just remember that VMX is active, and do not save or even
7290 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
7291 * do not currently need to store anything in that guest-allocated memory
7292 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
7293 * argument is different from the VMXON pointer (which the spec says they do).
7294 */
7295 static int handle_vmon(struct kvm_vcpu *vcpu)
7296 {
7297 int ret;
7298 gpa_t vmptr;
7299 struct page *page;
7300 struct vcpu_vmx *vmx = to_vmx(vcpu);
7301 const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
7302 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7303
7304 /*
7305 * The Intel VMX Instruction Reference lists a bunch of bits that are
7306 * prerequisite to running VMXON, most notably cr4.VMXE must be set to
7307 * 1 (see vmx_set_cr4() for when we allow the guest to set this).
7308 * Otherwise, we should fail with #UD. But most faulting conditions
7309 * have already been checked by hardware, prior to the VM-exit for
7310 * VMXON. We do test guest cr4.VMXE because processor CR4 always has
7311 * that bit set to 1 in non-root mode.
7312 */
7313 if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
7314 kvm_queue_exception(vcpu, UD_VECTOR);
7315 return 1;
7316 }
7317
7318 if (vmx->nested.vmxon) {
7319 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
7320 return kvm_skip_emulated_instruction(vcpu);
7321 }
7322
7323 if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
7324 != VMXON_NEEDED_FEATURES) {
7325 kvm_inject_gp(vcpu, 0);
7326 return 1;
7327 }
7328
7329 if (nested_vmx_get_vmptr(vcpu, &vmptr))
7330 return 1;
7331
7332 /*
7333 * SDM 3: 24.11.5
7334 * The first 4 bytes of VMXON region contain the supported
7335 * VMCS revision identifier
7336 *
7337 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
7338 * which replaces physical address width with 32
7339 */
7340 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7341 nested_vmx_failInvalid(vcpu);
7342 return kvm_skip_emulated_instruction(vcpu);
7343 }
7344
7345 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7346 if (is_error_page(page)) {
7347 nested_vmx_failInvalid(vcpu);
7348 return kvm_skip_emulated_instruction(vcpu);
7349 }
7350 if (*(u32 *)kmap(page) != VMCS12_REVISION) {
7351 kunmap(page);
7352 kvm_release_page_clean(page);
7353 nested_vmx_failInvalid(vcpu);
7354 return kvm_skip_emulated_instruction(vcpu);
7355 }
7356 kunmap(page);
7357 kvm_release_page_clean(page);
7358
7359 vmx->nested.vmxon_ptr = vmptr;
7360 ret = enter_vmx_operation(vcpu);
7361 if (ret)
7362 return ret;
7363
7364 nested_vmx_succeed(vcpu);
7365 return kvm_skip_emulated_instruction(vcpu);
7366 }
7367
7368 /*
7369 * Intel's VMX Instruction Reference specifies a common set of prerequisites
7370 * for running VMX instructions (except VMXON, whose prerequisites are
7371 * slightly different). It also specifies what exception to inject otherwise.
7372 * Note that many of these exceptions have priority over VM exits, so they
7373 * don't have to be checked again here.
7374 */
7375 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
7376 {
7377 if (!to_vmx(vcpu)->nested.vmxon) {
7378 kvm_queue_exception(vcpu, UD_VECTOR);
7379 return 0;
7380 }
7381 return 1;
7382 }
7383
7384 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
7385 {
7386 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
7387 vmcs_write64(VMCS_LINK_POINTER, -1ull);
7388 }
7389
7390 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
7391 {
7392 if (vmx->nested.current_vmptr == -1ull)
7393 return;
7394
7395 if (enable_shadow_vmcs) {
7396 /* copy to memory all shadowed fields in case
7397 they were modified */
7398 copy_shadow_to_vmcs12(vmx);
7399 vmx->nested.sync_shadow_vmcs = false;
7400 vmx_disable_shadow_vmcs(vmx);
7401 }
7402 vmx->nested.posted_intr_nv = -1;
7403
7404 /* Flush VMCS12 to guest memory */
7405 kvm_vcpu_write_guest_page(&vmx->vcpu,
7406 vmx->nested.current_vmptr >> PAGE_SHIFT,
7407 vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
7408
7409 vmx->nested.current_vmptr = -1ull;
7410 }
7411
7412 /*
7413 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
7414 * just stops using VMX.
7415 */
7416 static void free_nested(struct vcpu_vmx *vmx)
7417 {
7418 if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
7419 return;
7420
7421 vmx->nested.vmxon = false;
7422 vmx->nested.smm.vmxon = false;
7423 free_vpid(vmx->nested.vpid02);
7424 vmx->nested.posted_intr_nv = -1;
7425 vmx->nested.current_vmptr = -1ull;
7426 if (vmx->nested.msr_bitmap) {
7427 free_page((unsigned long)vmx->nested.msr_bitmap);
7428 vmx->nested.msr_bitmap = NULL;
7429 }
7430 if (enable_shadow_vmcs) {
7431 vmx_disable_shadow_vmcs(vmx);
7432 vmcs_clear(vmx->vmcs01.shadow_vmcs);
7433 free_vmcs(vmx->vmcs01.shadow_vmcs);
7434 vmx->vmcs01.shadow_vmcs = NULL;
7435 }
7436 kfree(vmx->nested.cached_vmcs12);
7437 /* Unpin physical memory we referred to in current vmcs02 */
7438 if (vmx->nested.apic_access_page) {
7439 kvm_release_page_dirty(vmx->nested.apic_access_page);
7440 vmx->nested.apic_access_page = NULL;
7441 }
7442 if (vmx->nested.virtual_apic_page) {
7443 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
7444 vmx->nested.virtual_apic_page = NULL;
7445 }
7446 if (vmx->nested.pi_desc_page) {
7447 kunmap(vmx->nested.pi_desc_page);
7448 kvm_release_page_dirty(vmx->nested.pi_desc_page);
7449 vmx->nested.pi_desc_page = NULL;
7450 vmx->nested.pi_desc = NULL;
7451 }
7452
7453 nested_free_all_saved_vmcss(vmx);
7454 }
7455
7456 /* Emulate the VMXOFF instruction */
7457 static int handle_vmoff(struct kvm_vcpu *vcpu)
7458 {
7459 if (!nested_vmx_check_permission(vcpu))
7460 return 1;
7461 free_nested(to_vmx(vcpu));
7462 nested_vmx_succeed(vcpu);
7463 return kvm_skip_emulated_instruction(vcpu);
7464 }
7465
7466 /* Emulate the VMCLEAR instruction */
7467 static int handle_vmclear(struct kvm_vcpu *vcpu)
7468 {
7469 struct vcpu_vmx *vmx = to_vmx(vcpu);
7470 u32 zero = 0;
7471 gpa_t vmptr;
7472
7473 if (!nested_vmx_check_permission(vcpu))
7474 return 1;
7475
7476 if (nested_vmx_get_vmptr(vcpu, &vmptr))
7477 return 1;
7478
7479 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7480 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
7481 return kvm_skip_emulated_instruction(vcpu);
7482 }
7483
7484 if (vmptr == vmx->nested.vmxon_ptr) {
7485 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
7486 return kvm_skip_emulated_instruction(vcpu);
7487 }
7488
7489 if (vmptr == vmx->nested.current_vmptr)
7490 nested_release_vmcs12(vmx);
7491
7492 kvm_vcpu_write_guest(vcpu,
7493 vmptr + offsetof(struct vmcs12, launch_state),
7494 &zero, sizeof(zero));
7495
7496 nested_free_vmcs02(vmx, vmptr);
7497
7498 nested_vmx_succeed(vcpu);
7499 return kvm_skip_emulated_instruction(vcpu);
7500 }
7501
7502 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
7503
7504 /* Emulate the VMLAUNCH instruction */
7505 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
7506 {
7507 return nested_vmx_run(vcpu, true);
7508 }
7509
7510 /* Emulate the VMRESUME instruction */
7511 static int handle_vmresume(struct kvm_vcpu *vcpu)
7512 {
7513
7514 return nested_vmx_run(vcpu, false);
7515 }
7516
7517 /*
7518 * Read a vmcs12 field. Since these can have varying lengths and we return
7519 * one type, we chose the biggest type (u64) and zero-extend the return value
7520 * to that size. Note that the caller, handle_vmread, might need to use only
7521 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
7522 * 64-bit fields are to be returned).
7523 */
7524 static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
7525 unsigned long field, u64 *ret)
7526 {
7527 short offset = vmcs_field_to_offset(field);
7528 char *p;
7529
7530 if (offset < 0)
7531 return offset;
7532
7533 p = ((char *)(get_vmcs12(vcpu))) + offset;
7534
7535 switch (vmcs_field_type(field)) {
7536 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7537 *ret = *((natural_width *)p);
7538 return 0;
7539 case VMCS_FIELD_TYPE_U16:
7540 *ret = *((u16 *)p);
7541 return 0;
7542 case VMCS_FIELD_TYPE_U32:
7543 *ret = *((u32 *)p);
7544 return 0;
7545 case VMCS_FIELD_TYPE_U64:
7546 *ret = *((u64 *)p);
7547 return 0;
7548 default:
7549 WARN_ON(1);
7550 return -ENOENT;
7551 }
7552 }
7553
7554
7555 static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
7556 unsigned long field, u64 field_value){
7557 short offset = vmcs_field_to_offset(field);
7558 char *p = ((char *) get_vmcs12(vcpu)) + offset;
7559 if (offset < 0)
7560 return offset;
7561
7562 switch (vmcs_field_type(field)) {
7563 case VMCS_FIELD_TYPE_U16:
7564 *(u16 *)p = field_value;
7565 return 0;
7566 case VMCS_FIELD_TYPE_U32:
7567 *(u32 *)p = field_value;
7568 return 0;
7569 case VMCS_FIELD_TYPE_U64:
7570 *(u64 *)p = field_value;
7571 return 0;
7572 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7573 *(natural_width *)p = field_value;
7574 return 0;
7575 default:
7576 WARN_ON(1);
7577 return -ENOENT;
7578 }
7579
7580 }
7581
7582 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
7583 {
7584 int i;
7585 unsigned long field;
7586 u64 field_value;
7587 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7588 const unsigned long *fields = shadow_read_write_fields;
7589 const int num_fields = max_shadow_read_write_fields;
7590
7591 preempt_disable();
7592
7593 vmcs_load(shadow_vmcs);
7594
7595 for (i = 0; i < num_fields; i++) {
7596 field = fields[i];
7597 switch (vmcs_field_type(field)) {
7598 case VMCS_FIELD_TYPE_U16:
7599 field_value = vmcs_read16(field);
7600 break;
7601 case VMCS_FIELD_TYPE_U32:
7602 field_value = vmcs_read32(field);
7603 break;
7604 case VMCS_FIELD_TYPE_U64:
7605 field_value = vmcs_read64(field);
7606 break;
7607 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7608 field_value = vmcs_readl(field);
7609 break;
7610 default:
7611 WARN_ON(1);
7612 continue;
7613 }
7614 vmcs12_write_any(&vmx->vcpu, field, field_value);
7615 }
7616
7617 vmcs_clear(shadow_vmcs);
7618 vmcs_load(vmx->loaded_vmcs->vmcs);
7619
7620 preempt_enable();
7621 }
7622
7623 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
7624 {
7625 const unsigned long *fields[] = {
7626 shadow_read_write_fields,
7627 shadow_read_only_fields
7628 };
7629 const int max_fields[] = {
7630 max_shadow_read_write_fields,
7631 max_shadow_read_only_fields
7632 };
7633 int i, q;
7634 unsigned long field;
7635 u64 field_value = 0;
7636 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7637
7638 vmcs_load(shadow_vmcs);
7639
7640 for (q = 0; q < ARRAY_SIZE(fields); q++) {
7641 for (i = 0; i < max_fields[q]; i++) {
7642 field = fields[q][i];
7643 vmcs12_read_any(&vmx->vcpu, field, &field_value);
7644
7645 switch (vmcs_field_type(field)) {
7646 case VMCS_FIELD_TYPE_U16:
7647 vmcs_write16(field, (u16)field_value);
7648 break;
7649 case VMCS_FIELD_TYPE_U32:
7650 vmcs_write32(field, (u32)field_value);
7651 break;
7652 case VMCS_FIELD_TYPE_U64:
7653 vmcs_write64(field, (u64)field_value);
7654 break;
7655 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7656 vmcs_writel(field, (long)field_value);
7657 break;
7658 default:
7659 WARN_ON(1);
7660 break;
7661 }
7662 }
7663 }
7664
7665 vmcs_clear(shadow_vmcs);
7666 vmcs_load(vmx->loaded_vmcs->vmcs);
7667 }
7668
7669 /*
7670 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
7671 * used before) all generate the same failure when it is missing.
7672 */
7673 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
7674 {
7675 struct vcpu_vmx *vmx = to_vmx(vcpu);
7676 if (vmx->nested.current_vmptr == -1ull) {
7677 nested_vmx_failInvalid(vcpu);
7678 return 0;
7679 }
7680 return 1;
7681 }
7682
7683 static int handle_vmread(struct kvm_vcpu *vcpu)
7684 {
7685 unsigned long field;
7686 u64 field_value;
7687 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7688 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7689 gva_t gva = 0;
7690
7691 if (!nested_vmx_check_permission(vcpu))
7692 return 1;
7693
7694 if (!nested_vmx_check_vmcs12(vcpu))
7695 return kvm_skip_emulated_instruction(vcpu);
7696
7697 /* Decode instruction info and find the field to read */
7698 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7699 /* Read the field, zero-extended to a u64 field_value */
7700 if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
7701 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7702 return kvm_skip_emulated_instruction(vcpu);
7703 }
7704 /*
7705 * Now copy part of this value to register or memory, as requested.
7706 * Note that the number of bits actually copied is 32 or 64 depending
7707 * on the guest's mode (32 or 64 bit), not on the given field's length.
7708 */
7709 if (vmx_instruction_info & (1u << 10)) {
7710 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
7711 field_value);
7712 } else {
7713 if (get_vmx_mem_address(vcpu, exit_qualification,
7714 vmx_instruction_info, true, &gva))
7715 return 1;
7716 /* _system ok, as hardware has verified cpl=0 */
7717 kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
7718 &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
7719 }
7720
7721 nested_vmx_succeed(vcpu);
7722 return kvm_skip_emulated_instruction(vcpu);
7723 }
7724
7725
7726 static int handle_vmwrite(struct kvm_vcpu *vcpu)
7727 {
7728 unsigned long field;
7729 gva_t gva;
7730 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7731 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7732 /* The value to write might be 32 or 64 bits, depending on L1's long
7733 * mode, and eventually we need to write that into a field of several
7734 * possible lengths. The code below first zero-extends the value to 64
7735 * bit (field_value), and then copies only the appropriate number of
7736 * bits into the vmcs12 field.
7737 */
7738 u64 field_value = 0;
7739 struct x86_exception e;
7740
7741 if (!nested_vmx_check_permission(vcpu))
7742 return 1;
7743
7744 if (!nested_vmx_check_vmcs12(vcpu))
7745 return kvm_skip_emulated_instruction(vcpu);
7746
7747 if (vmx_instruction_info & (1u << 10))
7748 field_value = kvm_register_readl(vcpu,
7749 (((vmx_instruction_info) >> 3) & 0xf));
7750 else {
7751 if (get_vmx_mem_address(vcpu, exit_qualification,
7752 vmx_instruction_info, false, &gva))
7753 return 1;
7754 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
7755 &field_value, (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
7756 kvm_inject_page_fault(vcpu, &e);
7757 return 1;
7758 }
7759 }
7760
7761
7762 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7763 if (vmcs_field_readonly(field)) {
7764 nested_vmx_failValid(vcpu,
7765 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
7766 return kvm_skip_emulated_instruction(vcpu);
7767 }
7768
7769 if (vmcs12_write_any(vcpu, field, field_value) < 0) {
7770 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7771 return kvm_skip_emulated_instruction(vcpu);
7772 }
7773
7774 nested_vmx_succeed(vcpu);
7775 return kvm_skip_emulated_instruction(vcpu);
7776 }
7777
7778 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
7779 {
7780 vmx->nested.current_vmptr = vmptr;
7781 if (enable_shadow_vmcs) {
7782 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
7783 SECONDARY_EXEC_SHADOW_VMCS);
7784 vmcs_write64(VMCS_LINK_POINTER,
7785 __pa(vmx->vmcs01.shadow_vmcs));
7786 vmx->nested.sync_shadow_vmcs = true;
7787 }
7788 }
7789
7790 /* Emulate the VMPTRLD instruction */
7791 static int handle_vmptrld(struct kvm_vcpu *vcpu)
7792 {
7793 struct vcpu_vmx *vmx = to_vmx(vcpu);
7794 gpa_t vmptr;
7795
7796 if (!nested_vmx_check_permission(vcpu))
7797 return 1;
7798
7799 if (nested_vmx_get_vmptr(vcpu, &vmptr))
7800 return 1;
7801
7802 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7803 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
7804 return kvm_skip_emulated_instruction(vcpu);
7805 }
7806
7807 if (vmptr == vmx->nested.vmxon_ptr) {
7808 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
7809 return kvm_skip_emulated_instruction(vcpu);
7810 }
7811
7812 if (vmx->nested.current_vmptr != vmptr) {
7813 struct vmcs12 *new_vmcs12;
7814 struct page *page;
7815 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7816 if (is_error_page(page)) {
7817 nested_vmx_failInvalid(vcpu);
7818 return kvm_skip_emulated_instruction(vcpu);
7819 }
7820 new_vmcs12 = kmap(page);
7821 if (new_vmcs12->revision_id != VMCS12_REVISION) {
7822 kunmap(page);
7823 kvm_release_page_clean(page);
7824 nested_vmx_failValid(vcpu,
7825 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
7826 return kvm_skip_emulated_instruction(vcpu);
7827 }
7828
7829 nested_release_vmcs12(vmx);
7830 /*
7831 * Load VMCS12 from guest memory since it is not already
7832 * cached.
7833 */
7834 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
7835 kunmap(page);
7836 kvm_release_page_clean(page);
7837
7838 set_current_vmptr(vmx, vmptr);
7839 }
7840
7841 nested_vmx_succeed(vcpu);
7842 return kvm_skip_emulated_instruction(vcpu);
7843 }
7844
7845 /* Emulate the VMPTRST instruction */
7846 static int handle_vmptrst(struct kvm_vcpu *vcpu)
7847 {
7848 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7849 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7850 gva_t vmcs_gva;
7851 struct x86_exception e;
7852
7853 if (!nested_vmx_check_permission(vcpu))
7854 return 1;
7855
7856 if (get_vmx_mem_address(vcpu, exit_qualification,
7857 vmx_instruction_info, true, &vmcs_gva))
7858 return 1;
7859 /* ok to use *_system, as hardware has verified cpl=0 */
7860 if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
7861 (void *)&to_vmx(vcpu)->nested.current_vmptr,
7862 sizeof(u64), &e)) {
7863 kvm_inject_page_fault(vcpu, &e);
7864 return 1;
7865 }
7866 nested_vmx_succeed(vcpu);
7867 return kvm_skip_emulated_instruction(vcpu);
7868 }
7869
7870 /* Emulate the INVEPT instruction */
7871 static int handle_invept(struct kvm_vcpu *vcpu)
7872 {
7873 struct vcpu_vmx *vmx = to_vmx(vcpu);
7874 u32 vmx_instruction_info, types;
7875 unsigned long type;
7876 gva_t gva;
7877 struct x86_exception e;
7878 struct {
7879 u64 eptp, gpa;
7880 } operand;
7881
7882 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7883 SECONDARY_EXEC_ENABLE_EPT) ||
7884 !(vmx->nested.nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
7885 kvm_queue_exception(vcpu, UD_VECTOR);
7886 return 1;
7887 }
7888
7889 if (!nested_vmx_check_permission(vcpu))
7890 return 1;
7891
7892 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7893 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7894
7895 types = (vmx->nested.nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
7896
7897 if (type >= 32 || !(types & (1 << type))) {
7898 nested_vmx_failValid(vcpu,
7899 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7900 return kvm_skip_emulated_instruction(vcpu);
7901 }
7902
7903 /* According to the Intel VMX instruction reference, the memory
7904 * operand is read even if it isn't needed (e.g., for type==global)
7905 */
7906 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7907 vmx_instruction_info, false, &gva))
7908 return 1;
7909 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
7910 sizeof(operand), &e)) {
7911 kvm_inject_page_fault(vcpu, &e);
7912 return 1;
7913 }
7914
7915 switch (type) {
7916 case VMX_EPT_EXTENT_GLOBAL:
7917 /*
7918 * TODO: track mappings and invalidate
7919 * single context requests appropriately
7920 */
7921 case VMX_EPT_EXTENT_CONTEXT:
7922 kvm_mmu_sync_roots(vcpu);
7923 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
7924 nested_vmx_succeed(vcpu);
7925 break;
7926 default:
7927 BUG_ON(1);
7928 break;
7929 }
7930
7931 return kvm_skip_emulated_instruction(vcpu);
7932 }
7933
7934 static int handle_invvpid(struct kvm_vcpu *vcpu)
7935 {
7936 struct vcpu_vmx *vmx = to_vmx(vcpu);
7937 u32 vmx_instruction_info;
7938 unsigned long type, types;
7939 gva_t gva;
7940 struct x86_exception e;
7941 struct {
7942 u64 vpid;
7943 u64 gla;
7944 } operand;
7945
7946 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7947 SECONDARY_EXEC_ENABLE_VPID) ||
7948 !(vmx->nested.nested_vmx_vpid_caps & VMX_VPID_INVVPID_BIT)) {
7949 kvm_queue_exception(vcpu, UD_VECTOR);
7950 return 1;
7951 }
7952
7953 if (!nested_vmx_check_permission(vcpu))
7954 return 1;
7955
7956 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7957 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7958
7959 types = (vmx->nested.nested_vmx_vpid_caps &
7960 VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
7961
7962 if (type >= 32 || !(types & (1 << type))) {
7963 nested_vmx_failValid(vcpu,
7964 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7965 return kvm_skip_emulated_instruction(vcpu);
7966 }
7967
7968 /* according to the intel vmx instruction reference, the memory
7969 * operand is read even if it isn't needed (e.g., for type==global)
7970 */
7971 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7972 vmx_instruction_info, false, &gva))
7973 return 1;
7974 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
7975 sizeof(operand), &e)) {
7976 kvm_inject_page_fault(vcpu, &e);
7977 return 1;
7978 }
7979 if (operand.vpid >> 16) {
7980 nested_vmx_failValid(vcpu,
7981 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7982 return kvm_skip_emulated_instruction(vcpu);
7983 }
7984
7985 switch (type) {
7986 case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
7987 if (is_noncanonical_address(operand.gla, vcpu)) {
7988 nested_vmx_failValid(vcpu,
7989 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7990 return kvm_skip_emulated_instruction(vcpu);
7991 }
7992 /* fall through */
7993 case VMX_VPID_EXTENT_SINGLE_CONTEXT:
7994 case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
7995 if (!operand.vpid) {
7996 nested_vmx_failValid(vcpu,
7997 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7998 return kvm_skip_emulated_instruction(vcpu);
7999 }
8000 break;
8001 case VMX_VPID_EXTENT_ALL_CONTEXT:
8002 break;
8003 default:
8004 WARN_ON_ONCE(1);
8005 return kvm_skip_emulated_instruction(vcpu);
8006 }
8007
8008 __vmx_flush_tlb(vcpu, vmx->nested.vpid02);
8009 nested_vmx_succeed(vcpu);
8010
8011 return kvm_skip_emulated_instruction(vcpu);
8012 }
8013
8014 static int handle_pml_full(struct kvm_vcpu *vcpu)
8015 {
8016 unsigned long exit_qualification;
8017
8018 trace_kvm_pml_full(vcpu->vcpu_id);
8019
8020 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8021
8022 /*
8023 * PML buffer FULL happened while executing iret from NMI,
8024 * "blocked by NMI" bit has to be set before next VM entry.
8025 */
8026 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
8027 enable_vnmi &&
8028 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
8029 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
8030 GUEST_INTR_STATE_NMI);
8031
8032 /*
8033 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
8034 * here.., and there's no userspace involvement needed for PML.
8035 */
8036 return 1;
8037 }
8038
8039 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
8040 {
8041 kvm_lapic_expired_hv_timer(vcpu);
8042 return 1;
8043 }
8044
8045 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
8046 {
8047 struct vcpu_vmx *vmx = to_vmx(vcpu);
8048 int maxphyaddr = cpuid_maxphyaddr(vcpu);
8049
8050 /* Check for memory type validity */
8051 switch (address & VMX_EPTP_MT_MASK) {
8052 case VMX_EPTP_MT_UC:
8053 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPTP_UC_BIT))
8054 return false;
8055 break;
8056 case VMX_EPTP_MT_WB:
8057 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPTP_WB_BIT))
8058 return false;
8059 break;
8060 default:
8061 return false;
8062 }
8063
8064 /* only 4 levels page-walk length are valid */
8065 if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
8066 return false;
8067
8068 /* Reserved bits should not be set */
8069 if (address >> maxphyaddr || ((address >> 7) & 0x1f))
8070 return false;
8071
8072 /* AD, if set, should be supported */
8073 if (address & VMX_EPTP_AD_ENABLE_BIT) {
8074 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPT_AD_BIT))
8075 return false;
8076 }
8077
8078 return true;
8079 }
8080
8081 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
8082 struct vmcs12 *vmcs12)
8083 {
8084 u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
8085 u64 address;
8086 bool accessed_dirty;
8087 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8088
8089 if (!nested_cpu_has_eptp_switching(vmcs12) ||
8090 !nested_cpu_has_ept(vmcs12))
8091 return 1;
8092
8093 if (index >= VMFUNC_EPTP_ENTRIES)
8094 return 1;
8095
8096
8097 if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
8098 &address, index * 8, 8))
8099 return 1;
8100
8101 accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
8102
8103 /*
8104 * If the (L2) guest does a vmfunc to the currently
8105 * active ept pointer, we don't have to do anything else
8106 */
8107 if (vmcs12->ept_pointer != address) {
8108 if (!valid_ept_address(vcpu, address))
8109 return 1;
8110
8111 kvm_mmu_unload(vcpu);
8112 mmu->ept_ad = accessed_dirty;
8113 mmu->base_role.ad_disabled = !accessed_dirty;
8114 vmcs12->ept_pointer = address;
8115 /*
8116 * TODO: Check what's the correct approach in case
8117 * mmu reload fails. Currently, we just let the next
8118 * reload potentially fail
8119 */
8120 kvm_mmu_reload(vcpu);
8121 }
8122
8123 return 0;
8124 }
8125
8126 static int handle_vmfunc(struct kvm_vcpu *vcpu)
8127 {
8128 struct vcpu_vmx *vmx = to_vmx(vcpu);
8129 struct vmcs12 *vmcs12;
8130 u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
8131
8132 /*
8133 * VMFUNC is only supported for nested guests, but we always enable the
8134 * secondary control for simplicity; for non-nested mode, fake that we
8135 * didn't by injecting #UD.
8136 */
8137 if (!is_guest_mode(vcpu)) {
8138 kvm_queue_exception(vcpu, UD_VECTOR);
8139 return 1;
8140 }
8141
8142 vmcs12 = get_vmcs12(vcpu);
8143 if ((vmcs12->vm_function_control & (1 << function)) == 0)
8144 goto fail;
8145
8146 switch (function) {
8147 case 0:
8148 if (nested_vmx_eptp_switching(vcpu, vmcs12))
8149 goto fail;
8150 break;
8151 default:
8152 goto fail;
8153 }
8154 return kvm_skip_emulated_instruction(vcpu);
8155
8156 fail:
8157 nested_vmx_vmexit(vcpu, vmx->exit_reason,
8158 vmcs_read32(VM_EXIT_INTR_INFO),
8159 vmcs_readl(EXIT_QUALIFICATION));
8160 return 1;
8161 }
8162
8163 /*
8164 * The exit handlers return 1 if the exit was handled fully and guest execution
8165 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
8166 * to be done to userspace and return 0.
8167 */
8168 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
8169 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
8170 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
8171 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
8172 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
8173 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
8174 [EXIT_REASON_CR_ACCESS] = handle_cr,
8175 [EXIT_REASON_DR_ACCESS] = handle_dr,
8176 [EXIT_REASON_CPUID] = handle_cpuid,
8177 [EXIT_REASON_MSR_READ] = handle_rdmsr,
8178 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
8179 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
8180 [EXIT_REASON_HLT] = handle_halt,
8181 [EXIT_REASON_INVD] = handle_invd,
8182 [EXIT_REASON_INVLPG] = handle_invlpg,
8183 [EXIT_REASON_RDPMC] = handle_rdpmc,
8184 [EXIT_REASON_VMCALL] = handle_vmcall,
8185 [EXIT_REASON_VMCLEAR] = handle_vmclear,
8186 [EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
8187 [EXIT_REASON_VMPTRLD] = handle_vmptrld,
8188 [EXIT_REASON_VMPTRST] = handle_vmptrst,
8189 [EXIT_REASON_VMREAD] = handle_vmread,
8190 [EXIT_REASON_VMRESUME] = handle_vmresume,
8191 [EXIT_REASON_VMWRITE] = handle_vmwrite,
8192 [EXIT_REASON_VMOFF] = handle_vmoff,
8193 [EXIT_REASON_VMON] = handle_vmon,
8194 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
8195 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
8196 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
8197 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
8198 [EXIT_REASON_WBINVD] = handle_wbinvd,
8199 [EXIT_REASON_XSETBV] = handle_xsetbv,
8200 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
8201 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
8202 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
8203 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
8204 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
8205 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
8206 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
8207 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
8208 [EXIT_REASON_INVEPT] = handle_invept,
8209 [EXIT_REASON_INVVPID] = handle_invvpid,
8210 [EXIT_REASON_RDRAND] = handle_invalid_op,
8211 [EXIT_REASON_RDSEED] = handle_invalid_op,
8212 [EXIT_REASON_XSAVES] = handle_xsaves,
8213 [EXIT_REASON_XRSTORS] = handle_xrstors,
8214 [EXIT_REASON_PML_FULL] = handle_pml_full,
8215 [EXIT_REASON_VMFUNC] = handle_vmfunc,
8216 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
8217 };
8218
8219 static const int kvm_vmx_max_exit_handlers =
8220 ARRAY_SIZE(kvm_vmx_exit_handlers);
8221
8222 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
8223 struct vmcs12 *vmcs12)
8224 {
8225 unsigned long exit_qualification;
8226 gpa_t bitmap, last_bitmap;
8227 unsigned int port;
8228 int size;
8229 u8 b;
8230
8231 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
8232 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
8233
8234 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8235
8236 port = exit_qualification >> 16;
8237 size = (exit_qualification & 7) + 1;
8238
8239 last_bitmap = (gpa_t)-1;
8240 b = -1;
8241
8242 while (size > 0) {
8243 if (port < 0x8000)
8244 bitmap = vmcs12->io_bitmap_a;
8245 else if (port < 0x10000)
8246 bitmap = vmcs12->io_bitmap_b;
8247 else
8248 return true;
8249 bitmap += (port & 0x7fff) / 8;
8250
8251 if (last_bitmap != bitmap)
8252 if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
8253 return true;
8254 if (b & (1 << (port & 7)))
8255 return true;
8256
8257 port++;
8258 size--;
8259 last_bitmap = bitmap;
8260 }
8261
8262 return false;
8263 }
8264
8265 /*
8266 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
8267 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
8268 * disinterest in the current event (read or write a specific MSR) by using an
8269 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
8270 */
8271 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
8272 struct vmcs12 *vmcs12, u32 exit_reason)
8273 {
8274 u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
8275 gpa_t bitmap;
8276
8277 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
8278 return true;
8279
8280 /*
8281 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
8282 * for the four combinations of read/write and low/high MSR numbers.
8283 * First we need to figure out which of the four to use:
8284 */
8285 bitmap = vmcs12->msr_bitmap;
8286 if (exit_reason == EXIT_REASON_MSR_WRITE)
8287 bitmap += 2048;
8288 if (msr_index >= 0xc0000000) {
8289 msr_index -= 0xc0000000;
8290 bitmap += 1024;
8291 }
8292
8293 /* Then read the msr_index'th bit from this bitmap: */
8294 if (msr_index < 1024*8) {
8295 unsigned char b;
8296 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
8297 return true;
8298 return 1 & (b >> (msr_index & 7));
8299 } else
8300 return true; /* let L1 handle the wrong parameter */
8301 }
8302
8303 /*
8304 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
8305 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
8306 * intercept (via guest_host_mask etc.) the current event.
8307 */
8308 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
8309 struct vmcs12 *vmcs12)
8310 {
8311 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8312 int cr = exit_qualification & 15;
8313 int reg;
8314 unsigned long val;
8315
8316 switch ((exit_qualification >> 4) & 3) {
8317 case 0: /* mov to cr */
8318 reg = (exit_qualification >> 8) & 15;
8319 val = kvm_register_readl(vcpu, reg);
8320 switch (cr) {
8321 case 0:
8322 if (vmcs12->cr0_guest_host_mask &
8323 (val ^ vmcs12->cr0_read_shadow))
8324 return true;
8325 break;
8326 case 3:
8327 if ((vmcs12->cr3_target_count >= 1 &&
8328 vmcs12->cr3_target_value0 == val) ||
8329 (vmcs12->cr3_target_count >= 2 &&
8330 vmcs12->cr3_target_value1 == val) ||
8331 (vmcs12->cr3_target_count >= 3 &&
8332 vmcs12->cr3_target_value2 == val) ||
8333 (vmcs12->cr3_target_count >= 4 &&
8334 vmcs12->cr3_target_value3 == val))
8335 return false;
8336 if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
8337 return true;
8338 break;
8339 case 4:
8340 if (vmcs12->cr4_guest_host_mask &
8341 (vmcs12->cr4_read_shadow ^ val))
8342 return true;
8343 break;
8344 case 8:
8345 if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
8346 return true;
8347 break;
8348 }
8349 break;
8350 case 2: /* clts */
8351 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
8352 (vmcs12->cr0_read_shadow & X86_CR0_TS))
8353 return true;
8354 break;
8355 case 1: /* mov from cr */
8356 switch (cr) {
8357 case 3:
8358 if (vmcs12->cpu_based_vm_exec_control &
8359 CPU_BASED_CR3_STORE_EXITING)
8360 return true;
8361 break;
8362 case 8:
8363 if (vmcs12->cpu_based_vm_exec_control &
8364 CPU_BASED_CR8_STORE_EXITING)
8365 return true;
8366 break;
8367 }
8368 break;
8369 case 3: /* lmsw */
8370 /*
8371 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
8372 * cr0. Other attempted changes are ignored, with no exit.
8373 */
8374 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
8375 if (vmcs12->cr0_guest_host_mask & 0xe &
8376 (val ^ vmcs12->cr0_read_shadow))
8377 return true;
8378 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
8379 !(vmcs12->cr0_read_shadow & 0x1) &&
8380 (val & 0x1))
8381 return true;
8382 break;
8383 }
8384 return false;
8385 }
8386
8387 /*
8388 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
8389 * should handle it ourselves in L0 (and then continue L2). Only call this
8390 * when in is_guest_mode (L2).
8391 */
8392 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
8393 {
8394 u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8395 struct vcpu_vmx *vmx = to_vmx(vcpu);
8396 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8397
8398 if (vmx->nested.nested_run_pending)
8399 return false;
8400
8401 if (unlikely(vmx->fail)) {
8402 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
8403 vmcs_read32(VM_INSTRUCTION_ERROR));
8404 return true;
8405 }
8406
8407 /*
8408 * The host physical addresses of some pages of guest memory
8409 * are loaded into VMCS02 (e.g. L1's Virtual APIC Page). The CPU
8410 * may write to these pages via their host physical address while
8411 * L2 is running, bypassing any address-translation-based dirty
8412 * tracking (e.g. EPT write protection).
8413 *
8414 * Mark them dirty on every exit from L2 to prevent them from
8415 * getting out of sync with dirty tracking.
8416 */
8417 nested_mark_vmcs12_pages_dirty(vcpu);
8418
8419 trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
8420 vmcs_readl(EXIT_QUALIFICATION),
8421 vmx->idt_vectoring_info,
8422 intr_info,
8423 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8424 KVM_ISA_VMX);
8425
8426 switch (exit_reason) {
8427 case EXIT_REASON_EXCEPTION_NMI:
8428 if (is_nmi(intr_info))
8429 return false;
8430 else if (is_page_fault(intr_info))
8431 return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
8432 else if (is_no_device(intr_info) &&
8433 !(vmcs12->guest_cr0 & X86_CR0_TS))
8434 return false;
8435 else if (is_debug(intr_info) &&
8436 vcpu->guest_debug &
8437 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
8438 return false;
8439 else if (is_breakpoint(intr_info) &&
8440 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
8441 return false;
8442 return vmcs12->exception_bitmap &
8443 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
8444 case EXIT_REASON_EXTERNAL_INTERRUPT:
8445 return false;
8446 case EXIT_REASON_TRIPLE_FAULT:
8447 return true;
8448 case EXIT_REASON_PENDING_INTERRUPT:
8449 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
8450 case EXIT_REASON_NMI_WINDOW:
8451 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
8452 case EXIT_REASON_TASK_SWITCH:
8453 return true;
8454 case EXIT_REASON_CPUID:
8455 return true;
8456 case EXIT_REASON_HLT:
8457 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
8458 case EXIT_REASON_INVD:
8459 return true;
8460 case EXIT_REASON_INVLPG:
8461 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8462 case EXIT_REASON_RDPMC:
8463 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
8464 case EXIT_REASON_RDRAND:
8465 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
8466 case EXIT_REASON_RDSEED:
8467 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
8468 case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
8469 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
8470 case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
8471 case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
8472 case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
8473 case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
8474 case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
8475 case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
8476 /*
8477 * VMX instructions trap unconditionally. This allows L1 to
8478 * emulate them for its L2 guest, i.e., allows 3-level nesting!
8479 */
8480 return true;
8481 case EXIT_REASON_CR_ACCESS:
8482 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
8483 case EXIT_REASON_DR_ACCESS:
8484 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
8485 case EXIT_REASON_IO_INSTRUCTION:
8486 return nested_vmx_exit_handled_io(vcpu, vmcs12);
8487 case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
8488 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
8489 case EXIT_REASON_MSR_READ:
8490 case EXIT_REASON_MSR_WRITE:
8491 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
8492 case EXIT_REASON_INVALID_STATE:
8493 return true;
8494 case EXIT_REASON_MWAIT_INSTRUCTION:
8495 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
8496 case EXIT_REASON_MONITOR_TRAP_FLAG:
8497 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
8498 case EXIT_REASON_MONITOR_INSTRUCTION:
8499 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
8500 case EXIT_REASON_PAUSE_INSTRUCTION:
8501 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
8502 nested_cpu_has2(vmcs12,
8503 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
8504 case EXIT_REASON_MCE_DURING_VMENTRY:
8505 return false;
8506 case EXIT_REASON_TPR_BELOW_THRESHOLD:
8507 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
8508 case EXIT_REASON_APIC_ACCESS:
8509 return nested_cpu_has2(vmcs12,
8510 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
8511 case EXIT_REASON_APIC_WRITE:
8512 case EXIT_REASON_EOI_INDUCED:
8513 /* apic_write and eoi_induced should exit unconditionally. */
8514 return true;
8515 case EXIT_REASON_EPT_VIOLATION:
8516 /*
8517 * L0 always deals with the EPT violation. If nested EPT is
8518 * used, and the nested mmu code discovers that the address is
8519 * missing in the guest EPT table (EPT12), the EPT violation
8520 * will be injected with nested_ept_inject_page_fault()
8521 */
8522 return false;
8523 case EXIT_REASON_EPT_MISCONFIG:
8524 /*
8525 * L2 never uses directly L1's EPT, but rather L0's own EPT
8526 * table (shadow on EPT) or a merged EPT table that L0 built
8527 * (EPT on EPT). So any problems with the structure of the
8528 * table is L0's fault.
8529 */
8530 return false;
8531 case EXIT_REASON_INVPCID:
8532 return
8533 nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
8534 nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8535 case EXIT_REASON_WBINVD:
8536 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
8537 case EXIT_REASON_XSETBV:
8538 return true;
8539 case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
8540 /*
8541 * This should never happen, since it is not possible to
8542 * set XSS to a non-zero value---neither in L1 nor in L2.
8543 * If if it were, XSS would have to be checked against
8544 * the XSS exit bitmap in vmcs12.
8545 */
8546 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
8547 case EXIT_REASON_PREEMPTION_TIMER:
8548 return false;
8549 case EXIT_REASON_PML_FULL:
8550 /* We emulate PML support to L1. */
8551 return false;
8552 case EXIT_REASON_VMFUNC:
8553 /* VM functions are emulated through L2->L0 vmexits. */
8554 return false;
8555 default:
8556 return true;
8557 }
8558 }
8559
8560 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
8561 {
8562 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8563
8564 /*
8565 * At this point, the exit interruption info in exit_intr_info
8566 * is only valid for EXCEPTION_NMI exits. For EXTERNAL_INTERRUPT
8567 * we need to query the in-kernel LAPIC.
8568 */
8569 WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
8570 if ((exit_intr_info &
8571 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
8572 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
8573 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8574 vmcs12->vm_exit_intr_error_code =
8575 vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
8576 }
8577
8578 nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
8579 vmcs_readl(EXIT_QUALIFICATION));
8580 return 1;
8581 }
8582
8583 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
8584 {
8585 *info1 = vmcs_readl(EXIT_QUALIFICATION);
8586 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
8587 }
8588
8589 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
8590 {
8591 if (vmx->pml_pg) {
8592 __free_page(vmx->pml_pg);
8593 vmx->pml_pg = NULL;
8594 }
8595 }
8596
8597 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
8598 {
8599 struct vcpu_vmx *vmx = to_vmx(vcpu);
8600 u64 *pml_buf;
8601 u16 pml_idx;
8602
8603 pml_idx = vmcs_read16(GUEST_PML_INDEX);
8604
8605 /* Do nothing if PML buffer is empty */
8606 if (pml_idx == (PML_ENTITY_NUM - 1))
8607 return;
8608
8609 /* PML index always points to next available PML buffer entity */
8610 if (pml_idx >= PML_ENTITY_NUM)
8611 pml_idx = 0;
8612 else
8613 pml_idx++;
8614
8615 pml_buf = page_address(vmx->pml_pg);
8616 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
8617 u64 gpa;
8618
8619 gpa = pml_buf[pml_idx];
8620 WARN_ON(gpa & (PAGE_SIZE - 1));
8621 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
8622 }
8623
8624 /* reset PML index */
8625 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
8626 }
8627
8628 /*
8629 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
8630 * Called before reporting dirty_bitmap to userspace.
8631 */
8632 static void kvm_flush_pml_buffers(struct kvm *kvm)
8633 {
8634 int i;
8635 struct kvm_vcpu *vcpu;
8636 /*
8637 * We only need to kick vcpu out of guest mode here, as PML buffer
8638 * is flushed at beginning of all VMEXITs, and it's obvious that only
8639 * vcpus running in guest are possible to have unflushed GPAs in PML
8640 * buffer.
8641 */
8642 kvm_for_each_vcpu(i, vcpu, kvm)
8643 kvm_vcpu_kick(vcpu);
8644 }
8645
8646 static void vmx_dump_sel(char *name, uint32_t sel)
8647 {
8648 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
8649 name, vmcs_read16(sel),
8650 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
8651 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
8652 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
8653 }
8654
8655 static void vmx_dump_dtsel(char *name, uint32_t limit)
8656 {
8657 pr_err("%s limit=0x%08x, base=0x%016lx\n",
8658 name, vmcs_read32(limit),
8659 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
8660 }
8661
8662 static void dump_vmcs(void)
8663 {
8664 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
8665 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
8666 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
8667 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
8668 u32 secondary_exec_control = 0;
8669 unsigned long cr4 = vmcs_readl(GUEST_CR4);
8670 u64 efer = vmcs_read64(GUEST_IA32_EFER);
8671 int i, n;
8672
8673 if (cpu_has_secondary_exec_ctrls())
8674 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8675
8676 pr_err("*** Guest State ***\n");
8677 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8678 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
8679 vmcs_readl(CR0_GUEST_HOST_MASK));
8680 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8681 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
8682 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
8683 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
8684 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
8685 {
8686 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
8687 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
8688 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
8689 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
8690 }
8691 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
8692 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
8693 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
8694 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
8695 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8696 vmcs_readl(GUEST_SYSENTER_ESP),
8697 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
8698 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
8699 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
8700 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
8701 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
8702 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
8703 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
8704 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
8705 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
8706 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
8707 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
8708 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
8709 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
8710 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
8711 efer, vmcs_read64(GUEST_IA32_PAT));
8712 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
8713 vmcs_read64(GUEST_IA32_DEBUGCTL),
8714 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
8715 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
8716 pr_err("PerfGlobCtl = 0x%016llx\n",
8717 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
8718 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
8719 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
8720 pr_err("Interruptibility = %08x ActivityState = %08x\n",
8721 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
8722 vmcs_read32(GUEST_ACTIVITY_STATE));
8723 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
8724 pr_err("InterruptStatus = %04x\n",
8725 vmcs_read16(GUEST_INTR_STATUS));
8726
8727 pr_err("*** Host State ***\n");
8728 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
8729 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
8730 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
8731 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
8732 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
8733 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
8734 vmcs_read16(HOST_TR_SELECTOR));
8735 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
8736 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
8737 vmcs_readl(HOST_TR_BASE));
8738 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
8739 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
8740 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
8741 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
8742 vmcs_readl(HOST_CR4));
8743 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8744 vmcs_readl(HOST_IA32_SYSENTER_ESP),
8745 vmcs_read32(HOST_IA32_SYSENTER_CS),
8746 vmcs_readl(HOST_IA32_SYSENTER_EIP));
8747 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
8748 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
8749 vmcs_read64(HOST_IA32_EFER),
8750 vmcs_read64(HOST_IA32_PAT));
8751 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
8752 pr_err("PerfGlobCtl = 0x%016llx\n",
8753 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
8754
8755 pr_err("*** Control State ***\n");
8756 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
8757 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
8758 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
8759 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
8760 vmcs_read32(EXCEPTION_BITMAP),
8761 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
8762 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
8763 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
8764 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
8765 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
8766 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
8767 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
8768 vmcs_read32(VM_EXIT_INTR_INFO),
8769 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8770 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
8771 pr_err(" reason=%08x qualification=%016lx\n",
8772 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
8773 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
8774 vmcs_read32(IDT_VECTORING_INFO_FIELD),
8775 vmcs_read32(IDT_VECTORING_ERROR_CODE));
8776 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
8777 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
8778 pr_err("TSC Multiplier = 0x%016llx\n",
8779 vmcs_read64(TSC_MULTIPLIER));
8780 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
8781 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
8782 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
8783 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
8784 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
8785 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
8786 n = vmcs_read32(CR3_TARGET_COUNT);
8787 for (i = 0; i + 1 < n; i += 4)
8788 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
8789 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
8790 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
8791 if (i < n)
8792 pr_err("CR3 target%u=%016lx\n",
8793 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
8794 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
8795 pr_err("PLE Gap=%08x Window=%08x\n",
8796 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
8797 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
8798 pr_err("Virtual processor ID = 0x%04x\n",
8799 vmcs_read16(VIRTUAL_PROCESSOR_ID));
8800 }
8801
8802 /*
8803 * The guest has exited. See if we can fix it or if we need userspace
8804 * assistance.
8805 */
8806 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
8807 {
8808 struct vcpu_vmx *vmx = to_vmx(vcpu);
8809 u32 exit_reason = vmx->exit_reason;
8810 u32 vectoring_info = vmx->idt_vectoring_info;
8811
8812 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
8813
8814 /*
8815 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
8816 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
8817 * querying dirty_bitmap, we only need to kick all vcpus out of guest
8818 * mode as if vcpus is in root mode, the PML buffer must has been
8819 * flushed already.
8820 */
8821 if (enable_pml)
8822 vmx_flush_pml_buffer(vcpu);
8823
8824 /* If guest state is invalid, start emulating */
8825 if (vmx->emulation_required)
8826 return handle_invalid_guest_state(vcpu);
8827
8828 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
8829 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
8830
8831 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
8832 dump_vmcs();
8833 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8834 vcpu->run->fail_entry.hardware_entry_failure_reason
8835 = exit_reason;
8836 return 0;
8837 }
8838
8839 if (unlikely(vmx->fail)) {
8840 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8841 vcpu->run->fail_entry.hardware_entry_failure_reason
8842 = vmcs_read32(VM_INSTRUCTION_ERROR);
8843 return 0;
8844 }
8845
8846 /*
8847 * Note:
8848 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
8849 * delivery event since it indicates guest is accessing MMIO.
8850 * The vm-exit can be triggered again after return to guest that
8851 * will cause infinite loop.
8852 */
8853 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
8854 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
8855 exit_reason != EXIT_REASON_EPT_VIOLATION &&
8856 exit_reason != EXIT_REASON_PML_FULL &&
8857 exit_reason != EXIT_REASON_TASK_SWITCH)) {
8858 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8859 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8860 vcpu->run->internal.ndata = 3;
8861 vcpu->run->internal.data[0] = vectoring_info;
8862 vcpu->run->internal.data[1] = exit_reason;
8863 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
8864 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
8865 vcpu->run->internal.ndata++;
8866 vcpu->run->internal.data[3] =
8867 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
8868 }
8869 return 0;
8870 }
8871
8872 if (unlikely(!enable_vnmi &&
8873 vmx->loaded_vmcs->soft_vnmi_blocked)) {
8874 if (vmx_interrupt_allowed(vcpu)) {
8875 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
8876 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
8877 vcpu->arch.nmi_pending) {
8878 /*
8879 * This CPU don't support us in finding the end of an
8880 * NMI-blocked window if the guest runs with IRQs
8881 * disabled. So we pull the trigger after 1 s of
8882 * futile waiting, but inform the user about this.
8883 */
8884 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
8885 "state on VCPU %d after 1 s timeout\n",
8886 __func__, vcpu->vcpu_id);
8887 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
8888 }
8889 }
8890
8891 if (exit_reason < kvm_vmx_max_exit_handlers
8892 && kvm_vmx_exit_handlers[exit_reason])
8893 return kvm_vmx_exit_handlers[exit_reason](vcpu);
8894 else {
8895 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
8896 exit_reason);
8897 kvm_queue_exception(vcpu, UD_VECTOR);
8898 return 1;
8899 }
8900 }
8901
8902 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
8903 {
8904 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8905
8906 if (is_guest_mode(vcpu) &&
8907 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
8908 return;
8909
8910 if (irr == -1 || tpr < irr) {
8911 vmcs_write32(TPR_THRESHOLD, 0);
8912 return;
8913 }
8914
8915 vmcs_write32(TPR_THRESHOLD, irr);
8916 }
8917
8918 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
8919 {
8920 u32 sec_exec_control;
8921
8922 /* Postpone execution until vmcs01 is the current VMCS. */
8923 if (is_guest_mode(vcpu)) {
8924 to_vmx(vcpu)->nested.change_vmcs01_virtual_x2apic_mode = true;
8925 return;
8926 }
8927
8928 if (!cpu_has_vmx_virtualize_x2apic_mode())
8929 return;
8930
8931 if (!cpu_need_tpr_shadow(vcpu))
8932 return;
8933
8934 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8935
8936 if (set) {
8937 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
8938 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
8939 } else {
8940 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
8941 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
8942 vmx_flush_tlb_ept_only(vcpu);
8943 }
8944 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
8945
8946 vmx_set_msr_bitmap(vcpu);
8947 }
8948
8949 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
8950 {
8951 struct vcpu_vmx *vmx = to_vmx(vcpu);
8952
8953 /*
8954 * Currently we do not handle the nested case where L2 has an
8955 * APIC access page of its own; that page is still pinned.
8956 * Hence, we skip the case where the VCPU is in guest mode _and_
8957 * L1 prepared an APIC access page for L2.
8958 *
8959 * For the case where L1 and L2 share the same APIC access page
8960 * (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
8961 * in the vmcs12), this function will only update either the vmcs01
8962 * or the vmcs02. If the former, the vmcs02 will be updated by
8963 * prepare_vmcs02. If the latter, the vmcs01 will be updated in
8964 * the next L2->L1 exit.
8965 */
8966 if (!is_guest_mode(vcpu) ||
8967 !nested_cpu_has2(get_vmcs12(&vmx->vcpu),
8968 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
8969 vmcs_write64(APIC_ACCESS_ADDR, hpa);
8970 vmx_flush_tlb_ept_only(vcpu);
8971 }
8972 }
8973
8974 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
8975 {
8976 u16 status;
8977 u8 old;
8978
8979 if (max_isr == -1)
8980 max_isr = 0;
8981
8982 status = vmcs_read16(GUEST_INTR_STATUS);
8983 old = status >> 8;
8984 if (max_isr != old) {
8985 status &= 0xff;
8986 status |= max_isr << 8;
8987 vmcs_write16(GUEST_INTR_STATUS, status);
8988 }
8989 }
8990
8991 static void vmx_set_rvi(int vector)
8992 {
8993 u16 status;
8994 u8 old;
8995
8996 if (vector == -1)
8997 vector = 0;
8998
8999 status = vmcs_read16(GUEST_INTR_STATUS);
9000 old = (u8)status & 0xff;
9001 if ((u8)vector != old) {
9002 status &= ~0xff;
9003 status |= (u8)vector;
9004 vmcs_write16(GUEST_INTR_STATUS, status);
9005 }
9006 }
9007
9008 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
9009 {
9010 if (!is_guest_mode(vcpu)) {
9011 vmx_set_rvi(max_irr);
9012 return;
9013 }
9014
9015 if (max_irr == -1)
9016 return;
9017
9018 /*
9019 * In guest mode. If a vmexit is needed, vmx_check_nested_events
9020 * handles it.
9021 */
9022 if (nested_exit_on_intr(vcpu))
9023 return;
9024
9025 /*
9026 * Else, fall back to pre-APICv interrupt injection since L2
9027 * is run without virtual interrupt delivery.
9028 */
9029 if (!kvm_event_needs_reinjection(vcpu) &&
9030 vmx_interrupt_allowed(vcpu)) {
9031 kvm_queue_interrupt(vcpu, max_irr, false);
9032 vmx_inject_irq(vcpu);
9033 }
9034 }
9035
9036 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
9037 {
9038 struct vcpu_vmx *vmx = to_vmx(vcpu);
9039 int max_irr;
9040
9041 WARN_ON(!vcpu->arch.apicv_active);
9042 if (pi_test_on(&vmx->pi_desc)) {
9043 pi_clear_on(&vmx->pi_desc);
9044 /*
9045 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
9046 * But on x86 this is just a compiler barrier anyway.
9047 */
9048 smp_mb__after_atomic();
9049 max_irr = kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
9050 } else {
9051 max_irr = kvm_lapic_find_highest_irr(vcpu);
9052 }
9053 vmx_hwapic_irr_update(vcpu, max_irr);
9054 return max_irr;
9055 }
9056
9057 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
9058 {
9059 if (!kvm_vcpu_apicv_active(vcpu))
9060 return;
9061
9062 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
9063 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
9064 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
9065 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
9066 }
9067
9068 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
9069 {
9070 struct vcpu_vmx *vmx = to_vmx(vcpu);
9071
9072 pi_clear_on(&vmx->pi_desc);
9073 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
9074 }
9075
9076 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
9077 {
9078 u32 exit_intr_info = 0;
9079 u16 basic_exit_reason = (u16)vmx->exit_reason;
9080
9081 if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
9082 || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
9083 return;
9084
9085 if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9086 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9087 vmx->exit_intr_info = exit_intr_info;
9088
9089 /* if exit due to PF check for async PF */
9090 if (is_page_fault(exit_intr_info))
9091 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
9092
9093 /* Handle machine checks before interrupts are enabled */
9094 if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
9095 is_machine_check(exit_intr_info))
9096 kvm_machine_check();
9097
9098 /* We need to handle NMIs before interrupts are enabled */
9099 if (is_nmi(exit_intr_info)) {
9100 kvm_before_handle_nmi(&vmx->vcpu);
9101 asm("int $2");
9102 kvm_after_handle_nmi(&vmx->vcpu);
9103 }
9104 }
9105
9106 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
9107 {
9108 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9109
9110 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
9111 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
9112 unsigned int vector;
9113 unsigned long entry;
9114 gate_desc *desc;
9115 struct vcpu_vmx *vmx = to_vmx(vcpu);
9116 #ifdef CONFIG_X86_64
9117 unsigned long tmp;
9118 #endif
9119
9120 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
9121 desc = (gate_desc *)vmx->host_idt_base + vector;
9122 entry = gate_offset(desc);
9123 asm volatile(
9124 #ifdef CONFIG_X86_64
9125 "mov %%" _ASM_SP ", %[sp]\n\t"
9126 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
9127 "push $%c[ss]\n\t"
9128 "push %[sp]\n\t"
9129 #endif
9130 "pushf\n\t"
9131 __ASM_SIZE(push) " $%c[cs]\n\t"
9132 "call *%[entry]\n\t"
9133 :
9134 #ifdef CONFIG_X86_64
9135 [sp]"=&r"(tmp),
9136 #endif
9137 ASM_CALL_CONSTRAINT
9138 :
9139 [entry]"r"(entry),
9140 [ss]"i"(__KERNEL_DS),
9141 [cs]"i"(__KERNEL_CS)
9142 );
9143 }
9144 }
9145 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
9146
9147 static bool vmx_has_high_real_mode_segbase(void)
9148 {
9149 return enable_unrestricted_guest || emulate_invalid_guest_state;
9150 }
9151
9152 static bool vmx_mpx_supported(void)
9153 {
9154 return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
9155 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
9156 }
9157
9158 static bool vmx_xsaves_supported(void)
9159 {
9160 return vmcs_config.cpu_based_2nd_exec_ctrl &
9161 SECONDARY_EXEC_XSAVES;
9162 }
9163
9164 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
9165 {
9166 u32 exit_intr_info;
9167 bool unblock_nmi;
9168 u8 vector;
9169 bool idtv_info_valid;
9170
9171 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9172
9173 if (enable_vnmi) {
9174 if (vmx->loaded_vmcs->nmi_known_unmasked)
9175 return;
9176 /*
9177 * Can't use vmx->exit_intr_info since we're not sure what
9178 * the exit reason is.
9179 */
9180 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9181 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
9182 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
9183 /*
9184 * SDM 3: 27.7.1.2 (September 2008)
9185 * Re-set bit "block by NMI" before VM entry if vmexit caused by
9186 * a guest IRET fault.
9187 * SDM 3: 23.2.2 (September 2008)
9188 * Bit 12 is undefined in any of the following cases:
9189 * If the VM exit sets the valid bit in the IDT-vectoring
9190 * information field.
9191 * If the VM exit is due to a double fault.
9192 */
9193 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
9194 vector != DF_VECTOR && !idtv_info_valid)
9195 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9196 GUEST_INTR_STATE_NMI);
9197 else
9198 vmx->loaded_vmcs->nmi_known_unmasked =
9199 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
9200 & GUEST_INTR_STATE_NMI);
9201 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
9202 vmx->loaded_vmcs->vnmi_blocked_time +=
9203 ktime_to_ns(ktime_sub(ktime_get(),
9204 vmx->loaded_vmcs->entry_time));
9205 }
9206
9207 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
9208 u32 idt_vectoring_info,
9209 int instr_len_field,
9210 int error_code_field)
9211 {
9212 u8 vector;
9213 int type;
9214 bool idtv_info_valid;
9215
9216 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9217
9218 vcpu->arch.nmi_injected = false;
9219 kvm_clear_exception_queue(vcpu);
9220 kvm_clear_interrupt_queue(vcpu);
9221
9222 if (!idtv_info_valid)
9223 return;
9224
9225 kvm_make_request(KVM_REQ_EVENT, vcpu);
9226
9227 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
9228 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
9229
9230 switch (type) {
9231 case INTR_TYPE_NMI_INTR:
9232 vcpu->arch.nmi_injected = true;
9233 /*
9234 * SDM 3: 27.7.1.2 (September 2008)
9235 * Clear bit "block by NMI" before VM entry if a NMI
9236 * delivery faulted.
9237 */
9238 vmx_set_nmi_mask(vcpu, false);
9239 break;
9240 case INTR_TYPE_SOFT_EXCEPTION:
9241 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9242 /* fall through */
9243 case INTR_TYPE_HARD_EXCEPTION:
9244 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
9245 u32 err = vmcs_read32(error_code_field);
9246 kvm_requeue_exception_e(vcpu, vector, err);
9247 } else
9248 kvm_requeue_exception(vcpu, vector);
9249 break;
9250 case INTR_TYPE_SOFT_INTR:
9251 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9252 /* fall through */
9253 case INTR_TYPE_EXT_INTR:
9254 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
9255 break;
9256 default:
9257 break;
9258 }
9259 }
9260
9261 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
9262 {
9263 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
9264 VM_EXIT_INSTRUCTION_LEN,
9265 IDT_VECTORING_ERROR_CODE);
9266 }
9267
9268 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
9269 {
9270 __vmx_complete_interrupts(vcpu,
9271 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
9272 VM_ENTRY_INSTRUCTION_LEN,
9273 VM_ENTRY_EXCEPTION_ERROR_CODE);
9274
9275 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
9276 }
9277
9278 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
9279 {
9280 int i, nr_msrs;
9281 struct perf_guest_switch_msr *msrs;
9282
9283 msrs = perf_guest_get_msrs(&nr_msrs);
9284
9285 if (!msrs)
9286 return;
9287
9288 for (i = 0; i < nr_msrs; i++)
9289 if (msrs[i].host == msrs[i].guest)
9290 clear_atomic_switch_msr(vmx, msrs[i].msr);
9291 else
9292 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
9293 msrs[i].host);
9294 }
9295
9296 static void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
9297 {
9298 struct vcpu_vmx *vmx = to_vmx(vcpu);
9299 u64 tscl;
9300 u32 delta_tsc;
9301
9302 if (vmx->hv_deadline_tsc == -1)
9303 return;
9304
9305 tscl = rdtsc();
9306 if (vmx->hv_deadline_tsc > tscl)
9307 /* sure to be 32 bit only because checked on set_hv_timer */
9308 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
9309 cpu_preemption_timer_multi);
9310 else
9311 delta_tsc = 0;
9312
9313 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
9314 }
9315
9316 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
9317 {
9318 struct vcpu_vmx *vmx = to_vmx(vcpu);
9319 unsigned long debugctlmsr, cr3, cr4;
9320
9321 /* Record the guest's net vcpu time for enforced NMI injections. */
9322 if (unlikely(!enable_vnmi &&
9323 vmx->loaded_vmcs->soft_vnmi_blocked))
9324 vmx->loaded_vmcs->entry_time = ktime_get();
9325
9326 /* Don't enter VMX if guest state is invalid, let the exit handler
9327 start emulation until we arrive back to a valid state */
9328 if (vmx->emulation_required)
9329 return;
9330
9331 if (vmx->ple_window_dirty) {
9332 vmx->ple_window_dirty = false;
9333 vmcs_write32(PLE_WINDOW, vmx->ple_window);
9334 }
9335
9336 if (vmx->nested.sync_shadow_vmcs) {
9337 copy_vmcs12_to_shadow(vmx);
9338 vmx->nested.sync_shadow_vmcs = false;
9339 }
9340
9341 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
9342 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
9343 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
9344 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
9345
9346 cr3 = __get_current_cr3_fast();
9347 if (unlikely(cr3 != vmx->loaded_vmcs->vmcs_host_cr3)) {
9348 vmcs_writel(HOST_CR3, cr3);
9349 vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
9350 }
9351
9352 cr4 = cr4_read_shadow();
9353 if (unlikely(cr4 != vmx->loaded_vmcs->vmcs_host_cr4)) {
9354 vmcs_writel(HOST_CR4, cr4);
9355 vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
9356 }
9357
9358 /* When single-stepping over STI and MOV SS, we must clear the
9359 * corresponding interruptibility bits in the guest state. Otherwise
9360 * vmentry fails as it then expects bit 14 (BS) in pending debug
9361 * exceptions being set, but that's not correct for the guest debugging
9362 * case. */
9363 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9364 vmx_set_interrupt_shadow(vcpu, 0);
9365
9366 if (static_cpu_has(X86_FEATURE_PKU) &&
9367 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
9368 vcpu->arch.pkru != vmx->host_pkru)
9369 __write_pkru(vcpu->arch.pkru);
9370
9371 atomic_switch_perf_msrs(vmx);
9372 debugctlmsr = get_debugctlmsr();
9373
9374 vmx_arm_hv_timer(vcpu);
9375
9376 vmx->__launched = vmx->loaded_vmcs->launched;
9377 asm(
9378 /* Store host registers */
9379 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
9380 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
9381 "push %%" _ASM_CX " \n\t"
9382 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9383 "je 1f \n\t"
9384 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9385 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
9386 "1: \n\t"
9387 /* Reload cr2 if changed */
9388 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
9389 "mov %%cr2, %%" _ASM_DX " \n\t"
9390 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
9391 "je 2f \n\t"
9392 "mov %%" _ASM_AX", %%cr2 \n\t"
9393 "2: \n\t"
9394 /* Check if vmlaunch of vmresume is needed */
9395 "cmpl $0, %c[launched](%0) \n\t"
9396 /* Load guest registers. Don't clobber flags. */
9397 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
9398 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
9399 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
9400 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
9401 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
9402 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
9403 #ifdef CONFIG_X86_64
9404 "mov %c[r8](%0), %%r8 \n\t"
9405 "mov %c[r9](%0), %%r9 \n\t"
9406 "mov %c[r10](%0), %%r10 \n\t"
9407 "mov %c[r11](%0), %%r11 \n\t"
9408 "mov %c[r12](%0), %%r12 \n\t"
9409 "mov %c[r13](%0), %%r13 \n\t"
9410 "mov %c[r14](%0), %%r14 \n\t"
9411 "mov %c[r15](%0), %%r15 \n\t"
9412 #endif
9413 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
9414
9415 /* Enter guest mode */
9416 "jne 1f \n\t"
9417 __ex(ASM_VMX_VMLAUNCH) "\n\t"
9418 "jmp 2f \n\t"
9419 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
9420 "2: "
9421 /* Save guest registers, load host registers, keep flags */
9422 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
9423 "pop %0 \n\t"
9424 "setbe %c[fail](%0)\n\t"
9425 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
9426 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
9427 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
9428 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
9429 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
9430 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
9431 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
9432 #ifdef CONFIG_X86_64
9433 "mov %%r8, %c[r8](%0) \n\t"
9434 "mov %%r9, %c[r9](%0) \n\t"
9435 "mov %%r10, %c[r10](%0) \n\t"
9436 "mov %%r11, %c[r11](%0) \n\t"
9437 "mov %%r12, %c[r12](%0) \n\t"
9438 "mov %%r13, %c[r13](%0) \n\t"
9439 "mov %%r14, %c[r14](%0) \n\t"
9440 "mov %%r15, %c[r15](%0) \n\t"
9441 "xor %%r8d, %%r8d \n\t"
9442 "xor %%r9d, %%r9d \n\t"
9443 "xor %%r10d, %%r10d \n\t"
9444 "xor %%r11d, %%r11d \n\t"
9445 "xor %%r12d, %%r12d \n\t"
9446 "xor %%r13d, %%r13d \n\t"
9447 "xor %%r14d, %%r14d \n\t"
9448 "xor %%r15d, %%r15d \n\t"
9449 #endif
9450 "mov %%cr2, %%" _ASM_AX " \n\t"
9451 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
9452
9453 "xor %%eax, %%eax \n\t"
9454 "xor %%ebx, %%ebx \n\t"
9455 "xor %%esi, %%esi \n\t"
9456 "xor %%edi, %%edi \n\t"
9457 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
9458 ".pushsection .rodata \n\t"
9459 ".global vmx_return \n\t"
9460 "vmx_return: " _ASM_PTR " 2b \n\t"
9461 ".popsection"
9462 : : "c"(vmx), "d"((unsigned long)HOST_RSP),
9463 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
9464 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
9465 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
9466 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
9467 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
9468 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
9469 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
9470 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
9471 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
9472 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
9473 #ifdef CONFIG_X86_64
9474 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
9475 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
9476 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
9477 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
9478 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
9479 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
9480 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
9481 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
9482 #endif
9483 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
9484 [wordsize]"i"(sizeof(ulong))
9485 : "cc", "memory"
9486 #ifdef CONFIG_X86_64
9487 , "rax", "rbx", "rdi", "rsi"
9488 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
9489 #else
9490 , "eax", "ebx", "edi", "esi"
9491 #endif
9492 );
9493
9494 /* Eliminate branch target predictions from guest mode */
9495 vmexit_fill_RSB();
9496
9497 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
9498 if (debugctlmsr)
9499 update_debugctlmsr(debugctlmsr);
9500
9501 #ifndef CONFIG_X86_64
9502 /*
9503 * The sysexit path does not restore ds/es, so we must set them to
9504 * a reasonable value ourselves.
9505 *
9506 * We can't defer this to vmx_load_host_state() since that function
9507 * may be executed in interrupt context, which saves and restore segments
9508 * around it, nullifying its effect.
9509 */
9510 loadsegment(ds, __USER_DS);
9511 loadsegment(es, __USER_DS);
9512 #endif
9513
9514 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
9515 | (1 << VCPU_EXREG_RFLAGS)
9516 | (1 << VCPU_EXREG_PDPTR)
9517 | (1 << VCPU_EXREG_SEGMENTS)
9518 | (1 << VCPU_EXREG_CR3));
9519 vcpu->arch.regs_dirty = 0;
9520
9521 /*
9522 * eager fpu is enabled if PKEY is supported and CR4 is switched
9523 * back on host, so it is safe to read guest PKRU from current
9524 * XSAVE.
9525 */
9526 if (static_cpu_has(X86_FEATURE_PKU) &&
9527 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
9528 vcpu->arch.pkru = __read_pkru();
9529 if (vcpu->arch.pkru != vmx->host_pkru)
9530 __write_pkru(vmx->host_pkru);
9531 }
9532
9533 /*
9534 * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
9535 * we did not inject a still-pending event to L1 now because of
9536 * nested_run_pending, we need to re-enable this bit.
9537 */
9538 if (vmx->nested.nested_run_pending)
9539 kvm_make_request(KVM_REQ_EVENT, vcpu);
9540
9541 vmx->nested.nested_run_pending = 0;
9542 vmx->idt_vectoring_info = 0;
9543
9544 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
9545 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9546 return;
9547
9548 vmx->loaded_vmcs->launched = 1;
9549 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
9550
9551 vmx_complete_atomic_exit(vmx);
9552 vmx_recover_nmi_blocking(vmx);
9553 vmx_complete_interrupts(vmx);
9554 }
9555 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
9556
9557 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
9558 {
9559 struct vcpu_vmx *vmx = to_vmx(vcpu);
9560 int cpu;
9561
9562 if (vmx->loaded_vmcs == vmcs)
9563 return;
9564
9565 cpu = get_cpu();
9566 vmx->loaded_vmcs = vmcs;
9567 vmx_vcpu_put(vcpu);
9568 vmx_vcpu_load(vcpu, cpu);
9569 put_cpu();
9570 }
9571
9572 /*
9573 * Ensure that the current vmcs of the logical processor is the
9574 * vmcs01 of the vcpu before calling free_nested().
9575 */
9576 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
9577 {
9578 struct vcpu_vmx *vmx = to_vmx(vcpu);
9579 int r;
9580
9581 r = vcpu_load(vcpu);
9582 BUG_ON(r);
9583 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
9584 free_nested(vmx);
9585 vcpu_put(vcpu);
9586 }
9587
9588 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
9589 {
9590 struct vcpu_vmx *vmx = to_vmx(vcpu);
9591
9592 if (enable_pml)
9593 vmx_destroy_pml_buffer(vmx);
9594 free_vpid(vmx->vpid);
9595 leave_guest_mode(vcpu);
9596 vmx_free_vcpu_nested(vcpu);
9597 free_loaded_vmcs(vmx->loaded_vmcs);
9598 kfree(vmx->guest_msrs);
9599 kvm_vcpu_uninit(vcpu);
9600 kmem_cache_free(kvm_vcpu_cache, vmx);
9601 }
9602
9603 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
9604 {
9605 int err;
9606 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
9607 int cpu;
9608
9609 if (!vmx)
9610 return ERR_PTR(-ENOMEM);
9611
9612 vmx->vpid = allocate_vpid();
9613
9614 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
9615 if (err)
9616 goto free_vcpu;
9617
9618 err = -ENOMEM;
9619
9620 /*
9621 * If PML is turned on, failure on enabling PML just results in failure
9622 * of creating the vcpu, therefore we can simplify PML logic (by
9623 * avoiding dealing with cases, such as enabling PML partially on vcpus
9624 * for the guest, etc.
9625 */
9626 if (enable_pml) {
9627 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
9628 if (!vmx->pml_pg)
9629 goto uninit_vcpu;
9630 }
9631
9632 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
9633 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
9634 > PAGE_SIZE);
9635
9636 if (!vmx->guest_msrs)
9637 goto free_pml;
9638
9639 vmx->loaded_vmcs = &vmx->vmcs01;
9640 vmx->loaded_vmcs->vmcs = alloc_vmcs();
9641 vmx->loaded_vmcs->shadow_vmcs = NULL;
9642 if (!vmx->loaded_vmcs->vmcs)
9643 goto free_msrs;
9644 loaded_vmcs_init(vmx->loaded_vmcs);
9645
9646 cpu = get_cpu();
9647 vmx_vcpu_load(&vmx->vcpu, cpu);
9648 vmx->vcpu.cpu = cpu;
9649 vmx_vcpu_setup(vmx);
9650 vmx_vcpu_put(&vmx->vcpu);
9651 put_cpu();
9652 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
9653 err = alloc_apic_access_page(kvm);
9654 if (err)
9655 goto free_vmcs;
9656 }
9657
9658 if (enable_ept) {
9659 err = init_rmode_identity_map(kvm);
9660 if (err)
9661 goto free_vmcs;
9662 }
9663
9664 if (nested) {
9665 nested_vmx_setup_ctls_msrs(vmx);
9666 vmx->nested.vpid02 = allocate_vpid();
9667 }
9668
9669 vmx->nested.posted_intr_nv = -1;
9670 vmx->nested.current_vmptr = -1ull;
9671
9672 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
9673
9674 /*
9675 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
9676 * or POSTED_INTR_WAKEUP_VECTOR.
9677 */
9678 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
9679 vmx->pi_desc.sn = 1;
9680
9681 return &vmx->vcpu;
9682
9683 free_vmcs:
9684 free_vpid(vmx->nested.vpid02);
9685 free_loaded_vmcs(vmx->loaded_vmcs);
9686 free_msrs:
9687 kfree(vmx->guest_msrs);
9688 free_pml:
9689 vmx_destroy_pml_buffer(vmx);
9690 uninit_vcpu:
9691 kvm_vcpu_uninit(&vmx->vcpu);
9692 free_vcpu:
9693 free_vpid(vmx->vpid);
9694 kmem_cache_free(kvm_vcpu_cache, vmx);
9695 return ERR_PTR(err);
9696 }
9697
9698 static void __init vmx_check_processor_compat(void *rtn)
9699 {
9700 struct vmcs_config vmcs_conf;
9701
9702 *(int *)rtn = 0;
9703 if (setup_vmcs_config(&vmcs_conf) < 0)
9704 *(int *)rtn = -EIO;
9705 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
9706 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
9707 smp_processor_id());
9708 *(int *)rtn = -EIO;
9709 }
9710 }
9711
9712 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
9713 {
9714 u8 cache;
9715 u64 ipat = 0;
9716
9717 /* For VT-d and EPT combination
9718 * 1. MMIO: always map as UC
9719 * 2. EPT with VT-d:
9720 * a. VT-d without snooping control feature: can't guarantee the
9721 * result, try to trust guest.
9722 * b. VT-d with snooping control feature: snooping control feature of
9723 * VT-d engine can guarantee the cache correctness. Just set it
9724 * to WB to keep consistent with host. So the same as item 3.
9725 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
9726 * consistent with host MTRR
9727 */
9728 if (is_mmio) {
9729 cache = MTRR_TYPE_UNCACHABLE;
9730 goto exit;
9731 }
9732
9733 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
9734 ipat = VMX_EPT_IPAT_BIT;
9735 cache = MTRR_TYPE_WRBACK;
9736 goto exit;
9737 }
9738
9739 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
9740 ipat = VMX_EPT_IPAT_BIT;
9741 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
9742 cache = MTRR_TYPE_WRBACK;
9743 else
9744 cache = MTRR_TYPE_UNCACHABLE;
9745 goto exit;
9746 }
9747
9748 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
9749
9750 exit:
9751 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
9752 }
9753
9754 static int vmx_get_lpage_level(void)
9755 {
9756 if (enable_ept && !cpu_has_vmx_ept_1g_page())
9757 return PT_DIRECTORY_LEVEL;
9758 else
9759 /* For shadow and EPT supported 1GB page */
9760 return PT_PDPE_LEVEL;
9761 }
9762
9763 static void vmcs_set_secondary_exec_control(u32 new_ctl)
9764 {
9765 /*
9766 * These bits in the secondary execution controls field
9767 * are dynamic, the others are mostly based on the hypervisor
9768 * architecture and the guest's CPUID. Do not touch the
9769 * dynamic bits.
9770 */
9771 u32 mask =
9772 SECONDARY_EXEC_SHADOW_VMCS |
9773 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
9774 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9775
9776 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9777
9778 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
9779 (new_ctl & ~mask) | (cur_ctl & mask));
9780 }
9781
9782 /*
9783 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
9784 * (indicating "allowed-1") if they are supported in the guest's CPUID.
9785 */
9786 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
9787 {
9788 struct vcpu_vmx *vmx = to_vmx(vcpu);
9789 struct kvm_cpuid_entry2 *entry;
9790
9791 vmx->nested.nested_vmx_cr0_fixed1 = 0xffffffff;
9792 vmx->nested.nested_vmx_cr4_fixed1 = X86_CR4_PCE;
9793
9794 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
9795 if (entry && (entry->_reg & (_cpuid_mask))) \
9796 vmx->nested.nested_vmx_cr4_fixed1 |= (_cr4_mask); \
9797 } while (0)
9798
9799 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
9800 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
9801 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
9802 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
9803 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
9804 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
9805 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
9806 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
9807 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
9808 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
9809 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
9810 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
9811 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
9812 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
9813 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
9814
9815 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
9816 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
9817 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
9818 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
9819 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
9820 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
9821
9822 #undef cr4_fixed1_update
9823 }
9824
9825 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
9826 {
9827 struct vcpu_vmx *vmx = to_vmx(vcpu);
9828
9829 if (cpu_has_secondary_exec_ctrls()) {
9830 vmx_compute_secondary_exec_control(vmx);
9831 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
9832 }
9833
9834 if (nested_vmx_allowed(vcpu))
9835 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
9836 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9837 else
9838 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
9839 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9840
9841 if (nested_vmx_allowed(vcpu))
9842 nested_vmx_cr_fixed1_bits_update(vcpu);
9843 }
9844
9845 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
9846 {
9847 if (func == 1 && nested)
9848 entry->ecx |= bit(X86_FEATURE_VMX);
9849 }
9850
9851 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
9852 struct x86_exception *fault)
9853 {
9854 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9855 struct vcpu_vmx *vmx = to_vmx(vcpu);
9856 u32 exit_reason;
9857 unsigned long exit_qualification = vcpu->arch.exit_qualification;
9858
9859 if (vmx->nested.pml_full) {
9860 exit_reason = EXIT_REASON_PML_FULL;
9861 vmx->nested.pml_full = false;
9862 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
9863 } else if (fault->error_code & PFERR_RSVD_MASK)
9864 exit_reason = EXIT_REASON_EPT_MISCONFIG;
9865 else
9866 exit_reason = EXIT_REASON_EPT_VIOLATION;
9867
9868 nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
9869 vmcs12->guest_physical_address = fault->address;
9870 }
9871
9872 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
9873 {
9874 return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
9875 }
9876
9877 /* Callbacks for nested_ept_init_mmu_context: */
9878
9879 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
9880 {
9881 /* return the page table to be shadowed - in our case, EPT12 */
9882 return get_vmcs12(vcpu)->ept_pointer;
9883 }
9884
9885 static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
9886 {
9887 WARN_ON(mmu_is_nested(vcpu));
9888 if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
9889 return 1;
9890
9891 kvm_mmu_unload(vcpu);
9892 kvm_init_shadow_ept_mmu(vcpu,
9893 to_vmx(vcpu)->nested.nested_vmx_ept_caps &
9894 VMX_EPT_EXECUTE_ONLY_BIT,
9895 nested_ept_ad_enabled(vcpu));
9896 vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
9897 vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
9898 vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
9899
9900 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
9901 return 0;
9902 }
9903
9904 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
9905 {
9906 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
9907 }
9908
9909 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
9910 u16 error_code)
9911 {
9912 bool inequality, bit;
9913
9914 bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
9915 inequality =
9916 (error_code & vmcs12->page_fault_error_code_mask) !=
9917 vmcs12->page_fault_error_code_match;
9918 return inequality ^ bit;
9919 }
9920
9921 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
9922 struct x86_exception *fault)
9923 {
9924 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9925
9926 WARN_ON(!is_guest_mode(vcpu));
9927
9928 if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
9929 !to_vmx(vcpu)->nested.nested_run_pending) {
9930 vmcs12->vm_exit_intr_error_code = fault->error_code;
9931 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
9932 PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
9933 INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
9934 fault->address);
9935 } else {
9936 kvm_inject_page_fault(vcpu, fault);
9937 }
9938 }
9939
9940 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
9941 struct vmcs12 *vmcs12);
9942
9943 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
9944 struct vmcs12 *vmcs12)
9945 {
9946 struct vcpu_vmx *vmx = to_vmx(vcpu);
9947 struct page *page;
9948 u64 hpa;
9949
9950 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
9951 /*
9952 * Translate L1 physical address to host physical
9953 * address for vmcs02. Keep the page pinned, so this
9954 * physical address remains valid. We keep a reference
9955 * to it so we can release it later.
9956 */
9957 if (vmx->nested.apic_access_page) { /* shouldn't happen */
9958 kvm_release_page_dirty(vmx->nested.apic_access_page);
9959 vmx->nested.apic_access_page = NULL;
9960 }
9961 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
9962 /*
9963 * If translation failed, no matter: This feature asks
9964 * to exit when accessing the given address, and if it
9965 * can never be accessed, this feature won't do
9966 * anything anyway.
9967 */
9968 if (!is_error_page(page)) {
9969 vmx->nested.apic_access_page = page;
9970 hpa = page_to_phys(vmx->nested.apic_access_page);
9971 vmcs_write64(APIC_ACCESS_ADDR, hpa);
9972 } else {
9973 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
9974 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
9975 }
9976 } else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
9977 cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
9978 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
9979 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
9980 kvm_vcpu_reload_apic_access_page(vcpu);
9981 }
9982
9983 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
9984 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
9985 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
9986 vmx->nested.virtual_apic_page = NULL;
9987 }
9988 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
9989
9990 /*
9991 * If translation failed, VM entry will fail because
9992 * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
9993 * Failing the vm entry is _not_ what the processor
9994 * does but it's basically the only possibility we
9995 * have. We could still enter the guest if CR8 load
9996 * exits are enabled, CR8 store exits are enabled, and
9997 * virtualize APIC access is disabled; in this case
9998 * the processor would never use the TPR shadow and we
9999 * could simply clear the bit from the execution
10000 * control. But such a configuration is useless, so
10001 * let's keep the code simple.
10002 */
10003 if (!is_error_page(page)) {
10004 vmx->nested.virtual_apic_page = page;
10005 hpa = page_to_phys(vmx->nested.virtual_apic_page);
10006 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
10007 }
10008 }
10009
10010 if (nested_cpu_has_posted_intr(vmcs12)) {
10011 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
10012 kunmap(vmx->nested.pi_desc_page);
10013 kvm_release_page_dirty(vmx->nested.pi_desc_page);
10014 vmx->nested.pi_desc_page = NULL;
10015 }
10016 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
10017 if (is_error_page(page))
10018 return;
10019 vmx->nested.pi_desc_page = page;
10020 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
10021 vmx->nested.pi_desc =
10022 (struct pi_desc *)((void *)vmx->nested.pi_desc +
10023 (unsigned long)(vmcs12->posted_intr_desc_addr &
10024 (PAGE_SIZE - 1)));
10025 vmcs_write64(POSTED_INTR_DESC_ADDR,
10026 page_to_phys(vmx->nested.pi_desc_page) +
10027 (unsigned long)(vmcs12->posted_intr_desc_addr &
10028 (PAGE_SIZE - 1)));
10029 }
10030 if (cpu_has_vmx_msr_bitmap() &&
10031 nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS) &&
10032 nested_vmx_merge_msr_bitmap(vcpu, vmcs12))
10033 ;
10034 else
10035 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
10036 CPU_BASED_USE_MSR_BITMAPS);
10037 }
10038
10039 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
10040 {
10041 u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
10042 struct vcpu_vmx *vmx = to_vmx(vcpu);
10043
10044 if (vcpu->arch.virtual_tsc_khz == 0)
10045 return;
10046
10047 /* Make sure short timeouts reliably trigger an immediate vmexit.
10048 * hrtimer_start does not guarantee this. */
10049 if (preemption_timeout <= 1) {
10050 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
10051 return;
10052 }
10053
10054 preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
10055 preemption_timeout *= 1000000;
10056 do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
10057 hrtimer_start(&vmx->nested.preemption_timer,
10058 ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
10059 }
10060
10061 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
10062 struct vmcs12 *vmcs12)
10063 {
10064 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
10065 return 0;
10066
10067 if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
10068 !page_address_valid(vcpu, vmcs12->io_bitmap_b))
10069 return -EINVAL;
10070
10071 return 0;
10072 }
10073
10074 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
10075 struct vmcs12 *vmcs12)
10076 {
10077 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
10078 return 0;
10079
10080 if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
10081 return -EINVAL;
10082
10083 return 0;
10084 }
10085
10086 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
10087 struct vmcs12 *vmcs12)
10088 {
10089 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10090 return 0;
10091
10092 if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
10093 return -EINVAL;
10094
10095 return 0;
10096 }
10097
10098 /*
10099 * Merge L0's and L1's MSR bitmap, return false to indicate that
10100 * we do not use the hardware.
10101 */
10102 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
10103 struct vmcs12 *vmcs12)
10104 {
10105 int msr;
10106 struct page *page;
10107 unsigned long *msr_bitmap_l1;
10108 unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.msr_bitmap;
10109
10110 /* This shortcut is ok because we support only x2APIC MSRs so far. */
10111 if (!nested_cpu_has_virt_x2apic_mode(vmcs12))
10112 return false;
10113
10114 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
10115 if (is_error_page(page))
10116 return false;
10117 msr_bitmap_l1 = (unsigned long *)kmap(page);
10118
10119 memset(msr_bitmap_l0, 0xff, PAGE_SIZE);
10120
10121 if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
10122 if (nested_cpu_has_apic_reg_virt(vmcs12))
10123 for (msr = 0x800; msr <= 0x8ff; msr++)
10124 nested_vmx_disable_intercept_for_msr(
10125 msr_bitmap_l1, msr_bitmap_l0,
10126 msr, MSR_TYPE_R);
10127
10128 nested_vmx_disable_intercept_for_msr(
10129 msr_bitmap_l1, msr_bitmap_l0,
10130 APIC_BASE_MSR + (APIC_TASKPRI >> 4),
10131 MSR_TYPE_R | MSR_TYPE_W);
10132
10133 if (nested_cpu_has_vid(vmcs12)) {
10134 nested_vmx_disable_intercept_for_msr(
10135 msr_bitmap_l1, msr_bitmap_l0,
10136 APIC_BASE_MSR + (APIC_EOI >> 4),
10137 MSR_TYPE_W);
10138 nested_vmx_disable_intercept_for_msr(
10139 msr_bitmap_l1, msr_bitmap_l0,
10140 APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
10141 MSR_TYPE_W);
10142 }
10143 }
10144 kunmap(page);
10145 kvm_release_page_clean(page);
10146
10147 return true;
10148 }
10149
10150 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
10151 struct vmcs12 *vmcs12)
10152 {
10153 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10154 !nested_cpu_has_apic_reg_virt(vmcs12) &&
10155 !nested_cpu_has_vid(vmcs12) &&
10156 !nested_cpu_has_posted_intr(vmcs12))
10157 return 0;
10158
10159 /*
10160 * If virtualize x2apic mode is enabled,
10161 * virtualize apic access must be disabled.
10162 */
10163 if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10164 nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
10165 return -EINVAL;
10166
10167 /*
10168 * If virtual interrupt delivery is enabled,
10169 * we must exit on external interrupts.
10170 */
10171 if (nested_cpu_has_vid(vmcs12) &&
10172 !nested_exit_on_intr(vcpu))
10173 return -EINVAL;
10174
10175 /*
10176 * bits 15:8 should be zero in posted_intr_nv,
10177 * the descriptor address has been already checked
10178 * in nested_get_vmcs12_pages.
10179 */
10180 if (nested_cpu_has_posted_intr(vmcs12) &&
10181 (!nested_cpu_has_vid(vmcs12) ||
10182 !nested_exit_intr_ack_set(vcpu) ||
10183 vmcs12->posted_intr_nv & 0xff00))
10184 return -EINVAL;
10185
10186 /* tpr shadow is needed by all apicv features. */
10187 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10188 return -EINVAL;
10189
10190 return 0;
10191 }
10192
10193 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
10194 unsigned long count_field,
10195 unsigned long addr_field)
10196 {
10197 int maxphyaddr;
10198 u64 count, addr;
10199
10200 if (vmcs12_read_any(vcpu, count_field, &count) ||
10201 vmcs12_read_any(vcpu, addr_field, &addr)) {
10202 WARN_ON(1);
10203 return -EINVAL;
10204 }
10205 if (count == 0)
10206 return 0;
10207 maxphyaddr = cpuid_maxphyaddr(vcpu);
10208 if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
10209 (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
10210 pr_debug_ratelimited(
10211 "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
10212 addr_field, maxphyaddr, count, addr);
10213 return -EINVAL;
10214 }
10215 return 0;
10216 }
10217
10218 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
10219 struct vmcs12 *vmcs12)
10220 {
10221 if (vmcs12->vm_exit_msr_load_count == 0 &&
10222 vmcs12->vm_exit_msr_store_count == 0 &&
10223 vmcs12->vm_entry_msr_load_count == 0)
10224 return 0; /* Fast path */
10225 if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
10226 VM_EXIT_MSR_LOAD_ADDR) ||
10227 nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
10228 VM_EXIT_MSR_STORE_ADDR) ||
10229 nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
10230 VM_ENTRY_MSR_LOAD_ADDR))
10231 return -EINVAL;
10232 return 0;
10233 }
10234
10235 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
10236 struct vmcs12 *vmcs12)
10237 {
10238 u64 address = vmcs12->pml_address;
10239 int maxphyaddr = cpuid_maxphyaddr(vcpu);
10240
10241 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
10242 if (!nested_cpu_has_ept(vmcs12) ||
10243 !IS_ALIGNED(address, 4096) ||
10244 address >> maxphyaddr)
10245 return -EINVAL;
10246 }
10247
10248 return 0;
10249 }
10250
10251 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
10252 struct vmx_msr_entry *e)
10253 {
10254 /* x2APIC MSR accesses are not allowed */
10255 if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
10256 return -EINVAL;
10257 if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
10258 e->index == MSR_IA32_UCODE_REV)
10259 return -EINVAL;
10260 if (e->reserved != 0)
10261 return -EINVAL;
10262 return 0;
10263 }
10264
10265 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
10266 struct vmx_msr_entry *e)
10267 {
10268 if (e->index == MSR_FS_BASE ||
10269 e->index == MSR_GS_BASE ||
10270 e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
10271 nested_vmx_msr_check_common(vcpu, e))
10272 return -EINVAL;
10273 return 0;
10274 }
10275
10276 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
10277 struct vmx_msr_entry *e)
10278 {
10279 if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
10280 nested_vmx_msr_check_common(vcpu, e))
10281 return -EINVAL;
10282 return 0;
10283 }
10284
10285 /*
10286 * Load guest's/host's msr at nested entry/exit.
10287 * return 0 for success, entry index for failure.
10288 */
10289 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10290 {
10291 u32 i;
10292 struct vmx_msr_entry e;
10293 struct msr_data msr;
10294
10295 msr.host_initiated = false;
10296 for (i = 0; i < count; i++) {
10297 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
10298 &e, sizeof(e))) {
10299 pr_debug_ratelimited(
10300 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10301 __func__, i, gpa + i * sizeof(e));
10302 goto fail;
10303 }
10304 if (nested_vmx_load_msr_check(vcpu, &e)) {
10305 pr_debug_ratelimited(
10306 "%s check failed (%u, 0x%x, 0x%x)\n",
10307 __func__, i, e.index, e.reserved);
10308 goto fail;
10309 }
10310 msr.index = e.index;
10311 msr.data = e.value;
10312 if (kvm_set_msr(vcpu, &msr)) {
10313 pr_debug_ratelimited(
10314 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10315 __func__, i, e.index, e.value);
10316 goto fail;
10317 }
10318 }
10319 return 0;
10320 fail:
10321 return i + 1;
10322 }
10323
10324 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10325 {
10326 u32 i;
10327 struct vmx_msr_entry e;
10328
10329 for (i = 0; i < count; i++) {
10330 struct msr_data msr_info;
10331 if (kvm_vcpu_read_guest(vcpu,
10332 gpa + i * sizeof(e),
10333 &e, 2 * sizeof(u32))) {
10334 pr_debug_ratelimited(
10335 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10336 __func__, i, gpa + i * sizeof(e));
10337 return -EINVAL;
10338 }
10339 if (nested_vmx_store_msr_check(vcpu, &e)) {
10340 pr_debug_ratelimited(
10341 "%s check failed (%u, 0x%x, 0x%x)\n",
10342 __func__, i, e.index, e.reserved);
10343 return -EINVAL;
10344 }
10345 msr_info.host_initiated = false;
10346 msr_info.index = e.index;
10347 if (kvm_get_msr(vcpu, &msr_info)) {
10348 pr_debug_ratelimited(
10349 "%s cannot read MSR (%u, 0x%x)\n",
10350 __func__, i, e.index);
10351 return -EINVAL;
10352 }
10353 if (kvm_vcpu_write_guest(vcpu,
10354 gpa + i * sizeof(e) +
10355 offsetof(struct vmx_msr_entry, value),
10356 &msr_info.data, sizeof(msr_info.data))) {
10357 pr_debug_ratelimited(
10358 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10359 __func__, i, e.index, msr_info.data);
10360 return -EINVAL;
10361 }
10362 }
10363 return 0;
10364 }
10365
10366 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
10367 {
10368 unsigned long invalid_mask;
10369
10370 invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
10371 return (val & invalid_mask) == 0;
10372 }
10373
10374 /*
10375 * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
10376 * emulating VM entry into a guest with EPT enabled.
10377 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10378 * is assigned to entry_failure_code on failure.
10379 */
10380 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
10381 u32 *entry_failure_code)
10382 {
10383 if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
10384 if (!nested_cr3_valid(vcpu, cr3)) {
10385 *entry_failure_code = ENTRY_FAIL_DEFAULT;
10386 return 1;
10387 }
10388
10389 /*
10390 * If PAE paging and EPT are both on, CR3 is not used by the CPU and
10391 * must not be dereferenced.
10392 */
10393 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
10394 !nested_ept) {
10395 if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
10396 *entry_failure_code = ENTRY_FAIL_PDPTE;
10397 return 1;
10398 }
10399 }
10400
10401 vcpu->arch.cr3 = cr3;
10402 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
10403 }
10404
10405 kvm_mmu_reset_context(vcpu);
10406 return 0;
10407 }
10408
10409 /*
10410 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
10411 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
10412 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
10413 * guest in a way that will both be appropriate to L1's requests, and our
10414 * needs. In addition to modifying the active vmcs (which is vmcs02), this
10415 * function also has additional necessary side-effects, like setting various
10416 * vcpu->arch fields.
10417 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10418 * is assigned to entry_failure_code on failure.
10419 */
10420 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10421 bool from_vmentry, u32 *entry_failure_code)
10422 {
10423 struct vcpu_vmx *vmx = to_vmx(vcpu);
10424 u32 exec_control, vmcs12_exec_ctrl;
10425
10426 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
10427 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
10428 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
10429 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
10430 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
10431 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
10432 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
10433 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
10434 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
10435 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
10436 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
10437 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
10438 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
10439 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
10440 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
10441 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
10442 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
10443 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
10444 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
10445 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
10446 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
10447 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
10448 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
10449 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
10450 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
10451 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
10452 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
10453 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
10454 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
10455 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
10456 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
10457 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
10458 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
10459 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
10460 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
10461 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
10462
10463 if (from_vmentry &&
10464 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
10465 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
10466 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
10467 } else {
10468 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
10469 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
10470 }
10471 if (from_vmentry) {
10472 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
10473 vmcs12->vm_entry_intr_info_field);
10474 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
10475 vmcs12->vm_entry_exception_error_code);
10476 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
10477 vmcs12->vm_entry_instruction_len);
10478 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
10479 vmcs12->guest_interruptibility_info);
10480 vmx->loaded_vmcs->nmi_known_unmasked =
10481 !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
10482 } else {
10483 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10484 }
10485 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
10486 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
10487 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
10488 vmcs12->guest_pending_dbg_exceptions);
10489 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
10490 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
10491
10492 if (nested_cpu_has_xsaves(vmcs12))
10493 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
10494 vmcs_write64(VMCS_LINK_POINTER, -1ull);
10495
10496 exec_control = vmcs12->pin_based_vm_exec_control;
10497
10498 /* Preemption timer setting is only taken from vmcs01. */
10499 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10500 exec_control |= vmcs_config.pin_based_exec_ctrl;
10501 if (vmx->hv_deadline_tsc == -1)
10502 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10503
10504 /* Posted interrupts setting is only taken from vmcs12. */
10505 if (nested_cpu_has_posted_intr(vmcs12)) {
10506 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
10507 vmx->nested.pi_pending = false;
10508 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
10509 } else {
10510 exec_control &= ~PIN_BASED_POSTED_INTR;
10511 }
10512
10513 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
10514
10515 vmx->nested.preemption_timer_expired = false;
10516 if (nested_cpu_has_preemption_timer(vmcs12))
10517 vmx_start_preemption_timer(vcpu);
10518
10519 /*
10520 * Whether page-faults are trapped is determined by a combination of
10521 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
10522 * If enable_ept, L0 doesn't care about page faults and we should
10523 * set all of these to L1's desires. However, if !enable_ept, L0 does
10524 * care about (at least some) page faults, and because it is not easy
10525 * (if at all possible?) to merge L0 and L1's desires, we simply ask
10526 * to exit on each and every L2 page fault. This is done by setting
10527 * MASK=MATCH=0 and (see below) EB.PF=1.
10528 * Note that below we don't need special code to set EB.PF beyond the
10529 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
10530 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
10531 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
10532 */
10533 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
10534 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
10535 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
10536 enable_ept ? vmcs12->page_fault_error_code_match : 0);
10537
10538 if (cpu_has_secondary_exec_ctrls()) {
10539 exec_control = vmx->secondary_exec_control;
10540
10541 /* Take the following fields only from vmcs12 */
10542 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10543 SECONDARY_EXEC_ENABLE_INVPCID |
10544 SECONDARY_EXEC_RDTSCP |
10545 SECONDARY_EXEC_XSAVES |
10546 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
10547 SECONDARY_EXEC_APIC_REGISTER_VIRT |
10548 SECONDARY_EXEC_ENABLE_VMFUNC);
10549 if (nested_cpu_has(vmcs12,
10550 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
10551 vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
10552 ~SECONDARY_EXEC_ENABLE_PML;
10553 exec_control |= vmcs12_exec_ctrl;
10554 }
10555
10556 /* All VMFUNCs are currently emulated through L0 vmexits. */
10557 if (exec_control & SECONDARY_EXEC_ENABLE_VMFUNC)
10558 vmcs_write64(VM_FUNCTION_CONTROL, 0);
10559
10560 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
10561 vmcs_write64(EOI_EXIT_BITMAP0,
10562 vmcs12->eoi_exit_bitmap0);
10563 vmcs_write64(EOI_EXIT_BITMAP1,
10564 vmcs12->eoi_exit_bitmap1);
10565 vmcs_write64(EOI_EXIT_BITMAP2,
10566 vmcs12->eoi_exit_bitmap2);
10567 vmcs_write64(EOI_EXIT_BITMAP3,
10568 vmcs12->eoi_exit_bitmap3);
10569 vmcs_write16(GUEST_INTR_STATUS,
10570 vmcs12->guest_intr_status);
10571 }
10572
10573 /*
10574 * Write an illegal value to APIC_ACCESS_ADDR. Later,
10575 * nested_get_vmcs12_pages will either fix it up or
10576 * remove the VM execution control.
10577 */
10578 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
10579 vmcs_write64(APIC_ACCESS_ADDR, -1ull);
10580
10581 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
10582 }
10583
10584
10585 /*
10586 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
10587 * Some constant fields are set here by vmx_set_constant_host_state().
10588 * Other fields are different per CPU, and will be set later when
10589 * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
10590 */
10591 vmx_set_constant_host_state(vmx);
10592
10593 /*
10594 * Set the MSR load/store lists to match L0's settings.
10595 */
10596 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
10597 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10598 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
10599 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10600 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
10601
10602 /*
10603 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
10604 * entry, but only if the current (host) sp changed from the value
10605 * we wrote last (vmx->host_rsp). This cache is no longer relevant
10606 * if we switch vmcs, and rather than hold a separate cache per vmcs,
10607 * here we just force the write to happen on entry.
10608 */
10609 vmx->host_rsp = 0;
10610
10611 exec_control = vmx_exec_control(vmx); /* L0's desires */
10612 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
10613 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
10614 exec_control &= ~CPU_BASED_TPR_SHADOW;
10615 exec_control |= vmcs12->cpu_based_vm_exec_control;
10616
10617 /*
10618 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
10619 * nested_get_vmcs12_pages can't fix it up, the illegal value
10620 * will result in a VM entry failure.
10621 */
10622 if (exec_control & CPU_BASED_TPR_SHADOW) {
10623 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
10624 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
10625 } else {
10626 #ifdef CONFIG_X86_64
10627 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
10628 CPU_BASED_CR8_STORE_EXITING;
10629 #endif
10630 }
10631
10632 /*
10633 * Merging of IO bitmap not currently supported.
10634 * Rather, exit every time.
10635 */
10636 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
10637 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
10638
10639 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
10640
10641 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
10642 * bitwise-or of what L1 wants to trap for L2, and what we want to
10643 * trap. Note that CR0.TS also needs updating - we do this later.
10644 */
10645 update_exception_bitmap(vcpu);
10646 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
10647 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
10648
10649 /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
10650 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
10651 * bits are further modified by vmx_set_efer() below.
10652 */
10653 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
10654
10655 /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
10656 * emulated by vmx_set_efer(), below.
10657 */
10658 vm_entry_controls_init(vmx,
10659 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
10660 ~VM_ENTRY_IA32E_MODE) |
10661 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
10662
10663 if (from_vmentry &&
10664 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
10665 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
10666 vcpu->arch.pat = vmcs12->guest_ia32_pat;
10667 } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
10668 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
10669 }
10670
10671 set_cr4_guest_host_mask(vmx);
10672
10673 if (from_vmentry &&
10674 vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
10675 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
10676
10677 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
10678 vmcs_write64(TSC_OFFSET,
10679 vcpu->arch.tsc_offset + vmcs12->tsc_offset);
10680 else
10681 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
10682 if (kvm_has_tsc_control)
10683 decache_tsc_multiplier(vmx);
10684
10685 if (enable_vpid) {
10686 /*
10687 * There is no direct mapping between vpid02 and vpid12, the
10688 * vpid02 is per-vCPU for L0 and reused while the value of
10689 * vpid12 is changed w/ one invvpid during nested vmentry.
10690 * The vpid12 is allocated by L1 for L2, so it will not
10691 * influence global bitmap(for vpid01 and vpid02 allocation)
10692 * even if spawn a lot of nested vCPUs.
10693 */
10694 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
10695 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
10696 if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
10697 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
10698 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02);
10699 }
10700 } else {
10701 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
10702 vmx_flush_tlb(vcpu);
10703 }
10704
10705 }
10706
10707 if (enable_pml) {
10708 /*
10709 * Conceptually we want to copy the PML address and index from
10710 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
10711 * since we always flush the log on each vmexit, this happens
10712 * to be equivalent to simply resetting the fields in vmcs02.
10713 */
10714 ASSERT(vmx->pml_pg);
10715 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
10716 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10717 }
10718
10719 if (nested_cpu_has_ept(vmcs12)) {
10720 if (nested_ept_init_mmu_context(vcpu)) {
10721 *entry_failure_code = ENTRY_FAIL_DEFAULT;
10722 return 1;
10723 }
10724 } else if (nested_cpu_has2(vmcs12,
10725 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10726 vmx_flush_tlb_ept_only(vcpu);
10727 }
10728
10729 /*
10730 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
10731 * bits which we consider mandatory enabled.
10732 * The CR0_READ_SHADOW is what L2 should have expected to read given
10733 * the specifications by L1; It's not enough to take
10734 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
10735 * have more bits than L1 expected.
10736 */
10737 vmx_set_cr0(vcpu, vmcs12->guest_cr0);
10738 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
10739
10740 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
10741 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
10742
10743 if (from_vmentry &&
10744 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
10745 vcpu->arch.efer = vmcs12->guest_ia32_efer;
10746 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
10747 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
10748 else
10749 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
10750 /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
10751 vmx_set_efer(vcpu, vcpu->arch.efer);
10752
10753 /* Shadow page tables on either EPT or shadow page tables. */
10754 if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
10755 entry_failure_code))
10756 return 1;
10757
10758 if (!enable_ept)
10759 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
10760
10761 /*
10762 * L1 may access the L2's PDPTR, so save them to construct vmcs12
10763 */
10764 if (enable_ept) {
10765 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
10766 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
10767 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
10768 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
10769 }
10770
10771 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
10772 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
10773 return 0;
10774 }
10775
10776 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10777 {
10778 struct vcpu_vmx *vmx = to_vmx(vcpu);
10779
10780 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
10781 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
10782 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10783
10784 if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
10785 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10786
10787 if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
10788 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10789
10790 if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
10791 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10792
10793 if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
10794 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10795
10796 if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
10797 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10798
10799 if (nested_vmx_check_pml_controls(vcpu, vmcs12))
10800 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10801
10802 if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
10803 vmx->nested.nested_vmx_procbased_ctls_low,
10804 vmx->nested.nested_vmx_procbased_ctls_high) ||
10805 (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
10806 !vmx_control_verify(vmcs12->secondary_vm_exec_control,
10807 vmx->nested.nested_vmx_secondary_ctls_low,
10808 vmx->nested.nested_vmx_secondary_ctls_high)) ||
10809 !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
10810 vmx->nested.nested_vmx_pinbased_ctls_low,
10811 vmx->nested.nested_vmx_pinbased_ctls_high) ||
10812 !vmx_control_verify(vmcs12->vm_exit_controls,
10813 vmx->nested.nested_vmx_exit_ctls_low,
10814 vmx->nested.nested_vmx_exit_ctls_high) ||
10815 !vmx_control_verify(vmcs12->vm_entry_controls,
10816 vmx->nested.nested_vmx_entry_ctls_low,
10817 vmx->nested.nested_vmx_entry_ctls_high))
10818 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10819
10820 if (nested_cpu_has_vmfunc(vmcs12)) {
10821 if (vmcs12->vm_function_control &
10822 ~vmx->nested.nested_vmx_vmfunc_controls)
10823 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10824
10825 if (nested_cpu_has_eptp_switching(vmcs12)) {
10826 if (!nested_cpu_has_ept(vmcs12) ||
10827 !page_address_valid(vcpu, vmcs12->eptp_list_address))
10828 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10829 }
10830 }
10831
10832 if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
10833 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10834
10835 if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
10836 !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
10837 !nested_cr3_valid(vcpu, vmcs12->host_cr3))
10838 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
10839
10840 return 0;
10841 }
10842
10843 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10844 u32 *exit_qual)
10845 {
10846 bool ia32e;
10847
10848 *exit_qual = ENTRY_FAIL_DEFAULT;
10849
10850 if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
10851 !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
10852 return 1;
10853
10854 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS) &&
10855 vmcs12->vmcs_link_pointer != -1ull) {
10856 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
10857 return 1;
10858 }
10859
10860 /*
10861 * If the load IA32_EFER VM-entry control is 1, the following checks
10862 * are performed on the field for the IA32_EFER MSR:
10863 * - Bits reserved in the IA32_EFER MSR must be 0.
10864 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
10865 * the IA-32e mode guest VM-exit control. It must also be identical
10866 * to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
10867 * CR0.PG) is 1.
10868 */
10869 if (to_vmx(vcpu)->nested.nested_run_pending &&
10870 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
10871 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
10872 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
10873 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
10874 ((vmcs12->guest_cr0 & X86_CR0_PG) &&
10875 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
10876 return 1;
10877 }
10878
10879 /*
10880 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
10881 * IA32_EFER MSR must be 0 in the field for that register. In addition,
10882 * the values of the LMA and LME bits in the field must each be that of
10883 * the host address-space size VM-exit control.
10884 */
10885 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
10886 ia32e = (vmcs12->vm_exit_controls &
10887 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
10888 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
10889 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
10890 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
10891 return 1;
10892 }
10893
10894 if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
10895 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
10896 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
10897 return 1;
10898
10899 return 0;
10900 }
10901
10902 static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, bool from_vmentry)
10903 {
10904 struct vcpu_vmx *vmx = to_vmx(vcpu);
10905 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10906 struct loaded_vmcs *vmcs02;
10907 u32 msr_entry_idx;
10908 u32 exit_qual;
10909
10910 vmcs02 = nested_get_current_vmcs02(vmx);
10911 if (!vmcs02)
10912 return -ENOMEM;
10913
10914 enter_guest_mode(vcpu);
10915
10916 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
10917 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
10918
10919 vmx_switch_vmcs(vcpu, vmcs02);
10920 vmx_segment_cache_clear(vmx);
10921
10922 if (prepare_vmcs02(vcpu, vmcs12, from_vmentry, &exit_qual)) {
10923 leave_guest_mode(vcpu);
10924 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
10925 nested_vmx_entry_failure(vcpu, vmcs12,
10926 EXIT_REASON_INVALID_STATE, exit_qual);
10927 return 1;
10928 }
10929
10930 nested_get_vmcs12_pages(vcpu, vmcs12);
10931
10932 msr_entry_idx = nested_vmx_load_msr(vcpu,
10933 vmcs12->vm_entry_msr_load_addr,
10934 vmcs12->vm_entry_msr_load_count);
10935 if (msr_entry_idx) {
10936 leave_guest_mode(vcpu);
10937 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
10938 nested_vmx_entry_failure(vcpu, vmcs12,
10939 EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
10940 return 1;
10941 }
10942
10943 /*
10944 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
10945 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
10946 * returned as far as L1 is concerned. It will only return (and set
10947 * the success flag) when L2 exits (see nested_vmx_vmexit()).
10948 */
10949 return 0;
10950 }
10951
10952 /*
10953 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
10954 * for running an L2 nested guest.
10955 */
10956 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
10957 {
10958 struct vmcs12 *vmcs12;
10959 struct vcpu_vmx *vmx = to_vmx(vcpu);
10960 u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
10961 u32 exit_qual;
10962 int ret;
10963
10964 if (!nested_vmx_check_permission(vcpu))
10965 return 1;
10966
10967 if (!nested_vmx_check_vmcs12(vcpu))
10968 goto out;
10969
10970 vmcs12 = get_vmcs12(vcpu);
10971
10972 if (enable_shadow_vmcs)
10973 copy_shadow_to_vmcs12(vmx);
10974
10975 /*
10976 * The nested entry process starts with enforcing various prerequisites
10977 * on vmcs12 as required by the Intel SDM, and act appropriately when
10978 * they fail: As the SDM explains, some conditions should cause the
10979 * instruction to fail, while others will cause the instruction to seem
10980 * to succeed, but return an EXIT_REASON_INVALID_STATE.
10981 * To speed up the normal (success) code path, we should avoid checking
10982 * for misconfigurations which will anyway be caught by the processor
10983 * when using the merged vmcs02.
10984 */
10985 if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
10986 nested_vmx_failValid(vcpu,
10987 VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
10988 goto out;
10989 }
10990
10991 if (vmcs12->launch_state == launch) {
10992 nested_vmx_failValid(vcpu,
10993 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
10994 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
10995 goto out;
10996 }
10997
10998 ret = check_vmentry_prereqs(vcpu, vmcs12);
10999 if (ret) {
11000 nested_vmx_failValid(vcpu, ret);
11001 goto out;
11002 }
11003
11004 /*
11005 * After this point, the trap flag no longer triggers a singlestep trap
11006 * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
11007 * This is not 100% correct; for performance reasons, we delegate most
11008 * of the checks on host state to the processor. If those fail,
11009 * the singlestep trap is missed.
11010 */
11011 skip_emulated_instruction(vcpu);
11012
11013 ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
11014 if (ret) {
11015 nested_vmx_entry_failure(vcpu, vmcs12,
11016 EXIT_REASON_INVALID_STATE, exit_qual);
11017 return 1;
11018 }
11019
11020 /*
11021 * We're finally done with prerequisite checking, and can start with
11022 * the nested entry.
11023 */
11024
11025 ret = enter_vmx_non_root_mode(vcpu, true);
11026 if (ret)
11027 return ret;
11028
11029 if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
11030 return kvm_vcpu_halt(vcpu);
11031
11032 vmx->nested.nested_run_pending = 1;
11033
11034 return 1;
11035
11036 out:
11037 return kvm_skip_emulated_instruction(vcpu);
11038 }
11039
11040 /*
11041 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
11042 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
11043 * This function returns the new value we should put in vmcs12.guest_cr0.
11044 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
11045 * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
11046 * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
11047 * didn't trap the bit, because if L1 did, so would L0).
11048 * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
11049 * been modified by L2, and L1 knows it. So just leave the old value of
11050 * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
11051 * isn't relevant, because if L0 traps this bit it can set it to anything.
11052 * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
11053 * changed these bits, and therefore they need to be updated, but L0
11054 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather
11055 * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
11056 */
11057 static inline unsigned long
11058 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11059 {
11060 return
11061 /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
11062 /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
11063 /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
11064 vcpu->arch.cr0_guest_owned_bits));
11065 }
11066
11067 static inline unsigned long
11068 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11069 {
11070 return
11071 /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
11072 /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
11073 /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
11074 vcpu->arch.cr4_guest_owned_bits));
11075 }
11076
11077 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
11078 struct vmcs12 *vmcs12)
11079 {
11080 u32 idt_vectoring;
11081 unsigned int nr;
11082
11083 if (vcpu->arch.exception.injected) {
11084 nr = vcpu->arch.exception.nr;
11085 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11086
11087 if (kvm_exception_is_soft(nr)) {
11088 vmcs12->vm_exit_instruction_len =
11089 vcpu->arch.event_exit_inst_len;
11090 idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
11091 } else
11092 idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
11093
11094 if (vcpu->arch.exception.has_error_code) {
11095 idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
11096 vmcs12->idt_vectoring_error_code =
11097 vcpu->arch.exception.error_code;
11098 }
11099
11100 vmcs12->idt_vectoring_info_field = idt_vectoring;
11101 } else if (vcpu->arch.nmi_injected) {
11102 vmcs12->idt_vectoring_info_field =
11103 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
11104 } else if (vcpu->arch.interrupt.pending) {
11105 nr = vcpu->arch.interrupt.nr;
11106 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11107
11108 if (vcpu->arch.interrupt.soft) {
11109 idt_vectoring |= INTR_TYPE_SOFT_INTR;
11110 vmcs12->vm_entry_instruction_len =
11111 vcpu->arch.event_exit_inst_len;
11112 } else
11113 idt_vectoring |= INTR_TYPE_EXT_INTR;
11114
11115 vmcs12->idt_vectoring_info_field = idt_vectoring;
11116 }
11117 }
11118
11119 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
11120 {
11121 struct vcpu_vmx *vmx = to_vmx(vcpu);
11122 unsigned long exit_qual;
11123 bool block_nested_events =
11124 vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
11125
11126 if (vcpu->arch.exception.pending &&
11127 nested_vmx_check_exception(vcpu, &exit_qual)) {
11128 if (block_nested_events)
11129 return -EBUSY;
11130 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
11131 vcpu->arch.exception.pending = false;
11132 return 0;
11133 }
11134
11135 if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
11136 vmx->nested.preemption_timer_expired) {
11137 if (block_nested_events)
11138 return -EBUSY;
11139 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
11140 return 0;
11141 }
11142
11143 if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
11144 if (block_nested_events)
11145 return -EBUSY;
11146 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11147 NMI_VECTOR | INTR_TYPE_NMI_INTR |
11148 INTR_INFO_VALID_MASK, 0);
11149 /*
11150 * The NMI-triggered VM exit counts as injection:
11151 * clear this one and block further NMIs.
11152 */
11153 vcpu->arch.nmi_pending = 0;
11154 vmx_set_nmi_mask(vcpu, true);
11155 return 0;
11156 }
11157
11158 if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
11159 nested_exit_on_intr(vcpu)) {
11160 if (block_nested_events)
11161 return -EBUSY;
11162 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
11163 return 0;
11164 }
11165
11166 vmx_complete_nested_posted_interrupt(vcpu);
11167 return 0;
11168 }
11169
11170 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
11171 {
11172 ktime_t remaining =
11173 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
11174 u64 value;
11175
11176 if (ktime_to_ns(remaining) <= 0)
11177 return 0;
11178
11179 value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
11180 do_div(value, 1000000);
11181 return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11182 }
11183
11184 /*
11185 * Update the guest state fields of vmcs12 to reflect changes that
11186 * occurred while L2 was running. (The "IA-32e mode guest" bit of the
11187 * VM-entry controls is also updated, since this is really a guest
11188 * state bit.)
11189 */
11190 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11191 {
11192 vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
11193 vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
11194
11195 vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
11196 vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
11197 vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
11198
11199 vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
11200 vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
11201 vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
11202 vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
11203 vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
11204 vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
11205 vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
11206 vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
11207 vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
11208 vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
11209 vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
11210 vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
11211 vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
11212 vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
11213 vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
11214 vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
11215 vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
11216 vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
11217 vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
11218 vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
11219 vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
11220 vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
11221 vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
11222 vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
11223 vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
11224 vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
11225 vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
11226 vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
11227 vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
11228 vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
11229 vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
11230 vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
11231 vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
11232 vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
11233 vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
11234 vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
11235
11236 vmcs12->guest_interruptibility_info =
11237 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
11238 vmcs12->guest_pending_dbg_exceptions =
11239 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
11240 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11241 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
11242 else
11243 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
11244
11245 if (nested_cpu_has_preemption_timer(vmcs12)) {
11246 if (vmcs12->vm_exit_controls &
11247 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
11248 vmcs12->vmx_preemption_timer_value =
11249 vmx_get_preemption_timer_value(vcpu);
11250 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
11251 }
11252
11253 /*
11254 * In some cases (usually, nested EPT), L2 is allowed to change its
11255 * own CR3 without exiting. If it has changed it, we must keep it.
11256 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
11257 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
11258 *
11259 * Additionally, restore L2's PDPTR to vmcs12.
11260 */
11261 if (enable_ept) {
11262 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
11263 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
11264 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
11265 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
11266 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
11267 }
11268
11269 vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
11270
11271 if (nested_cpu_has_vid(vmcs12))
11272 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
11273
11274 vmcs12->vm_entry_controls =
11275 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
11276 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
11277
11278 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
11279 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
11280 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11281 }
11282
11283 /* TODO: These cannot have changed unless we have MSR bitmaps and
11284 * the relevant bit asks not to trap the change */
11285 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
11286 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
11287 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
11288 vmcs12->guest_ia32_efer = vcpu->arch.efer;
11289 vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
11290 vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
11291 vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
11292 if (kvm_mpx_supported())
11293 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
11294 }
11295
11296 /*
11297 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
11298 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
11299 * and this function updates it to reflect the changes to the guest state while
11300 * L2 was running (and perhaps made some exits which were handled directly by L0
11301 * without going back to L1), and to reflect the exit reason.
11302 * Note that we do not have to copy here all VMCS fields, just those that
11303 * could have changed by the L2 guest or the exit - i.e., the guest-state and
11304 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
11305 * which already writes to vmcs12 directly.
11306 */
11307 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11308 u32 exit_reason, u32 exit_intr_info,
11309 unsigned long exit_qualification)
11310 {
11311 /* update guest state fields: */
11312 sync_vmcs12(vcpu, vmcs12);
11313
11314 /* update exit information fields: */
11315
11316 vmcs12->vm_exit_reason = exit_reason;
11317 vmcs12->exit_qualification = exit_qualification;
11318 vmcs12->vm_exit_intr_info = exit_intr_info;
11319
11320 vmcs12->idt_vectoring_info_field = 0;
11321 vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
11322 vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
11323
11324 if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
11325 vmcs12->launch_state = 1;
11326
11327 /* vm_entry_intr_info_field is cleared on exit. Emulate this
11328 * instead of reading the real value. */
11329 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
11330
11331 /*
11332 * Transfer the event that L0 or L1 may wanted to inject into
11333 * L2 to IDT_VECTORING_INFO_FIELD.
11334 */
11335 vmcs12_save_pending_event(vcpu, vmcs12);
11336 }
11337
11338 /*
11339 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
11340 * preserved above and would only end up incorrectly in L1.
11341 */
11342 vcpu->arch.nmi_injected = false;
11343 kvm_clear_exception_queue(vcpu);
11344 kvm_clear_interrupt_queue(vcpu);
11345 }
11346
11347 static void load_vmcs12_mmu_host_state(struct kvm_vcpu *vcpu,
11348 struct vmcs12 *vmcs12)
11349 {
11350 u32 entry_failure_code;
11351
11352 nested_ept_uninit_mmu_context(vcpu);
11353
11354 /*
11355 * Only PDPTE load can fail as the value of cr3 was checked on entry and
11356 * couldn't have changed.
11357 */
11358 if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
11359 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
11360
11361 if (!enable_ept)
11362 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
11363 }
11364
11365 /*
11366 * A part of what we need to when the nested L2 guest exits and we want to
11367 * run its L1 parent, is to reset L1's guest state to the host state specified
11368 * in vmcs12.
11369 * This function is to be called not only on normal nested exit, but also on
11370 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
11371 * Failures During or After Loading Guest State").
11372 * This function should be called when the active VMCS is L1's (vmcs01).
11373 */
11374 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
11375 struct vmcs12 *vmcs12)
11376 {
11377 struct kvm_segment seg;
11378
11379 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
11380 vcpu->arch.efer = vmcs12->host_ia32_efer;
11381 else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11382 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11383 else
11384 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11385 vmx_set_efer(vcpu, vcpu->arch.efer);
11386
11387 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
11388 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
11389 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
11390 /*
11391 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
11392 * actually changed, because vmx_set_cr0 refers to efer set above.
11393 *
11394 * CR0_GUEST_HOST_MASK is already set in the original vmcs01
11395 * (KVM doesn't change it);
11396 */
11397 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
11398 vmx_set_cr0(vcpu, vmcs12->host_cr0);
11399
11400 /* Same as above - no reason to call set_cr4_guest_host_mask(). */
11401 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
11402 vmx_set_cr4(vcpu, vmcs12->host_cr4);
11403
11404 load_vmcs12_mmu_host_state(vcpu, vmcs12);
11405
11406 if (enable_vpid) {
11407 /*
11408 * Trivially support vpid by letting L2s share their parent
11409 * L1's vpid. TODO: move to a more elaborate solution, giving
11410 * each L2 its own vpid and exposing the vpid feature to L1.
11411 */
11412 vmx_flush_tlb(vcpu);
11413 }
11414 /* Restore posted intr vector. */
11415 if (nested_cpu_has_posted_intr(vmcs12))
11416 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
11417
11418 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
11419 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
11420 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
11421 vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
11422 vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
11423 vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
11424 vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
11425
11426 /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
11427 if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
11428 vmcs_write64(GUEST_BNDCFGS, 0);
11429
11430 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
11431 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
11432 vcpu->arch.pat = vmcs12->host_ia32_pat;
11433 }
11434 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
11435 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
11436 vmcs12->host_ia32_perf_global_ctrl);
11437
11438 /* Set L1 segment info according to Intel SDM
11439 27.5.2 Loading Host Segment and Descriptor-Table Registers */
11440 seg = (struct kvm_segment) {
11441 .base = 0,
11442 .limit = 0xFFFFFFFF,
11443 .selector = vmcs12->host_cs_selector,
11444 .type = 11,
11445 .present = 1,
11446 .s = 1,
11447 .g = 1
11448 };
11449 if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11450 seg.l = 1;
11451 else
11452 seg.db = 1;
11453 vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
11454 seg = (struct kvm_segment) {
11455 .base = 0,
11456 .limit = 0xFFFFFFFF,
11457 .type = 3,
11458 .present = 1,
11459 .s = 1,
11460 .db = 1,
11461 .g = 1
11462 };
11463 seg.selector = vmcs12->host_ds_selector;
11464 vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
11465 seg.selector = vmcs12->host_es_selector;
11466 vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
11467 seg.selector = vmcs12->host_ss_selector;
11468 vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
11469 seg.selector = vmcs12->host_fs_selector;
11470 seg.base = vmcs12->host_fs_base;
11471 vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
11472 seg.selector = vmcs12->host_gs_selector;
11473 seg.base = vmcs12->host_gs_base;
11474 vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
11475 seg = (struct kvm_segment) {
11476 .base = vmcs12->host_tr_base,
11477 .limit = 0x67,
11478 .selector = vmcs12->host_tr_selector,
11479 .type = 11,
11480 .present = 1
11481 };
11482 vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
11483
11484 kvm_set_dr(vcpu, 7, 0x400);
11485 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
11486
11487 if (cpu_has_vmx_msr_bitmap())
11488 vmx_set_msr_bitmap(vcpu);
11489
11490 if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
11491 vmcs12->vm_exit_msr_load_count))
11492 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
11493 }
11494
11495 /*
11496 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
11497 * and modify vmcs12 to make it see what it would expect to see there if
11498 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
11499 */
11500 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
11501 u32 exit_intr_info,
11502 unsigned long exit_qualification)
11503 {
11504 struct vcpu_vmx *vmx = to_vmx(vcpu);
11505 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11506
11507 /* trying to cancel vmlaunch/vmresume is a bug */
11508 WARN_ON_ONCE(vmx->nested.nested_run_pending);
11509
11510 /*
11511 * The only expected VM-instruction error is "VM entry with
11512 * invalid control field(s)." Anything else indicates a
11513 * problem with L0.
11514 */
11515 WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
11516 VMXERR_ENTRY_INVALID_CONTROL_FIELD));
11517
11518 leave_guest_mode(vcpu);
11519
11520 if (likely(!vmx->fail)) {
11521 if (exit_reason == -1)
11522 sync_vmcs12(vcpu, vmcs12);
11523 else
11524 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
11525 exit_qualification);
11526
11527 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
11528 vmcs12->vm_exit_msr_store_count))
11529 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
11530 }
11531
11532 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11533 vm_entry_controls_reset_shadow(vmx);
11534 vm_exit_controls_reset_shadow(vmx);
11535 vmx_segment_cache_clear(vmx);
11536
11537 /* if no vmcs02 cache requested, remove the one we used */
11538 if (VMCS02_POOL_SIZE == 0)
11539 nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
11540
11541 /* Update any VMCS fields that might have changed while L2 ran */
11542 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11543 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11544 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
11545 if (vmx->hv_deadline_tsc == -1)
11546 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11547 PIN_BASED_VMX_PREEMPTION_TIMER);
11548 else
11549 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11550 PIN_BASED_VMX_PREEMPTION_TIMER);
11551 if (kvm_has_tsc_control)
11552 decache_tsc_multiplier(vmx);
11553
11554 if (vmx->nested.change_vmcs01_virtual_x2apic_mode) {
11555 vmx->nested.change_vmcs01_virtual_x2apic_mode = false;
11556 vmx_set_virtual_x2apic_mode(vcpu,
11557 vcpu->arch.apic_base & X2APIC_ENABLE);
11558 } else if (!nested_cpu_has_ept(vmcs12) &&
11559 nested_cpu_has2(vmcs12,
11560 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11561 vmx_flush_tlb_ept_only(vcpu);
11562 }
11563
11564 /* This is needed for same reason as it was needed in prepare_vmcs02 */
11565 vmx->host_rsp = 0;
11566
11567 /* Unpin physical memory we referred to in vmcs02 */
11568 if (vmx->nested.apic_access_page) {
11569 kvm_release_page_dirty(vmx->nested.apic_access_page);
11570 vmx->nested.apic_access_page = NULL;
11571 }
11572 if (vmx->nested.virtual_apic_page) {
11573 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11574 vmx->nested.virtual_apic_page = NULL;
11575 }
11576 if (vmx->nested.pi_desc_page) {
11577 kunmap(vmx->nested.pi_desc_page);
11578 kvm_release_page_dirty(vmx->nested.pi_desc_page);
11579 vmx->nested.pi_desc_page = NULL;
11580 vmx->nested.pi_desc = NULL;
11581 }
11582
11583 /*
11584 * We are now running in L2, mmu_notifier will force to reload the
11585 * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
11586 */
11587 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
11588
11589 if (enable_shadow_vmcs && exit_reason != -1)
11590 vmx->nested.sync_shadow_vmcs = true;
11591
11592 /* in case we halted in L2 */
11593 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11594
11595 if (likely(!vmx->fail)) {
11596 /*
11597 * TODO: SDM says that with acknowledge interrupt on
11598 * exit, bit 31 of the VM-exit interrupt information
11599 * (valid interrupt) is always set to 1 on
11600 * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
11601 * need kvm_cpu_has_interrupt(). See the commit
11602 * message for details.
11603 */
11604 if (nested_exit_intr_ack_set(vcpu) &&
11605 exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
11606 kvm_cpu_has_interrupt(vcpu)) {
11607 int irq = kvm_cpu_get_interrupt(vcpu);
11608 WARN_ON(irq < 0);
11609 vmcs12->vm_exit_intr_info = irq |
11610 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
11611 }
11612
11613 if (exit_reason != -1)
11614 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
11615 vmcs12->exit_qualification,
11616 vmcs12->idt_vectoring_info_field,
11617 vmcs12->vm_exit_intr_info,
11618 vmcs12->vm_exit_intr_error_code,
11619 KVM_ISA_VMX);
11620
11621 load_vmcs12_host_state(vcpu, vmcs12);
11622
11623 return;
11624 }
11625
11626 /*
11627 * After an early L2 VM-entry failure, we're now back
11628 * in L1 which thinks it just finished a VMLAUNCH or
11629 * VMRESUME instruction, so we need to set the failure
11630 * flag and the VM-instruction error field of the VMCS
11631 * accordingly.
11632 */
11633 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
11634
11635 load_vmcs12_mmu_host_state(vcpu, vmcs12);
11636
11637 /*
11638 * The emulated instruction was already skipped in
11639 * nested_vmx_run, but the updated RIP was never
11640 * written back to the vmcs01.
11641 */
11642 skip_emulated_instruction(vcpu);
11643 vmx->fail = 0;
11644 }
11645
11646 /*
11647 * Forcibly leave nested mode in order to be able to reset the VCPU later on.
11648 */
11649 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
11650 {
11651 if (is_guest_mode(vcpu)) {
11652 to_vmx(vcpu)->nested.nested_run_pending = 0;
11653 nested_vmx_vmexit(vcpu, -1, 0, 0);
11654 }
11655 free_nested(to_vmx(vcpu));
11656 }
11657
11658 /*
11659 * L1's failure to enter L2 is a subset of a normal exit, as explained in
11660 * 23.7 "VM-entry failures during or after loading guest state" (this also
11661 * lists the acceptable exit-reason and exit-qualification parameters).
11662 * It should only be called before L2 actually succeeded to run, and when
11663 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
11664 */
11665 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
11666 struct vmcs12 *vmcs12,
11667 u32 reason, unsigned long qualification)
11668 {
11669 load_vmcs12_host_state(vcpu, vmcs12);
11670 vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
11671 vmcs12->exit_qualification = qualification;
11672 nested_vmx_succeed(vcpu);
11673 if (enable_shadow_vmcs)
11674 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
11675 }
11676
11677 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
11678 struct x86_instruction_info *info,
11679 enum x86_intercept_stage stage)
11680 {
11681 return X86EMUL_CONTINUE;
11682 }
11683
11684 #ifdef CONFIG_X86_64
11685 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
11686 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
11687 u64 divisor, u64 *result)
11688 {
11689 u64 low = a << shift, high = a >> (64 - shift);
11690
11691 /* To avoid the overflow on divq */
11692 if (high >= divisor)
11693 return 1;
11694
11695 /* Low hold the result, high hold rem which is discarded */
11696 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
11697 "rm" (divisor), "0" (low), "1" (high));
11698 *result = low;
11699
11700 return 0;
11701 }
11702
11703 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
11704 {
11705 struct vcpu_vmx *vmx = to_vmx(vcpu);
11706 u64 tscl = rdtsc();
11707 u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
11708 u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
11709
11710 /* Convert to host delta tsc if tsc scaling is enabled */
11711 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
11712 u64_shl_div_u64(delta_tsc,
11713 kvm_tsc_scaling_ratio_frac_bits,
11714 vcpu->arch.tsc_scaling_ratio,
11715 &delta_tsc))
11716 return -ERANGE;
11717
11718 /*
11719 * If the delta tsc can't fit in the 32 bit after the multi shift,
11720 * we can't use the preemption timer.
11721 * It's possible that it fits on later vmentries, but checking
11722 * on every vmentry is costly so we just use an hrtimer.
11723 */
11724 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
11725 return -ERANGE;
11726
11727 vmx->hv_deadline_tsc = tscl + delta_tsc;
11728 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11729 PIN_BASED_VMX_PREEMPTION_TIMER);
11730
11731 return delta_tsc == 0;
11732 }
11733
11734 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
11735 {
11736 struct vcpu_vmx *vmx = to_vmx(vcpu);
11737 vmx->hv_deadline_tsc = -1;
11738 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11739 PIN_BASED_VMX_PREEMPTION_TIMER);
11740 }
11741 #endif
11742
11743 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
11744 {
11745 if (ple_gap)
11746 shrink_ple_window(vcpu);
11747 }
11748
11749 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
11750 struct kvm_memory_slot *slot)
11751 {
11752 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
11753 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
11754 }
11755
11756 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
11757 struct kvm_memory_slot *slot)
11758 {
11759 kvm_mmu_slot_set_dirty(kvm, slot);
11760 }
11761
11762 static void vmx_flush_log_dirty(struct kvm *kvm)
11763 {
11764 kvm_flush_pml_buffers(kvm);
11765 }
11766
11767 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
11768 {
11769 struct vmcs12 *vmcs12;
11770 struct vcpu_vmx *vmx = to_vmx(vcpu);
11771 gpa_t gpa;
11772 struct page *page = NULL;
11773 u64 *pml_address;
11774
11775 if (is_guest_mode(vcpu)) {
11776 WARN_ON_ONCE(vmx->nested.pml_full);
11777
11778 /*
11779 * Check if PML is enabled for the nested guest.
11780 * Whether eptp bit 6 is set is already checked
11781 * as part of A/D emulation.
11782 */
11783 vmcs12 = get_vmcs12(vcpu);
11784 if (!nested_cpu_has_pml(vmcs12))
11785 return 0;
11786
11787 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
11788 vmx->nested.pml_full = true;
11789 return 1;
11790 }
11791
11792 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
11793
11794 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
11795 if (is_error_page(page))
11796 return 0;
11797
11798 pml_address = kmap(page);
11799 pml_address[vmcs12->guest_pml_index--] = gpa;
11800 kunmap(page);
11801 kvm_release_page_clean(page);
11802 }
11803
11804 return 0;
11805 }
11806
11807 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
11808 struct kvm_memory_slot *memslot,
11809 gfn_t offset, unsigned long mask)
11810 {
11811 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
11812 }
11813
11814 static void __pi_post_block(struct kvm_vcpu *vcpu)
11815 {
11816 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11817 struct pi_desc old, new;
11818 unsigned int dest;
11819
11820 do {
11821 old.control = new.control = pi_desc->control;
11822 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
11823 "Wakeup handler not enabled while the VCPU is blocked\n");
11824
11825 dest = cpu_physical_id(vcpu->cpu);
11826
11827 if (x2apic_enabled())
11828 new.ndst = dest;
11829 else
11830 new.ndst = (dest << 8) & 0xFF00;
11831
11832 /* set 'NV' to 'notification vector' */
11833 new.nv = POSTED_INTR_VECTOR;
11834 } while (cmpxchg64(&pi_desc->control, old.control,
11835 new.control) != old.control);
11836
11837 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
11838 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11839 list_del(&vcpu->blocked_vcpu_list);
11840 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11841 vcpu->pre_pcpu = -1;
11842 }
11843 }
11844
11845 /*
11846 * This routine does the following things for vCPU which is going
11847 * to be blocked if VT-d PI is enabled.
11848 * - Store the vCPU to the wakeup list, so when interrupts happen
11849 * we can find the right vCPU to wake up.
11850 * - Change the Posted-interrupt descriptor as below:
11851 * 'NDST' <-- vcpu->pre_pcpu
11852 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
11853 * - If 'ON' is set during this process, which means at least one
11854 * interrupt is posted for this vCPU, we cannot block it, in
11855 * this case, return 1, otherwise, return 0.
11856 *
11857 */
11858 static int pi_pre_block(struct kvm_vcpu *vcpu)
11859 {
11860 unsigned int dest;
11861 struct pi_desc old, new;
11862 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11863
11864 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
11865 !irq_remapping_cap(IRQ_POSTING_CAP) ||
11866 !kvm_vcpu_apicv_active(vcpu))
11867 return 0;
11868
11869 WARN_ON(irqs_disabled());
11870 local_irq_disable();
11871 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
11872 vcpu->pre_pcpu = vcpu->cpu;
11873 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11874 list_add_tail(&vcpu->blocked_vcpu_list,
11875 &per_cpu(blocked_vcpu_on_cpu,
11876 vcpu->pre_pcpu));
11877 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11878 }
11879
11880 do {
11881 old.control = new.control = pi_desc->control;
11882
11883 WARN((pi_desc->sn == 1),
11884 "Warning: SN field of posted-interrupts "
11885 "is set before blocking\n");
11886
11887 /*
11888 * Since vCPU can be preempted during this process,
11889 * vcpu->cpu could be different with pre_pcpu, we
11890 * need to set pre_pcpu as the destination of wakeup
11891 * notification event, then we can find the right vCPU
11892 * to wakeup in wakeup handler if interrupts happen
11893 * when the vCPU is in blocked state.
11894 */
11895 dest = cpu_physical_id(vcpu->pre_pcpu);
11896
11897 if (x2apic_enabled())
11898 new.ndst = dest;
11899 else
11900 new.ndst = (dest << 8) & 0xFF00;
11901
11902 /* set 'NV' to 'wakeup vector' */
11903 new.nv = POSTED_INTR_WAKEUP_VECTOR;
11904 } while (cmpxchg64(&pi_desc->control, old.control,
11905 new.control) != old.control);
11906
11907 /* We should not block the vCPU if an interrupt is posted for it. */
11908 if (pi_test_on(pi_desc) == 1)
11909 __pi_post_block(vcpu);
11910
11911 local_irq_enable();
11912 return (vcpu->pre_pcpu == -1);
11913 }
11914
11915 static int vmx_pre_block(struct kvm_vcpu *vcpu)
11916 {
11917 if (pi_pre_block(vcpu))
11918 return 1;
11919
11920 if (kvm_lapic_hv_timer_in_use(vcpu))
11921 kvm_lapic_switch_to_sw_timer(vcpu);
11922
11923 return 0;
11924 }
11925
11926 static void pi_post_block(struct kvm_vcpu *vcpu)
11927 {
11928 if (vcpu->pre_pcpu == -1)
11929 return;
11930
11931 WARN_ON(irqs_disabled());
11932 local_irq_disable();
11933 __pi_post_block(vcpu);
11934 local_irq_enable();
11935 }
11936
11937 static void vmx_post_block(struct kvm_vcpu *vcpu)
11938 {
11939 if (kvm_x86_ops->set_hv_timer)
11940 kvm_lapic_switch_to_hv_timer(vcpu);
11941
11942 pi_post_block(vcpu);
11943 }
11944
11945 /*
11946 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
11947 *
11948 * @kvm: kvm
11949 * @host_irq: host irq of the interrupt
11950 * @guest_irq: gsi of the interrupt
11951 * @set: set or unset PI
11952 * returns 0 on success, < 0 on failure
11953 */
11954 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
11955 uint32_t guest_irq, bool set)
11956 {
11957 struct kvm_kernel_irq_routing_entry *e;
11958 struct kvm_irq_routing_table *irq_rt;
11959 struct kvm_lapic_irq irq;
11960 struct kvm_vcpu *vcpu;
11961 struct vcpu_data vcpu_info;
11962 int idx, ret = 0;
11963
11964 if (!kvm_arch_has_assigned_device(kvm) ||
11965 !irq_remapping_cap(IRQ_POSTING_CAP) ||
11966 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
11967 return 0;
11968
11969 idx = srcu_read_lock(&kvm->irq_srcu);
11970 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
11971 if (guest_irq >= irq_rt->nr_rt_entries ||
11972 hlist_empty(&irq_rt->map[guest_irq])) {
11973 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
11974 guest_irq, irq_rt->nr_rt_entries);
11975 goto out;
11976 }
11977
11978 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
11979 if (e->type != KVM_IRQ_ROUTING_MSI)
11980 continue;
11981 /*
11982 * VT-d PI cannot support posting multicast/broadcast
11983 * interrupts to a vCPU, we still use interrupt remapping
11984 * for these kind of interrupts.
11985 *
11986 * For lowest-priority interrupts, we only support
11987 * those with single CPU as the destination, e.g. user
11988 * configures the interrupts via /proc/irq or uses
11989 * irqbalance to make the interrupts single-CPU.
11990 *
11991 * We will support full lowest-priority interrupt later.
11992 */
11993
11994 kvm_set_msi_irq(kvm, e, &irq);
11995 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
11996 /*
11997 * Make sure the IRTE is in remapped mode if
11998 * we don't handle it in posted mode.
11999 */
12000 ret = irq_set_vcpu_affinity(host_irq, NULL);
12001 if (ret < 0) {
12002 printk(KERN_INFO
12003 "failed to back to remapped mode, irq: %u\n",
12004 host_irq);
12005 goto out;
12006 }
12007
12008 continue;
12009 }
12010
12011 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
12012 vcpu_info.vector = irq.vector;
12013
12014 trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
12015 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
12016
12017 if (set)
12018 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
12019 else
12020 ret = irq_set_vcpu_affinity(host_irq, NULL);
12021
12022 if (ret < 0) {
12023 printk(KERN_INFO "%s: failed to update PI IRTE\n",
12024 __func__);
12025 goto out;
12026 }
12027 }
12028
12029 ret = 0;
12030 out:
12031 srcu_read_unlock(&kvm->irq_srcu, idx);
12032 return ret;
12033 }
12034
12035 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
12036 {
12037 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
12038 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
12039 FEATURE_CONTROL_LMCE;
12040 else
12041 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
12042 ~FEATURE_CONTROL_LMCE;
12043 }
12044
12045 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
12046 {
12047 /* we need a nested vmexit to enter SMM, postpone if run is pending */
12048 if (to_vmx(vcpu)->nested.nested_run_pending)
12049 return 0;
12050 return 1;
12051 }
12052
12053 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
12054 {
12055 struct vcpu_vmx *vmx = to_vmx(vcpu);
12056
12057 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
12058 if (vmx->nested.smm.guest_mode)
12059 nested_vmx_vmexit(vcpu, -1, 0, 0);
12060
12061 vmx->nested.smm.vmxon = vmx->nested.vmxon;
12062 vmx->nested.vmxon = false;
12063 return 0;
12064 }
12065
12066 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
12067 {
12068 struct vcpu_vmx *vmx = to_vmx(vcpu);
12069 int ret;
12070
12071 if (vmx->nested.smm.vmxon) {
12072 vmx->nested.vmxon = true;
12073 vmx->nested.smm.vmxon = false;
12074 }
12075
12076 if (vmx->nested.smm.guest_mode) {
12077 vcpu->arch.hflags &= ~HF_SMM_MASK;
12078 ret = enter_vmx_non_root_mode(vcpu, false);
12079 vcpu->arch.hflags |= HF_SMM_MASK;
12080 if (ret)
12081 return ret;
12082
12083 vmx->nested.smm.guest_mode = false;
12084 }
12085 return 0;
12086 }
12087
12088 static int enable_smi_window(struct kvm_vcpu *vcpu)
12089 {
12090 return 0;
12091 }
12092
12093 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
12094 .cpu_has_kvm_support = cpu_has_kvm_support,
12095 .disabled_by_bios = vmx_disabled_by_bios,
12096 .hardware_setup = hardware_setup,
12097 .hardware_unsetup = hardware_unsetup,
12098 .check_processor_compatibility = vmx_check_processor_compat,
12099 .hardware_enable = hardware_enable,
12100 .hardware_disable = hardware_disable,
12101 .cpu_has_accelerated_tpr = report_flexpriority,
12102 .cpu_has_high_real_mode_segbase = vmx_has_high_real_mode_segbase,
12103
12104 .vcpu_create = vmx_create_vcpu,
12105 .vcpu_free = vmx_free_vcpu,
12106 .vcpu_reset = vmx_vcpu_reset,
12107
12108 .prepare_guest_switch = vmx_save_host_state,
12109 .vcpu_load = vmx_vcpu_load,
12110 .vcpu_put = vmx_vcpu_put,
12111
12112 .update_bp_intercept = update_exception_bitmap,
12113 .get_msr = vmx_get_msr,
12114 .set_msr = vmx_set_msr,
12115 .get_segment_base = vmx_get_segment_base,
12116 .get_segment = vmx_get_segment,
12117 .set_segment = vmx_set_segment,
12118 .get_cpl = vmx_get_cpl,
12119 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
12120 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
12121 .decache_cr3 = vmx_decache_cr3,
12122 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
12123 .set_cr0 = vmx_set_cr0,
12124 .set_cr3 = vmx_set_cr3,
12125 .set_cr4 = vmx_set_cr4,
12126 .set_efer = vmx_set_efer,
12127 .get_idt = vmx_get_idt,
12128 .set_idt = vmx_set_idt,
12129 .get_gdt = vmx_get_gdt,
12130 .set_gdt = vmx_set_gdt,
12131 .get_dr6 = vmx_get_dr6,
12132 .set_dr6 = vmx_set_dr6,
12133 .set_dr7 = vmx_set_dr7,
12134 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
12135 .cache_reg = vmx_cache_reg,
12136 .get_rflags = vmx_get_rflags,
12137 .set_rflags = vmx_set_rflags,
12138
12139 .tlb_flush = vmx_flush_tlb,
12140
12141 .run = vmx_vcpu_run,
12142 .handle_exit = vmx_handle_exit,
12143 .skip_emulated_instruction = skip_emulated_instruction,
12144 .set_interrupt_shadow = vmx_set_interrupt_shadow,
12145 .get_interrupt_shadow = vmx_get_interrupt_shadow,
12146 .patch_hypercall = vmx_patch_hypercall,
12147 .set_irq = vmx_inject_irq,
12148 .set_nmi = vmx_inject_nmi,
12149 .queue_exception = vmx_queue_exception,
12150 .cancel_injection = vmx_cancel_injection,
12151 .interrupt_allowed = vmx_interrupt_allowed,
12152 .nmi_allowed = vmx_nmi_allowed,
12153 .get_nmi_mask = vmx_get_nmi_mask,
12154 .set_nmi_mask = vmx_set_nmi_mask,
12155 .enable_nmi_window = enable_nmi_window,
12156 .enable_irq_window = enable_irq_window,
12157 .update_cr8_intercept = update_cr8_intercept,
12158 .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
12159 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
12160 .get_enable_apicv = vmx_get_enable_apicv,
12161 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
12162 .load_eoi_exitmap = vmx_load_eoi_exitmap,
12163 .apicv_post_state_restore = vmx_apicv_post_state_restore,
12164 .hwapic_irr_update = vmx_hwapic_irr_update,
12165 .hwapic_isr_update = vmx_hwapic_isr_update,
12166 .sync_pir_to_irr = vmx_sync_pir_to_irr,
12167 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
12168
12169 .set_tss_addr = vmx_set_tss_addr,
12170 .get_tdp_level = get_ept_level,
12171 .get_mt_mask = vmx_get_mt_mask,
12172
12173 .get_exit_info = vmx_get_exit_info,
12174
12175 .get_lpage_level = vmx_get_lpage_level,
12176
12177 .cpuid_update = vmx_cpuid_update,
12178
12179 .rdtscp_supported = vmx_rdtscp_supported,
12180 .invpcid_supported = vmx_invpcid_supported,
12181
12182 .set_supported_cpuid = vmx_set_supported_cpuid,
12183
12184 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
12185
12186 .write_tsc_offset = vmx_write_tsc_offset,
12187
12188 .set_tdp_cr3 = vmx_set_cr3,
12189
12190 .check_intercept = vmx_check_intercept,
12191 .handle_external_intr = vmx_handle_external_intr,
12192 .mpx_supported = vmx_mpx_supported,
12193 .xsaves_supported = vmx_xsaves_supported,
12194
12195 .check_nested_events = vmx_check_nested_events,
12196
12197 .sched_in = vmx_sched_in,
12198
12199 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
12200 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
12201 .flush_log_dirty = vmx_flush_log_dirty,
12202 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
12203 .write_log_dirty = vmx_write_pml_buffer,
12204
12205 .pre_block = vmx_pre_block,
12206 .post_block = vmx_post_block,
12207
12208 .pmu_ops = &intel_pmu_ops,
12209
12210 .update_pi_irte = vmx_update_pi_irte,
12211
12212 #ifdef CONFIG_X86_64
12213 .set_hv_timer = vmx_set_hv_timer,
12214 .cancel_hv_timer = vmx_cancel_hv_timer,
12215 #endif
12216
12217 .setup_mce = vmx_setup_mce,
12218
12219 .smi_allowed = vmx_smi_allowed,
12220 .pre_enter_smm = vmx_pre_enter_smm,
12221 .pre_leave_smm = vmx_pre_leave_smm,
12222 .enable_smi_window = enable_smi_window,
12223 };
12224
12225 static int __init vmx_init(void)
12226 {
12227 int r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
12228 __alignof__(struct vcpu_vmx), THIS_MODULE);
12229 if (r)
12230 return r;
12231
12232 #ifdef CONFIG_KEXEC_CORE
12233 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
12234 crash_vmclear_local_loaded_vmcss);
12235 #endif
12236
12237 return 0;
12238 }
12239
12240 static void __exit vmx_exit(void)
12241 {
12242 #ifdef CONFIG_KEXEC_CORE
12243 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
12244 synchronize_rcu();
12245 #endif
12246
12247 kvm_exit();
12248 }
12249
12250 module_init(vmx_init)
12251 module_exit(vmx_exit)