]> git.ipfire.org Git - thirdparty/linux.git/blob - arch/x86/kvm/vmx/vmx.c
KVM: VMX: Move capabilities structs and helpers to dedicated file
[thirdparty/linux.git] / arch / x86 / kvm / vmx / 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 <linux/frame.h>
20 #include <linux/highmem.h>
21 #include <linux/hrtimer.h>
22 #include <linux/kernel.h>
23 #include <linux/kvm_host.h>
24 #include <linux/module.h>
25 #include <linux/moduleparam.h>
26 #include <linux/mod_devicetable.h>
27 #include <linux/mm.h>
28 #include <linux/nospec.h>
29 #include <linux/sched.h>
30 #include <linux/slab.h>
31 #include <linux/tboot.h>
32 #include <linux/trace_events.h>
33
34 #include <asm/apic.h>
35 #include <asm/asm.h>
36 #include <asm/cpu.h>
37 #include <asm/debugreg.h>
38 #include <asm/desc.h>
39 #include <asm/fpu/internal.h>
40 #include <asm/io.h>
41 #include <asm/irq_remapping.h>
42 #include <asm/kexec.h>
43 #include <asm/perf_event.h>
44 #include <asm/mce.h>
45 #include <asm/mmu_context.h>
46 #include <asm/mshyperv.h>
47 #include <asm/spec-ctrl.h>
48 #include <asm/virtext.h>
49 #include <asm/vmx.h>
50
51 #include "capabilities.h"
52 #include "cpuid.h"
53 #include "evmcs.h"
54 #include "hyperv.h"
55 #include "irq.h"
56 #include "kvm_cache_regs.h"
57 #include "lapic.h"
58 #include "mmu.h"
59 #include "pmu.h"
60 #include "trace.h"
61 #include "x86.h"
62
63 #define __ex(x) __kvm_handle_fault_on_reboot(x)
64 #define __ex_clear(x, reg) \
65 ____kvm_handle_fault_on_reboot(x, "xor " reg ", " reg)
66
67 MODULE_AUTHOR("Qumranet");
68 MODULE_LICENSE("GPL");
69
70 static const struct x86_cpu_id vmx_cpu_id[] = {
71 X86_FEATURE_MATCH(X86_FEATURE_VMX),
72 {}
73 };
74 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
75
76 static bool __read_mostly enable_vpid = 1;
77 module_param_named(vpid, enable_vpid, bool, 0444);
78
79 static bool __read_mostly enable_vnmi = 1;
80 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
81
82 static bool __read_mostly flexpriority_enabled = 1;
83 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
84
85 static bool __read_mostly enable_ept = 1;
86 module_param_named(ept, enable_ept, bool, S_IRUGO);
87
88 static bool __read_mostly enable_unrestricted_guest = 1;
89 module_param_named(unrestricted_guest,
90 enable_unrestricted_guest, bool, S_IRUGO);
91
92 static bool __read_mostly enable_ept_ad_bits = 1;
93 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
94
95 static bool __read_mostly emulate_invalid_guest_state = true;
96 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
97
98 static bool __read_mostly fasteoi = 1;
99 module_param(fasteoi, bool, S_IRUGO);
100
101 static bool __read_mostly enable_apicv = 1;
102 module_param(enable_apicv, bool, S_IRUGO);
103
104 static bool __read_mostly enable_shadow_vmcs = 1;
105 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
106 /*
107 * If nested=1, nested virtualization is supported, i.e., guests may use
108 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
109 * use VMX instructions.
110 */
111 static bool __read_mostly nested = 1;
112 module_param(nested, bool, S_IRUGO);
113
114 static bool __read_mostly nested_early_check = 0;
115 module_param(nested_early_check, bool, S_IRUGO);
116
117 static u64 __read_mostly host_xss;
118
119 static bool __read_mostly enable_pml = 1;
120 module_param_named(pml, enable_pml, bool, S_IRUGO);
121
122 #define MSR_TYPE_R 1
123 #define MSR_TYPE_W 2
124 #define MSR_TYPE_RW 3
125
126 #define MSR_BITMAP_MODE_X2APIC 1
127 #define MSR_BITMAP_MODE_X2APIC_APICV 2
128
129 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
130
131 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
132 static int __read_mostly cpu_preemption_timer_multi;
133 static bool __read_mostly enable_preemption_timer = 1;
134 #ifdef CONFIG_X86_64
135 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
136 #endif
137
138 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
139 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
140 #define KVM_VM_CR0_ALWAYS_ON \
141 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
142 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
143 #define KVM_CR4_GUEST_OWNED_BITS \
144 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
145 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
146
147 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
148 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
149 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
150
151 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
152
153 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
154
155 /*
156 * Hyper-V requires all of these, so mark them as supported even though
157 * they are just treated the same as all-context.
158 */
159 #define VMX_VPID_EXTENT_SUPPORTED_MASK \
160 (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
161 VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
162 VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
163 VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
164
165 /*
166 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
167 * ple_gap: upper bound on the amount of time between two successive
168 * executions of PAUSE in a loop. Also indicate if ple enabled.
169 * According to test, this time is usually smaller than 128 cycles.
170 * ple_window: upper bound on the amount of time a guest is allowed to execute
171 * in a PAUSE loop. Tests indicate that most spinlocks are held for
172 * less than 2^12 cycles
173 * Time is measured based on a counter that runs at the same rate as the TSC,
174 * refer SDM volume 3b section 21.6.13 & 22.1.3.
175 */
176 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
177 module_param(ple_gap, uint, 0444);
178
179 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
180 module_param(ple_window, uint, 0444);
181
182 /* Default doubles per-vcpu window every exit. */
183 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
184 module_param(ple_window_grow, uint, 0444);
185
186 /* Default resets per-vcpu window every exit to ple_window. */
187 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
188 module_param(ple_window_shrink, uint, 0444);
189
190 /* Default is to compute the maximum so we can never overflow. */
191 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
192 module_param(ple_window_max, uint, 0444);
193
194 extern const ulong vmx_return;
195 extern const ulong vmx_early_consistency_check_return;
196
197 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
198 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
199 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
200
201 /* Storage for pre module init parameter parsing */
202 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
203
204 static const struct {
205 const char *option;
206 bool for_parse;
207 } vmentry_l1d_param[] = {
208 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
209 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
210 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
211 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
212 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
213 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
214 };
215
216 #define L1D_CACHE_ORDER 4
217 static void *vmx_l1d_flush_pages;
218
219 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
220 {
221 struct page *page;
222 unsigned int i;
223
224 if (!enable_ept) {
225 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
226 return 0;
227 }
228
229 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
230 u64 msr;
231
232 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
233 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
234 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
235 return 0;
236 }
237 }
238
239 /* If set to auto use the default l1tf mitigation method */
240 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
241 switch (l1tf_mitigation) {
242 case L1TF_MITIGATION_OFF:
243 l1tf = VMENTER_L1D_FLUSH_NEVER;
244 break;
245 case L1TF_MITIGATION_FLUSH_NOWARN:
246 case L1TF_MITIGATION_FLUSH:
247 case L1TF_MITIGATION_FLUSH_NOSMT:
248 l1tf = VMENTER_L1D_FLUSH_COND;
249 break;
250 case L1TF_MITIGATION_FULL:
251 case L1TF_MITIGATION_FULL_FORCE:
252 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
253 break;
254 }
255 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
256 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
257 }
258
259 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
260 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
261 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
262 if (!page)
263 return -ENOMEM;
264 vmx_l1d_flush_pages = page_address(page);
265
266 /*
267 * Initialize each page with a different pattern in
268 * order to protect against KSM in the nested
269 * virtualization case.
270 */
271 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
272 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
273 PAGE_SIZE);
274 }
275 }
276
277 l1tf_vmx_mitigation = l1tf;
278
279 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
280 static_branch_enable(&vmx_l1d_should_flush);
281 else
282 static_branch_disable(&vmx_l1d_should_flush);
283
284 if (l1tf == VMENTER_L1D_FLUSH_COND)
285 static_branch_enable(&vmx_l1d_flush_cond);
286 else
287 static_branch_disable(&vmx_l1d_flush_cond);
288 return 0;
289 }
290
291 static int vmentry_l1d_flush_parse(const char *s)
292 {
293 unsigned int i;
294
295 if (s) {
296 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
297 if (vmentry_l1d_param[i].for_parse &&
298 sysfs_streq(s, vmentry_l1d_param[i].option))
299 return i;
300 }
301 }
302 return -EINVAL;
303 }
304
305 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
306 {
307 int l1tf, ret;
308
309 l1tf = vmentry_l1d_flush_parse(s);
310 if (l1tf < 0)
311 return l1tf;
312
313 if (!boot_cpu_has(X86_BUG_L1TF))
314 return 0;
315
316 /*
317 * Has vmx_init() run already? If not then this is the pre init
318 * parameter parsing. In that case just store the value and let
319 * vmx_init() do the proper setup after enable_ept has been
320 * established.
321 */
322 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
323 vmentry_l1d_flush_param = l1tf;
324 return 0;
325 }
326
327 mutex_lock(&vmx_l1d_flush_mutex);
328 ret = vmx_setup_l1d_flush(l1tf);
329 mutex_unlock(&vmx_l1d_flush_mutex);
330 return ret;
331 }
332
333 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
334 {
335 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
336 return sprintf(s, "???\n");
337
338 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
339 }
340
341 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
342 .set = vmentry_l1d_flush_set,
343 .get = vmentry_l1d_flush_get,
344 };
345 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
346
347 enum ept_pointers_status {
348 EPT_POINTERS_CHECK = 0,
349 EPT_POINTERS_MATCH = 1,
350 EPT_POINTERS_MISMATCH = 2
351 };
352
353 struct kvm_vmx {
354 struct kvm kvm;
355
356 unsigned int tss_addr;
357 bool ept_identity_pagetable_done;
358 gpa_t ept_identity_map_addr;
359
360 enum ept_pointers_status ept_pointers_match;
361 spinlock_t ept_pointer_lock;
362 };
363
364 #define NR_AUTOLOAD_MSRS 8
365
366 struct vmcs_hdr {
367 u32 revision_id:31;
368 u32 shadow_vmcs:1;
369 };
370
371 struct vmcs {
372 struct vmcs_hdr hdr;
373 u32 abort;
374 char data[0];
375 };
376
377 /*
378 * vmcs_host_state tracks registers that are loaded from the VMCS on VMEXIT
379 * and whose values change infrequently, but are not constant. I.e. this is
380 * used as a write-through cache of the corresponding VMCS fields.
381 */
382 struct vmcs_host_state {
383 unsigned long cr3; /* May not match real cr3 */
384 unsigned long cr4; /* May not match real cr4 */
385 unsigned long gs_base;
386 unsigned long fs_base;
387
388 u16 fs_sel, gs_sel, ldt_sel;
389 #ifdef CONFIG_X86_64
390 u16 ds_sel, es_sel;
391 #endif
392 };
393
394 /*
395 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
396 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
397 * loaded on this CPU (so we can clear them if the CPU goes down).
398 */
399 struct loaded_vmcs {
400 struct vmcs *vmcs;
401 struct vmcs *shadow_vmcs;
402 int cpu;
403 bool launched;
404 bool nmi_known_unmasked;
405 bool hv_timer_armed;
406 /* Support for vnmi-less CPUs */
407 int soft_vnmi_blocked;
408 ktime_t entry_time;
409 s64 vnmi_blocked_time;
410 unsigned long *msr_bitmap;
411 struct list_head loaded_vmcss_on_cpu_link;
412 struct vmcs_host_state host_state;
413 };
414
415 struct shared_msr_entry {
416 unsigned index;
417 u64 data;
418 u64 mask;
419 };
420
421 /*
422 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
423 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
424 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
425 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
426 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
427 * More than one of these structures may exist, if L1 runs multiple L2 guests.
428 * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
429 * underlying hardware which will be used to run L2.
430 * This structure is packed to ensure that its layout is identical across
431 * machines (necessary for live migration).
432 *
433 * IMPORTANT: Changing the layout of existing fields in this structure
434 * will break save/restore compatibility with older kvm releases. When
435 * adding new fields, either use space in the reserved padding* arrays
436 * or add the new fields to the end of the structure.
437 */
438 typedef u64 natural_width;
439 struct __packed vmcs12 {
440 /* According to the Intel spec, a VMCS region must start with the
441 * following two fields. Then follow implementation-specific data.
442 */
443 struct vmcs_hdr hdr;
444 u32 abort;
445
446 u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
447 u32 padding[7]; /* room for future expansion */
448
449 u64 io_bitmap_a;
450 u64 io_bitmap_b;
451 u64 msr_bitmap;
452 u64 vm_exit_msr_store_addr;
453 u64 vm_exit_msr_load_addr;
454 u64 vm_entry_msr_load_addr;
455 u64 tsc_offset;
456 u64 virtual_apic_page_addr;
457 u64 apic_access_addr;
458 u64 posted_intr_desc_addr;
459 u64 ept_pointer;
460 u64 eoi_exit_bitmap0;
461 u64 eoi_exit_bitmap1;
462 u64 eoi_exit_bitmap2;
463 u64 eoi_exit_bitmap3;
464 u64 xss_exit_bitmap;
465 u64 guest_physical_address;
466 u64 vmcs_link_pointer;
467 u64 guest_ia32_debugctl;
468 u64 guest_ia32_pat;
469 u64 guest_ia32_efer;
470 u64 guest_ia32_perf_global_ctrl;
471 u64 guest_pdptr0;
472 u64 guest_pdptr1;
473 u64 guest_pdptr2;
474 u64 guest_pdptr3;
475 u64 guest_bndcfgs;
476 u64 host_ia32_pat;
477 u64 host_ia32_efer;
478 u64 host_ia32_perf_global_ctrl;
479 u64 vmread_bitmap;
480 u64 vmwrite_bitmap;
481 u64 vm_function_control;
482 u64 eptp_list_address;
483 u64 pml_address;
484 u64 padding64[3]; /* room for future expansion */
485 /*
486 * To allow migration of L1 (complete with its L2 guests) between
487 * machines of different natural widths (32 or 64 bit), we cannot have
488 * unsigned long fields with no explict size. We use u64 (aliased
489 * natural_width) instead. Luckily, x86 is little-endian.
490 */
491 natural_width cr0_guest_host_mask;
492 natural_width cr4_guest_host_mask;
493 natural_width cr0_read_shadow;
494 natural_width cr4_read_shadow;
495 natural_width cr3_target_value0;
496 natural_width cr3_target_value1;
497 natural_width cr3_target_value2;
498 natural_width cr3_target_value3;
499 natural_width exit_qualification;
500 natural_width guest_linear_address;
501 natural_width guest_cr0;
502 natural_width guest_cr3;
503 natural_width guest_cr4;
504 natural_width guest_es_base;
505 natural_width guest_cs_base;
506 natural_width guest_ss_base;
507 natural_width guest_ds_base;
508 natural_width guest_fs_base;
509 natural_width guest_gs_base;
510 natural_width guest_ldtr_base;
511 natural_width guest_tr_base;
512 natural_width guest_gdtr_base;
513 natural_width guest_idtr_base;
514 natural_width guest_dr7;
515 natural_width guest_rsp;
516 natural_width guest_rip;
517 natural_width guest_rflags;
518 natural_width guest_pending_dbg_exceptions;
519 natural_width guest_sysenter_esp;
520 natural_width guest_sysenter_eip;
521 natural_width host_cr0;
522 natural_width host_cr3;
523 natural_width host_cr4;
524 natural_width host_fs_base;
525 natural_width host_gs_base;
526 natural_width host_tr_base;
527 natural_width host_gdtr_base;
528 natural_width host_idtr_base;
529 natural_width host_ia32_sysenter_esp;
530 natural_width host_ia32_sysenter_eip;
531 natural_width host_rsp;
532 natural_width host_rip;
533 natural_width paddingl[8]; /* room for future expansion */
534 u32 pin_based_vm_exec_control;
535 u32 cpu_based_vm_exec_control;
536 u32 exception_bitmap;
537 u32 page_fault_error_code_mask;
538 u32 page_fault_error_code_match;
539 u32 cr3_target_count;
540 u32 vm_exit_controls;
541 u32 vm_exit_msr_store_count;
542 u32 vm_exit_msr_load_count;
543 u32 vm_entry_controls;
544 u32 vm_entry_msr_load_count;
545 u32 vm_entry_intr_info_field;
546 u32 vm_entry_exception_error_code;
547 u32 vm_entry_instruction_len;
548 u32 tpr_threshold;
549 u32 secondary_vm_exec_control;
550 u32 vm_instruction_error;
551 u32 vm_exit_reason;
552 u32 vm_exit_intr_info;
553 u32 vm_exit_intr_error_code;
554 u32 idt_vectoring_info_field;
555 u32 idt_vectoring_error_code;
556 u32 vm_exit_instruction_len;
557 u32 vmx_instruction_info;
558 u32 guest_es_limit;
559 u32 guest_cs_limit;
560 u32 guest_ss_limit;
561 u32 guest_ds_limit;
562 u32 guest_fs_limit;
563 u32 guest_gs_limit;
564 u32 guest_ldtr_limit;
565 u32 guest_tr_limit;
566 u32 guest_gdtr_limit;
567 u32 guest_idtr_limit;
568 u32 guest_es_ar_bytes;
569 u32 guest_cs_ar_bytes;
570 u32 guest_ss_ar_bytes;
571 u32 guest_ds_ar_bytes;
572 u32 guest_fs_ar_bytes;
573 u32 guest_gs_ar_bytes;
574 u32 guest_ldtr_ar_bytes;
575 u32 guest_tr_ar_bytes;
576 u32 guest_interruptibility_info;
577 u32 guest_activity_state;
578 u32 guest_sysenter_cs;
579 u32 host_ia32_sysenter_cs;
580 u32 vmx_preemption_timer_value;
581 u32 padding32[7]; /* room for future expansion */
582 u16 virtual_processor_id;
583 u16 posted_intr_nv;
584 u16 guest_es_selector;
585 u16 guest_cs_selector;
586 u16 guest_ss_selector;
587 u16 guest_ds_selector;
588 u16 guest_fs_selector;
589 u16 guest_gs_selector;
590 u16 guest_ldtr_selector;
591 u16 guest_tr_selector;
592 u16 guest_intr_status;
593 u16 host_es_selector;
594 u16 host_cs_selector;
595 u16 host_ss_selector;
596 u16 host_ds_selector;
597 u16 host_fs_selector;
598 u16 host_gs_selector;
599 u16 host_tr_selector;
600 u16 guest_pml_index;
601 };
602
603 /*
604 * For save/restore compatibility, the vmcs12 field offsets must not change.
605 */
606 #define CHECK_OFFSET(field, loc) \
607 BUILD_BUG_ON_MSG(offsetof(struct vmcs12, field) != (loc), \
608 "Offset of " #field " in struct vmcs12 has changed.")
609
610 static inline void vmx_check_vmcs12_offsets(void) {
611 CHECK_OFFSET(hdr, 0);
612 CHECK_OFFSET(abort, 4);
613 CHECK_OFFSET(launch_state, 8);
614 CHECK_OFFSET(io_bitmap_a, 40);
615 CHECK_OFFSET(io_bitmap_b, 48);
616 CHECK_OFFSET(msr_bitmap, 56);
617 CHECK_OFFSET(vm_exit_msr_store_addr, 64);
618 CHECK_OFFSET(vm_exit_msr_load_addr, 72);
619 CHECK_OFFSET(vm_entry_msr_load_addr, 80);
620 CHECK_OFFSET(tsc_offset, 88);
621 CHECK_OFFSET(virtual_apic_page_addr, 96);
622 CHECK_OFFSET(apic_access_addr, 104);
623 CHECK_OFFSET(posted_intr_desc_addr, 112);
624 CHECK_OFFSET(ept_pointer, 120);
625 CHECK_OFFSET(eoi_exit_bitmap0, 128);
626 CHECK_OFFSET(eoi_exit_bitmap1, 136);
627 CHECK_OFFSET(eoi_exit_bitmap2, 144);
628 CHECK_OFFSET(eoi_exit_bitmap3, 152);
629 CHECK_OFFSET(xss_exit_bitmap, 160);
630 CHECK_OFFSET(guest_physical_address, 168);
631 CHECK_OFFSET(vmcs_link_pointer, 176);
632 CHECK_OFFSET(guest_ia32_debugctl, 184);
633 CHECK_OFFSET(guest_ia32_pat, 192);
634 CHECK_OFFSET(guest_ia32_efer, 200);
635 CHECK_OFFSET(guest_ia32_perf_global_ctrl, 208);
636 CHECK_OFFSET(guest_pdptr0, 216);
637 CHECK_OFFSET(guest_pdptr1, 224);
638 CHECK_OFFSET(guest_pdptr2, 232);
639 CHECK_OFFSET(guest_pdptr3, 240);
640 CHECK_OFFSET(guest_bndcfgs, 248);
641 CHECK_OFFSET(host_ia32_pat, 256);
642 CHECK_OFFSET(host_ia32_efer, 264);
643 CHECK_OFFSET(host_ia32_perf_global_ctrl, 272);
644 CHECK_OFFSET(vmread_bitmap, 280);
645 CHECK_OFFSET(vmwrite_bitmap, 288);
646 CHECK_OFFSET(vm_function_control, 296);
647 CHECK_OFFSET(eptp_list_address, 304);
648 CHECK_OFFSET(pml_address, 312);
649 CHECK_OFFSET(cr0_guest_host_mask, 344);
650 CHECK_OFFSET(cr4_guest_host_mask, 352);
651 CHECK_OFFSET(cr0_read_shadow, 360);
652 CHECK_OFFSET(cr4_read_shadow, 368);
653 CHECK_OFFSET(cr3_target_value0, 376);
654 CHECK_OFFSET(cr3_target_value1, 384);
655 CHECK_OFFSET(cr3_target_value2, 392);
656 CHECK_OFFSET(cr3_target_value3, 400);
657 CHECK_OFFSET(exit_qualification, 408);
658 CHECK_OFFSET(guest_linear_address, 416);
659 CHECK_OFFSET(guest_cr0, 424);
660 CHECK_OFFSET(guest_cr3, 432);
661 CHECK_OFFSET(guest_cr4, 440);
662 CHECK_OFFSET(guest_es_base, 448);
663 CHECK_OFFSET(guest_cs_base, 456);
664 CHECK_OFFSET(guest_ss_base, 464);
665 CHECK_OFFSET(guest_ds_base, 472);
666 CHECK_OFFSET(guest_fs_base, 480);
667 CHECK_OFFSET(guest_gs_base, 488);
668 CHECK_OFFSET(guest_ldtr_base, 496);
669 CHECK_OFFSET(guest_tr_base, 504);
670 CHECK_OFFSET(guest_gdtr_base, 512);
671 CHECK_OFFSET(guest_idtr_base, 520);
672 CHECK_OFFSET(guest_dr7, 528);
673 CHECK_OFFSET(guest_rsp, 536);
674 CHECK_OFFSET(guest_rip, 544);
675 CHECK_OFFSET(guest_rflags, 552);
676 CHECK_OFFSET(guest_pending_dbg_exceptions, 560);
677 CHECK_OFFSET(guest_sysenter_esp, 568);
678 CHECK_OFFSET(guest_sysenter_eip, 576);
679 CHECK_OFFSET(host_cr0, 584);
680 CHECK_OFFSET(host_cr3, 592);
681 CHECK_OFFSET(host_cr4, 600);
682 CHECK_OFFSET(host_fs_base, 608);
683 CHECK_OFFSET(host_gs_base, 616);
684 CHECK_OFFSET(host_tr_base, 624);
685 CHECK_OFFSET(host_gdtr_base, 632);
686 CHECK_OFFSET(host_idtr_base, 640);
687 CHECK_OFFSET(host_ia32_sysenter_esp, 648);
688 CHECK_OFFSET(host_ia32_sysenter_eip, 656);
689 CHECK_OFFSET(host_rsp, 664);
690 CHECK_OFFSET(host_rip, 672);
691 CHECK_OFFSET(pin_based_vm_exec_control, 744);
692 CHECK_OFFSET(cpu_based_vm_exec_control, 748);
693 CHECK_OFFSET(exception_bitmap, 752);
694 CHECK_OFFSET(page_fault_error_code_mask, 756);
695 CHECK_OFFSET(page_fault_error_code_match, 760);
696 CHECK_OFFSET(cr3_target_count, 764);
697 CHECK_OFFSET(vm_exit_controls, 768);
698 CHECK_OFFSET(vm_exit_msr_store_count, 772);
699 CHECK_OFFSET(vm_exit_msr_load_count, 776);
700 CHECK_OFFSET(vm_entry_controls, 780);
701 CHECK_OFFSET(vm_entry_msr_load_count, 784);
702 CHECK_OFFSET(vm_entry_intr_info_field, 788);
703 CHECK_OFFSET(vm_entry_exception_error_code, 792);
704 CHECK_OFFSET(vm_entry_instruction_len, 796);
705 CHECK_OFFSET(tpr_threshold, 800);
706 CHECK_OFFSET(secondary_vm_exec_control, 804);
707 CHECK_OFFSET(vm_instruction_error, 808);
708 CHECK_OFFSET(vm_exit_reason, 812);
709 CHECK_OFFSET(vm_exit_intr_info, 816);
710 CHECK_OFFSET(vm_exit_intr_error_code, 820);
711 CHECK_OFFSET(idt_vectoring_info_field, 824);
712 CHECK_OFFSET(idt_vectoring_error_code, 828);
713 CHECK_OFFSET(vm_exit_instruction_len, 832);
714 CHECK_OFFSET(vmx_instruction_info, 836);
715 CHECK_OFFSET(guest_es_limit, 840);
716 CHECK_OFFSET(guest_cs_limit, 844);
717 CHECK_OFFSET(guest_ss_limit, 848);
718 CHECK_OFFSET(guest_ds_limit, 852);
719 CHECK_OFFSET(guest_fs_limit, 856);
720 CHECK_OFFSET(guest_gs_limit, 860);
721 CHECK_OFFSET(guest_ldtr_limit, 864);
722 CHECK_OFFSET(guest_tr_limit, 868);
723 CHECK_OFFSET(guest_gdtr_limit, 872);
724 CHECK_OFFSET(guest_idtr_limit, 876);
725 CHECK_OFFSET(guest_es_ar_bytes, 880);
726 CHECK_OFFSET(guest_cs_ar_bytes, 884);
727 CHECK_OFFSET(guest_ss_ar_bytes, 888);
728 CHECK_OFFSET(guest_ds_ar_bytes, 892);
729 CHECK_OFFSET(guest_fs_ar_bytes, 896);
730 CHECK_OFFSET(guest_gs_ar_bytes, 900);
731 CHECK_OFFSET(guest_ldtr_ar_bytes, 904);
732 CHECK_OFFSET(guest_tr_ar_bytes, 908);
733 CHECK_OFFSET(guest_interruptibility_info, 912);
734 CHECK_OFFSET(guest_activity_state, 916);
735 CHECK_OFFSET(guest_sysenter_cs, 920);
736 CHECK_OFFSET(host_ia32_sysenter_cs, 924);
737 CHECK_OFFSET(vmx_preemption_timer_value, 928);
738 CHECK_OFFSET(virtual_processor_id, 960);
739 CHECK_OFFSET(posted_intr_nv, 962);
740 CHECK_OFFSET(guest_es_selector, 964);
741 CHECK_OFFSET(guest_cs_selector, 966);
742 CHECK_OFFSET(guest_ss_selector, 968);
743 CHECK_OFFSET(guest_ds_selector, 970);
744 CHECK_OFFSET(guest_fs_selector, 972);
745 CHECK_OFFSET(guest_gs_selector, 974);
746 CHECK_OFFSET(guest_ldtr_selector, 976);
747 CHECK_OFFSET(guest_tr_selector, 978);
748 CHECK_OFFSET(guest_intr_status, 980);
749 CHECK_OFFSET(host_es_selector, 982);
750 CHECK_OFFSET(host_cs_selector, 984);
751 CHECK_OFFSET(host_ss_selector, 986);
752 CHECK_OFFSET(host_ds_selector, 988);
753 CHECK_OFFSET(host_fs_selector, 990);
754 CHECK_OFFSET(host_gs_selector, 992);
755 CHECK_OFFSET(host_tr_selector, 994);
756 CHECK_OFFSET(guest_pml_index, 996);
757 }
758
759 /*
760 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
761 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
762 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
763 *
764 * IMPORTANT: Changing this value will break save/restore compatibility with
765 * older kvm releases.
766 */
767 #define VMCS12_REVISION 0x11e57ed0
768
769 /*
770 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
771 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
772 * current implementation, 4K are reserved to avoid future complications.
773 */
774 #define VMCS12_SIZE 0x1000
775
776 /*
777 * VMCS12_MAX_FIELD_INDEX is the highest index value used in any
778 * supported VMCS12 field encoding.
779 */
780 #define VMCS12_MAX_FIELD_INDEX 0x17
781
782 /*
783 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
784 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
785 */
786 struct nested_vmx {
787 /* Has the level1 guest done vmxon? */
788 bool vmxon;
789 gpa_t vmxon_ptr;
790 bool pml_full;
791
792 /* The guest-physical address of the current VMCS L1 keeps for L2 */
793 gpa_t current_vmptr;
794 /*
795 * Cache of the guest's VMCS, existing outside of guest memory.
796 * Loaded from guest memory during VMPTRLD. Flushed to guest
797 * memory during VMCLEAR and VMPTRLD.
798 */
799 struct vmcs12 *cached_vmcs12;
800 /*
801 * Cache of the guest's shadow VMCS, existing outside of guest
802 * memory. Loaded from guest memory during VM entry. Flushed
803 * to guest memory during VM exit.
804 */
805 struct vmcs12 *cached_shadow_vmcs12;
806 /*
807 * Indicates if the shadow vmcs or enlightened vmcs must be updated
808 * with the data held by struct vmcs12.
809 */
810 bool need_vmcs12_sync;
811 bool dirty_vmcs12;
812
813 /*
814 * vmcs02 has been initialized, i.e. state that is constant for
815 * vmcs02 has been written to the backing VMCS. Initialization
816 * is delayed until L1 actually attempts to run a nested VM.
817 */
818 bool vmcs02_initialized;
819
820 bool change_vmcs01_virtual_apic_mode;
821
822 /*
823 * Enlightened VMCS has been enabled. It does not mean that L1 has to
824 * use it. However, VMX features available to L1 will be limited based
825 * on what the enlightened VMCS supports.
826 */
827 bool enlightened_vmcs_enabled;
828
829 /* L2 must run next, and mustn't decide to exit to L1. */
830 bool nested_run_pending;
831
832 struct loaded_vmcs vmcs02;
833
834 /*
835 * Guest pages referred to in the vmcs02 with host-physical
836 * pointers, so we must keep them pinned while L2 runs.
837 */
838 struct page *apic_access_page;
839 struct page *virtual_apic_page;
840 struct page *pi_desc_page;
841 struct pi_desc *pi_desc;
842 bool pi_pending;
843 u16 posted_intr_nv;
844
845 struct hrtimer preemption_timer;
846 bool preemption_timer_expired;
847
848 /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
849 u64 vmcs01_debugctl;
850 u64 vmcs01_guest_bndcfgs;
851
852 u16 vpid02;
853 u16 last_vpid;
854
855 struct nested_vmx_msrs msrs;
856
857 /* SMM related state */
858 struct {
859 /* in VMX operation on SMM entry? */
860 bool vmxon;
861 /* in guest mode on SMM entry? */
862 bool guest_mode;
863 } smm;
864
865 gpa_t hv_evmcs_vmptr;
866 struct page *hv_evmcs_page;
867 struct hv_enlightened_vmcs *hv_evmcs;
868 };
869
870 #define POSTED_INTR_ON 0
871 #define POSTED_INTR_SN 1
872
873 /* Posted-Interrupt Descriptor */
874 struct pi_desc {
875 u32 pir[8]; /* Posted interrupt requested */
876 union {
877 struct {
878 /* bit 256 - Outstanding Notification */
879 u16 on : 1,
880 /* bit 257 - Suppress Notification */
881 sn : 1,
882 /* bit 271:258 - Reserved */
883 rsvd_1 : 14;
884 /* bit 279:272 - Notification Vector */
885 u8 nv;
886 /* bit 287:280 - Reserved */
887 u8 rsvd_2;
888 /* bit 319:288 - Notification Destination */
889 u32 ndst;
890 };
891 u64 control;
892 };
893 u32 rsvd[6];
894 } __aligned(64);
895
896 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
897 {
898 return test_and_set_bit(POSTED_INTR_ON,
899 (unsigned long *)&pi_desc->control);
900 }
901
902 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
903 {
904 return test_and_clear_bit(POSTED_INTR_ON,
905 (unsigned long *)&pi_desc->control);
906 }
907
908 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
909 {
910 return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
911 }
912
913 static inline void pi_clear_sn(struct pi_desc *pi_desc)
914 {
915 return clear_bit(POSTED_INTR_SN,
916 (unsigned long *)&pi_desc->control);
917 }
918
919 static inline void pi_set_sn(struct pi_desc *pi_desc)
920 {
921 return set_bit(POSTED_INTR_SN,
922 (unsigned long *)&pi_desc->control);
923 }
924
925 static inline void pi_clear_on(struct pi_desc *pi_desc)
926 {
927 clear_bit(POSTED_INTR_ON,
928 (unsigned long *)&pi_desc->control);
929 }
930
931 static inline int pi_test_on(struct pi_desc *pi_desc)
932 {
933 return test_bit(POSTED_INTR_ON,
934 (unsigned long *)&pi_desc->control);
935 }
936
937 static inline int pi_test_sn(struct pi_desc *pi_desc)
938 {
939 return test_bit(POSTED_INTR_SN,
940 (unsigned long *)&pi_desc->control);
941 }
942
943 struct vmx_msrs {
944 unsigned int nr;
945 struct vmx_msr_entry val[NR_AUTOLOAD_MSRS];
946 };
947
948 struct vcpu_vmx {
949 struct kvm_vcpu vcpu;
950 unsigned long host_rsp;
951 u8 fail;
952 u8 msr_bitmap_mode;
953 u32 exit_intr_info;
954 u32 idt_vectoring_info;
955 ulong rflags;
956 struct shared_msr_entry *guest_msrs;
957 int nmsrs;
958 int save_nmsrs;
959 bool guest_msrs_dirty;
960 unsigned long host_idt_base;
961 #ifdef CONFIG_X86_64
962 u64 msr_host_kernel_gs_base;
963 u64 msr_guest_kernel_gs_base;
964 #endif
965
966 u64 arch_capabilities;
967 u64 spec_ctrl;
968
969 u32 vm_entry_controls_shadow;
970 u32 vm_exit_controls_shadow;
971 u32 secondary_exec_control;
972
973 /*
974 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
975 * non-nested (L1) guest, it always points to vmcs01. For a nested
976 * guest (L2), it points to a different VMCS. loaded_cpu_state points
977 * to the VMCS whose state is loaded into the CPU registers that only
978 * need to be switched when transitioning to/from the kernel; a NULL
979 * value indicates that host state is loaded.
980 */
981 struct loaded_vmcs vmcs01;
982 struct loaded_vmcs *loaded_vmcs;
983 struct loaded_vmcs *loaded_cpu_state;
984 bool __launched; /* temporary, used in vmx_vcpu_run */
985 struct msr_autoload {
986 struct vmx_msrs guest;
987 struct vmx_msrs host;
988 } msr_autoload;
989
990 struct {
991 int vm86_active;
992 ulong save_rflags;
993 struct kvm_segment segs[8];
994 } rmode;
995 struct {
996 u32 bitmask; /* 4 bits per segment (1 bit per field) */
997 struct kvm_save_segment {
998 u16 selector;
999 unsigned long base;
1000 u32 limit;
1001 u32 ar;
1002 } seg[8];
1003 } segment_cache;
1004 int vpid;
1005 bool emulation_required;
1006
1007 u32 exit_reason;
1008
1009 /* Posted interrupt descriptor */
1010 struct pi_desc pi_desc;
1011
1012 /* Support for a guest hypervisor (nested VMX) */
1013 struct nested_vmx nested;
1014
1015 /* Dynamic PLE window. */
1016 int ple_window;
1017 bool ple_window_dirty;
1018
1019 bool req_immediate_exit;
1020
1021 /* Support for PML */
1022 #define PML_ENTITY_NUM 512
1023 struct page *pml_pg;
1024
1025 /* apic deadline value in host tsc */
1026 u64 hv_deadline_tsc;
1027
1028 u64 current_tsc_ratio;
1029
1030 u32 host_pkru;
1031
1032 unsigned long host_debugctlmsr;
1033
1034 /*
1035 * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
1036 * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
1037 * in msr_ia32_feature_control_valid_bits.
1038 */
1039 u64 msr_ia32_feature_control;
1040 u64 msr_ia32_feature_control_valid_bits;
1041 u64 ept_pointer;
1042 };
1043
1044 enum segment_cache_field {
1045 SEG_FIELD_SEL = 0,
1046 SEG_FIELD_BASE = 1,
1047 SEG_FIELD_LIMIT = 2,
1048 SEG_FIELD_AR = 3,
1049
1050 SEG_FIELD_NR = 4
1051 };
1052
1053 static inline struct kvm_vmx *to_kvm_vmx(struct kvm *kvm)
1054 {
1055 return container_of(kvm, struct kvm_vmx, kvm);
1056 }
1057
1058 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
1059 {
1060 return container_of(vcpu, struct vcpu_vmx, vcpu);
1061 }
1062
1063 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
1064 {
1065 return &(to_vmx(vcpu)->pi_desc);
1066 }
1067
1068 #define ROL16(val, n) ((u16)(((u16)(val) << (n)) | ((u16)(val) >> (16 - (n)))))
1069 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
1070 #define FIELD(number, name) [ROL16(number, 6)] = VMCS12_OFFSET(name)
1071 #define FIELD64(number, name) \
1072 FIELD(number, name), \
1073 [ROL16(number##_HIGH, 6)] = VMCS12_OFFSET(name) + sizeof(u32)
1074
1075
1076 static u16 shadow_read_only_fields[] = {
1077 #define SHADOW_FIELD_RO(x) x,
1078 #include "vmcs_shadow_fields.h"
1079 };
1080 static int max_shadow_read_only_fields =
1081 ARRAY_SIZE(shadow_read_only_fields);
1082
1083 static u16 shadow_read_write_fields[] = {
1084 #define SHADOW_FIELD_RW(x) x,
1085 #include "vmcs_shadow_fields.h"
1086 };
1087 static int max_shadow_read_write_fields =
1088 ARRAY_SIZE(shadow_read_write_fields);
1089
1090 static const unsigned short vmcs_field_to_offset_table[] = {
1091 FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
1092 FIELD(POSTED_INTR_NV, posted_intr_nv),
1093 FIELD(GUEST_ES_SELECTOR, guest_es_selector),
1094 FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
1095 FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
1096 FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
1097 FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
1098 FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
1099 FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
1100 FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
1101 FIELD(GUEST_INTR_STATUS, guest_intr_status),
1102 FIELD(GUEST_PML_INDEX, guest_pml_index),
1103 FIELD(HOST_ES_SELECTOR, host_es_selector),
1104 FIELD(HOST_CS_SELECTOR, host_cs_selector),
1105 FIELD(HOST_SS_SELECTOR, host_ss_selector),
1106 FIELD(HOST_DS_SELECTOR, host_ds_selector),
1107 FIELD(HOST_FS_SELECTOR, host_fs_selector),
1108 FIELD(HOST_GS_SELECTOR, host_gs_selector),
1109 FIELD(HOST_TR_SELECTOR, host_tr_selector),
1110 FIELD64(IO_BITMAP_A, io_bitmap_a),
1111 FIELD64(IO_BITMAP_B, io_bitmap_b),
1112 FIELD64(MSR_BITMAP, msr_bitmap),
1113 FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
1114 FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
1115 FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
1116 FIELD64(PML_ADDRESS, pml_address),
1117 FIELD64(TSC_OFFSET, tsc_offset),
1118 FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
1119 FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
1120 FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
1121 FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
1122 FIELD64(EPT_POINTER, ept_pointer),
1123 FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
1124 FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
1125 FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
1126 FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
1127 FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
1128 FIELD64(VMREAD_BITMAP, vmread_bitmap),
1129 FIELD64(VMWRITE_BITMAP, vmwrite_bitmap),
1130 FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
1131 FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
1132 FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
1133 FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
1134 FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
1135 FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
1136 FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
1137 FIELD64(GUEST_PDPTR0, guest_pdptr0),
1138 FIELD64(GUEST_PDPTR1, guest_pdptr1),
1139 FIELD64(GUEST_PDPTR2, guest_pdptr2),
1140 FIELD64(GUEST_PDPTR3, guest_pdptr3),
1141 FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
1142 FIELD64(HOST_IA32_PAT, host_ia32_pat),
1143 FIELD64(HOST_IA32_EFER, host_ia32_efer),
1144 FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
1145 FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
1146 FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
1147 FIELD(EXCEPTION_BITMAP, exception_bitmap),
1148 FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
1149 FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
1150 FIELD(CR3_TARGET_COUNT, cr3_target_count),
1151 FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
1152 FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
1153 FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
1154 FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
1155 FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
1156 FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
1157 FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
1158 FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
1159 FIELD(TPR_THRESHOLD, tpr_threshold),
1160 FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
1161 FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
1162 FIELD(VM_EXIT_REASON, vm_exit_reason),
1163 FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
1164 FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
1165 FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
1166 FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
1167 FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
1168 FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
1169 FIELD(GUEST_ES_LIMIT, guest_es_limit),
1170 FIELD(GUEST_CS_LIMIT, guest_cs_limit),
1171 FIELD(GUEST_SS_LIMIT, guest_ss_limit),
1172 FIELD(GUEST_DS_LIMIT, guest_ds_limit),
1173 FIELD(GUEST_FS_LIMIT, guest_fs_limit),
1174 FIELD(GUEST_GS_LIMIT, guest_gs_limit),
1175 FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
1176 FIELD(GUEST_TR_LIMIT, guest_tr_limit),
1177 FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
1178 FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
1179 FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
1180 FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
1181 FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
1182 FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
1183 FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
1184 FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
1185 FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
1186 FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
1187 FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
1188 FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
1189 FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
1190 FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
1191 FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
1192 FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
1193 FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
1194 FIELD(CR0_READ_SHADOW, cr0_read_shadow),
1195 FIELD(CR4_READ_SHADOW, cr4_read_shadow),
1196 FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
1197 FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
1198 FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
1199 FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
1200 FIELD(EXIT_QUALIFICATION, exit_qualification),
1201 FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
1202 FIELD(GUEST_CR0, guest_cr0),
1203 FIELD(GUEST_CR3, guest_cr3),
1204 FIELD(GUEST_CR4, guest_cr4),
1205 FIELD(GUEST_ES_BASE, guest_es_base),
1206 FIELD(GUEST_CS_BASE, guest_cs_base),
1207 FIELD(GUEST_SS_BASE, guest_ss_base),
1208 FIELD(GUEST_DS_BASE, guest_ds_base),
1209 FIELD(GUEST_FS_BASE, guest_fs_base),
1210 FIELD(GUEST_GS_BASE, guest_gs_base),
1211 FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
1212 FIELD(GUEST_TR_BASE, guest_tr_base),
1213 FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
1214 FIELD(GUEST_IDTR_BASE, guest_idtr_base),
1215 FIELD(GUEST_DR7, guest_dr7),
1216 FIELD(GUEST_RSP, guest_rsp),
1217 FIELD(GUEST_RIP, guest_rip),
1218 FIELD(GUEST_RFLAGS, guest_rflags),
1219 FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
1220 FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
1221 FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
1222 FIELD(HOST_CR0, host_cr0),
1223 FIELD(HOST_CR3, host_cr3),
1224 FIELD(HOST_CR4, host_cr4),
1225 FIELD(HOST_FS_BASE, host_fs_base),
1226 FIELD(HOST_GS_BASE, host_gs_base),
1227 FIELD(HOST_TR_BASE, host_tr_base),
1228 FIELD(HOST_GDTR_BASE, host_gdtr_base),
1229 FIELD(HOST_IDTR_BASE, host_idtr_base),
1230 FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
1231 FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
1232 FIELD(HOST_RSP, host_rsp),
1233 FIELD(HOST_RIP, host_rip),
1234 };
1235
1236 static inline short vmcs_field_to_offset(unsigned long field)
1237 {
1238 const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
1239 unsigned short offset;
1240 unsigned index;
1241
1242 if (field >> 15)
1243 return -ENOENT;
1244
1245 index = ROL16(field, 6);
1246 if (index >= size)
1247 return -ENOENT;
1248
1249 index = array_index_nospec(index, size);
1250 offset = vmcs_field_to_offset_table[index];
1251 if (offset == 0)
1252 return -ENOENT;
1253 return offset;
1254 }
1255
1256 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
1257 {
1258 return to_vmx(vcpu)->nested.cached_vmcs12;
1259 }
1260
1261 static inline struct vmcs12 *get_shadow_vmcs12(struct kvm_vcpu *vcpu)
1262 {
1263 return to_vmx(vcpu)->nested.cached_shadow_vmcs12;
1264 }
1265
1266 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
1267 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
1268 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
1269 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1270 struct kvm_segment *var, int seg);
1271 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1272 struct kvm_segment *var, int seg);
1273 static bool guest_state_valid(struct kvm_vcpu *vcpu);
1274 static u32 vmx_segment_access_rights(struct kvm_segment *var);
1275 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
1276 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
1277 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
1278 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
1279 u16 error_code);
1280 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
1281 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
1282 u32 msr, int type);
1283
1284 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
1285 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
1286 /*
1287 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
1288 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
1289 */
1290 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
1291
1292 /*
1293 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
1294 * can find which vCPU should be waken up.
1295 */
1296 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
1297 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
1298
1299 enum {
1300 VMX_VMREAD_BITMAP,
1301 VMX_VMWRITE_BITMAP,
1302 VMX_BITMAP_NR
1303 };
1304
1305 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
1306
1307 #define vmx_vmread_bitmap (vmx_bitmap[VMX_VMREAD_BITMAP])
1308 #define vmx_vmwrite_bitmap (vmx_bitmap[VMX_VMWRITE_BITMAP])
1309
1310 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
1311 static DEFINE_SPINLOCK(vmx_vpid_lock);
1312
1313 struct vmcs_config vmcs_config;
1314 struct vmx_capability vmx_capability;
1315
1316 #define VMX_SEGMENT_FIELD(seg) \
1317 [VCPU_SREG_##seg] = { \
1318 .selector = GUEST_##seg##_SELECTOR, \
1319 .base = GUEST_##seg##_BASE, \
1320 .limit = GUEST_##seg##_LIMIT, \
1321 .ar_bytes = GUEST_##seg##_AR_BYTES, \
1322 }
1323
1324 static const struct kvm_vmx_segment_field {
1325 unsigned selector;
1326 unsigned base;
1327 unsigned limit;
1328 unsigned ar_bytes;
1329 } kvm_vmx_segment_fields[] = {
1330 VMX_SEGMENT_FIELD(CS),
1331 VMX_SEGMENT_FIELD(DS),
1332 VMX_SEGMENT_FIELD(ES),
1333 VMX_SEGMENT_FIELD(FS),
1334 VMX_SEGMENT_FIELD(GS),
1335 VMX_SEGMENT_FIELD(SS),
1336 VMX_SEGMENT_FIELD(TR),
1337 VMX_SEGMENT_FIELD(LDTR),
1338 };
1339
1340 static u64 host_efer;
1341
1342 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1343
1344 /*
1345 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1346 * away by decrementing the array size.
1347 */
1348 static const u32 vmx_msr_index[] = {
1349 #ifdef CONFIG_X86_64
1350 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1351 #endif
1352 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1353 };
1354
1355 DEFINE_STATIC_KEY_FALSE(enable_evmcs);
1356
1357 #define current_evmcs ((struct hv_enlightened_vmcs *)this_cpu_read(current_vmcs))
1358
1359 #define KVM_EVMCS_VERSION 1
1360
1361 /*
1362 * Enlightened VMCSv1 doesn't support these:
1363 *
1364 * POSTED_INTR_NV = 0x00000002,
1365 * GUEST_INTR_STATUS = 0x00000810,
1366 * APIC_ACCESS_ADDR = 0x00002014,
1367 * POSTED_INTR_DESC_ADDR = 0x00002016,
1368 * EOI_EXIT_BITMAP0 = 0x0000201c,
1369 * EOI_EXIT_BITMAP1 = 0x0000201e,
1370 * EOI_EXIT_BITMAP2 = 0x00002020,
1371 * EOI_EXIT_BITMAP3 = 0x00002022,
1372 * GUEST_PML_INDEX = 0x00000812,
1373 * PML_ADDRESS = 0x0000200e,
1374 * VM_FUNCTION_CONTROL = 0x00002018,
1375 * EPTP_LIST_ADDRESS = 0x00002024,
1376 * VMREAD_BITMAP = 0x00002026,
1377 * VMWRITE_BITMAP = 0x00002028,
1378 *
1379 * TSC_MULTIPLIER = 0x00002032,
1380 * PLE_GAP = 0x00004020,
1381 * PLE_WINDOW = 0x00004022,
1382 * VMX_PREEMPTION_TIMER_VALUE = 0x0000482E,
1383 * GUEST_IA32_PERF_GLOBAL_CTRL = 0x00002808,
1384 * HOST_IA32_PERF_GLOBAL_CTRL = 0x00002c04,
1385 *
1386 * Currently unsupported in KVM:
1387 * GUEST_IA32_RTIT_CTL = 0x00002814,
1388 */
1389 #define EVMCS1_UNSUPPORTED_PINCTRL (PIN_BASED_POSTED_INTR | \
1390 PIN_BASED_VMX_PREEMPTION_TIMER)
1391 #define EVMCS1_UNSUPPORTED_2NDEXEC \
1392 (SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY | \
1393 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES | \
1394 SECONDARY_EXEC_APIC_REGISTER_VIRT | \
1395 SECONDARY_EXEC_ENABLE_PML | \
1396 SECONDARY_EXEC_ENABLE_VMFUNC | \
1397 SECONDARY_EXEC_SHADOW_VMCS | \
1398 SECONDARY_EXEC_TSC_SCALING | \
1399 SECONDARY_EXEC_PAUSE_LOOP_EXITING)
1400 #define EVMCS1_UNSUPPORTED_VMEXIT_CTRL (VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
1401 #define EVMCS1_UNSUPPORTED_VMENTRY_CTRL (VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
1402 #define EVMCS1_UNSUPPORTED_VMFUNC (VMX_VMFUNC_EPTP_SWITCHING)
1403
1404 #if IS_ENABLED(CONFIG_HYPERV)
1405 static bool __read_mostly enlightened_vmcs = true;
1406 module_param(enlightened_vmcs, bool, 0444);
1407
1408 static inline void evmcs_write64(unsigned long field, u64 value)
1409 {
1410 u16 clean_field;
1411 int offset = get_evmcs_offset(field, &clean_field);
1412
1413 if (offset < 0)
1414 return;
1415
1416 *(u64 *)((char *)current_evmcs + offset) = value;
1417
1418 current_evmcs->hv_clean_fields &= ~clean_field;
1419 }
1420
1421 static inline void evmcs_write32(unsigned long field, u32 value)
1422 {
1423 u16 clean_field;
1424 int offset = get_evmcs_offset(field, &clean_field);
1425
1426 if (offset < 0)
1427 return;
1428
1429 *(u32 *)((char *)current_evmcs + offset) = value;
1430 current_evmcs->hv_clean_fields &= ~clean_field;
1431 }
1432
1433 static inline void evmcs_write16(unsigned long field, u16 value)
1434 {
1435 u16 clean_field;
1436 int offset = get_evmcs_offset(field, &clean_field);
1437
1438 if (offset < 0)
1439 return;
1440
1441 *(u16 *)((char *)current_evmcs + offset) = value;
1442 current_evmcs->hv_clean_fields &= ~clean_field;
1443 }
1444
1445 static inline u64 evmcs_read64(unsigned long field)
1446 {
1447 int offset = get_evmcs_offset(field, NULL);
1448
1449 if (offset < 0)
1450 return 0;
1451
1452 return *(u64 *)((char *)current_evmcs + offset);
1453 }
1454
1455 static inline u32 evmcs_read32(unsigned long field)
1456 {
1457 int offset = get_evmcs_offset(field, NULL);
1458
1459 if (offset < 0)
1460 return 0;
1461
1462 return *(u32 *)((char *)current_evmcs + offset);
1463 }
1464
1465 static inline u16 evmcs_read16(unsigned long field)
1466 {
1467 int offset = get_evmcs_offset(field, NULL);
1468
1469 if (offset < 0)
1470 return 0;
1471
1472 return *(u16 *)((char *)current_evmcs + offset);
1473 }
1474
1475 static inline void evmcs_touch_msr_bitmap(void)
1476 {
1477 if (unlikely(!current_evmcs))
1478 return;
1479
1480 if (current_evmcs->hv_enlightenments_control.msr_bitmap)
1481 current_evmcs->hv_clean_fields &=
1482 ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
1483 }
1484
1485 static void evmcs_load(u64 phys_addr)
1486 {
1487 struct hv_vp_assist_page *vp_ap =
1488 hv_get_vp_assist_page(smp_processor_id());
1489
1490 vp_ap->current_nested_vmcs = phys_addr;
1491 vp_ap->enlighten_vmentry = 1;
1492 }
1493
1494 static void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf)
1495 {
1496 vmcs_conf->pin_based_exec_ctrl &= ~EVMCS1_UNSUPPORTED_PINCTRL;
1497 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~EVMCS1_UNSUPPORTED_2NDEXEC;
1498
1499 vmcs_conf->vmexit_ctrl &= ~EVMCS1_UNSUPPORTED_VMEXIT_CTRL;
1500 vmcs_conf->vmentry_ctrl &= ~EVMCS1_UNSUPPORTED_VMENTRY_CTRL;
1501
1502 }
1503
1504 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
1505 static void check_ept_pointer_match(struct kvm *kvm)
1506 {
1507 struct kvm_vcpu *vcpu;
1508 u64 tmp_eptp = INVALID_PAGE;
1509 int i;
1510
1511 kvm_for_each_vcpu(i, vcpu, kvm) {
1512 if (!VALID_PAGE(tmp_eptp)) {
1513 tmp_eptp = to_vmx(vcpu)->ept_pointer;
1514 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
1515 to_kvm_vmx(kvm)->ept_pointers_match
1516 = EPT_POINTERS_MISMATCH;
1517 return;
1518 }
1519 }
1520
1521 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
1522 }
1523
1524 static int vmx_hv_remote_flush_tlb(struct kvm *kvm)
1525 {
1526 struct kvm_vcpu *vcpu;
1527 int ret = -ENOTSUPP, i;
1528
1529 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1530
1531 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
1532 check_ept_pointer_match(kvm);
1533
1534 /*
1535 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs the address of the
1536 * base of EPT PML4 table, strip off EPT configuration information.
1537 */
1538 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
1539 kvm_for_each_vcpu(i, vcpu, kvm)
1540 ret |= hyperv_flush_guest_mapping(
1541 to_vmx(kvm_get_vcpu(kvm, i))->ept_pointer & PAGE_MASK);
1542 } else {
1543 ret = hyperv_flush_guest_mapping(
1544 to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer & PAGE_MASK);
1545 }
1546
1547 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1548 return ret;
1549 }
1550 #else /* !IS_ENABLED(CONFIG_HYPERV) */
1551 static inline void evmcs_write64(unsigned long field, u64 value) {}
1552 static inline void evmcs_write32(unsigned long field, u32 value) {}
1553 static inline void evmcs_write16(unsigned long field, u16 value) {}
1554 static inline u64 evmcs_read64(unsigned long field) { return 0; }
1555 static inline u32 evmcs_read32(unsigned long field) { return 0; }
1556 static inline u16 evmcs_read16(unsigned long field) { return 0; }
1557 static inline void evmcs_load(u64 phys_addr) {}
1558 static inline void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf) {}
1559 static inline void evmcs_touch_msr_bitmap(void) {}
1560 #endif /* IS_ENABLED(CONFIG_HYPERV) */
1561
1562 static int nested_enable_evmcs(struct kvm_vcpu *vcpu,
1563 uint16_t *vmcs_version)
1564 {
1565 struct vcpu_vmx *vmx = to_vmx(vcpu);
1566
1567 /*
1568 * vmcs_version represents the range of supported Enlightened VMCS
1569 * versions: lower 8 bits is the minimal version, higher 8 bits is the
1570 * maximum supported version. KVM supports versions from 1 to
1571 * KVM_EVMCS_VERSION.
1572 */
1573 if (vmcs_version)
1574 *vmcs_version = (KVM_EVMCS_VERSION << 8) | 1;
1575
1576 /* We don't support disabling the feature for simplicity. */
1577 if (vmx->nested.enlightened_vmcs_enabled)
1578 return 0;
1579
1580 vmx->nested.enlightened_vmcs_enabled = true;
1581
1582 vmx->nested.msrs.pinbased_ctls_high &= ~EVMCS1_UNSUPPORTED_PINCTRL;
1583 vmx->nested.msrs.entry_ctls_high &= ~EVMCS1_UNSUPPORTED_VMENTRY_CTRL;
1584 vmx->nested.msrs.exit_ctls_high &= ~EVMCS1_UNSUPPORTED_VMEXIT_CTRL;
1585 vmx->nested.msrs.secondary_ctls_high &= ~EVMCS1_UNSUPPORTED_2NDEXEC;
1586 vmx->nested.msrs.vmfunc_controls &= ~EVMCS1_UNSUPPORTED_VMFUNC;
1587
1588 return 0;
1589 }
1590
1591 static inline bool is_exception_n(u32 intr_info, u8 vector)
1592 {
1593 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1594 INTR_INFO_VALID_MASK)) ==
1595 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1596 }
1597
1598 static inline bool is_debug(u32 intr_info)
1599 {
1600 return is_exception_n(intr_info, DB_VECTOR);
1601 }
1602
1603 static inline bool is_breakpoint(u32 intr_info)
1604 {
1605 return is_exception_n(intr_info, BP_VECTOR);
1606 }
1607
1608 static inline bool is_page_fault(u32 intr_info)
1609 {
1610 return is_exception_n(intr_info, PF_VECTOR);
1611 }
1612
1613 static inline bool is_invalid_opcode(u32 intr_info)
1614 {
1615 return is_exception_n(intr_info, UD_VECTOR);
1616 }
1617
1618 static inline bool is_gp_fault(u32 intr_info)
1619 {
1620 return is_exception_n(intr_info, GP_VECTOR);
1621 }
1622
1623 static inline bool is_machine_check(u32 intr_info)
1624 {
1625 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1626 INTR_INFO_VALID_MASK)) ==
1627 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1628 }
1629
1630 /* Undocumented: icebp/int1 */
1631 static inline bool is_icebp(u32 intr_info)
1632 {
1633 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1634 == (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1635 }
1636
1637 /*
1638 * Comment's format: document - errata name - stepping - processor name.
1639 * Refer from
1640 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1641 */
1642 static u32 vmx_preemption_cpu_tfms[] = {
1643 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
1644 0x000206E6,
1645 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
1646 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1647 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1648 0x00020652,
1649 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1650 0x00020655,
1651 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
1652 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
1653 /*
1654 * 320767.pdf - AAP86 - B1 -
1655 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1656 */
1657 0x000106E5,
1658 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1659 0x000106A0,
1660 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1661 0x000106A1,
1662 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1663 0x000106A4,
1664 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1665 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1666 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1667 0x000106A5,
1668 };
1669
1670 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1671 {
1672 u32 eax = cpuid_eax(0x00000001), i;
1673
1674 /* Clear the reserved bits */
1675 eax &= ~(0x3U << 14 | 0xfU << 28);
1676 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1677 if (eax == vmx_preemption_cpu_tfms[i])
1678 return true;
1679
1680 return false;
1681 }
1682
1683 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1684 {
1685 return flexpriority_enabled && lapic_in_kernel(vcpu);
1686 }
1687
1688 static inline bool report_flexpriority(void)
1689 {
1690 return flexpriority_enabled;
1691 }
1692
1693 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1694 {
1695 return vmx_misc_cr3_count(to_vmx(vcpu)->nested.msrs.misc_low);
1696 }
1697
1698 /*
1699 * Do the virtual VMX capability MSRs specify that L1 can use VMWRITE
1700 * to modify any valid field of the VMCS, or are the VM-exit
1701 * information fields read-only?
1702 */
1703 static inline bool nested_cpu_has_vmwrite_any_field(struct kvm_vcpu *vcpu)
1704 {
1705 return to_vmx(vcpu)->nested.msrs.misc_low &
1706 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
1707 }
1708
1709 static inline bool nested_cpu_has_zero_length_injection(struct kvm_vcpu *vcpu)
1710 {
1711 return to_vmx(vcpu)->nested.msrs.misc_low & VMX_MISC_ZERO_LEN_INS;
1712 }
1713
1714 static inline bool nested_cpu_supports_monitor_trap_flag(struct kvm_vcpu *vcpu)
1715 {
1716 return to_vmx(vcpu)->nested.msrs.procbased_ctls_high &
1717 CPU_BASED_MONITOR_TRAP_FLAG;
1718 }
1719
1720 static inline bool nested_cpu_has_vmx_shadow_vmcs(struct kvm_vcpu *vcpu)
1721 {
1722 return to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
1723 SECONDARY_EXEC_SHADOW_VMCS;
1724 }
1725
1726 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1727 {
1728 return vmcs12->cpu_based_vm_exec_control & bit;
1729 }
1730
1731 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1732 {
1733 return (vmcs12->cpu_based_vm_exec_control &
1734 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1735 (vmcs12->secondary_vm_exec_control & bit);
1736 }
1737
1738 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1739 {
1740 return vmcs12->pin_based_vm_exec_control &
1741 PIN_BASED_VMX_PREEMPTION_TIMER;
1742 }
1743
1744 static inline bool nested_cpu_has_nmi_exiting(struct vmcs12 *vmcs12)
1745 {
1746 return vmcs12->pin_based_vm_exec_control & PIN_BASED_NMI_EXITING;
1747 }
1748
1749 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1750 {
1751 return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1752 }
1753
1754 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1755 {
1756 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1757 }
1758
1759 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1760 {
1761 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
1762 }
1763
1764 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
1765 {
1766 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
1767 }
1768
1769 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1770 {
1771 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1772 }
1773
1774 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1775 {
1776 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1777 }
1778
1779 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1780 {
1781 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1782 }
1783
1784 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1785 {
1786 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1787 }
1788
1789 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1790 {
1791 return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1792 }
1793
1794 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
1795 {
1796 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
1797 }
1798
1799 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
1800 {
1801 return nested_cpu_has_vmfunc(vmcs12) &&
1802 (vmcs12->vm_function_control &
1803 VMX_VMFUNC_EPTP_SWITCHING);
1804 }
1805
1806 static inline bool nested_cpu_has_shadow_vmcs(struct vmcs12 *vmcs12)
1807 {
1808 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS);
1809 }
1810
1811 static inline bool nested_cpu_has_save_preemption_timer(struct vmcs12 *vmcs12)
1812 {
1813 return vmcs12->vm_exit_controls &
1814 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER;
1815 }
1816
1817 static inline bool is_nmi(u32 intr_info)
1818 {
1819 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1820 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1821 }
1822
1823 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1824 u32 exit_intr_info,
1825 unsigned long exit_qualification);
1826
1827 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1828 {
1829 int i;
1830
1831 for (i = 0; i < vmx->nmsrs; ++i)
1832 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1833 return i;
1834 return -1;
1835 }
1836
1837 static inline void __invvpid(unsigned long ext, u16 vpid, gva_t gva)
1838 {
1839 struct {
1840 u64 vpid : 16;
1841 u64 rsvd : 48;
1842 u64 gva;
1843 } operand = { vpid, 0, gva };
1844 bool error;
1845
1846 asm volatile (__ex("invvpid %2, %1") CC_SET(na)
1847 : CC_OUT(na) (error) : "r"(ext), "m"(operand));
1848 BUG_ON(error);
1849 }
1850
1851 static inline void __invept(unsigned long ext, u64 eptp, gpa_t gpa)
1852 {
1853 struct {
1854 u64 eptp, gpa;
1855 } operand = {eptp, gpa};
1856 bool error;
1857
1858 asm volatile (__ex("invept %2, %1") CC_SET(na)
1859 : CC_OUT(na) (error) : "r"(ext), "m"(operand));
1860 BUG_ON(error);
1861 }
1862
1863 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1864 {
1865 int i;
1866
1867 i = __find_msr_index(vmx, msr);
1868 if (i >= 0)
1869 return &vmx->guest_msrs[i];
1870 return NULL;
1871 }
1872
1873 static void vmcs_clear(struct vmcs *vmcs)
1874 {
1875 u64 phys_addr = __pa(vmcs);
1876 bool error;
1877
1878 asm volatile (__ex("vmclear %1") CC_SET(na)
1879 : CC_OUT(na) (error) : "m"(phys_addr));
1880 if (unlikely(error))
1881 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1882 vmcs, phys_addr);
1883 }
1884
1885 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1886 {
1887 vmcs_clear(loaded_vmcs->vmcs);
1888 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1889 vmcs_clear(loaded_vmcs->shadow_vmcs);
1890 loaded_vmcs->cpu = -1;
1891 loaded_vmcs->launched = 0;
1892 }
1893
1894 static void vmcs_load(struct vmcs *vmcs)
1895 {
1896 u64 phys_addr = __pa(vmcs);
1897 bool error;
1898
1899 if (static_branch_unlikely(&enable_evmcs))
1900 return evmcs_load(phys_addr);
1901
1902 asm volatile (__ex("vmptrld %1") CC_SET(na)
1903 : CC_OUT(na) (error) : "m"(phys_addr));
1904 if (unlikely(error))
1905 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1906 vmcs, phys_addr);
1907 }
1908
1909 #ifdef CONFIG_KEXEC_CORE
1910 /*
1911 * This bitmap is used to indicate whether the vmclear
1912 * operation is enabled on all cpus. All disabled by
1913 * default.
1914 */
1915 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1916
1917 static inline void crash_enable_local_vmclear(int cpu)
1918 {
1919 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1920 }
1921
1922 static inline void crash_disable_local_vmclear(int cpu)
1923 {
1924 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1925 }
1926
1927 static inline int crash_local_vmclear_enabled(int cpu)
1928 {
1929 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1930 }
1931
1932 static void crash_vmclear_local_loaded_vmcss(void)
1933 {
1934 int cpu = raw_smp_processor_id();
1935 struct loaded_vmcs *v;
1936
1937 if (!crash_local_vmclear_enabled(cpu))
1938 return;
1939
1940 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1941 loaded_vmcss_on_cpu_link)
1942 vmcs_clear(v->vmcs);
1943 }
1944 #else
1945 static inline void crash_enable_local_vmclear(int cpu) { }
1946 static inline void crash_disable_local_vmclear(int cpu) { }
1947 #endif /* CONFIG_KEXEC_CORE */
1948
1949 static void __loaded_vmcs_clear(void *arg)
1950 {
1951 struct loaded_vmcs *loaded_vmcs = arg;
1952 int cpu = raw_smp_processor_id();
1953
1954 if (loaded_vmcs->cpu != cpu)
1955 return; /* vcpu migration can race with cpu offline */
1956 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1957 per_cpu(current_vmcs, cpu) = NULL;
1958 crash_disable_local_vmclear(cpu);
1959 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1960
1961 /*
1962 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1963 * is before setting loaded_vmcs->vcpu to -1 which is done in
1964 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1965 * then adds the vmcs into percpu list before it is deleted.
1966 */
1967 smp_wmb();
1968
1969 loaded_vmcs_init(loaded_vmcs);
1970 crash_enable_local_vmclear(cpu);
1971 }
1972
1973 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1974 {
1975 int cpu = loaded_vmcs->cpu;
1976
1977 if (cpu != -1)
1978 smp_call_function_single(cpu,
1979 __loaded_vmcs_clear, loaded_vmcs, 1);
1980 }
1981
1982 static inline bool vpid_sync_vcpu_addr(int vpid, gva_t addr)
1983 {
1984 if (vpid == 0)
1985 return true;
1986
1987 if (cpu_has_vmx_invvpid_individual_addr()) {
1988 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR, vpid, addr);
1989 return true;
1990 }
1991
1992 return false;
1993 }
1994
1995 static inline void vpid_sync_vcpu_single(int vpid)
1996 {
1997 if (vpid == 0)
1998 return;
1999
2000 if (cpu_has_vmx_invvpid_single())
2001 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
2002 }
2003
2004 static inline void vpid_sync_vcpu_global(void)
2005 {
2006 if (cpu_has_vmx_invvpid_global())
2007 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
2008 }
2009
2010 static inline void vpid_sync_context(int vpid)
2011 {
2012 if (cpu_has_vmx_invvpid_single())
2013 vpid_sync_vcpu_single(vpid);
2014 else
2015 vpid_sync_vcpu_global();
2016 }
2017
2018 static inline void ept_sync_global(void)
2019 {
2020 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
2021 }
2022
2023 static inline void ept_sync_context(u64 eptp)
2024 {
2025 if (cpu_has_vmx_invept_context())
2026 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
2027 else
2028 ept_sync_global();
2029 }
2030
2031 static __always_inline void vmcs_check16(unsigned long field)
2032 {
2033 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2034 "16-bit accessor invalid for 64-bit field");
2035 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2036 "16-bit accessor invalid for 64-bit high field");
2037 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2038 "16-bit accessor invalid for 32-bit high field");
2039 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2040 "16-bit accessor invalid for natural width field");
2041 }
2042
2043 static __always_inline void vmcs_check32(unsigned long field)
2044 {
2045 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2046 "32-bit accessor invalid for 16-bit field");
2047 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2048 "32-bit accessor invalid for natural width field");
2049 }
2050
2051 static __always_inline void vmcs_check64(unsigned long field)
2052 {
2053 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2054 "64-bit accessor invalid for 16-bit field");
2055 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2056 "64-bit accessor invalid for 64-bit high field");
2057 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2058 "64-bit accessor invalid for 32-bit field");
2059 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2060 "64-bit accessor invalid for natural width field");
2061 }
2062
2063 static __always_inline void vmcs_checkl(unsigned long field)
2064 {
2065 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2066 "Natural width accessor invalid for 16-bit field");
2067 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2068 "Natural width accessor invalid for 64-bit field");
2069 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2070 "Natural width accessor invalid for 64-bit high field");
2071 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2072 "Natural width accessor invalid for 32-bit field");
2073 }
2074
2075 static __always_inline unsigned long __vmcs_readl(unsigned long field)
2076 {
2077 unsigned long value;
2078
2079 asm volatile (__ex_clear("vmread %1, %0", "%k0")
2080 : "=r"(value) : "r"(field));
2081 return value;
2082 }
2083
2084 static __always_inline u16 vmcs_read16(unsigned long field)
2085 {
2086 vmcs_check16(field);
2087 if (static_branch_unlikely(&enable_evmcs))
2088 return evmcs_read16(field);
2089 return __vmcs_readl(field);
2090 }
2091
2092 static __always_inline u32 vmcs_read32(unsigned long field)
2093 {
2094 vmcs_check32(field);
2095 if (static_branch_unlikely(&enable_evmcs))
2096 return evmcs_read32(field);
2097 return __vmcs_readl(field);
2098 }
2099
2100 static __always_inline u64 vmcs_read64(unsigned long field)
2101 {
2102 vmcs_check64(field);
2103 if (static_branch_unlikely(&enable_evmcs))
2104 return evmcs_read64(field);
2105 #ifdef CONFIG_X86_64
2106 return __vmcs_readl(field);
2107 #else
2108 return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
2109 #endif
2110 }
2111
2112 static __always_inline unsigned long vmcs_readl(unsigned long field)
2113 {
2114 vmcs_checkl(field);
2115 if (static_branch_unlikely(&enable_evmcs))
2116 return evmcs_read64(field);
2117 return __vmcs_readl(field);
2118 }
2119
2120 static noinline void vmwrite_error(unsigned long field, unsigned long value)
2121 {
2122 printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
2123 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
2124 dump_stack();
2125 }
2126
2127 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
2128 {
2129 bool error;
2130
2131 asm volatile (__ex("vmwrite %2, %1") CC_SET(na)
2132 : CC_OUT(na) (error) : "r"(field), "rm"(value));
2133 if (unlikely(error))
2134 vmwrite_error(field, value);
2135 }
2136
2137 static __always_inline void vmcs_write16(unsigned long field, u16 value)
2138 {
2139 vmcs_check16(field);
2140 if (static_branch_unlikely(&enable_evmcs))
2141 return evmcs_write16(field, value);
2142
2143 __vmcs_writel(field, value);
2144 }
2145
2146 static __always_inline void vmcs_write32(unsigned long field, u32 value)
2147 {
2148 vmcs_check32(field);
2149 if (static_branch_unlikely(&enable_evmcs))
2150 return evmcs_write32(field, value);
2151
2152 __vmcs_writel(field, value);
2153 }
2154
2155 static __always_inline void vmcs_write64(unsigned long field, u64 value)
2156 {
2157 vmcs_check64(field);
2158 if (static_branch_unlikely(&enable_evmcs))
2159 return evmcs_write64(field, value);
2160
2161 __vmcs_writel(field, value);
2162 #ifndef CONFIG_X86_64
2163 asm volatile ("");
2164 __vmcs_writel(field+1, value >> 32);
2165 #endif
2166 }
2167
2168 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
2169 {
2170 vmcs_checkl(field);
2171 if (static_branch_unlikely(&enable_evmcs))
2172 return evmcs_write64(field, value);
2173
2174 __vmcs_writel(field, value);
2175 }
2176
2177 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
2178 {
2179 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2180 "vmcs_clear_bits does not support 64-bit fields");
2181 if (static_branch_unlikely(&enable_evmcs))
2182 return evmcs_write32(field, evmcs_read32(field) & ~mask);
2183
2184 __vmcs_writel(field, __vmcs_readl(field) & ~mask);
2185 }
2186
2187 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
2188 {
2189 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2190 "vmcs_set_bits does not support 64-bit fields");
2191 if (static_branch_unlikely(&enable_evmcs))
2192 return evmcs_write32(field, evmcs_read32(field) | mask);
2193
2194 __vmcs_writel(field, __vmcs_readl(field) | mask);
2195 }
2196
2197 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
2198 {
2199 vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
2200 }
2201
2202 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
2203 {
2204 vmcs_write32(VM_ENTRY_CONTROLS, val);
2205 vmx->vm_entry_controls_shadow = val;
2206 }
2207
2208 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
2209 {
2210 if (vmx->vm_entry_controls_shadow != val)
2211 vm_entry_controls_init(vmx, val);
2212 }
2213
2214 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
2215 {
2216 return vmx->vm_entry_controls_shadow;
2217 }
2218
2219
2220 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2221 {
2222 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
2223 }
2224
2225 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2226 {
2227 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
2228 }
2229
2230 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
2231 {
2232 vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
2233 }
2234
2235 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
2236 {
2237 vmcs_write32(VM_EXIT_CONTROLS, val);
2238 vmx->vm_exit_controls_shadow = val;
2239 }
2240
2241 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
2242 {
2243 if (vmx->vm_exit_controls_shadow != val)
2244 vm_exit_controls_init(vmx, val);
2245 }
2246
2247 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
2248 {
2249 return vmx->vm_exit_controls_shadow;
2250 }
2251
2252
2253 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2254 {
2255 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
2256 }
2257
2258 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2259 {
2260 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
2261 }
2262
2263 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
2264 {
2265 vmx->segment_cache.bitmask = 0;
2266 }
2267
2268 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
2269 unsigned field)
2270 {
2271 bool ret;
2272 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
2273
2274 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
2275 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
2276 vmx->segment_cache.bitmask = 0;
2277 }
2278 ret = vmx->segment_cache.bitmask & mask;
2279 vmx->segment_cache.bitmask |= mask;
2280 return ret;
2281 }
2282
2283 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
2284 {
2285 u16 *p = &vmx->segment_cache.seg[seg].selector;
2286
2287 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
2288 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
2289 return *p;
2290 }
2291
2292 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
2293 {
2294 ulong *p = &vmx->segment_cache.seg[seg].base;
2295
2296 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
2297 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
2298 return *p;
2299 }
2300
2301 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
2302 {
2303 u32 *p = &vmx->segment_cache.seg[seg].limit;
2304
2305 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
2306 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
2307 return *p;
2308 }
2309
2310 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
2311 {
2312 u32 *p = &vmx->segment_cache.seg[seg].ar;
2313
2314 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
2315 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
2316 return *p;
2317 }
2318
2319 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
2320 {
2321 u32 eb;
2322
2323 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
2324 (1u << DB_VECTOR) | (1u << AC_VECTOR);
2325 /*
2326 * Guest access to VMware backdoor ports could legitimately
2327 * trigger #GP because of TSS I/O permission bitmap.
2328 * We intercept those #GP and allow access to them anyway
2329 * as VMware does.
2330 */
2331 if (enable_vmware_backdoor)
2332 eb |= (1u << GP_VECTOR);
2333 if ((vcpu->guest_debug &
2334 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
2335 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
2336 eb |= 1u << BP_VECTOR;
2337 if (to_vmx(vcpu)->rmode.vm86_active)
2338 eb = ~0;
2339 if (enable_ept)
2340 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
2341
2342 /* When we are running a nested L2 guest and L1 specified for it a
2343 * certain exception bitmap, we must trap the same exceptions and pass
2344 * them to L1. When running L2, we will only handle the exceptions
2345 * specified above if L1 did not want them.
2346 */
2347 if (is_guest_mode(vcpu))
2348 eb |= get_vmcs12(vcpu)->exception_bitmap;
2349
2350 vmcs_write32(EXCEPTION_BITMAP, eb);
2351 }
2352
2353 /*
2354 * Check if MSR is intercepted for currently loaded MSR bitmap.
2355 */
2356 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2357 {
2358 unsigned long *msr_bitmap;
2359 int f = sizeof(unsigned long);
2360
2361 if (!cpu_has_vmx_msr_bitmap())
2362 return true;
2363
2364 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2365
2366 if (msr <= 0x1fff) {
2367 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2368 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2369 msr &= 0x1fff;
2370 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2371 }
2372
2373 return true;
2374 }
2375
2376 /*
2377 * Check if MSR is intercepted for L01 MSR bitmap.
2378 */
2379 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2380 {
2381 unsigned long *msr_bitmap;
2382 int f = sizeof(unsigned long);
2383
2384 if (!cpu_has_vmx_msr_bitmap())
2385 return true;
2386
2387 msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2388
2389 if (msr <= 0x1fff) {
2390 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2391 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2392 msr &= 0x1fff;
2393 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2394 }
2395
2396 return true;
2397 }
2398
2399 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2400 unsigned long entry, unsigned long exit)
2401 {
2402 vm_entry_controls_clearbit(vmx, entry);
2403 vm_exit_controls_clearbit(vmx, exit);
2404 }
2405
2406 static int find_msr(struct vmx_msrs *m, unsigned int msr)
2407 {
2408 unsigned int i;
2409
2410 for (i = 0; i < m->nr; ++i) {
2411 if (m->val[i].index == msr)
2412 return i;
2413 }
2414 return -ENOENT;
2415 }
2416
2417 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2418 {
2419 int i;
2420 struct msr_autoload *m = &vmx->msr_autoload;
2421
2422 switch (msr) {
2423 case MSR_EFER:
2424 if (cpu_has_load_ia32_efer()) {
2425 clear_atomic_switch_msr_special(vmx,
2426 VM_ENTRY_LOAD_IA32_EFER,
2427 VM_EXIT_LOAD_IA32_EFER);
2428 return;
2429 }
2430 break;
2431 case MSR_CORE_PERF_GLOBAL_CTRL:
2432 if (cpu_has_load_perf_global_ctrl()) {
2433 clear_atomic_switch_msr_special(vmx,
2434 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2435 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2436 return;
2437 }
2438 break;
2439 }
2440 i = find_msr(&m->guest, msr);
2441 if (i < 0)
2442 goto skip_guest;
2443 --m->guest.nr;
2444 m->guest.val[i] = m->guest.val[m->guest.nr];
2445 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2446
2447 skip_guest:
2448 i = find_msr(&m->host, msr);
2449 if (i < 0)
2450 return;
2451
2452 --m->host.nr;
2453 m->host.val[i] = m->host.val[m->host.nr];
2454 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2455 }
2456
2457 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2458 unsigned long entry, unsigned long exit,
2459 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2460 u64 guest_val, u64 host_val)
2461 {
2462 vmcs_write64(guest_val_vmcs, guest_val);
2463 if (host_val_vmcs != HOST_IA32_EFER)
2464 vmcs_write64(host_val_vmcs, host_val);
2465 vm_entry_controls_setbit(vmx, entry);
2466 vm_exit_controls_setbit(vmx, exit);
2467 }
2468
2469 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2470 u64 guest_val, u64 host_val, bool entry_only)
2471 {
2472 int i, j = 0;
2473 struct msr_autoload *m = &vmx->msr_autoload;
2474
2475 switch (msr) {
2476 case MSR_EFER:
2477 if (cpu_has_load_ia32_efer()) {
2478 add_atomic_switch_msr_special(vmx,
2479 VM_ENTRY_LOAD_IA32_EFER,
2480 VM_EXIT_LOAD_IA32_EFER,
2481 GUEST_IA32_EFER,
2482 HOST_IA32_EFER,
2483 guest_val, host_val);
2484 return;
2485 }
2486 break;
2487 case MSR_CORE_PERF_GLOBAL_CTRL:
2488 if (cpu_has_load_perf_global_ctrl()) {
2489 add_atomic_switch_msr_special(vmx,
2490 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2491 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2492 GUEST_IA32_PERF_GLOBAL_CTRL,
2493 HOST_IA32_PERF_GLOBAL_CTRL,
2494 guest_val, host_val);
2495 return;
2496 }
2497 break;
2498 case MSR_IA32_PEBS_ENABLE:
2499 /* PEBS needs a quiescent period after being disabled (to write
2500 * a record). Disabling PEBS through VMX MSR swapping doesn't
2501 * provide that period, so a CPU could write host's record into
2502 * guest's memory.
2503 */
2504 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2505 }
2506
2507 i = find_msr(&m->guest, msr);
2508 if (!entry_only)
2509 j = find_msr(&m->host, msr);
2510
2511 if (i == NR_AUTOLOAD_MSRS || j == NR_AUTOLOAD_MSRS) {
2512 printk_once(KERN_WARNING "Not enough msr switch entries. "
2513 "Can't add msr %x\n", msr);
2514 return;
2515 }
2516 if (i < 0) {
2517 i = m->guest.nr++;
2518 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2519 }
2520 m->guest.val[i].index = msr;
2521 m->guest.val[i].value = guest_val;
2522
2523 if (entry_only)
2524 return;
2525
2526 if (j < 0) {
2527 j = m->host.nr++;
2528 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2529 }
2530 m->host.val[j].index = msr;
2531 m->host.val[j].value = host_val;
2532 }
2533
2534 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2535 {
2536 u64 guest_efer = vmx->vcpu.arch.efer;
2537 u64 ignore_bits = 0;
2538
2539 if (!enable_ept) {
2540 /*
2541 * NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
2542 * host CPUID is more efficient than testing guest CPUID
2543 * or CR4. Host SMEP is anyway a requirement for guest SMEP.
2544 */
2545 if (boot_cpu_has(X86_FEATURE_SMEP))
2546 guest_efer |= EFER_NX;
2547 else if (!(guest_efer & EFER_NX))
2548 ignore_bits |= EFER_NX;
2549 }
2550
2551 /*
2552 * LMA and LME handled by hardware; SCE meaningless outside long mode.
2553 */
2554 ignore_bits |= EFER_SCE;
2555 #ifdef CONFIG_X86_64
2556 ignore_bits |= EFER_LMA | EFER_LME;
2557 /* SCE is meaningful only in long mode on Intel */
2558 if (guest_efer & EFER_LMA)
2559 ignore_bits &= ~(u64)EFER_SCE;
2560 #endif
2561
2562 /*
2563 * On EPT, we can't emulate NX, so we must switch EFER atomically.
2564 * On CPUs that support "load IA32_EFER", always switch EFER
2565 * atomically, since it's faster than switching it manually.
2566 */
2567 if (cpu_has_load_ia32_efer() ||
2568 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2569 if (!(guest_efer & EFER_LMA))
2570 guest_efer &= ~EFER_LME;
2571 if (guest_efer != host_efer)
2572 add_atomic_switch_msr(vmx, MSR_EFER,
2573 guest_efer, host_efer, false);
2574 else
2575 clear_atomic_switch_msr(vmx, MSR_EFER);
2576 return false;
2577 } else {
2578 clear_atomic_switch_msr(vmx, MSR_EFER);
2579
2580 guest_efer &= ~ignore_bits;
2581 guest_efer |= host_efer & ignore_bits;
2582
2583 vmx->guest_msrs[efer_offset].data = guest_efer;
2584 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2585
2586 return true;
2587 }
2588 }
2589
2590 #ifdef CONFIG_X86_32
2591 /*
2592 * On 32-bit kernels, VM exits still load the FS and GS bases from the
2593 * VMCS rather than the segment table. KVM uses this helper to figure
2594 * out the current bases to poke them into the VMCS before entry.
2595 */
2596 static unsigned long segment_base(u16 selector)
2597 {
2598 struct desc_struct *table;
2599 unsigned long v;
2600
2601 if (!(selector & ~SEGMENT_RPL_MASK))
2602 return 0;
2603
2604 table = get_current_gdt_ro();
2605
2606 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2607 u16 ldt_selector = kvm_read_ldt();
2608
2609 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2610 return 0;
2611
2612 table = (struct desc_struct *)segment_base(ldt_selector);
2613 }
2614 v = get_desc_base(&table[selector >> 3]);
2615 return v;
2616 }
2617 #endif
2618
2619 static void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
2620 {
2621 struct vcpu_vmx *vmx = to_vmx(vcpu);
2622 struct vmcs_host_state *host_state;
2623 #ifdef CONFIG_X86_64
2624 int cpu = raw_smp_processor_id();
2625 #endif
2626 unsigned long fs_base, gs_base;
2627 u16 fs_sel, gs_sel;
2628 int i;
2629
2630 vmx->req_immediate_exit = false;
2631
2632 /*
2633 * Note that guest MSRs to be saved/restored can also be changed
2634 * when guest state is loaded. This happens when guest transitions
2635 * to/from long-mode by setting MSR_EFER.LMA.
2636 */
2637 if (!vmx->loaded_cpu_state || vmx->guest_msrs_dirty) {
2638 vmx->guest_msrs_dirty = false;
2639 for (i = 0; i < vmx->save_nmsrs; ++i)
2640 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2641 vmx->guest_msrs[i].data,
2642 vmx->guest_msrs[i].mask);
2643
2644 }
2645
2646 if (vmx->loaded_cpu_state)
2647 return;
2648
2649 vmx->loaded_cpu_state = vmx->loaded_vmcs;
2650 host_state = &vmx->loaded_cpu_state->host_state;
2651
2652 /*
2653 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
2654 * allow segment selectors with cpl > 0 or ti == 1.
2655 */
2656 host_state->ldt_sel = kvm_read_ldt();
2657
2658 #ifdef CONFIG_X86_64
2659 savesegment(ds, host_state->ds_sel);
2660 savesegment(es, host_state->es_sel);
2661
2662 gs_base = cpu_kernelmode_gs_base(cpu);
2663 if (likely(is_64bit_mm(current->mm))) {
2664 save_fsgs_for_kvm();
2665 fs_sel = current->thread.fsindex;
2666 gs_sel = current->thread.gsindex;
2667 fs_base = current->thread.fsbase;
2668 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
2669 } else {
2670 savesegment(fs, fs_sel);
2671 savesegment(gs, gs_sel);
2672 fs_base = read_msr(MSR_FS_BASE);
2673 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
2674 }
2675
2676 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2677 #else
2678 savesegment(fs, fs_sel);
2679 savesegment(gs, gs_sel);
2680 fs_base = segment_base(fs_sel);
2681 gs_base = segment_base(gs_sel);
2682 #endif
2683
2684 if (unlikely(fs_sel != host_state->fs_sel)) {
2685 if (!(fs_sel & 7))
2686 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
2687 else
2688 vmcs_write16(HOST_FS_SELECTOR, 0);
2689 host_state->fs_sel = fs_sel;
2690 }
2691 if (unlikely(gs_sel != host_state->gs_sel)) {
2692 if (!(gs_sel & 7))
2693 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
2694 else
2695 vmcs_write16(HOST_GS_SELECTOR, 0);
2696 host_state->gs_sel = gs_sel;
2697 }
2698 if (unlikely(fs_base != host_state->fs_base)) {
2699 vmcs_writel(HOST_FS_BASE, fs_base);
2700 host_state->fs_base = fs_base;
2701 }
2702 if (unlikely(gs_base != host_state->gs_base)) {
2703 vmcs_writel(HOST_GS_BASE, gs_base);
2704 host_state->gs_base = gs_base;
2705 }
2706 }
2707
2708 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
2709 {
2710 struct vmcs_host_state *host_state;
2711
2712 if (!vmx->loaded_cpu_state)
2713 return;
2714
2715 WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
2716 host_state = &vmx->loaded_cpu_state->host_state;
2717
2718 ++vmx->vcpu.stat.host_state_reload;
2719 vmx->loaded_cpu_state = NULL;
2720
2721 #ifdef CONFIG_X86_64
2722 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2723 #endif
2724 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
2725 kvm_load_ldt(host_state->ldt_sel);
2726 #ifdef CONFIG_X86_64
2727 load_gs_index(host_state->gs_sel);
2728 #else
2729 loadsegment(gs, host_state->gs_sel);
2730 #endif
2731 }
2732 if (host_state->fs_sel & 7)
2733 loadsegment(fs, host_state->fs_sel);
2734 #ifdef CONFIG_X86_64
2735 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
2736 loadsegment(ds, host_state->ds_sel);
2737 loadsegment(es, host_state->es_sel);
2738 }
2739 #endif
2740 invalidate_tss_limit();
2741 #ifdef CONFIG_X86_64
2742 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2743 #endif
2744 load_fixmap_gdt(raw_smp_processor_id());
2745 }
2746
2747 #ifdef CONFIG_X86_64
2748 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
2749 {
2750 preempt_disable();
2751 if (vmx->loaded_cpu_state)
2752 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2753 preempt_enable();
2754 return vmx->msr_guest_kernel_gs_base;
2755 }
2756
2757 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
2758 {
2759 preempt_disable();
2760 if (vmx->loaded_cpu_state)
2761 wrmsrl(MSR_KERNEL_GS_BASE, data);
2762 preempt_enable();
2763 vmx->msr_guest_kernel_gs_base = data;
2764 }
2765 #endif
2766
2767 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2768 {
2769 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2770 struct pi_desc old, new;
2771 unsigned int dest;
2772
2773 /*
2774 * In case of hot-plug or hot-unplug, we may have to undo
2775 * vmx_vcpu_pi_put even if there is no assigned device. And we
2776 * always keep PI.NDST up to date for simplicity: it makes the
2777 * code easier, and CPU migration is not a fast path.
2778 */
2779 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
2780 return;
2781
2782 /*
2783 * First handle the simple case where no cmpxchg is necessary; just
2784 * allow posting non-urgent interrupts.
2785 *
2786 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
2787 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
2788 * expects the VCPU to be on the blocked_vcpu_list that matches
2789 * PI.NDST.
2790 */
2791 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
2792 vcpu->cpu == cpu) {
2793 pi_clear_sn(pi_desc);
2794 return;
2795 }
2796
2797 /* The full case. */
2798 do {
2799 old.control = new.control = pi_desc->control;
2800
2801 dest = cpu_physical_id(cpu);
2802
2803 if (x2apic_enabled())
2804 new.ndst = dest;
2805 else
2806 new.ndst = (dest << 8) & 0xFF00;
2807
2808 new.sn = 0;
2809 } while (cmpxchg64(&pi_desc->control, old.control,
2810 new.control) != old.control);
2811 }
2812
2813 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2814 {
2815 vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2816 vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2817 }
2818
2819 /*
2820 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2821 * vcpu mutex is already taken.
2822 */
2823 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2824 {
2825 struct vcpu_vmx *vmx = to_vmx(vcpu);
2826 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2827
2828 if (!already_loaded) {
2829 loaded_vmcs_clear(vmx->loaded_vmcs);
2830 local_irq_disable();
2831 crash_disable_local_vmclear(cpu);
2832
2833 /*
2834 * Read loaded_vmcs->cpu should be before fetching
2835 * loaded_vmcs->loaded_vmcss_on_cpu_link.
2836 * See the comments in __loaded_vmcs_clear().
2837 */
2838 smp_rmb();
2839
2840 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2841 &per_cpu(loaded_vmcss_on_cpu, cpu));
2842 crash_enable_local_vmclear(cpu);
2843 local_irq_enable();
2844 }
2845
2846 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2847 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2848 vmcs_load(vmx->loaded_vmcs->vmcs);
2849 indirect_branch_prediction_barrier();
2850 }
2851
2852 if (!already_loaded) {
2853 void *gdt = get_current_gdt_ro();
2854 unsigned long sysenter_esp;
2855
2856 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2857
2858 /*
2859 * Linux uses per-cpu TSS and GDT, so set these when switching
2860 * processors. See 22.2.4.
2861 */
2862 vmcs_writel(HOST_TR_BASE,
2863 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
2864 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
2865
2866 /*
2867 * VM exits change the host TR limit to 0x67 after a VM
2868 * exit. This is okay, since 0x67 covers everything except
2869 * the IO bitmap and have have code to handle the IO bitmap
2870 * being lost after a VM exit.
2871 */
2872 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
2873
2874 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2875 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2876
2877 vmx->loaded_vmcs->cpu = cpu;
2878 }
2879
2880 /* Setup TSC multiplier */
2881 if (kvm_has_tsc_control &&
2882 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2883 decache_tsc_multiplier(vmx);
2884
2885 vmx_vcpu_pi_load(vcpu, cpu);
2886 vmx->host_pkru = read_pkru();
2887 vmx->host_debugctlmsr = get_debugctlmsr();
2888 }
2889
2890 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2891 {
2892 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2893
2894 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2895 !irq_remapping_cap(IRQ_POSTING_CAP) ||
2896 !kvm_vcpu_apicv_active(vcpu))
2897 return;
2898
2899 /* Set SN when the vCPU is preempted */
2900 if (vcpu->preempted)
2901 pi_set_sn(pi_desc);
2902 }
2903
2904 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2905 {
2906 vmx_vcpu_pi_put(vcpu);
2907
2908 vmx_prepare_switch_to_host(to_vmx(vcpu));
2909 }
2910
2911 static bool emulation_required(struct kvm_vcpu *vcpu)
2912 {
2913 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
2914 }
2915
2916 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
2917
2918 /*
2919 * Return the cr0 value that a nested guest would read. This is a combination
2920 * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
2921 * its hypervisor (cr0_read_shadow).
2922 */
2923 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
2924 {
2925 return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
2926 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
2927 }
2928 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
2929 {
2930 return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
2931 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
2932 }
2933
2934 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2935 {
2936 unsigned long rflags, save_rflags;
2937
2938 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2939 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2940 rflags = vmcs_readl(GUEST_RFLAGS);
2941 if (to_vmx(vcpu)->rmode.vm86_active) {
2942 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2943 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2944 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2945 }
2946 to_vmx(vcpu)->rflags = rflags;
2947 }
2948 return to_vmx(vcpu)->rflags;
2949 }
2950
2951 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2952 {
2953 unsigned long old_rflags = vmx_get_rflags(vcpu);
2954
2955 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2956 to_vmx(vcpu)->rflags = rflags;
2957 if (to_vmx(vcpu)->rmode.vm86_active) {
2958 to_vmx(vcpu)->rmode.save_rflags = rflags;
2959 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2960 }
2961 vmcs_writel(GUEST_RFLAGS, rflags);
2962
2963 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
2964 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
2965 }
2966
2967 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2968 {
2969 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2970 int ret = 0;
2971
2972 if (interruptibility & GUEST_INTR_STATE_STI)
2973 ret |= KVM_X86_SHADOW_INT_STI;
2974 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2975 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2976
2977 return ret;
2978 }
2979
2980 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2981 {
2982 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2983 u32 interruptibility = interruptibility_old;
2984
2985 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2986
2987 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2988 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2989 else if (mask & KVM_X86_SHADOW_INT_STI)
2990 interruptibility |= GUEST_INTR_STATE_STI;
2991
2992 if ((interruptibility != interruptibility_old))
2993 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2994 }
2995
2996 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2997 {
2998 unsigned long rip;
2999
3000 rip = kvm_rip_read(vcpu);
3001 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3002 kvm_rip_write(vcpu, rip);
3003
3004 /* skipping an emulated instruction also counts */
3005 vmx_set_interrupt_shadow(vcpu, 0);
3006 }
3007
3008 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3009 unsigned long exit_qual)
3010 {
3011 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3012 unsigned int nr = vcpu->arch.exception.nr;
3013 u32 intr_info = nr | INTR_INFO_VALID_MASK;
3014
3015 if (vcpu->arch.exception.has_error_code) {
3016 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3017 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3018 }
3019
3020 if (kvm_exception_is_soft(nr))
3021 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3022 else
3023 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3024
3025 if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3026 vmx_get_nmi_mask(vcpu))
3027 intr_info |= INTR_INFO_UNBLOCK_NMI;
3028
3029 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3030 }
3031
3032 /*
3033 * KVM wants to inject page-faults which it got to the guest. This function
3034 * checks whether in a nested guest, we need to inject them to L1 or L2.
3035 */
3036 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
3037 {
3038 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3039 unsigned int nr = vcpu->arch.exception.nr;
3040 bool has_payload = vcpu->arch.exception.has_payload;
3041 unsigned long payload = vcpu->arch.exception.payload;
3042
3043 if (nr == PF_VECTOR) {
3044 if (vcpu->arch.exception.nested_apf) {
3045 *exit_qual = vcpu->arch.apf.nested_apf_token;
3046 return 1;
3047 }
3048 if (nested_vmx_is_page_fault_vmexit(vmcs12,
3049 vcpu->arch.exception.error_code)) {
3050 *exit_qual = has_payload ? payload : vcpu->arch.cr2;
3051 return 1;
3052 }
3053 } else if (vmcs12->exception_bitmap & (1u << nr)) {
3054 if (nr == DB_VECTOR) {
3055 if (!has_payload) {
3056 payload = vcpu->arch.dr6;
3057 payload &= ~(DR6_FIXED_1 | DR6_BT);
3058 payload ^= DR6_RTM;
3059 }
3060 *exit_qual = payload;
3061 } else
3062 *exit_qual = 0;
3063 return 1;
3064 }
3065
3066 return 0;
3067 }
3068
3069 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
3070 {
3071 /*
3072 * Ensure that we clear the HLT state in the VMCS. We don't need to
3073 * explicitly skip the instruction because if the HLT state is set,
3074 * then the instruction is already executing and RIP has already been
3075 * advanced.
3076 */
3077 if (kvm_hlt_in_guest(vcpu->kvm) &&
3078 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
3079 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3080 }
3081
3082 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
3083 {
3084 struct vcpu_vmx *vmx = to_vmx(vcpu);
3085 unsigned nr = vcpu->arch.exception.nr;
3086 bool has_error_code = vcpu->arch.exception.has_error_code;
3087 u32 error_code = vcpu->arch.exception.error_code;
3088 u32 intr_info = nr | INTR_INFO_VALID_MASK;
3089
3090 kvm_deliver_exception_payload(vcpu);
3091
3092 if (has_error_code) {
3093 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
3094 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3095 }
3096
3097 if (vmx->rmode.vm86_active) {
3098 int inc_eip = 0;
3099 if (kvm_exception_is_soft(nr))
3100 inc_eip = vcpu->arch.event_exit_inst_len;
3101 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
3102 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3103 return;
3104 }
3105
3106 WARN_ON_ONCE(vmx->emulation_required);
3107
3108 if (kvm_exception_is_soft(nr)) {
3109 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
3110 vmx->vcpu.arch.event_exit_inst_len);
3111 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3112 } else
3113 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3114
3115 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
3116
3117 vmx_clear_hlt(vcpu);
3118 }
3119
3120 static bool vmx_rdtscp_supported(void)
3121 {
3122 return cpu_has_vmx_rdtscp();
3123 }
3124
3125 static bool vmx_invpcid_supported(void)
3126 {
3127 return cpu_has_vmx_invpcid();
3128 }
3129
3130 /*
3131 * Swap MSR entry in host/guest MSR entry array.
3132 */
3133 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
3134 {
3135 struct shared_msr_entry tmp;
3136
3137 tmp = vmx->guest_msrs[to];
3138 vmx->guest_msrs[to] = vmx->guest_msrs[from];
3139 vmx->guest_msrs[from] = tmp;
3140 }
3141
3142 /*
3143 * Set up the vmcs to automatically save and restore system
3144 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
3145 * mode, as fiddling with msrs is very expensive.
3146 */
3147 static void setup_msrs(struct vcpu_vmx *vmx)
3148 {
3149 int save_nmsrs, index;
3150
3151 save_nmsrs = 0;
3152 #ifdef CONFIG_X86_64
3153 if (is_long_mode(&vmx->vcpu)) {
3154 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
3155 if (index >= 0)
3156 move_msr_up(vmx, index, save_nmsrs++);
3157 index = __find_msr_index(vmx, MSR_LSTAR);
3158 if (index >= 0)
3159 move_msr_up(vmx, index, save_nmsrs++);
3160 index = __find_msr_index(vmx, MSR_CSTAR);
3161 if (index >= 0)
3162 move_msr_up(vmx, index, save_nmsrs++);
3163 index = __find_msr_index(vmx, MSR_TSC_AUX);
3164 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
3165 move_msr_up(vmx, index, save_nmsrs++);
3166 /*
3167 * MSR_STAR is only needed on long mode guests, and only
3168 * if efer.sce is enabled.
3169 */
3170 index = __find_msr_index(vmx, MSR_STAR);
3171 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
3172 move_msr_up(vmx, index, save_nmsrs++);
3173 }
3174 #endif
3175 index = __find_msr_index(vmx, MSR_EFER);
3176 if (index >= 0 && update_transition_efer(vmx, index))
3177 move_msr_up(vmx, index, save_nmsrs++);
3178
3179 vmx->save_nmsrs = save_nmsrs;
3180 vmx->guest_msrs_dirty = true;
3181
3182 if (cpu_has_vmx_msr_bitmap())
3183 vmx_update_msr_bitmap(&vmx->vcpu);
3184 }
3185
3186 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
3187 {
3188 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3189
3190 if (is_guest_mode(vcpu) &&
3191 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
3192 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
3193
3194 return vcpu->arch.tsc_offset;
3195 }
3196
3197 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
3198 {
3199 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3200 u64 g_tsc_offset = 0;
3201
3202 /*
3203 * We're here if L1 chose not to trap WRMSR to TSC. According
3204 * to the spec, this should set L1's TSC; The offset that L1
3205 * set for L2 remains unchanged, and still needs to be added
3206 * to the newly set TSC to get L2's TSC.
3207 */
3208 if (is_guest_mode(vcpu) &&
3209 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
3210 g_tsc_offset = vmcs12->tsc_offset;
3211
3212 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
3213 vcpu->arch.tsc_offset - g_tsc_offset,
3214 offset);
3215 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
3216 return offset + g_tsc_offset;
3217 }
3218
3219 /*
3220 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
3221 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
3222 * all guests if the "nested" module option is off, and can also be disabled
3223 * for a single guest by disabling its VMX cpuid bit.
3224 */
3225 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
3226 {
3227 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
3228 }
3229
3230 /*
3231 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
3232 * returned for the various VMX controls MSRs when nested VMX is enabled.
3233 * The same values should also be used to verify that vmcs12 control fields are
3234 * valid during nested entry from L1 to L2.
3235 * Each of these control msrs has a low and high 32-bit half: A low bit is on
3236 * if the corresponding bit in the (32-bit) control field *must* be on, and a
3237 * bit in the high half is on if the corresponding bit in the control field
3238 * may be on. See also vmx_control_verify().
3239 */
3240 static void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs,
3241 u32 ept_caps, bool apicv)
3242 {
3243 if (!nested) {
3244 memset(msrs, 0, sizeof(*msrs));
3245 return;
3246 }
3247
3248 /*
3249 * Note that as a general rule, the high half of the MSRs (bits in
3250 * the control fields which may be 1) should be initialized by the
3251 * intersection of the underlying hardware's MSR (i.e., features which
3252 * can be supported) and the list of features we want to expose -
3253 * because they are known to be properly supported in our code.
3254 * Also, usually, the low half of the MSRs (bits which must be 1) can
3255 * be set to 0, meaning that L1 may turn off any of these bits. The
3256 * reason is that if one of these bits is necessary, it will appear
3257 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
3258 * fields of vmcs01 and vmcs02, will turn these bits off - and
3259 * nested_vmx_exit_reflected() will not pass related exits to L1.
3260 * These rules have exceptions below.
3261 */
3262
3263 /* pin-based controls */
3264 rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
3265 msrs->pinbased_ctls_low,
3266 msrs->pinbased_ctls_high);
3267 msrs->pinbased_ctls_low |=
3268 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3269 msrs->pinbased_ctls_high &=
3270 PIN_BASED_EXT_INTR_MASK |
3271 PIN_BASED_NMI_EXITING |
3272 PIN_BASED_VIRTUAL_NMIS |
3273 (apicv ? PIN_BASED_POSTED_INTR : 0);
3274 msrs->pinbased_ctls_high |=
3275 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3276 PIN_BASED_VMX_PREEMPTION_TIMER;
3277
3278 /* exit controls */
3279 rdmsr(MSR_IA32_VMX_EXIT_CTLS,
3280 msrs->exit_ctls_low,
3281 msrs->exit_ctls_high);
3282 msrs->exit_ctls_low =
3283 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3284
3285 msrs->exit_ctls_high &=
3286 #ifdef CONFIG_X86_64
3287 VM_EXIT_HOST_ADDR_SPACE_SIZE |
3288 #endif
3289 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
3290 msrs->exit_ctls_high |=
3291 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
3292 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
3293 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
3294
3295 /* We support free control of debug control saving. */
3296 msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
3297
3298 /* entry controls */
3299 rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
3300 msrs->entry_ctls_low,
3301 msrs->entry_ctls_high);
3302 msrs->entry_ctls_low =
3303 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3304 msrs->entry_ctls_high &=
3305 #ifdef CONFIG_X86_64
3306 VM_ENTRY_IA32E_MODE |
3307 #endif
3308 VM_ENTRY_LOAD_IA32_PAT;
3309 msrs->entry_ctls_high |=
3310 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
3311
3312 /* We support free control of debug control loading. */
3313 msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
3314
3315 /* cpu-based controls */
3316 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
3317 msrs->procbased_ctls_low,
3318 msrs->procbased_ctls_high);
3319 msrs->procbased_ctls_low =
3320 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3321 msrs->procbased_ctls_high &=
3322 CPU_BASED_VIRTUAL_INTR_PENDING |
3323 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
3324 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
3325 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
3326 CPU_BASED_CR3_STORE_EXITING |
3327 #ifdef CONFIG_X86_64
3328 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
3329 #endif
3330 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
3331 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
3332 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
3333 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
3334 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3335 /*
3336 * We can allow some features even when not supported by the
3337 * hardware. For example, L1 can specify an MSR bitmap - and we
3338 * can use it to avoid exits to L1 - even when L0 runs L2
3339 * without MSR bitmaps.
3340 */
3341 msrs->procbased_ctls_high |=
3342 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3343 CPU_BASED_USE_MSR_BITMAPS;
3344
3345 /* We support free control of CR3 access interception. */
3346 msrs->procbased_ctls_low &=
3347 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
3348
3349 /*
3350 * secondary cpu-based controls. Do not include those that
3351 * depend on CPUID bits, they are added later by vmx_cpuid_update.
3352 */
3353 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
3354 msrs->secondary_ctls_low,
3355 msrs->secondary_ctls_high);
3356 msrs->secondary_ctls_low = 0;
3357 msrs->secondary_ctls_high &=
3358 SECONDARY_EXEC_DESC |
3359 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3360 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3361 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3362 SECONDARY_EXEC_WBINVD_EXITING;
3363
3364 /*
3365 * We can emulate "VMCS shadowing," even if the hardware
3366 * doesn't support it.
3367 */
3368 msrs->secondary_ctls_high |=
3369 SECONDARY_EXEC_SHADOW_VMCS;
3370
3371 if (enable_ept) {
3372 /* nested EPT: emulate EPT also to L1 */
3373 msrs->secondary_ctls_high |=
3374 SECONDARY_EXEC_ENABLE_EPT;
3375 msrs->ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
3376 VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
3377 if (cpu_has_vmx_ept_execute_only())
3378 msrs->ept_caps |=
3379 VMX_EPT_EXECUTE_ONLY_BIT;
3380 msrs->ept_caps &= ept_caps;
3381 msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
3382 VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
3383 VMX_EPT_1GB_PAGE_BIT;
3384 if (enable_ept_ad_bits) {
3385 msrs->secondary_ctls_high |=
3386 SECONDARY_EXEC_ENABLE_PML;
3387 msrs->ept_caps |= VMX_EPT_AD_BIT;
3388 }
3389 }
3390
3391 if (cpu_has_vmx_vmfunc()) {
3392 msrs->secondary_ctls_high |=
3393 SECONDARY_EXEC_ENABLE_VMFUNC;
3394 /*
3395 * Advertise EPTP switching unconditionally
3396 * since we emulate it
3397 */
3398 if (enable_ept)
3399 msrs->vmfunc_controls =
3400 VMX_VMFUNC_EPTP_SWITCHING;
3401 }
3402
3403 /*
3404 * Old versions of KVM use the single-context version without
3405 * checking for support, so declare that it is supported even
3406 * though it is treated as global context. The alternative is
3407 * not failing the single-context invvpid, and it is worse.
3408 */
3409 if (enable_vpid) {
3410 msrs->secondary_ctls_high |=
3411 SECONDARY_EXEC_ENABLE_VPID;
3412 msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
3413 VMX_VPID_EXTENT_SUPPORTED_MASK;
3414 }
3415
3416 if (enable_unrestricted_guest)
3417 msrs->secondary_ctls_high |=
3418 SECONDARY_EXEC_UNRESTRICTED_GUEST;
3419
3420 if (flexpriority_enabled)
3421 msrs->secondary_ctls_high |=
3422 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3423
3424 /* miscellaneous data */
3425 rdmsr(MSR_IA32_VMX_MISC,
3426 msrs->misc_low,
3427 msrs->misc_high);
3428 msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
3429 msrs->misc_low |=
3430 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
3431 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
3432 VMX_MISC_ACTIVITY_HLT;
3433 msrs->misc_high = 0;
3434
3435 /*
3436 * This MSR reports some information about VMX support. We
3437 * should return information about the VMX we emulate for the
3438 * guest, and the VMCS structure we give it - not about the
3439 * VMX support of the underlying hardware.
3440 */
3441 msrs->basic =
3442 VMCS12_REVISION |
3443 VMX_BASIC_TRUE_CTLS |
3444 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
3445 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
3446
3447 if (cpu_has_vmx_basic_inout())
3448 msrs->basic |= VMX_BASIC_INOUT;
3449
3450 /*
3451 * These MSRs specify bits which the guest must keep fixed on
3452 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
3453 * We picked the standard core2 setting.
3454 */
3455 #define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
3456 #define VMXON_CR4_ALWAYSON X86_CR4_VMXE
3457 msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
3458 msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
3459
3460 /* These MSRs specify bits which the guest must keep fixed off. */
3461 rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
3462 rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
3463
3464 /* highest index: VMX_PREEMPTION_TIMER_VALUE */
3465 msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
3466 }
3467
3468 /*
3469 * if fixed0[i] == 1: val[i] must be 1
3470 * if fixed1[i] == 0: val[i] must be 0
3471 */
3472 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
3473 {
3474 return ((val & fixed1) | fixed0) == val;
3475 }
3476
3477 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
3478 {
3479 return fixed_bits_valid(control, low, high);
3480 }
3481
3482 static inline u64 vmx_control_msr(u32 low, u32 high)
3483 {
3484 return low | ((u64)high << 32);
3485 }
3486
3487 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
3488 {
3489 superset &= mask;
3490 subset &= mask;
3491
3492 return (superset | subset) == superset;
3493 }
3494
3495 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
3496 {
3497 const u64 feature_and_reserved =
3498 /* feature (except bit 48; see below) */
3499 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
3500 /* reserved */
3501 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
3502 u64 vmx_basic = vmx->nested.msrs.basic;
3503
3504 if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
3505 return -EINVAL;
3506
3507 /*
3508 * KVM does not emulate a version of VMX that constrains physical
3509 * addresses of VMX structures (e.g. VMCS) to 32-bits.
3510 */
3511 if (data & BIT_ULL(48))
3512 return -EINVAL;
3513
3514 if (vmx_basic_vmcs_revision_id(vmx_basic) !=
3515 vmx_basic_vmcs_revision_id(data))
3516 return -EINVAL;
3517
3518 if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
3519 return -EINVAL;
3520
3521 vmx->nested.msrs.basic = data;
3522 return 0;
3523 }
3524
3525 static int
3526 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3527 {
3528 u64 supported;
3529 u32 *lowp, *highp;
3530
3531 switch (msr_index) {
3532 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3533 lowp = &vmx->nested.msrs.pinbased_ctls_low;
3534 highp = &vmx->nested.msrs.pinbased_ctls_high;
3535 break;
3536 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3537 lowp = &vmx->nested.msrs.procbased_ctls_low;
3538 highp = &vmx->nested.msrs.procbased_ctls_high;
3539 break;
3540 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3541 lowp = &vmx->nested.msrs.exit_ctls_low;
3542 highp = &vmx->nested.msrs.exit_ctls_high;
3543 break;
3544 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3545 lowp = &vmx->nested.msrs.entry_ctls_low;
3546 highp = &vmx->nested.msrs.entry_ctls_high;
3547 break;
3548 case MSR_IA32_VMX_PROCBASED_CTLS2:
3549 lowp = &vmx->nested.msrs.secondary_ctls_low;
3550 highp = &vmx->nested.msrs.secondary_ctls_high;
3551 break;
3552 default:
3553 BUG();
3554 }
3555
3556 supported = vmx_control_msr(*lowp, *highp);
3557
3558 /* Check must-be-1 bits are still 1. */
3559 if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3560 return -EINVAL;
3561
3562 /* Check must-be-0 bits are still 0. */
3563 if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3564 return -EINVAL;
3565
3566 *lowp = data;
3567 *highp = data >> 32;
3568 return 0;
3569 }
3570
3571 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3572 {
3573 const u64 feature_and_reserved_bits =
3574 /* feature */
3575 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3576 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3577 /* reserved */
3578 GENMASK_ULL(13, 9) | BIT_ULL(31);
3579 u64 vmx_misc;
3580
3581 vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
3582 vmx->nested.msrs.misc_high);
3583
3584 if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3585 return -EINVAL;
3586
3587 if ((vmx->nested.msrs.pinbased_ctls_high &
3588 PIN_BASED_VMX_PREEMPTION_TIMER) &&
3589 vmx_misc_preemption_timer_rate(data) !=
3590 vmx_misc_preemption_timer_rate(vmx_misc))
3591 return -EINVAL;
3592
3593 if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3594 return -EINVAL;
3595
3596 if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3597 return -EINVAL;
3598
3599 if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3600 return -EINVAL;
3601
3602 vmx->nested.msrs.misc_low = data;
3603 vmx->nested.msrs.misc_high = data >> 32;
3604
3605 /*
3606 * If L1 has read-only VM-exit information fields, use the
3607 * less permissive vmx_vmwrite_bitmap to specify write
3608 * permissions for the shadow VMCS.
3609 */
3610 if (enable_shadow_vmcs && !nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
3611 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
3612
3613 return 0;
3614 }
3615
3616 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3617 {
3618 u64 vmx_ept_vpid_cap;
3619
3620 vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.msrs.ept_caps,
3621 vmx->nested.msrs.vpid_caps);
3622
3623 /* Every bit is either reserved or a feature bit. */
3624 if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3625 return -EINVAL;
3626
3627 vmx->nested.msrs.ept_caps = data;
3628 vmx->nested.msrs.vpid_caps = data >> 32;
3629 return 0;
3630 }
3631
3632 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3633 {
3634 u64 *msr;
3635
3636 switch (msr_index) {
3637 case MSR_IA32_VMX_CR0_FIXED0:
3638 msr = &vmx->nested.msrs.cr0_fixed0;
3639 break;
3640 case MSR_IA32_VMX_CR4_FIXED0:
3641 msr = &vmx->nested.msrs.cr4_fixed0;
3642 break;
3643 default:
3644 BUG();
3645 }
3646
3647 /*
3648 * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3649 * must be 1 in the restored value.
3650 */
3651 if (!is_bitwise_subset(data, *msr, -1ULL))
3652 return -EINVAL;
3653
3654 *msr = data;
3655 return 0;
3656 }
3657
3658 /*
3659 * Called when userspace is restoring VMX MSRs.
3660 *
3661 * Returns 0 on success, non-0 otherwise.
3662 */
3663 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3664 {
3665 struct vcpu_vmx *vmx = to_vmx(vcpu);
3666
3667 /*
3668 * Don't allow changes to the VMX capability MSRs while the vCPU
3669 * is in VMX operation.
3670 */
3671 if (vmx->nested.vmxon)
3672 return -EBUSY;
3673
3674 switch (msr_index) {
3675 case MSR_IA32_VMX_BASIC:
3676 return vmx_restore_vmx_basic(vmx, data);
3677 case MSR_IA32_VMX_PINBASED_CTLS:
3678 case MSR_IA32_VMX_PROCBASED_CTLS:
3679 case MSR_IA32_VMX_EXIT_CTLS:
3680 case MSR_IA32_VMX_ENTRY_CTLS:
3681 /*
3682 * The "non-true" VMX capability MSRs are generated from the
3683 * "true" MSRs, so we do not support restoring them directly.
3684 *
3685 * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3686 * should restore the "true" MSRs with the must-be-1 bits
3687 * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3688 * DEFAULT SETTINGS".
3689 */
3690 return -EINVAL;
3691 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3692 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3693 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3694 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3695 case MSR_IA32_VMX_PROCBASED_CTLS2:
3696 return vmx_restore_control_msr(vmx, msr_index, data);
3697 case MSR_IA32_VMX_MISC:
3698 return vmx_restore_vmx_misc(vmx, data);
3699 case MSR_IA32_VMX_CR0_FIXED0:
3700 case MSR_IA32_VMX_CR4_FIXED0:
3701 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3702 case MSR_IA32_VMX_CR0_FIXED1:
3703 case MSR_IA32_VMX_CR4_FIXED1:
3704 /*
3705 * These MSRs are generated based on the vCPU's CPUID, so we
3706 * do not support restoring them directly.
3707 */
3708 return -EINVAL;
3709 case MSR_IA32_VMX_EPT_VPID_CAP:
3710 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3711 case MSR_IA32_VMX_VMCS_ENUM:
3712 vmx->nested.msrs.vmcs_enum = data;
3713 return 0;
3714 default:
3715 /*
3716 * The rest of the VMX capability MSRs do not support restore.
3717 */
3718 return -EINVAL;
3719 }
3720 }
3721
3722 /* Returns 0 on success, non-0 otherwise. */
3723 static int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
3724 {
3725 switch (msr_index) {
3726 case MSR_IA32_VMX_BASIC:
3727 *pdata = msrs->basic;
3728 break;
3729 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3730 case MSR_IA32_VMX_PINBASED_CTLS:
3731 *pdata = vmx_control_msr(
3732 msrs->pinbased_ctls_low,
3733 msrs->pinbased_ctls_high);
3734 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3735 *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3736 break;
3737 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3738 case MSR_IA32_VMX_PROCBASED_CTLS:
3739 *pdata = vmx_control_msr(
3740 msrs->procbased_ctls_low,
3741 msrs->procbased_ctls_high);
3742 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3743 *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3744 break;
3745 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3746 case MSR_IA32_VMX_EXIT_CTLS:
3747 *pdata = vmx_control_msr(
3748 msrs->exit_ctls_low,
3749 msrs->exit_ctls_high);
3750 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3751 *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3752 break;
3753 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3754 case MSR_IA32_VMX_ENTRY_CTLS:
3755 *pdata = vmx_control_msr(
3756 msrs->entry_ctls_low,
3757 msrs->entry_ctls_high);
3758 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
3759 *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3760 break;
3761 case MSR_IA32_VMX_MISC:
3762 *pdata = vmx_control_msr(
3763 msrs->misc_low,
3764 msrs->misc_high);
3765 break;
3766 case MSR_IA32_VMX_CR0_FIXED0:
3767 *pdata = msrs->cr0_fixed0;
3768 break;
3769 case MSR_IA32_VMX_CR0_FIXED1:
3770 *pdata = msrs->cr0_fixed1;
3771 break;
3772 case MSR_IA32_VMX_CR4_FIXED0:
3773 *pdata = msrs->cr4_fixed0;
3774 break;
3775 case MSR_IA32_VMX_CR4_FIXED1:
3776 *pdata = msrs->cr4_fixed1;
3777 break;
3778 case MSR_IA32_VMX_VMCS_ENUM:
3779 *pdata = msrs->vmcs_enum;
3780 break;
3781 case MSR_IA32_VMX_PROCBASED_CTLS2:
3782 *pdata = vmx_control_msr(
3783 msrs->secondary_ctls_low,
3784 msrs->secondary_ctls_high);
3785 break;
3786 case MSR_IA32_VMX_EPT_VPID_CAP:
3787 *pdata = msrs->ept_caps |
3788 ((u64)msrs->vpid_caps << 32);
3789 break;
3790 case MSR_IA32_VMX_VMFUNC:
3791 *pdata = msrs->vmfunc_controls;
3792 break;
3793 default:
3794 return 1;
3795 }
3796
3797 return 0;
3798 }
3799
3800 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3801 uint64_t val)
3802 {
3803 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3804
3805 return !(val & ~valid_bits);
3806 }
3807
3808 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
3809 {
3810 switch (msr->index) {
3811 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3812 if (!nested)
3813 return 1;
3814 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
3815 default:
3816 return 1;
3817 }
3818
3819 return 0;
3820 }
3821
3822 /*
3823 * Reads an msr value (of 'msr_index') into 'pdata'.
3824 * Returns 0 on success, non-0 otherwise.
3825 * Assumes vcpu_load() was already called.
3826 */
3827 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3828 {
3829 struct vcpu_vmx *vmx = to_vmx(vcpu);
3830 struct shared_msr_entry *msr;
3831
3832 switch (msr_info->index) {
3833 #ifdef CONFIG_X86_64
3834 case MSR_FS_BASE:
3835 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3836 break;
3837 case MSR_GS_BASE:
3838 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3839 break;
3840 case MSR_KERNEL_GS_BASE:
3841 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
3842 break;
3843 #endif
3844 case MSR_EFER:
3845 return kvm_get_msr_common(vcpu, msr_info);
3846 case MSR_IA32_SPEC_CTRL:
3847 if (!msr_info->host_initiated &&
3848 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3849 return 1;
3850
3851 msr_info->data = to_vmx(vcpu)->spec_ctrl;
3852 break;
3853 case MSR_IA32_ARCH_CAPABILITIES:
3854 if (!msr_info->host_initiated &&
3855 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3856 return 1;
3857 msr_info->data = to_vmx(vcpu)->arch_capabilities;
3858 break;
3859 case MSR_IA32_SYSENTER_CS:
3860 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3861 break;
3862 case MSR_IA32_SYSENTER_EIP:
3863 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3864 break;
3865 case MSR_IA32_SYSENTER_ESP:
3866 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3867 break;
3868 case MSR_IA32_BNDCFGS:
3869 if (!kvm_mpx_supported() ||
3870 (!msr_info->host_initiated &&
3871 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3872 return 1;
3873 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3874 break;
3875 case MSR_IA32_MCG_EXT_CTL:
3876 if (!msr_info->host_initiated &&
3877 !(vmx->msr_ia32_feature_control &
3878 FEATURE_CONTROL_LMCE))
3879 return 1;
3880 msr_info->data = vcpu->arch.mcg_ext_ctl;
3881 break;
3882 case MSR_IA32_FEATURE_CONTROL:
3883 msr_info->data = vmx->msr_ia32_feature_control;
3884 break;
3885 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3886 if (!nested_vmx_allowed(vcpu))
3887 return 1;
3888 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
3889 &msr_info->data);
3890 case MSR_IA32_XSS:
3891 if (!vmx_xsaves_supported())
3892 return 1;
3893 msr_info->data = vcpu->arch.ia32_xss;
3894 break;
3895 case MSR_TSC_AUX:
3896 if (!msr_info->host_initiated &&
3897 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3898 return 1;
3899 /* Otherwise falls through */
3900 default:
3901 msr = find_msr_entry(vmx, msr_info->index);
3902 if (msr) {
3903 msr_info->data = msr->data;
3904 break;
3905 }
3906 return kvm_get_msr_common(vcpu, msr_info);
3907 }
3908
3909 return 0;
3910 }
3911
3912 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3913
3914 /*
3915 * Writes msr value into into the appropriate "register".
3916 * Returns 0 on success, non-0 otherwise.
3917 * Assumes vcpu_load() was already called.
3918 */
3919 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3920 {
3921 struct vcpu_vmx *vmx = to_vmx(vcpu);
3922 struct shared_msr_entry *msr;
3923 int ret = 0;
3924 u32 msr_index = msr_info->index;
3925 u64 data = msr_info->data;
3926
3927 switch (msr_index) {
3928 case MSR_EFER:
3929 ret = kvm_set_msr_common(vcpu, msr_info);
3930 break;
3931 #ifdef CONFIG_X86_64
3932 case MSR_FS_BASE:
3933 vmx_segment_cache_clear(vmx);
3934 vmcs_writel(GUEST_FS_BASE, data);
3935 break;
3936 case MSR_GS_BASE:
3937 vmx_segment_cache_clear(vmx);
3938 vmcs_writel(GUEST_GS_BASE, data);
3939 break;
3940 case MSR_KERNEL_GS_BASE:
3941 vmx_write_guest_kernel_gs_base(vmx, data);
3942 break;
3943 #endif
3944 case MSR_IA32_SYSENTER_CS:
3945 vmcs_write32(GUEST_SYSENTER_CS, data);
3946 break;
3947 case MSR_IA32_SYSENTER_EIP:
3948 vmcs_writel(GUEST_SYSENTER_EIP, data);
3949 break;
3950 case MSR_IA32_SYSENTER_ESP:
3951 vmcs_writel(GUEST_SYSENTER_ESP, data);
3952 break;
3953 case MSR_IA32_BNDCFGS:
3954 if (!kvm_mpx_supported() ||
3955 (!msr_info->host_initiated &&
3956 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3957 return 1;
3958 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
3959 (data & MSR_IA32_BNDCFGS_RSVD))
3960 return 1;
3961 vmcs_write64(GUEST_BNDCFGS, data);
3962 break;
3963 case MSR_IA32_SPEC_CTRL:
3964 if (!msr_info->host_initiated &&
3965 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3966 return 1;
3967
3968 /* The STIBP bit doesn't fault even if it's not advertised */
3969 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
3970 return 1;
3971
3972 vmx->spec_ctrl = data;
3973
3974 if (!data)
3975 break;
3976
3977 /*
3978 * For non-nested:
3979 * When it's written (to non-zero) for the first time, pass
3980 * it through.
3981 *
3982 * For nested:
3983 * The handling of the MSR bitmap for L2 guests is done in
3984 * nested_vmx_merge_msr_bitmap. We should not touch the
3985 * vmcs02.msr_bitmap here since it gets completely overwritten
3986 * in the merging. We update the vmcs01 here for L1 as well
3987 * since it will end up touching the MSR anyway now.
3988 */
3989 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
3990 MSR_IA32_SPEC_CTRL,
3991 MSR_TYPE_RW);
3992 break;
3993 case MSR_IA32_PRED_CMD:
3994 if (!msr_info->host_initiated &&
3995 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3996 return 1;
3997
3998 if (data & ~PRED_CMD_IBPB)
3999 return 1;
4000
4001 if (!data)
4002 break;
4003
4004 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4005
4006 /*
4007 * For non-nested:
4008 * When it's written (to non-zero) for the first time, pass
4009 * it through.
4010 *
4011 * For nested:
4012 * The handling of the MSR bitmap for L2 guests is done in
4013 * nested_vmx_merge_msr_bitmap. We should not touch the
4014 * vmcs02.msr_bitmap here since it gets completely overwritten
4015 * in the merging.
4016 */
4017 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
4018 MSR_TYPE_W);
4019 break;
4020 case MSR_IA32_ARCH_CAPABILITIES:
4021 if (!msr_info->host_initiated)
4022 return 1;
4023 vmx->arch_capabilities = data;
4024 break;
4025 case MSR_IA32_CR_PAT:
4026 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4027 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4028 return 1;
4029 vmcs_write64(GUEST_IA32_PAT, data);
4030 vcpu->arch.pat = data;
4031 break;
4032 }
4033 ret = kvm_set_msr_common(vcpu, msr_info);
4034 break;
4035 case MSR_IA32_TSC_ADJUST:
4036 ret = kvm_set_msr_common(vcpu, msr_info);
4037 break;
4038 case MSR_IA32_MCG_EXT_CTL:
4039 if ((!msr_info->host_initiated &&
4040 !(to_vmx(vcpu)->msr_ia32_feature_control &
4041 FEATURE_CONTROL_LMCE)) ||
4042 (data & ~MCG_EXT_CTL_LMCE_EN))
4043 return 1;
4044 vcpu->arch.mcg_ext_ctl = data;
4045 break;
4046 case MSR_IA32_FEATURE_CONTROL:
4047 if (!vmx_feature_control_msr_valid(vcpu, data) ||
4048 (to_vmx(vcpu)->msr_ia32_feature_control &
4049 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
4050 return 1;
4051 vmx->msr_ia32_feature_control = data;
4052 if (msr_info->host_initiated && data == 0)
4053 vmx_leave_nested(vcpu);
4054 break;
4055 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4056 if (!msr_info->host_initiated)
4057 return 1; /* they are read-only */
4058 if (!nested_vmx_allowed(vcpu))
4059 return 1;
4060 return vmx_set_vmx_msr(vcpu, msr_index, data);
4061 case MSR_IA32_XSS:
4062 if (!vmx_xsaves_supported())
4063 return 1;
4064 /*
4065 * The only supported bit as of Skylake is bit 8, but
4066 * it is not supported on KVM.
4067 */
4068 if (data != 0)
4069 return 1;
4070 vcpu->arch.ia32_xss = data;
4071 if (vcpu->arch.ia32_xss != host_xss)
4072 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
4073 vcpu->arch.ia32_xss, host_xss, false);
4074 else
4075 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
4076 break;
4077 case MSR_TSC_AUX:
4078 if (!msr_info->host_initiated &&
4079 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4080 return 1;
4081 /* Check reserved bit, higher 32 bits should be zero */
4082 if ((data >> 32) != 0)
4083 return 1;
4084 /* Otherwise falls through */
4085 default:
4086 msr = find_msr_entry(vmx, msr_index);
4087 if (msr) {
4088 u64 old_msr_data = msr->data;
4089 msr->data = data;
4090 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
4091 preempt_disable();
4092 ret = kvm_set_shared_msr(msr->index, msr->data,
4093 msr->mask);
4094 preempt_enable();
4095 if (ret)
4096 msr->data = old_msr_data;
4097 }
4098 break;
4099 }
4100 ret = kvm_set_msr_common(vcpu, msr_info);
4101 }
4102
4103 return ret;
4104 }
4105
4106 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
4107 {
4108 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
4109 switch (reg) {
4110 case VCPU_REGS_RSP:
4111 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
4112 break;
4113 case VCPU_REGS_RIP:
4114 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
4115 break;
4116 case VCPU_EXREG_PDPTR:
4117 if (enable_ept)
4118 ept_save_pdptrs(vcpu);
4119 break;
4120 default:
4121 break;
4122 }
4123 }
4124
4125 static __init int cpu_has_kvm_support(void)
4126 {
4127 return cpu_has_vmx();
4128 }
4129
4130 static __init int vmx_disabled_by_bios(void)
4131 {
4132 u64 msr;
4133
4134 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
4135 if (msr & FEATURE_CONTROL_LOCKED) {
4136 /* launched w/ TXT and VMX disabled */
4137 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4138 && tboot_enabled())
4139 return 1;
4140 /* launched w/o TXT and VMX only enabled w/ TXT */
4141 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4142 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4143 && !tboot_enabled()) {
4144 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
4145 "activate TXT before enabling KVM\n");
4146 return 1;
4147 }
4148 /* launched w/o TXT and VMX disabled */
4149 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4150 && !tboot_enabled())
4151 return 1;
4152 }
4153
4154 return 0;
4155 }
4156
4157 static void kvm_cpu_vmxon(u64 addr)
4158 {
4159 cr4_set_bits(X86_CR4_VMXE);
4160 intel_pt_handle_vmx(1);
4161
4162 asm volatile ("vmxon %0" : : "m"(addr));
4163 }
4164
4165 static int hardware_enable(void)
4166 {
4167 int cpu = raw_smp_processor_id();
4168 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
4169 u64 old, test_bits;
4170
4171 if (cr4_read_shadow() & X86_CR4_VMXE)
4172 return -EBUSY;
4173
4174 /*
4175 * This can happen if we hot-added a CPU but failed to allocate
4176 * VP assist page for it.
4177 */
4178 if (static_branch_unlikely(&enable_evmcs) &&
4179 !hv_get_vp_assist_page(cpu))
4180 return -EFAULT;
4181
4182 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
4183 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
4184 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4185
4186 /*
4187 * Now we can enable the vmclear operation in kdump
4188 * since the loaded_vmcss_on_cpu list on this cpu
4189 * has been initialized.
4190 *
4191 * Though the cpu is not in VMX operation now, there
4192 * is no problem to enable the vmclear operation
4193 * for the loaded_vmcss_on_cpu list is empty!
4194 */
4195 crash_enable_local_vmclear(cpu);
4196
4197 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
4198
4199 test_bits = FEATURE_CONTROL_LOCKED;
4200 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
4201 if (tboot_enabled())
4202 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
4203
4204 if ((old & test_bits) != test_bits) {
4205 /* enable and lock */
4206 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
4207 }
4208 kvm_cpu_vmxon(phys_addr);
4209 if (enable_ept)
4210 ept_sync_global();
4211
4212 return 0;
4213 }
4214
4215 static void vmclear_local_loaded_vmcss(void)
4216 {
4217 int cpu = raw_smp_processor_id();
4218 struct loaded_vmcs *v, *n;
4219
4220 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
4221 loaded_vmcss_on_cpu_link)
4222 __loaded_vmcs_clear(v);
4223 }
4224
4225
4226 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
4227 * tricks.
4228 */
4229 static void kvm_cpu_vmxoff(void)
4230 {
4231 asm volatile (__ex("vmxoff"));
4232
4233 intel_pt_handle_vmx(0);
4234 cr4_clear_bits(X86_CR4_VMXE);
4235 }
4236
4237 static void hardware_disable(void)
4238 {
4239 vmclear_local_loaded_vmcss();
4240 kvm_cpu_vmxoff();
4241 }
4242
4243 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
4244 u32 msr, u32 *result)
4245 {
4246 u32 vmx_msr_low, vmx_msr_high;
4247 u32 ctl = ctl_min | ctl_opt;
4248
4249 rdmsr(msr, vmx_msr_low, vmx_msr_high);
4250
4251 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
4252 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
4253
4254 /* Ensure minimum (required) set of control bits are supported. */
4255 if (ctl_min & ~ctl)
4256 return -EIO;
4257
4258 *result = ctl;
4259 return 0;
4260 }
4261
4262 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
4263 struct vmx_capability *vmx_cap)
4264 {
4265 u32 vmx_msr_low, vmx_msr_high;
4266 u32 min, opt, min2, opt2;
4267 u32 _pin_based_exec_control = 0;
4268 u32 _cpu_based_exec_control = 0;
4269 u32 _cpu_based_2nd_exec_control = 0;
4270 u32 _vmexit_control = 0;
4271 u32 _vmentry_control = 0;
4272
4273 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
4274 min = CPU_BASED_HLT_EXITING |
4275 #ifdef CONFIG_X86_64
4276 CPU_BASED_CR8_LOAD_EXITING |
4277 CPU_BASED_CR8_STORE_EXITING |
4278 #endif
4279 CPU_BASED_CR3_LOAD_EXITING |
4280 CPU_BASED_CR3_STORE_EXITING |
4281 CPU_BASED_UNCOND_IO_EXITING |
4282 CPU_BASED_MOV_DR_EXITING |
4283 CPU_BASED_USE_TSC_OFFSETING |
4284 CPU_BASED_MWAIT_EXITING |
4285 CPU_BASED_MONITOR_EXITING |
4286 CPU_BASED_INVLPG_EXITING |
4287 CPU_BASED_RDPMC_EXITING;
4288
4289 opt = CPU_BASED_TPR_SHADOW |
4290 CPU_BASED_USE_MSR_BITMAPS |
4291 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
4292 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
4293 &_cpu_based_exec_control) < 0)
4294 return -EIO;
4295 #ifdef CONFIG_X86_64
4296 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4297 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
4298 ~CPU_BASED_CR8_STORE_EXITING;
4299 #endif
4300 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
4301 min2 = 0;
4302 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
4303 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4304 SECONDARY_EXEC_WBINVD_EXITING |
4305 SECONDARY_EXEC_ENABLE_VPID |
4306 SECONDARY_EXEC_ENABLE_EPT |
4307 SECONDARY_EXEC_UNRESTRICTED_GUEST |
4308 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
4309 SECONDARY_EXEC_DESC |
4310 SECONDARY_EXEC_RDTSCP |
4311 SECONDARY_EXEC_ENABLE_INVPCID |
4312 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4313 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
4314 SECONDARY_EXEC_SHADOW_VMCS |
4315 SECONDARY_EXEC_XSAVES |
4316 SECONDARY_EXEC_RDSEED_EXITING |
4317 SECONDARY_EXEC_RDRAND_EXITING |
4318 SECONDARY_EXEC_ENABLE_PML |
4319 SECONDARY_EXEC_TSC_SCALING |
4320 SECONDARY_EXEC_ENABLE_VMFUNC |
4321 SECONDARY_EXEC_ENCLS_EXITING;
4322 if (adjust_vmx_controls(min2, opt2,
4323 MSR_IA32_VMX_PROCBASED_CTLS2,
4324 &_cpu_based_2nd_exec_control) < 0)
4325 return -EIO;
4326 }
4327 #ifndef CONFIG_X86_64
4328 if (!(_cpu_based_2nd_exec_control &
4329 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
4330 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
4331 #endif
4332
4333 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4334 _cpu_based_2nd_exec_control &= ~(
4335 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4336 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4337 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4338
4339 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
4340 &vmx_cap->ept, &vmx_cap->vpid);
4341
4342 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
4343 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
4344 enabled */
4345 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4346 CPU_BASED_CR3_STORE_EXITING |
4347 CPU_BASED_INVLPG_EXITING);
4348 } else if (vmx_cap->ept) {
4349 vmx_cap->ept = 0;
4350 pr_warn_once("EPT CAP should not exist if not support "
4351 "1-setting enable EPT VM-execution control\n");
4352 }
4353 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
4354 vmx_cap->vpid) {
4355 vmx_cap->vpid = 0;
4356 pr_warn_once("VPID CAP should not exist if not support "
4357 "1-setting enable VPID VM-execution control\n");
4358 }
4359
4360 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
4361 #ifdef CONFIG_X86_64
4362 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
4363 #endif
4364 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
4365 VM_EXIT_SAVE_IA32_PAT |
4366 VM_EXIT_LOAD_IA32_PAT |
4367 VM_EXIT_LOAD_IA32_EFER |
4368 VM_EXIT_CLEAR_BNDCFGS;
4369 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
4370 &_vmexit_control) < 0)
4371 return -EIO;
4372
4373 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
4374 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
4375 PIN_BASED_VMX_PREEMPTION_TIMER;
4376 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
4377 &_pin_based_exec_control) < 0)
4378 return -EIO;
4379
4380 if (cpu_has_broken_vmx_preemption_timer())
4381 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4382 if (!(_cpu_based_2nd_exec_control &
4383 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
4384 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
4385
4386 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
4387 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
4388 VM_ENTRY_LOAD_IA32_PAT |
4389 VM_ENTRY_LOAD_IA32_EFER |
4390 VM_ENTRY_LOAD_BNDCFGS;
4391 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
4392 &_vmentry_control) < 0)
4393 return -EIO;
4394
4395 /*
4396 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
4397 * can't be used due to an errata where VM Exit may incorrectly clear
4398 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
4399 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
4400 */
4401 if (boot_cpu_data.x86 == 0x6) {
4402 switch (boot_cpu_data.x86_model) {
4403 case 26: /* AAK155 */
4404 case 30: /* AAP115 */
4405 case 37: /* AAT100 */
4406 case 44: /* BC86,AAY89,BD102 */
4407 case 46: /* BA97 */
4408 _vmexit_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4409 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
4410 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
4411 "does not work properly. Using workaround\n");
4412 break;
4413 default:
4414 break;
4415 }
4416 }
4417
4418
4419 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
4420
4421 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
4422 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
4423 return -EIO;
4424
4425 #ifdef CONFIG_X86_64
4426 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
4427 if (vmx_msr_high & (1u<<16))
4428 return -EIO;
4429 #endif
4430
4431 /* Require Write-Back (WB) memory type for VMCS accesses. */
4432 if (((vmx_msr_high >> 18) & 15) != 6)
4433 return -EIO;
4434
4435 vmcs_conf->size = vmx_msr_high & 0x1fff;
4436 vmcs_conf->order = get_order(vmcs_conf->size);
4437 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
4438
4439 vmcs_conf->revision_id = vmx_msr_low;
4440
4441 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
4442 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
4443 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
4444 vmcs_conf->vmexit_ctrl = _vmexit_control;
4445 vmcs_conf->vmentry_ctrl = _vmentry_control;
4446
4447 if (static_branch_unlikely(&enable_evmcs))
4448 evmcs_sanitize_exec_ctrls(vmcs_conf);
4449
4450 return 0;
4451 }
4452
4453 static struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
4454 {
4455 int node = cpu_to_node(cpu);
4456 struct page *pages;
4457 struct vmcs *vmcs;
4458
4459 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
4460 if (!pages)
4461 return NULL;
4462 vmcs = page_address(pages);
4463 memset(vmcs, 0, vmcs_config.size);
4464
4465 /* KVM supports Enlightened VMCS v1 only */
4466 if (static_branch_unlikely(&enable_evmcs))
4467 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
4468 else
4469 vmcs->hdr.revision_id = vmcs_config.revision_id;
4470
4471 if (shadow)
4472 vmcs->hdr.shadow_vmcs = 1;
4473 return vmcs;
4474 }
4475
4476 static void free_vmcs(struct vmcs *vmcs)
4477 {
4478 free_pages((unsigned long)vmcs, vmcs_config.order);
4479 }
4480
4481 /*
4482 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
4483 */
4484 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4485 {
4486 if (!loaded_vmcs->vmcs)
4487 return;
4488 loaded_vmcs_clear(loaded_vmcs);
4489 free_vmcs(loaded_vmcs->vmcs);
4490 loaded_vmcs->vmcs = NULL;
4491 if (loaded_vmcs->msr_bitmap)
4492 free_page((unsigned long)loaded_vmcs->msr_bitmap);
4493 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
4494 }
4495
4496 static struct vmcs *alloc_vmcs(bool shadow)
4497 {
4498 return alloc_vmcs_cpu(shadow, raw_smp_processor_id());
4499 }
4500
4501 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4502 {
4503 loaded_vmcs->vmcs = alloc_vmcs(false);
4504 if (!loaded_vmcs->vmcs)
4505 return -ENOMEM;
4506
4507 loaded_vmcs->shadow_vmcs = NULL;
4508 loaded_vmcs_init(loaded_vmcs);
4509
4510 if (cpu_has_vmx_msr_bitmap()) {
4511 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
4512 if (!loaded_vmcs->msr_bitmap)
4513 goto out_vmcs;
4514 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
4515
4516 if (IS_ENABLED(CONFIG_HYPERV) &&
4517 static_branch_unlikely(&enable_evmcs) &&
4518 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
4519 struct hv_enlightened_vmcs *evmcs =
4520 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
4521
4522 evmcs->hv_enlightenments_control.msr_bitmap = 1;
4523 }
4524 }
4525
4526 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
4527
4528 return 0;
4529
4530 out_vmcs:
4531 free_loaded_vmcs(loaded_vmcs);
4532 return -ENOMEM;
4533 }
4534
4535 static void free_kvm_area(void)
4536 {
4537 int cpu;
4538
4539 for_each_possible_cpu(cpu) {
4540 free_vmcs(per_cpu(vmxarea, cpu));
4541 per_cpu(vmxarea, cpu) = NULL;
4542 }
4543 }
4544
4545 enum vmcs_field_width {
4546 VMCS_FIELD_WIDTH_U16 = 0,
4547 VMCS_FIELD_WIDTH_U64 = 1,
4548 VMCS_FIELD_WIDTH_U32 = 2,
4549 VMCS_FIELD_WIDTH_NATURAL_WIDTH = 3
4550 };
4551
4552 static inline int vmcs_field_width(unsigned long field)
4553 {
4554 if (0x1 & field) /* the *_HIGH fields are all 32 bit */
4555 return VMCS_FIELD_WIDTH_U32;
4556 return (field >> 13) & 0x3 ;
4557 }
4558
4559 static inline int vmcs_field_readonly(unsigned long field)
4560 {
4561 return (((field >> 10) & 0x3) == 1);
4562 }
4563
4564 static void init_vmcs_shadow_fields(void)
4565 {
4566 int i, j;
4567
4568 memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
4569 memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
4570
4571 for (i = j = 0; i < max_shadow_read_only_fields; i++) {
4572 u16 field = shadow_read_only_fields[i];
4573 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4574 (i + 1 == max_shadow_read_only_fields ||
4575 shadow_read_only_fields[i + 1] != field + 1))
4576 pr_err("Missing field from shadow_read_only_field %x\n",
4577 field + 1);
4578
4579 clear_bit(field, vmx_vmread_bitmap);
4580 #ifdef CONFIG_X86_64
4581 if (field & 1)
4582 continue;
4583 #endif
4584 if (j < i)
4585 shadow_read_only_fields[j] = field;
4586 j++;
4587 }
4588 max_shadow_read_only_fields = j;
4589
4590 for (i = j = 0; i < max_shadow_read_write_fields; i++) {
4591 u16 field = shadow_read_write_fields[i];
4592 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4593 (i + 1 == max_shadow_read_write_fields ||
4594 shadow_read_write_fields[i + 1] != field + 1))
4595 pr_err("Missing field from shadow_read_write_field %x\n",
4596 field + 1);
4597
4598 /*
4599 * PML and the preemption timer can be emulated, but the
4600 * processor cannot vmwrite to fields that don't exist
4601 * on bare metal.
4602 */
4603 switch (field) {
4604 case GUEST_PML_INDEX:
4605 if (!cpu_has_vmx_pml())
4606 continue;
4607 break;
4608 case VMX_PREEMPTION_TIMER_VALUE:
4609 if (!cpu_has_vmx_preemption_timer())
4610 continue;
4611 break;
4612 case GUEST_INTR_STATUS:
4613 if (!cpu_has_vmx_apicv())
4614 continue;
4615 break;
4616 default:
4617 break;
4618 }
4619
4620 clear_bit(field, vmx_vmwrite_bitmap);
4621 clear_bit(field, vmx_vmread_bitmap);
4622 #ifdef CONFIG_X86_64
4623 if (field & 1)
4624 continue;
4625 #endif
4626 if (j < i)
4627 shadow_read_write_fields[j] = field;
4628 j++;
4629 }
4630 max_shadow_read_write_fields = j;
4631 }
4632
4633 static __init int alloc_kvm_area(void)
4634 {
4635 int cpu;
4636
4637 for_each_possible_cpu(cpu) {
4638 struct vmcs *vmcs;
4639
4640 vmcs = alloc_vmcs_cpu(false, cpu);
4641 if (!vmcs) {
4642 free_kvm_area();
4643 return -ENOMEM;
4644 }
4645
4646 /*
4647 * When eVMCS is enabled, alloc_vmcs_cpu() sets
4648 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
4649 * revision_id reported by MSR_IA32_VMX_BASIC.
4650 *
4651 * However, even though not explictly documented by
4652 * TLFS, VMXArea passed as VMXON argument should
4653 * still be marked with revision_id reported by
4654 * physical CPU.
4655 */
4656 if (static_branch_unlikely(&enable_evmcs))
4657 vmcs->hdr.revision_id = vmcs_config.revision_id;
4658
4659 per_cpu(vmxarea, cpu) = vmcs;
4660 }
4661 return 0;
4662 }
4663
4664 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4665 struct kvm_segment *save)
4666 {
4667 if (!emulate_invalid_guest_state) {
4668 /*
4669 * CS and SS RPL should be equal during guest entry according
4670 * to VMX spec, but in reality it is not always so. Since vcpu
4671 * is in the middle of the transition from real mode to
4672 * protected mode it is safe to assume that RPL 0 is a good
4673 * default value.
4674 */
4675 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4676 save->selector &= ~SEGMENT_RPL_MASK;
4677 save->dpl = save->selector & SEGMENT_RPL_MASK;
4678 save->s = 1;
4679 }
4680 vmx_set_segment(vcpu, save, seg);
4681 }
4682
4683 static void enter_pmode(struct kvm_vcpu *vcpu)
4684 {
4685 unsigned long flags;
4686 struct vcpu_vmx *vmx = to_vmx(vcpu);
4687
4688 /*
4689 * Update real mode segment cache. It may be not up-to-date if sement
4690 * register was written while vcpu was in a guest mode.
4691 */
4692 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4693 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4694 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4695 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4696 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4697 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4698
4699 vmx->rmode.vm86_active = 0;
4700
4701 vmx_segment_cache_clear(vmx);
4702
4703 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4704
4705 flags = vmcs_readl(GUEST_RFLAGS);
4706 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4707 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4708 vmcs_writel(GUEST_RFLAGS, flags);
4709
4710 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4711 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4712
4713 update_exception_bitmap(vcpu);
4714
4715 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4716 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4717 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4718 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4719 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4720 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4721 }
4722
4723 static void fix_rmode_seg(int seg, struct kvm_segment *save)
4724 {
4725 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4726 struct kvm_segment var = *save;
4727
4728 var.dpl = 0x3;
4729 if (seg == VCPU_SREG_CS)
4730 var.type = 0x3;
4731
4732 if (!emulate_invalid_guest_state) {
4733 var.selector = var.base >> 4;
4734 var.base = var.base & 0xffff0;
4735 var.limit = 0xffff;
4736 var.g = 0;
4737 var.db = 0;
4738 var.present = 1;
4739 var.s = 1;
4740 var.l = 0;
4741 var.unusable = 0;
4742 var.type = 0x3;
4743 var.avl = 0;
4744 if (save->base & 0xf)
4745 printk_once(KERN_WARNING "kvm: segment base is not "
4746 "paragraph aligned when entering "
4747 "protected mode (seg=%d)", seg);
4748 }
4749
4750 vmcs_write16(sf->selector, var.selector);
4751 vmcs_writel(sf->base, var.base);
4752 vmcs_write32(sf->limit, var.limit);
4753 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
4754 }
4755
4756 static void enter_rmode(struct kvm_vcpu *vcpu)
4757 {
4758 unsigned long flags;
4759 struct vcpu_vmx *vmx = to_vmx(vcpu);
4760 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
4761
4762 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4763 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4764 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4765 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4766 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4767 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4768 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4769
4770 vmx->rmode.vm86_active = 1;
4771
4772 /*
4773 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4774 * vcpu. Warn the user that an update is overdue.
4775 */
4776 if (!kvm_vmx->tss_addr)
4777 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
4778 "called before entering vcpu\n");
4779
4780 vmx_segment_cache_clear(vmx);
4781
4782 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
4783 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
4784 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4785
4786 flags = vmcs_readl(GUEST_RFLAGS);
4787 vmx->rmode.save_rflags = flags;
4788
4789 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
4790
4791 vmcs_writel(GUEST_RFLAGS, flags);
4792 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
4793 update_exception_bitmap(vcpu);
4794
4795 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4796 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4797 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4798 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4799 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4800 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4801
4802 kvm_mmu_reset_context(vcpu);
4803 }
4804
4805 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
4806 {
4807 struct vcpu_vmx *vmx = to_vmx(vcpu);
4808 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
4809
4810 if (!msr)
4811 return;
4812
4813 vcpu->arch.efer = efer;
4814 if (efer & EFER_LMA) {
4815 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4816 msr->data = efer;
4817 } else {
4818 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4819
4820 msr->data = efer & ~EFER_LME;
4821 }
4822 setup_msrs(vmx);
4823 }
4824
4825 #ifdef CONFIG_X86_64
4826
4827 static void enter_lmode(struct kvm_vcpu *vcpu)
4828 {
4829 u32 guest_tr_ar;
4830
4831 vmx_segment_cache_clear(to_vmx(vcpu));
4832
4833 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4834 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
4835 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
4836 __func__);
4837 vmcs_write32(GUEST_TR_AR_BYTES,
4838 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
4839 | VMX_AR_TYPE_BUSY_64_TSS);
4840 }
4841 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
4842 }
4843
4844 static void exit_lmode(struct kvm_vcpu *vcpu)
4845 {
4846 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4847 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
4848 }
4849
4850 #endif
4851
4852 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
4853 bool invalidate_gpa)
4854 {
4855 if (enable_ept && (invalidate_gpa || !enable_vpid)) {
4856 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
4857 return;
4858 ept_sync_context(construct_eptp(vcpu,
4859 vcpu->arch.mmu->root_hpa));
4860 } else {
4861 vpid_sync_context(vpid);
4862 }
4863 }
4864
4865 static void vmx_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
4866 {
4867 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid, invalidate_gpa);
4868 }
4869
4870 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
4871 {
4872 int vpid = to_vmx(vcpu)->vpid;
4873
4874 if (!vpid_sync_vcpu_addr(vpid, addr))
4875 vpid_sync_context(vpid);
4876
4877 /*
4878 * If VPIDs are not supported or enabled, then the above is a no-op.
4879 * But we don't really need a TLB flush in that case anyway, because
4880 * each VM entry/exit includes an implicit flush when VPID is 0.
4881 */
4882 }
4883
4884 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
4885 {
4886 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
4887
4888 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
4889 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
4890 }
4891
4892 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
4893 {
4894 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
4895 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4896 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
4897 }
4898
4899 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
4900 {
4901 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
4902
4903 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
4904 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
4905 }
4906
4907 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
4908 {
4909 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4910
4911 if (!test_bit(VCPU_EXREG_PDPTR,
4912 (unsigned long *)&vcpu->arch.regs_dirty))
4913 return;
4914
4915 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4916 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
4917 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
4918 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
4919 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
4920 }
4921 }
4922
4923 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
4924 {
4925 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4926
4927 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4928 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
4929 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
4930 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
4931 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
4932 }
4933
4934 __set_bit(VCPU_EXREG_PDPTR,
4935 (unsigned long *)&vcpu->arch.regs_avail);
4936 __set_bit(VCPU_EXREG_PDPTR,
4937 (unsigned long *)&vcpu->arch.regs_dirty);
4938 }
4939
4940 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4941 {
4942 u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
4943 u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
4944 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4945
4946 if (to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
4947 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
4948 nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
4949 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
4950
4951 return fixed_bits_valid(val, fixed0, fixed1);
4952 }
4953
4954 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4955 {
4956 u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
4957 u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
4958
4959 return fixed_bits_valid(val, fixed0, fixed1);
4960 }
4961
4962 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
4963 {
4964 u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr4_fixed0;
4965 u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr4_fixed1;
4966
4967 return fixed_bits_valid(val, fixed0, fixed1);
4968 }
4969
4970 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
4971 #define nested_guest_cr4_valid nested_cr4_valid
4972 #define nested_host_cr4_valid nested_cr4_valid
4973
4974 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
4975
4976 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
4977 unsigned long cr0,
4978 struct kvm_vcpu *vcpu)
4979 {
4980 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
4981 vmx_decache_cr3(vcpu);
4982 if (!(cr0 & X86_CR0_PG)) {
4983 /* From paging/starting to nonpaging */
4984 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4985 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
4986 (CPU_BASED_CR3_LOAD_EXITING |
4987 CPU_BASED_CR3_STORE_EXITING));
4988 vcpu->arch.cr0 = cr0;
4989 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4990 } else if (!is_paging(vcpu)) {
4991 /* From nonpaging to paging */
4992 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4993 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
4994 ~(CPU_BASED_CR3_LOAD_EXITING |
4995 CPU_BASED_CR3_STORE_EXITING));
4996 vcpu->arch.cr0 = cr0;
4997 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4998 }
4999
5000 if (!(cr0 & X86_CR0_WP))
5001 *hw_cr0 &= ~X86_CR0_WP;
5002 }
5003
5004 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
5005 {
5006 struct vcpu_vmx *vmx = to_vmx(vcpu);
5007 unsigned long hw_cr0;
5008
5009 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
5010 if (enable_unrestricted_guest)
5011 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
5012 else {
5013 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
5014
5015 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
5016 enter_pmode(vcpu);
5017
5018 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
5019 enter_rmode(vcpu);
5020 }
5021
5022 #ifdef CONFIG_X86_64
5023 if (vcpu->arch.efer & EFER_LME) {
5024 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
5025 enter_lmode(vcpu);
5026 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
5027 exit_lmode(vcpu);
5028 }
5029 #endif
5030
5031 if (enable_ept && !enable_unrestricted_guest)
5032 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
5033
5034 vmcs_writel(CR0_READ_SHADOW, cr0);
5035 vmcs_writel(GUEST_CR0, hw_cr0);
5036 vcpu->arch.cr0 = cr0;
5037
5038 /* depends on vcpu->arch.cr0 to be set to a new value */
5039 vmx->emulation_required = emulation_required(vcpu);
5040 }
5041
5042 static int get_ept_level(struct kvm_vcpu *vcpu)
5043 {
5044 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
5045 return 5;
5046 return 4;
5047 }
5048
5049 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
5050 {
5051 u64 eptp = VMX_EPTP_MT_WB;
5052
5053 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
5054
5055 if (enable_ept_ad_bits &&
5056 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
5057 eptp |= VMX_EPTP_AD_ENABLE_BIT;
5058 eptp |= (root_hpa & PAGE_MASK);
5059
5060 return eptp;
5061 }
5062
5063 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
5064 {
5065 struct kvm *kvm = vcpu->kvm;
5066 unsigned long guest_cr3;
5067 u64 eptp;
5068
5069 guest_cr3 = cr3;
5070 if (enable_ept) {
5071 eptp = construct_eptp(vcpu, cr3);
5072 vmcs_write64(EPT_POINTER, eptp);
5073
5074 if (kvm_x86_ops->tlb_remote_flush) {
5075 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5076 to_vmx(vcpu)->ept_pointer = eptp;
5077 to_kvm_vmx(kvm)->ept_pointers_match
5078 = EPT_POINTERS_CHECK;
5079 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5080 }
5081
5082 if (enable_unrestricted_guest || is_paging(vcpu) ||
5083 is_guest_mode(vcpu))
5084 guest_cr3 = kvm_read_cr3(vcpu);
5085 else
5086 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
5087 ept_load_pdptrs(vcpu);
5088 }
5089
5090 vmcs_writel(GUEST_CR3, guest_cr3);
5091 }
5092
5093 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
5094 {
5095 /*
5096 * Pass through host's Machine Check Enable value to hw_cr4, which
5097 * is in force while we are in guest mode. Do not let guests control
5098 * this bit, even if host CR4.MCE == 0.
5099 */
5100 unsigned long hw_cr4;
5101
5102 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
5103 if (enable_unrestricted_guest)
5104 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
5105 else if (to_vmx(vcpu)->rmode.vm86_active)
5106 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
5107 else
5108 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
5109
5110 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
5111 if (cr4 & X86_CR4_UMIP) {
5112 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5113 SECONDARY_EXEC_DESC);
5114 hw_cr4 &= ~X86_CR4_UMIP;
5115 } else if (!is_guest_mode(vcpu) ||
5116 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
5117 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5118 SECONDARY_EXEC_DESC);
5119 }
5120
5121 if (cr4 & X86_CR4_VMXE) {
5122 /*
5123 * To use VMXON (and later other VMX instructions), a guest
5124 * must first be able to turn on cr4.VMXE (see handle_vmon()).
5125 * So basically the check on whether to allow nested VMX
5126 * is here. We operate under the default treatment of SMM,
5127 * so VMX cannot be enabled under SMM.
5128 */
5129 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
5130 return 1;
5131 }
5132
5133 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
5134 return 1;
5135
5136 vcpu->arch.cr4 = cr4;
5137
5138 if (!enable_unrestricted_guest) {
5139 if (enable_ept) {
5140 if (!is_paging(vcpu)) {
5141 hw_cr4 &= ~X86_CR4_PAE;
5142 hw_cr4 |= X86_CR4_PSE;
5143 } else if (!(cr4 & X86_CR4_PAE)) {
5144 hw_cr4 &= ~X86_CR4_PAE;
5145 }
5146 }
5147
5148 /*
5149 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
5150 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
5151 * to be manually disabled when guest switches to non-paging
5152 * mode.
5153 *
5154 * If !enable_unrestricted_guest, the CPU is always running
5155 * with CR0.PG=1 and CR4 needs to be modified.
5156 * If enable_unrestricted_guest, the CPU automatically
5157 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
5158 */
5159 if (!is_paging(vcpu))
5160 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
5161 }
5162
5163 vmcs_writel(CR4_READ_SHADOW, cr4);
5164 vmcs_writel(GUEST_CR4, hw_cr4);
5165 return 0;
5166 }
5167
5168 static void vmx_get_segment(struct kvm_vcpu *vcpu,
5169 struct kvm_segment *var, int seg)
5170 {
5171 struct vcpu_vmx *vmx = to_vmx(vcpu);
5172 u32 ar;
5173
5174 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5175 *var = vmx->rmode.segs[seg];
5176 if (seg == VCPU_SREG_TR
5177 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
5178 return;
5179 var->base = vmx_read_guest_seg_base(vmx, seg);
5180 var->selector = vmx_read_guest_seg_selector(vmx, seg);
5181 return;
5182 }
5183 var->base = vmx_read_guest_seg_base(vmx, seg);
5184 var->limit = vmx_read_guest_seg_limit(vmx, seg);
5185 var->selector = vmx_read_guest_seg_selector(vmx, seg);
5186 ar = vmx_read_guest_seg_ar(vmx, seg);
5187 var->unusable = (ar >> 16) & 1;
5188 var->type = ar & 15;
5189 var->s = (ar >> 4) & 1;
5190 var->dpl = (ar >> 5) & 3;
5191 /*
5192 * Some userspaces do not preserve unusable property. Since usable
5193 * segment has to be present according to VMX spec we can use present
5194 * property to amend userspace bug by making unusable segment always
5195 * nonpresent. vmx_segment_access_rights() already marks nonpresent
5196 * segment as unusable.
5197 */
5198 var->present = !var->unusable;
5199 var->avl = (ar >> 12) & 1;
5200 var->l = (ar >> 13) & 1;
5201 var->db = (ar >> 14) & 1;
5202 var->g = (ar >> 15) & 1;
5203 }
5204
5205 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
5206 {
5207 struct kvm_segment s;
5208
5209 if (to_vmx(vcpu)->rmode.vm86_active) {
5210 vmx_get_segment(vcpu, &s, seg);
5211 return s.base;
5212 }
5213 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
5214 }
5215
5216 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
5217 {
5218 struct vcpu_vmx *vmx = to_vmx(vcpu);
5219
5220 if (unlikely(vmx->rmode.vm86_active))
5221 return 0;
5222 else {
5223 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
5224 return VMX_AR_DPL(ar);
5225 }
5226 }
5227
5228 static u32 vmx_segment_access_rights(struct kvm_segment *var)
5229 {
5230 u32 ar;
5231
5232 if (var->unusable || !var->present)
5233 ar = 1 << 16;
5234 else {
5235 ar = var->type & 15;
5236 ar |= (var->s & 1) << 4;
5237 ar |= (var->dpl & 3) << 5;
5238 ar |= (var->present & 1) << 7;
5239 ar |= (var->avl & 1) << 12;
5240 ar |= (var->l & 1) << 13;
5241 ar |= (var->db & 1) << 14;
5242 ar |= (var->g & 1) << 15;
5243 }
5244
5245 return ar;
5246 }
5247
5248 static void vmx_set_segment(struct kvm_vcpu *vcpu,
5249 struct kvm_segment *var, int seg)
5250 {
5251 struct vcpu_vmx *vmx = to_vmx(vcpu);
5252 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5253
5254 vmx_segment_cache_clear(vmx);
5255
5256 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5257 vmx->rmode.segs[seg] = *var;
5258 if (seg == VCPU_SREG_TR)
5259 vmcs_write16(sf->selector, var->selector);
5260 else if (var->s)
5261 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
5262 goto out;
5263 }
5264
5265 vmcs_writel(sf->base, var->base);
5266 vmcs_write32(sf->limit, var->limit);
5267 vmcs_write16(sf->selector, var->selector);
5268
5269 /*
5270 * Fix the "Accessed" bit in AR field of segment registers for older
5271 * qemu binaries.
5272 * IA32 arch specifies that at the time of processor reset the
5273 * "Accessed" bit in the AR field of segment registers is 1. And qemu
5274 * is setting it to 0 in the userland code. This causes invalid guest
5275 * state vmexit when "unrestricted guest" mode is turned on.
5276 * Fix for this setup issue in cpu_reset is being pushed in the qemu
5277 * tree. Newer qemu binaries with that qemu fix would not need this
5278 * kvm hack.
5279 */
5280 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
5281 var->type |= 0x1; /* Accessed */
5282
5283 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
5284
5285 out:
5286 vmx->emulation_required = emulation_required(vcpu);
5287 }
5288
5289 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5290 {
5291 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
5292
5293 *db = (ar >> 14) & 1;
5294 *l = (ar >> 13) & 1;
5295 }
5296
5297 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5298 {
5299 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
5300 dt->address = vmcs_readl(GUEST_IDTR_BASE);
5301 }
5302
5303 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5304 {
5305 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
5306 vmcs_writel(GUEST_IDTR_BASE, dt->address);
5307 }
5308
5309 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5310 {
5311 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
5312 dt->address = vmcs_readl(GUEST_GDTR_BASE);
5313 }
5314
5315 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5316 {
5317 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
5318 vmcs_writel(GUEST_GDTR_BASE, dt->address);
5319 }
5320
5321 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
5322 {
5323 struct kvm_segment var;
5324 u32 ar;
5325
5326 vmx_get_segment(vcpu, &var, seg);
5327 var.dpl = 0x3;
5328 if (seg == VCPU_SREG_CS)
5329 var.type = 0x3;
5330 ar = vmx_segment_access_rights(&var);
5331
5332 if (var.base != (var.selector << 4))
5333 return false;
5334 if (var.limit != 0xffff)
5335 return false;
5336 if (ar != 0xf3)
5337 return false;
5338
5339 return true;
5340 }
5341
5342 static bool code_segment_valid(struct kvm_vcpu *vcpu)
5343 {
5344 struct kvm_segment cs;
5345 unsigned int cs_rpl;
5346
5347 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5348 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
5349
5350 if (cs.unusable)
5351 return false;
5352 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
5353 return false;
5354 if (!cs.s)
5355 return false;
5356 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
5357 if (cs.dpl > cs_rpl)
5358 return false;
5359 } else {
5360 if (cs.dpl != cs_rpl)
5361 return false;
5362 }
5363 if (!cs.present)
5364 return false;
5365
5366 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
5367 return true;
5368 }
5369
5370 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
5371 {
5372 struct kvm_segment ss;
5373 unsigned int ss_rpl;
5374
5375 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5376 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
5377
5378 if (ss.unusable)
5379 return true;
5380 if (ss.type != 3 && ss.type != 7)
5381 return false;
5382 if (!ss.s)
5383 return false;
5384 if (ss.dpl != ss_rpl) /* DPL != RPL */
5385 return false;
5386 if (!ss.present)
5387 return false;
5388
5389 return true;
5390 }
5391
5392 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
5393 {
5394 struct kvm_segment var;
5395 unsigned int rpl;
5396
5397 vmx_get_segment(vcpu, &var, seg);
5398 rpl = var.selector & SEGMENT_RPL_MASK;
5399
5400 if (var.unusable)
5401 return true;
5402 if (!var.s)
5403 return false;
5404 if (!var.present)
5405 return false;
5406 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
5407 if (var.dpl < rpl) /* DPL < RPL */
5408 return false;
5409 }
5410
5411 /* TODO: Add other members to kvm_segment_field to allow checking for other access
5412 * rights flags
5413 */
5414 return true;
5415 }
5416
5417 static bool tr_valid(struct kvm_vcpu *vcpu)
5418 {
5419 struct kvm_segment tr;
5420
5421 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
5422
5423 if (tr.unusable)
5424 return false;
5425 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
5426 return false;
5427 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
5428 return false;
5429 if (!tr.present)
5430 return false;
5431
5432 return true;
5433 }
5434
5435 static bool ldtr_valid(struct kvm_vcpu *vcpu)
5436 {
5437 struct kvm_segment ldtr;
5438
5439 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
5440
5441 if (ldtr.unusable)
5442 return true;
5443 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
5444 return false;
5445 if (ldtr.type != 2)
5446 return false;
5447 if (!ldtr.present)
5448 return false;
5449
5450 return true;
5451 }
5452
5453 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
5454 {
5455 struct kvm_segment cs, ss;
5456
5457 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5458 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5459
5460 return ((cs.selector & SEGMENT_RPL_MASK) ==
5461 (ss.selector & SEGMENT_RPL_MASK));
5462 }
5463
5464 /*
5465 * Check if guest state is valid. Returns true if valid, false if
5466 * not.
5467 * We assume that registers are always usable
5468 */
5469 static bool guest_state_valid(struct kvm_vcpu *vcpu)
5470 {
5471 if (enable_unrestricted_guest)
5472 return true;
5473
5474 /* real mode guest state checks */
5475 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5476 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
5477 return false;
5478 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
5479 return false;
5480 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
5481 return false;
5482 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
5483 return false;
5484 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
5485 return false;
5486 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
5487 return false;
5488 } else {
5489 /* protected mode guest state checks */
5490 if (!cs_ss_rpl_check(vcpu))
5491 return false;
5492 if (!code_segment_valid(vcpu))
5493 return false;
5494 if (!stack_segment_valid(vcpu))
5495 return false;
5496 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
5497 return false;
5498 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
5499 return false;
5500 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
5501 return false;
5502 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
5503 return false;
5504 if (!tr_valid(vcpu))
5505 return false;
5506 if (!ldtr_valid(vcpu))
5507 return false;
5508 }
5509 /* TODO:
5510 * - Add checks on RIP
5511 * - Add checks on RFLAGS
5512 */
5513
5514 return true;
5515 }
5516
5517 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
5518 {
5519 return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
5520 }
5521
5522 static int init_rmode_tss(struct kvm *kvm)
5523 {
5524 gfn_t fn;
5525 u16 data = 0;
5526 int idx, r;
5527
5528 idx = srcu_read_lock(&kvm->srcu);
5529 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
5530 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5531 if (r < 0)
5532 goto out;
5533 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
5534 r = kvm_write_guest_page(kvm, fn++, &data,
5535 TSS_IOPB_BASE_OFFSET, sizeof(u16));
5536 if (r < 0)
5537 goto out;
5538 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
5539 if (r < 0)
5540 goto out;
5541 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5542 if (r < 0)
5543 goto out;
5544 data = ~0;
5545 r = kvm_write_guest_page(kvm, fn, &data,
5546 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
5547 sizeof(u8));
5548 out:
5549 srcu_read_unlock(&kvm->srcu, idx);
5550 return r;
5551 }
5552
5553 static int init_rmode_identity_map(struct kvm *kvm)
5554 {
5555 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
5556 int i, idx, r = 0;
5557 kvm_pfn_t identity_map_pfn;
5558 u32 tmp;
5559
5560 /* Protect kvm_vmx->ept_identity_pagetable_done. */
5561 mutex_lock(&kvm->slots_lock);
5562
5563 if (likely(kvm_vmx->ept_identity_pagetable_done))
5564 goto out2;
5565
5566 if (!kvm_vmx->ept_identity_map_addr)
5567 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
5568 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
5569
5570 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
5571 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
5572 if (r < 0)
5573 goto out2;
5574
5575 idx = srcu_read_lock(&kvm->srcu);
5576 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
5577 if (r < 0)
5578 goto out;
5579 /* Set up identity-mapping pagetable for EPT in real mode */
5580 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
5581 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
5582 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
5583 r = kvm_write_guest_page(kvm, identity_map_pfn,
5584 &tmp, i * sizeof(tmp), sizeof(tmp));
5585 if (r < 0)
5586 goto out;
5587 }
5588 kvm_vmx->ept_identity_pagetable_done = true;
5589
5590 out:
5591 srcu_read_unlock(&kvm->srcu, idx);
5592
5593 out2:
5594 mutex_unlock(&kvm->slots_lock);
5595 return r;
5596 }
5597
5598 static void seg_setup(int seg)
5599 {
5600 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5601 unsigned int ar;
5602
5603 vmcs_write16(sf->selector, 0);
5604 vmcs_writel(sf->base, 0);
5605 vmcs_write32(sf->limit, 0xffff);
5606 ar = 0x93;
5607 if (seg == VCPU_SREG_CS)
5608 ar |= 0x08; /* code segment */
5609
5610 vmcs_write32(sf->ar_bytes, ar);
5611 }
5612
5613 static int alloc_apic_access_page(struct kvm *kvm)
5614 {
5615 struct page *page;
5616 int r = 0;
5617
5618 mutex_lock(&kvm->slots_lock);
5619 if (kvm->arch.apic_access_page_done)
5620 goto out;
5621 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
5622 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
5623 if (r)
5624 goto out;
5625
5626 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
5627 if (is_error_page(page)) {
5628 r = -EFAULT;
5629 goto out;
5630 }
5631
5632 /*
5633 * Do not pin the page in memory, so that memory hot-unplug
5634 * is able to migrate it.
5635 */
5636 put_page(page);
5637 kvm->arch.apic_access_page_done = true;
5638 out:
5639 mutex_unlock(&kvm->slots_lock);
5640 return r;
5641 }
5642
5643 static int allocate_vpid(void)
5644 {
5645 int vpid;
5646
5647 if (!enable_vpid)
5648 return 0;
5649 spin_lock(&vmx_vpid_lock);
5650 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5651 if (vpid < VMX_NR_VPIDS)
5652 __set_bit(vpid, vmx_vpid_bitmap);
5653 else
5654 vpid = 0;
5655 spin_unlock(&vmx_vpid_lock);
5656 return vpid;
5657 }
5658
5659 static void free_vpid(int vpid)
5660 {
5661 if (!enable_vpid || vpid == 0)
5662 return;
5663 spin_lock(&vmx_vpid_lock);
5664 __clear_bit(vpid, vmx_vpid_bitmap);
5665 spin_unlock(&vmx_vpid_lock);
5666 }
5667
5668 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5669 u32 msr, int type)
5670 {
5671 int f = sizeof(unsigned long);
5672
5673 if (!cpu_has_vmx_msr_bitmap())
5674 return;
5675
5676 if (static_branch_unlikely(&enable_evmcs))
5677 evmcs_touch_msr_bitmap();
5678
5679 /*
5680 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5681 * have the write-low and read-high bitmap offsets the wrong way round.
5682 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5683 */
5684 if (msr <= 0x1fff) {
5685 if (type & MSR_TYPE_R)
5686 /* read-low */
5687 __clear_bit(msr, msr_bitmap + 0x000 / f);
5688
5689 if (type & MSR_TYPE_W)
5690 /* write-low */
5691 __clear_bit(msr, msr_bitmap + 0x800 / f);
5692
5693 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5694 msr &= 0x1fff;
5695 if (type & MSR_TYPE_R)
5696 /* read-high */
5697 __clear_bit(msr, msr_bitmap + 0x400 / f);
5698
5699 if (type & MSR_TYPE_W)
5700 /* write-high */
5701 __clear_bit(msr, msr_bitmap + 0xc00 / f);
5702
5703 }
5704 }
5705
5706 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5707 u32 msr, int type)
5708 {
5709 int f = sizeof(unsigned long);
5710
5711 if (!cpu_has_vmx_msr_bitmap())
5712 return;
5713
5714 if (static_branch_unlikely(&enable_evmcs))
5715 evmcs_touch_msr_bitmap();
5716
5717 /*
5718 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5719 * have the write-low and read-high bitmap offsets the wrong way round.
5720 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5721 */
5722 if (msr <= 0x1fff) {
5723 if (type & MSR_TYPE_R)
5724 /* read-low */
5725 __set_bit(msr, msr_bitmap + 0x000 / f);
5726
5727 if (type & MSR_TYPE_W)
5728 /* write-low */
5729 __set_bit(msr, msr_bitmap + 0x800 / f);
5730
5731 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5732 msr &= 0x1fff;
5733 if (type & MSR_TYPE_R)
5734 /* read-high */
5735 __set_bit(msr, msr_bitmap + 0x400 / f);
5736
5737 if (type & MSR_TYPE_W)
5738 /* write-high */
5739 __set_bit(msr, msr_bitmap + 0xc00 / f);
5740
5741 }
5742 }
5743
5744 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
5745 u32 msr, int type, bool value)
5746 {
5747 if (value)
5748 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
5749 else
5750 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
5751 }
5752
5753 /*
5754 * If a msr is allowed by L0, we should check whether it is allowed by L1.
5755 * The corresponding bit will be cleared unless both of L0 and L1 allow it.
5756 */
5757 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
5758 unsigned long *msr_bitmap_nested,
5759 u32 msr, int type)
5760 {
5761 int f = sizeof(unsigned long);
5762
5763 /*
5764 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5765 * have the write-low and read-high bitmap offsets the wrong way round.
5766 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5767 */
5768 if (msr <= 0x1fff) {
5769 if (type & MSR_TYPE_R &&
5770 !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
5771 /* read-low */
5772 __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
5773
5774 if (type & MSR_TYPE_W &&
5775 !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
5776 /* write-low */
5777 __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
5778
5779 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5780 msr &= 0x1fff;
5781 if (type & MSR_TYPE_R &&
5782 !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
5783 /* read-high */
5784 __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
5785
5786 if (type & MSR_TYPE_W &&
5787 !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
5788 /* write-high */
5789 __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
5790
5791 }
5792 }
5793
5794 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
5795 {
5796 u8 mode = 0;
5797
5798 if (cpu_has_secondary_exec_ctrls() &&
5799 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
5800 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
5801 mode |= MSR_BITMAP_MODE_X2APIC;
5802 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
5803 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
5804 }
5805
5806 return mode;
5807 }
5808
5809 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
5810
5811 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
5812 u8 mode)
5813 {
5814 int msr;
5815
5816 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
5817 unsigned word = msr / BITS_PER_LONG;
5818 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
5819 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
5820 }
5821
5822 if (mode & MSR_BITMAP_MODE_X2APIC) {
5823 /*
5824 * TPR reads and writes can be virtualized even if virtual interrupt
5825 * delivery is not in use.
5826 */
5827 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
5828 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
5829 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
5830 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
5831 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
5832 }
5833 }
5834 }
5835
5836 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
5837 {
5838 struct vcpu_vmx *vmx = to_vmx(vcpu);
5839 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
5840 u8 mode = vmx_msr_bitmap_mode(vcpu);
5841 u8 changed = mode ^ vmx->msr_bitmap_mode;
5842
5843 if (!changed)
5844 return;
5845
5846 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
5847 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
5848
5849 vmx->msr_bitmap_mode = mode;
5850 }
5851
5852 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
5853 {
5854 return enable_apicv;
5855 }
5856
5857 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
5858 {
5859 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5860 gfn_t gfn;
5861
5862 /*
5863 * Don't need to mark the APIC access page dirty; it is never
5864 * written to by the CPU during APIC virtualization.
5865 */
5866
5867 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
5868 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
5869 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5870 }
5871
5872 if (nested_cpu_has_posted_intr(vmcs12)) {
5873 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
5874 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5875 }
5876 }
5877
5878
5879 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
5880 {
5881 struct vcpu_vmx *vmx = to_vmx(vcpu);
5882 int max_irr;
5883 void *vapic_page;
5884 u16 status;
5885
5886 if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
5887 return;
5888
5889 vmx->nested.pi_pending = false;
5890 if (!pi_test_and_clear_on(vmx->nested.pi_desc))
5891 return;
5892
5893 max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
5894 if (max_irr != 256) {
5895 vapic_page = kmap(vmx->nested.virtual_apic_page);
5896 __kvm_apic_update_irr(vmx->nested.pi_desc->pir,
5897 vapic_page, &max_irr);
5898 kunmap(vmx->nested.virtual_apic_page);
5899
5900 status = vmcs_read16(GUEST_INTR_STATUS);
5901 if ((u8)max_irr > ((u8)status & 0xff)) {
5902 status &= ~0xff;
5903 status |= (u8)max_irr;
5904 vmcs_write16(GUEST_INTR_STATUS, status);
5905 }
5906 }
5907
5908 nested_mark_vmcs12_pages_dirty(vcpu);
5909 }
5910
5911 static u8 vmx_get_rvi(void)
5912 {
5913 return vmcs_read16(GUEST_INTR_STATUS) & 0xff;
5914 }
5915
5916 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
5917 {
5918 struct vcpu_vmx *vmx = to_vmx(vcpu);
5919 void *vapic_page;
5920 u32 vppr;
5921 int rvi;
5922
5923 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
5924 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
5925 WARN_ON_ONCE(!vmx->nested.virtual_apic_page))
5926 return false;
5927
5928 rvi = vmx_get_rvi();
5929
5930 vapic_page = kmap(vmx->nested.virtual_apic_page);
5931 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
5932 kunmap(vmx->nested.virtual_apic_page);
5933
5934 return ((rvi & 0xf0) > (vppr & 0xf0));
5935 }
5936
5937 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
5938 bool nested)
5939 {
5940 #ifdef CONFIG_SMP
5941 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
5942
5943 if (vcpu->mode == IN_GUEST_MODE) {
5944 /*
5945 * The vector of interrupt to be delivered to vcpu had
5946 * been set in PIR before this function.
5947 *
5948 * Following cases will be reached in this block, and
5949 * we always send a notification event in all cases as
5950 * explained below.
5951 *
5952 * Case 1: vcpu keeps in non-root mode. Sending a
5953 * notification event posts the interrupt to vcpu.
5954 *
5955 * Case 2: vcpu exits to root mode and is still
5956 * runnable. PIR will be synced to vIRR before the
5957 * next vcpu entry. Sending a notification event in
5958 * this case has no effect, as vcpu is not in root
5959 * mode.
5960 *
5961 * Case 3: vcpu exits to root mode and is blocked.
5962 * vcpu_block() has already synced PIR to vIRR and
5963 * never blocks vcpu if vIRR is not cleared. Therefore,
5964 * a blocked vcpu here does not wait for any requested
5965 * interrupts in PIR, and sending a notification event
5966 * which has no effect is safe here.
5967 */
5968
5969 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
5970 return true;
5971 }
5972 #endif
5973 return false;
5974 }
5975
5976 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
5977 int vector)
5978 {
5979 struct vcpu_vmx *vmx = to_vmx(vcpu);
5980
5981 if (is_guest_mode(vcpu) &&
5982 vector == vmx->nested.posted_intr_nv) {
5983 /*
5984 * If a posted intr is not recognized by hardware,
5985 * we will accomplish it in the next vmentry.
5986 */
5987 vmx->nested.pi_pending = true;
5988 kvm_make_request(KVM_REQ_EVENT, vcpu);
5989 /* the PIR and ON have been set by L1. */
5990 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
5991 kvm_vcpu_kick(vcpu);
5992 return 0;
5993 }
5994 return -1;
5995 }
5996 /*
5997 * Send interrupt to vcpu via posted interrupt way.
5998 * 1. If target vcpu is running(non-root mode), send posted interrupt
5999 * notification to vcpu and hardware will sync PIR to vIRR atomically.
6000 * 2. If target vcpu isn't running(root mode), kick it to pick up the
6001 * interrupt from PIR in next vmentry.
6002 */
6003 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
6004 {
6005 struct vcpu_vmx *vmx = to_vmx(vcpu);
6006 int r;
6007
6008 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
6009 if (!r)
6010 return;
6011
6012 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
6013 return;
6014
6015 /* If a previous notification has sent the IPI, nothing to do. */
6016 if (pi_test_and_set_on(&vmx->pi_desc))
6017 return;
6018
6019 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
6020 kvm_vcpu_kick(vcpu);
6021 }
6022
6023 /*
6024 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
6025 * will not change in the lifetime of the guest.
6026 * Note that host-state that does change is set elsewhere. E.g., host-state
6027 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
6028 */
6029 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
6030 {
6031 u32 low32, high32;
6032 unsigned long tmpl;
6033 struct desc_ptr dt;
6034 unsigned long cr0, cr3, cr4;
6035
6036 cr0 = read_cr0();
6037 WARN_ON(cr0 & X86_CR0_TS);
6038 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
6039
6040 /*
6041 * Save the most likely value for this task's CR3 in the VMCS.
6042 * We can't use __get_current_cr3_fast() because we're not atomic.
6043 */
6044 cr3 = __read_cr3();
6045 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
6046 vmx->loaded_vmcs->host_state.cr3 = cr3;
6047
6048 /* Save the most likely value for this task's CR4 in the VMCS. */
6049 cr4 = cr4_read_shadow();
6050 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
6051 vmx->loaded_vmcs->host_state.cr4 = cr4;
6052
6053 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
6054 #ifdef CONFIG_X86_64
6055 /*
6056 * Load null selectors, so we can avoid reloading them in
6057 * vmx_prepare_switch_to_host(), in case userspace uses
6058 * the null selectors too (the expected case).
6059 */
6060 vmcs_write16(HOST_DS_SELECTOR, 0);
6061 vmcs_write16(HOST_ES_SELECTOR, 0);
6062 #else
6063 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
6064 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
6065 #endif
6066 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
6067 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
6068
6069 store_idt(&dt);
6070 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
6071 vmx->host_idt_base = dt.address;
6072
6073 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
6074
6075 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
6076 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
6077 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
6078 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
6079
6080 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
6081 rdmsr(MSR_IA32_CR_PAT, low32, high32);
6082 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
6083 }
6084
6085 if (cpu_has_load_ia32_efer())
6086 vmcs_write64(HOST_IA32_EFER, host_efer);
6087 }
6088
6089 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
6090 {
6091 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
6092 if (enable_ept)
6093 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
6094 if (is_guest_mode(&vmx->vcpu))
6095 vmx->vcpu.arch.cr4_guest_owned_bits &=
6096 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
6097 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
6098 }
6099
6100 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
6101 {
6102 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
6103
6104 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
6105 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
6106
6107 if (!enable_vnmi)
6108 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
6109
6110 /* Enable the preemption timer dynamically */
6111 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
6112 return pin_based_exec_ctrl;
6113 }
6114
6115 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
6116 {
6117 struct vcpu_vmx *vmx = to_vmx(vcpu);
6118
6119 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6120 if (cpu_has_secondary_exec_ctrls()) {
6121 if (kvm_vcpu_apicv_active(vcpu))
6122 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
6123 SECONDARY_EXEC_APIC_REGISTER_VIRT |
6124 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6125 else
6126 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
6127 SECONDARY_EXEC_APIC_REGISTER_VIRT |
6128 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6129 }
6130
6131 if (cpu_has_vmx_msr_bitmap())
6132 vmx_update_msr_bitmap(vcpu);
6133 }
6134
6135 static u32 vmx_vmentry_ctrl(void)
6136 {
6137 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
6138 return vmcs_config.vmentry_ctrl &
6139 ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL | VM_ENTRY_LOAD_IA32_EFER);
6140 }
6141
6142 static u32 vmx_vmexit_ctrl(void)
6143 {
6144 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
6145 return vmcs_config.vmexit_ctrl &
6146 ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
6147 }
6148
6149 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
6150 {
6151 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
6152
6153 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
6154 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
6155
6156 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
6157 exec_control &= ~CPU_BASED_TPR_SHADOW;
6158 #ifdef CONFIG_X86_64
6159 exec_control |= CPU_BASED_CR8_STORE_EXITING |
6160 CPU_BASED_CR8_LOAD_EXITING;
6161 #endif
6162 }
6163 if (!enable_ept)
6164 exec_control |= CPU_BASED_CR3_STORE_EXITING |
6165 CPU_BASED_CR3_LOAD_EXITING |
6166 CPU_BASED_INVLPG_EXITING;
6167 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
6168 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
6169 CPU_BASED_MONITOR_EXITING);
6170 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
6171 exec_control &= ~CPU_BASED_HLT_EXITING;
6172 return exec_control;
6173 }
6174
6175
6176 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
6177 {
6178 struct kvm_vcpu *vcpu = &vmx->vcpu;
6179
6180 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
6181
6182 if (!cpu_need_virtualize_apic_accesses(vcpu))
6183 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6184 if (vmx->vpid == 0)
6185 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
6186 if (!enable_ept) {
6187 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
6188 enable_unrestricted_guest = 0;
6189 }
6190 if (!enable_unrestricted_guest)
6191 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
6192 if (kvm_pause_in_guest(vmx->vcpu.kvm))
6193 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
6194 if (!kvm_vcpu_apicv_active(vcpu))
6195 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
6196 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6197 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6198
6199 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
6200 * in vmx_set_cr4. */
6201 exec_control &= ~SECONDARY_EXEC_DESC;
6202
6203 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
6204 (handle_vmptrld).
6205 We can NOT enable shadow_vmcs here because we don't have yet
6206 a current VMCS12
6207 */
6208 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
6209
6210 if (!enable_pml)
6211 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
6212
6213 if (vmx_xsaves_supported()) {
6214 /* Exposing XSAVES only when XSAVE is exposed */
6215 bool xsaves_enabled =
6216 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
6217 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
6218
6219 if (!xsaves_enabled)
6220 exec_control &= ~SECONDARY_EXEC_XSAVES;
6221
6222 if (nested) {
6223 if (xsaves_enabled)
6224 vmx->nested.msrs.secondary_ctls_high |=
6225 SECONDARY_EXEC_XSAVES;
6226 else
6227 vmx->nested.msrs.secondary_ctls_high &=
6228 ~SECONDARY_EXEC_XSAVES;
6229 }
6230 }
6231
6232 if (vmx_rdtscp_supported()) {
6233 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
6234 if (!rdtscp_enabled)
6235 exec_control &= ~SECONDARY_EXEC_RDTSCP;
6236
6237 if (nested) {
6238 if (rdtscp_enabled)
6239 vmx->nested.msrs.secondary_ctls_high |=
6240 SECONDARY_EXEC_RDTSCP;
6241 else
6242 vmx->nested.msrs.secondary_ctls_high &=
6243 ~SECONDARY_EXEC_RDTSCP;
6244 }
6245 }
6246
6247 if (vmx_invpcid_supported()) {
6248 /* Exposing INVPCID only when PCID is exposed */
6249 bool invpcid_enabled =
6250 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
6251 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
6252
6253 if (!invpcid_enabled) {
6254 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
6255 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
6256 }
6257
6258 if (nested) {
6259 if (invpcid_enabled)
6260 vmx->nested.msrs.secondary_ctls_high |=
6261 SECONDARY_EXEC_ENABLE_INVPCID;
6262 else
6263 vmx->nested.msrs.secondary_ctls_high &=
6264 ~SECONDARY_EXEC_ENABLE_INVPCID;
6265 }
6266 }
6267
6268 if (vmx_rdrand_supported()) {
6269 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
6270 if (rdrand_enabled)
6271 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
6272
6273 if (nested) {
6274 if (rdrand_enabled)
6275 vmx->nested.msrs.secondary_ctls_high |=
6276 SECONDARY_EXEC_RDRAND_EXITING;
6277 else
6278 vmx->nested.msrs.secondary_ctls_high &=
6279 ~SECONDARY_EXEC_RDRAND_EXITING;
6280 }
6281 }
6282
6283 if (vmx_rdseed_supported()) {
6284 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
6285 if (rdseed_enabled)
6286 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
6287
6288 if (nested) {
6289 if (rdseed_enabled)
6290 vmx->nested.msrs.secondary_ctls_high |=
6291 SECONDARY_EXEC_RDSEED_EXITING;
6292 else
6293 vmx->nested.msrs.secondary_ctls_high &=
6294 ~SECONDARY_EXEC_RDSEED_EXITING;
6295 }
6296 }
6297
6298 vmx->secondary_exec_control = exec_control;
6299 }
6300
6301 static void ept_set_mmio_spte_mask(void)
6302 {
6303 /*
6304 * EPT Misconfigurations can be generated if the value of bits 2:0
6305 * of an EPT paging-structure entry is 110b (write/execute).
6306 */
6307 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
6308 VMX_EPT_MISCONFIG_WX_VALUE);
6309 }
6310
6311 #define VMX_XSS_EXIT_BITMAP 0
6312 /*
6313 * Sets up the vmcs for emulated real mode.
6314 */
6315 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
6316 {
6317 int i;
6318
6319 if (enable_shadow_vmcs) {
6320 /*
6321 * At vCPU creation, "VMWRITE to any supported field
6322 * in the VMCS" is supported, so use the more
6323 * permissive vmx_vmread_bitmap to specify both read
6324 * and write permissions for the shadow VMCS.
6325 */
6326 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
6327 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmread_bitmap));
6328 }
6329 if (cpu_has_vmx_msr_bitmap())
6330 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
6331
6332 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
6333
6334 /* Control */
6335 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6336 vmx->hv_deadline_tsc = -1;
6337
6338 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
6339
6340 if (cpu_has_secondary_exec_ctrls()) {
6341 vmx_compute_secondary_exec_control(vmx);
6342 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6343 vmx->secondary_exec_control);
6344 }
6345
6346 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
6347 vmcs_write64(EOI_EXIT_BITMAP0, 0);
6348 vmcs_write64(EOI_EXIT_BITMAP1, 0);
6349 vmcs_write64(EOI_EXIT_BITMAP2, 0);
6350 vmcs_write64(EOI_EXIT_BITMAP3, 0);
6351
6352 vmcs_write16(GUEST_INTR_STATUS, 0);
6353
6354 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
6355 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
6356 }
6357
6358 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
6359 vmcs_write32(PLE_GAP, ple_gap);
6360 vmx->ple_window = ple_window;
6361 vmx->ple_window_dirty = true;
6362 }
6363
6364 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
6365 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
6366 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
6367
6368 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
6369 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
6370 vmx_set_constant_host_state(vmx);
6371 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
6372 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
6373
6374 if (cpu_has_vmx_vmfunc())
6375 vmcs_write64(VM_FUNCTION_CONTROL, 0);
6376
6377 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
6378 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
6379 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
6380 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
6381 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
6382
6383 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
6384 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
6385
6386 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6387 u32 index = vmx_msr_index[i];
6388 u32 data_low, data_high;
6389 int j = vmx->nmsrs;
6390
6391 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6392 continue;
6393 if (wrmsr_safe(index, data_low, data_high) < 0)
6394 continue;
6395 vmx->guest_msrs[j].index = i;
6396 vmx->guest_msrs[j].data = 0;
6397 vmx->guest_msrs[j].mask = -1ull;
6398 ++vmx->nmsrs;
6399 }
6400
6401 vmx->arch_capabilities = kvm_get_arch_capabilities();
6402
6403 vm_exit_controls_init(vmx, vmx_vmexit_ctrl());
6404
6405 /* 22.2.1, 20.8.1 */
6406 vm_entry_controls_init(vmx, vmx_vmentry_ctrl());
6407
6408 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
6409 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
6410
6411 set_cr4_guest_host_mask(vmx);
6412
6413 if (vmx_xsaves_supported())
6414 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
6415
6416 if (enable_pml) {
6417 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
6418 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6419 }
6420
6421 if (cpu_has_vmx_encls_vmexit())
6422 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
6423 }
6424
6425 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
6426 {
6427 struct vcpu_vmx *vmx = to_vmx(vcpu);
6428 struct msr_data apic_base_msr;
6429 u64 cr0;
6430
6431 vmx->rmode.vm86_active = 0;
6432 vmx->spec_ctrl = 0;
6433
6434 vcpu->arch.microcode_version = 0x100000000ULL;
6435 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
6436 kvm_set_cr8(vcpu, 0);
6437
6438 if (!init_event) {
6439 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
6440 MSR_IA32_APICBASE_ENABLE;
6441 if (kvm_vcpu_is_reset_bsp(vcpu))
6442 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
6443 apic_base_msr.host_initiated = true;
6444 kvm_set_apic_base(vcpu, &apic_base_msr);
6445 }
6446
6447 vmx_segment_cache_clear(vmx);
6448
6449 seg_setup(VCPU_SREG_CS);
6450 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
6451 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
6452
6453 seg_setup(VCPU_SREG_DS);
6454 seg_setup(VCPU_SREG_ES);
6455 seg_setup(VCPU_SREG_FS);
6456 seg_setup(VCPU_SREG_GS);
6457 seg_setup(VCPU_SREG_SS);
6458
6459 vmcs_write16(GUEST_TR_SELECTOR, 0);
6460 vmcs_writel(GUEST_TR_BASE, 0);
6461 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
6462 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
6463
6464 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
6465 vmcs_writel(GUEST_LDTR_BASE, 0);
6466 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
6467 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
6468
6469 if (!init_event) {
6470 vmcs_write32(GUEST_SYSENTER_CS, 0);
6471 vmcs_writel(GUEST_SYSENTER_ESP, 0);
6472 vmcs_writel(GUEST_SYSENTER_EIP, 0);
6473 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
6474 }
6475
6476 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6477 kvm_rip_write(vcpu, 0xfff0);
6478
6479 vmcs_writel(GUEST_GDTR_BASE, 0);
6480 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
6481
6482 vmcs_writel(GUEST_IDTR_BASE, 0);
6483 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
6484
6485 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
6486 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
6487 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
6488 if (kvm_mpx_supported())
6489 vmcs_write64(GUEST_BNDCFGS, 0);
6490
6491 setup_msrs(vmx);
6492
6493 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
6494
6495 if (cpu_has_vmx_tpr_shadow() && !init_event) {
6496 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
6497 if (cpu_need_tpr_shadow(vcpu))
6498 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
6499 __pa(vcpu->arch.apic->regs));
6500 vmcs_write32(TPR_THRESHOLD, 0);
6501 }
6502
6503 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6504
6505 if (vmx->vpid != 0)
6506 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
6507
6508 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
6509 vmx->vcpu.arch.cr0 = cr0;
6510 vmx_set_cr0(vcpu, cr0); /* enter rmode */
6511 vmx_set_cr4(vcpu, 0);
6512 vmx_set_efer(vcpu, 0);
6513
6514 update_exception_bitmap(vcpu);
6515
6516 vpid_sync_context(vmx->vpid);
6517 if (init_event)
6518 vmx_clear_hlt(vcpu);
6519 }
6520
6521 /*
6522 * In nested virtualization, check if L1 asked to exit on external interrupts.
6523 * For most existing hypervisors, this will always return true.
6524 */
6525 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
6526 {
6527 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
6528 PIN_BASED_EXT_INTR_MASK;
6529 }
6530
6531 /*
6532 * In nested virtualization, check if L1 has set
6533 * VM_EXIT_ACK_INTR_ON_EXIT
6534 */
6535 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
6536 {
6537 return get_vmcs12(vcpu)->vm_exit_controls &
6538 VM_EXIT_ACK_INTR_ON_EXIT;
6539 }
6540
6541 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
6542 {
6543 return nested_cpu_has_nmi_exiting(get_vmcs12(vcpu));
6544 }
6545
6546 static void enable_irq_window(struct kvm_vcpu *vcpu)
6547 {
6548 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6549 CPU_BASED_VIRTUAL_INTR_PENDING);
6550 }
6551
6552 static void enable_nmi_window(struct kvm_vcpu *vcpu)
6553 {
6554 if (!enable_vnmi ||
6555 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
6556 enable_irq_window(vcpu);
6557 return;
6558 }
6559
6560 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6561 CPU_BASED_VIRTUAL_NMI_PENDING);
6562 }
6563
6564 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
6565 {
6566 struct vcpu_vmx *vmx = to_vmx(vcpu);
6567 uint32_t intr;
6568 int irq = vcpu->arch.interrupt.nr;
6569
6570 trace_kvm_inj_virq(irq);
6571
6572 ++vcpu->stat.irq_injections;
6573 if (vmx->rmode.vm86_active) {
6574 int inc_eip = 0;
6575 if (vcpu->arch.interrupt.soft)
6576 inc_eip = vcpu->arch.event_exit_inst_len;
6577 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
6578 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6579 return;
6580 }
6581 intr = irq | INTR_INFO_VALID_MASK;
6582 if (vcpu->arch.interrupt.soft) {
6583 intr |= INTR_TYPE_SOFT_INTR;
6584 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6585 vmx->vcpu.arch.event_exit_inst_len);
6586 } else
6587 intr |= INTR_TYPE_EXT_INTR;
6588 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
6589
6590 vmx_clear_hlt(vcpu);
6591 }
6592
6593 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
6594 {
6595 struct vcpu_vmx *vmx = to_vmx(vcpu);
6596
6597 if (!enable_vnmi) {
6598 /*
6599 * Tracking the NMI-blocked state in software is built upon
6600 * finding the next open IRQ window. This, in turn, depends on
6601 * well-behaving guests: They have to keep IRQs disabled at
6602 * least as long as the NMI handler runs. Otherwise we may
6603 * cause NMI nesting, maybe breaking the guest. But as this is
6604 * highly unlikely, we can live with the residual risk.
6605 */
6606 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
6607 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6608 }
6609
6610 ++vcpu->stat.nmi_injections;
6611 vmx->loaded_vmcs->nmi_known_unmasked = false;
6612
6613 if (vmx->rmode.vm86_active) {
6614 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
6615 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6616 return;
6617 }
6618
6619 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6620 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
6621
6622 vmx_clear_hlt(vcpu);
6623 }
6624
6625 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
6626 {
6627 struct vcpu_vmx *vmx = to_vmx(vcpu);
6628 bool masked;
6629
6630 if (!enable_vnmi)
6631 return vmx->loaded_vmcs->soft_vnmi_blocked;
6632 if (vmx->loaded_vmcs->nmi_known_unmasked)
6633 return false;
6634 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
6635 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6636 return masked;
6637 }
6638
6639 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
6640 {
6641 struct vcpu_vmx *vmx = to_vmx(vcpu);
6642
6643 if (!enable_vnmi) {
6644 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
6645 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
6646 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6647 }
6648 } else {
6649 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6650 if (masked)
6651 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6652 GUEST_INTR_STATE_NMI);
6653 else
6654 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
6655 GUEST_INTR_STATE_NMI);
6656 }
6657 }
6658
6659 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
6660 {
6661 if (to_vmx(vcpu)->nested.nested_run_pending)
6662 return 0;
6663
6664 if (!enable_vnmi &&
6665 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
6666 return 0;
6667
6668 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6669 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
6670 | GUEST_INTR_STATE_NMI));
6671 }
6672
6673 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
6674 {
6675 return (!to_vmx(vcpu)->nested.nested_run_pending &&
6676 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6677 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6678 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6679 }
6680
6681 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6682 {
6683 int ret;
6684
6685 if (enable_unrestricted_guest)
6686 return 0;
6687
6688 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6689 PAGE_SIZE * 3);
6690 if (ret)
6691 return ret;
6692 to_kvm_vmx(kvm)->tss_addr = addr;
6693 return init_rmode_tss(kvm);
6694 }
6695
6696 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
6697 {
6698 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
6699 return 0;
6700 }
6701
6702 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6703 {
6704 switch (vec) {
6705 case BP_VECTOR:
6706 /*
6707 * Update instruction length as we may reinject the exception
6708 * from user space while in guest debugging mode.
6709 */
6710 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6711 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6712 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6713 return false;
6714 /* fall through */
6715 case DB_VECTOR:
6716 if (vcpu->guest_debug &
6717 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6718 return false;
6719 /* fall through */
6720 case DE_VECTOR:
6721 case OF_VECTOR:
6722 case BR_VECTOR:
6723 case UD_VECTOR:
6724 case DF_VECTOR:
6725 case SS_VECTOR:
6726 case GP_VECTOR:
6727 case MF_VECTOR:
6728 return true;
6729 break;
6730 }
6731 return false;
6732 }
6733
6734 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
6735 int vec, u32 err_code)
6736 {
6737 /*
6738 * Instruction with address size override prefix opcode 0x67
6739 * Cause the #SS fault with 0 error code in VM86 mode.
6740 */
6741 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
6742 if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
6743 if (vcpu->arch.halt_request) {
6744 vcpu->arch.halt_request = 0;
6745 return kvm_vcpu_halt(vcpu);
6746 }
6747 return 1;
6748 }
6749 return 0;
6750 }
6751
6752 /*
6753 * Forward all other exceptions that are valid in real mode.
6754 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
6755 * the required debugging infrastructure rework.
6756 */
6757 kvm_queue_exception(vcpu, vec);
6758 return 1;
6759 }
6760
6761 /*
6762 * Trigger machine check on the host. We assume all the MSRs are already set up
6763 * by the CPU and that we still run on the same CPU as the MCE occurred on.
6764 * We pass a fake environment to the machine check handler because we want
6765 * the guest to be always treated like user space, no matter what context
6766 * it used internally.
6767 */
6768 static void kvm_machine_check(void)
6769 {
6770 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
6771 struct pt_regs regs = {
6772 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
6773 .flags = X86_EFLAGS_IF,
6774 };
6775
6776 do_machine_check(&regs, 0);
6777 #endif
6778 }
6779
6780 static int handle_machine_check(struct kvm_vcpu *vcpu)
6781 {
6782 /* already handled by vcpu_run */
6783 return 1;
6784 }
6785
6786 static int handle_exception(struct kvm_vcpu *vcpu)
6787 {
6788 struct vcpu_vmx *vmx = to_vmx(vcpu);
6789 struct kvm_run *kvm_run = vcpu->run;
6790 u32 intr_info, ex_no, error_code;
6791 unsigned long cr2, rip, dr6;
6792 u32 vect_info;
6793 enum emulation_result er;
6794
6795 vect_info = vmx->idt_vectoring_info;
6796 intr_info = vmx->exit_intr_info;
6797
6798 if (is_machine_check(intr_info))
6799 return handle_machine_check(vcpu);
6800
6801 if (is_nmi(intr_info))
6802 return 1; /* already handled by vmx_vcpu_run() */
6803
6804 if (is_invalid_opcode(intr_info))
6805 return handle_ud(vcpu);
6806
6807 error_code = 0;
6808 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
6809 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6810
6811 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
6812 WARN_ON_ONCE(!enable_vmware_backdoor);
6813 er = kvm_emulate_instruction(vcpu,
6814 EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
6815 if (er == EMULATE_USER_EXIT)
6816 return 0;
6817 else if (er != EMULATE_DONE)
6818 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
6819 return 1;
6820 }
6821
6822 /*
6823 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
6824 * MMIO, it is better to report an internal error.
6825 * See the comments in vmx_handle_exit.
6826 */
6827 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
6828 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
6829 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6830 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
6831 vcpu->run->internal.ndata = 3;
6832 vcpu->run->internal.data[0] = vect_info;
6833 vcpu->run->internal.data[1] = intr_info;
6834 vcpu->run->internal.data[2] = error_code;
6835 return 0;
6836 }
6837
6838 if (is_page_fault(intr_info)) {
6839 cr2 = vmcs_readl(EXIT_QUALIFICATION);
6840 /* EPT won't cause page fault directly */
6841 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
6842 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
6843 }
6844
6845 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
6846
6847 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
6848 return handle_rmode_exception(vcpu, ex_no, error_code);
6849
6850 switch (ex_no) {
6851 case AC_VECTOR:
6852 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
6853 return 1;
6854 case DB_VECTOR:
6855 dr6 = vmcs_readl(EXIT_QUALIFICATION);
6856 if (!(vcpu->guest_debug &
6857 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
6858 vcpu->arch.dr6 &= ~15;
6859 vcpu->arch.dr6 |= dr6 | DR6_RTM;
6860 if (is_icebp(intr_info))
6861 skip_emulated_instruction(vcpu);
6862
6863 kvm_queue_exception(vcpu, DB_VECTOR);
6864 return 1;
6865 }
6866 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
6867 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
6868 /* fall through */
6869 case BP_VECTOR:
6870 /*
6871 * Update instruction length as we may reinject #BP from
6872 * user space while in guest debugging mode. Reading it for
6873 * #DB as well causes no harm, it is not used in that case.
6874 */
6875 vmx->vcpu.arch.event_exit_inst_len =
6876 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6877 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6878 rip = kvm_rip_read(vcpu);
6879 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
6880 kvm_run->debug.arch.exception = ex_no;
6881 break;
6882 default:
6883 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
6884 kvm_run->ex.exception = ex_no;
6885 kvm_run->ex.error_code = error_code;
6886 break;
6887 }
6888 return 0;
6889 }
6890
6891 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
6892 {
6893 ++vcpu->stat.irq_exits;
6894 return 1;
6895 }
6896
6897 static int handle_triple_fault(struct kvm_vcpu *vcpu)
6898 {
6899 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6900 vcpu->mmio_needed = 0;
6901 return 0;
6902 }
6903
6904 static int handle_io(struct kvm_vcpu *vcpu)
6905 {
6906 unsigned long exit_qualification;
6907 int size, in, string;
6908 unsigned port;
6909
6910 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6911 string = (exit_qualification & 16) != 0;
6912
6913 ++vcpu->stat.io_exits;
6914
6915 if (string)
6916 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
6917
6918 port = exit_qualification >> 16;
6919 size = (exit_qualification & 7) + 1;
6920 in = (exit_qualification & 8) != 0;
6921
6922 return kvm_fast_pio(vcpu, size, port, in);
6923 }
6924
6925 static void
6926 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
6927 {
6928 /*
6929 * Patch in the VMCALL instruction:
6930 */
6931 hypercall[0] = 0x0f;
6932 hypercall[1] = 0x01;
6933 hypercall[2] = 0xc1;
6934 }
6935
6936 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
6937 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
6938 {
6939 if (is_guest_mode(vcpu)) {
6940 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6941 unsigned long orig_val = val;
6942
6943 /*
6944 * We get here when L2 changed cr0 in a way that did not change
6945 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6946 * but did change L0 shadowed bits. So we first calculate the
6947 * effective cr0 value that L1 would like to write into the
6948 * hardware. It consists of the L2-owned bits from the new
6949 * value combined with the L1-owned bits from L1's guest_cr0.
6950 */
6951 val = (val & ~vmcs12->cr0_guest_host_mask) |
6952 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6953
6954 if (!nested_guest_cr0_valid(vcpu, val))
6955 return 1;
6956
6957 if (kvm_set_cr0(vcpu, val))
6958 return 1;
6959 vmcs_writel(CR0_READ_SHADOW, orig_val);
6960 return 0;
6961 } else {
6962 if (to_vmx(vcpu)->nested.vmxon &&
6963 !nested_host_cr0_valid(vcpu, val))
6964 return 1;
6965
6966 return kvm_set_cr0(vcpu, val);
6967 }
6968 }
6969
6970 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6971 {
6972 if (is_guest_mode(vcpu)) {
6973 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6974 unsigned long orig_val = val;
6975
6976 /* analogously to handle_set_cr0 */
6977 val = (val & ~vmcs12->cr4_guest_host_mask) |
6978 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6979 if (kvm_set_cr4(vcpu, val))
6980 return 1;
6981 vmcs_writel(CR4_READ_SHADOW, orig_val);
6982 return 0;
6983 } else
6984 return kvm_set_cr4(vcpu, val);
6985 }
6986
6987 static int handle_desc(struct kvm_vcpu *vcpu)
6988 {
6989 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
6990 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
6991 }
6992
6993 static int handle_cr(struct kvm_vcpu *vcpu)
6994 {
6995 unsigned long exit_qualification, val;
6996 int cr;
6997 int reg;
6998 int err;
6999 int ret;
7000
7001 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7002 cr = exit_qualification & 15;
7003 reg = (exit_qualification >> 8) & 15;
7004 switch ((exit_qualification >> 4) & 3) {
7005 case 0: /* mov to cr */
7006 val = kvm_register_readl(vcpu, reg);
7007 trace_kvm_cr_write(cr, val);
7008 switch (cr) {
7009 case 0:
7010 err = handle_set_cr0(vcpu, val);
7011 return kvm_complete_insn_gp(vcpu, err);
7012 case 3:
7013 WARN_ON_ONCE(enable_unrestricted_guest);
7014 err = kvm_set_cr3(vcpu, val);
7015 return kvm_complete_insn_gp(vcpu, err);
7016 case 4:
7017 err = handle_set_cr4(vcpu, val);
7018 return kvm_complete_insn_gp(vcpu, err);
7019 case 8: {
7020 u8 cr8_prev = kvm_get_cr8(vcpu);
7021 u8 cr8 = (u8)val;
7022 err = kvm_set_cr8(vcpu, cr8);
7023 ret = kvm_complete_insn_gp(vcpu, err);
7024 if (lapic_in_kernel(vcpu))
7025 return ret;
7026 if (cr8_prev <= cr8)
7027 return ret;
7028 /*
7029 * TODO: we might be squashing a
7030 * KVM_GUESTDBG_SINGLESTEP-triggered
7031 * KVM_EXIT_DEBUG here.
7032 */
7033 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
7034 return 0;
7035 }
7036 }
7037 break;
7038 case 2: /* clts */
7039 WARN_ONCE(1, "Guest should always own CR0.TS");
7040 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
7041 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
7042 return kvm_skip_emulated_instruction(vcpu);
7043 case 1: /*mov from cr*/
7044 switch (cr) {
7045 case 3:
7046 WARN_ON_ONCE(enable_unrestricted_guest);
7047 val = kvm_read_cr3(vcpu);
7048 kvm_register_write(vcpu, reg, val);
7049 trace_kvm_cr_read(cr, val);
7050 return kvm_skip_emulated_instruction(vcpu);
7051 case 8:
7052 val = kvm_get_cr8(vcpu);
7053 kvm_register_write(vcpu, reg, val);
7054 trace_kvm_cr_read(cr, val);
7055 return kvm_skip_emulated_instruction(vcpu);
7056 }
7057 break;
7058 case 3: /* lmsw */
7059 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
7060 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
7061 kvm_lmsw(vcpu, val);
7062
7063 return kvm_skip_emulated_instruction(vcpu);
7064 default:
7065 break;
7066 }
7067 vcpu->run->exit_reason = 0;
7068 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
7069 (int)(exit_qualification >> 4) & 3, cr);
7070 return 0;
7071 }
7072
7073 static int handle_dr(struct kvm_vcpu *vcpu)
7074 {
7075 unsigned long exit_qualification;
7076 int dr, dr7, reg;
7077
7078 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7079 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
7080
7081 /* First, if DR does not exist, trigger UD */
7082 if (!kvm_require_dr(vcpu, dr))
7083 return 1;
7084
7085 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
7086 if (!kvm_require_cpl(vcpu, 0))
7087 return 1;
7088 dr7 = vmcs_readl(GUEST_DR7);
7089 if (dr7 & DR7_GD) {
7090 /*
7091 * As the vm-exit takes precedence over the debug trap, we
7092 * need to emulate the latter, either for the host or the
7093 * guest debugging itself.
7094 */
7095 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7096 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
7097 vcpu->run->debug.arch.dr7 = dr7;
7098 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
7099 vcpu->run->debug.arch.exception = DB_VECTOR;
7100 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
7101 return 0;
7102 } else {
7103 vcpu->arch.dr6 &= ~15;
7104 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
7105 kvm_queue_exception(vcpu, DB_VECTOR);
7106 return 1;
7107 }
7108 }
7109
7110 if (vcpu->guest_debug == 0) {
7111 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7112 CPU_BASED_MOV_DR_EXITING);
7113
7114 /*
7115 * No more DR vmexits; force a reload of the debug registers
7116 * and reenter on this instruction. The next vmexit will
7117 * retrieve the full state of the debug registers.
7118 */
7119 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
7120 return 1;
7121 }
7122
7123 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
7124 if (exit_qualification & TYPE_MOV_FROM_DR) {
7125 unsigned long val;
7126
7127 if (kvm_get_dr(vcpu, dr, &val))
7128 return 1;
7129 kvm_register_write(vcpu, reg, val);
7130 } else
7131 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
7132 return 1;
7133
7134 return kvm_skip_emulated_instruction(vcpu);
7135 }
7136
7137 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
7138 {
7139 return vcpu->arch.dr6;
7140 }
7141
7142 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
7143 {
7144 }
7145
7146 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
7147 {
7148 get_debugreg(vcpu->arch.db[0], 0);
7149 get_debugreg(vcpu->arch.db[1], 1);
7150 get_debugreg(vcpu->arch.db[2], 2);
7151 get_debugreg(vcpu->arch.db[3], 3);
7152 get_debugreg(vcpu->arch.dr6, 6);
7153 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
7154
7155 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
7156 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
7157 }
7158
7159 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
7160 {
7161 vmcs_writel(GUEST_DR7, val);
7162 }
7163
7164 static int handle_cpuid(struct kvm_vcpu *vcpu)
7165 {
7166 return kvm_emulate_cpuid(vcpu);
7167 }
7168
7169 static int handle_rdmsr(struct kvm_vcpu *vcpu)
7170 {
7171 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7172 struct msr_data msr_info;
7173
7174 msr_info.index = ecx;
7175 msr_info.host_initiated = false;
7176 if (vmx_get_msr(vcpu, &msr_info)) {
7177 trace_kvm_msr_read_ex(ecx);
7178 kvm_inject_gp(vcpu, 0);
7179 return 1;
7180 }
7181
7182 trace_kvm_msr_read(ecx, msr_info.data);
7183
7184 /* FIXME: handling of bits 32:63 of rax, rdx */
7185 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
7186 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
7187 return kvm_skip_emulated_instruction(vcpu);
7188 }
7189
7190 static int handle_wrmsr(struct kvm_vcpu *vcpu)
7191 {
7192 struct msr_data msr;
7193 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7194 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
7195 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
7196
7197 msr.data = data;
7198 msr.index = ecx;
7199 msr.host_initiated = false;
7200 if (kvm_set_msr(vcpu, &msr) != 0) {
7201 trace_kvm_msr_write_ex(ecx, data);
7202 kvm_inject_gp(vcpu, 0);
7203 return 1;
7204 }
7205
7206 trace_kvm_msr_write(ecx, data);
7207 return kvm_skip_emulated_instruction(vcpu);
7208 }
7209
7210 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
7211 {
7212 kvm_apic_update_ppr(vcpu);
7213 return 1;
7214 }
7215
7216 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
7217 {
7218 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7219 CPU_BASED_VIRTUAL_INTR_PENDING);
7220
7221 kvm_make_request(KVM_REQ_EVENT, vcpu);
7222
7223 ++vcpu->stat.irq_window_exits;
7224 return 1;
7225 }
7226
7227 static int handle_halt(struct kvm_vcpu *vcpu)
7228 {
7229 return kvm_emulate_halt(vcpu);
7230 }
7231
7232 static int handle_vmcall(struct kvm_vcpu *vcpu)
7233 {
7234 return kvm_emulate_hypercall(vcpu);
7235 }
7236
7237 static int handle_invd(struct kvm_vcpu *vcpu)
7238 {
7239 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7240 }
7241
7242 static int handle_invlpg(struct kvm_vcpu *vcpu)
7243 {
7244 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7245
7246 kvm_mmu_invlpg(vcpu, exit_qualification);
7247 return kvm_skip_emulated_instruction(vcpu);
7248 }
7249
7250 static int handle_rdpmc(struct kvm_vcpu *vcpu)
7251 {
7252 int err;
7253
7254 err = kvm_rdpmc(vcpu);
7255 return kvm_complete_insn_gp(vcpu, err);
7256 }
7257
7258 static int handle_wbinvd(struct kvm_vcpu *vcpu)
7259 {
7260 return kvm_emulate_wbinvd(vcpu);
7261 }
7262
7263 static int handle_xsetbv(struct kvm_vcpu *vcpu)
7264 {
7265 u64 new_bv = kvm_read_edx_eax(vcpu);
7266 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
7267
7268 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
7269 return kvm_skip_emulated_instruction(vcpu);
7270 return 1;
7271 }
7272
7273 static int handle_xsaves(struct kvm_vcpu *vcpu)
7274 {
7275 kvm_skip_emulated_instruction(vcpu);
7276 WARN(1, "this should never happen\n");
7277 return 1;
7278 }
7279
7280 static int handle_xrstors(struct kvm_vcpu *vcpu)
7281 {
7282 kvm_skip_emulated_instruction(vcpu);
7283 WARN(1, "this should never happen\n");
7284 return 1;
7285 }
7286
7287 static int handle_apic_access(struct kvm_vcpu *vcpu)
7288 {
7289 if (likely(fasteoi)) {
7290 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7291 int access_type, offset;
7292
7293 access_type = exit_qualification & APIC_ACCESS_TYPE;
7294 offset = exit_qualification & APIC_ACCESS_OFFSET;
7295 /*
7296 * Sane guest uses MOV to write EOI, with written value
7297 * not cared. So make a short-circuit here by avoiding
7298 * heavy instruction emulation.
7299 */
7300 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
7301 (offset == APIC_EOI)) {
7302 kvm_lapic_set_eoi(vcpu);
7303 return kvm_skip_emulated_instruction(vcpu);
7304 }
7305 }
7306 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7307 }
7308
7309 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
7310 {
7311 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7312 int vector = exit_qualification & 0xff;
7313
7314 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
7315 kvm_apic_set_eoi_accelerated(vcpu, vector);
7316 return 1;
7317 }
7318
7319 static int handle_apic_write(struct kvm_vcpu *vcpu)
7320 {
7321 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7322 u32 offset = exit_qualification & 0xfff;
7323
7324 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
7325 kvm_apic_write_nodecode(vcpu, offset);
7326 return 1;
7327 }
7328
7329 static int handle_task_switch(struct kvm_vcpu *vcpu)
7330 {
7331 struct vcpu_vmx *vmx = to_vmx(vcpu);
7332 unsigned long exit_qualification;
7333 bool has_error_code = false;
7334 u32 error_code = 0;
7335 u16 tss_selector;
7336 int reason, type, idt_v, idt_index;
7337
7338 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
7339 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
7340 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
7341
7342 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7343
7344 reason = (u32)exit_qualification >> 30;
7345 if (reason == TASK_SWITCH_GATE && idt_v) {
7346 switch (type) {
7347 case INTR_TYPE_NMI_INTR:
7348 vcpu->arch.nmi_injected = false;
7349 vmx_set_nmi_mask(vcpu, true);
7350 break;
7351 case INTR_TYPE_EXT_INTR:
7352 case INTR_TYPE_SOFT_INTR:
7353 kvm_clear_interrupt_queue(vcpu);
7354 break;
7355 case INTR_TYPE_HARD_EXCEPTION:
7356 if (vmx->idt_vectoring_info &
7357 VECTORING_INFO_DELIVER_CODE_MASK) {
7358 has_error_code = true;
7359 error_code =
7360 vmcs_read32(IDT_VECTORING_ERROR_CODE);
7361 }
7362 /* fall through */
7363 case INTR_TYPE_SOFT_EXCEPTION:
7364 kvm_clear_exception_queue(vcpu);
7365 break;
7366 default:
7367 break;
7368 }
7369 }
7370 tss_selector = exit_qualification;
7371
7372 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
7373 type != INTR_TYPE_EXT_INTR &&
7374 type != INTR_TYPE_NMI_INTR))
7375 skip_emulated_instruction(vcpu);
7376
7377 if (kvm_task_switch(vcpu, tss_selector,
7378 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
7379 has_error_code, error_code) == EMULATE_FAIL) {
7380 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7381 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7382 vcpu->run->internal.ndata = 0;
7383 return 0;
7384 }
7385
7386 /*
7387 * TODO: What about debug traps on tss switch?
7388 * Are we supposed to inject them and update dr6?
7389 */
7390
7391 return 1;
7392 }
7393
7394 static int handle_ept_violation(struct kvm_vcpu *vcpu)
7395 {
7396 unsigned long exit_qualification;
7397 gpa_t gpa;
7398 u64 error_code;
7399
7400 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7401
7402 /*
7403 * EPT violation happened while executing iret from NMI,
7404 * "blocked by NMI" bit has to be set before next VM entry.
7405 * There are errata that may cause this bit to not be set:
7406 * AAK134, BY25.
7407 */
7408 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
7409 enable_vnmi &&
7410 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
7411 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
7412
7413 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7414 trace_kvm_page_fault(gpa, exit_qualification);
7415
7416 /* Is it a read fault? */
7417 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
7418 ? PFERR_USER_MASK : 0;
7419 /* Is it a write fault? */
7420 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
7421 ? PFERR_WRITE_MASK : 0;
7422 /* Is it a fetch fault? */
7423 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
7424 ? PFERR_FETCH_MASK : 0;
7425 /* ept page table entry is present? */
7426 error_code |= (exit_qualification &
7427 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
7428 EPT_VIOLATION_EXECUTABLE))
7429 ? PFERR_PRESENT_MASK : 0;
7430
7431 error_code |= (exit_qualification & 0x100) != 0 ?
7432 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
7433
7434 vcpu->arch.exit_qualification = exit_qualification;
7435 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
7436 }
7437
7438 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
7439 {
7440 gpa_t gpa;
7441
7442 /*
7443 * A nested guest cannot optimize MMIO vmexits, because we have an
7444 * nGPA here instead of the required GPA.
7445 */
7446 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7447 if (!is_guest_mode(vcpu) &&
7448 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
7449 trace_kvm_fast_mmio(gpa);
7450 /*
7451 * Doing kvm_skip_emulated_instruction() depends on undefined
7452 * behavior: Intel's manual doesn't mandate
7453 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
7454 * occurs and while on real hardware it was observed to be set,
7455 * other hypervisors (namely Hyper-V) don't set it, we end up
7456 * advancing IP with some random value. Disable fast mmio when
7457 * running nested and keep it for real hardware in hope that
7458 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
7459 */
7460 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
7461 return kvm_skip_emulated_instruction(vcpu);
7462 else
7463 return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
7464 EMULATE_DONE;
7465 }
7466
7467 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
7468 }
7469
7470 static int handle_nmi_window(struct kvm_vcpu *vcpu)
7471 {
7472 WARN_ON_ONCE(!enable_vnmi);
7473 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7474 CPU_BASED_VIRTUAL_NMI_PENDING);
7475 ++vcpu->stat.nmi_window_exits;
7476 kvm_make_request(KVM_REQ_EVENT, vcpu);
7477
7478 return 1;
7479 }
7480
7481 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
7482 {
7483 struct vcpu_vmx *vmx = to_vmx(vcpu);
7484 enum emulation_result err = EMULATE_DONE;
7485 int ret = 1;
7486 u32 cpu_exec_ctrl;
7487 bool intr_window_requested;
7488 unsigned count = 130;
7489
7490 /*
7491 * We should never reach the point where we are emulating L2
7492 * due to invalid guest state as that means we incorrectly
7493 * allowed a nested VMEntry with an invalid vmcs12.
7494 */
7495 WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
7496
7497 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
7498 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
7499
7500 while (vmx->emulation_required && count-- != 0) {
7501 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
7502 return handle_interrupt_window(&vmx->vcpu);
7503
7504 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
7505 return 1;
7506
7507 err = kvm_emulate_instruction(vcpu, 0);
7508
7509 if (err == EMULATE_USER_EXIT) {
7510 ++vcpu->stat.mmio_exits;
7511 ret = 0;
7512 goto out;
7513 }
7514
7515 if (err != EMULATE_DONE)
7516 goto emulation_error;
7517
7518 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
7519 vcpu->arch.exception.pending)
7520 goto emulation_error;
7521
7522 if (vcpu->arch.halt_request) {
7523 vcpu->arch.halt_request = 0;
7524 ret = kvm_vcpu_halt(vcpu);
7525 goto out;
7526 }
7527
7528 if (signal_pending(current))
7529 goto out;
7530 if (need_resched())
7531 schedule();
7532 }
7533
7534 out:
7535 return ret;
7536
7537 emulation_error:
7538 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7539 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7540 vcpu->run->internal.ndata = 0;
7541 return 0;
7542 }
7543
7544 static void grow_ple_window(struct kvm_vcpu *vcpu)
7545 {
7546 struct vcpu_vmx *vmx = to_vmx(vcpu);
7547 int old = vmx->ple_window;
7548
7549 vmx->ple_window = __grow_ple_window(old, ple_window,
7550 ple_window_grow,
7551 ple_window_max);
7552
7553 if (vmx->ple_window != old)
7554 vmx->ple_window_dirty = true;
7555
7556 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
7557 }
7558
7559 static void shrink_ple_window(struct kvm_vcpu *vcpu)
7560 {
7561 struct vcpu_vmx *vmx = to_vmx(vcpu);
7562 int old = vmx->ple_window;
7563
7564 vmx->ple_window = __shrink_ple_window(old, ple_window,
7565 ple_window_shrink,
7566 ple_window);
7567
7568 if (vmx->ple_window != old)
7569 vmx->ple_window_dirty = true;
7570
7571 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
7572 }
7573
7574 /*
7575 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
7576 */
7577 static void wakeup_handler(void)
7578 {
7579 struct kvm_vcpu *vcpu;
7580 int cpu = smp_processor_id();
7581
7582 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7583 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
7584 blocked_vcpu_list) {
7585 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7586
7587 if (pi_test_on(pi_desc) == 1)
7588 kvm_vcpu_kick(vcpu);
7589 }
7590 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7591 }
7592
7593 static void vmx_enable_tdp(void)
7594 {
7595 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
7596 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
7597 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
7598 0ull, VMX_EPT_EXECUTABLE_MASK,
7599 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
7600 VMX_EPT_RWX_MASK, 0ull);
7601
7602 ept_set_mmio_spte_mask();
7603 kvm_enable_tdp();
7604 }
7605
7606 static __init int hardware_setup(void)
7607 {
7608 unsigned long host_bndcfgs;
7609 int r = -ENOMEM, i;
7610
7611 rdmsrl_safe(MSR_EFER, &host_efer);
7612
7613 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7614 kvm_define_shared_msr(i, vmx_msr_index[i]);
7615
7616 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7617 return -EIO;
7618
7619 if (boot_cpu_has(X86_FEATURE_NX))
7620 kvm_enable_efer_bits(EFER_NX);
7621
7622 if (boot_cpu_has(X86_FEATURE_MPX)) {
7623 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7624 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7625 }
7626
7627 if (boot_cpu_has(X86_FEATURE_XSAVES))
7628 rdmsrl(MSR_IA32_XSS, host_xss);
7629
7630 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7631 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7632 enable_vpid = 0;
7633
7634 if (!cpu_has_vmx_ept() ||
7635 !cpu_has_vmx_ept_4levels() ||
7636 !cpu_has_vmx_ept_mt_wb() ||
7637 !cpu_has_vmx_invept_global())
7638 enable_ept = 0;
7639
7640 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7641 enable_ept_ad_bits = 0;
7642
7643 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7644 enable_unrestricted_guest = 0;
7645
7646 if (!cpu_has_vmx_flexpriority())
7647 flexpriority_enabled = 0;
7648
7649 if (!cpu_has_virtual_nmis())
7650 enable_vnmi = 0;
7651
7652 /*
7653 * set_apic_access_page_addr() is used to reload apic access
7654 * page upon invalidation. No need to do anything if not
7655 * using the APIC_ACCESS_ADDR VMCS field.
7656 */
7657 if (!flexpriority_enabled)
7658 kvm_x86_ops->set_apic_access_page_addr = NULL;
7659
7660 if (!cpu_has_vmx_tpr_shadow())
7661 kvm_x86_ops->update_cr8_intercept = NULL;
7662
7663 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7664 kvm_disable_largepages();
7665
7666 #if IS_ENABLED(CONFIG_HYPERV)
7667 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7668 && enable_ept)
7669 kvm_x86_ops->tlb_remote_flush = vmx_hv_remote_flush_tlb;
7670 #endif
7671
7672 if (!cpu_has_vmx_ple()) {
7673 ple_gap = 0;
7674 ple_window = 0;
7675 ple_window_grow = 0;
7676 ple_window_max = 0;
7677 ple_window_shrink = 0;
7678 }
7679
7680 if (!cpu_has_vmx_apicv()) {
7681 enable_apicv = 0;
7682 kvm_x86_ops->sync_pir_to_irr = NULL;
7683 }
7684
7685 if (cpu_has_vmx_tsc_scaling()) {
7686 kvm_has_tsc_control = true;
7687 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7688 kvm_tsc_scaling_ratio_frac_bits = 48;
7689 }
7690
7691 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7692
7693 if (enable_ept)
7694 vmx_enable_tdp();
7695 else
7696 kvm_disable_tdp();
7697
7698 if (!nested) {
7699 kvm_x86_ops->get_nested_state = NULL;
7700 kvm_x86_ops->set_nested_state = NULL;
7701 }
7702
7703 /*
7704 * Only enable PML when hardware supports PML feature, and both EPT
7705 * and EPT A/D bit features are enabled -- PML depends on them to work.
7706 */
7707 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7708 enable_pml = 0;
7709
7710 if (!enable_pml) {
7711 kvm_x86_ops->slot_enable_log_dirty = NULL;
7712 kvm_x86_ops->slot_disable_log_dirty = NULL;
7713 kvm_x86_ops->flush_log_dirty = NULL;
7714 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7715 }
7716
7717 if (!cpu_has_vmx_preemption_timer())
7718 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7719
7720 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7721 u64 vmx_msr;
7722
7723 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7724 cpu_preemption_timer_multi =
7725 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7726 } else {
7727 kvm_x86_ops->set_hv_timer = NULL;
7728 kvm_x86_ops->cancel_hv_timer = NULL;
7729 }
7730
7731 if (!cpu_has_vmx_shadow_vmcs() || !nested)
7732 enable_shadow_vmcs = 0;
7733 if (enable_shadow_vmcs) {
7734 for (i = 0; i < VMX_BITMAP_NR; i++) {
7735 vmx_bitmap[i] = (unsigned long *)
7736 __get_free_page(GFP_KERNEL);
7737 if (!vmx_bitmap[i])
7738 goto out;
7739 }
7740
7741 init_vmcs_shadow_fields();
7742 }
7743
7744 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7745 nested_vmx_setup_ctls_msrs(&vmcs_config.nested, vmx_capability.ept,
7746 enable_apicv);
7747
7748 kvm_mce_cap_supported |= MCG_LMCE_P;
7749
7750 r = alloc_kvm_area();
7751 if (r)
7752 goto out;
7753 return 0;
7754
7755 out:
7756 if (enable_shadow_vmcs) {
7757 for (i = 0; i < VMX_BITMAP_NR; i++)
7758 free_page((unsigned long)vmx_bitmap[i]);
7759 }
7760 return r;
7761 }
7762
7763 static __exit void hardware_unsetup(void)
7764 {
7765 int i;
7766
7767 if (enable_shadow_vmcs) {
7768 for (i = 0; i < VMX_BITMAP_NR; i++)
7769 free_page((unsigned long)vmx_bitmap[i]);
7770 }
7771
7772 free_kvm_area();
7773 }
7774
7775 /*
7776 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
7777 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
7778 */
7779 static int handle_pause(struct kvm_vcpu *vcpu)
7780 {
7781 if (!kvm_pause_in_guest(vcpu->kvm))
7782 grow_ple_window(vcpu);
7783
7784 /*
7785 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
7786 * VM-execution control is ignored if CPL > 0. OTOH, KVM
7787 * never set PAUSE_EXITING and just set PLE if supported,
7788 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
7789 */
7790 kvm_vcpu_on_spin(vcpu, true);
7791 return kvm_skip_emulated_instruction(vcpu);
7792 }
7793
7794 static int handle_nop(struct kvm_vcpu *vcpu)
7795 {
7796 return kvm_skip_emulated_instruction(vcpu);
7797 }
7798
7799 static int handle_mwait(struct kvm_vcpu *vcpu)
7800 {
7801 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
7802 return handle_nop(vcpu);
7803 }
7804
7805 static int handle_invalid_op(struct kvm_vcpu *vcpu)
7806 {
7807 kvm_queue_exception(vcpu, UD_VECTOR);
7808 return 1;
7809 }
7810
7811 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
7812 {
7813 return 1;
7814 }
7815
7816 static int handle_monitor(struct kvm_vcpu *vcpu)
7817 {
7818 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
7819 return handle_nop(vcpu);
7820 }
7821
7822 /*
7823 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
7824 * set the success or error code of an emulated VMX instruction (as specified
7825 * by Vol 2B, VMX Instruction Reference, "Conventions"), and skip the emulated
7826 * instruction.
7827 */
7828 static int nested_vmx_succeed(struct kvm_vcpu *vcpu)
7829 {
7830 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
7831 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7832 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
7833 return kvm_skip_emulated_instruction(vcpu);
7834 }
7835
7836 static int nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
7837 {
7838 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7839 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
7840 X86_EFLAGS_SF | X86_EFLAGS_OF))
7841 | X86_EFLAGS_CF);
7842 return kvm_skip_emulated_instruction(vcpu);
7843 }
7844
7845 static int nested_vmx_failValid(struct kvm_vcpu *vcpu,
7846 u32 vm_instruction_error)
7847 {
7848 struct vcpu_vmx *vmx = to_vmx(vcpu);
7849
7850 /*
7851 * failValid writes the error number to the current VMCS, which
7852 * can't be done if there isn't a current VMCS.
7853 */
7854 if (vmx->nested.current_vmptr == -1ull && !vmx->nested.hv_evmcs)
7855 return nested_vmx_failInvalid(vcpu);
7856
7857 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7858 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7859 X86_EFLAGS_SF | X86_EFLAGS_OF))
7860 | X86_EFLAGS_ZF);
7861 get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
7862 /*
7863 * We don't need to force a shadow sync because
7864 * VM_INSTRUCTION_ERROR is not shadowed
7865 */
7866 return kvm_skip_emulated_instruction(vcpu);
7867 }
7868
7869 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
7870 {
7871 /* TODO: not to reset guest simply here. */
7872 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7873 pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
7874 }
7875
7876 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
7877 {
7878 struct vcpu_vmx *vmx =
7879 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
7880
7881 vmx->nested.preemption_timer_expired = true;
7882 kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
7883 kvm_vcpu_kick(&vmx->vcpu);
7884
7885 return HRTIMER_NORESTART;
7886 }
7887
7888 /*
7889 * Decode the memory-address operand of a vmx instruction, as recorded on an
7890 * exit caused by such an instruction (run by a guest hypervisor).
7891 * On success, returns 0. When the operand is invalid, returns 1 and throws
7892 * #UD or #GP.
7893 */
7894 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
7895 unsigned long exit_qualification,
7896 u32 vmx_instruction_info, bool wr, gva_t *ret)
7897 {
7898 gva_t off;
7899 bool exn;
7900 struct kvm_segment s;
7901
7902 /*
7903 * According to Vol. 3B, "Information for VM Exits Due to Instruction
7904 * Execution", on an exit, vmx_instruction_info holds most of the
7905 * addressing components of the operand. Only the displacement part
7906 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
7907 * For how an actual address is calculated from all these components,
7908 * refer to Vol. 1, "Operand Addressing".
7909 */
7910 int scaling = vmx_instruction_info & 3;
7911 int addr_size = (vmx_instruction_info >> 7) & 7;
7912 bool is_reg = vmx_instruction_info & (1u << 10);
7913 int seg_reg = (vmx_instruction_info >> 15) & 7;
7914 int index_reg = (vmx_instruction_info >> 18) & 0xf;
7915 bool index_is_valid = !(vmx_instruction_info & (1u << 22));
7916 int base_reg = (vmx_instruction_info >> 23) & 0xf;
7917 bool base_is_valid = !(vmx_instruction_info & (1u << 27));
7918
7919 if (is_reg) {
7920 kvm_queue_exception(vcpu, UD_VECTOR);
7921 return 1;
7922 }
7923
7924 /* Addr = segment_base + offset */
7925 /* offset = base + [index * scale] + displacement */
7926 off = exit_qualification; /* holds the displacement */
7927 if (base_is_valid)
7928 off += kvm_register_read(vcpu, base_reg);
7929 if (index_is_valid)
7930 off += kvm_register_read(vcpu, index_reg)<<scaling;
7931 vmx_get_segment(vcpu, &s, seg_reg);
7932 *ret = s.base + off;
7933
7934 if (addr_size == 1) /* 32 bit */
7935 *ret &= 0xffffffff;
7936
7937 /* Checks for #GP/#SS exceptions. */
7938 exn = false;
7939 if (is_long_mode(vcpu)) {
7940 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
7941 * non-canonical form. This is the only check on the memory
7942 * destination for long mode!
7943 */
7944 exn = is_noncanonical_address(*ret, vcpu);
7945 } else if (is_protmode(vcpu)) {
7946 /* Protected mode: apply checks for segment validity in the
7947 * following order:
7948 * - segment type check (#GP(0) may be thrown)
7949 * - usability check (#GP(0)/#SS(0))
7950 * - limit check (#GP(0)/#SS(0))
7951 */
7952 if (wr)
7953 /* #GP(0) if the destination operand is located in a
7954 * read-only data segment or any code segment.
7955 */
7956 exn = ((s.type & 0xa) == 0 || (s.type & 8));
7957 else
7958 /* #GP(0) if the source operand is located in an
7959 * execute-only code segment
7960 */
7961 exn = ((s.type & 0xa) == 8);
7962 if (exn) {
7963 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7964 return 1;
7965 }
7966 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
7967 */
7968 exn = (s.unusable != 0);
7969 /* Protected mode: #GP(0)/#SS(0) if the memory
7970 * operand is outside the segment limit.
7971 */
7972 exn = exn || (off + sizeof(u64) > s.limit);
7973 }
7974 if (exn) {
7975 kvm_queue_exception_e(vcpu,
7976 seg_reg == VCPU_SREG_SS ?
7977 SS_VECTOR : GP_VECTOR,
7978 0);
7979 return 1;
7980 }
7981
7982 return 0;
7983 }
7984
7985 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
7986 {
7987 gva_t gva;
7988 struct x86_exception e;
7989
7990 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7991 vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
7992 return 1;
7993
7994 if (kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e)) {
7995 kvm_inject_page_fault(vcpu, &e);
7996 return 1;
7997 }
7998
7999 return 0;
8000 }
8001
8002 /*
8003 * Allocate a shadow VMCS and associate it with the currently loaded
8004 * VMCS, unless such a shadow VMCS already exists. The newly allocated
8005 * VMCS is also VMCLEARed, so that it is ready for use.
8006 */
8007 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
8008 {
8009 struct vcpu_vmx *vmx = to_vmx(vcpu);
8010 struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
8011
8012 /*
8013 * We should allocate a shadow vmcs for vmcs01 only when L1
8014 * executes VMXON and free it when L1 executes VMXOFF.
8015 * As it is invalid to execute VMXON twice, we shouldn't reach
8016 * here when vmcs01 already have an allocated shadow vmcs.
8017 */
8018 WARN_ON(loaded_vmcs == &vmx->vmcs01 && loaded_vmcs->shadow_vmcs);
8019
8020 if (!loaded_vmcs->shadow_vmcs) {
8021 loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
8022 if (loaded_vmcs->shadow_vmcs)
8023 vmcs_clear(loaded_vmcs->shadow_vmcs);
8024 }
8025 return loaded_vmcs->shadow_vmcs;
8026 }
8027
8028 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
8029 {
8030 struct vcpu_vmx *vmx = to_vmx(vcpu);
8031 int r;
8032
8033 r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
8034 if (r < 0)
8035 goto out_vmcs02;
8036
8037 vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
8038 if (!vmx->nested.cached_vmcs12)
8039 goto out_cached_vmcs12;
8040
8041 vmx->nested.cached_shadow_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
8042 if (!vmx->nested.cached_shadow_vmcs12)
8043 goto out_cached_shadow_vmcs12;
8044
8045 if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
8046 goto out_shadow_vmcs;
8047
8048 hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
8049 HRTIMER_MODE_REL_PINNED);
8050 vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
8051
8052 vmx->nested.vpid02 = allocate_vpid();
8053
8054 vmx->nested.vmcs02_initialized = false;
8055 vmx->nested.vmxon = true;
8056 return 0;
8057
8058 out_shadow_vmcs:
8059 kfree(vmx->nested.cached_shadow_vmcs12);
8060
8061 out_cached_shadow_vmcs12:
8062 kfree(vmx->nested.cached_vmcs12);
8063
8064 out_cached_vmcs12:
8065 free_loaded_vmcs(&vmx->nested.vmcs02);
8066
8067 out_vmcs02:
8068 return -ENOMEM;
8069 }
8070
8071 /*
8072 * Emulate the VMXON instruction.
8073 * Currently, we just remember that VMX is active, and do not save or even
8074 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
8075 * do not currently need to store anything in that guest-allocated memory
8076 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
8077 * argument is different from the VMXON pointer (which the spec says they do).
8078 */
8079 static int handle_vmon(struct kvm_vcpu *vcpu)
8080 {
8081 int ret;
8082 gpa_t vmptr;
8083 struct page *page;
8084 struct vcpu_vmx *vmx = to_vmx(vcpu);
8085 const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
8086 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
8087
8088 /*
8089 * The Intel VMX Instruction Reference lists a bunch of bits that are
8090 * prerequisite to running VMXON, most notably cr4.VMXE must be set to
8091 * 1 (see vmx_set_cr4() for when we allow the guest to set this).
8092 * Otherwise, we should fail with #UD. But most faulting conditions
8093 * have already been checked by hardware, prior to the VM-exit for
8094 * VMXON. We do test guest cr4.VMXE because processor CR4 always has
8095 * that bit set to 1 in non-root mode.
8096 */
8097 if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
8098 kvm_queue_exception(vcpu, UD_VECTOR);
8099 return 1;
8100 }
8101
8102 /* CPL=0 must be checked manually. */
8103 if (vmx_get_cpl(vcpu)) {
8104 kvm_inject_gp(vcpu, 0);
8105 return 1;
8106 }
8107
8108 if (vmx->nested.vmxon)
8109 return nested_vmx_failValid(vcpu,
8110 VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
8111
8112 if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
8113 != VMXON_NEEDED_FEATURES) {
8114 kvm_inject_gp(vcpu, 0);
8115 return 1;
8116 }
8117
8118 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8119 return 1;
8120
8121 /*
8122 * SDM 3: 24.11.5
8123 * The first 4 bytes of VMXON region contain the supported
8124 * VMCS revision identifier
8125 *
8126 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
8127 * which replaces physical address width with 32
8128 */
8129 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
8130 return nested_vmx_failInvalid(vcpu);
8131
8132 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8133 if (is_error_page(page))
8134 return nested_vmx_failInvalid(vcpu);
8135
8136 if (*(u32 *)kmap(page) != VMCS12_REVISION) {
8137 kunmap(page);
8138 kvm_release_page_clean(page);
8139 return nested_vmx_failInvalid(vcpu);
8140 }
8141 kunmap(page);
8142 kvm_release_page_clean(page);
8143
8144 vmx->nested.vmxon_ptr = vmptr;
8145 ret = enter_vmx_operation(vcpu);
8146 if (ret)
8147 return ret;
8148
8149 return nested_vmx_succeed(vcpu);
8150 }
8151
8152 /*
8153 * Intel's VMX Instruction Reference specifies a common set of prerequisites
8154 * for running VMX instructions (except VMXON, whose prerequisites are
8155 * slightly different). It also specifies what exception to inject otherwise.
8156 * Note that many of these exceptions have priority over VM exits, so they
8157 * don't have to be checked again here.
8158 */
8159 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
8160 {
8161 if (!to_vmx(vcpu)->nested.vmxon) {
8162 kvm_queue_exception(vcpu, UD_VECTOR);
8163 return 0;
8164 }
8165
8166 if (vmx_get_cpl(vcpu)) {
8167 kvm_inject_gp(vcpu, 0);
8168 return 0;
8169 }
8170
8171 return 1;
8172 }
8173
8174 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
8175 {
8176 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
8177 vmcs_write64(VMCS_LINK_POINTER, -1ull);
8178 }
8179
8180 static inline void nested_release_evmcs(struct kvm_vcpu *vcpu)
8181 {
8182 struct vcpu_vmx *vmx = to_vmx(vcpu);
8183
8184 if (!vmx->nested.hv_evmcs)
8185 return;
8186
8187 kunmap(vmx->nested.hv_evmcs_page);
8188 kvm_release_page_dirty(vmx->nested.hv_evmcs_page);
8189 vmx->nested.hv_evmcs_vmptr = -1ull;
8190 vmx->nested.hv_evmcs_page = NULL;
8191 vmx->nested.hv_evmcs = NULL;
8192 }
8193
8194 static inline void nested_release_vmcs12(struct kvm_vcpu *vcpu)
8195 {
8196 struct vcpu_vmx *vmx = to_vmx(vcpu);
8197
8198 if (vmx->nested.current_vmptr == -1ull)
8199 return;
8200
8201 if (enable_shadow_vmcs) {
8202 /* copy to memory all shadowed fields in case
8203 they were modified */
8204 copy_shadow_to_vmcs12(vmx);
8205 vmx->nested.need_vmcs12_sync = false;
8206 vmx_disable_shadow_vmcs(vmx);
8207 }
8208 vmx->nested.posted_intr_nv = -1;
8209
8210 /* Flush VMCS12 to guest memory */
8211 kvm_vcpu_write_guest_page(vcpu,
8212 vmx->nested.current_vmptr >> PAGE_SHIFT,
8213 vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
8214
8215 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
8216
8217 vmx->nested.current_vmptr = -1ull;
8218 }
8219
8220 /*
8221 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
8222 * just stops using VMX.
8223 */
8224 static void free_nested(struct kvm_vcpu *vcpu)
8225 {
8226 struct vcpu_vmx *vmx = to_vmx(vcpu);
8227
8228 if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
8229 return;
8230
8231 vmx->nested.vmxon = false;
8232 vmx->nested.smm.vmxon = false;
8233 free_vpid(vmx->nested.vpid02);
8234 vmx->nested.posted_intr_nv = -1;
8235 vmx->nested.current_vmptr = -1ull;
8236 if (enable_shadow_vmcs) {
8237 vmx_disable_shadow_vmcs(vmx);
8238 vmcs_clear(vmx->vmcs01.shadow_vmcs);
8239 free_vmcs(vmx->vmcs01.shadow_vmcs);
8240 vmx->vmcs01.shadow_vmcs = NULL;
8241 }
8242 kfree(vmx->nested.cached_vmcs12);
8243 kfree(vmx->nested.cached_shadow_vmcs12);
8244 /* Unpin physical memory we referred to in the vmcs02 */
8245 if (vmx->nested.apic_access_page) {
8246 kvm_release_page_dirty(vmx->nested.apic_access_page);
8247 vmx->nested.apic_access_page = NULL;
8248 }
8249 if (vmx->nested.virtual_apic_page) {
8250 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
8251 vmx->nested.virtual_apic_page = NULL;
8252 }
8253 if (vmx->nested.pi_desc_page) {
8254 kunmap(vmx->nested.pi_desc_page);
8255 kvm_release_page_dirty(vmx->nested.pi_desc_page);
8256 vmx->nested.pi_desc_page = NULL;
8257 vmx->nested.pi_desc = NULL;
8258 }
8259
8260 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
8261
8262 nested_release_evmcs(vcpu);
8263
8264 free_loaded_vmcs(&vmx->nested.vmcs02);
8265 }
8266
8267 /* Emulate the VMXOFF instruction */
8268 static int handle_vmoff(struct kvm_vcpu *vcpu)
8269 {
8270 if (!nested_vmx_check_permission(vcpu))
8271 return 1;
8272 free_nested(vcpu);
8273 return nested_vmx_succeed(vcpu);
8274 }
8275
8276 /* Emulate the VMCLEAR instruction */
8277 static int handle_vmclear(struct kvm_vcpu *vcpu)
8278 {
8279 struct vcpu_vmx *vmx = to_vmx(vcpu);
8280 u32 zero = 0;
8281 gpa_t vmptr;
8282
8283 if (!nested_vmx_check_permission(vcpu))
8284 return 1;
8285
8286 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8287 return 1;
8288
8289 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
8290 return nested_vmx_failValid(vcpu,
8291 VMXERR_VMCLEAR_INVALID_ADDRESS);
8292
8293 if (vmptr == vmx->nested.vmxon_ptr)
8294 return nested_vmx_failValid(vcpu,
8295 VMXERR_VMCLEAR_VMXON_POINTER);
8296
8297 if (vmx->nested.hv_evmcs_page) {
8298 if (vmptr == vmx->nested.hv_evmcs_vmptr)
8299 nested_release_evmcs(vcpu);
8300 } else {
8301 if (vmptr == vmx->nested.current_vmptr)
8302 nested_release_vmcs12(vcpu);
8303
8304 kvm_vcpu_write_guest(vcpu,
8305 vmptr + offsetof(struct vmcs12,
8306 launch_state),
8307 &zero, sizeof(zero));
8308 }
8309
8310 return nested_vmx_succeed(vcpu);
8311 }
8312
8313 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
8314
8315 /* Emulate the VMLAUNCH instruction */
8316 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
8317 {
8318 return nested_vmx_run(vcpu, true);
8319 }
8320
8321 /* Emulate the VMRESUME instruction */
8322 static int handle_vmresume(struct kvm_vcpu *vcpu)
8323 {
8324
8325 return nested_vmx_run(vcpu, false);
8326 }
8327
8328 /*
8329 * Read a vmcs12 field. Since these can have varying lengths and we return
8330 * one type, we chose the biggest type (u64) and zero-extend the return value
8331 * to that size. Note that the caller, handle_vmread, might need to use only
8332 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
8333 * 64-bit fields are to be returned).
8334 */
8335 static inline int vmcs12_read_any(struct vmcs12 *vmcs12,
8336 unsigned long field, u64 *ret)
8337 {
8338 short offset = vmcs_field_to_offset(field);
8339 char *p;
8340
8341 if (offset < 0)
8342 return offset;
8343
8344 p = (char *)vmcs12 + offset;
8345
8346 switch (vmcs_field_width(field)) {
8347 case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8348 *ret = *((natural_width *)p);
8349 return 0;
8350 case VMCS_FIELD_WIDTH_U16:
8351 *ret = *((u16 *)p);
8352 return 0;
8353 case VMCS_FIELD_WIDTH_U32:
8354 *ret = *((u32 *)p);
8355 return 0;
8356 case VMCS_FIELD_WIDTH_U64:
8357 *ret = *((u64 *)p);
8358 return 0;
8359 default:
8360 WARN_ON(1);
8361 return -ENOENT;
8362 }
8363 }
8364
8365
8366 static inline int vmcs12_write_any(struct vmcs12 *vmcs12,
8367 unsigned long field, u64 field_value){
8368 short offset = vmcs_field_to_offset(field);
8369 char *p = (char *)vmcs12 + offset;
8370 if (offset < 0)
8371 return offset;
8372
8373 switch (vmcs_field_width(field)) {
8374 case VMCS_FIELD_WIDTH_U16:
8375 *(u16 *)p = field_value;
8376 return 0;
8377 case VMCS_FIELD_WIDTH_U32:
8378 *(u32 *)p = field_value;
8379 return 0;
8380 case VMCS_FIELD_WIDTH_U64:
8381 *(u64 *)p = field_value;
8382 return 0;
8383 case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8384 *(natural_width *)p = field_value;
8385 return 0;
8386 default:
8387 WARN_ON(1);
8388 return -ENOENT;
8389 }
8390
8391 }
8392
8393 static int copy_enlightened_to_vmcs12(struct vcpu_vmx *vmx)
8394 {
8395 struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
8396 struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
8397
8398 /* HV_VMX_ENLIGHTENED_CLEAN_FIELD_NONE */
8399 vmcs12->tpr_threshold = evmcs->tpr_threshold;
8400 vmcs12->guest_rip = evmcs->guest_rip;
8401
8402 if (unlikely(!(evmcs->hv_clean_fields &
8403 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_BASIC))) {
8404 vmcs12->guest_rsp = evmcs->guest_rsp;
8405 vmcs12->guest_rflags = evmcs->guest_rflags;
8406 vmcs12->guest_interruptibility_info =
8407 evmcs->guest_interruptibility_info;
8408 }
8409
8410 if (unlikely(!(evmcs->hv_clean_fields &
8411 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
8412 vmcs12->cpu_based_vm_exec_control =
8413 evmcs->cpu_based_vm_exec_control;
8414 }
8415
8416 if (unlikely(!(evmcs->hv_clean_fields &
8417 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
8418 vmcs12->exception_bitmap = evmcs->exception_bitmap;
8419 }
8420
8421 if (unlikely(!(evmcs->hv_clean_fields &
8422 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_ENTRY))) {
8423 vmcs12->vm_entry_controls = evmcs->vm_entry_controls;
8424 }
8425
8426 if (unlikely(!(evmcs->hv_clean_fields &
8427 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_EVENT))) {
8428 vmcs12->vm_entry_intr_info_field =
8429 evmcs->vm_entry_intr_info_field;
8430 vmcs12->vm_entry_exception_error_code =
8431 evmcs->vm_entry_exception_error_code;
8432 vmcs12->vm_entry_instruction_len =
8433 evmcs->vm_entry_instruction_len;
8434 }
8435
8436 if (unlikely(!(evmcs->hv_clean_fields &
8437 HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
8438 vmcs12->host_ia32_pat = evmcs->host_ia32_pat;
8439 vmcs12->host_ia32_efer = evmcs->host_ia32_efer;
8440 vmcs12->host_cr0 = evmcs->host_cr0;
8441 vmcs12->host_cr3 = evmcs->host_cr3;
8442 vmcs12->host_cr4 = evmcs->host_cr4;
8443 vmcs12->host_ia32_sysenter_esp = evmcs->host_ia32_sysenter_esp;
8444 vmcs12->host_ia32_sysenter_eip = evmcs->host_ia32_sysenter_eip;
8445 vmcs12->host_rip = evmcs->host_rip;
8446 vmcs12->host_ia32_sysenter_cs = evmcs->host_ia32_sysenter_cs;
8447 vmcs12->host_es_selector = evmcs->host_es_selector;
8448 vmcs12->host_cs_selector = evmcs->host_cs_selector;
8449 vmcs12->host_ss_selector = evmcs->host_ss_selector;
8450 vmcs12->host_ds_selector = evmcs->host_ds_selector;
8451 vmcs12->host_fs_selector = evmcs->host_fs_selector;
8452 vmcs12->host_gs_selector = evmcs->host_gs_selector;
8453 vmcs12->host_tr_selector = evmcs->host_tr_selector;
8454 }
8455
8456 if (unlikely(!(evmcs->hv_clean_fields &
8457 HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
8458 vmcs12->pin_based_vm_exec_control =
8459 evmcs->pin_based_vm_exec_control;
8460 vmcs12->vm_exit_controls = evmcs->vm_exit_controls;
8461 vmcs12->secondary_vm_exec_control =
8462 evmcs->secondary_vm_exec_control;
8463 }
8464
8465 if (unlikely(!(evmcs->hv_clean_fields &
8466 HV_VMX_ENLIGHTENED_CLEAN_FIELD_IO_BITMAP))) {
8467 vmcs12->io_bitmap_a = evmcs->io_bitmap_a;
8468 vmcs12->io_bitmap_b = evmcs->io_bitmap_b;
8469 }
8470
8471 if (unlikely(!(evmcs->hv_clean_fields &
8472 HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP))) {
8473 vmcs12->msr_bitmap = evmcs->msr_bitmap;
8474 }
8475
8476 if (unlikely(!(evmcs->hv_clean_fields &
8477 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2))) {
8478 vmcs12->guest_es_base = evmcs->guest_es_base;
8479 vmcs12->guest_cs_base = evmcs->guest_cs_base;
8480 vmcs12->guest_ss_base = evmcs->guest_ss_base;
8481 vmcs12->guest_ds_base = evmcs->guest_ds_base;
8482 vmcs12->guest_fs_base = evmcs->guest_fs_base;
8483 vmcs12->guest_gs_base = evmcs->guest_gs_base;
8484 vmcs12->guest_ldtr_base = evmcs->guest_ldtr_base;
8485 vmcs12->guest_tr_base = evmcs->guest_tr_base;
8486 vmcs12->guest_gdtr_base = evmcs->guest_gdtr_base;
8487 vmcs12->guest_idtr_base = evmcs->guest_idtr_base;
8488 vmcs12->guest_es_limit = evmcs->guest_es_limit;
8489 vmcs12->guest_cs_limit = evmcs->guest_cs_limit;
8490 vmcs12->guest_ss_limit = evmcs->guest_ss_limit;
8491 vmcs12->guest_ds_limit = evmcs->guest_ds_limit;
8492 vmcs12->guest_fs_limit = evmcs->guest_fs_limit;
8493 vmcs12->guest_gs_limit = evmcs->guest_gs_limit;
8494 vmcs12->guest_ldtr_limit = evmcs->guest_ldtr_limit;
8495 vmcs12->guest_tr_limit = evmcs->guest_tr_limit;
8496 vmcs12->guest_gdtr_limit = evmcs->guest_gdtr_limit;
8497 vmcs12->guest_idtr_limit = evmcs->guest_idtr_limit;
8498 vmcs12->guest_es_ar_bytes = evmcs->guest_es_ar_bytes;
8499 vmcs12->guest_cs_ar_bytes = evmcs->guest_cs_ar_bytes;
8500 vmcs12->guest_ss_ar_bytes = evmcs->guest_ss_ar_bytes;
8501 vmcs12->guest_ds_ar_bytes = evmcs->guest_ds_ar_bytes;
8502 vmcs12->guest_fs_ar_bytes = evmcs->guest_fs_ar_bytes;
8503 vmcs12->guest_gs_ar_bytes = evmcs->guest_gs_ar_bytes;
8504 vmcs12->guest_ldtr_ar_bytes = evmcs->guest_ldtr_ar_bytes;
8505 vmcs12->guest_tr_ar_bytes = evmcs->guest_tr_ar_bytes;
8506 vmcs12->guest_es_selector = evmcs->guest_es_selector;
8507 vmcs12->guest_cs_selector = evmcs->guest_cs_selector;
8508 vmcs12->guest_ss_selector = evmcs->guest_ss_selector;
8509 vmcs12->guest_ds_selector = evmcs->guest_ds_selector;
8510 vmcs12->guest_fs_selector = evmcs->guest_fs_selector;
8511 vmcs12->guest_gs_selector = evmcs->guest_gs_selector;
8512 vmcs12->guest_ldtr_selector = evmcs->guest_ldtr_selector;
8513 vmcs12->guest_tr_selector = evmcs->guest_tr_selector;
8514 }
8515
8516 if (unlikely(!(evmcs->hv_clean_fields &
8517 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_GRP2))) {
8518 vmcs12->tsc_offset = evmcs->tsc_offset;
8519 vmcs12->virtual_apic_page_addr = evmcs->virtual_apic_page_addr;
8520 vmcs12->xss_exit_bitmap = evmcs->xss_exit_bitmap;
8521 }
8522
8523 if (unlikely(!(evmcs->hv_clean_fields &
8524 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CRDR))) {
8525 vmcs12->cr0_guest_host_mask = evmcs->cr0_guest_host_mask;
8526 vmcs12->cr4_guest_host_mask = evmcs->cr4_guest_host_mask;
8527 vmcs12->cr0_read_shadow = evmcs->cr0_read_shadow;
8528 vmcs12->cr4_read_shadow = evmcs->cr4_read_shadow;
8529 vmcs12->guest_cr0 = evmcs->guest_cr0;
8530 vmcs12->guest_cr3 = evmcs->guest_cr3;
8531 vmcs12->guest_cr4 = evmcs->guest_cr4;
8532 vmcs12->guest_dr7 = evmcs->guest_dr7;
8533 }
8534
8535 if (unlikely(!(evmcs->hv_clean_fields &
8536 HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_POINTER))) {
8537 vmcs12->host_fs_base = evmcs->host_fs_base;
8538 vmcs12->host_gs_base = evmcs->host_gs_base;
8539 vmcs12->host_tr_base = evmcs->host_tr_base;
8540 vmcs12->host_gdtr_base = evmcs->host_gdtr_base;
8541 vmcs12->host_idtr_base = evmcs->host_idtr_base;
8542 vmcs12->host_rsp = evmcs->host_rsp;
8543 }
8544
8545 if (unlikely(!(evmcs->hv_clean_fields &
8546 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_XLAT))) {
8547 vmcs12->ept_pointer = evmcs->ept_pointer;
8548 vmcs12->virtual_processor_id = evmcs->virtual_processor_id;
8549 }
8550
8551 if (unlikely(!(evmcs->hv_clean_fields &
8552 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1))) {
8553 vmcs12->vmcs_link_pointer = evmcs->vmcs_link_pointer;
8554 vmcs12->guest_ia32_debugctl = evmcs->guest_ia32_debugctl;
8555 vmcs12->guest_ia32_pat = evmcs->guest_ia32_pat;
8556 vmcs12->guest_ia32_efer = evmcs->guest_ia32_efer;
8557 vmcs12->guest_pdptr0 = evmcs->guest_pdptr0;
8558 vmcs12->guest_pdptr1 = evmcs->guest_pdptr1;
8559 vmcs12->guest_pdptr2 = evmcs->guest_pdptr2;
8560 vmcs12->guest_pdptr3 = evmcs->guest_pdptr3;
8561 vmcs12->guest_pending_dbg_exceptions =
8562 evmcs->guest_pending_dbg_exceptions;
8563 vmcs12->guest_sysenter_esp = evmcs->guest_sysenter_esp;
8564 vmcs12->guest_sysenter_eip = evmcs->guest_sysenter_eip;
8565 vmcs12->guest_bndcfgs = evmcs->guest_bndcfgs;
8566 vmcs12->guest_activity_state = evmcs->guest_activity_state;
8567 vmcs12->guest_sysenter_cs = evmcs->guest_sysenter_cs;
8568 }
8569
8570 /*
8571 * Not used?
8572 * vmcs12->vm_exit_msr_store_addr = evmcs->vm_exit_msr_store_addr;
8573 * vmcs12->vm_exit_msr_load_addr = evmcs->vm_exit_msr_load_addr;
8574 * vmcs12->vm_entry_msr_load_addr = evmcs->vm_entry_msr_load_addr;
8575 * vmcs12->cr3_target_value0 = evmcs->cr3_target_value0;
8576 * vmcs12->cr3_target_value1 = evmcs->cr3_target_value1;
8577 * vmcs12->cr3_target_value2 = evmcs->cr3_target_value2;
8578 * vmcs12->cr3_target_value3 = evmcs->cr3_target_value3;
8579 * vmcs12->page_fault_error_code_mask =
8580 * evmcs->page_fault_error_code_mask;
8581 * vmcs12->page_fault_error_code_match =
8582 * evmcs->page_fault_error_code_match;
8583 * vmcs12->cr3_target_count = evmcs->cr3_target_count;
8584 * vmcs12->vm_exit_msr_store_count = evmcs->vm_exit_msr_store_count;
8585 * vmcs12->vm_exit_msr_load_count = evmcs->vm_exit_msr_load_count;
8586 * vmcs12->vm_entry_msr_load_count = evmcs->vm_entry_msr_load_count;
8587 */
8588
8589 /*
8590 * Read only fields:
8591 * vmcs12->guest_physical_address = evmcs->guest_physical_address;
8592 * vmcs12->vm_instruction_error = evmcs->vm_instruction_error;
8593 * vmcs12->vm_exit_reason = evmcs->vm_exit_reason;
8594 * vmcs12->vm_exit_intr_info = evmcs->vm_exit_intr_info;
8595 * vmcs12->vm_exit_intr_error_code = evmcs->vm_exit_intr_error_code;
8596 * vmcs12->idt_vectoring_info_field = evmcs->idt_vectoring_info_field;
8597 * vmcs12->idt_vectoring_error_code = evmcs->idt_vectoring_error_code;
8598 * vmcs12->vm_exit_instruction_len = evmcs->vm_exit_instruction_len;
8599 * vmcs12->vmx_instruction_info = evmcs->vmx_instruction_info;
8600 * vmcs12->exit_qualification = evmcs->exit_qualification;
8601 * vmcs12->guest_linear_address = evmcs->guest_linear_address;
8602 *
8603 * Not present in struct vmcs12:
8604 * vmcs12->exit_io_instruction_ecx = evmcs->exit_io_instruction_ecx;
8605 * vmcs12->exit_io_instruction_esi = evmcs->exit_io_instruction_esi;
8606 * vmcs12->exit_io_instruction_edi = evmcs->exit_io_instruction_edi;
8607 * vmcs12->exit_io_instruction_eip = evmcs->exit_io_instruction_eip;
8608 */
8609
8610 return 0;
8611 }
8612
8613 static int copy_vmcs12_to_enlightened(struct vcpu_vmx *vmx)
8614 {
8615 struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
8616 struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
8617
8618 /*
8619 * Should not be changed by KVM:
8620 *
8621 * evmcs->host_es_selector = vmcs12->host_es_selector;
8622 * evmcs->host_cs_selector = vmcs12->host_cs_selector;
8623 * evmcs->host_ss_selector = vmcs12->host_ss_selector;
8624 * evmcs->host_ds_selector = vmcs12->host_ds_selector;
8625 * evmcs->host_fs_selector = vmcs12->host_fs_selector;
8626 * evmcs->host_gs_selector = vmcs12->host_gs_selector;
8627 * evmcs->host_tr_selector = vmcs12->host_tr_selector;
8628 * evmcs->host_ia32_pat = vmcs12->host_ia32_pat;
8629 * evmcs->host_ia32_efer = vmcs12->host_ia32_efer;
8630 * evmcs->host_cr0 = vmcs12->host_cr0;
8631 * evmcs->host_cr3 = vmcs12->host_cr3;
8632 * evmcs->host_cr4 = vmcs12->host_cr4;
8633 * evmcs->host_ia32_sysenter_esp = vmcs12->host_ia32_sysenter_esp;
8634 * evmcs->host_ia32_sysenter_eip = vmcs12->host_ia32_sysenter_eip;
8635 * evmcs->host_rip = vmcs12->host_rip;
8636 * evmcs->host_ia32_sysenter_cs = vmcs12->host_ia32_sysenter_cs;
8637 * evmcs->host_fs_base = vmcs12->host_fs_base;
8638 * evmcs->host_gs_base = vmcs12->host_gs_base;
8639 * evmcs->host_tr_base = vmcs12->host_tr_base;
8640 * evmcs->host_gdtr_base = vmcs12->host_gdtr_base;
8641 * evmcs->host_idtr_base = vmcs12->host_idtr_base;
8642 * evmcs->host_rsp = vmcs12->host_rsp;
8643 * sync_vmcs12() doesn't read these:
8644 * evmcs->io_bitmap_a = vmcs12->io_bitmap_a;
8645 * evmcs->io_bitmap_b = vmcs12->io_bitmap_b;
8646 * evmcs->msr_bitmap = vmcs12->msr_bitmap;
8647 * evmcs->ept_pointer = vmcs12->ept_pointer;
8648 * evmcs->xss_exit_bitmap = vmcs12->xss_exit_bitmap;
8649 * evmcs->vm_exit_msr_store_addr = vmcs12->vm_exit_msr_store_addr;
8650 * evmcs->vm_exit_msr_load_addr = vmcs12->vm_exit_msr_load_addr;
8651 * evmcs->vm_entry_msr_load_addr = vmcs12->vm_entry_msr_load_addr;
8652 * evmcs->cr3_target_value0 = vmcs12->cr3_target_value0;
8653 * evmcs->cr3_target_value1 = vmcs12->cr3_target_value1;
8654 * evmcs->cr3_target_value2 = vmcs12->cr3_target_value2;
8655 * evmcs->cr3_target_value3 = vmcs12->cr3_target_value3;
8656 * evmcs->tpr_threshold = vmcs12->tpr_threshold;
8657 * evmcs->virtual_processor_id = vmcs12->virtual_processor_id;
8658 * evmcs->exception_bitmap = vmcs12->exception_bitmap;
8659 * evmcs->vmcs_link_pointer = vmcs12->vmcs_link_pointer;
8660 * evmcs->pin_based_vm_exec_control = vmcs12->pin_based_vm_exec_control;
8661 * evmcs->vm_exit_controls = vmcs12->vm_exit_controls;
8662 * evmcs->secondary_vm_exec_control = vmcs12->secondary_vm_exec_control;
8663 * evmcs->page_fault_error_code_mask =
8664 * vmcs12->page_fault_error_code_mask;
8665 * evmcs->page_fault_error_code_match =
8666 * vmcs12->page_fault_error_code_match;
8667 * evmcs->cr3_target_count = vmcs12->cr3_target_count;
8668 * evmcs->virtual_apic_page_addr = vmcs12->virtual_apic_page_addr;
8669 * evmcs->tsc_offset = vmcs12->tsc_offset;
8670 * evmcs->guest_ia32_debugctl = vmcs12->guest_ia32_debugctl;
8671 * evmcs->cr0_guest_host_mask = vmcs12->cr0_guest_host_mask;
8672 * evmcs->cr4_guest_host_mask = vmcs12->cr4_guest_host_mask;
8673 * evmcs->cr0_read_shadow = vmcs12->cr0_read_shadow;
8674 * evmcs->cr4_read_shadow = vmcs12->cr4_read_shadow;
8675 * evmcs->vm_exit_msr_store_count = vmcs12->vm_exit_msr_store_count;
8676 * evmcs->vm_exit_msr_load_count = vmcs12->vm_exit_msr_load_count;
8677 * evmcs->vm_entry_msr_load_count = vmcs12->vm_entry_msr_load_count;
8678 *
8679 * Not present in struct vmcs12:
8680 * evmcs->exit_io_instruction_ecx = vmcs12->exit_io_instruction_ecx;
8681 * evmcs->exit_io_instruction_esi = vmcs12->exit_io_instruction_esi;
8682 * evmcs->exit_io_instruction_edi = vmcs12->exit_io_instruction_edi;
8683 * evmcs->exit_io_instruction_eip = vmcs12->exit_io_instruction_eip;
8684 */
8685
8686 evmcs->guest_es_selector = vmcs12->guest_es_selector;
8687 evmcs->guest_cs_selector = vmcs12->guest_cs_selector;
8688 evmcs->guest_ss_selector = vmcs12->guest_ss_selector;
8689 evmcs->guest_ds_selector = vmcs12->guest_ds_selector;
8690 evmcs->guest_fs_selector = vmcs12->guest_fs_selector;
8691 evmcs->guest_gs_selector = vmcs12->guest_gs_selector;
8692 evmcs->guest_ldtr_selector = vmcs12->guest_ldtr_selector;
8693 evmcs->guest_tr_selector = vmcs12->guest_tr_selector;
8694
8695 evmcs->guest_es_limit = vmcs12->guest_es_limit;
8696 evmcs->guest_cs_limit = vmcs12->guest_cs_limit;
8697 evmcs->guest_ss_limit = vmcs12->guest_ss_limit;
8698 evmcs->guest_ds_limit = vmcs12->guest_ds_limit;
8699 evmcs->guest_fs_limit = vmcs12->guest_fs_limit;
8700 evmcs->guest_gs_limit = vmcs12->guest_gs_limit;
8701 evmcs->guest_ldtr_limit = vmcs12->guest_ldtr_limit;
8702 evmcs->guest_tr_limit = vmcs12->guest_tr_limit;
8703 evmcs->guest_gdtr_limit = vmcs12->guest_gdtr_limit;
8704 evmcs->guest_idtr_limit = vmcs12->guest_idtr_limit;
8705
8706 evmcs->guest_es_ar_bytes = vmcs12->guest_es_ar_bytes;
8707 evmcs->guest_cs_ar_bytes = vmcs12->guest_cs_ar_bytes;
8708 evmcs->guest_ss_ar_bytes = vmcs12->guest_ss_ar_bytes;
8709 evmcs->guest_ds_ar_bytes = vmcs12->guest_ds_ar_bytes;
8710 evmcs->guest_fs_ar_bytes = vmcs12->guest_fs_ar_bytes;
8711 evmcs->guest_gs_ar_bytes = vmcs12->guest_gs_ar_bytes;
8712 evmcs->guest_ldtr_ar_bytes = vmcs12->guest_ldtr_ar_bytes;
8713 evmcs->guest_tr_ar_bytes = vmcs12->guest_tr_ar_bytes;
8714
8715 evmcs->guest_es_base = vmcs12->guest_es_base;
8716 evmcs->guest_cs_base = vmcs12->guest_cs_base;
8717 evmcs->guest_ss_base = vmcs12->guest_ss_base;
8718 evmcs->guest_ds_base = vmcs12->guest_ds_base;
8719 evmcs->guest_fs_base = vmcs12->guest_fs_base;
8720 evmcs->guest_gs_base = vmcs12->guest_gs_base;
8721 evmcs->guest_ldtr_base = vmcs12->guest_ldtr_base;
8722 evmcs->guest_tr_base = vmcs12->guest_tr_base;
8723 evmcs->guest_gdtr_base = vmcs12->guest_gdtr_base;
8724 evmcs->guest_idtr_base = vmcs12->guest_idtr_base;
8725
8726 evmcs->guest_ia32_pat = vmcs12->guest_ia32_pat;
8727 evmcs->guest_ia32_efer = vmcs12->guest_ia32_efer;
8728
8729 evmcs->guest_pdptr0 = vmcs12->guest_pdptr0;
8730 evmcs->guest_pdptr1 = vmcs12->guest_pdptr1;
8731 evmcs->guest_pdptr2 = vmcs12->guest_pdptr2;
8732 evmcs->guest_pdptr3 = vmcs12->guest_pdptr3;
8733
8734 evmcs->guest_pending_dbg_exceptions =
8735 vmcs12->guest_pending_dbg_exceptions;
8736 evmcs->guest_sysenter_esp = vmcs12->guest_sysenter_esp;
8737 evmcs->guest_sysenter_eip = vmcs12->guest_sysenter_eip;
8738
8739 evmcs->guest_activity_state = vmcs12->guest_activity_state;
8740 evmcs->guest_sysenter_cs = vmcs12->guest_sysenter_cs;
8741
8742 evmcs->guest_cr0 = vmcs12->guest_cr0;
8743 evmcs->guest_cr3 = vmcs12->guest_cr3;
8744 evmcs->guest_cr4 = vmcs12->guest_cr4;
8745 evmcs->guest_dr7 = vmcs12->guest_dr7;
8746
8747 evmcs->guest_physical_address = vmcs12->guest_physical_address;
8748
8749 evmcs->vm_instruction_error = vmcs12->vm_instruction_error;
8750 evmcs->vm_exit_reason = vmcs12->vm_exit_reason;
8751 evmcs->vm_exit_intr_info = vmcs12->vm_exit_intr_info;
8752 evmcs->vm_exit_intr_error_code = vmcs12->vm_exit_intr_error_code;
8753 evmcs->idt_vectoring_info_field = vmcs12->idt_vectoring_info_field;
8754 evmcs->idt_vectoring_error_code = vmcs12->idt_vectoring_error_code;
8755 evmcs->vm_exit_instruction_len = vmcs12->vm_exit_instruction_len;
8756 evmcs->vmx_instruction_info = vmcs12->vmx_instruction_info;
8757
8758 evmcs->exit_qualification = vmcs12->exit_qualification;
8759
8760 evmcs->guest_linear_address = vmcs12->guest_linear_address;
8761 evmcs->guest_rsp = vmcs12->guest_rsp;
8762 evmcs->guest_rflags = vmcs12->guest_rflags;
8763
8764 evmcs->guest_interruptibility_info =
8765 vmcs12->guest_interruptibility_info;
8766 evmcs->cpu_based_vm_exec_control = vmcs12->cpu_based_vm_exec_control;
8767 evmcs->vm_entry_controls = vmcs12->vm_entry_controls;
8768 evmcs->vm_entry_intr_info_field = vmcs12->vm_entry_intr_info_field;
8769 evmcs->vm_entry_exception_error_code =
8770 vmcs12->vm_entry_exception_error_code;
8771 evmcs->vm_entry_instruction_len = vmcs12->vm_entry_instruction_len;
8772
8773 evmcs->guest_rip = vmcs12->guest_rip;
8774
8775 evmcs->guest_bndcfgs = vmcs12->guest_bndcfgs;
8776
8777 return 0;
8778 }
8779
8780 /*
8781 * Copy the writable VMCS shadow fields back to the VMCS12, in case
8782 * they have been modified by the L1 guest. Note that the "read-only"
8783 * VM-exit information fields are actually writable if the vCPU is
8784 * configured to support "VMWRITE to any supported field in the VMCS."
8785 */
8786 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
8787 {
8788 const u16 *fields[] = {
8789 shadow_read_write_fields,
8790 shadow_read_only_fields
8791 };
8792 const int max_fields[] = {
8793 max_shadow_read_write_fields,
8794 max_shadow_read_only_fields
8795 };
8796 int i, q;
8797 unsigned long field;
8798 u64 field_value;
8799 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
8800
8801 preempt_disable();
8802
8803 vmcs_load(shadow_vmcs);
8804
8805 for (q = 0; q < ARRAY_SIZE(fields); q++) {
8806 for (i = 0; i < max_fields[q]; i++) {
8807 field = fields[q][i];
8808 field_value = __vmcs_readl(field);
8809 vmcs12_write_any(get_vmcs12(&vmx->vcpu), field, field_value);
8810 }
8811 /*
8812 * Skip the VM-exit information fields if they are read-only.
8813 */
8814 if (!nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
8815 break;
8816 }
8817
8818 vmcs_clear(shadow_vmcs);
8819 vmcs_load(vmx->loaded_vmcs->vmcs);
8820
8821 preempt_enable();
8822 }
8823
8824 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
8825 {
8826 const u16 *fields[] = {
8827 shadow_read_write_fields,
8828 shadow_read_only_fields
8829 };
8830 const int max_fields[] = {
8831 max_shadow_read_write_fields,
8832 max_shadow_read_only_fields
8833 };
8834 int i, q;
8835 unsigned long field;
8836 u64 field_value = 0;
8837 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
8838
8839 vmcs_load(shadow_vmcs);
8840
8841 for (q = 0; q < ARRAY_SIZE(fields); q++) {
8842 for (i = 0; i < max_fields[q]; i++) {
8843 field = fields[q][i];
8844 vmcs12_read_any(get_vmcs12(&vmx->vcpu), field, &field_value);
8845 __vmcs_writel(field, field_value);
8846 }
8847 }
8848
8849 vmcs_clear(shadow_vmcs);
8850 vmcs_load(vmx->loaded_vmcs->vmcs);
8851 }
8852
8853 static int handle_vmread(struct kvm_vcpu *vcpu)
8854 {
8855 unsigned long field;
8856 u64 field_value;
8857 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8858 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8859 gva_t gva = 0;
8860 struct vmcs12 *vmcs12;
8861
8862 if (!nested_vmx_check_permission(vcpu))
8863 return 1;
8864
8865 if (to_vmx(vcpu)->nested.current_vmptr == -1ull)
8866 return nested_vmx_failInvalid(vcpu);
8867
8868 if (!is_guest_mode(vcpu))
8869 vmcs12 = get_vmcs12(vcpu);
8870 else {
8871 /*
8872 * When vmcs->vmcs_link_pointer is -1ull, any VMREAD
8873 * to shadowed-field sets the ALU flags for VMfailInvalid.
8874 */
8875 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull)
8876 return nested_vmx_failInvalid(vcpu);
8877 vmcs12 = get_shadow_vmcs12(vcpu);
8878 }
8879
8880 /* Decode instruction info and find the field to read */
8881 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8882 /* Read the field, zero-extended to a u64 field_value */
8883 if (vmcs12_read_any(vmcs12, field, &field_value) < 0)
8884 return nested_vmx_failValid(vcpu,
8885 VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8886
8887 /*
8888 * Now copy part of this value to register or memory, as requested.
8889 * Note that the number of bits actually copied is 32 or 64 depending
8890 * on the guest's mode (32 or 64 bit), not on the given field's length.
8891 */
8892 if (vmx_instruction_info & (1u << 10)) {
8893 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
8894 field_value);
8895 } else {
8896 if (get_vmx_mem_address(vcpu, exit_qualification,
8897 vmx_instruction_info, true, &gva))
8898 return 1;
8899 /* _system ok, nested_vmx_check_permission has verified cpl=0 */
8900 kvm_write_guest_virt_system(vcpu, gva, &field_value,
8901 (is_long_mode(vcpu) ? 8 : 4), NULL);
8902 }
8903
8904 return nested_vmx_succeed(vcpu);
8905 }
8906
8907
8908 static int handle_vmwrite(struct kvm_vcpu *vcpu)
8909 {
8910 unsigned long field;
8911 gva_t gva;
8912 struct vcpu_vmx *vmx = to_vmx(vcpu);
8913 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8914 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8915
8916 /* The value to write might be 32 or 64 bits, depending on L1's long
8917 * mode, and eventually we need to write that into a field of several
8918 * possible lengths. The code below first zero-extends the value to 64
8919 * bit (field_value), and then copies only the appropriate number of
8920 * bits into the vmcs12 field.
8921 */
8922 u64 field_value = 0;
8923 struct x86_exception e;
8924 struct vmcs12 *vmcs12;
8925
8926 if (!nested_vmx_check_permission(vcpu))
8927 return 1;
8928
8929 if (vmx->nested.current_vmptr == -1ull)
8930 return nested_vmx_failInvalid(vcpu);
8931
8932 if (vmx_instruction_info & (1u << 10))
8933 field_value = kvm_register_readl(vcpu,
8934 (((vmx_instruction_info) >> 3) & 0xf));
8935 else {
8936 if (get_vmx_mem_address(vcpu, exit_qualification,
8937 vmx_instruction_info, false, &gva))
8938 return 1;
8939 if (kvm_read_guest_virt(vcpu, gva, &field_value,
8940 (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
8941 kvm_inject_page_fault(vcpu, &e);
8942 return 1;
8943 }
8944 }
8945
8946
8947 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8948 /*
8949 * If the vCPU supports "VMWRITE to any supported field in the
8950 * VMCS," then the "read-only" fields are actually read/write.
8951 */
8952 if (vmcs_field_readonly(field) &&
8953 !nested_cpu_has_vmwrite_any_field(vcpu))
8954 return nested_vmx_failValid(vcpu,
8955 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
8956
8957 if (!is_guest_mode(vcpu))
8958 vmcs12 = get_vmcs12(vcpu);
8959 else {
8960 /*
8961 * When vmcs->vmcs_link_pointer is -1ull, any VMWRITE
8962 * to shadowed-field sets the ALU flags for VMfailInvalid.
8963 */
8964 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull)
8965 return nested_vmx_failInvalid(vcpu);
8966 vmcs12 = get_shadow_vmcs12(vcpu);
8967 }
8968
8969 if (vmcs12_write_any(vmcs12, field, field_value) < 0)
8970 return nested_vmx_failValid(vcpu,
8971 VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8972
8973 /*
8974 * Do not track vmcs12 dirty-state if in guest-mode
8975 * as we actually dirty shadow vmcs12 instead of vmcs12.
8976 */
8977 if (!is_guest_mode(vcpu)) {
8978 switch (field) {
8979 #define SHADOW_FIELD_RW(x) case x:
8980 #include "vmcs_shadow_fields.h"
8981 /*
8982 * The fields that can be updated by L1 without a vmexit are
8983 * always updated in the vmcs02, the others go down the slow
8984 * path of prepare_vmcs02.
8985 */
8986 break;
8987 default:
8988 vmx->nested.dirty_vmcs12 = true;
8989 break;
8990 }
8991 }
8992
8993 return nested_vmx_succeed(vcpu);
8994 }
8995
8996 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
8997 {
8998 vmx->nested.current_vmptr = vmptr;
8999 if (enable_shadow_vmcs) {
9000 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
9001 SECONDARY_EXEC_SHADOW_VMCS);
9002 vmcs_write64(VMCS_LINK_POINTER,
9003 __pa(vmx->vmcs01.shadow_vmcs));
9004 vmx->nested.need_vmcs12_sync = true;
9005 }
9006 vmx->nested.dirty_vmcs12 = true;
9007 }
9008
9009 /* Emulate the VMPTRLD instruction */
9010 static int handle_vmptrld(struct kvm_vcpu *vcpu)
9011 {
9012 struct vcpu_vmx *vmx = to_vmx(vcpu);
9013 gpa_t vmptr;
9014
9015 if (!nested_vmx_check_permission(vcpu))
9016 return 1;
9017
9018 if (nested_vmx_get_vmptr(vcpu, &vmptr))
9019 return 1;
9020
9021 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
9022 return nested_vmx_failValid(vcpu,
9023 VMXERR_VMPTRLD_INVALID_ADDRESS);
9024
9025 if (vmptr == vmx->nested.vmxon_ptr)
9026 return nested_vmx_failValid(vcpu,
9027 VMXERR_VMPTRLD_VMXON_POINTER);
9028
9029 /* Forbid normal VMPTRLD if Enlightened version was used */
9030 if (vmx->nested.hv_evmcs)
9031 return 1;
9032
9033 if (vmx->nested.current_vmptr != vmptr) {
9034 struct vmcs12 *new_vmcs12;
9035 struct page *page;
9036 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
9037 if (is_error_page(page)) {
9038 /*
9039 * Reads from an unbacked page return all 1s,
9040 * which means that the 32 bits located at the
9041 * given physical address won't match the required
9042 * VMCS12_REVISION identifier.
9043 */
9044 nested_vmx_failValid(vcpu,
9045 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
9046 return kvm_skip_emulated_instruction(vcpu);
9047 }
9048 new_vmcs12 = kmap(page);
9049 if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
9050 (new_vmcs12->hdr.shadow_vmcs &&
9051 !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
9052 kunmap(page);
9053 kvm_release_page_clean(page);
9054 return nested_vmx_failValid(vcpu,
9055 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
9056 }
9057
9058 nested_release_vmcs12(vcpu);
9059
9060 /*
9061 * Load VMCS12 from guest memory since it is not already
9062 * cached.
9063 */
9064 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
9065 kunmap(page);
9066 kvm_release_page_clean(page);
9067
9068 set_current_vmptr(vmx, vmptr);
9069 }
9070
9071 return nested_vmx_succeed(vcpu);
9072 }
9073
9074 /*
9075 * This is an equivalent of the nested hypervisor executing the vmptrld
9076 * instruction.
9077 */
9078 static int nested_vmx_handle_enlightened_vmptrld(struct kvm_vcpu *vcpu,
9079 bool from_launch)
9080 {
9081 struct vcpu_vmx *vmx = to_vmx(vcpu);
9082 struct hv_vp_assist_page assist_page;
9083
9084 if (likely(!vmx->nested.enlightened_vmcs_enabled))
9085 return 1;
9086
9087 if (unlikely(!kvm_hv_get_assist_page(vcpu, &assist_page)))
9088 return 1;
9089
9090 if (unlikely(!assist_page.enlighten_vmentry))
9091 return 1;
9092
9093 if (unlikely(assist_page.current_nested_vmcs !=
9094 vmx->nested.hv_evmcs_vmptr)) {
9095
9096 if (!vmx->nested.hv_evmcs)
9097 vmx->nested.current_vmptr = -1ull;
9098
9099 nested_release_evmcs(vcpu);
9100
9101 vmx->nested.hv_evmcs_page = kvm_vcpu_gpa_to_page(
9102 vcpu, assist_page.current_nested_vmcs);
9103
9104 if (unlikely(is_error_page(vmx->nested.hv_evmcs_page)))
9105 return 0;
9106
9107 vmx->nested.hv_evmcs = kmap(vmx->nested.hv_evmcs_page);
9108
9109 /*
9110 * Currently, KVM only supports eVMCS version 1
9111 * (== KVM_EVMCS_VERSION) and thus we expect guest to set this
9112 * value to first u32 field of eVMCS which should specify eVMCS
9113 * VersionNumber.
9114 *
9115 * Guest should be aware of supported eVMCS versions by host by
9116 * examining CPUID.0x4000000A.EAX[0:15]. Host userspace VMM is
9117 * expected to set this CPUID leaf according to the value
9118 * returned in vmcs_version from nested_enable_evmcs().
9119 *
9120 * However, it turns out that Microsoft Hyper-V fails to comply
9121 * to their own invented interface: When Hyper-V use eVMCS, it
9122 * just sets first u32 field of eVMCS to revision_id specified
9123 * in MSR_IA32_VMX_BASIC. Instead of used eVMCS version number
9124 * which is one of the supported versions specified in
9125 * CPUID.0x4000000A.EAX[0:15].
9126 *
9127 * To overcome Hyper-V bug, we accept here either a supported
9128 * eVMCS version or VMCS12 revision_id as valid values for first
9129 * u32 field of eVMCS.
9130 */
9131 if ((vmx->nested.hv_evmcs->revision_id != KVM_EVMCS_VERSION) &&
9132 (vmx->nested.hv_evmcs->revision_id != VMCS12_REVISION)) {
9133 nested_release_evmcs(vcpu);
9134 return 0;
9135 }
9136
9137 vmx->nested.dirty_vmcs12 = true;
9138 /*
9139 * As we keep L2 state for one guest only 'hv_clean_fields' mask
9140 * can't be used when we switch between them. Reset it here for
9141 * simplicity.
9142 */
9143 vmx->nested.hv_evmcs->hv_clean_fields &=
9144 ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
9145 vmx->nested.hv_evmcs_vmptr = assist_page.current_nested_vmcs;
9146
9147 /*
9148 * Unlike normal vmcs12, enlightened vmcs12 is not fully
9149 * reloaded from guest's memory (read only fields, fields not
9150 * present in struct hv_enlightened_vmcs, ...). Make sure there
9151 * are no leftovers.
9152 */
9153 if (from_launch) {
9154 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9155 memset(vmcs12, 0, sizeof(*vmcs12));
9156 vmcs12->hdr.revision_id = VMCS12_REVISION;
9157 }
9158
9159 }
9160 return 1;
9161 }
9162
9163 /* Emulate the VMPTRST instruction */
9164 static int handle_vmptrst(struct kvm_vcpu *vcpu)
9165 {
9166 unsigned long exit_qual = vmcs_readl(EXIT_QUALIFICATION);
9167 u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9168 gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
9169 struct x86_exception e;
9170 gva_t gva;
9171
9172 if (!nested_vmx_check_permission(vcpu))
9173 return 1;
9174
9175 if (unlikely(to_vmx(vcpu)->nested.hv_evmcs))
9176 return 1;
9177
9178 if (get_vmx_mem_address(vcpu, exit_qual, instr_info, true, &gva))
9179 return 1;
9180 /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
9181 if (kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
9182 sizeof(gpa_t), &e)) {
9183 kvm_inject_page_fault(vcpu, &e);
9184 return 1;
9185 }
9186 return nested_vmx_succeed(vcpu);
9187 }
9188
9189 /* Emulate the INVEPT instruction */
9190 static int handle_invept(struct kvm_vcpu *vcpu)
9191 {
9192 struct vcpu_vmx *vmx = to_vmx(vcpu);
9193 u32 vmx_instruction_info, types;
9194 unsigned long type;
9195 gva_t gva;
9196 struct x86_exception e;
9197 struct {
9198 u64 eptp, gpa;
9199 } operand;
9200
9201 if (!(vmx->nested.msrs.secondary_ctls_high &
9202 SECONDARY_EXEC_ENABLE_EPT) ||
9203 !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
9204 kvm_queue_exception(vcpu, UD_VECTOR);
9205 return 1;
9206 }
9207
9208 if (!nested_vmx_check_permission(vcpu))
9209 return 1;
9210
9211 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9212 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9213
9214 types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
9215
9216 if (type >= 32 || !(types & (1 << type)))
9217 return nested_vmx_failValid(vcpu,
9218 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9219
9220 /* According to the Intel VMX instruction reference, the memory
9221 * operand is read even if it isn't needed (e.g., for type==global)
9222 */
9223 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9224 vmx_instruction_info, false, &gva))
9225 return 1;
9226 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9227 kvm_inject_page_fault(vcpu, &e);
9228 return 1;
9229 }
9230
9231 switch (type) {
9232 case VMX_EPT_EXTENT_GLOBAL:
9233 /*
9234 * TODO: track mappings and invalidate
9235 * single context requests appropriately
9236 */
9237 case VMX_EPT_EXTENT_CONTEXT:
9238 kvm_mmu_sync_roots(vcpu);
9239 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9240 break;
9241 default:
9242 BUG_ON(1);
9243 break;
9244 }
9245
9246 return nested_vmx_succeed(vcpu);
9247 }
9248
9249 static u16 nested_get_vpid02(struct kvm_vcpu *vcpu)
9250 {
9251 struct vcpu_vmx *vmx = to_vmx(vcpu);
9252
9253 return vmx->nested.vpid02 ? vmx->nested.vpid02 : vmx->vpid;
9254 }
9255
9256 static int handle_invvpid(struct kvm_vcpu *vcpu)
9257 {
9258 struct vcpu_vmx *vmx = to_vmx(vcpu);
9259 u32 vmx_instruction_info;
9260 unsigned long type, types;
9261 gva_t gva;
9262 struct x86_exception e;
9263 struct {
9264 u64 vpid;
9265 u64 gla;
9266 } operand;
9267 u16 vpid02;
9268
9269 if (!(vmx->nested.msrs.secondary_ctls_high &
9270 SECONDARY_EXEC_ENABLE_VPID) ||
9271 !(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
9272 kvm_queue_exception(vcpu, UD_VECTOR);
9273 return 1;
9274 }
9275
9276 if (!nested_vmx_check_permission(vcpu))
9277 return 1;
9278
9279 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9280 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9281
9282 types = (vmx->nested.msrs.vpid_caps &
9283 VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
9284
9285 if (type >= 32 || !(types & (1 << type)))
9286 return nested_vmx_failValid(vcpu,
9287 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9288
9289 /* according to the intel vmx instruction reference, the memory
9290 * operand is read even if it isn't needed (e.g., for type==global)
9291 */
9292 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9293 vmx_instruction_info, false, &gva))
9294 return 1;
9295 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9296 kvm_inject_page_fault(vcpu, &e);
9297 return 1;
9298 }
9299 if (operand.vpid >> 16)
9300 return nested_vmx_failValid(vcpu,
9301 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9302
9303 vpid02 = nested_get_vpid02(vcpu);
9304 switch (type) {
9305 case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
9306 if (!operand.vpid ||
9307 is_noncanonical_address(operand.gla, vcpu))
9308 return nested_vmx_failValid(vcpu,
9309 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9310 if (cpu_has_vmx_invvpid_individual_addr()) {
9311 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR,
9312 vpid02, operand.gla);
9313 } else
9314 __vmx_flush_tlb(vcpu, vpid02, false);
9315 break;
9316 case VMX_VPID_EXTENT_SINGLE_CONTEXT:
9317 case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
9318 if (!operand.vpid)
9319 return nested_vmx_failValid(vcpu,
9320 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9321 __vmx_flush_tlb(vcpu, vpid02, false);
9322 break;
9323 case VMX_VPID_EXTENT_ALL_CONTEXT:
9324 __vmx_flush_tlb(vcpu, vpid02, false);
9325 break;
9326 default:
9327 WARN_ON_ONCE(1);
9328 return kvm_skip_emulated_instruction(vcpu);
9329 }
9330
9331 return nested_vmx_succeed(vcpu);
9332 }
9333
9334 static int handle_invpcid(struct kvm_vcpu *vcpu)
9335 {
9336 u32 vmx_instruction_info;
9337 unsigned long type;
9338 bool pcid_enabled;
9339 gva_t gva;
9340 struct x86_exception e;
9341 unsigned i;
9342 unsigned long roots_to_free = 0;
9343 struct {
9344 u64 pcid;
9345 u64 gla;
9346 } operand;
9347
9348 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
9349 kvm_queue_exception(vcpu, UD_VECTOR);
9350 return 1;
9351 }
9352
9353 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9354 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9355
9356 if (type > 3) {
9357 kvm_inject_gp(vcpu, 0);
9358 return 1;
9359 }
9360
9361 /* According to the Intel instruction reference, the memory operand
9362 * is read even if it isn't needed (e.g., for type==all)
9363 */
9364 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9365 vmx_instruction_info, false, &gva))
9366 return 1;
9367
9368 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9369 kvm_inject_page_fault(vcpu, &e);
9370 return 1;
9371 }
9372
9373 if (operand.pcid >> 12 != 0) {
9374 kvm_inject_gp(vcpu, 0);
9375 return 1;
9376 }
9377
9378 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
9379
9380 switch (type) {
9381 case INVPCID_TYPE_INDIV_ADDR:
9382 if ((!pcid_enabled && (operand.pcid != 0)) ||
9383 is_noncanonical_address(operand.gla, vcpu)) {
9384 kvm_inject_gp(vcpu, 0);
9385 return 1;
9386 }
9387 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
9388 return kvm_skip_emulated_instruction(vcpu);
9389
9390 case INVPCID_TYPE_SINGLE_CTXT:
9391 if (!pcid_enabled && (operand.pcid != 0)) {
9392 kvm_inject_gp(vcpu, 0);
9393 return 1;
9394 }
9395
9396 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
9397 kvm_mmu_sync_roots(vcpu);
9398 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9399 }
9400
9401 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
9402 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
9403 == operand.pcid)
9404 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
9405
9406 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
9407 /*
9408 * If neither the current cr3 nor any of the prev_roots use the
9409 * given PCID, then nothing needs to be done here because a
9410 * resync will happen anyway before switching to any other CR3.
9411 */
9412
9413 return kvm_skip_emulated_instruction(vcpu);
9414
9415 case INVPCID_TYPE_ALL_NON_GLOBAL:
9416 /*
9417 * Currently, KVM doesn't mark global entries in the shadow
9418 * page tables, so a non-global flush just degenerates to a
9419 * global flush. If needed, we could optimize this later by
9420 * keeping track of global entries in shadow page tables.
9421 */
9422
9423 /* fall-through */
9424 case INVPCID_TYPE_ALL_INCL_GLOBAL:
9425 kvm_mmu_unload(vcpu);
9426 return kvm_skip_emulated_instruction(vcpu);
9427
9428 default:
9429 BUG(); /* We have already checked above that type <= 3 */
9430 }
9431 }
9432
9433 static int handle_pml_full(struct kvm_vcpu *vcpu)
9434 {
9435 unsigned long exit_qualification;
9436
9437 trace_kvm_pml_full(vcpu->vcpu_id);
9438
9439 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9440
9441 /*
9442 * PML buffer FULL happened while executing iret from NMI,
9443 * "blocked by NMI" bit has to be set before next VM entry.
9444 */
9445 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
9446 enable_vnmi &&
9447 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
9448 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9449 GUEST_INTR_STATE_NMI);
9450
9451 /*
9452 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
9453 * here.., and there's no userspace involvement needed for PML.
9454 */
9455 return 1;
9456 }
9457
9458 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
9459 {
9460 if (!to_vmx(vcpu)->req_immediate_exit)
9461 kvm_lapic_expired_hv_timer(vcpu);
9462 return 1;
9463 }
9464
9465 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
9466 {
9467 struct vcpu_vmx *vmx = to_vmx(vcpu);
9468 int maxphyaddr = cpuid_maxphyaddr(vcpu);
9469
9470 /* Check for memory type validity */
9471 switch (address & VMX_EPTP_MT_MASK) {
9472 case VMX_EPTP_MT_UC:
9473 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT))
9474 return false;
9475 break;
9476 case VMX_EPTP_MT_WB:
9477 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT))
9478 return false;
9479 break;
9480 default:
9481 return false;
9482 }
9483
9484 /* only 4 levels page-walk length are valid */
9485 if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
9486 return false;
9487
9488 /* Reserved bits should not be set */
9489 if (address >> maxphyaddr || ((address >> 7) & 0x1f))
9490 return false;
9491
9492 /* AD, if set, should be supported */
9493 if (address & VMX_EPTP_AD_ENABLE_BIT) {
9494 if (!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT))
9495 return false;
9496 }
9497
9498 return true;
9499 }
9500
9501 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
9502 struct vmcs12 *vmcs12)
9503 {
9504 u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
9505 u64 address;
9506 bool accessed_dirty;
9507 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
9508
9509 if (!nested_cpu_has_eptp_switching(vmcs12) ||
9510 !nested_cpu_has_ept(vmcs12))
9511 return 1;
9512
9513 if (index >= VMFUNC_EPTP_ENTRIES)
9514 return 1;
9515
9516
9517 if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
9518 &address, index * 8, 8))
9519 return 1;
9520
9521 accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
9522
9523 /*
9524 * If the (L2) guest does a vmfunc to the currently
9525 * active ept pointer, we don't have to do anything else
9526 */
9527 if (vmcs12->ept_pointer != address) {
9528 if (!valid_ept_address(vcpu, address))
9529 return 1;
9530
9531 kvm_mmu_unload(vcpu);
9532 mmu->ept_ad = accessed_dirty;
9533 mmu->mmu_role.base.ad_disabled = !accessed_dirty;
9534 vmcs12->ept_pointer = address;
9535 /*
9536 * TODO: Check what's the correct approach in case
9537 * mmu reload fails. Currently, we just let the next
9538 * reload potentially fail
9539 */
9540 kvm_mmu_reload(vcpu);
9541 }
9542
9543 return 0;
9544 }
9545
9546 static int handle_vmfunc(struct kvm_vcpu *vcpu)
9547 {
9548 struct vcpu_vmx *vmx = to_vmx(vcpu);
9549 struct vmcs12 *vmcs12;
9550 u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
9551
9552 /*
9553 * VMFUNC is only supported for nested guests, but we always enable the
9554 * secondary control for simplicity; for non-nested mode, fake that we
9555 * didn't by injecting #UD.
9556 */
9557 if (!is_guest_mode(vcpu)) {
9558 kvm_queue_exception(vcpu, UD_VECTOR);
9559 return 1;
9560 }
9561
9562 vmcs12 = get_vmcs12(vcpu);
9563 if ((vmcs12->vm_function_control & (1 << function)) == 0)
9564 goto fail;
9565
9566 switch (function) {
9567 case 0:
9568 if (nested_vmx_eptp_switching(vcpu, vmcs12))
9569 goto fail;
9570 break;
9571 default:
9572 goto fail;
9573 }
9574 return kvm_skip_emulated_instruction(vcpu);
9575
9576 fail:
9577 nested_vmx_vmexit(vcpu, vmx->exit_reason,
9578 vmcs_read32(VM_EXIT_INTR_INFO),
9579 vmcs_readl(EXIT_QUALIFICATION));
9580 return 1;
9581 }
9582
9583 static int handle_encls(struct kvm_vcpu *vcpu)
9584 {
9585 /*
9586 * SGX virtualization is not yet supported. There is no software
9587 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
9588 * to prevent the guest from executing ENCLS.
9589 */
9590 kvm_queue_exception(vcpu, UD_VECTOR);
9591 return 1;
9592 }
9593
9594 /*
9595 * The exit handlers return 1 if the exit was handled fully and guest execution
9596 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
9597 * to be done to userspace and return 0.
9598 */
9599 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
9600 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
9601 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
9602 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
9603 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
9604 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
9605 [EXIT_REASON_CR_ACCESS] = handle_cr,
9606 [EXIT_REASON_DR_ACCESS] = handle_dr,
9607 [EXIT_REASON_CPUID] = handle_cpuid,
9608 [EXIT_REASON_MSR_READ] = handle_rdmsr,
9609 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
9610 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
9611 [EXIT_REASON_HLT] = handle_halt,
9612 [EXIT_REASON_INVD] = handle_invd,
9613 [EXIT_REASON_INVLPG] = handle_invlpg,
9614 [EXIT_REASON_RDPMC] = handle_rdpmc,
9615 [EXIT_REASON_VMCALL] = handle_vmcall,
9616 [EXIT_REASON_VMCLEAR] = handle_vmclear,
9617 [EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
9618 [EXIT_REASON_VMPTRLD] = handle_vmptrld,
9619 [EXIT_REASON_VMPTRST] = handle_vmptrst,
9620 [EXIT_REASON_VMREAD] = handle_vmread,
9621 [EXIT_REASON_VMRESUME] = handle_vmresume,
9622 [EXIT_REASON_VMWRITE] = handle_vmwrite,
9623 [EXIT_REASON_VMOFF] = handle_vmoff,
9624 [EXIT_REASON_VMON] = handle_vmon,
9625 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
9626 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
9627 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
9628 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
9629 [EXIT_REASON_WBINVD] = handle_wbinvd,
9630 [EXIT_REASON_XSETBV] = handle_xsetbv,
9631 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
9632 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
9633 [EXIT_REASON_GDTR_IDTR] = handle_desc,
9634 [EXIT_REASON_LDTR_TR] = handle_desc,
9635 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
9636 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
9637 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
9638 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
9639 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
9640 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
9641 [EXIT_REASON_INVEPT] = handle_invept,
9642 [EXIT_REASON_INVVPID] = handle_invvpid,
9643 [EXIT_REASON_RDRAND] = handle_invalid_op,
9644 [EXIT_REASON_RDSEED] = handle_invalid_op,
9645 [EXIT_REASON_XSAVES] = handle_xsaves,
9646 [EXIT_REASON_XRSTORS] = handle_xrstors,
9647 [EXIT_REASON_PML_FULL] = handle_pml_full,
9648 [EXIT_REASON_INVPCID] = handle_invpcid,
9649 [EXIT_REASON_VMFUNC] = handle_vmfunc,
9650 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
9651 [EXIT_REASON_ENCLS] = handle_encls,
9652 };
9653
9654 static const int kvm_vmx_max_exit_handlers =
9655 ARRAY_SIZE(kvm_vmx_exit_handlers);
9656
9657 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
9658 struct vmcs12 *vmcs12)
9659 {
9660 unsigned long exit_qualification;
9661 gpa_t bitmap, last_bitmap;
9662 unsigned int port;
9663 int size;
9664 u8 b;
9665
9666 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
9667 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
9668
9669 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9670
9671 port = exit_qualification >> 16;
9672 size = (exit_qualification & 7) + 1;
9673
9674 last_bitmap = (gpa_t)-1;
9675 b = -1;
9676
9677 while (size > 0) {
9678 if (port < 0x8000)
9679 bitmap = vmcs12->io_bitmap_a;
9680 else if (port < 0x10000)
9681 bitmap = vmcs12->io_bitmap_b;
9682 else
9683 return true;
9684 bitmap += (port & 0x7fff) / 8;
9685
9686 if (last_bitmap != bitmap)
9687 if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
9688 return true;
9689 if (b & (1 << (port & 7)))
9690 return true;
9691
9692 port++;
9693 size--;
9694 last_bitmap = bitmap;
9695 }
9696
9697 return false;
9698 }
9699
9700 /*
9701 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
9702 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
9703 * disinterest in the current event (read or write a specific MSR) by using an
9704 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
9705 */
9706 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
9707 struct vmcs12 *vmcs12, u32 exit_reason)
9708 {
9709 u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
9710 gpa_t bitmap;
9711
9712 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
9713 return true;
9714
9715 /*
9716 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
9717 * for the four combinations of read/write and low/high MSR numbers.
9718 * First we need to figure out which of the four to use:
9719 */
9720 bitmap = vmcs12->msr_bitmap;
9721 if (exit_reason == EXIT_REASON_MSR_WRITE)
9722 bitmap += 2048;
9723 if (msr_index >= 0xc0000000) {
9724 msr_index -= 0xc0000000;
9725 bitmap += 1024;
9726 }
9727
9728 /* Then read the msr_index'th bit from this bitmap: */
9729 if (msr_index < 1024*8) {
9730 unsigned char b;
9731 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
9732 return true;
9733 return 1 & (b >> (msr_index & 7));
9734 } else
9735 return true; /* let L1 handle the wrong parameter */
9736 }
9737
9738 /*
9739 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
9740 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
9741 * intercept (via guest_host_mask etc.) the current event.
9742 */
9743 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
9744 struct vmcs12 *vmcs12)
9745 {
9746 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9747 int cr = exit_qualification & 15;
9748 int reg;
9749 unsigned long val;
9750
9751 switch ((exit_qualification >> 4) & 3) {
9752 case 0: /* mov to cr */
9753 reg = (exit_qualification >> 8) & 15;
9754 val = kvm_register_readl(vcpu, reg);
9755 switch (cr) {
9756 case 0:
9757 if (vmcs12->cr0_guest_host_mask &
9758 (val ^ vmcs12->cr0_read_shadow))
9759 return true;
9760 break;
9761 case 3:
9762 if ((vmcs12->cr3_target_count >= 1 &&
9763 vmcs12->cr3_target_value0 == val) ||
9764 (vmcs12->cr3_target_count >= 2 &&
9765 vmcs12->cr3_target_value1 == val) ||
9766 (vmcs12->cr3_target_count >= 3 &&
9767 vmcs12->cr3_target_value2 == val) ||
9768 (vmcs12->cr3_target_count >= 4 &&
9769 vmcs12->cr3_target_value3 == val))
9770 return false;
9771 if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
9772 return true;
9773 break;
9774 case 4:
9775 if (vmcs12->cr4_guest_host_mask &
9776 (vmcs12->cr4_read_shadow ^ val))
9777 return true;
9778 break;
9779 case 8:
9780 if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
9781 return true;
9782 break;
9783 }
9784 break;
9785 case 2: /* clts */
9786 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
9787 (vmcs12->cr0_read_shadow & X86_CR0_TS))
9788 return true;
9789 break;
9790 case 1: /* mov from cr */
9791 switch (cr) {
9792 case 3:
9793 if (vmcs12->cpu_based_vm_exec_control &
9794 CPU_BASED_CR3_STORE_EXITING)
9795 return true;
9796 break;
9797 case 8:
9798 if (vmcs12->cpu_based_vm_exec_control &
9799 CPU_BASED_CR8_STORE_EXITING)
9800 return true;
9801 break;
9802 }
9803 break;
9804 case 3: /* lmsw */
9805 /*
9806 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
9807 * cr0. Other attempted changes are ignored, with no exit.
9808 */
9809 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
9810 if (vmcs12->cr0_guest_host_mask & 0xe &
9811 (val ^ vmcs12->cr0_read_shadow))
9812 return true;
9813 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
9814 !(vmcs12->cr0_read_shadow & 0x1) &&
9815 (val & 0x1))
9816 return true;
9817 break;
9818 }
9819 return false;
9820 }
9821
9822 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
9823 struct vmcs12 *vmcs12, gpa_t bitmap)
9824 {
9825 u32 vmx_instruction_info;
9826 unsigned long field;
9827 u8 b;
9828
9829 if (!nested_cpu_has_shadow_vmcs(vmcs12))
9830 return true;
9831
9832 /* Decode instruction info and find the field to access */
9833 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9834 field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
9835
9836 /* Out-of-range fields always cause a VM exit from L2 to L1 */
9837 if (field >> 15)
9838 return true;
9839
9840 if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
9841 return true;
9842
9843 return 1 & (b >> (field & 7));
9844 }
9845
9846 /*
9847 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
9848 * should handle it ourselves in L0 (and then continue L2). Only call this
9849 * when in is_guest_mode (L2).
9850 */
9851 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
9852 {
9853 u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9854 struct vcpu_vmx *vmx = to_vmx(vcpu);
9855 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9856
9857 if (vmx->nested.nested_run_pending)
9858 return false;
9859
9860 if (unlikely(vmx->fail)) {
9861 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
9862 vmcs_read32(VM_INSTRUCTION_ERROR));
9863 return true;
9864 }
9865
9866 /*
9867 * The host physical addresses of some pages of guest memory
9868 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
9869 * Page). The CPU may write to these pages via their host
9870 * physical address while L2 is running, bypassing any
9871 * address-translation-based dirty tracking (e.g. EPT write
9872 * protection).
9873 *
9874 * Mark them dirty on every exit from L2 to prevent them from
9875 * getting out of sync with dirty tracking.
9876 */
9877 nested_mark_vmcs12_pages_dirty(vcpu);
9878
9879 trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
9880 vmcs_readl(EXIT_QUALIFICATION),
9881 vmx->idt_vectoring_info,
9882 intr_info,
9883 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
9884 KVM_ISA_VMX);
9885
9886 switch (exit_reason) {
9887 case EXIT_REASON_EXCEPTION_NMI:
9888 if (is_nmi(intr_info))
9889 return false;
9890 else if (is_page_fault(intr_info))
9891 return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
9892 else if (is_debug(intr_info) &&
9893 vcpu->guest_debug &
9894 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
9895 return false;
9896 else if (is_breakpoint(intr_info) &&
9897 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
9898 return false;
9899 return vmcs12->exception_bitmap &
9900 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
9901 case EXIT_REASON_EXTERNAL_INTERRUPT:
9902 return false;
9903 case EXIT_REASON_TRIPLE_FAULT:
9904 return true;
9905 case EXIT_REASON_PENDING_INTERRUPT:
9906 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
9907 case EXIT_REASON_NMI_WINDOW:
9908 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
9909 case EXIT_REASON_TASK_SWITCH:
9910 return true;
9911 case EXIT_REASON_CPUID:
9912 return true;
9913 case EXIT_REASON_HLT:
9914 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
9915 case EXIT_REASON_INVD:
9916 return true;
9917 case EXIT_REASON_INVLPG:
9918 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
9919 case EXIT_REASON_RDPMC:
9920 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
9921 case EXIT_REASON_RDRAND:
9922 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
9923 case EXIT_REASON_RDSEED:
9924 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
9925 case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
9926 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
9927 case EXIT_REASON_VMREAD:
9928 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
9929 vmcs12->vmread_bitmap);
9930 case EXIT_REASON_VMWRITE:
9931 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
9932 vmcs12->vmwrite_bitmap);
9933 case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
9934 case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
9935 case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
9936 case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
9937 case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
9938 /*
9939 * VMX instructions trap unconditionally. This allows L1 to
9940 * emulate them for its L2 guest, i.e., allows 3-level nesting!
9941 */
9942 return true;
9943 case EXIT_REASON_CR_ACCESS:
9944 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
9945 case EXIT_REASON_DR_ACCESS:
9946 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
9947 case EXIT_REASON_IO_INSTRUCTION:
9948 return nested_vmx_exit_handled_io(vcpu, vmcs12);
9949 case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
9950 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
9951 case EXIT_REASON_MSR_READ:
9952 case EXIT_REASON_MSR_WRITE:
9953 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
9954 case EXIT_REASON_INVALID_STATE:
9955 return true;
9956 case EXIT_REASON_MWAIT_INSTRUCTION:
9957 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
9958 case EXIT_REASON_MONITOR_TRAP_FLAG:
9959 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
9960 case EXIT_REASON_MONITOR_INSTRUCTION:
9961 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
9962 case EXIT_REASON_PAUSE_INSTRUCTION:
9963 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
9964 nested_cpu_has2(vmcs12,
9965 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
9966 case EXIT_REASON_MCE_DURING_VMENTRY:
9967 return false;
9968 case EXIT_REASON_TPR_BELOW_THRESHOLD:
9969 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
9970 case EXIT_REASON_APIC_ACCESS:
9971 case EXIT_REASON_APIC_WRITE:
9972 case EXIT_REASON_EOI_INDUCED:
9973 /*
9974 * The controls for "virtualize APIC accesses," "APIC-
9975 * register virtualization," and "virtual-interrupt
9976 * delivery" only come from vmcs12.
9977 */
9978 return true;
9979 case EXIT_REASON_EPT_VIOLATION:
9980 /*
9981 * L0 always deals with the EPT violation. If nested EPT is
9982 * used, and the nested mmu code discovers that the address is
9983 * missing in the guest EPT table (EPT12), the EPT violation
9984 * will be injected with nested_ept_inject_page_fault()
9985 */
9986 return false;
9987 case EXIT_REASON_EPT_MISCONFIG:
9988 /*
9989 * L2 never uses directly L1's EPT, but rather L0's own EPT
9990 * table (shadow on EPT) or a merged EPT table that L0 built
9991 * (EPT on EPT). So any problems with the structure of the
9992 * table is L0's fault.
9993 */
9994 return false;
9995 case EXIT_REASON_INVPCID:
9996 return
9997 nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
9998 nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
9999 case EXIT_REASON_WBINVD:
10000 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
10001 case EXIT_REASON_XSETBV:
10002 return true;
10003 case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
10004 /*
10005 * This should never happen, since it is not possible to
10006 * set XSS to a non-zero value---neither in L1 nor in L2.
10007 * If if it were, XSS would have to be checked against
10008 * the XSS exit bitmap in vmcs12.
10009 */
10010 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
10011 case EXIT_REASON_PREEMPTION_TIMER:
10012 return false;
10013 case EXIT_REASON_PML_FULL:
10014 /* We emulate PML support to L1. */
10015 return false;
10016 case EXIT_REASON_VMFUNC:
10017 /* VM functions are emulated through L2->L0 vmexits. */
10018 return false;
10019 case EXIT_REASON_ENCLS:
10020 /* SGX is never exposed to L1 */
10021 return false;
10022 default:
10023 return true;
10024 }
10025 }
10026
10027 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
10028 {
10029 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10030
10031 /*
10032 * At this point, the exit interruption info in exit_intr_info
10033 * is only valid for EXCEPTION_NMI exits. For EXTERNAL_INTERRUPT
10034 * we need to query the in-kernel LAPIC.
10035 */
10036 WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
10037 if ((exit_intr_info &
10038 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
10039 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
10040 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10041 vmcs12->vm_exit_intr_error_code =
10042 vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
10043 }
10044
10045 nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
10046 vmcs_readl(EXIT_QUALIFICATION));
10047 return 1;
10048 }
10049
10050 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
10051 {
10052 *info1 = vmcs_readl(EXIT_QUALIFICATION);
10053 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
10054 }
10055
10056 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
10057 {
10058 if (vmx->pml_pg) {
10059 __free_page(vmx->pml_pg);
10060 vmx->pml_pg = NULL;
10061 }
10062 }
10063
10064 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
10065 {
10066 struct vcpu_vmx *vmx = to_vmx(vcpu);
10067 u64 *pml_buf;
10068 u16 pml_idx;
10069
10070 pml_idx = vmcs_read16(GUEST_PML_INDEX);
10071
10072 /* Do nothing if PML buffer is empty */
10073 if (pml_idx == (PML_ENTITY_NUM - 1))
10074 return;
10075
10076 /* PML index always points to next available PML buffer entity */
10077 if (pml_idx >= PML_ENTITY_NUM)
10078 pml_idx = 0;
10079 else
10080 pml_idx++;
10081
10082 pml_buf = page_address(vmx->pml_pg);
10083 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
10084 u64 gpa;
10085
10086 gpa = pml_buf[pml_idx];
10087 WARN_ON(gpa & (PAGE_SIZE - 1));
10088 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
10089 }
10090
10091 /* reset PML index */
10092 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10093 }
10094
10095 /*
10096 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
10097 * Called before reporting dirty_bitmap to userspace.
10098 */
10099 static void kvm_flush_pml_buffers(struct kvm *kvm)
10100 {
10101 int i;
10102 struct kvm_vcpu *vcpu;
10103 /*
10104 * We only need to kick vcpu out of guest mode here, as PML buffer
10105 * is flushed at beginning of all VMEXITs, and it's obvious that only
10106 * vcpus running in guest are possible to have unflushed GPAs in PML
10107 * buffer.
10108 */
10109 kvm_for_each_vcpu(i, vcpu, kvm)
10110 kvm_vcpu_kick(vcpu);
10111 }
10112
10113 static void vmx_dump_sel(char *name, uint32_t sel)
10114 {
10115 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
10116 name, vmcs_read16(sel),
10117 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
10118 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
10119 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
10120 }
10121
10122 static void vmx_dump_dtsel(char *name, uint32_t limit)
10123 {
10124 pr_err("%s limit=0x%08x, base=0x%016lx\n",
10125 name, vmcs_read32(limit),
10126 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
10127 }
10128
10129 static void dump_vmcs(void)
10130 {
10131 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
10132 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
10133 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
10134 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
10135 u32 secondary_exec_control = 0;
10136 unsigned long cr4 = vmcs_readl(GUEST_CR4);
10137 u64 efer = vmcs_read64(GUEST_IA32_EFER);
10138 int i, n;
10139
10140 if (cpu_has_secondary_exec_ctrls())
10141 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10142
10143 pr_err("*** Guest State ***\n");
10144 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
10145 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
10146 vmcs_readl(CR0_GUEST_HOST_MASK));
10147 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
10148 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
10149 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
10150 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
10151 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
10152 {
10153 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
10154 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
10155 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
10156 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
10157 }
10158 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
10159 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
10160 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
10161 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
10162 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
10163 vmcs_readl(GUEST_SYSENTER_ESP),
10164 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
10165 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
10166 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
10167 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
10168 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
10169 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
10170 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
10171 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
10172 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
10173 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
10174 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
10175 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
10176 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
10177 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
10178 efer, vmcs_read64(GUEST_IA32_PAT));
10179 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
10180 vmcs_read64(GUEST_IA32_DEBUGCTL),
10181 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
10182 if (cpu_has_load_perf_global_ctrl() &&
10183 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
10184 pr_err("PerfGlobCtl = 0x%016llx\n",
10185 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
10186 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
10187 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
10188 pr_err("Interruptibility = %08x ActivityState = %08x\n",
10189 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
10190 vmcs_read32(GUEST_ACTIVITY_STATE));
10191 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
10192 pr_err("InterruptStatus = %04x\n",
10193 vmcs_read16(GUEST_INTR_STATUS));
10194
10195 pr_err("*** Host State ***\n");
10196 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
10197 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
10198 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
10199 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
10200 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
10201 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
10202 vmcs_read16(HOST_TR_SELECTOR));
10203 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
10204 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
10205 vmcs_readl(HOST_TR_BASE));
10206 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
10207 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
10208 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
10209 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
10210 vmcs_readl(HOST_CR4));
10211 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
10212 vmcs_readl(HOST_IA32_SYSENTER_ESP),
10213 vmcs_read32(HOST_IA32_SYSENTER_CS),
10214 vmcs_readl(HOST_IA32_SYSENTER_EIP));
10215 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
10216 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
10217 vmcs_read64(HOST_IA32_EFER),
10218 vmcs_read64(HOST_IA32_PAT));
10219 if (cpu_has_load_perf_global_ctrl() &&
10220 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
10221 pr_err("PerfGlobCtl = 0x%016llx\n",
10222 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
10223
10224 pr_err("*** Control State ***\n");
10225 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
10226 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
10227 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
10228 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
10229 vmcs_read32(EXCEPTION_BITMAP),
10230 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
10231 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
10232 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
10233 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10234 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
10235 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
10236 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
10237 vmcs_read32(VM_EXIT_INTR_INFO),
10238 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
10239 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
10240 pr_err(" reason=%08x qualification=%016lx\n",
10241 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
10242 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
10243 vmcs_read32(IDT_VECTORING_INFO_FIELD),
10244 vmcs_read32(IDT_VECTORING_ERROR_CODE));
10245 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
10246 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
10247 pr_err("TSC Multiplier = 0x%016llx\n",
10248 vmcs_read64(TSC_MULTIPLIER));
10249 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
10250 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
10251 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
10252 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
10253 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
10254 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
10255 n = vmcs_read32(CR3_TARGET_COUNT);
10256 for (i = 0; i + 1 < n; i += 4)
10257 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
10258 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
10259 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
10260 if (i < n)
10261 pr_err("CR3 target%u=%016lx\n",
10262 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
10263 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
10264 pr_err("PLE Gap=%08x Window=%08x\n",
10265 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
10266 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
10267 pr_err("Virtual processor ID = 0x%04x\n",
10268 vmcs_read16(VIRTUAL_PROCESSOR_ID));
10269 }
10270
10271 /*
10272 * The guest has exited. See if we can fix it or if we need userspace
10273 * assistance.
10274 */
10275 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
10276 {
10277 struct vcpu_vmx *vmx = to_vmx(vcpu);
10278 u32 exit_reason = vmx->exit_reason;
10279 u32 vectoring_info = vmx->idt_vectoring_info;
10280
10281 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
10282
10283 /*
10284 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
10285 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
10286 * querying dirty_bitmap, we only need to kick all vcpus out of guest
10287 * mode as if vcpus is in root mode, the PML buffer must has been
10288 * flushed already.
10289 */
10290 if (enable_pml)
10291 vmx_flush_pml_buffer(vcpu);
10292
10293 /* If guest state is invalid, start emulating */
10294 if (vmx->emulation_required)
10295 return handle_invalid_guest_state(vcpu);
10296
10297 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
10298 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
10299
10300 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
10301 dump_vmcs();
10302 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10303 vcpu->run->fail_entry.hardware_entry_failure_reason
10304 = exit_reason;
10305 return 0;
10306 }
10307
10308 if (unlikely(vmx->fail)) {
10309 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10310 vcpu->run->fail_entry.hardware_entry_failure_reason
10311 = vmcs_read32(VM_INSTRUCTION_ERROR);
10312 return 0;
10313 }
10314
10315 /*
10316 * Note:
10317 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
10318 * delivery event since it indicates guest is accessing MMIO.
10319 * The vm-exit can be triggered again after return to guest that
10320 * will cause infinite loop.
10321 */
10322 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
10323 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
10324 exit_reason != EXIT_REASON_EPT_VIOLATION &&
10325 exit_reason != EXIT_REASON_PML_FULL &&
10326 exit_reason != EXIT_REASON_TASK_SWITCH)) {
10327 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10328 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
10329 vcpu->run->internal.ndata = 3;
10330 vcpu->run->internal.data[0] = vectoring_info;
10331 vcpu->run->internal.data[1] = exit_reason;
10332 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
10333 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
10334 vcpu->run->internal.ndata++;
10335 vcpu->run->internal.data[3] =
10336 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
10337 }
10338 return 0;
10339 }
10340
10341 if (unlikely(!enable_vnmi &&
10342 vmx->loaded_vmcs->soft_vnmi_blocked)) {
10343 if (vmx_interrupt_allowed(vcpu)) {
10344 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10345 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
10346 vcpu->arch.nmi_pending) {
10347 /*
10348 * This CPU don't support us in finding the end of an
10349 * NMI-blocked window if the guest runs with IRQs
10350 * disabled. So we pull the trigger after 1 s of
10351 * futile waiting, but inform the user about this.
10352 */
10353 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
10354 "state on VCPU %d after 1 s timeout\n",
10355 __func__, vcpu->vcpu_id);
10356 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10357 }
10358 }
10359
10360 if (exit_reason < kvm_vmx_max_exit_handlers
10361 && kvm_vmx_exit_handlers[exit_reason])
10362 return kvm_vmx_exit_handlers[exit_reason](vcpu);
10363 else {
10364 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
10365 exit_reason);
10366 kvm_queue_exception(vcpu, UD_VECTOR);
10367 return 1;
10368 }
10369 }
10370
10371 /*
10372 * Software based L1D cache flush which is used when microcode providing
10373 * the cache control MSR is not loaded.
10374 *
10375 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
10376 * flush it is required to read in 64 KiB because the replacement algorithm
10377 * is not exactly LRU. This could be sized at runtime via topology
10378 * information but as all relevant affected CPUs have 32KiB L1D cache size
10379 * there is no point in doing so.
10380 */
10381 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
10382 {
10383 int size = PAGE_SIZE << L1D_CACHE_ORDER;
10384
10385 /*
10386 * This code is only executed when the the flush mode is 'cond' or
10387 * 'always'
10388 */
10389 if (static_branch_likely(&vmx_l1d_flush_cond)) {
10390 bool flush_l1d;
10391
10392 /*
10393 * Clear the per-vcpu flush bit, it gets set again
10394 * either from vcpu_run() or from one of the unsafe
10395 * VMEXIT handlers.
10396 */
10397 flush_l1d = vcpu->arch.l1tf_flush_l1d;
10398 vcpu->arch.l1tf_flush_l1d = false;
10399
10400 /*
10401 * Clear the per-cpu flush bit, it gets set again from
10402 * the interrupt handlers.
10403 */
10404 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
10405 kvm_clear_cpu_l1tf_flush_l1d();
10406
10407 if (!flush_l1d)
10408 return;
10409 }
10410
10411 vcpu->stat.l1d_flush++;
10412
10413 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
10414 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
10415 return;
10416 }
10417
10418 asm volatile(
10419 /* First ensure the pages are in the TLB */
10420 "xorl %%eax, %%eax\n"
10421 ".Lpopulate_tlb:\n\t"
10422 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10423 "addl $4096, %%eax\n\t"
10424 "cmpl %%eax, %[size]\n\t"
10425 "jne .Lpopulate_tlb\n\t"
10426 "xorl %%eax, %%eax\n\t"
10427 "cpuid\n\t"
10428 /* Now fill the cache */
10429 "xorl %%eax, %%eax\n"
10430 ".Lfill_cache:\n"
10431 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10432 "addl $64, %%eax\n\t"
10433 "cmpl %%eax, %[size]\n\t"
10434 "jne .Lfill_cache\n\t"
10435 "lfence\n"
10436 :: [flush_pages] "r" (vmx_l1d_flush_pages),
10437 [size] "r" (size)
10438 : "eax", "ebx", "ecx", "edx");
10439 }
10440
10441 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
10442 {
10443 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10444
10445 if (is_guest_mode(vcpu) &&
10446 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10447 return;
10448
10449 if (irr == -1 || tpr < irr) {
10450 vmcs_write32(TPR_THRESHOLD, 0);
10451 return;
10452 }
10453
10454 vmcs_write32(TPR_THRESHOLD, irr);
10455 }
10456
10457 static void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
10458 {
10459 u32 sec_exec_control;
10460
10461 if (!lapic_in_kernel(vcpu))
10462 return;
10463
10464 if (!flexpriority_enabled &&
10465 !cpu_has_vmx_virtualize_x2apic_mode())
10466 return;
10467
10468 /* Postpone execution until vmcs01 is the current VMCS. */
10469 if (is_guest_mode(vcpu)) {
10470 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
10471 return;
10472 }
10473
10474 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10475 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10476 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
10477
10478 switch (kvm_get_apic_mode(vcpu)) {
10479 case LAPIC_MODE_INVALID:
10480 WARN_ONCE(true, "Invalid local APIC state");
10481 case LAPIC_MODE_DISABLED:
10482 break;
10483 case LAPIC_MODE_XAPIC:
10484 if (flexpriority_enabled) {
10485 sec_exec_control |=
10486 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10487 vmx_flush_tlb(vcpu, true);
10488 }
10489 break;
10490 case LAPIC_MODE_X2APIC:
10491 if (cpu_has_vmx_virtualize_x2apic_mode())
10492 sec_exec_control |=
10493 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
10494 break;
10495 }
10496 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
10497
10498 vmx_update_msr_bitmap(vcpu);
10499 }
10500
10501 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
10502 {
10503 if (!is_guest_mode(vcpu)) {
10504 vmcs_write64(APIC_ACCESS_ADDR, hpa);
10505 vmx_flush_tlb(vcpu, true);
10506 }
10507 }
10508
10509 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
10510 {
10511 u16 status;
10512 u8 old;
10513
10514 if (max_isr == -1)
10515 max_isr = 0;
10516
10517 status = vmcs_read16(GUEST_INTR_STATUS);
10518 old = status >> 8;
10519 if (max_isr != old) {
10520 status &= 0xff;
10521 status |= max_isr << 8;
10522 vmcs_write16(GUEST_INTR_STATUS, status);
10523 }
10524 }
10525
10526 static void vmx_set_rvi(int vector)
10527 {
10528 u16 status;
10529 u8 old;
10530
10531 if (vector == -1)
10532 vector = 0;
10533
10534 status = vmcs_read16(GUEST_INTR_STATUS);
10535 old = (u8)status & 0xff;
10536 if ((u8)vector != old) {
10537 status &= ~0xff;
10538 status |= (u8)vector;
10539 vmcs_write16(GUEST_INTR_STATUS, status);
10540 }
10541 }
10542
10543 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
10544 {
10545 /*
10546 * When running L2, updating RVI is only relevant when
10547 * vmcs12 virtual-interrupt-delivery enabled.
10548 * However, it can be enabled only when L1 also
10549 * intercepts external-interrupts and in that case
10550 * we should not update vmcs02 RVI but instead intercept
10551 * interrupt. Therefore, do nothing when running L2.
10552 */
10553 if (!is_guest_mode(vcpu))
10554 vmx_set_rvi(max_irr);
10555 }
10556
10557 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
10558 {
10559 struct vcpu_vmx *vmx = to_vmx(vcpu);
10560 int max_irr;
10561 bool max_irr_updated;
10562
10563 WARN_ON(!vcpu->arch.apicv_active);
10564 if (pi_test_on(&vmx->pi_desc)) {
10565 pi_clear_on(&vmx->pi_desc);
10566 /*
10567 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
10568 * But on x86 this is just a compiler barrier anyway.
10569 */
10570 smp_mb__after_atomic();
10571 max_irr_updated =
10572 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
10573
10574 /*
10575 * If we are running L2 and L1 has a new pending interrupt
10576 * which can be injected, we should re-evaluate
10577 * what should be done with this new L1 interrupt.
10578 * If L1 intercepts external-interrupts, we should
10579 * exit from L2 to L1. Otherwise, interrupt should be
10580 * delivered directly to L2.
10581 */
10582 if (is_guest_mode(vcpu) && max_irr_updated) {
10583 if (nested_exit_on_intr(vcpu))
10584 kvm_vcpu_exiting_guest_mode(vcpu);
10585 else
10586 kvm_make_request(KVM_REQ_EVENT, vcpu);
10587 }
10588 } else {
10589 max_irr = kvm_lapic_find_highest_irr(vcpu);
10590 }
10591 vmx_hwapic_irr_update(vcpu, max_irr);
10592 return max_irr;
10593 }
10594
10595 static u8 vmx_has_apicv_interrupt(struct kvm_vcpu *vcpu)
10596 {
10597 u8 rvi = vmx_get_rvi();
10598 u8 vppr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_PROCPRI);
10599
10600 return ((rvi & 0xf0) > (vppr & 0xf0));
10601 }
10602
10603 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
10604 {
10605 if (!kvm_vcpu_apicv_active(vcpu))
10606 return;
10607
10608 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
10609 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
10610 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
10611 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
10612 }
10613
10614 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
10615 {
10616 struct vcpu_vmx *vmx = to_vmx(vcpu);
10617
10618 pi_clear_on(&vmx->pi_desc);
10619 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
10620 }
10621
10622 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
10623 {
10624 u32 exit_intr_info = 0;
10625 u16 basic_exit_reason = (u16)vmx->exit_reason;
10626
10627 if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
10628 || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
10629 return;
10630
10631 if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10632 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10633 vmx->exit_intr_info = exit_intr_info;
10634
10635 /* if exit due to PF check for async PF */
10636 if (is_page_fault(exit_intr_info))
10637 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
10638
10639 /* Handle machine checks before interrupts are enabled */
10640 if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
10641 is_machine_check(exit_intr_info))
10642 kvm_machine_check();
10643
10644 /* We need to handle NMIs before interrupts are enabled */
10645 if (is_nmi(exit_intr_info)) {
10646 kvm_before_interrupt(&vmx->vcpu);
10647 asm("int $2");
10648 kvm_after_interrupt(&vmx->vcpu);
10649 }
10650 }
10651
10652 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
10653 {
10654 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10655
10656 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
10657 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
10658 unsigned int vector;
10659 unsigned long entry;
10660 gate_desc *desc;
10661 struct vcpu_vmx *vmx = to_vmx(vcpu);
10662 #ifdef CONFIG_X86_64
10663 unsigned long tmp;
10664 #endif
10665
10666 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
10667 desc = (gate_desc *)vmx->host_idt_base + vector;
10668 entry = gate_offset(desc);
10669 asm volatile(
10670 #ifdef CONFIG_X86_64
10671 "mov %%" _ASM_SP ", %[sp]\n\t"
10672 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
10673 "push $%c[ss]\n\t"
10674 "push %[sp]\n\t"
10675 #endif
10676 "pushf\n\t"
10677 __ASM_SIZE(push) " $%c[cs]\n\t"
10678 CALL_NOSPEC
10679 :
10680 #ifdef CONFIG_X86_64
10681 [sp]"=&r"(tmp),
10682 #endif
10683 ASM_CALL_CONSTRAINT
10684 :
10685 THUNK_TARGET(entry),
10686 [ss]"i"(__KERNEL_DS),
10687 [cs]"i"(__KERNEL_CS)
10688 );
10689 }
10690 }
10691 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
10692
10693 static bool vmx_has_emulated_msr(int index)
10694 {
10695 switch (index) {
10696 case MSR_IA32_SMBASE:
10697 /*
10698 * We cannot do SMM unless we can run the guest in big
10699 * real mode.
10700 */
10701 return enable_unrestricted_guest || emulate_invalid_guest_state;
10702 case MSR_AMD64_VIRT_SPEC_CTRL:
10703 /* This is AMD only. */
10704 return false;
10705 default:
10706 return true;
10707 }
10708 }
10709
10710 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
10711 {
10712 u32 exit_intr_info;
10713 bool unblock_nmi;
10714 u8 vector;
10715 bool idtv_info_valid;
10716
10717 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10718
10719 if (enable_vnmi) {
10720 if (vmx->loaded_vmcs->nmi_known_unmasked)
10721 return;
10722 /*
10723 * Can't use vmx->exit_intr_info since we're not sure what
10724 * the exit reason is.
10725 */
10726 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10727 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
10728 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
10729 /*
10730 * SDM 3: 27.7.1.2 (September 2008)
10731 * Re-set bit "block by NMI" before VM entry if vmexit caused by
10732 * a guest IRET fault.
10733 * SDM 3: 23.2.2 (September 2008)
10734 * Bit 12 is undefined in any of the following cases:
10735 * If the VM exit sets the valid bit in the IDT-vectoring
10736 * information field.
10737 * If the VM exit is due to a double fault.
10738 */
10739 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
10740 vector != DF_VECTOR && !idtv_info_valid)
10741 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
10742 GUEST_INTR_STATE_NMI);
10743 else
10744 vmx->loaded_vmcs->nmi_known_unmasked =
10745 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
10746 & GUEST_INTR_STATE_NMI);
10747 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
10748 vmx->loaded_vmcs->vnmi_blocked_time +=
10749 ktime_to_ns(ktime_sub(ktime_get(),
10750 vmx->loaded_vmcs->entry_time));
10751 }
10752
10753 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
10754 u32 idt_vectoring_info,
10755 int instr_len_field,
10756 int error_code_field)
10757 {
10758 u8 vector;
10759 int type;
10760 bool idtv_info_valid;
10761
10762 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10763
10764 vcpu->arch.nmi_injected = false;
10765 kvm_clear_exception_queue(vcpu);
10766 kvm_clear_interrupt_queue(vcpu);
10767
10768 if (!idtv_info_valid)
10769 return;
10770
10771 kvm_make_request(KVM_REQ_EVENT, vcpu);
10772
10773 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
10774 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
10775
10776 switch (type) {
10777 case INTR_TYPE_NMI_INTR:
10778 vcpu->arch.nmi_injected = true;
10779 /*
10780 * SDM 3: 27.7.1.2 (September 2008)
10781 * Clear bit "block by NMI" before VM entry if a NMI
10782 * delivery faulted.
10783 */
10784 vmx_set_nmi_mask(vcpu, false);
10785 break;
10786 case INTR_TYPE_SOFT_EXCEPTION:
10787 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
10788 /* fall through */
10789 case INTR_TYPE_HARD_EXCEPTION:
10790 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
10791 u32 err = vmcs_read32(error_code_field);
10792 kvm_requeue_exception_e(vcpu, vector, err);
10793 } else
10794 kvm_requeue_exception(vcpu, vector);
10795 break;
10796 case INTR_TYPE_SOFT_INTR:
10797 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
10798 /* fall through */
10799 case INTR_TYPE_EXT_INTR:
10800 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
10801 break;
10802 default:
10803 break;
10804 }
10805 }
10806
10807 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
10808 {
10809 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
10810 VM_EXIT_INSTRUCTION_LEN,
10811 IDT_VECTORING_ERROR_CODE);
10812 }
10813
10814 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
10815 {
10816 __vmx_complete_interrupts(vcpu,
10817 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10818 VM_ENTRY_INSTRUCTION_LEN,
10819 VM_ENTRY_EXCEPTION_ERROR_CODE);
10820
10821 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10822 }
10823
10824 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
10825 {
10826 int i, nr_msrs;
10827 struct perf_guest_switch_msr *msrs;
10828
10829 msrs = perf_guest_get_msrs(&nr_msrs);
10830
10831 if (!msrs)
10832 return;
10833
10834 for (i = 0; i < nr_msrs; i++)
10835 if (msrs[i].host == msrs[i].guest)
10836 clear_atomic_switch_msr(vmx, msrs[i].msr);
10837 else
10838 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
10839 msrs[i].host, false);
10840 }
10841
10842 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
10843 {
10844 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
10845 if (!vmx->loaded_vmcs->hv_timer_armed)
10846 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
10847 PIN_BASED_VMX_PREEMPTION_TIMER);
10848 vmx->loaded_vmcs->hv_timer_armed = true;
10849 }
10850
10851 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
10852 {
10853 struct vcpu_vmx *vmx = to_vmx(vcpu);
10854 u64 tscl;
10855 u32 delta_tsc;
10856
10857 if (vmx->req_immediate_exit) {
10858 vmx_arm_hv_timer(vmx, 0);
10859 return;
10860 }
10861
10862 if (vmx->hv_deadline_tsc != -1) {
10863 tscl = rdtsc();
10864 if (vmx->hv_deadline_tsc > tscl)
10865 /* set_hv_timer ensures the delta fits in 32-bits */
10866 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
10867 cpu_preemption_timer_multi);
10868 else
10869 delta_tsc = 0;
10870
10871 vmx_arm_hv_timer(vmx, delta_tsc);
10872 return;
10873 }
10874
10875 if (vmx->loaded_vmcs->hv_timer_armed)
10876 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
10877 PIN_BASED_VMX_PREEMPTION_TIMER);
10878 vmx->loaded_vmcs->hv_timer_armed = false;
10879 }
10880
10881 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
10882 {
10883 struct vcpu_vmx *vmx = to_vmx(vcpu);
10884 unsigned long cr3, cr4, evmcs_rsp;
10885
10886 /* Record the guest's net vcpu time for enforced NMI injections. */
10887 if (unlikely(!enable_vnmi &&
10888 vmx->loaded_vmcs->soft_vnmi_blocked))
10889 vmx->loaded_vmcs->entry_time = ktime_get();
10890
10891 /* Don't enter VMX if guest state is invalid, let the exit handler
10892 start emulation until we arrive back to a valid state */
10893 if (vmx->emulation_required)
10894 return;
10895
10896 if (vmx->ple_window_dirty) {
10897 vmx->ple_window_dirty = false;
10898 vmcs_write32(PLE_WINDOW, vmx->ple_window);
10899 }
10900
10901 if (vmx->nested.need_vmcs12_sync) {
10902 /*
10903 * hv_evmcs may end up being not mapped after migration (when
10904 * L2 was running), map it here to make sure vmcs12 changes are
10905 * properly reflected.
10906 */
10907 if (vmx->nested.enlightened_vmcs_enabled &&
10908 !vmx->nested.hv_evmcs)
10909 nested_vmx_handle_enlightened_vmptrld(vcpu, false);
10910
10911 if (vmx->nested.hv_evmcs) {
10912 copy_vmcs12_to_enlightened(vmx);
10913 /* All fields are clean */
10914 vmx->nested.hv_evmcs->hv_clean_fields |=
10915 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
10916 } else {
10917 copy_vmcs12_to_shadow(vmx);
10918 }
10919 vmx->nested.need_vmcs12_sync = false;
10920 }
10921
10922 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
10923 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
10924 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
10925 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
10926
10927 cr3 = __get_current_cr3_fast();
10928 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
10929 vmcs_writel(HOST_CR3, cr3);
10930 vmx->loaded_vmcs->host_state.cr3 = cr3;
10931 }
10932
10933 cr4 = cr4_read_shadow();
10934 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
10935 vmcs_writel(HOST_CR4, cr4);
10936 vmx->loaded_vmcs->host_state.cr4 = cr4;
10937 }
10938
10939 /* When single-stepping over STI and MOV SS, we must clear the
10940 * corresponding interruptibility bits in the guest state. Otherwise
10941 * vmentry fails as it then expects bit 14 (BS) in pending debug
10942 * exceptions being set, but that's not correct for the guest debugging
10943 * case. */
10944 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10945 vmx_set_interrupt_shadow(vcpu, 0);
10946
10947 if (static_cpu_has(X86_FEATURE_PKU) &&
10948 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
10949 vcpu->arch.pkru != vmx->host_pkru)
10950 __write_pkru(vcpu->arch.pkru);
10951
10952 atomic_switch_perf_msrs(vmx);
10953
10954 vmx_update_hv_timer(vcpu);
10955
10956 /*
10957 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
10958 * it's non-zero. Since vmentry is serialising on affected CPUs, there
10959 * is no need to worry about the conditional branch over the wrmsr
10960 * being speculatively taken.
10961 */
10962 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
10963
10964 vmx->__launched = vmx->loaded_vmcs->launched;
10965
10966 evmcs_rsp = static_branch_unlikely(&enable_evmcs) ?
10967 (unsigned long)&current_evmcs->host_rsp : 0;
10968
10969 if (static_branch_unlikely(&vmx_l1d_should_flush))
10970 vmx_l1d_flush(vcpu);
10971
10972 asm(
10973 /* Store host registers */
10974 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
10975 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
10976 "push %%" _ASM_CX " \n\t"
10977 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
10978 "je 1f \n\t"
10979 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
10980 /* Avoid VMWRITE when Enlightened VMCS is in use */
10981 "test %%" _ASM_SI ", %%" _ASM_SI " \n\t"
10982 "jz 2f \n\t"
10983 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
10984 "jmp 1f \n\t"
10985 "2: \n\t"
10986 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
10987 "1: \n\t"
10988 /* Reload cr2 if changed */
10989 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
10990 "mov %%cr2, %%" _ASM_DX " \n\t"
10991 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
10992 "je 3f \n\t"
10993 "mov %%" _ASM_AX", %%cr2 \n\t"
10994 "3: \n\t"
10995 /* Check if vmlaunch or vmresume is needed */
10996 "cmpl $0, %c[launched](%0) \n\t"
10997 /* Load guest registers. Don't clobber flags. */
10998 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
10999 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
11000 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
11001 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
11002 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
11003 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
11004 #ifdef CONFIG_X86_64
11005 "mov %c[r8](%0), %%r8 \n\t"
11006 "mov %c[r9](%0), %%r9 \n\t"
11007 "mov %c[r10](%0), %%r10 \n\t"
11008 "mov %c[r11](%0), %%r11 \n\t"
11009 "mov %c[r12](%0), %%r12 \n\t"
11010 "mov %c[r13](%0), %%r13 \n\t"
11011 "mov %c[r14](%0), %%r14 \n\t"
11012 "mov %c[r15](%0), %%r15 \n\t"
11013 #endif
11014 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
11015
11016 /* Enter guest mode */
11017 "jne 1f \n\t"
11018 __ex("vmlaunch") "\n\t"
11019 "jmp 2f \n\t"
11020 "1: " __ex("vmresume") "\n\t"
11021 "2: "
11022 /* Save guest registers, load host registers, keep flags */
11023 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
11024 "pop %0 \n\t"
11025 "setbe %c[fail](%0)\n\t"
11026 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
11027 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
11028 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
11029 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
11030 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
11031 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
11032 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
11033 #ifdef CONFIG_X86_64
11034 "mov %%r8, %c[r8](%0) \n\t"
11035 "mov %%r9, %c[r9](%0) \n\t"
11036 "mov %%r10, %c[r10](%0) \n\t"
11037 "mov %%r11, %c[r11](%0) \n\t"
11038 "mov %%r12, %c[r12](%0) \n\t"
11039 "mov %%r13, %c[r13](%0) \n\t"
11040 "mov %%r14, %c[r14](%0) \n\t"
11041 "mov %%r15, %c[r15](%0) \n\t"
11042 /*
11043 * Clear host registers marked as clobbered to prevent
11044 * speculative use.
11045 */
11046 "xor %%r8d, %%r8d \n\t"
11047 "xor %%r9d, %%r9d \n\t"
11048 "xor %%r10d, %%r10d \n\t"
11049 "xor %%r11d, %%r11d \n\t"
11050 "xor %%r12d, %%r12d \n\t"
11051 "xor %%r13d, %%r13d \n\t"
11052 "xor %%r14d, %%r14d \n\t"
11053 "xor %%r15d, %%r15d \n\t"
11054 #endif
11055 "mov %%cr2, %%" _ASM_AX " \n\t"
11056 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
11057
11058 "xor %%eax, %%eax \n\t"
11059 "xor %%ebx, %%ebx \n\t"
11060 "xor %%esi, %%esi \n\t"
11061 "xor %%edi, %%edi \n\t"
11062 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
11063 ".pushsection .rodata \n\t"
11064 ".global vmx_return \n\t"
11065 "vmx_return: " _ASM_PTR " 2b \n\t"
11066 ".popsection"
11067 : : "c"(vmx), "d"((unsigned long)HOST_RSP), "S"(evmcs_rsp),
11068 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
11069 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
11070 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
11071 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
11072 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
11073 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
11074 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
11075 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
11076 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
11077 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
11078 #ifdef CONFIG_X86_64
11079 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
11080 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
11081 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
11082 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
11083 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
11084 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
11085 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
11086 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
11087 #endif
11088 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
11089 [wordsize]"i"(sizeof(ulong))
11090 : "cc", "memory"
11091 #ifdef CONFIG_X86_64
11092 , "rax", "rbx", "rdi"
11093 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
11094 #else
11095 , "eax", "ebx", "edi"
11096 #endif
11097 );
11098
11099 /*
11100 * We do not use IBRS in the kernel. If this vCPU has used the
11101 * SPEC_CTRL MSR it may have left it on; save the value and
11102 * turn it off. This is much more efficient than blindly adding
11103 * it to the atomic save/restore list. Especially as the former
11104 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
11105 *
11106 * For non-nested case:
11107 * If the L01 MSR bitmap does not intercept the MSR, then we need to
11108 * save it.
11109 *
11110 * For nested case:
11111 * If the L02 MSR bitmap does not intercept the MSR, then we need to
11112 * save it.
11113 */
11114 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
11115 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
11116
11117 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
11118
11119 /* Eliminate branch target predictions from guest mode */
11120 vmexit_fill_RSB();
11121
11122 /* All fields are clean at this point */
11123 if (static_branch_unlikely(&enable_evmcs))
11124 current_evmcs->hv_clean_fields |=
11125 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
11126
11127 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
11128 if (vmx->host_debugctlmsr)
11129 update_debugctlmsr(vmx->host_debugctlmsr);
11130
11131 #ifndef CONFIG_X86_64
11132 /*
11133 * The sysexit path does not restore ds/es, so we must set them to
11134 * a reasonable value ourselves.
11135 *
11136 * We can't defer this to vmx_prepare_switch_to_host() since that
11137 * function may be executed in interrupt context, which saves and
11138 * restore segments around it, nullifying its effect.
11139 */
11140 loadsegment(ds, __USER_DS);
11141 loadsegment(es, __USER_DS);
11142 #endif
11143
11144 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
11145 | (1 << VCPU_EXREG_RFLAGS)
11146 | (1 << VCPU_EXREG_PDPTR)
11147 | (1 << VCPU_EXREG_SEGMENTS)
11148 | (1 << VCPU_EXREG_CR3));
11149 vcpu->arch.regs_dirty = 0;
11150
11151 /*
11152 * eager fpu is enabled if PKEY is supported and CR4 is switched
11153 * back on host, so it is safe to read guest PKRU from current
11154 * XSAVE.
11155 */
11156 if (static_cpu_has(X86_FEATURE_PKU) &&
11157 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
11158 vcpu->arch.pkru = __read_pkru();
11159 if (vcpu->arch.pkru != vmx->host_pkru)
11160 __write_pkru(vmx->host_pkru);
11161 }
11162
11163 vmx->nested.nested_run_pending = 0;
11164 vmx->idt_vectoring_info = 0;
11165
11166 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
11167 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
11168 return;
11169
11170 vmx->loaded_vmcs->launched = 1;
11171 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
11172
11173 vmx_complete_atomic_exit(vmx);
11174 vmx_recover_nmi_blocking(vmx);
11175 vmx_complete_interrupts(vmx);
11176 }
11177 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
11178
11179 static struct kvm *vmx_vm_alloc(void)
11180 {
11181 struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
11182 return &kvm_vmx->kvm;
11183 }
11184
11185 static void vmx_vm_free(struct kvm *kvm)
11186 {
11187 vfree(to_kvm_vmx(kvm));
11188 }
11189
11190 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
11191 {
11192 struct vcpu_vmx *vmx = to_vmx(vcpu);
11193 int cpu;
11194
11195 if (vmx->loaded_vmcs == vmcs)
11196 return;
11197
11198 cpu = get_cpu();
11199 vmx_vcpu_put(vcpu);
11200 vmx->loaded_vmcs = vmcs;
11201 vmx_vcpu_load(vcpu, cpu);
11202 put_cpu();
11203
11204 vm_entry_controls_reset_shadow(vmx);
11205 vm_exit_controls_reset_shadow(vmx);
11206 vmx_segment_cache_clear(vmx);
11207 }
11208
11209 /*
11210 * Ensure that the current vmcs of the logical processor is the
11211 * vmcs01 of the vcpu before calling free_nested().
11212 */
11213 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
11214 {
11215 vcpu_load(vcpu);
11216 vmx_switch_vmcs(vcpu, &to_vmx(vcpu)->vmcs01);
11217 free_nested(vcpu);
11218 vcpu_put(vcpu);
11219 }
11220
11221 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
11222 {
11223 struct vcpu_vmx *vmx = to_vmx(vcpu);
11224
11225 if (enable_pml)
11226 vmx_destroy_pml_buffer(vmx);
11227 free_vpid(vmx->vpid);
11228 leave_guest_mode(vcpu);
11229 vmx_free_vcpu_nested(vcpu);
11230 free_loaded_vmcs(vmx->loaded_vmcs);
11231 kfree(vmx->guest_msrs);
11232 kvm_vcpu_uninit(vcpu);
11233 kmem_cache_free(kvm_vcpu_cache, vmx);
11234 }
11235
11236 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
11237 {
11238 int err;
11239 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
11240 unsigned long *msr_bitmap;
11241 int cpu;
11242
11243 if (!vmx)
11244 return ERR_PTR(-ENOMEM);
11245
11246 vmx->vpid = allocate_vpid();
11247
11248 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
11249 if (err)
11250 goto free_vcpu;
11251
11252 err = -ENOMEM;
11253
11254 /*
11255 * If PML is turned on, failure on enabling PML just results in failure
11256 * of creating the vcpu, therefore we can simplify PML logic (by
11257 * avoiding dealing with cases, such as enabling PML partially on vcpus
11258 * for the guest, etc.
11259 */
11260 if (enable_pml) {
11261 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
11262 if (!vmx->pml_pg)
11263 goto uninit_vcpu;
11264 }
11265
11266 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
11267 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
11268 > PAGE_SIZE);
11269
11270 if (!vmx->guest_msrs)
11271 goto free_pml;
11272
11273 err = alloc_loaded_vmcs(&vmx->vmcs01);
11274 if (err < 0)
11275 goto free_msrs;
11276
11277 msr_bitmap = vmx->vmcs01.msr_bitmap;
11278 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
11279 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
11280 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
11281 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
11282 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
11283 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
11284 vmx->msr_bitmap_mode = 0;
11285
11286 vmx->loaded_vmcs = &vmx->vmcs01;
11287 cpu = get_cpu();
11288 vmx_vcpu_load(&vmx->vcpu, cpu);
11289 vmx->vcpu.cpu = cpu;
11290 vmx_vcpu_setup(vmx);
11291 vmx_vcpu_put(&vmx->vcpu);
11292 put_cpu();
11293 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
11294 err = alloc_apic_access_page(kvm);
11295 if (err)
11296 goto free_vmcs;
11297 }
11298
11299 if (enable_ept && !enable_unrestricted_guest) {
11300 err = init_rmode_identity_map(kvm);
11301 if (err)
11302 goto free_vmcs;
11303 }
11304
11305 if (nested)
11306 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
11307 vmx_capability.ept,
11308 kvm_vcpu_apicv_active(&vmx->vcpu));
11309
11310 vmx->nested.posted_intr_nv = -1;
11311 vmx->nested.current_vmptr = -1ull;
11312
11313 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
11314
11315 /*
11316 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
11317 * or POSTED_INTR_WAKEUP_VECTOR.
11318 */
11319 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
11320 vmx->pi_desc.sn = 1;
11321
11322 return &vmx->vcpu;
11323
11324 free_vmcs:
11325 free_loaded_vmcs(vmx->loaded_vmcs);
11326 free_msrs:
11327 kfree(vmx->guest_msrs);
11328 free_pml:
11329 vmx_destroy_pml_buffer(vmx);
11330 uninit_vcpu:
11331 kvm_vcpu_uninit(&vmx->vcpu);
11332 free_vcpu:
11333 free_vpid(vmx->vpid);
11334 kmem_cache_free(kvm_vcpu_cache, vmx);
11335 return ERR_PTR(err);
11336 }
11337
11338 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/l1tf.html for details.\n"
11339 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/l1tf.html for details.\n"
11340
11341 static int vmx_vm_init(struct kvm *kvm)
11342 {
11343 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
11344
11345 if (!ple_gap)
11346 kvm->arch.pause_in_guest = true;
11347
11348 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
11349 switch (l1tf_mitigation) {
11350 case L1TF_MITIGATION_OFF:
11351 case L1TF_MITIGATION_FLUSH_NOWARN:
11352 /* 'I explicitly don't care' is set */
11353 break;
11354 case L1TF_MITIGATION_FLUSH:
11355 case L1TF_MITIGATION_FLUSH_NOSMT:
11356 case L1TF_MITIGATION_FULL:
11357 /*
11358 * Warn upon starting the first VM in a potentially
11359 * insecure environment.
11360 */
11361 if (cpu_smt_control == CPU_SMT_ENABLED)
11362 pr_warn_once(L1TF_MSG_SMT);
11363 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
11364 pr_warn_once(L1TF_MSG_L1D);
11365 break;
11366 case L1TF_MITIGATION_FULL_FORCE:
11367 /* Flush is enforced */
11368 break;
11369 }
11370 }
11371 return 0;
11372 }
11373
11374 static void __init vmx_check_processor_compat(void *rtn)
11375 {
11376 struct vmcs_config vmcs_conf;
11377 struct vmx_capability vmx_cap;
11378
11379 *(int *)rtn = 0;
11380 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
11381 *(int *)rtn = -EIO;
11382 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept, enable_apicv);
11383 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
11384 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
11385 smp_processor_id());
11386 *(int *)rtn = -EIO;
11387 }
11388 }
11389
11390 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
11391 {
11392 u8 cache;
11393 u64 ipat = 0;
11394
11395 /* For VT-d and EPT combination
11396 * 1. MMIO: always map as UC
11397 * 2. EPT with VT-d:
11398 * a. VT-d without snooping control feature: can't guarantee the
11399 * result, try to trust guest.
11400 * b. VT-d with snooping control feature: snooping control feature of
11401 * VT-d engine can guarantee the cache correctness. Just set it
11402 * to WB to keep consistent with host. So the same as item 3.
11403 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
11404 * consistent with host MTRR
11405 */
11406 if (is_mmio) {
11407 cache = MTRR_TYPE_UNCACHABLE;
11408 goto exit;
11409 }
11410
11411 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
11412 ipat = VMX_EPT_IPAT_BIT;
11413 cache = MTRR_TYPE_WRBACK;
11414 goto exit;
11415 }
11416
11417 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
11418 ipat = VMX_EPT_IPAT_BIT;
11419 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
11420 cache = MTRR_TYPE_WRBACK;
11421 else
11422 cache = MTRR_TYPE_UNCACHABLE;
11423 goto exit;
11424 }
11425
11426 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
11427
11428 exit:
11429 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
11430 }
11431
11432 static int vmx_get_lpage_level(void)
11433 {
11434 if (enable_ept && !cpu_has_vmx_ept_1g_page())
11435 return PT_DIRECTORY_LEVEL;
11436 else
11437 /* For shadow and EPT supported 1GB page */
11438 return PT_PDPE_LEVEL;
11439 }
11440
11441 static void vmcs_set_secondary_exec_control(u32 new_ctl)
11442 {
11443 /*
11444 * These bits in the secondary execution controls field
11445 * are dynamic, the others are mostly based on the hypervisor
11446 * architecture and the guest's CPUID. Do not touch the
11447 * dynamic bits.
11448 */
11449 u32 mask =
11450 SECONDARY_EXEC_SHADOW_VMCS |
11451 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
11452 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
11453 SECONDARY_EXEC_DESC;
11454
11455 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
11456
11457 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
11458 (new_ctl & ~mask) | (cur_ctl & mask));
11459 }
11460
11461 /*
11462 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
11463 * (indicating "allowed-1") if they are supported in the guest's CPUID.
11464 */
11465 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
11466 {
11467 struct vcpu_vmx *vmx = to_vmx(vcpu);
11468 struct kvm_cpuid_entry2 *entry;
11469
11470 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
11471 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
11472
11473 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
11474 if (entry && (entry->_reg & (_cpuid_mask))) \
11475 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
11476 } while (0)
11477
11478 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
11479 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
11480 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
11481 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
11482 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
11483 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
11484 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
11485 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
11486 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
11487 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
11488 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
11489 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
11490 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
11491 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
11492 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
11493
11494 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
11495 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
11496 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
11497 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
11498 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
11499 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
11500
11501 #undef cr4_fixed1_update
11502 }
11503
11504 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
11505 {
11506 struct vcpu_vmx *vmx = to_vmx(vcpu);
11507
11508 if (kvm_mpx_supported()) {
11509 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
11510
11511 if (mpx_enabled) {
11512 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
11513 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
11514 } else {
11515 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
11516 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
11517 }
11518 }
11519 }
11520
11521 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
11522 {
11523 struct vcpu_vmx *vmx = to_vmx(vcpu);
11524
11525 if (cpu_has_secondary_exec_ctrls()) {
11526 vmx_compute_secondary_exec_control(vmx);
11527 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
11528 }
11529
11530 if (nested_vmx_allowed(vcpu))
11531 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11532 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11533 else
11534 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
11535 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11536
11537 if (nested_vmx_allowed(vcpu)) {
11538 nested_vmx_cr_fixed1_bits_update(vcpu);
11539 nested_vmx_entry_exit_ctls_update(vcpu);
11540 }
11541 }
11542
11543 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
11544 {
11545 if (func == 1 && nested)
11546 entry->ecx |= bit(X86_FEATURE_VMX);
11547 }
11548
11549 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
11550 struct x86_exception *fault)
11551 {
11552 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11553 struct vcpu_vmx *vmx = to_vmx(vcpu);
11554 u32 exit_reason;
11555 unsigned long exit_qualification = vcpu->arch.exit_qualification;
11556
11557 if (vmx->nested.pml_full) {
11558 exit_reason = EXIT_REASON_PML_FULL;
11559 vmx->nested.pml_full = false;
11560 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
11561 } else if (fault->error_code & PFERR_RSVD_MASK)
11562 exit_reason = EXIT_REASON_EPT_MISCONFIG;
11563 else
11564 exit_reason = EXIT_REASON_EPT_VIOLATION;
11565
11566 nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
11567 vmcs12->guest_physical_address = fault->address;
11568 }
11569
11570 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
11571 {
11572 return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
11573 }
11574
11575 /* Callbacks for nested_ept_init_mmu_context: */
11576
11577 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
11578 {
11579 /* return the page table to be shadowed - in our case, EPT12 */
11580 return get_vmcs12(vcpu)->ept_pointer;
11581 }
11582
11583 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
11584 {
11585 WARN_ON(mmu_is_nested(vcpu));
11586
11587 vcpu->arch.mmu = &vcpu->arch.guest_mmu;
11588 kvm_init_shadow_ept_mmu(vcpu,
11589 to_vmx(vcpu)->nested.msrs.ept_caps &
11590 VMX_EPT_EXECUTE_ONLY_BIT,
11591 nested_ept_ad_enabled(vcpu),
11592 nested_ept_get_cr3(vcpu));
11593 vcpu->arch.mmu->set_cr3 = vmx_set_cr3;
11594 vcpu->arch.mmu->get_cr3 = nested_ept_get_cr3;
11595 vcpu->arch.mmu->inject_page_fault = nested_ept_inject_page_fault;
11596 vcpu->arch.mmu->get_pdptr = kvm_pdptr_read;
11597
11598 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
11599 }
11600
11601 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
11602 {
11603 vcpu->arch.mmu = &vcpu->arch.root_mmu;
11604 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
11605 }
11606
11607 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
11608 u16 error_code)
11609 {
11610 bool inequality, bit;
11611
11612 bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
11613 inequality =
11614 (error_code & vmcs12->page_fault_error_code_mask) !=
11615 vmcs12->page_fault_error_code_match;
11616 return inequality ^ bit;
11617 }
11618
11619 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
11620 struct x86_exception *fault)
11621 {
11622 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11623
11624 WARN_ON(!is_guest_mode(vcpu));
11625
11626 if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
11627 !to_vmx(vcpu)->nested.nested_run_pending) {
11628 vmcs12->vm_exit_intr_error_code = fault->error_code;
11629 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11630 PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
11631 INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
11632 fault->address);
11633 } else {
11634 kvm_inject_page_fault(vcpu, fault);
11635 }
11636 }
11637
11638 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11639 struct vmcs12 *vmcs12);
11640
11641 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
11642 {
11643 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11644 struct vcpu_vmx *vmx = to_vmx(vcpu);
11645 struct page *page;
11646 u64 hpa;
11647
11648 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11649 /*
11650 * Translate L1 physical address to host physical
11651 * address for vmcs02. Keep the page pinned, so this
11652 * physical address remains valid. We keep a reference
11653 * to it so we can release it later.
11654 */
11655 if (vmx->nested.apic_access_page) { /* shouldn't happen */
11656 kvm_release_page_dirty(vmx->nested.apic_access_page);
11657 vmx->nested.apic_access_page = NULL;
11658 }
11659 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
11660 /*
11661 * If translation failed, no matter: This feature asks
11662 * to exit when accessing the given address, and if it
11663 * can never be accessed, this feature won't do
11664 * anything anyway.
11665 */
11666 if (!is_error_page(page)) {
11667 vmx->nested.apic_access_page = page;
11668 hpa = page_to_phys(vmx->nested.apic_access_page);
11669 vmcs_write64(APIC_ACCESS_ADDR, hpa);
11670 } else {
11671 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
11672 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
11673 }
11674 }
11675
11676 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
11677 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
11678 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11679 vmx->nested.virtual_apic_page = NULL;
11680 }
11681 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
11682
11683 /*
11684 * If translation failed, VM entry will fail because
11685 * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
11686 * Failing the vm entry is _not_ what the processor
11687 * does but it's basically the only possibility we
11688 * have. We could still enter the guest if CR8 load
11689 * exits are enabled, CR8 store exits are enabled, and
11690 * virtualize APIC access is disabled; in this case
11691 * the processor would never use the TPR shadow and we
11692 * could simply clear the bit from the execution
11693 * control. But such a configuration is useless, so
11694 * let's keep the code simple.
11695 */
11696 if (!is_error_page(page)) {
11697 vmx->nested.virtual_apic_page = page;
11698 hpa = page_to_phys(vmx->nested.virtual_apic_page);
11699 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
11700 }
11701 }
11702
11703 if (nested_cpu_has_posted_intr(vmcs12)) {
11704 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
11705 kunmap(vmx->nested.pi_desc_page);
11706 kvm_release_page_dirty(vmx->nested.pi_desc_page);
11707 vmx->nested.pi_desc_page = NULL;
11708 }
11709 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
11710 if (is_error_page(page))
11711 return;
11712 vmx->nested.pi_desc_page = page;
11713 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
11714 vmx->nested.pi_desc =
11715 (struct pi_desc *)((void *)vmx->nested.pi_desc +
11716 (unsigned long)(vmcs12->posted_intr_desc_addr &
11717 (PAGE_SIZE - 1)));
11718 vmcs_write64(POSTED_INTR_DESC_ADDR,
11719 page_to_phys(vmx->nested.pi_desc_page) +
11720 (unsigned long)(vmcs12->posted_intr_desc_addr &
11721 (PAGE_SIZE - 1)));
11722 }
11723 if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
11724 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
11725 CPU_BASED_USE_MSR_BITMAPS);
11726 else
11727 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
11728 CPU_BASED_USE_MSR_BITMAPS);
11729 }
11730
11731 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
11732 {
11733 u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
11734 struct vcpu_vmx *vmx = to_vmx(vcpu);
11735
11736 /*
11737 * A timer value of zero is architecturally guaranteed to cause
11738 * a VMExit prior to executing any instructions in the guest.
11739 */
11740 if (preemption_timeout == 0) {
11741 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
11742 return;
11743 }
11744
11745 if (vcpu->arch.virtual_tsc_khz == 0)
11746 return;
11747
11748 preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11749 preemption_timeout *= 1000000;
11750 do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
11751 hrtimer_start(&vmx->nested.preemption_timer,
11752 ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
11753 }
11754
11755 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
11756 struct vmcs12 *vmcs12)
11757 {
11758 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
11759 return 0;
11760
11761 if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
11762 !page_address_valid(vcpu, vmcs12->io_bitmap_b))
11763 return -EINVAL;
11764
11765 return 0;
11766 }
11767
11768 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
11769 struct vmcs12 *vmcs12)
11770 {
11771 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
11772 return 0;
11773
11774 if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
11775 return -EINVAL;
11776
11777 return 0;
11778 }
11779
11780 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
11781 struct vmcs12 *vmcs12)
11782 {
11783 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
11784 return 0;
11785
11786 if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
11787 return -EINVAL;
11788
11789 return 0;
11790 }
11791
11792 /*
11793 * Merge L0's and L1's MSR bitmap, return false to indicate that
11794 * we do not use the hardware.
11795 */
11796 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11797 struct vmcs12 *vmcs12)
11798 {
11799 int msr;
11800 struct page *page;
11801 unsigned long *msr_bitmap_l1;
11802 unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
11803 /*
11804 * pred_cmd & spec_ctrl are trying to verify two things:
11805 *
11806 * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
11807 * ensures that we do not accidentally generate an L02 MSR bitmap
11808 * from the L12 MSR bitmap that is too permissive.
11809 * 2. That L1 or L2s have actually used the MSR. This avoids
11810 * unnecessarily merging of the bitmap if the MSR is unused. This
11811 * works properly because we only update the L01 MSR bitmap lazily.
11812 * So even if L0 should pass L1 these MSRs, the L01 bitmap is only
11813 * updated to reflect this when L1 (or its L2s) actually write to
11814 * the MSR.
11815 */
11816 bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
11817 bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
11818
11819 /* Nothing to do if the MSR bitmap is not in use. */
11820 if (!cpu_has_vmx_msr_bitmap() ||
11821 !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
11822 return false;
11823
11824 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11825 !pred_cmd && !spec_ctrl)
11826 return false;
11827
11828 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
11829 if (is_error_page(page))
11830 return false;
11831
11832 msr_bitmap_l1 = (unsigned long *)kmap(page);
11833 if (nested_cpu_has_apic_reg_virt(vmcs12)) {
11834 /*
11835 * L0 need not intercept reads for MSRs between 0x800 and 0x8ff, it
11836 * just lets the processor take the value from the virtual-APIC page;
11837 * take those 256 bits directly from the L1 bitmap.
11838 */
11839 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
11840 unsigned word = msr / BITS_PER_LONG;
11841 msr_bitmap_l0[word] = msr_bitmap_l1[word];
11842 msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
11843 }
11844 } else {
11845 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
11846 unsigned word = msr / BITS_PER_LONG;
11847 msr_bitmap_l0[word] = ~0;
11848 msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
11849 }
11850 }
11851
11852 nested_vmx_disable_intercept_for_msr(
11853 msr_bitmap_l1, msr_bitmap_l0,
11854 X2APIC_MSR(APIC_TASKPRI),
11855 MSR_TYPE_W);
11856
11857 if (nested_cpu_has_vid(vmcs12)) {
11858 nested_vmx_disable_intercept_for_msr(
11859 msr_bitmap_l1, msr_bitmap_l0,
11860 X2APIC_MSR(APIC_EOI),
11861 MSR_TYPE_W);
11862 nested_vmx_disable_intercept_for_msr(
11863 msr_bitmap_l1, msr_bitmap_l0,
11864 X2APIC_MSR(APIC_SELF_IPI),
11865 MSR_TYPE_W);
11866 }
11867
11868 if (spec_ctrl)
11869 nested_vmx_disable_intercept_for_msr(
11870 msr_bitmap_l1, msr_bitmap_l0,
11871 MSR_IA32_SPEC_CTRL,
11872 MSR_TYPE_R | MSR_TYPE_W);
11873
11874 if (pred_cmd)
11875 nested_vmx_disable_intercept_for_msr(
11876 msr_bitmap_l1, msr_bitmap_l0,
11877 MSR_IA32_PRED_CMD,
11878 MSR_TYPE_W);
11879
11880 kunmap(page);
11881 kvm_release_page_clean(page);
11882
11883 return true;
11884 }
11885
11886 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
11887 struct vmcs12 *vmcs12)
11888 {
11889 struct vmcs12 *shadow;
11890 struct page *page;
11891
11892 if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
11893 vmcs12->vmcs_link_pointer == -1ull)
11894 return;
11895
11896 shadow = get_shadow_vmcs12(vcpu);
11897 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
11898
11899 memcpy(shadow, kmap(page), VMCS12_SIZE);
11900
11901 kunmap(page);
11902 kvm_release_page_clean(page);
11903 }
11904
11905 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
11906 struct vmcs12 *vmcs12)
11907 {
11908 struct vcpu_vmx *vmx = to_vmx(vcpu);
11909
11910 if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
11911 vmcs12->vmcs_link_pointer == -1ull)
11912 return;
11913
11914 kvm_write_guest(vmx->vcpu.kvm, vmcs12->vmcs_link_pointer,
11915 get_shadow_vmcs12(vcpu), VMCS12_SIZE);
11916 }
11917
11918 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
11919 struct vmcs12 *vmcs12)
11920 {
11921 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
11922 !page_address_valid(vcpu, vmcs12->apic_access_addr))
11923 return -EINVAL;
11924 else
11925 return 0;
11926 }
11927
11928 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
11929 struct vmcs12 *vmcs12)
11930 {
11931 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11932 !nested_cpu_has_apic_reg_virt(vmcs12) &&
11933 !nested_cpu_has_vid(vmcs12) &&
11934 !nested_cpu_has_posted_intr(vmcs12))
11935 return 0;
11936
11937 /*
11938 * If virtualize x2apic mode is enabled,
11939 * virtualize apic access must be disabled.
11940 */
11941 if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11942 nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
11943 return -EINVAL;
11944
11945 /*
11946 * If virtual interrupt delivery is enabled,
11947 * we must exit on external interrupts.
11948 */
11949 if (nested_cpu_has_vid(vmcs12) &&
11950 !nested_exit_on_intr(vcpu))
11951 return -EINVAL;
11952
11953 /*
11954 * bits 15:8 should be zero in posted_intr_nv,
11955 * the descriptor address has been already checked
11956 * in nested_get_vmcs12_pages.
11957 *
11958 * bits 5:0 of posted_intr_desc_addr should be zero.
11959 */
11960 if (nested_cpu_has_posted_intr(vmcs12) &&
11961 (!nested_cpu_has_vid(vmcs12) ||
11962 !nested_exit_intr_ack_set(vcpu) ||
11963 (vmcs12->posted_intr_nv & 0xff00) ||
11964 (vmcs12->posted_intr_desc_addr & 0x3f) ||
11965 (vmcs12->posted_intr_desc_addr >> cpuid_maxphyaddr(vcpu))))
11966 return -EINVAL;
11967
11968 /* tpr shadow is needed by all apicv features. */
11969 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
11970 return -EINVAL;
11971
11972 return 0;
11973 }
11974
11975 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
11976 unsigned long count_field,
11977 unsigned long addr_field)
11978 {
11979 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11980 int maxphyaddr;
11981 u64 count, addr;
11982
11983 if (vmcs12_read_any(vmcs12, count_field, &count) ||
11984 vmcs12_read_any(vmcs12, addr_field, &addr)) {
11985 WARN_ON(1);
11986 return -EINVAL;
11987 }
11988 if (count == 0)
11989 return 0;
11990 maxphyaddr = cpuid_maxphyaddr(vcpu);
11991 if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
11992 (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
11993 pr_debug_ratelimited(
11994 "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
11995 addr_field, maxphyaddr, count, addr);
11996 return -EINVAL;
11997 }
11998 return 0;
11999 }
12000
12001 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
12002 struct vmcs12 *vmcs12)
12003 {
12004 if (vmcs12->vm_exit_msr_load_count == 0 &&
12005 vmcs12->vm_exit_msr_store_count == 0 &&
12006 vmcs12->vm_entry_msr_load_count == 0)
12007 return 0; /* Fast path */
12008 if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
12009 VM_EXIT_MSR_LOAD_ADDR) ||
12010 nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
12011 VM_EXIT_MSR_STORE_ADDR) ||
12012 nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
12013 VM_ENTRY_MSR_LOAD_ADDR))
12014 return -EINVAL;
12015 return 0;
12016 }
12017
12018 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
12019 struct vmcs12 *vmcs12)
12020 {
12021 if (!nested_cpu_has_pml(vmcs12))
12022 return 0;
12023
12024 if (!nested_cpu_has_ept(vmcs12) ||
12025 !page_address_valid(vcpu, vmcs12->pml_address))
12026 return -EINVAL;
12027
12028 return 0;
12029 }
12030
12031 static int nested_vmx_check_unrestricted_guest_controls(struct kvm_vcpu *vcpu,
12032 struct vmcs12 *vmcs12)
12033 {
12034 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST) &&
12035 !nested_cpu_has_ept(vmcs12))
12036 return -EINVAL;
12037 return 0;
12038 }
12039
12040 static int nested_vmx_check_mode_based_ept_exec_controls(struct kvm_vcpu *vcpu,
12041 struct vmcs12 *vmcs12)
12042 {
12043 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_MODE_BASED_EPT_EXEC) &&
12044 !nested_cpu_has_ept(vmcs12))
12045 return -EINVAL;
12046 return 0;
12047 }
12048
12049 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
12050 struct vmcs12 *vmcs12)
12051 {
12052 if (!nested_cpu_has_shadow_vmcs(vmcs12))
12053 return 0;
12054
12055 if (!page_address_valid(vcpu, vmcs12->vmread_bitmap) ||
12056 !page_address_valid(vcpu, vmcs12->vmwrite_bitmap))
12057 return -EINVAL;
12058
12059 return 0;
12060 }
12061
12062 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
12063 struct vmx_msr_entry *e)
12064 {
12065 /* x2APIC MSR accesses are not allowed */
12066 if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
12067 return -EINVAL;
12068 if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
12069 e->index == MSR_IA32_UCODE_REV)
12070 return -EINVAL;
12071 if (e->reserved != 0)
12072 return -EINVAL;
12073 return 0;
12074 }
12075
12076 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
12077 struct vmx_msr_entry *e)
12078 {
12079 if (e->index == MSR_FS_BASE ||
12080 e->index == MSR_GS_BASE ||
12081 e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
12082 nested_vmx_msr_check_common(vcpu, e))
12083 return -EINVAL;
12084 return 0;
12085 }
12086
12087 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
12088 struct vmx_msr_entry *e)
12089 {
12090 if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
12091 nested_vmx_msr_check_common(vcpu, e))
12092 return -EINVAL;
12093 return 0;
12094 }
12095
12096 /*
12097 * Load guest's/host's msr at nested entry/exit.
12098 * return 0 for success, entry index for failure.
12099 */
12100 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
12101 {
12102 u32 i;
12103 struct vmx_msr_entry e;
12104 struct msr_data msr;
12105
12106 msr.host_initiated = false;
12107 for (i = 0; i < count; i++) {
12108 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
12109 &e, sizeof(e))) {
12110 pr_debug_ratelimited(
12111 "%s cannot read MSR entry (%u, 0x%08llx)\n",
12112 __func__, i, gpa + i * sizeof(e));
12113 goto fail;
12114 }
12115 if (nested_vmx_load_msr_check(vcpu, &e)) {
12116 pr_debug_ratelimited(
12117 "%s check failed (%u, 0x%x, 0x%x)\n",
12118 __func__, i, e.index, e.reserved);
12119 goto fail;
12120 }
12121 msr.index = e.index;
12122 msr.data = e.value;
12123 if (kvm_set_msr(vcpu, &msr)) {
12124 pr_debug_ratelimited(
12125 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
12126 __func__, i, e.index, e.value);
12127 goto fail;
12128 }
12129 }
12130 return 0;
12131 fail:
12132 return i + 1;
12133 }
12134
12135 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
12136 {
12137 u32 i;
12138 struct vmx_msr_entry e;
12139
12140 for (i = 0; i < count; i++) {
12141 struct msr_data msr_info;
12142 if (kvm_vcpu_read_guest(vcpu,
12143 gpa + i * sizeof(e),
12144 &e, 2 * sizeof(u32))) {
12145 pr_debug_ratelimited(
12146 "%s cannot read MSR entry (%u, 0x%08llx)\n",
12147 __func__, i, gpa + i * sizeof(e));
12148 return -EINVAL;
12149 }
12150 if (nested_vmx_store_msr_check(vcpu, &e)) {
12151 pr_debug_ratelimited(
12152 "%s check failed (%u, 0x%x, 0x%x)\n",
12153 __func__, i, e.index, e.reserved);
12154 return -EINVAL;
12155 }
12156 msr_info.host_initiated = false;
12157 msr_info.index = e.index;
12158 if (kvm_get_msr(vcpu, &msr_info)) {
12159 pr_debug_ratelimited(
12160 "%s cannot read MSR (%u, 0x%x)\n",
12161 __func__, i, e.index);
12162 return -EINVAL;
12163 }
12164 if (kvm_vcpu_write_guest(vcpu,
12165 gpa + i * sizeof(e) +
12166 offsetof(struct vmx_msr_entry, value),
12167 &msr_info.data, sizeof(msr_info.data))) {
12168 pr_debug_ratelimited(
12169 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
12170 __func__, i, e.index, msr_info.data);
12171 return -EINVAL;
12172 }
12173 }
12174 return 0;
12175 }
12176
12177 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
12178 {
12179 unsigned long invalid_mask;
12180
12181 invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
12182 return (val & invalid_mask) == 0;
12183 }
12184
12185 /*
12186 * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
12187 * emulating VM entry into a guest with EPT enabled.
12188 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12189 * is assigned to entry_failure_code on failure.
12190 */
12191 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
12192 u32 *entry_failure_code)
12193 {
12194 if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
12195 if (!nested_cr3_valid(vcpu, cr3)) {
12196 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12197 return 1;
12198 }
12199
12200 /*
12201 * If PAE paging and EPT are both on, CR3 is not used by the CPU and
12202 * must not be dereferenced.
12203 */
12204 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
12205 !nested_ept) {
12206 if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
12207 *entry_failure_code = ENTRY_FAIL_PDPTE;
12208 return 1;
12209 }
12210 }
12211 }
12212
12213 if (!nested_ept)
12214 kvm_mmu_new_cr3(vcpu, cr3, false);
12215
12216 vcpu->arch.cr3 = cr3;
12217 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
12218
12219 kvm_init_mmu(vcpu, false);
12220
12221 return 0;
12222 }
12223
12224 /*
12225 * Returns if KVM is able to config CPU to tag TLB entries
12226 * populated by L2 differently than TLB entries populated
12227 * by L1.
12228 *
12229 * If L1 uses EPT, then TLB entries are tagged with different EPTP.
12230 *
12231 * If L1 uses VPID and we allocated a vpid02, TLB entries are tagged
12232 * with different VPID (L1 entries are tagged with vmx->vpid
12233 * while L2 entries are tagged with vmx->nested.vpid02).
12234 */
12235 static bool nested_has_guest_tlb_tag(struct kvm_vcpu *vcpu)
12236 {
12237 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12238
12239 return nested_cpu_has_ept(vmcs12) ||
12240 (nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02);
12241 }
12242
12243 static u64 nested_vmx_calc_efer(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12244 {
12245 if (vmx->nested.nested_run_pending &&
12246 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
12247 return vmcs12->guest_ia32_efer;
12248 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
12249 return vmx->vcpu.arch.efer | (EFER_LMA | EFER_LME);
12250 else
12251 return vmx->vcpu.arch.efer & ~(EFER_LMA | EFER_LME);
12252 }
12253
12254 static void prepare_vmcs02_constant_state(struct vcpu_vmx *vmx)
12255 {
12256 /*
12257 * If vmcs02 hasn't been initialized, set the constant vmcs02 state
12258 * according to L0's settings (vmcs12 is irrelevant here). Host
12259 * fields that come from L0 and are not constant, e.g. HOST_CR3,
12260 * will be set as needed prior to VMLAUNCH/VMRESUME.
12261 */
12262 if (vmx->nested.vmcs02_initialized)
12263 return;
12264 vmx->nested.vmcs02_initialized = true;
12265
12266 /*
12267 * We don't care what the EPTP value is we just need to guarantee
12268 * it's valid so we don't get a false positive when doing early
12269 * consistency checks.
12270 */
12271 if (enable_ept && nested_early_check)
12272 vmcs_write64(EPT_POINTER, construct_eptp(&vmx->vcpu, 0));
12273
12274 /* All VMFUNCs are currently emulated through L0 vmexits. */
12275 if (cpu_has_vmx_vmfunc())
12276 vmcs_write64(VM_FUNCTION_CONTROL, 0);
12277
12278 if (cpu_has_vmx_posted_intr())
12279 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
12280
12281 if (cpu_has_vmx_msr_bitmap())
12282 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
12283
12284 if (enable_pml)
12285 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
12286
12287 /*
12288 * Set the MSR load/store lists to match L0's settings. Only the
12289 * addresses are constant (for vmcs02), the counts can change based
12290 * on L2's behavior, e.g. switching to/from long mode.
12291 */
12292 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
12293 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
12294 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
12295
12296 vmx_set_constant_host_state(vmx);
12297 }
12298
12299 static void prepare_vmcs02_early_full(struct vcpu_vmx *vmx,
12300 struct vmcs12 *vmcs12)
12301 {
12302 prepare_vmcs02_constant_state(vmx);
12303
12304 vmcs_write64(VMCS_LINK_POINTER, -1ull);
12305
12306 if (enable_vpid) {
12307 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
12308 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
12309 else
12310 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
12311 }
12312 }
12313
12314 static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12315 {
12316 u32 exec_control, vmcs12_exec_ctrl;
12317 u64 guest_efer = nested_vmx_calc_efer(vmx, vmcs12);
12318
12319 if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs)
12320 prepare_vmcs02_early_full(vmx, vmcs12);
12321
12322 /*
12323 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
12324 * entry, but only if the current (host) sp changed from the value
12325 * we wrote last (vmx->host_rsp). This cache is no longer relevant
12326 * if we switch vmcs, and rather than hold a separate cache per vmcs,
12327 * here we just force the write to happen on entry. host_rsp will
12328 * also be written unconditionally by nested_vmx_check_vmentry_hw()
12329 * if we are doing early consistency checks via hardware.
12330 */
12331 vmx->host_rsp = 0;
12332
12333 /*
12334 * PIN CONTROLS
12335 */
12336 exec_control = vmcs12->pin_based_vm_exec_control;
12337
12338 /* Preemption timer setting is computed directly in vmx_vcpu_run. */
12339 exec_control |= vmcs_config.pin_based_exec_ctrl;
12340 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
12341 vmx->loaded_vmcs->hv_timer_armed = false;
12342
12343 /* Posted interrupts setting is only taken from vmcs12. */
12344 if (nested_cpu_has_posted_intr(vmcs12)) {
12345 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
12346 vmx->nested.pi_pending = false;
12347 } else {
12348 exec_control &= ~PIN_BASED_POSTED_INTR;
12349 }
12350 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
12351
12352 /*
12353 * EXEC CONTROLS
12354 */
12355 exec_control = vmx_exec_control(vmx); /* L0's desires */
12356 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
12357 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
12358 exec_control &= ~CPU_BASED_TPR_SHADOW;
12359 exec_control |= vmcs12->cpu_based_vm_exec_control;
12360
12361 /*
12362 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
12363 * nested_get_vmcs12_pages can't fix it up, the illegal value
12364 * will result in a VM entry failure.
12365 */
12366 if (exec_control & CPU_BASED_TPR_SHADOW) {
12367 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
12368 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
12369 } else {
12370 #ifdef CONFIG_X86_64
12371 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
12372 CPU_BASED_CR8_STORE_EXITING;
12373 #endif
12374 }
12375
12376 /*
12377 * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
12378 * for I/O port accesses.
12379 */
12380 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
12381 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
12382 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
12383
12384 /*
12385 * SECONDARY EXEC CONTROLS
12386 */
12387 if (cpu_has_secondary_exec_ctrls()) {
12388 exec_control = vmx->secondary_exec_control;
12389
12390 /* Take the following fields only from vmcs12 */
12391 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
12392 SECONDARY_EXEC_ENABLE_INVPCID |
12393 SECONDARY_EXEC_RDTSCP |
12394 SECONDARY_EXEC_XSAVES |
12395 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
12396 SECONDARY_EXEC_APIC_REGISTER_VIRT |
12397 SECONDARY_EXEC_ENABLE_VMFUNC);
12398 if (nested_cpu_has(vmcs12,
12399 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
12400 vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
12401 ~SECONDARY_EXEC_ENABLE_PML;
12402 exec_control |= vmcs12_exec_ctrl;
12403 }
12404
12405 /* VMCS shadowing for L2 is emulated for now */
12406 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
12407
12408 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
12409 vmcs_write16(GUEST_INTR_STATUS,
12410 vmcs12->guest_intr_status);
12411
12412 /*
12413 * Write an illegal value to APIC_ACCESS_ADDR. Later,
12414 * nested_get_vmcs12_pages will either fix it up or
12415 * remove the VM execution control.
12416 */
12417 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
12418 vmcs_write64(APIC_ACCESS_ADDR, -1ull);
12419
12420 if (exec_control & SECONDARY_EXEC_ENCLS_EXITING)
12421 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
12422
12423 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
12424 }
12425
12426 /*
12427 * ENTRY CONTROLS
12428 *
12429 * vmcs12's VM_{ENTRY,EXIT}_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE
12430 * are emulated by vmx_set_efer() in prepare_vmcs02(), but speculate
12431 * on the related bits (if supported by the CPU) in the hope that
12432 * we can avoid VMWrites during vmx_set_efer().
12433 */
12434 exec_control = (vmcs12->vm_entry_controls | vmx_vmentry_ctrl()) &
12435 ~VM_ENTRY_IA32E_MODE & ~VM_ENTRY_LOAD_IA32_EFER;
12436 if (cpu_has_load_ia32_efer()) {
12437 if (guest_efer & EFER_LMA)
12438 exec_control |= VM_ENTRY_IA32E_MODE;
12439 if (guest_efer != host_efer)
12440 exec_control |= VM_ENTRY_LOAD_IA32_EFER;
12441 }
12442 vm_entry_controls_init(vmx, exec_control);
12443
12444 /*
12445 * EXIT CONTROLS
12446 *
12447 * L2->L1 exit controls are emulated - the hardware exit is to L0 so
12448 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
12449 * bits may be modified by vmx_set_efer() in prepare_vmcs02().
12450 */
12451 exec_control = vmx_vmexit_ctrl();
12452 if (cpu_has_load_ia32_efer() && guest_efer != host_efer)
12453 exec_control |= VM_EXIT_LOAD_IA32_EFER;
12454 vm_exit_controls_init(vmx, exec_control);
12455
12456 /*
12457 * Conceptually we want to copy the PML address and index from
12458 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
12459 * since we always flush the log on each vmexit and never change
12460 * the PML address (once set), this happens to be equivalent to
12461 * simply resetting the index in vmcs02.
12462 */
12463 if (enable_pml)
12464 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
12465
12466 /*
12467 * Interrupt/Exception Fields
12468 */
12469 if (vmx->nested.nested_run_pending) {
12470 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
12471 vmcs12->vm_entry_intr_info_field);
12472 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
12473 vmcs12->vm_entry_exception_error_code);
12474 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
12475 vmcs12->vm_entry_instruction_len);
12476 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
12477 vmcs12->guest_interruptibility_info);
12478 vmx->loaded_vmcs->nmi_known_unmasked =
12479 !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
12480 } else {
12481 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
12482 }
12483 }
12484
12485 static void prepare_vmcs02_full(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12486 {
12487 struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
12488
12489 if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12490 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
12491 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
12492 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
12493 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
12494 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
12495 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
12496 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
12497 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
12498 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
12499 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
12500 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
12501 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
12502 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
12503 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
12504 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
12505 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
12506 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
12507 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
12508 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
12509 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
12510 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
12511 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
12512 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
12513 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
12514 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
12515 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
12516 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
12517 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
12518 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
12519 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
12520 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
12521 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
12522 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
12523 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
12524 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
12525 }
12526
12527 if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12528 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1)) {
12529 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
12530 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
12531 vmcs12->guest_pending_dbg_exceptions);
12532 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
12533 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
12534
12535 /*
12536 * L1 may access the L2's PDPTR, so save them to construct
12537 * vmcs12
12538 */
12539 if (enable_ept) {
12540 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
12541 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
12542 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
12543 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
12544 }
12545 }
12546
12547 if (nested_cpu_has_xsaves(vmcs12))
12548 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
12549
12550 /*
12551 * Whether page-faults are trapped is determined by a combination of
12552 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
12553 * If enable_ept, L0 doesn't care about page faults and we should
12554 * set all of these to L1's desires. However, if !enable_ept, L0 does
12555 * care about (at least some) page faults, and because it is not easy
12556 * (if at all possible?) to merge L0 and L1's desires, we simply ask
12557 * to exit on each and every L2 page fault. This is done by setting
12558 * MASK=MATCH=0 and (see below) EB.PF=1.
12559 * Note that below we don't need special code to set EB.PF beyond the
12560 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
12561 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
12562 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
12563 */
12564 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
12565 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
12566 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
12567 enable_ept ? vmcs12->page_fault_error_code_match : 0);
12568
12569 if (cpu_has_vmx_apicv()) {
12570 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
12571 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
12572 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
12573 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
12574 }
12575
12576 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
12577 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
12578
12579 set_cr4_guest_host_mask(vmx);
12580
12581 if (kvm_mpx_supported()) {
12582 if (vmx->nested.nested_run_pending &&
12583 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12584 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
12585 else
12586 vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
12587 }
12588 }
12589
12590 /*
12591 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
12592 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
12593 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
12594 * guest in a way that will both be appropriate to L1's requests, and our
12595 * needs. In addition to modifying the active vmcs (which is vmcs02), this
12596 * function also has additional necessary side-effects, like setting various
12597 * vcpu->arch fields.
12598 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12599 * is assigned to entry_failure_code on failure.
12600 */
12601 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12602 u32 *entry_failure_code)
12603 {
12604 struct vcpu_vmx *vmx = to_vmx(vcpu);
12605 struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
12606
12607 if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs) {
12608 prepare_vmcs02_full(vmx, vmcs12);
12609 vmx->nested.dirty_vmcs12 = false;
12610 }
12611
12612 /*
12613 * First, the fields that are shadowed. This must be kept in sync
12614 * with vmcs_shadow_fields.h.
12615 */
12616 if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12617 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
12618 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
12619 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
12620 }
12621
12622 if (vmx->nested.nested_run_pending &&
12623 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
12624 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
12625 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
12626 } else {
12627 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
12628 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
12629 }
12630 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
12631
12632 vmx->nested.preemption_timer_expired = false;
12633 if (nested_cpu_has_preemption_timer(vmcs12))
12634 vmx_start_preemption_timer(vcpu);
12635
12636 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
12637 * bitwise-or of what L1 wants to trap for L2, and what we want to
12638 * trap. Note that CR0.TS also needs updating - we do this later.
12639 */
12640 update_exception_bitmap(vcpu);
12641 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
12642 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
12643
12644 if (vmx->nested.nested_run_pending &&
12645 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
12646 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
12647 vcpu->arch.pat = vmcs12->guest_ia32_pat;
12648 } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
12649 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
12650 }
12651
12652 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
12653
12654 if (kvm_has_tsc_control)
12655 decache_tsc_multiplier(vmx);
12656
12657 if (enable_vpid) {
12658 /*
12659 * There is no direct mapping between vpid02 and vpid12, the
12660 * vpid02 is per-vCPU for L0 and reused while the value of
12661 * vpid12 is changed w/ one invvpid during nested vmentry.
12662 * The vpid12 is allocated by L1 for L2, so it will not
12663 * influence global bitmap(for vpid01 and vpid02 allocation)
12664 * even if spawn a lot of nested vCPUs.
12665 */
12666 if (nested_cpu_has_vpid(vmcs12) && nested_has_guest_tlb_tag(vcpu)) {
12667 if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
12668 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
12669 __vmx_flush_tlb(vcpu, nested_get_vpid02(vcpu), false);
12670 }
12671 } else {
12672 /*
12673 * If L1 use EPT, then L0 needs to execute INVEPT on
12674 * EPTP02 instead of EPTP01. Therefore, delay TLB
12675 * flush until vmcs02->eptp is fully updated by
12676 * KVM_REQ_LOAD_CR3. Note that this assumes
12677 * KVM_REQ_TLB_FLUSH is evaluated after
12678 * KVM_REQ_LOAD_CR3 in vcpu_enter_guest().
12679 */
12680 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
12681 }
12682 }
12683
12684 if (nested_cpu_has_ept(vmcs12))
12685 nested_ept_init_mmu_context(vcpu);
12686 else if (nested_cpu_has2(vmcs12,
12687 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
12688 vmx_flush_tlb(vcpu, true);
12689
12690 /*
12691 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
12692 * bits which we consider mandatory enabled.
12693 * The CR0_READ_SHADOW is what L2 should have expected to read given
12694 * the specifications by L1; It's not enough to take
12695 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
12696 * have more bits than L1 expected.
12697 */
12698 vmx_set_cr0(vcpu, vmcs12->guest_cr0);
12699 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
12700
12701 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
12702 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
12703
12704 vcpu->arch.efer = nested_vmx_calc_efer(vmx, vmcs12);
12705 /* Note: may modify VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
12706 vmx_set_efer(vcpu, vcpu->arch.efer);
12707
12708 /*
12709 * Guest state is invalid and unrestricted guest is disabled,
12710 * which means L1 attempted VMEntry to L2 with invalid state.
12711 * Fail the VMEntry.
12712 */
12713 if (vmx->emulation_required) {
12714 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12715 return 1;
12716 }
12717
12718 /* Shadow page tables on either EPT or shadow page tables. */
12719 if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
12720 entry_failure_code))
12721 return 1;
12722
12723 if (!enable_ept)
12724 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
12725
12726 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
12727 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
12728 return 0;
12729 }
12730
12731 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
12732 {
12733 if (!nested_cpu_has_nmi_exiting(vmcs12) &&
12734 nested_cpu_has_virtual_nmis(vmcs12))
12735 return -EINVAL;
12736
12737 if (!nested_cpu_has_virtual_nmis(vmcs12) &&
12738 nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING))
12739 return -EINVAL;
12740
12741 return 0;
12742 }
12743
12744 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12745 {
12746 struct vcpu_vmx *vmx = to_vmx(vcpu);
12747 bool ia32e;
12748
12749 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
12750 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
12751 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12752
12753 if (nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id)
12754 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12755
12756 if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
12757 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12758
12759 if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
12760 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12761
12762 if (nested_vmx_check_apic_access_controls(vcpu, vmcs12))
12763 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12764
12765 if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
12766 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12767
12768 if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
12769 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12770
12771 if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
12772 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12773
12774 if (!nested_cpu_has_preemption_timer(vmcs12) &&
12775 nested_cpu_has_save_preemption_timer(vmcs12))
12776 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12777
12778 if (nested_vmx_check_pml_controls(vcpu, vmcs12))
12779 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12780
12781 if (nested_vmx_check_unrestricted_guest_controls(vcpu, vmcs12))
12782 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12783
12784 if (nested_vmx_check_mode_based_ept_exec_controls(vcpu, vmcs12))
12785 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12786
12787 if (nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12))
12788 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12789
12790 if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
12791 vmx->nested.msrs.procbased_ctls_low,
12792 vmx->nested.msrs.procbased_ctls_high) ||
12793 (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
12794 !vmx_control_verify(vmcs12->secondary_vm_exec_control,
12795 vmx->nested.msrs.secondary_ctls_low,
12796 vmx->nested.msrs.secondary_ctls_high)) ||
12797 !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
12798 vmx->nested.msrs.pinbased_ctls_low,
12799 vmx->nested.msrs.pinbased_ctls_high) ||
12800 !vmx_control_verify(vmcs12->vm_exit_controls,
12801 vmx->nested.msrs.exit_ctls_low,
12802 vmx->nested.msrs.exit_ctls_high) ||
12803 !vmx_control_verify(vmcs12->vm_entry_controls,
12804 vmx->nested.msrs.entry_ctls_low,
12805 vmx->nested.msrs.entry_ctls_high))
12806 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12807
12808 if (nested_vmx_check_nmi_controls(vmcs12))
12809 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12810
12811 if (nested_cpu_has_vmfunc(vmcs12)) {
12812 if (vmcs12->vm_function_control &
12813 ~vmx->nested.msrs.vmfunc_controls)
12814 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12815
12816 if (nested_cpu_has_eptp_switching(vmcs12)) {
12817 if (!nested_cpu_has_ept(vmcs12) ||
12818 !page_address_valid(vcpu, vmcs12->eptp_list_address))
12819 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12820 }
12821 }
12822
12823 if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
12824 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12825
12826 if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
12827 !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
12828 !nested_cr3_valid(vcpu, vmcs12->host_cr3))
12829 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
12830
12831 /*
12832 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
12833 * IA32_EFER MSR must be 0 in the field for that register. In addition,
12834 * the values of the LMA and LME bits in the field must each be that of
12835 * the host address-space size VM-exit control.
12836 */
12837 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
12838 ia32e = (vmcs12->vm_exit_controls &
12839 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
12840 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
12841 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
12842 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
12843 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
12844 }
12845
12846 /*
12847 * From the Intel SDM, volume 3:
12848 * Fields relevant to VM-entry event injection must be set properly.
12849 * These fields are the VM-entry interruption-information field, the
12850 * VM-entry exception error code, and the VM-entry instruction length.
12851 */
12852 if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
12853 u32 intr_info = vmcs12->vm_entry_intr_info_field;
12854 u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
12855 u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
12856 bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
12857 bool should_have_error_code;
12858 bool urg = nested_cpu_has2(vmcs12,
12859 SECONDARY_EXEC_UNRESTRICTED_GUEST);
12860 bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
12861
12862 /* VM-entry interruption-info field: interruption type */
12863 if (intr_type == INTR_TYPE_RESERVED ||
12864 (intr_type == INTR_TYPE_OTHER_EVENT &&
12865 !nested_cpu_supports_monitor_trap_flag(vcpu)))
12866 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12867
12868 /* VM-entry interruption-info field: vector */
12869 if ((intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
12870 (intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
12871 (intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
12872 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12873
12874 /* VM-entry interruption-info field: deliver error code */
12875 should_have_error_code =
12876 intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
12877 x86_exception_has_error_code(vector);
12878 if (has_error_code != should_have_error_code)
12879 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12880
12881 /* VM-entry exception error code */
12882 if (has_error_code &&
12883 vmcs12->vm_entry_exception_error_code & GENMASK(31, 15))
12884 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12885
12886 /* VM-entry interruption-info field: reserved bits */
12887 if (intr_info & INTR_INFO_RESVD_BITS_MASK)
12888 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12889
12890 /* VM-entry instruction length */
12891 switch (intr_type) {
12892 case INTR_TYPE_SOFT_EXCEPTION:
12893 case INTR_TYPE_SOFT_INTR:
12894 case INTR_TYPE_PRIV_SW_EXCEPTION:
12895 if ((vmcs12->vm_entry_instruction_len > 15) ||
12896 (vmcs12->vm_entry_instruction_len == 0 &&
12897 !nested_cpu_has_zero_length_injection(vcpu)))
12898 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12899 }
12900 }
12901
12902 if (nested_cpu_has_ept(vmcs12) &&
12903 !valid_ept_address(vcpu, vmcs12->ept_pointer))
12904 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12905
12906 return 0;
12907 }
12908
12909 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
12910 struct vmcs12 *vmcs12)
12911 {
12912 int r;
12913 struct page *page;
12914 struct vmcs12 *shadow;
12915
12916 if (vmcs12->vmcs_link_pointer == -1ull)
12917 return 0;
12918
12919 if (!page_address_valid(vcpu, vmcs12->vmcs_link_pointer))
12920 return -EINVAL;
12921
12922 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
12923 if (is_error_page(page))
12924 return -EINVAL;
12925
12926 r = 0;
12927 shadow = kmap(page);
12928 if (shadow->hdr.revision_id != VMCS12_REVISION ||
12929 shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12))
12930 r = -EINVAL;
12931 kunmap(page);
12932 kvm_release_page_clean(page);
12933 return r;
12934 }
12935
12936 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12937 u32 *exit_qual)
12938 {
12939 bool ia32e;
12940
12941 *exit_qual = ENTRY_FAIL_DEFAULT;
12942
12943 if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
12944 !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
12945 return 1;
12946
12947 if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
12948 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
12949 return 1;
12950 }
12951
12952 /*
12953 * If the load IA32_EFER VM-entry control is 1, the following checks
12954 * are performed on the field for the IA32_EFER MSR:
12955 * - Bits reserved in the IA32_EFER MSR must be 0.
12956 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
12957 * the IA-32e mode guest VM-exit control. It must also be identical
12958 * to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
12959 * CR0.PG) is 1.
12960 */
12961 if (to_vmx(vcpu)->nested.nested_run_pending &&
12962 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
12963 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
12964 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
12965 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
12966 ((vmcs12->guest_cr0 & X86_CR0_PG) &&
12967 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
12968 return 1;
12969 }
12970
12971 if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
12972 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
12973 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
12974 return 1;
12975
12976 return 0;
12977 }
12978
12979 static int __noclone nested_vmx_check_vmentry_hw(struct kvm_vcpu *vcpu)
12980 {
12981 struct vcpu_vmx *vmx = to_vmx(vcpu);
12982 unsigned long cr3, cr4;
12983
12984 if (!nested_early_check)
12985 return 0;
12986
12987 if (vmx->msr_autoload.host.nr)
12988 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
12989 if (vmx->msr_autoload.guest.nr)
12990 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
12991
12992 preempt_disable();
12993
12994 vmx_prepare_switch_to_guest(vcpu);
12995
12996 /*
12997 * Induce a consistency check VMExit by clearing bit 1 in GUEST_RFLAGS,
12998 * which is reserved to '1' by hardware. GUEST_RFLAGS is guaranteed to
12999 * be written (by preparve_vmcs02()) before the "real" VMEnter, i.e.
13000 * there is no need to preserve other bits or save/restore the field.
13001 */
13002 vmcs_writel(GUEST_RFLAGS, 0);
13003
13004 vmcs_writel(HOST_RIP, vmx_early_consistency_check_return);
13005
13006 cr3 = __get_current_cr3_fast();
13007 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
13008 vmcs_writel(HOST_CR3, cr3);
13009 vmx->loaded_vmcs->host_state.cr3 = cr3;
13010 }
13011
13012 cr4 = cr4_read_shadow();
13013 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
13014 vmcs_writel(HOST_CR4, cr4);
13015 vmx->loaded_vmcs->host_state.cr4 = cr4;
13016 }
13017
13018 vmx->__launched = vmx->loaded_vmcs->launched;
13019
13020 asm(
13021 /* Set HOST_RSP */
13022 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
13023 "mov %%" _ASM_SP ", %c[host_rsp](%0)\n\t"
13024
13025 /* Check if vmlaunch or vmresume is needed */
13026 "cmpl $0, %c[launched](%0)\n\t"
13027 "jne 1f\n\t"
13028 __ex("vmlaunch") "\n\t"
13029 "jmp 2f\n\t"
13030 "1: " __ex("vmresume") "\n\t"
13031 "2: "
13032 /* Set vmx->fail accordingly */
13033 "setbe %c[fail](%0)\n\t"
13034
13035 ".pushsection .rodata\n\t"
13036 ".global vmx_early_consistency_check_return\n\t"
13037 "vmx_early_consistency_check_return: " _ASM_PTR " 2b\n\t"
13038 ".popsection"
13039 :
13040 : "c"(vmx), "d"((unsigned long)HOST_RSP),
13041 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
13042 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
13043 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp))
13044 : "rax", "cc", "memory"
13045 );
13046
13047 vmcs_writel(HOST_RIP, vmx_return);
13048
13049 preempt_enable();
13050
13051 if (vmx->msr_autoload.host.nr)
13052 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
13053 if (vmx->msr_autoload.guest.nr)
13054 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
13055
13056 if (vmx->fail) {
13057 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
13058 VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13059 vmx->fail = 0;
13060 return 1;
13061 }
13062
13063 /*
13064 * VMExit clears RFLAGS.IF and DR7, even on a consistency check.
13065 */
13066 local_irq_enable();
13067 if (hw_breakpoint_active())
13068 set_debugreg(__this_cpu_read(cpu_dr7), 7);
13069
13070 /*
13071 * A non-failing VMEntry means we somehow entered guest mode with
13072 * an illegal RIP, and that's just the tip of the iceberg. There
13073 * is no telling what memory has been modified or what state has
13074 * been exposed to unknown code. Hitting this all but guarantees
13075 * a (very critical) hardware issue.
13076 */
13077 WARN_ON(!(vmcs_read32(VM_EXIT_REASON) &
13078 VMX_EXIT_REASONS_FAILED_VMENTRY));
13079
13080 return 0;
13081 }
13082 STACK_FRAME_NON_STANDARD(nested_vmx_check_vmentry_hw);
13083
13084 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13085 struct vmcs12 *vmcs12);
13086
13087 /*
13088 * If from_vmentry is false, this is being called from state restore (either RSM
13089 * or KVM_SET_NESTED_STATE). Otherwise it's called from vmlaunch/vmresume.
13090 + *
13091 + * Returns:
13092 + * 0 - success, i.e. proceed with actual VMEnter
13093 + * 1 - consistency check VMExit
13094 + * -1 - consistency check VMFail
13095 */
13096 static int nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,
13097 bool from_vmentry)
13098 {
13099 struct vcpu_vmx *vmx = to_vmx(vcpu);
13100 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13101 bool evaluate_pending_interrupts;
13102 u32 exit_reason = EXIT_REASON_INVALID_STATE;
13103 u32 exit_qual;
13104
13105 evaluate_pending_interrupts = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
13106 (CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_VIRTUAL_NMI_PENDING);
13107 if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
13108 evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
13109
13110 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
13111 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13112 if (kvm_mpx_supported() &&
13113 !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
13114 vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13115
13116 vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
13117
13118 prepare_vmcs02_early(vmx, vmcs12);
13119
13120 if (from_vmentry) {
13121 nested_get_vmcs12_pages(vcpu);
13122
13123 if (nested_vmx_check_vmentry_hw(vcpu)) {
13124 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13125 return -1;
13126 }
13127
13128 if (check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
13129 goto vmentry_fail_vmexit;
13130 }
13131
13132 enter_guest_mode(vcpu);
13133 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13134 vcpu->arch.tsc_offset += vmcs12->tsc_offset;
13135
13136 if (prepare_vmcs02(vcpu, vmcs12, &exit_qual))
13137 goto vmentry_fail_vmexit_guest_mode;
13138
13139 if (from_vmentry) {
13140 exit_reason = EXIT_REASON_MSR_LOAD_FAIL;
13141 exit_qual = nested_vmx_load_msr(vcpu,
13142 vmcs12->vm_entry_msr_load_addr,
13143 vmcs12->vm_entry_msr_load_count);
13144 if (exit_qual)
13145 goto vmentry_fail_vmexit_guest_mode;
13146 } else {
13147 /*
13148 * The MMU is not initialized to point at the right entities yet and
13149 * "get pages" would need to read data from the guest (i.e. we will
13150 * need to perform gpa to hpa translation). Request a call
13151 * to nested_get_vmcs12_pages before the next VM-entry. The MSRs
13152 * have already been set at vmentry time and should not be reset.
13153 */
13154 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
13155 }
13156
13157 /*
13158 * If L1 had a pending IRQ/NMI until it executed
13159 * VMLAUNCH/VMRESUME which wasn't delivered because it was
13160 * disallowed (e.g. interrupts disabled), L0 needs to
13161 * evaluate if this pending event should cause an exit from L2
13162 * to L1 or delivered directly to L2 (e.g. In case L1 don't
13163 * intercept EXTERNAL_INTERRUPT).
13164 *
13165 * Usually this would be handled by the processor noticing an
13166 * IRQ/NMI window request, or checking RVI during evaluation of
13167 * pending virtual interrupts. However, this setting was done
13168 * on VMCS01 and now VMCS02 is active instead. Thus, we force L0
13169 * to perform pending event evaluation by requesting a KVM_REQ_EVENT.
13170 */
13171 if (unlikely(evaluate_pending_interrupts))
13172 kvm_make_request(KVM_REQ_EVENT, vcpu);
13173
13174 /*
13175 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
13176 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
13177 * returned as far as L1 is concerned. It will only return (and set
13178 * the success flag) when L2 exits (see nested_vmx_vmexit()).
13179 */
13180 return 0;
13181
13182 /*
13183 * A failed consistency check that leads to a VMExit during L1's
13184 * VMEnter to L2 is a variation of a normal VMexit, as explained in
13185 * 26.7 "VM-entry failures during or after loading guest state".
13186 */
13187 vmentry_fail_vmexit_guest_mode:
13188 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13189 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
13190 leave_guest_mode(vcpu);
13191
13192 vmentry_fail_vmexit:
13193 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13194
13195 if (!from_vmentry)
13196 return 1;
13197
13198 load_vmcs12_host_state(vcpu, vmcs12);
13199 vmcs12->vm_exit_reason = exit_reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
13200 vmcs12->exit_qualification = exit_qual;
13201 if (enable_shadow_vmcs || vmx->nested.hv_evmcs)
13202 vmx->nested.need_vmcs12_sync = true;
13203 return 1;
13204 }
13205
13206 /*
13207 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
13208 * for running an L2 nested guest.
13209 */
13210 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
13211 {
13212 struct vmcs12 *vmcs12;
13213 struct vcpu_vmx *vmx = to_vmx(vcpu);
13214 u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
13215 int ret;
13216
13217 if (!nested_vmx_check_permission(vcpu))
13218 return 1;
13219
13220 if (!nested_vmx_handle_enlightened_vmptrld(vcpu, true))
13221 return 1;
13222
13223 if (!vmx->nested.hv_evmcs && vmx->nested.current_vmptr == -1ull)
13224 return nested_vmx_failInvalid(vcpu);
13225
13226 vmcs12 = get_vmcs12(vcpu);
13227
13228 /*
13229 * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
13230 * that there *is* a valid VMCS pointer, RFLAGS.CF is set
13231 * rather than RFLAGS.ZF, and no error number is stored to the
13232 * VM-instruction error field.
13233 */
13234 if (vmcs12->hdr.shadow_vmcs)
13235 return nested_vmx_failInvalid(vcpu);
13236
13237 if (vmx->nested.hv_evmcs) {
13238 copy_enlightened_to_vmcs12(vmx);
13239 /* Enlightened VMCS doesn't have launch state */
13240 vmcs12->launch_state = !launch;
13241 } else if (enable_shadow_vmcs) {
13242 copy_shadow_to_vmcs12(vmx);
13243 }
13244
13245 /*
13246 * The nested entry process starts with enforcing various prerequisites
13247 * on vmcs12 as required by the Intel SDM, and act appropriately when
13248 * they fail: As the SDM explains, some conditions should cause the
13249 * instruction to fail, while others will cause the instruction to seem
13250 * to succeed, but return an EXIT_REASON_INVALID_STATE.
13251 * To speed up the normal (success) code path, we should avoid checking
13252 * for misconfigurations which will anyway be caught by the processor
13253 * when using the merged vmcs02.
13254 */
13255 if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS)
13256 return nested_vmx_failValid(vcpu,
13257 VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
13258
13259 if (vmcs12->launch_state == launch)
13260 return nested_vmx_failValid(vcpu,
13261 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
13262 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
13263
13264 ret = check_vmentry_prereqs(vcpu, vmcs12);
13265 if (ret)
13266 return nested_vmx_failValid(vcpu, ret);
13267
13268 /*
13269 * We're finally done with prerequisite checking, and can start with
13270 * the nested entry.
13271 */
13272 vmx->nested.nested_run_pending = 1;
13273 ret = nested_vmx_enter_non_root_mode(vcpu, true);
13274 vmx->nested.nested_run_pending = !ret;
13275 if (ret > 0)
13276 return 1;
13277 else if (ret)
13278 return nested_vmx_failValid(vcpu,
13279 VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13280
13281 /* Hide L1D cache contents from the nested guest. */
13282 vmx->vcpu.arch.l1tf_flush_l1d = true;
13283
13284 /*
13285 * Must happen outside of nested_vmx_enter_non_root_mode() as it will
13286 * also be used as part of restoring nVMX state for
13287 * snapshot restore (migration).
13288 *
13289 * In this flow, it is assumed that vmcs12 cache was
13290 * trasferred as part of captured nVMX state and should
13291 * therefore not be read from guest memory (which may not
13292 * exist on destination host yet).
13293 */
13294 nested_cache_shadow_vmcs12(vcpu, vmcs12);
13295
13296 /*
13297 * If we're entering a halted L2 vcpu and the L2 vcpu won't be woken
13298 * by event injection, halt vcpu.
13299 */
13300 if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
13301 !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK)) {
13302 vmx->nested.nested_run_pending = 0;
13303 return kvm_vcpu_halt(vcpu);
13304 }
13305 return 1;
13306 }
13307
13308 /*
13309 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
13310 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
13311 * This function returns the new value we should put in vmcs12.guest_cr0.
13312 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
13313 * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
13314 * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
13315 * didn't trap the bit, because if L1 did, so would L0).
13316 * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
13317 * been modified by L2, and L1 knows it. So just leave the old value of
13318 * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
13319 * isn't relevant, because if L0 traps this bit it can set it to anything.
13320 * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
13321 * changed these bits, and therefore they need to be updated, but L0
13322 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather
13323 * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
13324 */
13325 static inline unsigned long
13326 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13327 {
13328 return
13329 /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
13330 /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
13331 /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
13332 vcpu->arch.cr0_guest_owned_bits));
13333 }
13334
13335 static inline unsigned long
13336 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13337 {
13338 return
13339 /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
13340 /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
13341 /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
13342 vcpu->arch.cr4_guest_owned_bits));
13343 }
13344
13345 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
13346 struct vmcs12 *vmcs12)
13347 {
13348 u32 idt_vectoring;
13349 unsigned int nr;
13350
13351 if (vcpu->arch.exception.injected) {
13352 nr = vcpu->arch.exception.nr;
13353 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
13354
13355 if (kvm_exception_is_soft(nr)) {
13356 vmcs12->vm_exit_instruction_len =
13357 vcpu->arch.event_exit_inst_len;
13358 idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
13359 } else
13360 idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
13361
13362 if (vcpu->arch.exception.has_error_code) {
13363 idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
13364 vmcs12->idt_vectoring_error_code =
13365 vcpu->arch.exception.error_code;
13366 }
13367
13368 vmcs12->idt_vectoring_info_field = idt_vectoring;
13369 } else if (vcpu->arch.nmi_injected) {
13370 vmcs12->idt_vectoring_info_field =
13371 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
13372 } else if (vcpu->arch.interrupt.injected) {
13373 nr = vcpu->arch.interrupt.nr;
13374 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
13375
13376 if (vcpu->arch.interrupt.soft) {
13377 idt_vectoring |= INTR_TYPE_SOFT_INTR;
13378 vmcs12->vm_entry_instruction_len =
13379 vcpu->arch.event_exit_inst_len;
13380 } else
13381 idt_vectoring |= INTR_TYPE_EXT_INTR;
13382
13383 vmcs12->idt_vectoring_info_field = idt_vectoring;
13384 }
13385 }
13386
13387 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
13388 {
13389 struct vcpu_vmx *vmx = to_vmx(vcpu);
13390 unsigned long exit_qual;
13391 bool block_nested_events =
13392 vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
13393
13394 if (vcpu->arch.exception.pending &&
13395 nested_vmx_check_exception(vcpu, &exit_qual)) {
13396 if (block_nested_events)
13397 return -EBUSY;
13398 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
13399 return 0;
13400 }
13401
13402 if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
13403 vmx->nested.preemption_timer_expired) {
13404 if (block_nested_events)
13405 return -EBUSY;
13406 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
13407 return 0;
13408 }
13409
13410 if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
13411 if (block_nested_events)
13412 return -EBUSY;
13413 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
13414 NMI_VECTOR | INTR_TYPE_NMI_INTR |
13415 INTR_INFO_VALID_MASK, 0);
13416 /*
13417 * The NMI-triggered VM exit counts as injection:
13418 * clear this one and block further NMIs.
13419 */
13420 vcpu->arch.nmi_pending = 0;
13421 vmx_set_nmi_mask(vcpu, true);
13422 return 0;
13423 }
13424
13425 if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
13426 nested_exit_on_intr(vcpu)) {
13427 if (block_nested_events)
13428 return -EBUSY;
13429 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
13430 return 0;
13431 }
13432
13433 vmx_complete_nested_posted_interrupt(vcpu);
13434 return 0;
13435 }
13436
13437 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
13438 {
13439 to_vmx(vcpu)->req_immediate_exit = true;
13440 }
13441
13442 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
13443 {
13444 ktime_t remaining =
13445 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
13446 u64 value;
13447
13448 if (ktime_to_ns(remaining) <= 0)
13449 return 0;
13450
13451 value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
13452 do_div(value, 1000000);
13453 return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
13454 }
13455
13456 /*
13457 * Update the guest state fields of vmcs12 to reflect changes that
13458 * occurred while L2 was running. (The "IA-32e mode guest" bit of the
13459 * VM-entry controls is also updated, since this is really a guest
13460 * state bit.)
13461 */
13462 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13463 {
13464 vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
13465 vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
13466
13467 vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
13468 vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
13469 vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
13470
13471 vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
13472 vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
13473 vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
13474 vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
13475 vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
13476 vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
13477 vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
13478 vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
13479 vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
13480 vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
13481 vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
13482 vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
13483 vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
13484 vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
13485 vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
13486 vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
13487 vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
13488 vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
13489 vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
13490 vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
13491 vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
13492 vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
13493 vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
13494 vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
13495 vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
13496 vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
13497 vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
13498 vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
13499 vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
13500 vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
13501 vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
13502 vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
13503 vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
13504 vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
13505 vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
13506 vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
13507
13508 vmcs12->guest_interruptibility_info =
13509 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
13510 vmcs12->guest_pending_dbg_exceptions =
13511 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
13512 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
13513 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
13514 else
13515 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
13516
13517 if (nested_cpu_has_preemption_timer(vmcs12)) {
13518 if (vmcs12->vm_exit_controls &
13519 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
13520 vmcs12->vmx_preemption_timer_value =
13521 vmx_get_preemption_timer_value(vcpu);
13522 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
13523 }
13524
13525 /*
13526 * In some cases (usually, nested EPT), L2 is allowed to change its
13527 * own CR3 without exiting. If it has changed it, we must keep it.
13528 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
13529 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
13530 *
13531 * Additionally, restore L2's PDPTR to vmcs12.
13532 */
13533 if (enable_ept) {
13534 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
13535 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
13536 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
13537 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
13538 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
13539 }
13540
13541 vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
13542
13543 if (nested_cpu_has_vid(vmcs12))
13544 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
13545
13546 vmcs12->vm_entry_controls =
13547 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
13548 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
13549
13550 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
13551 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
13552 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13553 }
13554
13555 /* TODO: These cannot have changed unless we have MSR bitmaps and
13556 * the relevant bit asks not to trap the change */
13557 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
13558 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
13559 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
13560 vmcs12->guest_ia32_efer = vcpu->arch.efer;
13561 vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
13562 vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
13563 vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
13564 if (kvm_mpx_supported())
13565 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13566 }
13567
13568 /*
13569 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
13570 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
13571 * and this function updates it to reflect the changes to the guest state while
13572 * L2 was running (and perhaps made some exits which were handled directly by L0
13573 * without going back to L1), and to reflect the exit reason.
13574 * Note that we do not have to copy here all VMCS fields, just those that
13575 * could have changed by the L2 guest or the exit - i.e., the guest-state and
13576 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
13577 * which already writes to vmcs12 directly.
13578 */
13579 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13580 u32 exit_reason, u32 exit_intr_info,
13581 unsigned long exit_qualification)
13582 {
13583 /* update guest state fields: */
13584 sync_vmcs12(vcpu, vmcs12);
13585
13586 /* update exit information fields: */
13587
13588 vmcs12->vm_exit_reason = exit_reason;
13589 vmcs12->exit_qualification = exit_qualification;
13590 vmcs12->vm_exit_intr_info = exit_intr_info;
13591
13592 vmcs12->idt_vectoring_info_field = 0;
13593 vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
13594 vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
13595
13596 if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
13597 vmcs12->launch_state = 1;
13598
13599 /* vm_entry_intr_info_field is cleared on exit. Emulate this
13600 * instead of reading the real value. */
13601 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
13602
13603 /*
13604 * Transfer the event that L0 or L1 may wanted to inject into
13605 * L2 to IDT_VECTORING_INFO_FIELD.
13606 */
13607 vmcs12_save_pending_event(vcpu, vmcs12);
13608 }
13609
13610 /*
13611 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
13612 * preserved above and would only end up incorrectly in L1.
13613 */
13614 vcpu->arch.nmi_injected = false;
13615 kvm_clear_exception_queue(vcpu);
13616 kvm_clear_interrupt_queue(vcpu);
13617 }
13618
13619 /*
13620 * A part of what we need to when the nested L2 guest exits and we want to
13621 * run its L1 parent, is to reset L1's guest state to the host state specified
13622 * in vmcs12.
13623 * This function is to be called not only on normal nested exit, but also on
13624 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
13625 * Failures During or After Loading Guest State").
13626 * This function should be called when the active VMCS is L1's (vmcs01).
13627 */
13628 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13629 struct vmcs12 *vmcs12)
13630 {
13631 struct kvm_segment seg;
13632 u32 entry_failure_code;
13633
13634 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
13635 vcpu->arch.efer = vmcs12->host_ia32_efer;
13636 else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13637 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
13638 else
13639 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
13640 vmx_set_efer(vcpu, vcpu->arch.efer);
13641
13642 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
13643 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
13644 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
13645 vmx_set_interrupt_shadow(vcpu, 0);
13646
13647 /*
13648 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
13649 * actually changed, because vmx_set_cr0 refers to efer set above.
13650 *
13651 * CR0_GUEST_HOST_MASK is already set in the original vmcs01
13652 * (KVM doesn't change it);
13653 */
13654 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
13655 vmx_set_cr0(vcpu, vmcs12->host_cr0);
13656
13657 /* Same as above - no reason to call set_cr4_guest_host_mask(). */
13658 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13659 vmx_set_cr4(vcpu, vmcs12->host_cr4);
13660
13661 nested_ept_uninit_mmu_context(vcpu);
13662
13663 /*
13664 * Only PDPTE load can fail as the value of cr3 was checked on entry and
13665 * couldn't have changed.
13666 */
13667 if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
13668 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
13669
13670 if (!enable_ept)
13671 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
13672
13673 /*
13674 * If vmcs01 doesn't use VPID, CPU flushes TLB on every
13675 * VMEntry/VMExit. Thus, no need to flush TLB.
13676 *
13677 * If vmcs12 doesn't use VPID, L1 expects TLB to be
13678 * flushed on every VMEntry/VMExit.
13679 *
13680 * Otherwise, we can preserve TLB entries as long as we are
13681 * able to tag L1 TLB entries differently than L2 TLB entries.
13682 *
13683 * If vmcs12 uses EPT, we need to execute this flush on EPTP01
13684 * and therefore we request the TLB flush to happen only after VMCS EPTP
13685 * has been set by KVM_REQ_LOAD_CR3.
13686 */
13687 if (enable_vpid &&
13688 (!nested_cpu_has_vpid(vmcs12) || !nested_has_guest_tlb_tag(vcpu))) {
13689 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
13690 }
13691
13692 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
13693 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
13694 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
13695 vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
13696 vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
13697 vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
13698 vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
13699
13700 /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
13701 if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
13702 vmcs_write64(GUEST_BNDCFGS, 0);
13703
13704 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
13705 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
13706 vcpu->arch.pat = vmcs12->host_ia32_pat;
13707 }
13708 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
13709 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
13710 vmcs12->host_ia32_perf_global_ctrl);
13711
13712 /* Set L1 segment info according to Intel SDM
13713 27.5.2 Loading Host Segment and Descriptor-Table Registers */
13714 seg = (struct kvm_segment) {
13715 .base = 0,
13716 .limit = 0xFFFFFFFF,
13717 .selector = vmcs12->host_cs_selector,
13718 .type = 11,
13719 .present = 1,
13720 .s = 1,
13721 .g = 1
13722 };
13723 if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13724 seg.l = 1;
13725 else
13726 seg.db = 1;
13727 vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
13728 seg = (struct kvm_segment) {
13729 .base = 0,
13730 .limit = 0xFFFFFFFF,
13731 .type = 3,
13732 .present = 1,
13733 .s = 1,
13734 .db = 1,
13735 .g = 1
13736 };
13737 seg.selector = vmcs12->host_ds_selector;
13738 vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
13739 seg.selector = vmcs12->host_es_selector;
13740 vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
13741 seg.selector = vmcs12->host_ss_selector;
13742 vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
13743 seg.selector = vmcs12->host_fs_selector;
13744 seg.base = vmcs12->host_fs_base;
13745 vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
13746 seg.selector = vmcs12->host_gs_selector;
13747 seg.base = vmcs12->host_gs_base;
13748 vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
13749 seg = (struct kvm_segment) {
13750 .base = vmcs12->host_tr_base,
13751 .limit = 0x67,
13752 .selector = vmcs12->host_tr_selector,
13753 .type = 11,
13754 .present = 1
13755 };
13756 vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
13757
13758 kvm_set_dr(vcpu, 7, 0x400);
13759 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
13760
13761 if (cpu_has_vmx_msr_bitmap())
13762 vmx_update_msr_bitmap(vcpu);
13763
13764 if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
13765 vmcs12->vm_exit_msr_load_count))
13766 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
13767 }
13768
13769 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
13770 {
13771 struct shared_msr_entry *efer_msr;
13772 unsigned int i;
13773
13774 if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
13775 return vmcs_read64(GUEST_IA32_EFER);
13776
13777 if (cpu_has_load_ia32_efer())
13778 return host_efer;
13779
13780 for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
13781 if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
13782 return vmx->msr_autoload.guest.val[i].value;
13783 }
13784
13785 efer_msr = find_msr_entry(vmx, MSR_EFER);
13786 if (efer_msr)
13787 return efer_msr->data;
13788
13789 return host_efer;
13790 }
13791
13792 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
13793 {
13794 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13795 struct vcpu_vmx *vmx = to_vmx(vcpu);
13796 struct vmx_msr_entry g, h;
13797 struct msr_data msr;
13798 gpa_t gpa;
13799 u32 i, j;
13800
13801 vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
13802
13803 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
13804 /*
13805 * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
13806 * as vmcs01.GUEST_DR7 contains a userspace defined value
13807 * and vcpu->arch.dr7 is not squirreled away before the
13808 * nested VMENTER (not worth adding a variable in nested_vmx).
13809 */
13810 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
13811 kvm_set_dr(vcpu, 7, DR7_FIXED_1);
13812 else
13813 WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
13814 }
13815
13816 /*
13817 * Note that calling vmx_set_{efer,cr0,cr4} is important as they
13818 * handle a variety of side effects to KVM's software model.
13819 */
13820 vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
13821
13822 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
13823 vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
13824
13825 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13826 vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
13827
13828 nested_ept_uninit_mmu_context(vcpu);
13829 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
13830 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
13831
13832 /*
13833 * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
13834 * from vmcs01 (if necessary). The PDPTRs are not loaded on
13835 * VMFail, like everything else we just need to ensure our
13836 * software model is up-to-date.
13837 */
13838 ept_save_pdptrs(vcpu);
13839
13840 kvm_mmu_reset_context(vcpu);
13841
13842 if (cpu_has_vmx_msr_bitmap())
13843 vmx_update_msr_bitmap(vcpu);
13844
13845 /*
13846 * This nasty bit of open coding is a compromise between blindly
13847 * loading L1's MSRs using the exit load lists (incorrect emulation
13848 * of VMFail), leaving the nested VM's MSRs in the software model
13849 * (incorrect behavior) and snapshotting the modified MSRs (too
13850 * expensive since the lists are unbound by hardware). For each
13851 * MSR that was (prematurely) loaded from the nested VMEntry load
13852 * list, reload it from the exit load list if it exists and differs
13853 * from the guest value. The intent is to stuff host state as
13854 * silently as possible, not to fully process the exit load list.
13855 */
13856 msr.host_initiated = false;
13857 for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
13858 gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
13859 if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
13860 pr_debug_ratelimited(
13861 "%s read MSR index failed (%u, 0x%08llx)\n",
13862 __func__, i, gpa);
13863 goto vmabort;
13864 }
13865
13866 for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
13867 gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
13868 if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
13869 pr_debug_ratelimited(
13870 "%s read MSR failed (%u, 0x%08llx)\n",
13871 __func__, j, gpa);
13872 goto vmabort;
13873 }
13874 if (h.index != g.index)
13875 continue;
13876 if (h.value == g.value)
13877 break;
13878
13879 if (nested_vmx_load_msr_check(vcpu, &h)) {
13880 pr_debug_ratelimited(
13881 "%s check failed (%u, 0x%x, 0x%x)\n",
13882 __func__, j, h.index, h.reserved);
13883 goto vmabort;
13884 }
13885
13886 msr.index = h.index;
13887 msr.data = h.value;
13888 if (kvm_set_msr(vcpu, &msr)) {
13889 pr_debug_ratelimited(
13890 "%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
13891 __func__, j, h.index, h.value);
13892 goto vmabort;
13893 }
13894 }
13895 }
13896
13897 return;
13898
13899 vmabort:
13900 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
13901 }
13902
13903 /*
13904 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
13905 * and modify vmcs12 to make it see what it would expect to see there if
13906 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
13907 */
13908 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
13909 u32 exit_intr_info,
13910 unsigned long exit_qualification)
13911 {
13912 struct vcpu_vmx *vmx = to_vmx(vcpu);
13913 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13914
13915 /* trying to cancel vmlaunch/vmresume is a bug */
13916 WARN_ON_ONCE(vmx->nested.nested_run_pending);
13917
13918 leave_guest_mode(vcpu);
13919
13920 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13921 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
13922
13923 if (likely(!vmx->fail)) {
13924 if (exit_reason == -1)
13925 sync_vmcs12(vcpu, vmcs12);
13926 else
13927 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
13928 exit_qualification);
13929
13930 /*
13931 * Must happen outside of sync_vmcs12() as it will
13932 * also be used to capture vmcs12 cache as part of
13933 * capturing nVMX state for snapshot (migration).
13934 *
13935 * Otherwise, this flush will dirty guest memory at a
13936 * point it is already assumed by user-space to be
13937 * immutable.
13938 */
13939 nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
13940
13941 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
13942 vmcs12->vm_exit_msr_store_count))
13943 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
13944 } else {
13945 /*
13946 * The only expected VM-instruction error is "VM entry with
13947 * invalid control field(s)." Anything else indicates a
13948 * problem with L0. And we should never get here with a
13949 * VMFail of any type if early consistency checks are enabled.
13950 */
13951 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
13952 VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13953 WARN_ON_ONCE(nested_early_check);
13954 }
13955
13956 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13957
13958 /* Update any VMCS fields that might have changed while L2 ran */
13959 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
13960 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
13961 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
13962
13963 if (kvm_has_tsc_control)
13964 decache_tsc_multiplier(vmx);
13965
13966 if (vmx->nested.change_vmcs01_virtual_apic_mode) {
13967 vmx->nested.change_vmcs01_virtual_apic_mode = false;
13968 vmx_set_virtual_apic_mode(vcpu);
13969 } else if (!nested_cpu_has_ept(vmcs12) &&
13970 nested_cpu_has2(vmcs12,
13971 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
13972 vmx_flush_tlb(vcpu, true);
13973 }
13974
13975 /* This is needed for same reason as it was needed in prepare_vmcs02 */
13976 vmx->host_rsp = 0;
13977
13978 /* Unpin physical memory we referred to in vmcs02 */
13979 if (vmx->nested.apic_access_page) {
13980 kvm_release_page_dirty(vmx->nested.apic_access_page);
13981 vmx->nested.apic_access_page = NULL;
13982 }
13983 if (vmx->nested.virtual_apic_page) {
13984 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
13985 vmx->nested.virtual_apic_page = NULL;
13986 }
13987 if (vmx->nested.pi_desc_page) {
13988 kunmap(vmx->nested.pi_desc_page);
13989 kvm_release_page_dirty(vmx->nested.pi_desc_page);
13990 vmx->nested.pi_desc_page = NULL;
13991 vmx->nested.pi_desc = NULL;
13992 }
13993
13994 /*
13995 * We are now running in L2, mmu_notifier will force to reload the
13996 * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
13997 */
13998 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
13999
14000 if ((exit_reason != -1) && (enable_shadow_vmcs || vmx->nested.hv_evmcs))
14001 vmx->nested.need_vmcs12_sync = true;
14002
14003 /* in case we halted in L2 */
14004 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
14005
14006 if (likely(!vmx->fail)) {
14007 /*
14008 * TODO: SDM says that with acknowledge interrupt on
14009 * exit, bit 31 of the VM-exit interrupt information
14010 * (valid interrupt) is always set to 1 on
14011 * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
14012 * need kvm_cpu_has_interrupt(). See the commit
14013 * message for details.
14014 */
14015 if (nested_exit_intr_ack_set(vcpu) &&
14016 exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
14017 kvm_cpu_has_interrupt(vcpu)) {
14018 int irq = kvm_cpu_get_interrupt(vcpu);
14019 WARN_ON(irq < 0);
14020 vmcs12->vm_exit_intr_info = irq |
14021 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
14022 }
14023
14024 if (exit_reason != -1)
14025 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
14026 vmcs12->exit_qualification,
14027 vmcs12->idt_vectoring_info_field,
14028 vmcs12->vm_exit_intr_info,
14029 vmcs12->vm_exit_intr_error_code,
14030 KVM_ISA_VMX);
14031
14032 load_vmcs12_host_state(vcpu, vmcs12);
14033
14034 return;
14035 }
14036
14037 /*
14038 * After an early L2 VM-entry failure, we're now back
14039 * in L1 which thinks it just finished a VMLAUNCH or
14040 * VMRESUME instruction, so we need to set the failure
14041 * flag and the VM-instruction error field of the VMCS
14042 * accordingly, and skip the emulated instruction.
14043 */
14044 (void)nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
14045
14046 /*
14047 * Restore L1's host state to KVM's software model. We're here
14048 * because a consistency check was caught by hardware, which
14049 * means some amount of guest state has been propagated to KVM's
14050 * model and needs to be unwound to the host's state.
14051 */
14052 nested_vmx_restore_host_state(vcpu);
14053
14054 vmx->fail = 0;
14055 }
14056
14057 /*
14058 * Forcibly leave nested mode in order to be able to reset the VCPU later on.
14059 */
14060 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
14061 {
14062 if (is_guest_mode(vcpu)) {
14063 to_vmx(vcpu)->nested.nested_run_pending = 0;
14064 nested_vmx_vmexit(vcpu, -1, 0, 0);
14065 }
14066 free_nested(vcpu);
14067 }
14068
14069 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
14070 struct x86_instruction_info *info,
14071 enum x86_intercept_stage stage)
14072 {
14073 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14074 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
14075
14076 /*
14077 * RDPID causes #UD if disabled through secondary execution controls.
14078 * Because it is marked as EmulateOnUD, we need to intercept it here.
14079 */
14080 if (info->intercept == x86_intercept_rdtscp &&
14081 !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
14082 ctxt->exception.vector = UD_VECTOR;
14083 ctxt->exception.error_code_valid = false;
14084 return X86EMUL_PROPAGATE_FAULT;
14085 }
14086
14087 /* TODO: check more intercepts... */
14088 return X86EMUL_CONTINUE;
14089 }
14090
14091 #ifdef CONFIG_X86_64
14092 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
14093 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
14094 u64 divisor, u64 *result)
14095 {
14096 u64 low = a << shift, high = a >> (64 - shift);
14097
14098 /* To avoid the overflow on divq */
14099 if (high >= divisor)
14100 return 1;
14101
14102 /* Low hold the result, high hold rem which is discarded */
14103 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
14104 "rm" (divisor), "0" (low), "1" (high));
14105 *result = low;
14106
14107 return 0;
14108 }
14109
14110 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
14111 {
14112 struct vcpu_vmx *vmx;
14113 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
14114
14115 if (kvm_mwait_in_guest(vcpu->kvm))
14116 return -EOPNOTSUPP;
14117
14118 vmx = to_vmx(vcpu);
14119 tscl = rdtsc();
14120 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
14121 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
14122 lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
14123
14124 if (delta_tsc > lapic_timer_advance_cycles)
14125 delta_tsc -= lapic_timer_advance_cycles;
14126 else
14127 delta_tsc = 0;
14128
14129 /* Convert to host delta tsc if tsc scaling is enabled */
14130 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
14131 u64_shl_div_u64(delta_tsc,
14132 kvm_tsc_scaling_ratio_frac_bits,
14133 vcpu->arch.tsc_scaling_ratio,
14134 &delta_tsc))
14135 return -ERANGE;
14136
14137 /*
14138 * If the delta tsc can't fit in the 32 bit after the multi shift,
14139 * we can't use the preemption timer.
14140 * It's possible that it fits on later vmentries, but checking
14141 * on every vmentry is costly so we just use an hrtimer.
14142 */
14143 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
14144 return -ERANGE;
14145
14146 vmx->hv_deadline_tsc = tscl + delta_tsc;
14147 return delta_tsc == 0;
14148 }
14149
14150 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
14151 {
14152 to_vmx(vcpu)->hv_deadline_tsc = -1;
14153 }
14154 #endif
14155
14156 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
14157 {
14158 if (!kvm_pause_in_guest(vcpu->kvm))
14159 shrink_ple_window(vcpu);
14160 }
14161
14162 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
14163 struct kvm_memory_slot *slot)
14164 {
14165 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
14166 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
14167 }
14168
14169 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
14170 struct kvm_memory_slot *slot)
14171 {
14172 kvm_mmu_slot_set_dirty(kvm, slot);
14173 }
14174
14175 static void vmx_flush_log_dirty(struct kvm *kvm)
14176 {
14177 kvm_flush_pml_buffers(kvm);
14178 }
14179
14180 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
14181 {
14182 struct vmcs12 *vmcs12;
14183 struct vcpu_vmx *vmx = to_vmx(vcpu);
14184 gpa_t gpa;
14185 struct page *page = NULL;
14186 u64 *pml_address;
14187
14188 if (is_guest_mode(vcpu)) {
14189 WARN_ON_ONCE(vmx->nested.pml_full);
14190
14191 /*
14192 * Check if PML is enabled for the nested guest.
14193 * Whether eptp bit 6 is set is already checked
14194 * as part of A/D emulation.
14195 */
14196 vmcs12 = get_vmcs12(vcpu);
14197 if (!nested_cpu_has_pml(vmcs12))
14198 return 0;
14199
14200 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
14201 vmx->nested.pml_full = true;
14202 return 1;
14203 }
14204
14205 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
14206
14207 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
14208 if (is_error_page(page))
14209 return 0;
14210
14211 pml_address = kmap(page);
14212 pml_address[vmcs12->guest_pml_index--] = gpa;
14213 kunmap(page);
14214 kvm_release_page_clean(page);
14215 }
14216
14217 return 0;
14218 }
14219
14220 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
14221 struct kvm_memory_slot *memslot,
14222 gfn_t offset, unsigned long mask)
14223 {
14224 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
14225 }
14226
14227 static void __pi_post_block(struct kvm_vcpu *vcpu)
14228 {
14229 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
14230 struct pi_desc old, new;
14231 unsigned int dest;
14232
14233 do {
14234 old.control = new.control = pi_desc->control;
14235 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
14236 "Wakeup handler not enabled while the VCPU is blocked\n");
14237
14238 dest = cpu_physical_id(vcpu->cpu);
14239
14240 if (x2apic_enabled())
14241 new.ndst = dest;
14242 else
14243 new.ndst = (dest << 8) & 0xFF00;
14244
14245 /* set 'NV' to 'notification vector' */
14246 new.nv = POSTED_INTR_VECTOR;
14247 } while (cmpxchg64(&pi_desc->control, old.control,
14248 new.control) != old.control);
14249
14250 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
14251 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14252 list_del(&vcpu->blocked_vcpu_list);
14253 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14254 vcpu->pre_pcpu = -1;
14255 }
14256 }
14257
14258 /*
14259 * This routine does the following things for vCPU which is going
14260 * to be blocked if VT-d PI is enabled.
14261 * - Store the vCPU to the wakeup list, so when interrupts happen
14262 * we can find the right vCPU to wake up.
14263 * - Change the Posted-interrupt descriptor as below:
14264 * 'NDST' <-- vcpu->pre_pcpu
14265 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
14266 * - If 'ON' is set during this process, which means at least one
14267 * interrupt is posted for this vCPU, we cannot block it, in
14268 * this case, return 1, otherwise, return 0.
14269 *
14270 */
14271 static int pi_pre_block(struct kvm_vcpu *vcpu)
14272 {
14273 unsigned int dest;
14274 struct pi_desc old, new;
14275 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
14276
14277 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
14278 !irq_remapping_cap(IRQ_POSTING_CAP) ||
14279 !kvm_vcpu_apicv_active(vcpu))
14280 return 0;
14281
14282 WARN_ON(irqs_disabled());
14283 local_irq_disable();
14284 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
14285 vcpu->pre_pcpu = vcpu->cpu;
14286 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14287 list_add_tail(&vcpu->blocked_vcpu_list,
14288 &per_cpu(blocked_vcpu_on_cpu,
14289 vcpu->pre_pcpu));
14290 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14291 }
14292
14293 do {
14294 old.control = new.control = pi_desc->control;
14295
14296 WARN((pi_desc->sn == 1),
14297 "Warning: SN field of posted-interrupts "
14298 "is set before blocking\n");
14299
14300 /*
14301 * Since vCPU can be preempted during this process,
14302 * vcpu->cpu could be different with pre_pcpu, we
14303 * need to set pre_pcpu as the destination of wakeup
14304 * notification event, then we can find the right vCPU
14305 * to wakeup in wakeup handler if interrupts happen
14306 * when the vCPU is in blocked state.
14307 */
14308 dest = cpu_physical_id(vcpu->pre_pcpu);
14309
14310 if (x2apic_enabled())
14311 new.ndst = dest;
14312 else
14313 new.ndst = (dest << 8) & 0xFF00;
14314
14315 /* set 'NV' to 'wakeup vector' */
14316 new.nv = POSTED_INTR_WAKEUP_VECTOR;
14317 } while (cmpxchg64(&pi_desc->control, old.control,
14318 new.control) != old.control);
14319
14320 /* We should not block the vCPU if an interrupt is posted for it. */
14321 if (pi_test_on(pi_desc) == 1)
14322 __pi_post_block(vcpu);
14323
14324 local_irq_enable();
14325 return (vcpu->pre_pcpu == -1);
14326 }
14327
14328 static int vmx_pre_block(struct kvm_vcpu *vcpu)
14329 {
14330 if (pi_pre_block(vcpu))
14331 return 1;
14332
14333 if (kvm_lapic_hv_timer_in_use(vcpu))
14334 kvm_lapic_switch_to_sw_timer(vcpu);
14335
14336 return 0;
14337 }
14338
14339 static void pi_post_block(struct kvm_vcpu *vcpu)
14340 {
14341 if (vcpu->pre_pcpu == -1)
14342 return;
14343
14344 WARN_ON(irqs_disabled());
14345 local_irq_disable();
14346 __pi_post_block(vcpu);
14347 local_irq_enable();
14348 }
14349
14350 static void vmx_post_block(struct kvm_vcpu *vcpu)
14351 {
14352 if (kvm_x86_ops->set_hv_timer)
14353 kvm_lapic_switch_to_hv_timer(vcpu);
14354
14355 pi_post_block(vcpu);
14356 }
14357
14358 /*
14359 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
14360 *
14361 * @kvm: kvm
14362 * @host_irq: host irq of the interrupt
14363 * @guest_irq: gsi of the interrupt
14364 * @set: set or unset PI
14365 * returns 0 on success, < 0 on failure
14366 */
14367 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
14368 uint32_t guest_irq, bool set)
14369 {
14370 struct kvm_kernel_irq_routing_entry *e;
14371 struct kvm_irq_routing_table *irq_rt;
14372 struct kvm_lapic_irq irq;
14373 struct kvm_vcpu *vcpu;
14374 struct vcpu_data vcpu_info;
14375 int idx, ret = 0;
14376
14377 if (!kvm_arch_has_assigned_device(kvm) ||
14378 !irq_remapping_cap(IRQ_POSTING_CAP) ||
14379 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
14380 return 0;
14381
14382 idx = srcu_read_lock(&kvm->irq_srcu);
14383 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
14384 if (guest_irq >= irq_rt->nr_rt_entries ||
14385 hlist_empty(&irq_rt->map[guest_irq])) {
14386 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
14387 guest_irq, irq_rt->nr_rt_entries);
14388 goto out;
14389 }
14390
14391 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
14392 if (e->type != KVM_IRQ_ROUTING_MSI)
14393 continue;
14394 /*
14395 * VT-d PI cannot support posting multicast/broadcast
14396 * interrupts to a vCPU, we still use interrupt remapping
14397 * for these kind of interrupts.
14398 *
14399 * For lowest-priority interrupts, we only support
14400 * those with single CPU as the destination, e.g. user
14401 * configures the interrupts via /proc/irq or uses
14402 * irqbalance to make the interrupts single-CPU.
14403 *
14404 * We will support full lowest-priority interrupt later.
14405 */
14406
14407 kvm_set_msi_irq(kvm, e, &irq);
14408 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
14409 /*
14410 * Make sure the IRTE is in remapped mode if
14411 * we don't handle it in posted mode.
14412 */
14413 ret = irq_set_vcpu_affinity(host_irq, NULL);
14414 if (ret < 0) {
14415 printk(KERN_INFO
14416 "failed to back to remapped mode, irq: %u\n",
14417 host_irq);
14418 goto out;
14419 }
14420
14421 continue;
14422 }
14423
14424 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
14425 vcpu_info.vector = irq.vector;
14426
14427 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
14428 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
14429
14430 if (set)
14431 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
14432 else
14433 ret = irq_set_vcpu_affinity(host_irq, NULL);
14434
14435 if (ret < 0) {
14436 printk(KERN_INFO "%s: failed to update PI IRTE\n",
14437 __func__);
14438 goto out;
14439 }
14440 }
14441
14442 ret = 0;
14443 out:
14444 srcu_read_unlock(&kvm->irq_srcu, idx);
14445 return ret;
14446 }
14447
14448 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
14449 {
14450 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
14451 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
14452 FEATURE_CONTROL_LMCE;
14453 else
14454 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
14455 ~FEATURE_CONTROL_LMCE;
14456 }
14457
14458 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
14459 {
14460 /* we need a nested vmexit to enter SMM, postpone if run is pending */
14461 if (to_vmx(vcpu)->nested.nested_run_pending)
14462 return 0;
14463 return 1;
14464 }
14465
14466 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
14467 {
14468 struct vcpu_vmx *vmx = to_vmx(vcpu);
14469
14470 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
14471 if (vmx->nested.smm.guest_mode)
14472 nested_vmx_vmexit(vcpu, -1, 0, 0);
14473
14474 vmx->nested.smm.vmxon = vmx->nested.vmxon;
14475 vmx->nested.vmxon = false;
14476 vmx_clear_hlt(vcpu);
14477 return 0;
14478 }
14479
14480 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
14481 {
14482 struct vcpu_vmx *vmx = to_vmx(vcpu);
14483 int ret;
14484
14485 if (vmx->nested.smm.vmxon) {
14486 vmx->nested.vmxon = true;
14487 vmx->nested.smm.vmxon = false;
14488 }
14489
14490 if (vmx->nested.smm.guest_mode) {
14491 vcpu->arch.hflags &= ~HF_SMM_MASK;
14492 ret = nested_vmx_enter_non_root_mode(vcpu, false);
14493 vcpu->arch.hflags |= HF_SMM_MASK;
14494 if (ret)
14495 return ret;
14496
14497 vmx->nested.smm.guest_mode = false;
14498 }
14499 return 0;
14500 }
14501
14502 static int enable_smi_window(struct kvm_vcpu *vcpu)
14503 {
14504 return 0;
14505 }
14506
14507 static inline int vmx_has_valid_vmcs12(struct kvm_vcpu *vcpu)
14508 {
14509 struct vcpu_vmx *vmx = to_vmx(vcpu);
14510
14511 /*
14512 * In case we do two consecutive get/set_nested_state()s while L2 was
14513 * running hv_evmcs may end up not being mapped (we map it from
14514 * nested_vmx_run()/vmx_vcpu_run()). Check is_guest_mode() as we always
14515 * have vmcs12 if it is true.
14516 */
14517 return is_guest_mode(vcpu) || vmx->nested.current_vmptr != -1ull ||
14518 vmx->nested.hv_evmcs;
14519 }
14520
14521 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
14522 struct kvm_nested_state __user *user_kvm_nested_state,
14523 u32 user_data_size)
14524 {
14525 struct vcpu_vmx *vmx;
14526 struct vmcs12 *vmcs12;
14527 struct kvm_nested_state kvm_state = {
14528 .flags = 0,
14529 .format = 0,
14530 .size = sizeof(kvm_state),
14531 .vmx.vmxon_pa = -1ull,
14532 .vmx.vmcs_pa = -1ull,
14533 };
14534
14535 if (!vcpu)
14536 return kvm_state.size + 2 * VMCS12_SIZE;
14537
14538 vmx = to_vmx(vcpu);
14539 vmcs12 = get_vmcs12(vcpu);
14540
14541 if (nested_vmx_allowed(vcpu) && vmx->nested.enlightened_vmcs_enabled)
14542 kvm_state.flags |= KVM_STATE_NESTED_EVMCS;
14543
14544 if (nested_vmx_allowed(vcpu) &&
14545 (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
14546 kvm_state.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
14547 kvm_state.vmx.vmcs_pa = vmx->nested.current_vmptr;
14548
14549 if (vmx_has_valid_vmcs12(vcpu)) {
14550 kvm_state.size += VMCS12_SIZE;
14551
14552 if (is_guest_mode(vcpu) &&
14553 nested_cpu_has_shadow_vmcs(vmcs12) &&
14554 vmcs12->vmcs_link_pointer != -1ull)
14555 kvm_state.size += VMCS12_SIZE;
14556 }
14557
14558 if (vmx->nested.smm.vmxon)
14559 kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
14560
14561 if (vmx->nested.smm.guest_mode)
14562 kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
14563
14564 if (is_guest_mode(vcpu)) {
14565 kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
14566
14567 if (vmx->nested.nested_run_pending)
14568 kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
14569 }
14570 }
14571
14572 if (user_data_size < kvm_state.size)
14573 goto out;
14574
14575 if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
14576 return -EFAULT;
14577
14578 if (!vmx_has_valid_vmcs12(vcpu))
14579 goto out;
14580
14581 /*
14582 * When running L2, the authoritative vmcs12 state is in the
14583 * vmcs02. When running L1, the authoritative vmcs12 state is
14584 * in the shadow or enlightened vmcs linked to vmcs01, unless
14585 * need_vmcs12_sync is set, in which case, the authoritative
14586 * vmcs12 state is in the vmcs12 already.
14587 */
14588 if (is_guest_mode(vcpu)) {
14589 sync_vmcs12(vcpu, vmcs12);
14590 } else if (!vmx->nested.need_vmcs12_sync) {
14591 if (vmx->nested.hv_evmcs)
14592 copy_enlightened_to_vmcs12(vmx);
14593 else if (enable_shadow_vmcs)
14594 copy_shadow_to_vmcs12(vmx);
14595 }
14596
14597 if (copy_to_user(user_kvm_nested_state->data, vmcs12, sizeof(*vmcs12)))
14598 return -EFAULT;
14599
14600 if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14601 vmcs12->vmcs_link_pointer != -1ull) {
14602 if (copy_to_user(user_kvm_nested_state->data + VMCS12_SIZE,
14603 get_shadow_vmcs12(vcpu), sizeof(*vmcs12)))
14604 return -EFAULT;
14605 }
14606
14607 out:
14608 return kvm_state.size;
14609 }
14610
14611 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
14612 struct kvm_nested_state __user *user_kvm_nested_state,
14613 struct kvm_nested_state *kvm_state)
14614 {
14615 struct vcpu_vmx *vmx = to_vmx(vcpu);
14616 struct vmcs12 *vmcs12;
14617 u32 exit_qual;
14618 int ret;
14619
14620 if (kvm_state->format != 0)
14621 return -EINVAL;
14622
14623 if (kvm_state->flags & KVM_STATE_NESTED_EVMCS)
14624 nested_enable_evmcs(vcpu, NULL);
14625
14626 if (!nested_vmx_allowed(vcpu))
14627 return kvm_state->vmx.vmxon_pa == -1ull ? 0 : -EINVAL;
14628
14629 if (kvm_state->vmx.vmxon_pa == -1ull) {
14630 if (kvm_state->vmx.smm.flags)
14631 return -EINVAL;
14632
14633 if (kvm_state->vmx.vmcs_pa != -1ull)
14634 return -EINVAL;
14635
14636 vmx_leave_nested(vcpu);
14637 return 0;
14638 }
14639
14640 if (!page_address_valid(vcpu, kvm_state->vmx.vmxon_pa))
14641 return -EINVAL;
14642
14643 if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14644 (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14645 return -EINVAL;
14646
14647 if (kvm_state->vmx.smm.flags &
14648 ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
14649 return -EINVAL;
14650
14651 /*
14652 * SMM temporarily disables VMX, so we cannot be in guest mode,
14653 * nor can VMLAUNCH/VMRESUME be pending. Outside SMM, SMM flags
14654 * must be zero.
14655 */
14656 if (is_smm(vcpu) ? kvm_state->flags : kvm_state->vmx.smm.flags)
14657 return -EINVAL;
14658
14659 if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14660 !(kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
14661 return -EINVAL;
14662
14663 vmx_leave_nested(vcpu);
14664 if (kvm_state->vmx.vmxon_pa == -1ull)
14665 return 0;
14666
14667 vmx->nested.vmxon_ptr = kvm_state->vmx.vmxon_pa;
14668 ret = enter_vmx_operation(vcpu);
14669 if (ret)
14670 return ret;
14671
14672 /* Empty 'VMXON' state is permitted */
14673 if (kvm_state->size < sizeof(kvm_state) + sizeof(*vmcs12))
14674 return 0;
14675
14676 if (kvm_state->vmx.vmcs_pa != -1ull) {
14677 if (kvm_state->vmx.vmcs_pa == kvm_state->vmx.vmxon_pa ||
14678 !page_address_valid(vcpu, kvm_state->vmx.vmcs_pa))
14679 return -EINVAL;
14680
14681 set_current_vmptr(vmx, kvm_state->vmx.vmcs_pa);
14682 } else if (kvm_state->flags & KVM_STATE_NESTED_EVMCS) {
14683 /*
14684 * Sync eVMCS upon entry as we may not have
14685 * HV_X64_MSR_VP_ASSIST_PAGE set up yet.
14686 */
14687 vmx->nested.need_vmcs12_sync = true;
14688 } else {
14689 return -EINVAL;
14690 }
14691
14692 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
14693 vmx->nested.smm.vmxon = true;
14694 vmx->nested.vmxon = false;
14695
14696 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
14697 vmx->nested.smm.guest_mode = true;
14698 }
14699
14700 vmcs12 = get_vmcs12(vcpu);
14701 if (copy_from_user(vmcs12, user_kvm_nested_state->data, sizeof(*vmcs12)))
14702 return -EFAULT;
14703
14704 if (vmcs12->hdr.revision_id != VMCS12_REVISION)
14705 return -EINVAL;
14706
14707 if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14708 return 0;
14709
14710 vmx->nested.nested_run_pending =
14711 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
14712
14713 if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14714 vmcs12->vmcs_link_pointer != -1ull) {
14715 struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
14716 if (kvm_state->size < sizeof(kvm_state) + 2 * sizeof(*vmcs12))
14717 return -EINVAL;
14718
14719 if (copy_from_user(shadow_vmcs12,
14720 user_kvm_nested_state->data + VMCS12_SIZE,
14721 sizeof(*vmcs12)))
14722 return -EFAULT;
14723
14724 if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
14725 !shadow_vmcs12->hdr.shadow_vmcs)
14726 return -EINVAL;
14727 }
14728
14729 if (check_vmentry_prereqs(vcpu, vmcs12) ||
14730 check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
14731 return -EINVAL;
14732
14733 vmx->nested.dirty_vmcs12 = true;
14734 ret = nested_vmx_enter_non_root_mode(vcpu, false);
14735 if (ret)
14736 return -EINVAL;
14737
14738 return 0;
14739 }
14740
14741 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
14742 .cpu_has_kvm_support = cpu_has_kvm_support,
14743 .disabled_by_bios = vmx_disabled_by_bios,
14744 .hardware_setup = hardware_setup,
14745 .hardware_unsetup = hardware_unsetup,
14746 .check_processor_compatibility = vmx_check_processor_compat,
14747 .hardware_enable = hardware_enable,
14748 .hardware_disable = hardware_disable,
14749 .cpu_has_accelerated_tpr = report_flexpriority,
14750 .has_emulated_msr = vmx_has_emulated_msr,
14751
14752 .vm_init = vmx_vm_init,
14753 .vm_alloc = vmx_vm_alloc,
14754 .vm_free = vmx_vm_free,
14755
14756 .vcpu_create = vmx_create_vcpu,
14757 .vcpu_free = vmx_free_vcpu,
14758 .vcpu_reset = vmx_vcpu_reset,
14759
14760 .prepare_guest_switch = vmx_prepare_switch_to_guest,
14761 .vcpu_load = vmx_vcpu_load,
14762 .vcpu_put = vmx_vcpu_put,
14763
14764 .update_bp_intercept = update_exception_bitmap,
14765 .get_msr_feature = vmx_get_msr_feature,
14766 .get_msr = vmx_get_msr,
14767 .set_msr = vmx_set_msr,
14768 .get_segment_base = vmx_get_segment_base,
14769 .get_segment = vmx_get_segment,
14770 .set_segment = vmx_set_segment,
14771 .get_cpl = vmx_get_cpl,
14772 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
14773 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
14774 .decache_cr3 = vmx_decache_cr3,
14775 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
14776 .set_cr0 = vmx_set_cr0,
14777 .set_cr3 = vmx_set_cr3,
14778 .set_cr4 = vmx_set_cr4,
14779 .set_efer = vmx_set_efer,
14780 .get_idt = vmx_get_idt,
14781 .set_idt = vmx_set_idt,
14782 .get_gdt = vmx_get_gdt,
14783 .set_gdt = vmx_set_gdt,
14784 .get_dr6 = vmx_get_dr6,
14785 .set_dr6 = vmx_set_dr6,
14786 .set_dr7 = vmx_set_dr7,
14787 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
14788 .cache_reg = vmx_cache_reg,
14789 .get_rflags = vmx_get_rflags,
14790 .set_rflags = vmx_set_rflags,
14791
14792 .tlb_flush = vmx_flush_tlb,
14793 .tlb_flush_gva = vmx_flush_tlb_gva,
14794
14795 .run = vmx_vcpu_run,
14796 .handle_exit = vmx_handle_exit,
14797 .skip_emulated_instruction = skip_emulated_instruction,
14798 .set_interrupt_shadow = vmx_set_interrupt_shadow,
14799 .get_interrupt_shadow = vmx_get_interrupt_shadow,
14800 .patch_hypercall = vmx_patch_hypercall,
14801 .set_irq = vmx_inject_irq,
14802 .set_nmi = vmx_inject_nmi,
14803 .queue_exception = vmx_queue_exception,
14804 .cancel_injection = vmx_cancel_injection,
14805 .interrupt_allowed = vmx_interrupt_allowed,
14806 .nmi_allowed = vmx_nmi_allowed,
14807 .get_nmi_mask = vmx_get_nmi_mask,
14808 .set_nmi_mask = vmx_set_nmi_mask,
14809 .enable_nmi_window = enable_nmi_window,
14810 .enable_irq_window = enable_irq_window,
14811 .update_cr8_intercept = update_cr8_intercept,
14812 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
14813 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
14814 .get_enable_apicv = vmx_get_enable_apicv,
14815 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
14816 .load_eoi_exitmap = vmx_load_eoi_exitmap,
14817 .apicv_post_state_restore = vmx_apicv_post_state_restore,
14818 .hwapic_irr_update = vmx_hwapic_irr_update,
14819 .hwapic_isr_update = vmx_hwapic_isr_update,
14820 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
14821 .sync_pir_to_irr = vmx_sync_pir_to_irr,
14822 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
14823
14824 .set_tss_addr = vmx_set_tss_addr,
14825 .set_identity_map_addr = vmx_set_identity_map_addr,
14826 .get_tdp_level = get_ept_level,
14827 .get_mt_mask = vmx_get_mt_mask,
14828
14829 .get_exit_info = vmx_get_exit_info,
14830
14831 .get_lpage_level = vmx_get_lpage_level,
14832
14833 .cpuid_update = vmx_cpuid_update,
14834
14835 .rdtscp_supported = vmx_rdtscp_supported,
14836 .invpcid_supported = vmx_invpcid_supported,
14837
14838 .set_supported_cpuid = vmx_set_supported_cpuid,
14839
14840 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
14841
14842 .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
14843 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
14844
14845 .set_tdp_cr3 = vmx_set_cr3,
14846
14847 .check_intercept = vmx_check_intercept,
14848 .handle_external_intr = vmx_handle_external_intr,
14849 .mpx_supported = vmx_mpx_supported,
14850 .xsaves_supported = vmx_xsaves_supported,
14851 .umip_emulated = vmx_umip_emulated,
14852
14853 .check_nested_events = vmx_check_nested_events,
14854 .request_immediate_exit = vmx_request_immediate_exit,
14855
14856 .sched_in = vmx_sched_in,
14857
14858 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
14859 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
14860 .flush_log_dirty = vmx_flush_log_dirty,
14861 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
14862 .write_log_dirty = vmx_write_pml_buffer,
14863
14864 .pre_block = vmx_pre_block,
14865 .post_block = vmx_post_block,
14866
14867 .pmu_ops = &intel_pmu_ops,
14868
14869 .update_pi_irte = vmx_update_pi_irte,
14870
14871 #ifdef CONFIG_X86_64
14872 .set_hv_timer = vmx_set_hv_timer,
14873 .cancel_hv_timer = vmx_cancel_hv_timer,
14874 #endif
14875
14876 .setup_mce = vmx_setup_mce,
14877
14878 .get_nested_state = vmx_get_nested_state,
14879 .set_nested_state = vmx_set_nested_state,
14880 .get_vmcs12_pages = nested_get_vmcs12_pages,
14881
14882 .smi_allowed = vmx_smi_allowed,
14883 .pre_enter_smm = vmx_pre_enter_smm,
14884 .pre_leave_smm = vmx_pre_leave_smm,
14885 .enable_smi_window = enable_smi_window,
14886
14887 .nested_enable_evmcs = nested_enable_evmcs,
14888 };
14889
14890 static void vmx_cleanup_l1d_flush(void)
14891 {
14892 if (vmx_l1d_flush_pages) {
14893 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
14894 vmx_l1d_flush_pages = NULL;
14895 }
14896 /* Restore state so sysfs ignores VMX */
14897 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
14898 }
14899
14900 static void vmx_exit(void)
14901 {
14902 #ifdef CONFIG_KEXEC_CORE
14903 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
14904 synchronize_rcu();
14905 #endif
14906
14907 kvm_exit();
14908
14909 #if IS_ENABLED(CONFIG_HYPERV)
14910 if (static_branch_unlikely(&enable_evmcs)) {
14911 int cpu;
14912 struct hv_vp_assist_page *vp_ap;
14913 /*
14914 * Reset everything to support using non-enlightened VMCS
14915 * access later (e.g. when we reload the module with
14916 * enlightened_vmcs=0)
14917 */
14918 for_each_online_cpu(cpu) {
14919 vp_ap = hv_get_vp_assist_page(cpu);
14920
14921 if (!vp_ap)
14922 continue;
14923
14924 vp_ap->current_nested_vmcs = 0;
14925 vp_ap->enlighten_vmentry = 0;
14926 }
14927
14928 static_branch_disable(&enable_evmcs);
14929 }
14930 #endif
14931 vmx_cleanup_l1d_flush();
14932 }
14933 module_exit(vmx_exit);
14934
14935 static int __init vmx_init(void)
14936 {
14937 int r;
14938
14939 #if IS_ENABLED(CONFIG_HYPERV)
14940 /*
14941 * Enlightened VMCS usage should be recommended and the host needs
14942 * to support eVMCS v1 or above. We can also disable eVMCS support
14943 * with module parameter.
14944 */
14945 if (enlightened_vmcs &&
14946 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
14947 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
14948 KVM_EVMCS_VERSION) {
14949 int cpu;
14950
14951 /* Check that we have assist pages on all online CPUs */
14952 for_each_online_cpu(cpu) {
14953 if (!hv_get_vp_assist_page(cpu)) {
14954 enlightened_vmcs = false;
14955 break;
14956 }
14957 }
14958
14959 if (enlightened_vmcs) {
14960 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
14961 static_branch_enable(&enable_evmcs);
14962 }
14963 } else {
14964 enlightened_vmcs = false;
14965 }
14966 #endif
14967
14968 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
14969 __alignof__(struct vcpu_vmx), THIS_MODULE);
14970 if (r)
14971 return r;
14972
14973 /*
14974 * Must be called after kvm_init() so enable_ept is properly set
14975 * up. Hand the parameter mitigation value in which was stored in
14976 * the pre module init parser. If no parameter was given, it will
14977 * contain 'auto' which will be turned into the default 'cond'
14978 * mitigation mode.
14979 */
14980 if (boot_cpu_has(X86_BUG_L1TF)) {
14981 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
14982 if (r) {
14983 vmx_exit();
14984 return r;
14985 }
14986 }
14987
14988 #ifdef CONFIG_KEXEC_CORE
14989 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
14990 crash_vmclear_local_loaded_vmcss);
14991 #endif
14992 vmx_check_vmcs12_offsets();
14993
14994 return 0;
14995 }
14996 module_init(vmx_init);