xref: /openbmc/linux/arch/x86/kvm/vmx/vmx.c (revision ae213c44)
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2.  See
15  * the COPYING file in the top-level directory.
16  *
17  */
18 
19 #include <linux/frame.h>
20 #include <linux/highmem.h>
21 #include <linux/hrtimer.h>
22 #include <linux/kernel.h>
23 #include <linux/kvm_host.h>
24 #include <linux/module.h>
25 #include <linux/moduleparam.h>
26 #include <linux/mod_devicetable.h>
27 #include <linux/mm.h>
28 #include <linux/sched.h>
29 #include <linux/sched/smt.h>
30 #include <linux/slab.h>
31 #include <linux/tboot.h>
32 #include <linux/trace_events.h>
33 
34 #include <asm/apic.h>
35 #include <asm/asm.h>
36 #include <asm/cpu.h>
37 #include <asm/debugreg.h>
38 #include <asm/desc.h>
39 #include <asm/fpu/internal.h>
40 #include <asm/io.h>
41 #include <asm/irq_remapping.h>
42 #include <asm/kexec.h>
43 #include <asm/perf_event.h>
44 #include <asm/mce.h>
45 #include <asm/mmu_context.h>
46 #include <asm/mshyperv.h>
47 #include <asm/spec-ctrl.h>
48 #include <asm/virtext.h>
49 #include <asm/vmx.h>
50 
51 #include "capabilities.h"
52 #include "cpuid.h"
53 #include "evmcs.h"
54 #include "irq.h"
55 #include "kvm_cache_regs.h"
56 #include "lapic.h"
57 #include "mmu.h"
58 #include "nested.h"
59 #include "ops.h"
60 #include "pmu.h"
61 #include "trace.h"
62 #include "vmcs.h"
63 #include "vmcs12.h"
64 #include "vmx.h"
65 #include "x86.h"
66 
67 MODULE_AUTHOR("Qumranet");
68 MODULE_LICENSE("GPL");
69 
70 static const struct x86_cpu_id vmx_cpu_id[] = {
71 	X86_FEATURE_MATCH(X86_FEATURE_VMX),
72 	{}
73 };
74 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
75 
76 bool __read_mostly enable_vpid = 1;
77 module_param_named(vpid, enable_vpid, bool, 0444);
78 
79 static bool __read_mostly enable_vnmi = 1;
80 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
81 
82 bool __read_mostly flexpriority_enabled = 1;
83 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
84 
85 bool __read_mostly enable_ept = 1;
86 module_param_named(ept, enable_ept, bool, S_IRUGO);
87 
88 bool __read_mostly enable_unrestricted_guest = 1;
89 module_param_named(unrestricted_guest,
90 			enable_unrestricted_guest, bool, S_IRUGO);
91 
92 bool __read_mostly enable_ept_ad_bits = 1;
93 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
94 
95 static bool __read_mostly emulate_invalid_guest_state = true;
96 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
97 
98 static bool __read_mostly fasteoi = 1;
99 module_param(fasteoi, bool, S_IRUGO);
100 
101 static bool __read_mostly enable_apicv = 1;
102 module_param(enable_apicv, bool, S_IRUGO);
103 
104 /*
105  * If nested=1, nested virtualization is supported, i.e., guests may use
106  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
107  * use VMX instructions.
108  */
109 static bool __read_mostly nested = 1;
110 module_param(nested, bool, S_IRUGO);
111 
112 static u64 __read_mostly host_xss;
113 
114 bool __read_mostly enable_pml = 1;
115 module_param_named(pml, enable_pml, bool, S_IRUGO);
116 
117 static bool __read_mostly dump_invalid_vmcs = 0;
118 module_param(dump_invalid_vmcs, bool, 0644);
119 
120 #define MSR_BITMAP_MODE_X2APIC		1
121 #define MSR_BITMAP_MODE_X2APIC_APICV	2
122 
123 #define KVM_VMX_TSC_MULTIPLIER_MAX     0xffffffffffffffffULL
124 
125 /* Guest_tsc -> host_tsc conversion requires 64-bit division.  */
126 static int __read_mostly cpu_preemption_timer_multi;
127 static bool __read_mostly enable_preemption_timer = 1;
128 #ifdef CONFIG_X86_64
129 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
130 #endif
131 
132 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
133 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
134 #define KVM_VM_CR0_ALWAYS_ON				\
135 	(KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | 	\
136 	 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
137 #define KVM_CR4_GUEST_OWNED_BITS				      \
138 	(X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
139 	 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
140 
141 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
142 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
143 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
144 
145 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
146 
147 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
148 	RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
149 	RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
150 	RTIT_STATUS_BYTECNT))
151 
152 #define MSR_IA32_RTIT_OUTPUT_BASE_MASK \
153 	(~((1UL << cpuid_query_maxphyaddr(vcpu)) - 1) | 0x7f)
154 
155 /*
156  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
157  * ple_gap:    upper bound on the amount of time between two successive
158  *             executions of PAUSE in a loop. Also indicate if ple enabled.
159  *             According to test, this time is usually smaller than 128 cycles.
160  * ple_window: upper bound on the amount of time a guest is allowed to execute
161  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
162  *             less than 2^12 cycles
163  * Time is measured based on a counter that runs at the same rate as the TSC,
164  * refer SDM volume 3b section 21.6.13 & 22.1.3.
165  */
166 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
167 module_param(ple_gap, uint, 0444);
168 
169 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
170 module_param(ple_window, uint, 0444);
171 
172 /* Default doubles per-vcpu window every exit. */
173 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
174 module_param(ple_window_grow, uint, 0444);
175 
176 /* Default resets per-vcpu window every exit to ple_window. */
177 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
178 module_param(ple_window_shrink, uint, 0444);
179 
180 /* Default is to compute the maximum so we can never overflow. */
181 static unsigned int ple_window_max        = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
182 module_param(ple_window_max, uint, 0444);
183 
184 /* Default is SYSTEM mode, 1 for host-guest mode */
185 int __read_mostly pt_mode = PT_MODE_SYSTEM;
186 module_param(pt_mode, int, S_IRUGO);
187 
188 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
189 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
190 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
191 
192 /* Storage for pre module init parameter parsing */
193 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
194 
195 static const struct {
196 	const char *option;
197 	bool for_parse;
198 } vmentry_l1d_param[] = {
199 	[VMENTER_L1D_FLUSH_AUTO]	 = {"auto", true},
200 	[VMENTER_L1D_FLUSH_NEVER]	 = {"never", true},
201 	[VMENTER_L1D_FLUSH_COND]	 = {"cond", true},
202 	[VMENTER_L1D_FLUSH_ALWAYS]	 = {"always", true},
203 	[VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
204 	[VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
205 };
206 
207 #define L1D_CACHE_ORDER 4
208 static void *vmx_l1d_flush_pages;
209 
210 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
211 {
212 	struct page *page;
213 	unsigned int i;
214 
215 	if (!enable_ept) {
216 		l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
217 		return 0;
218 	}
219 
220 	if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
221 		u64 msr;
222 
223 		rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
224 		if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
225 			l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
226 			return 0;
227 		}
228 	}
229 
230 	/* If set to auto use the default l1tf mitigation method */
231 	if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
232 		switch (l1tf_mitigation) {
233 		case L1TF_MITIGATION_OFF:
234 			l1tf = VMENTER_L1D_FLUSH_NEVER;
235 			break;
236 		case L1TF_MITIGATION_FLUSH_NOWARN:
237 		case L1TF_MITIGATION_FLUSH:
238 		case L1TF_MITIGATION_FLUSH_NOSMT:
239 			l1tf = VMENTER_L1D_FLUSH_COND;
240 			break;
241 		case L1TF_MITIGATION_FULL:
242 		case L1TF_MITIGATION_FULL_FORCE:
243 			l1tf = VMENTER_L1D_FLUSH_ALWAYS;
244 			break;
245 		}
246 	} else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
247 		l1tf = VMENTER_L1D_FLUSH_ALWAYS;
248 	}
249 
250 	if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
251 	    !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
252 		/*
253 		 * This allocation for vmx_l1d_flush_pages is not tied to a VM
254 		 * lifetime and so should not be charged to a memcg.
255 		 */
256 		page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
257 		if (!page)
258 			return -ENOMEM;
259 		vmx_l1d_flush_pages = page_address(page);
260 
261 		/*
262 		 * Initialize each page with a different pattern in
263 		 * order to protect against KSM in the nested
264 		 * virtualization case.
265 		 */
266 		for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
267 			memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
268 			       PAGE_SIZE);
269 		}
270 	}
271 
272 	l1tf_vmx_mitigation = l1tf;
273 
274 	if (l1tf != VMENTER_L1D_FLUSH_NEVER)
275 		static_branch_enable(&vmx_l1d_should_flush);
276 	else
277 		static_branch_disable(&vmx_l1d_should_flush);
278 
279 	if (l1tf == VMENTER_L1D_FLUSH_COND)
280 		static_branch_enable(&vmx_l1d_flush_cond);
281 	else
282 		static_branch_disable(&vmx_l1d_flush_cond);
283 	return 0;
284 }
285 
286 static int vmentry_l1d_flush_parse(const char *s)
287 {
288 	unsigned int i;
289 
290 	if (s) {
291 		for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
292 			if (vmentry_l1d_param[i].for_parse &&
293 			    sysfs_streq(s, vmentry_l1d_param[i].option))
294 				return i;
295 		}
296 	}
297 	return -EINVAL;
298 }
299 
300 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
301 {
302 	int l1tf, ret;
303 
304 	l1tf = vmentry_l1d_flush_parse(s);
305 	if (l1tf < 0)
306 		return l1tf;
307 
308 	if (!boot_cpu_has(X86_BUG_L1TF))
309 		return 0;
310 
311 	/*
312 	 * Has vmx_init() run already? If not then this is the pre init
313 	 * parameter parsing. In that case just store the value and let
314 	 * vmx_init() do the proper setup after enable_ept has been
315 	 * established.
316 	 */
317 	if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
318 		vmentry_l1d_flush_param = l1tf;
319 		return 0;
320 	}
321 
322 	mutex_lock(&vmx_l1d_flush_mutex);
323 	ret = vmx_setup_l1d_flush(l1tf);
324 	mutex_unlock(&vmx_l1d_flush_mutex);
325 	return ret;
326 }
327 
328 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
329 {
330 	if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
331 		return sprintf(s, "???\n");
332 
333 	return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
334 }
335 
336 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
337 	.set = vmentry_l1d_flush_set,
338 	.get = vmentry_l1d_flush_get,
339 };
340 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
341 
342 static bool guest_state_valid(struct kvm_vcpu *vcpu);
343 static u32 vmx_segment_access_rights(struct kvm_segment *var);
344 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
345 							  u32 msr, int type);
346 
347 void vmx_vmexit(void);
348 
349 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
350 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
351 /*
352  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
353  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
354  */
355 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
356 
357 /*
358  * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
359  * can find which vCPU should be waken up.
360  */
361 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
362 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
363 
364 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
365 static DEFINE_SPINLOCK(vmx_vpid_lock);
366 
367 struct vmcs_config vmcs_config;
368 struct vmx_capability vmx_capability;
369 
370 #define VMX_SEGMENT_FIELD(seg)					\
371 	[VCPU_SREG_##seg] = {                                   \
372 		.selector = GUEST_##seg##_SELECTOR,		\
373 		.base = GUEST_##seg##_BASE,		   	\
374 		.limit = GUEST_##seg##_LIMIT,		   	\
375 		.ar_bytes = GUEST_##seg##_AR_BYTES,	   	\
376 	}
377 
378 static const struct kvm_vmx_segment_field {
379 	unsigned selector;
380 	unsigned base;
381 	unsigned limit;
382 	unsigned ar_bytes;
383 } kvm_vmx_segment_fields[] = {
384 	VMX_SEGMENT_FIELD(CS),
385 	VMX_SEGMENT_FIELD(DS),
386 	VMX_SEGMENT_FIELD(ES),
387 	VMX_SEGMENT_FIELD(FS),
388 	VMX_SEGMENT_FIELD(GS),
389 	VMX_SEGMENT_FIELD(SS),
390 	VMX_SEGMENT_FIELD(TR),
391 	VMX_SEGMENT_FIELD(LDTR),
392 };
393 
394 u64 host_efer;
395 
396 /*
397  * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
398  * will emulate SYSCALL in legacy mode if the vendor string in guest
399  * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
400  * support this emulation, IA32_STAR must always be included in
401  * vmx_msr_index[], even in i386 builds.
402  */
403 const u32 vmx_msr_index[] = {
404 #ifdef CONFIG_X86_64
405 	MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
406 #endif
407 	MSR_EFER, MSR_TSC_AUX, MSR_STAR,
408 };
409 
410 #if IS_ENABLED(CONFIG_HYPERV)
411 static bool __read_mostly enlightened_vmcs = true;
412 module_param(enlightened_vmcs, bool, 0444);
413 
414 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
415 static void check_ept_pointer_match(struct kvm *kvm)
416 {
417 	struct kvm_vcpu *vcpu;
418 	u64 tmp_eptp = INVALID_PAGE;
419 	int i;
420 
421 	kvm_for_each_vcpu(i, vcpu, kvm) {
422 		if (!VALID_PAGE(tmp_eptp)) {
423 			tmp_eptp = to_vmx(vcpu)->ept_pointer;
424 		} else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
425 			to_kvm_vmx(kvm)->ept_pointers_match
426 				= EPT_POINTERS_MISMATCH;
427 			return;
428 		}
429 	}
430 
431 	to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
432 }
433 
434 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
435 		void *data)
436 {
437 	struct kvm_tlb_range *range = data;
438 
439 	return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
440 			range->pages);
441 }
442 
443 static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
444 		struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
445 {
446 	u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
447 
448 	/*
449 	 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
450 	 * of the base of EPT PML4 table, strip off EPT configuration
451 	 * information.
452 	 */
453 	if (range)
454 		return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
455 				kvm_fill_hv_flush_list_func, (void *)range);
456 	else
457 		return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
458 }
459 
460 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
461 		struct kvm_tlb_range *range)
462 {
463 	struct kvm_vcpu *vcpu;
464 	int ret = 0, i;
465 
466 	spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
467 
468 	if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
469 		check_ept_pointer_match(kvm);
470 
471 	if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
472 		kvm_for_each_vcpu(i, vcpu, kvm) {
473 			/* If ept_pointer is invalid pointer, bypass flush request. */
474 			if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
475 				ret |= __hv_remote_flush_tlb_with_range(
476 					kvm, vcpu, range);
477 		}
478 	} else {
479 		ret = __hv_remote_flush_tlb_with_range(kvm,
480 				kvm_get_vcpu(kvm, 0), range);
481 	}
482 
483 	spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
484 	return ret;
485 }
486 static int hv_remote_flush_tlb(struct kvm *kvm)
487 {
488 	return hv_remote_flush_tlb_with_range(kvm, NULL);
489 }
490 
491 #endif /* IS_ENABLED(CONFIG_HYPERV) */
492 
493 /*
494  * Comment's format: document - errata name - stepping - processor name.
495  * Refer from
496  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
497  */
498 static u32 vmx_preemption_cpu_tfms[] = {
499 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
500 0x000206E6,
501 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
502 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
503 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
504 0x00020652,
505 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
506 0x00020655,
507 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
508 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
509 /*
510  * 320767.pdf - AAP86  - B1 -
511  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
512  */
513 0x000106E5,
514 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
515 0x000106A0,
516 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
517 0x000106A1,
518 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
519 0x000106A4,
520  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
521  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
522  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
523 0x000106A5,
524  /* Xeon E3-1220 V2 */
525 0x000306A8,
526 };
527 
528 static inline bool cpu_has_broken_vmx_preemption_timer(void)
529 {
530 	u32 eax = cpuid_eax(0x00000001), i;
531 
532 	/* Clear the reserved bits */
533 	eax &= ~(0x3U << 14 | 0xfU << 28);
534 	for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
535 		if (eax == vmx_preemption_cpu_tfms[i])
536 			return true;
537 
538 	return false;
539 }
540 
541 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
542 {
543 	return flexpriority_enabled && lapic_in_kernel(vcpu);
544 }
545 
546 static inline bool report_flexpriority(void)
547 {
548 	return flexpriority_enabled;
549 }
550 
551 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
552 {
553 	int i;
554 
555 	for (i = 0; i < vmx->nmsrs; ++i)
556 		if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
557 			return i;
558 	return -1;
559 }
560 
561 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
562 {
563 	int i;
564 
565 	i = __find_msr_index(vmx, msr);
566 	if (i >= 0)
567 		return &vmx->guest_msrs[i];
568 	return NULL;
569 }
570 
571 void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
572 {
573 	vmcs_clear(loaded_vmcs->vmcs);
574 	if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
575 		vmcs_clear(loaded_vmcs->shadow_vmcs);
576 	loaded_vmcs->cpu = -1;
577 	loaded_vmcs->launched = 0;
578 }
579 
580 #ifdef CONFIG_KEXEC_CORE
581 /*
582  * This bitmap is used to indicate whether the vmclear
583  * operation is enabled on all cpus. All disabled by
584  * default.
585  */
586 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
587 
588 static inline void crash_enable_local_vmclear(int cpu)
589 {
590 	cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
591 }
592 
593 static inline void crash_disable_local_vmclear(int cpu)
594 {
595 	cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
596 }
597 
598 static inline int crash_local_vmclear_enabled(int cpu)
599 {
600 	return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
601 }
602 
603 static void crash_vmclear_local_loaded_vmcss(void)
604 {
605 	int cpu = raw_smp_processor_id();
606 	struct loaded_vmcs *v;
607 
608 	if (!crash_local_vmclear_enabled(cpu))
609 		return;
610 
611 	list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
612 			    loaded_vmcss_on_cpu_link)
613 		vmcs_clear(v->vmcs);
614 }
615 #else
616 static inline void crash_enable_local_vmclear(int cpu) { }
617 static inline void crash_disable_local_vmclear(int cpu) { }
618 #endif /* CONFIG_KEXEC_CORE */
619 
620 static void __loaded_vmcs_clear(void *arg)
621 {
622 	struct loaded_vmcs *loaded_vmcs = arg;
623 	int cpu = raw_smp_processor_id();
624 
625 	if (loaded_vmcs->cpu != cpu)
626 		return; /* vcpu migration can race with cpu offline */
627 	if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
628 		per_cpu(current_vmcs, cpu) = NULL;
629 	crash_disable_local_vmclear(cpu);
630 	list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
631 
632 	/*
633 	 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
634 	 * is before setting loaded_vmcs->vcpu to -1 which is done in
635 	 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
636 	 * then adds the vmcs into percpu list before it is deleted.
637 	 */
638 	smp_wmb();
639 
640 	loaded_vmcs_init(loaded_vmcs);
641 	crash_enable_local_vmclear(cpu);
642 }
643 
644 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
645 {
646 	int cpu = loaded_vmcs->cpu;
647 
648 	if (cpu != -1)
649 		smp_call_function_single(cpu,
650 			 __loaded_vmcs_clear, loaded_vmcs, 1);
651 }
652 
653 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
654 				       unsigned field)
655 {
656 	bool ret;
657 	u32 mask = 1 << (seg * SEG_FIELD_NR + field);
658 
659 	if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
660 		vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
661 		vmx->segment_cache.bitmask = 0;
662 	}
663 	ret = vmx->segment_cache.bitmask & mask;
664 	vmx->segment_cache.bitmask |= mask;
665 	return ret;
666 }
667 
668 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
669 {
670 	u16 *p = &vmx->segment_cache.seg[seg].selector;
671 
672 	if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
673 		*p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
674 	return *p;
675 }
676 
677 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
678 {
679 	ulong *p = &vmx->segment_cache.seg[seg].base;
680 
681 	if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
682 		*p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
683 	return *p;
684 }
685 
686 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
687 {
688 	u32 *p = &vmx->segment_cache.seg[seg].limit;
689 
690 	if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
691 		*p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
692 	return *p;
693 }
694 
695 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
696 {
697 	u32 *p = &vmx->segment_cache.seg[seg].ar;
698 
699 	if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
700 		*p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
701 	return *p;
702 }
703 
704 void update_exception_bitmap(struct kvm_vcpu *vcpu)
705 {
706 	u32 eb;
707 
708 	eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
709 	     (1u << DB_VECTOR) | (1u << AC_VECTOR);
710 	/*
711 	 * Guest access to VMware backdoor ports could legitimately
712 	 * trigger #GP because of TSS I/O permission bitmap.
713 	 * We intercept those #GP and allow access to them anyway
714 	 * as VMware does.
715 	 */
716 	if (enable_vmware_backdoor)
717 		eb |= (1u << GP_VECTOR);
718 	if ((vcpu->guest_debug &
719 	     (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
720 	    (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
721 		eb |= 1u << BP_VECTOR;
722 	if (to_vmx(vcpu)->rmode.vm86_active)
723 		eb = ~0;
724 	if (enable_ept)
725 		eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
726 
727 	/* When we are running a nested L2 guest and L1 specified for it a
728 	 * certain exception bitmap, we must trap the same exceptions and pass
729 	 * them to L1. When running L2, we will only handle the exceptions
730 	 * specified above if L1 did not want them.
731 	 */
732 	if (is_guest_mode(vcpu))
733 		eb |= get_vmcs12(vcpu)->exception_bitmap;
734 
735 	vmcs_write32(EXCEPTION_BITMAP, eb);
736 }
737 
738 /*
739  * Check if MSR is intercepted for currently loaded MSR bitmap.
740  */
741 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
742 {
743 	unsigned long *msr_bitmap;
744 	int f = sizeof(unsigned long);
745 
746 	if (!cpu_has_vmx_msr_bitmap())
747 		return true;
748 
749 	msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
750 
751 	if (msr <= 0x1fff) {
752 		return !!test_bit(msr, msr_bitmap + 0x800 / f);
753 	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
754 		msr &= 0x1fff;
755 		return !!test_bit(msr, msr_bitmap + 0xc00 / f);
756 	}
757 
758 	return true;
759 }
760 
761 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
762 		unsigned long entry, unsigned long exit)
763 {
764 	vm_entry_controls_clearbit(vmx, entry);
765 	vm_exit_controls_clearbit(vmx, exit);
766 }
767 
768 static int find_msr(struct vmx_msrs *m, unsigned int msr)
769 {
770 	unsigned int i;
771 
772 	for (i = 0; i < m->nr; ++i) {
773 		if (m->val[i].index == msr)
774 			return i;
775 	}
776 	return -ENOENT;
777 }
778 
779 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
780 {
781 	int i;
782 	struct msr_autoload *m = &vmx->msr_autoload;
783 
784 	switch (msr) {
785 	case MSR_EFER:
786 		if (cpu_has_load_ia32_efer()) {
787 			clear_atomic_switch_msr_special(vmx,
788 					VM_ENTRY_LOAD_IA32_EFER,
789 					VM_EXIT_LOAD_IA32_EFER);
790 			return;
791 		}
792 		break;
793 	case MSR_CORE_PERF_GLOBAL_CTRL:
794 		if (cpu_has_load_perf_global_ctrl()) {
795 			clear_atomic_switch_msr_special(vmx,
796 					VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
797 					VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
798 			return;
799 		}
800 		break;
801 	}
802 	i = find_msr(&m->guest, msr);
803 	if (i < 0)
804 		goto skip_guest;
805 	--m->guest.nr;
806 	m->guest.val[i] = m->guest.val[m->guest.nr];
807 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
808 
809 skip_guest:
810 	i = find_msr(&m->host, msr);
811 	if (i < 0)
812 		return;
813 
814 	--m->host.nr;
815 	m->host.val[i] = m->host.val[m->host.nr];
816 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
817 }
818 
819 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
820 		unsigned long entry, unsigned long exit,
821 		unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
822 		u64 guest_val, u64 host_val)
823 {
824 	vmcs_write64(guest_val_vmcs, guest_val);
825 	if (host_val_vmcs != HOST_IA32_EFER)
826 		vmcs_write64(host_val_vmcs, host_val);
827 	vm_entry_controls_setbit(vmx, entry);
828 	vm_exit_controls_setbit(vmx, exit);
829 }
830 
831 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
832 				  u64 guest_val, u64 host_val, bool entry_only)
833 {
834 	int i, j = 0;
835 	struct msr_autoload *m = &vmx->msr_autoload;
836 
837 	switch (msr) {
838 	case MSR_EFER:
839 		if (cpu_has_load_ia32_efer()) {
840 			add_atomic_switch_msr_special(vmx,
841 					VM_ENTRY_LOAD_IA32_EFER,
842 					VM_EXIT_LOAD_IA32_EFER,
843 					GUEST_IA32_EFER,
844 					HOST_IA32_EFER,
845 					guest_val, host_val);
846 			return;
847 		}
848 		break;
849 	case MSR_CORE_PERF_GLOBAL_CTRL:
850 		if (cpu_has_load_perf_global_ctrl()) {
851 			add_atomic_switch_msr_special(vmx,
852 					VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
853 					VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
854 					GUEST_IA32_PERF_GLOBAL_CTRL,
855 					HOST_IA32_PERF_GLOBAL_CTRL,
856 					guest_val, host_val);
857 			return;
858 		}
859 		break;
860 	case MSR_IA32_PEBS_ENABLE:
861 		/* PEBS needs a quiescent period after being disabled (to write
862 		 * a record).  Disabling PEBS through VMX MSR swapping doesn't
863 		 * provide that period, so a CPU could write host's record into
864 		 * guest's memory.
865 		 */
866 		wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
867 	}
868 
869 	i = find_msr(&m->guest, msr);
870 	if (!entry_only)
871 		j = find_msr(&m->host, msr);
872 
873 	if ((i < 0 && m->guest.nr == NR_AUTOLOAD_MSRS) ||
874 		(j < 0 &&  m->host.nr == NR_AUTOLOAD_MSRS)) {
875 		printk_once(KERN_WARNING "Not enough msr switch entries. "
876 				"Can't add msr %x\n", msr);
877 		return;
878 	}
879 	if (i < 0) {
880 		i = m->guest.nr++;
881 		vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
882 	}
883 	m->guest.val[i].index = msr;
884 	m->guest.val[i].value = guest_val;
885 
886 	if (entry_only)
887 		return;
888 
889 	if (j < 0) {
890 		j = m->host.nr++;
891 		vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
892 	}
893 	m->host.val[j].index = msr;
894 	m->host.val[j].value = host_val;
895 }
896 
897 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
898 {
899 	u64 guest_efer = vmx->vcpu.arch.efer;
900 	u64 ignore_bits = 0;
901 
902 	if (!enable_ept) {
903 		/*
904 		 * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
905 		 * host CPUID is more efficient than testing guest CPUID
906 		 * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
907 		 */
908 		if (boot_cpu_has(X86_FEATURE_SMEP))
909 			guest_efer |= EFER_NX;
910 		else if (!(guest_efer & EFER_NX))
911 			ignore_bits |= EFER_NX;
912 	}
913 
914 	/*
915 	 * LMA and LME handled by hardware; SCE meaningless outside long mode.
916 	 */
917 	ignore_bits |= EFER_SCE;
918 #ifdef CONFIG_X86_64
919 	ignore_bits |= EFER_LMA | EFER_LME;
920 	/* SCE is meaningful only in long mode on Intel */
921 	if (guest_efer & EFER_LMA)
922 		ignore_bits &= ~(u64)EFER_SCE;
923 #endif
924 
925 	/*
926 	 * On EPT, we can't emulate NX, so we must switch EFER atomically.
927 	 * On CPUs that support "load IA32_EFER", always switch EFER
928 	 * atomically, since it's faster than switching it manually.
929 	 */
930 	if (cpu_has_load_ia32_efer() ||
931 	    (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
932 		if (!(guest_efer & EFER_LMA))
933 			guest_efer &= ~EFER_LME;
934 		if (guest_efer != host_efer)
935 			add_atomic_switch_msr(vmx, MSR_EFER,
936 					      guest_efer, host_efer, false);
937 		else
938 			clear_atomic_switch_msr(vmx, MSR_EFER);
939 		return false;
940 	} else {
941 		clear_atomic_switch_msr(vmx, MSR_EFER);
942 
943 		guest_efer &= ~ignore_bits;
944 		guest_efer |= host_efer & ignore_bits;
945 
946 		vmx->guest_msrs[efer_offset].data = guest_efer;
947 		vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
948 
949 		return true;
950 	}
951 }
952 
953 #ifdef CONFIG_X86_32
954 /*
955  * On 32-bit kernels, VM exits still load the FS and GS bases from the
956  * VMCS rather than the segment table.  KVM uses this helper to figure
957  * out the current bases to poke them into the VMCS before entry.
958  */
959 static unsigned long segment_base(u16 selector)
960 {
961 	struct desc_struct *table;
962 	unsigned long v;
963 
964 	if (!(selector & ~SEGMENT_RPL_MASK))
965 		return 0;
966 
967 	table = get_current_gdt_ro();
968 
969 	if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
970 		u16 ldt_selector = kvm_read_ldt();
971 
972 		if (!(ldt_selector & ~SEGMENT_RPL_MASK))
973 			return 0;
974 
975 		table = (struct desc_struct *)segment_base(ldt_selector);
976 	}
977 	v = get_desc_base(&table[selector >> 3]);
978 	return v;
979 }
980 #endif
981 
982 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
983 {
984 	u32 i;
985 
986 	wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
987 	wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
988 	wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
989 	wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
990 	for (i = 0; i < addr_range; i++) {
991 		wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
992 		wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
993 	}
994 }
995 
996 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
997 {
998 	u32 i;
999 
1000 	rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1001 	rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1002 	rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1003 	rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1004 	for (i = 0; i < addr_range; i++) {
1005 		rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1006 		rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1007 	}
1008 }
1009 
1010 static void pt_guest_enter(struct vcpu_vmx *vmx)
1011 {
1012 	if (pt_mode == PT_MODE_SYSTEM)
1013 		return;
1014 
1015 	/*
1016 	 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1017 	 * Save host state before VM entry.
1018 	 */
1019 	rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1020 	if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1021 		wrmsrl(MSR_IA32_RTIT_CTL, 0);
1022 		pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1023 		pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1024 	}
1025 }
1026 
1027 static void pt_guest_exit(struct vcpu_vmx *vmx)
1028 {
1029 	if (pt_mode == PT_MODE_SYSTEM)
1030 		return;
1031 
1032 	if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1033 		pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1034 		pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1035 	}
1036 
1037 	/* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1038 	wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1039 }
1040 
1041 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1042 {
1043 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1044 	struct vmcs_host_state *host_state;
1045 #ifdef CONFIG_X86_64
1046 	int cpu = raw_smp_processor_id();
1047 #endif
1048 	unsigned long fs_base, gs_base;
1049 	u16 fs_sel, gs_sel;
1050 	int i;
1051 
1052 	vmx->req_immediate_exit = false;
1053 
1054 	/*
1055 	 * Note that guest MSRs to be saved/restored can also be changed
1056 	 * when guest state is loaded. This happens when guest transitions
1057 	 * to/from long-mode by setting MSR_EFER.LMA.
1058 	 */
1059 	if (!vmx->loaded_cpu_state || vmx->guest_msrs_dirty) {
1060 		vmx->guest_msrs_dirty = false;
1061 		for (i = 0; i < vmx->save_nmsrs; ++i)
1062 			kvm_set_shared_msr(vmx->guest_msrs[i].index,
1063 					   vmx->guest_msrs[i].data,
1064 					   vmx->guest_msrs[i].mask);
1065 
1066 	}
1067 
1068 	if (vmx->loaded_cpu_state)
1069 		return;
1070 
1071 	vmx->loaded_cpu_state = vmx->loaded_vmcs;
1072 	host_state = &vmx->loaded_cpu_state->host_state;
1073 
1074 	/*
1075 	 * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
1076 	 * allow segment selectors with cpl > 0 or ti == 1.
1077 	 */
1078 	host_state->ldt_sel = kvm_read_ldt();
1079 
1080 #ifdef CONFIG_X86_64
1081 	savesegment(ds, host_state->ds_sel);
1082 	savesegment(es, host_state->es_sel);
1083 
1084 	gs_base = cpu_kernelmode_gs_base(cpu);
1085 	if (likely(is_64bit_mm(current->mm))) {
1086 		save_fsgs_for_kvm();
1087 		fs_sel = current->thread.fsindex;
1088 		gs_sel = current->thread.gsindex;
1089 		fs_base = current->thread.fsbase;
1090 		vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1091 	} else {
1092 		savesegment(fs, fs_sel);
1093 		savesegment(gs, gs_sel);
1094 		fs_base = read_msr(MSR_FS_BASE);
1095 		vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1096 	}
1097 
1098 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1099 #else
1100 	savesegment(fs, fs_sel);
1101 	savesegment(gs, gs_sel);
1102 	fs_base = segment_base(fs_sel);
1103 	gs_base = segment_base(gs_sel);
1104 #endif
1105 
1106 	if (unlikely(fs_sel != host_state->fs_sel)) {
1107 		if (!(fs_sel & 7))
1108 			vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1109 		else
1110 			vmcs_write16(HOST_FS_SELECTOR, 0);
1111 		host_state->fs_sel = fs_sel;
1112 	}
1113 	if (unlikely(gs_sel != host_state->gs_sel)) {
1114 		if (!(gs_sel & 7))
1115 			vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1116 		else
1117 			vmcs_write16(HOST_GS_SELECTOR, 0);
1118 		host_state->gs_sel = gs_sel;
1119 	}
1120 	if (unlikely(fs_base != host_state->fs_base)) {
1121 		vmcs_writel(HOST_FS_BASE, fs_base);
1122 		host_state->fs_base = fs_base;
1123 	}
1124 	if (unlikely(gs_base != host_state->gs_base)) {
1125 		vmcs_writel(HOST_GS_BASE, gs_base);
1126 		host_state->gs_base = gs_base;
1127 	}
1128 }
1129 
1130 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1131 {
1132 	struct vmcs_host_state *host_state;
1133 
1134 	if (!vmx->loaded_cpu_state)
1135 		return;
1136 
1137 	WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
1138 	host_state = &vmx->loaded_cpu_state->host_state;
1139 
1140 	++vmx->vcpu.stat.host_state_reload;
1141 	vmx->loaded_cpu_state = NULL;
1142 
1143 #ifdef CONFIG_X86_64
1144 	rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1145 #endif
1146 	if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1147 		kvm_load_ldt(host_state->ldt_sel);
1148 #ifdef CONFIG_X86_64
1149 		load_gs_index(host_state->gs_sel);
1150 #else
1151 		loadsegment(gs, host_state->gs_sel);
1152 #endif
1153 	}
1154 	if (host_state->fs_sel & 7)
1155 		loadsegment(fs, host_state->fs_sel);
1156 #ifdef CONFIG_X86_64
1157 	if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1158 		loadsegment(ds, host_state->ds_sel);
1159 		loadsegment(es, host_state->es_sel);
1160 	}
1161 #endif
1162 	invalidate_tss_limit();
1163 #ifdef CONFIG_X86_64
1164 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1165 #endif
1166 	load_fixmap_gdt(raw_smp_processor_id());
1167 }
1168 
1169 #ifdef CONFIG_X86_64
1170 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1171 {
1172 	preempt_disable();
1173 	if (vmx->loaded_cpu_state)
1174 		rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1175 	preempt_enable();
1176 	return vmx->msr_guest_kernel_gs_base;
1177 }
1178 
1179 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1180 {
1181 	preempt_disable();
1182 	if (vmx->loaded_cpu_state)
1183 		wrmsrl(MSR_KERNEL_GS_BASE, data);
1184 	preempt_enable();
1185 	vmx->msr_guest_kernel_gs_base = data;
1186 }
1187 #endif
1188 
1189 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1190 {
1191 	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1192 	struct pi_desc old, new;
1193 	unsigned int dest;
1194 
1195 	/*
1196 	 * In case of hot-plug or hot-unplug, we may have to undo
1197 	 * vmx_vcpu_pi_put even if there is no assigned device.  And we
1198 	 * always keep PI.NDST up to date for simplicity: it makes the
1199 	 * code easier, and CPU migration is not a fast path.
1200 	 */
1201 	if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1202 		return;
1203 
1204 	/* The full case.  */
1205 	do {
1206 		old.control = new.control = pi_desc->control;
1207 
1208 		dest = cpu_physical_id(cpu);
1209 
1210 		if (x2apic_enabled())
1211 			new.ndst = dest;
1212 		else
1213 			new.ndst = (dest << 8) & 0xFF00;
1214 
1215 		new.sn = 0;
1216 	} while (cmpxchg64(&pi_desc->control, old.control,
1217 			   new.control) != old.control);
1218 
1219 	/*
1220 	 * Clear SN before reading the bitmap.  The VT-d firmware
1221 	 * writes the bitmap and reads SN atomically (5.2.3 in the
1222 	 * spec), so it doesn't really have a memory barrier that
1223 	 * pairs with this, but we cannot do that and we need one.
1224 	 */
1225 	smp_mb__after_atomic();
1226 
1227 	if (!bitmap_empty((unsigned long *)pi_desc->pir, NR_VECTORS))
1228 		pi_set_on(pi_desc);
1229 }
1230 
1231 /*
1232  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1233  * vcpu mutex is already taken.
1234  */
1235 void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1236 {
1237 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1238 	bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1239 
1240 	if (!already_loaded) {
1241 		loaded_vmcs_clear(vmx->loaded_vmcs);
1242 		local_irq_disable();
1243 		crash_disable_local_vmclear(cpu);
1244 
1245 		/*
1246 		 * Read loaded_vmcs->cpu should be before fetching
1247 		 * loaded_vmcs->loaded_vmcss_on_cpu_link.
1248 		 * See the comments in __loaded_vmcs_clear().
1249 		 */
1250 		smp_rmb();
1251 
1252 		list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1253 			 &per_cpu(loaded_vmcss_on_cpu, cpu));
1254 		crash_enable_local_vmclear(cpu);
1255 		local_irq_enable();
1256 	}
1257 
1258 	if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1259 		per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1260 		vmcs_load(vmx->loaded_vmcs->vmcs);
1261 		indirect_branch_prediction_barrier();
1262 	}
1263 
1264 	if (!already_loaded) {
1265 		void *gdt = get_current_gdt_ro();
1266 		unsigned long sysenter_esp;
1267 
1268 		kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1269 
1270 		/*
1271 		 * Linux uses per-cpu TSS and GDT, so set these when switching
1272 		 * processors.  See 22.2.4.
1273 		 */
1274 		vmcs_writel(HOST_TR_BASE,
1275 			    (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1276 		vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
1277 
1278 		/*
1279 		 * VM exits change the host TR limit to 0x67 after a VM
1280 		 * exit.  This is okay, since 0x67 covers everything except
1281 		 * the IO bitmap and have have code to handle the IO bitmap
1282 		 * being lost after a VM exit.
1283 		 */
1284 		BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
1285 
1286 		rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1287 		vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1288 
1289 		vmx->loaded_vmcs->cpu = cpu;
1290 	}
1291 
1292 	/* Setup TSC multiplier */
1293 	if (kvm_has_tsc_control &&
1294 	    vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1295 		decache_tsc_multiplier(vmx);
1296 
1297 	vmx_vcpu_pi_load(vcpu, cpu);
1298 	vmx->host_pkru = read_pkru();
1299 	vmx->host_debugctlmsr = get_debugctlmsr();
1300 }
1301 
1302 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1303 {
1304 	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1305 
1306 	if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1307 		!irq_remapping_cap(IRQ_POSTING_CAP)  ||
1308 		!kvm_vcpu_apicv_active(vcpu))
1309 		return;
1310 
1311 	/* Set SN when the vCPU is preempted */
1312 	if (vcpu->preempted)
1313 		pi_set_sn(pi_desc);
1314 }
1315 
1316 void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1317 {
1318 	vmx_vcpu_pi_put(vcpu);
1319 
1320 	vmx_prepare_switch_to_host(to_vmx(vcpu));
1321 }
1322 
1323 static bool emulation_required(struct kvm_vcpu *vcpu)
1324 {
1325 	return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1326 }
1327 
1328 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1329 
1330 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1331 {
1332 	unsigned long rflags, save_rflags;
1333 
1334 	if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1335 		__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1336 		rflags = vmcs_readl(GUEST_RFLAGS);
1337 		if (to_vmx(vcpu)->rmode.vm86_active) {
1338 			rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1339 			save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1340 			rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1341 		}
1342 		to_vmx(vcpu)->rflags = rflags;
1343 	}
1344 	return to_vmx(vcpu)->rflags;
1345 }
1346 
1347 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1348 {
1349 	unsigned long old_rflags = vmx_get_rflags(vcpu);
1350 
1351 	__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1352 	to_vmx(vcpu)->rflags = rflags;
1353 	if (to_vmx(vcpu)->rmode.vm86_active) {
1354 		to_vmx(vcpu)->rmode.save_rflags = rflags;
1355 		rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1356 	}
1357 	vmcs_writel(GUEST_RFLAGS, rflags);
1358 
1359 	if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
1360 		to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
1361 }
1362 
1363 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1364 {
1365 	u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1366 	int ret = 0;
1367 
1368 	if (interruptibility & GUEST_INTR_STATE_STI)
1369 		ret |= KVM_X86_SHADOW_INT_STI;
1370 	if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1371 		ret |= KVM_X86_SHADOW_INT_MOV_SS;
1372 
1373 	return ret;
1374 }
1375 
1376 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1377 {
1378 	u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1379 	u32 interruptibility = interruptibility_old;
1380 
1381 	interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1382 
1383 	if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1384 		interruptibility |= GUEST_INTR_STATE_MOV_SS;
1385 	else if (mask & KVM_X86_SHADOW_INT_STI)
1386 		interruptibility |= GUEST_INTR_STATE_STI;
1387 
1388 	if ((interruptibility != interruptibility_old))
1389 		vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1390 }
1391 
1392 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1393 {
1394 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1395 	unsigned long value;
1396 
1397 	/*
1398 	 * Any MSR write that attempts to change bits marked reserved will
1399 	 * case a #GP fault.
1400 	 */
1401 	if (data & vmx->pt_desc.ctl_bitmask)
1402 		return 1;
1403 
1404 	/*
1405 	 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1406 	 * result in a #GP unless the same write also clears TraceEn.
1407 	 */
1408 	if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1409 		((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1410 		return 1;
1411 
1412 	/*
1413 	 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1414 	 * and FabricEn would cause #GP, if
1415 	 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1416 	 */
1417 	if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1418 		!(data & RTIT_CTL_FABRIC_EN) &&
1419 		!intel_pt_validate_cap(vmx->pt_desc.caps,
1420 					PT_CAP_single_range_output))
1421 		return 1;
1422 
1423 	/*
1424 	 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1425 	 * utilize encodings marked reserved will casue a #GP fault.
1426 	 */
1427 	value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1428 	if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1429 			!test_bit((data & RTIT_CTL_MTC_RANGE) >>
1430 			RTIT_CTL_MTC_RANGE_OFFSET, &value))
1431 		return 1;
1432 	value = intel_pt_validate_cap(vmx->pt_desc.caps,
1433 						PT_CAP_cycle_thresholds);
1434 	if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1435 			!test_bit((data & RTIT_CTL_CYC_THRESH) >>
1436 			RTIT_CTL_CYC_THRESH_OFFSET, &value))
1437 		return 1;
1438 	value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1439 	if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1440 			!test_bit((data & RTIT_CTL_PSB_FREQ) >>
1441 			RTIT_CTL_PSB_FREQ_OFFSET, &value))
1442 		return 1;
1443 
1444 	/*
1445 	 * If ADDRx_CFG is reserved or the encodings is >2 will
1446 	 * cause a #GP fault.
1447 	 */
1448 	value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1449 	if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1450 		return 1;
1451 	value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1452 	if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1453 		return 1;
1454 	value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1455 	if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1456 		return 1;
1457 	value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1458 	if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1459 		return 1;
1460 
1461 	return 0;
1462 }
1463 
1464 
1465 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1466 {
1467 	unsigned long rip;
1468 
1469 	rip = kvm_rip_read(vcpu);
1470 	rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1471 	kvm_rip_write(vcpu, rip);
1472 
1473 	/* skipping an emulated instruction also counts */
1474 	vmx_set_interrupt_shadow(vcpu, 0);
1475 }
1476 
1477 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1478 {
1479 	/*
1480 	 * Ensure that we clear the HLT state in the VMCS.  We don't need to
1481 	 * explicitly skip the instruction because if the HLT state is set,
1482 	 * then the instruction is already executing and RIP has already been
1483 	 * advanced.
1484 	 */
1485 	if (kvm_hlt_in_guest(vcpu->kvm) &&
1486 			vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1487 		vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1488 }
1489 
1490 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1491 {
1492 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1493 	unsigned nr = vcpu->arch.exception.nr;
1494 	bool has_error_code = vcpu->arch.exception.has_error_code;
1495 	u32 error_code = vcpu->arch.exception.error_code;
1496 	u32 intr_info = nr | INTR_INFO_VALID_MASK;
1497 
1498 	kvm_deliver_exception_payload(vcpu);
1499 
1500 	if (has_error_code) {
1501 		vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1502 		intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1503 	}
1504 
1505 	if (vmx->rmode.vm86_active) {
1506 		int inc_eip = 0;
1507 		if (kvm_exception_is_soft(nr))
1508 			inc_eip = vcpu->arch.event_exit_inst_len;
1509 		if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1510 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1511 		return;
1512 	}
1513 
1514 	WARN_ON_ONCE(vmx->emulation_required);
1515 
1516 	if (kvm_exception_is_soft(nr)) {
1517 		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1518 			     vmx->vcpu.arch.event_exit_inst_len);
1519 		intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1520 	} else
1521 		intr_info |= INTR_TYPE_HARD_EXCEPTION;
1522 
1523 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1524 
1525 	vmx_clear_hlt(vcpu);
1526 }
1527 
1528 static bool vmx_rdtscp_supported(void)
1529 {
1530 	return cpu_has_vmx_rdtscp();
1531 }
1532 
1533 static bool vmx_invpcid_supported(void)
1534 {
1535 	return cpu_has_vmx_invpcid();
1536 }
1537 
1538 /*
1539  * Swap MSR entry in host/guest MSR entry array.
1540  */
1541 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1542 {
1543 	struct shared_msr_entry tmp;
1544 
1545 	tmp = vmx->guest_msrs[to];
1546 	vmx->guest_msrs[to] = vmx->guest_msrs[from];
1547 	vmx->guest_msrs[from] = tmp;
1548 }
1549 
1550 /*
1551  * Set up the vmcs to automatically save and restore system
1552  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
1553  * mode, as fiddling with msrs is very expensive.
1554  */
1555 static void setup_msrs(struct vcpu_vmx *vmx)
1556 {
1557 	int save_nmsrs, index;
1558 
1559 	save_nmsrs = 0;
1560 #ifdef CONFIG_X86_64
1561 	/*
1562 	 * The SYSCALL MSRs are only needed on long mode guests, and only
1563 	 * when EFER.SCE is set.
1564 	 */
1565 	if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1566 		index = __find_msr_index(vmx, MSR_STAR);
1567 		if (index >= 0)
1568 			move_msr_up(vmx, index, save_nmsrs++);
1569 		index = __find_msr_index(vmx, MSR_LSTAR);
1570 		if (index >= 0)
1571 			move_msr_up(vmx, index, save_nmsrs++);
1572 		index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1573 		if (index >= 0)
1574 			move_msr_up(vmx, index, save_nmsrs++);
1575 	}
1576 #endif
1577 	index = __find_msr_index(vmx, MSR_EFER);
1578 	if (index >= 0 && update_transition_efer(vmx, index))
1579 		move_msr_up(vmx, index, save_nmsrs++);
1580 	index = __find_msr_index(vmx, MSR_TSC_AUX);
1581 	if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1582 		move_msr_up(vmx, index, save_nmsrs++);
1583 
1584 	vmx->save_nmsrs = save_nmsrs;
1585 	vmx->guest_msrs_dirty = true;
1586 
1587 	if (cpu_has_vmx_msr_bitmap())
1588 		vmx_update_msr_bitmap(&vmx->vcpu);
1589 }
1590 
1591 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1592 {
1593 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1594 
1595 	if (is_guest_mode(vcpu) &&
1596 	    (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1597 		return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
1598 
1599 	return vcpu->arch.tsc_offset;
1600 }
1601 
1602 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1603 {
1604 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1605 	u64 g_tsc_offset = 0;
1606 
1607 	/*
1608 	 * We're here if L1 chose not to trap WRMSR to TSC. According
1609 	 * to the spec, this should set L1's TSC; The offset that L1
1610 	 * set for L2 remains unchanged, and still needs to be added
1611 	 * to the newly set TSC to get L2's TSC.
1612 	 */
1613 	if (is_guest_mode(vcpu) &&
1614 	    (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1615 		g_tsc_offset = vmcs12->tsc_offset;
1616 
1617 	trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1618 				   vcpu->arch.tsc_offset - g_tsc_offset,
1619 				   offset);
1620 	vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1621 	return offset + g_tsc_offset;
1622 }
1623 
1624 /*
1625  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1626  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1627  * all guests if the "nested" module option is off, and can also be disabled
1628  * for a single guest by disabling its VMX cpuid bit.
1629  */
1630 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1631 {
1632 	return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1633 }
1634 
1635 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1636 						 uint64_t val)
1637 {
1638 	uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1639 
1640 	return !(val & ~valid_bits);
1641 }
1642 
1643 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1644 {
1645 	switch (msr->index) {
1646 	case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1647 		if (!nested)
1648 			return 1;
1649 		return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1650 	default:
1651 		return 1;
1652 	}
1653 
1654 	return 0;
1655 }
1656 
1657 /*
1658  * Reads an msr value (of 'msr_index') into 'pdata'.
1659  * Returns 0 on success, non-0 otherwise.
1660  * Assumes vcpu_load() was already called.
1661  */
1662 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1663 {
1664 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1665 	struct shared_msr_entry *msr;
1666 	u32 index;
1667 
1668 	switch (msr_info->index) {
1669 #ifdef CONFIG_X86_64
1670 	case MSR_FS_BASE:
1671 		msr_info->data = vmcs_readl(GUEST_FS_BASE);
1672 		break;
1673 	case MSR_GS_BASE:
1674 		msr_info->data = vmcs_readl(GUEST_GS_BASE);
1675 		break;
1676 	case MSR_KERNEL_GS_BASE:
1677 		msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1678 		break;
1679 #endif
1680 	case MSR_EFER:
1681 		return kvm_get_msr_common(vcpu, msr_info);
1682 	case MSR_IA32_SPEC_CTRL:
1683 		if (!msr_info->host_initiated &&
1684 		    !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1685 			return 1;
1686 
1687 		msr_info->data = to_vmx(vcpu)->spec_ctrl;
1688 		break;
1689 	case MSR_IA32_SYSENTER_CS:
1690 		msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1691 		break;
1692 	case MSR_IA32_SYSENTER_EIP:
1693 		msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1694 		break;
1695 	case MSR_IA32_SYSENTER_ESP:
1696 		msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1697 		break;
1698 	case MSR_IA32_POWER_CTL:
1699 		msr_info->data = vmx->msr_ia32_power_ctl;
1700 		break;
1701 	case MSR_IA32_BNDCFGS:
1702 		if (!kvm_mpx_supported() ||
1703 		    (!msr_info->host_initiated &&
1704 		     !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1705 			return 1;
1706 		msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1707 		break;
1708 	case MSR_IA32_MCG_EXT_CTL:
1709 		if (!msr_info->host_initiated &&
1710 		    !(vmx->msr_ia32_feature_control &
1711 		      FEATURE_CONTROL_LMCE))
1712 			return 1;
1713 		msr_info->data = vcpu->arch.mcg_ext_ctl;
1714 		break;
1715 	case MSR_IA32_FEATURE_CONTROL:
1716 		msr_info->data = vmx->msr_ia32_feature_control;
1717 		break;
1718 	case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1719 		if (!nested_vmx_allowed(vcpu))
1720 			return 1;
1721 		return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1722 				       &msr_info->data);
1723 	case MSR_IA32_XSS:
1724 		if (!vmx_xsaves_supported())
1725 			return 1;
1726 		msr_info->data = vcpu->arch.ia32_xss;
1727 		break;
1728 	case MSR_IA32_RTIT_CTL:
1729 		if (pt_mode != PT_MODE_HOST_GUEST)
1730 			return 1;
1731 		msr_info->data = vmx->pt_desc.guest.ctl;
1732 		break;
1733 	case MSR_IA32_RTIT_STATUS:
1734 		if (pt_mode != PT_MODE_HOST_GUEST)
1735 			return 1;
1736 		msr_info->data = vmx->pt_desc.guest.status;
1737 		break;
1738 	case MSR_IA32_RTIT_CR3_MATCH:
1739 		if ((pt_mode != PT_MODE_HOST_GUEST) ||
1740 			!intel_pt_validate_cap(vmx->pt_desc.caps,
1741 						PT_CAP_cr3_filtering))
1742 			return 1;
1743 		msr_info->data = vmx->pt_desc.guest.cr3_match;
1744 		break;
1745 	case MSR_IA32_RTIT_OUTPUT_BASE:
1746 		if ((pt_mode != PT_MODE_HOST_GUEST) ||
1747 			(!intel_pt_validate_cap(vmx->pt_desc.caps,
1748 					PT_CAP_topa_output) &&
1749 			 !intel_pt_validate_cap(vmx->pt_desc.caps,
1750 					PT_CAP_single_range_output)))
1751 			return 1;
1752 		msr_info->data = vmx->pt_desc.guest.output_base;
1753 		break;
1754 	case MSR_IA32_RTIT_OUTPUT_MASK:
1755 		if ((pt_mode != PT_MODE_HOST_GUEST) ||
1756 			(!intel_pt_validate_cap(vmx->pt_desc.caps,
1757 					PT_CAP_topa_output) &&
1758 			 !intel_pt_validate_cap(vmx->pt_desc.caps,
1759 					PT_CAP_single_range_output)))
1760 			return 1;
1761 		msr_info->data = vmx->pt_desc.guest.output_mask;
1762 		break;
1763 	case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1764 		index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1765 		if ((pt_mode != PT_MODE_HOST_GUEST) ||
1766 			(index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1767 					PT_CAP_num_address_ranges)))
1768 			return 1;
1769 		if (index % 2)
1770 			msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1771 		else
1772 			msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1773 		break;
1774 	case MSR_TSC_AUX:
1775 		if (!msr_info->host_initiated &&
1776 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1777 			return 1;
1778 		/* Else, falls through */
1779 	default:
1780 		msr = find_msr_entry(vmx, msr_info->index);
1781 		if (msr) {
1782 			msr_info->data = msr->data;
1783 			break;
1784 		}
1785 		return kvm_get_msr_common(vcpu, msr_info);
1786 	}
1787 
1788 	return 0;
1789 }
1790 
1791 /*
1792  * Writes msr value into into the appropriate "register".
1793  * Returns 0 on success, non-0 otherwise.
1794  * Assumes vcpu_load() was already called.
1795  */
1796 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1797 {
1798 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1799 	struct shared_msr_entry *msr;
1800 	int ret = 0;
1801 	u32 msr_index = msr_info->index;
1802 	u64 data = msr_info->data;
1803 	u32 index;
1804 
1805 	switch (msr_index) {
1806 	case MSR_EFER:
1807 		ret = kvm_set_msr_common(vcpu, msr_info);
1808 		break;
1809 #ifdef CONFIG_X86_64
1810 	case MSR_FS_BASE:
1811 		vmx_segment_cache_clear(vmx);
1812 		vmcs_writel(GUEST_FS_BASE, data);
1813 		break;
1814 	case MSR_GS_BASE:
1815 		vmx_segment_cache_clear(vmx);
1816 		vmcs_writel(GUEST_GS_BASE, data);
1817 		break;
1818 	case MSR_KERNEL_GS_BASE:
1819 		vmx_write_guest_kernel_gs_base(vmx, data);
1820 		break;
1821 #endif
1822 	case MSR_IA32_SYSENTER_CS:
1823 		vmcs_write32(GUEST_SYSENTER_CS, data);
1824 		break;
1825 	case MSR_IA32_SYSENTER_EIP:
1826 		vmcs_writel(GUEST_SYSENTER_EIP, data);
1827 		break;
1828 	case MSR_IA32_SYSENTER_ESP:
1829 		vmcs_writel(GUEST_SYSENTER_ESP, data);
1830 		break;
1831 	case MSR_IA32_POWER_CTL:
1832 		vmx->msr_ia32_power_ctl = data;
1833 		break;
1834 	case MSR_IA32_BNDCFGS:
1835 		if (!kvm_mpx_supported() ||
1836 		    (!msr_info->host_initiated &&
1837 		     !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1838 			return 1;
1839 		if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
1840 		    (data & MSR_IA32_BNDCFGS_RSVD))
1841 			return 1;
1842 		vmcs_write64(GUEST_BNDCFGS, data);
1843 		break;
1844 	case MSR_IA32_SPEC_CTRL:
1845 		if (!msr_info->host_initiated &&
1846 		    !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1847 			return 1;
1848 
1849 		/* The STIBP bit doesn't fault even if it's not advertised */
1850 		if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
1851 			return 1;
1852 
1853 		vmx->spec_ctrl = data;
1854 
1855 		if (!data)
1856 			break;
1857 
1858 		/*
1859 		 * For non-nested:
1860 		 * When it's written (to non-zero) for the first time, pass
1861 		 * it through.
1862 		 *
1863 		 * For nested:
1864 		 * The handling of the MSR bitmap for L2 guests is done in
1865 		 * nested_vmx_merge_msr_bitmap. We should not touch the
1866 		 * vmcs02.msr_bitmap here since it gets completely overwritten
1867 		 * in the merging. We update the vmcs01 here for L1 as well
1868 		 * since it will end up touching the MSR anyway now.
1869 		 */
1870 		vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
1871 					      MSR_IA32_SPEC_CTRL,
1872 					      MSR_TYPE_RW);
1873 		break;
1874 	case MSR_IA32_PRED_CMD:
1875 		if (!msr_info->host_initiated &&
1876 		    !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1877 			return 1;
1878 
1879 		if (data & ~PRED_CMD_IBPB)
1880 			return 1;
1881 
1882 		if (!data)
1883 			break;
1884 
1885 		wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
1886 
1887 		/*
1888 		 * For non-nested:
1889 		 * When it's written (to non-zero) for the first time, pass
1890 		 * it through.
1891 		 *
1892 		 * For nested:
1893 		 * The handling of the MSR bitmap for L2 guests is done in
1894 		 * nested_vmx_merge_msr_bitmap. We should not touch the
1895 		 * vmcs02.msr_bitmap here since it gets completely overwritten
1896 		 * in the merging.
1897 		 */
1898 		vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
1899 					      MSR_TYPE_W);
1900 		break;
1901 	case MSR_IA32_CR_PAT:
1902 		if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
1903 			if (!kvm_pat_valid(data))
1904 				return 1;
1905 			vmcs_write64(GUEST_IA32_PAT, data);
1906 			vcpu->arch.pat = data;
1907 			break;
1908 		}
1909 		ret = kvm_set_msr_common(vcpu, msr_info);
1910 		break;
1911 	case MSR_IA32_TSC_ADJUST:
1912 		ret = kvm_set_msr_common(vcpu, msr_info);
1913 		break;
1914 	case MSR_IA32_MCG_EXT_CTL:
1915 		if ((!msr_info->host_initiated &&
1916 		     !(to_vmx(vcpu)->msr_ia32_feature_control &
1917 		       FEATURE_CONTROL_LMCE)) ||
1918 		    (data & ~MCG_EXT_CTL_LMCE_EN))
1919 			return 1;
1920 		vcpu->arch.mcg_ext_ctl = data;
1921 		break;
1922 	case MSR_IA32_FEATURE_CONTROL:
1923 		if (!vmx_feature_control_msr_valid(vcpu, data) ||
1924 		    (to_vmx(vcpu)->msr_ia32_feature_control &
1925 		     FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
1926 			return 1;
1927 		vmx->msr_ia32_feature_control = data;
1928 		if (msr_info->host_initiated && data == 0)
1929 			vmx_leave_nested(vcpu);
1930 		break;
1931 	case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1932 		if (!msr_info->host_initiated)
1933 			return 1; /* they are read-only */
1934 		if (!nested_vmx_allowed(vcpu))
1935 			return 1;
1936 		return vmx_set_vmx_msr(vcpu, msr_index, data);
1937 	case MSR_IA32_XSS:
1938 		if (!vmx_xsaves_supported())
1939 			return 1;
1940 		/*
1941 		 * The only supported bit as of Skylake is bit 8, but
1942 		 * it is not supported on KVM.
1943 		 */
1944 		if (data != 0)
1945 			return 1;
1946 		vcpu->arch.ia32_xss = data;
1947 		if (vcpu->arch.ia32_xss != host_xss)
1948 			add_atomic_switch_msr(vmx, MSR_IA32_XSS,
1949 				vcpu->arch.ia32_xss, host_xss, false);
1950 		else
1951 			clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
1952 		break;
1953 	case MSR_IA32_RTIT_CTL:
1954 		if ((pt_mode != PT_MODE_HOST_GUEST) ||
1955 			vmx_rtit_ctl_check(vcpu, data) ||
1956 			vmx->nested.vmxon)
1957 			return 1;
1958 		vmcs_write64(GUEST_IA32_RTIT_CTL, data);
1959 		vmx->pt_desc.guest.ctl = data;
1960 		pt_update_intercept_for_msr(vmx);
1961 		break;
1962 	case MSR_IA32_RTIT_STATUS:
1963 		if ((pt_mode != PT_MODE_HOST_GUEST) ||
1964 			(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1965 			(data & MSR_IA32_RTIT_STATUS_MASK))
1966 			return 1;
1967 		vmx->pt_desc.guest.status = data;
1968 		break;
1969 	case MSR_IA32_RTIT_CR3_MATCH:
1970 		if ((pt_mode != PT_MODE_HOST_GUEST) ||
1971 			(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1972 			!intel_pt_validate_cap(vmx->pt_desc.caps,
1973 						PT_CAP_cr3_filtering))
1974 			return 1;
1975 		vmx->pt_desc.guest.cr3_match = data;
1976 		break;
1977 	case MSR_IA32_RTIT_OUTPUT_BASE:
1978 		if ((pt_mode != PT_MODE_HOST_GUEST) ||
1979 			(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1980 			(!intel_pt_validate_cap(vmx->pt_desc.caps,
1981 					PT_CAP_topa_output) &&
1982 			 !intel_pt_validate_cap(vmx->pt_desc.caps,
1983 					PT_CAP_single_range_output)) ||
1984 			(data & MSR_IA32_RTIT_OUTPUT_BASE_MASK))
1985 			return 1;
1986 		vmx->pt_desc.guest.output_base = data;
1987 		break;
1988 	case MSR_IA32_RTIT_OUTPUT_MASK:
1989 		if ((pt_mode != PT_MODE_HOST_GUEST) ||
1990 			(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1991 			(!intel_pt_validate_cap(vmx->pt_desc.caps,
1992 					PT_CAP_topa_output) &&
1993 			 !intel_pt_validate_cap(vmx->pt_desc.caps,
1994 					PT_CAP_single_range_output)))
1995 			return 1;
1996 		vmx->pt_desc.guest.output_mask = data;
1997 		break;
1998 	case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1999 		index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2000 		if ((pt_mode != PT_MODE_HOST_GUEST) ||
2001 			(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2002 			(index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2003 					PT_CAP_num_address_ranges)))
2004 			return 1;
2005 		if (index % 2)
2006 			vmx->pt_desc.guest.addr_b[index / 2] = data;
2007 		else
2008 			vmx->pt_desc.guest.addr_a[index / 2] = data;
2009 		break;
2010 	case MSR_TSC_AUX:
2011 		if (!msr_info->host_initiated &&
2012 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2013 			return 1;
2014 		/* Check reserved bit, higher 32 bits should be zero */
2015 		if ((data >> 32) != 0)
2016 			return 1;
2017 		/* Else, falls through */
2018 	default:
2019 		msr = find_msr_entry(vmx, msr_index);
2020 		if (msr) {
2021 			u64 old_msr_data = msr->data;
2022 			msr->data = data;
2023 			if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2024 				preempt_disable();
2025 				ret = kvm_set_shared_msr(msr->index, msr->data,
2026 							 msr->mask);
2027 				preempt_enable();
2028 				if (ret)
2029 					msr->data = old_msr_data;
2030 			}
2031 			break;
2032 		}
2033 		ret = kvm_set_msr_common(vcpu, msr_info);
2034 	}
2035 
2036 	return ret;
2037 }
2038 
2039 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2040 {
2041 	__set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2042 	switch (reg) {
2043 	case VCPU_REGS_RSP:
2044 		vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2045 		break;
2046 	case VCPU_REGS_RIP:
2047 		vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2048 		break;
2049 	case VCPU_EXREG_PDPTR:
2050 		if (enable_ept)
2051 			ept_save_pdptrs(vcpu);
2052 		break;
2053 	default:
2054 		break;
2055 	}
2056 }
2057 
2058 static __init int cpu_has_kvm_support(void)
2059 {
2060 	return cpu_has_vmx();
2061 }
2062 
2063 static __init int vmx_disabled_by_bios(void)
2064 {
2065 	u64 msr;
2066 
2067 	rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2068 	if (msr & FEATURE_CONTROL_LOCKED) {
2069 		/* launched w/ TXT and VMX disabled */
2070 		if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2071 			&& tboot_enabled())
2072 			return 1;
2073 		/* launched w/o TXT and VMX only enabled w/ TXT */
2074 		if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2075 			&& (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2076 			&& !tboot_enabled()) {
2077 			printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2078 				"activate TXT before enabling KVM\n");
2079 			return 1;
2080 		}
2081 		/* launched w/o TXT and VMX disabled */
2082 		if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2083 			&& !tboot_enabled())
2084 			return 1;
2085 	}
2086 
2087 	return 0;
2088 }
2089 
2090 static void kvm_cpu_vmxon(u64 addr)
2091 {
2092 	cr4_set_bits(X86_CR4_VMXE);
2093 	intel_pt_handle_vmx(1);
2094 
2095 	asm volatile ("vmxon %0" : : "m"(addr));
2096 }
2097 
2098 static int hardware_enable(void)
2099 {
2100 	int cpu = raw_smp_processor_id();
2101 	u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2102 	u64 old, test_bits;
2103 
2104 	if (cr4_read_shadow() & X86_CR4_VMXE)
2105 		return -EBUSY;
2106 
2107 	/*
2108 	 * This can happen if we hot-added a CPU but failed to allocate
2109 	 * VP assist page for it.
2110 	 */
2111 	if (static_branch_unlikely(&enable_evmcs) &&
2112 	    !hv_get_vp_assist_page(cpu))
2113 		return -EFAULT;
2114 
2115 	INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2116 	INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
2117 	spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
2118 
2119 	/*
2120 	 * Now we can enable the vmclear operation in kdump
2121 	 * since the loaded_vmcss_on_cpu list on this cpu
2122 	 * has been initialized.
2123 	 *
2124 	 * Though the cpu is not in VMX operation now, there
2125 	 * is no problem to enable the vmclear operation
2126 	 * for the loaded_vmcss_on_cpu list is empty!
2127 	 */
2128 	crash_enable_local_vmclear(cpu);
2129 
2130 	rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2131 
2132 	test_bits = FEATURE_CONTROL_LOCKED;
2133 	test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2134 	if (tboot_enabled())
2135 		test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2136 
2137 	if ((old & test_bits) != test_bits) {
2138 		/* enable and lock */
2139 		wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2140 	}
2141 	kvm_cpu_vmxon(phys_addr);
2142 	if (enable_ept)
2143 		ept_sync_global();
2144 
2145 	return 0;
2146 }
2147 
2148 static void vmclear_local_loaded_vmcss(void)
2149 {
2150 	int cpu = raw_smp_processor_id();
2151 	struct loaded_vmcs *v, *n;
2152 
2153 	list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2154 				 loaded_vmcss_on_cpu_link)
2155 		__loaded_vmcs_clear(v);
2156 }
2157 
2158 
2159 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2160  * tricks.
2161  */
2162 static void kvm_cpu_vmxoff(void)
2163 {
2164 	asm volatile (__ex("vmxoff"));
2165 
2166 	intel_pt_handle_vmx(0);
2167 	cr4_clear_bits(X86_CR4_VMXE);
2168 }
2169 
2170 static void hardware_disable(void)
2171 {
2172 	vmclear_local_loaded_vmcss();
2173 	kvm_cpu_vmxoff();
2174 }
2175 
2176 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2177 				      u32 msr, u32 *result)
2178 {
2179 	u32 vmx_msr_low, vmx_msr_high;
2180 	u32 ctl = ctl_min | ctl_opt;
2181 
2182 	rdmsr(msr, vmx_msr_low, vmx_msr_high);
2183 
2184 	ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2185 	ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
2186 
2187 	/* Ensure minimum (required) set of control bits are supported. */
2188 	if (ctl_min & ~ctl)
2189 		return -EIO;
2190 
2191 	*result = ctl;
2192 	return 0;
2193 }
2194 
2195 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2196 				    struct vmx_capability *vmx_cap)
2197 {
2198 	u32 vmx_msr_low, vmx_msr_high;
2199 	u32 min, opt, min2, opt2;
2200 	u32 _pin_based_exec_control = 0;
2201 	u32 _cpu_based_exec_control = 0;
2202 	u32 _cpu_based_2nd_exec_control = 0;
2203 	u32 _vmexit_control = 0;
2204 	u32 _vmentry_control = 0;
2205 
2206 	memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2207 	min = CPU_BASED_HLT_EXITING |
2208 #ifdef CONFIG_X86_64
2209 	      CPU_BASED_CR8_LOAD_EXITING |
2210 	      CPU_BASED_CR8_STORE_EXITING |
2211 #endif
2212 	      CPU_BASED_CR3_LOAD_EXITING |
2213 	      CPU_BASED_CR3_STORE_EXITING |
2214 	      CPU_BASED_UNCOND_IO_EXITING |
2215 	      CPU_BASED_MOV_DR_EXITING |
2216 	      CPU_BASED_USE_TSC_OFFSETING |
2217 	      CPU_BASED_MWAIT_EXITING |
2218 	      CPU_BASED_MONITOR_EXITING |
2219 	      CPU_BASED_INVLPG_EXITING |
2220 	      CPU_BASED_RDPMC_EXITING;
2221 
2222 	opt = CPU_BASED_TPR_SHADOW |
2223 	      CPU_BASED_USE_MSR_BITMAPS |
2224 	      CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2225 	if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2226 				&_cpu_based_exec_control) < 0)
2227 		return -EIO;
2228 #ifdef CONFIG_X86_64
2229 	if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2230 		_cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2231 					   ~CPU_BASED_CR8_STORE_EXITING;
2232 #endif
2233 	if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2234 		min2 = 0;
2235 		opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2236 			SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2237 			SECONDARY_EXEC_WBINVD_EXITING |
2238 			SECONDARY_EXEC_ENABLE_VPID |
2239 			SECONDARY_EXEC_ENABLE_EPT |
2240 			SECONDARY_EXEC_UNRESTRICTED_GUEST |
2241 			SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2242 			SECONDARY_EXEC_DESC |
2243 			SECONDARY_EXEC_RDTSCP |
2244 			SECONDARY_EXEC_ENABLE_INVPCID |
2245 			SECONDARY_EXEC_APIC_REGISTER_VIRT |
2246 			SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2247 			SECONDARY_EXEC_SHADOW_VMCS |
2248 			SECONDARY_EXEC_XSAVES |
2249 			SECONDARY_EXEC_RDSEED_EXITING |
2250 			SECONDARY_EXEC_RDRAND_EXITING |
2251 			SECONDARY_EXEC_ENABLE_PML |
2252 			SECONDARY_EXEC_TSC_SCALING |
2253 			SECONDARY_EXEC_PT_USE_GPA |
2254 			SECONDARY_EXEC_PT_CONCEAL_VMX |
2255 			SECONDARY_EXEC_ENABLE_VMFUNC |
2256 			SECONDARY_EXEC_ENCLS_EXITING;
2257 		if (adjust_vmx_controls(min2, opt2,
2258 					MSR_IA32_VMX_PROCBASED_CTLS2,
2259 					&_cpu_based_2nd_exec_control) < 0)
2260 			return -EIO;
2261 	}
2262 #ifndef CONFIG_X86_64
2263 	if (!(_cpu_based_2nd_exec_control &
2264 				SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2265 		_cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2266 #endif
2267 
2268 	if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2269 		_cpu_based_2nd_exec_control &= ~(
2270 				SECONDARY_EXEC_APIC_REGISTER_VIRT |
2271 				SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2272 				SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2273 
2274 	rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2275 		&vmx_cap->ept, &vmx_cap->vpid);
2276 
2277 	if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2278 		/* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2279 		   enabled */
2280 		_cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2281 					     CPU_BASED_CR3_STORE_EXITING |
2282 					     CPU_BASED_INVLPG_EXITING);
2283 	} else if (vmx_cap->ept) {
2284 		vmx_cap->ept = 0;
2285 		pr_warn_once("EPT CAP should not exist if not support "
2286 				"1-setting enable EPT VM-execution control\n");
2287 	}
2288 	if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2289 		vmx_cap->vpid) {
2290 		vmx_cap->vpid = 0;
2291 		pr_warn_once("VPID CAP should not exist if not support "
2292 				"1-setting enable VPID VM-execution control\n");
2293 	}
2294 
2295 	min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2296 #ifdef CONFIG_X86_64
2297 	min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2298 #endif
2299 	opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2300 	      VM_EXIT_LOAD_IA32_PAT |
2301 	      VM_EXIT_LOAD_IA32_EFER |
2302 	      VM_EXIT_CLEAR_BNDCFGS |
2303 	      VM_EXIT_PT_CONCEAL_PIP |
2304 	      VM_EXIT_CLEAR_IA32_RTIT_CTL;
2305 	if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2306 				&_vmexit_control) < 0)
2307 		return -EIO;
2308 
2309 	min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2310 	opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2311 		 PIN_BASED_VMX_PREEMPTION_TIMER;
2312 	if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2313 				&_pin_based_exec_control) < 0)
2314 		return -EIO;
2315 
2316 	if (cpu_has_broken_vmx_preemption_timer())
2317 		_pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2318 	if (!(_cpu_based_2nd_exec_control &
2319 		SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2320 		_pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2321 
2322 	min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2323 	opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2324 	      VM_ENTRY_LOAD_IA32_PAT |
2325 	      VM_ENTRY_LOAD_IA32_EFER |
2326 	      VM_ENTRY_LOAD_BNDCFGS |
2327 	      VM_ENTRY_PT_CONCEAL_PIP |
2328 	      VM_ENTRY_LOAD_IA32_RTIT_CTL;
2329 	if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2330 				&_vmentry_control) < 0)
2331 		return -EIO;
2332 
2333 	/*
2334 	 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2335 	 * can't be used due to an errata where VM Exit may incorrectly clear
2336 	 * IA32_PERF_GLOBAL_CTRL[34:32].  Workaround the errata by using the
2337 	 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2338 	 */
2339 	if (boot_cpu_data.x86 == 0x6) {
2340 		switch (boot_cpu_data.x86_model) {
2341 		case 26: /* AAK155 */
2342 		case 30: /* AAP115 */
2343 		case 37: /* AAT100 */
2344 		case 44: /* BC86,AAY89,BD102 */
2345 		case 46: /* BA97 */
2346 			_vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2347 			_vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2348 			pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2349 					"does not work properly. Using workaround\n");
2350 			break;
2351 		default:
2352 			break;
2353 		}
2354 	}
2355 
2356 
2357 	rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2358 
2359 	/* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2360 	if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2361 		return -EIO;
2362 
2363 #ifdef CONFIG_X86_64
2364 	/* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2365 	if (vmx_msr_high & (1u<<16))
2366 		return -EIO;
2367 #endif
2368 
2369 	/* Require Write-Back (WB) memory type for VMCS accesses. */
2370 	if (((vmx_msr_high >> 18) & 15) != 6)
2371 		return -EIO;
2372 
2373 	vmcs_conf->size = vmx_msr_high & 0x1fff;
2374 	vmcs_conf->order = get_order(vmcs_conf->size);
2375 	vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2376 
2377 	vmcs_conf->revision_id = vmx_msr_low;
2378 
2379 	vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2380 	vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2381 	vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2382 	vmcs_conf->vmexit_ctrl         = _vmexit_control;
2383 	vmcs_conf->vmentry_ctrl        = _vmentry_control;
2384 
2385 	if (static_branch_unlikely(&enable_evmcs))
2386 		evmcs_sanitize_exec_ctrls(vmcs_conf);
2387 
2388 	return 0;
2389 }
2390 
2391 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2392 {
2393 	int node = cpu_to_node(cpu);
2394 	struct page *pages;
2395 	struct vmcs *vmcs;
2396 
2397 	pages = __alloc_pages_node(node, flags, vmcs_config.order);
2398 	if (!pages)
2399 		return NULL;
2400 	vmcs = page_address(pages);
2401 	memset(vmcs, 0, vmcs_config.size);
2402 
2403 	/* KVM supports Enlightened VMCS v1 only */
2404 	if (static_branch_unlikely(&enable_evmcs))
2405 		vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2406 	else
2407 		vmcs->hdr.revision_id = vmcs_config.revision_id;
2408 
2409 	if (shadow)
2410 		vmcs->hdr.shadow_vmcs = 1;
2411 	return vmcs;
2412 }
2413 
2414 void free_vmcs(struct vmcs *vmcs)
2415 {
2416 	free_pages((unsigned long)vmcs, vmcs_config.order);
2417 }
2418 
2419 /*
2420  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2421  */
2422 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2423 {
2424 	if (!loaded_vmcs->vmcs)
2425 		return;
2426 	loaded_vmcs_clear(loaded_vmcs);
2427 	free_vmcs(loaded_vmcs->vmcs);
2428 	loaded_vmcs->vmcs = NULL;
2429 	if (loaded_vmcs->msr_bitmap)
2430 		free_page((unsigned long)loaded_vmcs->msr_bitmap);
2431 	WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2432 }
2433 
2434 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2435 {
2436 	loaded_vmcs->vmcs = alloc_vmcs(false);
2437 	if (!loaded_vmcs->vmcs)
2438 		return -ENOMEM;
2439 
2440 	loaded_vmcs->shadow_vmcs = NULL;
2441 	loaded_vmcs_init(loaded_vmcs);
2442 
2443 	if (cpu_has_vmx_msr_bitmap()) {
2444 		loaded_vmcs->msr_bitmap = (unsigned long *)
2445 				__get_free_page(GFP_KERNEL_ACCOUNT);
2446 		if (!loaded_vmcs->msr_bitmap)
2447 			goto out_vmcs;
2448 		memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2449 
2450 		if (IS_ENABLED(CONFIG_HYPERV) &&
2451 		    static_branch_unlikely(&enable_evmcs) &&
2452 		    (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2453 			struct hv_enlightened_vmcs *evmcs =
2454 				(struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2455 
2456 			evmcs->hv_enlightenments_control.msr_bitmap = 1;
2457 		}
2458 	}
2459 
2460 	memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2461 
2462 	return 0;
2463 
2464 out_vmcs:
2465 	free_loaded_vmcs(loaded_vmcs);
2466 	return -ENOMEM;
2467 }
2468 
2469 static void free_kvm_area(void)
2470 {
2471 	int cpu;
2472 
2473 	for_each_possible_cpu(cpu) {
2474 		free_vmcs(per_cpu(vmxarea, cpu));
2475 		per_cpu(vmxarea, cpu) = NULL;
2476 	}
2477 }
2478 
2479 static __init int alloc_kvm_area(void)
2480 {
2481 	int cpu;
2482 
2483 	for_each_possible_cpu(cpu) {
2484 		struct vmcs *vmcs;
2485 
2486 		vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2487 		if (!vmcs) {
2488 			free_kvm_area();
2489 			return -ENOMEM;
2490 		}
2491 
2492 		/*
2493 		 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2494 		 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2495 		 * revision_id reported by MSR_IA32_VMX_BASIC.
2496 		 *
2497 		 * However, even though not explicitly documented by
2498 		 * TLFS, VMXArea passed as VMXON argument should
2499 		 * still be marked with revision_id reported by
2500 		 * physical CPU.
2501 		 */
2502 		if (static_branch_unlikely(&enable_evmcs))
2503 			vmcs->hdr.revision_id = vmcs_config.revision_id;
2504 
2505 		per_cpu(vmxarea, cpu) = vmcs;
2506 	}
2507 	return 0;
2508 }
2509 
2510 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2511 		struct kvm_segment *save)
2512 {
2513 	if (!emulate_invalid_guest_state) {
2514 		/*
2515 		 * CS and SS RPL should be equal during guest entry according
2516 		 * to VMX spec, but in reality it is not always so. Since vcpu
2517 		 * is in the middle of the transition from real mode to
2518 		 * protected mode it is safe to assume that RPL 0 is a good
2519 		 * default value.
2520 		 */
2521 		if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2522 			save->selector &= ~SEGMENT_RPL_MASK;
2523 		save->dpl = save->selector & SEGMENT_RPL_MASK;
2524 		save->s = 1;
2525 	}
2526 	vmx_set_segment(vcpu, save, seg);
2527 }
2528 
2529 static void enter_pmode(struct kvm_vcpu *vcpu)
2530 {
2531 	unsigned long flags;
2532 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2533 
2534 	/*
2535 	 * Update real mode segment cache. It may be not up-to-date if sement
2536 	 * register was written while vcpu was in a guest mode.
2537 	 */
2538 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2539 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2540 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2541 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2542 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2543 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2544 
2545 	vmx->rmode.vm86_active = 0;
2546 
2547 	vmx_segment_cache_clear(vmx);
2548 
2549 	vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2550 
2551 	flags = vmcs_readl(GUEST_RFLAGS);
2552 	flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2553 	flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2554 	vmcs_writel(GUEST_RFLAGS, flags);
2555 
2556 	vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2557 			(vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2558 
2559 	update_exception_bitmap(vcpu);
2560 
2561 	fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2562 	fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2563 	fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2564 	fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2565 	fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2566 	fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2567 }
2568 
2569 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2570 {
2571 	const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2572 	struct kvm_segment var = *save;
2573 
2574 	var.dpl = 0x3;
2575 	if (seg == VCPU_SREG_CS)
2576 		var.type = 0x3;
2577 
2578 	if (!emulate_invalid_guest_state) {
2579 		var.selector = var.base >> 4;
2580 		var.base = var.base & 0xffff0;
2581 		var.limit = 0xffff;
2582 		var.g = 0;
2583 		var.db = 0;
2584 		var.present = 1;
2585 		var.s = 1;
2586 		var.l = 0;
2587 		var.unusable = 0;
2588 		var.type = 0x3;
2589 		var.avl = 0;
2590 		if (save->base & 0xf)
2591 			printk_once(KERN_WARNING "kvm: segment base is not "
2592 					"paragraph aligned when entering "
2593 					"protected mode (seg=%d)", seg);
2594 	}
2595 
2596 	vmcs_write16(sf->selector, var.selector);
2597 	vmcs_writel(sf->base, var.base);
2598 	vmcs_write32(sf->limit, var.limit);
2599 	vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2600 }
2601 
2602 static void enter_rmode(struct kvm_vcpu *vcpu)
2603 {
2604 	unsigned long flags;
2605 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2606 	struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2607 
2608 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2609 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2610 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2611 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2612 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2613 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2614 	vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2615 
2616 	vmx->rmode.vm86_active = 1;
2617 
2618 	/*
2619 	 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2620 	 * vcpu. Warn the user that an update is overdue.
2621 	 */
2622 	if (!kvm_vmx->tss_addr)
2623 		printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2624 			     "called before entering vcpu\n");
2625 
2626 	vmx_segment_cache_clear(vmx);
2627 
2628 	vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2629 	vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2630 	vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2631 
2632 	flags = vmcs_readl(GUEST_RFLAGS);
2633 	vmx->rmode.save_rflags = flags;
2634 
2635 	flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2636 
2637 	vmcs_writel(GUEST_RFLAGS, flags);
2638 	vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2639 	update_exception_bitmap(vcpu);
2640 
2641 	fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2642 	fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2643 	fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2644 	fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2645 	fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2646 	fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2647 
2648 	kvm_mmu_reset_context(vcpu);
2649 }
2650 
2651 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2652 {
2653 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2654 	struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2655 
2656 	if (!msr)
2657 		return;
2658 
2659 	vcpu->arch.efer = efer;
2660 	if (efer & EFER_LMA) {
2661 		vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2662 		msr->data = efer;
2663 	} else {
2664 		vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2665 
2666 		msr->data = efer & ~EFER_LME;
2667 	}
2668 	setup_msrs(vmx);
2669 }
2670 
2671 #ifdef CONFIG_X86_64
2672 
2673 static void enter_lmode(struct kvm_vcpu *vcpu)
2674 {
2675 	u32 guest_tr_ar;
2676 
2677 	vmx_segment_cache_clear(to_vmx(vcpu));
2678 
2679 	guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2680 	if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2681 		pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2682 				     __func__);
2683 		vmcs_write32(GUEST_TR_AR_BYTES,
2684 			     (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2685 			     | VMX_AR_TYPE_BUSY_64_TSS);
2686 	}
2687 	vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2688 }
2689 
2690 static void exit_lmode(struct kvm_vcpu *vcpu)
2691 {
2692 	vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2693 	vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2694 }
2695 
2696 #endif
2697 
2698 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2699 {
2700 	int vpid = to_vmx(vcpu)->vpid;
2701 
2702 	if (!vpid_sync_vcpu_addr(vpid, addr))
2703 		vpid_sync_context(vpid);
2704 
2705 	/*
2706 	 * If VPIDs are not supported or enabled, then the above is a no-op.
2707 	 * But we don't really need a TLB flush in that case anyway, because
2708 	 * each VM entry/exit includes an implicit flush when VPID is 0.
2709 	 */
2710 }
2711 
2712 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2713 {
2714 	ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2715 
2716 	vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
2717 	vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
2718 }
2719 
2720 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2721 {
2722 	if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
2723 		vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2724 	__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2725 }
2726 
2727 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2728 {
2729 	ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2730 
2731 	vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2732 	vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2733 }
2734 
2735 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2736 {
2737 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2738 
2739 	if (!test_bit(VCPU_EXREG_PDPTR,
2740 		      (unsigned long *)&vcpu->arch.regs_dirty))
2741 		return;
2742 
2743 	if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2744 		vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2745 		vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2746 		vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2747 		vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2748 	}
2749 }
2750 
2751 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2752 {
2753 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2754 
2755 	if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2756 		mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2757 		mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2758 		mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2759 		mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2760 	}
2761 
2762 	__set_bit(VCPU_EXREG_PDPTR,
2763 		  (unsigned long *)&vcpu->arch.regs_avail);
2764 	__set_bit(VCPU_EXREG_PDPTR,
2765 		  (unsigned long *)&vcpu->arch.regs_dirty);
2766 }
2767 
2768 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2769 					unsigned long cr0,
2770 					struct kvm_vcpu *vcpu)
2771 {
2772 	if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2773 		vmx_decache_cr3(vcpu);
2774 	if (!(cr0 & X86_CR0_PG)) {
2775 		/* From paging/starting to nonpaging */
2776 		vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2777 			     vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
2778 			     (CPU_BASED_CR3_LOAD_EXITING |
2779 			      CPU_BASED_CR3_STORE_EXITING));
2780 		vcpu->arch.cr0 = cr0;
2781 		vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2782 	} else if (!is_paging(vcpu)) {
2783 		/* From nonpaging to paging */
2784 		vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2785 			     vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
2786 			     ~(CPU_BASED_CR3_LOAD_EXITING |
2787 			       CPU_BASED_CR3_STORE_EXITING));
2788 		vcpu->arch.cr0 = cr0;
2789 		vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2790 	}
2791 
2792 	if (!(cr0 & X86_CR0_WP))
2793 		*hw_cr0 &= ~X86_CR0_WP;
2794 }
2795 
2796 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2797 {
2798 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2799 	unsigned long hw_cr0;
2800 
2801 	hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
2802 	if (enable_unrestricted_guest)
2803 		hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
2804 	else {
2805 		hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
2806 
2807 		if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
2808 			enter_pmode(vcpu);
2809 
2810 		if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
2811 			enter_rmode(vcpu);
2812 	}
2813 
2814 #ifdef CONFIG_X86_64
2815 	if (vcpu->arch.efer & EFER_LME) {
2816 		if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
2817 			enter_lmode(vcpu);
2818 		if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
2819 			exit_lmode(vcpu);
2820 	}
2821 #endif
2822 
2823 	if (enable_ept && !enable_unrestricted_guest)
2824 		ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
2825 
2826 	vmcs_writel(CR0_READ_SHADOW, cr0);
2827 	vmcs_writel(GUEST_CR0, hw_cr0);
2828 	vcpu->arch.cr0 = cr0;
2829 
2830 	/* depends on vcpu->arch.cr0 to be set to a new value */
2831 	vmx->emulation_required = emulation_required(vcpu);
2832 }
2833 
2834 static int get_ept_level(struct kvm_vcpu *vcpu)
2835 {
2836 	if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
2837 		return 5;
2838 	return 4;
2839 }
2840 
2841 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
2842 {
2843 	u64 eptp = VMX_EPTP_MT_WB;
2844 
2845 	eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
2846 
2847 	if (enable_ept_ad_bits &&
2848 	    (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
2849 		eptp |= VMX_EPTP_AD_ENABLE_BIT;
2850 	eptp |= (root_hpa & PAGE_MASK);
2851 
2852 	return eptp;
2853 }
2854 
2855 void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
2856 {
2857 	struct kvm *kvm = vcpu->kvm;
2858 	unsigned long guest_cr3;
2859 	u64 eptp;
2860 
2861 	guest_cr3 = cr3;
2862 	if (enable_ept) {
2863 		eptp = construct_eptp(vcpu, cr3);
2864 		vmcs_write64(EPT_POINTER, eptp);
2865 
2866 		if (kvm_x86_ops->tlb_remote_flush) {
2867 			spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2868 			to_vmx(vcpu)->ept_pointer = eptp;
2869 			to_kvm_vmx(kvm)->ept_pointers_match
2870 				= EPT_POINTERS_CHECK;
2871 			spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2872 		}
2873 
2874 		if (enable_unrestricted_guest || is_paging(vcpu) ||
2875 		    is_guest_mode(vcpu))
2876 			guest_cr3 = kvm_read_cr3(vcpu);
2877 		else
2878 			guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
2879 		ept_load_pdptrs(vcpu);
2880 	}
2881 
2882 	vmcs_writel(GUEST_CR3, guest_cr3);
2883 }
2884 
2885 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2886 {
2887 	/*
2888 	 * Pass through host's Machine Check Enable value to hw_cr4, which
2889 	 * is in force while we are in guest mode.  Do not let guests control
2890 	 * this bit, even if host CR4.MCE == 0.
2891 	 */
2892 	unsigned long hw_cr4;
2893 
2894 	hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
2895 	if (enable_unrestricted_guest)
2896 		hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
2897 	else if (to_vmx(vcpu)->rmode.vm86_active)
2898 		hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
2899 	else
2900 		hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
2901 
2902 	if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
2903 		if (cr4 & X86_CR4_UMIP) {
2904 			vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
2905 				SECONDARY_EXEC_DESC);
2906 			hw_cr4 &= ~X86_CR4_UMIP;
2907 		} else if (!is_guest_mode(vcpu) ||
2908 			!nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
2909 			vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
2910 					SECONDARY_EXEC_DESC);
2911 	}
2912 
2913 	if (cr4 & X86_CR4_VMXE) {
2914 		/*
2915 		 * To use VMXON (and later other VMX instructions), a guest
2916 		 * must first be able to turn on cr4.VMXE (see handle_vmon()).
2917 		 * So basically the check on whether to allow nested VMX
2918 		 * is here.  We operate under the default treatment of SMM,
2919 		 * so VMX cannot be enabled under SMM.
2920 		 */
2921 		if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
2922 			return 1;
2923 	}
2924 
2925 	if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
2926 		return 1;
2927 
2928 	vcpu->arch.cr4 = cr4;
2929 
2930 	if (!enable_unrestricted_guest) {
2931 		if (enable_ept) {
2932 			if (!is_paging(vcpu)) {
2933 				hw_cr4 &= ~X86_CR4_PAE;
2934 				hw_cr4 |= X86_CR4_PSE;
2935 			} else if (!(cr4 & X86_CR4_PAE)) {
2936 				hw_cr4 &= ~X86_CR4_PAE;
2937 			}
2938 		}
2939 
2940 		/*
2941 		 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
2942 		 * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
2943 		 * to be manually disabled when guest switches to non-paging
2944 		 * mode.
2945 		 *
2946 		 * If !enable_unrestricted_guest, the CPU is always running
2947 		 * with CR0.PG=1 and CR4 needs to be modified.
2948 		 * If enable_unrestricted_guest, the CPU automatically
2949 		 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
2950 		 */
2951 		if (!is_paging(vcpu))
2952 			hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
2953 	}
2954 
2955 	vmcs_writel(CR4_READ_SHADOW, cr4);
2956 	vmcs_writel(GUEST_CR4, hw_cr4);
2957 	return 0;
2958 }
2959 
2960 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
2961 {
2962 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2963 	u32 ar;
2964 
2965 	if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
2966 		*var = vmx->rmode.segs[seg];
2967 		if (seg == VCPU_SREG_TR
2968 		    || var->selector == vmx_read_guest_seg_selector(vmx, seg))
2969 			return;
2970 		var->base = vmx_read_guest_seg_base(vmx, seg);
2971 		var->selector = vmx_read_guest_seg_selector(vmx, seg);
2972 		return;
2973 	}
2974 	var->base = vmx_read_guest_seg_base(vmx, seg);
2975 	var->limit = vmx_read_guest_seg_limit(vmx, seg);
2976 	var->selector = vmx_read_guest_seg_selector(vmx, seg);
2977 	ar = vmx_read_guest_seg_ar(vmx, seg);
2978 	var->unusable = (ar >> 16) & 1;
2979 	var->type = ar & 15;
2980 	var->s = (ar >> 4) & 1;
2981 	var->dpl = (ar >> 5) & 3;
2982 	/*
2983 	 * Some userspaces do not preserve unusable property. Since usable
2984 	 * segment has to be present according to VMX spec we can use present
2985 	 * property to amend userspace bug by making unusable segment always
2986 	 * nonpresent. vmx_segment_access_rights() already marks nonpresent
2987 	 * segment as unusable.
2988 	 */
2989 	var->present = !var->unusable;
2990 	var->avl = (ar >> 12) & 1;
2991 	var->l = (ar >> 13) & 1;
2992 	var->db = (ar >> 14) & 1;
2993 	var->g = (ar >> 15) & 1;
2994 }
2995 
2996 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2997 {
2998 	struct kvm_segment s;
2999 
3000 	if (to_vmx(vcpu)->rmode.vm86_active) {
3001 		vmx_get_segment(vcpu, &s, seg);
3002 		return s.base;
3003 	}
3004 	return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3005 }
3006 
3007 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3008 {
3009 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3010 
3011 	if (unlikely(vmx->rmode.vm86_active))
3012 		return 0;
3013 	else {
3014 		int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3015 		return VMX_AR_DPL(ar);
3016 	}
3017 }
3018 
3019 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3020 {
3021 	u32 ar;
3022 
3023 	if (var->unusable || !var->present)
3024 		ar = 1 << 16;
3025 	else {
3026 		ar = var->type & 15;
3027 		ar |= (var->s & 1) << 4;
3028 		ar |= (var->dpl & 3) << 5;
3029 		ar |= (var->present & 1) << 7;
3030 		ar |= (var->avl & 1) << 12;
3031 		ar |= (var->l & 1) << 13;
3032 		ar |= (var->db & 1) << 14;
3033 		ar |= (var->g & 1) << 15;
3034 	}
3035 
3036 	return ar;
3037 }
3038 
3039 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3040 {
3041 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3042 	const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3043 
3044 	vmx_segment_cache_clear(vmx);
3045 
3046 	if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3047 		vmx->rmode.segs[seg] = *var;
3048 		if (seg == VCPU_SREG_TR)
3049 			vmcs_write16(sf->selector, var->selector);
3050 		else if (var->s)
3051 			fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3052 		goto out;
3053 	}
3054 
3055 	vmcs_writel(sf->base, var->base);
3056 	vmcs_write32(sf->limit, var->limit);
3057 	vmcs_write16(sf->selector, var->selector);
3058 
3059 	/*
3060 	 *   Fix the "Accessed" bit in AR field of segment registers for older
3061 	 * qemu binaries.
3062 	 *   IA32 arch specifies that at the time of processor reset the
3063 	 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3064 	 * is setting it to 0 in the userland code. This causes invalid guest
3065 	 * state vmexit when "unrestricted guest" mode is turned on.
3066 	 *    Fix for this setup issue in cpu_reset is being pushed in the qemu
3067 	 * tree. Newer qemu binaries with that qemu fix would not need this
3068 	 * kvm hack.
3069 	 */
3070 	if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3071 		var->type |= 0x1; /* Accessed */
3072 
3073 	vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3074 
3075 out:
3076 	vmx->emulation_required = emulation_required(vcpu);
3077 }
3078 
3079 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3080 {
3081 	u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3082 
3083 	*db = (ar >> 14) & 1;
3084 	*l = (ar >> 13) & 1;
3085 }
3086 
3087 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3088 {
3089 	dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3090 	dt->address = vmcs_readl(GUEST_IDTR_BASE);
3091 }
3092 
3093 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3094 {
3095 	vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3096 	vmcs_writel(GUEST_IDTR_BASE, dt->address);
3097 }
3098 
3099 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3100 {
3101 	dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3102 	dt->address = vmcs_readl(GUEST_GDTR_BASE);
3103 }
3104 
3105 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3106 {
3107 	vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3108 	vmcs_writel(GUEST_GDTR_BASE, dt->address);
3109 }
3110 
3111 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3112 {
3113 	struct kvm_segment var;
3114 	u32 ar;
3115 
3116 	vmx_get_segment(vcpu, &var, seg);
3117 	var.dpl = 0x3;
3118 	if (seg == VCPU_SREG_CS)
3119 		var.type = 0x3;
3120 	ar = vmx_segment_access_rights(&var);
3121 
3122 	if (var.base != (var.selector << 4))
3123 		return false;
3124 	if (var.limit != 0xffff)
3125 		return false;
3126 	if (ar != 0xf3)
3127 		return false;
3128 
3129 	return true;
3130 }
3131 
3132 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3133 {
3134 	struct kvm_segment cs;
3135 	unsigned int cs_rpl;
3136 
3137 	vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3138 	cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3139 
3140 	if (cs.unusable)
3141 		return false;
3142 	if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3143 		return false;
3144 	if (!cs.s)
3145 		return false;
3146 	if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3147 		if (cs.dpl > cs_rpl)
3148 			return false;
3149 	} else {
3150 		if (cs.dpl != cs_rpl)
3151 			return false;
3152 	}
3153 	if (!cs.present)
3154 		return false;
3155 
3156 	/* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3157 	return true;
3158 }
3159 
3160 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3161 {
3162 	struct kvm_segment ss;
3163 	unsigned int ss_rpl;
3164 
3165 	vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3166 	ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3167 
3168 	if (ss.unusable)
3169 		return true;
3170 	if (ss.type != 3 && ss.type != 7)
3171 		return false;
3172 	if (!ss.s)
3173 		return false;
3174 	if (ss.dpl != ss_rpl) /* DPL != RPL */
3175 		return false;
3176 	if (!ss.present)
3177 		return false;
3178 
3179 	return true;
3180 }
3181 
3182 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3183 {
3184 	struct kvm_segment var;
3185 	unsigned int rpl;
3186 
3187 	vmx_get_segment(vcpu, &var, seg);
3188 	rpl = var.selector & SEGMENT_RPL_MASK;
3189 
3190 	if (var.unusable)
3191 		return true;
3192 	if (!var.s)
3193 		return false;
3194 	if (!var.present)
3195 		return false;
3196 	if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3197 		if (var.dpl < rpl) /* DPL < RPL */
3198 			return false;
3199 	}
3200 
3201 	/* TODO: Add other members to kvm_segment_field to allow checking for other access
3202 	 * rights flags
3203 	 */
3204 	return true;
3205 }
3206 
3207 static bool tr_valid(struct kvm_vcpu *vcpu)
3208 {
3209 	struct kvm_segment tr;
3210 
3211 	vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3212 
3213 	if (tr.unusable)
3214 		return false;
3215 	if (tr.selector & SEGMENT_TI_MASK)	/* TI = 1 */
3216 		return false;
3217 	if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3218 		return false;
3219 	if (!tr.present)
3220 		return false;
3221 
3222 	return true;
3223 }
3224 
3225 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3226 {
3227 	struct kvm_segment ldtr;
3228 
3229 	vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3230 
3231 	if (ldtr.unusable)
3232 		return true;
3233 	if (ldtr.selector & SEGMENT_TI_MASK)	/* TI = 1 */
3234 		return false;
3235 	if (ldtr.type != 2)
3236 		return false;
3237 	if (!ldtr.present)
3238 		return false;
3239 
3240 	return true;
3241 }
3242 
3243 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3244 {
3245 	struct kvm_segment cs, ss;
3246 
3247 	vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3248 	vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3249 
3250 	return ((cs.selector & SEGMENT_RPL_MASK) ==
3251 		 (ss.selector & SEGMENT_RPL_MASK));
3252 }
3253 
3254 /*
3255  * Check if guest state is valid. Returns true if valid, false if
3256  * not.
3257  * We assume that registers are always usable
3258  */
3259 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3260 {
3261 	if (enable_unrestricted_guest)
3262 		return true;
3263 
3264 	/* real mode guest state checks */
3265 	if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3266 		if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3267 			return false;
3268 		if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3269 			return false;
3270 		if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3271 			return false;
3272 		if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3273 			return false;
3274 		if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3275 			return false;
3276 		if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3277 			return false;
3278 	} else {
3279 	/* protected mode guest state checks */
3280 		if (!cs_ss_rpl_check(vcpu))
3281 			return false;
3282 		if (!code_segment_valid(vcpu))
3283 			return false;
3284 		if (!stack_segment_valid(vcpu))
3285 			return false;
3286 		if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3287 			return false;
3288 		if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3289 			return false;
3290 		if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3291 			return false;
3292 		if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3293 			return false;
3294 		if (!tr_valid(vcpu))
3295 			return false;
3296 		if (!ldtr_valid(vcpu))
3297 			return false;
3298 	}
3299 	/* TODO:
3300 	 * - Add checks on RIP
3301 	 * - Add checks on RFLAGS
3302 	 */
3303 
3304 	return true;
3305 }
3306 
3307 static int init_rmode_tss(struct kvm *kvm)
3308 {
3309 	gfn_t fn;
3310 	u16 data = 0;
3311 	int idx, r;
3312 
3313 	idx = srcu_read_lock(&kvm->srcu);
3314 	fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3315 	r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3316 	if (r < 0)
3317 		goto out;
3318 	data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3319 	r = kvm_write_guest_page(kvm, fn++, &data,
3320 			TSS_IOPB_BASE_OFFSET, sizeof(u16));
3321 	if (r < 0)
3322 		goto out;
3323 	r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3324 	if (r < 0)
3325 		goto out;
3326 	r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3327 	if (r < 0)
3328 		goto out;
3329 	data = ~0;
3330 	r = kvm_write_guest_page(kvm, fn, &data,
3331 				 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3332 				 sizeof(u8));
3333 out:
3334 	srcu_read_unlock(&kvm->srcu, idx);
3335 	return r;
3336 }
3337 
3338 static int init_rmode_identity_map(struct kvm *kvm)
3339 {
3340 	struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3341 	int i, idx, r = 0;
3342 	kvm_pfn_t identity_map_pfn;
3343 	u32 tmp;
3344 
3345 	/* Protect kvm_vmx->ept_identity_pagetable_done. */
3346 	mutex_lock(&kvm->slots_lock);
3347 
3348 	if (likely(kvm_vmx->ept_identity_pagetable_done))
3349 		goto out2;
3350 
3351 	if (!kvm_vmx->ept_identity_map_addr)
3352 		kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3353 	identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3354 
3355 	r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3356 				    kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3357 	if (r < 0)
3358 		goto out2;
3359 
3360 	idx = srcu_read_lock(&kvm->srcu);
3361 	r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3362 	if (r < 0)
3363 		goto out;
3364 	/* Set up identity-mapping pagetable for EPT in real mode */
3365 	for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3366 		tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3367 			_PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3368 		r = kvm_write_guest_page(kvm, identity_map_pfn,
3369 				&tmp, i * sizeof(tmp), sizeof(tmp));
3370 		if (r < 0)
3371 			goto out;
3372 	}
3373 	kvm_vmx->ept_identity_pagetable_done = true;
3374 
3375 out:
3376 	srcu_read_unlock(&kvm->srcu, idx);
3377 
3378 out2:
3379 	mutex_unlock(&kvm->slots_lock);
3380 	return r;
3381 }
3382 
3383 static void seg_setup(int seg)
3384 {
3385 	const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3386 	unsigned int ar;
3387 
3388 	vmcs_write16(sf->selector, 0);
3389 	vmcs_writel(sf->base, 0);
3390 	vmcs_write32(sf->limit, 0xffff);
3391 	ar = 0x93;
3392 	if (seg == VCPU_SREG_CS)
3393 		ar |= 0x08; /* code segment */
3394 
3395 	vmcs_write32(sf->ar_bytes, ar);
3396 }
3397 
3398 static int alloc_apic_access_page(struct kvm *kvm)
3399 {
3400 	struct page *page;
3401 	int r = 0;
3402 
3403 	mutex_lock(&kvm->slots_lock);
3404 	if (kvm->arch.apic_access_page_done)
3405 		goto out;
3406 	r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3407 				    APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3408 	if (r)
3409 		goto out;
3410 
3411 	page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3412 	if (is_error_page(page)) {
3413 		r = -EFAULT;
3414 		goto out;
3415 	}
3416 
3417 	/*
3418 	 * Do not pin the page in memory, so that memory hot-unplug
3419 	 * is able to migrate it.
3420 	 */
3421 	put_page(page);
3422 	kvm->arch.apic_access_page_done = true;
3423 out:
3424 	mutex_unlock(&kvm->slots_lock);
3425 	return r;
3426 }
3427 
3428 int allocate_vpid(void)
3429 {
3430 	int vpid;
3431 
3432 	if (!enable_vpid)
3433 		return 0;
3434 	spin_lock(&vmx_vpid_lock);
3435 	vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3436 	if (vpid < VMX_NR_VPIDS)
3437 		__set_bit(vpid, vmx_vpid_bitmap);
3438 	else
3439 		vpid = 0;
3440 	spin_unlock(&vmx_vpid_lock);
3441 	return vpid;
3442 }
3443 
3444 void free_vpid(int vpid)
3445 {
3446 	if (!enable_vpid || vpid == 0)
3447 		return;
3448 	spin_lock(&vmx_vpid_lock);
3449 	__clear_bit(vpid, vmx_vpid_bitmap);
3450 	spin_unlock(&vmx_vpid_lock);
3451 }
3452 
3453 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3454 							  u32 msr, int type)
3455 {
3456 	int f = sizeof(unsigned long);
3457 
3458 	if (!cpu_has_vmx_msr_bitmap())
3459 		return;
3460 
3461 	if (static_branch_unlikely(&enable_evmcs))
3462 		evmcs_touch_msr_bitmap();
3463 
3464 	/*
3465 	 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3466 	 * have the write-low and read-high bitmap offsets the wrong way round.
3467 	 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3468 	 */
3469 	if (msr <= 0x1fff) {
3470 		if (type & MSR_TYPE_R)
3471 			/* read-low */
3472 			__clear_bit(msr, msr_bitmap + 0x000 / f);
3473 
3474 		if (type & MSR_TYPE_W)
3475 			/* write-low */
3476 			__clear_bit(msr, msr_bitmap + 0x800 / f);
3477 
3478 	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3479 		msr &= 0x1fff;
3480 		if (type & MSR_TYPE_R)
3481 			/* read-high */
3482 			__clear_bit(msr, msr_bitmap + 0x400 / f);
3483 
3484 		if (type & MSR_TYPE_W)
3485 			/* write-high */
3486 			__clear_bit(msr, msr_bitmap + 0xc00 / f);
3487 
3488 	}
3489 }
3490 
3491 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3492 							 u32 msr, int type)
3493 {
3494 	int f = sizeof(unsigned long);
3495 
3496 	if (!cpu_has_vmx_msr_bitmap())
3497 		return;
3498 
3499 	if (static_branch_unlikely(&enable_evmcs))
3500 		evmcs_touch_msr_bitmap();
3501 
3502 	/*
3503 	 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3504 	 * have the write-low and read-high bitmap offsets the wrong way round.
3505 	 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3506 	 */
3507 	if (msr <= 0x1fff) {
3508 		if (type & MSR_TYPE_R)
3509 			/* read-low */
3510 			__set_bit(msr, msr_bitmap + 0x000 / f);
3511 
3512 		if (type & MSR_TYPE_W)
3513 			/* write-low */
3514 			__set_bit(msr, msr_bitmap + 0x800 / f);
3515 
3516 	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3517 		msr &= 0x1fff;
3518 		if (type & MSR_TYPE_R)
3519 			/* read-high */
3520 			__set_bit(msr, msr_bitmap + 0x400 / f);
3521 
3522 		if (type & MSR_TYPE_W)
3523 			/* write-high */
3524 			__set_bit(msr, msr_bitmap + 0xc00 / f);
3525 
3526 	}
3527 }
3528 
3529 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3530 			     			      u32 msr, int type, bool value)
3531 {
3532 	if (value)
3533 		vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3534 	else
3535 		vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3536 }
3537 
3538 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3539 {
3540 	u8 mode = 0;
3541 
3542 	if (cpu_has_secondary_exec_ctrls() &&
3543 	    (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
3544 	     SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3545 		mode |= MSR_BITMAP_MODE_X2APIC;
3546 		if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3547 			mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3548 	}
3549 
3550 	return mode;
3551 }
3552 
3553 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3554 					 u8 mode)
3555 {
3556 	int msr;
3557 
3558 	for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3559 		unsigned word = msr / BITS_PER_LONG;
3560 		msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3561 		msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3562 	}
3563 
3564 	if (mode & MSR_BITMAP_MODE_X2APIC) {
3565 		/*
3566 		 * TPR reads and writes can be virtualized even if virtual interrupt
3567 		 * delivery is not in use.
3568 		 */
3569 		vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3570 		if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3571 			vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3572 			vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3573 			vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3574 		}
3575 	}
3576 }
3577 
3578 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3579 {
3580 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3581 	unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3582 	u8 mode = vmx_msr_bitmap_mode(vcpu);
3583 	u8 changed = mode ^ vmx->msr_bitmap_mode;
3584 
3585 	if (!changed)
3586 		return;
3587 
3588 	if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3589 		vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3590 
3591 	vmx->msr_bitmap_mode = mode;
3592 }
3593 
3594 void pt_update_intercept_for_msr(struct vcpu_vmx *vmx)
3595 {
3596 	unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3597 	bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3598 	u32 i;
3599 
3600 	vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_STATUS,
3601 							MSR_TYPE_RW, flag);
3602 	vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_BASE,
3603 							MSR_TYPE_RW, flag);
3604 	vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_MASK,
3605 							MSR_TYPE_RW, flag);
3606 	vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_CR3_MATCH,
3607 							MSR_TYPE_RW, flag);
3608 	for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3609 		vmx_set_intercept_for_msr(msr_bitmap,
3610 			MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3611 		vmx_set_intercept_for_msr(msr_bitmap,
3612 			MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3613 	}
3614 }
3615 
3616 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
3617 {
3618 	return enable_apicv;
3619 }
3620 
3621 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3622 {
3623 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3624 	void *vapic_page;
3625 	u32 vppr;
3626 	int rvi;
3627 
3628 	if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3629 		!nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3630 		WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3631 		return false;
3632 
3633 	rvi = vmx_get_rvi();
3634 
3635 	vapic_page = vmx->nested.virtual_apic_map.hva;
3636 	vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3637 
3638 	return ((rvi & 0xf0) > (vppr & 0xf0));
3639 }
3640 
3641 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3642 						     bool nested)
3643 {
3644 #ifdef CONFIG_SMP
3645 	int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3646 
3647 	if (vcpu->mode == IN_GUEST_MODE) {
3648 		/*
3649 		 * The vector of interrupt to be delivered to vcpu had
3650 		 * been set in PIR before this function.
3651 		 *
3652 		 * Following cases will be reached in this block, and
3653 		 * we always send a notification event in all cases as
3654 		 * explained below.
3655 		 *
3656 		 * Case 1: vcpu keeps in non-root mode. Sending a
3657 		 * notification event posts the interrupt to vcpu.
3658 		 *
3659 		 * Case 2: vcpu exits to root mode and is still
3660 		 * runnable. PIR will be synced to vIRR before the
3661 		 * next vcpu entry. Sending a notification event in
3662 		 * this case has no effect, as vcpu is not in root
3663 		 * mode.
3664 		 *
3665 		 * Case 3: vcpu exits to root mode and is blocked.
3666 		 * vcpu_block() has already synced PIR to vIRR and
3667 		 * never blocks vcpu if vIRR is not cleared. Therefore,
3668 		 * a blocked vcpu here does not wait for any requested
3669 		 * interrupts in PIR, and sending a notification event
3670 		 * which has no effect is safe here.
3671 		 */
3672 
3673 		apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3674 		return true;
3675 	}
3676 #endif
3677 	return false;
3678 }
3679 
3680 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3681 						int vector)
3682 {
3683 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3684 
3685 	if (is_guest_mode(vcpu) &&
3686 	    vector == vmx->nested.posted_intr_nv) {
3687 		/*
3688 		 * If a posted intr is not recognized by hardware,
3689 		 * we will accomplish it in the next vmentry.
3690 		 */
3691 		vmx->nested.pi_pending = true;
3692 		kvm_make_request(KVM_REQ_EVENT, vcpu);
3693 		/* the PIR and ON have been set by L1. */
3694 		if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3695 			kvm_vcpu_kick(vcpu);
3696 		return 0;
3697 	}
3698 	return -1;
3699 }
3700 /*
3701  * Send interrupt to vcpu via posted interrupt way.
3702  * 1. If target vcpu is running(non-root mode), send posted interrupt
3703  * notification to vcpu and hardware will sync PIR to vIRR atomically.
3704  * 2. If target vcpu isn't running(root mode), kick it to pick up the
3705  * interrupt from PIR in next vmentry.
3706  */
3707 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3708 {
3709 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3710 	int r;
3711 
3712 	r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3713 	if (!r)
3714 		return;
3715 
3716 	if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3717 		return;
3718 
3719 	/* If a previous notification has sent the IPI, nothing to do.  */
3720 	if (pi_test_and_set_on(&vmx->pi_desc))
3721 		return;
3722 
3723 	if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3724 		kvm_vcpu_kick(vcpu);
3725 }
3726 
3727 /*
3728  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3729  * will not change in the lifetime of the guest.
3730  * Note that host-state that does change is set elsewhere. E.g., host-state
3731  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3732  */
3733 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3734 {
3735 	u32 low32, high32;
3736 	unsigned long tmpl;
3737 	struct desc_ptr dt;
3738 	unsigned long cr0, cr3, cr4;
3739 
3740 	cr0 = read_cr0();
3741 	WARN_ON(cr0 & X86_CR0_TS);
3742 	vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
3743 
3744 	/*
3745 	 * Save the most likely value for this task's CR3 in the VMCS.
3746 	 * We can't use __get_current_cr3_fast() because we're not atomic.
3747 	 */
3748 	cr3 = __read_cr3();
3749 	vmcs_writel(HOST_CR3, cr3);		/* 22.2.3  FIXME: shadow tables */
3750 	vmx->loaded_vmcs->host_state.cr3 = cr3;
3751 
3752 	/* Save the most likely value for this task's CR4 in the VMCS. */
3753 	cr4 = cr4_read_shadow();
3754 	vmcs_writel(HOST_CR4, cr4);			/* 22.2.3, 22.2.5 */
3755 	vmx->loaded_vmcs->host_state.cr4 = cr4;
3756 
3757 	vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
3758 #ifdef CONFIG_X86_64
3759 	/*
3760 	 * Load null selectors, so we can avoid reloading them in
3761 	 * vmx_prepare_switch_to_host(), in case userspace uses
3762 	 * the null selectors too (the expected case).
3763 	 */
3764 	vmcs_write16(HOST_DS_SELECTOR, 0);
3765 	vmcs_write16(HOST_ES_SELECTOR, 0);
3766 #else
3767 	vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3768 	vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3769 #endif
3770 	vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3771 	vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
3772 
3773 	store_idt(&dt);
3774 	vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
3775 	vmx->host_idt_base = dt.address;
3776 
3777 	vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
3778 
3779 	rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3780 	vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3781 	rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
3782 	vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
3783 
3784 	if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
3785 		rdmsr(MSR_IA32_CR_PAT, low32, high32);
3786 		vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
3787 	}
3788 
3789 	if (cpu_has_load_ia32_efer())
3790 		vmcs_write64(HOST_IA32_EFER, host_efer);
3791 }
3792 
3793 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
3794 {
3795 	vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
3796 	if (enable_ept)
3797 		vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
3798 	if (is_guest_mode(&vmx->vcpu))
3799 		vmx->vcpu.arch.cr4_guest_owned_bits &=
3800 			~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
3801 	vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
3802 }
3803 
3804 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
3805 {
3806 	u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
3807 
3808 	if (!kvm_vcpu_apicv_active(&vmx->vcpu))
3809 		pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
3810 
3811 	if (!enable_vnmi)
3812 		pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
3813 
3814 	/* Enable the preemption timer dynamically */
3815 	pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3816 	return pin_based_exec_ctrl;
3817 }
3818 
3819 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
3820 {
3821 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3822 
3823 	vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
3824 	if (cpu_has_secondary_exec_ctrls()) {
3825 		if (kvm_vcpu_apicv_active(vcpu))
3826 			vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
3827 				      SECONDARY_EXEC_APIC_REGISTER_VIRT |
3828 				      SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3829 		else
3830 			vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
3831 					SECONDARY_EXEC_APIC_REGISTER_VIRT |
3832 					SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3833 	}
3834 
3835 	if (cpu_has_vmx_msr_bitmap())
3836 		vmx_update_msr_bitmap(vcpu);
3837 }
3838 
3839 u32 vmx_exec_control(struct vcpu_vmx *vmx)
3840 {
3841 	u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
3842 
3843 	if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
3844 		exec_control &= ~CPU_BASED_MOV_DR_EXITING;
3845 
3846 	if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
3847 		exec_control &= ~CPU_BASED_TPR_SHADOW;
3848 #ifdef CONFIG_X86_64
3849 		exec_control |= CPU_BASED_CR8_STORE_EXITING |
3850 				CPU_BASED_CR8_LOAD_EXITING;
3851 #endif
3852 	}
3853 	if (!enable_ept)
3854 		exec_control |= CPU_BASED_CR3_STORE_EXITING |
3855 				CPU_BASED_CR3_LOAD_EXITING  |
3856 				CPU_BASED_INVLPG_EXITING;
3857 	if (kvm_mwait_in_guest(vmx->vcpu.kvm))
3858 		exec_control &= ~(CPU_BASED_MWAIT_EXITING |
3859 				CPU_BASED_MONITOR_EXITING);
3860 	if (kvm_hlt_in_guest(vmx->vcpu.kvm))
3861 		exec_control &= ~CPU_BASED_HLT_EXITING;
3862 	return exec_control;
3863 }
3864 
3865 
3866 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
3867 {
3868 	struct kvm_vcpu *vcpu = &vmx->vcpu;
3869 
3870 	u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
3871 
3872 	if (pt_mode == PT_MODE_SYSTEM)
3873 		exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
3874 	if (!cpu_need_virtualize_apic_accesses(vcpu))
3875 		exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3876 	if (vmx->vpid == 0)
3877 		exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
3878 	if (!enable_ept) {
3879 		exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
3880 		enable_unrestricted_guest = 0;
3881 	}
3882 	if (!enable_unrestricted_guest)
3883 		exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
3884 	if (kvm_pause_in_guest(vmx->vcpu.kvm))
3885 		exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
3886 	if (!kvm_vcpu_apicv_active(vcpu))
3887 		exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
3888 				  SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3889 	exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
3890 
3891 	/* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
3892 	 * in vmx_set_cr4.  */
3893 	exec_control &= ~SECONDARY_EXEC_DESC;
3894 
3895 	/* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
3896 	   (handle_vmptrld).
3897 	   We can NOT enable shadow_vmcs here because we don't have yet
3898 	   a current VMCS12
3899 	*/
3900 	exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
3901 
3902 	if (!enable_pml)
3903 		exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
3904 
3905 	if (vmx_xsaves_supported()) {
3906 		/* Exposing XSAVES only when XSAVE is exposed */
3907 		bool xsaves_enabled =
3908 			guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
3909 			guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
3910 
3911 		if (!xsaves_enabled)
3912 			exec_control &= ~SECONDARY_EXEC_XSAVES;
3913 
3914 		if (nested) {
3915 			if (xsaves_enabled)
3916 				vmx->nested.msrs.secondary_ctls_high |=
3917 					SECONDARY_EXEC_XSAVES;
3918 			else
3919 				vmx->nested.msrs.secondary_ctls_high &=
3920 					~SECONDARY_EXEC_XSAVES;
3921 		}
3922 	}
3923 
3924 	if (vmx_rdtscp_supported()) {
3925 		bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
3926 		if (!rdtscp_enabled)
3927 			exec_control &= ~SECONDARY_EXEC_RDTSCP;
3928 
3929 		if (nested) {
3930 			if (rdtscp_enabled)
3931 				vmx->nested.msrs.secondary_ctls_high |=
3932 					SECONDARY_EXEC_RDTSCP;
3933 			else
3934 				vmx->nested.msrs.secondary_ctls_high &=
3935 					~SECONDARY_EXEC_RDTSCP;
3936 		}
3937 	}
3938 
3939 	if (vmx_invpcid_supported()) {
3940 		/* Exposing INVPCID only when PCID is exposed */
3941 		bool invpcid_enabled =
3942 			guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
3943 			guest_cpuid_has(vcpu, X86_FEATURE_PCID);
3944 
3945 		if (!invpcid_enabled) {
3946 			exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
3947 			guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
3948 		}
3949 
3950 		if (nested) {
3951 			if (invpcid_enabled)
3952 				vmx->nested.msrs.secondary_ctls_high |=
3953 					SECONDARY_EXEC_ENABLE_INVPCID;
3954 			else
3955 				vmx->nested.msrs.secondary_ctls_high &=
3956 					~SECONDARY_EXEC_ENABLE_INVPCID;
3957 		}
3958 	}
3959 
3960 	if (vmx_rdrand_supported()) {
3961 		bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
3962 		if (rdrand_enabled)
3963 			exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
3964 
3965 		if (nested) {
3966 			if (rdrand_enabled)
3967 				vmx->nested.msrs.secondary_ctls_high |=
3968 					SECONDARY_EXEC_RDRAND_EXITING;
3969 			else
3970 				vmx->nested.msrs.secondary_ctls_high &=
3971 					~SECONDARY_EXEC_RDRAND_EXITING;
3972 		}
3973 	}
3974 
3975 	if (vmx_rdseed_supported()) {
3976 		bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
3977 		if (rdseed_enabled)
3978 			exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
3979 
3980 		if (nested) {
3981 			if (rdseed_enabled)
3982 				vmx->nested.msrs.secondary_ctls_high |=
3983 					SECONDARY_EXEC_RDSEED_EXITING;
3984 			else
3985 				vmx->nested.msrs.secondary_ctls_high &=
3986 					~SECONDARY_EXEC_RDSEED_EXITING;
3987 		}
3988 	}
3989 
3990 	vmx->secondary_exec_control = exec_control;
3991 }
3992 
3993 static void ept_set_mmio_spte_mask(void)
3994 {
3995 	/*
3996 	 * EPT Misconfigurations can be generated if the value of bits 2:0
3997 	 * of an EPT paging-structure entry is 110b (write/execute).
3998 	 */
3999 	kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
4000 				   VMX_EPT_MISCONFIG_WX_VALUE);
4001 }
4002 
4003 #define VMX_XSS_EXIT_BITMAP 0
4004 
4005 /*
4006  * Sets up the vmcs for emulated real mode.
4007  */
4008 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
4009 {
4010 	int i;
4011 
4012 	if (nested)
4013 		nested_vmx_vcpu_setup();
4014 
4015 	if (cpu_has_vmx_msr_bitmap())
4016 		vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4017 
4018 	vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4019 
4020 	/* Control */
4021 	vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
4022 	vmx->hv_deadline_tsc = -1;
4023 
4024 	vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
4025 
4026 	if (cpu_has_secondary_exec_ctrls()) {
4027 		vmx_compute_secondary_exec_control(vmx);
4028 		vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4029 			     vmx->secondary_exec_control);
4030 	}
4031 
4032 	if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4033 		vmcs_write64(EOI_EXIT_BITMAP0, 0);
4034 		vmcs_write64(EOI_EXIT_BITMAP1, 0);
4035 		vmcs_write64(EOI_EXIT_BITMAP2, 0);
4036 		vmcs_write64(EOI_EXIT_BITMAP3, 0);
4037 
4038 		vmcs_write16(GUEST_INTR_STATUS, 0);
4039 
4040 		vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4041 		vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4042 	}
4043 
4044 	if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4045 		vmcs_write32(PLE_GAP, ple_gap);
4046 		vmx->ple_window = ple_window;
4047 		vmx->ple_window_dirty = true;
4048 	}
4049 
4050 	vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4051 	vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4052 	vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
4053 
4054 	vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
4055 	vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
4056 	vmx_set_constant_host_state(vmx);
4057 	vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4058 	vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4059 
4060 	if (cpu_has_vmx_vmfunc())
4061 		vmcs_write64(VM_FUNCTION_CONTROL, 0);
4062 
4063 	vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4064 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4065 	vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4066 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4067 	vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4068 
4069 	if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4070 		vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4071 
4072 	for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
4073 		u32 index = vmx_msr_index[i];
4074 		u32 data_low, data_high;
4075 		int j = vmx->nmsrs;
4076 
4077 		if (rdmsr_safe(index, &data_low, &data_high) < 0)
4078 			continue;
4079 		if (wrmsr_safe(index, data_low, data_high) < 0)
4080 			continue;
4081 		vmx->guest_msrs[j].index = i;
4082 		vmx->guest_msrs[j].data = 0;
4083 		vmx->guest_msrs[j].mask = -1ull;
4084 		++vmx->nmsrs;
4085 	}
4086 
4087 	vm_exit_controls_init(vmx, vmx_vmexit_ctrl());
4088 
4089 	/* 22.2.1, 20.8.1 */
4090 	vm_entry_controls_init(vmx, vmx_vmentry_ctrl());
4091 
4092 	vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
4093 	vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
4094 
4095 	set_cr4_guest_host_mask(vmx);
4096 
4097 	if (vmx_xsaves_supported())
4098 		vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4099 
4100 	if (enable_pml) {
4101 		vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4102 		vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4103 	}
4104 
4105 	if (cpu_has_vmx_encls_vmexit())
4106 		vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
4107 
4108 	if (pt_mode == PT_MODE_HOST_GUEST) {
4109 		memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4110 		/* Bit[6~0] are forced to 1, writes are ignored. */
4111 		vmx->pt_desc.guest.output_mask = 0x7F;
4112 		vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4113 	}
4114 }
4115 
4116 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4117 {
4118 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4119 	struct msr_data apic_base_msr;
4120 	u64 cr0;
4121 
4122 	vmx->rmode.vm86_active = 0;
4123 	vmx->spec_ctrl = 0;
4124 
4125 	vcpu->arch.microcode_version = 0x100000000ULL;
4126 	vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4127 	kvm_set_cr8(vcpu, 0);
4128 
4129 	if (!init_event) {
4130 		apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4131 				     MSR_IA32_APICBASE_ENABLE;
4132 		if (kvm_vcpu_is_reset_bsp(vcpu))
4133 			apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4134 		apic_base_msr.host_initiated = true;
4135 		kvm_set_apic_base(vcpu, &apic_base_msr);
4136 	}
4137 
4138 	vmx_segment_cache_clear(vmx);
4139 
4140 	seg_setup(VCPU_SREG_CS);
4141 	vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4142 	vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4143 
4144 	seg_setup(VCPU_SREG_DS);
4145 	seg_setup(VCPU_SREG_ES);
4146 	seg_setup(VCPU_SREG_FS);
4147 	seg_setup(VCPU_SREG_GS);
4148 	seg_setup(VCPU_SREG_SS);
4149 
4150 	vmcs_write16(GUEST_TR_SELECTOR, 0);
4151 	vmcs_writel(GUEST_TR_BASE, 0);
4152 	vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4153 	vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4154 
4155 	vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4156 	vmcs_writel(GUEST_LDTR_BASE, 0);
4157 	vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4158 	vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4159 
4160 	if (!init_event) {
4161 		vmcs_write32(GUEST_SYSENTER_CS, 0);
4162 		vmcs_writel(GUEST_SYSENTER_ESP, 0);
4163 		vmcs_writel(GUEST_SYSENTER_EIP, 0);
4164 		vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4165 	}
4166 
4167 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4168 	kvm_rip_write(vcpu, 0xfff0);
4169 
4170 	vmcs_writel(GUEST_GDTR_BASE, 0);
4171 	vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4172 
4173 	vmcs_writel(GUEST_IDTR_BASE, 0);
4174 	vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4175 
4176 	vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4177 	vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4178 	vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4179 	if (kvm_mpx_supported())
4180 		vmcs_write64(GUEST_BNDCFGS, 0);
4181 
4182 	setup_msrs(vmx);
4183 
4184 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
4185 
4186 	if (cpu_has_vmx_tpr_shadow() && !init_event) {
4187 		vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4188 		if (cpu_need_tpr_shadow(vcpu))
4189 			vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4190 				     __pa(vcpu->arch.apic->regs));
4191 		vmcs_write32(TPR_THRESHOLD, 0);
4192 	}
4193 
4194 	kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4195 
4196 	if (vmx->vpid != 0)
4197 		vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4198 
4199 	cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4200 	vmx->vcpu.arch.cr0 = cr0;
4201 	vmx_set_cr0(vcpu, cr0); /* enter rmode */
4202 	vmx_set_cr4(vcpu, 0);
4203 	vmx_set_efer(vcpu, 0);
4204 
4205 	update_exception_bitmap(vcpu);
4206 
4207 	vpid_sync_context(vmx->vpid);
4208 	if (init_event)
4209 		vmx_clear_hlt(vcpu);
4210 }
4211 
4212 static void enable_irq_window(struct kvm_vcpu *vcpu)
4213 {
4214 	vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
4215 		      CPU_BASED_VIRTUAL_INTR_PENDING);
4216 }
4217 
4218 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4219 {
4220 	if (!enable_vnmi ||
4221 	    vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4222 		enable_irq_window(vcpu);
4223 		return;
4224 	}
4225 
4226 	vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
4227 		      CPU_BASED_VIRTUAL_NMI_PENDING);
4228 }
4229 
4230 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4231 {
4232 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4233 	uint32_t intr;
4234 	int irq = vcpu->arch.interrupt.nr;
4235 
4236 	trace_kvm_inj_virq(irq);
4237 
4238 	++vcpu->stat.irq_injections;
4239 	if (vmx->rmode.vm86_active) {
4240 		int inc_eip = 0;
4241 		if (vcpu->arch.interrupt.soft)
4242 			inc_eip = vcpu->arch.event_exit_inst_len;
4243 		if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
4244 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4245 		return;
4246 	}
4247 	intr = irq | INTR_INFO_VALID_MASK;
4248 	if (vcpu->arch.interrupt.soft) {
4249 		intr |= INTR_TYPE_SOFT_INTR;
4250 		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4251 			     vmx->vcpu.arch.event_exit_inst_len);
4252 	} else
4253 		intr |= INTR_TYPE_EXT_INTR;
4254 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4255 
4256 	vmx_clear_hlt(vcpu);
4257 }
4258 
4259 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4260 {
4261 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4262 
4263 	if (!enable_vnmi) {
4264 		/*
4265 		 * Tracking the NMI-blocked state in software is built upon
4266 		 * finding the next open IRQ window. This, in turn, depends on
4267 		 * well-behaving guests: They have to keep IRQs disabled at
4268 		 * least as long as the NMI handler runs. Otherwise we may
4269 		 * cause NMI nesting, maybe breaking the guest. But as this is
4270 		 * highly unlikely, we can live with the residual risk.
4271 		 */
4272 		vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4273 		vmx->loaded_vmcs->vnmi_blocked_time = 0;
4274 	}
4275 
4276 	++vcpu->stat.nmi_injections;
4277 	vmx->loaded_vmcs->nmi_known_unmasked = false;
4278 
4279 	if (vmx->rmode.vm86_active) {
4280 		if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
4281 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4282 		return;
4283 	}
4284 
4285 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4286 			INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4287 
4288 	vmx_clear_hlt(vcpu);
4289 }
4290 
4291 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4292 {
4293 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4294 	bool masked;
4295 
4296 	if (!enable_vnmi)
4297 		return vmx->loaded_vmcs->soft_vnmi_blocked;
4298 	if (vmx->loaded_vmcs->nmi_known_unmasked)
4299 		return false;
4300 	masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4301 	vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4302 	return masked;
4303 }
4304 
4305 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4306 {
4307 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4308 
4309 	if (!enable_vnmi) {
4310 		if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4311 			vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4312 			vmx->loaded_vmcs->vnmi_blocked_time = 0;
4313 		}
4314 	} else {
4315 		vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4316 		if (masked)
4317 			vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4318 				      GUEST_INTR_STATE_NMI);
4319 		else
4320 			vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4321 					GUEST_INTR_STATE_NMI);
4322 	}
4323 }
4324 
4325 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4326 {
4327 	if (to_vmx(vcpu)->nested.nested_run_pending)
4328 		return 0;
4329 
4330 	if (!enable_vnmi &&
4331 	    to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4332 		return 0;
4333 
4334 	return	!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4335 		  (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4336 		   | GUEST_INTR_STATE_NMI));
4337 }
4338 
4339 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4340 {
4341 	return (!to_vmx(vcpu)->nested.nested_run_pending &&
4342 		vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4343 		!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4344 			(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4345 }
4346 
4347 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4348 {
4349 	int ret;
4350 
4351 	if (enable_unrestricted_guest)
4352 		return 0;
4353 
4354 	ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4355 				    PAGE_SIZE * 3);
4356 	if (ret)
4357 		return ret;
4358 	to_kvm_vmx(kvm)->tss_addr = addr;
4359 	return init_rmode_tss(kvm);
4360 }
4361 
4362 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4363 {
4364 	to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4365 	return 0;
4366 }
4367 
4368 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4369 {
4370 	switch (vec) {
4371 	case BP_VECTOR:
4372 		/*
4373 		 * Update instruction length as we may reinject the exception
4374 		 * from user space while in guest debugging mode.
4375 		 */
4376 		to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4377 			vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4378 		if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4379 			return false;
4380 		/* fall through */
4381 	case DB_VECTOR:
4382 		if (vcpu->guest_debug &
4383 			(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4384 			return false;
4385 		/* fall through */
4386 	case DE_VECTOR:
4387 	case OF_VECTOR:
4388 	case BR_VECTOR:
4389 	case UD_VECTOR:
4390 	case DF_VECTOR:
4391 	case SS_VECTOR:
4392 	case GP_VECTOR:
4393 	case MF_VECTOR:
4394 		return true;
4395 	break;
4396 	}
4397 	return false;
4398 }
4399 
4400 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4401 				  int vec, u32 err_code)
4402 {
4403 	/*
4404 	 * Instruction with address size override prefix opcode 0x67
4405 	 * Cause the #SS fault with 0 error code in VM86 mode.
4406 	 */
4407 	if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4408 		if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
4409 			if (vcpu->arch.halt_request) {
4410 				vcpu->arch.halt_request = 0;
4411 				return kvm_vcpu_halt(vcpu);
4412 			}
4413 			return 1;
4414 		}
4415 		return 0;
4416 	}
4417 
4418 	/*
4419 	 * Forward all other exceptions that are valid in real mode.
4420 	 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4421 	 *        the required debugging infrastructure rework.
4422 	 */
4423 	kvm_queue_exception(vcpu, vec);
4424 	return 1;
4425 }
4426 
4427 /*
4428  * Trigger machine check on the host. We assume all the MSRs are already set up
4429  * by the CPU and that we still run on the same CPU as the MCE occurred on.
4430  * We pass a fake environment to the machine check handler because we want
4431  * the guest to be always treated like user space, no matter what context
4432  * it used internally.
4433  */
4434 static void kvm_machine_check(void)
4435 {
4436 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4437 	struct pt_regs regs = {
4438 		.cs = 3, /* Fake ring 3 no matter what the guest ran on */
4439 		.flags = X86_EFLAGS_IF,
4440 	};
4441 
4442 	do_machine_check(&regs, 0);
4443 #endif
4444 }
4445 
4446 static int handle_machine_check(struct kvm_vcpu *vcpu)
4447 {
4448 	/* already handled by vcpu_run */
4449 	return 1;
4450 }
4451 
4452 static int handle_exception(struct kvm_vcpu *vcpu)
4453 {
4454 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4455 	struct kvm_run *kvm_run = vcpu->run;
4456 	u32 intr_info, ex_no, error_code;
4457 	unsigned long cr2, rip, dr6;
4458 	u32 vect_info;
4459 	enum emulation_result er;
4460 
4461 	vect_info = vmx->idt_vectoring_info;
4462 	intr_info = vmx->exit_intr_info;
4463 
4464 	if (is_machine_check(intr_info))
4465 		return handle_machine_check(vcpu);
4466 
4467 	if (is_nmi(intr_info))
4468 		return 1;  /* already handled by vmx_vcpu_run() */
4469 
4470 	if (is_invalid_opcode(intr_info))
4471 		return handle_ud(vcpu);
4472 
4473 	error_code = 0;
4474 	if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4475 		error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4476 
4477 	if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4478 		WARN_ON_ONCE(!enable_vmware_backdoor);
4479 		er = kvm_emulate_instruction(vcpu,
4480 			EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
4481 		if (er == EMULATE_USER_EXIT)
4482 			return 0;
4483 		else if (er != EMULATE_DONE)
4484 			kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4485 		return 1;
4486 	}
4487 
4488 	/*
4489 	 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4490 	 * MMIO, it is better to report an internal error.
4491 	 * See the comments in vmx_handle_exit.
4492 	 */
4493 	if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4494 	    !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4495 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4496 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4497 		vcpu->run->internal.ndata = 3;
4498 		vcpu->run->internal.data[0] = vect_info;
4499 		vcpu->run->internal.data[1] = intr_info;
4500 		vcpu->run->internal.data[2] = error_code;
4501 		return 0;
4502 	}
4503 
4504 	if (is_page_fault(intr_info)) {
4505 		cr2 = vmcs_readl(EXIT_QUALIFICATION);
4506 		/* EPT won't cause page fault directly */
4507 		WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
4508 		return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4509 	}
4510 
4511 	ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4512 
4513 	if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4514 		return handle_rmode_exception(vcpu, ex_no, error_code);
4515 
4516 	switch (ex_no) {
4517 	case AC_VECTOR:
4518 		kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4519 		return 1;
4520 	case DB_VECTOR:
4521 		dr6 = vmcs_readl(EXIT_QUALIFICATION);
4522 		if (!(vcpu->guest_debug &
4523 		      (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4524 			vcpu->arch.dr6 &= ~15;
4525 			vcpu->arch.dr6 |= dr6 | DR6_RTM;
4526 			if (is_icebp(intr_info))
4527 				skip_emulated_instruction(vcpu);
4528 
4529 			kvm_queue_exception(vcpu, DB_VECTOR);
4530 			return 1;
4531 		}
4532 		kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4533 		kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4534 		/* fall through */
4535 	case BP_VECTOR:
4536 		/*
4537 		 * Update instruction length as we may reinject #BP from
4538 		 * user space while in guest debugging mode. Reading it for
4539 		 * #DB as well causes no harm, it is not used in that case.
4540 		 */
4541 		vmx->vcpu.arch.event_exit_inst_len =
4542 			vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4543 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
4544 		rip = kvm_rip_read(vcpu);
4545 		kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4546 		kvm_run->debug.arch.exception = ex_no;
4547 		break;
4548 	default:
4549 		kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4550 		kvm_run->ex.exception = ex_no;
4551 		kvm_run->ex.error_code = error_code;
4552 		break;
4553 	}
4554 	return 0;
4555 }
4556 
4557 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4558 {
4559 	++vcpu->stat.irq_exits;
4560 	return 1;
4561 }
4562 
4563 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4564 {
4565 	vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4566 	vcpu->mmio_needed = 0;
4567 	return 0;
4568 }
4569 
4570 static int handle_io(struct kvm_vcpu *vcpu)
4571 {
4572 	unsigned long exit_qualification;
4573 	int size, in, string;
4574 	unsigned port;
4575 
4576 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4577 	string = (exit_qualification & 16) != 0;
4578 
4579 	++vcpu->stat.io_exits;
4580 
4581 	if (string)
4582 		return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4583 
4584 	port = exit_qualification >> 16;
4585 	size = (exit_qualification & 7) + 1;
4586 	in = (exit_qualification & 8) != 0;
4587 
4588 	return kvm_fast_pio(vcpu, size, port, in);
4589 }
4590 
4591 static void
4592 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4593 {
4594 	/*
4595 	 * Patch in the VMCALL instruction:
4596 	 */
4597 	hypercall[0] = 0x0f;
4598 	hypercall[1] = 0x01;
4599 	hypercall[2] = 0xc1;
4600 }
4601 
4602 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4603 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4604 {
4605 	if (is_guest_mode(vcpu)) {
4606 		struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4607 		unsigned long orig_val = val;
4608 
4609 		/*
4610 		 * We get here when L2 changed cr0 in a way that did not change
4611 		 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4612 		 * but did change L0 shadowed bits. So we first calculate the
4613 		 * effective cr0 value that L1 would like to write into the
4614 		 * hardware. It consists of the L2-owned bits from the new
4615 		 * value combined with the L1-owned bits from L1's guest_cr0.
4616 		 */
4617 		val = (val & ~vmcs12->cr0_guest_host_mask) |
4618 			(vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4619 
4620 		if (!nested_guest_cr0_valid(vcpu, val))
4621 			return 1;
4622 
4623 		if (kvm_set_cr0(vcpu, val))
4624 			return 1;
4625 		vmcs_writel(CR0_READ_SHADOW, orig_val);
4626 		return 0;
4627 	} else {
4628 		if (to_vmx(vcpu)->nested.vmxon &&
4629 		    !nested_host_cr0_valid(vcpu, val))
4630 			return 1;
4631 
4632 		return kvm_set_cr0(vcpu, val);
4633 	}
4634 }
4635 
4636 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4637 {
4638 	if (is_guest_mode(vcpu)) {
4639 		struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4640 		unsigned long orig_val = val;
4641 
4642 		/* analogously to handle_set_cr0 */
4643 		val = (val & ~vmcs12->cr4_guest_host_mask) |
4644 			(vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4645 		if (kvm_set_cr4(vcpu, val))
4646 			return 1;
4647 		vmcs_writel(CR4_READ_SHADOW, orig_val);
4648 		return 0;
4649 	} else
4650 		return kvm_set_cr4(vcpu, val);
4651 }
4652 
4653 static int handle_desc(struct kvm_vcpu *vcpu)
4654 {
4655 	WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4656 	return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4657 }
4658 
4659 static int handle_cr(struct kvm_vcpu *vcpu)
4660 {
4661 	unsigned long exit_qualification, val;
4662 	int cr;
4663 	int reg;
4664 	int err;
4665 	int ret;
4666 
4667 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4668 	cr = exit_qualification & 15;
4669 	reg = (exit_qualification >> 8) & 15;
4670 	switch ((exit_qualification >> 4) & 3) {
4671 	case 0: /* mov to cr */
4672 		val = kvm_register_readl(vcpu, reg);
4673 		trace_kvm_cr_write(cr, val);
4674 		switch (cr) {
4675 		case 0:
4676 			err = handle_set_cr0(vcpu, val);
4677 			return kvm_complete_insn_gp(vcpu, err);
4678 		case 3:
4679 			WARN_ON_ONCE(enable_unrestricted_guest);
4680 			err = kvm_set_cr3(vcpu, val);
4681 			return kvm_complete_insn_gp(vcpu, err);
4682 		case 4:
4683 			err = handle_set_cr4(vcpu, val);
4684 			return kvm_complete_insn_gp(vcpu, err);
4685 		case 8: {
4686 				u8 cr8_prev = kvm_get_cr8(vcpu);
4687 				u8 cr8 = (u8)val;
4688 				err = kvm_set_cr8(vcpu, cr8);
4689 				ret = kvm_complete_insn_gp(vcpu, err);
4690 				if (lapic_in_kernel(vcpu))
4691 					return ret;
4692 				if (cr8_prev <= cr8)
4693 					return ret;
4694 				/*
4695 				 * TODO: we might be squashing a
4696 				 * KVM_GUESTDBG_SINGLESTEP-triggered
4697 				 * KVM_EXIT_DEBUG here.
4698 				 */
4699 				vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4700 				return 0;
4701 			}
4702 		}
4703 		break;
4704 	case 2: /* clts */
4705 		WARN_ONCE(1, "Guest should always own CR0.TS");
4706 		vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4707 		trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4708 		return kvm_skip_emulated_instruction(vcpu);
4709 	case 1: /*mov from cr*/
4710 		switch (cr) {
4711 		case 3:
4712 			WARN_ON_ONCE(enable_unrestricted_guest);
4713 			val = kvm_read_cr3(vcpu);
4714 			kvm_register_write(vcpu, reg, val);
4715 			trace_kvm_cr_read(cr, val);
4716 			return kvm_skip_emulated_instruction(vcpu);
4717 		case 8:
4718 			val = kvm_get_cr8(vcpu);
4719 			kvm_register_write(vcpu, reg, val);
4720 			trace_kvm_cr_read(cr, val);
4721 			return kvm_skip_emulated_instruction(vcpu);
4722 		}
4723 		break;
4724 	case 3: /* lmsw */
4725 		val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4726 		trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4727 		kvm_lmsw(vcpu, val);
4728 
4729 		return kvm_skip_emulated_instruction(vcpu);
4730 	default:
4731 		break;
4732 	}
4733 	vcpu->run->exit_reason = 0;
4734 	vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4735 	       (int)(exit_qualification >> 4) & 3, cr);
4736 	return 0;
4737 }
4738 
4739 static int handle_dr(struct kvm_vcpu *vcpu)
4740 {
4741 	unsigned long exit_qualification;
4742 	int dr, dr7, reg;
4743 
4744 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4745 	dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
4746 
4747 	/* First, if DR does not exist, trigger UD */
4748 	if (!kvm_require_dr(vcpu, dr))
4749 		return 1;
4750 
4751 	/* Do not handle if the CPL > 0, will trigger GP on re-entry */
4752 	if (!kvm_require_cpl(vcpu, 0))
4753 		return 1;
4754 	dr7 = vmcs_readl(GUEST_DR7);
4755 	if (dr7 & DR7_GD) {
4756 		/*
4757 		 * As the vm-exit takes precedence over the debug trap, we
4758 		 * need to emulate the latter, either for the host or the
4759 		 * guest debugging itself.
4760 		 */
4761 		if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
4762 			vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
4763 			vcpu->run->debug.arch.dr7 = dr7;
4764 			vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
4765 			vcpu->run->debug.arch.exception = DB_VECTOR;
4766 			vcpu->run->exit_reason = KVM_EXIT_DEBUG;
4767 			return 0;
4768 		} else {
4769 			vcpu->arch.dr6 &= ~15;
4770 			vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
4771 			kvm_queue_exception(vcpu, DB_VECTOR);
4772 			return 1;
4773 		}
4774 	}
4775 
4776 	if (vcpu->guest_debug == 0) {
4777 		vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4778 				CPU_BASED_MOV_DR_EXITING);
4779 
4780 		/*
4781 		 * No more DR vmexits; force a reload of the debug registers
4782 		 * and reenter on this instruction.  The next vmexit will
4783 		 * retrieve the full state of the debug registers.
4784 		 */
4785 		vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4786 		return 1;
4787 	}
4788 
4789 	reg = DEBUG_REG_ACCESS_REG(exit_qualification);
4790 	if (exit_qualification & TYPE_MOV_FROM_DR) {
4791 		unsigned long val;
4792 
4793 		if (kvm_get_dr(vcpu, dr, &val))
4794 			return 1;
4795 		kvm_register_write(vcpu, reg, val);
4796 	} else
4797 		if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
4798 			return 1;
4799 
4800 	return kvm_skip_emulated_instruction(vcpu);
4801 }
4802 
4803 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
4804 {
4805 	return vcpu->arch.dr6;
4806 }
4807 
4808 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
4809 {
4810 }
4811 
4812 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
4813 {
4814 	get_debugreg(vcpu->arch.db[0], 0);
4815 	get_debugreg(vcpu->arch.db[1], 1);
4816 	get_debugreg(vcpu->arch.db[2], 2);
4817 	get_debugreg(vcpu->arch.db[3], 3);
4818 	get_debugreg(vcpu->arch.dr6, 6);
4819 	vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
4820 
4821 	vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
4822 	vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
4823 }
4824 
4825 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
4826 {
4827 	vmcs_writel(GUEST_DR7, val);
4828 }
4829 
4830 static int handle_cpuid(struct kvm_vcpu *vcpu)
4831 {
4832 	return kvm_emulate_cpuid(vcpu);
4833 }
4834 
4835 static int handle_rdmsr(struct kvm_vcpu *vcpu)
4836 {
4837 	u32 ecx = kvm_rcx_read(vcpu);
4838 	struct msr_data msr_info;
4839 
4840 	msr_info.index = ecx;
4841 	msr_info.host_initiated = false;
4842 	if (vmx_get_msr(vcpu, &msr_info)) {
4843 		trace_kvm_msr_read_ex(ecx);
4844 		kvm_inject_gp(vcpu, 0);
4845 		return 1;
4846 	}
4847 
4848 	trace_kvm_msr_read(ecx, msr_info.data);
4849 
4850 	kvm_rax_write(vcpu, msr_info.data & -1u);
4851 	kvm_rdx_write(vcpu, (msr_info.data >> 32) & -1u);
4852 	return kvm_skip_emulated_instruction(vcpu);
4853 }
4854 
4855 static int handle_wrmsr(struct kvm_vcpu *vcpu)
4856 {
4857 	struct msr_data msr;
4858 	u32 ecx = kvm_rcx_read(vcpu);
4859 	u64 data = kvm_read_edx_eax(vcpu);
4860 
4861 	msr.data = data;
4862 	msr.index = ecx;
4863 	msr.host_initiated = false;
4864 	if (kvm_set_msr(vcpu, &msr) != 0) {
4865 		trace_kvm_msr_write_ex(ecx, data);
4866 		kvm_inject_gp(vcpu, 0);
4867 		return 1;
4868 	}
4869 
4870 	trace_kvm_msr_write(ecx, data);
4871 	return kvm_skip_emulated_instruction(vcpu);
4872 }
4873 
4874 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
4875 {
4876 	kvm_apic_update_ppr(vcpu);
4877 	return 1;
4878 }
4879 
4880 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
4881 {
4882 	vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4883 			CPU_BASED_VIRTUAL_INTR_PENDING);
4884 
4885 	kvm_make_request(KVM_REQ_EVENT, vcpu);
4886 
4887 	++vcpu->stat.irq_window_exits;
4888 	return 1;
4889 }
4890 
4891 static int handle_halt(struct kvm_vcpu *vcpu)
4892 {
4893 	return kvm_emulate_halt(vcpu);
4894 }
4895 
4896 static int handle_vmcall(struct kvm_vcpu *vcpu)
4897 {
4898 	return kvm_emulate_hypercall(vcpu);
4899 }
4900 
4901 static int handle_invd(struct kvm_vcpu *vcpu)
4902 {
4903 	return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4904 }
4905 
4906 static int handle_invlpg(struct kvm_vcpu *vcpu)
4907 {
4908 	unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4909 
4910 	kvm_mmu_invlpg(vcpu, exit_qualification);
4911 	return kvm_skip_emulated_instruction(vcpu);
4912 }
4913 
4914 static int handle_rdpmc(struct kvm_vcpu *vcpu)
4915 {
4916 	int err;
4917 
4918 	err = kvm_rdpmc(vcpu);
4919 	return kvm_complete_insn_gp(vcpu, err);
4920 }
4921 
4922 static int handle_wbinvd(struct kvm_vcpu *vcpu)
4923 {
4924 	return kvm_emulate_wbinvd(vcpu);
4925 }
4926 
4927 static int handle_xsetbv(struct kvm_vcpu *vcpu)
4928 {
4929 	u64 new_bv = kvm_read_edx_eax(vcpu);
4930 	u32 index = kvm_rcx_read(vcpu);
4931 
4932 	if (kvm_set_xcr(vcpu, index, new_bv) == 0)
4933 		return kvm_skip_emulated_instruction(vcpu);
4934 	return 1;
4935 }
4936 
4937 static int handle_xsaves(struct kvm_vcpu *vcpu)
4938 {
4939 	kvm_skip_emulated_instruction(vcpu);
4940 	WARN(1, "this should never happen\n");
4941 	return 1;
4942 }
4943 
4944 static int handle_xrstors(struct kvm_vcpu *vcpu)
4945 {
4946 	kvm_skip_emulated_instruction(vcpu);
4947 	WARN(1, "this should never happen\n");
4948 	return 1;
4949 }
4950 
4951 static int handle_apic_access(struct kvm_vcpu *vcpu)
4952 {
4953 	if (likely(fasteoi)) {
4954 		unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4955 		int access_type, offset;
4956 
4957 		access_type = exit_qualification & APIC_ACCESS_TYPE;
4958 		offset = exit_qualification & APIC_ACCESS_OFFSET;
4959 		/*
4960 		 * Sane guest uses MOV to write EOI, with written value
4961 		 * not cared. So make a short-circuit here by avoiding
4962 		 * heavy instruction emulation.
4963 		 */
4964 		if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
4965 		    (offset == APIC_EOI)) {
4966 			kvm_lapic_set_eoi(vcpu);
4967 			return kvm_skip_emulated_instruction(vcpu);
4968 		}
4969 	}
4970 	return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4971 }
4972 
4973 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
4974 {
4975 	unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4976 	int vector = exit_qualification & 0xff;
4977 
4978 	/* EOI-induced VM exit is trap-like and thus no need to adjust IP */
4979 	kvm_apic_set_eoi_accelerated(vcpu, vector);
4980 	return 1;
4981 }
4982 
4983 static int handle_apic_write(struct kvm_vcpu *vcpu)
4984 {
4985 	unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4986 	u32 offset = exit_qualification & 0xfff;
4987 
4988 	/* APIC-write VM exit is trap-like and thus no need to adjust IP */
4989 	kvm_apic_write_nodecode(vcpu, offset);
4990 	return 1;
4991 }
4992 
4993 static int handle_task_switch(struct kvm_vcpu *vcpu)
4994 {
4995 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4996 	unsigned long exit_qualification;
4997 	bool has_error_code = false;
4998 	u32 error_code = 0;
4999 	u16 tss_selector;
5000 	int reason, type, idt_v, idt_index;
5001 
5002 	idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5003 	idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5004 	type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5005 
5006 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5007 
5008 	reason = (u32)exit_qualification >> 30;
5009 	if (reason == TASK_SWITCH_GATE && idt_v) {
5010 		switch (type) {
5011 		case INTR_TYPE_NMI_INTR:
5012 			vcpu->arch.nmi_injected = false;
5013 			vmx_set_nmi_mask(vcpu, true);
5014 			break;
5015 		case INTR_TYPE_EXT_INTR:
5016 		case INTR_TYPE_SOFT_INTR:
5017 			kvm_clear_interrupt_queue(vcpu);
5018 			break;
5019 		case INTR_TYPE_HARD_EXCEPTION:
5020 			if (vmx->idt_vectoring_info &
5021 			    VECTORING_INFO_DELIVER_CODE_MASK) {
5022 				has_error_code = true;
5023 				error_code =
5024 					vmcs_read32(IDT_VECTORING_ERROR_CODE);
5025 			}
5026 			/* fall through */
5027 		case INTR_TYPE_SOFT_EXCEPTION:
5028 			kvm_clear_exception_queue(vcpu);
5029 			break;
5030 		default:
5031 			break;
5032 		}
5033 	}
5034 	tss_selector = exit_qualification;
5035 
5036 	if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5037 		       type != INTR_TYPE_EXT_INTR &&
5038 		       type != INTR_TYPE_NMI_INTR))
5039 		skip_emulated_instruction(vcpu);
5040 
5041 	if (kvm_task_switch(vcpu, tss_selector,
5042 			    type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
5043 			    has_error_code, error_code) == EMULATE_FAIL) {
5044 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5045 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5046 		vcpu->run->internal.ndata = 0;
5047 		return 0;
5048 	}
5049 
5050 	/*
5051 	 * TODO: What about debug traps on tss switch?
5052 	 *       Are we supposed to inject them and update dr6?
5053 	 */
5054 
5055 	return 1;
5056 }
5057 
5058 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5059 {
5060 	unsigned long exit_qualification;
5061 	gpa_t gpa;
5062 	u64 error_code;
5063 
5064 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5065 
5066 	/*
5067 	 * EPT violation happened while executing iret from NMI,
5068 	 * "blocked by NMI" bit has to be set before next VM entry.
5069 	 * There are errata that may cause this bit to not be set:
5070 	 * AAK134, BY25.
5071 	 */
5072 	if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5073 			enable_vnmi &&
5074 			(exit_qualification & INTR_INFO_UNBLOCK_NMI))
5075 		vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5076 
5077 	gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5078 	trace_kvm_page_fault(gpa, exit_qualification);
5079 
5080 	/* Is it a read fault? */
5081 	error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5082 		     ? PFERR_USER_MASK : 0;
5083 	/* Is it a write fault? */
5084 	error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5085 		      ? PFERR_WRITE_MASK : 0;
5086 	/* Is it a fetch fault? */
5087 	error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5088 		      ? PFERR_FETCH_MASK : 0;
5089 	/* ept page table entry is present? */
5090 	error_code |= (exit_qualification &
5091 		       (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5092 			EPT_VIOLATION_EXECUTABLE))
5093 		      ? PFERR_PRESENT_MASK : 0;
5094 
5095 	error_code |= (exit_qualification & 0x100) != 0 ?
5096 	       PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5097 
5098 	vcpu->arch.exit_qualification = exit_qualification;
5099 	return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5100 }
5101 
5102 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5103 {
5104 	gpa_t gpa;
5105 
5106 	/*
5107 	 * A nested guest cannot optimize MMIO vmexits, because we have an
5108 	 * nGPA here instead of the required GPA.
5109 	 */
5110 	gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5111 	if (!is_guest_mode(vcpu) &&
5112 	    !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5113 		trace_kvm_fast_mmio(gpa);
5114 		/*
5115 		 * Doing kvm_skip_emulated_instruction() depends on undefined
5116 		 * behavior: Intel's manual doesn't mandate
5117 		 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
5118 		 * occurs and while on real hardware it was observed to be set,
5119 		 * other hypervisors (namely Hyper-V) don't set it, we end up
5120 		 * advancing IP with some random value. Disable fast mmio when
5121 		 * running nested and keep it for real hardware in hope that
5122 		 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
5123 		 */
5124 		if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
5125 			return kvm_skip_emulated_instruction(vcpu);
5126 		else
5127 			return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
5128 								EMULATE_DONE;
5129 	}
5130 
5131 	return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5132 }
5133 
5134 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5135 {
5136 	WARN_ON_ONCE(!enable_vnmi);
5137 	vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
5138 			CPU_BASED_VIRTUAL_NMI_PENDING);
5139 	++vcpu->stat.nmi_window_exits;
5140 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5141 
5142 	return 1;
5143 }
5144 
5145 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5146 {
5147 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5148 	enum emulation_result err = EMULATE_DONE;
5149 	int ret = 1;
5150 	u32 cpu_exec_ctrl;
5151 	bool intr_window_requested;
5152 	unsigned count = 130;
5153 
5154 	/*
5155 	 * We should never reach the point where we are emulating L2
5156 	 * due to invalid guest state as that means we incorrectly
5157 	 * allowed a nested VMEntry with an invalid vmcs12.
5158 	 */
5159 	WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
5160 
5161 	cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5162 	intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
5163 
5164 	while (vmx->emulation_required && count-- != 0) {
5165 		if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5166 			return handle_interrupt_window(&vmx->vcpu);
5167 
5168 		if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5169 			return 1;
5170 
5171 		err = kvm_emulate_instruction(vcpu, 0);
5172 
5173 		if (err == EMULATE_USER_EXIT) {
5174 			++vcpu->stat.mmio_exits;
5175 			ret = 0;
5176 			goto out;
5177 		}
5178 
5179 		if (err != EMULATE_DONE)
5180 			goto emulation_error;
5181 
5182 		if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5183 		    vcpu->arch.exception.pending)
5184 			goto emulation_error;
5185 
5186 		if (vcpu->arch.halt_request) {
5187 			vcpu->arch.halt_request = 0;
5188 			ret = kvm_vcpu_halt(vcpu);
5189 			goto out;
5190 		}
5191 
5192 		if (signal_pending(current))
5193 			goto out;
5194 		if (need_resched())
5195 			schedule();
5196 	}
5197 
5198 out:
5199 	return ret;
5200 
5201 emulation_error:
5202 	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5203 	vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5204 	vcpu->run->internal.ndata = 0;
5205 	return 0;
5206 }
5207 
5208 static void grow_ple_window(struct kvm_vcpu *vcpu)
5209 {
5210 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5211 	int old = vmx->ple_window;
5212 
5213 	vmx->ple_window = __grow_ple_window(old, ple_window,
5214 					    ple_window_grow,
5215 					    ple_window_max);
5216 
5217 	if (vmx->ple_window != old)
5218 		vmx->ple_window_dirty = true;
5219 
5220 	trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
5221 }
5222 
5223 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5224 {
5225 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5226 	int old = vmx->ple_window;
5227 
5228 	vmx->ple_window = __shrink_ple_window(old, ple_window,
5229 					      ple_window_shrink,
5230 					      ple_window);
5231 
5232 	if (vmx->ple_window != old)
5233 		vmx->ple_window_dirty = true;
5234 
5235 	trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
5236 }
5237 
5238 /*
5239  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5240  */
5241 static void wakeup_handler(void)
5242 {
5243 	struct kvm_vcpu *vcpu;
5244 	int cpu = smp_processor_id();
5245 
5246 	spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5247 	list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5248 			blocked_vcpu_list) {
5249 		struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5250 
5251 		if (pi_test_on(pi_desc) == 1)
5252 			kvm_vcpu_kick(vcpu);
5253 	}
5254 	spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5255 }
5256 
5257 static void vmx_enable_tdp(void)
5258 {
5259 	kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5260 		enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5261 		enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5262 		0ull, VMX_EPT_EXECUTABLE_MASK,
5263 		cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5264 		VMX_EPT_RWX_MASK, 0ull);
5265 
5266 	ept_set_mmio_spte_mask();
5267 	kvm_enable_tdp();
5268 }
5269 
5270 /*
5271  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5272  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5273  */
5274 static int handle_pause(struct kvm_vcpu *vcpu)
5275 {
5276 	if (!kvm_pause_in_guest(vcpu->kvm))
5277 		grow_ple_window(vcpu);
5278 
5279 	/*
5280 	 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5281 	 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5282 	 * never set PAUSE_EXITING and just set PLE if supported,
5283 	 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5284 	 */
5285 	kvm_vcpu_on_spin(vcpu, true);
5286 	return kvm_skip_emulated_instruction(vcpu);
5287 }
5288 
5289 static int handle_nop(struct kvm_vcpu *vcpu)
5290 {
5291 	return kvm_skip_emulated_instruction(vcpu);
5292 }
5293 
5294 static int handle_mwait(struct kvm_vcpu *vcpu)
5295 {
5296 	printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5297 	return handle_nop(vcpu);
5298 }
5299 
5300 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5301 {
5302 	kvm_queue_exception(vcpu, UD_VECTOR);
5303 	return 1;
5304 }
5305 
5306 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5307 {
5308 	return 1;
5309 }
5310 
5311 static int handle_monitor(struct kvm_vcpu *vcpu)
5312 {
5313 	printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5314 	return handle_nop(vcpu);
5315 }
5316 
5317 static int handle_invpcid(struct kvm_vcpu *vcpu)
5318 {
5319 	u32 vmx_instruction_info;
5320 	unsigned long type;
5321 	bool pcid_enabled;
5322 	gva_t gva;
5323 	struct x86_exception e;
5324 	unsigned i;
5325 	unsigned long roots_to_free = 0;
5326 	struct {
5327 		u64 pcid;
5328 		u64 gla;
5329 	} operand;
5330 
5331 	if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5332 		kvm_queue_exception(vcpu, UD_VECTOR);
5333 		return 1;
5334 	}
5335 
5336 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5337 	type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5338 
5339 	if (type > 3) {
5340 		kvm_inject_gp(vcpu, 0);
5341 		return 1;
5342 	}
5343 
5344 	/* According to the Intel instruction reference, the memory operand
5345 	 * is read even if it isn't needed (e.g., for type==all)
5346 	 */
5347 	if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5348 				vmx_instruction_info, false, &gva))
5349 		return 1;
5350 
5351 	if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5352 		kvm_inject_page_fault(vcpu, &e);
5353 		return 1;
5354 	}
5355 
5356 	if (operand.pcid >> 12 != 0) {
5357 		kvm_inject_gp(vcpu, 0);
5358 		return 1;
5359 	}
5360 
5361 	pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5362 
5363 	switch (type) {
5364 	case INVPCID_TYPE_INDIV_ADDR:
5365 		if ((!pcid_enabled && (operand.pcid != 0)) ||
5366 		    is_noncanonical_address(operand.gla, vcpu)) {
5367 			kvm_inject_gp(vcpu, 0);
5368 			return 1;
5369 		}
5370 		kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5371 		return kvm_skip_emulated_instruction(vcpu);
5372 
5373 	case INVPCID_TYPE_SINGLE_CTXT:
5374 		if (!pcid_enabled && (operand.pcid != 0)) {
5375 			kvm_inject_gp(vcpu, 0);
5376 			return 1;
5377 		}
5378 
5379 		if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5380 			kvm_mmu_sync_roots(vcpu);
5381 			kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5382 		}
5383 
5384 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5385 			if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
5386 			    == operand.pcid)
5387 				roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5388 
5389 		kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5390 		/*
5391 		 * If neither the current cr3 nor any of the prev_roots use the
5392 		 * given PCID, then nothing needs to be done here because a
5393 		 * resync will happen anyway before switching to any other CR3.
5394 		 */
5395 
5396 		return kvm_skip_emulated_instruction(vcpu);
5397 
5398 	case INVPCID_TYPE_ALL_NON_GLOBAL:
5399 		/*
5400 		 * Currently, KVM doesn't mark global entries in the shadow
5401 		 * page tables, so a non-global flush just degenerates to a
5402 		 * global flush. If needed, we could optimize this later by
5403 		 * keeping track of global entries in shadow page tables.
5404 		 */
5405 
5406 		/* fall-through */
5407 	case INVPCID_TYPE_ALL_INCL_GLOBAL:
5408 		kvm_mmu_unload(vcpu);
5409 		return kvm_skip_emulated_instruction(vcpu);
5410 
5411 	default:
5412 		BUG(); /* We have already checked above that type <= 3 */
5413 	}
5414 }
5415 
5416 static int handle_pml_full(struct kvm_vcpu *vcpu)
5417 {
5418 	unsigned long exit_qualification;
5419 
5420 	trace_kvm_pml_full(vcpu->vcpu_id);
5421 
5422 	exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5423 
5424 	/*
5425 	 * PML buffer FULL happened while executing iret from NMI,
5426 	 * "blocked by NMI" bit has to be set before next VM entry.
5427 	 */
5428 	if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5429 			enable_vnmi &&
5430 			(exit_qualification & INTR_INFO_UNBLOCK_NMI))
5431 		vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5432 				GUEST_INTR_STATE_NMI);
5433 
5434 	/*
5435 	 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5436 	 * here.., and there's no userspace involvement needed for PML.
5437 	 */
5438 	return 1;
5439 }
5440 
5441 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5442 {
5443 	if (!to_vmx(vcpu)->req_immediate_exit)
5444 		kvm_lapic_expired_hv_timer(vcpu);
5445 	return 1;
5446 }
5447 
5448 /*
5449  * When nested=0, all VMX instruction VM Exits filter here.  The handlers
5450  * are overwritten by nested_vmx_setup() when nested=1.
5451  */
5452 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5453 {
5454 	kvm_queue_exception(vcpu, UD_VECTOR);
5455 	return 1;
5456 }
5457 
5458 static int handle_encls(struct kvm_vcpu *vcpu)
5459 {
5460 	/*
5461 	 * SGX virtualization is not yet supported.  There is no software
5462 	 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5463 	 * to prevent the guest from executing ENCLS.
5464 	 */
5465 	kvm_queue_exception(vcpu, UD_VECTOR);
5466 	return 1;
5467 }
5468 
5469 /*
5470  * The exit handlers return 1 if the exit was handled fully and guest execution
5471  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
5472  * to be done to userspace and return 0.
5473  */
5474 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5475 	[EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
5476 	[EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
5477 	[EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
5478 	[EXIT_REASON_NMI_WINDOW]	      = handle_nmi_window,
5479 	[EXIT_REASON_IO_INSTRUCTION]          = handle_io,
5480 	[EXIT_REASON_CR_ACCESS]               = handle_cr,
5481 	[EXIT_REASON_DR_ACCESS]               = handle_dr,
5482 	[EXIT_REASON_CPUID]                   = handle_cpuid,
5483 	[EXIT_REASON_MSR_READ]                = handle_rdmsr,
5484 	[EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
5485 	[EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
5486 	[EXIT_REASON_HLT]                     = handle_halt,
5487 	[EXIT_REASON_INVD]		      = handle_invd,
5488 	[EXIT_REASON_INVLPG]		      = handle_invlpg,
5489 	[EXIT_REASON_RDPMC]                   = handle_rdpmc,
5490 	[EXIT_REASON_VMCALL]                  = handle_vmcall,
5491 	[EXIT_REASON_VMCLEAR]		      = handle_vmx_instruction,
5492 	[EXIT_REASON_VMLAUNCH]		      = handle_vmx_instruction,
5493 	[EXIT_REASON_VMPTRLD]		      = handle_vmx_instruction,
5494 	[EXIT_REASON_VMPTRST]		      = handle_vmx_instruction,
5495 	[EXIT_REASON_VMREAD]		      = handle_vmx_instruction,
5496 	[EXIT_REASON_VMRESUME]		      = handle_vmx_instruction,
5497 	[EXIT_REASON_VMWRITE]		      = handle_vmx_instruction,
5498 	[EXIT_REASON_VMOFF]		      = handle_vmx_instruction,
5499 	[EXIT_REASON_VMON]		      = handle_vmx_instruction,
5500 	[EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
5501 	[EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
5502 	[EXIT_REASON_APIC_WRITE]              = handle_apic_write,
5503 	[EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
5504 	[EXIT_REASON_WBINVD]                  = handle_wbinvd,
5505 	[EXIT_REASON_XSETBV]                  = handle_xsetbv,
5506 	[EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
5507 	[EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
5508 	[EXIT_REASON_GDTR_IDTR]		      = handle_desc,
5509 	[EXIT_REASON_LDTR_TR]		      = handle_desc,
5510 	[EXIT_REASON_EPT_VIOLATION]	      = handle_ept_violation,
5511 	[EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
5512 	[EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
5513 	[EXIT_REASON_MWAIT_INSTRUCTION]	      = handle_mwait,
5514 	[EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
5515 	[EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
5516 	[EXIT_REASON_INVEPT]                  = handle_vmx_instruction,
5517 	[EXIT_REASON_INVVPID]                 = handle_vmx_instruction,
5518 	[EXIT_REASON_RDRAND]                  = handle_invalid_op,
5519 	[EXIT_REASON_RDSEED]                  = handle_invalid_op,
5520 	[EXIT_REASON_XSAVES]                  = handle_xsaves,
5521 	[EXIT_REASON_XRSTORS]                 = handle_xrstors,
5522 	[EXIT_REASON_PML_FULL]		      = handle_pml_full,
5523 	[EXIT_REASON_INVPCID]                 = handle_invpcid,
5524 	[EXIT_REASON_VMFUNC]		      = handle_vmx_instruction,
5525 	[EXIT_REASON_PREEMPTION_TIMER]	      = handle_preemption_timer,
5526 	[EXIT_REASON_ENCLS]		      = handle_encls,
5527 };
5528 
5529 static const int kvm_vmx_max_exit_handlers =
5530 	ARRAY_SIZE(kvm_vmx_exit_handlers);
5531 
5532 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5533 {
5534 	*info1 = vmcs_readl(EXIT_QUALIFICATION);
5535 	*info2 = vmcs_read32(VM_EXIT_INTR_INFO);
5536 }
5537 
5538 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5539 {
5540 	if (vmx->pml_pg) {
5541 		__free_page(vmx->pml_pg);
5542 		vmx->pml_pg = NULL;
5543 	}
5544 }
5545 
5546 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5547 {
5548 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5549 	u64 *pml_buf;
5550 	u16 pml_idx;
5551 
5552 	pml_idx = vmcs_read16(GUEST_PML_INDEX);
5553 
5554 	/* Do nothing if PML buffer is empty */
5555 	if (pml_idx == (PML_ENTITY_NUM - 1))
5556 		return;
5557 
5558 	/* PML index always points to next available PML buffer entity */
5559 	if (pml_idx >= PML_ENTITY_NUM)
5560 		pml_idx = 0;
5561 	else
5562 		pml_idx++;
5563 
5564 	pml_buf = page_address(vmx->pml_pg);
5565 	for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5566 		u64 gpa;
5567 
5568 		gpa = pml_buf[pml_idx];
5569 		WARN_ON(gpa & (PAGE_SIZE - 1));
5570 		kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5571 	}
5572 
5573 	/* reset PML index */
5574 	vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5575 }
5576 
5577 /*
5578  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5579  * Called before reporting dirty_bitmap to userspace.
5580  */
5581 static void kvm_flush_pml_buffers(struct kvm *kvm)
5582 {
5583 	int i;
5584 	struct kvm_vcpu *vcpu;
5585 	/*
5586 	 * We only need to kick vcpu out of guest mode here, as PML buffer
5587 	 * is flushed at beginning of all VMEXITs, and it's obvious that only
5588 	 * vcpus running in guest are possible to have unflushed GPAs in PML
5589 	 * buffer.
5590 	 */
5591 	kvm_for_each_vcpu(i, vcpu, kvm)
5592 		kvm_vcpu_kick(vcpu);
5593 }
5594 
5595 static void vmx_dump_sel(char *name, uint32_t sel)
5596 {
5597 	pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5598 	       name, vmcs_read16(sel),
5599 	       vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5600 	       vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5601 	       vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5602 }
5603 
5604 static void vmx_dump_dtsel(char *name, uint32_t limit)
5605 {
5606 	pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
5607 	       name, vmcs_read32(limit),
5608 	       vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5609 }
5610 
5611 void dump_vmcs(void)
5612 {
5613 	u32 vmentry_ctl, vmexit_ctl;
5614 	u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5615 	unsigned long cr4;
5616 	u64 efer;
5617 	int i, n;
5618 
5619 	if (!dump_invalid_vmcs) {
5620 		pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5621 		return;
5622 	}
5623 
5624 	vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5625 	vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5626 	cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5627 	pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5628 	cr4 = vmcs_readl(GUEST_CR4);
5629 	efer = vmcs_read64(GUEST_IA32_EFER);
5630 	secondary_exec_control = 0;
5631 	if (cpu_has_secondary_exec_ctrls())
5632 		secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5633 
5634 	pr_err("*** Guest State ***\n");
5635 	pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5636 	       vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5637 	       vmcs_readl(CR0_GUEST_HOST_MASK));
5638 	pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5639 	       cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5640 	pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5641 	if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5642 	    (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5643 	{
5644 		pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
5645 		       vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5646 		pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
5647 		       vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5648 	}
5649 	pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
5650 	       vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5651 	pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
5652 	       vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5653 	pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5654 	       vmcs_readl(GUEST_SYSENTER_ESP),
5655 	       vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5656 	vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
5657 	vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
5658 	vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
5659 	vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
5660 	vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
5661 	vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
5662 	vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5663 	vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5664 	vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5665 	vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
5666 	if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5667 	    (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5668 		pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
5669 		       efer, vmcs_read64(GUEST_IA32_PAT));
5670 	pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
5671 	       vmcs_read64(GUEST_IA32_DEBUGCTL),
5672 	       vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5673 	if (cpu_has_load_perf_global_ctrl() &&
5674 	    vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5675 		pr_err("PerfGlobCtl = 0x%016llx\n",
5676 		       vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5677 	if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5678 		pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5679 	pr_err("Interruptibility = %08x  ActivityState = %08x\n",
5680 	       vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5681 	       vmcs_read32(GUEST_ACTIVITY_STATE));
5682 	if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5683 		pr_err("InterruptStatus = %04x\n",
5684 		       vmcs_read16(GUEST_INTR_STATUS));
5685 
5686 	pr_err("*** Host State ***\n");
5687 	pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
5688 	       vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5689 	pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5690 	       vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5691 	       vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5692 	       vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5693 	       vmcs_read16(HOST_TR_SELECTOR));
5694 	pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5695 	       vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5696 	       vmcs_readl(HOST_TR_BASE));
5697 	pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5698 	       vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5699 	pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5700 	       vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5701 	       vmcs_readl(HOST_CR4));
5702 	pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5703 	       vmcs_readl(HOST_IA32_SYSENTER_ESP),
5704 	       vmcs_read32(HOST_IA32_SYSENTER_CS),
5705 	       vmcs_readl(HOST_IA32_SYSENTER_EIP));
5706 	if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5707 		pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
5708 		       vmcs_read64(HOST_IA32_EFER),
5709 		       vmcs_read64(HOST_IA32_PAT));
5710 	if (cpu_has_load_perf_global_ctrl() &&
5711 	    vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5712 		pr_err("PerfGlobCtl = 0x%016llx\n",
5713 		       vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5714 
5715 	pr_err("*** Control State ***\n");
5716 	pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5717 	       pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5718 	pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5719 	pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5720 	       vmcs_read32(EXCEPTION_BITMAP),
5721 	       vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5722 	       vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5723 	pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5724 	       vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5725 	       vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5726 	       vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5727 	pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5728 	       vmcs_read32(VM_EXIT_INTR_INFO),
5729 	       vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5730 	       vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5731 	pr_err("        reason=%08x qualification=%016lx\n",
5732 	       vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5733 	pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5734 	       vmcs_read32(IDT_VECTORING_INFO_FIELD),
5735 	       vmcs_read32(IDT_VECTORING_ERROR_CODE));
5736 	pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5737 	if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5738 		pr_err("TSC Multiplier = 0x%016llx\n",
5739 		       vmcs_read64(TSC_MULTIPLIER));
5740 	if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5741 		if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5742 			u16 status = vmcs_read16(GUEST_INTR_STATUS);
5743 			pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5744 		}
5745 		pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5746 		if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5747 			pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5748 		pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5749 	}
5750 	if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5751 		pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5752 	if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5753 		pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5754 	n = vmcs_read32(CR3_TARGET_COUNT);
5755 	for (i = 0; i + 1 < n; i += 4)
5756 		pr_err("CR3 target%u=%016lx target%u=%016lx\n",
5757 		       i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
5758 		       i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
5759 	if (i < n)
5760 		pr_err("CR3 target%u=%016lx\n",
5761 		       i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
5762 	if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5763 		pr_err("PLE Gap=%08x Window=%08x\n",
5764 		       vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5765 	if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5766 		pr_err("Virtual processor ID = 0x%04x\n",
5767 		       vmcs_read16(VIRTUAL_PROCESSOR_ID));
5768 }
5769 
5770 /*
5771  * The guest has exited.  See if we can fix it or if we need userspace
5772  * assistance.
5773  */
5774 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
5775 {
5776 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5777 	u32 exit_reason = vmx->exit_reason;
5778 	u32 vectoring_info = vmx->idt_vectoring_info;
5779 
5780 	trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
5781 
5782 	/*
5783 	 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5784 	 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5785 	 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5786 	 * mode as if vcpus is in root mode, the PML buffer must has been
5787 	 * flushed already.
5788 	 */
5789 	if (enable_pml)
5790 		vmx_flush_pml_buffer(vcpu);
5791 
5792 	/* If guest state is invalid, start emulating */
5793 	if (vmx->emulation_required)
5794 		return handle_invalid_guest_state(vcpu);
5795 
5796 	if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
5797 		return nested_vmx_reflect_vmexit(vcpu, exit_reason);
5798 
5799 	if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5800 		dump_vmcs();
5801 		vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5802 		vcpu->run->fail_entry.hardware_entry_failure_reason
5803 			= exit_reason;
5804 		return 0;
5805 	}
5806 
5807 	if (unlikely(vmx->fail)) {
5808 		vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5809 		vcpu->run->fail_entry.hardware_entry_failure_reason
5810 			= vmcs_read32(VM_INSTRUCTION_ERROR);
5811 		return 0;
5812 	}
5813 
5814 	/*
5815 	 * Note:
5816 	 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5817 	 * delivery event since it indicates guest is accessing MMIO.
5818 	 * The vm-exit can be triggered again after return to guest that
5819 	 * will cause infinite loop.
5820 	 */
5821 	if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5822 			(exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5823 			exit_reason != EXIT_REASON_EPT_VIOLATION &&
5824 			exit_reason != EXIT_REASON_PML_FULL &&
5825 			exit_reason != EXIT_REASON_TASK_SWITCH)) {
5826 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5827 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
5828 		vcpu->run->internal.ndata = 3;
5829 		vcpu->run->internal.data[0] = vectoring_info;
5830 		vcpu->run->internal.data[1] = exit_reason;
5831 		vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
5832 		if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
5833 			vcpu->run->internal.ndata++;
5834 			vcpu->run->internal.data[3] =
5835 				vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5836 		}
5837 		return 0;
5838 	}
5839 
5840 	if (unlikely(!enable_vnmi &&
5841 		     vmx->loaded_vmcs->soft_vnmi_blocked)) {
5842 		if (vmx_interrupt_allowed(vcpu)) {
5843 			vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5844 		} else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
5845 			   vcpu->arch.nmi_pending) {
5846 			/*
5847 			 * This CPU don't support us in finding the end of an
5848 			 * NMI-blocked window if the guest runs with IRQs
5849 			 * disabled. So we pull the trigger after 1 s of
5850 			 * futile waiting, but inform the user about this.
5851 			 */
5852 			printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
5853 			       "state on VCPU %d after 1 s timeout\n",
5854 			       __func__, vcpu->vcpu_id);
5855 			vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5856 		}
5857 	}
5858 
5859 	if (exit_reason < kvm_vmx_max_exit_handlers
5860 	    && kvm_vmx_exit_handlers[exit_reason])
5861 		return kvm_vmx_exit_handlers[exit_reason](vcpu);
5862 	else {
5863 		vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
5864 				exit_reason);
5865 		kvm_queue_exception(vcpu, UD_VECTOR);
5866 		return 1;
5867 	}
5868 }
5869 
5870 /*
5871  * Software based L1D cache flush which is used when microcode providing
5872  * the cache control MSR is not loaded.
5873  *
5874  * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
5875  * flush it is required to read in 64 KiB because the replacement algorithm
5876  * is not exactly LRU. This could be sized at runtime via topology
5877  * information but as all relevant affected CPUs have 32KiB L1D cache size
5878  * there is no point in doing so.
5879  */
5880 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
5881 {
5882 	int size = PAGE_SIZE << L1D_CACHE_ORDER;
5883 
5884 	/*
5885 	 * This code is only executed when the the flush mode is 'cond' or
5886 	 * 'always'
5887 	 */
5888 	if (static_branch_likely(&vmx_l1d_flush_cond)) {
5889 		bool flush_l1d;
5890 
5891 		/*
5892 		 * Clear the per-vcpu flush bit, it gets set again
5893 		 * either from vcpu_run() or from one of the unsafe
5894 		 * VMEXIT handlers.
5895 		 */
5896 		flush_l1d = vcpu->arch.l1tf_flush_l1d;
5897 		vcpu->arch.l1tf_flush_l1d = false;
5898 
5899 		/*
5900 		 * Clear the per-cpu flush bit, it gets set again from
5901 		 * the interrupt handlers.
5902 		 */
5903 		flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
5904 		kvm_clear_cpu_l1tf_flush_l1d();
5905 
5906 		if (!flush_l1d)
5907 			return;
5908 	}
5909 
5910 	vcpu->stat.l1d_flush++;
5911 
5912 	if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
5913 		wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
5914 		return;
5915 	}
5916 
5917 	asm volatile(
5918 		/* First ensure the pages are in the TLB */
5919 		"xorl	%%eax, %%eax\n"
5920 		".Lpopulate_tlb:\n\t"
5921 		"movzbl	(%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5922 		"addl	$4096, %%eax\n\t"
5923 		"cmpl	%%eax, %[size]\n\t"
5924 		"jne	.Lpopulate_tlb\n\t"
5925 		"xorl	%%eax, %%eax\n\t"
5926 		"cpuid\n\t"
5927 		/* Now fill the cache */
5928 		"xorl	%%eax, %%eax\n"
5929 		".Lfill_cache:\n"
5930 		"movzbl	(%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5931 		"addl	$64, %%eax\n\t"
5932 		"cmpl	%%eax, %[size]\n\t"
5933 		"jne	.Lfill_cache\n\t"
5934 		"lfence\n"
5935 		:: [flush_pages] "r" (vmx_l1d_flush_pages),
5936 		    [size] "r" (size)
5937 		: "eax", "ebx", "ecx", "edx");
5938 }
5939 
5940 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5941 {
5942 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5943 
5944 	if (is_guest_mode(vcpu) &&
5945 		nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
5946 		return;
5947 
5948 	if (irr == -1 || tpr < irr) {
5949 		vmcs_write32(TPR_THRESHOLD, 0);
5950 		return;
5951 	}
5952 
5953 	vmcs_write32(TPR_THRESHOLD, irr);
5954 }
5955 
5956 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5957 {
5958 	u32 sec_exec_control;
5959 
5960 	if (!lapic_in_kernel(vcpu))
5961 		return;
5962 
5963 	if (!flexpriority_enabled &&
5964 	    !cpu_has_vmx_virtualize_x2apic_mode())
5965 		return;
5966 
5967 	/* Postpone execution until vmcs01 is the current VMCS. */
5968 	if (is_guest_mode(vcpu)) {
5969 		to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
5970 		return;
5971 	}
5972 
5973 	sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5974 	sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
5975 			      SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
5976 
5977 	switch (kvm_get_apic_mode(vcpu)) {
5978 	case LAPIC_MODE_INVALID:
5979 		WARN_ONCE(true, "Invalid local APIC state");
5980 	case LAPIC_MODE_DISABLED:
5981 		break;
5982 	case LAPIC_MODE_XAPIC:
5983 		if (flexpriority_enabled) {
5984 			sec_exec_control |=
5985 				SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5986 			vmx_flush_tlb(vcpu, true);
5987 		}
5988 		break;
5989 	case LAPIC_MODE_X2APIC:
5990 		if (cpu_has_vmx_virtualize_x2apic_mode())
5991 			sec_exec_control |=
5992 				SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5993 		break;
5994 	}
5995 	vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
5996 
5997 	vmx_update_msr_bitmap(vcpu);
5998 }
5999 
6000 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
6001 {
6002 	if (!is_guest_mode(vcpu)) {
6003 		vmcs_write64(APIC_ACCESS_ADDR, hpa);
6004 		vmx_flush_tlb(vcpu, true);
6005 	}
6006 }
6007 
6008 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6009 {
6010 	u16 status;
6011 	u8 old;
6012 
6013 	if (max_isr == -1)
6014 		max_isr = 0;
6015 
6016 	status = vmcs_read16(GUEST_INTR_STATUS);
6017 	old = status >> 8;
6018 	if (max_isr != old) {
6019 		status &= 0xff;
6020 		status |= max_isr << 8;
6021 		vmcs_write16(GUEST_INTR_STATUS, status);
6022 	}
6023 }
6024 
6025 static void vmx_set_rvi(int vector)
6026 {
6027 	u16 status;
6028 	u8 old;
6029 
6030 	if (vector == -1)
6031 		vector = 0;
6032 
6033 	status = vmcs_read16(GUEST_INTR_STATUS);
6034 	old = (u8)status & 0xff;
6035 	if ((u8)vector != old) {
6036 		status &= ~0xff;
6037 		status |= (u8)vector;
6038 		vmcs_write16(GUEST_INTR_STATUS, status);
6039 	}
6040 }
6041 
6042 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6043 {
6044 	/*
6045 	 * When running L2, updating RVI is only relevant when
6046 	 * vmcs12 virtual-interrupt-delivery enabled.
6047 	 * However, it can be enabled only when L1 also
6048 	 * intercepts external-interrupts and in that case
6049 	 * we should not update vmcs02 RVI but instead intercept
6050 	 * interrupt. Therefore, do nothing when running L2.
6051 	 */
6052 	if (!is_guest_mode(vcpu))
6053 		vmx_set_rvi(max_irr);
6054 }
6055 
6056 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6057 {
6058 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6059 	int max_irr;
6060 	bool max_irr_updated;
6061 
6062 	WARN_ON(!vcpu->arch.apicv_active);
6063 	if (pi_test_on(&vmx->pi_desc)) {
6064 		pi_clear_on(&vmx->pi_desc);
6065 		/*
6066 		 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
6067 		 * But on x86 this is just a compiler barrier anyway.
6068 		 */
6069 		smp_mb__after_atomic();
6070 		max_irr_updated =
6071 			kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6072 
6073 		/*
6074 		 * If we are running L2 and L1 has a new pending interrupt
6075 		 * which can be injected, we should re-evaluate
6076 		 * what should be done with this new L1 interrupt.
6077 		 * If L1 intercepts external-interrupts, we should
6078 		 * exit from L2 to L1. Otherwise, interrupt should be
6079 		 * delivered directly to L2.
6080 		 */
6081 		if (is_guest_mode(vcpu) && max_irr_updated) {
6082 			if (nested_exit_on_intr(vcpu))
6083 				kvm_vcpu_exiting_guest_mode(vcpu);
6084 			else
6085 				kvm_make_request(KVM_REQ_EVENT, vcpu);
6086 		}
6087 	} else {
6088 		max_irr = kvm_lapic_find_highest_irr(vcpu);
6089 	}
6090 	vmx_hwapic_irr_update(vcpu, max_irr);
6091 	return max_irr;
6092 }
6093 
6094 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6095 {
6096 	if (!kvm_vcpu_apicv_active(vcpu))
6097 		return;
6098 
6099 	vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6100 	vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6101 	vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6102 	vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6103 }
6104 
6105 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6106 {
6107 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6108 
6109 	pi_clear_on(&vmx->pi_desc);
6110 	memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6111 }
6112 
6113 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
6114 {
6115 	u32 exit_intr_info = 0;
6116 	u16 basic_exit_reason = (u16)vmx->exit_reason;
6117 
6118 	if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
6119 	      || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
6120 		return;
6121 
6122 	if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6123 		exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6124 	vmx->exit_intr_info = exit_intr_info;
6125 
6126 	/* if exit due to PF check for async PF */
6127 	if (is_page_fault(exit_intr_info))
6128 		vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
6129 
6130 	/* Handle machine checks before interrupts are enabled */
6131 	if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
6132 	    is_machine_check(exit_intr_info))
6133 		kvm_machine_check();
6134 
6135 	/* We need to handle NMIs before interrupts are enabled */
6136 	if (is_nmi(exit_intr_info)) {
6137 		kvm_before_interrupt(&vmx->vcpu);
6138 		asm("int $2");
6139 		kvm_after_interrupt(&vmx->vcpu);
6140 	}
6141 }
6142 
6143 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
6144 {
6145 	u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6146 
6147 	if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
6148 			== (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
6149 		unsigned int vector;
6150 		unsigned long entry;
6151 		gate_desc *desc;
6152 		struct vcpu_vmx *vmx = to_vmx(vcpu);
6153 #ifdef CONFIG_X86_64
6154 		unsigned long tmp;
6155 #endif
6156 
6157 		vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
6158 		desc = (gate_desc *)vmx->host_idt_base + vector;
6159 		entry = gate_offset(desc);
6160 		asm volatile(
6161 #ifdef CONFIG_X86_64
6162 			"mov %%" _ASM_SP ", %[sp]\n\t"
6163 			"and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
6164 			"push $%c[ss]\n\t"
6165 			"push %[sp]\n\t"
6166 #endif
6167 			"pushf\n\t"
6168 			__ASM_SIZE(push) " $%c[cs]\n\t"
6169 			CALL_NOSPEC
6170 			:
6171 #ifdef CONFIG_X86_64
6172 			[sp]"=&r"(tmp),
6173 #endif
6174 			ASM_CALL_CONSTRAINT
6175 			:
6176 			THUNK_TARGET(entry),
6177 			[ss]"i"(__KERNEL_DS),
6178 			[cs]"i"(__KERNEL_CS)
6179 			);
6180 	}
6181 }
6182 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
6183 
6184 static bool vmx_has_emulated_msr(int index)
6185 {
6186 	switch (index) {
6187 	case MSR_IA32_SMBASE:
6188 		/*
6189 		 * We cannot do SMM unless we can run the guest in big
6190 		 * real mode.
6191 		 */
6192 		return enable_unrestricted_guest || emulate_invalid_guest_state;
6193 	case MSR_AMD64_VIRT_SPEC_CTRL:
6194 		/* This is AMD only.  */
6195 		return false;
6196 	default:
6197 		return true;
6198 	}
6199 }
6200 
6201 static bool vmx_pt_supported(void)
6202 {
6203 	return pt_mode == PT_MODE_HOST_GUEST;
6204 }
6205 
6206 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6207 {
6208 	u32 exit_intr_info;
6209 	bool unblock_nmi;
6210 	u8 vector;
6211 	bool idtv_info_valid;
6212 
6213 	idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6214 
6215 	if (enable_vnmi) {
6216 		if (vmx->loaded_vmcs->nmi_known_unmasked)
6217 			return;
6218 		/*
6219 		 * Can't use vmx->exit_intr_info since we're not sure what
6220 		 * the exit reason is.
6221 		 */
6222 		exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6223 		unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6224 		vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6225 		/*
6226 		 * SDM 3: 27.7.1.2 (September 2008)
6227 		 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6228 		 * a guest IRET fault.
6229 		 * SDM 3: 23.2.2 (September 2008)
6230 		 * Bit 12 is undefined in any of the following cases:
6231 		 *  If the VM exit sets the valid bit in the IDT-vectoring
6232 		 *   information field.
6233 		 *  If the VM exit is due to a double fault.
6234 		 */
6235 		if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6236 		    vector != DF_VECTOR && !idtv_info_valid)
6237 			vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6238 				      GUEST_INTR_STATE_NMI);
6239 		else
6240 			vmx->loaded_vmcs->nmi_known_unmasked =
6241 				!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6242 				  & GUEST_INTR_STATE_NMI);
6243 	} else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6244 		vmx->loaded_vmcs->vnmi_blocked_time +=
6245 			ktime_to_ns(ktime_sub(ktime_get(),
6246 					      vmx->loaded_vmcs->entry_time));
6247 }
6248 
6249 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6250 				      u32 idt_vectoring_info,
6251 				      int instr_len_field,
6252 				      int error_code_field)
6253 {
6254 	u8 vector;
6255 	int type;
6256 	bool idtv_info_valid;
6257 
6258 	idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6259 
6260 	vcpu->arch.nmi_injected = false;
6261 	kvm_clear_exception_queue(vcpu);
6262 	kvm_clear_interrupt_queue(vcpu);
6263 
6264 	if (!idtv_info_valid)
6265 		return;
6266 
6267 	kvm_make_request(KVM_REQ_EVENT, vcpu);
6268 
6269 	vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6270 	type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6271 
6272 	switch (type) {
6273 	case INTR_TYPE_NMI_INTR:
6274 		vcpu->arch.nmi_injected = true;
6275 		/*
6276 		 * SDM 3: 27.7.1.2 (September 2008)
6277 		 * Clear bit "block by NMI" before VM entry if a NMI
6278 		 * delivery faulted.
6279 		 */
6280 		vmx_set_nmi_mask(vcpu, false);
6281 		break;
6282 	case INTR_TYPE_SOFT_EXCEPTION:
6283 		vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6284 		/* fall through */
6285 	case INTR_TYPE_HARD_EXCEPTION:
6286 		if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6287 			u32 err = vmcs_read32(error_code_field);
6288 			kvm_requeue_exception_e(vcpu, vector, err);
6289 		} else
6290 			kvm_requeue_exception(vcpu, vector);
6291 		break;
6292 	case INTR_TYPE_SOFT_INTR:
6293 		vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6294 		/* fall through */
6295 	case INTR_TYPE_EXT_INTR:
6296 		kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6297 		break;
6298 	default:
6299 		break;
6300 	}
6301 }
6302 
6303 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6304 {
6305 	__vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6306 				  VM_EXIT_INSTRUCTION_LEN,
6307 				  IDT_VECTORING_ERROR_CODE);
6308 }
6309 
6310 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6311 {
6312 	__vmx_complete_interrupts(vcpu,
6313 				  vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6314 				  VM_ENTRY_INSTRUCTION_LEN,
6315 				  VM_ENTRY_EXCEPTION_ERROR_CODE);
6316 
6317 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6318 }
6319 
6320 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6321 {
6322 	int i, nr_msrs;
6323 	struct perf_guest_switch_msr *msrs;
6324 
6325 	msrs = perf_guest_get_msrs(&nr_msrs);
6326 
6327 	if (!msrs)
6328 		return;
6329 
6330 	for (i = 0; i < nr_msrs; i++)
6331 		if (msrs[i].host == msrs[i].guest)
6332 			clear_atomic_switch_msr(vmx, msrs[i].msr);
6333 		else
6334 			add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6335 					msrs[i].host, false);
6336 }
6337 
6338 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
6339 {
6340 	vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
6341 	if (!vmx->loaded_vmcs->hv_timer_armed)
6342 		vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
6343 			      PIN_BASED_VMX_PREEMPTION_TIMER);
6344 	vmx->loaded_vmcs->hv_timer_armed = true;
6345 }
6346 
6347 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6348 {
6349 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6350 	u64 tscl;
6351 	u32 delta_tsc;
6352 
6353 	if (vmx->req_immediate_exit) {
6354 		vmx_arm_hv_timer(vmx, 0);
6355 		return;
6356 	}
6357 
6358 	if (vmx->hv_deadline_tsc != -1) {
6359 		tscl = rdtsc();
6360 		if (vmx->hv_deadline_tsc > tscl)
6361 			/* set_hv_timer ensures the delta fits in 32-bits */
6362 			delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6363 				cpu_preemption_timer_multi);
6364 		else
6365 			delta_tsc = 0;
6366 
6367 		vmx_arm_hv_timer(vmx, delta_tsc);
6368 		return;
6369 	}
6370 
6371 	if (vmx->loaded_vmcs->hv_timer_armed)
6372 		vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
6373 				PIN_BASED_VMX_PREEMPTION_TIMER);
6374 	vmx->loaded_vmcs->hv_timer_armed = false;
6375 }
6376 
6377 void vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6378 {
6379 	if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6380 		vmx->loaded_vmcs->host_state.rsp = host_rsp;
6381 		vmcs_writel(HOST_RSP, host_rsp);
6382 	}
6383 }
6384 
6385 bool __vmx_vcpu_run(struct vcpu_vmx *vmx, unsigned long *regs, bool launched);
6386 
6387 static void vmx_vcpu_run(struct kvm_vcpu *vcpu)
6388 {
6389 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6390 	unsigned long cr3, cr4;
6391 
6392 	/* Record the guest's net vcpu time for enforced NMI injections. */
6393 	if (unlikely(!enable_vnmi &&
6394 		     vmx->loaded_vmcs->soft_vnmi_blocked))
6395 		vmx->loaded_vmcs->entry_time = ktime_get();
6396 
6397 	/* Don't enter VMX if guest state is invalid, let the exit handler
6398 	   start emulation until we arrive back to a valid state */
6399 	if (vmx->emulation_required)
6400 		return;
6401 
6402 	if (vmx->ple_window_dirty) {
6403 		vmx->ple_window_dirty = false;
6404 		vmcs_write32(PLE_WINDOW, vmx->ple_window);
6405 	}
6406 
6407 	if (vmx->nested.need_vmcs12_sync)
6408 		nested_sync_from_vmcs12(vcpu);
6409 
6410 	if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
6411 		vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6412 	if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
6413 		vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6414 
6415 	cr3 = __get_current_cr3_fast();
6416 	if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6417 		vmcs_writel(HOST_CR3, cr3);
6418 		vmx->loaded_vmcs->host_state.cr3 = cr3;
6419 	}
6420 
6421 	cr4 = cr4_read_shadow();
6422 	if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6423 		vmcs_writel(HOST_CR4, cr4);
6424 		vmx->loaded_vmcs->host_state.cr4 = cr4;
6425 	}
6426 
6427 	/* When single-stepping over STI and MOV SS, we must clear the
6428 	 * corresponding interruptibility bits in the guest state. Otherwise
6429 	 * vmentry fails as it then expects bit 14 (BS) in pending debug
6430 	 * exceptions being set, but that's not correct for the guest debugging
6431 	 * case. */
6432 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6433 		vmx_set_interrupt_shadow(vcpu, 0);
6434 
6435 	kvm_load_guest_xcr0(vcpu);
6436 
6437 	if (static_cpu_has(X86_FEATURE_PKU) &&
6438 	    kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
6439 	    vcpu->arch.pkru != vmx->host_pkru)
6440 		__write_pkru(vcpu->arch.pkru);
6441 
6442 	pt_guest_enter(vmx);
6443 
6444 	atomic_switch_perf_msrs(vmx);
6445 
6446 	vmx_update_hv_timer(vcpu);
6447 
6448 	/*
6449 	 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6450 	 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6451 	 * is no need to worry about the conditional branch over the wrmsr
6452 	 * being speculatively taken.
6453 	 */
6454 	x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6455 
6456 	/* L1D Flush includes CPU buffer clear to mitigate MDS */
6457 	if (static_branch_unlikely(&vmx_l1d_should_flush))
6458 		vmx_l1d_flush(vcpu);
6459 	else if (static_branch_unlikely(&mds_user_clear))
6460 		mds_clear_cpu_buffers();
6461 
6462 	if (vcpu->arch.cr2 != read_cr2())
6463 		write_cr2(vcpu->arch.cr2);
6464 
6465 	vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6466 				   vmx->loaded_vmcs->launched);
6467 
6468 	vcpu->arch.cr2 = read_cr2();
6469 
6470 	/*
6471 	 * We do not use IBRS in the kernel. If this vCPU has used the
6472 	 * SPEC_CTRL MSR it may have left it on; save the value and
6473 	 * turn it off. This is much more efficient than blindly adding
6474 	 * it to the atomic save/restore list. Especially as the former
6475 	 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6476 	 *
6477 	 * For non-nested case:
6478 	 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6479 	 * save it.
6480 	 *
6481 	 * For nested case:
6482 	 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6483 	 * save it.
6484 	 */
6485 	if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6486 		vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6487 
6488 	x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6489 
6490 	/* All fields are clean at this point */
6491 	if (static_branch_unlikely(&enable_evmcs))
6492 		current_evmcs->hv_clean_fields |=
6493 			HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6494 
6495 	/* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6496 	if (vmx->host_debugctlmsr)
6497 		update_debugctlmsr(vmx->host_debugctlmsr);
6498 
6499 #ifndef CONFIG_X86_64
6500 	/*
6501 	 * The sysexit path does not restore ds/es, so we must set them to
6502 	 * a reasonable value ourselves.
6503 	 *
6504 	 * We can't defer this to vmx_prepare_switch_to_host() since that
6505 	 * function may be executed in interrupt context, which saves and
6506 	 * restore segments around it, nullifying its effect.
6507 	 */
6508 	loadsegment(ds, __USER_DS);
6509 	loadsegment(es, __USER_DS);
6510 #endif
6511 
6512 	vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
6513 				  | (1 << VCPU_EXREG_RFLAGS)
6514 				  | (1 << VCPU_EXREG_PDPTR)
6515 				  | (1 << VCPU_EXREG_SEGMENTS)
6516 				  | (1 << VCPU_EXREG_CR3));
6517 	vcpu->arch.regs_dirty = 0;
6518 
6519 	pt_guest_exit(vmx);
6520 
6521 	/*
6522 	 * eager fpu is enabled if PKEY is supported and CR4 is switched
6523 	 * back on host, so it is safe to read guest PKRU from current
6524 	 * XSAVE.
6525 	 */
6526 	if (static_cpu_has(X86_FEATURE_PKU) &&
6527 	    kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
6528 		vcpu->arch.pkru = rdpkru();
6529 		if (vcpu->arch.pkru != vmx->host_pkru)
6530 			__write_pkru(vmx->host_pkru);
6531 	}
6532 
6533 	kvm_put_guest_xcr0(vcpu);
6534 
6535 	vmx->nested.nested_run_pending = 0;
6536 	vmx->idt_vectoring_info = 0;
6537 
6538 	vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
6539 	if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6540 		return;
6541 
6542 	vmx->loaded_vmcs->launched = 1;
6543 	vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6544 
6545 	vmx_complete_atomic_exit(vmx);
6546 	vmx_recover_nmi_blocking(vmx);
6547 	vmx_complete_interrupts(vmx);
6548 }
6549 
6550 static struct kvm *vmx_vm_alloc(void)
6551 {
6552 	struct kvm_vmx *kvm_vmx = __vmalloc(sizeof(struct kvm_vmx),
6553 					    GFP_KERNEL_ACCOUNT | __GFP_ZERO,
6554 					    PAGE_KERNEL);
6555 	return &kvm_vmx->kvm;
6556 }
6557 
6558 static void vmx_vm_free(struct kvm *kvm)
6559 {
6560 	vfree(to_kvm_vmx(kvm));
6561 }
6562 
6563 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6564 {
6565 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6566 
6567 	if (enable_pml)
6568 		vmx_destroy_pml_buffer(vmx);
6569 	free_vpid(vmx->vpid);
6570 	nested_vmx_free_vcpu(vcpu);
6571 	free_loaded_vmcs(vmx->loaded_vmcs);
6572 	kfree(vmx->guest_msrs);
6573 	kvm_vcpu_uninit(vcpu);
6574 	kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6575 	kmem_cache_free(kvm_vcpu_cache, vmx);
6576 }
6577 
6578 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
6579 {
6580 	int err;
6581 	struct vcpu_vmx *vmx;
6582 	unsigned long *msr_bitmap;
6583 	int cpu;
6584 
6585 	vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
6586 	if (!vmx)
6587 		return ERR_PTR(-ENOMEM);
6588 
6589 	vmx->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
6590 			GFP_KERNEL_ACCOUNT);
6591 	if (!vmx->vcpu.arch.guest_fpu) {
6592 		printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
6593 		err = -ENOMEM;
6594 		goto free_partial_vcpu;
6595 	}
6596 
6597 	vmx->vpid = allocate_vpid();
6598 
6599 	err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
6600 	if (err)
6601 		goto free_vcpu;
6602 
6603 	err = -ENOMEM;
6604 
6605 	/*
6606 	 * If PML is turned on, failure on enabling PML just results in failure
6607 	 * of creating the vcpu, therefore we can simplify PML logic (by
6608 	 * avoiding dealing with cases, such as enabling PML partially on vcpus
6609 	 * for the guest, etc.
6610 	 */
6611 	if (enable_pml) {
6612 		vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6613 		if (!vmx->pml_pg)
6614 			goto uninit_vcpu;
6615 	}
6616 
6617 	vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
6618 	BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
6619 		     > PAGE_SIZE);
6620 
6621 	if (!vmx->guest_msrs)
6622 		goto free_pml;
6623 
6624 	err = alloc_loaded_vmcs(&vmx->vmcs01);
6625 	if (err < 0)
6626 		goto free_msrs;
6627 
6628 	msr_bitmap = vmx->vmcs01.msr_bitmap;
6629 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6630 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6631 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6632 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6633 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6634 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6635 	vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6636 	vmx->msr_bitmap_mode = 0;
6637 
6638 	vmx->loaded_vmcs = &vmx->vmcs01;
6639 	cpu = get_cpu();
6640 	vmx_vcpu_load(&vmx->vcpu, cpu);
6641 	vmx->vcpu.cpu = cpu;
6642 	vmx_vcpu_setup(vmx);
6643 	vmx_vcpu_put(&vmx->vcpu);
6644 	put_cpu();
6645 	if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
6646 		err = alloc_apic_access_page(kvm);
6647 		if (err)
6648 			goto free_vmcs;
6649 	}
6650 
6651 	if (enable_ept && !enable_unrestricted_guest) {
6652 		err = init_rmode_identity_map(kvm);
6653 		if (err)
6654 			goto free_vmcs;
6655 	}
6656 
6657 	if (nested)
6658 		nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
6659 					   vmx_capability.ept,
6660 					   kvm_vcpu_apicv_active(&vmx->vcpu));
6661 	else
6662 		memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6663 
6664 	vmx->nested.posted_intr_nv = -1;
6665 	vmx->nested.current_vmptr = -1ull;
6666 
6667 	vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
6668 
6669 	/*
6670 	 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6671 	 * or POSTED_INTR_WAKEUP_VECTOR.
6672 	 */
6673 	vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6674 	vmx->pi_desc.sn = 1;
6675 
6676 	vmx->ept_pointer = INVALID_PAGE;
6677 
6678 	return &vmx->vcpu;
6679 
6680 free_vmcs:
6681 	free_loaded_vmcs(vmx->loaded_vmcs);
6682 free_msrs:
6683 	kfree(vmx->guest_msrs);
6684 free_pml:
6685 	vmx_destroy_pml_buffer(vmx);
6686 uninit_vcpu:
6687 	kvm_vcpu_uninit(&vmx->vcpu);
6688 free_vcpu:
6689 	free_vpid(vmx->vpid);
6690 	kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6691 free_partial_vcpu:
6692 	kmem_cache_free(kvm_vcpu_cache, vmx);
6693 	return ERR_PTR(err);
6694 }
6695 
6696 #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"
6697 #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"
6698 
6699 static int vmx_vm_init(struct kvm *kvm)
6700 {
6701 	spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
6702 
6703 	if (!ple_gap)
6704 		kvm->arch.pause_in_guest = true;
6705 
6706 	if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6707 		switch (l1tf_mitigation) {
6708 		case L1TF_MITIGATION_OFF:
6709 		case L1TF_MITIGATION_FLUSH_NOWARN:
6710 			/* 'I explicitly don't care' is set */
6711 			break;
6712 		case L1TF_MITIGATION_FLUSH:
6713 		case L1TF_MITIGATION_FLUSH_NOSMT:
6714 		case L1TF_MITIGATION_FULL:
6715 			/*
6716 			 * Warn upon starting the first VM in a potentially
6717 			 * insecure environment.
6718 			 */
6719 			if (sched_smt_active())
6720 				pr_warn_once(L1TF_MSG_SMT);
6721 			if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6722 				pr_warn_once(L1TF_MSG_L1D);
6723 			break;
6724 		case L1TF_MITIGATION_FULL_FORCE:
6725 			/* Flush is enforced */
6726 			break;
6727 		}
6728 	}
6729 	return 0;
6730 }
6731 
6732 static void __init vmx_check_processor_compat(void *rtn)
6733 {
6734 	struct vmcs_config vmcs_conf;
6735 	struct vmx_capability vmx_cap;
6736 
6737 	*(int *)rtn = 0;
6738 	if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
6739 		*(int *)rtn = -EIO;
6740 	if (nested)
6741 		nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept,
6742 					   enable_apicv);
6743 	if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6744 		printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6745 				smp_processor_id());
6746 		*(int *)rtn = -EIO;
6747 	}
6748 }
6749 
6750 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6751 {
6752 	u8 cache;
6753 	u64 ipat = 0;
6754 
6755 	/* For VT-d and EPT combination
6756 	 * 1. MMIO: always map as UC
6757 	 * 2. EPT with VT-d:
6758 	 *   a. VT-d without snooping control feature: can't guarantee the
6759 	 *	result, try to trust guest.
6760 	 *   b. VT-d with snooping control feature: snooping control feature of
6761 	 *	VT-d engine can guarantee the cache correctness. Just set it
6762 	 *	to WB to keep consistent with host. So the same as item 3.
6763 	 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
6764 	 *    consistent with host MTRR
6765 	 */
6766 	if (is_mmio) {
6767 		cache = MTRR_TYPE_UNCACHABLE;
6768 		goto exit;
6769 	}
6770 
6771 	if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
6772 		ipat = VMX_EPT_IPAT_BIT;
6773 		cache = MTRR_TYPE_WRBACK;
6774 		goto exit;
6775 	}
6776 
6777 	if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
6778 		ipat = VMX_EPT_IPAT_BIT;
6779 		if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
6780 			cache = MTRR_TYPE_WRBACK;
6781 		else
6782 			cache = MTRR_TYPE_UNCACHABLE;
6783 		goto exit;
6784 	}
6785 
6786 	cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
6787 
6788 exit:
6789 	return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
6790 }
6791 
6792 static int vmx_get_lpage_level(void)
6793 {
6794 	if (enable_ept && !cpu_has_vmx_ept_1g_page())
6795 		return PT_DIRECTORY_LEVEL;
6796 	else
6797 		/* For shadow and EPT supported 1GB page */
6798 		return PT_PDPE_LEVEL;
6799 }
6800 
6801 static void vmcs_set_secondary_exec_control(u32 new_ctl)
6802 {
6803 	/*
6804 	 * These bits in the secondary execution controls field
6805 	 * are dynamic, the others are mostly based on the hypervisor
6806 	 * architecture and the guest's CPUID.  Do not touch the
6807 	 * dynamic bits.
6808 	 */
6809 	u32 mask =
6810 		SECONDARY_EXEC_SHADOW_VMCS |
6811 		SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
6812 		SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6813 		SECONDARY_EXEC_DESC;
6814 
6815 	u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6816 
6817 	vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6818 		     (new_ctl & ~mask) | (cur_ctl & mask));
6819 }
6820 
6821 /*
6822  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
6823  * (indicating "allowed-1") if they are supported in the guest's CPUID.
6824  */
6825 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
6826 {
6827 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6828 	struct kvm_cpuid_entry2 *entry;
6829 
6830 	vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
6831 	vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
6832 
6833 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {		\
6834 	if (entry && (entry->_reg & (_cpuid_mask)))			\
6835 		vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask);	\
6836 } while (0)
6837 
6838 	entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
6839 	cr4_fixed1_update(X86_CR4_VME,        edx, bit(X86_FEATURE_VME));
6840 	cr4_fixed1_update(X86_CR4_PVI,        edx, bit(X86_FEATURE_VME));
6841 	cr4_fixed1_update(X86_CR4_TSD,        edx, bit(X86_FEATURE_TSC));
6842 	cr4_fixed1_update(X86_CR4_DE,         edx, bit(X86_FEATURE_DE));
6843 	cr4_fixed1_update(X86_CR4_PSE,        edx, bit(X86_FEATURE_PSE));
6844 	cr4_fixed1_update(X86_CR4_PAE,        edx, bit(X86_FEATURE_PAE));
6845 	cr4_fixed1_update(X86_CR4_MCE,        edx, bit(X86_FEATURE_MCE));
6846 	cr4_fixed1_update(X86_CR4_PGE,        edx, bit(X86_FEATURE_PGE));
6847 	cr4_fixed1_update(X86_CR4_OSFXSR,     edx, bit(X86_FEATURE_FXSR));
6848 	cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
6849 	cr4_fixed1_update(X86_CR4_VMXE,       ecx, bit(X86_FEATURE_VMX));
6850 	cr4_fixed1_update(X86_CR4_SMXE,       ecx, bit(X86_FEATURE_SMX));
6851 	cr4_fixed1_update(X86_CR4_PCIDE,      ecx, bit(X86_FEATURE_PCID));
6852 	cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, bit(X86_FEATURE_XSAVE));
6853 
6854 	entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
6855 	cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, bit(X86_FEATURE_FSGSBASE));
6856 	cr4_fixed1_update(X86_CR4_SMEP,       ebx, bit(X86_FEATURE_SMEP));
6857 	cr4_fixed1_update(X86_CR4_SMAP,       ebx, bit(X86_FEATURE_SMAP));
6858 	cr4_fixed1_update(X86_CR4_PKE,        ecx, bit(X86_FEATURE_PKU));
6859 	cr4_fixed1_update(X86_CR4_UMIP,       ecx, bit(X86_FEATURE_UMIP));
6860 
6861 #undef cr4_fixed1_update
6862 }
6863 
6864 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
6865 {
6866 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6867 
6868 	if (kvm_mpx_supported()) {
6869 		bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
6870 
6871 		if (mpx_enabled) {
6872 			vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
6873 			vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
6874 		} else {
6875 			vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
6876 			vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
6877 		}
6878 	}
6879 }
6880 
6881 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
6882 {
6883 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6884 	struct kvm_cpuid_entry2 *best = NULL;
6885 	int i;
6886 
6887 	for (i = 0; i < PT_CPUID_LEAVES; i++) {
6888 		best = kvm_find_cpuid_entry(vcpu, 0x14, i);
6889 		if (!best)
6890 			return;
6891 		vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
6892 		vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
6893 		vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
6894 		vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
6895 	}
6896 
6897 	/* Get the number of configurable Address Ranges for filtering */
6898 	vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
6899 						PT_CAP_num_address_ranges);
6900 
6901 	/* Initialize and clear the no dependency bits */
6902 	vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
6903 			RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
6904 
6905 	/*
6906 	 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
6907 	 * will inject an #GP
6908 	 */
6909 	if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
6910 		vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
6911 
6912 	/*
6913 	 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
6914 	 * PSBFreq can be set
6915 	 */
6916 	if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
6917 		vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
6918 				RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
6919 
6920 	/*
6921 	 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
6922 	 * MTCFreq can be set
6923 	 */
6924 	if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
6925 		vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
6926 				RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
6927 
6928 	/* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
6929 	if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
6930 		vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
6931 							RTIT_CTL_PTW_EN);
6932 
6933 	/* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
6934 	if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
6935 		vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
6936 
6937 	/* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
6938 	if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
6939 		vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
6940 
6941 	/* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
6942 	if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
6943 		vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
6944 
6945 	/* unmask address range configure area */
6946 	for (i = 0; i < vmx->pt_desc.addr_range; i++)
6947 		vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
6948 }
6949 
6950 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
6951 {
6952 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6953 
6954 	if (cpu_has_secondary_exec_ctrls()) {
6955 		vmx_compute_secondary_exec_control(vmx);
6956 		vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
6957 	}
6958 
6959 	if (nested_vmx_allowed(vcpu))
6960 		to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
6961 			FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
6962 	else
6963 		to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
6964 			~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
6965 
6966 	if (nested_vmx_allowed(vcpu)) {
6967 		nested_vmx_cr_fixed1_bits_update(vcpu);
6968 		nested_vmx_entry_exit_ctls_update(vcpu);
6969 	}
6970 
6971 	if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
6972 			guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
6973 		update_intel_pt_cfg(vcpu);
6974 }
6975 
6976 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
6977 {
6978 	if (func == 1 && nested)
6979 		entry->ecx |= bit(X86_FEATURE_VMX);
6980 }
6981 
6982 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
6983 {
6984 	to_vmx(vcpu)->req_immediate_exit = true;
6985 }
6986 
6987 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
6988 			       struct x86_instruction_info *info,
6989 			       enum x86_intercept_stage stage)
6990 {
6991 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6992 	struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6993 
6994 	/*
6995 	 * RDPID causes #UD if disabled through secondary execution controls.
6996 	 * Because it is marked as EmulateOnUD, we need to intercept it here.
6997 	 */
6998 	if (info->intercept == x86_intercept_rdtscp &&
6999 	    !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
7000 		ctxt->exception.vector = UD_VECTOR;
7001 		ctxt->exception.error_code_valid = false;
7002 		return X86EMUL_PROPAGATE_FAULT;
7003 	}
7004 
7005 	/* TODO: check more intercepts... */
7006 	return X86EMUL_CONTINUE;
7007 }
7008 
7009 #ifdef CONFIG_X86_64
7010 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7011 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7012 				  u64 divisor, u64 *result)
7013 {
7014 	u64 low = a << shift, high = a >> (64 - shift);
7015 
7016 	/* To avoid the overflow on divq */
7017 	if (high >= divisor)
7018 		return 1;
7019 
7020 	/* Low hold the result, high hold rem which is discarded */
7021 	asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7022 	    "rm" (divisor), "0" (low), "1" (high));
7023 	*result = low;
7024 
7025 	return 0;
7026 }
7027 
7028 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7029 			    bool *expired)
7030 {
7031 	struct vcpu_vmx *vmx;
7032 	u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7033 	struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7034 
7035 	if (kvm_mwait_in_guest(vcpu->kvm))
7036 		return -EOPNOTSUPP;
7037 
7038 	vmx = to_vmx(vcpu);
7039 	tscl = rdtsc();
7040 	guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7041 	delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7042 	lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7043 						    ktimer->timer_advance_ns);
7044 
7045 	if (delta_tsc > lapic_timer_advance_cycles)
7046 		delta_tsc -= lapic_timer_advance_cycles;
7047 	else
7048 		delta_tsc = 0;
7049 
7050 	/* Convert to host delta tsc if tsc scaling is enabled */
7051 	if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7052 	    delta_tsc && u64_shl_div_u64(delta_tsc,
7053 				kvm_tsc_scaling_ratio_frac_bits,
7054 				vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7055 		return -ERANGE;
7056 
7057 	/*
7058 	 * If the delta tsc can't fit in the 32 bit after the multi shift,
7059 	 * we can't use the preemption timer.
7060 	 * It's possible that it fits on later vmentries, but checking
7061 	 * on every vmentry is costly so we just use an hrtimer.
7062 	 */
7063 	if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7064 		return -ERANGE;
7065 
7066 	vmx->hv_deadline_tsc = tscl + delta_tsc;
7067 	*expired = !delta_tsc;
7068 	return 0;
7069 }
7070 
7071 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7072 {
7073 	to_vmx(vcpu)->hv_deadline_tsc = -1;
7074 }
7075 #endif
7076 
7077 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7078 {
7079 	if (!kvm_pause_in_guest(vcpu->kvm))
7080 		shrink_ple_window(vcpu);
7081 }
7082 
7083 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7084 				     struct kvm_memory_slot *slot)
7085 {
7086 	kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7087 	kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7088 }
7089 
7090 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7091 				       struct kvm_memory_slot *slot)
7092 {
7093 	kvm_mmu_slot_set_dirty(kvm, slot);
7094 }
7095 
7096 static void vmx_flush_log_dirty(struct kvm *kvm)
7097 {
7098 	kvm_flush_pml_buffers(kvm);
7099 }
7100 
7101 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
7102 {
7103 	struct vmcs12 *vmcs12;
7104 	struct vcpu_vmx *vmx = to_vmx(vcpu);
7105 	gpa_t gpa, dst;
7106 
7107 	if (is_guest_mode(vcpu)) {
7108 		WARN_ON_ONCE(vmx->nested.pml_full);
7109 
7110 		/*
7111 		 * Check if PML is enabled for the nested guest.
7112 		 * Whether eptp bit 6 is set is already checked
7113 		 * as part of A/D emulation.
7114 		 */
7115 		vmcs12 = get_vmcs12(vcpu);
7116 		if (!nested_cpu_has_pml(vmcs12))
7117 			return 0;
7118 
7119 		if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
7120 			vmx->nested.pml_full = true;
7121 			return 1;
7122 		}
7123 
7124 		gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
7125 		dst = vmcs12->pml_address + sizeof(u64) * vmcs12->guest_pml_index;
7126 
7127 		if (kvm_write_guest_page(vcpu->kvm, gpa_to_gfn(dst), &gpa,
7128 					 offset_in_page(dst), sizeof(gpa)))
7129 			return 0;
7130 
7131 		vmcs12->guest_pml_index--;
7132 	}
7133 
7134 	return 0;
7135 }
7136 
7137 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7138 					   struct kvm_memory_slot *memslot,
7139 					   gfn_t offset, unsigned long mask)
7140 {
7141 	kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7142 }
7143 
7144 static void __pi_post_block(struct kvm_vcpu *vcpu)
7145 {
7146 	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7147 	struct pi_desc old, new;
7148 	unsigned int dest;
7149 
7150 	do {
7151 		old.control = new.control = pi_desc->control;
7152 		WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
7153 		     "Wakeup handler not enabled while the VCPU is blocked\n");
7154 
7155 		dest = cpu_physical_id(vcpu->cpu);
7156 
7157 		if (x2apic_enabled())
7158 			new.ndst = dest;
7159 		else
7160 			new.ndst = (dest << 8) & 0xFF00;
7161 
7162 		/* set 'NV' to 'notification vector' */
7163 		new.nv = POSTED_INTR_VECTOR;
7164 	} while (cmpxchg64(&pi_desc->control, old.control,
7165 			   new.control) != old.control);
7166 
7167 	if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
7168 		spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7169 		list_del(&vcpu->blocked_vcpu_list);
7170 		spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7171 		vcpu->pre_pcpu = -1;
7172 	}
7173 }
7174 
7175 /*
7176  * This routine does the following things for vCPU which is going
7177  * to be blocked if VT-d PI is enabled.
7178  * - Store the vCPU to the wakeup list, so when interrupts happen
7179  *   we can find the right vCPU to wake up.
7180  * - Change the Posted-interrupt descriptor as below:
7181  *      'NDST' <-- vcpu->pre_pcpu
7182  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
7183  * - If 'ON' is set during this process, which means at least one
7184  *   interrupt is posted for this vCPU, we cannot block it, in
7185  *   this case, return 1, otherwise, return 0.
7186  *
7187  */
7188 static int pi_pre_block(struct kvm_vcpu *vcpu)
7189 {
7190 	unsigned int dest;
7191 	struct pi_desc old, new;
7192 	struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7193 
7194 	if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
7195 		!irq_remapping_cap(IRQ_POSTING_CAP)  ||
7196 		!kvm_vcpu_apicv_active(vcpu))
7197 		return 0;
7198 
7199 	WARN_ON(irqs_disabled());
7200 	local_irq_disable();
7201 	if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
7202 		vcpu->pre_pcpu = vcpu->cpu;
7203 		spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7204 		list_add_tail(&vcpu->blocked_vcpu_list,
7205 			      &per_cpu(blocked_vcpu_on_cpu,
7206 				       vcpu->pre_pcpu));
7207 		spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7208 	}
7209 
7210 	do {
7211 		old.control = new.control = pi_desc->control;
7212 
7213 		WARN((pi_desc->sn == 1),
7214 		     "Warning: SN field of posted-interrupts "
7215 		     "is set before blocking\n");
7216 
7217 		/*
7218 		 * Since vCPU can be preempted during this process,
7219 		 * vcpu->cpu could be different with pre_pcpu, we
7220 		 * need to set pre_pcpu as the destination of wakeup
7221 		 * notification event, then we can find the right vCPU
7222 		 * to wakeup in wakeup handler if interrupts happen
7223 		 * when the vCPU is in blocked state.
7224 		 */
7225 		dest = cpu_physical_id(vcpu->pre_pcpu);
7226 
7227 		if (x2apic_enabled())
7228 			new.ndst = dest;
7229 		else
7230 			new.ndst = (dest << 8) & 0xFF00;
7231 
7232 		/* set 'NV' to 'wakeup vector' */
7233 		new.nv = POSTED_INTR_WAKEUP_VECTOR;
7234 	} while (cmpxchg64(&pi_desc->control, old.control,
7235 			   new.control) != old.control);
7236 
7237 	/* We should not block the vCPU if an interrupt is posted for it.  */
7238 	if (pi_test_on(pi_desc) == 1)
7239 		__pi_post_block(vcpu);
7240 
7241 	local_irq_enable();
7242 	return (vcpu->pre_pcpu == -1);
7243 }
7244 
7245 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7246 {
7247 	if (pi_pre_block(vcpu))
7248 		return 1;
7249 
7250 	if (kvm_lapic_hv_timer_in_use(vcpu))
7251 		kvm_lapic_switch_to_sw_timer(vcpu);
7252 
7253 	return 0;
7254 }
7255 
7256 static void pi_post_block(struct kvm_vcpu *vcpu)
7257 {
7258 	if (vcpu->pre_pcpu == -1)
7259 		return;
7260 
7261 	WARN_ON(irqs_disabled());
7262 	local_irq_disable();
7263 	__pi_post_block(vcpu);
7264 	local_irq_enable();
7265 }
7266 
7267 static void vmx_post_block(struct kvm_vcpu *vcpu)
7268 {
7269 	if (kvm_x86_ops->set_hv_timer)
7270 		kvm_lapic_switch_to_hv_timer(vcpu);
7271 
7272 	pi_post_block(vcpu);
7273 }
7274 
7275 /*
7276  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
7277  *
7278  * @kvm: kvm
7279  * @host_irq: host irq of the interrupt
7280  * @guest_irq: gsi of the interrupt
7281  * @set: set or unset PI
7282  * returns 0 on success, < 0 on failure
7283  */
7284 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7285 			      uint32_t guest_irq, bool set)
7286 {
7287 	struct kvm_kernel_irq_routing_entry *e;
7288 	struct kvm_irq_routing_table *irq_rt;
7289 	struct kvm_lapic_irq irq;
7290 	struct kvm_vcpu *vcpu;
7291 	struct vcpu_data vcpu_info;
7292 	int idx, ret = 0;
7293 
7294 	if (!kvm_arch_has_assigned_device(kvm) ||
7295 		!irq_remapping_cap(IRQ_POSTING_CAP) ||
7296 		!kvm_vcpu_apicv_active(kvm->vcpus[0]))
7297 		return 0;
7298 
7299 	idx = srcu_read_lock(&kvm->irq_srcu);
7300 	irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7301 	if (guest_irq >= irq_rt->nr_rt_entries ||
7302 	    hlist_empty(&irq_rt->map[guest_irq])) {
7303 		pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7304 			     guest_irq, irq_rt->nr_rt_entries);
7305 		goto out;
7306 	}
7307 
7308 	hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7309 		if (e->type != KVM_IRQ_ROUTING_MSI)
7310 			continue;
7311 		/*
7312 		 * VT-d PI cannot support posting multicast/broadcast
7313 		 * interrupts to a vCPU, we still use interrupt remapping
7314 		 * for these kind of interrupts.
7315 		 *
7316 		 * For lowest-priority interrupts, we only support
7317 		 * those with single CPU as the destination, e.g. user
7318 		 * configures the interrupts via /proc/irq or uses
7319 		 * irqbalance to make the interrupts single-CPU.
7320 		 *
7321 		 * We will support full lowest-priority interrupt later.
7322 		 */
7323 
7324 		kvm_set_msi_irq(kvm, e, &irq);
7325 		if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
7326 			/*
7327 			 * Make sure the IRTE is in remapped mode if
7328 			 * we don't handle it in posted mode.
7329 			 */
7330 			ret = irq_set_vcpu_affinity(host_irq, NULL);
7331 			if (ret < 0) {
7332 				printk(KERN_INFO
7333 				   "failed to back to remapped mode, irq: %u\n",
7334 				   host_irq);
7335 				goto out;
7336 			}
7337 
7338 			continue;
7339 		}
7340 
7341 		vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7342 		vcpu_info.vector = irq.vector;
7343 
7344 		trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7345 				vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7346 
7347 		if (set)
7348 			ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7349 		else
7350 			ret = irq_set_vcpu_affinity(host_irq, NULL);
7351 
7352 		if (ret < 0) {
7353 			printk(KERN_INFO "%s: failed to update PI IRTE\n",
7354 					__func__);
7355 			goto out;
7356 		}
7357 	}
7358 
7359 	ret = 0;
7360 out:
7361 	srcu_read_unlock(&kvm->irq_srcu, idx);
7362 	return ret;
7363 }
7364 
7365 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7366 {
7367 	if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7368 		to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7369 			FEATURE_CONTROL_LMCE;
7370 	else
7371 		to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7372 			~FEATURE_CONTROL_LMCE;
7373 }
7374 
7375 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
7376 {
7377 	/* we need a nested vmexit to enter SMM, postpone if run is pending */
7378 	if (to_vmx(vcpu)->nested.nested_run_pending)
7379 		return 0;
7380 	return 1;
7381 }
7382 
7383 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7384 {
7385 	struct vcpu_vmx *vmx = to_vmx(vcpu);
7386 
7387 	vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7388 	if (vmx->nested.smm.guest_mode)
7389 		nested_vmx_vmexit(vcpu, -1, 0, 0);
7390 
7391 	vmx->nested.smm.vmxon = vmx->nested.vmxon;
7392 	vmx->nested.vmxon = false;
7393 	vmx_clear_hlt(vcpu);
7394 	return 0;
7395 }
7396 
7397 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7398 {
7399 	struct vcpu_vmx *vmx = to_vmx(vcpu);
7400 	int ret;
7401 
7402 	if (vmx->nested.smm.vmxon) {
7403 		vmx->nested.vmxon = true;
7404 		vmx->nested.smm.vmxon = false;
7405 	}
7406 
7407 	if (vmx->nested.smm.guest_mode) {
7408 		ret = nested_vmx_enter_non_root_mode(vcpu, false);
7409 		if (ret)
7410 			return ret;
7411 
7412 		vmx->nested.smm.guest_mode = false;
7413 	}
7414 	return 0;
7415 }
7416 
7417 static int enable_smi_window(struct kvm_vcpu *vcpu)
7418 {
7419 	return 0;
7420 }
7421 
7422 static bool vmx_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7423 {
7424 	return 0;
7425 }
7426 
7427 static __init int hardware_setup(void)
7428 {
7429 	unsigned long host_bndcfgs;
7430 	int r, i;
7431 
7432 	rdmsrl_safe(MSR_EFER, &host_efer);
7433 
7434 	for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7435 		kvm_define_shared_msr(i, vmx_msr_index[i]);
7436 
7437 	if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7438 		return -EIO;
7439 
7440 	if (boot_cpu_has(X86_FEATURE_NX))
7441 		kvm_enable_efer_bits(EFER_NX);
7442 
7443 	if (boot_cpu_has(X86_FEATURE_MPX)) {
7444 		rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7445 		WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7446 	}
7447 
7448 	if (boot_cpu_has(X86_FEATURE_XSAVES))
7449 		rdmsrl(MSR_IA32_XSS, host_xss);
7450 
7451 	if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7452 	    !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7453 		enable_vpid = 0;
7454 
7455 	if (!cpu_has_vmx_ept() ||
7456 	    !cpu_has_vmx_ept_4levels() ||
7457 	    !cpu_has_vmx_ept_mt_wb() ||
7458 	    !cpu_has_vmx_invept_global())
7459 		enable_ept = 0;
7460 
7461 	if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7462 		enable_ept_ad_bits = 0;
7463 
7464 	if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7465 		enable_unrestricted_guest = 0;
7466 
7467 	if (!cpu_has_vmx_flexpriority())
7468 		flexpriority_enabled = 0;
7469 
7470 	if (!cpu_has_virtual_nmis())
7471 		enable_vnmi = 0;
7472 
7473 	/*
7474 	 * set_apic_access_page_addr() is used to reload apic access
7475 	 * page upon invalidation.  No need to do anything if not
7476 	 * using the APIC_ACCESS_ADDR VMCS field.
7477 	 */
7478 	if (!flexpriority_enabled)
7479 		kvm_x86_ops->set_apic_access_page_addr = NULL;
7480 
7481 	if (!cpu_has_vmx_tpr_shadow())
7482 		kvm_x86_ops->update_cr8_intercept = NULL;
7483 
7484 	if (enable_ept && !cpu_has_vmx_ept_2m_page())
7485 		kvm_disable_largepages();
7486 
7487 #if IS_ENABLED(CONFIG_HYPERV)
7488 	if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7489 	    && enable_ept) {
7490 		kvm_x86_ops->tlb_remote_flush = hv_remote_flush_tlb;
7491 		kvm_x86_ops->tlb_remote_flush_with_range =
7492 				hv_remote_flush_tlb_with_range;
7493 	}
7494 #endif
7495 
7496 	if (!cpu_has_vmx_ple()) {
7497 		ple_gap = 0;
7498 		ple_window = 0;
7499 		ple_window_grow = 0;
7500 		ple_window_max = 0;
7501 		ple_window_shrink = 0;
7502 	}
7503 
7504 	if (!cpu_has_vmx_apicv()) {
7505 		enable_apicv = 0;
7506 		kvm_x86_ops->sync_pir_to_irr = NULL;
7507 	}
7508 
7509 	if (cpu_has_vmx_tsc_scaling()) {
7510 		kvm_has_tsc_control = true;
7511 		kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7512 		kvm_tsc_scaling_ratio_frac_bits = 48;
7513 	}
7514 
7515 	set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7516 
7517 	if (enable_ept)
7518 		vmx_enable_tdp();
7519 	else
7520 		kvm_disable_tdp();
7521 
7522 	/*
7523 	 * Only enable PML when hardware supports PML feature, and both EPT
7524 	 * and EPT A/D bit features are enabled -- PML depends on them to work.
7525 	 */
7526 	if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7527 		enable_pml = 0;
7528 
7529 	if (!enable_pml) {
7530 		kvm_x86_ops->slot_enable_log_dirty = NULL;
7531 		kvm_x86_ops->slot_disable_log_dirty = NULL;
7532 		kvm_x86_ops->flush_log_dirty = NULL;
7533 		kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7534 	}
7535 
7536 	if (!cpu_has_vmx_preemption_timer())
7537 		kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7538 
7539 	if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7540 		u64 vmx_msr;
7541 
7542 		rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7543 		cpu_preemption_timer_multi =
7544 			vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7545 	} else {
7546 		kvm_x86_ops->set_hv_timer = NULL;
7547 		kvm_x86_ops->cancel_hv_timer = NULL;
7548 	}
7549 
7550 	kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7551 
7552 	kvm_mce_cap_supported |= MCG_LMCE_P;
7553 
7554 	if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7555 		return -EINVAL;
7556 	if (!enable_ept || !cpu_has_vmx_intel_pt())
7557 		pt_mode = PT_MODE_SYSTEM;
7558 
7559 	if (nested) {
7560 		nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7561 					   vmx_capability.ept, enable_apicv);
7562 
7563 		r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7564 		if (r)
7565 			return r;
7566 	}
7567 
7568 	r = alloc_kvm_area();
7569 	if (r)
7570 		nested_vmx_hardware_unsetup();
7571 	return r;
7572 }
7573 
7574 static __exit void hardware_unsetup(void)
7575 {
7576 	if (nested)
7577 		nested_vmx_hardware_unsetup();
7578 
7579 	free_kvm_area();
7580 }
7581 
7582 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
7583 	.cpu_has_kvm_support = cpu_has_kvm_support,
7584 	.disabled_by_bios = vmx_disabled_by_bios,
7585 	.hardware_setup = hardware_setup,
7586 	.hardware_unsetup = hardware_unsetup,
7587 	.check_processor_compatibility = vmx_check_processor_compat,
7588 	.hardware_enable = hardware_enable,
7589 	.hardware_disable = hardware_disable,
7590 	.cpu_has_accelerated_tpr = report_flexpriority,
7591 	.has_emulated_msr = vmx_has_emulated_msr,
7592 
7593 	.vm_init = vmx_vm_init,
7594 	.vm_alloc = vmx_vm_alloc,
7595 	.vm_free = vmx_vm_free,
7596 
7597 	.vcpu_create = vmx_create_vcpu,
7598 	.vcpu_free = vmx_free_vcpu,
7599 	.vcpu_reset = vmx_vcpu_reset,
7600 
7601 	.prepare_guest_switch = vmx_prepare_switch_to_guest,
7602 	.vcpu_load = vmx_vcpu_load,
7603 	.vcpu_put = vmx_vcpu_put,
7604 
7605 	.update_bp_intercept = update_exception_bitmap,
7606 	.get_msr_feature = vmx_get_msr_feature,
7607 	.get_msr = vmx_get_msr,
7608 	.set_msr = vmx_set_msr,
7609 	.get_segment_base = vmx_get_segment_base,
7610 	.get_segment = vmx_get_segment,
7611 	.set_segment = vmx_set_segment,
7612 	.get_cpl = vmx_get_cpl,
7613 	.get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7614 	.decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
7615 	.decache_cr3 = vmx_decache_cr3,
7616 	.decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
7617 	.set_cr0 = vmx_set_cr0,
7618 	.set_cr3 = vmx_set_cr3,
7619 	.set_cr4 = vmx_set_cr4,
7620 	.set_efer = vmx_set_efer,
7621 	.get_idt = vmx_get_idt,
7622 	.set_idt = vmx_set_idt,
7623 	.get_gdt = vmx_get_gdt,
7624 	.set_gdt = vmx_set_gdt,
7625 	.get_dr6 = vmx_get_dr6,
7626 	.set_dr6 = vmx_set_dr6,
7627 	.set_dr7 = vmx_set_dr7,
7628 	.sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7629 	.cache_reg = vmx_cache_reg,
7630 	.get_rflags = vmx_get_rflags,
7631 	.set_rflags = vmx_set_rflags,
7632 
7633 	.tlb_flush = vmx_flush_tlb,
7634 	.tlb_flush_gva = vmx_flush_tlb_gva,
7635 
7636 	.run = vmx_vcpu_run,
7637 	.handle_exit = vmx_handle_exit,
7638 	.skip_emulated_instruction = skip_emulated_instruction,
7639 	.set_interrupt_shadow = vmx_set_interrupt_shadow,
7640 	.get_interrupt_shadow = vmx_get_interrupt_shadow,
7641 	.patch_hypercall = vmx_patch_hypercall,
7642 	.set_irq = vmx_inject_irq,
7643 	.set_nmi = vmx_inject_nmi,
7644 	.queue_exception = vmx_queue_exception,
7645 	.cancel_injection = vmx_cancel_injection,
7646 	.interrupt_allowed = vmx_interrupt_allowed,
7647 	.nmi_allowed = vmx_nmi_allowed,
7648 	.get_nmi_mask = vmx_get_nmi_mask,
7649 	.set_nmi_mask = vmx_set_nmi_mask,
7650 	.enable_nmi_window = enable_nmi_window,
7651 	.enable_irq_window = enable_irq_window,
7652 	.update_cr8_intercept = update_cr8_intercept,
7653 	.set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7654 	.set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7655 	.get_enable_apicv = vmx_get_enable_apicv,
7656 	.refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7657 	.load_eoi_exitmap = vmx_load_eoi_exitmap,
7658 	.apicv_post_state_restore = vmx_apicv_post_state_restore,
7659 	.hwapic_irr_update = vmx_hwapic_irr_update,
7660 	.hwapic_isr_update = vmx_hwapic_isr_update,
7661 	.guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7662 	.sync_pir_to_irr = vmx_sync_pir_to_irr,
7663 	.deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7664 
7665 	.set_tss_addr = vmx_set_tss_addr,
7666 	.set_identity_map_addr = vmx_set_identity_map_addr,
7667 	.get_tdp_level = get_ept_level,
7668 	.get_mt_mask = vmx_get_mt_mask,
7669 
7670 	.get_exit_info = vmx_get_exit_info,
7671 
7672 	.get_lpage_level = vmx_get_lpage_level,
7673 
7674 	.cpuid_update = vmx_cpuid_update,
7675 
7676 	.rdtscp_supported = vmx_rdtscp_supported,
7677 	.invpcid_supported = vmx_invpcid_supported,
7678 
7679 	.set_supported_cpuid = vmx_set_supported_cpuid,
7680 
7681 	.has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7682 
7683 	.read_l1_tsc_offset = vmx_read_l1_tsc_offset,
7684 	.write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7685 
7686 	.set_tdp_cr3 = vmx_set_cr3,
7687 
7688 	.check_intercept = vmx_check_intercept,
7689 	.handle_external_intr = vmx_handle_external_intr,
7690 	.mpx_supported = vmx_mpx_supported,
7691 	.xsaves_supported = vmx_xsaves_supported,
7692 	.umip_emulated = vmx_umip_emulated,
7693 	.pt_supported = vmx_pt_supported,
7694 
7695 	.request_immediate_exit = vmx_request_immediate_exit,
7696 
7697 	.sched_in = vmx_sched_in,
7698 
7699 	.slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7700 	.slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7701 	.flush_log_dirty = vmx_flush_log_dirty,
7702 	.enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7703 	.write_log_dirty = vmx_write_pml_buffer,
7704 
7705 	.pre_block = vmx_pre_block,
7706 	.post_block = vmx_post_block,
7707 
7708 	.pmu_ops = &intel_pmu_ops,
7709 
7710 	.update_pi_irte = vmx_update_pi_irte,
7711 
7712 #ifdef CONFIG_X86_64
7713 	.set_hv_timer = vmx_set_hv_timer,
7714 	.cancel_hv_timer = vmx_cancel_hv_timer,
7715 #endif
7716 
7717 	.setup_mce = vmx_setup_mce,
7718 
7719 	.smi_allowed = vmx_smi_allowed,
7720 	.pre_enter_smm = vmx_pre_enter_smm,
7721 	.pre_leave_smm = vmx_pre_leave_smm,
7722 	.enable_smi_window = enable_smi_window,
7723 
7724 	.check_nested_events = NULL,
7725 	.get_nested_state = NULL,
7726 	.set_nested_state = NULL,
7727 	.get_vmcs12_pages = NULL,
7728 	.nested_enable_evmcs = NULL,
7729 	.need_emulation_on_page_fault = vmx_need_emulation_on_page_fault,
7730 };
7731 
7732 static void vmx_cleanup_l1d_flush(void)
7733 {
7734 	if (vmx_l1d_flush_pages) {
7735 		free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7736 		vmx_l1d_flush_pages = NULL;
7737 	}
7738 	/* Restore state so sysfs ignores VMX */
7739 	l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
7740 }
7741 
7742 static void vmx_exit(void)
7743 {
7744 #ifdef CONFIG_KEXEC_CORE
7745 	RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
7746 	synchronize_rcu();
7747 #endif
7748 
7749 	kvm_exit();
7750 
7751 #if IS_ENABLED(CONFIG_HYPERV)
7752 	if (static_branch_unlikely(&enable_evmcs)) {
7753 		int cpu;
7754 		struct hv_vp_assist_page *vp_ap;
7755 		/*
7756 		 * Reset everything to support using non-enlightened VMCS
7757 		 * access later (e.g. when we reload the module with
7758 		 * enlightened_vmcs=0)
7759 		 */
7760 		for_each_online_cpu(cpu) {
7761 			vp_ap =	hv_get_vp_assist_page(cpu);
7762 
7763 			if (!vp_ap)
7764 				continue;
7765 
7766 			vp_ap->current_nested_vmcs = 0;
7767 			vp_ap->enlighten_vmentry = 0;
7768 		}
7769 
7770 		static_branch_disable(&enable_evmcs);
7771 	}
7772 #endif
7773 	vmx_cleanup_l1d_flush();
7774 }
7775 module_exit(vmx_exit);
7776 
7777 static int __init vmx_init(void)
7778 {
7779 	int r;
7780 
7781 #if IS_ENABLED(CONFIG_HYPERV)
7782 	/*
7783 	 * Enlightened VMCS usage should be recommended and the host needs
7784 	 * to support eVMCS v1 or above. We can also disable eVMCS support
7785 	 * with module parameter.
7786 	 */
7787 	if (enlightened_vmcs &&
7788 	    ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
7789 	    (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
7790 	    KVM_EVMCS_VERSION) {
7791 		int cpu;
7792 
7793 		/* Check that we have assist pages on all online CPUs */
7794 		for_each_online_cpu(cpu) {
7795 			if (!hv_get_vp_assist_page(cpu)) {
7796 				enlightened_vmcs = false;
7797 				break;
7798 			}
7799 		}
7800 
7801 		if (enlightened_vmcs) {
7802 			pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
7803 			static_branch_enable(&enable_evmcs);
7804 		}
7805 	} else {
7806 		enlightened_vmcs = false;
7807 	}
7808 #endif
7809 
7810 	r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
7811 		     __alignof__(struct vcpu_vmx), THIS_MODULE);
7812 	if (r)
7813 		return r;
7814 
7815 	/*
7816 	 * Must be called after kvm_init() so enable_ept is properly set
7817 	 * up. Hand the parameter mitigation value in which was stored in
7818 	 * the pre module init parser. If no parameter was given, it will
7819 	 * contain 'auto' which will be turned into the default 'cond'
7820 	 * mitigation mode.
7821 	 */
7822 	if (boot_cpu_has(X86_BUG_L1TF)) {
7823 		r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
7824 		if (r) {
7825 			vmx_exit();
7826 			return r;
7827 		}
7828 	}
7829 
7830 #ifdef CONFIG_KEXEC_CORE
7831 	rcu_assign_pointer(crash_vmclear_loaded_vmcss,
7832 			   crash_vmclear_local_loaded_vmcss);
7833 #endif
7834 	vmx_check_vmcs12_offsets();
7835 
7836 	return 0;
7837 }
7838 module_init(vmx_init);
7839