1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2.  See
15  * the COPYING file in the top-level directory.
16  *
17  */
18 
19 #include "irq.h"
20 #include "mmu.h"
21 #include "cpuid.h"
22 #include "lapic.h"
23 
24 #include <linux/kvm_host.h>
25 #include <linux/module.h>
26 #include <linux/kernel.h>
27 #include <linux/mm.h>
28 #include <linux/highmem.h>
29 #include <linux/sched.h>
30 #include <linux/moduleparam.h>
31 #include <linux/mod_devicetable.h>
32 #include <linux/trace_events.h>
33 #include <linux/slab.h>
34 #include <linux/tboot.h>
35 #include <linux/hrtimer.h>
36 #include <linux/frame.h>
37 #include <linux/nospec.h>
38 #include "kvm_cache_regs.h"
39 #include "x86.h"
40 
41 #include <asm/asm.h>
42 #include <asm/cpu.h>
43 #include <asm/io.h>
44 #include <asm/desc.h>
45 #include <asm/vmx.h>
46 #include <asm/virtext.h>
47 #include <asm/mce.h>
48 #include <asm/fpu/internal.h>
49 #include <asm/perf_event.h>
50 #include <asm/debugreg.h>
51 #include <asm/kexec.h>
52 #include <asm/apic.h>
53 #include <asm/irq_remapping.h>
54 #include <asm/mmu_context.h>
55 #include <asm/spec-ctrl.h>
56 #include <asm/mshyperv.h>
57 
58 #include "trace.h"
59 #include "pmu.h"
60 #include "vmx_evmcs.h"
61 
62 #define __ex(x) __kvm_handle_fault_on_reboot(x)
63 #define __ex_clear(x, reg) \
64 	____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
65 
66 MODULE_AUTHOR("Qumranet");
67 MODULE_LICENSE("GPL");
68 
69 static const struct x86_cpu_id vmx_cpu_id[] = {
70 	X86_FEATURE_MATCH(X86_FEATURE_VMX),
71 	{}
72 };
73 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
74 
75 static bool __read_mostly enable_vpid = 1;
76 module_param_named(vpid, enable_vpid, bool, 0444);
77 
78 static bool __read_mostly enable_vnmi = 1;
79 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
80 
81 static bool __read_mostly flexpriority_enabled = 1;
82 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
83 
84 static bool __read_mostly enable_ept = 1;
85 module_param_named(ept, enable_ept, bool, S_IRUGO);
86 
87 static bool __read_mostly enable_unrestricted_guest = 1;
88 module_param_named(unrestricted_guest,
89 			enable_unrestricted_guest, bool, S_IRUGO);
90 
91 static bool __read_mostly enable_ept_ad_bits = 1;
92 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
93 
94 static bool __read_mostly emulate_invalid_guest_state = true;
95 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
96 
97 static bool __read_mostly fasteoi = 1;
98 module_param(fasteoi, bool, S_IRUGO);
99 
100 static bool __read_mostly enable_apicv = 1;
101 module_param(enable_apicv, bool, S_IRUGO);
102 
103 static bool __read_mostly enable_shadow_vmcs = 1;
104 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
105 /*
106  * If nested=1, nested virtualization is supported, i.e., guests may use
107  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
108  * use VMX instructions.
109  */
110 static bool __read_mostly nested = 0;
111 module_param(nested, bool, S_IRUGO);
112 
113 static u64 __read_mostly host_xss;
114 
115 static bool __read_mostly enable_pml = 1;
116 module_param_named(pml, enable_pml, bool, S_IRUGO);
117 
118 #define MSR_TYPE_R	1
119 #define MSR_TYPE_W	2
120 #define MSR_TYPE_RW	3
121 
122 #define MSR_BITMAP_MODE_X2APIC		1
123 #define MSR_BITMAP_MODE_X2APIC_APICV	2
124 
125 #define KVM_VMX_TSC_MULTIPLIER_MAX     0xffffffffffffffffULL
126 
127 /* Guest_tsc -> host_tsc conversion requires 64-bit division.  */
128 static int __read_mostly cpu_preemption_timer_multi;
129 static bool __read_mostly enable_preemption_timer = 1;
130 #ifdef CONFIG_X86_64
131 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
132 #endif
133 
134 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
135 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
136 #define KVM_VM_CR0_ALWAYS_ON				\
137 	(KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | 	\
138 	 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
139 #define KVM_CR4_GUEST_OWNED_BITS				      \
140 	(X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
141 	 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
142 
143 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
144 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
145 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
146 
147 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
148 
149 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
150 
151 /*
152  * Hyper-V requires all of these, so mark them as supported even though
153  * they are just treated the same as all-context.
154  */
155 #define VMX_VPID_EXTENT_SUPPORTED_MASK		\
156 	(VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT |	\
157 	VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT |	\
158 	VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT |	\
159 	VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
160 
161 /*
162  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
163  * ple_gap:    upper bound on the amount of time between two successive
164  *             executions of PAUSE in a loop. Also indicate if ple enabled.
165  *             According to test, this time is usually smaller than 128 cycles.
166  * ple_window: upper bound on the amount of time a guest is allowed to execute
167  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
168  *             less than 2^12 cycles
169  * Time is measured based on a counter that runs at the same rate as the TSC,
170  * refer SDM volume 3b section 21.6.13 & 22.1.3.
171  */
172 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
173 
174 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
175 module_param(ple_window, uint, 0444);
176 
177 /* Default doubles per-vcpu window every exit. */
178 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
179 module_param(ple_window_grow, uint, 0444);
180 
181 /* Default resets per-vcpu window every exit to ple_window. */
182 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
183 module_param(ple_window_shrink, uint, 0444);
184 
185 /* Default is to compute the maximum so we can never overflow. */
186 static unsigned int ple_window_max        = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
187 module_param(ple_window_max, uint, 0444);
188 
189 extern const ulong vmx_return;
190 
191 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
192 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
193 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
194 
195 /* Storage for pre module init parameter parsing */
196 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
197 
198 static const struct {
199 	const char *option;
200 	bool for_parse;
201 } vmentry_l1d_param[] = {
202 	[VMENTER_L1D_FLUSH_AUTO]	 = {"auto", true},
203 	[VMENTER_L1D_FLUSH_NEVER]	 = {"never", true},
204 	[VMENTER_L1D_FLUSH_COND]	 = {"cond", true},
205 	[VMENTER_L1D_FLUSH_ALWAYS]	 = {"always", true},
206 	[VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
207 	[VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
208 };
209 
210 #define L1D_CACHE_ORDER 4
211 static void *vmx_l1d_flush_pages;
212 
vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)213 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
214 {
215 	struct page *page;
216 	unsigned int i;
217 
218 	if (!enable_ept) {
219 		l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
220 		return 0;
221 	}
222 
223 	if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
224 		u64 msr;
225 
226 		rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
227 		if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
228 			l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
229 			return 0;
230 		}
231 	}
232 
233 	/* If set to auto use the default l1tf mitigation method */
234 	if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
235 		switch (l1tf_mitigation) {
236 		case L1TF_MITIGATION_OFF:
237 			l1tf = VMENTER_L1D_FLUSH_NEVER;
238 			break;
239 		case L1TF_MITIGATION_FLUSH_NOWARN:
240 		case L1TF_MITIGATION_FLUSH:
241 		case L1TF_MITIGATION_FLUSH_NOSMT:
242 			l1tf = VMENTER_L1D_FLUSH_COND;
243 			break;
244 		case L1TF_MITIGATION_FULL:
245 		case L1TF_MITIGATION_FULL_FORCE:
246 			l1tf = VMENTER_L1D_FLUSH_ALWAYS;
247 			break;
248 		}
249 	} else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
250 		l1tf = VMENTER_L1D_FLUSH_ALWAYS;
251 	}
252 
253 	if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
254 	    !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
255 		page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
256 		if (!page)
257 			return -ENOMEM;
258 		vmx_l1d_flush_pages = page_address(page);
259 
260 		/*
261 		 * Initialize each page with a different pattern in
262 		 * order to protect against KSM in the nested
263 		 * virtualization case.
264 		 */
265 		for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
266 			memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
267 			       PAGE_SIZE);
268 		}
269 	}
270 
271 	l1tf_vmx_mitigation = l1tf;
272 
273 	if (l1tf != VMENTER_L1D_FLUSH_NEVER)
274 		static_branch_enable(&vmx_l1d_should_flush);
275 	else
276 		static_branch_disable(&vmx_l1d_should_flush);
277 
278 	if (l1tf == VMENTER_L1D_FLUSH_COND)
279 		static_branch_enable(&vmx_l1d_flush_cond);
280 	else
281 		static_branch_disable(&vmx_l1d_flush_cond);
282 	return 0;
283 }
284 
vmentry_l1d_flush_parse(const char * s)285 static int vmentry_l1d_flush_parse(const char *s)
286 {
287 	unsigned int i;
288 
289 	if (s) {
290 		for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
291 			if (vmentry_l1d_param[i].for_parse &&
292 			    sysfs_streq(s, vmentry_l1d_param[i].option))
293 				return i;
294 		}
295 	}
296 	return -EINVAL;
297 }
298 
vmentry_l1d_flush_set(const char * s,const struct kernel_param * kp)299 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
300 {
301 	int l1tf, ret;
302 
303 	l1tf = vmentry_l1d_flush_parse(s);
304 	if (l1tf < 0)
305 		return l1tf;
306 
307 	if (!boot_cpu_has(X86_BUG_L1TF))
308 		return 0;
309 
310 	/*
311 	 * Has vmx_init() run already? If not then this is the pre init
312 	 * parameter parsing. In that case just store the value and let
313 	 * vmx_init() do the proper setup after enable_ept has been
314 	 * established.
315 	 */
316 	if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
317 		vmentry_l1d_flush_param = l1tf;
318 		return 0;
319 	}
320 
321 	mutex_lock(&vmx_l1d_flush_mutex);
322 	ret = vmx_setup_l1d_flush(l1tf);
323 	mutex_unlock(&vmx_l1d_flush_mutex);
324 	return ret;
325 }
326 
vmentry_l1d_flush_get(char * s,const struct kernel_param * kp)327 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
328 {
329 	if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
330 		return sprintf(s, "???\n");
331 
332 	return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
333 }
334 
335 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
336 	.set = vmentry_l1d_flush_set,
337 	.get = vmentry_l1d_flush_get,
338 };
339 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
340 
341 enum ept_pointers_status {
342 	EPT_POINTERS_CHECK = 0,
343 	EPT_POINTERS_MATCH = 1,
344 	EPT_POINTERS_MISMATCH = 2
345 };
346 
347 struct kvm_vmx {
348 	struct kvm kvm;
349 
350 	unsigned int tss_addr;
351 	bool ept_identity_pagetable_done;
352 	gpa_t ept_identity_map_addr;
353 
354 	enum ept_pointers_status ept_pointers_match;
355 	spinlock_t ept_pointer_lock;
356 };
357 
358 #define NR_AUTOLOAD_MSRS 8
359 
360 struct vmcs_hdr {
361 	u32 revision_id:31;
362 	u32 shadow_vmcs:1;
363 };
364 
365 struct vmcs {
366 	struct vmcs_hdr hdr;
367 	u32 abort;
368 	char data[0];
369 };
370 
371 /*
372  * vmcs_host_state tracks registers that are loaded from the VMCS on VMEXIT
373  * and whose values change infrequently, but are not constant.  I.e. this is
374  * used as a write-through cache of the corresponding VMCS fields.
375  */
376 struct vmcs_host_state {
377 	unsigned long cr3;	/* May not match real cr3 */
378 	unsigned long cr4;	/* May not match real cr4 */
379 	unsigned long gs_base;
380 	unsigned long fs_base;
381 
382 	u16           fs_sel, gs_sel, ldt_sel;
383 #ifdef CONFIG_X86_64
384 	u16           ds_sel, es_sel;
385 #endif
386 };
387 
388 /*
389  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
390  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
391  * loaded on this CPU (so we can clear them if the CPU goes down).
392  */
393 struct loaded_vmcs {
394 	struct vmcs *vmcs;
395 	struct vmcs *shadow_vmcs;
396 	int cpu;
397 	bool launched;
398 	bool nmi_known_unmasked;
399 	bool hv_timer_armed;
400 	/* Support for vnmi-less CPUs */
401 	int soft_vnmi_blocked;
402 	ktime_t entry_time;
403 	s64 vnmi_blocked_time;
404 	unsigned long *msr_bitmap;
405 	struct list_head loaded_vmcss_on_cpu_link;
406 	struct vmcs_host_state host_state;
407 };
408 
409 struct shared_msr_entry {
410 	unsigned index;
411 	u64 data;
412 	u64 mask;
413 };
414 
415 /*
416  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
417  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
418  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
419  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
420  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
421  * More than one of these structures may exist, if L1 runs multiple L2 guests.
422  * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
423  * underlying hardware which will be used to run L2.
424  * This structure is packed to ensure that its layout is identical across
425  * machines (necessary for live migration).
426  *
427  * IMPORTANT: Changing the layout of existing fields in this structure
428  * will break save/restore compatibility with older kvm releases. When
429  * adding new fields, either use space in the reserved padding* arrays
430  * or add the new fields to the end of the structure.
431  */
432 typedef u64 natural_width;
433 struct __packed vmcs12 {
434 	/* According to the Intel spec, a VMCS region must start with the
435 	 * following two fields. Then follow implementation-specific data.
436 	 */
437 	struct vmcs_hdr hdr;
438 	u32 abort;
439 
440 	u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
441 	u32 padding[7]; /* room for future expansion */
442 
443 	u64 io_bitmap_a;
444 	u64 io_bitmap_b;
445 	u64 msr_bitmap;
446 	u64 vm_exit_msr_store_addr;
447 	u64 vm_exit_msr_load_addr;
448 	u64 vm_entry_msr_load_addr;
449 	u64 tsc_offset;
450 	u64 virtual_apic_page_addr;
451 	u64 apic_access_addr;
452 	u64 posted_intr_desc_addr;
453 	u64 ept_pointer;
454 	u64 eoi_exit_bitmap0;
455 	u64 eoi_exit_bitmap1;
456 	u64 eoi_exit_bitmap2;
457 	u64 eoi_exit_bitmap3;
458 	u64 xss_exit_bitmap;
459 	u64 guest_physical_address;
460 	u64 vmcs_link_pointer;
461 	u64 guest_ia32_debugctl;
462 	u64 guest_ia32_pat;
463 	u64 guest_ia32_efer;
464 	u64 guest_ia32_perf_global_ctrl;
465 	u64 guest_pdptr0;
466 	u64 guest_pdptr1;
467 	u64 guest_pdptr2;
468 	u64 guest_pdptr3;
469 	u64 guest_bndcfgs;
470 	u64 host_ia32_pat;
471 	u64 host_ia32_efer;
472 	u64 host_ia32_perf_global_ctrl;
473 	u64 vmread_bitmap;
474 	u64 vmwrite_bitmap;
475 	u64 vm_function_control;
476 	u64 eptp_list_address;
477 	u64 pml_address;
478 	u64 padding64[3]; /* room for future expansion */
479 	/*
480 	 * To allow migration of L1 (complete with its L2 guests) between
481 	 * machines of different natural widths (32 or 64 bit), we cannot have
482 	 * unsigned long fields with no explict size. We use u64 (aliased
483 	 * natural_width) instead. Luckily, x86 is little-endian.
484 	 */
485 	natural_width cr0_guest_host_mask;
486 	natural_width cr4_guest_host_mask;
487 	natural_width cr0_read_shadow;
488 	natural_width cr4_read_shadow;
489 	natural_width cr3_target_value0;
490 	natural_width cr3_target_value1;
491 	natural_width cr3_target_value2;
492 	natural_width cr3_target_value3;
493 	natural_width exit_qualification;
494 	natural_width guest_linear_address;
495 	natural_width guest_cr0;
496 	natural_width guest_cr3;
497 	natural_width guest_cr4;
498 	natural_width guest_es_base;
499 	natural_width guest_cs_base;
500 	natural_width guest_ss_base;
501 	natural_width guest_ds_base;
502 	natural_width guest_fs_base;
503 	natural_width guest_gs_base;
504 	natural_width guest_ldtr_base;
505 	natural_width guest_tr_base;
506 	natural_width guest_gdtr_base;
507 	natural_width guest_idtr_base;
508 	natural_width guest_dr7;
509 	natural_width guest_rsp;
510 	natural_width guest_rip;
511 	natural_width guest_rflags;
512 	natural_width guest_pending_dbg_exceptions;
513 	natural_width guest_sysenter_esp;
514 	natural_width guest_sysenter_eip;
515 	natural_width host_cr0;
516 	natural_width host_cr3;
517 	natural_width host_cr4;
518 	natural_width host_fs_base;
519 	natural_width host_gs_base;
520 	natural_width host_tr_base;
521 	natural_width host_gdtr_base;
522 	natural_width host_idtr_base;
523 	natural_width host_ia32_sysenter_esp;
524 	natural_width host_ia32_sysenter_eip;
525 	natural_width host_rsp;
526 	natural_width host_rip;
527 	natural_width paddingl[8]; /* room for future expansion */
528 	u32 pin_based_vm_exec_control;
529 	u32 cpu_based_vm_exec_control;
530 	u32 exception_bitmap;
531 	u32 page_fault_error_code_mask;
532 	u32 page_fault_error_code_match;
533 	u32 cr3_target_count;
534 	u32 vm_exit_controls;
535 	u32 vm_exit_msr_store_count;
536 	u32 vm_exit_msr_load_count;
537 	u32 vm_entry_controls;
538 	u32 vm_entry_msr_load_count;
539 	u32 vm_entry_intr_info_field;
540 	u32 vm_entry_exception_error_code;
541 	u32 vm_entry_instruction_len;
542 	u32 tpr_threshold;
543 	u32 secondary_vm_exec_control;
544 	u32 vm_instruction_error;
545 	u32 vm_exit_reason;
546 	u32 vm_exit_intr_info;
547 	u32 vm_exit_intr_error_code;
548 	u32 idt_vectoring_info_field;
549 	u32 idt_vectoring_error_code;
550 	u32 vm_exit_instruction_len;
551 	u32 vmx_instruction_info;
552 	u32 guest_es_limit;
553 	u32 guest_cs_limit;
554 	u32 guest_ss_limit;
555 	u32 guest_ds_limit;
556 	u32 guest_fs_limit;
557 	u32 guest_gs_limit;
558 	u32 guest_ldtr_limit;
559 	u32 guest_tr_limit;
560 	u32 guest_gdtr_limit;
561 	u32 guest_idtr_limit;
562 	u32 guest_es_ar_bytes;
563 	u32 guest_cs_ar_bytes;
564 	u32 guest_ss_ar_bytes;
565 	u32 guest_ds_ar_bytes;
566 	u32 guest_fs_ar_bytes;
567 	u32 guest_gs_ar_bytes;
568 	u32 guest_ldtr_ar_bytes;
569 	u32 guest_tr_ar_bytes;
570 	u32 guest_interruptibility_info;
571 	u32 guest_activity_state;
572 	u32 guest_sysenter_cs;
573 	u32 host_ia32_sysenter_cs;
574 	u32 vmx_preemption_timer_value;
575 	u32 padding32[7]; /* room for future expansion */
576 	u16 virtual_processor_id;
577 	u16 posted_intr_nv;
578 	u16 guest_es_selector;
579 	u16 guest_cs_selector;
580 	u16 guest_ss_selector;
581 	u16 guest_ds_selector;
582 	u16 guest_fs_selector;
583 	u16 guest_gs_selector;
584 	u16 guest_ldtr_selector;
585 	u16 guest_tr_selector;
586 	u16 guest_intr_status;
587 	u16 host_es_selector;
588 	u16 host_cs_selector;
589 	u16 host_ss_selector;
590 	u16 host_ds_selector;
591 	u16 host_fs_selector;
592 	u16 host_gs_selector;
593 	u16 host_tr_selector;
594 	u16 guest_pml_index;
595 };
596 
597 /*
598  * For save/restore compatibility, the vmcs12 field offsets must not change.
599  */
600 #define CHECK_OFFSET(field, loc)				\
601 	BUILD_BUG_ON_MSG(offsetof(struct vmcs12, field) != (loc),	\
602 		"Offset of " #field " in struct vmcs12 has changed.")
603 
vmx_check_vmcs12_offsets(void)604 static inline void vmx_check_vmcs12_offsets(void) {
605 	CHECK_OFFSET(hdr, 0);
606 	CHECK_OFFSET(abort, 4);
607 	CHECK_OFFSET(launch_state, 8);
608 	CHECK_OFFSET(io_bitmap_a, 40);
609 	CHECK_OFFSET(io_bitmap_b, 48);
610 	CHECK_OFFSET(msr_bitmap, 56);
611 	CHECK_OFFSET(vm_exit_msr_store_addr, 64);
612 	CHECK_OFFSET(vm_exit_msr_load_addr, 72);
613 	CHECK_OFFSET(vm_entry_msr_load_addr, 80);
614 	CHECK_OFFSET(tsc_offset, 88);
615 	CHECK_OFFSET(virtual_apic_page_addr, 96);
616 	CHECK_OFFSET(apic_access_addr, 104);
617 	CHECK_OFFSET(posted_intr_desc_addr, 112);
618 	CHECK_OFFSET(ept_pointer, 120);
619 	CHECK_OFFSET(eoi_exit_bitmap0, 128);
620 	CHECK_OFFSET(eoi_exit_bitmap1, 136);
621 	CHECK_OFFSET(eoi_exit_bitmap2, 144);
622 	CHECK_OFFSET(eoi_exit_bitmap3, 152);
623 	CHECK_OFFSET(xss_exit_bitmap, 160);
624 	CHECK_OFFSET(guest_physical_address, 168);
625 	CHECK_OFFSET(vmcs_link_pointer, 176);
626 	CHECK_OFFSET(guest_ia32_debugctl, 184);
627 	CHECK_OFFSET(guest_ia32_pat, 192);
628 	CHECK_OFFSET(guest_ia32_efer, 200);
629 	CHECK_OFFSET(guest_ia32_perf_global_ctrl, 208);
630 	CHECK_OFFSET(guest_pdptr0, 216);
631 	CHECK_OFFSET(guest_pdptr1, 224);
632 	CHECK_OFFSET(guest_pdptr2, 232);
633 	CHECK_OFFSET(guest_pdptr3, 240);
634 	CHECK_OFFSET(guest_bndcfgs, 248);
635 	CHECK_OFFSET(host_ia32_pat, 256);
636 	CHECK_OFFSET(host_ia32_efer, 264);
637 	CHECK_OFFSET(host_ia32_perf_global_ctrl, 272);
638 	CHECK_OFFSET(vmread_bitmap, 280);
639 	CHECK_OFFSET(vmwrite_bitmap, 288);
640 	CHECK_OFFSET(vm_function_control, 296);
641 	CHECK_OFFSET(eptp_list_address, 304);
642 	CHECK_OFFSET(pml_address, 312);
643 	CHECK_OFFSET(cr0_guest_host_mask, 344);
644 	CHECK_OFFSET(cr4_guest_host_mask, 352);
645 	CHECK_OFFSET(cr0_read_shadow, 360);
646 	CHECK_OFFSET(cr4_read_shadow, 368);
647 	CHECK_OFFSET(cr3_target_value0, 376);
648 	CHECK_OFFSET(cr3_target_value1, 384);
649 	CHECK_OFFSET(cr3_target_value2, 392);
650 	CHECK_OFFSET(cr3_target_value3, 400);
651 	CHECK_OFFSET(exit_qualification, 408);
652 	CHECK_OFFSET(guest_linear_address, 416);
653 	CHECK_OFFSET(guest_cr0, 424);
654 	CHECK_OFFSET(guest_cr3, 432);
655 	CHECK_OFFSET(guest_cr4, 440);
656 	CHECK_OFFSET(guest_es_base, 448);
657 	CHECK_OFFSET(guest_cs_base, 456);
658 	CHECK_OFFSET(guest_ss_base, 464);
659 	CHECK_OFFSET(guest_ds_base, 472);
660 	CHECK_OFFSET(guest_fs_base, 480);
661 	CHECK_OFFSET(guest_gs_base, 488);
662 	CHECK_OFFSET(guest_ldtr_base, 496);
663 	CHECK_OFFSET(guest_tr_base, 504);
664 	CHECK_OFFSET(guest_gdtr_base, 512);
665 	CHECK_OFFSET(guest_idtr_base, 520);
666 	CHECK_OFFSET(guest_dr7, 528);
667 	CHECK_OFFSET(guest_rsp, 536);
668 	CHECK_OFFSET(guest_rip, 544);
669 	CHECK_OFFSET(guest_rflags, 552);
670 	CHECK_OFFSET(guest_pending_dbg_exceptions, 560);
671 	CHECK_OFFSET(guest_sysenter_esp, 568);
672 	CHECK_OFFSET(guest_sysenter_eip, 576);
673 	CHECK_OFFSET(host_cr0, 584);
674 	CHECK_OFFSET(host_cr3, 592);
675 	CHECK_OFFSET(host_cr4, 600);
676 	CHECK_OFFSET(host_fs_base, 608);
677 	CHECK_OFFSET(host_gs_base, 616);
678 	CHECK_OFFSET(host_tr_base, 624);
679 	CHECK_OFFSET(host_gdtr_base, 632);
680 	CHECK_OFFSET(host_idtr_base, 640);
681 	CHECK_OFFSET(host_ia32_sysenter_esp, 648);
682 	CHECK_OFFSET(host_ia32_sysenter_eip, 656);
683 	CHECK_OFFSET(host_rsp, 664);
684 	CHECK_OFFSET(host_rip, 672);
685 	CHECK_OFFSET(pin_based_vm_exec_control, 744);
686 	CHECK_OFFSET(cpu_based_vm_exec_control, 748);
687 	CHECK_OFFSET(exception_bitmap, 752);
688 	CHECK_OFFSET(page_fault_error_code_mask, 756);
689 	CHECK_OFFSET(page_fault_error_code_match, 760);
690 	CHECK_OFFSET(cr3_target_count, 764);
691 	CHECK_OFFSET(vm_exit_controls, 768);
692 	CHECK_OFFSET(vm_exit_msr_store_count, 772);
693 	CHECK_OFFSET(vm_exit_msr_load_count, 776);
694 	CHECK_OFFSET(vm_entry_controls, 780);
695 	CHECK_OFFSET(vm_entry_msr_load_count, 784);
696 	CHECK_OFFSET(vm_entry_intr_info_field, 788);
697 	CHECK_OFFSET(vm_entry_exception_error_code, 792);
698 	CHECK_OFFSET(vm_entry_instruction_len, 796);
699 	CHECK_OFFSET(tpr_threshold, 800);
700 	CHECK_OFFSET(secondary_vm_exec_control, 804);
701 	CHECK_OFFSET(vm_instruction_error, 808);
702 	CHECK_OFFSET(vm_exit_reason, 812);
703 	CHECK_OFFSET(vm_exit_intr_info, 816);
704 	CHECK_OFFSET(vm_exit_intr_error_code, 820);
705 	CHECK_OFFSET(idt_vectoring_info_field, 824);
706 	CHECK_OFFSET(idt_vectoring_error_code, 828);
707 	CHECK_OFFSET(vm_exit_instruction_len, 832);
708 	CHECK_OFFSET(vmx_instruction_info, 836);
709 	CHECK_OFFSET(guest_es_limit, 840);
710 	CHECK_OFFSET(guest_cs_limit, 844);
711 	CHECK_OFFSET(guest_ss_limit, 848);
712 	CHECK_OFFSET(guest_ds_limit, 852);
713 	CHECK_OFFSET(guest_fs_limit, 856);
714 	CHECK_OFFSET(guest_gs_limit, 860);
715 	CHECK_OFFSET(guest_ldtr_limit, 864);
716 	CHECK_OFFSET(guest_tr_limit, 868);
717 	CHECK_OFFSET(guest_gdtr_limit, 872);
718 	CHECK_OFFSET(guest_idtr_limit, 876);
719 	CHECK_OFFSET(guest_es_ar_bytes, 880);
720 	CHECK_OFFSET(guest_cs_ar_bytes, 884);
721 	CHECK_OFFSET(guest_ss_ar_bytes, 888);
722 	CHECK_OFFSET(guest_ds_ar_bytes, 892);
723 	CHECK_OFFSET(guest_fs_ar_bytes, 896);
724 	CHECK_OFFSET(guest_gs_ar_bytes, 900);
725 	CHECK_OFFSET(guest_ldtr_ar_bytes, 904);
726 	CHECK_OFFSET(guest_tr_ar_bytes, 908);
727 	CHECK_OFFSET(guest_interruptibility_info, 912);
728 	CHECK_OFFSET(guest_activity_state, 916);
729 	CHECK_OFFSET(guest_sysenter_cs, 920);
730 	CHECK_OFFSET(host_ia32_sysenter_cs, 924);
731 	CHECK_OFFSET(vmx_preemption_timer_value, 928);
732 	CHECK_OFFSET(virtual_processor_id, 960);
733 	CHECK_OFFSET(posted_intr_nv, 962);
734 	CHECK_OFFSET(guest_es_selector, 964);
735 	CHECK_OFFSET(guest_cs_selector, 966);
736 	CHECK_OFFSET(guest_ss_selector, 968);
737 	CHECK_OFFSET(guest_ds_selector, 970);
738 	CHECK_OFFSET(guest_fs_selector, 972);
739 	CHECK_OFFSET(guest_gs_selector, 974);
740 	CHECK_OFFSET(guest_ldtr_selector, 976);
741 	CHECK_OFFSET(guest_tr_selector, 978);
742 	CHECK_OFFSET(guest_intr_status, 980);
743 	CHECK_OFFSET(host_es_selector, 982);
744 	CHECK_OFFSET(host_cs_selector, 984);
745 	CHECK_OFFSET(host_ss_selector, 986);
746 	CHECK_OFFSET(host_ds_selector, 988);
747 	CHECK_OFFSET(host_fs_selector, 990);
748 	CHECK_OFFSET(host_gs_selector, 992);
749 	CHECK_OFFSET(host_tr_selector, 994);
750 	CHECK_OFFSET(guest_pml_index, 996);
751 }
752 
753 /*
754  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
755  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
756  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
757  *
758  * IMPORTANT: Changing this value will break save/restore compatibility with
759  * older kvm releases.
760  */
761 #define VMCS12_REVISION 0x11e57ed0
762 
763 /*
764  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
765  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
766  * current implementation, 4K are reserved to avoid future complications.
767  */
768 #define VMCS12_SIZE 0x1000
769 
770 /*
771  * VMCS12_MAX_FIELD_INDEX is the highest index value used in any
772  * supported VMCS12 field encoding.
773  */
774 #define VMCS12_MAX_FIELD_INDEX 0x17
775 
776 struct nested_vmx_msrs {
777 	/*
778 	 * We only store the "true" versions of the VMX capability MSRs. We
779 	 * generate the "non-true" versions by setting the must-be-1 bits
780 	 * according to the SDM.
781 	 */
782 	u32 procbased_ctls_low;
783 	u32 procbased_ctls_high;
784 	u32 secondary_ctls_low;
785 	u32 secondary_ctls_high;
786 	u32 pinbased_ctls_low;
787 	u32 pinbased_ctls_high;
788 	u32 exit_ctls_low;
789 	u32 exit_ctls_high;
790 	u32 entry_ctls_low;
791 	u32 entry_ctls_high;
792 	u32 misc_low;
793 	u32 misc_high;
794 	u32 ept_caps;
795 	u32 vpid_caps;
796 	u64 basic;
797 	u64 cr0_fixed0;
798 	u64 cr0_fixed1;
799 	u64 cr4_fixed0;
800 	u64 cr4_fixed1;
801 	u64 vmcs_enum;
802 	u64 vmfunc_controls;
803 };
804 
805 /*
806  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
807  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
808  */
809 struct nested_vmx {
810 	/* Has the level1 guest done vmxon? */
811 	bool vmxon;
812 	gpa_t vmxon_ptr;
813 	bool pml_full;
814 
815 	/* The guest-physical address of the current VMCS L1 keeps for L2 */
816 	gpa_t current_vmptr;
817 	/*
818 	 * Cache of the guest's VMCS, existing outside of guest memory.
819 	 * Loaded from guest memory during VMPTRLD. Flushed to guest
820 	 * memory during VMCLEAR and VMPTRLD.
821 	 */
822 	struct vmcs12 *cached_vmcs12;
823 	/*
824 	 * Cache of the guest's shadow VMCS, existing outside of guest
825 	 * memory. Loaded from guest memory during VM entry. Flushed
826 	 * to guest memory during VM exit.
827 	 */
828 	struct vmcs12 *cached_shadow_vmcs12;
829 	/*
830 	 * Indicates if the shadow vmcs must be updated with the
831 	 * data hold by vmcs12
832 	 */
833 	bool sync_shadow_vmcs;
834 	bool dirty_vmcs12;
835 
836 	bool change_vmcs01_virtual_apic_mode;
837 
838 	/* L2 must run next, and mustn't decide to exit to L1. */
839 	bool nested_run_pending;
840 
841 	struct loaded_vmcs vmcs02;
842 
843 	/*
844 	 * Guest pages referred to in the vmcs02 with host-physical
845 	 * pointers, so we must keep them pinned while L2 runs.
846 	 */
847 	struct page *apic_access_page;
848 	struct page *virtual_apic_page;
849 	struct page *pi_desc_page;
850 	struct pi_desc *pi_desc;
851 	bool pi_pending;
852 	u16 posted_intr_nv;
853 
854 	struct hrtimer preemption_timer;
855 	bool preemption_timer_expired;
856 
857 	/* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
858 	u64 vmcs01_debugctl;
859 	u64 vmcs01_guest_bndcfgs;
860 
861 	u16 vpid02;
862 	u16 last_vpid;
863 
864 	struct nested_vmx_msrs msrs;
865 
866 	/* SMM related state */
867 	struct {
868 		/* in VMX operation on SMM entry? */
869 		bool vmxon;
870 		/* in guest mode on SMM entry? */
871 		bool guest_mode;
872 	} smm;
873 };
874 
875 #define POSTED_INTR_ON  0
876 #define POSTED_INTR_SN  1
877 
878 /* Posted-Interrupt Descriptor */
879 struct pi_desc {
880 	u32 pir[8];     /* Posted interrupt requested */
881 	union {
882 		struct {
883 				/* bit 256 - Outstanding Notification */
884 			u16	on	: 1,
885 				/* bit 257 - Suppress Notification */
886 				sn	: 1,
887 				/* bit 271:258 - Reserved */
888 				rsvd_1	: 14;
889 				/* bit 279:272 - Notification Vector */
890 			u8	nv;
891 				/* bit 287:280 - Reserved */
892 			u8	rsvd_2;
893 				/* bit 319:288 - Notification Destination */
894 			u32	ndst;
895 		};
896 		u64 control;
897 	};
898 	u32 rsvd[6];
899 } __aligned(64);
900 
pi_test_and_set_on(struct pi_desc * pi_desc)901 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
902 {
903 	return test_and_set_bit(POSTED_INTR_ON,
904 			(unsigned long *)&pi_desc->control);
905 }
906 
pi_test_and_clear_on(struct pi_desc * pi_desc)907 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
908 {
909 	return test_and_clear_bit(POSTED_INTR_ON,
910 			(unsigned long *)&pi_desc->control);
911 }
912 
pi_test_and_set_pir(int vector,struct pi_desc * pi_desc)913 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
914 {
915 	return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
916 }
917 
pi_clear_sn(struct pi_desc * pi_desc)918 static inline void pi_clear_sn(struct pi_desc *pi_desc)
919 {
920 	return clear_bit(POSTED_INTR_SN,
921 			(unsigned long *)&pi_desc->control);
922 }
923 
pi_set_sn(struct pi_desc * pi_desc)924 static inline void pi_set_sn(struct pi_desc *pi_desc)
925 {
926 	return set_bit(POSTED_INTR_SN,
927 			(unsigned long *)&pi_desc->control);
928 }
929 
pi_clear_on(struct pi_desc * pi_desc)930 static inline void pi_clear_on(struct pi_desc *pi_desc)
931 {
932 	clear_bit(POSTED_INTR_ON,
933   		  (unsigned long *)&pi_desc->control);
934 }
935 
pi_test_on(struct pi_desc * pi_desc)936 static inline int pi_test_on(struct pi_desc *pi_desc)
937 {
938 	return test_bit(POSTED_INTR_ON,
939 			(unsigned long *)&pi_desc->control);
940 }
941 
pi_test_sn(struct pi_desc * pi_desc)942 static inline int pi_test_sn(struct pi_desc *pi_desc)
943 {
944 	return test_bit(POSTED_INTR_SN,
945 			(unsigned long *)&pi_desc->control);
946 }
947 
948 struct vmx_msrs {
949 	unsigned int		nr;
950 	struct vmx_msr_entry	val[NR_AUTOLOAD_MSRS];
951 };
952 
953 struct vcpu_vmx {
954 	struct kvm_vcpu       vcpu;
955 	unsigned long         host_rsp;
956 	u8                    fail;
957 	u8		      msr_bitmap_mode;
958 	u32                   exit_intr_info;
959 	u32                   idt_vectoring_info;
960 	ulong                 rflags;
961 	struct shared_msr_entry *guest_msrs;
962 	int                   nmsrs;
963 	int                   save_nmsrs;
964 	unsigned long	      host_idt_base;
965 #ifdef CONFIG_X86_64
966 	u64 		      msr_host_kernel_gs_base;
967 	u64 		      msr_guest_kernel_gs_base;
968 #endif
969 
970 	u64 		      arch_capabilities;
971 	u64 		      spec_ctrl;
972 
973 	u32 vm_entry_controls_shadow;
974 	u32 vm_exit_controls_shadow;
975 	u32 secondary_exec_control;
976 
977 	/*
978 	 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
979 	 * non-nested (L1) guest, it always points to vmcs01. For a nested
980 	 * guest (L2), it points to a different VMCS.  loaded_cpu_state points
981 	 * to the VMCS whose state is loaded into the CPU registers that only
982 	 * need to be switched when transitioning to/from the kernel; a NULL
983 	 * value indicates that host state is loaded.
984 	 */
985 	struct loaded_vmcs    vmcs01;
986 	struct loaded_vmcs   *loaded_vmcs;
987 	struct loaded_vmcs   *loaded_cpu_state;
988 	bool                  __launched; /* temporary, used in vmx_vcpu_run */
989 	struct msr_autoload {
990 		struct vmx_msrs guest;
991 		struct vmx_msrs host;
992 	} msr_autoload;
993 
994 	struct {
995 		int vm86_active;
996 		ulong save_rflags;
997 		struct kvm_segment segs[8];
998 	} rmode;
999 	struct {
1000 		u32 bitmask; /* 4 bits per segment (1 bit per field) */
1001 		struct kvm_save_segment {
1002 			u16 selector;
1003 			unsigned long base;
1004 			u32 limit;
1005 			u32 ar;
1006 		} seg[8];
1007 	} segment_cache;
1008 	int vpid;
1009 	bool emulation_required;
1010 
1011 	u32 exit_reason;
1012 
1013 	/* Posted interrupt descriptor */
1014 	struct pi_desc pi_desc;
1015 
1016 	/* Support for a guest hypervisor (nested VMX) */
1017 	struct nested_vmx nested;
1018 
1019 	/* Dynamic PLE window. */
1020 	int ple_window;
1021 	bool ple_window_dirty;
1022 
1023 	bool req_immediate_exit;
1024 
1025 	/* Support for PML */
1026 #define PML_ENTITY_NUM		512
1027 	struct page *pml_pg;
1028 
1029 	/* apic deadline value in host tsc */
1030 	u64 hv_deadline_tsc;
1031 
1032 	u64 current_tsc_ratio;
1033 
1034 	u32 host_pkru;
1035 
1036 	unsigned long host_debugctlmsr;
1037 
1038 	/*
1039 	 * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
1040 	 * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
1041 	 * in msr_ia32_feature_control_valid_bits.
1042 	 */
1043 	u64 msr_ia32_feature_control;
1044 	u64 msr_ia32_feature_control_valid_bits;
1045 	u64 ept_pointer;
1046 };
1047 
1048 enum segment_cache_field {
1049 	SEG_FIELD_SEL = 0,
1050 	SEG_FIELD_BASE = 1,
1051 	SEG_FIELD_LIMIT = 2,
1052 	SEG_FIELD_AR = 3,
1053 
1054 	SEG_FIELD_NR = 4
1055 };
1056 
to_kvm_vmx(struct kvm * kvm)1057 static inline struct kvm_vmx *to_kvm_vmx(struct kvm *kvm)
1058 {
1059 	return container_of(kvm, struct kvm_vmx, kvm);
1060 }
1061 
to_vmx(struct kvm_vcpu * vcpu)1062 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
1063 {
1064 	return container_of(vcpu, struct vcpu_vmx, vcpu);
1065 }
1066 
vcpu_to_pi_desc(struct kvm_vcpu * vcpu)1067 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
1068 {
1069 	return &(to_vmx(vcpu)->pi_desc);
1070 }
1071 
1072 #define ROL16(val, n) ((u16)(((u16)(val) << (n)) | ((u16)(val) >> (16 - (n)))))
1073 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
1074 #define FIELD(number, name)	[ROL16(number, 6)] = VMCS12_OFFSET(name)
1075 #define FIELD64(number, name)						\
1076 	FIELD(number, name),						\
1077 	[ROL16(number##_HIGH, 6)] = VMCS12_OFFSET(name) + sizeof(u32)
1078 
1079 
1080 static u16 shadow_read_only_fields[] = {
1081 #define SHADOW_FIELD_RO(x) x,
1082 #include "vmx_shadow_fields.h"
1083 };
1084 static int max_shadow_read_only_fields =
1085 	ARRAY_SIZE(shadow_read_only_fields);
1086 
1087 static u16 shadow_read_write_fields[] = {
1088 #define SHADOW_FIELD_RW(x) x,
1089 #include "vmx_shadow_fields.h"
1090 };
1091 static int max_shadow_read_write_fields =
1092 	ARRAY_SIZE(shadow_read_write_fields);
1093 
1094 static const unsigned short vmcs_field_to_offset_table[] = {
1095 	FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
1096 	FIELD(POSTED_INTR_NV, posted_intr_nv),
1097 	FIELD(GUEST_ES_SELECTOR, guest_es_selector),
1098 	FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
1099 	FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
1100 	FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
1101 	FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
1102 	FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
1103 	FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
1104 	FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
1105 	FIELD(GUEST_INTR_STATUS, guest_intr_status),
1106 	FIELD(GUEST_PML_INDEX, guest_pml_index),
1107 	FIELD(HOST_ES_SELECTOR, host_es_selector),
1108 	FIELD(HOST_CS_SELECTOR, host_cs_selector),
1109 	FIELD(HOST_SS_SELECTOR, host_ss_selector),
1110 	FIELD(HOST_DS_SELECTOR, host_ds_selector),
1111 	FIELD(HOST_FS_SELECTOR, host_fs_selector),
1112 	FIELD(HOST_GS_SELECTOR, host_gs_selector),
1113 	FIELD(HOST_TR_SELECTOR, host_tr_selector),
1114 	FIELD64(IO_BITMAP_A, io_bitmap_a),
1115 	FIELD64(IO_BITMAP_B, io_bitmap_b),
1116 	FIELD64(MSR_BITMAP, msr_bitmap),
1117 	FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
1118 	FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
1119 	FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
1120 	FIELD64(PML_ADDRESS, pml_address),
1121 	FIELD64(TSC_OFFSET, tsc_offset),
1122 	FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
1123 	FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
1124 	FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
1125 	FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
1126 	FIELD64(EPT_POINTER, ept_pointer),
1127 	FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
1128 	FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
1129 	FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
1130 	FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
1131 	FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
1132 	FIELD64(VMREAD_BITMAP, vmread_bitmap),
1133 	FIELD64(VMWRITE_BITMAP, vmwrite_bitmap),
1134 	FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
1135 	FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
1136 	FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
1137 	FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
1138 	FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
1139 	FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
1140 	FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
1141 	FIELD64(GUEST_PDPTR0, guest_pdptr0),
1142 	FIELD64(GUEST_PDPTR1, guest_pdptr1),
1143 	FIELD64(GUEST_PDPTR2, guest_pdptr2),
1144 	FIELD64(GUEST_PDPTR3, guest_pdptr3),
1145 	FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
1146 	FIELD64(HOST_IA32_PAT, host_ia32_pat),
1147 	FIELD64(HOST_IA32_EFER, host_ia32_efer),
1148 	FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
1149 	FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
1150 	FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
1151 	FIELD(EXCEPTION_BITMAP, exception_bitmap),
1152 	FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
1153 	FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
1154 	FIELD(CR3_TARGET_COUNT, cr3_target_count),
1155 	FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
1156 	FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
1157 	FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
1158 	FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
1159 	FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
1160 	FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
1161 	FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
1162 	FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
1163 	FIELD(TPR_THRESHOLD, tpr_threshold),
1164 	FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
1165 	FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
1166 	FIELD(VM_EXIT_REASON, vm_exit_reason),
1167 	FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
1168 	FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
1169 	FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
1170 	FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
1171 	FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
1172 	FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
1173 	FIELD(GUEST_ES_LIMIT, guest_es_limit),
1174 	FIELD(GUEST_CS_LIMIT, guest_cs_limit),
1175 	FIELD(GUEST_SS_LIMIT, guest_ss_limit),
1176 	FIELD(GUEST_DS_LIMIT, guest_ds_limit),
1177 	FIELD(GUEST_FS_LIMIT, guest_fs_limit),
1178 	FIELD(GUEST_GS_LIMIT, guest_gs_limit),
1179 	FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
1180 	FIELD(GUEST_TR_LIMIT, guest_tr_limit),
1181 	FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
1182 	FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
1183 	FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
1184 	FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
1185 	FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
1186 	FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
1187 	FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
1188 	FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
1189 	FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
1190 	FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
1191 	FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
1192 	FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
1193 	FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
1194 	FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
1195 	FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
1196 	FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
1197 	FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
1198 	FIELD(CR0_READ_SHADOW, cr0_read_shadow),
1199 	FIELD(CR4_READ_SHADOW, cr4_read_shadow),
1200 	FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
1201 	FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
1202 	FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
1203 	FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
1204 	FIELD(EXIT_QUALIFICATION, exit_qualification),
1205 	FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
1206 	FIELD(GUEST_CR0, guest_cr0),
1207 	FIELD(GUEST_CR3, guest_cr3),
1208 	FIELD(GUEST_CR4, guest_cr4),
1209 	FIELD(GUEST_ES_BASE, guest_es_base),
1210 	FIELD(GUEST_CS_BASE, guest_cs_base),
1211 	FIELD(GUEST_SS_BASE, guest_ss_base),
1212 	FIELD(GUEST_DS_BASE, guest_ds_base),
1213 	FIELD(GUEST_FS_BASE, guest_fs_base),
1214 	FIELD(GUEST_GS_BASE, guest_gs_base),
1215 	FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
1216 	FIELD(GUEST_TR_BASE, guest_tr_base),
1217 	FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
1218 	FIELD(GUEST_IDTR_BASE, guest_idtr_base),
1219 	FIELD(GUEST_DR7, guest_dr7),
1220 	FIELD(GUEST_RSP, guest_rsp),
1221 	FIELD(GUEST_RIP, guest_rip),
1222 	FIELD(GUEST_RFLAGS, guest_rflags),
1223 	FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
1224 	FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
1225 	FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
1226 	FIELD(HOST_CR0, host_cr0),
1227 	FIELD(HOST_CR3, host_cr3),
1228 	FIELD(HOST_CR4, host_cr4),
1229 	FIELD(HOST_FS_BASE, host_fs_base),
1230 	FIELD(HOST_GS_BASE, host_gs_base),
1231 	FIELD(HOST_TR_BASE, host_tr_base),
1232 	FIELD(HOST_GDTR_BASE, host_gdtr_base),
1233 	FIELD(HOST_IDTR_BASE, host_idtr_base),
1234 	FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
1235 	FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
1236 	FIELD(HOST_RSP, host_rsp),
1237 	FIELD(HOST_RIP, host_rip),
1238 };
1239 
vmcs_field_to_offset(unsigned long field)1240 static inline short vmcs_field_to_offset(unsigned long field)
1241 {
1242 	const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
1243 	unsigned short offset;
1244 	unsigned index;
1245 
1246 	if (field >> 15)
1247 		return -ENOENT;
1248 
1249 	index = ROL16(field, 6);
1250 	if (index >= size)
1251 		return -ENOENT;
1252 
1253 	index = array_index_nospec(index, size);
1254 	offset = vmcs_field_to_offset_table[index];
1255 	if (offset == 0)
1256 		return -ENOENT;
1257 	return offset;
1258 }
1259 
get_vmcs12(struct kvm_vcpu * vcpu)1260 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
1261 {
1262 	return to_vmx(vcpu)->nested.cached_vmcs12;
1263 }
1264 
get_shadow_vmcs12(struct kvm_vcpu * vcpu)1265 static inline struct vmcs12 *get_shadow_vmcs12(struct kvm_vcpu *vcpu)
1266 {
1267 	return to_vmx(vcpu)->nested.cached_shadow_vmcs12;
1268 }
1269 
1270 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
1271 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
1272 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
1273 static bool vmx_xsaves_supported(void);
1274 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1275 			    struct kvm_segment *var, int seg);
1276 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1277 			    struct kvm_segment *var, int seg);
1278 static bool guest_state_valid(struct kvm_vcpu *vcpu);
1279 static u32 vmx_segment_access_rights(struct kvm_segment *var);
1280 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
1281 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
1282 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
1283 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
1284 					    u16 error_code);
1285 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
1286 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
1287 							  u32 msr, int type);
1288 
1289 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
1290 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
1291 /*
1292  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
1293  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
1294  */
1295 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
1296 
1297 /*
1298  * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
1299  * can find which vCPU should be waken up.
1300  */
1301 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
1302 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
1303 
1304 enum {
1305 	VMX_VMREAD_BITMAP,
1306 	VMX_VMWRITE_BITMAP,
1307 	VMX_BITMAP_NR
1308 };
1309 
1310 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
1311 
1312 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
1313 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
1314 
1315 static bool cpu_has_load_ia32_efer;
1316 static bool cpu_has_load_perf_global_ctrl;
1317 
1318 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
1319 static DEFINE_SPINLOCK(vmx_vpid_lock);
1320 
1321 static struct vmcs_config {
1322 	int size;
1323 	int order;
1324 	u32 basic_cap;
1325 	u32 revision_id;
1326 	u32 pin_based_exec_ctrl;
1327 	u32 cpu_based_exec_ctrl;
1328 	u32 cpu_based_2nd_exec_ctrl;
1329 	u32 vmexit_ctrl;
1330 	u32 vmentry_ctrl;
1331 	struct nested_vmx_msrs nested;
1332 } vmcs_config;
1333 
1334 static struct vmx_capability {
1335 	u32 ept;
1336 	u32 vpid;
1337 } vmx_capability;
1338 
1339 #define VMX_SEGMENT_FIELD(seg)					\
1340 	[VCPU_SREG_##seg] = {                                   \
1341 		.selector = GUEST_##seg##_SELECTOR,		\
1342 		.base = GUEST_##seg##_BASE,		   	\
1343 		.limit = GUEST_##seg##_LIMIT,		   	\
1344 		.ar_bytes = GUEST_##seg##_AR_BYTES,	   	\
1345 	}
1346 
1347 static const struct kvm_vmx_segment_field {
1348 	unsigned selector;
1349 	unsigned base;
1350 	unsigned limit;
1351 	unsigned ar_bytes;
1352 } kvm_vmx_segment_fields[] = {
1353 	VMX_SEGMENT_FIELD(CS),
1354 	VMX_SEGMENT_FIELD(DS),
1355 	VMX_SEGMENT_FIELD(ES),
1356 	VMX_SEGMENT_FIELD(FS),
1357 	VMX_SEGMENT_FIELD(GS),
1358 	VMX_SEGMENT_FIELD(SS),
1359 	VMX_SEGMENT_FIELD(TR),
1360 	VMX_SEGMENT_FIELD(LDTR),
1361 };
1362 
1363 static u64 host_efer;
1364 
1365 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1366 
1367 /*
1368  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1369  * away by decrementing the array size.
1370  */
1371 static const u32 vmx_msr_index[] = {
1372 #ifdef CONFIG_X86_64
1373 	MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1374 #endif
1375 	MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1376 };
1377 
1378 DEFINE_STATIC_KEY_FALSE(enable_evmcs);
1379 
1380 #define current_evmcs ((struct hv_enlightened_vmcs *)this_cpu_read(current_vmcs))
1381 
1382 #define KVM_EVMCS_VERSION 1
1383 
1384 #if IS_ENABLED(CONFIG_HYPERV)
1385 static bool __read_mostly enlightened_vmcs = true;
1386 module_param(enlightened_vmcs, bool, 0444);
1387 
evmcs_write64(unsigned long field,u64 value)1388 static inline void evmcs_write64(unsigned long field, u64 value)
1389 {
1390 	u16 clean_field;
1391 	int offset = get_evmcs_offset(field, &clean_field);
1392 
1393 	if (offset < 0)
1394 		return;
1395 
1396 	*(u64 *)((char *)current_evmcs + offset) = value;
1397 
1398 	current_evmcs->hv_clean_fields &= ~clean_field;
1399 }
1400 
evmcs_write32(unsigned long field,u32 value)1401 static inline void evmcs_write32(unsigned long field, u32 value)
1402 {
1403 	u16 clean_field;
1404 	int offset = get_evmcs_offset(field, &clean_field);
1405 
1406 	if (offset < 0)
1407 		return;
1408 
1409 	*(u32 *)((char *)current_evmcs + offset) = value;
1410 	current_evmcs->hv_clean_fields &= ~clean_field;
1411 }
1412 
evmcs_write16(unsigned long field,u16 value)1413 static inline void evmcs_write16(unsigned long field, u16 value)
1414 {
1415 	u16 clean_field;
1416 	int offset = get_evmcs_offset(field, &clean_field);
1417 
1418 	if (offset < 0)
1419 		return;
1420 
1421 	*(u16 *)((char *)current_evmcs + offset) = value;
1422 	current_evmcs->hv_clean_fields &= ~clean_field;
1423 }
1424 
evmcs_read64(unsigned long field)1425 static inline u64 evmcs_read64(unsigned long field)
1426 {
1427 	int offset = get_evmcs_offset(field, NULL);
1428 
1429 	if (offset < 0)
1430 		return 0;
1431 
1432 	return *(u64 *)((char *)current_evmcs + offset);
1433 }
1434 
evmcs_read32(unsigned long field)1435 static inline u32 evmcs_read32(unsigned long field)
1436 {
1437 	int offset = get_evmcs_offset(field, NULL);
1438 
1439 	if (offset < 0)
1440 		return 0;
1441 
1442 	return *(u32 *)((char *)current_evmcs + offset);
1443 }
1444 
evmcs_read16(unsigned long field)1445 static inline u16 evmcs_read16(unsigned long field)
1446 {
1447 	int offset = get_evmcs_offset(field, NULL);
1448 
1449 	if (offset < 0)
1450 		return 0;
1451 
1452 	return *(u16 *)((char *)current_evmcs + offset);
1453 }
1454 
evmcs_touch_msr_bitmap(void)1455 static inline void evmcs_touch_msr_bitmap(void)
1456 {
1457 	if (unlikely(!current_evmcs))
1458 		return;
1459 
1460 	if (current_evmcs->hv_enlightenments_control.msr_bitmap)
1461 		current_evmcs->hv_clean_fields &=
1462 			~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
1463 }
1464 
evmcs_load(u64 phys_addr)1465 static void evmcs_load(u64 phys_addr)
1466 {
1467 	struct hv_vp_assist_page *vp_ap =
1468 		hv_get_vp_assist_page(smp_processor_id());
1469 
1470 	vp_ap->current_nested_vmcs = phys_addr;
1471 	vp_ap->enlighten_vmentry = 1;
1472 }
1473 
evmcs_sanitize_exec_ctrls(struct vmcs_config * vmcs_conf)1474 static void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf)
1475 {
1476 	/*
1477 	 * Enlightened VMCSv1 doesn't support these:
1478 	 *
1479 	 *	POSTED_INTR_NV                  = 0x00000002,
1480 	 *	GUEST_INTR_STATUS               = 0x00000810,
1481 	 *	APIC_ACCESS_ADDR		= 0x00002014,
1482 	 *	POSTED_INTR_DESC_ADDR           = 0x00002016,
1483 	 *	EOI_EXIT_BITMAP0                = 0x0000201c,
1484 	 *	EOI_EXIT_BITMAP1                = 0x0000201e,
1485 	 *	EOI_EXIT_BITMAP2                = 0x00002020,
1486 	 *	EOI_EXIT_BITMAP3                = 0x00002022,
1487 	 */
1488 	vmcs_conf->pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
1489 	vmcs_conf->cpu_based_2nd_exec_ctrl &=
1490 		~SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1491 	vmcs_conf->cpu_based_2nd_exec_ctrl &=
1492 		~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1493 	vmcs_conf->cpu_based_2nd_exec_ctrl &=
1494 		~SECONDARY_EXEC_APIC_REGISTER_VIRT;
1495 
1496 	/*
1497 	 *	GUEST_PML_INDEX			= 0x00000812,
1498 	 *	PML_ADDRESS			= 0x0000200e,
1499 	 */
1500 	vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_ENABLE_PML;
1501 
1502 	/*	VM_FUNCTION_CONTROL             = 0x00002018, */
1503 	vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_ENABLE_VMFUNC;
1504 
1505 	/*
1506 	 *	EPTP_LIST_ADDRESS               = 0x00002024,
1507 	 *	VMREAD_BITMAP                   = 0x00002026,
1508 	 *	VMWRITE_BITMAP                  = 0x00002028,
1509 	 */
1510 	vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_SHADOW_VMCS;
1511 
1512 	/*
1513 	 *	TSC_MULTIPLIER                  = 0x00002032,
1514 	 */
1515 	vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_TSC_SCALING;
1516 
1517 	/*
1518 	 *	PLE_GAP                         = 0x00004020,
1519 	 *	PLE_WINDOW                      = 0x00004022,
1520 	 */
1521 	vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1522 
1523 	/*
1524 	 *	VMX_PREEMPTION_TIMER_VALUE      = 0x0000482E,
1525 	 */
1526 	vmcs_conf->pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
1527 
1528 	/*
1529 	 *      GUEST_IA32_PERF_GLOBAL_CTRL     = 0x00002808,
1530 	 *      HOST_IA32_PERF_GLOBAL_CTRL      = 0x00002c04,
1531 	 */
1532 	vmcs_conf->vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
1533 	vmcs_conf->vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
1534 
1535 	/*
1536 	 * Currently unsupported in KVM:
1537 	 *	GUEST_IA32_RTIT_CTL		= 0x00002814,
1538 	 */
1539 }
1540 
1541 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
check_ept_pointer_match(struct kvm * kvm)1542 static void check_ept_pointer_match(struct kvm *kvm)
1543 {
1544 	struct kvm_vcpu *vcpu;
1545 	u64 tmp_eptp = INVALID_PAGE;
1546 	int i;
1547 
1548 	kvm_for_each_vcpu(i, vcpu, kvm) {
1549 		if (!VALID_PAGE(tmp_eptp)) {
1550 			tmp_eptp = to_vmx(vcpu)->ept_pointer;
1551 		} else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
1552 			to_kvm_vmx(kvm)->ept_pointers_match
1553 				= EPT_POINTERS_MISMATCH;
1554 			return;
1555 		}
1556 	}
1557 
1558 	to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
1559 }
1560 
vmx_hv_remote_flush_tlb(struct kvm * kvm)1561 static int vmx_hv_remote_flush_tlb(struct kvm *kvm)
1562 {
1563 	int ret;
1564 
1565 	spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1566 
1567 	if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
1568 		check_ept_pointer_match(kvm);
1569 
1570 	if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
1571 		ret = -ENOTSUPP;
1572 		goto out;
1573 	}
1574 
1575 	/*
1576 	 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs the address of the
1577 	 * base of EPT PML4 table, strip off EPT configuration information.
1578 	 */
1579 	ret = hyperv_flush_guest_mapping(
1580 			to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer & PAGE_MASK);
1581 
1582 out:
1583 	spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1584 	return ret;
1585 }
1586 #else /* !IS_ENABLED(CONFIG_HYPERV) */
evmcs_write64(unsigned long field,u64 value)1587 static inline void evmcs_write64(unsigned long field, u64 value) {}
evmcs_write32(unsigned long field,u32 value)1588 static inline void evmcs_write32(unsigned long field, u32 value) {}
evmcs_write16(unsigned long field,u16 value)1589 static inline void evmcs_write16(unsigned long field, u16 value) {}
evmcs_read64(unsigned long field)1590 static inline u64 evmcs_read64(unsigned long field) { return 0; }
evmcs_read32(unsigned long field)1591 static inline u32 evmcs_read32(unsigned long field) { return 0; }
evmcs_read16(unsigned long field)1592 static inline u16 evmcs_read16(unsigned long field) { return 0; }
evmcs_load(u64 phys_addr)1593 static inline void evmcs_load(u64 phys_addr) {}
evmcs_sanitize_exec_ctrls(struct vmcs_config * vmcs_conf)1594 static inline void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf) {}
evmcs_touch_msr_bitmap(void)1595 static inline void evmcs_touch_msr_bitmap(void) {}
1596 #endif /* IS_ENABLED(CONFIG_HYPERV) */
1597 
is_exception_n(u32 intr_info,u8 vector)1598 static inline bool is_exception_n(u32 intr_info, u8 vector)
1599 {
1600 	return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1601 			     INTR_INFO_VALID_MASK)) ==
1602 		(INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1603 }
1604 
is_debug(u32 intr_info)1605 static inline bool is_debug(u32 intr_info)
1606 {
1607 	return is_exception_n(intr_info, DB_VECTOR);
1608 }
1609 
is_breakpoint(u32 intr_info)1610 static inline bool is_breakpoint(u32 intr_info)
1611 {
1612 	return is_exception_n(intr_info, BP_VECTOR);
1613 }
1614 
is_page_fault(u32 intr_info)1615 static inline bool is_page_fault(u32 intr_info)
1616 {
1617 	return is_exception_n(intr_info, PF_VECTOR);
1618 }
1619 
is_no_device(u32 intr_info)1620 static inline bool is_no_device(u32 intr_info)
1621 {
1622 	return is_exception_n(intr_info, NM_VECTOR);
1623 }
1624 
is_invalid_opcode(u32 intr_info)1625 static inline bool is_invalid_opcode(u32 intr_info)
1626 {
1627 	return is_exception_n(intr_info, UD_VECTOR);
1628 }
1629 
is_gp_fault(u32 intr_info)1630 static inline bool is_gp_fault(u32 intr_info)
1631 {
1632 	return is_exception_n(intr_info, GP_VECTOR);
1633 }
1634 
is_external_interrupt(u32 intr_info)1635 static inline bool is_external_interrupt(u32 intr_info)
1636 {
1637 	return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1638 		== (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1639 }
1640 
is_machine_check(u32 intr_info)1641 static inline bool is_machine_check(u32 intr_info)
1642 {
1643 	return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1644 			     INTR_INFO_VALID_MASK)) ==
1645 		(INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1646 }
1647 
1648 /* Undocumented: icebp/int1 */
is_icebp(u32 intr_info)1649 static inline bool is_icebp(u32 intr_info)
1650 {
1651 	return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1652 		== (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1653 }
1654 
cpu_has_vmx_msr_bitmap(void)1655 static inline bool cpu_has_vmx_msr_bitmap(void)
1656 {
1657 	return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1658 }
1659 
cpu_has_vmx_tpr_shadow(void)1660 static inline bool cpu_has_vmx_tpr_shadow(void)
1661 {
1662 	return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1663 }
1664 
cpu_need_tpr_shadow(struct kvm_vcpu * vcpu)1665 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1666 {
1667 	return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1668 }
1669 
cpu_has_secondary_exec_ctrls(void)1670 static inline bool cpu_has_secondary_exec_ctrls(void)
1671 {
1672 	return vmcs_config.cpu_based_exec_ctrl &
1673 		CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1674 }
1675 
cpu_has_vmx_virtualize_apic_accesses(void)1676 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1677 {
1678 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1679 		SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1680 }
1681 
cpu_has_vmx_virtualize_x2apic_mode(void)1682 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1683 {
1684 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1685 		SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1686 }
1687 
cpu_has_vmx_apic_register_virt(void)1688 static inline bool cpu_has_vmx_apic_register_virt(void)
1689 {
1690 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1691 		SECONDARY_EXEC_APIC_REGISTER_VIRT;
1692 }
1693 
cpu_has_vmx_virtual_intr_delivery(void)1694 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1695 {
1696 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1697 		SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1698 }
1699 
cpu_has_vmx_encls_vmexit(void)1700 static inline bool cpu_has_vmx_encls_vmexit(void)
1701 {
1702 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1703 		SECONDARY_EXEC_ENCLS_EXITING;
1704 }
1705 
1706 /*
1707  * Comment's format: document - errata name - stepping - processor name.
1708  * Refer from
1709  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1710  */
1711 static u32 vmx_preemption_cpu_tfms[] = {
1712 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
1713 0x000206E6,
1714 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
1715 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1716 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1717 0x00020652,
1718 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1719 0x00020655,
1720 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
1721 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
1722 /*
1723  * 320767.pdf - AAP86  - B1 -
1724  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1725  */
1726 0x000106E5,
1727 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1728 0x000106A0,
1729 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1730 0x000106A1,
1731 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1732 0x000106A4,
1733  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1734  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1735  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1736 0x000106A5,
1737 };
1738 
cpu_has_broken_vmx_preemption_timer(void)1739 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1740 {
1741 	u32 eax = cpuid_eax(0x00000001), i;
1742 
1743 	/* Clear the reserved bits */
1744 	eax &= ~(0x3U << 14 | 0xfU << 28);
1745 	for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1746 		if (eax == vmx_preemption_cpu_tfms[i])
1747 			return true;
1748 
1749 	return false;
1750 }
1751 
cpu_has_vmx_preemption_timer(void)1752 static inline bool cpu_has_vmx_preemption_timer(void)
1753 {
1754 	return vmcs_config.pin_based_exec_ctrl &
1755 		PIN_BASED_VMX_PREEMPTION_TIMER;
1756 }
1757 
cpu_has_vmx_posted_intr(void)1758 static inline bool cpu_has_vmx_posted_intr(void)
1759 {
1760 	return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1761 		vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1762 }
1763 
cpu_has_vmx_apicv(void)1764 static inline bool cpu_has_vmx_apicv(void)
1765 {
1766 	return cpu_has_vmx_apic_register_virt() &&
1767 		cpu_has_vmx_virtual_intr_delivery() &&
1768 		cpu_has_vmx_posted_intr();
1769 }
1770 
cpu_has_vmx_flexpriority(void)1771 static inline bool cpu_has_vmx_flexpriority(void)
1772 {
1773 	return cpu_has_vmx_tpr_shadow() &&
1774 		cpu_has_vmx_virtualize_apic_accesses();
1775 }
1776 
cpu_has_vmx_ept_execute_only(void)1777 static inline bool cpu_has_vmx_ept_execute_only(void)
1778 {
1779 	return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1780 }
1781 
cpu_has_vmx_ept_2m_page(void)1782 static inline bool cpu_has_vmx_ept_2m_page(void)
1783 {
1784 	return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1785 }
1786 
cpu_has_vmx_ept_1g_page(void)1787 static inline bool cpu_has_vmx_ept_1g_page(void)
1788 {
1789 	return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1790 }
1791 
cpu_has_vmx_ept_4levels(void)1792 static inline bool cpu_has_vmx_ept_4levels(void)
1793 {
1794 	return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1795 }
1796 
cpu_has_vmx_ept_mt_wb(void)1797 static inline bool cpu_has_vmx_ept_mt_wb(void)
1798 {
1799 	return vmx_capability.ept & VMX_EPTP_WB_BIT;
1800 }
1801 
cpu_has_vmx_ept_5levels(void)1802 static inline bool cpu_has_vmx_ept_5levels(void)
1803 {
1804 	return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1805 }
1806 
cpu_has_vmx_ept_ad_bits(void)1807 static inline bool cpu_has_vmx_ept_ad_bits(void)
1808 {
1809 	return vmx_capability.ept & VMX_EPT_AD_BIT;
1810 }
1811 
cpu_has_vmx_invept_context(void)1812 static inline bool cpu_has_vmx_invept_context(void)
1813 {
1814 	return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1815 }
1816 
cpu_has_vmx_invept_global(void)1817 static inline bool cpu_has_vmx_invept_global(void)
1818 {
1819 	return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1820 }
1821 
cpu_has_vmx_invvpid_individual_addr(void)1822 static inline bool cpu_has_vmx_invvpid_individual_addr(void)
1823 {
1824 	return vmx_capability.vpid & VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT;
1825 }
1826 
cpu_has_vmx_invvpid_single(void)1827 static inline bool cpu_has_vmx_invvpid_single(void)
1828 {
1829 	return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1830 }
1831 
cpu_has_vmx_invvpid_global(void)1832 static inline bool cpu_has_vmx_invvpid_global(void)
1833 {
1834 	return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1835 }
1836 
cpu_has_vmx_invvpid(void)1837 static inline bool cpu_has_vmx_invvpid(void)
1838 {
1839 	return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1840 }
1841 
cpu_has_vmx_ept(void)1842 static inline bool cpu_has_vmx_ept(void)
1843 {
1844 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1845 		SECONDARY_EXEC_ENABLE_EPT;
1846 }
1847 
cpu_has_vmx_unrestricted_guest(void)1848 static inline bool cpu_has_vmx_unrestricted_guest(void)
1849 {
1850 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1851 		SECONDARY_EXEC_UNRESTRICTED_GUEST;
1852 }
1853 
cpu_has_vmx_ple(void)1854 static inline bool cpu_has_vmx_ple(void)
1855 {
1856 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1857 		SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1858 }
1859 
cpu_has_vmx_basic_inout(void)1860 static inline bool cpu_has_vmx_basic_inout(void)
1861 {
1862 	return	(((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1863 }
1864 
cpu_need_virtualize_apic_accesses(struct kvm_vcpu * vcpu)1865 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1866 {
1867 	return flexpriority_enabled && lapic_in_kernel(vcpu);
1868 }
1869 
cpu_has_vmx_vpid(void)1870 static inline bool cpu_has_vmx_vpid(void)
1871 {
1872 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1873 		SECONDARY_EXEC_ENABLE_VPID;
1874 }
1875 
cpu_has_vmx_rdtscp(void)1876 static inline bool cpu_has_vmx_rdtscp(void)
1877 {
1878 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1879 		SECONDARY_EXEC_RDTSCP;
1880 }
1881 
cpu_has_vmx_invpcid(void)1882 static inline bool cpu_has_vmx_invpcid(void)
1883 {
1884 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1885 		SECONDARY_EXEC_ENABLE_INVPCID;
1886 }
1887 
cpu_has_virtual_nmis(void)1888 static inline bool cpu_has_virtual_nmis(void)
1889 {
1890 	return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1891 }
1892 
cpu_has_vmx_wbinvd_exit(void)1893 static inline bool cpu_has_vmx_wbinvd_exit(void)
1894 {
1895 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1896 		SECONDARY_EXEC_WBINVD_EXITING;
1897 }
1898 
cpu_has_vmx_shadow_vmcs(void)1899 static inline bool cpu_has_vmx_shadow_vmcs(void)
1900 {
1901 	u64 vmx_msr;
1902 	rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1903 	/* check if the cpu supports writing r/o exit information fields */
1904 	if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1905 		return false;
1906 
1907 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1908 		SECONDARY_EXEC_SHADOW_VMCS;
1909 }
1910 
cpu_has_vmx_pml(void)1911 static inline bool cpu_has_vmx_pml(void)
1912 {
1913 	return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1914 }
1915 
cpu_has_vmx_tsc_scaling(void)1916 static inline bool cpu_has_vmx_tsc_scaling(void)
1917 {
1918 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1919 		SECONDARY_EXEC_TSC_SCALING;
1920 }
1921 
cpu_has_vmx_vmfunc(void)1922 static inline bool cpu_has_vmx_vmfunc(void)
1923 {
1924 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1925 		SECONDARY_EXEC_ENABLE_VMFUNC;
1926 }
1927 
vmx_umip_emulated(void)1928 static bool vmx_umip_emulated(void)
1929 {
1930 	return vmcs_config.cpu_based_2nd_exec_ctrl &
1931 		SECONDARY_EXEC_DESC;
1932 }
1933 
report_flexpriority(void)1934 static inline bool report_flexpriority(void)
1935 {
1936 	return flexpriority_enabled;
1937 }
1938 
nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu * vcpu)1939 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1940 {
1941 	return vmx_misc_cr3_count(to_vmx(vcpu)->nested.msrs.misc_low);
1942 }
1943 
1944 /*
1945  * Do the virtual VMX capability MSRs specify that L1 can use VMWRITE
1946  * to modify any valid field of the VMCS, or are the VM-exit
1947  * information fields read-only?
1948  */
nested_cpu_has_vmwrite_any_field(struct kvm_vcpu * vcpu)1949 static inline bool nested_cpu_has_vmwrite_any_field(struct kvm_vcpu *vcpu)
1950 {
1951 	return to_vmx(vcpu)->nested.msrs.misc_low &
1952 		MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
1953 }
1954 
nested_cpu_has_zero_length_injection(struct kvm_vcpu * vcpu)1955 static inline bool nested_cpu_has_zero_length_injection(struct kvm_vcpu *vcpu)
1956 {
1957 	return to_vmx(vcpu)->nested.msrs.misc_low & VMX_MISC_ZERO_LEN_INS;
1958 }
1959 
nested_cpu_supports_monitor_trap_flag(struct kvm_vcpu * vcpu)1960 static inline bool nested_cpu_supports_monitor_trap_flag(struct kvm_vcpu *vcpu)
1961 {
1962 	return to_vmx(vcpu)->nested.msrs.procbased_ctls_high &
1963 			CPU_BASED_MONITOR_TRAP_FLAG;
1964 }
1965 
nested_cpu_has_vmx_shadow_vmcs(struct kvm_vcpu * vcpu)1966 static inline bool nested_cpu_has_vmx_shadow_vmcs(struct kvm_vcpu *vcpu)
1967 {
1968 	return to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
1969 		SECONDARY_EXEC_SHADOW_VMCS;
1970 }
1971 
nested_cpu_has(struct vmcs12 * vmcs12,u32 bit)1972 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1973 {
1974 	return vmcs12->cpu_based_vm_exec_control & bit;
1975 }
1976 
nested_cpu_has2(struct vmcs12 * vmcs12,u32 bit)1977 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1978 {
1979 	return (vmcs12->cpu_based_vm_exec_control &
1980 			CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1981 		(vmcs12->secondary_vm_exec_control & bit);
1982 }
1983 
nested_cpu_has_preemption_timer(struct vmcs12 * vmcs12)1984 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1985 {
1986 	return vmcs12->pin_based_vm_exec_control &
1987 		PIN_BASED_VMX_PREEMPTION_TIMER;
1988 }
1989 
nested_cpu_has_nmi_exiting(struct vmcs12 * vmcs12)1990 static inline bool nested_cpu_has_nmi_exiting(struct vmcs12 *vmcs12)
1991 {
1992 	return vmcs12->pin_based_vm_exec_control & PIN_BASED_NMI_EXITING;
1993 }
1994 
nested_cpu_has_virtual_nmis(struct vmcs12 * vmcs12)1995 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1996 {
1997 	return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1998 }
1999 
nested_cpu_has_ept(struct vmcs12 * vmcs12)2000 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
2001 {
2002 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
2003 }
2004 
nested_cpu_has_xsaves(struct vmcs12 * vmcs12)2005 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
2006 {
2007 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
2008 }
2009 
nested_cpu_has_pml(struct vmcs12 * vmcs12)2010 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
2011 {
2012 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
2013 }
2014 
nested_cpu_has_virt_x2apic_mode(struct vmcs12 * vmcs12)2015 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
2016 {
2017 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
2018 }
2019 
nested_cpu_has_vpid(struct vmcs12 * vmcs12)2020 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
2021 {
2022 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
2023 }
2024 
nested_cpu_has_apic_reg_virt(struct vmcs12 * vmcs12)2025 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
2026 {
2027 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
2028 }
2029 
nested_cpu_has_vid(struct vmcs12 * vmcs12)2030 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
2031 {
2032 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2033 }
2034 
nested_cpu_has_posted_intr(struct vmcs12 * vmcs12)2035 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
2036 {
2037 	return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
2038 }
2039 
nested_cpu_has_vmfunc(struct vmcs12 * vmcs12)2040 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
2041 {
2042 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
2043 }
2044 
nested_cpu_has_eptp_switching(struct vmcs12 * vmcs12)2045 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
2046 {
2047 	return nested_cpu_has_vmfunc(vmcs12) &&
2048 		(vmcs12->vm_function_control &
2049 		 VMX_VMFUNC_EPTP_SWITCHING);
2050 }
2051 
nested_cpu_has_shadow_vmcs(struct vmcs12 * vmcs12)2052 static inline bool nested_cpu_has_shadow_vmcs(struct vmcs12 *vmcs12)
2053 {
2054 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS);
2055 }
2056 
is_nmi(u32 intr_info)2057 static inline bool is_nmi(u32 intr_info)
2058 {
2059 	return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
2060 		== (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
2061 }
2062 
2063 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
2064 			      u32 exit_intr_info,
2065 			      unsigned long exit_qualification);
2066 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
2067 			struct vmcs12 *vmcs12,
2068 			u32 reason, unsigned long qualification);
2069 
__find_msr_index(struct vcpu_vmx * vmx,u32 msr)2070 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
2071 {
2072 	int i;
2073 
2074 	for (i = 0; i < vmx->nmsrs; ++i)
2075 		if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
2076 			return i;
2077 	return -1;
2078 }
2079 
__invvpid(int ext,u16 vpid,gva_t gva)2080 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
2081 {
2082     struct {
2083 	u64 vpid : 16;
2084 	u64 rsvd : 48;
2085 	u64 gva;
2086     } operand = { vpid, 0, gva };
2087     bool error;
2088 
2089     asm volatile (__ex(ASM_VMX_INVVPID) CC_SET(na)
2090 		  : CC_OUT(na) (error) : "a"(&operand), "c"(ext)
2091 		  : "memory");
2092     BUG_ON(error);
2093 }
2094 
__invept(int ext,u64 eptp,gpa_t gpa)2095 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
2096 {
2097 	struct {
2098 		u64 eptp, gpa;
2099 	} operand = {eptp, gpa};
2100 	bool error;
2101 
2102 	asm volatile (__ex(ASM_VMX_INVEPT) CC_SET(na)
2103 		      : CC_OUT(na) (error) : "a" (&operand), "c" (ext)
2104 		      : "memory");
2105 	BUG_ON(error);
2106 }
2107 
find_msr_entry(struct vcpu_vmx * vmx,u32 msr)2108 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
2109 {
2110 	int i;
2111 
2112 	i = __find_msr_index(vmx, msr);
2113 	if (i >= 0)
2114 		return &vmx->guest_msrs[i];
2115 	return NULL;
2116 }
2117 
vmcs_clear(struct vmcs * vmcs)2118 static void vmcs_clear(struct vmcs *vmcs)
2119 {
2120 	u64 phys_addr = __pa(vmcs);
2121 	bool error;
2122 
2123 	asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) CC_SET(na)
2124 		      : CC_OUT(na) (error) : "a"(&phys_addr), "m"(phys_addr)
2125 		      : "memory");
2126 	if (unlikely(error))
2127 		printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
2128 		       vmcs, phys_addr);
2129 }
2130 
loaded_vmcs_init(struct loaded_vmcs * loaded_vmcs)2131 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
2132 {
2133 	vmcs_clear(loaded_vmcs->vmcs);
2134 	if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
2135 		vmcs_clear(loaded_vmcs->shadow_vmcs);
2136 	loaded_vmcs->cpu = -1;
2137 	loaded_vmcs->launched = 0;
2138 }
2139 
vmcs_load(struct vmcs * vmcs)2140 static void vmcs_load(struct vmcs *vmcs)
2141 {
2142 	u64 phys_addr = __pa(vmcs);
2143 	bool error;
2144 
2145 	if (static_branch_unlikely(&enable_evmcs))
2146 		return evmcs_load(phys_addr);
2147 
2148 	asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) CC_SET(na)
2149 		      : CC_OUT(na) (error) : "a"(&phys_addr), "m"(phys_addr)
2150 		      : "memory");
2151 	if (unlikely(error))
2152 		printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
2153 		       vmcs, phys_addr);
2154 }
2155 
2156 #ifdef CONFIG_KEXEC_CORE
2157 /*
2158  * This bitmap is used to indicate whether the vmclear
2159  * operation is enabled on all cpus. All disabled by
2160  * default.
2161  */
2162 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
2163 
crash_enable_local_vmclear(int cpu)2164 static inline void crash_enable_local_vmclear(int cpu)
2165 {
2166 	cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
2167 }
2168 
crash_disable_local_vmclear(int cpu)2169 static inline void crash_disable_local_vmclear(int cpu)
2170 {
2171 	cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
2172 }
2173 
crash_local_vmclear_enabled(int cpu)2174 static inline int crash_local_vmclear_enabled(int cpu)
2175 {
2176 	return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
2177 }
2178 
crash_vmclear_local_loaded_vmcss(void)2179 static void crash_vmclear_local_loaded_vmcss(void)
2180 {
2181 	int cpu = raw_smp_processor_id();
2182 	struct loaded_vmcs *v;
2183 
2184 	if (!crash_local_vmclear_enabled(cpu))
2185 		return;
2186 
2187 	list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
2188 			    loaded_vmcss_on_cpu_link)
2189 		vmcs_clear(v->vmcs);
2190 }
2191 #else
crash_enable_local_vmclear(int cpu)2192 static inline void crash_enable_local_vmclear(int cpu) { }
crash_disable_local_vmclear(int cpu)2193 static inline void crash_disable_local_vmclear(int cpu) { }
2194 #endif /* CONFIG_KEXEC_CORE */
2195 
__loaded_vmcs_clear(void * arg)2196 static void __loaded_vmcs_clear(void *arg)
2197 {
2198 	struct loaded_vmcs *loaded_vmcs = arg;
2199 	int cpu = raw_smp_processor_id();
2200 
2201 	if (loaded_vmcs->cpu != cpu)
2202 		return; /* vcpu migration can race with cpu offline */
2203 	if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
2204 		per_cpu(current_vmcs, cpu) = NULL;
2205 	crash_disable_local_vmclear(cpu);
2206 	list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
2207 
2208 	/*
2209 	 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
2210 	 * is before setting loaded_vmcs->vcpu to -1 which is done in
2211 	 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
2212 	 * then adds the vmcs into percpu list before it is deleted.
2213 	 */
2214 	smp_wmb();
2215 
2216 	loaded_vmcs_init(loaded_vmcs);
2217 	crash_enable_local_vmclear(cpu);
2218 }
2219 
loaded_vmcs_clear(struct loaded_vmcs * loaded_vmcs)2220 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
2221 {
2222 	int cpu = loaded_vmcs->cpu;
2223 
2224 	if (cpu != -1)
2225 		smp_call_function_single(cpu,
2226 			 __loaded_vmcs_clear, loaded_vmcs, 1);
2227 }
2228 
vpid_sync_vcpu_addr(int vpid,gva_t addr)2229 static inline bool vpid_sync_vcpu_addr(int vpid, gva_t addr)
2230 {
2231 	if (vpid == 0)
2232 		return true;
2233 
2234 	if (cpu_has_vmx_invvpid_individual_addr()) {
2235 		__invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR, vpid, addr);
2236 		return true;
2237 	}
2238 
2239 	return false;
2240 }
2241 
vpid_sync_vcpu_single(int vpid)2242 static inline void vpid_sync_vcpu_single(int vpid)
2243 {
2244 	if (vpid == 0)
2245 		return;
2246 
2247 	if (cpu_has_vmx_invvpid_single())
2248 		__invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
2249 }
2250 
vpid_sync_vcpu_global(void)2251 static inline void vpid_sync_vcpu_global(void)
2252 {
2253 	if (cpu_has_vmx_invvpid_global())
2254 		__invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
2255 }
2256 
vpid_sync_context(int vpid)2257 static inline void vpid_sync_context(int vpid)
2258 {
2259 	if (cpu_has_vmx_invvpid_single())
2260 		vpid_sync_vcpu_single(vpid);
2261 	else
2262 		vpid_sync_vcpu_global();
2263 }
2264 
ept_sync_global(void)2265 static inline void ept_sync_global(void)
2266 {
2267 	__invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
2268 }
2269 
ept_sync_context(u64 eptp)2270 static inline void ept_sync_context(u64 eptp)
2271 {
2272 	if (cpu_has_vmx_invept_context())
2273 		__invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
2274 	else
2275 		ept_sync_global();
2276 }
2277 
vmcs_check16(unsigned long field)2278 static __always_inline void vmcs_check16(unsigned long field)
2279 {
2280         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2281 			 "16-bit accessor invalid for 64-bit field");
2282         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2283 			 "16-bit accessor invalid for 64-bit high field");
2284         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2285 			 "16-bit accessor invalid for 32-bit high field");
2286         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2287 			 "16-bit accessor invalid for natural width field");
2288 }
2289 
vmcs_check32(unsigned long field)2290 static __always_inline void vmcs_check32(unsigned long field)
2291 {
2292         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2293 			 "32-bit accessor invalid for 16-bit field");
2294         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2295 			 "32-bit accessor invalid for natural width field");
2296 }
2297 
vmcs_check64(unsigned long field)2298 static __always_inline void vmcs_check64(unsigned long field)
2299 {
2300         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2301 			 "64-bit accessor invalid for 16-bit field");
2302         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2303 			 "64-bit accessor invalid for 64-bit high field");
2304         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2305 			 "64-bit accessor invalid for 32-bit field");
2306         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2307 			 "64-bit accessor invalid for natural width field");
2308 }
2309 
vmcs_checkl(unsigned long field)2310 static __always_inline void vmcs_checkl(unsigned long field)
2311 {
2312         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2313 			 "Natural width accessor invalid for 16-bit field");
2314         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2315 			 "Natural width accessor invalid for 64-bit field");
2316         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2317 			 "Natural width accessor invalid for 64-bit high field");
2318         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2319 			 "Natural width accessor invalid for 32-bit field");
2320 }
2321 
__vmcs_readl(unsigned long field)2322 static __always_inline unsigned long __vmcs_readl(unsigned long field)
2323 {
2324 	unsigned long value;
2325 
2326 	asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
2327 		      : "=a"(value) : "d"(field) : "cc");
2328 	return value;
2329 }
2330 
vmcs_read16(unsigned long field)2331 static __always_inline u16 vmcs_read16(unsigned long field)
2332 {
2333 	vmcs_check16(field);
2334 	if (static_branch_unlikely(&enable_evmcs))
2335 		return evmcs_read16(field);
2336 	return __vmcs_readl(field);
2337 }
2338 
vmcs_read32(unsigned long field)2339 static __always_inline u32 vmcs_read32(unsigned long field)
2340 {
2341 	vmcs_check32(field);
2342 	if (static_branch_unlikely(&enable_evmcs))
2343 		return evmcs_read32(field);
2344 	return __vmcs_readl(field);
2345 }
2346 
vmcs_read64(unsigned long field)2347 static __always_inline u64 vmcs_read64(unsigned long field)
2348 {
2349 	vmcs_check64(field);
2350 	if (static_branch_unlikely(&enable_evmcs))
2351 		return evmcs_read64(field);
2352 #ifdef CONFIG_X86_64
2353 	return __vmcs_readl(field);
2354 #else
2355 	return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
2356 #endif
2357 }
2358 
vmcs_readl(unsigned long field)2359 static __always_inline unsigned long vmcs_readl(unsigned long field)
2360 {
2361 	vmcs_checkl(field);
2362 	if (static_branch_unlikely(&enable_evmcs))
2363 		return evmcs_read64(field);
2364 	return __vmcs_readl(field);
2365 }
2366 
vmwrite_error(unsigned long field,unsigned long value)2367 static noinline void vmwrite_error(unsigned long field, unsigned long value)
2368 {
2369 	printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
2370 	       field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
2371 	dump_stack();
2372 }
2373 
__vmcs_writel(unsigned long field,unsigned long value)2374 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
2375 {
2376 	bool error;
2377 
2378 	asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) CC_SET(na)
2379 		      : CC_OUT(na) (error) : "a"(value), "d"(field));
2380 	if (unlikely(error))
2381 		vmwrite_error(field, value);
2382 }
2383 
vmcs_write16(unsigned long field,u16 value)2384 static __always_inline void vmcs_write16(unsigned long field, u16 value)
2385 {
2386 	vmcs_check16(field);
2387 	if (static_branch_unlikely(&enable_evmcs))
2388 		return evmcs_write16(field, value);
2389 
2390 	__vmcs_writel(field, value);
2391 }
2392 
vmcs_write32(unsigned long field,u32 value)2393 static __always_inline void vmcs_write32(unsigned long field, u32 value)
2394 {
2395 	vmcs_check32(field);
2396 	if (static_branch_unlikely(&enable_evmcs))
2397 		return evmcs_write32(field, value);
2398 
2399 	__vmcs_writel(field, value);
2400 }
2401 
vmcs_write64(unsigned long field,u64 value)2402 static __always_inline void vmcs_write64(unsigned long field, u64 value)
2403 {
2404 	vmcs_check64(field);
2405 	if (static_branch_unlikely(&enable_evmcs))
2406 		return evmcs_write64(field, value);
2407 
2408 	__vmcs_writel(field, value);
2409 #ifndef CONFIG_X86_64
2410 	asm volatile ("");
2411 	__vmcs_writel(field+1, value >> 32);
2412 #endif
2413 }
2414 
vmcs_writel(unsigned long field,unsigned long value)2415 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
2416 {
2417 	vmcs_checkl(field);
2418 	if (static_branch_unlikely(&enable_evmcs))
2419 		return evmcs_write64(field, value);
2420 
2421 	__vmcs_writel(field, value);
2422 }
2423 
vmcs_clear_bits(unsigned long field,u32 mask)2424 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
2425 {
2426         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2427 			 "vmcs_clear_bits does not support 64-bit fields");
2428 	if (static_branch_unlikely(&enable_evmcs))
2429 		return evmcs_write32(field, evmcs_read32(field) & ~mask);
2430 
2431 	__vmcs_writel(field, __vmcs_readl(field) & ~mask);
2432 }
2433 
vmcs_set_bits(unsigned long field,u32 mask)2434 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
2435 {
2436         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2437 			 "vmcs_set_bits does not support 64-bit fields");
2438 	if (static_branch_unlikely(&enable_evmcs))
2439 		return evmcs_write32(field, evmcs_read32(field) | mask);
2440 
2441 	__vmcs_writel(field, __vmcs_readl(field) | mask);
2442 }
2443 
vm_entry_controls_reset_shadow(struct vcpu_vmx * vmx)2444 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
2445 {
2446 	vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
2447 }
2448 
vm_entry_controls_init(struct vcpu_vmx * vmx,u32 val)2449 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
2450 {
2451 	vmcs_write32(VM_ENTRY_CONTROLS, val);
2452 	vmx->vm_entry_controls_shadow = val;
2453 }
2454 
vm_entry_controls_set(struct vcpu_vmx * vmx,u32 val)2455 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
2456 {
2457 	if (vmx->vm_entry_controls_shadow != val)
2458 		vm_entry_controls_init(vmx, val);
2459 }
2460 
vm_entry_controls_get(struct vcpu_vmx * vmx)2461 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
2462 {
2463 	return vmx->vm_entry_controls_shadow;
2464 }
2465 
2466 
vm_entry_controls_setbit(struct vcpu_vmx * vmx,u32 val)2467 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2468 {
2469 	vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
2470 }
2471 
vm_entry_controls_clearbit(struct vcpu_vmx * vmx,u32 val)2472 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2473 {
2474 	vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
2475 }
2476 
vm_exit_controls_reset_shadow(struct vcpu_vmx * vmx)2477 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
2478 {
2479 	vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
2480 }
2481 
vm_exit_controls_init(struct vcpu_vmx * vmx,u32 val)2482 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
2483 {
2484 	vmcs_write32(VM_EXIT_CONTROLS, val);
2485 	vmx->vm_exit_controls_shadow = val;
2486 }
2487 
vm_exit_controls_set(struct vcpu_vmx * vmx,u32 val)2488 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
2489 {
2490 	if (vmx->vm_exit_controls_shadow != val)
2491 		vm_exit_controls_init(vmx, val);
2492 }
2493 
vm_exit_controls_get(struct vcpu_vmx * vmx)2494 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
2495 {
2496 	return vmx->vm_exit_controls_shadow;
2497 }
2498 
2499 
vm_exit_controls_setbit(struct vcpu_vmx * vmx,u32 val)2500 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2501 {
2502 	vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
2503 }
2504 
vm_exit_controls_clearbit(struct vcpu_vmx * vmx,u32 val)2505 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2506 {
2507 	vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
2508 }
2509 
vmx_segment_cache_clear(struct vcpu_vmx * vmx)2510 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
2511 {
2512 	vmx->segment_cache.bitmask = 0;
2513 }
2514 
vmx_segment_cache_test_set(struct vcpu_vmx * vmx,unsigned seg,unsigned field)2515 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
2516 				       unsigned field)
2517 {
2518 	bool ret;
2519 	u32 mask = 1 << (seg * SEG_FIELD_NR + field);
2520 
2521 	if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
2522 		vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
2523 		vmx->segment_cache.bitmask = 0;
2524 	}
2525 	ret = vmx->segment_cache.bitmask & mask;
2526 	vmx->segment_cache.bitmask |= mask;
2527 	return ret;
2528 }
2529 
vmx_read_guest_seg_selector(struct vcpu_vmx * vmx,unsigned seg)2530 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
2531 {
2532 	u16 *p = &vmx->segment_cache.seg[seg].selector;
2533 
2534 	if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
2535 		*p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
2536 	return *p;
2537 }
2538 
vmx_read_guest_seg_base(struct vcpu_vmx * vmx,unsigned seg)2539 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
2540 {
2541 	ulong *p = &vmx->segment_cache.seg[seg].base;
2542 
2543 	if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
2544 		*p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
2545 	return *p;
2546 }
2547 
vmx_read_guest_seg_limit(struct vcpu_vmx * vmx,unsigned seg)2548 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
2549 {
2550 	u32 *p = &vmx->segment_cache.seg[seg].limit;
2551 
2552 	if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
2553 		*p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
2554 	return *p;
2555 }
2556 
vmx_read_guest_seg_ar(struct vcpu_vmx * vmx,unsigned seg)2557 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
2558 {
2559 	u32 *p = &vmx->segment_cache.seg[seg].ar;
2560 
2561 	if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
2562 		*p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
2563 	return *p;
2564 }
2565 
update_exception_bitmap(struct kvm_vcpu * vcpu)2566 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
2567 {
2568 	u32 eb;
2569 
2570 	eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
2571 	     (1u << DB_VECTOR) | (1u << AC_VECTOR);
2572 	/*
2573 	 * Guest access to VMware backdoor ports could legitimately
2574 	 * trigger #GP because of TSS I/O permission bitmap.
2575 	 * We intercept those #GP and allow access to them anyway
2576 	 * as VMware does.
2577 	 */
2578 	if (enable_vmware_backdoor)
2579 		eb |= (1u << GP_VECTOR);
2580 	if ((vcpu->guest_debug &
2581 	     (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
2582 	    (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
2583 		eb |= 1u << BP_VECTOR;
2584 	if (to_vmx(vcpu)->rmode.vm86_active)
2585 		eb = ~0;
2586 	if (enable_ept)
2587 		eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
2588 
2589 	/* When we are running a nested L2 guest and L1 specified for it a
2590 	 * certain exception bitmap, we must trap the same exceptions and pass
2591 	 * them to L1. When running L2, we will only handle the exceptions
2592 	 * specified above if L1 did not want them.
2593 	 */
2594 	if (is_guest_mode(vcpu))
2595 		eb |= get_vmcs12(vcpu)->exception_bitmap;
2596 
2597 	vmcs_write32(EXCEPTION_BITMAP, eb);
2598 }
2599 
2600 /*
2601  * Check if MSR is intercepted for currently loaded MSR bitmap.
2602  */
msr_write_intercepted(struct kvm_vcpu * vcpu,u32 msr)2603 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2604 {
2605 	unsigned long *msr_bitmap;
2606 	int f = sizeof(unsigned long);
2607 
2608 	if (!cpu_has_vmx_msr_bitmap())
2609 		return true;
2610 
2611 	msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2612 
2613 	if (msr <= 0x1fff) {
2614 		return !!test_bit(msr, msr_bitmap + 0x800 / f);
2615 	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2616 		msr &= 0x1fff;
2617 		return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2618 	}
2619 
2620 	return true;
2621 }
2622 
2623 /*
2624  * Check if MSR is intercepted for L01 MSR bitmap.
2625  */
msr_write_intercepted_l01(struct kvm_vcpu * vcpu,u32 msr)2626 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2627 {
2628 	unsigned long *msr_bitmap;
2629 	int f = sizeof(unsigned long);
2630 
2631 	if (!cpu_has_vmx_msr_bitmap())
2632 		return true;
2633 
2634 	msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2635 
2636 	if (msr <= 0x1fff) {
2637 		return !!test_bit(msr, msr_bitmap + 0x800 / f);
2638 	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2639 		msr &= 0x1fff;
2640 		return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2641 	}
2642 
2643 	return true;
2644 }
2645 
clear_atomic_switch_msr_special(struct vcpu_vmx * vmx,unsigned long entry,unsigned long exit)2646 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2647 		unsigned long entry, unsigned long exit)
2648 {
2649 	vm_entry_controls_clearbit(vmx, entry);
2650 	vm_exit_controls_clearbit(vmx, exit);
2651 }
2652 
find_msr(struct vmx_msrs * m,unsigned int msr)2653 static int find_msr(struct vmx_msrs *m, unsigned int msr)
2654 {
2655 	unsigned int i;
2656 
2657 	for (i = 0; i < m->nr; ++i) {
2658 		if (m->val[i].index == msr)
2659 			return i;
2660 	}
2661 	return -ENOENT;
2662 }
2663 
clear_atomic_switch_msr(struct vcpu_vmx * vmx,unsigned msr)2664 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2665 {
2666 	int i;
2667 	struct msr_autoload *m = &vmx->msr_autoload;
2668 
2669 	switch (msr) {
2670 	case MSR_EFER:
2671 		if (cpu_has_load_ia32_efer) {
2672 			clear_atomic_switch_msr_special(vmx,
2673 					VM_ENTRY_LOAD_IA32_EFER,
2674 					VM_EXIT_LOAD_IA32_EFER);
2675 			return;
2676 		}
2677 		break;
2678 	case MSR_CORE_PERF_GLOBAL_CTRL:
2679 		if (cpu_has_load_perf_global_ctrl) {
2680 			clear_atomic_switch_msr_special(vmx,
2681 					VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2682 					VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2683 			return;
2684 		}
2685 		break;
2686 	}
2687 	i = find_msr(&m->guest, msr);
2688 	if (i < 0)
2689 		goto skip_guest;
2690 	--m->guest.nr;
2691 	m->guest.val[i] = m->guest.val[m->guest.nr];
2692 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2693 
2694 skip_guest:
2695 	i = find_msr(&m->host, msr);
2696 	if (i < 0)
2697 		return;
2698 
2699 	--m->host.nr;
2700 	m->host.val[i] = m->host.val[m->host.nr];
2701 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2702 }
2703 
add_atomic_switch_msr_special(struct vcpu_vmx * vmx,unsigned long entry,unsigned long exit,unsigned long guest_val_vmcs,unsigned long host_val_vmcs,u64 guest_val,u64 host_val)2704 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2705 		unsigned long entry, unsigned long exit,
2706 		unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2707 		u64 guest_val, u64 host_val)
2708 {
2709 	vmcs_write64(guest_val_vmcs, guest_val);
2710 	vmcs_write64(host_val_vmcs, host_val);
2711 	vm_entry_controls_setbit(vmx, entry);
2712 	vm_exit_controls_setbit(vmx, exit);
2713 }
2714 
add_atomic_switch_msr(struct vcpu_vmx * vmx,unsigned msr,u64 guest_val,u64 host_val,bool entry_only)2715 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2716 				  u64 guest_val, u64 host_val, bool entry_only)
2717 {
2718 	int i, j = 0;
2719 	struct msr_autoload *m = &vmx->msr_autoload;
2720 
2721 	switch (msr) {
2722 	case MSR_EFER:
2723 		if (cpu_has_load_ia32_efer) {
2724 			add_atomic_switch_msr_special(vmx,
2725 					VM_ENTRY_LOAD_IA32_EFER,
2726 					VM_EXIT_LOAD_IA32_EFER,
2727 					GUEST_IA32_EFER,
2728 					HOST_IA32_EFER,
2729 					guest_val, host_val);
2730 			return;
2731 		}
2732 		break;
2733 	case MSR_CORE_PERF_GLOBAL_CTRL:
2734 		if (cpu_has_load_perf_global_ctrl) {
2735 			add_atomic_switch_msr_special(vmx,
2736 					VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2737 					VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2738 					GUEST_IA32_PERF_GLOBAL_CTRL,
2739 					HOST_IA32_PERF_GLOBAL_CTRL,
2740 					guest_val, host_val);
2741 			return;
2742 		}
2743 		break;
2744 	case MSR_IA32_PEBS_ENABLE:
2745 		/* PEBS needs a quiescent period after being disabled (to write
2746 		 * a record).  Disabling PEBS through VMX MSR swapping doesn't
2747 		 * provide that period, so a CPU could write host's record into
2748 		 * guest's memory.
2749 		 */
2750 		wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2751 	}
2752 
2753 	i = find_msr(&m->guest, msr);
2754 	if (!entry_only)
2755 		j = find_msr(&m->host, msr);
2756 
2757 	if (i == NR_AUTOLOAD_MSRS || j == NR_AUTOLOAD_MSRS) {
2758 		printk_once(KERN_WARNING "Not enough msr switch entries. "
2759 				"Can't add msr %x\n", msr);
2760 		return;
2761 	}
2762 	if (i < 0) {
2763 		i = m->guest.nr++;
2764 		vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2765 	}
2766 	m->guest.val[i].index = msr;
2767 	m->guest.val[i].value = guest_val;
2768 
2769 	if (entry_only)
2770 		return;
2771 
2772 	if (j < 0) {
2773 		j = m->host.nr++;
2774 		vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2775 	}
2776 	m->host.val[j].index = msr;
2777 	m->host.val[j].value = host_val;
2778 }
2779 
update_transition_efer(struct vcpu_vmx * vmx,int efer_offset)2780 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2781 {
2782 	u64 guest_efer = vmx->vcpu.arch.efer;
2783 	u64 ignore_bits = 0;
2784 
2785 	if (!enable_ept) {
2786 		/*
2787 		 * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
2788 		 * host CPUID is more efficient than testing guest CPUID
2789 		 * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
2790 		 */
2791 		if (boot_cpu_has(X86_FEATURE_SMEP))
2792 			guest_efer |= EFER_NX;
2793 		else if (!(guest_efer & EFER_NX))
2794 			ignore_bits |= EFER_NX;
2795 	}
2796 
2797 	/*
2798 	 * LMA and LME handled by hardware; SCE meaningless outside long mode.
2799 	 */
2800 	ignore_bits |= EFER_SCE;
2801 #ifdef CONFIG_X86_64
2802 	ignore_bits |= EFER_LMA | EFER_LME;
2803 	/* SCE is meaningful only in long mode on Intel */
2804 	if (guest_efer & EFER_LMA)
2805 		ignore_bits &= ~(u64)EFER_SCE;
2806 #endif
2807 
2808 	clear_atomic_switch_msr(vmx, MSR_EFER);
2809 
2810 	/*
2811 	 * On EPT, we can't emulate NX, so we must switch EFER atomically.
2812 	 * On CPUs that support "load IA32_EFER", always switch EFER
2813 	 * atomically, since it's faster than switching it manually.
2814 	 */
2815 	if (cpu_has_load_ia32_efer ||
2816 	    (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2817 		if (!(guest_efer & EFER_LMA))
2818 			guest_efer &= ~EFER_LME;
2819 		if (guest_efer != host_efer)
2820 			add_atomic_switch_msr(vmx, MSR_EFER,
2821 					      guest_efer, host_efer, false);
2822 		return false;
2823 	} else {
2824 		guest_efer &= ~ignore_bits;
2825 		guest_efer |= host_efer & ignore_bits;
2826 
2827 		vmx->guest_msrs[efer_offset].data = guest_efer;
2828 		vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2829 
2830 		return true;
2831 	}
2832 }
2833 
2834 #ifdef CONFIG_X86_32
2835 /*
2836  * On 32-bit kernels, VM exits still load the FS and GS bases from the
2837  * VMCS rather than the segment table.  KVM uses this helper to figure
2838  * out the current bases to poke them into the VMCS before entry.
2839  */
segment_base(u16 selector)2840 static unsigned long segment_base(u16 selector)
2841 {
2842 	struct desc_struct *table;
2843 	unsigned long v;
2844 
2845 	if (!(selector & ~SEGMENT_RPL_MASK))
2846 		return 0;
2847 
2848 	table = get_current_gdt_ro();
2849 
2850 	if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2851 		u16 ldt_selector = kvm_read_ldt();
2852 
2853 		if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2854 			return 0;
2855 
2856 		table = (struct desc_struct *)segment_base(ldt_selector);
2857 	}
2858 	v = get_desc_base(&table[selector >> 3]);
2859 	return v;
2860 }
2861 #endif
2862 
vmx_prepare_switch_to_guest(struct kvm_vcpu * vcpu)2863 static void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
2864 {
2865 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2866 	struct vmcs_host_state *host_state;
2867 #ifdef CONFIG_X86_64
2868 	int cpu = raw_smp_processor_id();
2869 #endif
2870 	unsigned long fs_base, gs_base;
2871 	u16 fs_sel, gs_sel;
2872 	int i;
2873 
2874 	vmx->req_immediate_exit = false;
2875 
2876 	if (vmx->loaded_cpu_state)
2877 		return;
2878 
2879 	vmx->loaded_cpu_state = vmx->loaded_vmcs;
2880 	host_state = &vmx->loaded_cpu_state->host_state;
2881 
2882 	/*
2883 	 * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
2884 	 * allow segment selectors with cpl > 0 or ti == 1.
2885 	 */
2886 	host_state->ldt_sel = kvm_read_ldt();
2887 
2888 #ifdef CONFIG_X86_64
2889 	savesegment(ds, host_state->ds_sel);
2890 	savesegment(es, host_state->es_sel);
2891 
2892 	gs_base = cpu_kernelmode_gs_base(cpu);
2893 	if (likely(is_64bit_mm(current->mm))) {
2894 		save_fsgs_for_kvm();
2895 		fs_sel = current->thread.fsindex;
2896 		gs_sel = current->thread.gsindex;
2897 		fs_base = current->thread.fsbase;
2898 		vmx->msr_host_kernel_gs_base = current->thread.gsbase;
2899 	} else {
2900 		savesegment(fs, fs_sel);
2901 		savesegment(gs, gs_sel);
2902 		fs_base = read_msr(MSR_FS_BASE);
2903 		vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
2904 	}
2905 
2906 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2907 #else
2908 	savesegment(fs, fs_sel);
2909 	savesegment(gs, gs_sel);
2910 	fs_base = segment_base(fs_sel);
2911 	gs_base = segment_base(gs_sel);
2912 #endif
2913 
2914 	if (unlikely(fs_sel != host_state->fs_sel)) {
2915 		if (!(fs_sel & 7))
2916 			vmcs_write16(HOST_FS_SELECTOR, fs_sel);
2917 		else
2918 			vmcs_write16(HOST_FS_SELECTOR, 0);
2919 		host_state->fs_sel = fs_sel;
2920 	}
2921 	if (unlikely(gs_sel != host_state->gs_sel)) {
2922 		if (!(gs_sel & 7))
2923 			vmcs_write16(HOST_GS_SELECTOR, gs_sel);
2924 		else
2925 			vmcs_write16(HOST_GS_SELECTOR, 0);
2926 		host_state->gs_sel = gs_sel;
2927 	}
2928 	if (unlikely(fs_base != host_state->fs_base)) {
2929 		vmcs_writel(HOST_FS_BASE, fs_base);
2930 		host_state->fs_base = fs_base;
2931 	}
2932 	if (unlikely(gs_base != host_state->gs_base)) {
2933 		vmcs_writel(HOST_GS_BASE, gs_base);
2934 		host_state->gs_base = gs_base;
2935 	}
2936 
2937 	for (i = 0; i < vmx->save_nmsrs; ++i)
2938 		kvm_set_shared_msr(vmx->guest_msrs[i].index,
2939 				   vmx->guest_msrs[i].data,
2940 				   vmx->guest_msrs[i].mask);
2941 }
2942 
vmx_prepare_switch_to_host(struct vcpu_vmx * vmx)2943 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
2944 {
2945 	struct vmcs_host_state *host_state;
2946 
2947 	if (!vmx->loaded_cpu_state)
2948 		return;
2949 
2950 	WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
2951 	host_state = &vmx->loaded_cpu_state->host_state;
2952 
2953 	++vmx->vcpu.stat.host_state_reload;
2954 	vmx->loaded_cpu_state = NULL;
2955 
2956 #ifdef CONFIG_X86_64
2957 	rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2958 #endif
2959 	if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
2960 		kvm_load_ldt(host_state->ldt_sel);
2961 #ifdef CONFIG_X86_64
2962 		load_gs_index(host_state->gs_sel);
2963 #else
2964 		loadsegment(gs, host_state->gs_sel);
2965 #endif
2966 	}
2967 	if (host_state->fs_sel & 7)
2968 		loadsegment(fs, host_state->fs_sel);
2969 #ifdef CONFIG_X86_64
2970 	if (unlikely(host_state->ds_sel | host_state->es_sel)) {
2971 		loadsegment(ds, host_state->ds_sel);
2972 		loadsegment(es, host_state->es_sel);
2973 	}
2974 #endif
2975 	invalidate_tss_limit();
2976 #ifdef CONFIG_X86_64
2977 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2978 #endif
2979 	load_fixmap_gdt(raw_smp_processor_id());
2980 }
2981 
2982 #ifdef CONFIG_X86_64
vmx_read_guest_kernel_gs_base(struct vcpu_vmx * vmx)2983 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
2984 {
2985 	preempt_disable();
2986 	if (vmx->loaded_cpu_state)
2987 		rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2988 	preempt_enable();
2989 	return vmx->msr_guest_kernel_gs_base;
2990 }
2991 
vmx_write_guest_kernel_gs_base(struct vcpu_vmx * vmx,u64 data)2992 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
2993 {
2994 	preempt_disable();
2995 	if (vmx->loaded_cpu_state)
2996 		wrmsrl(MSR_KERNEL_GS_BASE, data);
2997 	preempt_enable();
2998 	vmx->msr_guest_kernel_gs_base = data;
2999 }
3000 #endif
3001 
vmx_vcpu_pi_load(struct kvm_vcpu * vcpu,int cpu)3002 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
3003 {
3004 	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3005 	struct pi_desc old, new;
3006 	unsigned int dest;
3007 
3008 	/*
3009 	 * In case of hot-plug or hot-unplug, we may have to undo
3010 	 * vmx_vcpu_pi_put even if there is no assigned device.  And we
3011 	 * always keep PI.NDST up to date for simplicity: it makes the
3012 	 * code easier, and CPU migration is not a fast path.
3013 	 */
3014 	if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
3015 		return;
3016 
3017 	/*
3018 	 * First handle the simple case where no cmpxchg is necessary; just
3019 	 * allow posting non-urgent interrupts.
3020 	 *
3021 	 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
3022 	 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
3023 	 * expects the VCPU to be on the blocked_vcpu_list that matches
3024 	 * PI.NDST.
3025 	 */
3026 	if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
3027 	    vcpu->cpu == cpu) {
3028 		pi_clear_sn(pi_desc);
3029 		return;
3030 	}
3031 
3032 	/* The full case.  */
3033 	do {
3034 		old.control = new.control = pi_desc->control;
3035 
3036 		dest = cpu_physical_id(cpu);
3037 
3038 		if (x2apic_enabled())
3039 			new.ndst = dest;
3040 		else
3041 			new.ndst = (dest << 8) & 0xFF00;
3042 
3043 		new.sn = 0;
3044 	} while (cmpxchg64(&pi_desc->control, old.control,
3045 			   new.control) != old.control);
3046 }
3047 
decache_tsc_multiplier(struct vcpu_vmx * vmx)3048 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
3049 {
3050 	vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
3051 	vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
3052 }
3053 
3054 /*
3055  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
3056  * vcpu mutex is already taken.
3057  */
vmx_vcpu_load(struct kvm_vcpu * vcpu,int cpu)3058 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3059 {
3060 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3061 	bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
3062 
3063 	if (!already_loaded) {
3064 		loaded_vmcs_clear(vmx->loaded_vmcs);
3065 		local_irq_disable();
3066 		crash_disable_local_vmclear(cpu);
3067 
3068 		/*
3069 		 * Read loaded_vmcs->cpu should be before fetching
3070 		 * loaded_vmcs->loaded_vmcss_on_cpu_link.
3071 		 * See the comments in __loaded_vmcs_clear().
3072 		 */
3073 		smp_rmb();
3074 
3075 		list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
3076 			 &per_cpu(loaded_vmcss_on_cpu, cpu));
3077 		crash_enable_local_vmclear(cpu);
3078 		local_irq_enable();
3079 	}
3080 
3081 	if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
3082 		per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
3083 		vmcs_load(vmx->loaded_vmcs->vmcs);
3084 		indirect_branch_prediction_barrier();
3085 	}
3086 
3087 	if (!already_loaded) {
3088 		void *gdt = get_current_gdt_ro();
3089 		unsigned long sysenter_esp;
3090 
3091 		kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3092 
3093 		/*
3094 		 * Linux uses per-cpu TSS and GDT, so set these when switching
3095 		 * processors.  See 22.2.4.
3096 		 */
3097 		vmcs_writel(HOST_TR_BASE,
3098 			    (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
3099 		vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
3100 
3101 		/*
3102 		 * VM exits change the host TR limit to 0x67 after a VM
3103 		 * exit.  This is okay, since 0x67 covers everything except
3104 		 * the IO bitmap and have have code to handle the IO bitmap
3105 		 * being lost after a VM exit.
3106 		 */
3107 		BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
3108 
3109 		rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
3110 		vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
3111 
3112 		vmx->loaded_vmcs->cpu = cpu;
3113 	}
3114 
3115 	/* Setup TSC multiplier */
3116 	if (kvm_has_tsc_control &&
3117 	    vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
3118 		decache_tsc_multiplier(vmx);
3119 
3120 	vmx_vcpu_pi_load(vcpu, cpu);
3121 	vmx->host_pkru = read_pkru();
3122 	vmx->host_debugctlmsr = get_debugctlmsr();
3123 }
3124 
vmx_vcpu_pi_put(struct kvm_vcpu * vcpu)3125 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
3126 {
3127 	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3128 
3129 	if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
3130 		!irq_remapping_cap(IRQ_POSTING_CAP)  ||
3131 		!kvm_vcpu_apicv_active(vcpu))
3132 		return;
3133 
3134 	/* Set SN when the vCPU is preempted */
3135 	if (vcpu->preempted)
3136 		pi_set_sn(pi_desc);
3137 }
3138 
vmx_vcpu_put(struct kvm_vcpu * vcpu)3139 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
3140 {
3141 	vmx_vcpu_pi_put(vcpu);
3142 
3143 	vmx_prepare_switch_to_host(to_vmx(vcpu));
3144 }
3145 
emulation_required(struct kvm_vcpu * vcpu)3146 static bool emulation_required(struct kvm_vcpu *vcpu)
3147 {
3148 	return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3149 }
3150 
3151 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
3152 
3153 /*
3154  * Return the cr0 value that a nested guest would read. This is a combination
3155  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
3156  * its hypervisor (cr0_read_shadow).
3157  */
nested_read_cr0(struct vmcs12 * fields)3158 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
3159 {
3160 	return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
3161 		(fields->cr0_read_shadow & fields->cr0_guest_host_mask);
3162 }
nested_read_cr4(struct vmcs12 * fields)3163 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
3164 {
3165 	return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
3166 		(fields->cr4_read_shadow & fields->cr4_guest_host_mask);
3167 }
3168 
vmx_get_rflags(struct kvm_vcpu * vcpu)3169 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
3170 {
3171 	unsigned long rflags, save_rflags;
3172 
3173 	if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
3174 		__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3175 		rflags = vmcs_readl(GUEST_RFLAGS);
3176 		if (to_vmx(vcpu)->rmode.vm86_active) {
3177 			rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3178 			save_rflags = to_vmx(vcpu)->rmode.save_rflags;
3179 			rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3180 		}
3181 		to_vmx(vcpu)->rflags = rflags;
3182 	}
3183 	return to_vmx(vcpu)->rflags;
3184 }
3185 
vmx_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)3186 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
3187 {
3188 	unsigned long old_rflags = vmx_get_rflags(vcpu);
3189 
3190 	__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3191 	to_vmx(vcpu)->rflags = rflags;
3192 	if (to_vmx(vcpu)->rmode.vm86_active) {
3193 		to_vmx(vcpu)->rmode.save_rflags = rflags;
3194 		rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3195 	}
3196 	vmcs_writel(GUEST_RFLAGS, rflags);
3197 
3198 	if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
3199 		to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
3200 }
3201 
vmx_get_interrupt_shadow(struct kvm_vcpu * vcpu)3202 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
3203 {
3204 	u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3205 	int ret = 0;
3206 
3207 	if (interruptibility & GUEST_INTR_STATE_STI)
3208 		ret |= KVM_X86_SHADOW_INT_STI;
3209 	if (interruptibility & GUEST_INTR_STATE_MOV_SS)
3210 		ret |= KVM_X86_SHADOW_INT_MOV_SS;
3211 
3212 	return ret;
3213 }
3214 
vmx_set_interrupt_shadow(struct kvm_vcpu * vcpu,int mask)3215 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
3216 {
3217 	u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3218 	u32 interruptibility = interruptibility_old;
3219 
3220 	interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
3221 
3222 	if (mask & KVM_X86_SHADOW_INT_MOV_SS)
3223 		interruptibility |= GUEST_INTR_STATE_MOV_SS;
3224 	else if (mask & KVM_X86_SHADOW_INT_STI)
3225 		interruptibility |= GUEST_INTR_STATE_STI;
3226 
3227 	if ((interruptibility != interruptibility_old))
3228 		vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
3229 }
3230 
skip_emulated_instruction(struct kvm_vcpu * vcpu)3231 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
3232 {
3233 	unsigned long rip;
3234 
3235 	rip = kvm_rip_read(vcpu);
3236 	rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3237 	kvm_rip_write(vcpu, rip);
3238 
3239 	/* skipping an emulated instruction also counts */
3240 	vmx_set_interrupt_shadow(vcpu, 0);
3241 }
3242 
nested_vmx_inject_exception_vmexit(struct kvm_vcpu * vcpu,unsigned long exit_qual)3243 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3244 					       unsigned long exit_qual)
3245 {
3246 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3247 	unsigned int nr = vcpu->arch.exception.nr;
3248 	u32 intr_info = nr | INTR_INFO_VALID_MASK;
3249 
3250 	if (vcpu->arch.exception.has_error_code) {
3251 		vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3252 		intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3253 	}
3254 
3255 	if (kvm_exception_is_soft(nr))
3256 		intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3257 	else
3258 		intr_info |= INTR_TYPE_HARD_EXCEPTION;
3259 
3260 	if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3261 	    vmx_get_nmi_mask(vcpu))
3262 		intr_info |= INTR_INFO_UNBLOCK_NMI;
3263 
3264 	nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3265 }
3266 
3267 /*
3268  * KVM wants to inject page-faults which it got to the guest. This function
3269  * checks whether in a nested guest, we need to inject them to L1 or L2.
3270  */
nested_vmx_check_exception(struct kvm_vcpu * vcpu,unsigned long * exit_qual)3271 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
3272 {
3273 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3274 	unsigned int nr = vcpu->arch.exception.nr;
3275 
3276 	if (nr == PF_VECTOR) {
3277 		if (vcpu->arch.exception.nested_apf) {
3278 			*exit_qual = vcpu->arch.apf.nested_apf_token;
3279 			return 1;
3280 		}
3281 		/*
3282 		 * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
3283 		 * The fix is to add the ancillary datum (CR2 or DR6) to structs
3284 		 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
3285 		 * can be written only when inject_pending_event runs.  This should be
3286 		 * conditional on a new capability---if the capability is disabled,
3287 		 * kvm_multiple_exception would write the ancillary information to
3288 		 * CR2 or DR6, for backwards ABI-compatibility.
3289 		 */
3290 		if (nested_vmx_is_page_fault_vmexit(vmcs12,
3291 						    vcpu->arch.exception.error_code)) {
3292 			*exit_qual = vcpu->arch.cr2;
3293 			return 1;
3294 		}
3295 	} else {
3296 		if (vmcs12->exception_bitmap & (1u << nr)) {
3297 			if (nr == DB_VECTOR)
3298 				*exit_qual = vcpu->arch.dr6;
3299 			else
3300 				*exit_qual = 0;
3301 			return 1;
3302 		}
3303 	}
3304 
3305 	return 0;
3306 }
3307 
vmx_clear_hlt(struct kvm_vcpu * vcpu)3308 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
3309 {
3310 	/*
3311 	 * Ensure that we clear the HLT state in the VMCS.  We don't need to
3312 	 * explicitly skip the instruction because if the HLT state is set,
3313 	 * then the instruction is already executing and RIP has already been
3314 	 * advanced.
3315 	 */
3316 	if (kvm_hlt_in_guest(vcpu->kvm) &&
3317 			vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
3318 		vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3319 }
3320 
vmx_queue_exception(struct kvm_vcpu * vcpu)3321 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
3322 {
3323 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3324 	unsigned nr = vcpu->arch.exception.nr;
3325 	bool has_error_code = vcpu->arch.exception.has_error_code;
3326 	u32 error_code = vcpu->arch.exception.error_code;
3327 	u32 intr_info = nr | INTR_INFO_VALID_MASK;
3328 
3329 	if (has_error_code) {
3330 		vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
3331 		intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3332 	}
3333 
3334 	if (vmx->rmode.vm86_active) {
3335 		int inc_eip = 0;
3336 		if (kvm_exception_is_soft(nr))
3337 			inc_eip = vcpu->arch.event_exit_inst_len;
3338 		if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
3339 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3340 		return;
3341 	}
3342 
3343 	WARN_ON_ONCE(vmx->emulation_required);
3344 
3345 	if (kvm_exception_is_soft(nr)) {
3346 		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
3347 			     vmx->vcpu.arch.event_exit_inst_len);
3348 		intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3349 	} else
3350 		intr_info |= INTR_TYPE_HARD_EXCEPTION;
3351 
3352 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
3353 
3354 	vmx_clear_hlt(vcpu);
3355 }
3356 
vmx_rdtscp_supported(void)3357 static bool vmx_rdtscp_supported(void)
3358 {
3359 	return cpu_has_vmx_rdtscp();
3360 }
3361 
vmx_invpcid_supported(void)3362 static bool vmx_invpcid_supported(void)
3363 {
3364 	return cpu_has_vmx_invpcid();
3365 }
3366 
3367 /*
3368  * Swap MSR entry in host/guest MSR entry array.
3369  */
move_msr_up(struct vcpu_vmx * vmx,int from,int to)3370 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
3371 {
3372 	struct shared_msr_entry tmp;
3373 
3374 	tmp = vmx->guest_msrs[to];
3375 	vmx->guest_msrs[to] = vmx->guest_msrs[from];
3376 	vmx->guest_msrs[from] = tmp;
3377 }
3378 
3379 /*
3380  * Set up the vmcs to automatically save and restore system
3381  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
3382  * mode, as fiddling with msrs is very expensive.
3383  */
setup_msrs(struct vcpu_vmx * vmx)3384 static void setup_msrs(struct vcpu_vmx *vmx)
3385 {
3386 	int save_nmsrs, index;
3387 
3388 	save_nmsrs = 0;
3389 #ifdef CONFIG_X86_64
3390 	if (is_long_mode(&vmx->vcpu)) {
3391 		index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
3392 		if (index >= 0)
3393 			move_msr_up(vmx, index, save_nmsrs++);
3394 		index = __find_msr_index(vmx, MSR_LSTAR);
3395 		if (index >= 0)
3396 			move_msr_up(vmx, index, save_nmsrs++);
3397 		index = __find_msr_index(vmx, MSR_CSTAR);
3398 		if (index >= 0)
3399 			move_msr_up(vmx, index, save_nmsrs++);
3400 		index = __find_msr_index(vmx, MSR_TSC_AUX);
3401 		if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
3402 			move_msr_up(vmx, index, save_nmsrs++);
3403 		/*
3404 		 * MSR_STAR is only needed on long mode guests, and only
3405 		 * if efer.sce is enabled.
3406 		 */
3407 		index = __find_msr_index(vmx, MSR_STAR);
3408 		if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
3409 			move_msr_up(vmx, index, save_nmsrs++);
3410 	}
3411 #endif
3412 	index = __find_msr_index(vmx, MSR_EFER);
3413 	if (index >= 0 && update_transition_efer(vmx, index))
3414 		move_msr_up(vmx, index, save_nmsrs++);
3415 
3416 	vmx->save_nmsrs = save_nmsrs;
3417 
3418 	if (cpu_has_vmx_msr_bitmap())
3419 		vmx_update_msr_bitmap(&vmx->vcpu);
3420 }
3421 
vmx_read_l1_tsc_offset(struct kvm_vcpu * vcpu)3422 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
3423 {
3424 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3425 
3426 	if (is_guest_mode(vcpu) &&
3427 	    (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
3428 		return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
3429 
3430 	return vcpu->arch.tsc_offset;
3431 }
3432 
3433 /*
3434  * writes 'offset' into guest's timestamp counter offset register
3435  */
vmx_write_tsc_offset(struct kvm_vcpu * vcpu,u64 offset)3436 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
3437 {
3438 	if (is_guest_mode(vcpu)) {
3439 		/*
3440 		 * We're here if L1 chose not to trap WRMSR to TSC. According
3441 		 * to the spec, this should set L1's TSC; The offset that L1
3442 		 * set for L2 remains unchanged, and still needs to be added
3443 		 * to the newly set TSC to get L2's TSC.
3444 		 */
3445 		struct vmcs12 *vmcs12;
3446 		/* recalculate vmcs02.TSC_OFFSET: */
3447 		vmcs12 = get_vmcs12(vcpu);
3448 		vmcs_write64(TSC_OFFSET, offset +
3449 			(nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
3450 			 vmcs12->tsc_offset : 0));
3451 	} else {
3452 		trace_kvm_write_tsc_offset(vcpu->vcpu_id,
3453 					   vmcs_read64(TSC_OFFSET), offset);
3454 		vmcs_write64(TSC_OFFSET, offset);
3455 	}
3456 }
3457 
3458 /*
3459  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
3460  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
3461  * all guests if the "nested" module option is off, and can also be disabled
3462  * for a single guest by disabling its VMX cpuid bit.
3463  */
nested_vmx_allowed(struct kvm_vcpu * vcpu)3464 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
3465 {
3466 	return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
3467 }
3468 
3469 /*
3470  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
3471  * returned for the various VMX controls MSRs when nested VMX is enabled.
3472  * The same values should also be used to verify that vmcs12 control fields are
3473  * valid during nested entry from L1 to L2.
3474  * Each of these control msrs has a low and high 32-bit half: A low bit is on
3475  * if the corresponding bit in the (32-bit) control field *must* be on, and a
3476  * bit in the high half is on if the corresponding bit in the control field
3477  * may be on. See also vmx_control_verify().
3478  */
nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs * msrs,bool apicv)3479 static void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs, bool apicv)
3480 {
3481 	if (!nested) {
3482 		memset(msrs, 0, sizeof(*msrs));
3483 		return;
3484 	}
3485 
3486 	/*
3487 	 * Note that as a general rule, the high half of the MSRs (bits in
3488 	 * the control fields which may be 1) should be initialized by the
3489 	 * intersection of the underlying hardware's MSR (i.e., features which
3490 	 * can be supported) and the list of features we want to expose -
3491 	 * because they are known to be properly supported in our code.
3492 	 * Also, usually, the low half of the MSRs (bits which must be 1) can
3493 	 * be set to 0, meaning that L1 may turn off any of these bits. The
3494 	 * reason is that if one of these bits is necessary, it will appear
3495 	 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
3496 	 * fields of vmcs01 and vmcs02, will turn these bits off - and
3497 	 * nested_vmx_exit_reflected() will not pass related exits to L1.
3498 	 * These rules have exceptions below.
3499 	 */
3500 
3501 	/* pin-based controls */
3502 	rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
3503 		msrs->pinbased_ctls_low,
3504 		msrs->pinbased_ctls_high);
3505 	msrs->pinbased_ctls_low |=
3506 		PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3507 	msrs->pinbased_ctls_high &=
3508 		PIN_BASED_EXT_INTR_MASK |
3509 		PIN_BASED_NMI_EXITING |
3510 		PIN_BASED_VIRTUAL_NMIS |
3511 		(apicv ? PIN_BASED_POSTED_INTR : 0);
3512 	msrs->pinbased_ctls_high |=
3513 		PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3514 		PIN_BASED_VMX_PREEMPTION_TIMER;
3515 
3516 	/* exit controls */
3517 	rdmsr(MSR_IA32_VMX_EXIT_CTLS,
3518 		msrs->exit_ctls_low,
3519 		msrs->exit_ctls_high);
3520 	msrs->exit_ctls_low =
3521 		VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3522 
3523 	msrs->exit_ctls_high &=
3524 #ifdef CONFIG_X86_64
3525 		VM_EXIT_HOST_ADDR_SPACE_SIZE |
3526 #endif
3527 		VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
3528 	msrs->exit_ctls_high |=
3529 		VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
3530 		VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
3531 		VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
3532 
3533 	/* We support free control of debug control saving. */
3534 	msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
3535 
3536 	/* entry controls */
3537 	rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
3538 		msrs->entry_ctls_low,
3539 		msrs->entry_ctls_high);
3540 	msrs->entry_ctls_low =
3541 		VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3542 	msrs->entry_ctls_high &=
3543 #ifdef CONFIG_X86_64
3544 		VM_ENTRY_IA32E_MODE |
3545 #endif
3546 		VM_ENTRY_LOAD_IA32_PAT;
3547 	msrs->entry_ctls_high |=
3548 		(VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
3549 
3550 	/* We support free control of debug control loading. */
3551 	msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
3552 
3553 	/* cpu-based controls */
3554 	rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
3555 		msrs->procbased_ctls_low,
3556 		msrs->procbased_ctls_high);
3557 	msrs->procbased_ctls_low =
3558 		CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3559 	msrs->procbased_ctls_high &=
3560 		CPU_BASED_VIRTUAL_INTR_PENDING |
3561 		CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
3562 		CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
3563 		CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
3564 		CPU_BASED_CR3_STORE_EXITING |
3565 #ifdef CONFIG_X86_64
3566 		CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
3567 #endif
3568 		CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
3569 		CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
3570 		CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
3571 		CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
3572 		CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3573 	/*
3574 	 * We can allow some features even when not supported by the
3575 	 * hardware. For example, L1 can specify an MSR bitmap - and we
3576 	 * can use it to avoid exits to L1 - even when L0 runs L2
3577 	 * without MSR bitmaps.
3578 	 */
3579 	msrs->procbased_ctls_high |=
3580 		CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3581 		CPU_BASED_USE_MSR_BITMAPS;
3582 
3583 	/* We support free control of CR3 access interception. */
3584 	msrs->procbased_ctls_low &=
3585 		~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
3586 
3587 	/*
3588 	 * secondary cpu-based controls.  Do not include those that
3589 	 * depend on CPUID bits, they are added later by vmx_cpuid_update.
3590 	 */
3591 	rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
3592 		msrs->secondary_ctls_low,
3593 		msrs->secondary_ctls_high);
3594 	msrs->secondary_ctls_low = 0;
3595 	msrs->secondary_ctls_high &=
3596 		SECONDARY_EXEC_DESC |
3597 		SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3598 		SECONDARY_EXEC_APIC_REGISTER_VIRT |
3599 		SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3600 		SECONDARY_EXEC_WBINVD_EXITING;
3601 
3602 	/*
3603 	 * We can emulate "VMCS shadowing," even if the hardware
3604 	 * doesn't support it.
3605 	 */
3606 	msrs->secondary_ctls_high |=
3607 		SECONDARY_EXEC_SHADOW_VMCS;
3608 
3609 	if (enable_ept) {
3610 		/* nested EPT: emulate EPT also to L1 */
3611 		msrs->secondary_ctls_high |=
3612 			SECONDARY_EXEC_ENABLE_EPT;
3613 		msrs->ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
3614 			 VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
3615 		if (cpu_has_vmx_ept_execute_only())
3616 			msrs->ept_caps |=
3617 				VMX_EPT_EXECUTE_ONLY_BIT;
3618 		msrs->ept_caps &= vmx_capability.ept;
3619 		msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
3620 			VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
3621 			VMX_EPT_1GB_PAGE_BIT;
3622 		if (enable_ept_ad_bits) {
3623 			msrs->secondary_ctls_high |=
3624 				SECONDARY_EXEC_ENABLE_PML;
3625 			msrs->ept_caps |= VMX_EPT_AD_BIT;
3626 		}
3627 	}
3628 
3629 	if (cpu_has_vmx_vmfunc()) {
3630 		msrs->secondary_ctls_high |=
3631 			SECONDARY_EXEC_ENABLE_VMFUNC;
3632 		/*
3633 		 * Advertise EPTP switching unconditionally
3634 		 * since we emulate it
3635 		 */
3636 		if (enable_ept)
3637 			msrs->vmfunc_controls =
3638 				VMX_VMFUNC_EPTP_SWITCHING;
3639 	}
3640 
3641 	/*
3642 	 * Old versions of KVM use the single-context version without
3643 	 * checking for support, so declare that it is supported even
3644 	 * though it is treated as global context.  The alternative is
3645 	 * not failing the single-context invvpid, and it is worse.
3646 	 */
3647 	if (enable_vpid) {
3648 		msrs->secondary_ctls_high |=
3649 			SECONDARY_EXEC_ENABLE_VPID;
3650 		msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
3651 			VMX_VPID_EXTENT_SUPPORTED_MASK;
3652 	}
3653 
3654 	if (enable_unrestricted_guest)
3655 		msrs->secondary_ctls_high |=
3656 			SECONDARY_EXEC_UNRESTRICTED_GUEST;
3657 
3658 	if (flexpriority_enabled)
3659 		msrs->secondary_ctls_high |=
3660 			SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3661 
3662 	/* miscellaneous data */
3663 	rdmsr(MSR_IA32_VMX_MISC,
3664 		msrs->misc_low,
3665 		msrs->misc_high);
3666 	msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
3667 	msrs->misc_low |=
3668 		MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
3669 		VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
3670 		VMX_MISC_ACTIVITY_HLT;
3671 	msrs->misc_high = 0;
3672 
3673 	/*
3674 	 * This MSR reports some information about VMX support. We
3675 	 * should return information about the VMX we emulate for the
3676 	 * guest, and the VMCS structure we give it - not about the
3677 	 * VMX support of the underlying hardware.
3678 	 */
3679 	msrs->basic =
3680 		VMCS12_REVISION |
3681 		VMX_BASIC_TRUE_CTLS |
3682 		((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
3683 		(VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
3684 
3685 	if (cpu_has_vmx_basic_inout())
3686 		msrs->basic |= VMX_BASIC_INOUT;
3687 
3688 	/*
3689 	 * These MSRs specify bits which the guest must keep fixed on
3690 	 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
3691 	 * We picked the standard core2 setting.
3692 	 */
3693 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
3694 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
3695 	msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
3696 	msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
3697 
3698 	/* These MSRs specify bits which the guest must keep fixed off. */
3699 	rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
3700 	rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
3701 
3702 	/* highest index: VMX_PREEMPTION_TIMER_VALUE */
3703 	msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
3704 }
3705 
3706 /*
3707  * if fixed0[i] == 1: val[i] must be 1
3708  * if fixed1[i] == 0: val[i] must be 0
3709  */
fixed_bits_valid(u64 val,u64 fixed0,u64 fixed1)3710 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
3711 {
3712 	return ((val & fixed1) | fixed0) == val;
3713 }
3714 
vmx_control_verify(u32 control,u32 low,u32 high)3715 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
3716 {
3717 	return fixed_bits_valid(control, low, high);
3718 }
3719 
vmx_control_msr(u32 low,u32 high)3720 static inline u64 vmx_control_msr(u32 low, u32 high)
3721 {
3722 	return low | ((u64)high << 32);
3723 }
3724 
is_bitwise_subset(u64 superset,u64 subset,u64 mask)3725 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
3726 {
3727 	superset &= mask;
3728 	subset &= mask;
3729 
3730 	return (superset | subset) == superset;
3731 }
3732 
vmx_restore_vmx_basic(struct vcpu_vmx * vmx,u64 data)3733 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
3734 {
3735 	const u64 feature_and_reserved =
3736 		/* feature (except bit 48; see below) */
3737 		BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
3738 		/* reserved */
3739 		BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
3740 	u64 vmx_basic = vmx->nested.msrs.basic;
3741 
3742 	if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
3743 		return -EINVAL;
3744 
3745 	/*
3746 	 * KVM does not emulate a version of VMX that constrains physical
3747 	 * addresses of VMX structures (e.g. VMCS) to 32-bits.
3748 	 */
3749 	if (data & BIT_ULL(48))
3750 		return -EINVAL;
3751 
3752 	if (vmx_basic_vmcs_revision_id(vmx_basic) !=
3753 	    vmx_basic_vmcs_revision_id(data))
3754 		return -EINVAL;
3755 
3756 	if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
3757 		return -EINVAL;
3758 
3759 	vmx->nested.msrs.basic = data;
3760 	return 0;
3761 }
3762 
3763 static int
vmx_restore_control_msr(struct vcpu_vmx * vmx,u32 msr_index,u64 data)3764 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3765 {
3766 	u64 supported;
3767 	u32 *lowp, *highp;
3768 
3769 	switch (msr_index) {
3770 	case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3771 		lowp = &vmx->nested.msrs.pinbased_ctls_low;
3772 		highp = &vmx->nested.msrs.pinbased_ctls_high;
3773 		break;
3774 	case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3775 		lowp = &vmx->nested.msrs.procbased_ctls_low;
3776 		highp = &vmx->nested.msrs.procbased_ctls_high;
3777 		break;
3778 	case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3779 		lowp = &vmx->nested.msrs.exit_ctls_low;
3780 		highp = &vmx->nested.msrs.exit_ctls_high;
3781 		break;
3782 	case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3783 		lowp = &vmx->nested.msrs.entry_ctls_low;
3784 		highp = &vmx->nested.msrs.entry_ctls_high;
3785 		break;
3786 	case MSR_IA32_VMX_PROCBASED_CTLS2:
3787 		lowp = &vmx->nested.msrs.secondary_ctls_low;
3788 		highp = &vmx->nested.msrs.secondary_ctls_high;
3789 		break;
3790 	default:
3791 		BUG();
3792 	}
3793 
3794 	supported = vmx_control_msr(*lowp, *highp);
3795 
3796 	/* Check must-be-1 bits are still 1. */
3797 	if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3798 		return -EINVAL;
3799 
3800 	/* Check must-be-0 bits are still 0. */
3801 	if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3802 		return -EINVAL;
3803 
3804 	*lowp = data;
3805 	*highp = data >> 32;
3806 	return 0;
3807 }
3808 
vmx_restore_vmx_misc(struct vcpu_vmx * vmx,u64 data)3809 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3810 {
3811 	const u64 feature_and_reserved_bits =
3812 		/* feature */
3813 		BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3814 		BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3815 		/* reserved */
3816 		GENMASK_ULL(13, 9) | BIT_ULL(31);
3817 	u64 vmx_misc;
3818 
3819 	vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
3820 				   vmx->nested.msrs.misc_high);
3821 
3822 	if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3823 		return -EINVAL;
3824 
3825 	if ((vmx->nested.msrs.pinbased_ctls_high &
3826 	     PIN_BASED_VMX_PREEMPTION_TIMER) &&
3827 	    vmx_misc_preemption_timer_rate(data) !=
3828 	    vmx_misc_preemption_timer_rate(vmx_misc))
3829 		return -EINVAL;
3830 
3831 	if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3832 		return -EINVAL;
3833 
3834 	if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3835 		return -EINVAL;
3836 
3837 	if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3838 		return -EINVAL;
3839 
3840 	vmx->nested.msrs.misc_low = data;
3841 	vmx->nested.msrs.misc_high = data >> 32;
3842 
3843 	/*
3844 	 * If L1 has read-only VM-exit information fields, use the
3845 	 * less permissive vmx_vmwrite_bitmap to specify write
3846 	 * permissions for the shadow VMCS.
3847 	 */
3848 	if (enable_shadow_vmcs && !nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
3849 		vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
3850 
3851 	return 0;
3852 }
3853 
vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx * vmx,u64 data)3854 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3855 {
3856 	u64 vmx_ept_vpid_cap;
3857 
3858 	vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.msrs.ept_caps,
3859 					   vmx->nested.msrs.vpid_caps);
3860 
3861 	/* Every bit is either reserved or a feature bit. */
3862 	if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3863 		return -EINVAL;
3864 
3865 	vmx->nested.msrs.ept_caps = data;
3866 	vmx->nested.msrs.vpid_caps = data >> 32;
3867 	return 0;
3868 }
3869 
vmx_restore_fixed0_msr(struct vcpu_vmx * vmx,u32 msr_index,u64 data)3870 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3871 {
3872 	u64 *msr;
3873 
3874 	switch (msr_index) {
3875 	case MSR_IA32_VMX_CR0_FIXED0:
3876 		msr = &vmx->nested.msrs.cr0_fixed0;
3877 		break;
3878 	case MSR_IA32_VMX_CR4_FIXED0:
3879 		msr = &vmx->nested.msrs.cr4_fixed0;
3880 		break;
3881 	default:
3882 		BUG();
3883 	}
3884 
3885 	/*
3886 	 * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3887 	 * must be 1 in the restored value.
3888 	 */
3889 	if (!is_bitwise_subset(data, *msr, -1ULL))
3890 		return -EINVAL;
3891 
3892 	*msr = data;
3893 	return 0;
3894 }
3895 
3896 /*
3897  * Called when userspace is restoring VMX MSRs.
3898  *
3899  * Returns 0 on success, non-0 otherwise.
3900  */
vmx_set_vmx_msr(struct kvm_vcpu * vcpu,u32 msr_index,u64 data)3901 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3902 {
3903 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3904 
3905 	/*
3906 	 * Don't allow changes to the VMX capability MSRs while the vCPU
3907 	 * is in VMX operation.
3908 	 */
3909 	if (vmx->nested.vmxon)
3910 		return -EBUSY;
3911 
3912 	switch (msr_index) {
3913 	case MSR_IA32_VMX_BASIC:
3914 		return vmx_restore_vmx_basic(vmx, data);
3915 	case MSR_IA32_VMX_PINBASED_CTLS:
3916 	case MSR_IA32_VMX_PROCBASED_CTLS:
3917 	case MSR_IA32_VMX_EXIT_CTLS:
3918 	case MSR_IA32_VMX_ENTRY_CTLS:
3919 		/*
3920 		 * The "non-true" VMX capability MSRs are generated from the
3921 		 * "true" MSRs, so we do not support restoring them directly.
3922 		 *
3923 		 * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3924 		 * should restore the "true" MSRs with the must-be-1 bits
3925 		 * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3926 		 * DEFAULT SETTINGS".
3927 		 */
3928 		return -EINVAL;
3929 	case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3930 	case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3931 	case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3932 	case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3933 	case MSR_IA32_VMX_PROCBASED_CTLS2:
3934 		return vmx_restore_control_msr(vmx, msr_index, data);
3935 	case MSR_IA32_VMX_MISC:
3936 		return vmx_restore_vmx_misc(vmx, data);
3937 	case MSR_IA32_VMX_CR0_FIXED0:
3938 	case MSR_IA32_VMX_CR4_FIXED0:
3939 		return vmx_restore_fixed0_msr(vmx, msr_index, data);
3940 	case MSR_IA32_VMX_CR0_FIXED1:
3941 	case MSR_IA32_VMX_CR4_FIXED1:
3942 		/*
3943 		 * These MSRs are generated based on the vCPU's CPUID, so we
3944 		 * do not support restoring them directly.
3945 		 */
3946 		return -EINVAL;
3947 	case MSR_IA32_VMX_EPT_VPID_CAP:
3948 		return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3949 	case MSR_IA32_VMX_VMCS_ENUM:
3950 		vmx->nested.msrs.vmcs_enum = data;
3951 		return 0;
3952 	default:
3953 		/*
3954 		 * The rest of the VMX capability MSRs do not support restore.
3955 		 */
3956 		return -EINVAL;
3957 	}
3958 }
3959 
3960 /* Returns 0 on success, non-0 otherwise. */
vmx_get_vmx_msr(struct nested_vmx_msrs * msrs,u32 msr_index,u64 * pdata)3961 static int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
3962 {
3963 	switch (msr_index) {
3964 	case MSR_IA32_VMX_BASIC:
3965 		*pdata = msrs->basic;
3966 		break;
3967 	case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3968 	case MSR_IA32_VMX_PINBASED_CTLS:
3969 		*pdata = vmx_control_msr(
3970 			msrs->pinbased_ctls_low,
3971 			msrs->pinbased_ctls_high);
3972 		if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3973 			*pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3974 		break;
3975 	case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3976 	case MSR_IA32_VMX_PROCBASED_CTLS:
3977 		*pdata = vmx_control_msr(
3978 			msrs->procbased_ctls_low,
3979 			msrs->procbased_ctls_high);
3980 		if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3981 			*pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3982 		break;
3983 	case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3984 	case MSR_IA32_VMX_EXIT_CTLS:
3985 		*pdata = vmx_control_msr(
3986 			msrs->exit_ctls_low,
3987 			msrs->exit_ctls_high);
3988 		if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3989 			*pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3990 		break;
3991 	case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3992 	case MSR_IA32_VMX_ENTRY_CTLS:
3993 		*pdata = vmx_control_msr(
3994 			msrs->entry_ctls_low,
3995 			msrs->entry_ctls_high);
3996 		if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
3997 			*pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3998 		break;
3999 	case MSR_IA32_VMX_MISC:
4000 		*pdata = vmx_control_msr(
4001 			msrs->misc_low,
4002 			msrs->misc_high);
4003 		break;
4004 	case MSR_IA32_VMX_CR0_FIXED0:
4005 		*pdata = msrs->cr0_fixed0;
4006 		break;
4007 	case MSR_IA32_VMX_CR0_FIXED1:
4008 		*pdata = msrs->cr0_fixed1;
4009 		break;
4010 	case MSR_IA32_VMX_CR4_FIXED0:
4011 		*pdata = msrs->cr4_fixed0;
4012 		break;
4013 	case MSR_IA32_VMX_CR4_FIXED1:
4014 		*pdata = msrs->cr4_fixed1;
4015 		break;
4016 	case MSR_IA32_VMX_VMCS_ENUM:
4017 		*pdata = msrs->vmcs_enum;
4018 		break;
4019 	case MSR_IA32_VMX_PROCBASED_CTLS2:
4020 		*pdata = vmx_control_msr(
4021 			msrs->secondary_ctls_low,
4022 			msrs->secondary_ctls_high);
4023 		break;
4024 	case MSR_IA32_VMX_EPT_VPID_CAP:
4025 		*pdata = msrs->ept_caps |
4026 			((u64)msrs->vpid_caps << 32);
4027 		break;
4028 	case MSR_IA32_VMX_VMFUNC:
4029 		*pdata = msrs->vmfunc_controls;
4030 		break;
4031 	default:
4032 		return 1;
4033 	}
4034 
4035 	return 0;
4036 }
4037 
vmx_feature_control_msr_valid(struct kvm_vcpu * vcpu,uint64_t val)4038 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
4039 						 uint64_t val)
4040 {
4041 	uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
4042 
4043 	return !(val & ~valid_bits);
4044 }
4045 
vmx_get_msr_feature(struct kvm_msr_entry * msr)4046 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
4047 {
4048 	switch (msr->index) {
4049 	case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4050 		if (!nested)
4051 			return 1;
4052 		return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
4053 	default:
4054 		return 1;
4055 	}
4056 
4057 	return 0;
4058 }
4059 
4060 /*
4061  * Reads an msr value (of 'msr_index') into 'pdata'.
4062  * Returns 0 on success, non-0 otherwise.
4063  * Assumes vcpu_load() was already called.
4064  */
vmx_get_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4065 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4066 {
4067 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4068 	struct shared_msr_entry *msr;
4069 
4070 	switch (msr_info->index) {
4071 #ifdef CONFIG_X86_64
4072 	case MSR_FS_BASE:
4073 		msr_info->data = vmcs_readl(GUEST_FS_BASE);
4074 		break;
4075 	case MSR_GS_BASE:
4076 		msr_info->data = vmcs_readl(GUEST_GS_BASE);
4077 		break;
4078 	case MSR_KERNEL_GS_BASE:
4079 		msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
4080 		break;
4081 #endif
4082 	case MSR_EFER:
4083 		return kvm_get_msr_common(vcpu, msr_info);
4084 	case MSR_IA32_SPEC_CTRL:
4085 		if (!msr_info->host_initiated &&
4086 		    !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4087 			return 1;
4088 
4089 		msr_info->data = to_vmx(vcpu)->spec_ctrl;
4090 		break;
4091 	case MSR_IA32_ARCH_CAPABILITIES:
4092 		if (!msr_info->host_initiated &&
4093 		    !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4094 			return 1;
4095 		msr_info->data = to_vmx(vcpu)->arch_capabilities;
4096 		break;
4097 	case MSR_IA32_SYSENTER_CS:
4098 		msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
4099 		break;
4100 	case MSR_IA32_SYSENTER_EIP:
4101 		msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
4102 		break;
4103 	case MSR_IA32_SYSENTER_ESP:
4104 		msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
4105 		break;
4106 	case MSR_IA32_BNDCFGS:
4107 		if (!kvm_mpx_supported() ||
4108 		    (!msr_info->host_initiated &&
4109 		     !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
4110 			return 1;
4111 		msr_info->data = vmcs_read64(GUEST_BNDCFGS);
4112 		break;
4113 	case MSR_IA32_MCG_EXT_CTL:
4114 		if (!msr_info->host_initiated &&
4115 		    !(vmx->msr_ia32_feature_control &
4116 		      FEATURE_CONTROL_LMCE))
4117 			return 1;
4118 		msr_info->data = vcpu->arch.mcg_ext_ctl;
4119 		break;
4120 	case MSR_IA32_FEATURE_CONTROL:
4121 		msr_info->data = vmx->msr_ia32_feature_control;
4122 		break;
4123 	case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4124 		if (!nested_vmx_allowed(vcpu))
4125 			return 1;
4126 		return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
4127 				       &msr_info->data);
4128 	case MSR_IA32_XSS:
4129 		if (!vmx_xsaves_supported())
4130 			return 1;
4131 		msr_info->data = vcpu->arch.ia32_xss;
4132 		break;
4133 	case MSR_TSC_AUX:
4134 		if (!msr_info->host_initiated &&
4135 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4136 			return 1;
4137 		/* Otherwise falls through */
4138 	default:
4139 		msr = find_msr_entry(vmx, msr_info->index);
4140 		if (msr) {
4141 			msr_info->data = msr->data;
4142 			break;
4143 		}
4144 		return kvm_get_msr_common(vcpu, msr_info);
4145 	}
4146 
4147 	return 0;
4148 }
4149 
4150 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
4151 
4152 /*
4153  * Writes msr value into into the appropriate "register".
4154  * Returns 0 on success, non-0 otherwise.
4155  * Assumes vcpu_load() was already called.
4156  */
vmx_set_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4157 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4158 {
4159 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4160 	struct shared_msr_entry *msr;
4161 	int ret = 0;
4162 	u32 msr_index = msr_info->index;
4163 	u64 data = msr_info->data;
4164 
4165 	switch (msr_index) {
4166 	case MSR_EFER:
4167 		ret = kvm_set_msr_common(vcpu, msr_info);
4168 		break;
4169 #ifdef CONFIG_X86_64
4170 	case MSR_FS_BASE:
4171 		vmx_segment_cache_clear(vmx);
4172 		vmcs_writel(GUEST_FS_BASE, data);
4173 		break;
4174 	case MSR_GS_BASE:
4175 		vmx_segment_cache_clear(vmx);
4176 		vmcs_writel(GUEST_GS_BASE, data);
4177 		break;
4178 	case MSR_KERNEL_GS_BASE:
4179 		vmx_write_guest_kernel_gs_base(vmx, data);
4180 		break;
4181 #endif
4182 	case MSR_IA32_SYSENTER_CS:
4183 		vmcs_write32(GUEST_SYSENTER_CS, data);
4184 		break;
4185 	case MSR_IA32_SYSENTER_EIP:
4186 		vmcs_writel(GUEST_SYSENTER_EIP, data);
4187 		break;
4188 	case MSR_IA32_SYSENTER_ESP:
4189 		vmcs_writel(GUEST_SYSENTER_ESP, data);
4190 		break;
4191 	case MSR_IA32_BNDCFGS:
4192 		if (!kvm_mpx_supported() ||
4193 		    (!msr_info->host_initiated &&
4194 		     !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
4195 			return 1;
4196 		if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
4197 		    (data & MSR_IA32_BNDCFGS_RSVD))
4198 			return 1;
4199 		vmcs_write64(GUEST_BNDCFGS, data);
4200 		break;
4201 	case MSR_IA32_SPEC_CTRL:
4202 		if (!msr_info->host_initiated &&
4203 		    !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4204 			return 1;
4205 
4206 		/* The STIBP bit doesn't fault even if it's not advertised */
4207 		if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
4208 			return 1;
4209 
4210 		vmx->spec_ctrl = data;
4211 
4212 		if (!data)
4213 			break;
4214 
4215 		/*
4216 		 * For non-nested:
4217 		 * When it's written (to non-zero) for the first time, pass
4218 		 * it through.
4219 		 *
4220 		 * For nested:
4221 		 * The handling of the MSR bitmap for L2 guests is done in
4222 		 * nested_vmx_merge_msr_bitmap. We should not touch the
4223 		 * vmcs02.msr_bitmap here since it gets completely overwritten
4224 		 * in the merging. We update the vmcs01 here for L1 as well
4225 		 * since it will end up touching the MSR anyway now.
4226 		 */
4227 		vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
4228 					      MSR_IA32_SPEC_CTRL,
4229 					      MSR_TYPE_RW);
4230 		break;
4231 	case MSR_IA32_PRED_CMD:
4232 		if (!msr_info->host_initiated &&
4233 		    !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4234 			return 1;
4235 
4236 		if (data & ~PRED_CMD_IBPB)
4237 			return 1;
4238 
4239 		if (!data)
4240 			break;
4241 
4242 		wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4243 
4244 		/*
4245 		 * For non-nested:
4246 		 * When it's written (to non-zero) for the first time, pass
4247 		 * it through.
4248 		 *
4249 		 * For nested:
4250 		 * The handling of the MSR bitmap for L2 guests is done in
4251 		 * nested_vmx_merge_msr_bitmap. We should not touch the
4252 		 * vmcs02.msr_bitmap here since it gets completely overwritten
4253 		 * in the merging.
4254 		 */
4255 		vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
4256 					      MSR_TYPE_W);
4257 		break;
4258 	case MSR_IA32_ARCH_CAPABILITIES:
4259 		if (!msr_info->host_initiated)
4260 			return 1;
4261 		vmx->arch_capabilities = data;
4262 		break;
4263 	case MSR_IA32_CR_PAT:
4264 		if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4265 			if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4266 				return 1;
4267 			vmcs_write64(GUEST_IA32_PAT, data);
4268 			vcpu->arch.pat = data;
4269 			break;
4270 		}
4271 		ret = kvm_set_msr_common(vcpu, msr_info);
4272 		break;
4273 	case MSR_IA32_TSC_ADJUST:
4274 		ret = kvm_set_msr_common(vcpu, msr_info);
4275 		break;
4276 	case MSR_IA32_MCG_EXT_CTL:
4277 		if ((!msr_info->host_initiated &&
4278 		     !(to_vmx(vcpu)->msr_ia32_feature_control &
4279 		       FEATURE_CONTROL_LMCE)) ||
4280 		    (data & ~MCG_EXT_CTL_LMCE_EN))
4281 			return 1;
4282 		vcpu->arch.mcg_ext_ctl = data;
4283 		break;
4284 	case MSR_IA32_FEATURE_CONTROL:
4285 		if (!vmx_feature_control_msr_valid(vcpu, data) ||
4286 		    (to_vmx(vcpu)->msr_ia32_feature_control &
4287 		     FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
4288 			return 1;
4289 		vmx->msr_ia32_feature_control = data;
4290 		if (msr_info->host_initiated && data == 0)
4291 			vmx_leave_nested(vcpu);
4292 		break;
4293 	case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4294 		if (!msr_info->host_initiated)
4295 			return 1; /* they are read-only */
4296 		if (!nested_vmx_allowed(vcpu))
4297 			return 1;
4298 		return vmx_set_vmx_msr(vcpu, msr_index, data);
4299 	case MSR_IA32_XSS:
4300 		if (!vmx_xsaves_supported())
4301 			return 1;
4302 		/*
4303 		 * The only supported bit as of Skylake is bit 8, but
4304 		 * it is not supported on KVM.
4305 		 */
4306 		if (data != 0)
4307 			return 1;
4308 		vcpu->arch.ia32_xss = data;
4309 		if (vcpu->arch.ia32_xss != host_xss)
4310 			add_atomic_switch_msr(vmx, MSR_IA32_XSS,
4311 				vcpu->arch.ia32_xss, host_xss, false);
4312 		else
4313 			clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
4314 		break;
4315 	case MSR_TSC_AUX:
4316 		if (!msr_info->host_initiated &&
4317 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4318 			return 1;
4319 		/* Check reserved bit, higher 32 bits should be zero */
4320 		if ((data >> 32) != 0)
4321 			return 1;
4322 		/* Otherwise falls through */
4323 	default:
4324 		msr = find_msr_entry(vmx, msr_index);
4325 		if (msr) {
4326 			u64 old_msr_data = msr->data;
4327 			msr->data = data;
4328 			if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
4329 				preempt_disable();
4330 				ret = kvm_set_shared_msr(msr->index, msr->data,
4331 							 msr->mask);
4332 				preempt_enable();
4333 				if (ret)
4334 					msr->data = old_msr_data;
4335 			}
4336 			break;
4337 		}
4338 		ret = kvm_set_msr_common(vcpu, msr_info);
4339 	}
4340 
4341 	return ret;
4342 }
4343 
vmx_cache_reg(struct kvm_vcpu * vcpu,enum kvm_reg reg)4344 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
4345 {
4346 	__set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
4347 	switch (reg) {
4348 	case VCPU_REGS_RSP:
4349 		vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
4350 		break;
4351 	case VCPU_REGS_RIP:
4352 		vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
4353 		break;
4354 	case VCPU_EXREG_PDPTR:
4355 		if (enable_ept)
4356 			ept_save_pdptrs(vcpu);
4357 		break;
4358 	default:
4359 		break;
4360 	}
4361 }
4362 
cpu_has_kvm_support(void)4363 static __init int cpu_has_kvm_support(void)
4364 {
4365 	return cpu_has_vmx();
4366 }
4367 
vmx_disabled_by_bios(void)4368 static __init int vmx_disabled_by_bios(void)
4369 {
4370 	u64 msr;
4371 
4372 	rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
4373 	if (msr & FEATURE_CONTROL_LOCKED) {
4374 		/* launched w/ TXT and VMX disabled */
4375 		if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4376 			&& tboot_enabled())
4377 			return 1;
4378 		/* launched w/o TXT and VMX only enabled w/ TXT */
4379 		if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4380 			&& (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4381 			&& !tboot_enabled()) {
4382 			printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
4383 				"activate TXT before enabling KVM\n");
4384 			return 1;
4385 		}
4386 		/* launched w/o TXT and VMX disabled */
4387 		if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4388 			&& !tboot_enabled())
4389 			return 1;
4390 	}
4391 
4392 	return 0;
4393 }
4394 
kvm_cpu_vmxon(u64 addr)4395 static void kvm_cpu_vmxon(u64 addr)
4396 {
4397 	cr4_set_bits(X86_CR4_VMXE);
4398 	intel_pt_handle_vmx(1);
4399 
4400 	asm volatile (ASM_VMX_VMXON_RAX
4401 			: : "a"(&addr), "m"(addr)
4402 			: "memory", "cc");
4403 }
4404 
hardware_enable(void)4405 static int hardware_enable(void)
4406 {
4407 	int cpu = raw_smp_processor_id();
4408 	u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
4409 	u64 old, test_bits;
4410 
4411 	if (cr4_read_shadow() & X86_CR4_VMXE)
4412 		return -EBUSY;
4413 
4414 	/*
4415 	 * This can happen if we hot-added a CPU but failed to allocate
4416 	 * VP assist page for it.
4417 	 */
4418 	if (static_branch_unlikely(&enable_evmcs) &&
4419 	    !hv_get_vp_assist_page(cpu))
4420 		return -EFAULT;
4421 
4422 	INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
4423 	INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
4424 	spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4425 
4426 	/*
4427 	 * Now we can enable the vmclear operation in kdump
4428 	 * since the loaded_vmcss_on_cpu list on this cpu
4429 	 * has been initialized.
4430 	 *
4431 	 * Though the cpu is not in VMX operation now, there
4432 	 * is no problem to enable the vmclear operation
4433 	 * for the loaded_vmcss_on_cpu list is empty!
4434 	 */
4435 	crash_enable_local_vmclear(cpu);
4436 
4437 	rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
4438 
4439 	test_bits = FEATURE_CONTROL_LOCKED;
4440 	test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
4441 	if (tboot_enabled())
4442 		test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
4443 
4444 	if ((old & test_bits) != test_bits) {
4445 		/* enable and lock */
4446 		wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
4447 	}
4448 	kvm_cpu_vmxon(phys_addr);
4449 	if (enable_ept)
4450 		ept_sync_global();
4451 
4452 	return 0;
4453 }
4454 
vmclear_local_loaded_vmcss(void)4455 static void vmclear_local_loaded_vmcss(void)
4456 {
4457 	int cpu = raw_smp_processor_id();
4458 	struct loaded_vmcs *v, *n;
4459 
4460 	list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
4461 				 loaded_vmcss_on_cpu_link)
4462 		__loaded_vmcs_clear(v);
4463 }
4464 
4465 
4466 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
4467  * tricks.
4468  */
kvm_cpu_vmxoff(void)4469 static void kvm_cpu_vmxoff(void)
4470 {
4471 	asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
4472 
4473 	intel_pt_handle_vmx(0);
4474 	cr4_clear_bits(X86_CR4_VMXE);
4475 }
4476 
hardware_disable(void)4477 static void hardware_disable(void)
4478 {
4479 	vmclear_local_loaded_vmcss();
4480 	kvm_cpu_vmxoff();
4481 }
4482 
adjust_vmx_controls(u32 ctl_min,u32 ctl_opt,u32 msr,u32 * result)4483 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
4484 				      u32 msr, u32 *result)
4485 {
4486 	u32 vmx_msr_low, vmx_msr_high;
4487 	u32 ctl = ctl_min | ctl_opt;
4488 
4489 	rdmsr(msr, vmx_msr_low, vmx_msr_high);
4490 
4491 	ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
4492 	ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
4493 
4494 	/* Ensure minimum (required) set of control bits are supported. */
4495 	if (ctl_min & ~ctl)
4496 		return -EIO;
4497 
4498 	*result = ctl;
4499 	return 0;
4500 }
4501 
allow_1_setting(u32 msr,u32 ctl)4502 static __init bool allow_1_setting(u32 msr, u32 ctl)
4503 {
4504 	u32 vmx_msr_low, vmx_msr_high;
4505 
4506 	rdmsr(msr, vmx_msr_low, vmx_msr_high);
4507 	return vmx_msr_high & ctl;
4508 }
4509 
setup_vmcs_config(struct vmcs_config * vmcs_conf)4510 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
4511 {
4512 	u32 vmx_msr_low, vmx_msr_high;
4513 	u32 min, opt, min2, opt2;
4514 	u32 _pin_based_exec_control = 0;
4515 	u32 _cpu_based_exec_control = 0;
4516 	u32 _cpu_based_2nd_exec_control = 0;
4517 	u32 _vmexit_control = 0;
4518 	u32 _vmentry_control = 0;
4519 
4520 	memset(vmcs_conf, 0, sizeof(*vmcs_conf));
4521 	min = CPU_BASED_HLT_EXITING |
4522 #ifdef CONFIG_X86_64
4523 	      CPU_BASED_CR8_LOAD_EXITING |
4524 	      CPU_BASED_CR8_STORE_EXITING |
4525 #endif
4526 	      CPU_BASED_CR3_LOAD_EXITING |
4527 	      CPU_BASED_CR3_STORE_EXITING |
4528 	      CPU_BASED_UNCOND_IO_EXITING |
4529 	      CPU_BASED_MOV_DR_EXITING |
4530 	      CPU_BASED_USE_TSC_OFFSETING |
4531 	      CPU_BASED_MWAIT_EXITING |
4532 	      CPU_BASED_MONITOR_EXITING |
4533 	      CPU_BASED_INVLPG_EXITING |
4534 	      CPU_BASED_RDPMC_EXITING;
4535 
4536 	opt = CPU_BASED_TPR_SHADOW |
4537 	      CPU_BASED_USE_MSR_BITMAPS |
4538 	      CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
4539 	if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
4540 				&_cpu_based_exec_control) < 0)
4541 		return -EIO;
4542 #ifdef CONFIG_X86_64
4543 	if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4544 		_cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
4545 					   ~CPU_BASED_CR8_STORE_EXITING;
4546 #endif
4547 	if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
4548 		min2 = 0;
4549 		opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
4550 			SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4551 			SECONDARY_EXEC_WBINVD_EXITING |
4552 			SECONDARY_EXEC_ENABLE_VPID |
4553 			SECONDARY_EXEC_ENABLE_EPT |
4554 			SECONDARY_EXEC_UNRESTRICTED_GUEST |
4555 			SECONDARY_EXEC_PAUSE_LOOP_EXITING |
4556 			SECONDARY_EXEC_DESC |
4557 			SECONDARY_EXEC_RDTSCP |
4558 			SECONDARY_EXEC_ENABLE_INVPCID |
4559 			SECONDARY_EXEC_APIC_REGISTER_VIRT |
4560 			SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
4561 			SECONDARY_EXEC_SHADOW_VMCS |
4562 			SECONDARY_EXEC_XSAVES |
4563 			SECONDARY_EXEC_RDSEED_EXITING |
4564 			SECONDARY_EXEC_RDRAND_EXITING |
4565 			SECONDARY_EXEC_ENABLE_PML |
4566 			SECONDARY_EXEC_TSC_SCALING |
4567 			SECONDARY_EXEC_ENABLE_VMFUNC |
4568 			SECONDARY_EXEC_ENCLS_EXITING;
4569 		if (adjust_vmx_controls(min2, opt2,
4570 					MSR_IA32_VMX_PROCBASED_CTLS2,
4571 					&_cpu_based_2nd_exec_control) < 0)
4572 			return -EIO;
4573 	}
4574 #ifndef CONFIG_X86_64
4575 	if (!(_cpu_based_2nd_exec_control &
4576 				SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
4577 		_cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
4578 #endif
4579 
4580 	if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4581 		_cpu_based_2nd_exec_control &= ~(
4582 				SECONDARY_EXEC_APIC_REGISTER_VIRT |
4583 				SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4584 				SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4585 
4586 	rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
4587 		&vmx_capability.ept, &vmx_capability.vpid);
4588 
4589 	if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
4590 		/* CR3 accesses and invlpg don't need to cause VM Exits when EPT
4591 		   enabled */
4592 		_cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4593 					     CPU_BASED_CR3_STORE_EXITING |
4594 					     CPU_BASED_INVLPG_EXITING);
4595 	} else if (vmx_capability.ept) {
4596 		vmx_capability.ept = 0;
4597 		pr_warn_once("EPT CAP should not exist if not support "
4598 				"1-setting enable EPT VM-execution control\n");
4599 	}
4600 	if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
4601 		vmx_capability.vpid) {
4602 		vmx_capability.vpid = 0;
4603 		pr_warn_once("VPID CAP should not exist if not support "
4604 				"1-setting enable VPID VM-execution control\n");
4605 	}
4606 
4607 	min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
4608 #ifdef CONFIG_X86_64
4609 	min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
4610 #endif
4611 	opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
4612 		VM_EXIT_CLEAR_BNDCFGS;
4613 	if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
4614 				&_vmexit_control) < 0)
4615 		return -EIO;
4616 
4617 	min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
4618 	opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
4619 		 PIN_BASED_VMX_PREEMPTION_TIMER;
4620 	if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
4621 				&_pin_based_exec_control) < 0)
4622 		return -EIO;
4623 
4624 	if (cpu_has_broken_vmx_preemption_timer())
4625 		_pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4626 	if (!(_cpu_based_2nd_exec_control &
4627 		SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
4628 		_pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
4629 
4630 	min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
4631 	opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
4632 	if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
4633 				&_vmentry_control) < 0)
4634 		return -EIO;
4635 
4636 	rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
4637 
4638 	/* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
4639 	if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
4640 		return -EIO;
4641 
4642 #ifdef CONFIG_X86_64
4643 	/* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
4644 	if (vmx_msr_high & (1u<<16))
4645 		return -EIO;
4646 #endif
4647 
4648 	/* Require Write-Back (WB) memory type for VMCS accesses. */
4649 	if (((vmx_msr_high >> 18) & 15) != 6)
4650 		return -EIO;
4651 
4652 	vmcs_conf->size = vmx_msr_high & 0x1fff;
4653 	vmcs_conf->order = get_order(vmcs_conf->size);
4654 	vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
4655 
4656 	vmcs_conf->revision_id = vmx_msr_low;
4657 
4658 	vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
4659 	vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
4660 	vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
4661 	vmcs_conf->vmexit_ctrl         = _vmexit_control;
4662 	vmcs_conf->vmentry_ctrl        = _vmentry_control;
4663 
4664 	if (static_branch_unlikely(&enable_evmcs))
4665 		evmcs_sanitize_exec_ctrls(vmcs_conf);
4666 
4667 	cpu_has_load_ia32_efer =
4668 		allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4669 				VM_ENTRY_LOAD_IA32_EFER)
4670 		&& allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4671 				   VM_EXIT_LOAD_IA32_EFER);
4672 
4673 	cpu_has_load_perf_global_ctrl =
4674 		allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4675 				VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
4676 		&& allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4677 				   VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
4678 
4679 	/*
4680 	 * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
4681 	 * but due to errata below it can't be used. Workaround is to use
4682 	 * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
4683 	 *
4684 	 * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
4685 	 *
4686 	 * AAK155             (model 26)
4687 	 * AAP115             (model 30)
4688 	 * AAT100             (model 37)
4689 	 * BC86,AAY89,BD102   (model 44)
4690 	 * BA97               (model 46)
4691 	 *
4692 	 */
4693 	if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
4694 		switch (boot_cpu_data.x86_model) {
4695 		case 26:
4696 		case 30:
4697 		case 37:
4698 		case 44:
4699 		case 46:
4700 			cpu_has_load_perf_global_ctrl = false;
4701 			printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
4702 					"does not work properly. Using workaround\n");
4703 			break;
4704 		default:
4705 			break;
4706 		}
4707 	}
4708 
4709 	if (boot_cpu_has(X86_FEATURE_XSAVES))
4710 		rdmsrl(MSR_IA32_XSS, host_xss);
4711 
4712 	return 0;
4713 }
4714 
alloc_vmcs_cpu(bool shadow,int cpu)4715 static struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
4716 {
4717 	int node = cpu_to_node(cpu);
4718 	struct page *pages;
4719 	struct vmcs *vmcs;
4720 
4721 	pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
4722 	if (!pages)
4723 		return NULL;
4724 	vmcs = page_address(pages);
4725 	memset(vmcs, 0, vmcs_config.size);
4726 
4727 	/* KVM supports Enlightened VMCS v1 only */
4728 	if (static_branch_unlikely(&enable_evmcs))
4729 		vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
4730 	else
4731 		vmcs->hdr.revision_id = vmcs_config.revision_id;
4732 
4733 	if (shadow)
4734 		vmcs->hdr.shadow_vmcs = 1;
4735 	return vmcs;
4736 }
4737 
free_vmcs(struct vmcs * vmcs)4738 static void free_vmcs(struct vmcs *vmcs)
4739 {
4740 	free_pages((unsigned long)vmcs, vmcs_config.order);
4741 }
4742 
4743 /*
4744  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
4745  */
free_loaded_vmcs(struct loaded_vmcs * loaded_vmcs)4746 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4747 {
4748 	if (!loaded_vmcs->vmcs)
4749 		return;
4750 	loaded_vmcs_clear(loaded_vmcs);
4751 	free_vmcs(loaded_vmcs->vmcs);
4752 	loaded_vmcs->vmcs = NULL;
4753 	if (loaded_vmcs->msr_bitmap)
4754 		free_page((unsigned long)loaded_vmcs->msr_bitmap);
4755 	WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
4756 }
4757 
alloc_vmcs(bool shadow)4758 static struct vmcs *alloc_vmcs(bool shadow)
4759 {
4760 	return alloc_vmcs_cpu(shadow, raw_smp_processor_id());
4761 }
4762 
alloc_loaded_vmcs(struct loaded_vmcs * loaded_vmcs)4763 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4764 {
4765 	loaded_vmcs->vmcs = alloc_vmcs(false);
4766 	if (!loaded_vmcs->vmcs)
4767 		return -ENOMEM;
4768 
4769 	loaded_vmcs->shadow_vmcs = NULL;
4770 	loaded_vmcs_init(loaded_vmcs);
4771 
4772 	if (cpu_has_vmx_msr_bitmap()) {
4773 		loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
4774 		if (!loaded_vmcs->msr_bitmap)
4775 			goto out_vmcs;
4776 		memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
4777 
4778 		if (IS_ENABLED(CONFIG_HYPERV) &&
4779 		    static_branch_unlikely(&enable_evmcs) &&
4780 		    (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
4781 			struct hv_enlightened_vmcs *evmcs =
4782 				(struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
4783 
4784 			evmcs->hv_enlightenments_control.msr_bitmap = 1;
4785 		}
4786 	}
4787 
4788 	memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
4789 
4790 	return 0;
4791 
4792 out_vmcs:
4793 	free_loaded_vmcs(loaded_vmcs);
4794 	return -ENOMEM;
4795 }
4796 
free_kvm_area(void)4797 static void free_kvm_area(void)
4798 {
4799 	int cpu;
4800 
4801 	for_each_possible_cpu(cpu) {
4802 		free_vmcs(per_cpu(vmxarea, cpu));
4803 		per_cpu(vmxarea, cpu) = NULL;
4804 	}
4805 }
4806 
4807 enum vmcs_field_width {
4808 	VMCS_FIELD_WIDTH_U16 = 0,
4809 	VMCS_FIELD_WIDTH_U64 = 1,
4810 	VMCS_FIELD_WIDTH_U32 = 2,
4811 	VMCS_FIELD_WIDTH_NATURAL_WIDTH = 3
4812 };
4813 
vmcs_field_width(unsigned long field)4814 static inline int vmcs_field_width(unsigned long field)
4815 {
4816 	if (0x1 & field)	/* the *_HIGH fields are all 32 bit */
4817 		return VMCS_FIELD_WIDTH_U32;
4818 	return (field >> 13) & 0x3 ;
4819 }
4820 
vmcs_field_readonly(unsigned long field)4821 static inline int vmcs_field_readonly(unsigned long field)
4822 {
4823 	return (((field >> 10) & 0x3) == 1);
4824 }
4825 
init_vmcs_shadow_fields(void)4826 static void init_vmcs_shadow_fields(void)
4827 {
4828 	int i, j;
4829 
4830 	for (i = j = 0; i < max_shadow_read_only_fields; i++) {
4831 		u16 field = shadow_read_only_fields[i];
4832 		if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4833 		    (i + 1 == max_shadow_read_only_fields ||
4834 		     shadow_read_only_fields[i + 1] != field + 1))
4835 			pr_err("Missing field from shadow_read_only_field %x\n",
4836 			       field + 1);
4837 
4838 		clear_bit(field, vmx_vmread_bitmap);
4839 #ifdef CONFIG_X86_64
4840 		if (field & 1)
4841 			continue;
4842 #endif
4843 		if (j < i)
4844 			shadow_read_only_fields[j] = field;
4845 		j++;
4846 	}
4847 	max_shadow_read_only_fields = j;
4848 
4849 	for (i = j = 0; i < max_shadow_read_write_fields; i++) {
4850 		u16 field = shadow_read_write_fields[i];
4851 		if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4852 		    (i + 1 == max_shadow_read_write_fields ||
4853 		     shadow_read_write_fields[i + 1] != field + 1))
4854 			pr_err("Missing field from shadow_read_write_field %x\n",
4855 			       field + 1);
4856 
4857 		/*
4858 		 * PML and the preemption timer can be emulated, but the
4859 		 * processor cannot vmwrite to fields that don't exist
4860 		 * on bare metal.
4861 		 */
4862 		switch (field) {
4863 		case GUEST_PML_INDEX:
4864 			if (!cpu_has_vmx_pml())
4865 				continue;
4866 			break;
4867 		case VMX_PREEMPTION_TIMER_VALUE:
4868 			if (!cpu_has_vmx_preemption_timer())
4869 				continue;
4870 			break;
4871 		case GUEST_INTR_STATUS:
4872 			if (!cpu_has_vmx_apicv())
4873 				continue;
4874 			break;
4875 		default:
4876 			break;
4877 		}
4878 
4879 		clear_bit(field, vmx_vmwrite_bitmap);
4880 		clear_bit(field, vmx_vmread_bitmap);
4881 #ifdef CONFIG_X86_64
4882 		if (field & 1)
4883 			continue;
4884 #endif
4885 		if (j < i)
4886 			shadow_read_write_fields[j] = field;
4887 		j++;
4888 	}
4889 	max_shadow_read_write_fields = j;
4890 }
4891 
alloc_kvm_area(void)4892 static __init int alloc_kvm_area(void)
4893 {
4894 	int cpu;
4895 
4896 	for_each_possible_cpu(cpu) {
4897 		struct vmcs *vmcs;
4898 
4899 		vmcs = alloc_vmcs_cpu(false, cpu);
4900 		if (!vmcs) {
4901 			free_kvm_area();
4902 			return -ENOMEM;
4903 		}
4904 
4905 		/*
4906 		 * When eVMCS is enabled, alloc_vmcs_cpu() sets
4907 		 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
4908 		 * revision_id reported by MSR_IA32_VMX_BASIC.
4909 		 *
4910 		 * However, even though not explictly documented by
4911 		 * TLFS, VMXArea passed as VMXON argument should
4912 		 * still be marked with revision_id reported by
4913 		 * physical CPU.
4914 		 */
4915 		if (static_branch_unlikely(&enable_evmcs))
4916 			vmcs->hdr.revision_id = vmcs_config.revision_id;
4917 
4918 		per_cpu(vmxarea, cpu) = vmcs;
4919 	}
4920 	return 0;
4921 }
4922 
fix_pmode_seg(struct kvm_vcpu * vcpu,int seg,struct kvm_segment * save)4923 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4924 		struct kvm_segment *save)
4925 {
4926 	if (!emulate_invalid_guest_state) {
4927 		/*
4928 		 * CS and SS RPL should be equal during guest entry according
4929 		 * to VMX spec, but in reality it is not always so. Since vcpu
4930 		 * is in the middle of the transition from real mode to
4931 		 * protected mode it is safe to assume that RPL 0 is a good
4932 		 * default value.
4933 		 */
4934 		if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4935 			save->selector &= ~SEGMENT_RPL_MASK;
4936 		save->dpl = save->selector & SEGMENT_RPL_MASK;
4937 		save->s = 1;
4938 	}
4939 	vmx_set_segment(vcpu, save, seg);
4940 }
4941 
enter_pmode(struct kvm_vcpu * vcpu)4942 static void enter_pmode(struct kvm_vcpu *vcpu)
4943 {
4944 	unsigned long flags;
4945 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4946 
4947 	/*
4948 	 * Update real mode segment cache. It may be not up-to-date if sement
4949 	 * register was written while vcpu was in a guest mode.
4950 	 */
4951 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4952 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4953 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4954 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4955 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4956 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4957 
4958 	vmx->rmode.vm86_active = 0;
4959 
4960 	vmx_segment_cache_clear(vmx);
4961 
4962 	vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4963 
4964 	flags = vmcs_readl(GUEST_RFLAGS);
4965 	flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4966 	flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4967 	vmcs_writel(GUEST_RFLAGS, flags);
4968 
4969 	vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4970 			(vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4971 
4972 	update_exception_bitmap(vcpu);
4973 
4974 	fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4975 	fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4976 	fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4977 	fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4978 	fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4979 	fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4980 }
4981 
fix_rmode_seg(int seg,struct kvm_segment * save)4982 static void fix_rmode_seg(int seg, struct kvm_segment *save)
4983 {
4984 	const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4985 	struct kvm_segment var = *save;
4986 
4987 	var.dpl = 0x3;
4988 	if (seg == VCPU_SREG_CS)
4989 		var.type = 0x3;
4990 
4991 	if (!emulate_invalid_guest_state) {
4992 		var.selector = var.base >> 4;
4993 		var.base = var.base & 0xffff0;
4994 		var.limit = 0xffff;
4995 		var.g = 0;
4996 		var.db = 0;
4997 		var.present = 1;
4998 		var.s = 1;
4999 		var.l = 0;
5000 		var.unusable = 0;
5001 		var.type = 0x3;
5002 		var.avl = 0;
5003 		if (save->base & 0xf)
5004 			printk_once(KERN_WARNING "kvm: segment base is not "
5005 					"paragraph aligned when entering "
5006 					"protected mode (seg=%d)", seg);
5007 	}
5008 
5009 	vmcs_write16(sf->selector, var.selector);
5010 	vmcs_writel(sf->base, var.base);
5011 	vmcs_write32(sf->limit, var.limit);
5012 	vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
5013 }
5014 
enter_rmode(struct kvm_vcpu * vcpu)5015 static void enter_rmode(struct kvm_vcpu *vcpu)
5016 {
5017 	unsigned long flags;
5018 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5019 	struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
5020 
5021 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
5022 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
5023 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
5024 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
5025 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
5026 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
5027 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
5028 
5029 	vmx->rmode.vm86_active = 1;
5030 
5031 	/*
5032 	 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
5033 	 * vcpu. Warn the user that an update is overdue.
5034 	 */
5035 	if (!kvm_vmx->tss_addr)
5036 		printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
5037 			     "called before entering vcpu\n");
5038 
5039 	vmx_segment_cache_clear(vmx);
5040 
5041 	vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
5042 	vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
5043 	vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5044 
5045 	flags = vmcs_readl(GUEST_RFLAGS);
5046 	vmx->rmode.save_rflags = flags;
5047 
5048 	flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
5049 
5050 	vmcs_writel(GUEST_RFLAGS, flags);
5051 	vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
5052 	update_exception_bitmap(vcpu);
5053 
5054 	fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
5055 	fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
5056 	fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
5057 	fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
5058 	fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
5059 	fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
5060 
5061 	kvm_mmu_reset_context(vcpu);
5062 }
5063 
vmx_set_efer(struct kvm_vcpu * vcpu,u64 efer)5064 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
5065 {
5066 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5067 	struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
5068 
5069 	if (!msr)
5070 		return;
5071 
5072 	vcpu->arch.efer = efer;
5073 	if (efer & EFER_LMA) {
5074 		vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5075 		msr->data = efer;
5076 	} else {
5077 		vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5078 
5079 		msr->data = efer & ~EFER_LME;
5080 	}
5081 	setup_msrs(vmx);
5082 }
5083 
5084 #ifdef CONFIG_X86_64
5085 
enter_lmode(struct kvm_vcpu * vcpu)5086 static void enter_lmode(struct kvm_vcpu *vcpu)
5087 {
5088 	u32 guest_tr_ar;
5089 
5090 	vmx_segment_cache_clear(to_vmx(vcpu));
5091 
5092 	guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
5093 	if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
5094 		pr_debug_ratelimited("%s: tss fixup for long mode. \n",
5095 				     __func__);
5096 		vmcs_write32(GUEST_TR_AR_BYTES,
5097 			     (guest_tr_ar & ~VMX_AR_TYPE_MASK)
5098 			     | VMX_AR_TYPE_BUSY_64_TSS);
5099 	}
5100 	vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
5101 }
5102 
exit_lmode(struct kvm_vcpu * vcpu)5103 static void exit_lmode(struct kvm_vcpu *vcpu)
5104 {
5105 	vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5106 	vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
5107 }
5108 
5109 #endif
5110 
__vmx_flush_tlb(struct kvm_vcpu * vcpu,int vpid,bool invalidate_gpa)5111 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
5112 				bool invalidate_gpa)
5113 {
5114 	if (enable_ept && (invalidate_gpa || !enable_vpid)) {
5115 		if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
5116 			return;
5117 		ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa));
5118 	} else {
5119 		vpid_sync_context(vpid);
5120 	}
5121 }
5122 
vmx_flush_tlb(struct kvm_vcpu * vcpu,bool invalidate_gpa)5123 static void vmx_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5124 {
5125 	__vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid, invalidate_gpa);
5126 }
5127 
vmx_flush_tlb_gva(struct kvm_vcpu * vcpu,gva_t addr)5128 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
5129 {
5130 	int vpid = to_vmx(vcpu)->vpid;
5131 
5132 	if (!vpid_sync_vcpu_addr(vpid, addr))
5133 		vpid_sync_context(vpid);
5134 
5135 	/*
5136 	 * If VPIDs are not supported or enabled, then the above is a no-op.
5137 	 * But we don't really need a TLB flush in that case anyway, because
5138 	 * each VM entry/exit includes an implicit flush when VPID is 0.
5139 	 */
5140 }
5141 
vmx_decache_cr0_guest_bits(struct kvm_vcpu * vcpu)5142 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
5143 {
5144 	ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
5145 
5146 	vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
5147 	vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
5148 }
5149 
vmx_decache_cr3(struct kvm_vcpu * vcpu)5150 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
5151 {
5152 	if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
5153 		vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
5154 	__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
5155 }
5156 
vmx_decache_cr4_guest_bits(struct kvm_vcpu * vcpu)5157 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
5158 {
5159 	ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
5160 
5161 	vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
5162 	vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
5163 }
5164 
ept_load_pdptrs(struct kvm_vcpu * vcpu)5165 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
5166 {
5167 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5168 
5169 	if (!test_bit(VCPU_EXREG_PDPTR,
5170 		      (unsigned long *)&vcpu->arch.regs_dirty))
5171 		return;
5172 
5173 	if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
5174 		vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
5175 		vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
5176 		vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
5177 		vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
5178 	}
5179 }
5180 
ept_save_pdptrs(struct kvm_vcpu * vcpu)5181 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
5182 {
5183 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5184 
5185 	if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
5186 		mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
5187 		mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
5188 		mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
5189 		mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
5190 	}
5191 
5192 	__set_bit(VCPU_EXREG_PDPTR,
5193 		  (unsigned long *)&vcpu->arch.regs_avail);
5194 	__set_bit(VCPU_EXREG_PDPTR,
5195 		  (unsigned long *)&vcpu->arch.regs_dirty);
5196 }
5197 
nested_guest_cr0_valid(struct kvm_vcpu * vcpu,unsigned long val)5198 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5199 {
5200 	u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
5201 	u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
5202 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5203 
5204 	if (to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
5205 		SECONDARY_EXEC_UNRESTRICTED_GUEST &&
5206 	    nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
5207 		fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
5208 
5209 	return fixed_bits_valid(val, fixed0, fixed1);
5210 }
5211 
nested_host_cr0_valid(struct kvm_vcpu * vcpu,unsigned long val)5212 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5213 {
5214 	u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
5215 	u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
5216 
5217 	return fixed_bits_valid(val, fixed0, fixed1);
5218 }
5219 
nested_cr4_valid(struct kvm_vcpu * vcpu,unsigned long val)5220 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
5221 {
5222 	u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr4_fixed0;
5223 	u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr4_fixed1;
5224 
5225 	return fixed_bits_valid(val, fixed0, fixed1);
5226 }
5227 
5228 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
5229 #define nested_guest_cr4_valid	nested_cr4_valid
5230 #define nested_host_cr4_valid	nested_cr4_valid
5231 
5232 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
5233 
ept_update_paging_mode_cr0(unsigned long * hw_cr0,unsigned long cr0,struct kvm_vcpu * vcpu)5234 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
5235 					unsigned long cr0,
5236 					struct kvm_vcpu *vcpu)
5237 {
5238 	if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
5239 		vmx_decache_cr3(vcpu);
5240 	if (!(cr0 & X86_CR0_PG)) {
5241 		/* From paging/starting to nonpaging */
5242 		vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5243 			     vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
5244 			     (CPU_BASED_CR3_LOAD_EXITING |
5245 			      CPU_BASED_CR3_STORE_EXITING));
5246 		vcpu->arch.cr0 = cr0;
5247 		vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5248 	} else if (!is_paging(vcpu)) {
5249 		/* From nonpaging to paging */
5250 		vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5251 			     vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
5252 			     ~(CPU_BASED_CR3_LOAD_EXITING |
5253 			       CPU_BASED_CR3_STORE_EXITING));
5254 		vcpu->arch.cr0 = cr0;
5255 		vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5256 	}
5257 
5258 	if (!(cr0 & X86_CR0_WP))
5259 		*hw_cr0 &= ~X86_CR0_WP;
5260 }
5261 
vmx_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)5262 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
5263 {
5264 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5265 	unsigned long hw_cr0;
5266 
5267 	hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
5268 	if (enable_unrestricted_guest)
5269 		hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
5270 	else {
5271 		hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
5272 
5273 		if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
5274 			enter_pmode(vcpu);
5275 
5276 		if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
5277 			enter_rmode(vcpu);
5278 	}
5279 
5280 #ifdef CONFIG_X86_64
5281 	if (vcpu->arch.efer & EFER_LME) {
5282 		if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
5283 			enter_lmode(vcpu);
5284 		if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
5285 			exit_lmode(vcpu);
5286 	}
5287 #endif
5288 
5289 	if (enable_ept && !enable_unrestricted_guest)
5290 		ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
5291 
5292 	vmcs_writel(CR0_READ_SHADOW, cr0);
5293 	vmcs_writel(GUEST_CR0, hw_cr0);
5294 	vcpu->arch.cr0 = cr0;
5295 
5296 	/* depends on vcpu->arch.cr0 to be set to a new value */
5297 	vmx->emulation_required = emulation_required(vcpu);
5298 }
5299 
get_ept_level(struct kvm_vcpu * vcpu)5300 static int get_ept_level(struct kvm_vcpu *vcpu)
5301 {
5302 	if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
5303 		return 5;
5304 	return 4;
5305 }
5306 
construct_eptp(struct kvm_vcpu * vcpu,unsigned long root_hpa)5307 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
5308 {
5309 	u64 eptp = VMX_EPTP_MT_WB;
5310 
5311 	eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
5312 
5313 	if (enable_ept_ad_bits &&
5314 	    (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
5315 		eptp |= VMX_EPTP_AD_ENABLE_BIT;
5316 	eptp |= (root_hpa & PAGE_MASK);
5317 
5318 	return eptp;
5319 }
5320 
vmx_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)5321 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
5322 {
5323 	struct kvm *kvm = vcpu->kvm;
5324 	unsigned long guest_cr3;
5325 	u64 eptp;
5326 
5327 	guest_cr3 = cr3;
5328 	if (enable_ept) {
5329 		eptp = construct_eptp(vcpu, cr3);
5330 		vmcs_write64(EPT_POINTER, eptp);
5331 
5332 		if (kvm_x86_ops->tlb_remote_flush) {
5333 			spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5334 			to_vmx(vcpu)->ept_pointer = eptp;
5335 			to_kvm_vmx(kvm)->ept_pointers_match
5336 				= EPT_POINTERS_CHECK;
5337 			spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5338 		}
5339 
5340 		if (enable_unrestricted_guest || is_paging(vcpu) ||
5341 		    is_guest_mode(vcpu))
5342 			guest_cr3 = kvm_read_cr3(vcpu);
5343 		else
5344 			guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
5345 		ept_load_pdptrs(vcpu);
5346 	}
5347 
5348 	vmcs_writel(GUEST_CR3, guest_cr3);
5349 }
5350 
vmx_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)5351 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
5352 {
5353 	/*
5354 	 * Pass through host's Machine Check Enable value to hw_cr4, which
5355 	 * is in force while we are in guest mode.  Do not let guests control
5356 	 * this bit, even if host CR4.MCE == 0.
5357 	 */
5358 	unsigned long hw_cr4;
5359 
5360 	hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
5361 	if (enable_unrestricted_guest)
5362 		hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
5363 	else if (to_vmx(vcpu)->rmode.vm86_active)
5364 		hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
5365 	else
5366 		hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
5367 
5368 	if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
5369 		if (cr4 & X86_CR4_UMIP) {
5370 			vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5371 				SECONDARY_EXEC_DESC);
5372 			hw_cr4 &= ~X86_CR4_UMIP;
5373 		} else if (!is_guest_mode(vcpu) ||
5374 			!nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
5375 			vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5376 					SECONDARY_EXEC_DESC);
5377 	}
5378 
5379 	if (cr4 & X86_CR4_VMXE) {
5380 		/*
5381 		 * To use VMXON (and later other VMX instructions), a guest
5382 		 * must first be able to turn on cr4.VMXE (see handle_vmon()).
5383 		 * So basically the check on whether to allow nested VMX
5384 		 * is here.  We operate under the default treatment of SMM,
5385 		 * so VMX cannot be enabled under SMM.
5386 		 */
5387 		if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
5388 			return 1;
5389 	}
5390 
5391 	if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
5392 		return 1;
5393 
5394 	vcpu->arch.cr4 = cr4;
5395 
5396 	if (!enable_unrestricted_guest) {
5397 		if (enable_ept) {
5398 			if (!is_paging(vcpu)) {
5399 				hw_cr4 &= ~X86_CR4_PAE;
5400 				hw_cr4 |= X86_CR4_PSE;
5401 			} else if (!(cr4 & X86_CR4_PAE)) {
5402 				hw_cr4 &= ~X86_CR4_PAE;
5403 			}
5404 		}
5405 
5406 		/*
5407 		 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
5408 		 * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
5409 		 * to be manually disabled when guest switches to non-paging
5410 		 * mode.
5411 		 *
5412 		 * If !enable_unrestricted_guest, the CPU is always running
5413 		 * with CR0.PG=1 and CR4 needs to be modified.
5414 		 * If enable_unrestricted_guest, the CPU automatically
5415 		 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
5416 		 */
5417 		if (!is_paging(vcpu))
5418 			hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
5419 	}
5420 
5421 	vmcs_writel(CR4_READ_SHADOW, cr4);
5422 	vmcs_writel(GUEST_CR4, hw_cr4);
5423 	return 0;
5424 }
5425 
vmx_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)5426 static void vmx_get_segment(struct kvm_vcpu *vcpu,
5427 			    struct kvm_segment *var, int seg)
5428 {
5429 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5430 	u32 ar;
5431 
5432 	if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5433 		*var = vmx->rmode.segs[seg];
5434 		if (seg == VCPU_SREG_TR
5435 		    || var->selector == vmx_read_guest_seg_selector(vmx, seg))
5436 			return;
5437 		var->base = vmx_read_guest_seg_base(vmx, seg);
5438 		var->selector = vmx_read_guest_seg_selector(vmx, seg);
5439 		return;
5440 	}
5441 	var->base = vmx_read_guest_seg_base(vmx, seg);
5442 	var->limit = vmx_read_guest_seg_limit(vmx, seg);
5443 	var->selector = vmx_read_guest_seg_selector(vmx, seg);
5444 	ar = vmx_read_guest_seg_ar(vmx, seg);
5445 	var->unusable = (ar >> 16) & 1;
5446 	var->type = ar & 15;
5447 	var->s = (ar >> 4) & 1;
5448 	var->dpl = (ar >> 5) & 3;
5449 	/*
5450 	 * Some userspaces do not preserve unusable property. Since usable
5451 	 * segment has to be present according to VMX spec we can use present
5452 	 * property to amend userspace bug by making unusable segment always
5453 	 * nonpresent. vmx_segment_access_rights() already marks nonpresent
5454 	 * segment as unusable.
5455 	 */
5456 	var->present = !var->unusable;
5457 	var->avl = (ar >> 12) & 1;
5458 	var->l = (ar >> 13) & 1;
5459 	var->db = (ar >> 14) & 1;
5460 	var->g = (ar >> 15) & 1;
5461 }
5462 
vmx_get_segment_base(struct kvm_vcpu * vcpu,int seg)5463 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
5464 {
5465 	struct kvm_segment s;
5466 
5467 	if (to_vmx(vcpu)->rmode.vm86_active) {
5468 		vmx_get_segment(vcpu, &s, seg);
5469 		return s.base;
5470 	}
5471 	return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
5472 }
5473 
vmx_get_cpl(struct kvm_vcpu * vcpu)5474 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
5475 {
5476 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5477 
5478 	if (unlikely(vmx->rmode.vm86_active))
5479 		return 0;
5480 	else {
5481 		int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
5482 		return VMX_AR_DPL(ar);
5483 	}
5484 }
5485 
vmx_segment_access_rights(struct kvm_segment * var)5486 static u32 vmx_segment_access_rights(struct kvm_segment *var)
5487 {
5488 	u32 ar;
5489 
5490 	if (var->unusable || !var->present)
5491 		ar = 1 << 16;
5492 	else {
5493 		ar = var->type & 15;
5494 		ar |= (var->s & 1) << 4;
5495 		ar |= (var->dpl & 3) << 5;
5496 		ar |= (var->present & 1) << 7;
5497 		ar |= (var->avl & 1) << 12;
5498 		ar |= (var->l & 1) << 13;
5499 		ar |= (var->db & 1) << 14;
5500 		ar |= (var->g & 1) << 15;
5501 	}
5502 
5503 	return ar;
5504 }
5505 
vmx_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)5506 static void vmx_set_segment(struct kvm_vcpu *vcpu,
5507 			    struct kvm_segment *var, int seg)
5508 {
5509 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5510 	const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5511 
5512 	vmx_segment_cache_clear(vmx);
5513 
5514 	if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5515 		vmx->rmode.segs[seg] = *var;
5516 		if (seg == VCPU_SREG_TR)
5517 			vmcs_write16(sf->selector, var->selector);
5518 		else if (var->s)
5519 			fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
5520 		goto out;
5521 	}
5522 
5523 	vmcs_writel(sf->base, var->base);
5524 	vmcs_write32(sf->limit, var->limit);
5525 	vmcs_write16(sf->selector, var->selector);
5526 
5527 	/*
5528 	 *   Fix the "Accessed" bit in AR field of segment registers for older
5529 	 * qemu binaries.
5530 	 *   IA32 arch specifies that at the time of processor reset the
5531 	 * "Accessed" bit in the AR field of segment registers is 1. And qemu
5532 	 * is setting it to 0 in the userland code. This causes invalid guest
5533 	 * state vmexit when "unrestricted guest" mode is turned on.
5534 	 *    Fix for this setup issue in cpu_reset is being pushed in the qemu
5535 	 * tree. Newer qemu binaries with that qemu fix would not need this
5536 	 * kvm hack.
5537 	 */
5538 	if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
5539 		var->type |= 0x1; /* Accessed */
5540 
5541 	vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
5542 
5543 out:
5544 	vmx->emulation_required = emulation_required(vcpu);
5545 }
5546 
vmx_get_cs_db_l_bits(struct kvm_vcpu * vcpu,int * db,int * l)5547 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5548 {
5549 	u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
5550 
5551 	*db = (ar >> 14) & 1;
5552 	*l = (ar >> 13) & 1;
5553 }
5554 
vmx_get_idt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)5555 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5556 {
5557 	dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
5558 	dt->address = vmcs_readl(GUEST_IDTR_BASE);
5559 }
5560 
vmx_set_idt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)5561 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5562 {
5563 	vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
5564 	vmcs_writel(GUEST_IDTR_BASE, dt->address);
5565 }
5566 
vmx_get_gdt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)5567 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5568 {
5569 	dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
5570 	dt->address = vmcs_readl(GUEST_GDTR_BASE);
5571 }
5572 
vmx_set_gdt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)5573 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5574 {
5575 	vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
5576 	vmcs_writel(GUEST_GDTR_BASE, dt->address);
5577 }
5578 
rmode_segment_valid(struct kvm_vcpu * vcpu,int seg)5579 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
5580 {
5581 	struct kvm_segment var;
5582 	u32 ar;
5583 
5584 	vmx_get_segment(vcpu, &var, seg);
5585 	var.dpl = 0x3;
5586 	if (seg == VCPU_SREG_CS)
5587 		var.type = 0x3;
5588 	ar = vmx_segment_access_rights(&var);
5589 
5590 	if (var.base != (var.selector << 4))
5591 		return false;
5592 	if (var.limit != 0xffff)
5593 		return false;
5594 	if (ar != 0xf3)
5595 		return false;
5596 
5597 	return true;
5598 }
5599 
code_segment_valid(struct kvm_vcpu * vcpu)5600 static bool code_segment_valid(struct kvm_vcpu *vcpu)
5601 {
5602 	struct kvm_segment cs;
5603 	unsigned int cs_rpl;
5604 
5605 	vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5606 	cs_rpl = cs.selector & SEGMENT_RPL_MASK;
5607 
5608 	if (cs.unusable)
5609 		return false;
5610 	if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
5611 		return false;
5612 	if (!cs.s)
5613 		return false;
5614 	if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
5615 		if (cs.dpl > cs_rpl)
5616 			return false;
5617 	} else {
5618 		if (cs.dpl != cs_rpl)
5619 			return false;
5620 	}
5621 	if (!cs.present)
5622 		return false;
5623 
5624 	/* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
5625 	return true;
5626 }
5627 
stack_segment_valid(struct kvm_vcpu * vcpu)5628 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
5629 {
5630 	struct kvm_segment ss;
5631 	unsigned int ss_rpl;
5632 
5633 	vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5634 	ss_rpl = ss.selector & SEGMENT_RPL_MASK;
5635 
5636 	if (ss.unusable)
5637 		return true;
5638 	if (ss.type != 3 && ss.type != 7)
5639 		return false;
5640 	if (!ss.s)
5641 		return false;
5642 	if (ss.dpl != ss_rpl) /* DPL != RPL */
5643 		return false;
5644 	if (!ss.present)
5645 		return false;
5646 
5647 	return true;
5648 }
5649 
data_segment_valid(struct kvm_vcpu * vcpu,int seg)5650 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
5651 {
5652 	struct kvm_segment var;
5653 	unsigned int rpl;
5654 
5655 	vmx_get_segment(vcpu, &var, seg);
5656 	rpl = var.selector & SEGMENT_RPL_MASK;
5657 
5658 	if (var.unusable)
5659 		return true;
5660 	if (!var.s)
5661 		return false;
5662 	if (!var.present)
5663 		return false;
5664 	if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
5665 		if (var.dpl < rpl) /* DPL < RPL */
5666 			return false;
5667 	}
5668 
5669 	/* TODO: Add other members to kvm_segment_field to allow checking for other access
5670 	 * rights flags
5671 	 */
5672 	return true;
5673 }
5674 
tr_valid(struct kvm_vcpu * vcpu)5675 static bool tr_valid(struct kvm_vcpu *vcpu)
5676 {
5677 	struct kvm_segment tr;
5678 
5679 	vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
5680 
5681 	if (tr.unusable)
5682 		return false;
5683 	if (tr.selector & SEGMENT_TI_MASK)	/* TI = 1 */
5684 		return false;
5685 	if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
5686 		return false;
5687 	if (!tr.present)
5688 		return false;
5689 
5690 	return true;
5691 }
5692 
ldtr_valid(struct kvm_vcpu * vcpu)5693 static bool ldtr_valid(struct kvm_vcpu *vcpu)
5694 {
5695 	struct kvm_segment ldtr;
5696 
5697 	vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
5698 
5699 	if (ldtr.unusable)
5700 		return true;
5701 	if (ldtr.selector & SEGMENT_TI_MASK)	/* TI = 1 */
5702 		return false;
5703 	if (ldtr.type != 2)
5704 		return false;
5705 	if (!ldtr.present)
5706 		return false;
5707 
5708 	return true;
5709 }
5710 
cs_ss_rpl_check(struct kvm_vcpu * vcpu)5711 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
5712 {
5713 	struct kvm_segment cs, ss;
5714 
5715 	vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5716 	vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5717 
5718 	return ((cs.selector & SEGMENT_RPL_MASK) ==
5719 		 (ss.selector & SEGMENT_RPL_MASK));
5720 }
5721 
5722 /*
5723  * Check if guest state is valid. Returns true if valid, false if
5724  * not.
5725  * We assume that registers are always usable
5726  */
guest_state_valid(struct kvm_vcpu * vcpu)5727 static bool guest_state_valid(struct kvm_vcpu *vcpu)
5728 {
5729 	if (enable_unrestricted_guest)
5730 		return true;
5731 
5732 	/* real mode guest state checks */
5733 	if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5734 		if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
5735 			return false;
5736 		if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
5737 			return false;
5738 		if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
5739 			return false;
5740 		if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
5741 			return false;
5742 		if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
5743 			return false;
5744 		if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
5745 			return false;
5746 	} else {
5747 	/* protected mode guest state checks */
5748 		if (!cs_ss_rpl_check(vcpu))
5749 			return false;
5750 		if (!code_segment_valid(vcpu))
5751 			return false;
5752 		if (!stack_segment_valid(vcpu))
5753 			return false;
5754 		if (!data_segment_valid(vcpu, VCPU_SREG_DS))
5755 			return false;
5756 		if (!data_segment_valid(vcpu, VCPU_SREG_ES))
5757 			return false;
5758 		if (!data_segment_valid(vcpu, VCPU_SREG_FS))
5759 			return false;
5760 		if (!data_segment_valid(vcpu, VCPU_SREG_GS))
5761 			return false;
5762 		if (!tr_valid(vcpu))
5763 			return false;
5764 		if (!ldtr_valid(vcpu))
5765 			return false;
5766 	}
5767 	/* TODO:
5768 	 * - Add checks on RIP
5769 	 * - Add checks on RFLAGS
5770 	 */
5771 
5772 	return true;
5773 }
5774 
page_address_valid(struct kvm_vcpu * vcpu,gpa_t gpa)5775 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
5776 {
5777 	return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
5778 }
5779 
init_rmode_tss(struct kvm * kvm)5780 static int init_rmode_tss(struct kvm *kvm)
5781 {
5782 	gfn_t fn;
5783 	u16 data = 0;
5784 	int idx, r;
5785 
5786 	idx = srcu_read_lock(&kvm->srcu);
5787 	fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
5788 	r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5789 	if (r < 0)
5790 		goto out;
5791 	data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
5792 	r = kvm_write_guest_page(kvm, fn++, &data,
5793 			TSS_IOPB_BASE_OFFSET, sizeof(u16));
5794 	if (r < 0)
5795 		goto out;
5796 	r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
5797 	if (r < 0)
5798 		goto out;
5799 	r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5800 	if (r < 0)
5801 		goto out;
5802 	data = ~0;
5803 	r = kvm_write_guest_page(kvm, fn, &data,
5804 				 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
5805 				 sizeof(u8));
5806 out:
5807 	srcu_read_unlock(&kvm->srcu, idx);
5808 	return r;
5809 }
5810 
init_rmode_identity_map(struct kvm * kvm)5811 static int init_rmode_identity_map(struct kvm *kvm)
5812 {
5813 	struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
5814 	int i, idx, r = 0;
5815 	kvm_pfn_t identity_map_pfn;
5816 	u32 tmp;
5817 
5818 	/* Protect kvm_vmx->ept_identity_pagetable_done. */
5819 	mutex_lock(&kvm->slots_lock);
5820 
5821 	if (likely(kvm_vmx->ept_identity_pagetable_done))
5822 		goto out2;
5823 
5824 	if (!kvm_vmx->ept_identity_map_addr)
5825 		kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
5826 	identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
5827 
5828 	r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
5829 				    kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
5830 	if (r < 0)
5831 		goto out2;
5832 
5833 	idx = srcu_read_lock(&kvm->srcu);
5834 	r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
5835 	if (r < 0)
5836 		goto out;
5837 	/* Set up identity-mapping pagetable for EPT in real mode */
5838 	for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
5839 		tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
5840 			_PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
5841 		r = kvm_write_guest_page(kvm, identity_map_pfn,
5842 				&tmp, i * sizeof(tmp), sizeof(tmp));
5843 		if (r < 0)
5844 			goto out;
5845 	}
5846 	kvm_vmx->ept_identity_pagetable_done = true;
5847 
5848 out:
5849 	srcu_read_unlock(&kvm->srcu, idx);
5850 
5851 out2:
5852 	mutex_unlock(&kvm->slots_lock);
5853 	return r;
5854 }
5855 
seg_setup(int seg)5856 static void seg_setup(int seg)
5857 {
5858 	const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5859 	unsigned int ar;
5860 
5861 	vmcs_write16(sf->selector, 0);
5862 	vmcs_writel(sf->base, 0);
5863 	vmcs_write32(sf->limit, 0xffff);
5864 	ar = 0x93;
5865 	if (seg == VCPU_SREG_CS)
5866 		ar |= 0x08; /* code segment */
5867 
5868 	vmcs_write32(sf->ar_bytes, ar);
5869 }
5870 
alloc_apic_access_page(struct kvm * kvm)5871 static int alloc_apic_access_page(struct kvm *kvm)
5872 {
5873 	struct page *page;
5874 	int r = 0;
5875 
5876 	mutex_lock(&kvm->slots_lock);
5877 	if (kvm->arch.apic_access_page_done)
5878 		goto out;
5879 	r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
5880 				    APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
5881 	if (r)
5882 		goto out;
5883 
5884 	page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
5885 	if (is_error_page(page)) {
5886 		r = -EFAULT;
5887 		goto out;
5888 	}
5889 
5890 	/*
5891 	 * Do not pin the page in memory, so that memory hot-unplug
5892 	 * is able to migrate it.
5893 	 */
5894 	put_page(page);
5895 	kvm->arch.apic_access_page_done = true;
5896 out:
5897 	mutex_unlock(&kvm->slots_lock);
5898 	return r;
5899 }
5900 
allocate_vpid(void)5901 static int allocate_vpid(void)
5902 {
5903 	int vpid;
5904 
5905 	if (!enable_vpid)
5906 		return 0;
5907 	spin_lock(&vmx_vpid_lock);
5908 	vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5909 	if (vpid < VMX_NR_VPIDS)
5910 		__set_bit(vpid, vmx_vpid_bitmap);
5911 	else
5912 		vpid = 0;
5913 	spin_unlock(&vmx_vpid_lock);
5914 	return vpid;
5915 }
5916 
free_vpid(int vpid)5917 static void free_vpid(int vpid)
5918 {
5919 	if (!enable_vpid || vpid == 0)
5920 		return;
5921 	spin_lock(&vmx_vpid_lock);
5922 	__clear_bit(vpid, vmx_vpid_bitmap);
5923 	spin_unlock(&vmx_vpid_lock);
5924 }
5925 
vmx_disable_intercept_for_msr(unsigned long * msr_bitmap,u32 msr,int type)5926 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5927 							  u32 msr, int type)
5928 {
5929 	int f = sizeof(unsigned long);
5930 
5931 	if (!cpu_has_vmx_msr_bitmap())
5932 		return;
5933 
5934 	if (static_branch_unlikely(&enable_evmcs))
5935 		evmcs_touch_msr_bitmap();
5936 
5937 	/*
5938 	 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5939 	 * have the write-low and read-high bitmap offsets the wrong way round.
5940 	 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5941 	 */
5942 	if (msr <= 0x1fff) {
5943 		if (type & MSR_TYPE_R)
5944 			/* read-low */
5945 			__clear_bit(msr, msr_bitmap + 0x000 / f);
5946 
5947 		if (type & MSR_TYPE_W)
5948 			/* write-low */
5949 			__clear_bit(msr, msr_bitmap + 0x800 / f);
5950 
5951 	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5952 		msr &= 0x1fff;
5953 		if (type & MSR_TYPE_R)
5954 			/* read-high */
5955 			__clear_bit(msr, msr_bitmap + 0x400 / f);
5956 
5957 		if (type & MSR_TYPE_W)
5958 			/* write-high */
5959 			__clear_bit(msr, msr_bitmap + 0xc00 / f);
5960 
5961 	}
5962 }
5963 
vmx_enable_intercept_for_msr(unsigned long * msr_bitmap,u32 msr,int type)5964 static void __always_inline vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5965 							 u32 msr, int type)
5966 {
5967 	int f = sizeof(unsigned long);
5968 
5969 	if (!cpu_has_vmx_msr_bitmap())
5970 		return;
5971 
5972 	if (static_branch_unlikely(&enable_evmcs))
5973 		evmcs_touch_msr_bitmap();
5974 
5975 	/*
5976 	 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5977 	 * have the write-low and read-high bitmap offsets the wrong way round.
5978 	 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5979 	 */
5980 	if (msr <= 0x1fff) {
5981 		if (type & MSR_TYPE_R)
5982 			/* read-low */
5983 			__set_bit(msr, msr_bitmap + 0x000 / f);
5984 
5985 		if (type & MSR_TYPE_W)
5986 			/* write-low */
5987 			__set_bit(msr, msr_bitmap + 0x800 / f);
5988 
5989 	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5990 		msr &= 0x1fff;
5991 		if (type & MSR_TYPE_R)
5992 			/* read-high */
5993 			__set_bit(msr, msr_bitmap + 0x400 / f);
5994 
5995 		if (type & MSR_TYPE_W)
5996 			/* write-high */
5997 			__set_bit(msr, msr_bitmap + 0xc00 / f);
5998 
5999 	}
6000 }
6001 
vmx_set_intercept_for_msr(unsigned long * msr_bitmap,u32 msr,int type,bool value)6002 static void __always_inline vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
6003 			     			      u32 msr, int type, bool value)
6004 {
6005 	if (value)
6006 		vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
6007 	else
6008 		vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
6009 }
6010 
6011 /*
6012  * If a msr is allowed by L0, we should check whether it is allowed by L1.
6013  * The corresponding bit will be cleared unless both of L0 and L1 allow it.
6014  */
nested_vmx_disable_intercept_for_msr(unsigned long * msr_bitmap_l1,unsigned long * msr_bitmap_nested,u32 msr,int type)6015 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
6016 					       unsigned long *msr_bitmap_nested,
6017 					       u32 msr, int type)
6018 {
6019 	int f = sizeof(unsigned long);
6020 
6021 	/*
6022 	 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
6023 	 * have the write-low and read-high bitmap offsets the wrong way round.
6024 	 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
6025 	 */
6026 	if (msr <= 0x1fff) {
6027 		if (type & MSR_TYPE_R &&
6028 		   !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
6029 			/* read-low */
6030 			__clear_bit(msr, msr_bitmap_nested + 0x000 / f);
6031 
6032 		if (type & MSR_TYPE_W &&
6033 		   !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
6034 			/* write-low */
6035 			__clear_bit(msr, msr_bitmap_nested + 0x800 / f);
6036 
6037 	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
6038 		msr &= 0x1fff;
6039 		if (type & MSR_TYPE_R &&
6040 		   !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
6041 			/* read-high */
6042 			__clear_bit(msr, msr_bitmap_nested + 0x400 / f);
6043 
6044 		if (type & MSR_TYPE_W &&
6045 		   !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
6046 			/* write-high */
6047 			__clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
6048 
6049 	}
6050 }
6051 
vmx_msr_bitmap_mode(struct kvm_vcpu * vcpu)6052 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
6053 {
6054 	u8 mode = 0;
6055 
6056 	if (cpu_has_secondary_exec_ctrls() &&
6057 	    (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
6058 	     SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
6059 		mode |= MSR_BITMAP_MODE_X2APIC;
6060 		if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
6061 			mode |= MSR_BITMAP_MODE_X2APIC_APICV;
6062 	}
6063 
6064 	return mode;
6065 }
6066 
6067 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
6068 
vmx_update_msr_bitmap_x2apic(unsigned long * msr_bitmap,u8 mode)6069 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
6070 					 u8 mode)
6071 {
6072 	int msr;
6073 
6074 	for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
6075 		unsigned word = msr / BITS_PER_LONG;
6076 		msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
6077 		msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
6078 	}
6079 
6080 	if (mode & MSR_BITMAP_MODE_X2APIC) {
6081 		/*
6082 		 * TPR reads and writes can be virtualized even if virtual interrupt
6083 		 * delivery is not in use.
6084 		 */
6085 		vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
6086 		if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
6087 			vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
6088 			vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
6089 			vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
6090 		}
6091 	}
6092 }
6093 
vmx_update_msr_bitmap(struct kvm_vcpu * vcpu)6094 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
6095 {
6096 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6097 	unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
6098 	u8 mode = vmx_msr_bitmap_mode(vcpu);
6099 	u8 changed = mode ^ vmx->msr_bitmap_mode;
6100 
6101 	if (!changed)
6102 		return;
6103 
6104 	if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
6105 		vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
6106 
6107 	vmx->msr_bitmap_mode = mode;
6108 }
6109 
vmx_get_enable_apicv(struct kvm_vcpu * vcpu)6110 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
6111 {
6112 	return enable_apicv;
6113 }
6114 
nested_mark_vmcs12_pages_dirty(struct kvm_vcpu * vcpu)6115 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
6116 {
6117 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6118 	gfn_t gfn;
6119 
6120 	/*
6121 	 * Don't need to mark the APIC access page dirty; it is never
6122 	 * written to by the CPU during APIC virtualization.
6123 	 */
6124 
6125 	if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
6126 		gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
6127 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
6128 	}
6129 
6130 	if (nested_cpu_has_posted_intr(vmcs12)) {
6131 		gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
6132 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
6133 	}
6134 }
6135 
6136 
vmx_complete_nested_posted_interrupt(struct kvm_vcpu * vcpu)6137 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
6138 {
6139 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6140 	int max_irr;
6141 	void *vapic_page;
6142 	u16 status;
6143 
6144 	if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
6145 		return;
6146 
6147 	vmx->nested.pi_pending = false;
6148 	if (!pi_test_and_clear_on(vmx->nested.pi_desc))
6149 		return;
6150 
6151 	max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
6152 	if (max_irr != 256) {
6153 		vapic_page = kmap(vmx->nested.virtual_apic_page);
6154 		__kvm_apic_update_irr(vmx->nested.pi_desc->pir,
6155 			vapic_page, &max_irr);
6156 		kunmap(vmx->nested.virtual_apic_page);
6157 
6158 		status = vmcs_read16(GUEST_INTR_STATUS);
6159 		if ((u8)max_irr > ((u8)status & 0xff)) {
6160 			status &= ~0xff;
6161 			status |= (u8)max_irr;
6162 			vmcs_write16(GUEST_INTR_STATUS, status);
6163 		}
6164 	}
6165 
6166 	nested_mark_vmcs12_pages_dirty(vcpu);
6167 }
6168 
vmx_get_rvi(void)6169 static u8 vmx_get_rvi(void)
6170 {
6171 	return vmcs_read16(GUEST_INTR_STATUS) & 0xff;
6172 }
6173 
vmx_guest_apic_has_interrupt(struct kvm_vcpu * vcpu)6174 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
6175 {
6176 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6177 	void *vapic_page;
6178 	u32 vppr;
6179 	int rvi;
6180 
6181 	if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
6182 		!nested_cpu_has_vid(get_vmcs12(vcpu)) ||
6183 		WARN_ON_ONCE(!vmx->nested.virtual_apic_page))
6184 		return false;
6185 
6186 	rvi = vmx_get_rvi();
6187 
6188 	vapic_page = kmap(vmx->nested.virtual_apic_page);
6189 	vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
6190 	kunmap(vmx->nested.virtual_apic_page);
6191 
6192 	return ((rvi & 0xf0) > (vppr & 0xf0));
6193 }
6194 
kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu * vcpu,bool nested)6195 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
6196 						     bool nested)
6197 {
6198 #ifdef CONFIG_SMP
6199 	int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
6200 
6201 	if (vcpu->mode == IN_GUEST_MODE) {
6202 		/*
6203 		 * The vector of interrupt to be delivered to vcpu had
6204 		 * been set in PIR before this function.
6205 		 *
6206 		 * Following cases will be reached in this block, and
6207 		 * we always send a notification event in all cases as
6208 		 * explained below.
6209 		 *
6210 		 * Case 1: vcpu keeps in non-root mode. Sending a
6211 		 * notification event posts the interrupt to vcpu.
6212 		 *
6213 		 * Case 2: vcpu exits to root mode and is still
6214 		 * runnable. PIR will be synced to vIRR before the
6215 		 * next vcpu entry. Sending a notification event in
6216 		 * this case has no effect, as vcpu is not in root
6217 		 * mode.
6218 		 *
6219 		 * Case 3: vcpu exits to root mode and is blocked.
6220 		 * vcpu_block() has already synced PIR to vIRR and
6221 		 * never blocks vcpu if vIRR is not cleared. Therefore,
6222 		 * a blocked vcpu here does not wait for any requested
6223 		 * interrupts in PIR, and sending a notification event
6224 		 * which has no effect is safe here.
6225 		 */
6226 
6227 		apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
6228 		return true;
6229 	}
6230 #endif
6231 	return false;
6232 }
6233 
vmx_deliver_nested_posted_interrupt(struct kvm_vcpu * vcpu,int vector)6234 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
6235 						int vector)
6236 {
6237 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6238 
6239 	if (is_guest_mode(vcpu) &&
6240 	    vector == vmx->nested.posted_intr_nv) {
6241 		/*
6242 		 * If a posted intr is not recognized by hardware,
6243 		 * we will accomplish it in the next vmentry.
6244 		 */
6245 		vmx->nested.pi_pending = true;
6246 		kvm_make_request(KVM_REQ_EVENT, vcpu);
6247 		/* the PIR and ON have been set by L1. */
6248 		if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
6249 			kvm_vcpu_kick(vcpu);
6250 		return 0;
6251 	}
6252 	return -1;
6253 }
6254 /*
6255  * Send interrupt to vcpu via posted interrupt way.
6256  * 1. If target vcpu is running(non-root mode), send posted interrupt
6257  * notification to vcpu and hardware will sync PIR to vIRR atomically.
6258  * 2. If target vcpu isn't running(root mode), kick it to pick up the
6259  * interrupt from PIR in next vmentry.
6260  */
vmx_deliver_posted_interrupt(struct kvm_vcpu * vcpu,int vector)6261 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
6262 {
6263 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6264 	int r;
6265 
6266 	r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
6267 	if (!r)
6268 		return;
6269 
6270 	if (pi_test_and_set_pir(vector, &vmx->pi_desc))
6271 		return;
6272 
6273 	/* If a previous notification has sent the IPI, nothing to do.  */
6274 	if (pi_test_and_set_on(&vmx->pi_desc))
6275 		return;
6276 
6277 	if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
6278 		kvm_vcpu_kick(vcpu);
6279 }
6280 
6281 /*
6282  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
6283  * will not change in the lifetime of the guest.
6284  * Note that host-state that does change is set elsewhere. E.g., host-state
6285  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
6286  */
vmx_set_constant_host_state(struct vcpu_vmx * vmx)6287 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
6288 {
6289 	u32 low32, high32;
6290 	unsigned long tmpl;
6291 	struct desc_ptr dt;
6292 	unsigned long cr0, cr3, cr4;
6293 
6294 	cr0 = read_cr0();
6295 	WARN_ON(cr0 & X86_CR0_TS);
6296 	vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
6297 
6298 	/*
6299 	 * Save the most likely value for this task's CR3 in the VMCS.
6300 	 * We can't use __get_current_cr3_fast() because we're not atomic.
6301 	 */
6302 	cr3 = __read_cr3();
6303 	vmcs_writel(HOST_CR3, cr3);		/* 22.2.3  FIXME: shadow tables */
6304 	vmx->loaded_vmcs->host_state.cr3 = cr3;
6305 
6306 	/* Save the most likely value for this task's CR4 in the VMCS. */
6307 	cr4 = cr4_read_shadow();
6308 	vmcs_writel(HOST_CR4, cr4);			/* 22.2.3, 22.2.5 */
6309 	vmx->loaded_vmcs->host_state.cr4 = cr4;
6310 
6311 	vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
6312 #ifdef CONFIG_X86_64
6313 	/*
6314 	 * Load null selectors, so we can avoid reloading them in
6315 	 * vmx_prepare_switch_to_host(), in case userspace uses
6316 	 * the null selectors too (the expected case).
6317 	 */
6318 	vmcs_write16(HOST_DS_SELECTOR, 0);
6319 	vmcs_write16(HOST_ES_SELECTOR, 0);
6320 #else
6321 	vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6322 	vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6323 #endif
6324 	vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6325 	vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
6326 
6327 	store_idt(&dt);
6328 	vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
6329 	vmx->host_idt_base = dt.address;
6330 
6331 	vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
6332 
6333 	rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
6334 	vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
6335 	rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
6336 	vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
6337 
6338 	if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
6339 		rdmsr(MSR_IA32_CR_PAT, low32, high32);
6340 		vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
6341 	}
6342 }
6343 
set_cr4_guest_host_mask(struct vcpu_vmx * vmx)6344 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
6345 {
6346 	vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
6347 	if (enable_ept)
6348 		vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
6349 	if (is_guest_mode(&vmx->vcpu))
6350 		vmx->vcpu.arch.cr4_guest_owned_bits &=
6351 			~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
6352 	vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
6353 }
6354 
vmx_pin_based_exec_ctrl(struct vcpu_vmx * vmx)6355 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
6356 {
6357 	u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
6358 
6359 	if (!kvm_vcpu_apicv_active(&vmx->vcpu))
6360 		pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
6361 
6362 	if (!enable_vnmi)
6363 		pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
6364 
6365 	/* Enable the preemption timer dynamically */
6366 	pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
6367 	return pin_based_exec_ctrl;
6368 }
6369 
vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu * vcpu)6370 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
6371 {
6372 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6373 
6374 	vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6375 	if (cpu_has_secondary_exec_ctrls()) {
6376 		if (kvm_vcpu_apicv_active(vcpu))
6377 			vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
6378 				      SECONDARY_EXEC_APIC_REGISTER_VIRT |
6379 				      SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6380 		else
6381 			vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
6382 					SECONDARY_EXEC_APIC_REGISTER_VIRT |
6383 					SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6384 	}
6385 
6386 	if (cpu_has_vmx_msr_bitmap())
6387 		vmx_update_msr_bitmap(vcpu);
6388 }
6389 
vmx_exec_control(struct vcpu_vmx * vmx)6390 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
6391 {
6392 	u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
6393 
6394 	if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
6395 		exec_control &= ~CPU_BASED_MOV_DR_EXITING;
6396 
6397 	if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
6398 		exec_control &= ~CPU_BASED_TPR_SHADOW;
6399 #ifdef CONFIG_X86_64
6400 		exec_control |= CPU_BASED_CR8_STORE_EXITING |
6401 				CPU_BASED_CR8_LOAD_EXITING;
6402 #endif
6403 	}
6404 	if (!enable_ept)
6405 		exec_control |= CPU_BASED_CR3_STORE_EXITING |
6406 				CPU_BASED_CR3_LOAD_EXITING  |
6407 				CPU_BASED_INVLPG_EXITING;
6408 	if (kvm_mwait_in_guest(vmx->vcpu.kvm))
6409 		exec_control &= ~(CPU_BASED_MWAIT_EXITING |
6410 				CPU_BASED_MONITOR_EXITING);
6411 	if (kvm_hlt_in_guest(vmx->vcpu.kvm))
6412 		exec_control &= ~CPU_BASED_HLT_EXITING;
6413 	return exec_control;
6414 }
6415 
vmx_rdrand_supported(void)6416 static bool vmx_rdrand_supported(void)
6417 {
6418 	return vmcs_config.cpu_based_2nd_exec_ctrl &
6419 		SECONDARY_EXEC_RDRAND_EXITING;
6420 }
6421 
vmx_rdseed_supported(void)6422 static bool vmx_rdseed_supported(void)
6423 {
6424 	return vmcs_config.cpu_based_2nd_exec_ctrl &
6425 		SECONDARY_EXEC_RDSEED_EXITING;
6426 }
6427 
vmx_compute_secondary_exec_control(struct vcpu_vmx * vmx)6428 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
6429 {
6430 	struct kvm_vcpu *vcpu = &vmx->vcpu;
6431 
6432 	u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
6433 
6434 	if (!cpu_need_virtualize_apic_accesses(vcpu))
6435 		exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6436 	if (vmx->vpid == 0)
6437 		exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
6438 	if (!enable_ept) {
6439 		exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
6440 		enable_unrestricted_guest = 0;
6441 	}
6442 	if (!enable_unrestricted_guest)
6443 		exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
6444 	if (kvm_pause_in_guest(vmx->vcpu.kvm))
6445 		exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
6446 	if (!kvm_vcpu_apicv_active(vcpu))
6447 		exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
6448 				  SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6449 	exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6450 
6451 	/* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
6452 	 * in vmx_set_cr4.  */
6453 	exec_control &= ~SECONDARY_EXEC_DESC;
6454 
6455 	/* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
6456 	   (handle_vmptrld).
6457 	   We can NOT enable shadow_vmcs here because we don't have yet
6458 	   a current VMCS12
6459 	*/
6460 	exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
6461 
6462 	if (!enable_pml)
6463 		exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
6464 
6465 	if (vmx_xsaves_supported()) {
6466 		/* Exposing XSAVES only when XSAVE is exposed */
6467 		bool xsaves_enabled =
6468 			guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
6469 			guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
6470 
6471 		if (!xsaves_enabled)
6472 			exec_control &= ~SECONDARY_EXEC_XSAVES;
6473 
6474 		if (nested) {
6475 			if (xsaves_enabled)
6476 				vmx->nested.msrs.secondary_ctls_high |=
6477 					SECONDARY_EXEC_XSAVES;
6478 			else
6479 				vmx->nested.msrs.secondary_ctls_high &=
6480 					~SECONDARY_EXEC_XSAVES;
6481 		}
6482 	}
6483 
6484 	if (vmx_rdtscp_supported()) {
6485 		bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
6486 		if (!rdtscp_enabled)
6487 			exec_control &= ~SECONDARY_EXEC_RDTSCP;
6488 
6489 		if (nested) {
6490 			if (rdtscp_enabled)
6491 				vmx->nested.msrs.secondary_ctls_high |=
6492 					SECONDARY_EXEC_RDTSCP;
6493 			else
6494 				vmx->nested.msrs.secondary_ctls_high &=
6495 					~SECONDARY_EXEC_RDTSCP;
6496 		}
6497 	}
6498 
6499 	if (vmx_invpcid_supported()) {
6500 		/* Exposing INVPCID only when PCID is exposed */
6501 		bool invpcid_enabled =
6502 			guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
6503 			guest_cpuid_has(vcpu, X86_FEATURE_PCID);
6504 
6505 		if (!invpcid_enabled) {
6506 			exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
6507 			guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
6508 		}
6509 
6510 		if (nested) {
6511 			if (invpcid_enabled)
6512 				vmx->nested.msrs.secondary_ctls_high |=
6513 					SECONDARY_EXEC_ENABLE_INVPCID;
6514 			else
6515 				vmx->nested.msrs.secondary_ctls_high &=
6516 					~SECONDARY_EXEC_ENABLE_INVPCID;
6517 		}
6518 	}
6519 
6520 	if (vmx_rdrand_supported()) {
6521 		bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
6522 		if (rdrand_enabled)
6523 			exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
6524 
6525 		if (nested) {
6526 			if (rdrand_enabled)
6527 				vmx->nested.msrs.secondary_ctls_high |=
6528 					SECONDARY_EXEC_RDRAND_EXITING;
6529 			else
6530 				vmx->nested.msrs.secondary_ctls_high &=
6531 					~SECONDARY_EXEC_RDRAND_EXITING;
6532 		}
6533 	}
6534 
6535 	if (vmx_rdseed_supported()) {
6536 		bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
6537 		if (rdseed_enabled)
6538 			exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
6539 
6540 		if (nested) {
6541 			if (rdseed_enabled)
6542 				vmx->nested.msrs.secondary_ctls_high |=
6543 					SECONDARY_EXEC_RDSEED_EXITING;
6544 			else
6545 				vmx->nested.msrs.secondary_ctls_high &=
6546 					~SECONDARY_EXEC_RDSEED_EXITING;
6547 		}
6548 	}
6549 
6550 	vmx->secondary_exec_control = exec_control;
6551 }
6552 
ept_set_mmio_spte_mask(void)6553 static void ept_set_mmio_spte_mask(void)
6554 {
6555 	/*
6556 	 * EPT Misconfigurations can be generated if the value of bits 2:0
6557 	 * of an EPT paging-structure entry is 110b (write/execute).
6558 	 */
6559 	kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
6560 				   VMX_EPT_MISCONFIG_WX_VALUE);
6561 }
6562 
6563 #define VMX_XSS_EXIT_BITMAP 0
6564 /*
6565  * Sets up the vmcs for emulated real mode.
6566  */
vmx_vcpu_setup(struct vcpu_vmx * vmx)6567 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
6568 {
6569 	int i;
6570 
6571 	if (enable_shadow_vmcs) {
6572 		/*
6573 		 * At vCPU creation, "VMWRITE to any supported field
6574 		 * in the VMCS" is supported, so use the more
6575 		 * permissive vmx_vmread_bitmap to specify both read
6576 		 * and write permissions for the shadow VMCS.
6577 		 */
6578 		vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
6579 		vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmread_bitmap));
6580 	}
6581 	if (cpu_has_vmx_msr_bitmap())
6582 		vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
6583 
6584 	vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
6585 
6586 	/* Control */
6587 	vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6588 	vmx->hv_deadline_tsc = -1;
6589 
6590 	vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
6591 
6592 	if (cpu_has_secondary_exec_ctrls()) {
6593 		vmx_compute_secondary_exec_control(vmx);
6594 		vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6595 			     vmx->secondary_exec_control);
6596 	}
6597 
6598 	if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
6599 		vmcs_write64(EOI_EXIT_BITMAP0, 0);
6600 		vmcs_write64(EOI_EXIT_BITMAP1, 0);
6601 		vmcs_write64(EOI_EXIT_BITMAP2, 0);
6602 		vmcs_write64(EOI_EXIT_BITMAP3, 0);
6603 
6604 		vmcs_write16(GUEST_INTR_STATUS, 0);
6605 
6606 		vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
6607 		vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
6608 	}
6609 
6610 	if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
6611 		vmcs_write32(PLE_GAP, ple_gap);
6612 		vmx->ple_window = ple_window;
6613 		vmx->ple_window_dirty = true;
6614 	}
6615 
6616 	vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
6617 	vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
6618 	vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
6619 
6620 	vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
6621 	vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
6622 	vmx_set_constant_host_state(vmx);
6623 	vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
6624 	vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
6625 
6626 	if (cpu_has_vmx_vmfunc())
6627 		vmcs_write64(VM_FUNCTION_CONTROL, 0);
6628 
6629 	vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
6630 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
6631 	vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
6632 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
6633 	vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
6634 
6635 	if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
6636 		vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
6637 
6638 	for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6639 		u32 index = vmx_msr_index[i];
6640 		u32 data_low, data_high;
6641 		int j = vmx->nmsrs;
6642 
6643 		if (rdmsr_safe(index, &data_low, &data_high) < 0)
6644 			continue;
6645 		if (wrmsr_safe(index, data_low, data_high) < 0)
6646 			continue;
6647 		vmx->guest_msrs[j].index = i;
6648 		vmx->guest_msrs[j].data = 0;
6649 		vmx->guest_msrs[j].mask = -1ull;
6650 		++vmx->nmsrs;
6651 	}
6652 
6653 	vmx->arch_capabilities = kvm_get_arch_capabilities();
6654 
6655 	vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
6656 
6657 	/* 22.2.1, 20.8.1 */
6658 	vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
6659 
6660 	vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
6661 	vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
6662 
6663 	set_cr4_guest_host_mask(vmx);
6664 
6665 	if (vmx_xsaves_supported())
6666 		vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
6667 
6668 	if (enable_pml) {
6669 		ASSERT(vmx->pml_pg);
6670 		vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
6671 		vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6672 	}
6673 
6674 	if (cpu_has_vmx_encls_vmexit())
6675 		vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
6676 }
6677 
vmx_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)6678 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
6679 {
6680 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6681 	struct msr_data apic_base_msr;
6682 	u64 cr0;
6683 
6684 	vmx->rmode.vm86_active = 0;
6685 	vmx->spec_ctrl = 0;
6686 
6687 	vcpu->arch.microcode_version = 0x100000000ULL;
6688 	vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
6689 	kvm_set_cr8(vcpu, 0);
6690 
6691 	if (!init_event) {
6692 		apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
6693 				     MSR_IA32_APICBASE_ENABLE;
6694 		if (kvm_vcpu_is_reset_bsp(vcpu))
6695 			apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
6696 		apic_base_msr.host_initiated = true;
6697 		kvm_set_apic_base(vcpu, &apic_base_msr);
6698 	}
6699 
6700 	vmx_segment_cache_clear(vmx);
6701 
6702 	seg_setup(VCPU_SREG_CS);
6703 	vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
6704 	vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
6705 
6706 	seg_setup(VCPU_SREG_DS);
6707 	seg_setup(VCPU_SREG_ES);
6708 	seg_setup(VCPU_SREG_FS);
6709 	seg_setup(VCPU_SREG_GS);
6710 	seg_setup(VCPU_SREG_SS);
6711 
6712 	vmcs_write16(GUEST_TR_SELECTOR, 0);
6713 	vmcs_writel(GUEST_TR_BASE, 0);
6714 	vmcs_write32(GUEST_TR_LIMIT, 0xffff);
6715 	vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
6716 
6717 	vmcs_write16(GUEST_LDTR_SELECTOR, 0);
6718 	vmcs_writel(GUEST_LDTR_BASE, 0);
6719 	vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
6720 	vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
6721 
6722 	if (!init_event) {
6723 		vmcs_write32(GUEST_SYSENTER_CS, 0);
6724 		vmcs_writel(GUEST_SYSENTER_ESP, 0);
6725 		vmcs_writel(GUEST_SYSENTER_EIP, 0);
6726 		vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
6727 	}
6728 
6729 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6730 	kvm_rip_write(vcpu, 0xfff0);
6731 
6732 	vmcs_writel(GUEST_GDTR_BASE, 0);
6733 	vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
6734 
6735 	vmcs_writel(GUEST_IDTR_BASE, 0);
6736 	vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
6737 
6738 	vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
6739 	vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
6740 	vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
6741 	if (kvm_mpx_supported())
6742 		vmcs_write64(GUEST_BNDCFGS, 0);
6743 
6744 	setup_msrs(vmx);
6745 
6746 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
6747 
6748 	if (cpu_has_vmx_tpr_shadow() && !init_event) {
6749 		vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
6750 		if (cpu_need_tpr_shadow(vcpu))
6751 			vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
6752 				     __pa(vcpu->arch.apic->regs));
6753 		vmcs_write32(TPR_THRESHOLD, 0);
6754 	}
6755 
6756 	kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6757 
6758 	if (vmx->vpid != 0)
6759 		vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
6760 
6761 	cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
6762 	vmx->vcpu.arch.cr0 = cr0;
6763 	vmx_set_cr0(vcpu, cr0); /* enter rmode */
6764 	vmx_set_cr4(vcpu, 0);
6765 	vmx_set_efer(vcpu, 0);
6766 
6767 	update_exception_bitmap(vcpu);
6768 
6769 	vpid_sync_context(vmx->vpid);
6770 	if (init_event)
6771 		vmx_clear_hlt(vcpu);
6772 }
6773 
6774 /*
6775  * In nested virtualization, check if L1 asked to exit on external interrupts.
6776  * For most existing hypervisors, this will always return true.
6777  */
nested_exit_on_intr(struct kvm_vcpu * vcpu)6778 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
6779 {
6780 	return get_vmcs12(vcpu)->pin_based_vm_exec_control &
6781 		PIN_BASED_EXT_INTR_MASK;
6782 }
6783 
6784 /*
6785  * In nested virtualization, check if L1 has set
6786  * VM_EXIT_ACK_INTR_ON_EXIT
6787  */
nested_exit_intr_ack_set(struct kvm_vcpu * vcpu)6788 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
6789 {
6790 	return get_vmcs12(vcpu)->vm_exit_controls &
6791 		VM_EXIT_ACK_INTR_ON_EXIT;
6792 }
6793 
nested_exit_on_nmi(struct kvm_vcpu * vcpu)6794 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
6795 {
6796 	return nested_cpu_has_nmi_exiting(get_vmcs12(vcpu));
6797 }
6798 
enable_irq_window(struct kvm_vcpu * vcpu)6799 static void enable_irq_window(struct kvm_vcpu *vcpu)
6800 {
6801 	vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6802 		      CPU_BASED_VIRTUAL_INTR_PENDING);
6803 }
6804 
enable_nmi_window(struct kvm_vcpu * vcpu)6805 static void enable_nmi_window(struct kvm_vcpu *vcpu)
6806 {
6807 	if (!enable_vnmi ||
6808 	    vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
6809 		enable_irq_window(vcpu);
6810 		return;
6811 	}
6812 
6813 	vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6814 		      CPU_BASED_VIRTUAL_NMI_PENDING);
6815 }
6816 
vmx_inject_irq(struct kvm_vcpu * vcpu)6817 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
6818 {
6819 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6820 	uint32_t intr;
6821 	int irq = vcpu->arch.interrupt.nr;
6822 
6823 	trace_kvm_inj_virq(irq);
6824 
6825 	++vcpu->stat.irq_injections;
6826 	if (vmx->rmode.vm86_active) {
6827 		int inc_eip = 0;
6828 		if (vcpu->arch.interrupt.soft)
6829 			inc_eip = vcpu->arch.event_exit_inst_len;
6830 		if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
6831 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6832 		return;
6833 	}
6834 	intr = irq | INTR_INFO_VALID_MASK;
6835 	if (vcpu->arch.interrupt.soft) {
6836 		intr |= INTR_TYPE_SOFT_INTR;
6837 		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6838 			     vmx->vcpu.arch.event_exit_inst_len);
6839 	} else
6840 		intr |= INTR_TYPE_EXT_INTR;
6841 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
6842 
6843 	vmx_clear_hlt(vcpu);
6844 }
6845 
vmx_inject_nmi(struct kvm_vcpu * vcpu)6846 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
6847 {
6848 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6849 
6850 	if (!enable_vnmi) {
6851 		/*
6852 		 * Tracking the NMI-blocked state in software is built upon
6853 		 * finding the next open IRQ window. This, in turn, depends on
6854 		 * well-behaving guests: They have to keep IRQs disabled at
6855 		 * least as long as the NMI handler runs. Otherwise we may
6856 		 * cause NMI nesting, maybe breaking the guest. But as this is
6857 		 * highly unlikely, we can live with the residual risk.
6858 		 */
6859 		vmx->loaded_vmcs->soft_vnmi_blocked = 1;
6860 		vmx->loaded_vmcs->vnmi_blocked_time = 0;
6861 	}
6862 
6863 	++vcpu->stat.nmi_injections;
6864 	vmx->loaded_vmcs->nmi_known_unmasked = false;
6865 
6866 	if (vmx->rmode.vm86_active) {
6867 		if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
6868 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6869 		return;
6870 	}
6871 
6872 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6873 			INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
6874 
6875 	vmx_clear_hlt(vcpu);
6876 }
6877 
vmx_get_nmi_mask(struct kvm_vcpu * vcpu)6878 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
6879 {
6880 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6881 	bool masked;
6882 
6883 	if (!enable_vnmi)
6884 		return vmx->loaded_vmcs->soft_vnmi_blocked;
6885 	if (vmx->loaded_vmcs->nmi_known_unmasked)
6886 		return false;
6887 	masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
6888 	vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6889 	return masked;
6890 }
6891 
vmx_set_nmi_mask(struct kvm_vcpu * vcpu,bool masked)6892 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
6893 {
6894 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6895 
6896 	if (!enable_vnmi) {
6897 		if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
6898 			vmx->loaded_vmcs->soft_vnmi_blocked = masked;
6899 			vmx->loaded_vmcs->vnmi_blocked_time = 0;
6900 		}
6901 	} else {
6902 		vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6903 		if (masked)
6904 			vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6905 				      GUEST_INTR_STATE_NMI);
6906 		else
6907 			vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
6908 					GUEST_INTR_STATE_NMI);
6909 	}
6910 }
6911 
vmx_nmi_allowed(struct kvm_vcpu * vcpu)6912 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
6913 {
6914 	if (to_vmx(vcpu)->nested.nested_run_pending)
6915 		return 0;
6916 
6917 	if (!enable_vnmi &&
6918 	    to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
6919 		return 0;
6920 
6921 	return	!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6922 		  (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
6923 		   | GUEST_INTR_STATE_NMI));
6924 }
6925 
vmx_interrupt_allowed(struct kvm_vcpu * vcpu)6926 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
6927 {
6928 	return (!to_vmx(vcpu)->nested.nested_run_pending &&
6929 		vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6930 		!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6931 			(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6932 }
6933 
vmx_set_tss_addr(struct kvm * kvm,unsigned int addr)6934 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6935 {
6936 	int ret;
6937 
6938 	if (enable_unrestricted_guest)
6939 		return 0;
6940 
6941 	ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6942 				    PAGE_SIZE * 3);
6943 	if (ret)
6944 		return ret;
6945 	to_kvm_vmx(kvm)->tss_addr = addr;
6946 	return init_rmode_tss(kvm);
6947 }
6948 
vmx_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)6949 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
6950 {
6951 	to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
6952 	return 0;
6953 }
6954 
rmode_exception(struct kvm_vcpu * vcpu,int vec)6955 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6956 {
6957 	switch (vec) {
6958 	case BP_VECTOR:
6959 		/*
6960 		 * Update instruction length as we may reinject the exception
6961 		 * from user space while in guest debugging mode.
6962 		 */
6963 		to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6964 			vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6965 		if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6966 			return false;
6967 		/* fall through */
6968 	case DB_VECTOR:
6969 		if (vcpu->guest_debug &
6970 			(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6971 			return false;
6972 		/* fall through */
6973 	case DE_VECTOR:
6974 	case OF_VECTOR:
6975 	case BR_VECTOR:
6976 	case UD_VECTOR:
6977 	case DF_VECTOR:
6978 	case SS_VECTOR:
6979 	case GP_VECTOR:
6980 	case MF_VECTOR:
6981 		return true;
6982 	break;
6983 	}
6984 	return false;
6985 }
6986 
handle_rmode_exception(struct kvm_vcpu * vcpu,int vec,u32 err_code)6987 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
6988 				  int vec, u32 err_code)
6989 {
6990 	/*
6991 	 * Instruction with address size override prefix opcode 0x67
6992 	 * Cause the #SS fault with 0 error code in VM86 mode.
6993 	 */
6994 	if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
6995 		if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
6996 			if (vcpu->arch.halt_request) {
6997 				vcpu->arch.halt_request = 0;
6998 				return kvm_vcpu_halt(vcpu);
6999 			}
7000 			return 1;
7001 		}
7002 		return 0;
7003 	}
7004 
7005 	/*
7006 	 * Forward all other exceptions that are valid in real mode.
7007 	 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
7008 	 *        the required debugging infrastructure rework.
7009 	 */
7010 	kvm_queue_exception(vcpu, vec);
7011 	return 1;
7012 }
7013 
7014 /*
7015  * Trigger machine check on the host. We assume all the MSRs are already set up
7016  * by the CPU and that we still run on the same CPU as the MCE occurred on.
7017  * We pass a fake environment to the machine check handler because we want
7018  * the guest to be always treated like user space, no matter what context
7019  * it used internally.
7020  */
kvm_machine_check(void)7021 static void kvm_machine_check(void)
7022 {
7023 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
7024 	struct pt_regs regs = {
7025 		.cs = 3, /* Fake ring 3 no matter what the guest ran on */
7026 		.flags = X86_EFLAGS_IF,
7027 	};
7028 
7029 	do_machine_check(&regs, 0);
7030 #endif
7031 }
7032 
handle_machine_check(struct kvm_vcpu * vcpu)7033 static int handle_machine_check(struct kvm_vcpu *vcpu)
7034 {
7035 	/* already handled by vcpu_run */
7036 	return 1;
7037 }
7038 
handle_exception(struct kvm_vcpu * vcpu)7039 static int handle_exception(struct kvm_vcpu *vcpu)
7040 {
7041 	struct vcpu_vmx *vmx = to_vmx(vcpu);
7042 	struct kvm_run *kvm_run = vcpu->run;
7043 	u32 intr_info, ex_no, error_code;
7044 	unsigned long cr2, rip, dr6;
7045 	u32 vect_info;
7046 	enum emulation_result er;
7047 
7048 	vect_info = vmx->idt_vectoring_info;
7049 	intr_info = vmx->exit_intr_info;
7050 
7051 	if (is_machine_check(intr_info))
7052 		return handle_machine_check(vcpu);
7053 
7054 	if (is_nmi(intr_info))
7055 		return 1;  /* already handled by vmx_vcpu_run() */
7056 
7057 	if (is_invalid_opcode(intr_info))
7058 		return handle_ud(vcpu);
7059 
7060 	error_code = 0;
7061 	if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
7062 		error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
7063 
7064 	if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
7065 		WARN_ON_ONCE(!enable_vmware_backdoor);
7066 		er = kvm_emulate_instruction(vcpu,
7067 			EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
7068 		if (er == EMULATE_USER_EXIT)
7069 			return 0;
7070 		else if (er != EMULATE_DONE)
7071 			kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
7072 		return 1;
7073 	}
7074 
7075 	/*
7076 	 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
7077 	 * MMIO, it is better to report an internal error.
7078 	 * See the comments in vmx_handle_exit.
7079 	 */
7080 	if ((vect_info & VECTORING_INFO_VALID_MASK) &&
7081 	    !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
7082 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7083 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
7084 		vcpu->run->internal.ndata = 3;
7085 		vcpu->run->internal.data[0] = vect_info;
7086 		vcpu->run->internal.data[1] = intr_info;
7087 		vcpu->run->internal.data[2] = error_code;
7088 		return 0;
7089 	}
7090 
7091 	if (is_page_fault(intr_info)) {
7092 		cr2 = vmcs_readl(EXIT_QUALIFICATION);
7093 		/* EPT won't cause page fault directly */
7094 		WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
7095 		return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
7096 	}
7097 
7098 	ex_no = intr_info & INTR_INFO_VECTOR_MASK;
7099 
7100 	if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
7101 		return handle_rmode_exception(vcpu, ex_no, error_code);
7102 
7103 	switch (ex_no) {
7104 	case AC_VECTOR:
7105 		kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
7106 		return 1;
7107 	case DB_VECTOR:
7108 		dr6 = vmcs_readl(EXIT_QUALIFICATION);
7109 		if (!(vcpu->guest_debug &
7110 		      (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
7111 			vcpu->arch.dr6 &= ~15;
7112 			vcpu->arch.dr6 |= dr6 | DR6_RTM;
7113 			if (is_icebp(intr_info))
7114 				skip_emulated_instruction(vcpu);
7115 
7116 			kvm_queue_exception(vcpu, DB_VECTOR);
7117 			return 1;
7118 		}
7119 		kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
7120 		kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
7121 		/* fall through */
7122 	case BP_VECTOR:
7123 		/*
7124 		 * Update instruction length as we may reinject #BP from
7125 		 * user space while in guest debugging mode. Reading it for
7126 		 * #DB as well causes no harm, it is not used in that case.
7127 		 */
7128 		vmx->vcpu.arch.event_exit_inst_len =
7129 			vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
7130 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
7131 		rip = kvm_rip_read(vcpu);
7132 		kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
7133 		kvm_run->debug.arch.exception = ex_no;
7134 		break;
7135 	default:
7136 		kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
7137 		kvm_run->ex.exception = ex_no;
7138 		kvm_run->ex.error_code = error_code;
7139 		break;
7140 	}
7141 	return 0;
7142 }
7143 
handle_external_interrupt(struct kvm_vcpu * vcpu)7144 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
7145 {
7146 	++vcpu->stat.irq_exits;
7147 	return 1;
7148 }
7149 
handle_triple_fault(struct kvm_vcpu * vcpu)7150 static int handle_triple_fault(struct kvm_vcpu *vcpu)
7151 {
7152 	vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
7153 	vcpu->mmio_needed = 0;
7154 	return 0;
7155 }
7156 
handle_io(struct kvm_vcpu * vcpu)7157 static int handle_io(struct kvm_vcpu *vcpu)
7158 {
7159 	unsigned long exit_qualification;
7160 	int size, in, string;
7161 	unsigned port;
7162 
7163 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7164 	string = (exit_qualification & 16) != 0;
7165 
7166 	++vcpu->stat.io_exits;
7167 
7168 	if (string)
7169 		return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7170 
7171 	port = exit_qualification >> 16;
7172 	size = (exit_qualification & 7) + 1;
7173 	in = (exit_qualification & 8) != 0;
7174 
7175 	return kvm_fast_pio(vcpu, size, port, in);
7176 }
7177 
7178 static void
vmx_patch_hypercall(struct kvm_vcpu * vcpu,unsigned char * hypercall)7179 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
7180 {
7181 	/*
7182 	 * Patch in the VMCALL instruction:
7183 	 */
7184 	hypercall[0] = 0x0f;
7185 	hypercall[1] = 0x01;
7186 	hypercall[2] = 0xc1;
7187 }
7188 
7189 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
handle_set_cr0(struct kvm_vcpu * vcpu,unsigned long val)7190 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
7191 {
7192 	if (is_guest_mode(vcpu)) {
7193 		struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7194 		unsigned long orig_val = val;
7195 
7196 		/*
7197 		 * We get here when L2 changed cr0 in a way that did not change
7198 		 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
7199 		 * but did change L0 shadowed bits. So we first calculate the
7200 		 * effective cr0 value that L1 would like to write into the
7201 		 * hardware. It consists of the L2-owned bits from the new
7202 		 * value combined with the L1-owned bits from L1's guest_cr0.
7203 		 */
7204 		val = (val & ~vmcs12->cr0_guest_host_mask) |
7205 			(vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
7206 
7207 		if (!nested_guest_cr0_valid(vcpu, val))
7208 			return 1;
7209 
7210 		if (kvm_set_cr0(vcpu, val))
7211 			return 1;
7212 		vmcs_writel(CR0_READ_SHADOW, orig_val);
7213 		return 0;
7214 	} else {
7215 		if (to_vmx(vcpu)->nested.vmxon &&
7216 		    !nested_host_cr0_valid(vcpu, val))
7217 			return 1;
7218 
7219 		return kvm_set_cr0(vcpu, val);
7220 	}
7221 }
7222 
handle_set_cr4(struct kvm_vcpu * vcpu,unsigned long val)7223 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
7224 {
7225 	if (is_guest_mode(vcpu)) {
7226 		struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7227 		unsigned long orig_val = val;
7228 
7229 		/* analogously to handle_set_cr0 */
7230 		val = (val & ~vmcs12->cr4_guest_host_mask) |
7231 			(vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
7232 		if (kvm_set_cr4(vcpu, val))
7233 			return 1;
7234 		vmcs_writel(CR4_READ_SHADOW, orig_val);
7235 		return 0;
7236 	} else
7237 		return kvm_set_cr4(vcpu, val);
7238 }
7239 
handle_desc(struct kvm_vcpu * vcpu)7240 static int handle_desc(struct kvm_vcpu *vcpu)
7241 {
7242 	WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
7243 	return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7244 }
7245 
handle_cr(struct kvm_vcpu * vcpu)7246 static int handle_cr(struct kvm_vcpu *vcpu)
7247 {
7248 	unsigned long exit_qualification, val;
7249 	int cr;
7250 	int reg;
7251 	int err;
7252 	int ret;
7253 
7254 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7255 	cr = exit_qualification & 15;
7256 	reg = (exit_qualification >> 8) & 15;
7257 	switch ((exit_qualification >> 4) & 3) {
7258 	case 0: /* mov to cr */
7259 		val = kvm_register_readl(vcpu, reg);
7260 		trace_kvm_cr_write(cr, val);
7261 		switch (cr) {
7262 		case 0:
7263 			err = handle_set_cr0(vcpu, val);
7264 			return kvm_complete_insn_gp(vcpu, err);
7265 		case 3:
7266 			WARN_ON_ONCE(enable_unrestricted_guest);
7267 			err = kvm_set_cr3(vcpu, val);
7268 			return kvm_complete_insn_gp(vcpu, err);
7269 		case 4:
7270 			err = handle_set_cr4(vcpu, val);
7271 			return kvm_complete_insn_gp(vcpu, err);
7272 		case 8: {
7273 				u8 cr8_prev = kvm_get_cr8(vcpu);
7274 				u8 cr8 = (u8)val;
7275 				err = kvm_set_cr8(vcpu, cr8);
7276 				ret = kvm_complete_insn_gp(vcpu, err);
7277 				if (lapic_in_kernel(vcpu))
7278 					return ret;
7279 				if (cr8_prev <= cr8)
7280 					return ret;
7281 				/*
7282 				 * TODO: we might be squashing a
7283 				 * KVM_GUESTDBG_SINGLESTEP-triggered
7284 				 * KVM_EXIT_DEBUG here.
7285 				 */
7286 				vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
7287 				return 0;
7288 			}
7289 		}
7290 		break;
7291 	case 2: /* clts */
7292 		WARN_ONCE(1, "Guest should always own CR0.TS");
7293 		vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
7294 		trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
7295 		return kvm_skip_emulated_instruction(vcpu);
7296 	case 1: /*mov from cr*/
7297 		switch (cr) {
7298 		case 3:
7299 			WARN_ON_ONCE(enable_unrestricted_guest);
7300 			val = kvm_read_cr3(vcpu);
7301 			kvm_register_write(vcpu, reg, val);
7302 			trace_kvm_cr_read(cr, val);
7303 			return kvm_skip_emulated_instruction(vcpu);
7304 		case 8:
7305 			val = kvm_get_cr8(vcpu);
7306 			kvm_register_write(vcpu, reg, val);
7307 			trace_kvm_cr_read(cr, val);
7308 			return kvm_skip_emulated_instruction(vcpu);
7309 		}
7310 		break;
7311 	case 3: /* lmsw */
7312 		val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
7313 		trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
7314 		kvm_lmsw(vcpu, val);
7315 
7316 		return kvm_skip_emulated_instruction(vcpu);
7317 	default:
7318 		break;
7319 	}
7320 	vcpu->run->exit_reason = 0;
7321 	vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
7322 	       (int)(exit_qualification >> 4) & 3, cr);
7323 	return 0;
7324 }
7325 
handle_dr(struct kvm_vcpu * vcpu)7326 static int handle_dr(struct kvm_vcpu *vcpu)
7327 {
7328 	unsigned long exit_qualification;
7329 	int dr, dr7, reg;
7330 
7331 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7332 	dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
7333 
7334 	/* First, if DR does not exist, trigger UD */
7335 	if (!kvm_require_dr(vcpu, dr))
7336 		return 1;
7337 
7338 	/* Do not handle if the CPL > 0, will trigger GP on re-entry */
7339 	if (!kvm_require_cpl(vcpu, 0))
7340 		return 1;
7341 	dr7 = vmcs_readl(GUEST_DR7);
7342 	if (dr7 & DR7_GD) {
7343 		/*
7344 		 * As the vm-exit takes precedence over the debug trap, we
7345 		 * need to emulate the latter, either for the host or the
7346 		 * guest debugging itself.
7347 		 */
7348 		if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7349 			vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
7350 			vcpu->run->debug.arch.dr7 = dr7;
7351 			vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
7352 			vcpu->run->debug.arch.exception = DB_VECTOR;
7353 			vcpu->run->exit_reason = KVM_EXIT_DEBUG;
7354 			return 0;
7355 		} else {
7356 			vcpu->arch.dr6 &= ~15;
7357 			vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
7358 			kvm_queue_exception(vcpu, DB_VECTOR);
7359 			return 1;
7360 		}
7361 	}
7362 
7363 	if (vcpu->guest_debug == 0) {
7364 		vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7365 				CPU_BASED_MOV_DR_EXITING);
7366 
7367 		/*
7368 		 * No more DR vmexits; force a reload of the debug registers
7369 		 * and reenter on this instruction.  The next vmexit will
7370 		 * retrieve the full state of the debug registers.
7371 		 */
7372 		vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
7373 		return 1;
7374 	}
7375 
7376 	reg = DEBUG_REG_ACCESS_REG(exit_qualification);
7377 	if (exit_qualification & TYPE_MOV_FROM_DR) {
7378 		unsigned long val;
7379 
7380 		if (kvm_get_dr(vcpu, dr, &val))
7381 			return 1;
7382 		kvm_register_write(vcpu, reg, val);
7383 	} else
7384 		if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
7385 			return 1;
7386 
7387 	return kvm_skip_emulated_instruction(vcpu);
7388 }
7389 
vmx_get_dr6(struct kvm_vcpu * vcpu)7390 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
7391 {
7392 	return vcpu->arch.dr6;
7393 }
7394 
vmx_set_dr6(struct kvm_vcpu * vcpu,unsigned long val)7395 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
7396 {
7397 }
7398 
vmx_sync_dirty_debug_regs(struct kvm_vcpu * vcpu)7399 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
7400 {
7401 	get_debugreg(vcpu->arch.db[0], 0);
7402 	get_debugreg(vcpu->arch.db[1], 1);
7403 	get_debugreg(vcpu->arch.db[2], 2);
7404 	get_debugreg(vcpu->arch.db[3], 3);
7405 	get_debugreg(vcpu->arch.dr6, 6);
7406 	vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
7407 
7408 	vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
7409 	vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
7410 }
7411 
vmx_set_dr7(struct kvm_vcpu * vcpu,unsigned long val)7412 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
7413 {
7414 	vmcs_writel(GUEST_DR7, val);
7415 }
7416 
handle_cpuid(struct kvm_vcpu * vcpu)7417 static int handle_cpuid(struct kvm_vcpu *vcpu)
7418 {
7419 	return kvm_emulate_cpuid(vcpu);
7420 }
7421 
handle_rdmsr(struct kvm_vcpu * vcpu)7422 static int handle_rdmsr(struct kvm_vcpu *vcpu)
7423 {
7424 	u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7425 	struct msr_data msr_info;
7426 
7427 	msr_info.index = ecx;
7428 	msr_info.host_initiated = false;
7429 	if (vmx_get_msr(vcpu, &msr_info)) {
7430 		trace_kvm_msr_read_ex(ecx);
7431 		kvm_inject_gp(vcpu, 0);
7432 		return 1;
7433 	}
7434 
7435 	trace_kvm_msr_read(ecx, msr_info.data);
7436 
7437 	/* FIXME: handling of bits 32:63 of rax, rdx */
7438 	vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
7439 	vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
7440 	return kvm_skip_emulated_instruction(vcpu);
7441 }
7442 
handle_wrmsr(struct kvm_vcpu * vcpu)7443 static int handle_wrmsr(struct kvm_vcpu *vcpu)
7444 {
7445 	struct msr_data msr;
7446 	u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7447 	u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
7448 		| ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
7449 
7450 	msr.data = data;
7451 	msr.index = ecx;
7452 	msr.host_initiated = false;
7453 	if (kvm_set_msr(vcpu, &msr) != 0) {
7454 		trace_kvm_msr_write_ex(ecx, data);
7455 		kvm_inject_gp(vcpu, 0);
7456 		return 1;
7457 	}
7458 
7459 	trace_kvm_msr_write(ecx, data);
7460 	return kvm_skip_emulated_instruction(vcpu);
7461 }
7462 
handle_tpr_below_threshold(struct kvm_vcpu * vcpu)7463 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
7464 {
7465 	kvm_apic_update_ppr(vcpu);
7466 	return 1;
7467 }
7468 
handle_interrupt_window(struct kvm_vcpu * vcpu)7469 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
7470 {
7471 	vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7472 			CPU_BASED_VIRTUAL_INTR_PENDING);
7473 
7474 	kvm_make_request(KVM_REQ_EVENT, vcpu);
7475 
7476 	++vcpu->stat.irq_window_exits;
7477 	return 1;
7478 }
7479 
handle_halt(struct kvm_vcpu * vcpu)7480 static int handle_halt(struct kvm_vcpu *vcpu)
7481 {
7482 	return kvm_emulate_halt(vcpu);
7483 }
7484 
handle_vmcall(struct kvm_vcpu * vcpu)7485 static int handle_vmcall(struct kvm_vcpu *vcpu)
7486 {
7487 	return kvm_emulate_hypercall(vcpu);
7488 }
7489 
handle_invd(struct kvm_vcpu * vcpu)7490 static int handle_invd(struct kvm_vcpu *vcpu)
7491 {
7492 	return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7493 }
7494 
handle_invlpg(struct kvm_vcpu * vcpu)7495 static int handle_invlpg(struct kvm_vcpu *vcpu)
7496 {
7497 	unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7498 
7499 	kvm_mmu_invlpg(vcpu, exit_qualification);
7500 	return kvm_skip_emulated_instruction(vcpu);
7501 }
7502 
handle_rdpmc(struct kvm_vcpu * vcpu)7503 static int handle_rdpmc(struct kvm_vcpu *vcpu)
7504 {
7505 	int err;
7506 
7507 	err = kvm_rdpmc(vcpu);
7508 	return kvm_complete_insn_gp(vcpu, err);
7509 }
7510 
handle_wbinvd(struct kvm_vcpu * vcpu)7511 static int handle_wbinvd(struct kvm_vcpu *vcpu)
7512 {
7513 	return kvm_emulate_wbinvd(vcpu);
7514 }
7515 
handle_xsetbv(struct kvm_vcpu * vcpu)7516 static int handle_xsetbv(struct kvm_vcpu *vcpu)
7517 {
7518 	u64 new_bv = kvm_read_edx_eax(vcpu);
7519 	u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
7520 
7521 	if (kvm_set_xcr(vcpu, index, new_bv) == 0)
7522 		return kvm_skip_emulated_instruction(vcpu);
7523 	return 1;
7524 }
7525 
handle_xsaves(struct kvm_vcpu * vcpu)7526 static int handle_xsaves(struct kvm_vcpu *vcpu)
7527 {
7528 	kvm_skip_emulated_instruction(vcpu);
7529 	WARN(1, "this should never happen\n");
7530 	return 1;
7531 }
7532 
handle_xrstors(struct kvm_vcpu * vcpu)7533 static int handle_xrstors(struct kvm_vcpu *vcpu)
7534 {
7535 	kvm_skip_emulated_instruction(vcpu);
7536 	WARN(1, "this should never happen\n");
7537 	return 1;
7538 }
7539 
handle_apic_access(struct kvm_vcpu * vcpu)7540 static int handle_apic_access(struct kvm_vcpu *vcpu)
7541 {
7542 	if (likely(fasteoi)) {
7543 		unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7544 		int access_type, offset;
7545 
7546 		access_type = exit_qualification & APIC_ACCESS_TYPE;
7547 		offset = exit_qualification & APIC_ACCESS_OFFSET;
7548 		/*
7549 		 * Sane guest uses MOV to write EOI, with written value
7550 		 * not cared. So make a short-circuit here by avoiding
7551 		 * heavy instruction emulation.
7552 		 */
7553 		if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
7554 		    (offset == APIC_EOI)) {
7555 			kvm_lapic_set_eoi(vcpu);
7556 			return kvm_skip_emulated_instruction(vcpu);
7557 		}
7558 	}
7559 	return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7560 }
7561 
handle_apic_eoi_induced(struct kvm_vcpu * vcpu)7562 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
7563 {
7564 	unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7565 	int vector = exit_qualification & 0xff;
7566 
7567 	/* EOI-induced VM exit is trap-like and thus no need to adjust IP */
7568 	kvm_apic_set_eoi_accelerated(vcpu, vector);
7569 	return 1;
7570 }
7571 
handle_apic_write(struct kvm_vcpu * vcpu)7572 static int handle_apic_write(struct kvm_vcpu *vcpu)
7573 {
7574 	unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7575 	u32 offset = exit_qualification & 0xfff;
7576 
7577 	/* APIC-write VM exit is trap-like and thus no need to adjust IP */
7578 	kvm_apic_write_nodecode(vcpu, offset);
7579 	return 1;
7580 }
7581 
handle_task_switch(struct kvm_vcpu * vcpu)7582 static int handle_task_switch(struct kvm_vcpu *vcpu)
7583 {
7584 	struct vcpu_vmx *vmx = to_vmx(vcpu);
7585 	unsigned long exit_qualification;
7586 	bool has_error_code = false;
7587 	u32 error_code = 0;
7588 	u16 tss_selector;
7589 	int reason, type, idt_v, idt_index;
7590 
7591 	idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
7592 	idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
7593 	type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
7594 
7595 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7596 
7597 	reason = (u32)exit_qualification >> 30;
7598 	if (reason == TASK_SWITCH_GATE && idt_v) {
7599 		switch (type) {
7600 		case INTR_TYPE_NMI_INTR:
7601 			vcpu->arch.nmi_injected = false;
7602 			vmx_set_nmi_mask(vcpu, true);
7603 			break;
7604 		case INTR_TYPE_EXT_INTR:
7605 		case INTR_TYPE_SOFT_INTR:
7606 			kvm_clear_interrupt_queue(vcpu);
7607 			break;
7608 		case INTR_TYPE_HARD_EXCEPTION:
7609 			if (vmx->idt_vectoring_info &
7610 			    VECTORING_INFO_DELIVER_CODE_MASK) {
7611 				has_error_code = true;
7612 				error_code =
7613 					vmcs_read32(IDT_VECTORING_ERROR_CODE);
7614 			}
7615 			/* fall through */
7616 		case INTR_TYPE_SOFT_EXCEPTION:
7617 			kvm_clear_exception_queue(vcpu);
7618 			break;
7619 		default:
7620 			break;
7621 		}
7622 	}
7623 	tss_selector = exit_qualification;
7624 
7625 	if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
7626 		       type != INTR_TYPE_EXT_INTR &&
7627 		       type != INTR_TYPE_NMI_INTR))
7628 		skip_emulated_instruction(vcpu);
7629 
7630 	if (kvm_task_switch(vcpu, tss_selector,
7631 			    type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
7632 			    has_error_code, error_code) == EMULATE_FAIL) {
7633 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7634 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7635 		vcpu->run->internal.ndata = 0;
7636 		return 0;
7637 	}
7638 
7639 	/*
7640 	 * TODO: What about debug traps on tss switch?
7641 	 *       Are we supposed to inject them and update dr6?
7642 	 */
7643 
7644 	return 1;
7645 }
7646 
handle_ept_violation(struct kvm_vcpu * vcpu)7647 static int handle_ept_violation(struct kvm_vcpu *vcpu)
7648 {
7649 	unsigned long exit_qualification;
7650 	gpa_t gpa;
7651 	u64 error_code;
7652 
7653 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7654 
7655 	/*
7656 	 * EPT violation happened while executing iret from NMI,
7657 	 * "blocked by NMI" bit has to be set before next VM entry.
7658 	 * There are errata that may cause this bit to not be set:
7659 	 * AAK134, BY25.
7660 	 */
7661 	if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
7662 			enable_vnmi &&
7663 			(exit_qualification & INTR_INFO_UNBLOCK_NMI))
7664 		vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
7665 
7666 	gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7667 	trace_kvm_page_fault(gpa, exit_qualification);
7668 
7669 	/* Is it a read fault? */
7670 	error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
7671 		     ? PFERR_USER_MASK : 0;
7672 	/* Is it a write fault? */
7673 	error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
7674 		      ? PFERR_WRITE_MASK : 0;
7675 	/* Is it a fetch fault? */
7676 	error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
7677 		      ? PFERR_FETCH_MASK : 0;
7678 	/* ept page table entry is present? */
7679 	error_code |= (exit_qualification &
7680 		       (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
7681 			EPT_VIOLATION_EXECUTABLE))
7682 		      ? PFERR_PRESENT_MASK : 0;
7683 
7684 	error_code |= (exit_qualification & 0x100) != 0 ?
7685 	       PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
7686 
7687 	vcpu->arch.exit_qualification = exit_qualification;
7688 	return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
7689 }
7690 
handle_ept_misconfig(struct kvm_vcpu * vcpu)7691 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
7692 {
7693 	gpa_t gpa;
7694 
7695 	/*
7696 	 * A nested guest cannot optimize MMIO vmexits, because we have an
7697 	 * nGPA here instead of the required GPA.
7698 	 */
7699 	gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7700 	if (!is_guest_mode(vcpu) &&
7701 	    !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
7702 		trace_kvm_fast_mmio(gpa);
7703 		/*
7704 		 * Doing kvm_skip_emulated_instruction() depends on undefined
7705 		 * behavior: Intel's manual doesn't mandate
7706 		 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
7707 		 * occurs and while on real hardware it was observed to be set,
7708 		 * other hypervisors (namely Hyper-V) don't set it, we end up
7709 		 * advancing IP with some random value. Disable fast mmio when
7710 		 * running nested and keep it for real hardware in hope that
7711 		 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
7712 		 */
7713 		if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
7714 			return kvm_skip_emulated_instruction(vcpu);
7715 		else
7716 			return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
7717 								EMULATE_DONE;
7718 	}
7719 
7720 	return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
7721 }
7722 
handle_nmi_window(struct kvm_vcpu * vcpu)7723 static int handle_nmi_window(struct kvm_vcpu *vcpu)
7724 {
7725 	WARN_ON_ONCE(!enable_vnmi);
7726 	vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7727 			CPU_BASED_VIRTUAL_NMI_PENDING);
7728 	++vcpu->stat.nmi_window_exits;
7729 	kvm_make_request(KVM_REQ_EVENT, vcpu);
7730 
7731 	return 1;
7732 }
7733 
handle_invalid_guest_state(struct kvm_vcpu * vcpu)7734 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
7735 {
7736 	struct vcpu_vmx *vmx = to_vmx(vcpu);
7737 	enum emulation_result err = EMULATE_DONE;
7738 	int ret = 1;
7739 	u32 cpu_exec_ctrl;
7740 	bool intr_window_requested;
7741 	unsigned count = 130;
7742 
7743 	/*
7744 	 * We should never reach the point where we are emulating L2
7745 	 * due to invalid guest state as that means we incorrectly
7746 	 * allowed a nested VMEntry with an invalid vmcs12.
7747 	 */
7748 	WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
7749 
7750 	cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
7751 	intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
7752 
7753 	while (vmx->emulation_required && count-- != 0) {
7754 		if (intr_window_requested && vmx_interrupt_allowed(vcpu))
7755 			return handle_interrupt_window(&vmx->vcpu);
7756 
7757 		if (kvm_test_request(KVM_REQ_EVENT, vcpu))
7758 			return 1;
7759 
7760 		err = kvm_emulate_instruction(vcpu, 0);
7761 
7762 		if (err == EMULATE_USER_EXIT) {
7763 			++vcpu->stat.mmio_exits;
7764 			ret = 0;
7765 			goto out;
7766 		}
7767 
7768 		if (err != EMULATE_DONE)
7769 			goto emulation_error;
7770 
7771 		if (vmx->emulation_required && !vmx->rmode.vm86_active &&
7772 		    vcpu->arch.exception.pending)
7773 			goto emulation_error;
7774 
7775 		if (vcpu->arch.halt_request) {
7776 			vcpu->arch.halt_request = 0;
7777 			ret = kvm_vcpu_halt(vcpu);
7778 			goto out;
7779 		}
7780 
7781 		if (signal_pending(current))
7782 			goto out;
7783 		if (need_resched())
7784 			schedule();
7785 	}
7786 
7787 out:
7788 	return ret;
7789 
7790 emulation_error:
7791 	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7792 	vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7793 	vcpu->run->internal.ndata = 0;
7794 	return 0;
7795 }
7796 
grow_ple_window(struct kvm_vcpu * vcpu)7797 static void grow_ple_window(struct kvm_vcpu *vcpu)
7798 {
7799 	struct vcpu_vmx *vmx = to_vmx(vcpu);
7800 	int old = vmx->ple_window;
7801 
7802 	vmx->ple_window = __grow_ple_window(old, ple_window,
7803 					    ple_window_grow,
7804 					    ple_window_max);
7805 
7806 	if (vmx->ple_window != old)
7807 		vmx->ple_window_dirty = true;
7808 
7809 	trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
7810 }
7811 
shrink_ple_window(struct kvm_vcpu * vcpu)7812 static void shrink_ple_window(struct kvm_vcpu *vcpu)
7813 {
7814 	struct vcpu_vmx *vmx = to_vmx(vcpu);
7815 	int old = vmx->ple_window;
7816 
7817 	vmx->ple_window = __shrink_ple_window(old, ple_window,
7818 					      ple_window_shrink,
7819 					      ple_window);
7820 
7821 	if (vmx->ple_window != old)
7822 		vmx->ple_window_dirty = true;
7823 
7824 	trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
7825 }
7826 
7827 /*
7828  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
7829  */
wakeup_handler(void)7830 static void wakeup_handler(void)
7831 {
7832 	struct kvm_vcpu *vcpu;
7833 	int cpu = smp_processor_id();
7834 
7835 	spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7836 	list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
7837 			blocked_vcpu_list) {
7838 		struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7839 
7840 		if (pi_test_on(pi_desc) == 1)
7841 			kvm_vcpu_kick(vcpu);
7842 	}
7843 	spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7844 }
7845 
vmx_enable_tdp(void)7846 static void vmx_enable_tdp(void)
7847 {
7848 	kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
7849 		enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
7850 		enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
7851 		0ull, VMX_EPT_EXECUTABLE_MASK,
7852 		cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
7853 		VMX_EPT_RWX_MASK, 0ull);
7854 
7855 	ept_set_mmio_spte_mask();
7856 	kvm_enable_tdp();
7857 }
7858 
hardware_setup(void)7859 static __init int hardware_setup(void)
7860 {
7861 	unsigned long host_bndcfgs;
7862 	int r = -ENOMEM, i;
7863 
7864 	rdmsrl_safe(MSR_EFER, &host_efer);
7865 
7866 	for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7867 		kvm_define_shared_msr(i, vmx_msr_index[i]);
7868 
7869 	for (i = 0; i < VMX_BITMAP_NR; i++) {
7870 		vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
7871 		if (!vmx_bitmap[i])
7872 			goto out;
7873 	}
7874 
7875 	memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
7876 	memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
7877 
7878 	if (setup_vmcs_config(&vmcs_config) < 0) {
7879 		r = -EIO;
7880 		goto out;
7881 	}
7882 
7883 	if (boot_cpu_has(X86_FEATURE_NX))
7884 		kvm_enable_efer_bits(EFER_NX);
7885 
7886 	if (boot_cpu_has(X86_FEATURE_MPX)) {
7887 		rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7888 		WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7889 	}
7890 
7891 	if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7892 		!(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7893 		enable_vpid = 0;
7894 
7895 	if (!cpu_has_vmx_ept() ||
7896 	    !cpu_has_vmx_ept_4levels() ||
7897 	    !cpu_has_vmx_ept_mt_wb() ||
7898 	    !cpu_has_vmx_invept_global())
7899 		enable_ept = 0;
7900 
7901 	if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7902 		enable_ept_ad_bits = 0;
7903 
7904 	if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7905 		enable_unrestricted_guest = 0;
7906 
7907 	if (!cpu_has_vmx_flexpriority())
7908 		flexpriority_enabled = 0;
7909 
7910 	if (!cpu_has_virtual_nmis())
7911 		enable_vnmi = 0;
7912 
7913 	/*
7914 	 * set_apic_access_page_addr() is used to reload apic access
7915 	 * page upon invalidation.  No need to do anything if not
7916 	 * using the APIC_ACCESS_ADDR VMCS field.
7917 	 */
7918 	if (!flexpriority_enabled)
7919 		kvm_x86_ops->set_apic_access_page_addr = NULL;
7920 
7921 	if (!cpu_has_vmx_tpr_shadow())
7922 		kvm_x86_ops->update_cr8_intercept = NULL;
7923 
7924 	if (enable_ept && !cpu_has_vmx_ept_2m_page())
7925 		kvm_disable_largepages();
7926 
7927 #if IS_ENABLED(CONFIG_HYPERV)
7928 	if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7929 	    && enable_ept)
7930 		kvm_x86_ops->tlb_remote_flush = vmx_hv_remote_flush_tlb;
7931 #endif
7932 
7933 	if (!cpu_has_vmx_ple()) {
7934 		ple_gap = 0;
7935 		ple_window = 0;
7936 		ple_window_grow = 0;
7937 		ple_window_max = 0;
7938 		ple_window_shrink = 0;
7939 	}
7940 
7941 	if (!cpu_has_vmx_apicv()) {
7942 		enable_apicv = 0;
7943 		kvm_x86_ops->sync_pir_to_irr = NULL;
7944 	}
7945 
7946 	if (cpu_has_vmx_tsc_scaling()) {
7947 		kvm_has_tsc_control = true;
7948 		kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7949 		kvm_tsc_scaling_ratio_frac_bits = 48;
7950 	}
7951 
7952 	set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7953 
7954 	if (enable_ept)
7955 		vmx_enable_tdp();
7956 	else
7957 		kvm_disable_tdp();
7958 
7959 	if (!nested) {
7960 		kvm_x86_ops->get_nested_state = NULL;
7961 		kvm_x86_ops->set_nested_state = NULL;
7962 	}
7963 
7964 	/*
7965 	 * Only enable PML when hardware supports PML feature, and both EPT
7966 	 * and EPT A/D bit features are enabled -- PML depends on them to work.
7967 	 */
7968 	if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7969 		enable_pml = 0;
7970 
7971 	if (!enable_pml) {
7972 		kvm_x86_ops->slot_enable_log_dirty = NULL;
7973 		kvm_x86_ops->slot_disable_log_dirty = NULL;
7974 		kvm_x86_ops->flush_log_dirty = NULL;
7975 		kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7976 	}
7977 
7978 	if (!cpu_has_vmx_preemption_timer())
7979 		kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7980 
7981 	if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7982 		u64 vmx_msr;
7983 
7984 		rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7985 		cpu_preemption_timer_multi =
7986 			 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7987 	} else {
7988 		kvm_x86_ops->set_hv_timer = NULL;
7989 		kvm_x86_ops->cancel_hv_timer = NULL;
7990 	}
7991 
7992 	if (!cpu_has_vmx_shadow_vmcs())
7993 		enable_shadow_vmcs = 0;
7994 	if (enable_shadow_vmcs)
7995 		init_vmcs_shadow_fields();
7996 
7997 	kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7998 	nested_vmx_setup_ctls_msrs(&vmcs_config.nested, enable_apicv);
7999 
8000 	kvm_mce_cap_supported |= MCG_LMCE_P;
8001 
8002 	return alloc_kvm_area();
8003 
8004 out:
8005 	for (i = 0; i < VMX_BITMAP_NR; i++)
8006 		free_page((unsigned long)vmx_bitmap[i]);
8007 
8008     return r;
8009 }
8010 
hardware_unsetup(void)8011 static __exit void hardware_unsetup(void)
8012 {
8013 	int i;
8014 
8015 	for (i = 0; i < VMX_BITMAP_NR; i++)
8016 		free_page((unsigned long)vmx_bitmap[i]);
8017 
8018 	free_kvm_area();
8019 }
8020 
8021 /*
8022  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
8023  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
8024  */
handle_pause(struct kvm_vcpu * vcpu)8025 static int handle_pause(struct kvm_vcpu *vcpu)
8026 {
8027 	if (!kvm_pause_in_guest(vcpu->kvm))
8028 		grow_ple_window(vcpu);
8029 
8030 	/*
8031 	 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
8032 	 * VM-execution control is ignored if CPL > 0. OTOH, KVM
8033 	 * never set PAUSE_EXITING and just set PLE if supported,
8034 	 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
8035 	 */
8036 	kvm_vcpu_on_spin(vcpu, true);
8037 	return kvm_skip_emulated_instruction(vcpu);
8038 }
8039 
handle_nop(struct kvm_vcpu * vcpu)8040 static int handle_nop(struct kvm_vcpu *vcpu)
8041 {
8042 	return kvm_skip_emulated_instruction(vcpu);
8043 }
8044 
handle_mwait(struct kvm_vcpu * vcpu)8045 static int handle_mwait(struct kvm_vcpu *vcpu)
8046 {
8047 	printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
8048 	return handle_nop(vcpu);
8049 }
8050 
handle_invalid_op(struct kvm_vcpu * vcpu)8051 static int handle_invalid_op(struct kvm_vcpu *vcpu)
8052 {
8053 	kvm_queue_exception(vcpu, UD_VECTOR);
8054 	return 1;
8055 }
8056 
handle_monitor_trap(struct kvm_vcpu * vcpu)8057 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
8058 {
8059 	return 1;
8060 }
8061 
handle_monitor(struct kvm_vcpu * vcpu)8062 static int handle_monitor(struct kvm_vcpu *vcpu)
8063 {
8064 	printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
8065 	return handle_nop(vcpu);
8066 }
8067 
8068 /*
8069  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
8070  * set the success or error code of an emulated VMX instruction, as specified
8071  * by Vol 2B, VMX Instruction Reference, "Conventions".
8072  */
nested_vmx_succeed(struct kvm_vcpu * vcpu)8073 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
8074 {
8075 	vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
8076 			& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8077 			    X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
8078 }
8079 
nested_vmx_failInvalid(struct kvm_vcpu * vcpu)8080 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
8081 {
8082 	vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8083 			& ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
8084 			    X86_EFLAGS_SF | X86_EFLAGS_OF))
8085 			| X86_EFLAGS_CF);
8086 }
8087 
nested_vmx_failValid(struct kvm_vcpu * vcpu,u32 vm_instruction_error)8088 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
8089 					u32 vm_instruction_error)
8090 {
8091 	if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
8092 		/*
8093 		 * failValid writes the error number to the current VMCS, which
8094 		 * can't be done there isn't a current VMCS.
8095 		 */
8096 		nested_vmx_failInvalid(vcpu);
8097 		return;
8098 	}
8099 	vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8100 			& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8101 			    X86_EFLAGS_SF | X86_EFLAGS_OF))
8102 			| X86_EFLAGS_ZF);
8103 	get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
8104 	/*
8105 	 * We don't need to force a shadow sync because
8106 	 * VM_INSTRUCTION_ERROR is not shadowed
8107 	 */
8108 }
8109 
nested_vmx_abort(struct kvm_vcpu * vcpu,u32 indicator)8110 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
8111 {
8112 	/* TODO: not to reset guest simply here. */
8113 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8114 	pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
8115 }
8116 
vmx_preemption_timer_fn(struct hrtimer * timer)8117 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
8118 {
8119 	struct vcpu_vmx *vmx =
8120 		container_of(timer, struct vcpu_vmx, nested.preemption_timer);
8121 
8122 	vmx->nested.preemption_timer_expired = true;
8123 	kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
8124 	kvm_vcpu_kick(&vmx->vcpu);
8125 
8126 	return HRTIMER_NORESTART;
8127 }
8128 
8129 /*
8130  * Decode the memory-address operand of a vmx instruction, as recorded on an
8131  * exit caused by such an instruction (run by a guest hypervisor).
8132  * On success, returns 0. When the operand is invalid, returns 1 and throws
8133  * #UD or #GP.
8134  */
get_vmx_mem_address(struct kvm_vcpu * vcpu,unsigned long exit_qualification,u32 vmx_instruction_info,bool wr,gva_t * ret)8135 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
8136 				 unsigned long exit_qualification,
8137 				 u32 vmx_instruction_info, bool wr, gva_t *ret)
8138 {
8139 	gva_t off;
8140 	bool exn;
8141 	struct kvm_segment s;
8142 
8143 	/*
8144 	 * According to Vol. 3B, "Information for VM Exits Due to Instruction
8145 	 * Execution", on an exit, vmx_instruction_info holds most of the
8146 	 * addressing components of the operand. Only the displacement part
8147 	 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
8148 	 * For how an actual address is calculated from all these components,
8149 	 * refer to Vol. 1, "Operand Addressing".
8150 	 */
8151 	int  scaling = vmx_instruction_info & 3;
8152 	int  addr_size = (vmx_instruction_info >> 7) & 7;
8153 	bool is_reg = vmx_instruction_info & (1u << 10);
8154 	int  seg_reg = (vmx_instruction_info >> 15) & 7;
8155 	int  index_reg = (vmx_instruction_info >> 18) & 0xf;
8156 	bool index_is_valid = !(vmx_instruction_info & (1u << 22));
8157 	int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
8158 	bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
8159 
8160 	if (is_reg) {
8161 		kvm_queue_exception(vcpu, UD_VECTOR);
8162 		return 1;
8163 	}
8164 
8165 	/* Addr = segment_base + offset */
8166 	/* offset = base + [index * scale] + displacement */
8167 	off = exit_qualification; /* holds the displacement */
8168 	if (base_is_valid)
8169 		off += kvm_register_read(vcpu, base_reg);
8170 	if (index_is_valid)
8171 		off += kvm_register_read(vcpu, index_reg)<<scaling;
8172 	vmx_get_segment(vcpu, &s, seg_reg);
8173 	*ret = s.base + off;
8174 
8175 	if (addr_size == 1) /* 32 bit */
8176 		*ret &= 0xffffffff;
8177 
8178 	/* Checks for #GP/#SS exceptions. */
8179 	exn = false;
8180 	if (is_long_mode(vcpu)) {
8181 		/* Long mode: #GP(0)/#SS(0) if the memory address is in a
8182 		 * non-canonical form. This is the only check on the memory
8183 		 * destination for long mode!
8184 		 */
8185 		exn = is_noncanonical_address(*ret, vcpu);
8186 	} else if (is_protmode(vcpu)) {
8187 		/* Protected mode: apply checks for segment validity in the
8188 		 * following order:
8189 		 * - segment type check (#GP(0) may be thrown)
8190 		 * - usability check (#GP(0)/#SS(0))
8191 		 * - limit check (#GP(0)/#SS(0))
8192 		 */
8193 		if (wr)
8194 			/* #GP(0) if the destination operand is located in a
8195 			 * read-only data segment or any code segment.
8196 			 */
8197 			exn = ((s.type & 0xa) == 0 || (s.type & 8));
8198 		else
8199 			/* #GP(0) if the source operand is located in an
8200 			 * execute-only code segment
8201 			 */
8202 			exn = ((s.type & 0xa) == 8);
8203 		if (exn) {
8204 			kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8205 			return 1;
8206 		}
8207 		/* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
8208 		 */
8209 		exn = (s.unusable != 0);
8210 		/* Protected mode: #GP(0)/#SS(0) if the memory
8211 		 * operand is outside the segment limit.
8212 		 */
8213 		exn = exn || (off + sizeof(u64) > s.limit);
8214 	}
8215 	if (exn) {
8216 		kvm_queue_exception_e(vcpu,
8217 				      seg_reg == VCPU_SREG_SS ?
8218 						SS_VECTOR : GP_VECTOR,
8219 				      0);
8220 		return 1;
8221 	}
8222 
8223 	return 0;
8224 }
8225 
nested_vmx_get_vmptr(struct kvm_vcpu * vcpu,gpa_t * vmpointer)8226 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
8227 {
8228 	gva_t gva;
8229 	struct x86_exception e;
8230 
8231 	if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8232 			vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
8233 		return 1;
8234 
8235 	if (kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e)) {
8236 		kvm_inject_page_fault(vcpu, &e);
8237 		return 1;
8238 	}
8239 
8240 	return 0;
8241 }
8242 
8243 /*
8244  * Allocate a shadow VMCS and associate it with the currently loaded
8245  * VMCS, unless such a shadow VMCS already exists. The newly allocated
8246  * VMCS is also VMCLEARed, so that it is ready for use.
8247  */
alloc_shadow_vmcs(struct kvm_vcpu * vcpu)8248 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
8249 {
8250 	struct vcpu_vmx *vmx = to_vmx(vcpu);
8251 	struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
8252 
8253 	/*
8254 	 * We should allocate a shadow vmcs for vmcs01 only when L1
8255 	 * executes VMXON and free it when L1 executes VMXOFF.
8256 	 * As it is invalid to execute VMXON twice, we shouldn't reach
8257 	 * here when vmcs01 already have an allocated shadow vmcs.
8258 	 */
8259 	WARN_ON(loaded_vmcs == &vmx->vmcs01 && loaded_vmcs->shadow_vmcs);
8260 
8261 	if (!loaded_vmcs->shadow_vmcs) {
8262 		loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
8263 		if (loaded_vmcs->shadow_vmcs)
8264 			vmcs_clear(loaded_vmcs->shadow_vmcs);
8265 	}
8266 	return loaded_vmcs->shadow_vmcs;
8267 }
8268 
enter_vmx_operation(struct kvm_vcpu * vcpu)8269 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
8270 {
8271 	struct vcpu_vmx *vmx = to_vmx(vcpu);
8272 	int r;
8273 
8274 	r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
8275 	if (r < 0)
8276 		goto out_vmcs02;
8277 
8278 	vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
8279 	if (!vmx->nested.cached_vmcs12)
8280 		goto out_cached_vmcs12;
8281 
8282 	vmx->nested.cached_shadow_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
8283 	if (!vmx->nested.cached_shadow_vmcs12)
8284 		goto out_cached_shadow_vmcs12;
8285 
8286 	if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
8287 		goto out_shadow_vmcs;
8288 
8289 	hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
8290 		     HRTIMER_MODE_REL_PINNED);
8291 	vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
8292 
8293 	vmx->nested.vpid02 = allocate_vpid();
8294 
8295 	vmx->nested.vmxon = true;
8296 	return 0;
8297 
8298 out_shadow_vmcs:
8299 	kfree(vmx->nested.cached_shadow_vmcs12);
8300 
8301 out_cached_shadow_vmcs12:
8302 	kfree(vmx->nested.cached_vmcs12);
8303 
8304 out_cached_vmcs12:
8305 	free_loaded_vmcs(&vmx->nested.vmcs02);
8306 
8307 out_vmcs02:
8308 	return -ENOMEM;
8309 }
8310 
8311 /*
8312  * Emulate the VMXON instruction.
8313  * Currently, we just remember that VMX is active, and do not save or even
8314  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
8315  * do not currently need to store anything in that guest-allocated memory
8316  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
8317  * argument is different from the VMXON pointer (which the spec says they do).
8318  */
handle_vmon(struct kvm_vcpu * vcpu)8319 static int handle_vmon(struct kvm_vcpu *vcpu)
8320 {
8321 	int ret;
8322 	gpa_t vmptr;
8323 	struct page *page;
8324 	struct vcpu_vmx *vmx = to_vmx(vcpu);
8325 	const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
8326 		| FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
8327 
8328 	/*
8329 	 * The Intel VMX Instruction Reference lists a bunch of bits that are
8330 	 * prerequisite to running VMXON, most notably cr4.VMXE must be set to
8331 	 * 1 (see vmx_set_cr4() for when we allow the guest to set this).
8332 	 * Otherwise, we should fail with #UD.  But most faulting conditions
8333 	 * have already been checked by hardware, prior to the VM-exit for
8334 	 * VMXON.  We do test guest cr4.VMXE because processor CR4 always has
8335 	 * that bit set to 1 in non-root mode.
8336 	 */
8337 	if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
8338 		kvm_queue_exception(vcpu, UD_VECTOR);
8339 		return 1;
8340 	}
8341 
8342 	/* CPL=0 must be checked manually. */
8343 	if (vmx_get_cpl(vcpu)) {
8344 		kvm_inject_gp(vcpu, 0);
8345 		return 1;
8346 	}
8347 
8348 	if (vmx->nested.vmxon) {
8349 		nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
8350 		return kvm_skip_emulated_instruction(vcpu);
8351 	}
8352 
8353 	if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
8354 			!= VMXON_NEEDED_FEATURES) {
8355 		kvm_inject_gp(vcpu, 0);
8356 		return 1;
8357 	}
8358 
8359 	if (nested_vmx_get_vmptr(vcpu, &vmptr))
8360 		return 1;
8361 
8362 	/*
8363 	 * SDM 3: 24.11.5
8364 	 * The first 4 bytes of VMXON region contain the supported
8365 	 * VMCS revision identifier
8366 	 *
8367 	 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
8368 	 * which replaces physical address width with 32
8369 	 */
8370 	if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8371 		nested_vmx_failInvalid(vcpu);
8372 		return kvm_skip_emulated_instruction(vcpu);
8373 	}
8374 
8375 	page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8376 	if (is_error_page(page)) {
8377 		nested_vmx_failInvalid(vcpu);
8378 		return kvm_skip_emulated_instruction(vcpu);
8379 	}
8380 	if (*(u32 *)kmap(page) != VMCS12_REVISION) {
8381 		kunmap(page);
8382 		kvm_release_page_clean(page);
8383 		nested_vmx_failInvalid(vcpu);
8384 		return kvm_skip_emulated_instruction(vcpu);
8385 	}
8386 	kunmap(page);
8387 	kvm_release_page_clean(page);
8388 
8389 	vmx->nested.vmxon_ptr = vmptr;
8390 	ret = enter_vmx_operation(vcpu);
8391 	if (ret)
8392 		return ret;
8393 
8394 	nested_vmx_succeed(vcpu);
8395 	return kvm_skip_emulated_instruction(vcpu);
8396 }
8397 
8398 /*
8399  * Intel's VMX Instruction Reference specifies a common set of prerequisites
8400  * for running VMX instructions (except VMXON, whose prerequisites are
8401  * slightly different). It also specifies what exception to inject otherwise.
8402  * Note that many of these exceptions have priority over VM exits, so they
8403  * don't have to be checked again here.
8404  */
nested_vmx_check_permission(struct kvm_vcpu * vcpu)8405 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
8406 {
8407 	if (!to_vmx(vcpu)->nested.vmxon) {
8408 		kvm_queue_exception(vcpu, UD_VECTOR);
8409 		return 0;
8410 	}
8411 
8412 	if (vmx_get_cpl(vcpu)) {
8413 		kvm_inject_gp(vcpu, 0);
8414 		return 0;
8415 	}
8416 
8417 	return 1;
8418 }
8419 
vmx_disable_shadow_vmcs(struct vcpu_vmx * vmx)8420 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
8421 {
8422 	vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
8423 	vmcs_write64(VMCS_LINK_POINTER, -1ull);
8424 }
8425 
nested_release_vmcs12(struct vcpu_vmx * vmx)8426 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
8427 {
8428 	if (vmx->nested.current_vmptr == -1ull)
8429 		return;
8430 
8431 	if (enable_shadow_vmcs) {
8432 		/* copy to memory all shadowed fields in case
8433 		   they were modified */
8434 		copy_shadow_to_vmcs12(vmx);
8435 		vmx->nested.sync_shadow_vmcs = false;
8436 		vmx_disable_shadow_vmcs(vmx);
8437 	}
8438 	vmx->nested.posted_intr_nv = -1;
8439 
8440 	/* Flush VMCS12 to guest memory */
8441 	kvm_vcpu_write_guest_page(&vmx->vcpu,
8442 				  vmx->nested.current_vmptr >> PAGE_SHIFT,
8443 				  vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
8444 
8445 	vmx->nested.current_vmptr = -1ull;
8446 }
8447 
8448 /*
8449  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
8450  * just stops using VMX.
8451  */
free_nested(struct vcpu_vmx * vmx)8452 static void free_nested(struct vcpu_vmx *vmx)
8453 {
8454 	if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
8455 		return;
8456 
8457 	vmx->nested.vmxon = false;
8458 	vmx->nested.smm.vmxon = false;
8459 	free_vpid(vmx->nested.vpid02);
8460 	vmx->nested.posted_intr_nv = -1;
8461 	vmx->nested.current_vmptr = -1ull;
8462 	if (enable_shadow_vmcs) {
8463 		vmx_disable_shadow_vmcs(vmx);
8464 		vmcs_clear(vmx->vmcs01.shadow_vmcs);
8465 		free_vmcs(vmx->vmcs01.shadow_vmcs);
8466 		vmx->vmcs01.shadow_vmcs = NULL;
8467 	}
8468 	kfree(vmx->nested.cached_vmcs12);
8469 	kfree(vmx->nested.cached_shadow_vmcs12);
8470 	/* Unpin physical memory we referred to in the vmcs02 */
8471 	if (vmx->nested.apic_access_page) {
8472 		kvm_release_page_dirty(vmx->nested.apic_access_page);
8473 		vmx->nested.apic_access_page = NULL;
8474 	}
8475 	if (vmx->nested.virtual_apic_page) {
8476 		kvm_release_page_dirty(vmx->nested.virtual_apic_page);
8477 		vmx->nested.virtual_apic_page = NULL;
8478 	}
8479 	if (vmx->nested.pi_desc_page) {
8480 		kunmap(vmx->nested.pi_desc_page);
8481 		kvm_release_page_dirty(vmx->nested.pi_desc_page);
8482 		vmx->nested.pi_desc_page = NULL;
8483 		vmx->nested.pi_desc = NULL;
8484 	}
8485 
8486 	free_loaded_vmcs(&vmx->nested.vmcs02);
8487 }
8488 
8489 /* Emulate the VMXOFF instruction */
handle_vmoff(struct kvm_vcpu * vcpu)8490 static int handle_vmoff(struct kvm_vcpu *vcpu)
8491 {
8492 	if (!nested_vmx_check_permission(vcpu))
8493 		return 1;
8494 	free_nested(to_vmx(vcpu));
8495 	nested_vmx_succeed(vcpu);
8496 	return kvm_skip_emulated_instruction(vcpu);
8497 }
8498 
8499 /* Emulate the VMCLEAR instruction */
handle_vmclear(struct kvm_vcpu * vcpu)8500 static int handle_vmclear(struct kvm_vcpu *vcpu)
8501 {
8502 	struct vcpu_vmx *vmx = to_vmx(vcpu);
8503 	u32 zero = 0;
8504 	gpa_t vmptr;
8505 
8506 	if (!nested_vmx_check_permission(vcpu))
8507 		return 1;
8508 
8509 	if (nested_vmx_get_vmptr(vcpu, &vmptr))
8510 		return 1;
8511 
8512 	if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8513 		nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
8514 		return kvm_skip_emulated_instruction(vcpu);
8515 	}
8516 
8517 	if (vmptr == vmx->nested.vmxon_ptr) {
8518 		nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
8519 		return kvm_skip_emulated_instruction(vcpu);
8520 	}
8521 
8522 	if (vmptr == vmx->nested.current_vmptr)
8523 		nested_release_vmcs12(vmx);
8524 
8525 	kvm_vcpu_write_guest(vcpu,
8526 			vmptr + offsetof(struct vmcs12, launch_state),
8527 			&zero, sizeof(zero));
8528 
8529 	nested_vmx_succeed(vcpu);
8530 	return kvm_skip_emulated_instruction(vcpu);
8531 }
8532 
8533 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
8534 
8535 /* Emulate the VMLAUNCH instruction */
handle_vmlaunch(struct kvm_vcpu * vcpu)8536 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
8537 {
8538 	return nested_vmx_run(vcpu, true);
8539 }
8540 
8541 /* Emulate the VMRESUME instruction */
handle_vmresume(struct kvm_vcpu * vcpu)8542 static int handle_vmresume(struct kvm_vcpu *vcpu)
8543 {
8544 
8545 	return nested_vmx_run(vcpu, false);
8546 }
8547 
8548 /*
8549  * Read a vmcs12 field. Since these can have varying lengths and we return
8550  * one type, we chose the biggest type (u64) and zero-extend the return value
8551  * to that size. Note that the caller, handle_vmread, might need to use only
8552  * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
8553  * 64-bit fields are to be returned).
8554  */
vmcs12_read_any(struct vmcs12 * vmcs12,unsigned long field,u64 * ret)8555 static inline int vmcs12_read_any(struct vmcs12 *vmcs12,
8556 				  unsigned long field, u64 *ret)
8557 {
8558 	short offset = vmcs_field_to_offset(field);
8559 	char *p;
8560 
8561 	if (offset < 0)
8562 		return offset;
8563 
8564 	p = (char *)vmcs12 + offset;
8565 
8566 	switch (vmcs_field_width(field)) {
8567 	case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8568 		*ret = *((natural_width *)p);
8569 		return 0;
8570 	case VMCS_FIELD_WIDTH_U16:
8571 		*ret = *((u16 *)p);
8572 		return 0;
8573 	case VMCS_FIELD_WIDTH_U32:
8574 		*ret = *((u32 *)p);
8575 		return 0;
8576 	case VMCS_FIELD_WIDTH_U64:
8577 		*ret = *((u64 *)p);
8578 		return 0;
8579 	default:
8580 		WARN_ON(1);
8581 		return -ENOENT;
8582 	}
8583 }
8584 
8585 
vmcs12_write_any(struct vmcs12 * vmcs12,unsigned long field,u64 field_value)8586 static inline int vmcs12_write_any(struct vmcs12 *vmcs12,
8587 				   unsigned long field, u64 field_value){
8588 	short offset = vmcs_field_to_offset(field);
8589 	char *p = (char *)vmcs12 + offset;
8590 	if (offset < 0)
8591 		return offset;
8592 
8593 	switch (vmcs_field_width(field)) {
8594 	case VMCS_FIELD_WIDTH_U16:
8595 		*(u16 *)p = field_value;
8596 		return 0;
8597 	case VMCS_FIELD_WIDTH_U32:
8598 		*(u32 *)p = field_value;
8599 		return 0;
8600 	case VMCS_FIELD_WIDTH_U64:
8601 		*(u64 *)p = field_value;
8602 		return 0;
8603 	case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8604 		*(natural_width *)p = field_value;
8605 		return 0;
8606 	default:
8607 		WARN_ON(1);
8608 		return -ENOENT;
8609 	}
8610 
8611 }
8612 
8613 /*
8614  * Copy the writable VMCS shadow fields back to the VMCS12, in case
8615  * they have been modified by the L1 guest. Note that the "read-only"
8616  * VM-exit information fields are actually writable if the vCPU is
8617  * configured to support "VMWRITE to any supported field in the VMCS."
8618  */
copy_shadow_to_vmcs12(struct vcpu_vmx * vmx)8619 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
8620 {
8621 	const u16 *fields[] = {
8622 		shadow_read_write_fields,
8623 		shadow_read_only_fields
8624 	};
8625 	const int max_fields[] = {
8626 		max_shadow_read_write_fields,
8627 		max_shadow_read_only_fields
8628 	};
8629 	int i, q;
8630 	unsigned long field;
8631 	u64 field_value;
8632 	struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
8633 
8634 	preempt_disable();
8635 
8636 	vmcs_load(shadow_vmcs);
8637 
8638 	for (q = 0; q < ARRAY_SIZE(fields); q++) {
8639 		for (i = 0; i < max_fields[q]; i++) {
8640 			field = fields[q][i];
8641 			field_value = __vmcs_readl(field);
8642 			vmcs12_write_any(get_vmcs12(&vmx->vcpu), field, field_value);
8643 		}
8644 		/*
8645 		 * Skip the VM-exit information fields if they are read-only.
8646 		 */
8647 		if (!nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
8648 			break;
8649 	}
8650 
8651 	vmcs_clear(shadow_vmcs);
8652 	vmcs_load(vmx->loaded_vmcs->vmcs);
8653 
8654 	preempt_enable();
8655 }
8656 
copy_vmcs12_to_shadow(struct vcpu_vmx * vmx)8657 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
8658 {
8659 	const u16 *fields[] = {
8660 		shadow_read_write_fields,
8661 		shadow_read_only_fields
8662 	};
8663 	const int max_fields[] = {
8664 		max_shadow_read_write_fields,
8665 		max_shadow_read_only_fields
8666 	};
8667 	int i, q;
8668 	unsigned long field;
8669 	u64 field_value = 0;
8670 	struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
8671 
8672 	vmcs_load(shadow_vmcs);
8673 
8674 	for (q = 0; q < ARRAY_SIZE(fields); q++) {
8675 		for (i = 0; i < max_fields[q]; i++) {
8676 			field = fields[q][i];
8677 			vmcs12_read_any(get_vmcs12(&vmx->vcpu), field, &field_value);
8678 			__vmcs_writel(field, field_value);
8679 		}
8680 	}
8681 
8682 	vmcs_clear(shadow_vmcs);
8683 	vmcs_load(vmx->loaded_vmcs->vmcs);
8684 }
8685 
8686 /*
8687  * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
8688  * used before) all generate the same failure when it is missing.
8689  */
nested_vmx_check_vmcs12(struct kvm_vcpu * vcpu)8690 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
8691 {
8692 	struct vcpu_vmx *vmx = to_vmx(vcpu);
8693 	if (vmx->nested.current_vmptr == -1ull) {
8694 		nested_vmx_failInvalid(vcpu);
8695 		return 0;
8696 	}
8697 	return 1;
8698 }
8699 
handle_vmread(struct kvm_vcpu * vcpu)8700 static int handle_vmread(struct kvm_vcpu *vcpu)
8701 {
8702 	unsigned long field;
8703 	u64 field_value;
8704 	unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8705 	u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8706 	gva_t gva = 0;
8707 	struct vmcs12 *vmcs12;
8708 
8709 	if (!nested_vmx_check_permission(vcpu))
8710 		return 1;
8711 
8712 	if (!nested_vmx_check_vmcs12(vcpu))
8713 		return kvm_skip_emulated_instruction(vcpu);
8714 
8715 	if (!is_guest_mode(vcpu))
8716 		vmcs12 = get_vmcs12(vcpu);
8717 	else {
8718 		/*
8719 		 * When vmcs->vmcs_link_pointer is -1ull, any VMREAD
8720 		 * to shadowed-field sets the ALU flags for VMfailInvalid.
8721 		 */
8722 		if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull) {
8723 			nested_vmx_failInvalid(vcpu);
8724 			return kvm_skip_emulated_instruction(vcpu);
8725 		}
8726 		vmcs12 = get_shadow_vmcs12(vcpu);
8727 	}
8728 
8729 	/* Decode instruction info and find the field to read */
8730 	field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8731 	/* Read the field, zero-extended to a u64 field_value */
8732 	if (vmcs12_read_any(vmcs12, field, &field_value) < 0) {
8733 		nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8734 		return kvm_skip_emulated_instruction(vcpu);
8735 	}
8736 	/*
8737 	 * Now copy part of this value to register or memory, as requested.
8738 	 * Note that the number of bits actually copied is 32 or 64 depending
8739 	 * on the guest's mode (32 or 64 bit), not on the given field's length.
8740 	 */
8741 	if (vmx_instruction_info & (1u << 10)) {
8742 		kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
8743 			field_value);
8744 	} else {
8745 		if (get_vmx_mem_address(vcpu, exit_qualification,
8746 				vmx_instruction_info, true, &gva))
8747 			return 1;
8748 		/* _system ok, nested_vmx_check_permission has verified cpl=0 */
8749 		kvm_write_guest_virt_system(vcpu, gva, &field_value,
8750 					    (is_long_mode(vcpu) ? 8 : 4), NULL);
8751 	}
8752 
8753 	nested_vmx_succeed(vcpu);
8754 	return kvm_skip_emulated_instruction(vcpu);
8755 }
8756 
8757 
handle_vmwrite(struct kvm_vcpu * vcpu)8758 static int handle_vmwrite(struct kvm_vcpu *vcpu)
8759 {
8760 	unsigned long field;
8761 	gva_t gva;
8762 	struct vcpu_vmx *vmx = to_vmx(vcpu);
8763 	unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8764 	u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8765 
8766 	/* The value to write might be 32 or 64 bits, depending on L1's long
8767 	 * mode, and eventually we need to write that into a field of several
8768 	 * possible lengths. The code below first zero-extends the value to 64
8769 	 * bit (field_value), and then copies only the appropriate number of
8770 	 * bits into the vmcs12 field.
8771 	 */
8772 	u64 field_value = 0;
8773 	struct x86_exception e;
8774 	struct vmcs12 *vmcs12;
8775 
8776 	if (!nested_vmx_check_permission(vcpu))
8777 		return 1;
8778 
8779 	if (!nested_vmx_check_vmcs12(vcpu))
8780 		return kvm_skip_emulated_instruction(vcpu);
8781 
8782 	if (vmx_instruction_info & (1u << 10))
8783 		field_value = kvm_register_readl(vcpu,
8784 			(((vmx_instruction_info) >> 3) & 0xf));
8785 	else {
8786 		if (get_vmx_mem_address(vcpu, exit_qualification,
8787 				vmx_instruction_info, false, &gva))
8788 			return 1;
8789 		if (kvm_read_guest_virt(vcpu, gva, &field_value,
8790 					(is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
8791 			kvm_inject_page_fault(vcpu, &e);
8792 			return 1;
8793 		}
8794 	}
8795 
8796 
8797 	field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8798 	/*
8799 	 * If the vCPU supports "VMWRITE to any supported field in the
8800 	 * VMCS," then the "read-only" fields are actually read/write.
8801 	 */
8802 	if (vmcs_field_readonly(field) &&
8803 	    !nested_cpu_has_vmwrite_any_field(vcpu)) {
8804 		nested_vmx_failValid(vcpu,
8805 			VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
8806 		return kvm_skip_emulated_instruction(vcpu);
8807 	}
8808 
8809 	if (!is_guest_mode(vcpu))
8810 		vmcs12 = get_vmcs12(vcpu);
8811 	else {
8812 		/*
8813 		 * When vmcs->vmcs_link_pointer is -1ull, any VMWRITE
8814 		 * to shadowed-field sets the ALU flags for VMfailInvalid.
8815 		 */
8816 		if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull) {
8817 			nested_vmx_failInvalid(vcpu);
8818 			return kvm_skip_emulated_instruction(vcpu);
8819 		}
8820 		vmcs12 = get_shadow_vmcs12(vcpu);
8821 
8822 	}
8823 
8824 	if (vmcs12_write_any(vmcs12, field, field_value) < 0) {
8825 		nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8826 		return kvm_skip_emulated_instruction(vcpu);
8827 	}
8828 
8829 	/*
8830 	 * Do not track vmcs12 dirty-state if in guest-mode
8831 	 * as we actually dirty shadow vmcs12 instead of vmcs12.
8832 	 */
8833 	if (!is_guest_mode(vcpu)) {
8834 		switch (field) {
8835 #define SHADOW_FIELD_RW(x) case x:
8836 #include "vmx_shadow_fields.h"
8837 			/*
8838 			 * The fields that can be updated by L1 without a vmexit are
8839 			 * always updated in the vmcs02, the others go down the slow
8840 			 * path of prepare_vmcs02.
8841 			 */
8842 			break;
8843 		default:
8844 			vmx->nested.dirty_vmcs12 = true;
8845 			break;
8846 		}
8847 	}
8848 
8849 	nested_vmx_succeed(vcpu);
8850 	return kvm_skip_emulated_instruction(vcpu);
8851 }
8852 
set_current_vmptr(struct vcpu_vmx * vmx,gpa_t vmptr)8853 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
8854 {
8855 	vmx->nested.current_vmptr = vmptr;
8856 	if (enable_shadow_vmcs) {
8857 		vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
8858 			      SECONDARY_EXEC_SHADOW_VMCS);
8859 		vmcs_write64(VMCS_LINK_POINTER,
8860 			     __pa(vmx->vmcs01.shadow_vmcs));
8861 		vmx->nested.sync_shadow_vmcs = true;
8862 	}
8863 	vmx->nested.dirty_vmcs12 = true;
8864 }
8865 
8866 /* Emulate the VMPTRLD instruction */
handle_vmptrld(struct kvm_vcpu * vcpu)8867 static int handle_vmptrld(struct kvm_vcpu *vcpu)
8868 {
8869 	struct vcpu_vmx *vmx = to_vmx(vcpu);
8870 	gpa_t vmptr;
8871 
8872 	if (!nested_vmx_check_permission(vcpu))
8873 		return 1;
8874 
8875 	if (nested_vmx_get_vmptr(vcpu, &vmptr))
8876 		return 1;
8877 
8878 	if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8879 		nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
8880 		return kvm_skip_emulated_instruction(vcpu);
8881 	}
8882 
8883 	if (vmptr == vmx->nested.vmxon_ptr) {
8884 		nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
8885 		return kvm_skip_emulated_instruction(vcpu);
8886 	}
8887 
8888 	if (vmx->nested.current_vmptr != vmptr) {
8889 		struct vmcs12 *new_vmcs12;
8890 		struct page *page;
8891 		page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8892 		if (is_error_page(page)) {
8893 			nested_vmx_failInvalid(vcpu);
8894 			return kvm_skip_emulated_instruction(vcpu);
8895 		}
8896 		new_vmcs12 = kmap(page);
8897 		if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
8898 		    (new_vmcs12->hdr.shadow_vmcs &&
8899 		     !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
8900 			kunmap(page);
8901 			kvm_release_page_clean(page);
8902 			nested_vmx_failValid(vcpu,
8903 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
8904 			return kvm_skip_emulated_instruction(vcpu);
8905 		}
8906 
8907 		nested_release_vmcs12(vmx);
8908 		/*
8909 		 * Load VMCS12 from guest memory since it is not already
8910 		 * cached.
8911 		 */
8912 		memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
8913 		kunmap(page);
8914 		kvm_release_page_clean(page);
8915 
8916 		set_current_vmptr(vmx, vmptr);
8917 	}
8918 
8919 	nested_vmx_succeed(vcpu);
8920 	return kvm_skip_emulated_instruction(vcpu);
8921 }
8922 
8923 /* Emulate the VMPTRST instruction */
handle_vmptrst(struct kvm_vcpu * vcpu)8924 static int handle_vmptrst(struct kvm_vcpu *vcpu)
8925 {
8926 	unsigned long exit_qual = vmcs_readl(EXIT_QUALIFICATION);
8927 	u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8928 	gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
8929 	struct x86_exception e;
8930 	gva_t gva;
8931 
8932 	if (!nested_vmx_check_permission(vcpu))
8933 		return 1;
8934 
8935 	if (get_vmx_mem_address(vcpu, exit_qual, instr_info, true, &gva))
8936 		return 1;
8937 	/* *_system ok, nested_vmx_check_permission has verified cpl=0 */
8938 	if (kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
8939 					sizeof(gpa_t), &e)) {
8940 		kvm_inject_page_fault(vcpu, &e);
8941 		return 1;
8942 	}
8943 	nested_vmx_succeed(vcpu);
8944 	return kvm_skip_emulated_instruction(vcpu);
8945 }
8946 
8947 /* Emulate the INVEPT instruction */
handle_invept(struct kvm_vcpu * vcpu)8948 static int handle_invept(struct kvm_vcpu *vcpu)
8949 {
8950 	struct vcpu_vmx *vmx = to_vmx(vcpu);
8951 	u32 vmx_instruction_info, types;
8952 	unsigned long type;
8953 	gva_t gva;
8954 	struct x86_exception e;
8955 	struct {
8956 		u64 eptp, gpa;
8957 	} operand;
8958 
8959 	if (!(vmx->nested.msrs.secondary_ctls_high &
8960 	      SECONDARY_EXEC_ENABLE_EPT) ||
8961 	    !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
8962 		kvm_queue_exception(vcpu, UD_VECTOR);
8963 		return 1;
8964 	}
8965 
8966 	if (!nested_vmx_check_permission(vcpu))
8967 		return 1;
8968 
8969 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8970 	type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
8971 
8972 	types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
8973 
8974 	if (type >= 32 || !(types & (1 << type))) {
8975 		nested_vmx_failValid(vcpu,
8976 				VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8977 		return kvm_skip_emulated_instruction(vcpu);
8978 	}
8979 
8980 	/* According to the Intel VMX instruction reference, the memory
8981 	 * operand is read even if it isn't needed (e.g., for type==global)
8982 	 */
8983 	if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8984 			vmx_instruction_info, false, &gva))
8985 		return 1;
8986 	if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
8987 		kvm_inject_page_fault(vcpu, &e);
8988 		return 1;
8989 	}
8990 
8991 	switch (type) {
8992 	case VMX_EPT_EXTENT_GLOBAL:
8993 	/*
8994 	 * TODO: track mappings and invalidate
8995 	 * single context requests appropriately
8996 	 */
8997 	case VMX_EPT_EXTENT_CONTEXT:
8998 		kvm_mmu_sync_roots(vcpu);
8999 		kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9000 		nested_vmx_succeed(vcpu);
9001 		break;
9002 	default:
9003 		BUG_ON(1);
9004 		break;
9005 	}
9006 
9007 	return kvm_skip_emulated_instruction(vcpu);
9008 }
9009 
handle_invvpid(struct kvm_vcpu * vcpu)9010 static int handle_invvpid(struct kvm_vcpu *vcpu)
9011 {
9012 	struct vcpu_vmx *vmx = to_vmx(vcpu);
9013 	u32 vmx_instruction_info;
9014 	unsigned long type, types;
9015 	gva_t gva;
9016 	struct x86_exception e;
9017 	struct {
9018 		u64 vpid;
9019 		u64 gla;
9020 	} operand;
9021 
9022 	if (!(vmx->nested.msrs.secondary_ctls_high &
9023 	      SECONDARY_EXEC_ENABLE_VPID) ||
9024 			!(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
9025 		kvm_queue_exception(vcpu, UD_VECTOR);
9026 		return 1;
9027 	}
9028 
9029 	if (!nested_vmx_check_permission(vcpu))
9030 		return 1;
9031 
9032 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9033 	type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9034 
9035 	types = (vmx->nested.msrs.vpid_caps &
9036 			VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
9037 
9038 	if (type >= 32 || !(types & (1 << type))) {
9039 		nested_vmx_failValid(vcpu,
9040 			VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9041 		return kvm_skip_emulated_instruction(vcpu);
9042 	}
9043 
9044 	/* according to the intel vmx instruction reference, the memory
9045 	 * operand is read even if it isn't needed (e.g., for type==global)
9046 	 */
9047 	if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9048 			vmx_instruction_info, false, &gva))
9049 		return 1;
9050 	if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9051 		kvm_inject_page_fault(vcpu, &e);
9052 		return 1;
9053 	}
9054 	if (operand.vpid >> 16) {
9055 		nested_vmx_failValid(vcpu,
9056 			VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9057 		return kvm_skip_emulated_instruction(vcpu);
9058 	}
9059 
9060 	switch (type) {
9061 	case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
9062 		if (!operand.vpid ||
9063 		    is_noncanonical_address(operand.gla, vcpu)) {
9064 			nested_vmx_failValid(vcpu,
9065 				VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9066 			return kvm_skip_emulated_instruction(vcpu);
9067 		}
9068 		if (cpu_has_vmx_invvpid_individual_addr() &&
9069 		    vmx->nested.vpid02) {
9070 			__invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR,
9071 				vmx->nested.vpid02, operand.gla);
9072 		} else
9073 			__vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
9074 		break;
9075 	case VMX_VPID_EXTENT_SINGLE_CONTEXT:
9076 	case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
9077 		if (!operand.vpid) {
9078 			nested_vmx_failValid(vcpu,
9079 				VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9080 			return kvm_skip_emulated_instruction(vcpu);
9081 		}
9082 		__vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
9083 		break;
9084 	case VMX_VPID_EXTENT_ALL_CONTEXT:
9085 		__vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
9086 		break;
9087 	default:
9088 		WARN_ON_ONCE(1);
9089 		return kvm_skip_emulated_instruction(vcpu);
9090 	}
9091 
9092 	nested_vmx_succeed(vcpu);
9093 
9094 	return kvm_skip_emulated_instruction(vcpu);
9095 }
9096 
handle_invpcid(struct kvm_vcpu * vcpu)9097 static int handle_invpcid(struct kvm_vcpu *vcpu)
9098 {
9099 	u32 vmx_instruction_info;
9100 	unsigned long type;
9101 	bool pcid_enabled;
9102 	gva_t gva;
9103 	struct x86_exception e;
9104 	unsigned i;
9105 	unsigned long roots_to_free = 0;
9106 	struct {
9107 		u64 pcid;
9108 		u64 gla;
9109 	} operand;
9110 
9111 	if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
9112 		kvm_queue_exception(vcpu, UD_VECTOR);
9113 		return 1;
9114 	}
9115 
9116 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9117 	type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9118 
9119 	if (type > 3) {
9120 		kvm_inject_gp(vcpu, 0);
9121 		return 1;
9122 	}
9123 
9124 	/* According to the Intel instruction reference, the memory operand
9125 	 * is read even if it isn't needed (e.g., for type==all)
9126 	 */
9127 	if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9128 				vmx_instruction_info, false, &gva))
9129 		return 1;
9130 
9131 	if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9132 		kvm_inject_page_fault(vcpu, &e);
9133 		return 1;
9134 	}
9135 
9136 	if (operand.pcid >> 12 != 0) {
9137 		kvm_inject_gp(vcpu, 0);
9138 		return 1;
9139 	}
9140 
9141 	pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
9142 
9143 	switch (type) {
9144 	case INVPCID_TYPE_INDIV_ADDR:
9145 		if ((!pcid_enabled && (operand.pcid != 0)) ||
9146 		    is_noncanonical_address(operand.gla, vcpu)) {
9147 			kvm_inject_gp(vcpu, 0);
9148 			return 1;
9149 		}
9150 		kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
9151 		return kvm_skip_emulated_instruction(vcpu);
9152 
9153 	case INVPCID_TYPE_SINGLE_CTXT:
9154 		if (!pcid_enabled && (operand.pcid != 0)) {
9155 			kvm_inject_gp(vcpu, 0);
9156 			return 1;
9157 		}
9158 
9159 		if (kvm_get_active_pcid(vcpu) == operand.pcid) {
9160 			kvm_mmu_sync_roots(vcpu);
9161 			kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9162 		}
9163 
9164 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
9165 			if (kvm_get_pcid(vcpu, vcpu->arch.mmu.prev_roots[i].cr3)
9166 			    == operand.pcid)
9167 				roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
9168 
9169 		kvm_mmu_free_roots(vcpu, roots_to_free);
9170 		/*
9171 		 * If neither the current cr3 nor any of the prev_roots use the
9172 		 * given PCID, then nothing needs to be done here because a
9173 		 * resync will happen anyway before switching to any other CR3.
9174 		 */
9175 
9176 		return kvm_skip_emulated_instruction(vcpu);
9177 
9178 	case INVPCID_TYPE_ALL_NON_GLOBAL:
9179 		/*
9180 		 * Currently, KVM doesn't mark global entries in the shadow
9181 		 * page tables, so a non-global flush just degenerates to a
9182 		 * global flush. If needed, we could optimize this later by
9183 		 * keeping track of global entries in shadow page tables.
9184 		 */
9185 
9186 		/* fall-through */
9187 	case INVPCID_TYPE_ALL_INCL_GLOBAL:
9188 		kvm_mmu_unload(vcpu);
9189 		return kvm_skip_emulated_instruction(vcpu);
9190 
9191 	default:
9192 		BUG(); /* We have already checked above that type <= 3 */
9193 	}
9194 }
9195 
handle_pml_full(struct kvm_vcpu * vcpu)9196 static int handle_pml_full(struct kvm_vcpu *vcpu)
9197 {
9198 	unsigned long exit_qualification;
9199 
9200 	trace_kvm_pml_full(vcpu->vcpu_id);
9201 
9202 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9203 
9204 	/*
9205 	 * PML buffer FULL happened while executing iret from NMI,
9206 	 * "blocked by NMI" bit has to be set before next VM entry.
9207 	 */
9208 	if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
9209 			enable_vnmi &&
9210 			(exit_qualification & INTR_INFO_UNBLOCK_NMI))
9211 		vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9212 				GUEST_INTR_STATE_NMI);
9213 
9214 	/*
9215 	 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
9216 	 * here.., and there's no userspace involvement needed for PML.
9217 	 */
9218 	return 1;
9219 }
9220 
handle_preemption_timer(struct kvm_vcpu * vcpu)9221 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
9222 {
9223 	if (!to_vmx(vcpu)->req_immediate_exit)
9224 		kvm_lapic_expired_hv_timer(vcpu);
9225 	return 1;
9226 }
9227 
valid_ept_address(struct kvm_vcpu * vcpu,u64 address)9228 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
9229 {
9230 	struct vcpu_vmx *vmx = to_vmx(vcpu);
9231 	int maxphyaddr = cpuid_maxphyaddr(vcpu);
9232 
9233 	/* Check for memory type validity */
9234 	switch (address & VMX_EPTP_MT_MASK) {
9235 	case VMX_EPTP_MT_UC:
9236 		if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT))
9237 			return false;
9238 		break;
9239 	case VMX_EPTP_MT_WB:
9240 		if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT))
9241 			return false;
9242 		break;
9243 	default:
9244 		return false;
9245 	}
9246 
9247 	/* only 4 levels page-walk length are valid */
9248 	if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
9249 		return false;
9250 
9251 	/* Reserved bits should not be set */
9252 	if (address >> maxphyaddr || ((address >> 7) & 0x1f))
9253 		return false;
9254 
9255 	/* AD, if set, should be supported */
9256 	if (address & VMX_EPTP_AD_ENABLE_BIT) {
9257 		if (!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT))
9258 			return false;
9259 	}
9260 
9261 	return true;
9262 }
9263 
nested_vmx_eptp_switching(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)9264 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
9265 				     struct vmcs12 *vmcs12)
9266 {
9267 	u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
9268 	u64 address;
9269 	bool accessed_dirty;
9270 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
9271 
9272 	if (!nested_cpu_has_eptp_switching(vmcs12) ||
9273 	    !nested_cpu_has_ept(vmcs12))
9274 		return 1;
9275 
9276 	if (index >= VMFUNC_EPTP_ENTRIES)
9277 		return 1;
9278 
9279 
9280 	if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
9281 				     &address, index * 8, 8))
9282 		return 1;
9283 
9284 	accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
9285 
9286 	/*
9287 	 * If the (L2) guest does a vmfunc to the currently
9288 	 * active ept pointer, we don't have to do anything else
9289 	 */
9290 	if (vmcs12->ept_pointer != address) {
9291 		if (!valid_ept_address(vcpu, address))
9292 			return 1;
9293 
9294 		kvm_mmu_unload(vcpu);
9295 		mmu->ept_ad = accessed_dirty;
9296 		mmu->base_role.ad_disabled = !accessed_dirty;
9297 		vmcs12->ept_pointer = address;
9298 		/*
9299 		 * TODO: Check what's the correct approach in case
9300 		 * mmu reload fails. Currently, we just let the next
9301 		 * reload potentially fail
9302 		 */
9303 		kvm_mmu_reload(vcpu);
9304 	}
9305 
9306 	return 0;
9307 }
9308 
handle_vmfunc(struct kvm_vcpu * vcpu)9309 static int handle_vmfunc(struct kvm_vcpu *vcpu)
9310 {
9311 	struct vcpu_vmx *vmx = to_vmx(vcpu);
9312 	struct vmcs12 *vmcs12;
9313 	u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
9314 
9315 	/*
9316 	 * VMFUNC is only supported for nested guests, but we always enable the
9317 	 * secondary control for simplicity; for non-nested mode, fake that we
9318 	 * didn't by injecting #UD.
9319 	 */
9320 	if (!is_guest_mode(vcpu)) {
9321 		kvm_queue_exception(vcpu, UD_VECTOR);
9322 		return 1;
9323 	}
9324 
9325 	vmcs12 = get_vmcs12(vcpu);
9326 	if ((vmcs12->vm_function_control & (1 << function)) == 0)
9327 		goto fail;
9328 
9329 	switch (function) {
9330 	case 0:
9331 		if (nested_vmx_eptp_switching(vcpu, vmcs12))
9332 			goto fail;
9333 		break;
9334 	default:
9335 		goto fail;
9336 	}
9337 	return kvm_skip_emulated_instruction(vcpu);
9338 
9339 fail:
9340 	nested_vmx_vmexit(vcpu, vmx->exit_reason,
9341 			  vmcs_read32(VM_EXIT_INTR_INFO),
9342 			  vmcs_readl(EXIT_QUALIFICATION));
9343 	return 1;
9344 }
9345 
handle_encls(struct kvm_vcpu * vcpu)9346 static int handle_encls(struct kvm_vcpu *vcpu)
9347 {
9348 	/*
9349 	 * SGX virtualization is not yet supported.  There is no software
9350 	 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
9351 	 * to prevent the guest from executing ENCLS.
9352 	 */
9353 	kvm_queue_exception(vcpu, UD_VECTOR);
9354 	return 1;
9355 }
9356 
9357 /*
9358  * The exit handlers return 1 if the exit was handled fully and guest execution
9359  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
9360  * to be done to userspace and return 0.
9361  */
9362 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
9363 	[EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
9364 	[EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
9365 	[EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
9366 	[EXIT_REASON_NMI_WINDOW]	      = handle_nmi_window,
9367 	[EXIT_REASON_IO_INSTRUCTION]          = handle_io,
9368 	[EXIT_REASON_CR_ACCESS]               = handle_cr,
9369 	[EXIT_REASON_DR_ACCESS]               = handle_dr,
9370 	[EXIT_REASON_CPUID]                   = handle_cpuid,
9371 	[EXIT_REASON_MSR_READ]                = handle_rdmsr,
9372 	[EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
9373 	[EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
9374 	[EXIT_REASON_HLT]                     = handle_halt,
9375 	[EXIT_REASON_INVD]		      = handle_invd,
9376 	[EXIT_REASON_INVLPG]		      = handle_invlpg,
9377 	[EXIT_REASON_RDPMC]                   = handle_rdpmc,
9378 	[EXIT_REASON_VMCALL]                  = handle_vmcall,
9379 	[EXIT_REASON_VMCLEAR]	              = handle_vmclear,
9380 	[EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
9381 	[EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
9382 	[EXIT_REASON_VMPTRST]                 = handle_vmptrst,
9383 	[EXIT_REASON_VMREAD]                  = handle_vmread,
9384 	[EXIT_REASON_VMRESUME]                = handle_vmresume,
9385 	[EXIT_REASON_VMWRITE]                 = handle_vmwrite,
9386 	[EXIT_REASON_VMOFF]                   = handle_vmoff,
9387 	[EXIT_REASON_VMON]                    = handle_vmon,
9388 	[EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
9389 	[EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
9390 	[EXIT_REASON_APIC_WRITE]              = handle_apic_write,
9391 	[EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
9392 	[EXIT_REASON_WBINVD]                  = handle_wbinvd,
9393 	[EXIT_REASON_XSETBV]                  = handle_xsetbv,
9394 	[EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
9395 	[EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
9396 	[EXIT_REASON_GDTR_IDTR]		      = handle_desc,
9397 	[EXIT_REASON_LDTR_TR]		      = handle_desc,
9398 	[EXIT_REASON_EPT_VIOLATION]	      = handle_ept_violation,
9399 	[EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
9400 	[EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
9401 	[EXIT_REASON_MWAIT_INSTRUCTION]	      = handle_mwait,
9402 	[EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
9403 	[EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
9404 	[EXIT_REASON_INVEPT]                  = handle_invept,
9405 	[EXIT_REASON_INVVPID]                 = handle_invvpid,
9406 	[EXIT_REASON_RDRAND]                  = handle_invalid_op,
9407 	[EXIT_REASON_RDSEED]                  = handle_invalid_op,
9408 	[EXIT_REASON_XSAVES]                  = handle_xsaves,
9409 	[EXIT_REASON_XRSTORS]                 = handle_xrstors,
9410 	[EXIT_REASON_PML_FULL]		      = handle_pml_full,
9411 	[EXIT_REASON_INVPCID]                 = handle_invpcid,
9412 	[EXIT_REASON_VMFUNC]                  = handle_vmfunc,
9413 	[EXIT_REASON_PREEMPTION_TIMER]	      = handle_preemption_timer,
9414 	[EXIT_REASON_ENCLS]		      = handle_encls,
9415 };
9416 
9417 static const int kvm_vmx_max_exit_handlers =
9418 	ARRAY_SIZE(kvm_vmx_exit_handlers);
9419 
nested_vmx_exit_handled_io(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)9420 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
9421 				       struct vmcs12 *vmcs12)
9422 {
9423 	unsigned long exit_qualification;
9424 	gpa_t bitmap, last_bitmap;
9425 	unsigned int port;
9426 	int size;
9427 	u8 b;
9428 
9429 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
9430 		return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
9431 
9432 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9433 
9434 	port = exit_qualification >> 16;
9435 	size = (exit_qualification & 7) + 1;
9436 
9437 	last_bitmap = (gpa_t)-1;
9438 	b = -1;
9439 
9440 	while (size > 0) {
9441 		if (port < 0x8000)
9442 			bitmap = vmcs12->io_bitmap_a;
9443 		else if (port < 0x10000)
9444 			bitmap = vmcs12->io_bitmap_b;
9445 		else
9446 			return true;
9447 		bitmap += (port & 0x7fff) / 8;
9448 
9449 		if (last_bitmap != bitmap)
9450 			if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
9451 				return true;
9452 		if (b & (1 << (port & 7)))
9453 			return true;
9454 
9455 		port++;
9456 		size--;
9457 		last_bitmap = bitmap;
9458 	}
9459 
9460 	return false;
9461 }
9462 
9463 /*
9464  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
9465  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
9466  * disinterest in the current event (read or write a specific MSR) by using an
9467  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
9468  */
nested_vmx_exit_handled_msr(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12,u32 exit_reason)9469 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
9470 	struct vmcs12 *vmcs12, u32 exit_reason)
9471 {
9472 	u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
9473 	gpa_t bitmap;
9474 
9475 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
9476 		return true;
9477 
9478 	/*
9479 	 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
9480 	 * for the four combinations of read/write and low/high MSR numbers.
9481 	 * First we need to figure out which of the four to use:
9482 	 */
9483 	bitmap = vmcs12->msr_bitmap;
9484 	if (exit_reason == EXIT_REASON_MSR_WRITE)
9485 		bitmap += 2048;
9486 	if (msr_index >= 0xc0000000) {
9487 		msr_index -= 0xc0000000;
9488 		bitmap += 1024;
9489 	}
9490 
9491 	/* Then read the msr_index'th bit from this bitmap: */
9492 	if (msr_index < 1024*8) {
9493 		unsigned char b;
9494 		if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
9495 			return true;
9496 		return 1 & (b >> (msr_index & 7));
9497 	} else
9498 		return true; /* let L1 handle the wrong parameter */
9499 }
9500 
9501 /*
9502  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
9503  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
9504  * intercept (via guest_host_mask etc.) the current event.
9505  */
nested_vmx_exit_handled_cr(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)9506 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
9507 	struct vmcs12 *vmcs12)
9508 {
9509 	unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9510 	int cr = exit_qualification & 15;
9511 	int reg;
9512 	unsigned long val;
9513 
9514 	switch ((exit_qualification >> 4) & 3) {
9515 	case 0: /* mov to cr */
9516 		reg = (exit_qualification >> 8) & 15;
9517 		val = kvm_register_readl(vcpu, reg);
9518 		switch (cr) {
9519 		case 0:
9520 			if (vmcs12->cr0_guest_host_mask &
9521 			    (val ^ vmcs12->cr0_read_shadow))
9522 				return true;
9523 			break;
9524 		case 3:
9525 			if ((vmcs12->cr3_target_count >= 1 &&
9526 					vmcs12->cr3_target_value0 == val) ||
9527 				(vmcs12->cr3_target_count >= 2 &&
9528 					vmcs12->cr3_target_value1 == val) ||
9529 				(vmcs12->cr3_target_count >= 3 &&
9530 					vmcs12->cr3_target_value2 == val) ||
9531 				(vmcs12->cr3_target_count >= 4 &&
9532 					vmcs12->cr3_target_value3 == val))
9533 				return false;
9534 			if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
9535 				return true;
9536 			break;
9537 		case 4:
9538 			if (vmcs12->cr4_guest_host_mask &
9539 			    (vmcs12->cr4_read_shadow ^ val))
9540 				return true;
9541 			break;
9542 		case 8:
9543 			if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
9544 				return true;
9545 			break;
9546 		}
9547 		break;
9548 	case 2: /* clts */
9549 		if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
9550 		    (vmcs12->cr0_read_shadow & X86_CR0_TS))
9551 			return true;
9552 		break;
9553 	case 1: /* mov from cr */
9554 		switch (cr) {
9555 		case 3:
9556 			if (vmcs12->cpu_based_vm_exec_control &
9557 			    CPU_BASED_CR3_STORE_EXITING)
9558 				return true;
9559 			break;
9560 		case 8:
9561 			if (vmcs12->cpu_based_vm_exec_control &
9562 			    CPU_BASED_CR8_STORE_EXITING)
9563 				return true;
9564 			break;
9565 		}
9566 		break;
9567 	case 3: /* lmsw */
9568 		/*
9569 		 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
9570 		 * cr0. Other attempted changes are ignored, with no exit.
9571 		 */
9572 		val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
9573 		if (vmcs12->cr0_guest_host_mask & 0xe &
9574 		    (val ^ vmcs12->cr0_read_shadow))
9575 			return true;
9576 		if ((vmcs12->cr0_guest_host_mask & 0x1) &&
9577 		    !(vmcs12->cr0_read_shadow & 0x1) &&
9578 		    (val & 0x1))
9579 			return true;
9580 		break;
9581 	}
9582 	return false;
9583 }
9584 
nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12,gpa_t bitmap)9585 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
9586 	struct vmcs12 *vmcs12, gpa_t bitmap)
9587 {
9588 	u32 vmx_instruction_info;
9589 	unsigned long field;
9590 	u8 b;
9591 
9592 	if (!nested_cpu_has_shadow_vmcs(vmcs12))
9593 		return true;
9594 
9595 	/* Decode instruction info and find the field to access */
9596 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9597 	field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
9598 
9599 	/* Out-of-range fields always cause a VM exit from L2 to L1 */
9600 	if (field >> 15)
9601 		return true;
9602 
9603 	if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
9604 		return true;
9605 
9606 	return 1 & (b >> (field & 7));
9607 }
9608 
9609 /*
9610  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
9611  * should handle it ourselves in L0 (and then continue L2). Only call this
9612  * when in is_guest_mode (L2).
9613  */
nested_vmx_exit_reflected(struct kvm_vcpu * vcpu,u32 exit_reason)9614 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
9615 {
9616 	u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9617 	struct vcpu_vmx *vmx = to_vmx(vcpu);
9618 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9619 
9620 	if (vmx->nested.nested_run_pending)
9621 		return false;
9622 
9623 	if (unlikely(vmx->fail)) {
9624 		pr_info_ratelimited("%s failed vm entry %x\n", __func__,
9625 				    vmcs_read32(VM_INSTRUCTION_ERROR));
9626 		return true;
9627 	}
9628 
9629 	/*
9630 	 * The host physical addresses of some pages of guest memory
9631 	 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
9632 	 * Page). The CPU may write to these pages via their host
9633 	 * physical address while L2 is running, bypassing any
9634 	 * address-translation-based dirty tracking (e.g. EPT write
9635 	 * protection).
9636 	 *
9637 	 * Mark them dirty on every exit from L2 to prevent them from
9638 	 * getting out of sync with dirty tracking.
9639 	 */
9640 	nested_mark_vmcs12_pages_dirty(vcpu);
9641 
9642 	trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
9643 				vmcs_readl(EXIT_QUALIFICATION),
9644 				vmx->idt_vectoring_info,
9645 				intr_info,
9646 				vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
9647 				KVM_ISA_VMX);
9648 
9649 	switch (exit_reason) {
9650 	case EXIT_REASON_EXCEPTION_NMI:
9651 		if (is_nmi(intr_info))
9652 			return false;
9653 		else if (is_page_fault(intr_info))
9654 			return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
9655 		else if (is_no_device(intr_info) &&
9656 			 !(vmcs12->guest_cr0 & X86_CR0_TS))
9657 			return false;
9658 		else if (is_debug(intr_info) &&
9659 			 vcpu->guest_debug &
9660 			 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
9661 			return false;
9662 		else if (is_breakpoint(intr_info) &&
9663 			 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
9664 			return false;
9665 		return vmcs12->exception_bitmap &
9666 				(1u << (intr_info & INTR_INFO_VECTOR_MASK));
9667 	case EXIT_REASON_EXTERNAL_INTERRUPT:
9668 		return false;
9669 	case EXIT_REASON_TRIPLE_FAULT:
9670 		return true;
9671 	case EXIT_REASON_PENDING_INTERRUPT:
9672 		return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
9673 	case EXIT_REASON_NMI_WINDOW:
9674 		return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
9675 	case EXIT_REASON_TASK_SWITCH:
9676 		return true;
9677 	case EXIT_REASON_CPUID:
9678 		return true;
9679 	case EXIT_REASON_HLT:
9680 		return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
9681 	case EXIT_REASON_INVD:
9682 		return true;
9683 	case EXIT_REASON_INVLPG:
9684 		return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
9685 	case EXIT_REASON_RDPMC:
9686 		return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
9687 	case EXIT_REASON_RDRAND:
9688 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
9689 	case EXIT_REASON_RDSEED:
9690 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
9691 	case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
9692 		return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
9693 	case EXIT_REASON_VMREAD:
9694 		return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
9695 			vmcs12->vmread_bitmap);
9696 	case EXIT_REASON_VMWRITE:
9697 		return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
9698 			vmcs12->vmwrite_bitmap);
9699 	case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
9700 	case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
9701 	case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
9702 	case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
9703 	case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
9704 		/*
9705 		 * VMX instructions trap unconditionally. This allows L1 to
9706 		 * emulate them for its L2 guest, i.e., allows 3-level nesting!
9707 		 */
9708 		return true;
9709 	case EXIT_REASON_CR_ACCESS:
9710 		return nested_vmx_exit_handled_cr(vcpu, vmcs12);
9711 	case EXIT_REASON_DR_ACCESS:
9712 		return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
9713 	case EXIT_REASON_IO_INSTRUCTION:
9714 		return nested_vmx_exit_handled_io(vcpu, vmcs12);
9715 	case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
9716 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
9717 	case EXIT_REASON_MSR_READ:
9718 	case EXIT_REASON_MSR_WRITE:
9719 		return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
9720 	case EXIT_REASON_INVALID_STATE:
9721 		return true;
9722 	case EXIT_REASON_MWAIT_INSTRUCTION:
9723 		return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
9724 	case EXIT_REASON_MONITOR_TRAP_FLAG:
9725 		return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
9726 	case EXIT_REASON_MONITOR_INSTRUCTION:
9727 		return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
9728 	case EXIT_REASON_PAUSE_INSTRUCTION:
9729 		return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
9730 			nested_cpu_has2(vmcs12,
9731 				SECONDARY_EXEC_PAUSE_LOOP_EXITING);
9732 	case EXIT_REASON_MCE_DURING_VMENTRY:
9733 		return false;
9734 	case EXIT_REASON_TPR_BELOW_THRESHOLD:
9735 		return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
9736 	case EXIT_REASON_APIC_ACCESS:
9737 	case EXIT_REASON_APIC_WRITE:
9738 	case EXIT_REASON_EOI_INDUCED:
9739 		/*
9740 		 * The controls for "virtualize APIC accesses," "APIC-
9741 		 * register virtualization," and "virtual-interrupt
9742 		 * delivery" only come from vmcs12.
9743 		 */
9744 		return true;
9745 	case EXIT_REASON_EPT_VIOLATION:
9746 		/*
9747 		 * L0 always deals with the EPT violation. If nested EPT is
9748 		 * used, and the nested mmu code discovers that the address is
9749 		 * missing in the guest EPT table (EPT12), the EPT violation
9750 		 * will be injected with nested_ept_inject_page_fault()
9751 		 */
9752 		return false;
9753 	case EXIT_REASON_EPT_MISCONFIG:
9754 		/*
9755 		 * L2 never uses directly L1's EPT, but rather L0's own EPT
9756 		 * table (shadow on EPT) or a merged EPT table that L0 built
9757 		 * (EPT on EPT). So any problems with the structure of the
9758 		 * table is L0's fault.
9759 		 */
9760 		return false;
9761 	case EXIT_REASON_INVPCID:
9762 		return
9763 			nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
9764 			nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
9765 	case EXIT_REASON_WBINVD:
9766 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
9767 	case EXIT_REASON_XSETBV:
9768 		return true;
9769 	case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
9770 		/*
9771 		 * This should never happen, since it is not possible to
9772 		 * set XSS to a non-zero value---neither in L1 nor in L2.
9773 		 * If if it were, XSS would have to be checked against
9774 		 * the XSS exit bitmap in vmcs12.
9775 		 */
9776 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
9777 	case EXIT_REASON_PREEMPTION_TIMER:
9778 		return false;
9779 	case EXIT_REASON_PML_FULL:
9780 		/* We emulate PML support to L1. */
9781 		return false;
9782 	case EXIT_REASON_VMFUNC:
9783 		/* VM functions are emulated through L2->L0 vmexits. */
9784 		return false;
9785 	case EXIT_REASON_ENCLS:
9786 		/* SGX is never exposed to L1 */
9787 		return false;
9788 	default:
9789 		return true;
9790 	}
9791 }
9792 
nested_vmx_reflect_vmexit(struct kvm_vcpu * vcpu,u32 exit_reason)9793 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
9794 {
9795 	u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9796 
9797 	/*
9798 	 * At this point, the exit interruption info in exit_intr_info
9799 	 * is only valid for EXCEPTION_NMI exits.  For EXTERNAL_INTERRUPT
9800 	 * we need to query the in-kernel LAPIC.
9801 	 */
9802 	WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
9803 	if ((exit_intr_info &
9804 	     (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
9805 	    (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
9806 		struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9807 		vmcs12->vm_exit_intr_error_code =
9808 			vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
9809 	}
9810 
9811 	nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
9812 			  vmcs_readl(EXIT_QUALIFICATION));
9813 	return 1;
9814 }
9815 
vmx_get_exit_info(struct kvm_vcpu * vcpu,u64 * info1,u64 * info2)9816 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
9817 {
9818 	*info1 = vmcs_readl(EXIT_QUALIFICATION);
9819 	*info2 = vmcs_read32(VM_EXIT_INTR_INFO);
9820 }
9821 
vmx_destroy_pml_buffer(struct vcpu_vmx * vmx)9822 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
9823 {
9824 	if (vmx->pml_pg) {
9825 		__free_page(vmx->pml_pg);
9826 		vmx->pml_pg = NULL;
9827 	}
9828 }
9829 
vmx_flush_pml_buffer(struct kvm_vcpu * vcpu)9830 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
9831 {
9832 	struct vcpu_vmx *vmx = to_vmx(vcpu);
9833 	u64 *pml_buf;
9834 	u16 pml_idx;
9835 
9836 	pml_idx = vmcs_read16(GUEST_PML_INDEX);
9837 
9838 	/* Do nothing if PML buffer is empty */
9839 	if (pml_idx == (PML_ENTITY_NUM - 1))
9840 		return;
9841 
9842 	/* PML index always points to next available PML buffer entity */
9843 	if (pml_idx >= PML_ENTITY_NUM)
9844 		pml_idx = 0;
9845 	else
9846 		pml_idx++;
9847 
9848 	pml_buf = page_address(vmx->pml_pg);
9849 	for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
9850 		u64 gpa;
9851 
9852 		gpa = pml_buf[pml_idx];
9853 		WARN_ON(gpa & (PAGE_SIZE - 1));
9854 		kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
9855 	}
9856 
9857 	/* reset PML index */
9858 	vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
9859 }
9860 
9861 /*
9862  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
9863  * Called before reporting dirty_bitmap to userspace.
9864  */
kvm_flush_pml_buffers(struct kvm * kvm)9865 static void kvm_flush_pml_buffers(struct kvm *kvm)
9866 {
9867 	int i;
9868 	struct kvm_vcpu *vcpu;
9869 	/*
9870 	 * We only need to kick vcpu out of guest mode here, as PML buffer
9871 	 * is flushed at beginning of all VMEXITs, and it's obvious that only
9872 	 * vcpus running in guest are possible to have unflushed GPAs in PML
9873 	 * buffer.
9874 	 */
9875 	kvm_for_each_vcpu(i, vcpu, kvm)
9876 		kvm_vcpu_kick(vcpu);
9877 }
9878 
vmx_dump_sel(char * name,uint32_t sel)9879 static void vmx_dump_sel(char *name, uint32_t sel)
9880 {
9881 	pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
9882 	       name, vmcs_read16(sel),
9883 	       vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
9884 	       vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
9885 	       vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
9886 }
9887 
vmx_dump_dtsel(char * name,uint32_t limit)9888 static void vmx_dump_dtsel(char *name, uint32_t limit)
9889 {
9890 	pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
9891 	       name, vmcs_read32(limit),
9892 	       vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
9893 }
9894 
dump_vmcs(void)9895 static void dump_vmcs(void)
9896 {
9897 	u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
9898 	u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
9899 	u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
9900 	u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
9901 	u32 secondary_exec_control = 0;
9902 	unsigned long cr4 = vmcs_readl(GUEST_CR4);
9903 	u64 efer = vmcs_read64(GUEST_IA32_EFER);
9904 	int i, n;
9905 
9906 	if (cpu_has_secondary_exec_ctrls())
9907 		secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9908 
9909 	pr_err("*** Guest State ***\n");
9910 	pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
9911 	       vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
9912 	       vmcs_readl(CR0_GUEST_HOST_MASK));
9913 	pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
9914 	       cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
9915 	pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
9916 	if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
9917 	    (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
9918 	{
9919 		pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
9920 		       vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
9921 		pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
9922 		       vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
9923 	}
9924 	pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
9925 	       vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
9926 	pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
9927 	       vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
9928 	pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
9929 	       vmcs_readl(GUEST_SYSENTER_ESP),
9930 	       vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
9931 	vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
9932 	vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
9933 	vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
9934 	vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
9935 	vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
9936 	vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
9937 	vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
9938 	vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
9939 	vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
9940 	vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
9941 	if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
9942 	    (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
9943 		pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
9944 		       efer, vmcs_read64(GUEST_IA32_PAT));
9945 	pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
9946 	       vmcs_read64(GUEST_IA32_DEBUGCTL),
9947 	       vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
9948 	if (cpu_has_load_perf_global_ctrl &&
9949 	    vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
9950 		pr_err("PerfGlobCtl = 0x%016llx\n",
9951 		       vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
9952 	if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
9953 		pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
9954 	pr_err("Interruptibility = %08x  ActivityState = %08x\n",
9955 	       vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
9956 	       vmcs_read32(GUEST_ACTIVITY_STATE));
9957 	if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
9958 		pr_err("InterruptStatus = %04x\n",
9959 		       vmcs_read16(GUEST_INTR_STATUS));
9960 
9961 	pr_err("*** Host State ***\n");
9962 	pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
9963 	       vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
9964 	pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
9965 	       vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
9966 	       vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
9967 	       vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
9968 	       vmcs_read16(HOST_TR_SELECTOR));
9969 	pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
9970 	       vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
9971 	       vmcs_readl(HOST_TR_BASE));
9972 	pr_err("GDTBase=%016lx IDTBase=%016lx\n",
9973 	       vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
9974 	pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
9975 	       vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
9976 	       vmcs_readl(HOST_CR4));
9977 	pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
9978 	       vmcs_readl(HOST_IA32_SYSENTER_ESP),
9979 	       vmcs_read32(HOST_IA32_SYSENTER_CS),
9980 	       vmcs_readl(HOST_IA32_SYSENTER_EIP));
9981 	if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
9982 		pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
9983 		       vmcs_read64(HOST_IA32_EFER),
9984 		       vmcs_read64(HOST_IA32_PAT));
9985 	if (cpu_has_load_perf_global_ctrl &&
9986 	    vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
9987 		pr_err("PerfGlobCtl = 0x%016llx\n",
9988 		       vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
9989 
9990 	pr_err("*** Control State ***\n");
9991 	pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
9992 	       pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
9993 	pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
9994 	pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
9995 	       vmcs_read32(EXCEPTION_BITMAP),
9996 	       vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
9997 	       vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
9998 	pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
9999 	       vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10000 	       vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
10001 	       vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
10002 	pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
10003 	       vmcs_read32(VM_EXIT_INTR_INFO),
10004 	       vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
10005 	       vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
10006 	pr_err("        reason=%08x qualification=%016lx\n",
10007 	       vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
10008 	pr_err("IDTVectoring: info=%08x errcode=%08x\n",
10009 	       vmcs_read32(IDT_VECTORING_INFO_FIELD),
10010 	       vmcs_read32(IDT_VECTORING_ERROR_CODE));
10011 	pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
10012 	if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
10013 		pr_err("TSC Multiplier = 0x%016llx\n",
10014 		       vmcs_read64(TSC_MULTIPLIER));
10015 	if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
10016 		pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
10017 	if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
10018 		pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
10019 	if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
10020 		pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
10021 	n = vmcs_read32(CR3_TARGET_COUNT);
10022 	for (i = 0; i + 1 < n; i += 4)
10023 		pr_err("CR3 target%u=%016lx target%u=%016lx\n",
10024 		       i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
10025 		       i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
10026 	if (i < n)
10027 		pr_err("CR3 target%u=%016lx\n",
10028 		       i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
10029 	if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
10030 		pr_err("PLE Gap=%08x Window=%08x\n",
10031 		       vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
10032 	if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
10033 		pr_err("Virtual processor ID = 0x%04x\n",
10034 		       vmcs_read16(VIRTUAL_PROCESSOR_ID));
10035 }
10036 
10037 /*
10038  * The guest has exited.  See if we can fix it or if we need userspace
10039  * assistance.
10040  */
vmx_handle_exit(struct kvm_vcpu * vcpu)10041 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
10042 {
10043 	struct vcpu_vmx *vmx = to_vmx(vcpu);
10044 	u32 exit_reason = vmx->exit_reason;
10045 	u32 vectoring_info = vmx->idt_vectoring_info;
10046 
10047 	trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
10048 
10049 	/*
10050 	 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
10051 	 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
10052 	 * querying dirty_bitmap, we only need to kick all vcpus out of guest
10053 	 * mode as if vcpus is in root mode, the PML buffer must has been
10054 	 * flushed already.
10055 	 */
10056 	if (enable_pml)
10057 		vmx_flush_pml_buffer(vcpu);
10058 
10059 	/* If guest state is invalid, start emulating */
10060 	if (vmx->emulation_required)
10061 		return handle_invalid_guest_state(vcpu);
10062 
10063 	if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
10064 		return nested_vmx_reflect_vmexit(vcpu, exit_reason);
10065 
10066 	if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
10067 		dump_vmcs();
10068 		vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10069 		vcpu->run->fail_entry.hardware_entry_failure_reason
10070 			= exit_reason;
10071 		return 0;
10072 	}
10073 
10074 	if (unlikely(vmx->fail)) {
10075 		vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10076 		vcpu->run->fail_entry.hardware_entry_failure_reason
10077 			= vmcs_read32(VM_INSTRUCTION_ERROR);
10078 		return 0;
10079 	}
10080 
10081 	/*
10082 	 * Note:
10083 	 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
10084 	 * delivery event since it indicates guest is accessing MMIO.
10085 	 * The vm-exit can be triggered again after return to guest that
10086 	 * will cause infinite loop.
10087 	 */
10088 	if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
10089 			(exit_reason != EXIT_REASON_EXCEPTION_NMI &&
10090 			exit_reason != EXIT_REASON_EPT_VIOLATION &&
10091 			exit_reason != EXIT_REASON_PML_FULL &&
10092 			exit_reason != EXIT_REASON_TASK_SWITCH)) {
10093 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10094 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
10095 		vcpu->run->internal.ndata = 3;
10096 		vcpu->run->internal.data[0] = vectoring_info;
10097 		vcpu->run->internal.data[1] = exit_reason;
10098 		vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
10099 		if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
10100 			vcpu->run->internal.ndata++;
10101 			vcpu->run->internal.data[3] =
10102 				vmcs_read64(GUEST_PHYSICAL_ADDRESS);
10103 		}
10104 		return 0;
10105 	}
10106 
10107 	if (unlikely(!enable_vnmi &&
10108 		     vmx->loaded_vmcs->soft_vnmi_blocked)) {
10109 		if (vmx_interrupt_allowed(vcpu)) {
10110 			vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10111 		} else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
10112 			   vcpu->arch.nmi_pending) {
10113 			/*
10114 			 * This CPU don't support us in finding the end of an
10115 			 * NMI-blocked window if the guest runs with IRQs
10116 			 * disabled. So we pull the trigger after 1 s of
10117 			 * futile waiting, but inform the user about this.
10118 			 */
10119 			printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
10120 			       "state on VCPU %d after 1 s timeout\n",
10121 			       __func__, vcpu->vcpu_id);
10122 			vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10123 		}
10124 	}
10125 
10126 	if (exit_reason < kvm_vmx_max_exit_handlers
10127 	    && kvm_vmx_exit_handlers[exit_reason])
10128 		return kvm_vmx_exit_handlers[exit_reason](vcpu);
10129 	else {
10130 		vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
10131 				exit_reason);
10132 		kvm_queue_exception(vcpu, UD_VECTOR);
10133 		return 1;
10134 	}
10135 }
10136 
10137 /*
10138  * Software based L1D cache flush which is used when microcode providing
10139  * the cache control MSR is not loaded.
10140  *
10141  * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
10142  * flush it is required to read in 64 KiB because the replacement algorithm
10143  * is not exactly LRU. This could be sized at runtime via topology
10144  * information but as all relevant affected CPUs have 32KiB L1D cache size
10145  * there is no point in doing so.
10146  */
vmx_l1d_flush(struct kvm_vcpu * vcpu)10147 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
10148 {
10149 	int size = PAGE_SIZE << L1D_CACHE_ORDER;
10150 
10151 	/*
10152 	 * This code is only executed when the the flush mode is 'cond' or
10153 	 * 'always'
10154 	 */
10155 	if (static_branch_likely(&vmx_l1d_flush_cond)) {
10156 		bool flush_l1d;
10157 
10158 		/*
10159 		 * Clear the per-vcpu flush bit, it gets set again
10160 		 * either from vcpu_run() or from one of the unsafe
10161 		 * VMEXIT handlers.
10162 		 */
10163 		flush_l1d = vcpu->arch.l1tf_flush_l1d;
10164 		vcpu->arch.l1tf_flush_l1d = false;
10165 
10166 		/*
10167 		 * Clear the per-cpu flush bit, it gets set again from
10168 		 * the interrupt handlers.
10169 		 */
10170 		flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
10171 		kvm_clear_cpu_l1tf_flush_l1d();
10172 
10173 		if (!flush_l1d)
10174 			return;
10175 	}
10176 
10177 	vcpu->stat.l1d_flush++;
10178 
10179 	if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
10180 		wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
10181 		return;
10182 	}
10183 
10184 	asm volatile(
10185 		/* First ensure the pages are in the TLB */
10186 		"xorl	%%eax, %%eax\n"
10187 		".Lpopulate_tlb:\n\t"
10188 		"movzbl	(%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10189 		"addl	$4096, %%eax\n\t"
10190 		"cmpl	%%eax, %[size]\n\t"
10191 		"jne	.Lpopulate_tlb\n\t"
10192 		"xorl	%%eax, %%eax\n\t"
10193 		"cpuid\n\t"
10194 		/* Now fill the cache */
10195 		"xorl	%%eax, %%eax\n"
10196 		".Lfill_cache:\n"
10197 		"movzbl	(%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10198 		"addl	$64, %%eax\n\t"
10199 		"cmpl	%%eax, %[size]\n\t"
10200 		"jne	.Lfill_cache\n\t"
10201 		"lfence\n"
10202 		:: [flush_pages] "r" (vmx_l1d_flush_pages),
10203 		    [size] "r" (size)
10204 		: "eax", "ebx", "ecx", "edx");
10205 }
10206 
update_cr8_intercept(struct kvm_vcpu * vcpu,int tpr,int irr)10207 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
10208 {
10209 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10210 
10211 	if (is_guest_mode(vcpu) &&
10212 		nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10213 		return;
10214 
10215 	if (irr == -1 || tpr < irr) {
10216 		vmcs_write32(TPR_THRESHOLD, 0);
10217 		return;
10218 	}
10219 
10220 	vmcs_write32(TPR_THRESHOLD, irr);
10221 }
10222 
vmx_set_virtual_apic_mode(struct kvm_vcpu * vcpu)10223 static void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
10224 {
10225 	u32 sec_exec_control;
10226 
10227 	if (!lapic_in_kernel(vcpu))
10228 		return;
10229 
10230 	if (!flexpriority_enabled &&
10231 	    !cpu_has_vmx_virtualize_x2apic_mode())
10232 		return;
10233 
10234 	/* Postpone execution until vmcs01 is the current VMCS. */
10235 	if (is_guest_mode(vcpu)) {
10236 		to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
10237 		return;
10238 	}
10239 
10240 	sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10241 	sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10242 			      SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
10243 
10244 	switch (kvm_get_apic_mode(vcpu)) {
10245 	case LAPIC_MODE_INVALID:
10246 		WARN_ONCE(true, "Invalid local APIC state");
10247 	case LAPIC_MODE_DISABLED:
10248 		break;
10249 	case LAPIC_MODE_XAPIC:
10250 		if (flexpriority_enabled) {
10251 			sec_exec_control |=
10252 				SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10253 			vmx_flush_tlb(vcpu, true);
10254 		}
10255 		break;
10256 	case LAPIC_MODE_X2APIC:
10257 		if (cpu_has_vmx_virtualize_x2apic_mode())
10258 			sec_exec_control |=
10259 				SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
10260 		break;
10261 	}
10262 	vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
10263 
10264 	vmx_update_msr_bitmap(vcpu);
10265 }
10266 
vmx_set_apic_access_page_addr(struct kvm_vcpu * vcpu,hpa_t hpa)10267 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
10268 {
10269 	if (!is_guest_mode(vcpu)) {
10270 		vmcs_write64(APIC_ACCESS_ADDR, hpa);
10271 		vmx_flush_tlb(vcpu, true);
10272 	}
10273 }
10274 
vmx_hwapic_isr_update(struct kvm_vcpu * vcpu,int max_isr)10275 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
10276 {
10277 	u16 status;
10278 	u8 old;
10279 
10280 	if (max_isr == -1)
10281 		max_isr = 0;
10282 
10283 	status = vmcs_read16(GUEST_INTR_STATUS);
10284 	old = status >> 8;
10285 	if (max_isr != old) {
10286 		status &= 0xff;
10287 		status |= max_isr << 8;
10288 		vmcs_write16(GUEST_INTR_STATUS, status);
10289 	}
10290 }
10291 
vmx_set_rvi(int vector)10292 static void vmx_set_rvi(int vector)
10293 {
10294 	u16 status;
10295 	u8 old;
10296 
10297 	if (vector == -1)
10298 		vector = 0;
10299 
10300 	status = vmcs_read16(GUEST_INTR_STATUS);
10301 	old = (u8)status & 0xff;
10302 	if ((u8)vector != old) {
10303 		status &= ~0xff;
10304 		status |= (u8)vector;
10305 		vmcs_write16(GUEST_INTR_STATUS, status);
10306 	}
10307 }
10308 
vmx_hwapic_irr_update(struct kvm_vcpu * vcpu,int max_irr)10309 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
10310 {
10311 	/*
10312 	 * When running L2, updating RVI is only relevant when
10313 	 * vmcs12 virtual-interrupt-delivery enabled.
10314 	 * However, it can be enabled only when L1 also
10315 	 * intercepts external-interrupts and in that case
10316 	 * we should not update vmcs02 RVI but instead intercept
10317 	 * interrupt. Therefore, do nothing when running L2.
10318 	 */
10319 	if (!is_guest_mode(vcpu))
10320 		vmx_set_rvi(max_irr);
10321 }
10322 
vmx_sync_pir_to_irr(struct kvm_vcpu * vcpu)10323 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
10324 {
10325 	struct vcpu_vmx *vmx = to_vmx(vcpu);
10326 	int max_irr;
10327 	bool max_irr_updated;
10328 
10329 	WARN_ON(!vcpu->arch.apicv_active);
10330 	if (pi_test_on(&vmx->pi_desc)) {
10331 		pi_clear_on(&vmx->pi_desc);
10332 		/*
10333 		 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
10334 		 * But on x86 this is just a compiler barrier anyway.
10335 		 */
10336 		smp_mb__after_atomic();
10337 		max_irr_updated =
10338 			kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
10339 
10340 		/*
10341 		 * If we are running L2 and L1 has a new pending interrupt
10342 		 * which can be injected, we should re-evaluate
10343 		 * what should be done with this new L1 interrupt.
10344 		 * If L1 intercepts external-interrupts, we should
10345 		 * exit from L2 to L1. Otherwise, interrupt should be
10346 		 * delivered directly to L2.
10347 		 */
10348 		if (is_guest_mode(vcpu) && max_irr_updated) {
10349 			if (nested_exit_on_intr(vcpu))
10350 				kvm_vcpu_exiting_guest_mode(vcpu);
10351 			else
10352 				kvm_make_request(KVM_REQ_EVENT, vcpu);
10353 		}
10354 	} else {
10355 		max_irr = kvm_lapic_find_highest_irr(vcpu);
10356 	}
10357 	vmx_hwapic_irr_update(vcpu, max_irr);
10358 	return max_irr;
10359 }
10360 
vmx_has_apicv_interrupt(struct kvm_vcpu * vcpu)10361 static u8 vmx_has_apicv_interrupt(struct kvm_vcpu *vcpu)
10362 {
10363 	u8 rvi = vmx_get_rvi();
10364 	u8 vppr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_PROCPRI);
10365 
10366 	return ((rvi & 0xf0) > (vppr & 0xf0));
10367 }
10368 
vmx_load_eoi_exitmap(struct kvm_vcpu * vcpu,u64 * eoi_exit_bitmap)10369 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
10370 {
10371 	if (!kvm_vcpu_apicv_active(vcpu))
10372 		return;
10373 
10374 	vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
10375 	vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
10376 	vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
10377 	vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
10378 }
10379 
vmx_apicv_post_state_restore(struct kvm_vcpu * vcpu)10380 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
10381 {
10382 	struct vcpu_vmx *vmx = to_vmx(vcpu);
10383 
10384 	pi_clear_on(&vmx->pi_desc);
10385 	memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
10386 }
10387 
vmx_complete_atomic_exit(struct vcpu_vmx * vmx)10388 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
10389 {
10390 	u32 exit_intr_info = 0;
10391 	u16 basic_exit_reason = (u16)vmx->exit_reason;
10392 
10393 	if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
10394 	      || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
10395 		return;
10396 
10397 	if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10398 		exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10399 	vmx->exit_intr_info = exit_intr_info;
10400 
10401 	/* if exit due to PF check for async PF */
10402 	if (is_page_fault(exit_intr_info))
10403 		vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
10404 
10405 	/* Handle machine checks before interrupts are enabled */
10406 	if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
10407 	    is_machine_check(exit_intr_info))
10408 		kvm_machine_check();
10409 
10410 	/* We need to handle NMIs before interrupts are enabled */
10411 	if (is_nmi(exit_intr_info)) {
10412 		kvm_before_interrupt(&vmx->vcpu);
10413 		asm("int $2");
10414 		kvm_after_interrupt(&vmx->vcpu);
10415 	}
10416 }
10417 
vmx_handle_external_intr(struct kvm_vcpu * vcpu)10418 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
10419 {
10420 	u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10421 
10422 	if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
10423 			== (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
10424 		unsigned int vector;
10425 		unsigned long entry;
10426 		gate_desc *desc;
10427 		struct vcpu_vmx *vmx = to_vmx(vcpu);
10428 #ifdef CONFIG_X86_64
10429 		unsigned long tmp;
10430 #endif
10431 
10432 		vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
10433 		desc = (gate_desc *)vmx->host_idt_base + vector;
10434 		entry = gate_offset(desc);
10435 		asm volatile(
10436 #ifdef CONFIG_X86_64
10437 			"mov %%" _ASM_SP ", %[sp]\n\t"
10438 			"and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
10439 			"push $%c[ss]\n\t"
10440 			"push %[sp]\n\t"
10441 #endif
10442 			"pushf\n\t"
10443 			__ASM_SIZE(push) " $%c[cs]\n\t"
10444 			CALL_NOSPEC
10445 			:
10446 #ifdef CONFIG_X86_64
10447 			[sp]"=&r"(tmp),
10448 #endif
10449 			ASM_CALL_CONSTRAINT
10450 			:
10451 			THUNK_TARGET(entry),
10452 			[ss]"i"(__KERNEL_DS),
10453 			[cs]"i"(__KERNEL_CS)
10454 			);
10455 	}
10456 }
10457 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
10458 
vmx_has_emulated_msr(int index)10459 static bool vmx_has_emulated_msr(int index)
10460 {
10461 	switch (index) {
10462 	case MSR_IA32_SMBASE:
10463 		/*
10464 		 * We cannot do SMM unless we can run the guest in big
10465 		 * real mode.
10466 		 */
10467 		return enable_unrestricted_guest || emulate_invalid_guest_state;
10468 	case MSR_AMD64_VIRT_SPEC_CTRL:
10469 		/* This is AMD only.  */
10470 		return false;
10471 	default:
10472 		return true;
10473 	}
10474 }
10475 
vmx_mpx_supported(void)10476 static bool vmx_mpx_supported(void)
10477 {
10478 	return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
10479 		(vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
10480 }
10481 
vmx_xsaves_supported(void)10482 static bool vmx_xsaves_supported(void)
10483 {
10484 	return vmcs_config.cpu_based_2nd_exec_ctrl &
10485 		SECONDARY_EXEC_XSAVES;
10486 }
10487 
vmx_recover_nmi_blocking(struct vcpu_vmx * vmx)10488 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
10489 {
10490 	u32 exit_intr_info;
10491 	bool unblock_nmi;
10492 	u8 vector;
10493 	bool idtv_info_valid;
10494 
10495 	idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10496 
10497 	if (enable_vnmi) {
10498 		if (vmx->loaded_vmcs->nmi_known_unmasked)
10499 			return;
10500 		/*
10501 		 * Can't use vmx->exit_intr_info since we're not sure what
10502 		 * the exit reason is.
10503 		 */
10504 		exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10505 		unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
10506 		vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
10507 		/*
10508 		 * SDM 3: 27.7.1.2 (September 2008)
10509 		 * Re-set bit "block by NMI" before VM entry if vmexit caused by
10510 		 * a guest IRET fault.
10511 		 * SDM 3: 23.2.2 (September 2008)
10512 		 * Bit 12 is undefined in any of the following cases:
10513 		 *  If the VM exit sets the valid bit in the IDT-vectoring
10514 		 *   information field.
10515 		 *  If the VM exit is due to a double fault.
10516 		 */
10517 		if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
10518 		    vector != DF_VECTOR && !idtv_info_valid)
10519 			vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
10520 				      GUEST_INTR_STATE_NMI);
10521 		else
10522 			vmx->loaded_vmcs->nmi_known_unmasked =
10523 				!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
10524 				  & GUEST_INTR_STATE_NMI);
10525 	} else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
10526 		vmx->loaded_vmcs->vnmi_blocked_time +=
10527 			ktime_to_ns(ktime_sub(ktime_get(),
10528 					      vmx->loaded_vmcs->entry_time));
10529 }
10530 
__vmx_complete_interrupts(struct kvm_vcpu * vcpu,u32 idt_vectoring_info,int instr_len_field,int error_code_field)10531 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
10532 				      u32 idt_vectoring_info,
10533 				      int instr_len_field,
10534 				      int error_code_field)
10535 {
10536 	u8 vector;
10537 	int type;
10538 	bool idtv_info_valid;
10539 
10540 	idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10541 
10542 	vcpu->arch.nmi_injected = false;
10543 	kvm_clear_exception_queue(vcpu);
10544 	kvm_clear_interrupt_queue(vcpu);
10545 
10546 	if (!idtv_info_valid)
10547 		return;
10548 
10549 	kvm_make_request(KVM_REQ_EVENT, vcpu);
10550 
10551 	vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
10552 	type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
10553 
10554 	switch (type) {
10555 	case INTR_TYPE_NMI_INTR:
10556 		vcpu->arch.nmi_injected = true;
10557 		/*
10558 		 * SDM 3: 27.7.1.2 (September 2008)
10559 		 * Clear bit "block by NMI" before VM entry if a NMI
10560 		 * delivery faulted.
10561 		 */
10562 		vmx_set_nmi_mask(vcpu, false);
10563 		break;
10564 	case INTR_TYPE_SOFT_EXCEPTION:
10565 		vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
10566 		/* fall through */
10567 	case INTR_TYPE_HARD_EXCEPTION:
10568 		if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
10569 			u32 err = vmcs_read32(error_code_field);
10570 			kvm_requeue_exception_e(vcpu, vector, err);
10571 		} else
10572 			kvm_requeue_exception(vcpu, vector);
10573 		break;
10574 	case INTR_TYPE_SOFT_INTR:
10575 		vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
10576 		/* fall through */
10577 	case INTR_TYPE_EXT_INTR:
10578 		kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
10579 		break;
10580 	default:
10581 		break;
10582 	}
10583 }
10584 
vmx_complete_interrupts(struct vcpu_vmx * vmx)10585 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
10586 {
10587 	__vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
10588 				  VM_EXIT_INSTRUCTION_LEN,
10589 				  IDT_VECTORING_ERROR_CODE);
10590 }
10591 
vmx_cancel_injection(struct kvm_vcpu * vcpu)10592 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
10593 {
10594 	__vmx_complete_interrupts(vcpu,
10595 				  vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10596 				  VM_ENTRY_INSTRUCTION_LEN,
10597 				  VM_ENTRY_EXCEPTION_ERROR_CODE);
10598 
10599 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10600 }
10601 
atomic_switch_perf_msrs(struct vcpu_vmx * vmx)10602 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
10603 {
10604 	int i, nr_msrs;
10605 	struct perf_guest_switch_msr *msrs;
10606 
10607 	msrs = perf_guest_get_msrs(&nr_msrs);
10608 
10609 	if (!msrs)
10610 		return;
10611 
10612 	for (i = 0; i < nr_msrs; i++)
10613 		if (msrs[i].host == msrs[i].guest)
10614 			clear_atomic_switch_msr(vmx, msrs[i].msr);
10615 		else
10616 			add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
10617 					msrs[i].host, false);
10618 }
10619 
vmx_arm_hv_timer(struct vcpu_vmx * vmx,u32 val)10620 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
10621 {
10622 	vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
10623 	if (!vmx->loaded_vmcs->hv_timer_armed)
10624 		vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
10625 			      PIN_BASED_VMX_PREEMPTION_TIMER);
10626 	vmx->loaded_vmcs->hv_timer_armed = true;
10627 }
10628 
vmx_update_hv_timer(struct kvm_vcpu * vcpu)10629 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
10630 {
10631 	struct vcpu_vmx *vmx = to_vmx(vcpu);
10632 	u64 tscl;
10633 	u32 delta_tsc;
10634 
10635 	if (vmx->req_immediate_exit) {
10636 		vmx_arm_hv_timer(vmx, 0);
10637 		return;
10638 	}
10639 
10640 	if (vmx->hv_deadline_tsc != -1) {
10641 		tscl = rdtsc();
10642 		if (vmx->hv_deadline_tsc > tscl)
10643 			/* set_hv_timer ensures the delta fits in 32-bits */
10644 			delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
10645 				cpu_preemption_timer_multi);
10646 		else
10647 			delta_tsc = 0;
10648 
10649 		vmx_arm_hv_timer(vmx, delta_tsc);
10650 		return;
10651 	}
10652 
10653 	if (vmx->loaded_vmcs->hv_timer_armed)
10654 		vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
10655 				PIN_BASED_VMX_PREEMPTION_TIMER);
10656 	vmx->loaded_vmcs->hv_timer_armed = false;
10657 }
10658 
vmx_vcpu_run(struct kvm_vcpu * vcpu)10659 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
10660 {
10661 	struct vcpu_vmx *vmx = to_vmx(vcpu);
10662 	unsigned long cr3, cr4, evmcs_rsp;
10663 
10664 	/* Record the guest's net vcpu time for enforced NMI injections. */
10665 	if (unlikely(!enable_vnmi &&
10666 		     vmx->loaded_vmcs->soft_vnmi_blocked))
10667 		vmx->loaded_vmcs->entry_time = ktime_get();
10668 
10669 	/* Don't enter VMX if guest state is invalid, let the exit handler
10670 	   start emulation until we arrive back to a valid state */
10671 	if (vmx->emulation_required)
10672 		return;
10673 
10674 	if (vmx->ple_window_dirty) {
10675 		vmx->ple_window_dirty = false;
10676 		vmcs_write32(PLE_WINDOW, vmx->ple_window);
10677 	}
10678 
10679 	if (vmx->nested.sync_shadow_vmcs) {
10680 		copy_vmcs12_to_shadow(vmx);
10681 		vmx->nested.sync_shadow_vmcs = false;
10682 	}
10683 
10684 	if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
10685 		vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
10686 	if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
10687 		vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
10688 
10689 	cr3 = __get_current_cr3_fast();
10690 	if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
10691 		vmcs_writel(HOST_CR3, cr3);
10692 		vmx->loaded_vmcs->host_state.cr3 = cr3;
10693 	}
10694 
10695 	cr4 = cr4_read_shadow();
10696 	if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
10697 		vmcs_writel(HOST_CR4, cr4);
10698 		vmx->loaded_vmcs->host_state.cr4 = cr4;
10699 	}
10700 
10701 	/* When single-stepping over STI and MOV SS, we must clear the
10702 	 * corresponding interruptibility bits in the guest state. Otherwise
10703 	 * vmentry fails as it then expects bit 14 (BS) in pending debug
10704 	 * exceptions being set, but that's not correct for the guest debugging
10705 	 * case. */
10706 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10707 		vmx_set_interrupt_shadow(vcpu, 0);
10708 
10709 	if (static_cpu_has(X86_FEATURE_PKU) &&
10710 	    kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
10711 	    vcpu->arch.pkru != vmx->host_pkru)
10712 		__write_pkru(vcpu->arch.pkru);
10713 
10714 	atomic_switch_perf_msrs(vmx);
10715 
10716 	vmx_update_hv_timer(vcpu);
10717 
10718 	/*
10719 	 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
10720 	 * it's non-zero. Since vmentry is serialising on affected CPUs, there
10721 	 * is no need to worry about the conditional branch over the wrmsr
10722 	 * being speculatively taken.
10723 	 */
10724 	x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
10725 
10726 	vmx->__launched = vmx->loaded_vmcs->launched;
10727 
10728 	evmcs_rsp = static_branch_unlikely(&enable_evmcs) ?
10729 		(unsigned long)&current_evmcs->host_rsp : 0;
10730 
10731 	if (static_branch_unlikely(&vmx_l1d_should_flush))
10732 		vmx_l1d_flush(vcpu);
10733 
10734 	asm(
10735 		/* Store host registers */
10736 		"push %%" _ASM_DX "; push %%" _ASM_BP ";"
10737 		"push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
10738 		"push %%" _ASM_CX " \n\t"
10739 		"cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
10740 		"je 1f \n\t"
10741 		"mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
10742 		/* Avoid VMWRITE when Enlightened VMCS is in use */
10743 		"test %%" _ASM_SI ", %%" _ASM_SI " \n\t"
10744 		"jz 2f \n\t"
10745 		"mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
10746 		"jmp 1f \n\t"
10747 		"2: \n\t"
10748 		__ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
10749 		"1: \n\t"
10750 		/* Reload cr2 if changed */
10751 		"mov %c[cr2](%0), %%" _ASM_AX " \n\t"
10752 		"mov %%cr2, %%" _ASM_DX " \n\t"
10753 		"cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
10754 		"je 3f \n\t"
10755 		"mov %%" _ASM_AX", %%cr2 \n\t"
10756 		"3: \n\t"
10757 		/* Check if vmlaunch of vmresume is needed */
10758 		"cmpl $0, %c[launched](%0) \n\t"
10759 		/* Load guest registers.  Don't clobber flags. */
10760 		"mov %c[rax](%0), %%" _ASM_AX " \n\t"
10761 		"mov %c[rbx](%0), %%" _ASM_BX " \n\t"
10762 		"mov %c[rdx](%0), %%" _ASM_DX " \n\t"
10763 		"mov %c[rsi](%0), %%" _ASM_SI " \n\t"
10764 		"mov %c[rdi](%0), %%" _ASM_DI " \n\t"
10765 		"mov %c[rbp](%0), %%" _ASM_BP " \n\t"
10766 #ifdef CONFIG_X86_64
10767 		"mov %c[r8](%0),  %%r8  \n\t"
10768 		"mov %c[r9](%0),  %%r9  \n\t"
10769 		"mov %c[r10](%0), %%r10 \n\t"
10770 		"mov %c[r11](%0), %%r11 \n\t"
10771 		"mov %c[r12](%0), %%r12 \n\t"
10772 		"mov %c[r13](%0), %%r13 \n\t"
10773 		"mov %c[r14](%0), %%r14 \n\t"
10774 		"mov %c[r15](%0), %%r15 \n\t"
10775 #endif
10776 		"mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
10777 
10778 		/* Enter guest mode */
10779 		"jne 1f \n\t"
10780 		__ex(ASM_VMX_VMLAUNCH) "\n\t"
10781 		"jmp 2f \n\t"
10782 		"1: " __ex(ASM_VMX_VMRESUME) "\n\t"
10783 		"2: "
10784 		/* Save guest registers, load host registers, keep flags */
10785 		"mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
10786 		"pop %0 \n\t"
10787 		"setbe %c[fail](%0)\n\t"
10788 		"mov %%" _ASM_AX ", %c[rax](%0) \n\t"
10789 		"mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
10790 		__ASM_SIZE(pop) " %c[rcx](%0) \n\t"
10791 		"mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
10792 		"mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
10793 		"mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
10794 		"mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
10795 #ifdef CONFIG_X86_64
10796 		"mov %%r8,  %c[r8](%0) \n\t"
10797 		"mov %%r9,  %c[r9](%0) \n\t"
10798 		"mov %%r10, %c[r10](%0) \n\t"
10799 		"mov %%r11, %c[r11](%0) \n\t"
10800 		"mov %%r12, %c[r12](%0) \n\t"
10801 		"mov %%r13, %c[r13](%0) \n\t"
10802 		"mov %%r14, %c[r14](%0) \n\t"
10803 		"mov %%r15, %c[r15](%0) \n\t"
10804 		"xor %%r8d,  %%r8d \n\t"
10805 		"xor %%r9d,  %%r9d \n\t"
10806 		"xor %%r10d, %%r10d \n\t"
10807 		"xor %%r11d, %%r11d \n\t"
10808 		"xor %%r12d, %%r12d \n\t"
10809 		"xor %%r13d, %%r13d \n\t"
10810 		"xor %%r14d, %%r14d \n\t"
10811 		"xor %%r15d, %%r15d \n\t"
10812 #endif
10813 		"mov %%cr2, %%" _ASM_AX "   \n\t"
10814 		"mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
10815 
10816 		"xor %%eax, %%eax \n\t"
10817 		"xor %%ebx, %%ebx \n\t"
10818 		"xor %%esi, %%esi \n\t"
10819 		"xor %%edi, %%edi \n\t"
10820 		"pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
10821 		".pushsection .rodata \n\t"
10822 		".global vmx_return \n\t"
10823 		"vmx_return: " _ASM_PTR " 2b \n\t"
10824 		".popsection"
10825 	      : : "c"(vmx), "d"((unsigned long)HOST_RSP), "S"(evmcs_rsp),
10826 		[launched]"i"(offsetof(struct vcpu_vmx, __launched)),
10827 		[fail]"i"(offsetof(struct vcpu_vmx, fail)),
10828 		[host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
10829 		[rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
10830 		[rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
10831 		[rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
10832 		[rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
10833 		[rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
10834 		[rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
10835 		[rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
10836 #ifdef CONFIG_X86_64
10837 		[r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
10838 		[r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
10839 		[r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
10840 		[r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
10841 		[r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
10842 		[r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
10843 		[r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
10844 		[r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
10845 #endif
10846 		[cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
10847 		[wordsize]"i"(sizeof(ulong))
10848 	      : "cc", "memory"
10849 #ifdef CONFIG_X86_64
10850 		, "rax", "rbx", "rdi"
10851 		, "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
10852 #else
10853 		, "eax", "ebx", "edi"
10854 #endif
10855 	      );
10856 
10857 	/*
10858 	 * We do not use IBRS in the kernel. If this vCPU has used the
10859 	 * SPEC_CTRL MSR it may have left it on; save the value and
10860 	 * turn it off. This is much more efficient than blindly adding
10861 	 * it to the atomic save/restore list. Especially as the former
10862 	 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
10863 	 *
10864 	 * For non-nested case:
10865 	 * If the L01 MSR bitmap does not intercept the MSR, then we need to
10866 	 * save it.
10867 	 *
10868 	 * For nested case:
10869 	 * If the L02 MSR bitmap does not intercept the MSR, then we need to
10870 	 * save it.
10871 	 */
10872 	if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
10873 		vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
10874 
10875 	x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
10876 
10877 	/* Eliminate branch target predictions from guest mode */
10878 	vmexit_fill_RSB();
10879 
10880 	/* All fields are clean at this point */
10881 	if (static_branch_unlikely(&enable_evmcs))
10882 		current_evmcs->hv_clean_fields |=
10883 			HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
10884 
10885 	/* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
10886 	if (vmx->host_debugctlmsr)
10887 		update_debugctlmsr(vmx->host_debugctlmsr);
10888 
10889 #ifndef CONFIG_X86_64
10890 	/*
10891 	 * The sysexit path does not restore ds/es, so we must set them to
10892 	 * a reasonable value ourselves.
10893 	 *
10894 	 * We can't defer this to vmx_prepare_switch_to_host() since that
10895 	 * function may be executed in interrupt context, which saves and
10896 	 * restore segments around it, nullifying its effect.
10897 	 */
10898 	loadsegment(ds, __USER_DS);
10899 	loadsegment(es, __USER_DS);
10900 #endif
10901 
10902 	vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
10903 				  | (1 << VCPU_EXREG_RFLAGS)
10904 				  | (1 << VCPU_EXREG_PDPTR)
10905 				  | (1 << VCPU_EXREG_SEGMENTS)
10906 				  | (1 << VCPU_EXREG_CR3));
10907 	vcpu->arch.regs_dirty = 0;
10908 
10909 	/*
10910 	 * eager fpu is enabled if PKEY is supported and CR4 is switched
10911 	 * back on host, so it is safe to read guest PKRU from current
10912 	 * XSAVE.
10913 	 */
10914 	if (static_cpu_has(X86_FEATURE_PKU) &&
10915 	    kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
10916 		vcpu->arch.pkru = __read_pkru();
10917 		if (vcpu->arch.pkru != vmx->host_pkru)
10918 			__write_pkru(vmx->host_pkru);
10919 	}
10920 
10921 	vmx->nested.nested_run_pending = 0;
10922 	vmx->idt_vectoring_info = 0;
10923 
10924 	vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
10925 	if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10926 		return;
10927 
10928 	vmx->loaded_vmcs->launched = 1;
10929 	vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
10930 
10931 	vmx_complete_atomic_exit(vmx);
10932 	vmx_recover_nmi_blocking(vmx);
10933 	vmx_complete_interrupts(vmx);
10934 }
10935 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
10936 
vmx_vm_alloc(void)10937 static struct kvm *vmx_vm_alloc(void)
10938 {
10939 	struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
10940 	return &kvm_vmx->kvm;
10941 }
10942 
vmx_vm_free(struct kvm * kvm)10943 static void vmx_vm_free(struct kvm *kvm)
10944 {
10945 	vfree(to_kvm_vmx(kvm));
10946 }
10947 
vmx_switch_vmcs(struct kvm_vcpu * vcpu,struct loaded_vmcs * vmcs)10948 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
10949 {
10950 	struct vcpu_vmx *vmx = to_vmx(vcpu);
10951 	int cpu;
10952 
10953 	if (vmx->loaded_vmcs == vmcs)
10954 		return;
10955 
10956 	cpu = get_cpu();
10957 	vmx_vcpu_put(vcpu);
10958 	vmx->loaded_vmcs = vmcs;
10959 	vmx_vcpu_load(vcpu, cpu);
10960 	put_cpu();
10961 }
10962 
10963 /*
10964  * Ensure that the current vmcs of the logical processor is the
10965  * vmcs01 of the vcpu before calling free_nested().
10966  */
vmx_free_vcpu_nested(struct kvm_vcpu * vcpu)10967 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
10968 {
10969        struct vcpu_vmx *vmx = to_vmx(vcpu);
10970 
10971        vcpu_load(vcpu);
10972        vmx_switch_vmcs(vcpu, &vmx->vmcs01);
10973        free_nested(vmx);
10974        vcpu_put(vcpu);
10975 }
10976 
vmx_free_vcpu(struct kvm_vcpu * vcpu)10977 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
10978 {
10979 	struct vcpu_vmx *vmx = to_vmx(vcpu);
10980 
10981 	if (enable_pml)
10982 		vmx_destroy_pml_buffer(vmx);
10983 	free_vpid(vmx->vpid);
10984 	leave_guest_mode(vcpu);
10985 	vmx_free_vcpu_nested(vcpu);
10986 	free_loaded_vmcs(vmx->loaded_vmcs);
10987 	kfree(vmx->guest_msrs);
10988 	kvm_vcpu_uninit(vcpu);
10989 	kmem_cache_free(kvm_vcpu_cache, vmx);
10990 }
10991 
vmx_create_vcpu(struct kvm * kvm,unsigned int id)10992 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
10993 {
10994 	int err;
10995 	struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
10996 	unsigned long *msr_bitmap;
10997 	int cpu;
10998 
10999 	if (!vmx)
11000 		return ERR_PTR(-ENOMEM);
11001 
11002 	vmx->vpid = allocate_vpid();
11003 
11004 	err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
11005 	if (err)
11006 		goto free_vcpu;
11007 
11008 	err = -ENOMEM;
11009 
11010 	/*
11011 	 * If PML is turned on, failure on enabling PML just results in failure
11012 	 * of creating the vcpu, therefore we can simplify PML logic (by
11013 	 * avoiding dealing with cases, such as enabling PML partially on vcpus
11014 	 * for the guest, etc.
11015 	 */
11016 	if (enable_pml) {
11017 		vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
11018 		if (!vmx->pml_pg)
11019 			goto uninit_vcpu;
11020 	}
11021 
11022 	vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
11023 	BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
11024 		     > PAGE_SIZE);
11025 
11026 	if (!vmx->guest_msrs)
11027 		goto free_pml;
11028 
11029 	err = alloc_loaded_vmcs(&vmx->vmcs01);
11030 	if (err < 0)
11031 		goto free_msrs;
11032 
11033 	msr_bitmap = vmx->vmcs01.msr_bitmap;
11034 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
11035 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
11036 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
11037 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
11038 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
11039 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
11040 	vmx->msr_bitmap_mode = 0;
11041 
11042 	vmx->loaded_vmcs = &vmx->vmcs01;
11043 	cpu = get_cpu();
11044 	vmx_vcpu_load(&vmx->vcpu, cpu);
11045 	vmx->vcpu.cpu = cpu;
11046 	vmx_vcpu_setup(vmx);
11047 	vmx_vcpu_put(&vmx->vcpu);
11048 	put_cpu();
11049 	if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
11050 		err = alloc_apic_access_page(kvm);
11051 		if (err)
11052 			goto free_vmcs;
11053 	}
11054 
11055 	if (enable_ept && !enable_unrestricted_guest) {
11056 		err = init_rmode_identity_map(kvm);
11057 		if (err)
11058 			goto free_vmcs;
11059 	}
11060 
11061 	if (nested)
11062 		nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
11063 					   kvm_vcpu_apicv_active(&vmx->vcpu));
11064 
11065 	vmx->nested.posted_intr_nv = -1;
11066 	vmx->nested.current_vmptr = -1ull;
11067 
11068 	vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
11069 
11070 	/*
11071 	 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
11072 	 * or POSTED_INTR_WAKEUP_VECTOR.
11073 	 */
11074 	vmx->pi_desc.nv = POSTED_INTR_VECTOR;
11075 	vmx->pi_desc.sn = 1;
11076 
11077 	return &vmx->vcpu;
11078 
11079 free_vmcs:
11080 	free_loaded_vmcs(vmx->loaded_vmcs);
11081 free_msrs:
11082 	kfree(vmx->guest_msrs);
11083 free_pml:
11084 	vmx_destroy_pml_buffer(vmx);
11085 uninit_vcpu:
11086 	kvm_vcpu_uninit(&vmx->vcpu);
11087 free_vcpu:
11088 	free_vpid(vmx->vpid);
11089 	kmem_cache_free(kvm_vcpu_cache, vmx);
11090 	return ERR_PTR(err);
11091 }
11092 
11093 #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"
11094 #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"
11095 
vmx_vm_init(struct kvm * kvm)11096 static int vmx_vm_init(struct kvm *kvm)
11097 {
11098 	spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
11099 
11100 	if (!ple_gap)
11101 		kvm->arch.pause_in_guest = true;
11102 
11103 	if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
11104 		switch (l1tf_mitigation) {
11105 		case L1TF_MITIGATION_OFF:
11106 		case L1TF_MITIGATION_FLUSH_NOWARN:
11107 			/* 'I explicitly don't care' is set */
11108 			break;
11109 		case L1TF_MITIGATION_FLUSH:
11110 		case L1TF_MITIGATION_FLUSH_NOSMT:
11111 		case L1TF_MITIGATION_FULL:
11112 			/*
11113 			 * Warn upon starting the first VM in a potentially
11114 			 * insecure environment.
11115 			 */
11116 			if (cpu_smt_control == CPU_SMT_ENABLED)
11117 				pr_warn_once(L1TF_MSG_SMT);
11118 			if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
11119 				pr_warn_once(L1TF_MSG_L1D);
11120 			break;
11121 		case L1TF_MITIGATION_FULL_FORCE:
11122 			/* Flush is enforced */
11123 			break;
11124 		}
11125 	}
11126 	return 0;
11127 }
11128 
vmx_check_processor_compat(void * rtn)11129 static void __init vmx_check_processor_compat(void *rtn)
11130 {
11131 	struct vmcs_config vmcs_conf;
11132 
11133 	*(int *)rtn = 0;
11134 	if (setup_vmcs_config(&vmcs_conf) < 0)
11135 		*(int *)rtn = -EIO;
11136 	nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, enable_apicv);
11137 	if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
11138 		printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
11139 				smp_processor_id());
11140 		*(int *)rtn = -EIO;
11141 	}
11142 }
11143 
vmx_get_mt_mask(struct kvm_vcpu * vcpu,gfn_t gfn,bool is_mmio)11144 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
11145 {
11146 	u8 cache;
11147 	u64 ipat = 0;
11148 
11149 	/* For VT-d and EPT combination
11150 	 * 1. MMIO: always map as UC
11151 	 * 2. EPT with VT-d:
11152 	 *   a. VT-d without snooping control feature: can't guarantee the
11153 	 *	result, try to trust guest.
11154 	 *   b. VT-d with snooping control feature: snooping control feature of
11155 	 *	VT-d engine can guarantee the cache correctness. Just set it
11156 	 *	to WB to keep consistent with host. So the same as item 3.
11157 	 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
11158 	 *    consistent with host MTRR
11159 	 */
11160 	if (is_mmio) {
11161 		cache = MTRR_TYPE_UNCACHABLE;
11162 		goto exit;
11163 	}
11164 
11165 	if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
11166 		ipat = VMX_EPT_IPAT_BIT;
11167 		cache = MTRR_TYPE_WRBACK;
11168 		goto exit;
11169 	}
11170 
11171 	if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
11172 		ipat = VMX_EPT_IPAT_BIT;
11173 		if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
11174 			cache = MTRR_TYPE_WRBACK;
11175 		else
11176 			cache = MTRR_TYPE_UNCACHABLE;
11177 		goto exit;
11178 	}
11179 
11180 	cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
11181 
11182 exit:
11183 	return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
11184 }
11185 
vmx_get_lpage_level(void)11186 static int vmx_get_lpage_level(void)
11187 {
11188 	if (enable_ept && !cpu_has_vmx_ept_1g_page())
11189 		return PT_DIRECTORY_LEVEL;
11190 	else
11191 		/* For shadow and EPT supported 1GB page */
11192 		return PT_PDPE_LEVEL;
11193 }
11194 
vmcs_set_secondary_exec_control(u32 new_ctl)11195 static void vmcs_set_secondary_exec_control(u32 new_ctl)
11196 {
11197 	/*
11198 	 * These bits in the secondary execution controls field
11199 	 * are dynamic, the others are mostly based on the hypervisor
11200 	 * architecture and the guest's CPUID.  Do not touch the
11201 	 * dynamic bits.
11202 	 */
11203 	u32 mask =
11204 		SECONDARY_EXEC_SHADOW_VMCS |
11205 		SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
11206 		SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
11207 		SECONDARY_EXEC_DESC;
11208 
11209 	u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
11210 
11211 	vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
11212 		     (new_ctl & ~mask) | (cur_ctl & mask));
11213 }
11214 
11215 /*
11216  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
11217  * (indicating "allowed-1") if they are supported in the guest's CPUID.
11218  */
nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu * vcpu)11219 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
11220 {
11221 	struct vcpu_vmx *vmx = to_vmx(vcpu);
11222 	struct kvm_cpuid_entry2 *entry;
11223 
11224 	vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
11225 	vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
11226 
11227 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {		\
11228 	if (entry && (entry->_reg & (_cpuid_mask)))			\
11229 		vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask);	\
11230 } while (0)
11231 
11232 	entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
11233 	cr4_fixed1_update(X86_CR4_VME,        edx, bit(X86_FEATURE_VME));
11234 	cr4_fixed1_update(X86_CR4_PVI,        edx, bit(X86_FEATURE_VME));
11235 	cr4_fixed1_update(X86_CR4_TSD,        edx, bit(X86_FEATURE_TSC));
11236 	cr4_fixed1_update(X86_CR4_DE,         edx, bit(X86_FEATURE_DE));
11237 	cr4_fixed1_update(X86_CR4_PSE,        edx, bit(X86_FEATURE_PSE));
11238 	cr4_fixed1_update(X86_CR4_PAE,        edx, bit(X86_FEATURE_PAE));
11239 	cr4_fixed1_update(X86_CR4_MCE,        edx, bit(X86_FEATURE_MCE));
11240 	cr4_fixed1_update(X86_CR4_PGE,        edx, bit(X86_FEATURE_PGE));
11241 	cr4_fixed1_update(X86_CR4_OSFXSR,     edx, bit(X86_FEATURE_FXSR));
11242 	cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
11243 	cr4_fixed1_update(X86_CR4_VMXE,       ecx, bit(X86_FEATURE_VMX));
11244 	cr4_fixed1_update(X86_CR4_SMXE,       ecx, bit(X86_FEATURE_SMX));
11245 	cr4_fixed1_update(X86_CR4_PCIDE,      ecx, bit(X86_FEATURE_PCID));
11246 	cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, bit(X86_FEATURE_XSAVE));
11247 
11248 	entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
11249 	cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, bit(X86_FEATURE_FSGSBASE));
11250 	cr4_fixed1_update(X86_CR4_SMEP,       ebx, bit(X86_FEATURE_SMEP));
11251 	cr4_fixed1_update(X86_CR4_SMAP,       ebx, bit(X86_FEATURE_SMAP));
11252 	cr4_fixed1_update(X86_CR4_PKE,        ecx, bit(X86_FEATURE_PKU));
11253 	cr4_fixed1_update(X86_CR4_UMIP,       ecx, bit(X86_FEATURE_UMIP));
11254 
11255 #undef cr4_fixed1_update
11256 }
11257 
nested_vmx_entry_exit_ctls_update(struct kvm_vcpu * vcpu)11258 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
11259 {
11260 	struct vcpu_vmx *vmx = to_vmx(vcpu);
11261 
11262 	if (kvm_mpx_supported()) {
11263 		bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
11264 
11265 		if (mpx_enabled) {
11266 			vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
11267 			vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
11268 		} else {
11269 			vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
11270 			vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
11271 		}
11272 	}
11273 }
11274 
vmx_cpuid_update(struct kvm_vcpu * vcpu)11275 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
11276 {
11277 	struct vcpu_vmx *vmx = to_vmx(vcpu);
11278 
11279 	if (cpu_has_secondary_exec_ctrls()) {
11280 		vmx_compute_secondary_exec_control(vmx);
11281 		vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
11282 	}
11283 
11284 	if (nested_vmx_allowed(vcpu))
11285 		to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11286 			FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11287 	else
11288 		to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
11289 			~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11290 
11291 	if (nested_vmx_allowed(vcpu)) {
11292 		nested_vmx_cr_fixed1_bits_update(vcpu);
11293 		nested_vmx_entry_exit_ctls_update(vcpu);
11294 	}
11295 }
11296 
vmx_set_supported_cpuid(u32 func,struct kvm_cpuid_entry2 * entry)11297 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
11298 {
11299 	if (func == 1 && nested)
11300 		entry->ecx |= bit(X86_FEATURE_VMX);
11301 }
11302 
nested_ept_inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)11303 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
11304 		struct x86_exception *fault)
11305 {
11306 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11307 	struct vcpu_vmx *vmx = to_vmx(vcpu);
11308 	u32 exit_reason;
11309 	unsigned long exit_qualification = vcpu->arch.exit_qualification;
11310 
11311 	if (vmx->nested.pml_full) {
11312 		exit_reason = EXIT_REASON_PML_FULL;
11313 		vmx->nested.pml_full = false;
11314 		exit_qualification &= INTR_INFO_UNBLOCK_NMI;
11315 	} else if (fault->error_code & PFERR_RSVD_MASK)
11316 		exit_reason = EXIT_REASON_EPT_MISCONFIG;
11317 	else
11318 		exit_reason = EXIT_REASON_EPT_VIOLATION;
11319 
11320 	nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
11321 	vmcs12->guest_physical_address = fault->address;
11322 }
11323 
nested_ept_ad_enabled(struct kvm_vcpu * vcpu)11324 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
11325 {
11326 	return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
11327 }
11328 
11329 /* Callbacks for nested_ept_init_mmu_context: */
11330 
nested_ept_get_cr3(struct kvm_vcpu * vcpu)11331 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
11332 {
11333 	/* return the page table to be shadowed - in our case, EPT12 */
11334 	return get_vmcs12(vcpu)->ept_pointer;
11335 }
11336 
nested_ept_init_mmu_context(struct kvm_vcpu * vcpu)11337 static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
11338 {
11339 	WARN_ON(mmu_is_nested(vcpu));
11340 	if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
11341 		return 1;
11342 
11343 	kvm_init_shadow_ept_mmu(vcpu,
11344 			to_vmx(vcpu)->nested.msrs.ept_caps &
11345 			VMX_EPT_EXECUTE_ONLY_BIT,
11346 			nested_ept_ad_enabled(vcpu),
11347 			nested_ept_get_cr3(vcpu));
11348 	vcpu->arch.mmu.set_cr3           = vmx_set_cr3;
11349 	vcpu->arch.mmu.get_cr3           = nested_ept_get_cr3;
11350 	vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
11351 
11352 	vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
11353 	return 0;
11354 }
11355 
nested_ept_uninit_mmu_context(struct kvm_vcpu * vcpu)11356 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
11357 {
11358 	vcpu->arch.walk_mmu = &vcpu->arch.mmu;
11359 }
11360 
nested_vmx_is_page_fault_vmexit(struct vmcs12 * vmcs12,u16 error_code)11361 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
11362 					    u16 error_code)
11363 {
11364 	bool inequality, bit;
11365 
11366 	bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
11367 	inequality =
11368 		(error_code & vmcs12->page_fault_error_code_mask) !=
11369 		 vmcs12->page_fault_error_code_match;
11370 	return inequality ^ bit;
11371 }
11372 
vmx_inject_page_fault_nested(struct kvm_vcpu * vcpu,struct x86_exception * fault)11373 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
11374 		struct x86_exception *fault)
11375 {
11376 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11377 
11378 	WARN_ON(!is_guest_mode(vcpu));
11379 
11380 	if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
11381 		!to_vmx(vcpu)->nested.nested_run_pending) {
11382 		vmcs12->vm_exit_intr_error_code = fault->error_code;
11383 		nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11384 				  PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
11385 				  INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
11386 				  fault->address);
11387 	} else {
11388 		kvm_inject_page_fault(vcpu, fault);
11389 	}
11390 }
11391 
11392 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11393 						 struct vmcs12 *vmcs12);
11394 
nested_get_vmcs12_pages(struct kvm_vcpu * vcpu)11395 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
11396 {
11397 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11398 	struct vcpu_vmx *vmx = to_vmx(vcpu);
11399 	struct page *page;
11400 	u64 hpa;
11401 
11402 	if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11403 		/*
11404 		 * Translate L1 physical address to host physical
11405 		 * address for vmcs02. Keep the page pinned, so this
11406 		 * physical address remains valid. We keep a reference
11407 		 * to it so we can release it later.
11408 		 */
11409 		if (vmx->nested.apic_access_page) { /* shouldn't happen */
11410 			kvm_release_page_dirty(vmx->nested.apic_access_page);
11411 			vmx->nested.apic_access_page = NULL;
11412 		}
11413 		page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
11414 		/*
11415 		 * If translation failed, no matter: This feature asks
11416 		 * to exit when accessing the given address, and if it
11417 		 * can never be accessed, this feature won't do
11418 		 * anything anyway.
11419 		 */
11420 		if (!is_error_page(page)) {
11421 			vmx->nested.apic_access_page = page;
11422 			hpa = page_to_phys(vmx->nested.apic_access_page);
11423 			vmcs_write64(APIC_ACCESS_ADDR, hpa);
11424 		} else {
11425 			vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
11426 					SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
11427 		}
11428 	}
11429 
11430 	if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
11431 		if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
11432 			kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11433 			vmx->nested.virtual_apic_page = NULL;
11434 		}
11435 		page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
11436 
11437 		/*
11438 		 * If translation failed, VM entry will fail because
11439 		 * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
11440 		 * Failing the vm entry is _not_ what the processor
11441 		 * does but it's basically the only possibility we
11442 		 * have.  We could still enter the guest if CR8 load
11443 		 * exits are enabled, CR8 store exits are enabled, and
11444 		 * virtualize APIC access is disabled; in this case
11445 		 * the processor would never use the TPR shadow and we
11446 		 * could simply clear the bit from the execution
11447 		 * control.  But such a configuration is useless, so
11448 		 * let's keep the code simple.
11449 		 */
11450 		if (!is_error_page(page)) {
11451 			vmx->nested.virtual_apic_page = page;
11452 			hpa = page_to_phys(vmx->nested.virtual_apic_page);
11453 			vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
11454 		}
11455 	}
11456 
11457 	if (nested_cpu_has_posted_intr(vmcs12)) {
11458 		if (vmx->nested.pi_desc_page) { /* shouldn't happen */
11459 			kunmap(vmx->nested.pi_desc_page);
11460 			kvm_release_page_dirty(vmx->nested.pi_desc_page);
11461 			vmx->nested.pi_desc_page = NULL;
11462 		}
11463 		page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
11464 		if (is_error_page(page))
11465 			return;
11466 		vmx->nested.pi_desc_page = page;
11467 		vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
11468 		vmx->nested.pi_desc =
11469 			(struct pi_desc *)((void *)vmx->nested.pi_desc +
11470 			(unsigned long)(vmcs12->posted_intr_desc_addr &
11471 			(PAGE_SIZE - 1)));
11472 		vmcs_write64(POSTED_INTR_DESC_ADDR,
11473 			page_to_phys(vmx->nested.pi_desc_page) +
11474 			(unsigned long)(vmcs12->posted_intr_desc_addr &
11475 			(PAGE_SIZE - 1)));
11476 	}
11477 	if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
11478 		vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
11479 			      CPU_BASED_USE_MSR_BITMAPS);
11480 	else
11481 		vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
11482 				CPU_BASED_USE_MSR_BITMAPS);
11483 }
11484 
vmx_start_preemption_timer(struct kvm_vcpu * vcpu)11485 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
11486 {
11487 	u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
11488 	struct vcpu_vmx *vmx = to_vmx(vcpu);
11489 
11490 	/*
11491 	 * A timer value of zero is architecturally guaranteed to cause
11492 	 * a VMExit prior to executing any instructions in the guest.
11493 	 */
11494 	if (preemption_timeout == 0) {
11495 		vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
11496 		return;
11497 	}
11498 
11499 	if (vcpu->arch.virtual_tsc_khz == 0)
11500 		return;
11501 
11502 	preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11503 	preemption_timeout *= 1000000;
11504 	do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
11505 	hrtimer_start(&vmx->nested.preemption_timer,
11506 		      ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
11507 }
11508 
nested_vmx_check_io_bitmap_controls(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11509 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
11510 					       struct vmcs12 *vmcs12)
11511 {
11512 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
11513 		return 0;
11514 
11515 	if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
11516 	    !page_address_valid(vcpu, vmcs12->io_bitmap_b))
11517 		return -EINVAL;
11518 
11519 	return 0;
11520 }
11521 
nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11522 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
11523 						struct vmcs12 *vmcs12)
11524 {
11525 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
11526 		return 0;
11527 
11528 	if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
11529 		return -EINVAL;
11530 
11531 	return 0;
11532 }
11533 
nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11534 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
11535 						struct vmcs12 *vmcs12)
11536 {
11537 	if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
11538 		return 0;
11539 
11540 	if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
11541 		return -EINVAL;
11542 
11543 	return 0;
11544 }
11545 
11546 /*
11547  * Merge L0's and L1's MSR bitmap, return false to indicate that
11548  * we do not use the hardware.
11549  */
nested_vmx_prepare_msr_bitmap(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11550 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11551 						 struct vmcs12 *vmcs12)
11552 {
11553 	int msr;
11554 	struct page *page;
11555 	unsigned long *msr_bitmap_l1;
11556 	unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
11557 	/*
11558 	 * pred_cmd & spec_ctrl are trying to verify two things:
11559 	 *
11560 	 * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
11561 	 *    ensures that we do not accidentally generate an L02 MSR bitmap
11562 	 *    from the L12 MSR bitmap that is too permissive.
11563 	 * 2. That L1 or L2s have actually used the MSR. This avoids
11564 	 *    unnecessarily merging of the bitmap if the MSR is unused. This
11565 	 *    works properly because we only update the L01 MSR bitmap lazily.
11566 	 *    So even if L0 should pass L1 these MSRs, the L01 bitmap is only
11567 	 *    updated to reflect this when L1 (or its L2s) actually write to
11568 	 *    the MSR.
11569 	 */
11570 	bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
11571 	bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
11572 
11573 	/* Nothing to do if the MSR bitmap is not in use.  */
11574 	if (!cpu_has_vmx_msr_bitmap() ||
11575 	    !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
11576 		return false;
11577 
11578 	if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11579 	    !pred_cmd && !spec_ctrl)
11580 		return false;
11581 
11582 	page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
11583 	if (is_error_page(page))
11584 		return false;
11585 
11586 	msr_bitmap_l1 = (unsigned long *)kmap(page);
11587 	if (nested_cpu_has_apic_reg_virt(vmcs12)) {
11588 		/*
11589 		 * L0 need not intercept reads for MSRs between 0x800 and 0x8ff, it
11590 		 * just lets the processor take the value from the virtual-APIC page;
11591 		 * take those 256 bits directly from the L1 bitmap.
11592 		 */
11593 		for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
11594 			unsigned word = msr / BITS_PER_LONG;
11595 			msr_bitmap_l0[word] = msr_bitmap_l1[word];
11596 			msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
11597 		}
11598 	} else {
11599 		for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
11600 			unsigned word = msr / BITS_PER_LONG;
11601 			msr_bitmap_l0[word] = ~0;
11602 			msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
11603 		}
11604 	}
11605 
11606 	nested_vmx_disable_intercept_for_msr(
11607 		msr_bitmap_l1, msr_bitmap_l0,
11608 		X2APIC_MSR(APIC_TASKPRI),
11609 		MSR_TYPE_W);
11610 
11611 	if (nested_cpu_has_vid(vmcs12)) {
11612 		nested_vmx_disable_intercept_for_msr(
11613 			msr_bitmap_l1, msr_bitmap_l0,
11614 			X2APIC_MSR(APIC_EOI),
11615 			MSR_TYPE_W);
11616 		nested_vmx_disable_intercept_for_msr(
11617 			msr_bitmap_l1, msr_bitmap_l0,
11618 			X2APIC_MSR(APIC_SELF_IPI),
11619 			MSR_TYPE_W);
11620 	}
11621 
11622 	if (spec_ctrl)
11623 		nested_vmx_disable_intercept_for_msr(
11624 					msr_bitmap_l1, msr_bitmap_l0,
11625 					MSR_IA32_SPEC_CTRL,
11626 					MSR_TYPE_R | MSR_TYPE_W);
11627 
11628 	if (pred_cmd)
11629 		nested_vmx_disable_intercept_for_msr(
11630 					msr_bitmap_l1, msr_bitmap_l0,
11631 					MSR_IA32_PRED_CMD,
11632 					MSR_TYPE_W);
11633 
11634 	kunmap(page);
11635 	kvm_release_page_clean(page);
11636 
11637 	return true;
11638 }
11639 
nested_cache_shadow_vmcs12(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11640 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
11641 				       struct vmcs12 *vmcs12)
11642 {
11643 	struct vmcs12 *shadow;
11644 	struct page *page;
11645 
11646 	if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
11647 	    vmcs12->vmcs_link_pointer == -1ull)
11648 		return;
11649 
11650 	shadow = get_shadow_vmcs12(vcpu);
11651 	page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
11652 
11653 	memcpy(shadow, kmap(page), VMCS12_SIZE);
11654 
11655 	kunmap(page);
11656 	kvm_release_page_clean(page);
11657 }
11658 
nested_flush_cached_shadow_vmcs12(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11659 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
11660 					      struct vmcs12 *vmcs12)
11661 {
11662 	struct vcpu_vmx *vmx = to_vmx(vcpu);
11663 
11664 	if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
11665 	    vmcs12->vmcs_link_pointer == -1ull)
11666 		return;
11667 
11668 	kvm_write_guest(vmx->vcpu.kvm, vmcs12->vmcs_link_pointer,
11669 			get_shadow_vmcs12(vcpu), VMCS12_SIZE);
11670 }
11671 
nested_vmx_check_apic_access_controls(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11672 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
11673 					  struct vmcs12 *vmcs12)
11674 {
11675 	if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
11676 	    !page_address_valid(vcpu, vmcs12->apic_access_addr))
11677 		return -EINVAL;
11678 	else
11679 		return 0;
11680 }
11681 
nested_vmx_check_apicv_controls(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11682 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
11683 					   struct vmcs12 *vmcs12)
11684 {
11685 	if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11686 	    !nested_cpu_has_apic_reg_virt(vmcs12) &&
11687 	    !nested_cpu_has_vid(vmcs12) &&
11688 	    !nested_cpu_has_posted_intr(vmcs12))
11689 		return 0;
11690 
11691 	/*
11692 	 * If virtualize x2apic mode is enabled,
11693 	 * virtualize apic access must be disabled.
11694 	 */
11695 	if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11696 	    nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
11697 		return -EINVAL;
11698 
11699 	/*
11700 	 * If virtual interrupt delivery is enabled,
11701 	 * we must exit on external interrupts.
11702 	 */
11703 	if (nested_cpu_has_vid(vmcs12) &&
11704 	   !nested_exit_on_intr(vcpu))
11705 		return -EINVAL;
11706 
11707 	/*
11708 	 * bits 15:8 should be zero in posted_intr_nv,
11709 	 * the descriptor address has been already checked
11710 	 * in nested_get_vmcs12_pages.
11711 	 *
11712 	 * bits 5:0 of posted_intr_desc_addr should be zero.
11713 	 */
11714 	if (nested_cpu_has_posted_intr(vmcs12) &&
11715 	   (!nested_cpu_has_vid(vmcs12) ||
11716 	    !nested_exit_intr_ack_set(vcpu) ||
11717 	    (vmcs12->posted_intr_nv & 0xff00) ||
11718 	    (vmcs12->posted_intr_desc_addr & 0x3f) ||
11719 	    (!page_address_valid(vcpu, vmcs12->posted_intr_desc_addr))))
11720 		return -EINVAL;
11721 
11722 	/* tpr shadow is needed by all apicv features. */
11723 	if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
11724 		return -EINVAL;
11725 
11726 	return 0;
11727 }
11728 
nested_vmx_check_msr_switch(struct kvm_vcpu * vcpu,unsigned long count_field,unsigned long addr_field)11729 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
11730 				       unsigned long count_field,
11731 				       unsigned long addr_field)
11732 {
11733 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11734 	int maxphyaddr;
11735 	u64 count, addr;
11736 
11737 	if (vmcs12_read_any(vmcs12, count_field, &count) ||
11738 	    vmcs12_read_any(vmcs12, addr_field, &addr)) {
11739 		WARN_ON(1);
11740 		return -EINVAL;
11741 	}
11742 	if (count == 0)
11743 		return 0;
11744 	maxphyaddr = cpuid_maxphyaddr(vcpu);
11745 	if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
11746 	    (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
11747 		pr_debug_ratelimited(
11748 			"nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
11749 			addr_field, maxphyaddr, count, addr);
11750 		return -EINVAL;
11751 	}
11752 	return 0;
11753 }
11754 
nested_vmx_check_msr_switch_controls(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11755 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
11756 						struct vmcs12 *vmcs12)
11757 {
11758 	if (vmcs12->vm_exit_msr_load_count == 0 &&
11759 	    vmcs12->vm_exit_msr_store_count == 0 &&
11760 	    vmcs12->vm_entry_msr_load_count == 0)
11761 		return 0; /* Fast path */
11762 	if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
11763 					VM_EXIT_MSR_LOAD_ADDR) ||
11764 	    nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
11765 					VM_EXIT_MSR_STORE_ADDR) ||
11766 	    nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
11767 					VM_ENTRY_MSR_LOAD_ADDR))
11768 		return -EINVAL;
11769 	return 0;
11770 }
11771 
nested_vmx_check_pml_controls(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11772 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
11773 					 struct vmcs12 *vmcs12)
11774 {
11775 	u64 address = vmcs12->pml_address;
11776 	int maxphyaddr = cpuid_maxphyaddr(vcpu);
11777 
11778 	if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
11779 		if (!nested_cpu_has_ept(vmcs12) ||
11780 		    !IS_ALIGNED(address, 4096)  ||
11781 		    address >> maxphyaddr)
11782 			return -EINVAL;
11783 	}
11784 
11785 	return 0;
11786 }
11787 
nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11788 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
11789 						 struct vmcs12 *vmcs12)
11790 {
11791 	if (!nested_cpu_has_shadow_vmcs(vmcs12))
11792 		return 0;
11793 
11794 	if (!page_address_valid(vcpu, vmcs12->vmread_bitmap) ||
11795 	    !page_address_valid(vcpu, vmcs12->vmwrite_bitmap))
11796 		return -EINVAL;
11797 
11798 	return 0;
11799 }
11800 
nested_vmx_msr_check_common(struct kvm_vcpu * vcpu,struct vmx_msr_entry * e)11801 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
11802 				       struct vmx_msr_entry *e)
11803 {
11804 	/* x2APIC MSR accesses are not allowed */
11805 	if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
11806 		return -EINVAL;
11807 	if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
11808 	    e->index == MSR_IA32_UCODE_REV)
11809 		return -EINVAL;
11810 	if (e->reserved != 0)
11811 		return -EINVAL;
11812 	return 0;
11813 }
11814 
nested_vmx_load_msr_check(struct kvm_vcpu * vcpu,struct vmx_msr_entry * e)11815 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
11816 				     struct vmx_msr_entry *e)
11817 {
11818 	if (e->index == MSR_FS_BASE ||
11819 	    e->index == MSR_GS_BASE ||
11820 	    e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
11821 	    nested_vmx_msr_check_common(vcpu, e))
11822 		return -EINVAL;
11823 	return 0;
11824 }
11825 
nested_vmx_store_msr_check(struct kvm_vcpu * vcpu,struct vmx_msr_entry * e)11826 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
11827 				      struct vmx_msr_entry *e)
11828 {
11829 	if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
11830 	    nested_vmx_msr_check_common(vcpu, e))
11831 		return -EINVAL;
11832 	return 0;
11833 }
11834 
11835 /*
11836  * Load guest's/host's msr at nested entry/exit.
11837  * return 0 for success, entry index for failure.
11838  */
nested_vmx_load_msr(struct kvm_vcpu * vcpu,u64 gpa,u32 count)11839 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
11840 {
11841 	u32 i;
11842 	struct vmx_msr_entry e;
11843 	struct msr_data msr;
11844 
11845 	msr.host_initiated = false;
11846 	for (i = 0; i < count; i++) {
11847 		if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
11848 					&e, sizeof(e))) {
11849 			pr_debug_ratelimited(
11850 				"%s cannot read MSR entry (%u, 0x%08llx)\n",
11851 				__func__, i, gpa + i * sizeof(e));
11852 			goto fail;
11853 		}
11854 		if (nested_vmx_load_msr_check(vcpu, &e)) {
11855 			pr_debug_ratelimited(
11856 				"%s check failed (%u, 0x%x, 0x%x)\n",
11857 				__func__, i, e.index, e.reserved);
11858 			goto fail;
11859 		}
11860 		msr.index = e.index;
11861 		msr.data = e.value;
11862 		if (kvm_set_msr(vcpu, &msr)) {
11863 			pr_debug_ratelimited(
11864 				"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
11865 				__func__, i, e.index, e.value);
11866 			goto fail;
11867 		}
11868 	}
11869 	return 0;
11870 fail:
11871 	return i + 1;
11872 }
11873 
nested_vmx_store_msr(struct kvm_vcpu * vcpu,u64 gpa,u32 count)11874 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
11875 {
11876 	u32 i;
11877 	struct vmx_msr_entry e;
11878 
11879 	for (i = 0; i < count; i++) {
11880 		struct msr_data msr_info;
11881 		if (kvm_vcpu_read_guest(vcpu,
11882 					gpa + i * sizeof(e),
11883 					&e, 2 * sizeof(u32))) {
11884 			pr_debug_ratelimited(
11885 				"%s cannot read MSR entry (%u, 0x%08llx)\n",
11886 				__func__, i, gpa + i * sizeof(e));
11887 			return -EINVAL;
11888 		}
11889 		if (nested_vmx_store_msr_check(vcpu, &e)) {
11890 			pr_debug_ratelimited(
11891 				"%s check failed (%u, 0x%x, 0x%x)\n",
11892 				__func__, i, e.index, e.reserved);
11893 			return -EINVAL;
11894 		}
11895 		msr_info.host_initiated = false;
11896 		msr_info.index = e.index;
11897 		if (kvm_get_msr(vcpu, &msr_info)) {
11898 			pr_debug_ratelimited(
11899 				"%s cannot read MSR (%u, 0x%x)\n",
11900 				__func__, i, e.index);
11901 			return -EINVAL;
11902 		}
11903 		if (kvm_vcpu_write_guest(vcpu,
11904 					 gpa + i * sizeof(e) +
11905 					     offsetof(struct vmx_msr_entry, value),
11906 					 &msr_info.data, sizeof(msr_info.data))) {
11907 			pr_debug_ratelimited(
11908 				"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
11909 				__func__, i, e.index, msr_info.data);
11910 			return -EINVAL;
11911 		}
11912 	}
11913 	return 0;
11914 }
11915 
nested_cr3_valid(struct kvm_vcpu * vcpu,unsigned long val)11916 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
11917 {
11918 	unsigned long invalid_mask;
11919 
11920 	invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
11921 	return (val & invalid_mask) == 0;
11922 }
11923 
11924 /*
11925  * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
11926  * emulating VM entry into a guest with EPT enabled.
11927  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
11928  * is assigned to entry_failure_code on failure.
11929  */
nested_vmx_load_cr3(struct kvm_vcpu * vcpu,unsigned long cr3,bool nested_ept,u32 * entry_failure_code)11930 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
11931 			       u32 *entry_failure_code)
11932 {
11933 	if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
11934 		if (!nested_cr3_valid(vcpu, cr3)) {
11935 			*entry_failure_code = ENTRY_FAIL_DEFAULT;
11936 			return 1;
11937 		}
11938 
11939 		/*
11940 		 * If PAE paging and EPT are both on, CR3 is not used by the CPU and
11941 		 * must not be dereferenced.
11942 		 */
11943 		if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
11944 		    !nested_ept) {
11945 			if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
11946 				*entry_failure_code = ENTRY_FAIL_PDPTE;
11947 				return 1;
11948 			}
11949 		}
11950 	}
11951 
11952 	if (!nested_ept)
11953 		kvm_mmu_new_cr3(vcpu, cr3, false);
11954 
11955 	vcpu->arch.cr3 = cr3;
11956 	__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
11957 
11958 	kvm_init_mmu(vcpu, false);
11959 
11960 	return 0;
11961 }
11962 
prepare_vmcs02_full(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)11963 static void prepare_vmcs02_full(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11964 {
11965 	struct vcpu_vmx *vmx = to_vmx(vcpu);
11966 
11967 	vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
11968 	vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
11969 	vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
11970 	vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
11971 	vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
11972 	vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
11973 	vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
11974 	vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
11975 	vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
11976 	vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
11977 	vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
11978 	vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
11979 	vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
11980 	vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
11981 	vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
11982 	vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
11983 	vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
11984 	vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
11985 	vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
11986 	vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
11987 	vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
11988 	vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
11989 	vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
11990 	vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
11991 	vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
11992 	vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
11993 	vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
11994 	vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
11995 	vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
11996 	vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
11997 	vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
11998 
11999 	vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
12000 	vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
12001 		vmcs12->guest_pending_dbg_exceptions);
12002 	vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
12003 	vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
12004 
12005 	if (nested_cpu_has_xsaves(vmcs12))
12006 		vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
12007 	vmcs_write64(VMCS_LINK_POINTER, -1ull);
12008 
12009 	if (cpu_has_vmx_posted_intr())
12010 		vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
12011 
12012 	/*
12013 	 * Whether page-faults are trapped is determined by a combination of
12014 	 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
12015 	 * If enable_ept, L0 doesn't care about page faults and we should
12016 	 * set all of these to L1's desires. However, if !enable_ept, L0 does
12017 	 * care about (at least some) page faults, and because it is not easy
12018 	 * (if at all possible?) to merge L0 and L1's desires, we simply ask
12019 	 * to exit on each and every L2 page fault. This is done by setting
12020 	 * MASK=MATCH=0 and (see below) EB.PF=1.
12021 	 * Note that below we don't need special code to set EB.PF beyond the
12022 	 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
12023 	 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
12024 	 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
12025 	 */
12026 	vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
12027 		enable_ept ? vmcs12->page_fault_error_code_mask : 0);
12028 	vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
12029 		enable_ept ? vmcs12->page_fault_error_code_match : 0);
12030 
12031 	/* All VMFUNCs are currently emulated through L0 vmexits.  */
12032 	if (cpu_has_vmx_vmfunc())
12033 		vmcs_write64(VM_FUNCTION_CONTROL, 0);
12034 
12035 	if (cpu_has_vmx_apicv()) {
12036 		vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
12037 		vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
12038 		vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
12039 		vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
12040 	}
12041 
12042 	/*
12043 	 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
12044 	 * Some constant fields are set here by vmx_set_constant_host_state().
12045 	 * Other fields are different per CPU, and will be set later when
12046 	 * vmx_vcpu_load() is called, and when vmx_prepare_switch_to_guest()
12047 	 * is called.
12048 	 */
12049 	vmx_set_constant_host_state(vmx);
12050 
12051 	/*
12052 	 * Set the MSR load/store lists to match L0's settings.
12053 	 */
12054 	vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
12055 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
12056 	vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
12057 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
12058 	vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
12059 
12060 	set_cr4_guest_host_mask(vmx);
12061 
12062 	if (kvm_mpx_supported()) {
12063 		if (vmx->nested.nested_run_pending &&
12064 			(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12065 			vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
12066 		else
12067 			vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
12068 	}
12069 
12070 	if (enable_vpid) {
12071 		if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
12072 			vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
12073 		else
12074 			vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
12075 	}
12076 
12077 	/*
12078 	 * L1 may access the L2's PDPTR, so save them to construct vmcs12
12079 	 */
12080 	if (enable_ept) {
12081 		vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
12082 		vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
12083 		vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
12084 		vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
12085 	}
12086 
12087 	if (cpu_has_vmx_msr_bitmap())
12088 		vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
12089 }
12090 
12091 /*
12092  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
12093  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
12094  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
12095  * guest in a way that will both be appropriate to L1's requests, and our
12096  * needs. In addition to modifying the active vmcs (which is vmcs02), this
12097  * function also has additional necessary side-effects, like setting various
12098  * vcpu->arch fields.
12099  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12100  * is assigned to entry_failure_code on failure.
12101  */
prepare_vmcs02(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12,u32 * entry_failure_code)12102 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12103 			  u32 *entry_failure_code)
12104 {
12105 	struct vcpu_vmx *vmx = to_vmx(vcpu);
12106 	u32 exec_control, vmcs12_exec_ctrl;
12107 
12108 	if (vmx->nested.dirty_vmcs12) {
12109 		prepare_vmcs02_full(vcpu, vmcs12);
12110 		vmx->nested.dirty_vmcs12 = false;
12111 	}
12112 
12113 	/*
12114 	 * First, the fields that are shadowed.  This must be kept in sync
12115 	 * with vmx_shadow_fields.h.
12116 	 */
12117 
12118 	vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
12119 	vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
12120 	vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
12121 	vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
12122 	vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
12123 
12124 	if (vmx->nested.nested_run_pending &&
12125 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
12126 		kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
12127 		vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
12128 	} else {
12129 		kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
12130 		vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
12131 	}
12132 	if (vmx->nested.nested_run_pending) {
12133 		vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
12134 			     vmcs12->vm_entry_intr_info_field);
12135 		vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
12136 			     vmcs12->vm_entry_exception_error_code);
12137 		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
12138 			     vmcs12->vm_entry_instruction_len);
12139 		vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
12140 			     vmcs12->guest_interruptibility_info);
12141 		vmx->loaded_vmcs->nmi_known_unmasked =
12142 			!(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
12143 	} else {
12144 		vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
12145 	}
12146 	vmx_set_rflags(vcpu, vmcs12->guest_rflags);
12147 
12148 	exec_control = vmcs12->pin_based_vm_exec_control;
12149 
12150 	/* Preemption timer setting is computed directly in vmx_vcpu_run.  */
12151 	exec_control |= vmcs_config.pin_based_exec_ctrl;
12152 	exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
12153 	vmx->loaded_vmcs->hv_timer_armed = false;
12154 
12155 	/* Posted interrupts setting is only taken from vmcs12.  */
12156 	if (nested_cpu_has_posted_intr(vmcs12)) {
12157 		vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
12158 		vmx->nested.pi_pending = false;
12159 	} else {
12160 		exec_control &= ~PIN_BASED_POSTED_INTR;
12161 	}
12162 
12163 	vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
12164 
12165 	vmx->nested.preemption_timer_expired = false;
12166 	if (nested_cpu_has_preemption_timer(vmcs12))
12167 		vmx_start_preemption_timer(vcpu);
12168 
12169 	if (cpu_has_secondary_exec_ctrls()) {
12170 		exec_control = vmx->secondary_exec_control;
12171 
12172 		/* Take the following fields only from vmcs12 */
12173 		exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
12174 				  SECONDARY_EXEC_ENABLE_INVPCID |
12175 				  SECONDARY_EXEC_RDTSCP |
12176 				  SECONDARY_EXEC_XSAVES |
12177 				  SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
12178 				  SECONDARY_EXEC_APIC_REGISTER_VIRT |
12179 				  SECONDARY_EXEC_ENABLE_VMFUNC);
12180 		if (nested_cpu_has(vmcs12,
12181 				   CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
12182 			vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
12183 				~SECONDARY_EXEC_ENABLE_PML;
12184 			exec_control |= vmcs12_exec_ctrl;
12185 		}
12186 
12187 		/* VMCS shadowing for L2 is emulated for now */
12188 		exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
12189 
12190 		if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
12191 			vmcs_write16(GUEST_INTR_STATUS,
12192 				vmcs12->guest_intr_status);
12193 
12194 		/*
12195 		 * Write an illegal value to APIC_ACCESS_ADDR. Later,
12196 		 * nested_get_vmcs12_pages will either fix it up or
12197 		 * remove the VM execution control.
12198 		 */
12199 		if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
12200 			vmcs_write64(APIC_ACCESS_ADDR, -1ull);
12201 
12202 		if (exec_control & SECONDARY_EXEC_ENCLS_EXITING)
12203 			vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
12204 
12205 		vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
12206 	}
12207 
12208 	/*
12209 	 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
12210 	 * entry, but only if the current (host) sp changed from the value
12211 	 * we wrote last (vmx->host_rsp). This cache is no longer relevant
12212 	 * if we switch vmcs, and rather than hold a separate cache per vmcs,
12213 	 * here we just force the write to happen on entry.
12214 	 */
12215 	vmx->host_rsp = 0;
12216 
12217 	exec_control = vmx_exec_control(vmx); /* L0's desires */
12218 	exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
12219 	exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
12220 	exec_control &= ~CPU_BASED_TPR_SHADOW;
12221 	exec_control |= vmcs12->cpu_based_vm_exec_control;
12222 
12223 	/*
12224 	 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
12225 	 * nested_get_vmcs12_pages can't fix it up, the illegal value
12226 	 * will result in a VM entry failure.
12227 	 */
12228 	if (exec_control & CPU_BASED_TPR_SHADOW) {
12229 		vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
12230 		vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
12231 	} else {
12232 #ifdef CONFIG_X86_64
12233 		exec_control |= CPU_BASED_CR8_LOAD_EXITING |
12234 				CPU_BASED_CR8_STORE_EXITING;
12235 #endif
12236 	}
12237 
12238 	/*
12239 	 * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
12240 	 * for I/O port accesses.
12241 	 */
12242 	exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
12243 	exec_control |= CPU_BASED_UNCOND_IO_EXITING;
12244 
12245 	vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
12246 
12247 	/* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
12248 	 * bitwise-or of what L1 wants to trap for L2, and what we want to
12249 	 * trap. Note that CR0.TS also needs updating - we do this later.
12250 	 */
12251 	update_exception_bitmap(vcpu);
12252 	vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
12253 	vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
12254 
12255 	/* L2->L1 exit controls are emulated - the hardware exit is to L0 so
12256 	 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
12257 	 * bits are further modified by vmx_set_efer() below.
12258 	 */
12259 	vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
12260 
12261 	/* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
12262 	 * emulated by vmx_set_efer(), below.
12263 	 */
12264 	vm_entry_controls_init(vmx,
12265 		(vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
12266 			~VM_ENTRY_IA32E_MODE) |
12267 		(vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
12268 
12269 	if (vmx->nested.nested_run_pending &&
12270 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
12271 		vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
12272 		vcpu->arch.pat = vmcs12->guest_ia32_pat;
12273 	} else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
12274 		vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
12275 	}
12276 
12277 	vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
12278 
12279 	if (kvm_has_tsc_control)
12280 		decache_tsc_multiplier(vmx);
12281 
12282 	if (enable_vpid) {
12283 		/*
12284 		 * There is no direct mapping between vpid02 and vpid12, the
12285 		 * vpid02 is per-vCPU for L0 and reused while the value of
12286 		 * vpid12 is changed w/ one invvpid during nested vmentry.
12287 		 * The vpid12 is allocated by L1 for L2, so it will not
12288 		 * influence global bitmap(for vpid01 and vpid02 allocation)
12289 		 * even if spawn a lot of nested vCPUs.
12290 		 */
12291 		if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
12292 			if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
12293 				vmx->nested.last_vpid = vmcs12->virtual_processor_id;
12294 				__vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
12295 			}
12296 		} else {
12297 			vmx_flush_tlb(vcpu, true);
12298 		}
12299 	}
12300 
12301 	if (enable_pml) {
12302 		/*
12303 		 * Conceptually we want to copy the PML address and index from
12304 		 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
12305 		 * since we always flush the log on each vmexit, this happens
12306 		 * to be equivalent to simply resetting the fields in vmcs02.
12307 		 */
12308 		ASSERT(vmx->pml_pg);
12309 		vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
12310 		vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
12311 	}
12312 
12313 	if (nested_cpu_has_ept(vmcs12)) {
12314 		if (nested_ept_init_mmu_context(vcpu)) {
12315 			*entry_failure_code = ENTRY_FAIL_DEFAULT;
12316 			return 1;
12317 		}
12318 	} else if (nested_cpu_has2(vmcs12,
12319 				   SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
12320 		vmx_flush_tlb(vcpu, true);
12321 	}
12322 
12323 	/*
12324 	 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
12325 	 * bits which we consider mandatory enabled.
12326 	 * The CR0_READ_SHADOW is what L2 should have expected to read given
12327 	 * the specifications by L1; It's not enough to take
12328 	 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
12329 	 * have more bits than L1 expected.
12330 	 */
12331 	vmx_set_cr0(vcpu, vmcs12->guest_cr0);
12332 	vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
12333 
12334 	vmx_set_cr4(vcpu, vmcs12->guest_cr4);
12335 	vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
12336 
12337 	if (vmx->nested.nested_run_pending &&
12338 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
12339 		vcpu->arch.efer = vmcs12->guest_ia32_efer;
12340 	else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
12341 		vcpu->arch.efer |= (EFER_LMA | EFER_LME);
12342 	else
12343 		vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
12344 	/* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
12345 	vmx_set_efer(vcpu, vcpu->arch.efer);
12346 
12347 	/*
12348 	 * Guest state is invalid and unrestricted guest is disabled,
12349 	 * which means L1 attempted VMEntry to L2 with invalid state.
12350 	 * Fail the VMEntry.
12351 	 */
12352 	if (vmx->emulation_required) {
12353 		*entry_failure_code = ENTRY_FAIL_DEFAULT;
12354 		return 1;
12355 	}
12356 
12357 	/* Shadow page tables on either EPT or shadow page tables. */
12358 	if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
12359 				entry_failure_code))
12360 		return 1;
12361 
12362 	if (!enable_ept)
12363 		vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
12364 
12365 	kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
12366 	kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
12367 	return 0;
12368 }
12369 
nested_vmx_check_nmi_controls(struct vmcs12 * vmcs12)12370 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
12371 {
12372 	if (!nested_cpu_has_nmi_exiting(vmcs12) &&
12373 	    nested_cpu_has_virtual_nmis(vmcs12))
12374 		return -EINVAL;
12375 
12376 	if (!nested_cpu_has_virtual_nmis(vmcs12) &&
12377 	    nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING))
12378 		return -EINVAL;
12379 
12380 	return 0;
12381 }
12382 
check_vmentry_prereqs(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)12383 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12384 {
12385 	struct vcpu_vmx *vmx = to_vmx(vcpu);
12386 
12387 	if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
12388 	    vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
12389 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12390 
12391 	if (nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id)
12392 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12393 
12394 	if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
12395 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12396 
12397 	if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
12398 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12399 
12400 	if (nested_vmx_check_apic_access_controls(vcpu, vmcs12))
12401 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12402 
12403 	if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
12404 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12405 
12406 	if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
12407 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12408 
12409 	if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
12410 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12411 
12412 	if (nested_vmx_check_pml_controls(vcpu, vmcs12))
12413 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12414 
12415 	if (nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12))
12416 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12417 
12418 	if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
12419 				vmx->nested.msrs.procbased_ctls_low,
12420 				vmx->nested.msrs.procbased_ctls_high) ||
12421 	    (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
12422 	     !vmx_control_verify(vmcs12->secondary_vm_exec_control,
12423 				 vmx->nested.msrs.secondary_ctls_low,
12424 				 vmx->nested.msrs.secondary_ctls_high)) ||
12425 	    !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
12426 				vmx->nested.msrs.pinbased_ctls_low,
12427 				vmx->nested.msrs.pinbased_ctls_high) ||
12428 	    !vmx_control_verify(vmcs12->vm_exit_controls,
12429 				vmx->nested.msrs.exit_ctls_low,
12430 				vmx->nested.msrs.exit_ctls_high) ||
12431 	    !vmx_control_verify(vmcs12->vm_entry_controls,
12432 				vmx->nested.msrs.entry_ctls_low,
12433 				vmx->nested.msrs.entry_ctls_high))
12434 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12435 
12436 	if (nested_vmx_check_nmi_controls(vmcs12))
12437 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12438 
12439 	if (nested_cpu_has_vmfunc(vmcs12)) {
12440 		if (vmcs12->vm_function_control &
12441 		    ~vmx->nested.msrs.vmfunc_controls)
12442 			return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12443 
12444 		if (nested_cpu_has_eptp_switching(vmcs12)) {
12445 			if (!nested_cpu_has_ept(vmcs12) ||
12446 			    !page_address_valid(vcpu, vmcs12->eptp_list_address))
12447 				return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12448 		}
12449 	}
12450 
12451 	if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
12452 		return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12453 
12454 	if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
12455 	    !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
12456 	    !nested_cr3_valid(vcpu, vmcs12->host_cr3))
12457 		return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
12458 
12459 	/*
12460 	 * From the Intel SDM, volume 3:
12461 	 * Fields relevant to VM-entry event injection must be set properly.
12462 	 * These fields are the VM-entry interruption-information field, the
12463 	 * VM-entry exception error code, and the VM-entry instruction length.
12464 	 */
12465 	if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
12466 		u32 intr_info = vmcs12->vm_entry_intr_info_field;
12467 		u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
12468 		u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
12469 		bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
12470 		bool should_have_error_code;
12471 		bool urg = nested_cpu_has2(vmcs12,
12472 					   SECONDARY_EXEC_UNRESTRICTED_GUEST);
12473 		bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
12474 
12475 		/* VM-entry interruption-info field: interruption type */
12476 		if (intr_type == INTR_TYPE_RESERVED ||
12477 		    (intr_type == INTR_TYPE_OTHER_EVENT &&
12478 		     !nested_cpu_supports_monitor_trap_flag(vcpu)))
12479 			return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12480 
12481 		/* VM-entry interruption-info field: vector */
12482 		if ((intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
12483 		    (intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
12484 		    (intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
12485 			return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12486 
12487 		/* VM-entry interruption-info field: deliver error code */
12488 		should_have_error_code =
12489 			intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
12490 			x86_exception_has_error_code(vector);
12491 		if (has_error_code != should_have_error_code)
12492 			return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12493 
12494 		/* VM-entry exception error code */
12495 		if (has_error_code &&
12496 		    vmcs12->vm_entry_exception_error_code & GENMASK(31, 15))
12497 			return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12498 
12499 		/* VM-entry interruption-info field: reserved bits */
12500 		if (intr_info & INTR_INFO_RESVD_BITS_MASK)
12501 			return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12502 
12503 		/* VM-entry instruction length */
12504 		switch (intr_type) {
12505 		case INTR_TYPE_SOFT_EXCEPTION:
12506 		case INTR_TYPE_SOFT_INTR:
12507 		case INTR_TYPE_PRIV_SW_EXCEPTION:
12508 			if ((vmcs12->vm_entry_instruction_len > 15) ||
12509 			    (vmcs12->vm_entry_instruction_len == 0 &&
12510 			     !nested_cpu_has_zero_length_injection(vcpu)))
12511 				return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12512 		}
12513 	}
12514 
12515 	return 0;
12516 }
12517 
nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)12518 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
12519 					  struct vmcs12 *vmcs12)
12520 {
12521 	int r;
12522 	struct page *page;
12523 	struct vmcs12 *shadow;
12524 
12525 	if (vmcs12->vmcs_link_pointer == -1ull)
12526 		return 0;
12527 
12528 	if (!page_address_valid(vcpu, vmcs12->vmcs_link_pointer))
12529 		return -EINVAL;
12530 
12531 	page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
12532 	if (is_error_page(page))
12533 		return -EINVAL;
12534 
12535 	r = 0;
12536 	shadow = kmap(page);
12537 	if (shadow->hdr.revision_id != VMCS12_REVISION ||
12538 	    shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12))
12539 		r = -EINVAL;
12540 	kunmap(page);
12541 	kvm_release_page_clean(page);
12542 	return r;
12543 }
12544 
check_vmentry_postreqs(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12,u32 * exit_qual)12545 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12546 				  u32 *exit_qual)
12547 {
12548 	bool ia32e;
12549 
12550 	*exit_qual = ENTRY_FAIL_DEFAULT;
12551 
12552 	if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
12553 	    !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
12554 		return 1;
12555 
12556 	if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
12557 		*exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
12558 		return 1;
12559 	}
12560 
12561 	/*
12562 	 * If the load IA32_EFER VM-entry control is 1, the following checks
12563 	 * are performed on the field for the IA32_EFER MSR:
12564 	 * - Bits reserved in the IA32_EFER MSR must be 0.
12565 	 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
12566 	 *   the IA-32e mode guest VM-exit control. It must also be identical
12567 	 *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
12568 	 *   CR0.PG) is 1.
12569 	 */
12570 	if (to_vmx(vcpu)->nested.nested_run_pending &&
12571 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
12572 		ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
12573 		if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
12574 		    ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
12575 		    ((vmcs12->guest_cr0 & X86_CR0_PG) &&
12576 		     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
12577 			return 1;
12578 	}
12579 
12580 	/*
12581 	 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
12582 	 * IA32_EFER MSR must be 0 in the field for that register. In addition,
12583 	 * the values of the LMA and LME bits in the field must each be that of
12584 	 * the host address-space size VM-exit control.
12585 	 */
12586 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
12587 		ia32e = (vmcs12->vm_exit_controls &
12588 			 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
12589 		if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
12590 		    ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
12591 		    ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
12592 			return 1;
12593 	}
12594 
12595 	if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
12596 		(is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
12597 		(vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
12598 			return 1;
12599 
12600 	return 0;
12601 }
12602 
12603 /*
12604  * If exit_qual is NULL, this is being called from state restore (either RSM
12605  * or KVM_SET_NESTED_STATE).  Otherwise it's called from vmlaunch/vmresume.
12606  */
enter_vmx_non_root_mode(struct kvm_vcpu * vcpu,u32 * exit_qual)12607 static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, u32 *exit_qual)
12608 {
12609 	struct vcpu_vmx *vmx = to_vmx(vcpu);
12610 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12611 	bool from_vmentry = !!exit_qual;
12612 	u32 dummy_exit_qual;
12613 	bool evaluate_pending_interrupts;
12614 	int r = 0;
12615 
12616 	evaluate_pending_interrupts = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
12617 		(CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_VIRTUAL_NMI_PENDING);
12618 	if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
12619 		evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
12620 
12621 	enter_guest_mode(vcpu);
12622 
12623 	if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
12624 		vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
12625 	if (kvm_mpx_supported() &&
12626 		!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12627 		vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
12628 
12629 	vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
12630 	vmx_segment_cache_clear(vmx);
12631 
12632 	if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12633 		vcpu->arch.tsc_offset += vmcs12->tsc_offset;
12634 
12635 	r = EXIT_REASON_INVALID_STATE;
12636 	if (prepare_vmcs02(vcpu, vmcs12, from_vmentry ? exit_qual : &dummy_exit_qual))
12637 		goto fail;
12638 
12639 	if (from_vmentry) {
12640 		nested_get_vmcs12_pages(vcpu);
12641 
12642 		r = EXIT_REASON_MSR_LOAD_FAIL;
12643 		*exit_qual = nested_vmx_load_msr(vcpu,
12644 	     					 vmcs12->vm_entry_msr_load_addr,
12645 					      	 vmcs12->vm_entry_msr_load_count);
12646 		if (*exit_qual)
12647 			goto fail;
12648 	} else {
12649 		/*
12650 		 * The MMU is not initialized to point at the right entities yet and
12651 		 * "get pages" would need to read data from the guest (i.e. we will
12652 		 * need to perform gpa to hpa translation). Request a call
12653 		 * to nested_get_vmcs12_pages before the next VM-entry.  The MSRs
12654 		 * have already been set at vmentry time and should not be reset.
12655 		 */
12656 		kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
12657 	}
12658 
12659 	/*
12660 	 * If L1 had a pending IRQ/NMI until it executed
12661 	 * VMLAUNCH/VMRESUME which wasn't delivered because it was
12662 	 * disallowed (e.g. interrupts disabled), L0 needs to
12663 	 * evaluate if this pending event should cause an exit from L2
12664 	 * to L1 or delivered directly to L2 (e.g. In case L1 don't
12665 	 * intercept EXTERNAL_INTERRUPT).
12666 	 *
12667 	 * Usually this would be handled by the processor noticing an
12668 	 * IRQ/NMI window request, or checking RVI during evaluation of
12669 	 * pending virtual interrupts.  However, this setting was done
12670 	 * on VMCS01 and now VMCS02 is active instead. Thus, we force L0
12671 	 * to perform pending event evaluation by requesting a KVM_REQ_EVENT.
12672 	 */
12673 	if (unlikely(evaluate_pending_interrupts))
12674 		kvm_make_request(KVM_REQ_EVENT, vcpu);
12675 
12676 	/*
12677 	 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
12678 	 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
12679 	 * returned as far as L1 is concerned. It will only return (and set
12680 	 * the success flag) when L2 exits (see nested_vmx_vmexit()).
12681 	 */
12682 	return 0;
12683 
12684 fail:
12685 	if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12686 		vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
12687 	leave_guest_mode(vcpu);
12688 	vmx_switch_vmcs(vcpu, &vmx->vmcs01);
12689 	return r;
12690 }
12691 
12692 /*
12693  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
12694  * for running an L2 nested guest.
12695  */
nested_vmx_run(struct kvm_vcpu * vcpu,bool launch)12696 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
12697 {
12698 	struct vmcs12 *vmcs12;
12699 	struct vcpu_vmx *vmx = to_vmx(vcpu);
12700 	u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
12701 	u32 exit_qual;
12702 	int ret;
12703 
12704 	if (!nested_vmx_check_permission(vcpu))
12705 		return 1;
12706 
12707 	if (!nested_vmx_check_vmcs12(vcpu))
12708 		goto out;
12709 
12710 	vmcs12 = get_vmcs12(vcpu);
12711 
12712 	/*
12713 	 * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
12714 	 * that there *is* a valid VMCS pointer, RFLAGS.CF is set
12715 	 * rather than RFLAGS.ZF, and no error number is stored to the
12716 	 * VM-instruction error field.
12717 	 */
12718 	if (vmcs12->hdr.shadow_vmcs) {
12719 		nested_vmx_failInvalid(vcpu);
12720 		goto out;
12721 	}
12722 
12723 	if (enable_shadow_vmcs)
12724 		copy_shadow_to_vmcs12(vmx);
12725 
12726 	/*
12727 	 * The nested entry process starts with enforcing various prerequisites
12728 	 * on vmcs12 as required by the Intel SDM, and act appropriately when
12729 	 * they fail: As the SDM explains, some conditions should cause the
12730 	 * instruction to fail, while others will cause the instruction to seem
12731 	 * to succeed, but return an EXIT_REASON_INVALID_STATE.
12732 	 * To speed up the normal (success) code path, we should avoid checking
12733 	 * for misconfigurations which will anyway be caught by the processor
12734 	 * when using the merged vmcs02.
12735 	 */
12736 	if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
12737 		nested_vmx_failValid(vcpu,
12738 				     VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
12739 		goto out;
12740 	}
12741 
12742 	if (vmcs12->launch_state == launch) {
12743 		nested_vmx_failValid(vcpu,
12744 			launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
12745 			       : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
12746 		goto out;
12747 	}
12748 
12749 	ret = check_vmentry_prereqs(vcpu, vmcs12);
12750 	if (ret) {
12751 		nested_vmx_failValid(vcpu, ret);
12752 		goto out;
12753 	}
12754 
12755 	/*
12756 	 * After this point, the trap flag no longer triggers a singlestep trap
12757 	 * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
12758 	 * This is not 100% correct; for performance reasons, we delegate most
12759 	 * of the checks on host state to the processor.  If those fail,
12760 	 * the singlestep trap is missed.
12761 	 */
12762 	skip_emulated_instruction(vcpu);
12763 
12764 	ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
12765 	if (ret) {
12766 		nested_vmx_entry_failure(vcpu, vmcs12,
12767 					 EXIT_REASON_INVALID_STATE, exit_qual);
12768 		return 1;
12769 	}
12770 
12771 	/*
12772 	 * We're finally done with prerequisite checking, and can start with
12773 	 * the nested entry.
12774 	 */
12775 
12776 	vmx->nested.nested_run_pending = 1;
12777 	ret = enter_vmx_non_root_mode(vcpu, &exit_qual);
12778 	if (ret) {
12779 		nested_vmx_entry_failure(vcpu, vmcs12, ret, exit_qual);
12780 		vmx->nested.nested_run_pending = 0;
12781 		return 1;
12782 	}
12783 
12784 	/* Hide L1D cache contents from the nested guest.  */
12785 	vmx->vcpu.arch.l1tf_flush_l1d = true;
12786 
12787 	/*
12788 	 * Must happen outside of enter_vmx_non_root_mode() as it will
12789 	 * also be used as part of restoring nVMX state for
12790 	 * snapshot restore (migration).
12791 	 *
12792 	 * In this flow, it is assumed that vmcs12 cache was
12793 	 * trasferred as part of captured nVMX state and should
12794 	 * therefore not be read from guest memory (which may not
12795 	 * exist on destination host yet).
12796 	 */
12797 	nested_cache_shadow_vmcs12(vcpu, vmcs12);
12798 
12799 	/*
12800 	 * If we're entering a halted L2 vcpu and the L2 vcpu won't be woken
12801 	 * by event injection, halt vcpu.
12802 	 */
12803 	if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
12804 	    !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK)) {
12805 		vmx->nested.nested_run_pending = 0;
12806 		return kvm_vcpu_halt(vcpu);
12807 	}
12808 	return 1;
12809 
12810 out:
12811 	return kvm_skip_emulated_instruction(vcpu);
12812 }
12813 
12814 /*
12815  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
12816  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
12817  * This function returns the new value we should put in vmcs12.guest_cr0.
12818  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
12819  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
12820  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
12821  *     didn't trap the bit, because if L1 did, so would L0).
12822  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
12823  *     been modified by L2, and L1 knows it. So just leave the old value of
12824  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
12825  *     isn't relevant, because if L0 traps this bit it can set it to anything.
12826  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
12827  *     changed these bits, and therefore they need to be updated, but L0
12828  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
12829  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
12830  */
12831 static inline unsigned long
vmcs12_guest_cr0(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)12832 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12833 {
12834 	return
12835 	/*1*/	(vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
12836 	/*2*/	(vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
12837 	/*3*/	(vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
12838 			vcpu->arch.cr0_guest_owned_bits));
12839 }
12840 
12841 static inline unsigned long
vmcs12_guest_cr4(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)12842 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12843 {
12844 	return
12845 	/*1*/	(vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
12846 	/*2*/	(vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
12847 	/*3*/	(vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
12848 			vcpu->arch.cr4_guest_owned_bits));
12849 }
12850 
vmcs12_save_pending_event(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)12851 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
12852 				       struct vmcs12 *vmcs12)
12853 {
12854 	u32 idt_vectoring;
12855 	unsigned int nr;
12856 
12857 	if (vcpu->arch.exception.injected) {
12858 		nr = vcpu->arch.exception.nr;
12859 		idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
12860 
12861 		if (kvm_exception_is_soft(nr)) {
12862 			vmcs12->vm_exit_instruction_len =
12863 				vcpu->arch.event_exit_inst_len;
12864 			idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
12865 		} else
12866 			idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
12867 
12868 		if (vcpu->arch.exception.has_error_code) {
12869 			idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
12870 			vmcs12->idt_vectoring_error_code =
12871 				vcpu->arch.exception.error_code;
12872 		}
12873 
12874 		vmcs12->idt_vectoring_info_field = idt_vectoring;
12875 	} else if (vcpu->arch.nmi_injected) {
12876 		vmcs12->idt_vectoring_info_field =
12877 			INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
12878 	} else if (vcpu->arch.interrupt.injected) {
12879 		nr = vcpu->arch.interrupt.nr;
12880 		idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
12881 
12882 		if (vcpu->arch.interrupt.soft) {
12883 			idt_vectoring |= INTR_TYPE_SOFT_INTR;
12884 			vmcs12->vm_entry_instruction_len =
12885 				vcpu->arch.event_exit_inst_len;
12886 		} else
12887 			idt_vectoring |= INTR_TYPE_EXT_INTR;
12888 
12889 		vmcs12->idt_vectoring_info_field = idt_vectoring;
12890 	}
12891 }
12892 
vmx_check_nested_events(struct kvm_vcpu * vcpu,bool external_intr)12893 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
12894 {
12895 	struct vcpu_vmx *vmx = to_vmx(vcpu);
12896 	unsigned long exit_qual;
12897 	bool block_nested_events =
12898 	    vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
12899 
12900 	if (vcpu->arch.exception.pending &&
12901 		nested_vmx_check_exception(vcpu, &exit_qual)) {
12902 		if (block_nested_events)
12903 			return -EBUSY;
12904 		nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
12905 		return 0;
12906 	}
12907 
12908 	if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
12909 	    vmx->nested.preemption_timer_expired) {
12910 		if (block_nested_events)
12911 			return -EBUSY;
12912 		nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
12913 		return 0;
12914 	}
12915 
12916 	if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
12917 		if (block_nested_events)
12918 			return -EBUSY;
12919 		nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
12920 				  NMI_VECTOR | INTR_TYPE_NMI_INTR |
12921 				  INTR_INFO_VALID_MASK, 0);
12922 		/*
12923 		 * The NMI-triggered VM exit counts as injection:
12924 		 * clear this one and block further NMIs.
12925 		 */
12926 		vcpu->arch.nmi_pending = 0;
12927 		vmx_set_nmi_mask(vcpu, true);
12928 		return 0;
12929 	}
12930 
12931 	if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
12932 	    nested_exit_on_intr(vcpu)) {
12933 		if (block_nested_events)
12934 			return -EBUSY;
12935 		nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
12936 		return 0;
12937 	}
12938 
12939 	vmx_complete_nested_posted_interrupt(vcpu);
12940 	return 0;
12941 }
12942 
vmx_request_immediate_exit(struct kvm_vcpu * vcpu)12943 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
12944 {
12945 	to_vmx(vcpu)->req_immediate_exit = true;
12946 }
12947 
vmx_get_preemption_timer_value(struct kvm_vcpu * vcpu)12948 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
12949 {
12950 	ktime_t remaining =
12951 		hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
12952 	u64 value;
12953 
12954 	if (ktime_to_ns(remaining) <= 0)
12955 		return 0;
12956 
12957 	value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
12958 	do_div(value, 1000000);
12959 	return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
12960 }
12961 
12962 /*
12963  * Update the guest state fields of vmcs12 to reflect changes that
12964  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
12965  * VM-entry controls is also updated, since this is really a guest
12966  * state bit.)
12967  */
sync_vmcs12(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)12968 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12969 {
12970 	vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
12971 	vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
12972 
12973 	vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
12974 	vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
12975 	vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
12976 
12977 	vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
12978 	vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
12979 	vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
12980 	vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
12981 	vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
12982 	vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
12983 	vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
12984 	vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
12985 	vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
12986 	vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
12987 	vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
12988 	vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
12989 	vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
12990 	vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
12991 	vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
12992 	vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
12993 	vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
12994 	vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
12995 	vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
12996 	vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
12997 	vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
12998 	vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
12999 	vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
13000 	vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
13001 	vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
13002 	vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
13003 	vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
13004 	vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
13005 	vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
13006 	vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
13007 	vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
13008 	vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
13009 	vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
13010 	vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
13011 	vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
13012 	vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
13013 
13014 	vmcs12->guest_interruptibility_info =
13015 		vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
13016 	vmcs12->guest_pending_dbg_exceptions =
13017 		vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
13018 	if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
13019 		vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
13020 	else
13021 		vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
13022 
13023 	if (nested_cpu_has_preemption_timer(vmcs12)) {
13024 		if (vmcs12->vm_exit_controls &
13025 		    VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
13026 			vmcs12->vmx_preemption_timer_value =
13027 				vmx_get_preemption_timer_value(vcpu);
13028 		hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
13029 	}
13030 
13031 	/*
13032 	 * In some cases (usually, nested EPT), L2 is allowed to change its
13033 	 * own CR3 without exiting. If it has changed it, we must keep it.
13034 	 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
13035 	 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
13036 	 *
13037 	 * Additionally, restore L2's PDPTR to vmcs12.
13038 	 */
13039 	if (enable_ept) {
13040 		vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
13041 		vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
13042 		vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
13043 		vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
13044 		vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
13045 	}
13046 
13047 	vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
13048 
13049 	if (nested_cpu_has_vid(vmcs12))
13050 		vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
13051 
13052 	vmcs12->vm_entry_controls =
13053 		(vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
13054 		(vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
13055 
13056 	if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
13057 		kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
13058 		vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13059 	}
13060 
13061 	/* TODO: These cannot have changed unless we have MSR bitmaps and
13062 	 * the relevant bit asks not to trap the change */
13063 	if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
13064 		vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
13065 	if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
13066 		vmcs12->guest_ia32_efer = vcpu->arch.efer;
13067 	vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
13068 	vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
13069 	vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
13070 	if (kvm_mpx_supported())
13071 		vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13072 }
13073 
13074 /*
13075  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
13076  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
13077  * and this function updates it to reflect the changes to the guest state while
13078  * L2 was running (and perhaps made some exits which were handled directly by L0
13079  * without going back to L1), and to reflect the exit reason.
13080  * Note that we do not have to copy here all VMCS fields, just those that
13081  * could have changed by the L2 guest or the exit - i.e., the guest-state and
13082  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
13083  * which already writes to vmcs12 directly.
13084  */
prepare_vmcs12(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12,u32 exit_reason,u32 exit_intr_info,unsigned long exit_qualification)13085 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13086 			   u32 exit_reason, u32 exit_intr_info,
13087 			   unsigned long exit_qualification)
13088 {
13089 	/* update guest state fields: */
13090 	sync_vmcs12(vcpu, vmcs12);
13091 
13092 	/* update exit information fields: */
13093 
13094 	vmcs12->vm_exit_reason = exit_reason;
13095 	vmcs12->exit_qualification = exit_qualification;
13096 	vmcs12->vm_exit_intr_info = exit_intr_info;
13097 
13098 	vmcs12->idt_vectoring_info_field = 0;
13099 	vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
13100 	vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
13101 
13102 	if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
13103 		vmcs12->launch_state = 1;
13104 
13105 		/* vm_entry_intr_info_field is cleared on exit. Emulate this
13106 		 * instead of reading the real value. */
13107 		vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
13108 
13109 		/*
13110 		 * Transfer the event that L0 or L1 may wanted to inject into
13111 		 * L2 to IDT_VECTORING_INFO_FIELD.
13112 		 */
13113 		vmcs12_save_pending_event(vcpu, vmcs12);
13114 	}
13115 
13116 	/*
13117 	 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
13118 	 * preserved above and would only end up incorrectly in L1.
13119 	 */
13120 	vcpu->arch.nmi_injected = false;
13121 	kvm_clear_exception_queue(vcpu);
13122 	kvm_clear_interrupt_queue(vcpu);
13123 }
13124 
load_vmcs12_mmu_host_state(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)13125 static void load_vmcs12_mmu_host_state(struct kvm_vcpu *vcpu,
13126 			struct vmcs12 *vmcs12)
13127 {
13128 	u32 entry_failure_code;
13129 
13130 	nested_ept_uninit_mmu_context(vcpu);
13131 
13132 	/*
13133 	 * Only PDPTE load can fail as the value of cr3 was checked on entry and
13134 	 * couldn't have changed.
13135 	 */
13136 	if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
13137 		nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
13138 
13139 	if (!enable_ept)
13140 		vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
13141 }
13142 
13143 /*
13144  * A part of what we need to when the nested L2 guest exits and we want to
13145  * run its L1 parent, is to reset L1's guest state to the host state specified
13146  * in vmcs12.
13147  * This function is to be called not only on normal nested exit, but also on
13148  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
13149  * Failures During or After Loading Guest State").
13150  * This function should be called when the active VMCS is L1's (vmcs01).
13151  */
load_vmcs12_host_state(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12)13152 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13153 				   struct vmcs12 *vmcs12)
13154 {
13155 	struct kvm_segment seg;
13156 
13157 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
13158 		vcpu->arch.efer = vmcs12->host_ia32_efer;
13159 	else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13160 		vcpu->arch.efer |= (EFER_LMA | EFER_LME);
13161 	else
13162 		vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
13163 	vmx_set_efer(vcpu, vcpu->arch.efer);
13164 
13165 	kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
13166 	kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
13167 	vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
13168 	/*
13169 	 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
13170 	 * actually changed, because vmx_set_cr0 refers to efer set above.
13171 	 *
13172 	 * CR0_GUEST_HOST_MASK is already set in the original vmcs01
13173 	 * (KVM doesn't change it);
13174 	 */
13175 	vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
13176 	vmx_set_cr0(vcpu, vmcs12->host_cr0);
13177 
13178 	/* Same as above - no reason to call set_cr4_guest_host_mask().  */
13179 	vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13180 	vmx_set_cr4(vcpu, vmcs12->host_cr4);
13181 
13182 	load_vmcs12_mmu_host_state(vcpu, vmcs12);
13183 
13184 	/*
13185 	 * If vmcs01 don't use VPID, CPU flushes TLB on every
13186 	 * VMEntry/VMExit. Thus, no need to flush TLB.
13187 	 *
13188 	 * If vmcs12 uses VPID, TLB entries populated by L2 are
13189 	 * tagged with vmx->nested.vpid02 while L1 entries are tagged
13190 	 * with vmx->vpid. Thus, no need to flush TLB.
13191 	 *
13192 	 * Therefore, flush TLB only in case vmcs01 uses VPID and
13193 	 * vmcs12 don't use VPID as in this case L1 & L2 TLB entries
13194 	 * are both tagged with vmx->vpid.
13195 	 */
13196 	if (enable_vpid &&
13197 	    !(nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02)) {
13198 		vmx_flush_tlb(vcpu, true);
13199 	}
13200 
13201 	vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
13202 	vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
13203 	vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
13204 	vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
13205 	vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
13206 	vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
13207 	vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
13208 
13209 	/* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
13210 	if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
13211 		vmcs_write64(GUEST_BNDCFGS, 0);
13212 
13213 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
13214 		vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
13215 		vcpu->arch.pat = vmcs12->host_ia32_pat;
13216 	}
13217 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
13218 		vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
13219 			vmcs12->host_ia32_perf_global_ctrl);
13220 
13221 	/* Set L1 segment info according to Intel SDM
13222 	    27.5.2 Loading Host Segment and Descriptor-Table Registers */
13223 	seg = (struct kvm_segment) {
13224 		.base = 0,
13225 		.limit = 0xFFFFFFFF,
13226 		.selector = vmcs12->host_cs_selector,
13227 		.type = 11,
13228 		.present = 1,
13229 		.s = 1,
13230 		.g = 1
13231 	};
13232 	if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13233 		seg.l = 1;
13234 	else
13235 		seg.db = 1;
13236 	vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
13237 	seg = (struct kvm_segment) {
13238 		.base = 0,
13239 		.limit = 0xFFFFFFFF,
13240 		.type = 3,
13241 		.present = 1,
13242 		.s = 1,
13243 		.db = 1,
13244 		.g = 1
13245 	};
13246 	seg.selector = vmcs12->host_ds_selector;
13247 	vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
13248 	seg.selector = vmcs12->host_es_selector;
13249 	vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
13250 	seg.selector = vmcs12->host_ss_selector;
13251 	vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
13252 	seg.selector = vmcs12->host_fs_selector;
13253 	seg.base = vmcs12->host_fs_base;
13254 	vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
13255 	seg.selector = vmcs12->host_gs_selector;
13256 	seg.base = vmcs12->host_gs_base;
13257 	vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
13258 	seg = (struct kvm_segment) {
13259 		.base = vmcs12->host_tr_base,
13260 		.limit = 0x67,
13261 		.selector = vmcs12->host_tr_selector,
13262 		.type = 11,
13263 		.present = 1
13264 	};
13265 	vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
13266 
13267 	kvm_set_dr(vcpu, 7, 0x400);
13268 	vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
13269 
13270 	if (cpu_has_vmx_msr_bitmap())
13271 		vmx_update_msr_bitmap(vcpu);
13272 
13273 	if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
13274 				vmcs12->vm_exit_msr_load_count))
13275 		nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
13276 }
13277 
13278 /*
13279  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
13280  * and modify vmcs12 to make it see what it would expect to see there if
13281  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
13282  */
nested_vmx_vmexit(struct kvm_vcpu * vcpu,u32 exit_reason,u32 exit_intr_info,unsigned long exit_qualification)13283 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
13284 			      u32 exit_intr_info,
13285 			      unsigned long exit_qualification)
13286 {
13287 	struct vcpu_vmx *vmx = to_vmx(vcpu);
13288 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13289 
13290 	/* trying to cancel vmlaunch/vmresume is a bug */
13291 	WARN_ON_ONCE(vmx->nested.nested_run_pending);
13292 
13293 	/*
13294 	 * The only expected VM-instruction error is "VM entry with
13295 	 * invalid control field(s)." Anything else indicates a
13296 	 * problem with L0.
13297 	 */
13298 	WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
13299 				   VMXERR_ENTRY_INVALID_CONTROL_FIELD));
13300 
13301 	leave_guest_mode(vcpu);
13302 
13303 	if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13304 		vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
13305 
13306 	if (likely(!vmx->fail)) {
13307 		if (exit_reason == -1)
13308 			sync_vmcs12(vcpu, vmcs12);
13309 		else
13310 			prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
13311 				       exit_qualification);
13312 
13313 		/*
13314 		 * Must happen outside of sync_vmcs12() as it will
13315 		 * also be used to capture vmcs12 cache as part of
13316 		 * capturing nVMX state for snapshot (migration).
13317 		 *
13318 		 * Otherwise, this flush will dirty guest memory at a
13319 		 * point it is already assumed by user-space to be
13320 		 * immutable.
13321 		 */
13322 		nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
13323 
13324 		if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
13325 					 vmcs12->vm_exit_msr_store_count))
13326 			nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
13327 	}
13328 
13329 	vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13330 	vm_entry_controls_reset_shadow(vmx);
13331 	vm_exit_controls_reset_shadow(vmx);
13332 	vmx_segment_cache_clear(vmx);
13333 
13334 	/* Update any VMCS fields that might have changed while L2 ran */
13335 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
13336 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
13337 	vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
13338 
13339 	if (kvm_has_tsc_control)
13340 		decache_tsc_multiplier(vmx);
13341 
13342 	if (vmx->nested.change_vmcs01_virtual_apic_mode) {
13343 		vmx->nested.change_vmcs01_virtual_apic_mode = false;
13344 		vmx_set_virtual_apic_mode(vcpu);
13345 	} else if (!nested_cpu_has_ept(vmcs12) &&
13346 		   nested_cpu_has2(vmcs12,
13347 				   SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
13348 		vmx_flush_tlb(vcpu, true);
13349 	}
13350 
13351 	/* This is needed for same reason as it was needed in prepare_vmcs02 */
13352 	vmx->host_rsp = 0;
13353 
13354 	/* Unpin physical memory we referred to in vmcs02 */
13355 	if (vmx->nested.apic_access_page) {
13356 		kvm_release_page_dirty(vmx->nested.apic_access_page);
13357 		vmx->nested.apic_access_page = NULL;
13358 	}
13359 	if (vmx->nested.virtual_apic_page) {
13360 		kvm_release_page_dirty(vmx->nested.virtual_apic_page);
13361 		vmx->nested.virtual_apic_page = NULL;
13362 	}
13363 	if (vmx->nested.pi_desc_page) {
13364 		kunmap(vmx->nested.pi_desc_page);
13365 		kvm_release_page_dirty(vmx->nested.pi_desc_page);
13366 		vmx->nested.pi_desc_page = NULL;
13367 		vmx->nested.pi_desc = NULL;
13368 	}
13369 
13370 	/*
13371 	 * We are now running in L2, mmu_notifier will force to reload the
13372 	 * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
13373 	 */
13374 	kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
13375 
13376 	if (enable_shadow_vmcs && exit_reason != -1)
13377 		vmx->nested.sync_shadow_vmcs = true;
13378 
13379 	/* in case we halted in L2 */
13380 	vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
13381 
13382 	if (likely(!vmx->fail)) {
13383 		/*
13384 		 * TODO: SDM says that with acknowledge interrupt on
13385 		 * exit, bit 31 of the VM-exit interrupt information
13386 		 * (valid interrupt) is always set to 1 on
13387 		 * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
13388 		 * need kvm_cpu_has_interrupt().  See the commit
13389 		 * message for details.
13390 		 */
13391 		if (nested_exit_intr_ack_set(vcpu) &&
13392 		    exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
13393 		    kvm_cpu_has_interrupt(vcpu)) {
13394 			int irq = kvm_cpu_get_interrupt(vcpu);
13395 			WARN_ON(irq < 0);
13396 			vmcs12->vm_exit_intr_info = irq |
13397 				INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
13398 		}
13399 
13400 		if (exit_reason != -1)
13401 			trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
13402 						       vmcs12->exit_qualification,
13403 						       vmcs12->idt_vectoring_info_field,
13404 						       vmcs12->vm_exit_intr_info,
13405 						       vmcs12->vm_exit_intr_error_code,
13406 						       KVM_ISA_VMX);
13407 
13408 		load_vmcs12_host_state(vcpu, vmcs12);
13409 
13410 		return;
13411 	}
13412 
13413 	/*
13414 	 * After an early L2 VM-entry failure, we're now back
13415 	 * in L1 which thinks it just finished a VMLAUNCH or
13416 	 * VMRESUME instruction, so we need to set the failure
13417 	 * flag and the VM-instruction error field of the VMCS
13418 	 * accordingly.
13419 	 */
13420 	nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13421 
13422 	load_vmcs12_mmu_host_state(vcpu, vmcs12);
13423 
13424 	/*
13425 	 * The emulated instruction was already skipped in
13426 	 * nested_vmx_run, but the updated RIP was never
13427 	 * written back to the vmcs01.
13428 	 */
13429 	skip_emulated_instruction(vcpu);
13430 	vmx->fail = 0;
13431 }
13432 
13433 /*
13434  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
13435  */
vmx_leave_nested(struct kvm_vcpu * vcpu)13436 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
13437 {
13438 	if (is_guest_mode(vcpu)) {
13439 		to_vmx(vcpu)->nested.nested_run_pending = 0;
13440 		nested_vmx_vmexit(vcpu, -1, 0, 0);
13441 	}
13442 	free_nested(to_vmx(vcpu));
13443 }
13444 
13445 /*
13446  * L1's failure to enter L2 is a subset of a normal exit, as explained in
13447  * 23.7 "VM-entry failures during or after loading guest state" (this also
13448  * lists the acceptable exit-reason and exit-qualification parameters).
13449  * It should only be called before L2 actually succeeded to run, and when
13450  * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
13451  */
nested_vmx_entry_failure(struct kvm_vcpu * vcpu,struct vmcs12 * vmcs12,u32 reason,unsigned long qualification)13452 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
13453 			struct vmcs12 *vmcs12,
13454 			u32 reason, unsigned long qualification)
13455 {
13456 	load_vmcs12_host_state(vcpu, vmcs12);
13457 	vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
13458 	vmcs12->exit_qualification = qualification;
13459 	nested_vmx_succeed(vcpu);
13460 	if (enable_shadow_vmcs)
13461 		to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
13462 }
13463 
vmx_check_intercept(struct kvm_vcpu * vcpu,struct x86_instruction_info * info,enum x86_intercept_stage stage)13464 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
13465 			       struct x86_instruction_info *info,
13466 			       enum x86_intercept_stage stage)
13467 {
13468 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13469 	struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
13470 
13471 	/*
13472 	 * RDPID causes #UD if disabled through secondary execution controls.
13473 	 * Because it is marked as EmulateOnUD, we need to intercept it here.
13474 	 */
13475 	if (info->intercept == x86_intercept_rdtscp &&
13476 	    !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
13477 		ctxt->exception.vector = UD_VECTOR;
13478 		ctxt->exception.error_code_valid = false;
13479 		return X86EMUL_PROPAGATE_FAULT;
13480 	}
13481 
13482 	/* TODO: check more intercepts... */
13483 	return X86EMUL_CONTINUE;
13484 }
13485 
13486 #ifdef CONFIG_X86_64
13487 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
u64_shl_div_u64(u64 a,unsigned int shift,u64 divisor,u64 * result)13488 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
13489 				  u64 divisor, u64 *result)
13490 {
13491 	u64 low = a << shift, high = a >> (64 - shift);
13492 
13493 	/* To avoid the overflow on divq */
13494 	if (high >= divisor)
13495 		return 1;
13496 
13497 	/* Low hold the result, high hold rem which is discarded */
13498 	asm("divq %2\n\t" : "=a" (low), "=d" (high) :
13499 	    "rm" (divisor), "0" (low), "1" (high));
13500 	*result = low;
13501 
13502 	return 0;
13503 }
13504 
vmx_set_hv_timer(struct kvm_vcpu * vcpu,u64 guest_deadline_tsc)13505 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
13506 {
13507 	struct vcpu_vmx *vmx;
13508 	u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
13509 
13510 	if (kvm_mwait_in_guest(vcpu->kvm))
13511 		return -EOPNOTSUPP;
13512 
13513 	vmx = to_vmx(vcpu);
13514 	tscl = rdtsc();
13515 	guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
13516 	delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
13517 	lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
13518 
13519 	if (delta_tsc > lapic_timer_advance_cycles)
13520 		delta_tsc -= lapic_timer_advance_cycles;
13521 	else
13522 		delta_tsc = 0;
13523 
13524 	/* Convert to host delta tsc if tsc scaling is enabled */
13525 	if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
13526 			u64_shl_div_u64(delta_tsc,
13527 				kvm_tsc_scaling_ratio_frac_bits,
13528 				vcpu->arch.tsc_scaling_ratio,
13529 				&delta_tsc))
13530 		return -ERANGE;
13531 
13532 	/*
13533 	 * If the delta tsc can't fit in the 32 bit after the multi shift,
13534 	 * we can't use the preemption timer.
13535 	 * It's possible that it fits on later vmentries, but checking
13536 	 * on every vmentry is costly so we just use an hrtimer.
13537 	 */
13538 	if (delta_tsc >> (cpu_preemption_timer_multi + 32))
13539 		return -ERANGE;
13540 
13541 	vmx->hv_deadline_tsc = tscl + delta_tsc;
13542 	return delta_tsc == 0;
13543 }
13544 
vmx_cancel_hv_timer(struct kvm_vcpu * vcpu)13545 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
13546 {
13547 	to_vmx(vcpu)->hv_deadline_tsc = -1;
13548 }
13549 #endif
13550 
vmx_sched_in(struct kvm_vcpu * vcpu,int cpu)13551 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
13552 {
13553 	if (!kvm_pause_in_guest(vcpu->kvm))
13554 		shrink_ple_window(vcpu);
13555 }
13556 
vmx_slot_enable_log_dirty(struct kvm * kvm,struct kvm_memory_slot * slot)13557 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
13558 				     struct kvm_memory_slot *slot)
13559 {
13560 	kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
13561 	kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
13562 }
13563 
vmx_slot_disable_log_dirty(struct kvm * kvm,struct kvm_memory_slot * slot)13564 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
13565 				       struct kvm_memory_slot *slot)
13566 {
13567 	kvm_mmu_slot_set_dirty(kvm, slot);
13568 }
13569 
vmx_flush_log_dirty(struct kvm * kvm)13570 static void vmx_flush_log_dirty(struct kvm *kvm)
13571 {
13572 	kvm_flush_pml_buffers(kvm);
13573 }
13574 
vmx_write_pml_buffer(struct kvm_vcpu * vcpu)13575 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
13576 {
13577 	struct vmcs12 *vmcs12;
13578 	struct vcpu_vmx *vmx = to_vmx(vcpu);
13579 	gpa_t gpa;
13580 	struct page *page = NULL;
13581 	u64 *pml_address;
13582 
13583 	if (is_guest_mode(vcpu)) {
13584 		WARN_ON_ONCE(vmx->nested.pml_full);
13585 
13586 		/*
13587 		 * Check if PML is enabled for the nested guest.
13588 		 * Whether eptp bit 6 is set is already checked
13589 		 * as part of A/D emulation.
13590 		 */
13591 		vmcs12 = get_vmcs12(vcpu);
13592 		if (!nested_cpu_has_pml(vmcs12))
13593 			return 0;
13594 
13595 		if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
13596 			vmx->nested.pml_full = true;
13597 			return 1;
13598 		}
13599 
13600 		gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
13601 
13602 		page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
13603 		if (is_error_page(page))
13604 			return 0;
13605 
13606 		pml_address = kmap(page);
13607 		pml_address[vmcs12->guest_pml_index--] = gpa;
13608 		kunmap(page);
13609 		kvm_release_page_clean(page);
13610 	}
13611 
13612 	return 0;
13613 }
13614 
vmx_enable_log_dirty_pt_masked(struct kvm * kvm,struct kvm_memory_slot * memslot,gfn_t offset,unsigned long mask)13615 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
13616 					   struct kvm_memory_slot *memslot,
13617 					   gfn_t offset, unsigned long mask)
13618 {
13619 	kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
13620 }
13621 
__pi_post_block(struct kvm_vcpu * vcpu)13622 static void __pi_post_block(struct kvm_vcpu *vcpu)
13623 {
13624 	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
13625 	struct pi_desc old, new;
13626 	unsigned int dest;
13627 
13628 	do {
13629 		old.control = new.control = pi_desc->control;
13630 		WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
13631 		     "Wakeup handler not enabled while the VCPU is blocked\n");
13632 
13633 		dest = cpu_physical_id(vcpu->cpu);
13634 
13635 		if (x2apic_enabled())
13636 			new.ndst = dest;
13637 		else
13638 			new.ndst = (dest << 8) & 0xFF00;
13639 
13640 		/* set 'NV' to 'notification vector' */
13641 		new.nv = POSTED_INTR_VECTOR;
13642 	} while (cmpxchg64(&pi_desc->control, old.control,
13643 			   new.control) != old.control);
13644 
13645 	if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
13646 		spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13647 		list_del(&vcpu->blocked_vcpu_list);
13648 		spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13649 		vcpu->pre_pcpu = -1;
13650 	}
13651 }
13652 
13653 /*
13654  * This routine does the following things for vCPU which is going
13655  * to be blocked if VT-d PI is enabled.
13656  * - Store the vCPU to the wakeup list, so when interrupts happen
13657  *   we can find the right vCPU to wake up.
13658  * - Change the Posted-interrupt descriptor as below:
13659  *      'NDST' <-- vcpu->pre_pcpu
13660  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
13661  * - If 'ON' is set during this process, which means at least one
13662  *   interrupt is posted for this vCPU, we cannot block it, in
13663  *   this case, return 1, otherwise, return 0.
13664  *
13665  */
pi_pre_block(struct kvm_vcpu * vcpu)13666 static int pi_pre_block(struct kvm_vcpu *vcpu)
13667 {
13668 	unsigned int dest;
13669 	struct pi_desc old, new;
13670 	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
13671 
13672 	if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
13673 		!irq_remapping_cap(IRQ_POSTING_CAP)  ||
13674 		!kvm_vcpu_apicv_active(vcpu))
13675 		return 0;
13676 
13677 	WARN_ON(irqs_disabled());
13678 	local_irq_disable();
13679 	if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
13680 		vcpu->pre_pcpu = vcpu->cpu;
13681 		spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13682 		list_add_tail(&vcpu->blocked_vcpu_list,
13683 			      &per_cpu(blocked_vcpu_on_cpu,
13684 				       vcpu->pre_pcpu));
13685 		spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13686 	}
13687 
13688 	do {
13689 		old.control = new.control = pi_desc->control;
13690 
13691 		WARN((pi_desc->sn == 1),
13692 		     "Warning: SN field of posted-interrupts "
13693 		     "is set before blocking\n");
13694 
13695 		/*
13696 		 * Since vCPU can be preempted during this process,
13697 		 * vcpu->cpu could be different with pre_pcpu, we
13698 		 * need to set pre_pcpu as the destination of wakeup
13699 		 * notification event, then we can find the right vCPU
13700 		 * to wakeup in wakeup handler if interrupts happen
13701 		 * when the vCPU is in blocked state.
13702 		 */
13703 		dest = cpu_physical_id(vcpu->pre_pcpu);
13704 
13705 		if (x2apic_enabled())
13706 			new.ndst = dest;
13707 		else
13708 			new.ndst = (dest << 8) & 0xFF00;
13709 
13710 		/* set 'NV' to 'wakeup vector' */
13711 		new.nv = POSTED_INTR_WAKEUP_VECTOR;
13712 	} while (cmpxchg64(&pi_desc->control, old.control,
13713 			   new.control) != old.control);
13714 
13715 	/* We should not block the vCPU if an interrupt is posted for it.  */
13716 	if (pi_test_on(pi_desc) == 1)
13717 		__pi_post_block(vcpu);
13718 
13719 	local_irq_enable();
13720 	return (vcpu->pre_pcpu == -1);
13721 }
13722 
vmx_pre_block(struct kvm_vcpu * vcpu)13723 static int vmx_pre_block(struct kvm_vcpu *vcpu)
13724 {
13725 	if (pi_pre_block(vcpu))
13726 		return 1;
13727 
13728 	if (kvm_lapic_hv_timer_in_use(vcpu))
13729 		kvm_lapic_switch_to_sw_timer(vcpu);
13730 
13731 	return 0;
13732 }
13733 
pi_post_block(struct kvm_vcpu * vcpu)13734 static void pi_post_block(struct kvm_vcpu *vcpu)
13735 {
13736 	if (vcpu->pre_pcpu == -1)
13737 		return;
13738 
13739 	WARN_ON(irqs_disabled());
13740 	local_irq_disable();
13741 	__pi_post_block(vcpu);
13742 	local_irq_enable();
13743 }
13744 
vmx_post_block(struct kvm_vcpu * vcpu)13745 static void vmx_post_block(struct kvm_vcpu *vcpu)
13746 {
13747 	if (kvm_x86_ops->set_hv_timer)
13748 		kvm_lapic_switch_to_hv_timer(vcpu);
13749 
13750 	pi_post_block(vcpu);
13751 }
13752 
13753 /*
13754  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
13755  *
13756  * @kvm: kvm
13757  * @host_irq: host irq of the interrupt
13758  * @guest_irq: gsi of the interrupt
13759  * @set: set or unset PI
13760  * returns 0 on success, < 0 on failure
13761  */
vmx_update_pi_irte(struct kvm * kvm,unsigned int host_irq,uint32_t guest_irq,bool set)13762 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
13763 			      uint32_t guest_irq, bool set)
13764 {
13765 	struct kvm_kernel_irq_routing_entry *e;
13766 	struct kvm_irq_routing_table *irq_rt;
13767 	struct kvm_lapic_irq irq;
13768 	struct kvm_vcpu *vcpu;
13769 	struct vcpu_data vcpu_info;
13770 	int idx, ret = 0;
13771 
13772 	if (!kvm_arch_has_assigned_device(kvm) ||
13773 		!irq_remapping_cap(IRQ_POSTING_CAP) ||
13774 		!kvm_vcpu_apicv_active(kvm->vcpus[0]))
13775 		return 0;
13776 
13777 	idx = srcu_read_lock(&kvm->irq_srcu);
13778 	irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
13779 	if (guest_irq >= irq_rt->nr_rt_entries ||
13780 	    hlist_empty(&irq_rt->map[guest_irq])) {
13781 		pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
13782 			     guest_irq, irq_rt->nr_rt_entries);
13783 		goto out;
13784 	}
13785 
13786 	hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
13787 		if (e->type != KVM_IRQ_ROUTING_MSI)
13788 			continue;
13789 		/*
13790 		 * VT-d PI cannot support posting multicast/broadcast
13791 		 * interrupts to a vCPU, we still use interrupt remapping
13792 		 * for these kind of interrupts.
13793 		 *
13794 		 * For lowest-priority interrupts, we only support
13795 		 * those with single CPU as the destination, e.g. user
13796 		 * configures the interrupts via /proc/irq or uses
13797 		 * irqbalance to make the interrupts single-CPU.
13798 		 *
13799 		 * We will support full lowest-priority interrupt later.
13800 		 */
13801 
13802 		kvm_set_msi_irq(kvm, e, &irq);
13803 		if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
13804 			/*
13805 			 * Make sure the IRTE is in remapped mode if
13806 			 * we don't handle it in posted mode.
13807 			 */
13808 			ret = irq_set_vcpu_affinity(host_irq, NULL);
13809 			if (ret < 0) {
13810 				printk(KERN_INFO
13811 				   "failed to back to remapped mode, irq: %u\n",
13812 				   host_irq);
13813 				goto out;
13814 			}
13815 
13816 			continue;
13817 		}
13818 
13819 		vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
13820 		vcpu_info.vector = irq.vector;
13821 
13822 		trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
13823 				vcpu_info.vector, vcpu_info.pi_desc_addr, set);
13824 
13825 		if (set)
13826 			ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
13827 		else
13828 			ret = irq_set_vcpu_affinity(host_irq, NULL);
13829 
13830 		if (ret < 0) {
13831 			printk(KERN_INFO "%s: failed to update PI IRTE\n",
13832 					__func__);
13833 			goto out;
13834 		}
13835 	}
13836 
13837 	ret = 0;
13838 out:
13839 	srcu_read_unlock(&kvm->irq_srcu, idx);
13840 	return ret;
13841 }
13842 
vmx_setup_mce(struct kvm_vcpu * vcpu)13843 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
13844 {
13845 	if (vcpu->arch.mcg_cap & MCG_LMCE_P)
13846 		to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
13847 			FEATURE_CONTROL_LMCE;
13848 	else
13849 		to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
13850 			~FEATURE_CONTROL_LMCE;
13851 }
13852 
vmx_smi_allowed(struct kvm_vcpu * vcpu)13853 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
13854 {
13855 	/* we need a nested vmexit to enter SMM, postpone if run is pending */
13856 	if (to_vmx(vcpu)->nested.nested_run_pending)
13857 		return 0;
13858 	return 1;
13859 }
13860 
vmx_pre_enter_smm(struct kvm_vcpu * vcpu,char * smstate)13861 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
13862 {
13863 	struct vcpu_vmx *vmx = to_vmx(vcpu);
13864 
13865 	vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
13866 	if (vmx->nested.smm.guest_mode)
13867 		nested_vmx_vmexit(vcpu, -1, 0, 0);
13868 
13869 	vmx->nested.smm.vmxon = vmx->nested.vmxon;
13870 	vmx->nested.vmxon = false;
13871 	vmx_clear_hlt(vcpu);
13872 	return 0;
13873 }
13874 
vmx_pre_leave_smm(struct kvm_vcpu * vcpu,u64 smbase)13875 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
13876 {
13877 	struct vcpu_vmx *vmx = to_vmx(vcpu);
13878 	int ret;
13879 
13880 	if (vmx->nested.smm.vmxon) {
13881 		vmx->nested.vmxon = true;
13882 		vmx->nested.smm.vmxon = false;
13883 	}
13884 
13885 	if (vmx->nested.smm.guest_mode) {
13886 		vcpu->arch.hflags &= ~HF_SMM_MASK;
13887 		ret = enter_vmx_non_root_mode(vcpu, NULL);
13888 		vcpu->arch.hflags |= HF_SMM_MASK;
13889 		if (ret)
13890 			return ret;
13891 
13892 		vmx->nested.smm.guest_mode = false;
13893 	}
13894 	return 0;
13895 }
13896 
enable_smi_window(struct kvm_vcpu * vcpu)13897 static int enable_smi_window(struct kvm_vcpu *vcpu)
13898 {
13899 	return 0;
13900 }
13901 
vmx_get_nested_state(struct kvm_vcpu * vcpu,struct kvm_nested_state __user * user_kvm_nested_state,u32 user_data_size)13902 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
13903 				struct kvm_nested_state __user *user_kvm_nested_state,
13904 				u32 user_data_size)
13905 {
13906 	struct vcpu_vmx *vmx;
13907 	struct vmcs12 *vmcs12;
13908 	struct kvm_nested_state kvm_state = {
13909 		.flags = 0,
13910 		.format = 0,
13911 		.size = sizeof(kvm_state),
13912 		.vmx.vmxon_pa = -1ull,
13913 		.vmx.vmcs_pa = -1ull,
13914 	};
13915 
13916 	if (!vcpu)
13917 		return kvm_state.size + 2 * VMCS12_SIZE;
13918 
13919 	vmx = to_vmx(vcpu);
13920 	vmcs12 = get_vmcs12(vcpu);
13921 	if (nested_vmx_allowed(vcpu) &&
13922 	    (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
13923 		kvm_state.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
13924 		kvm_state.vmx.vmcs_pa = vmx->nested.current_vmptr;
13925 
13926 		if (vmx->nested.current_vmptr != -1ull) {
13927 			kvm_state.size += VMCS12_SIZE;
13928 
13929 			if (is_guest_mode(vcpu) &&
13930 			    nested_cpu_has_shadow_vmcs(vmcs12) &&
13931 			    vmcs12->vmcs_link_pointer != -1ull)
13932 				kvm_state.size += VMCS12_SIZE;
13933 		}
13934 
13935 		if (vmx->nested.smm.vmxon)
13936 			kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
13937 
13938 		if (vmx->nested.smm.guest_mode)
13939 			kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
13940 
13941 		if (is_guest_mode(vcpu)) {
13942 			kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
13943 
13944 			if (vmx->nested.nested_run_pending)
13945 				kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
13946 		}
13947 	}
13948 
13949 	if (user_data_size < kvm_state.size)
13950 		goto out;
13951 
13952 	if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
13953 		return -EFAULT;
13954 
13955 	if (vmx->nested.current_vmptr == -1ull)
13956 		goto out;
13957 
13958 	/*
13959 	 * When running L2, the authoritative vmcs12 state is in the
13960 	 * vmcs02. When running L1, the authoritative vmcs12 state is
13961 	 * in the shadow vmcs linked to vmcs01, unless
13962 	 * sync_shadow_vmcs is set, in which case, the authoritative
13963 	 * vmcs12 state is in the vmcs12 already.
13964 	 */
13965 	if (is_guest_mode(vcpu))
13966 		sync_vmcs12(vcpu, vmcs12);
13967 	else if (enable_shadow_vmcs && !vmx->nested.sync_shadow_vmcs)
13968 		copy_shadow_to_vmcs12(vmx);
13969 
13970 	if (copy_to_user(user_kvm_nested_state->data, vmcs12, sizeof(*vmcs12)))
13971 		return -EFAULT;
13972 
13973 	if (nested_cpu_has_shadow_vmcs(vmcs12) &&
13974 	    vmcs12->vmcs_link_pointer != -1ull) {
13975 		if (copy_to_user(user_kvm_nested_state->data + VMCS12_SIZE,
13976 				 get_shadow_vmcs12(vcpu), sizeof(*vmcs12)))
13977 			return -EFAULT;
13978 	}
13979 
13980 out:
13981 	return kvm_state.size;
13982 }
13983 
vmx_set_nested_state(struct kvm_vcpu * vcpu,struct kvm_nested_state __user * user_kvm_nested_state,struct kvm_nested_state * kvm_state)13984 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
13985 				struct kvm_nested_state __user *user_kvm_nested_state,
13986 				struct kvm_nested_state *kvm_state)
13987 {
13988 	struct vcpu_vmx *vmx = to_vmx(vcpu);
13989 	struct vmcs12 *vmcs12;
13990 	u32 exit_qual;
13991 	int ret;
13992 
13993 	if (kvm_state->format != 0)
13994 		return -EINVAL;
13995 
13996 	if (!nested_vmx_allowed(vcpu))
13997 		return kvm_state->vmx.vmxon_pa == -1ull ? 0 : -EINVAL;
13998 
13999 	if (kvm_state->vmx.vmxon_pa == -1ull) {
14000 		if (kvm_state->vmx.smm.flags)
14001 			return -EINVAL;
14002 
14003 		if (kvm_state->vmx.vmcs_pa != -1ull)
14004 			return -EINVAL;
14005 
14006 		vmx_leave_nested(vcpu);
14007 		return 0;
14008 	}
14009 
14010 	if (!page_address_valid(vcpu, kvm_state->vmx.vmxon_pa))
14011 		return -EINVAL;
14012 
14013 	if (kvm_state->size < sizeof(kvm_state) + sizeof(*vmcs12))
14014 		return -EINVAL;
14015 
14016 	if (kvm_state->vmx.vmcs_pa == kvm_state->vmx.vmxon_pa ||
14017 	    !page_address_valid(vcpu, kvm_state->vmx.vmcs_pa))
14018 		return -EINVAL;
14019 
14020 	if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14021 	    (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14022 		return -EINVAL;
14023 
14024 	if (kvm_state->vmx.smm.flags &
14025 	    ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
14026 		return -EINVAL;
14027 
14028 	/*
14029 	 * SMM temporarily disables VMX, so we cannot be in guest mode,
14030 	 * nor can VMLAUNCH/VMRESUME be pending.  Outside SMM, SMM flags
14031 	 * must be zero.
14032 	 */
14033 	if (is_smm(vcpu) ? kvm_state->flags : kvm_state->vmx.smm.flags)
14034 		return -EINVAL;
14035 
14036 	if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14037 	    !(kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
14038 		return -EINVAL;
14039 
14040 	vmx_leave_nested(vcpu);
14041 	if (kvm_state->vmx.vmxon_pa == -1ull)
14042 		return 0;
14043 
14044 	vmx->nested.vmxon_ptr = kvm_state->vmx.vmxon_pa;
14045 	ret = enter_vmx_operation(vcpu);
14046 	if (ret)
14047 		return ret;
14048 
14049 	set_current_vmptr(vmx, kvm_state->vmx.vmcs_pa);
14050 
14051 	if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
14052 		vmx->nested.smm.vmxon = true;
14053 		vmx->nested.vmxon = false;
14054 
14055 		if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
14056 			vmx->nested.smm.guest_mode = true;
14057 	}
14058 
14059 	vmcs12 = get_vmcs12(vcpu);
14060 	if (copy_from_user(vmcs12, user_kvm_nested_state->data, sizeof(*vmcs12)))
14061 		return -EFAULT;
14062 
14063 	if (vmcs12->hdr.revision_id != VMCS12_REVISION)
14064 		return -EINVAL;
14065 
14066 	if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14067 		return 0;
14068 
14069 	vmx->nested.nested_run_pending =
14070 		!!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
14071 
14072 	if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14073 	    vmcs12->vmcs_link_pointer != -1ull) {
14074 		struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
14075 		if (kvm_state->size < sizeof(kvm_state) + 2 * sizeof(*vmcs12))
14076 			return -EINVAL;
14077 
14078 		if (copy_from_user(shadow_vmcs12,
14079 				   user_kvm_nested_state->data + VMCS12_SIZE,
14080 				   sizeof(*vmcs12)))
14081 			return -EFAULT;
14082 
14083 		if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
14084 		    !shadow_vmcs12->hdr.shadow_vmcs)
14085 			return -EINVAL;
14086 	}
14087 
14088 	if (check_vmentry_prereqs(vcpu, vmcs12) ||
14089 	    check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
14090 		return -EINVAL;
14091 
14092 	vmx->nested.dirty_vmcs12 = true;
14093 	ret = enter_vmx_non_root_mode(vcpu, NULL);
14094 	if (ret)
14095 		return -EINVAL;
14096 
14097 	return 0;
14098 }
14099 
14100 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
14101 	.cpu_has_kvm_support = cpu_has_kvm_support,
14102 	.disabled_by_bios = vmx_disabled_by_bios,
14103 	.hardware_setup = hardware_setup,
14104 	.hardware_unsetup = hardware_unsetup,
14105 	.check_processor_compatibility = vmx_check_processor_compat,
14106 	.hardware_enable = hardware_enable,
14107 	.hardware_disable = hardware_disable,
14108 	.cpu_has_accelerated_tpr = report_flexpriority,
14109 	.has_emulated_msr = vmx_has_emulated_msr,
14110 
14111 	.vm_init = vmx_vm_init,
14112 	.vm_alloc = vmx_vm_alloc,
14113 	.vm_free = vmx_vm_free,
14114 
14115 	.vcpu_create = vmx_create_vcpu,
14116 	.vcpu_free = vmx_free_vcpu,
14117 	.vcpu_reset = vmx_vcpu_reset,
14118 
14119 	.prepare_guest_switch = vmx_prepare_switch_to_guest,
14120 	.vcpu_load = vmx_vcpu_load,
14121 	.vcpu_put = vmx_vcpu_put,
14122 
14123 	.update_bp_intercept = update_exception_bitmap,
14124 	.get_msr_feature = vmx_get_msr_feature,
14125 	.get_msr = vmx_get_msr,
14126 	.set_msr = vmx_set_msr,
14127 	.get_segment_base = vmx_get_segment_base,
14128 	.get_segment = vmx_get_segment,
14129 	.set_segment = vmx_set_segment,
14130 	.get_cpl = vmx_get_cpl,
14131 	.get_cs_db_l_bits = vmx_get_cs_db_l_bits,
14132 	.decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
14133 	.decache_cr3 = vmx_decache_cr3,
14134 	.decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
14135 	.set_cr0 = vmx_set_cr0,
14136 	.set_cr3 = vmx_set_cr3,
14137 	.set_cr4 = vmx_set_cr4,
14138 	.set_efer = vmx_set_efer,
14139 	.get_idt = vmx_get_idt,
14140 	.set_idt = vmx_set_idt,
14141 	.get_gdt = vmx_get_gdt,
14142 	.set_gdt = vmx_set_gdt,
14143 	.get_dr6 = vmx_get_dr6,
14144 	.set_dr6 = vmx_set_dr6,
14145 	.set_dr7 = vmx_set_dr7,
14146 	.sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
14147 	.cache_reg = vmx_cache_reg,
14148 	.get_rflags = vmx_get_rflags,
14149 	.set_rflags = vmx_set_rflags,
14150 
14151 	.tlb_flush = vmx_flush_tlb,
14152 	.tlb_flush_gva = vmx_flush_tlb_gva,
14153 
14154 	.run = vmx_vcpu_run,
14155 	.handle_exit = vmx_handle_exit,
14156 	.skip_emulated_instruction = skip_emulated_instruction,
14157 	.set_interrupt_shadow = vmx_set_interrupt_shadow,
14158 	.get_interrupt_shadow = vmx_get_interrupt_shadow,
14159 	.patch_hypercall = vmx_patch_hypercall,
14160 	.set_irq = vmx_inject_irq,
14161 	.set_nmi = vmx_inject_nmi,
14162 	.queue_exception = vmx_queue_exception,
14163 	.cancel_injection = vmx_cancel_injection,
14164 	.interrupt_allowed = vmx_interrupt_allowed,
14165 	.nmi_allowed = vmx_nmi_allowed,
14166 	.get_nmi_mask = vmx_get_nmi_mask,
14167 	.set_nmi_mask = vmx_set_nmi_mask,
14168 	.enable_nmi_window = enable_nmi_window,
14169 	.enable_irq_window = enable_irq_window,
14170 	.update_cr8_intercept = update_cr8_intercept,
14171 	.set_virtual_apic_mode = vmx_set_virtual_apic_mode,
14172 	.set_apic_access_page_addr = vmx_set_apic_access_page_addr,
14173 	.get_enable_apicv = vmx_get_enable_apicv,
14174 	.refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
14175 	.load_eoi_exitmap = vmx_load_eoi_exitmap,
14176 	.apicv_post_state_restore = vmx_apicv_post_state_restore,
14177 	.hwapic_irr_update = vmx_hwapic_irr_update,
14178 	.hwapic_isr_update = vmx_hwapic_isr_update,
14179 	.guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
14180 	.sync_pir_to_irr = vmx_sync_pir_to_irr,
14181 	.deliver_posted_interrupt = vmx_deliver_posted_interrupt,
14182 
14183 	.set_tss_addr = vmx_set_tss_addr,
14184 	.set_identity_map_addr = vmx_set_identity_map_addr,
14185 	.get_tdp_level = get_ept_level,
14186 	.get_mt_mask = vmx_get_mt_mask,
14187 
14188 	.get_exit_info = vmx_get_exit_info,
14189 
14190 	.get_lpage_level = vmx_get_lpage_level,
14191 
14192 	.cpuid_update = vmx_cpuid_update,
14193 
14194 	.rdtscp_supported = vmx_rdtscp_supported,
14195 	.invpcid_supported = vmx_invpcid_supported,
14196 
14197 	.set_supported_cpuid = vmx_set_supported_cpuid,
14198 
14199 	.has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
14200 
14201 	.read_l1_tsc_offset = vmx_read_l1_tsc_offset,
14202 	.write_tsc_offset = vmx_write_tsc_offset,
14203 
14204 	.set_tdp_cr3 = vmx_set_cr3,
14205 
14206 	.check_intercept = vmx_check_intercept,
14207 	.handle_external_intr = vmx_handle_external_intr,
14208 	.mpx_supported = vmx_mpx_supported,
14209 	.xsaves_supported = vmx_xsaves_supported,
14210 	.umip_emulated = vmx_umip_emulated,
14211 
14212 	.check_nested_events = vmx_check_nested_events,
14213 	.request_immediate_exit = vmx_request_immediate_exit,
14214 
14215 	.sched_in = vmx_sched_in,
14216 
14217 	.slot_enable_log_dirty = vmx_slot_enable_log_dirty,
14218 	.slot_disable_log_dirty = vmx_slot_disable_log_dirty,
14219 	.flush_log_dirty = vmx_flush_log_dirty,
14220 	.enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
14221 	.write_log_dirty = vmx_write_pml_buffer,
14222 
14223 	.pre_block = vmx_pre_block,
14224 	.post_block = vmx_post_block,
14225 
14226 	.pmu_ops = &intel_pmu_ops,
14227 
14228 	.update_pi_irte = vmx_update_pi_irte,
14229 
14230 #ifdef CONFIG_X86_64
14231 	.set_hv_timer = vmx_set_hv_timer,
14232 	.cancel_hv_timer = vmx_cancel_hv_timer,
14233 #endif
14234 
14235 	.setup_mce = vmx_setup_mce,
14236 
14237 	.get_nested_state = vmx_get_nested_state,
14238 	.set_nested_state = vmx_set_nested_state,
14239 	.get_vmcs12_pages = nested_get_vmcs12_pages,
14240 
14241 	.smi_allowed = vmx_smi_allowed,
14242 	.pre_enter_smm = vmx_pre_enter_smm,
14243 	.pre_leave_smm = vmx_pre_leave_smm,
14244 	.enable_smi_window = enable_smi_window,
14245 };
14246 
vmx_cleanup_l1d_flush(void)14247 static void vmx_cleanup_l1d_flush(void)
14248 {
14249 	if (vmx_l1d_flush_pages) {
14250 		free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
14251 		vmx_l1d_flush_pages = NULL;
14252 	}
14253 	/* Restore state so sysfs ignores VMX */
14254 	l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
14255 }
14256 
vmx_exit(void)14257 static void vmx_exit(void)
14258 {
14259 #ifdef CONFIG_KEXEC_CORE
14260 	RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
14261 	synchronize_rcu();
14262 #endif
14263 
14264 	kvm_exit();
14265 
14266 #if IS_ENABLED(CONFIG_HYPERV)
14267 	if (static_branch_unlikely(&enable_evmcs)) {
14268 		int cpu;
14269 		struct hv_vp_assist_page *vp_ap;
14270 		/*
14271 		 * Reset everything to support using non-enlightened VMCS
14272 		 * access later (e.g. when we reload the module with
14273 		 * enlightened_vmcs=0)
14274 		 */
14275 		for_each_online_cpu(cpu) {
14276 			vp_ap =	hv_get_vp_assist_page(cpu);
14277 
14278 			if (!vp_ap)
14279 				continue;
14280 
14281 			vp_ap->current_nested_vmcs = 0;
14282 			vp_ap->enlighten_vmentry = 0;
14283 		}
14284 
14285 		static_branch_disable(&enable_evmcs);
14286 	}
14287 #endif
14288 	vmx_cleanup_l1d_flush();
14289 }
14290 module_exit(vmx_exit);
14291 
vmx_init(void)14292 static int __init vmx_init(void)
14293 {
14294 	int r;
14295 
14296 #if IS_ENABLED(CONFIG_HYPERV)
14297 	/*
14298 	 * Enlightened VMCS usage should be recommended and the host needs
14299 	 * to support eVMCS v1 or above. We can also disable eVMCS support
14300 	 * with module parameter.
14301 	 */
14302 	if (enlightened_vmcs &&
14303 	    ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
14304 	    (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
14305 	    KVM_EVMCS_VERSION) {
14306 		int cpu;
14307 
14308 		/* Check that we have assist pages on all online CPUs */
14309 		for_each_online_cpu(cpu) {
14310 			if (!hv_get_vp_assist_page(cpu)) {
14311 				enlightened_vmcs = false;
14312 				break;
14313 			}
14314 		}
14315 
14316 		if (enlightened_vmcs) {
14317 			pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
14318 			static_branch_enable(&enable_evmcs);
14319 		}
14320 	} else {
14321 		enlightened_vmcs = false;
14322 	}
14323 #endif
14324 
14325 	r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
14326 		     __alignof__(struct vcpu_vmx), THIS_MODULE);
14327 	if (r)
14328 		return r;
14329 
14330 	/*
14331 	 * Must be called after kvm_init() so enable_ept is properly set
14332 	 * up. Hand the parameter mitigation value in which was stored in
14333 	 * the pre module init parser. If no parameter was given, it will
14334 	 * contain 'auto' which will be turned into the default 'cond'
14335 	 * mitigation mode.
14336 	 */
14337 	if (boot_cpu_has(X86_BUG_L1TF)) {
14338 		r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
14339 		if (r) {
14340 			vmx_exit();
14341 			return r;
14342 		}
14343 	}
14344 
14345 #ifdef CONFIG_KEXEC_CORE
14346 	rcu_assign_pointer(crash_vmclear_loaded_vmcss,
14347 			   crash_vmclear_local_loaded_vmcss);
14348 #endif
14349 	vmx_check_vmcs12_offsets();
14350 
14351 	return 0;
14352 }
14353 module_init(vmx_init);
14354