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