xref: /openbmc/linux/arch/x86/kvm/vmx/nested.c (revision cfc905f1)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <linux/frame.h>
4 #include <linux/percpu.h>
5 
6 #include <asm/debugreg.h>
7 #include <asm/mmu_context.h>
8 
9 #include "cpuid.h"
10 #include "hyperv.h"
11 #include "mmu.h"
12 #include "nested.h"
13 #include "pmu.h"
14 #include "trace.h"
15 #include "x86.h"
16 
17 static bool __read_mostly enable_shadow_vmcs = 1;
18 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
19 
20 static bool __read_mostly nested_early_check = 0;
21 module_param(nested_early_check, bool, S_IRUGO);
22 
23 #define CC(consistency_check)						\
24 ({									\
25 	bool failed = (consistency_check);				\
26 	if (failed)							\
27 		trace_kvm_nested_vmenter_failed(#consistency_check, 0);	\
28 	failed;								\
29 })
30 
31 /*
32  * Hyper-V requires all of these, so mark them as supported even though
33  * they are just treated the same as all-context.
34  */
35 #define VMX_VPID_EXTENT_SUPPORTED_MASK		\
36 	(VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT |	\
37 	VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT |	\
38 	VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT |	\
39 	VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
40 
41 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
42 
43 enum {
44 	VMX_VMREAD_BITMAP,
45 	VMX_VMWRITE_BITMAP,
46 	VMX_BITMAP_NR
47 };
48 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
49 
50 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
51 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
52 
53 struct shadow_vmcs_field {
54 	u16	encoding;
55 	u16	offset;
56 };
57 static struct shadow_vmcs_field shadow_read_only_fields[] = {
58 #define SHADOW_FIELD_RO(x, y) { x, offsetof(struct vmcs12, y) },
59 #include "vmcs_shadow_fields.h"
60 };
61 static int max_shadow_read_only_fields =
62 	ARRAY_SIZE(shadow_read_only_fields);
63 
64 static struct shadow_vmcs_field shadow_read_write_fields[] = {
65 #define SHADOW_FIELD_RW(x, y) { x, offsetof(struct vmcs12, y) },
66 #include "vmcs_shadow_fields.h"
67 };
68 static int max_shadow_read_write_fields =
69 	ARRAY_SIZE(shadow_read_write_fields);
70 
71 static void init_vmcs_shadow_fields(void)
72 {
73 	int i, j;
74 
75 	memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
76 	memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
77 
78 	for (i = j = 0; i < max_shadow_read_only_fields; i++) {
79 		struct shadow_vmcs_field entry = shadow_read_only_fields[i];
80 		u16 field = entry.encoding;
81 
82 		if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
83 		    (i + 1 == max_shadow_read_only_fields ||
84 		     shadow_read_only_fields[i + 1].encoding != field + 1))
85 			pr_err("Missing field from shadow_read_only_field %x\n",
86 			       field + 1);
87 
88 		clear_bit(field, vmx_vmread_bitmap);
89 		if (field & 1)
90 #ifdef CONFIG_X86_64
91 			continue;
92 #else
93 			entry.offset += sizeof(u32);
94 #endif
95 		shadow_read_only_fields[j++] = entry;
96 	}
97 	max_shadow_read_only_fields = j;
98 
99 	for (i = j = 0; i < max_shadow_read_write_fields; i++) {
100 		struct shadow_vmcs_field entry = shadow_read_write_fields[i];
101 		u16 field = entry.encoding;
102 
103 		if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
104 		    (i + 1 == max_shadow_read_write_fields ||
105 		     shadow_read_write_fields[i + 1].encoding != field + 1))
106 			pr_err("Missing field from shadow_read_write_field %x\n",
107 			       field + 1);
108 
109 		WARN_ONCE(field >= GUEST_ES_AR_BYTES &&
110 			  field <= GUEST_TR_AR_BYTES,
111 			  "Update vmcs12_write_any() to drop reserved bits from AR_BYTES");
112 
113 		/*
114 		 * PML and the preemption timer can be emulated, but the
115 		 * processor cannot vmwrite to fields that don't exist
116 		 * on bare metal.
117 		 */
118 		switch (field) {
119 		case GUEST_PML_INDEX:
120 			if (!cpu_has_vmx_pml())
121 				continue;
122 			break;
123 		case VMX_PREEMPTION_TIMER_VALUE:
124 			if (!cpu_has_vmx_preemption_timer())
125 				continue;
126 			break;
127 		case GUEST_INTR_STATUS:
128 			if (!cpu_has_vmx_apicv())
129 				continue;
130 			break;
131 		default:
132 			break;
133 		}
134 
135 		clear_bit(field, vmx_vmwrite_bitmap);
136 		clear_bit(field, vmx_vmread_bitmap);
137 		if (field & 1)
138 #ifdef CONFIG_X86_64
139 			continue;
140 #else
141 			entry.offset += sizeof(u32);
142 #endif
143 		shadow_read_write_fields[j++] = entry;
144 	}
145 	max_shadow_read_write_fields = j;
146 }
147 
148 /*
149  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
150  * set the success or error code of an emulated VMX instruction (as specified
151  * by Vol 2B, VMX Instruction Reference, "Conventions"), and skip the emulated
152  * instruction.
153  */
154 static int nested_vmx_succeed(struct kvm_vcpu *vcpu)
155 {
156 	vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
157 			& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
158 			    X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
159 	return kvm_skip_emulated_instruction(vcpu);
160 }
161 
162 static int nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
163 {
164 	vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
165 			& ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
166 			    X86_EFLAGS_SF | X86_EFLAGS_OF))
167 			| X86_EFLAGS_CF);
168 	return kvm_skip_emulated_instruction(vcpu);
169 }
170 
171 static int nested_vmx_failValid(struct kvm_vcpu *vcpu,
172 				u32 vm_instruction_error)
173 {
174 	vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
175 			& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
176 			    X86_EFLAGS_SF | X86_EFLAGS_OF))
177 			| X86_EFLAGS_ZF);
178 	get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
179 	/*
180 	 * We don't need to force a shadow sync because
181 	 * VM_INSTRUCTION_ERROR is not shadowed
182 	 */
183 	return kvm_skip_emulated_instruction(vcpu);
184 }
185 
186 static int nested_vmx_fail(struct kvm_vcpu *vcpu, u32 vm_instruction_error)
187 {
188 	struct vcpu_vmx *vmx = to_vmx(vcpu);
189 
190 	/*
191 	 * failValid writes the error number to the current VMCS, which
192 	 * can't be done if there isn't a current VMCS.
193 	 */
194 	if (vmx->nested.current_vmptr == -1ull && !vmx->nested.hv_evmcs)
195 		return nested_vmx_failInvalid(vcpu);
196 
197 	return nested_vmx_failValid(vcpu, vm_instruction_error);
198 }
199 
200 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
201 {
202 	/* TODO: not to reset guest simply here. */
203 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
204 	pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
205 }
206 
207 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
208 {
209 	return fixed_bits_valid(control, low, high);
210 }
211 
212 static inline u64 vmx_control_msr(u32 low, u32 high)
213 {
214 	return low | ((u64)high << 32);
215 }
216 
217 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
218 {
219 	secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_SHADOW_VMCS);
220 	vmcs_write64(VMCS_LINK_POINTER, -1ull);
221 	vmx->nested.need_vmcs12_to_shadow_sync = false;
222 }
223 
224 static inline void nested_release_evmcs(struct kvm_vcpu *vcpu)
225 {
226 	struct vcpu_vmx *vmx = to_vmx(vcpu);
227 
228 	if (!vmx->nested.hv_evmcs)
229 		return;
230 
231 	kvm_vcpu_unmap(vcpu, &vmx->nested.hv_evmcs_map, true);
232 	vmx->nested.hv_evmcs_vmptr = 0;
233 	vmx->nested.hv_evmcs = NULL;
234 }
235 
236 /*
237  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
238  * just stops using VMX.
239  */
240 static void free_nested(struct kvm_vcpu *vcpu)
241 {
242 	struct vcpu_vmx *vmx = to_vmx(vcpu);
243 
244 	if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
245 		return;
246 
247 	kvm_clear_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
248 
249 	vmx->nested.vmxon = false;
250 	vmx->nested.smm.vmxon = false;
251 	free_vpid(vmx->nested.vpid02);
252 	vmx->nested.posted_intr_nv = -1;
253 	vmx->nested.current_vmptr = -1ull;
254 	if (enable_shadow_vmcs) {
255 		vmx_disable_shadow_vmcs(vmx);
256 		vmcs_clear(vmx->vmcs01.shadow_vmcs);
257 		free_vmcs(vmx->vmcs01.shadow_vmcs);
258 		vmx->vmcs01.shadow_vmcs = NULL;
259 	}
260 	kfree(vmx->nested.cached_vmcs12);
261 	vmx->nested.cached_vmcs12 = NULL;
262 	kfree(vmx->nested.cached_shadow_vmcs12);
263 	vmx->nested.cached_shadow_vmcs12 = NULL;
264 	/* Unpin physical memory we referred to in the vmcs02 */
265 	if (vmx->nested.apic_access_page) {
266 		kvm_release_page_clean(vmx->nested.apic_access_page);
267 		vmx->nested.apic_access_page = NULL;
268 	}
269 	kvm_vcpu_unmap(vcpu, &vmx->nested.virtual_apic_map, true);
270 	kvm_vcpu_unmap(vcpu, &vmx->nested.pi_desc_map, true);
271 	vmx->nested.pi_desc = NULL;
272 
273 	kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
274 
275 	nested_release_evmcs(vcpu);
276 
277 	free_loaded_vmcs(&vmx->nested.vmcs02);
278 }
279 
280 static void vmx_sync_vmcs_host_state(struct vcpu_vmx *vmx,
281 				     struct loaded_vmcs *prev)
282 {
283 	struct vmcs_host_state *dest, *src;
284 
285 	if (unlikely(!vmx->guest_state_loaded))
286 		return;
287 
288 	src = &prev->host_state;
289 	dest = &vmx->loaded_vmcs->host_state;
290 
291 	vmx_set_host_fs_gs(dest, src->fs_sel, src->gs_sel, src->fs_base, src->gs_base);
292 	dest->ldt_sel = src->ldt_sel;
293 #ifdef CONFIG_X86_64
294 	dest->ds_sel = src->ds_sel;
295 	dest->es_sel = src->es_sel;
296 #endif
297 }
298 
299 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
300 {
301 	struct vcpu_vmx *vmx = to_vmx(vcpu);
302 	struct loaded_vmcs *prev;
303 	int cpu;
304 
305 	if (vmx->loaded_vmcs == vmcs)
306 		return;
307 
308 	cpu = get_cpu();
309 	prev = vmx->loaded_vmcs;
310 	vmx->loaded_vmcs = vmcs;
311 	vmx_vcpu_load_vmcs(vcpu, cpu, prev);
312 	vmx_sync_vmcs_host_state(vmx, prev);
313 	put_cpu();
314 
315 	vmx_register_cache_reset(vcpu);
316 }
317 
318 /*
319  * Ensure that the current vmcs of the logical processor is the
320  * vmcs01 of the vcpu before calling free_nested().
321  */
322 void nested_vmx_free_vcpu(struct kvm_vcpu *vcpu)
323 {
324 	vcpu_load(vcpu);
325 	vmx_leave_nested(vcpu);
326 	vmx_switch_vmcs(vcpu, &to_vmx(vcpu)->vmcs01);
327 	free_nested(vcpu);
328 	vcpu_put(vcpu);
329 }
330 
331 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
332 		struct x86_exception *fault)
333 {
334 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
335 	struct vcpu_vmx *vmx = to_vmx(vcpu);
336 	u32 vm_exit_reason;
337 	unsigned long exit_qualification = vcpu->arch.exit_qualification;
338 
339 	if (vmx->nested.pml_full) {
340 		vm_exit_reason = EXIT_REASON_PML_FULL;
341 		vmx->nested.pml_full = false;
342 		exit_qualification &= INTR_INFO_UNBLOCK_NMI;
343 	} else if (fault->error_code & PFERR_RSVD_MASK)
344 		vm_exit_reason = EXIT_REASON_EPT_MISCONFIG;
345 	else
346 		vm_exit_reason = EXIT_REASON_EPT_VIOLATION;
347 
348 	nested_vmx_vmexit(vcpu, vm_exit_reason, 0, exit_qualification);
349 	vmcs12->guest_physical_address = fault->address;
350 }
351 
352 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
353 {
354 	WARN_ON(mmu_is_nested(vcpu));
355 
356 	vcpu->arch.mmu = &vcpu->arch.guest_mmu;
357 	kvm_init_shadow_ept_mmu(vcpu,
358 			to_vmx(vcpu)->nested.msrs.ept_caps &
359 			VMX_EPT_EXECUTE_ONLY_BIT,
360 			nested_ept_ad_enabled(vcpu),
361 			nested_ept_get_eptp(vcpu));
362 	vcpu->arch.mmu->get_guest_pgd     = nested_ept_get_eptp;
363 	vcpu->arch.mmu->inject_page_fault = nested_ept_inject_page_fault;
364 	vcpu->arch.mmu->get_pdptr         = kvm_pdptr_read;
365 
366 	vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
367 }
368 
369 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
370 {
371 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
372 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
373 }
374 
375 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
376 					    u16 error_code)
377 {
378 	bool inequality, bit;
379 
380 	bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
381 	inequality =
382 		(error_code & vmcs12->page_fault_error_code_mask) !=
383 		 vmcs12->page_fault_error_code_match;
384 	return inequality ^ bit;
385 }
386 
387 
388 /*
389  * KVM wants to inject page-faults which it got to the guest. This function
390  * checks whether in a nested guest, we need to inject them to L1 or L2.
391  */
392 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
393 {
394 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
395 	unsigned int nr = vcpu->arch.exception.nr;
396 	bool has_payload = vcpu->arch.exception.has_payload;
397 	unsigned long payload = vcpu->arch.exception.payload;
398 
399 	if (nr == PF_VECTOR) {
400 		if (vcpu->arch.exception.nested_apf) {
401 			*exit_qual = vcpu->arch.apf.nested_apf_token;
402 			return 1;
403 		}
404 		if (nested_vmx_is_page_fault_vmexit(vmcs12,
405 						    vcpu->arch.exception.error_code)) {
406 			*exit_qual = has_payload ? payload : vcpu->arch.cr2;
407 			return 1;
408 		}
409 	} else if (vmcs12->exception_bitmap & (1u << nr)) {
410 		if (nr == DB_VECTOR) {
411 			if (!has_payload) {
412 				payload = vcpu->arch.dr6;
413 				payload &= ~(DR6_FIXED_1 | DR6_BT);
414 				payload ^= DR6_RTM;
415 			}
416 			*exit_qual = payload;
417 		} else
418 			*exit_qual = 0;
419 		return 1;
420 	}
421 
422 	return 0;
423 }
424 
425 
426 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
427 		struct x86_exception *fault)
428 {
429 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
430 
431 	WARN_ON(!is_guest_mode(vcpu));
432 
433 	if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
434 		!to_vmx(vcpu)->nested.nested_run_pending) {
435 		vmcs12->vm_exit_intr_error_code = fault->error_code;
436 		nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
437 				  PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
438 				  INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
439 				  fault->address);
440 	} else {
441 		kvm_inject_page_fault(vcpu, fault);
442 	}
443 }
444 
445 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
446 					       struct vmcs12 *vmcs12)
447 {
448 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
449 		return 0;
450 
451 	if (CC(!page_address_valid(vcpu, vmcs12->io_bitmap_a)) ||
452 	    CC(!page_address_valid(vcpu, vmcs12->io_bitmap_b)))
453 		return -EINVAL;
454 
455 	return 0;
456 }
457 
458 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
459 						struct vmcs12 *vmcs12)
460 {
461 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
462 		return 0;
463 
464 	if (CC(!page_address_valid(vcpu, vmcs12->msr_bitmap)))
465 		return -EINVAL;
466 
467 	return 0;
468 }
469 
470 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
471 						struct vmcs12 *vmcs12)
472 {
473 	if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
474 		return 0;
475 
476 	if (CC(!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr)))
477 		return -EINVAL;
478 
479 	return 0;
480 }
481 
482 /*
483  * Check if MSR is intercepted for L01 MSR bitmap.
484  */
485 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
486 {
487 	unsigned long *msr_bitmap;
488 	int f = sizeof(unsigned long);
489 
490 	if (!cpu_has_vmx_msr_bitmap())
491 		return true;
492 
493 	msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
494 
495 	if (msr <= 0x1fff) {
496 		return !!test_bit(msr, msr_bitmap + 0x800 / f);
497 	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
498 		msr &= 0x1fff;
499 		return !!test_bit(msr, msr_bitmap + 0xc00 / f);
500 	}
501 
502 	return true;
503 }
504 
505 /*
506  * If a msr is allowed by L0, we should check whether it is allowed by L1.
507  * The corresponding bit will be cleared unless both of L0 and L1 allow it.
508  */
509 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
510 					       unsigned long *msr_bitmap_nested,
511 					       u32 msr, int type)
512 {
513 	int f = sizeof(unsigned long);
514 
515 	/*
516 	 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
517 	 * have the write-low and read-high bitmap offsets the wrong way round.
518 	 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
519 	 */
520 	if (msr <= 0x1fff) {
521 		if (type & MSR_TYPE_R &&
522 		   !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
523 			/* read-low */
524 			__clear_bit(msr, msr_bitmap_nested + 0x000 / f);
525 
526 		if (type & MSR_TYPE_W &&
527 		   !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
528 			/* write-low */
529 			__clear_bit(msr, msr_bitmap_nested + 0x800 / f);
530 
531 	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
532 		msr &= 0x1fff;
533 		if (type & MSR_TYPE_R &&
534 		   !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
535 			/* read-high */
536 			__clear_bit(msr, msr_bitmap_nested + 0x400 / f);
537 
538 		if (type & MSR_TYPE_W &&
539 		   !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
540 			/* write-high */
541 			__clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
542 
543 	}
544 }
545 
546 static inline void enable_x2apic_msr_intercepts(unsigned long *msr_bitmap)
547 {
548 	int msr;
549 
550 	for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
551 		unsigned word = msr / BITS_PER_LONG;
552 
553 		msr_bitmap[word] = ~0;
554 		msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
555 	}
556 }
557 
558 /*
559  * Merge L0's and L1's MSR bitmap, return false to indicate that
560  * we do not use the hardware.
561  */
562 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
563 						 struct vmcs12 *vmcs12)
564 {
565 	int msr;
566 	unsigned long *msr_bitmap_l1;
567 	unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
568 	struct kvm_host_map *map = &to_vmx(vcpu)->nested.msr_bitmap_map;
569 
570 	/* Nothing to do if the MSR bitmap is not in use.  */
571 	if (!cpu_has_vmx_msr_bitmap() ||
572 	    !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
573 		return false;
574 
575 	if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->msr_bitmap), map))
576 		return false;
577 
578 	msr_bitmap_l1 = (unsigned long *)map->hva;
579 
580 	/*
581 	 * To keep the control flow simple, pay eight 8-byte writes (sixteen
582 	 * 4-byte writes on 32-bit systems) up front to enable intercepts for
583 	 * the x2APIC MSR range and selectively disable them below.
584 	 */
585 	enable_x2apic_msr_intercepts(msr_bitmap_l0);
586 
587 	if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
588 		if (nested_cpu_has_apic_reg_virt(vmcs12)) {
589 			/*
590 			 * L0 need not intercept reads for MSRs between 0x800
591 			 * and 0x8ff, it just lets the processor take the value
592 			 * from the virtual-APIC page; take those 256 bits
593 			 * directly from the L1 bitmap.
594 			 */
595 			for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
596 				unsigned word = msr / BITS_PER_LONG;
597 
598 				msr_bitmap_l0[word] = msr_bitmap_l1[word];
599 			}
600 		}
601 
602 		nested_vmx_disable_intercept_for_msr(
603 			msr_bitmap_l1, msr_bitmap_l0,
604 			X2APIC_MSR(APIC_TASKPRI),
605 			MSR_TYPE_R | MSR_TYPE_W);
606 
607 		if (nested_cpu_has_vid(vmcs12)) {
608 			nested_vmx_disable_intercept_for_msr(
609 				msr_bitmap_l1, msr_bitmap_l0,
610 				X2APIC_MSR(APIC_EOI),
611 				MSR_TYPE_W);
612 			nested_vmx_disable_intercept_for_msr(
613 				msr_bitmap_l1, msr_bitmap_l0,
614 				X2APIC_MSR(APIC_SELF_IPI),
615 				MSR_TYPE_W);
616 		}
617 	}
618 
619 	/* KVM unconditionally exposes the FS/GS base MSRs to L1. */
620 	nested_vmx_disable_intercept_for_msr(msr_bitmap_l1, msr_bitmap_l0,
621 					     MSR_FS_BASE, MSR_TYPE_RW);
622 
623 	nested_vmx_disable_intercept_for_msr(msr_bitmap_l1, msr_bitmap_l0,
624 					     MSR_GS_BASE, MSR_TYPE_RW);
625 
626 	nested_vmx_disable_intercept_for_msr(msr_bitmap_l1, msr_bitmap_l0,
627 					     MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
628 
629 	/*
630 	 * Checking the L0->L1 bitmap is trying to verify two things:
631 	 *
632 	 * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
633 	 *    ensures that we do not accidentally generate an L02 MSR bitmap
634 	 *    from the L12 MSR bitmap that is too permissive.
635 	 * 2. That L1 or L2s have actually used the MSR. This avoids
636 	 *    unnecessarily merging of the bitmap if the MSR is unused. This
637 	 *    works properly because we only update the L01 MSR bitmap lazily.
638 	 *    So even if L0 should pass L1 these MSRs, the L01 bitmap is only
639 	 *    updated to reflect this when L1 (or its L2s) actually write to
640 	 *    the MSR.
641 	 */
642 	if (!msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL))
643 		nested_vmx_disable_intercept_for_msr(
644 					msr_bitmap_l1, msr_bitmap_l0,
645 					MSR_IA32_SPEC_CTRL,
646 					MSR_TYPE_R | MSR_TYPE_W);
647 
648 	if (!msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD))
649 		nested_vmx_disable_intercept_for_msr(
650 					msr_bitmap_l1, msr_bitmap_l0,
651 					MSR_IA32_PRED_CMD,
652 					MSR_TYPE_W);
653 
654 	kvm_vcpu_unmap(vcpu, &to_vmx(vcpu)->nested.msr_bitmap_map, false);
655 
656 	return true;
657 }
658 
659 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
660 				       struct vmcs12 *vmcs12)
661 {
662 	struct kvm_host_map map;
663 	struct vmcs12 *shadow;
664 
665 	if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
666 	    vmcs12->vmcs_link_pointer == -1ull)
667 		return;
668 
669 	shadow = get_shadow_vmcs12(vcpu);
670 
671 	if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->vmcs_link_pointer), &map))
672 		return;
673 
674 	memcpy(shadow, map.hva, VMCS12_SIZE);
675 	kvm_vcpu_unmap(vcpu, &map, false);
676 }
677 
678 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
679 					      struct vmcs12 *vmcs12)
680 {
681 	struct vcpu_vmx *vmx = to_vmx(vcpu);
682 
683 	if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
684 	    vmcs12->vmcs_link_pointer == -1ull)
685 		return;
686 
687 	kvm_write_guest(vmx->vcpu.kvm, vmcs12->vmcs_link_pointer,
688 			get_shadow_vmcs12(vcpu), VMCS12_SIZE);
689 }
690 
691 /*
692  * In nested virtualization, check if L1 has set
693  * VM_EXIT_ACK_INTR_ON_EXIT
694  */
695 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
696 {
697 	return get_vmcs12(vcpu)->vm_exit_controls &
698 		VM_EXIT_ACK_INTR_ON_EXIT;
699 }
700 
701 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
702 					  struct vmcs12 *vmcs12)
703 {
704 	if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
705 	    CC(!page_address_valid(vcpu, vmcs12->apic_access_addr)))
706 		return -EINVAL;
707 	else
708 		return 0;
709 }
710 
711 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
712 					   struct vmcs12 *vmcs12)
713 {
714 	if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
715 	    !nested_cpu_has_apic_reg_virt(vmcs12) &&
716 	    !nested_cpu_has_vid(vmcs12) &&
717 	    !nested_cpu_has_posted_intr(vmcs12))
718 		return 0;
719 
720 	/*
721 	 * If virtualize x2apic mode is enabled,
722 	 * virtualize apic access must be disabled.
723 	 */
724 	if (CC(nested_cpu_has_virt_x2apic_mode(vmcs12) &&
725 	       nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)))
726 		return -EINVAL;
727 
728 	/*
729 	 * If virtual interrupt delivery is enabled,
730 	 * we must exit on external interrupts.
731 	 */
732 	if (CC(nested_cpu_has_vid(vmcs12) && !nested_exit_on_intr(vcpu)))
733 		return -EINVAL;
734 
735 	/*
736 	 * bits 15:8 should be zero in posted_intr_nv,
737 	 * the descriptor address has been already checked
738 	 * in nested_get_vmcs12_pages.
739 	 *
740 	 * bits 5:0 of posted_intr_desc_addr should be zero.
741 	 */
742 	if (nested_cpu_has_posted_intr(vmcs12) &&
743 	   (CC(!nested_cpu_has_vid(vmcs12)) ||
744 	    CC(!nested_exit_intr_ack_set(vcpu)) ||
745 	    CC((vmcs12->posted_intr_nv & 0xff00)) ||
746 	    CC((vmcs12->posted_intr_desc_addr & 0x3f)) ||
747 	    CC((vmcs12->posted_intr_desc_addr >> cpuid_maxphyaddr(vcpu)))))
748 		return -EINVAL;
749 
750 	/* tpr shadow is needed by all apicv features. */
751 	if (CC(!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)))
752 		return -EINVAL;
753 
754 	return 0;
755 }
756 
757 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
758 				       u32 count, u64 addr)
759 {
760 	int maxphyaddr;
761 
762 	if (count == 0)
763 		return 0;
764 	maxphyaddr = cpuid_maxphyaddr(vcpu);
765 	if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
766 	    (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr)
767 		return -EINVAL;
768 
769 	return 0;
770 }
771 
772 static int nested_vmx_check_exit_msr_switch_controls(struct kvm_vcpu *vcpu,
773 						     struct vmcs12 *vmcs12)
774 {
775 	if (CC(nested_vmx_check_msr_switch(vcpu,
776 					   vmcs12->vm_exit_msr_load_count,
777 					   vmcs12->vm_exit_msr_load_addr)) ||
778 	    CC(nested_vmx_check_msr_switch(vcpu,
779 					   vmcs12->vm_exit_msr_store_count,
780 					   vmcs12->vm_exit_msr_store_addr)))
781 		return -EINVAL;
782 
783 	return 0;
784 }
785 
786 static int nested_vmx_check_entry_msr_switch_controls(struct kvm_vcpu *vcpu,
787                                                       struct vmcs12 *vmcs12)
788 {
789 	if (CC(nested_vmx_check_msr_switch(vcpu,
790 					   vmcs12->vm_entry_msr_load_count,
791 					   vmcs12->vm_entry_msr_load_addr)))
792                 return -EINVAL;
793 
794 	return 0;
795 }
796 
797 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
798 					 struct vmcs12 *vmcs12)
799 {
800 	if (!nested_cpu_has_pml(vmcs12))
801 		return 0;
802 
803 	if (CC(!nested_cpu_has_ept(vmcs12)) ||
804 	    CC(!page_address_valid(vcpu, vmcs12->pml_address)))
805 		return -EINVAL;
806 
807 	return 0;
808 }
809 
810 static int nested_vmx_check_unrestricted_guest_controls(struct kvm_vcpu *vcpu,
811 							struct vmcs12 *vmcs12)
812 {
813 	if (CC(nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST) &&
814 	       !nested_cpu_has_ept(vmcs12)))
815 		return -EINVAL;
816 	return 0;
817 }
818 
819 static int nested_vmx_check_mode_based_ept_exec_controls(struct kvm_vcpu *vcpu,
820 							 struct vmcs12 *vmcs12)
821 {
822 	if (CC(nested_cpu_has2(vmcs12, SECONDARY_EXEC_MODE_BASED_EPT_EXEC) &&
823 	       !nested_cpu_has_ept(vmcs12)))
824 		return -EINVAL;
825 	return 0;
826 }
827 
828 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
829 						 struct vmcs12 *vmcs12)
830 {
831 	if (!nested_cpu_has_shadow_vmcs(vmcs12))
832 		return 0;
833 
834 	if (CC(!page_address_valid(vcpu, vmcs12->vmread_bitmap)) ||
835 	    CC(!page_address_valid(vcpu, vmcs12->vmwrite_bitmap)))
836 		return -EINVAL;
837 
838 	return 0;
839 }
840 
841 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
842 				       struct vmx_msr_entry *e)
843 {
844 	/* x2APIC MSR accesses are not allowed */
845 	if (CC(vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8))
846 		return -EINVAL;
847 	if (CC(e->index == MSR_IA32_UCODE_WRITE) || /* SDM Table 35-2 */
848 	    CC(e->index == MSR_IA32_UCODE_REV))
849 		return -EINVAL;
850 	if (CC(e->reserved != 0))
851 		return -EINVAL;
852 	return 0;
853 }
854 
855 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
856 				     struct vmx_msr_entry *e)
857 {
858 	if (CC(e->index == MSR_FS_BASE) ||
859 	    CC(e->index == MSR_GS_BASE) ||
860 	    CC(e->index == MSR_IA32_SMM_MONITOR_CTL) || /* SMM is not supported */
861 	    nested_vmx_msr_check_common(vcpu, e))
862 		return -EINVAL;
863 	return 0;
864 }
865 
866 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
867 				      struct vmx_msr_entry *e)
868 {
869 	if (CC(e->index == MSR_IA32_SMBASE) || /* SMM is not supported */
870 	    nested_vmx_msr_check_common(vcpu, e))
871 		return -EINVAL;
872 	return 0;
873 }
874 
875 static u32 nested_vmx_max_atomic_switch_msrs(struct kvm_vcpu *vcpu)
876 {
877 	struct vcpu_vmx *vmx = to_vmx(vcpu);
878 	u64 vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
879 				       vmx->nested.msrs.misc_high);
880 
881 	return (vmx_misc_max_msr(vmx_misc) + 1) * VMX_MISC_MSR_LIST_MULTIPLIER;
882 }
883 
884 /*
885  * Load guest's/host's msr at nested entry/exit.
886  * return 0 for success, entry index for failure.
887  *
888  * One of the failure modes for MSR load/store is when a list exceeds the
889  * virtual hardware's capacity. To maintain compatibility with hardware inasmuch
890  * as possible, process all valid entries before failing rather than precheck
891  * for a capacity violation.
892  */
893 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
894 {
895 	u32 i;
896 	struct vmx_msr_entry e;
897 	u32 max_msr_list_size = nested_vmx_max_atomic_switch_msrs(vcpu);
898 
899 	for (i = 0; i < count; i++) {
900 		if (unlikely(i >= max_msr_list_size))
901 			goto fail;
902 
903 		if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
904 					&e, sizeof(e))) {
905 			pr_debug_ratelimited(
906 				"%s cannot read MSR entry (%u, 0x%08llx)\n",
907 				__func__, i, gpa + i * sizeof(e));
908 			goto fail;
909 		}
910 		if (nested_vmx_load_msr_check(vcpu, &e)) {
911 			pr_debug_ratelimited(
912 				"%s check failed (%u, 0x%x, 0x%x)\n",
913 				__func__, i, e.index, e.reserved);
914 			goto fail;
915 		}
916 		if (kvm_set_msr(vcpu, e.index, e.value)) {
917 			pr_debug_ratelimited(
918 				"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
919 				__func__, i, e.index, e.value);
920 			goto fail;
921 		}
922 	}
923 	return 0;
924 fail:
925 	/* Note, max_msr_list_size is at most 4096, i.e. this can't wrap. */
926 	return i + 1;
927 }
928 
929 static bool nested_vmx_get_vmexit_msr_value(struct kvm_vcpu *vcpu,
930 					    u32 msr_index,
931 					    u64 *data)
932 {
933 	struct vcpu_vmx *vmx = to_vmx(vcpu);
934 
935 	/*
936 	 * If the L0 hypervisor stored a more accurate value for the TSC that
937 	 * does not include the time taken for emulation of the L2->L1
938 	 * VM-exit in L0, use the more accurate value.
939 	 */
940 	if (msr_index == MSR_IA32_TSC) {
941 		int index = vmx_find_msr_index(&vmx->msr_autostore.guest,
942 					       MSR_IA32_TSC);
943 
944 		if (index >= 0) {
945 			u64 val = vmx->msr_autostore.guest.val[index].value;
946 
947 			*data = kvm_read_l1_tsc(vcpu, val);
948 			return true;
949 		}
950 	}
951 
952 	if (kvm_get_msr(vcpu, msr_index, data)) {
953 		pr_debug_ratelimited("%s cannot read MSR (0x%x)\n", __func__,
954 			msr_index);
955 		return false;
956 	}
957 	return true;
958 }
959 
960 static bool read_and_check_msr_entry(struct kvm_vcpu *vcpu, u64 gpa, int i,
961 				     struct vmx_msr_entry *e)
962 {
963 	if (kvm_vcpu_read_guest(vcpu,
964 				gpa + i * sizeof(*e),
965 				e, 2 * sizeof(u32))) {
966 		pr_debug_ratelimited(
967 			"%s cannot read MSR entry (%u, 0x%08llx)\n",
968 			__func__, i, gpa + i * sizeof(*e));
969 		return false;
970 	}
971 	if (nested_vmx_store_msr_check(vcpu, e)) {
972 		pr_debug_ratelimited(
973 			"%s check failed (%u, 0x%x, 0x%x)\n",
974 			__func__, i, e->index, e->reserved);
975 		return false;
976 	}
977 	return true;
978 }
979 
980 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
981 {
982 	u64 data;
983 	u32 i;
984 	struct vmx_msr_entry e;
985 	u32 max_msr_list_size = nested_vmx_max_atomic_switch_msrs(vcpu);
986 
987 	for (i = 0; i < count; i++) {
988 		if (unlikely(i >= max_msr_list_size))
989 			return -EINVAL;
990 
991 		if (!read_and_check_msr_entry(vcpu, gpa, i, &e))
992 			return -EINVAL;
993 
994 		if (!nested_vmx_get_vmexit_msr_value(vcpu, e.index, &data))
995 			return -EINVAL;
996 
997 		if (kvm_vcpu_write_guest(vcpu,
998 					 gpa + i * sizeof(e) +
999 					     offsetof(struct vmx_msr_entry, value),
1000 					 &data, sizeof(data))) {
1001 			pr_debug_ratelimited(
1002 				"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
1003 				__func__, i, e.index, data);
1004 			return -EINVAL;
1005 		}
1006 	}
1007 	return 0;
1008 }
1009 
1010 static bool nested_msr_store_list_has_msr(struct kvm_vcpu *vcpu, u32 msr_index)
1011 {
1012 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1013 	u32 count = vmcs12->vm_exit_msr_store_count;
1014 	u64 gpa = vmcs12->vm_exit_msr_store_addr;
1015 	struct vmx_msr_entry e;
1016 	u32 i;
1017 
1018 	for (i = 0; i < count; i++) {
1019 		if (!read_and_check_msr_entry(vcpu, gpa, i, &e))
1020 			return false;
1021 
1022 		if (e.index == msr_index)
1023 			return true;
1024 	}
1025 	return false;
1026 }
1027 
1028 static void prepare_vmx_msr_autostore_list(struct kvm_vcpu *vcpu,
1029 					   u32 msr_index)
1030 {
1031 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1032 	struct vmx_msrs *autostore = &vmx->msr_autostore.guest;
1033 	bool in_vmcs12_store_list;
1034 	int msr_autostore_index;
1035 	bool in_autostore_list;
1036 	int last;
1037 
1038 	msr_autostore_index = vmx_find_msr_index(autostore, msr_index);
1039 	in_autostore_list = msr_autostore_index >= 0;
1040 	in_vmcs12_store_list = nested_msr_store_list_has_msr(vcpu, msr_index);
1041 
1042 	if (in_vmcs12_store_list && !in_autostore_list) {
1043 		if (autostore->nr == NR_LOADSTORE_MSRS) {
1044 			/*
1045 			 * Emulated VMEntry does not fail here.  Instead a less
1046 			 * accurate value will be returned by
1047 			 * nested_vmx_get_vmexit_msr_value() using kvm_get_msr()
1048 			 * instead of reading the value from the vmcs02 VMExit
1049 			 * MSR-store area.
1050 			 */
1051 			pr_warn_ratelimited(
1052 				"Not enough msr entries in msr_autostore.  Can't add msr %x\n",
1053 				msr_index);
1054 			return;
1055 		}
1056 		last = autostore->nr++;
1057 		autostore->val[last].index = msr_index;
1058 	} else if (!in_vmcs12_store_list && in_autostore_list) {
1059 		last = --autostore->nr;
1060 		autostore->val[msr_autostore_index] = autostore->val[last];
1061 	}
1062 }
1063 
1064 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
1065 {
1066 	unsigned long invalid_mask;
1067 
1068 	invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
1069 	return (val & invalid_mask) == 0;
1070 }
1071 
1072 /*
1073  * Returns true if the MMU needs to be sync'd on nested VM-Enter/VM-Exit.
1074  * tl;dr: the MMU needs a sync if L0 is using shadow paging and L1 didn't
1075  * enable VPID for L2 (implying it expects a TLB flush on VMX transitions).
1076  * Here's why.
1077  *
1078  * If EPT is enabled by L0 a sync is never needed:
1079  * - if it is disabled by L1, then L0 is not shadowing L1 or L2 PTEs, there
1080  *   cannot be unsync'd SPTEs for either L1 or L2.
1081  *
1082  * - if it is also enabled by L1, then L0 doesn't need to sync on VM-Enter
1083  *   VM-Enter as VM-Enter isn't required to invalidate guest-physical mappings
1084  *   (irrespective of VPID), i.e. L1 can't rely on the (virtual) CPU to flush
1085  *   stale guest-physical mappings for L2 from the TLB.  And as above, L0 isn't
1086  *   shadowing L1 PTEs so there are no unsync'd SPTEs to sync on VM-Exit.
1087  *
1088  * If EPT is disabled by L0:
1089  * - if VPID is enabled by L1 (for L2), the situation is similar to when L1
1090  *   enables EPT: L0 doesn't need to sync as VM-Enter and VM-Exit aren't
1091  *   required to invalidate linear mappings (EPT is disabled so there are
1092  *   no combined or guest-physical mappings), i.e. L1 can't rely on the
1093  *   (virtual) CPU to flush stale linear mappings for either L2 or itself (L1).
1094  *
1095  * - however if VPID is disabled by L1, then a sync is needed as L1 expects all
1096  *   linear mappings (EPT is disabled so there are no combined or guest-physical
1097  *   mappings) to be invalidated on both VM-Enter and VM-Exit.
1098  *
1099  * Note, this logic is subtly different than nested_has_guest_tlb_tag(), which
1100  * additionally checks that L2 has been assigned a VPID (when EPT is disabled).
1101  * Whether or not L2 has been assigned a VPID by L0 is irrelevant with respect
1102  * to L1's expectations, e.g. L0 needs to invalidate hardware TLB entries if L2
1103  * doesn't have a unique VPID to prevent reusing L1's entries (assuming L1 has
1104  * been assigned a VPID), but L0 doesn't need to do a MMU sync because L1
1105  * doesn't expect stale (virtual) TLB entries to be flushed, i.e. L1 doesn't
1106  * know that L0 will flush the TLB and so L1 will do INVVPID as needed to flush
1107  * stale TLB entries, at which point L0 will sync L2's MMU.
1108  */
1109 static bool nested_vmx_transition_mmu_sync(struct kvm_vcpu *vcpu)
1110 {
1111 	return !enable_ept && !nested_cpu_has_vpid(get_vmcs12(vcpu));
1112 }
1113 
1114 /*
1115  * Load guest's/host's cr3 at nested entry/exit.  @nested_ept is true if we are
1116  * emulating VM-Entry into a guest with EPT enabled.  On failure, the expected
1117  * Exit Qualification (for a VM-Entry consistency check VM-Exit) is assigned to
1118  * @entry_failure_code.
1119  */
1120 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
1121 			       enum vm_entry_failure_code *entry_failure_code)
1122 {
1123 	if (CC(!nested_cr3_valid(vcpu, cr3))) {
1124 		*entry_failure_code = ENTRY_FAIL_DEFAULT;
1125 		return -EINVAL;
1126 	}
1127 
1128 	/*
1129 	 * If PAE paging and EPT are both on, CR3 is not used by the CPU and
1130 	 * must not be dereferenced.
1131 	 */
1132 	if (!nested_ept && is_pae_paging(vcpu) &&
1133 	    (cr3 != kvm_read_cr3(vcpu) || pdptrs_changed(vcpu))) {
1134 		if (CC(!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))) {
1135 			*entry_failure_code = ENTRY_FAIL_PDPTE;
1136 			return -EINVAL;
1137 		}
1138 	}
1139 
1140 	/*
1141 	 * Unconditionally skip the TLB flush on fast CR3 switch, all TLB
1142 	 * flushes are handled by nested_vmx_transition_tlb_flush().  See
1143 	 * nested_vmx_transition_mmu_sync for details on skipping the MMU sync.
1144 	 */
1145 	if (!nested_ept)
1146 		kvm_mmu_new_pgd(vcpu, cr3, true,
1147 				!nested_vmx_transition_mmu_sync(vcpu));
1148 
1149 	vcpu->arch.cr3 = cr3;
1150 	kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
1151 
1152 	kvm_init_mmu(vcpu, false);
1153 
1154 	return 0;
1155 }
1156 
1157 /*
1158  * Returns if KVM is able to config CPU to tag TLB entries
1159  * populated by L2 differently than TLB entries populated
1160  * by L1.
1161  *
1162  * If L0 uses EPT, L1 and L2 run with different EPTP because
1163  * guest_mode is part of kvm_mmu_page_role. Thus, TLB entries
1164  * are tagged with different EPTP.
1165  *
1166  * If L1 uses VPID and we allocated a vpid02, TLB entries are tagged
1167  * with different VPID (L1 entries are tagged with vmx->vpid
1168  * while L2 entries are tagged with vmx->nested.vpid02).
1169  */
1170 static bool nested_has_guest_tlb_tag(struct kvm_vcpu *vcpu)
1171 {
1172 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1173 
1174 	return enable_ept ||
1175 	       (nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02);
1176 }
1177 
1178 static void nested_vmx_transition_tlb_flush(struct kvm_vcpu *vcpu,
1179 					    struct vmcs12 *vmcs12,
1180 					    bool is_vmenter)
1181 {
1182 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1183 
1184 	/*
1185 	 * If VPID is disabled, linear and combined mappings are flushed on
1186 	 * VM-Enter/VM-Exit, and guest-physical mappings are valid only for
1187 	 * their associated EPTP.
1188 	 */
1189 	if (!enable_vpid)
1190 		return;
1191 
1192 	/*
1193 	 * If vmcs12 doesn't use VPID, L1 expects linear and combined mappings
1194 	 * for *all* contexts to be flushed on VM-Enter/VM-Exit.
1195 	 *
1196 	 * If VPID is enabled and used by vmc12, but L2 does not have a unique
1197 	 * TLB tag (ASID), i.e. EPT is disabled and KVM was unable to allocate
1198 	 * a VPID for L2, flush the current context as the effective ASID is
1199 	 * common to both L1 and L2.
1200 	 *
1201 	 * Defer the flush so that it runs after vmcs02.EPTP has been set by
1202 	 * KVM_REQ_LOAD_MMU_PGD (if nested EPT is enabled) and to avoid
1203 	 * redundant flushes further down the nested pipeline.
1204 	 *
1205 	 * If a TLB flush isn't required due to any of the above, and vpid12 is
1206 	 * changing then the new "virtual" VPID (vpid12) will reuse the same
1207 	 * "real" VPID (vpid02), and so needs to be sync'd.  There is no direct
1208 	 * mapping between vpid02 and vpid12, vpid02 is per-vCPU and reused for
1209 	 * all nested vCPUs.
1210 	 */
1211 	if (!nested_cpu_has_vpid(vmcs12)) {
1212 		kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1213 	} else if (!nested_has_guest_tlb_tag(vcpu)) {
1214 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1215 	} else if (is_vmenter &&
1216 		   vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
1217 		vmx->nested.last_vpid = vmcs12->virtual_processor_id;
1218 		vpid_sync_context(nested_get_vpid02(vcpu));
1219 	}
1220 }
1221 
1222 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
1223 {
1224 	superset &= mask;
1225 	subset &= mask;
1226 
1227 	return (superset | subset) == superset;
1228 }
1229 
1230 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
1231 {
1232 	const u64 feature_and_reserved =
1233 		/* feature (except bit 48; see below) */
1234 		BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
1235 		/* reserved */
1236 		BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
1237 	u64 vmx_basic = vmx->nested.msrs.basic;
1238 
1239 	if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
1240 		return -EINVAL;
1241 
1242 	/*
1243 	 * KVM does not emulate a version of VMX that constrains physical
1244 	 * addresses of VMX structures (e.g. VMCS) to 32-bits.
1245 	 */
1246 	if (data & BIT_ULL(48))
1247 		return -EINVAL;
1248 
1249 	if (vmx_basic_vmcs_revision_id(vmx_basic) !=
1250 	    vmx_basic_vmcs_revision_id(data))
1251 		return -EINVAL;
1252 
1253 	if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
1254 		return -EINVAL;
1255 
1256 	vmx->nested.msrs.basic = data;
1257 	return 0;
1258 }
1259 
1260 static int
1261 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
1262 {
1263 	u64 supported;
1264 	u32 *lowp, *highp;
1265 
1266 	switch (msr_index) {
1267 	case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
1268 		lowp = &vmx->nested.msrs.pinbased_ctls_low;
1269 		highp = &vmx->nested.msrs.pinbased_ctls_high;
1270 		break;
1271 	case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
1272 		lowp = &vmx->nested.msrs.procbased_ctls_low;
1273 		highp = &vmx->nested.msrs.procbased_ctls_high;
1274 		break;
1275 	case MSR_IA32_VMX_TRUE_EXIT_CTLS:
1276 		lowp = &vmx->nested.msrs.exit_ctls_low;
1277 		highp = &vmx->nested.msrs.exit_ctls_high;
1278 		break;
1279 	case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
1280 		lowp = &vmx->nested.msrs.entry_ctls_low;
1281 		highp = &vmx->nested.msrs.entry_ctls_high;
1282 		break;
1283 	case MSR_IA32_VMX_PROCBASED_CTLS2:
1284 		lowp = &vmx->nested.msrs.secondary_ctls_low;
1285 		highp = &vmx->nested.msrs.secondary_ctls_high;
1286 		break;
1287 	default:
1288 		BUG();
1289 	}
1290 
1291 	supported = vmx_control_msr(*lowp, *highp);
1292 
1293 	/* Check must-be-1 bits are still 1. */
1294 	if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
1295 		return -EINVAL;
1296 
1297 	/* Check must-be-0 bits are still 0. */
1298 	if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
1299 		return -EINVAL;
1300 
1301 	*lowp = data;
1302 	*highp = data >> 32;
1303 	return 0;
1304 }
1305 
1306 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
1307 {
1308 	const u64 feature_and_reserved_bits =
1309 		/* feature */
1310 		BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
1311 		BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
1312 		/* reserved */
1313 		GENMASK_ULL(13, 9) | BIT_ULL(31);
1314 	u64 vmx_misc;
1315 
1316 	vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
1317 				   vmx->nested.msrs.misc_high);
1318 
1319 	if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
1320 		return -EINVAL;
1321 
1322 	if ((vmx->nested.msrs.pinbased_ctls_high &
1323 	     PIN_BASED_VMX_PREEMPTION_TIMER) &&
1324 	    vmx_misc_preemption_timer_rate(data) !=
1325 	    vmx_misc_preemption_timer_rate(vmx_misc))
1326 		return -EINVAL;
1327 
1328 	if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
1329 		return -EINVAL;
1330 
1331 	if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
1332 		return -EINVAL;
1333 
1334 	if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
1335 		return -EINVAL;
1336 
1337 	vmx->nested.msrs.misc_low = data;
1338 	vmx->nested.msrs.misc_high = data >> 32;
1339 
1340 	return 0;
1341 }
1342 
1343 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
1344 {
1345 	u64 vmx_ept_vpid_cap;
1346 
1347 	vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.msrs.ept_caps,
1348 					   vmx->nested.msrs.vpid_caps);
1349 
1350 	/* Every bit is either reserved or a feature bit. */
1351 	if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
1352 		return -EINVAL;
1353 
1354 	vmx->nested.msrs.ept_caps = data;
1355 	vmx->nested.msrs.vpid_caps = data >> 32;
1356 	return 0;
1357 }
1358 
1359 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
1360 {
1361 	u64 *msr;
1362 
1363 	switch (msr_index) {
1364 	case MSR_IA32_VMX_CR0_FIXED0:
1365 		msr = &vmx->nested.msrs.cr0_fixed0;
1366 		break;
1367 	case MSR_IA32_VMX_CR4_FIXED0:
1368 		msr = &vmx->nested.msrs.cr4_fixed0;
1369 		break;
1370 	default:
1371 		BUG();
1372 	}
1373 
1374 	/*
1375 	 * 1 bits (which indicates bits which "must-be-1" during VMX operation)
1376 	 * must be 1 in the restored value.
1377 	 */
1378 	if (!is_bitwise_subset(data, *msr, -1ULL))
1379 		return -EINVAL;
1380 
1381 	*msr = data;
1382 	return 0;
1383 }
1384 
1385 /*
1386  * Called when userspace is restoring VMX MSRs.
1387  *
1388  * Returns 0 on success, non-0 otherwise.
1389  */
1390 int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
1391 {
1392 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1393 
1394 	/*
1395 	 * Don't allow changes to the VMX capability MSRs while the vCPU
1396 	 * is in VMX operation.
1397 	 */
1398 	if (vmx->nested.vmxon)
1399 		return -EBUSY;
1400 
1401 	switch (msr_index) {
1402 	case MSR_IA32_VMX_BASIC:
1403 		return vmx_restore_vmx_basic(vmx, data);
1404 	case MSR_IA32_VMX_PINBASED_CTLS:
1405 	case MSR_IA32_VMX_PROCBASED_CTLS:
1406 	case MSR_IA32_VMX_EXIT_CTLS:
1407 	case MSR_IA32_VMX_ENTRY_CTLS:
1408 		/*
1409 		 * The "non-true" VMX capability MSRs are generated from the
1410 		 * "true" MSRs, so we do not support restoring them directly.
1411 		 *
1412 		 * If userspace wants to emulate VMX_BASIC[55]=0, userspace
1413 		 * should restore the "true" MSRs with the must-be-1 bits
1414 		 * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
1415 		 * DEFAULT SETTINGS".
1416 		 */
1417 		return -EINVAL;
1418 	case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
1419 	case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
1420 	case MSR_IA32_VMX_TRUE_EXIT_CTLS:
1421 	case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
1422 	case MSR_IA32_VMX_PROCBASED_CTLS2:
1423 		return vmx_restore_control_msr(vmx, msr_index, data);
1424 	case MSR_IA32_VMX_MISC:
1425 		return vmx_restore_vmx_misc(vmx, data);
1426 	case MSR_IA32_VMX_CR0_FIXED0:
1427 	case MSR_IA32_VMX_CR4_FIXED0:
1428 		return vmx_restore_fixed0_msr(vmx, msr_index, data);
1429 	case MSR_IA32_VMX_CR0_FIXED1:
1430 	case MSR_IA32_VMX_CR4_FIXED1:
1431 		/*
1432 		 * These MSRs are generated based on the vCPU's CPUID, so we
1433 		 * do not support restoring them directly.
1434 		 */
1435 		return -EINVAL;
1436 	case MSR_IA32_VMX_EPT_VPID_CAP:
1437 		return vmx_restore_vmx_ept_vpid_cap(vmx, data);
1438 	case MSR_IA32_VMX_VMCS_ENUM:
1439 		vmx->nested.msrs.vmcs_enum = data;
1440 		return 0;
1441 	case MSR_IA32_VMX_VMFUNC:
1442 		if (data & ~vmx->nested.msrs.vmfunc_controls)
1443 			return -EINVAL;
1444 		vmx->nested.msrs.vmfunc_controls = data;
1445 		return 0;
1446 	default:
1447 		/*
1448 		 * The rest of the VMX capability MSRs do not support restore.
1449 		 */
1450 		return -EINVAL;
1451 	}
1452 }
1453 
1454 /* Returns 0 on success, non-0 otherwise. */
1455 int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
1456 {
1457 	switch (msr_index) {
1458 	case MSR_IA32_VMX_BASIC:
1459 		*pdata = msrs->basic;
1460 		break;
1461 	case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
1462 	case MSR_IA32_VMX_PINBASED_CTLS:
1463 		*pdata = vmx_control_msr(
1464 			msrs->pinbased_ctls_low,
1465 			msrs->pinbased_ctls_high);
1466 		if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
1467 			*pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
1468 		break;
1469 	case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
1470 	case MSR_IA32_VMX_PROCBASED_CTLS:
1471 		*pdata = vmx_control_msr(
1472 			msrs->procbased_ctls_low,
1473 			msrs->procbased_ctls_high);
1474 		if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
1475 			*pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
1476 		break;
1477 	case MSR_IA32_VMX_TRUE_EXIT_CTLS:
1478 	case MSR_IA32_VMX_EXIT_CTLS:
1479 		*pdata = vmx_control_msr(
1480 			msrs->exit_ctls_low,
1481 			msrs->exit_ctls_high);
1482 		if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
1483 			*pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
1484 		break;
1485 	case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
1486 	case MSR_IA32_VMX_ENTRY_CTLS:
1487 		*pdata = vmx_control_msr(
1488 			msrs->entry_ctls_low,
1489 			msrs->entry_ctls_high);
1490 		if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
1491 			*pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
1492 		break;
1493 	case MSR_IA32_VMX_MISC:
1494 		*pdata = vmx_control_msr(
1495 			msrs->misc_low,
1496 			msrs->misc_high);
1497 		break;
1498 	case MSR_IA32_VMX_CR0_FIXED0:
1499 		*pdata = msrs->cr0_fixed0;
1500 		break;
1501 	case MSR_IA32_VMX_CR0_FIXED1:
1502 		*pdata = msrs->cr0_fixed1;
1503 		break;
1504 	case MSR_IA32_VMX_CR4_FIXED0:
1505 		*pdata = msrs->cr4_fixed0;
1506 		break;
1507 	case MSR_IA32_VMX_CR4_FIXED1:
1508 		*pdata = msrs->cr4_fixed1;
1509 		break;
1510 	case MSR_IA32_VMX_VMCS_ENUM:
1511 		*pdata = msrs->vmcs_enum;
1512 		break;
1513 	case MSR_IA32_VMX_PROCBASED_CTLS2:
1514 		*pdata = vmx_control_msr(
1515 			msrs->secondary_ctls_low,
1516 			msrs->secondary_ctls_high);
1517 		break;
1518 	case MSR_IA32_VMX_EPT_VPID_CAP:
1519 		*pdata = msrs->ept_caps |
1520 			((u64)msrs->vpid_caps << 32);
1521 		break;
1522 	case MSR_IA32_VMX_VMFUNC:
1523 		*pdata = msrs->vmfunc_controls;
1524 		break;
1525 	default:
1526 		return 1;
1527 	}
1528 
1529 	return 0;
1530 }
1531 
1532 /*
1533  * Copy the writable VMCS shadow fields back to the VMCS12, in case they have
1534  * been modified by the L1 guest.  Note, "writable" in this context means
1535  * "writable by the guest", i.e. tagged SHADOW_FIELD_RW; the set of
1536  * fields tagged SHADOW_FIELD_RO may or may not align with the "read-only"
1537  * VM-exit information fields (which are actually writable if the vCPU is
1538  * configured to support "VMWRITE to any supported field in the VMCS").
1539  */
1540 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
1541 {
1542 	struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
1543 	struct vmcs12 *vmcs12 = get_vmcs12(&vmx->vcpu);
1544 	struct shadow_vmcs_field field;
1545 	unsigned long val;
1546 	int i;
1547 
1548 	if (WARN_ON(!shadow_vmcs))
1549 		return;
1550 
1551 	preempt_disable();
1552 
1553 	vmcs_load(shadow_vmcs);
1554 
1555 	for (i = 0; i < max_shadow_read_write_fields; i++) {
1556 		field = shadow_read_write_fields[i];
1557 		val = __vmcs_readl(field.encoding);
1558 		vmcs12_write_any(vmcs12, field.encoding, field.offset, val);
1559 	}
1560 
1561 	vmcs_clear(shadow_vmcs);
1562 	vmcs_load(vmx->loaded_vmcs->vmcs);
1563 
1564 	preempt_enable();
1565 }
1566 
1567 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
1568 {
1569 	const struct shadow_vmcs_field *fields[] = {
1570 		shadow_read_write_fields,
1571 		shadow_read_only_fields
1572 	};
1573 	const int max_fields[] = {
1574 		max_shadow_read_write_fields,
1575 		max_shadow_read_only_fields
1576 	};
1577 	struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
1578 	struct vmcs12 *vmcs12 = get_vmcs12(&vmx->vcpu);
1579 	struct shadow_vmcs_field field;
1580 	unsigned long val;
1581 	int i, q;
1582 
1583 	if (WARN_ON(!shadow_vmcs))
1584 		return;
1585 
1586 	vmcs_load(shadow_vmcs);
1587 
1588 	for (q = 0; q < ARRAY_SIZE(fields); q++) {
1589 		for (i = 0; i < max_fields[q]; i++) {
1590 			field = fields[q][i];
1591 			val = vmcs12_read_any(vmcs12, field.encoding,
1592 					      field.offset);
1593 			__vmcs_writel(field.encoding, val);
1594 		}
1595 	}
1596 
1597 	vmcs_clear(shadow_vmcs);
1598 	vmcs_load(vmx->loaded_vmcs->vmcs);
1599 }
1600 
1601 static int copy_enlightened_to_vmcs12(struct vcpu_vmx *vmx)
1602 {
1603 	struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
1604 	struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
1605 
1606 	/* HV_VMX_ENLIGHTENED_CLEAN_FIELD_NONE */
1607 	vmcs12->tpr_threshold = evmcs->tpr_threshold;
1608 	vmcs12->guest_rip = evmcs->guest_rip;
1609 
1610 	if (unlikely(!(evmcs->hv_clean_fields &
1611 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_BASIC))) {
1612 		vmcs12->guest_rsp = evmcs->guest_rsp;
1613 		vmcs12->guest_rflags = evmcs->guest_rflags;
1614 		vmcs12->guest_interruptibility_info =
1615 			evmcs->guest_interruptibility_info;
1616 	}
1617 
1618 	if (unlikely(!(evmcs->hv_clean_fields &
1619 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
1620 		vmcs12->cpu_based_vm_exec_control =
1621 			evmcs->cpu_based_vm_exec_control;
1622 	}
1623 
1624 	if (unlikely(!(evmcs->hv_clean_fields &
1625 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_EXCPN))) {
1626 		vmcs12->exception_bitmap = evmcs->exception_bitmap;
1627 	}
1628 
1629 	if (unlikely(!(evmcs->hv_clean_fields &
1630 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_ENTRY))) {
1631 		vmcs12->vm_entry_controls = evmcs->vm_entry_controls;
1632 	}
1633 
1634 	if (unlikely(!(evmcs->hv_clean_fields &
1635 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_EVENT))) {
1636 		vmcs12->vm_entry_intr_info_field =
1637 			evmcs->vm_entry_intr_info_field;
1638 		vmcs12->vm_entry_exception_error_code =
1639 			evmcs->vm_entry_exception_error_code;
1640 		vmcs12->vm_entry_instruction_len =
1641 			evmcs->vm_entry_instruction_len;
1642 	}
1643 
1644 	if (unlikely(!(evmcs->hv_clean_fields &
1645 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
1646 		vmcs12->host_ia32_pat = evmcs->host_ia32_pat;
1647 		vmcs12->host_ia32_efer = evmcs->host_ia32_efer;
1648 		vmcs12->host_cr0 = evmcs->host_cr0;
1649 		vmcs12->host_cr3 = evmcs->host_cr3;
1650 		vmcs12->host_cr4 = evmcs->host_cr4;
1651 		vmcs12->host_ia32_sysenter_esp = evmcs->host_ia32_sysenter_esp;
1652 		vmcs12->host_ia32_sysenter_eip = evmcs->host_ia32_sysenter_eip;
1653 		vmcs12->host_rip = evmcs->host_rip;
1654 		vmcs12->host_ia32_sysenter_cs = evmcs->host_ia32_sysenter_cs;
1655 		vmcs12->host_es_selector = evmcs->host_es_selector;
1656 		vmcs12->host_cs_selector = evmcs->host_cs_selector;
1657 		vmcs12->host_ss_selector = evmcs->host_ss_selector;
1658 		vmcs12->host_ds_selector = evmcs->host_ds_selector;
1659 		vmcs12->host_fs_selector = evmcs->host_fs_selector;
1660 		vmcs12->host_gs_selector = evmcs->host_gs_selector;
1661 		vmcs12->host_tr_selector = evmcs->host_tr_selector;
1662 	}
1663 
1664 	if (unlikely(!(evmcs->hv_clean_fields &
1665 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_GRP1))) {
1666 		vmcs12->pin_based_vm_exec_control =
1667 			evmcs->pin_based_vm_exec_control;
1668 		vmcs12->vm_exit_controls = evmcs->vm_exit_controls;
1669 		vmcs12->secondary_vm_exec_control =
1670 			evmcs->secondary_vm_exec_control;
1671 	}
1672 
1673 	if (unlikely(!(evmcs->hv_clean_fields &
1674 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_IO_BITMAP))) {
1675 		vmcs12->io_bitmap_a = evmcs->io_bitmap_a;
1676 		vmcs12->io_bitmap_b = evmcs->io_bitmap_b;
1677 	}
1678 
1679 	if (unlikely(!(evmcs->hv_clean_fields &
1680 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP))) {
1681 		vmcs12->msr_bitmap = evmcs->msr_bitmap;
1682 	}
1683 
1684 	if (unlikely(!(evmcs->hv_clean_fields &
1685 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2))) {
1686 		vmcs12->guest_es_base = evmcs->guest_es_base;
1687 		vmcs12->guest_cs_base = evmcs->guest_cs_base;
1688 		vmcs12->guest_ss_base = evmcs->guest_ss_base;
1689 		vmcs12->guest_ds_base = evmcs->guest_ds_base;
1690 		vmcs12->guest_fs_base = evmcs->guest_fs_base;
1691 		vmcs12->guest_gs_base = evmcs->guest_gs_base;
1692 		vmcs12->guest_ldtr_base = evmcs->guest_ldtr_base;
1693 		vmcs12->guest_tr_base = evmcs->guest_tr_base;
1694 		vmcs12->guest_gdtr_base = evmcs->guest_gdtr_base;
1695 		vmcs12->guest_idtr_base = evmcs->guest_idtr_base;
1696 		vmcs12->guest_es_limit = evmcs->guest_es_limit;
1697 		vmcs12->guest_cs_limit = evmcs->guest_cs_limit;
1698 		vmcs12->guest_ss_limit = evmcs->guest_ss_limit;
1699 		vmcs12->guest_ds_limit = evmcs->guest_ds_limit;
1700 		vmcs12->guest_fs_limit = evmcs->guest_fs_limit;
1701 		vmcs12->guest_gs_limit = evmcs->guest_gs_limit;
1702 		vmcs12->guest_ldtr_limit = evmcs->guest_ldtr_limit;
1703 		vmcs12->guest_tr_limit = evmcs->guest_tr_limit;
1704 		vmcs12->guest_gdtr_limit = evmcs->guest_gdtr_limit;
1705 		vmcs12->guest_idtr_limit = evmcs->guest_idtr_limit;
1706 		vmcs12->guest_es_ar_bytes = evmcs->guest_es_ar_bytes;
1707 		vmcs12->guest_cs_ar_bytes = evmcs->guest_cs_ar_bytes;
1708 		vmcs12->guest_ss_ar_bytes = evmcs->guest_ss_ar_bytes;
1709 		vmcs12->guest_ds_ar_bytes = evmcs->guest_ds_ar_bytes;
1710 		vmcs12->guest_fs_ar_bytes = evmcs->guest_fs_ar_bytes;
1711 		vmcs12->guest_gs_ar_bytes = evmcs->guest_gs_ar_bytes;
1712 		vmcs12->guest_ldtr_ar_bytes = evmcs->guest_ldtr_ar_bytes;
1713 		vmcs12->guest_tr_ar_bytes = evmcs->guest_tr_ar_bytes;
1714 		vmcs12->guest_es_selector = evmcs->guest_es_selector;
1715 		vmcs12->guest_cs_selector = evmcs->guest_cs_selector;
1716 		vmcs12->guest_ss_selector = evmcs->guest_ss_selector;
1717 		vmcs12->guest_ds_selector = evmcs->guest_ds_selector;
1718 		vmcs12->guest_fs_selector = evmcs->guest_fs_selector;
1719 		vmcs12->guest_gs_selector = evmcs->guest_gs_selector;
1720 		vmcs12->guest_ldtr_selector = evmcs->guest_ldtr_selector;
1721 		vmcs12->guest_tr_selector = evmcs->guest_tr_selector;
1722 	}
1723 
1724 	if (unlikely(!(evmcs->hv_clean_fields &
1725 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_GRP2))) {
1726 		vmcs12->tsc_offset = evmcs->tsc_offset;
1727 		vmcs12->virtual_apic_page_addr = evmcs->virtual_apic_page_addr;
1728 		vmcs12->xss_exit_bitmap = evmcs->xss_exit_bitmap;
1729 	}
1730 
1731 	if (unlikely(!(evmcs->hv_clean_fields &
1732 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CRDR))) {
1733 		vmcs12->cr0_guest_host_mask = evmcs->cr0_guest_host_mask;
1734 		vmcs12->cr4_guest_host_mask = evmcs->cr4_guest_host_mask;
1735 		vmcs12->cr0_read_shadow = evmcs->cr0_read_shadow;
1736 		vmcs12->cr4_read_shadow = evmcs->cr4_read_shadow;
1737 		vmcs12->guest_cr0 = evmcs->guest_cr0;
1738 		vmcs12->guest_cr3 = evmcs->guest_cr3;
1739 		vmcs12->guest_cr4 = evmcs->guest_cr4;
1740 		vmcs12->guest_dr7 = evmcs->guest_dr7;
1741 	}
1742 
1743 	if (unlikely(!(evmcs->hv_clean_fields &
1744 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_POINTER))) {
1745 		vmcs12->host_fs_base = evmcs->host_fs_base;
1746 		vmcs12->host_gs_base = evmcs->host_gs_base;
1747 		vmcs12->host_tr_base = evmcs->host_tr_base;
1748 		vmcs12->host_gdtr_base = evmcs->host_gdtr_base;
1749 		vmcs12->host_idtr_base = evmcs->host_idtr_base;
1750 		vmcs12->host_rsp = evmcs->host_rsp;
1751 	}
1752 
1753 	if (unlikely(!(evmcs->hv_clean_fields &
1754 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_XLAT))) {
1755 		vmcs12->ept_pointer = evmcs->ept_pointer;
1756 		vmcs12->virtual_processor_id = evmcs->virtual_processor_id;
1757 	}
1758 
1759 	if (unlikely(!(evmcs->hv_clean_fields &
1760 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1))) {
1761 		vmcs12->vmcs_link_pointer = evmcs->vmcs_link_pointer;
1762 		vmcs12->guest_ia32_debugctl = evmcs->guest_ia32_debugctl;
1763 		vmcs12->guest_ia32_pat = evmcs->guest_ia32_pat;
1764 		vmcs12->guest_ia32_efer = evmcs->guest_ia32_efer;
1765 		vmcs12->guest_pdptr0 = evmcs->guest_pdptr0;
1766 		vmcs12->guest_pdptr1 = evmcs->guest_pdptr1;
1767 		vmcs12->guest_pdptr2 = evmcs->guest_pdptr2;
1768 		vmcs12->guest_pdptr3 = evmcs->guest_pdptr3;
1769 		vmcs12->guest_pending_dbg_exceptions =
1770 			evmcs->guest_pending_dbg_exceptions;
1771 		vmcs12->guest_sysenter_esp = evmcs->guest_sysenter_esp;
1772 		vmcs12->guest_sysenter_eip = evmcs->guest_sysenter_eip;
1773 		vmcs12->guest_bndcfgs = evmcs->guest_bndcfgs;
1774 		vmcs12->guest_activity_state = evmcs->guest_activity_state;
1775 		vmcs12->guest_sysenter_cs = evmcs->guest_sysenter_cs;
1776 	}
1777 
1778 	/*
1779 	 * Not used?
1780 	 * vmcs12->vm_exit_msr_store_addr = evmcs->vm_exit_msr_store_addr;
1781 	 * vmcs12->vm_exit_msr_load_addr = evmcs->vm_exit_msr_load_addr;
1782 	 * vmcs12->vm_entry_msr_load_addr = evmcs->vm_entry_msr_load_addr;
1783 	 * vmcs12->page_fault_error_code_mask =
1784 	 *		evmcs->page_fault_error_code_mask;
1785 	 * vmcs12->page_fault_error_code_match =
1786 	 *		evmcs->page_fault_error_code_match;
1787 	 * vmcs12->cr3_target_count = evmcs->cr3_target_count;
1788 	 * vmcs12->vm_exit_msr_store_count = evmcs->vm_exit_msr_store_count;
1789 	 * vmcs12->vm_exit_msr_load_count = evmcs->vm_exit_msr_load_count;
1790 	 * vmcs12->vm_entry_msr_load_count = evmcs->vm_entry_msr_load_count;
1791 	 */
1792 
1793 	/*
1794 	 * Read only fields:
1795 	 * vmcs12->guest_physical_address = evmcs->guest_physical_address;
1796 	 * vmcs12->vm_instruction_error = evmcs->vm_instruction_error;
1797 	 * vmcs12->vm_exit_reason = evmcs->vm_exit_reason;
1798 	 * vmcs12->vm_exit_intr_info = evmcs->vm_exit_intr_info;
1799 	 * vmcs12->vm_exit_intr_error_code = evmcs->vm_exit_intr_error_code;
1800 	 * vmcs12->idt_vectoring_info_field = evmcs->idt_vectoring_info_field;
1801 	 * vmcs12->idt_vectoring_error_code = evmcs->idt_vectoring_error_code;
1802 	 * vmcs12->vm_exit_instruction_len = evmcs->vm_exit_instruction_len;
1803 	 * vmcs12->vmx_instruction_info = evmcs->vmx_instruction_info;
1804 	 * vmcs12->exit_qualification = evmcs->exit_qualification;
1805 	 * vmcs12->guest_linear_address = evmcs->guest_linear_address;
1806 	 *
1807 	 * Not present in struct vmcs12:
1808 	 * vmcs12->exit_io_instruction_ecx = evmcs->exit_io_instruction_ecx;
1809 	 * vmcs12->exit_io_instruction_esi = evmcs->exit_io_instruction_esi;
1810 	 * vmcs12->exit_io_instruction_edi = evmcs->exit_io_instruction_edi;
1811 	 * vmcs12->exit_io_instruction_eip = evmcs->exit_io_instruction_eip;
1812 	 */
1813 
1814 	return 0;
1815 }
1816 
1817 static int copy_vmcs12_to_enlightened(struct vcpu_vmx *vmx)
1818 {
1819 	struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
1820 	struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
1821 
1822 	/*
1823 	 * Should not be changed by KVM:
1824 	 *
1825 	 * evmcs->host_es_selector = vmcs12->host_es_selector;
1826 	 * evmcs->host_cs_selector = vmcs12->host_cs_selector;
1827 	 * evmcs->host_ss_selector = vmcs12->host_ss_selector;
1828 	 * evmcs->host_ds_selector = vmcs12->host_ds_selector;
1829 	 * evmcs->host_fs_selector = vmcs12->host_fs_selector;
1830 	 * evmcs->host_gs_selector = vmcs12->host_gs_selector;
1831 	 * evmcs->host_tr_selector = vmcs12->host_tr_selector;
1832 	 * evmcs->host_ia32_pat = vmcs12->host_ia32_pat;
1833 	 * evmcs->host_ia32_efer = vmcs12->host_ia32_efer;
1834 	 * evmcs->host_cr0 = vmcs12->host_cr0;
1835 	 * evmcs->host_cr3 = vmcs12->host_cr3;
1836 	 * evmcs->host_cr4 = vmcs12->host_cr4;
1837 	 * evmcs->host_ia32_sysenter_esp = vmcs12->host_ia32_sysenter_esp;
1838 	 * evmcs->host_ia32_sysenter_eip = vmcs12->host_ia32_sysenter_eip;
1839 	 * evmcs->host_rip = vmcs12->host_rip;
1840 	 * evmcs->host_ia32_sysenter_cs = vmcs12->host_ia32_sysenter_cs;
1841 	 * evmcs->host_fs_base = vmcs12->host_fs_base;
1842 	 * evmcs->host_gs_base = vmcs12->host_gs_base;
1843 	 * evmcs->host_tr_base = vmcs12->host_tr_base;
1844 	 * evmcs->host_gdtr_base = vmcs12->host_gdtr_base;
1845 	 * evmcs->host_idtr_base = vmcs12->host_idtr_base;
1846 	 * evmcs->host_rsp = vmcs12->host_rsp;
1847 	 * sync_vmcs02_to_vmcs12() doesn't read these:
1848 	 * evmcs->io_bitmap_a = vmcs12->io_bitmap_a;
1849 	 * evmcs->io_bitmap_b = vmcs12->io_bitmap_b;
1850 	 * evmcs->msr_bitmap = vmcs12->msr_bitmap;
1851 	 * evmcs->ept_pointer = vmcs12->ept_pointer;
1852 	 * evmcs->xss_exit_bitmap = vmcs12->xss_exit_bitmap;
1853 	 * evmcs->vm_exit_msr_store_addr = vmcs12->vm_exit_msr_store_addr;
1854 	 * evmcs->vm_exit_msr_load_addr = vmcs12->vm_exit_msr_load_addr;
1855 	 * evmcs->vm_entry_msr_load_addr = vmcs12->vm_entry_msr_load_addr;
1856 	 * evmcs->tpr_threshold = vmcs12->tpr_threshold;
1857 	 * evmcs->virtual_processor_id = vmcs12->virtual_processor_id;
1858 	 * evmcs->exception_bitmap = vmcs12->exception_bitmap;
1859 	 * evmcs->vmcs_link_pointer = vmcs12->vmcs_link_pointer;
1860 	 * evmcs->pin_based_vm_exec_control = vmcs12->pin_based_vm_exec_control;
1861 	 * evmcs->vm_exit_controls = vmcs12->vm_exit_controls;
1862 	 * evmcs->secondary_vm_exec_control = vmcs12->secondary_vm_exec_control;
1863 	 * evmcs->page_fault_error_code_mask =
1864 	 *		vmcs12->page_fault_error_code_mask;
1865 	 * evmcs->page_fault_error_code_match =
1866 	 *		vmcs12->page_fault_error_code_match;
1867 	 * evmcs->cr3_target_count = vmcs12->cr3_target_count;
1868 	 * evmcs->virtual_apic_page_addr = vmcs12->virtual_apic_page_addr;
1869 	 * evmcs->tsc_offset = vmcs12->tsc_offset;
1870 	 * evmcs->guest_ia32_debugctl = vmcs12->guest_ia32_debugctl;
1871 	 * evmcs->cr0_guest_host_mask = vmcs12->cr0_guest_host_mask;
1872 	 * evmcs->cr4_guest_host_mask = vmcs12->cr4_guest_host_mask;
1873 	 * evmcs->cr0_read_shadow = vmcs12->cr0_read_shadow;
1874 	 * evmcs->cr4_read_shadow = vmcs12->cr4_read_shadow;
1875 	 * evmcs->vm_exit_msr_store_count = vmcs12->vm_exit_msr_store_count;
1876 	 * evmcs->vm_exit_msr_load_count = vmcs12->vm_exit_msr_load_count;
1877 	 * evmcs->vm_entry_msr_load_count = vmcs12->vm_entry_msr_load_count;
1878 	 *
1879 	 * Not present in struct vmcs12:
1880 	 * evmcs->exit_io_instruction_ecx = vmcs12->exit_io_instruction_ecx;
1881 	 * evmcs->exit_io_instruction_esi = vmcs12->exit_io_instruction_esi;
1882 	 * evmcs->exit_io_instruction_edi = vmcs12->exit_io_instruction_edi;
1883 	 * evmcs->exit_io_instruction_eip = vmcs12->exit_io_instruction_eip;
1884 	 */
1885 
1886 	evmcs->guest_es_selector = vmcs12->guest_es_selector;
1887 	evmcs->guest_cs_selector = vmcs12->guest_cs_selector;
1888 	evmcs->guest_ss_selector = vmcs12->guest_ss_selector;
1889 	evmcs->guest_ds_selector = vmcs12->guest_ds_selector;
1890 	evmcs->guest_fs_selector = vmcs12->guest_fs_selector;
1891 	evmcs->guest_gs_selector = vmcs12->guest_gs_selector;
1892 	evmcs->guest_ldtr_selector = vmcs12->guest_ldtr_selector;
1893 	evmcs->guest_tr_selector = vmcs12->guest_tr_selector;
1894 
1895 	evmcs->guest_es_limit = vmcs12->guest_es_limit;
1896 	evmcs->guest_cs_limit = vmcs12->guest_cs_limit;
1897 	evmcs->guest_ss_limit = vmcs12->guest_ss_limit;
1898 	evmcs->guest_ds_limit = vmcs12->guest_ds_limit;
1899 	evmcs->guest_fs_limit = vmcs12->guest_fs_limit;
1900 	evmcs->guest_gs_limit = vmcs12->guest_gs_limit;
1901 	evmcs->guest_ldtr_limit = vmcs12->guest_ldtr_limit;
1902 	evmcs->guest_tr_limit = vmcs12->guest_tr_limit;
1903 	evmcs->guest_gdtr_limit = vmcs12->guest_gdtr_limit;
1904 	evmcs->guest_idtr_limit = vmcs12->guest_idtr_limit;
1905 
1906 	evmcs->guest_es_ar_bytes = vmcs12->guest_es_ar_bytes;
1907 	evmcs->guest_cs_ar_bytes = vmcs12->guest_cs_ar_bytes;
1908 	evmcs->guest_ss_ar_bytes = vmcs12->guest_ss_ar_bytes;
1909 	evmcs->guest_ds_ar_bytes = vmcs12->guest_ds_ar_bytes;
1910 	evmcs->guest_fs_ar_bytes = vmcs12->guest_fs_ar_bytes;
1911 	evmcs->guest_gs_ar_bytes = vmcs12->guest_gs_ar_bytes;
1912 	evmcs->guest_ldtr_ar_bytes = vmcs12->guest_ldtr_ar_bytes;
1913 	evmcs->guest_tr_ar_bytes = vmcs12->guest_tr_ar_bytes;
1914 
1915 	evmcs->guest_es_base = vmcs12->guest_es_base;
1916 	evmcs->guest_cs_base = vmcs12->guest_cs_base;
1917 	evmcs->guest_ss_base = vmcs12->guest_ss_base;
1918 	evmcs->guest_ds_base = vmcs12->guest_ds_base;
1919 	evmcs->guest_fs_base = vmcs12->guest_fs_base;
1920 	evmcs->guest_gs_base = vmcs12->guest_gs_base;
1921 	evmcs->guest_ldtr_base = vmcs12->guest_ldtr_base;
1922 	evmcs->guest_tr_base = vmcs12->guest_tr_base;
1923 	evmcs->guest_gdtr_base = vmcs12->guest_gdtr_base;
1924 	evmcs->guest_idtr_base = vmcs12->guest_idtr_base;
1925 
1926 	evmcs->guest_ia32_pat = vmcs12->guest_ia32_pat;
1927 	evmcs->guest_ia32_efer = vmcs12->guest_ia32_efer;
1928 
1929 	evmcs->guest_pdptr0 = vmcs12->guest_pdptr0;
1930 	evmcs->guest_pdptr1 = vmcs12->guest_pdptr1;
1931 	evmcs->guest_pdptr2 = vmcs12->guest_pdptr2;
1932 	evmcs->guest_pdptr3 = vmcs12->guest_pdptr3;
1933 
1934 	evmcs->guest_pending_dbg_exceptions =
1935 		vmcs12->guest_pending_dbg_exceptions;
1936 	evmcs->guest_sysenter_esp = vmcs12->guest_sysenter_esp;
1937 	evmcs->guest_sysenter_eip = vmcs12->guest_sysenter_eip;
1938 
1939 	evmcs->guest_activity_state = vmcs12->guest_activity_state;
1940 	evmcs->guest_sysenter_cs = vmcs12->guest_sysenter_cs;
1941 
1942 	evmcs->guest_cr0 = vmcs12->guest_cr0;
1943 	evmcs->guest_cr3 = vmcs12->guest_cr3;
1944 	evmcs->guest_cr4 = vmcs12->guest_cr4;
1945 	evmcs->guest_dr7 = vmcs12->guest_dr7;
1946 
1947 	evmcs->guest_physical_address = vmcs12->guest_physical_address;
1948 
1949 	evmcs->vm_instruction_error = vmcs12->vm_instruction_error;
1950 	evmcs->vm_exit_reason = vmcs12->vm_exit_reason;
1951 	evmcs->vm_exit_intr_info = vmcs12->vm_exit_intr_info;
1952 	evmcs->vm_exit_intr_error_code = vmcs12->vm_exit_intr_error_code;
1953 	evmcs->idt_vectoring_info_field = vmcs12->idt_vectoring_info_field;
1954 	evmcs->idt_vectoring_error_code = vmcs12->idt_vectoring_error_code;
1955 	evmcs->vm_exit_instruction_len = vmcs12->vm_exit_instruction_len;
1956 	evmcs->vmx_instruction_info = vmcs12->vmx_instruction_info;
1957 
1958 	evmcs->exit_qualification = vmcs12->exit_qualification;
1959 
1960 	evmcs->guest_linear_address = vmcs12->guest_linear_address;
1961 	evmcs->guest_rsp = vmcs12->guest_rsp;
1962 	evmcs->guest_rflags = vmcs12->guest_rflags;
1963 
1964 	evmcs->guest_interruptibility_info =
1965 		vmcs12->guest_interruptibility_info;
1966 	evmcs->cpu_based_vm_exec_control = vmcs12->cpu_based_vm_exec_control;
1967 	evmcs->vm_entry_controls = vmcs12->vm_entry_controls;
1968 	evmcs->vm_entry_intr_info_field = vmcs12->vm_entry_intr_info_field;
1969 	evmcs->vm_entry_exception_error_code =
1970 		vmcs12->vm_entry_exception_error_code;
1971 	evmcs->vm_entry_instruction_len = vmcs12->vm_entry_instruction_len;
1972 
1973 	evmcs->guest_rip = vmcs12->guest_rip;
1974 
1975 	evmcs->guest_bndcfgs = vmcs12->guest_bndcfgs;
1976 
1977 	return 0;
1978 }
1979 
1980 /*
1981  * This is an equivalent of the nested hypervisor executing the vmptrld
1982  * instruction.
1983  */
1984 static enum nested_evmptrld_status nested_vmx_handle_enlightened_vmptrld(
1985 	struct kvm_vcpu *vcpu, bool from_launch)
1986 {
1987 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1988 	bool evmcs_gpa_changed = false;
1989 	u64 evmcs_gpa;
1990 
1991 	if (likely(!vmx->nested.enlightened_vmcs_enabled))
1992 		return EVMPTRLD_DISABLED;
1993 
1994 	if (!nested_enlightened_vmentry(vcpu, &evmcs_gpa))
1995 		return EVMPTRLD_DISABLED;
1996 
1997 	if (unlikely(!vmx->nested.hv_evmcs ||
1998 		     evmcs_gpa != vmx->nested.hv_evmcs_vmptr)) {
1999 		if (!vmx->nested.hv_evmcs)
2000 			vmx->nested.current_vmptr = -1ull;
2001 
2002 		nested_release_evmcs(vcpu);
2003 
2004 		if (kvm_vcpu_map(vcpu, gpa_to_gfn(evmcs_gpa),
2005 				 &vmx->nested.hv_evmcs_map))
2006 			return EVMPTRLD_ERROR;
2007 
2008 		vmx->nested.hv_evmcs = vmx->nested.hv_evmcs_map.hva;
2009 
2010 		/*
2011 		 * Currently, KVM only supports eVMCS version 1
2012 		 * (== KVM_EVMCS_VERSION) and thus we expect guest to set this
2013 		 * value to first u32 field of eVMCS which should specify eVMCS
2014 		 * VersionNumber.
2015 		 *
2016 		 * Guest should be aware of supported eVMCS versions by host by
2017 		 * examining CPUID.0x4000000A.EAX[0:15]. Host userspace VMM is
2018 		 * expected to set this CPUID leaf according to the value
2019 		 * returned in vmcs_version from nested_enable_evmcs().
2020 		 *
2021 		 * However, it turns out that Microsoft Hyper-V fails to comply
2022 		 * to their own invented interface: When Hyper-V use eVMCS, it
2023 		 * just sets first u32 field of eVMCS to revision_id specified
2024 		 * in MSR_IA32_VMX_BASIC. Instead of used eVMCS version number
2025 		 * which is one of the supported versions specified in
2026 		 * CPUID.0x4000000A.EAX[0:15].
2027 		 *
2028 		 * To overcome Hyper-V bug, we accept here either a supported
2029 		 * eVMCS version or VMCS12 revision_id as valid values for first
2030 		 * u32 field of eVMCS.
2031 		 */
2032 		if ((vmx->nested.hv_evmcs->revision_id != KVM_EVMCS_VERSION) &&
2033 		    (vmx->nested.hv_evmcs->revision_id != VMCS12_REVISION)) {
2034 			nested_release_evmcs(vcpu);
2035 			return EVMPTRLD_VMFAIL;
2036 		}
2037 
2038 		vmx->nested.dirty_vmcs12 = true;
2039 		vmx->nested.hv_evmcs_vmptr = evmcs_gpa;
2040 
2041 		evmcs_gpa_changed = true;
2042 		/*
2043 		 * Unlike normal vmcs12, enlightened vmcs12 is not fully
2044 		 * reloaded from guest's memory (read only fields, fields not
2045 		 * present in struct hv_enlightened_vmcs, ...). Make sure there
2046 		 * are no leftovers.
2047 		 */
2048 		if (from_launch) {
2049 			struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2050 			memset(vmcs12, 0, sizeof(*vmcs12));
2051 			vmcs12->hdr.revision_id = VMCS12_REVISION;
2052 		}
2053 
2054 	}
2055 
2056 	/*
2057 	 * Clean fields data can't be used on VMLAUNCH and when we switch
2058 	 * between different L2 guests as KVM keeps a single VMCS12 per L1.
2059 	 */
2060 	if (from_launch || evmcs_gpa_changed)
2061 		vmx->nested.hv_evmcs->hv_clean_fields &=
2062 			~HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
2063 
2064 	return EVMPTRLD_SUCCEEDED;
2065 }
2066 
2067 void nested_sync_vmcs12_to_shadow(struct kvm_vcpu *vcpu)
2068 {
2069 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2070 
2071 	if (vmx->nested.hv_evmcs) {
2072 		copy_vmcs12_to_enlightened(vmx);
2073 		/* All fields are clean */
2074 		vmx->nested.hv_evmcs->hv_clean_fields |=
2075 			HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
2076 	} else {
2077 		copy_vmcs12_to_shadow(vmx);
2078 	}
2079 
2080 	vmx->nested.need_vmcs12_to_shadow_sync = false;
2081 }
2082 
2083 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
2084 {
2085 	struct vcpu_vmx *vmx =
2086 		container_of(timer, struct vcpu_vmx, nested.preemption_timer);
2087 
2088 	vmx->nested.preemption_timer_expired = true;
2089 	kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
2090 	kvm_vcpu_kick(&vmx->vcpu);
2091 
2092 	return HRTIMER_NORESTART;
2093 }
2094 
2095 static u64 vmx_calc_preemption_timer_value(struct kvm_vcpu *vcpu)
2096 {
2097 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2098 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2099 
2100 	u64 l1_scaled_tsc = kvm_read_l1_tsc(vcpu, rdtsc()) >>
2101 			    VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
2102 
2103 	if (!vmx->nested.has_preemption_timer_deadline) {
2104 		vmx->nested.preemption_timer_deadline =
2105 			vmcs12->vmx_preemption_timer_value + l1_scaled_tsc;
2106 		vmx->nested.has_preemption_timer_deadline = true;
2107 	}
2108 	return vmx->nested.preemption_timer_deadline - l1_scaled_tsc;
2109 }
2110 
2111 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu,
2112 					u64 preemption_timeout)
2113 {
2114 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2115 
2116 	/*
2117 	 * A timer value of zero is architecturally guaranteed to cause
2118 	 * a VMExit prior to executing any instructions in the guest.
2119 	 */
2120 	if (preemption_timeout == 0) {
2121 		vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
2122 		return;
2123 	}
2124 
2125 	if (vcpu->arch.virtual_tsc_khz == 0)
2126 		return;
2127 
2128 	preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
2129 	preemption_timeout *= 1000000;
2130 	do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
2131 	hrtimer_start(&vmx->nested.preemption_timer,
2132 		      ktime_add_ns(ktime_get(), preemption_timeout),
2133 		      HRTIMER_MODE_ABS_PINNED);
2134 }
2135 
2136 static u64 nested_vmx_calc_efer(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2137 {
2138 	if (vmx->nested.nested_run_pending &&
2139 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
2140 		return vmcs12->guest_ia32_efer;
2141 	else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
2142 		return vmx->vcpu.arch.efer | (EFER_LMA | EFER_LME);
2143 	else
2144 		return vmx->vcpu.arch.efer & ~(EFER_LMA | EFER_LME);
2145 }
2146 
2147 static void prepare_vmcs02_constant_state(struct vcpu_vmx *vmx)
2148 {
2149 	/*
2150 	 * If vmcs02 hasn't been initialized, set the constant vmcs02 state
2151 	 * according to L0's settings (vmcs12 is irrelevant here).  Host
2152 	 * fields that come from L0 and are not constant, e.g. HOST_CR3,
2153 	 * will be set as needed prior to VMLAUNCH/VMRESUME.
2154 	 */
2155 	if (vmx->nested.vmcs02_initialized)
2156 		return;
2157 	vmx->nested.vmcs02_initialized = true;
2158 
2159 	/*
2160 	 * We don't care what the EPTP value is we just need to guarantee
2161 	 * it's valid so we don't get a false positive when doing early
2162 	 * consistency checks.
2163 	 */
2164 	if (enable_ept && nested_early_check)
2165 		vmcs_write64(EPT_POINTER,
2166 			     construct_eptp(&vmx->vcpu, 0, PT64_ROOT_4LEVEL));
2167 
2168 	/* All VMFUNCs are currently emulated through L0 vmexits.  */
2169 	if (cpu_has_vmx_vmfunc())
2170 		vmcs_write64(VM_FUNCTION_CONTROL, 0);
2171 
2172 	if (cpu_has_vmx_posted_intr())
2173 		vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
2174 
2175 	if (cpu_has_vmx_msr_bitmap())
2176 		vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
2177 
2178 	/*
2179 	 * The PML address never changes, so it is constant in vmcs02.
2180 	 * Conceptually we want to copy the PML index from vmcs01 here,
2181 	 * and then back to vmcs01 on nested vmexit.  But since we flush
2182 	 * the log and reset GUEST_PML_INDEX on each vmexit, the PML
2183 	 * index is also effectively constant in vmcs02.
2184 	 */
2185 	if (enable_pml) {
2186 		vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
2187 		vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
2188 	}
2189 
2190 	if (cpu_has_vmx_encls_vmexit())
2191 		vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
2192 
2193 	/*
2194 	 * Set the MSR load/store lists to match L0's settings.  Only the
2195 	 * addresses are constant (for vmcs02), the counts can change based
2196 	 * on L2's behavior, e.g. switching to/from long mode.
2197 	 */
2198 	vmcs_write64(VM_EXIT_MSR_STORE_ADDR, __pa(vmx->msr_autostore.guest.val));
2199 	vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
2200 	vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
2201 
2202 	vmx_set_constant_host_state(vmx);
2203 }
2204 
2205 static void prepare_vmcs02_early_rare(struct vcpu_vmx *vmx,
2206 				      struct vmcs12 *vmcs12)
2207 {
2208 	prepare_vmcs02_constant_state(vmx);
2209 
2210 	vmcs_write64(VMCS_LINK_POINTER, -1ull);
2211 
2212 	if (enable_vpid) {
2213 		if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
2214 			vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
2215 		else
2216 			vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
2217 	}
2218 }
2219 
2220 static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2221 {
2222 	u32 exec_control, vmcs12_exec_ctrl;
2223 	u64 guest_efer = nested_vmx_calc_efer(vmx, vmcs12);
2224 
2225 	if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs)
2226 		prepare_vmcs02_early_rare(vmx, vmcs12);
2227 
2228 	/*
2229 	 * PIN CONTROLS
2230 	 */
2231 	exec_control = vmx_pin_based_exec_ctrl(vmx);
2232 	exec_control |= (vmcs12->pin_based_vm_exec_control &
2233 			 ~PIN_BASED_VMX_PREEMPTION_TIMER);
2234 
2235 	/* Posted interrupts setting is only taken from vmcs12.  */
2236 	if (nested_cpu_has_posted_intr(vmcs12)) {
2237 		vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
2238 		vmx->nested.pi_pending = false;
2239 	} else {
2240 		exec_control &= ~PIN_BASED_POSTED_INTR;
2241 	}
2242 	pin_controls_set(vmx, exec_control);
2243 
2244 	/*
2245 	 * EXEC CONTROLS
2246 	 */
2247 	exec_control = vmx_exec_control(vmx); /* L0's desires */
2248 	exec_control &= ~CPU_BASED_INTR_WINDOW_EXITING;
2249 	exec_control &= ~CPU_BASED_NMI_WINDOW_EXITING;
2250 	exec_control &= ~CPU_BASED_TPR_SHADOW;
2251 	exec_control |= vmcs12->cpu_based_vm_exec_control;
2252 
2253 	vmx->nested.l1_tpr_threshold = -1;
2254 	if (exec_control & CPU_BASED_TPR_SHADOW)
2255 		vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
2256 #ifdef CONFIG_X86_64
2257 	else
2258 		exec_control |= CPU_BASED_CR8_LOAD_EXITING |
2259 				CPU_BASED_CR8_STORE_EXITING;
2260 #endif
2261 
2262 	/*
2263 	 * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
2264 	 * for I/O port accesses.
2265 	 */
2266 	exec_control |= CPU_BASED_UNCOND_IO_EXITING;
2267 	exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
2268 
2269 	/*
2270 	 * This bit will be computed in nested_get_vmcs12_pages, because
2271 	 * we do not have access to L1's MSR bitmap yet.  For now, keep
2272 	 * the same bit as before, hoping to avoid multiple VMWRITEs that
2273 	 * only set/clear this bit.
2274 	 */
2275 	exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
2276 	exec_control |= exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS;
2277 
2278 	exec_controls_set(vmx, exec_control);
2279 
2280 	/*
2281 	 * SECONDARY EXEC CONTROLS
2282 	 */
2283 	if (cpu_has_secondary_exec_ctrls()) {
2284 		exec_control = vmx->secondary_exec_control;
2285 
2286 		/* Take the following fields only from vmcs12 */
2287 		exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2288 				  SECONDARY_EXEC_ENABLE_INVPCID |
2289 				  SECONDARY_EXEC_RDTSCP |
2290 				  SECONDARY_EXEC_XSAVES |
2291 				  SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2292 				  SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2293 				  SECONDARY_EXEC_APIC_REGISTER_VIRT |
2294 				  SECONDARY_EXEC_ENABLE_VMFUNC);
2295 		if (nested_cpu_has(vmcs12,
2296 				   CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
2297 			vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
2298 				~SECONDARY_EXEC_ENABLE_PML;
2299 			exec_control |= vmcs12_exec_ctrl;
2300 		}
2301 
2302 		/* VMCS shadowing for L2 is emulated for now */
2303 		exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
2304 
2305 		/*
2306 		 * Preset *DT exiting when emulating UMIP, so that vmx_set_cr4()
2307 		 * will not have to rewrite the controls just for this bit.
2308 		 */
2309 		if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated() &&
2310 		    (vmcs12->guest_cr4 & X86_CR4_UMIP))
2311 			exec_control |= SECONDARY_EXEC_DESC;
2312 
2313 		if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
2314 			vmcs_write16(GUEST_INTR_STATUS,
2315 				vmcs12->guest_intr_status);
2316 
2317 		secondary_exec_controls_set(vmx, exec_control);
2318 	}
2319 
2320 	/*
2321 	 * ENTRY CONTROLS
2322 	 *
2323 	 * vmcs12's VM_{ENTRY,EXIT}_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE
2324 	 * are emulated by vmx_set_efer() in prepare_vmcs02(), but speculate
2325 	 * on the related bits (if supported by the CPU) in the hope that
2326 	 * we can avoid VMWrites during vmx_set_efer().
2327 	 */
2328 	exec_control = (vmcs12->vm_entry_controls | vmx_vmentry_ctrl()) &
2329 			~VM_ENTRY_IA32E_MODE & ~VM_ENTRY_LOAD_IA32_EFER;
2330 	if (cpu_has_load_ia32_efer()) {
2331 		if (guest_efer & EFER_LMA)
2332 			exec_control |= VM_ENTRY_IA32E_MODE;
2333 		if (guest_efer != host_efer)
2334 			exec_control |= VM_ENTRY_LOAD_IA32_EFER;
2335 	}
2336 	vm_entry_controls_set(vmx, exec_control);
2337 
2338 	/*
2339 	 * EXIT CONTROLS
2340 	 *
2341 	 * L2->L1 exit controls are emulated - the hardware exit is to L0 so
2342 	 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
2343 	 * bits may be modified by vmx_set_efer() in prepare_vmcs02().
2344 	 */
2345 	exec_control = vmx_vmexit_ctrl();
2346 	if (cpu_has_load_ia32_efer() && guest_efer != host_efer)
2347 		exec_control |= VM_EXIT_LOAD_IA32_EFER;
2348 	vm_exit_controls_set(vmx, exec_control);
2349 
2350 	/*
2351 	 * Interrupt/Exception Fields
2352 	 */
2353 	if (vmx->nested.nested_run_pending) {
2354 		vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2355 			     vmcs12->vm_entry_intr_info_field);
2356 		vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
2357 			     vmcs12->vm_entry_exception_error_code);
2358 		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2359 			     vmcs12->vm_entry_instruction_len);
2360 		vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
2361 			     vmcs12->guest_interruptibility_info);
2362 		vmx->loaded_vmcs->nmi_known_unmasked =
2363 			!(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
2364 	} else {
2365 		vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
2366 	}
2367 }
2368 
2369 static void prepare_vmcs02_rare(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2370 {
2371 	struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
2372 
2373 	if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
2374 			   HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
2375 		vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
2376 		vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
2377 		vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
2378 		vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
2379 		vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
2380 		vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
2381 		vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
2382 		vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
2383 		vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
2384 		vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
2385 		vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
2386 		vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
2387 		vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
2388 		vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
2389 		vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
2390 		vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
2391 		vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
2392 		vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
2393 		vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
2394 		vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
2395 		vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
2396 		vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
2397 		vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
2398 		vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
2399 		vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
2400 		vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
2401 		vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
2402 		vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
2403 		vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
2404 		vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
2405 		vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
2406 		vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
2407 		vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
2408 		vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
2409 		vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
2410 		vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
2411 	}
2412 
2413 	if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
2414 			   HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1)) {
2415 		vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
2416 		vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
2417 			    vmcs12->guest_pending_dbg_exceptions);
2418 		vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
2419 		vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
2420 
2421 		/*
2422 		 * L1 may access the L2's PDPTR, so save them to construct
2423 		 * vmcs12
2424 		 */
2425 		if (enable_ept) {
2426 			vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
2427 			vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
2428 			vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
2429 			vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
2430 		}
2431 
2432 		if (kvm_mpx_supported() && vmx->nested.nested_run_pending &&
2433 		    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
2434 			vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
2435 	}
2436 
2437 	if (nested_cpu_has_xsaves(vmcs12))
2438 		vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
2439 
2440 	/*
2441 	 * Whether page-faults are trapped is determined by a combination of
2442 	 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.  If L0
2443 	 * doesn't care about page faults then we should set all of these to
2444 	 * L1's desires. However, if L0 does care about (some) page faults, it
2445 	 * is not easy (if at all possible?) to merge L0 and L1's desires, we
2446 	 * simply ask to exit on each and every L2 page fault. This is done by
2447 	 * setting MASK=MATCH=0 and (see below) EB.PF=1.
2448 	 * Note that below we don't need special code to set EB.PF beyond the
2449 	 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
2450 	 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
2451 	 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
2452 	 */
2453 	if (vmx_need_pf_intercept(&vmx->vcpu)) {
2454 		/*
2455 		 * TODO: if both L0 and L1 need the same MASK and MATCH,
2456 		 * go ahead and use it?
2457 		 */
2458 		vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
2459 		vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
2460 	} else {
2461 		vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, vmcs12->page_fault_error_code_mask);
2462 		vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, vmcs12->page_fault_error_code_match);
2463 	}
2464 
2465 	if (cpu_has_vmx_apicv()) {
2466 		vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
2467 		vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
2468 		vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
2469 		vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
2470 	}
2471 
2472 	/*
2473 	 * Make sure the msr_autostore list is up to date before we set the
2474 	 * count in the vmcs02.
2475 	 */
2476 	prepare_vmx_msr_autostore_list(&vmx->vcpu, MSR_IA32_TSC);
2477 
2478 	vmcs_write32(VM_EXIT_MSR_STORE_COUNT, vmx->msr_autostore.guest.nr);
2479 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
2480 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
2481 
2482 	set_cr4_guest_host_mask(vmx);
2483 }
2484 
2485 /*
2486  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
2487  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
2488  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
2489  * guest in a way that will both be appropriate to L1's requests, and our
2490  * needs. In addition to modifying the active vmcs (which is vmcs02), this
2491  * function also has additional necessary side-effects, like setting various
2492  * vcpu->arch fields.
2493  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
2494  * is assigned to entry_failure_code on failure.
2495  */
2496 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
2497 			  enum vm_entry_failure_code *entry_failure_code)
2498 {
2499 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2500 	struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
2501 	bool load_guest_pdptrs_vmcs12 = false;
2502 
2503 	if (vmx->nested.dirty_vmcs12 || hv_evmcs) {
2504 		prepare_vmcs02_rare(vmx, vmcs12);
2505 		vmx->nested.dirty_vmcs12 = false;
2506 
2507 		load_guest_pdptrs_vmcs12 = !hv_evmcs ||
2508 			!(hv_evmcs->hv_clean_fields &
2509 			  HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1);
2510 	}
2511 
2512 	if (vmx->nested.nested_run_pending &&
2513 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
2514 		kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
2515 		vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
2516 	} else {
2517 		kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
2518 		vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
2519 	}
2520 	if (kvm_mpx_supported() && (!vmx->nested.nested_run_pending ||
2521 	    !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)))
2522 		vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
2523 	vmx_set_rflags(vcpu, vmcs12->guest_rflags);
2524 
2525 	/* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
2526 	 * bitwise-or of what L1 wants to trap for L2, and what we want to
2527 	 * trap. Note that CR0.TS also needs updating - we do this later.
2528 	 */
2529 	update_exception_bitmap(vcpu);
2530 	vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
2531 	vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2532 
2533 	if (vmx->nested.nested_run_pending &&
2534 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
2535 		vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
2536 		vcpu->arch.pat = vmcs12->guest_ia32_pat;
2537 	} else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2538 		vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
2539 	}
2540 
2541 	vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
2542 
2543 	if (kvm_has_tsc_control)
2544 		decache_tsc_multiplier(vmx);
2545 
2546 	nested_vmx_transition_tlb_flush(vcpu, vmcs12, true);
2547 
2548 	if (nested_cpu_has_ept(vmcs12))
2549 		nested_ept_init_mmu_context(vcpu);
2550 
2551 	/*
2552 	 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
2553 	 * bits which we consider mandatory enabled.
2554 	 * The CR0_READ_SHADOW is what L2 should have expected to read given
2555 	 * the specifications by L1; It's not enough to take
2556 	 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
2557 	 * have more bits than L1 expected.
2558 	 */
2559 	vmx_set_cr0(vcpu, vmcs12->guest_cr0);
2560 	vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
2561 
2562 	vmx_set_cr4(vcpu, vmcs12->guest_cr4);
2563 	vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
2564 
2565 	vcpu->arch.efer = nested_vmx_calc_efer(vmx, vmcs12);
2566 	/* Note: may modify VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
2567 	vmx_set_efer(vcpu, vcpu->arch.efer);
2568 
2569 	/*
2570 	 * Guest state is invalid and unrestricted guest is disabled,
2571 	 * which means L1 attempted VMEntry to L2 with invalid state.
2572 	 * Fail the VMEntry.
2573 	 */
2574 	if (vmx->emulation_required) {
2575 		*entry_failure_code = ENTRY_FAIL_DEFAULT;
2576 		return -EINVAL;
2577 	}
2578 
2579 	/* Shadow page tables on either EPT or shadow page tables. */
2580 	if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
2581 				entry_failure_code))
2582 		return -EINVAL;
2583 
2584 	/*
2585 	 * Immediately write vmcs02.GUEST_CR3.  It will be propagated to vmcs12
2586 	 * on nested VM-Exit, which can occur without actually running L2 and
2587 	 * thus without hitting vmx_load_mmu_pgd(), e.g. if L1 is entering L2 with
2588 	 * vmcs12.GUEST_ACTIVITYSTATE=HLT, in which case KVM will intercept the
2589 	 * transition to HLT instead of running L2.
2590 	 */
2591 	if (enable_ept)
2592 		vmcs_writel(GUEST_CR3, vmcs12->guest_cr3);
2593 
2594 	/* Late preparation of GUEST_PDPTRs now that EFER and CRs are set. */
2595 	if (load_guest_pdptrs_vmcs12 && nested_cpu_has_ept(vmcs12) &&
2596 	    is_pae_paging(vcpu)) {
2597 		vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
2598 		vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
2599 		vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
2600 		vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
2601 	}
2602 
2603 	if (!enable_ept)
2604 		vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
2605 
2606 	if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) &&
2607 	    WARN_ON_ONCE(kvm_set_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
2608 				     vmcs12->guest_ia32_perf_global_ctrl)))
2609 		return -EINVAL;
2610 
2611 	kvm_rsp_write(vcpu, vmcs12->guest_rsp);
2612 	kvm_rip_write(vcpu, vmcs12->guest_rip);
2613 	return 0;
2614 }
2615 
2616 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
2617 {
2618 	if (CC(!nested_cpu_has_nmi_exiting(vmcs12) &&
2619 	       nested_cpu_has_virtual_nmis(vmcs12)))
2620 		return -EINVAL;
2621 
2622 	if (CC(!nested_cpu_has_virtual_nmis(vmcs12) &&
2623 	       nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING)))
2624 		return -EINVAL;
2625 
2626 	return 0;
2627 }
2628 
2629 static bool nested_vmx_check_eptp(struct kvm_vcpu *vcpu, u64 new_eptp)
2630 {
2631 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2632 	int maxphyaddr = cpuid_maxphyaddr(vcpu);
2633 
2634 	/* Check for memory type validity */
2635 	switch (new_eptp & VMX_EPTP_MT_MASK) {
2636 	case VMX_EPTP_MT_UC:
2637 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT)))
2638 			return false;
2639 		break;
2640 	case VMX_EPTP_MT_WB:
2641 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT)))
2642 			return false;
2643 		break;
2644 	default:
2645 		return false;
2646 	}
2647 
2648 	/* Page-walk levels validity. */
2649 	switch (new_eptp & VMX_EPTP_PWL_MASK) {
2650 	case VMX_EPTP_PWL_5:
2651 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_PAGE_WALK_5_BIT)))
2652 			return false;
2653 		break;
2654 	case VMX_EPTP_PWL_4:
2655 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_PAGE_WALK_4_BIT)))
2656 			return false;
2657 		break;
2658 	default:
2659 		return false;
2660 	}
2661 
2662 	/* Reserved bits should not be set */
2663 	if (CC(new_eptp >> maxphyaddr || ((new_eptp >> 7) & 0x1f)))
2664 		return false;
2665 
2666 	/* AD, if set, should be supported */
2667 	if (new_eptp & VMX_EPTP_AD_ENABLE_BIT) {
2668 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT)))
2669 			return false;
2670 	}
2671 
2672 	return true;
2673 }
2674 
2675 /*
2676  * Checks related to VM-Execution Control Fields
2677  */
2678 static int nested_check_vm_execution_controls(struct kvm_vcpu *vcpu,
2679                                               struct vmcs12 *vmcs12)
2680 {
2681 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2682 
2683 	if (CC(!vmx_control_verify(vmcs12->pin_based_vm_exec_control,
2684 				   vmx->nested.msrs.pinbased_ctls_low,
2685 				   vmx->nested.msrs.pinbased_ctls_high)) ||
2686 	    CC(!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
2687 				   vmx->nested.msrs.procbased_ctls_low,
2688 				   vmx->nested.msrs.procbased_ctls_high)))
2689 		return -EINVAL;
2690 
2691 	if (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
2692 	    CC(!vmx_control_verify(vmcs12->secondary_vm_exec_control,
2693 				   vmx->nested.msrs.secondary_ctls_low,
2694 				   vmx->nested.msrs.secondary_ctls_high)))
2695 		return -EINVAL;
2696 
2697 	if (CC(vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu)) ||
2698 	    nested_vmx_check_io_bitmap_controls(vcpu, vmcs12) ||
2699 	    nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12) ||
2700 	    nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12) ||
2701 	    nested_vmx_check_apic_access_controls(vcpu, vmcs12) ||
2702 	    nested_vmx_check_apicv_controls(vcpu, vmcs12) ||
2703 	    nested_vmx_check_nmi_controls(vmcs12) ||
2704 	    nested_vmx_check_pml_controls(vcpu, vmcs12) ||
2705 	    nested_vmx_check_unrestricted_guest_controls(vcpu, vmcs12) ||
2706 	    nested_vmx_check_mode_based_ept_exec_controls(vcpu, vmcs12) ||
2707 	    nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12) ||
2708 	    CC(nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id))
2709 		return -EINVAL;
2710 
2711 	if (!nested_cpu_has_preemption_timer(vmcs12) &&
2712 	    nested_cpu_has_save_preemption_timer(vmcs12))
2713 		return -EINVAL;
2714 
2715 	if (nested_cpu_has_ept(vmcs12) &&
2716 	    CC(!nested_vmx_check_eptp(vcpu, vmcs12->ept_pointer)))
2717 		return -EINVAL;
2718 
2719 	if (nested_cpu_has_vmfunc(vmcs12)) {
2720 		if (CC(vmcs12->vm_function_control &
2721 		       ~vmx->nested.msrs.vmfunc_controls))
2722 			return -EINVAL;
2723 
2724 		if (nested_cpu_has_eptp_switching(vmcs12)) {
2725 			if (CC(!nested_cpu_has_ept(vmcs12)) ||
2726 			    CC(!page_address_valid(vcpu, vmcs12->eptp_list_address)))
2727 				return -EINVAL;
2728 		}
2729 	}
2730 
2731 	return 0;
2732 }
2733 
2734 /*
2735  * Checks related to VM-Exit Control Fields
2736  */
2737 static int nested_check_vm_exit_controls(struct kvm_vcpu *vcpu,
2738                                          struct vmcs12 *vmcs12)
2739 {
2740 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2741 
2742 	if (CC(!vmx_control_verify(vmcs12->vm_exit_controls,
2743 				    vmx->nested.msrs.exit_ctls_low,
2744 				    vmx->nested.msrs.exit_ctls_high)) ||
2745 	    CC(nested_vmx_check_exit_msr_switch_controls(vcpu, vmcs12)))
2746 		return -EINVAL;
2747 
2748 	return 0;
2749 }
2750 
2751 /*
2752  * Checks related to VM-Entry Control Fields
2753  */
2754 static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
2755 					  struct vmcs12 *vmcs12)
2756 {
2757 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2758 
2759 	if (CC(!vmx_control_verify(vmcs12->vm_entry_controls,
2760 				    vmx->nested.msrs.entry_ctls_low,
2761 				    vmx->nested.msrs.entry_ctls_high)))
2762 		return -EINVAL;
2763 
2764 	/*
2765 	 * From the Intel SDM, volume 3:
2766 	 * Fields relevant to VM-entry event injection must be set properly.
2767 	 * These fields are the VM-entry interruption-information field, the
2768 	 * VM-entry exception error code, and the VM-entry instruction length.
2769 	 */
2770 	if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
2771 		u32 intr_info = vmcs12->vm_entry_intr_info_field;
2772 		u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
2773 		u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
2774 		bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
2775 		bool should_have_error_code;
2776 		bool urg = nested_cpu_has2(vmcs12,
2777 					   SECONDARY_EXEC_UNRESTRICTED_GUEST);
2778 		bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
2779 
2780 		/* VM-entry interruption-info field: interruption type */
2781 		if (CC(intr_type == INTR_TYPE_RESERVED) ||
2782 		    CC(intr_type == INTR_TYPE_OTHER_EVENT &&
2783 		       !nested_cpu_supports_monitor_trap_flag(vcpu)))
2784 			return -EINVAL;
2785 
2786 		/* VM-entry interruption-info field: vector */
2787 		if (CC(intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
2788 		    CC(intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
2789 		    CC(intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
2790 			return -EINVAL;
2791 
2792 		/* VM-entry interruption-info field: deliver error code */
2793 		should_have_error_code =
2794 			intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
2795 			x86_exception_has_error_code(vector);
2796 		if (CC(has_error_code != should_have_error_code))
2797 			return -EINVAL;
2798 
2799 		/* VM-entry exception error code */
2800 		if (CC(has_error_code &&
2801 		       vmcs12->vm_entry_exception_error_code & GENMASK(31, 16)))
2802 			return -EINVAL;
2803 
2804 		/* VM-entry interruption-info field: reserved bits */
2805 		if (CC(intr_info & INTR_INFO_RESVD_BITS_MASK))
2806 			return -EINVAL;
2807 
2808 		/* VM-entry instruction length */
2809 		switch (intr_type) {
2810 		case INTR_TYPE_SOFT_EXCEPTION:
2811 		case INTR_TYPE_SOFT_INTR:
2812 		case INTR_TYPE_PRIV_SW_EXCEPTION:
2813 			if (CC(vmcs12->vm_entry_instruction_len > 15) ||
2814 			    CC(vmcs12->vm_entry_instruction_len == 0 &&
2815 			    CC(!nested_cpu_has_zero_length_injection(vcpu))))
2816 				return -EINVAL;
2817 		}
2818 	}
2819 
2820 	if (nested_vmx_check_entry_msr_switch_controls(vcpu, vmcs12))
2821 		return -EINVAL;
2822 
2823 	return 0;
2824 }
2825 
2826 static int nested_vmx_check_controls(struct kvm_vcpu *vcpu,
2827 				     struct vmcs12 *vmcs12)
2828 {
2829 	if (nested_check_vm_execution_controls(vcpu, vmcs12) ||
2830 	    nested_check_vm_exit_controls(vcpu, vmcs12) ||
2831 	    nested_check_vm_entry_controls(vcpu, vmcs12))
2832 		return -EINVAL;
2833 
2834 	if (to_vmx(vcpu)->nested.enlightened_vmcs_enabled)
2835 		return nested_evmcs_check_controls(vmcs12);
2836 
2837 	return 0;
2838 }
2839 
2840 static int nested_vmx_check_host_state(struct kvm_vcpu *vcpu,
2841 				       struct vmcs12 *vmcs12)
2842 {
2843 	bool ia32e;
2844 
2845 	if (CC(!nested_host_cr0_valid(vcpu, vmcs12->host_cr0)) ||
2846 	    CC(!nested_host_cr4_valid(vcpu, vmcs12->host_cr4)) ||
2847 	    CC(!nested_cr3_valid(vcpu, vmcs12->host_cr3)))
2848 		return -EINVAL;
2849 
2850 	if (CC(is_noncanonical_address(vmcs12->host_ia32_sysenter_esp, vcpu)) ||
2851 	    CC(is_noncanonical_address(vmcs12->host_ia32_sysenter_eip, vcpu)))
2852 		return -EINVAL;
2853 
2854 	if ((vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) &&
2855 	    CC(!kvm_pat_valid(vmcs12->host_ia32_pat)))
2856 		return -EINVAL;
2857 
2858 	if ((vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) &&
2859 	    CC(!kvm_valid_perf_global_ctrl(vcpu_to_pmu(vcpu),
2860 					   vmcs12->host_ia32_perf_global_ctrl)))
2861 		return -EINVAL;
2862 
2863 #ifdef CONFIG_X86_64
2864 	ia32e = !!(vcpu->arch.efer & EFER_LMA);
2865 #else
2866 	ia32e = false;
2867 #endif
2868 
2869 	if (ia32e) {
2870 		if (CC(!(vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)) ||
2871 		    CC(!(vmcs12->host_cr4 & X86_CR4_PAE)))
2872 			return -EINVAL;
2873 	} else {
2874 		if (CC(vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) ||
2875 		    CC(vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) ||
2876 		    CC(vmcs12->host_cr4 & X86_CR4_PCIDE) ||
2877 		    CC((vmcs12->host_rip) >> 32))
2878 			return -EINVAL;
2879 	}
2880 
2881 	if (CC(vmcs12->host_cs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2882 	    CC(vmcs12->host_ss_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2883 	    CC(vmcs12->host_ds_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2884 	    CC(vmcs12->host_es_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2885 	    CC(vmcs12->host_fs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2886 	    CC(vmcs12->host_gs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2887 	    CC(vmcs12->host_tr_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2888 	    CC(vmcs12->host_cs_selector == 0) ||
2889 	    CC(vmcs12->host_tr_selector == 0) ||
2890 	    CC(vmcs12->host_ss_selector == 0 && !ia32e))
2891 		return -EINVAL;
2892 
2893 	if (CC(is_noncanonical_address(vmcs12->host_fs_base, vcpu)) ||
2894 	    CC(is_noncanonical_address(vmcs12->host_gs_base, vcpu)) ||
2895 	    CC(is_noncanonical_address(vmcs12->host_gdtr_base, vcpu)) ||
2896 	    CC(is_noncanonical_address(vmcs12->host_idtr_base, vcpu)) ||
2897 	    CC(is_noncanonical_address(vmcs12->host_tr_base, vcpu)) ||
2898 	    CC(is_noncanonical_address(vmcs12->host_rip, vcpu)))
2899 		return -EINVAL;
2900 
2901 	/*
2902 	 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
2903 	 * IA32_EFER MSR must be 0 in the field for that register. In addition,
2904 	 * the values of the LMA and LME bits in the field must each be that of
2905 	 * the host address-space size VM-exit control.
2906 	 */
2907 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
2908 		if (CC(!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer)) ||
2909 		    CC(ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA)) ||
2910 		    CC(ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)))
2911 			return -EINVAL;
2912 	}
2913 
2914 	return 0;
2915 }
2916 
2917 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
2918 					  struct vmcs12 *vmcs12)
2919 {
2920 	int r = 0;
2921 	struct vmcs12 *shadow;
2922 	struct kvm_host_map map;
2923 
2924 	if (vmcs12->vmcs_link_pointer == -1ull)
2925 		return 0;
2926 
2927 	if (CC(!page_address_valid(vcpu, vmcs12->vmcs_link_pointer)))
2928 		return -EINVAL;
2929 
2930 	if (CC(kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->vmcs_link_pointer), &map)))
2931 		return -EINVAL;
2932 
2933 	shadow = map.hva;
2934 
2935 	if (CC(shadow->hdr.revision_id != VMCS12_REVISION) ||
2936 	    CC(shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12)))
2937 		r = -EINVAL;
2938 
2939 	kvm_vcpu_unmap(vcpu, &map, false);
2940 	return r;
2941 }
2942 
2943 /*
2944  * Checks related to Guest Non-register State
2945  */
2946 static int nested_check_guest_non_reg_state(struct vmcs12 *vmcs12)
2947 {
2948 	if (CC(vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
2949 	       vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT))
2950 		return -EINVAL;
2951 
2952 	return 0;
2953 }
2954 
2955 static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,
2956 					struct vmcs12 *vmcs12,
2957 					enum vm_entry_failure_code *entry_failure_code)
2958 {
2959 	bool ia32e;
2960 
2961 	*entry_failure_code = ENTRY_FAIL_DEFAULT;
2962 
2963 	if (CC(!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0)) ||
2964 	    CC(!nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4)))
2965 		return -EINVAL;
2966 
2967 	if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) &&
2968 	    CC(!kvm_dr7_valid(vmcs12->guest_dr7)))
2969 		return -EINVAL;
2970 
2971 	if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) &&
2972 	    CC(!kvm_pat_valid(vmcs12->guest_ia32_pat)))
2973 		return -EINVAL;
2974 
2975 	if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
2976 		*entry_failure_code = ENTRY_FAIL_VMCS_LINK_PTR;
2977 		return -EINVAL;
2978 	}
2979 
2980 	if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) &&
2981 	    CC(!kvm_valid_perf_global_ctrl(vcpu_to_pmu(vcpu),
2982 					   vmcs12->guest_ia32_perf_global_ctrl)))
2983 		return -EINVAL;
2984 
2985 	/*
2986 	 * If the load IA32_EFER VM-entry control is 1, the following checks
2987 	 * are performed on the field for the IA32_EFER MSR:
2988 	 * - Bits reserved in the IA32_EFER MSR must be 0.
2989 	 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
2990 	 *   the IA-32e mode guest VM-exit control. It must also be identical
2991 	 *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
2992 	 *   CR0.PG) is 1.
2993 	 */
2994 	if (to_vmx(vcpu)->nested.nested_run_pending &&
2995 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
2996 		ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
2997 		if (CC(!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer)) ||
2998 		    CC(ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA)) ||
2999 		    CC(((vmcs12->guest_cr0 & X86_CR0_PG) &&
3000 		     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))))
3001 			return -EINVAL;
3002 	}
3003 
3004 	if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
3005 	    (CC(is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu)) ||
3006 	     CC((vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD))))
3007 		return -EINVAL;
3008 
3009 	if (nested_check_guest_non_reg_state(vmcs12))
3010 		return -EINVAL;
3011 
3012 	return 0;
3013 }
3014 
3015 static int nested_vmx_check_vmentry_hw(struct kvm_vcpu *vcpu)
3016 {
3017 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3018 	unsigned long cr3, cr4;
3019 	bool vm_fail;
3020 
3021 	if (!nested_early_check)
3022 		return 0;
3023 
3024 	if (vmx->msr_autoload.host.nr)
3025 		vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
3026 	if (vmx->msr_autoload.guest.nr)
3027 		vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
3028 
3029 	preempt_disable();
3030 
3031 	vmx_prepare_switch_to_guest(vcpu);
3032 
3033 	/*
3034 	 * Induce a consistency check VMExit by clearing bit 1 in GUEST_RFLAGS,
3035 	 * which is reserved to '1' by hardware.  GUEST_RFLAGS is guaranteed to
3036 	 * be written (by prepare_vmcs02()) before the "real" VMEnter, i.e.
3037 	 * there is no need to preserve other bits or save/restore the field.
3038 	 */
3039 	vmcs_writel(GUEST_RFLAGS, 0);
3040 
3041 	cr3 = __get_current_cr3_fast();
3042 	if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
3043 		vmcs_writel(HOST_CR3, cr3);
3044 		vmx->loaded_vmcs->host_state.cr3 = cr3;
3045 	}
3046 
3047 	cr4 = cr4_read_shadow();
3048 	if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
3049 		vmcs_writel(HOST_CR4, cr4);
3050 		vmx->loaded_vmcs->host_state.cr4 = cr4;
3051 	}
3052 
3053 	asm(
3054 		"sub $%c[wordsize], %%" _ASM_SP "\n\t" /* temporarily adjust RSP for CALL */
3055 		"cmp %%" _ASM_SP ", %c[host_state_rsp](%[loaded_vmcs]) \n\t"
3056 		"je 1f \n\t"
3057 		__ex("vmwrite %%" _ASM_SP ", %[HOST_RSP]") "\n\t"
3058 		"mov %%" _ASM_SP ", %c[host_state_rsp](%[loaded_vmcs]) \n\t"
3059 		"1: \n\t"
3060 		"add $%c[wordsize], %%" _ASM_SP "\n\t" /* un-adjust RSP */
3061 
3062 		/* Check if vmlaunch or vmresume is needed */
3063 		"cmpb $0, %c[launched](%[loaded_vmcs])\n\t"
3064 
3065 		/*
3066 		 * VMLAUNCH and VMRESUME clear RFLAGS.{CF,ZF} on VM-Exit, set
3067 		 * RFLAGS.CF on VM-Fail Invalid and set RFLAGS.ZF on VM-Fail
3068 		 * Valid.  vmx_vmenter() directly "returns" RFLAGS, and so the
3069 		 * results of VM-Enter is captured via CC_{SET,OUT} to vm_fail.
3070 		 */
3071 		"call vmx_vmenter\n\t"
3072 
3073 		CC_SET(be)
3074 	      : ASM_CALL_CONSTRAINT, CC_OUT(be) (vm_fail)
3075 	      :	[HOST_RSP]"r"((unsigned long)HOST_RSP),
3076 		[loaded_vmcs]"r"(vmx->loaded_vmcs),
3077 		[launched]"i"(offsetof(struct loaded_vmcs, launched)),
3078 		[host_state_rsp]"i"(offsetof(struct loaded_vmcs, host_state.rsp)),
3079 		[wordsize]"i"(sizeof(ulong))
3080 	      : "memory"
3081 	);
3082 
3083 	if (vmx->msr_autoload.host.nr)
3084 		vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
3085 	if (vmx->msr_autoload.guest.nr)
3086 		vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
3087 
3088 	if (vm_fail) {
3089 		u32 error = vmcs_read32(VM_INSTRUCTION_ERROR);
3090 
3091 		preempt_enable();
3092 
3093 		trace_kvm_nested_vmenter_failed(
3094 			"early hardware check VM-instruction error: ", error);
3095 		WARN_ON_ONCE(error != VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3096 		return 1;
3097 	}
3098 
3099 	/*
3100 	 * VMExit clears RFLAGS.IF and DR7, even on a consistency check.
3101 	 */
3102 	if (hw_breakpoint_active())
3103 		set_debugreg(__this_cpu_read(cpu_dr7), 7);
3104 	local_irq_enable();
3105 	preempt_enable();
3106 
3107 	/*
3108 	 * A non-failing VMEntry means we somehow entered guest mode with
3109 	 * an illegal RIP, and that's just the tip of the iceberg.  There
3110 	 * is no telling what memory has been modified or what state has
3111 	 * been exposed to unknown code.  Hitting this all but guarantees
3112 	 * a (very critical) hardware issue.
3113 	 */
3114 	WARN_ON(!(vmcs_read32(VM_EXIT_REASON) &
3115 		VMX_EXIT_REASONS_FAILED_VMENTRY));
3116 
3117 	return 0;
3118 }
3119 
3120 static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
3121 {
3122 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3123 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3124 	struct kvm_host_map *map;
3125 	struct page *page;
3126 	u64 hpa;
3127 
3128 	/*
3129 	 * hv_evmcs may end up being not mapped after migration (when
3130 	 * L2 was running), map it here to make sure vmcs12 changes are
3131 	 * properly reflected.
3132 	 */
3133 	if (vmx->nested.enlightened_vmcs_enabled && !vmx->nested.hv_evmcs) {
3134 		enum nested_evmptrld_status evmptrld_status =
3135 			nested_vmx_handle_enlightened_vmptrld(vcpu, false);
3136 
3137 		if (evmptrld_status == EVMPTRLD_VMFAIL ||
3138 		    evmptrld_status == EVMPTRLD_ERROR) {
3139 			pr_debug_ratelimited("%s: enlightened vmptrld failed\n",
3140 					     __func__);
3141 			vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3142 			vcpu->run->internal.suberror =
3143 				KVM_INTERNAL_ERROR_EMULATION;
3144 			vcpu->run->internal.ndata = 0;
3145 			return false;
3146 		}
3147 	}
3148 
3149 	if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
3150 		/*
3151 		 * Translate L1 physical address to host physical
3152 		 * address for vmcs02. Keep the page pinned, so this
3153 		 * physical address remains valid. We keep a reference
3154 		 * to it so we can release it later.
3155 		 */
3156 		if (vmx->nested.apic_access_page) { /* shouldn't happen */
3157 			kvm_release_page_clean(vmx->nested.apic_access_page);
3158 			vmx->nested.apic_access_page = NULL;
3159 		}
3160 		page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
3161 		if (!is_error_page(page)) {
3162 			vmx->nested.apic_access_page = page;
3163 			hpa = page_to_phys(vmx->nested.apic_access_page);
3164 			vmcs_write64(APIC_ACCESS_ADDR, hpa);
3165 		} else {
3166 			pr_debug_ratelimited("%s: no backing 'struct page' for APIC-access address in vmcs12\n",
3167 					     __func__);
3168 			vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3169 			vcpu->run->internal.suberror =
3170 				KVM_INTERNAL_ERROR_EMULATION;
3171 			vcpu->run->internal.ndata = 0;
3172 			return false;
3173 		}
3174 	}
3175 
3176 	if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
3177 		map = &vmx->nested.virtual_apic_map;
3178 
3179 		if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->virtual_apic_page_addr), map)) {
3180 			vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, pfn_to_hpa(map->pfn));
3181 		} else if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING) &&
3182 		           nested_cpu_has(vmcs12, CPU_BASED_CR8_STORE_EXITING) &&
3183 			   !nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
3184 			/*
3185 			 * The processor will never use the TPR shadow, simply
3186 			 * clear the bit from the execution control.  Such a
3187 			 * configuration is useless, but it happens in tests.
3188 			 * For any other configuration, failing the vm entry is
3189 			 * _not_ what the processor does but it's basically the
3190 			 * only possibility we have.
3191 			 */
3192 			exec_controls_clearbit(vmx, CPU_BASED_TPR_SHADOW);
3193 		} else {
3194 			/*
3195 			 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR to
3196 			 * force VM-Entry to fail.
3197 			 */
3198 			vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
3199 		}
3200 	}
3201 
3202 	if (nested_cpu_has_posted_intr(vmcs12)) {
3203 		map = &vmx->nested.pi_desc_map;
3204 
3205 		if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->posted_intr_desc_addr), map)) {
3206 			vmx->nested.pi_desc =
3207 				(struct pi_desc *)(((void *)map->hva) +
3208 				offset_in_page(vmcs12->posted_intr_desc_addr));
3209 			vmcs_write64(POSTED_INTR_DESC_ADDR,
3210 				     pfn_to_hpa(map->pfn) + offset_in_page(vmcs12->posted_intr_desc_addr));
3211 		}
3212 	}
3213 	if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
3214 		exec_controls_setbit(vmx, CPU_BASED_USE_MSR_BITMAPS);
3215 	else
3216 		exec_controls_clearbit(vmx, CPU_BASED_USE_MSR_BITMAPS);
3217 	return true;
3218 }
3219 
3220 static int nested_vmx_write_pml_buffer(struct kvm_vcpu *vcpu, gpa_t gpa)
3221 {
3222 	struct vmcs12 *vmcs12;
3223 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3224 	gpa_t dst;
3225 
3226 	if (WARN_ON_ONCE(!is_guest_mode(vcpu)))
3227 		return 0;
3228 
3229 	if (WARN_ON_ONCE(vmx->nested.pml_full))
3230 		return 1;
3231 
3232 	/*
3233 	 * Check if PML is enabled for the nested guest. Whether eptp bit 6 is
3234 	 * set is already checked as part of A/D emulation.
3235 	 */
3236 	vmcs12 = get_vmcs12(vcpu);
3237 	if (!nested_cpu_has_pml(vmcs12))
3238 		return 0;
3239 
3240 	if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
3241 		vmx->nested.pml_full = true;
3242 		return 1;
3243 	}
3244 
3245 	gpa &= ~0xFFFull;
3246 	dst = vmcs12->pml_address + sizeof(u64) * vmcs12->guest_pml_index;
3247 
3248 	if (kvm_write_guest_page(vcpu->kvm, gpa_to_gfn(dst), &gpa,
3249 				 offset_in_page(dst), sizeof(gpa)))
3250 		return 0;
3251 
3252 	vmcs12->guest_pml_index--;
3253 
3254 	return 0;
3255 }
3256 
3257 /*
3258  * Intel's VMX Instruction Reference specifies a common set of prerequisites
3259  * for running VMX instructions (except VMXON, whose prerequisites are
3260  * slightly different). It also specifies what exception to inject otherwise.
3261  * Note that many of these exceptions have priority over VM exits, so they
3262  * don't have to be checked again here.
3263  */
3264 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
3265 {
3266 	if (!to_vmx(vcpu)->nested.vmxon) {
3267 		kvm_queue_exception(vcpu, UD_VECTOR);
3268 		return 0;
3269 	}
3270 
3271 	if (vmx_get_cpl(vcpu)) {
3272 		kvm_inject_gp(vcpu, 0);
3273 		return 0;
3274 	}
3275 
3276 	return 1;
3277 }
3278 
3279 static u8 vmx_has_apicv_interrupt(struct kvm_vcpu *vcpu)
3280 {
3281 	u8 rvi = vmx_get_rvi();
3282 	u8 vppr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_PROCPRI);
3283 
3284 	return ((rvi & 0xf0) > (vppr & 0xf0));
3285 }
3286 
3287 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
3288 				   struct vmcs12 *vmcs12);
3289 
3290 /*
3291  * If from_vmentry is false, this is being called from state restore (either RSM
3292  * or KVM_SET_NESTED_STATE).  Otherwise it's called from vmlaunch/vmresume.
3293  *
3294  * Returns:
3295  *	NVMX_VMENTRY_SUCCESS: Entered VMX non-root mode
3296  *	NVMX_VMENTRY_VMFAIL:  Consistency check VMFail
3297  *	NVMX_VMENTRY_VMEXIT:  Consistency check VMExit
3298  *	NVMX_VMENTRY_KVM_INTERNAL_ERROR: KVM internal error
3299  */
3300 enum nvmx_vmentry_status nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,
3301 							bool from_vmentry)
3302 {
3303 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3304 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3305 	enum vm_entry_failure_code entry_failure_code;
3306 	bool evaluate_pending_interrupts;
3307 	u32 exit_reason, failed_index;
3308 
3309 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3310 		kvm_vcpu_flush_tlb_current(vcpu);
3311 
3312 	evaluate_pending_interrupts = exec_controls_get(vmx) &
3313 		(CPU_BASED_INTR_WINDOW_EXITING | CPU_BASED_NMI_WINDOW_EXITING);
3314 	if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
3315 		evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
3316 
3317 	if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
3318 		vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
3319 	if (kvm_mpx_supported() &&
3320 		!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
3321 		vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
3322 
3323 	/*
3324 	 * Overwrite vmcs01.GUEST_CR3 with L1's CR3 if EPT is disabled *and*
3325 	 * nested early checks are disabled.  In the event of a "late" VM-Fail,
3326 	 * i.e. a VM-Fail detected by hardware but not KVM, KVM must unwind its
3327 	 * software model to the pre-VMEntry host state.  When EPT is disabled,
3328 	 * GUEST_CR3 holds KVM's shadow CR3, not L1's "real" CR3, which causes
3329 	 * nested_vmx_restore_host_state() to corrupt vcpu->arch.cr3.  Stuffing
3330 	 * vmcs01.GUEST_CR3 results in the unwind naturally setting arch.cr3 to
3331 	 * the correct value.  Smashing vmcs01.GUEST_CR3 is safe because nested
3332 	 * VM-Exits, and the unwind, reset KVM's MMU, i.e. vmcs01.GUEST_CR3 is
3333 	 * guaranteed to be overwritten with a shadow CR3 prior to re-entering
3334 	 * L1.  Don't stuff vmcs01.GUEST_CR3 when using nested early checks as
3335 	 * KVM modifies vcpu->arch.cr3 if and only if the early hardware checks
3336 	 * pass, and early VM-Fails do not reset KVM's MMU, i.e. the VM-Fail
3337 	 * path would need to manually save/restore vmcs01.GUEST_CR3.
3338 	 */
3339 	if (!enable_ept && !nested_early_check)
3340 		vmcs_writel(GUEST_CR3, vcpu->arch.cr3);
3341 
3342 	vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
3343 
3344 	prepare_vmcs02_early(vmx, vmcs12);
3345 
3346 	if (from_vmentry) {
3347 		if (unlikely(!nested_get_vmcs12_pages(vcpu)))
3348 			return NVMX_VMENTRY_KVM_INTERNAL_ERROR;
3349 
3350 		if (nested_vmx_check_vmentry_hw(vcpu)) {
3351 			vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3352 			return NVMX_VMENTRY_VMFAIL;
3353 		}
3354 
3355 		if (nested_vmx_check_guest_state(vcpu, vmcs12,
3356 						 &entry_failure_code)) {
3357 			exit_reason = EXIT_REASON_INVALID_STATE;
3358 			vmcs12->exit_qualification = entry_failure_code;
3359 			goto vmentry_fail_vmexit;
3360 		}
3361 	}
3362 
3363 	enter_guest_mode(vcpu);
3364 	if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
3365 		vcpu->arch.tsc_offset += vmcs12->tsc_offset;
3366 
3367 	if (prepare_vmcs02(vcpu, vmcs12, &entry_failure_code)) {
3368 		exit_reason = EXIT_REASON_INVALID_STATE;
3369 		vmcs12->exit_qualification = entry_failure_code;
3370 		goto vmentry_fail_vmexit_guest_mode;
3371 	}
3372 
3373 	if (from_vmentry) {
3374 		failed_index = nested_vmx_load_msr(vcpu,
3375 						   vmcs12->vm_entry_msr_load_addr,
3376 						   vmcs12->vm_entry_msr_load_count);
3377 		if (failed_index) {
3378 			exit_reason = EXIT_REASON_MSR_LOAD_FAIL;
3379 			vmcs12->exit_qualification = failed_index;
3380 			goto vmentry_fail_vmexit_guest_mode;
3381 		}
3382 	} else {
3383 		/*
3384 		 * The MMU is not initialized to point at the right entities yet and
3385 		 * "get pages" would need to read data from the guest (i.e. we will
3386 		 * need to perform gpa to hpa translation). Request a call
3387 		 * to nested_get_vmcs12_pages before the next VM-entry.  The MSRs
3388 		 * have already been set at vmentry time and should not be reset.
3389 		 */
3390 		kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
3391 	}
3392 
3393 	/*
3394 	 * If L1 had a pending IRQ/NMI until it executed
3395 	 * VMLAUNCH/VMRESUME which wasn't delivered because it was
3396 	 * disallowed (e.g. interrupts disabled), L0 needs to
3397 	 * evaluate if this pending event should cause an exit from L2
3398 	 * to L1 or delivered directly to L2 (e.g. In case L1 don't
3399 	 * intercept EXTERNAL_INTERRUPT).
3400 	 *
3401 	 * Usually this would be handled by the processor noticing an
3402 	 * IRQ/NMI window request, or checking RVI during evaluation of
3403 	 * pending virtual interrupts.  However, this setting was done
3404 	 * on VMCS01 and now VMCS02 is active instead. Thus, we force L0
3405 	 * to perform pending event evaluation by requesting a KVM_REQ_EVENT.
3406 	 */
3407 	if (unlikely(evaluate_pending_interrupts))
3408 		kvm_make_request(KVM_REQ_EVENT, vcpu);
3409 
3410 	/*
3411 	 * Do not start the preemption timer hrtimer until after we know
3412 	 * we are successful, so that only nested_vmx_vmexit needs to cancel
3413 	 * the timer.
3414 	 */
3415 	vmx->nested.preemption_timer_expired = false;
3416 	if (nested_cpu_has_preemption_timer(vmcs12)) {
3417 		u64 timer_value = vmx_calc_preemption_timer_value(vcpu);
3418 		vmx_start_preemption_timer(vcpu, timer_value);
3419 	}
3420 
3421 	/*
3422 	 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
3423 	 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
3424 	 * returned as far as L1 is concerned. It will only return (and set
3425 	 * the success flag) when L2 exits (see nested_vmx_vmexit()).
3426 	 */
3427 	return NVMX_VMENTRY_SUCCESS;
3428 
3429 	/*
3430 	 * A failed consistency check that leads to a VMExit during L1's
3431 	 * VMEnter to L2 is a variation of a normal VMexit, as explained in
3432 	 * 26.7 "VM-entry failures during or after loading guest state".
3433 	 */
3434 vmentry_fail_vmexit_guest_mode:
3435 	if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
3436 		vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
3437 	leave_guest_mode(vcpu);
3438 
3439 vmentry_fail_vmexit:
3440 	vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3441 
3442 	if (!from_vmentry)
3443 		return NVMX_VMENTRY_VMEXIT;
3444 
3445 	load_vmcs12_host_state(vcpu, vmcs12);
3446 	vmcs12->vm_exit_reason = exit_reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
3447 	if (enable_shadow_vmcs || vmx->nested.hv_evmcs)
3448 		vmx->nested.need_vmcs12_to_shadow_sync = true;
3449 	return NVMX_VMENTRY_VMEXIT;
3450 }
3451 
3452 /*
3453  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
3454  * for running an L2 nested guest.
3455  */
3456 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
3457 {
3458 	struct vmcs12 *vmcs12;
3459 	enum nvmx_vmentry_status status;
3460 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3461 	u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
3462 	enum nested_evmptrld_status evmptrld_status;
3463 
3464 	if (!nested_vmx_check_permission(vcpu))
3465 		return 1;
3466 
3467 	evmptrld_status = nested_vmx_handle_enlightened_vmptrld(vcpu, launch);
3468 	if (evmptrld_status == EVMPTRLD_ERROR) {
3469 		kvm_queue_exception(vcpu, UD_VECTOR);
3470 		return 1;
3471 	} else if (evmptrld_status == EVMPTRLD_VMFAIL) {
3472 		return nested_vmx_failInvalid(vcpu);
3473 	}
3474 
3475 	if (!vmx->nested.hv_evmcs && vmx->nested.current_vmptr == -1ull)
3476 		return nested_vmx_failInvalid(vcpu);
3477 
3478 	vmcs12 = get_vmcs12(vcpu);
3479 
3480 	/*
3481 	 * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
3482 	 * that there *is* a valid VMCS pointer, RFLAGS.CF is set
3483 	 * rather than RFLAGS.ZF, and no error number is stored to the
3484 	 * VM-instruction error field.
3485 	 */
3486 	if (vmcs12->hdr.shadow_vmcs)
3487 		return nested_vmx_failInvalid(vcpu);
3488 
3489 	if (vmx->nested.hv_evmcs) {
3490 		copy_enlightened_to_vmcs12(vmx);
3491 		/* Enlightened VMCS doesn't have launch state */
3492 		vmcs12->launch_state = !launch;
3493 	} else if (enable_shadow_vmcs) {
3494 		copy_shadow_to_vmcs12(vmx);
3495 	}
3496 
3497 	/*
3498 	 * The nested entry process starts with enforcing various prerequisites
3499 	 * on vmcs12 as required by the Intel SDM, and act appropriately when
3500 	 * they fail: As the SDM explains, some conditions should cause the
3501 	 * instruction to fail, while others will cause the instruction to seem
3502 	 * to succeed, but return an EXIT_REASON_INVALID_STATE.
3503 	 * To speed up the normal (success) code path, we should avoid checking
3504 	 * for misconfigurations which will anyway be caught by the processor
3505 	 * when using the merged vmcs02.
3506 	 */
3507 	if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS)
3508 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
3509 
3510 	if (vmcs12->launch_state == launch)
3511 		return nested_vmx_fail(vcpu,
3512 			launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
3513 			       : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
3514 
3515 	if (nested_vmx_check_controls(vcpu, vmcs12))
3516 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3517 
3518 	if (nested_vmx_check_host_state(vcpu, vmcs12))
3519 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
3520 
3521 	/*
3522 	 * We're finally done with prerequisite checking, and can start with
3523 	 * the nested entry.
3524 	 */
3525 	vmx->nested.nested_run_pending = 1;
3526 	vmx->nested.has_preemption_timer_deadline = false;
3527 	status = nested_vmx_enter_non_root_mode(vcpu, true);
3528 	if (unlikely(status != NVMX_VMENTRY_SUCCESS))
3529 		goto vmentry_failed;
3530 
3531 	/* Hide L1D cache contents from the nested guest.  */
3532 	vmx->vcpu.arch.l1tf_flush_l1d = true;
3533 
3534 	/*
3535 	 * Must happen outside of nested_vmx_enter_non_root_mode() as it will
3536 	 * also be used as part of restoring nVMX state for
3537 	 * snapshot restore (migration).
3538 	 *
3539 	 * In this flow, it is assumed that vmcs12 cache was
3540 	 * trasferred as part of captured nVMX state and should
3541 	 * therefore not be read from guest memory (which may not
3542 	 * exist on destination host yet).
3543 	 */
3544 	nested_cache_shadow_vmcs12(vcpu, vmcs12);
3545 
3546 	/*
3547 	 * If we're entering a halted L2 vcpu and the L2 vcpu won't be
3548 	 * awakened by event injection or by an NMI-window VM-exit or
3549 	 * by an interrupt-window VM-exit, halt the vcpu.
3550 	 */
3551 	if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
3552 	    !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) &&
3553 	    !(vmcs12->cpu_based_vm_exec_control & CPU_BASED_NMI_WINDOW_EXITING) &&
3554 	    !((vmcs12->cpu_based_vm_exec_control & CPU_BASED_INTR_WINDOW_EXITING) &&
3555 	      (vmcs12->guest_rflags & X86_EFLAGS_IF))) {
3556 		vmx->nested.nested_run_pending = 0;
3557 		return kvm_vcpu_halt(vcpu);
3558 	}
3559 	return 1;
3560 
3561 vmentry_failed:
3562 	vmx->nested.nested_run_pending = 0;
3563 	if (status == NVMX_VMENTRY_KVM_INTERNAL_ERROR)
3564 		return 0;
3565 	if (status == NVMX_VMENTRY_VMEXIT)
3566 		return 1;
3567 	WARN_ON_ONCE(status != NVMX_VMENTRY_VMFAIL);
3568 	return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3569 }
3570 
3571 /*
3572  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
3573  * because L2 may have changed some cr0 bits directly (CR0_GUEST_HOST_MASK).
3574  * This function returns the new value we should put in vmcs12.guest_cr0.
3575  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
3576  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
3577  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
3578  *     didn't trap the bit, because if L1 did, so would L0).
3579  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
3580  *     been modified by L2, and L1 knows it. So just leave the old value of
3581  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
3582  *     isn't relevant, because if L0 traps this bit it can set it to anything.
3583  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
3584  *     changed these bits, and therefore they need to be updated, but L0
3585  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
3586  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
3587  */
3588 static inline unsigned long
3589 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3590 {
3591 	return
3592 	/*1*/	(vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
3593 	/*2*/	(vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
3594 	/*3*/	(vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
3595 			vcpu->arch.cr0_guest_owned_bits));
3596 }
3597 
3598 static inline unsigned long
3599 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3600 {
3601 	return
3602 	/*1*/	(vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
3603 	/*2*/	(vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
3604 	/*3*/	(vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
3605 			vcpu->arch.cr4_guest_owned_bits));
3606 }
3607 
3608 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
3609 				      struct vmcs12 *vmcs12)
3610 {
3611 	u32 idt_vectoring;
3612 	unsigned int nr;
3613 
3614 	if (vcpu->arch.exception.injected) {
3615 		nr = vcpu->arch.exception.nr;
3616 		idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
3617 
3618 		if (kvm_exception_is_soft(nr)) {
3619 			vmcs12->vm_exit_instruction_len =
3620 				vcpu->arch.event_exit_inst_len;
3621 			idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
3622 		} else
3623 			idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
3624 
3625 		if (vcpu->arch.exception.has_error_code) {
3626 			idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
3627 			vmcs12->idt_vectoring_error_code =
3628 				vcpu->arch.exception.error_code;
3629 		}
3630 
3631 		vmcs12->idt_vectoring_info_field = idt_vectoring;
3632 	} else if (vcpu->arch.nmi_injected) {
3633 		vmcs12->idt_vectoring_info_field =
3634 			INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
3635 	} else if (vcpu->arch.interrupt.injected) {
3636 		nr = vcpu->arch.interrupt.nr;
3637 		idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
3638 
3639 		if (vcpu->arch.interrupt.soft) {
3640 			idt_vectoring |= INTR_TYPE_SOFT_INTR;
3641 			vmcs12->vm_entry_instruction_len =
3642 				vcpu->arch.event_exit_inst_len;
3643 		} else
3644 			idt_vectoring |= INTR_TYPE_EXT_INTR;
3645 
3646 		vmcs12->idt_vectoring_info_field = idt_vectoring;
3647 	}
3648 }
3649 
3650 
3651 void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
3652 {
3653 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3654 	gfn_t gfn;
3655 
3656 	/*
3657 	 * Don't need to mark the APIC access page dirty; it is never
3658 	 * written to by the CPU during APIC virtualization.
3659 	 */
3660 
3661 	if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
3662 		gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
3663 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
3664 	}
3665 
3666 	if (nested_cpu_has_posted_intr(vmcs12)) {
3667 		gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
3668 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
3669 	}
3670 }
3671 
3672 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
3673 {
3674 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3675 	int max_irr;
3676 	void *vapic_page;
3677 	u16 status;
3678 
3679 	if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
3680 		return;
3681 
3682 	vmx->nested.pi_pending = false;
3683 	if (!pi_test_and_clear_on(vmx->nested.pi_desc))
3684 		return;
3685 
3686 	max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
3687 	if (max_irr != 256) {
3688 		vapic_page = vmx->nested.virtual_apic_map.hva;
3689 		if (!vapic_page)
3690 			return;
3691 
3692 		__kvm_apic_update_irr(vmx->nested.pi_desc->pir,
3693 			vapic_page, &max_irr);
3694 		status = vmcs_read16(GUEST_INTR_STATUS);
3695 		if ((u8)max_irr > ((u8)status & 0xff)) {
3696 			status &= ~0xff;
3697 			status |= (u8)max_irr;
3698 			vmcs_write16(GUEST_INTR_STATUS, status);
3699 		}
3700 	}
3701 
3702 	nested_mark_vmcs12_pages_dirty(vcpu);
3703 }
3704 
3705 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3706 					       unsigned long exit_qual)
3707 {
3708 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3709 	unsigned int nr = vcpu->arch.exception.nr;
3710 	u32 intr_info = nr | INTR_INFO_VALID_MASK;
3711 
3712 	if (vcpu->arch.exception.has_error_code) {
3713 		vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3714 		intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3715 	}
3716 
3717 	if (kvm_exception_is_soft(nr))
3718 		intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3719 	else
3720 		intr_info |= INTR_TYPE_HARD_EXCEPTION;
3721 
3722 	if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3723 	    vmx_get_nmi_mask(vcpu))
3724 		intr_info |= INTR_INFO_UNBLOCK_NMI;
3725 
3726 	nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3727 }
3728 
3729 /*
3730  * Returns true if a debug trap is pending delivery.
3731  *
3732  * In KVM, debug traps bear an exception payload. As such, the class of a #DB
3733  * exception may be inferred from the presence of an exception payload.
3734  */
3735 static inline bool vmx_pending_dbg_trap(struct kvm_vcpu *vcpu)
3736 {
3737 	return vcpu->arch.exception.pending &&
3738 			vcpu->arch.exception.nr == DB_VECTOR &&
3739 			vcpu->arch.exception.payload;
3740 }
3741 
3742 /*
3743  * Certain VM-exits set the 'pending debug exceptions' field to indicate a
3744  * recognized #DB (data or single-step) that has yet to be delivered. Since KVM
3745  * represents these debug traps with a payload that is said to be compatible
3746  * with the 'pending debug exceptions' field, write the payload to the VMCS
3747  * field if a VM-exit is delivered before the debug trap.
3748  */
3749 static void nested_vmx_update_pending_dbg(struct kvm_vcpu *vcpu)
3750 {
3751 	if (vmx_pending_dbg_trap(vcpu))
3752 		vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
3753 			    vcpu->arch.exception.payload);
3754 }
3755 
3756 static bool nested_vmx_preemption_timer_pending(struct kvm_vcpu *vcpu)
3757 {
3758 	return nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
3759 	       to_vmx(vcpu)->nested.preemption_timer_expired;
3760 }
3761 
3762 static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
3763 {
3764 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3765 	unsigned long exit_qual;
3766 	bool block_nested_events =
3767 	    vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
3768 	bool mtf_pending = vmx->nested.mtf_pending;
3769 	struct kvm_lapic *apic = vcpu->arch.apic;
3770 
3771 	/*
3772 	 * Clear the MTF state. If a higher priority VM-exit is delivered first,
3773 	 * this state is discarded.
3774 	 */
3775 	if (!block_nested_events)
3776 		vmx->nested.mtf_pending = false;
3777 
3778 	if (lapic_in_kernel(vcpu) &&
3779 		test_bit(KVM_APIC_INIT, &apic->pending_events)) {
3780 		if (block_nested_events)
3781 			return -EBUSY;
3782 		nested_vmx_update_pending_dbg(vcpu);
3783 		clear_bit(KVM_APIC_INIT, &apic->pending_events);
3784 		nested_vmx_vmexit(vcpu, EXIT_REASON_INIT_SIGNAL, 0, 0);
3785 		return 0;
3786 	}
3787 
3788 	/*
3789 	 * Process any exceptions that are not debug traps before MTF.
3790 	 */
3791 	if (vcpu->arch.exception.pending && !vmx_pending_dbg_trap(vcpu)) {
3792 		if (block_nested_events)
3793 			return -EBUSY;
3794 		if (!nested_vmx_check_exception(vcpu, &exit_qual))
3795 			goto no_vmexit;
3796 		nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
3797 		return 0;
3798 	}
3799 
3800 	if (mtf_pending) {
3801 		if (block_nested_events)
3802 			return -EBUSY;
3803 		nested_vmx_update_pending_dbg(vcpu);
3804 		nested_vmx_vmexit(vcpu, EXIT_REASON_MONITOR_TRAP_FLAG, 0, 0);
3805 		return 0;
3806 	}
3807 
3808 	if (vcpu->arch.exception.pending) {
3809 		if (block_nested_events)
3810 			return -EBUSY;
3811 		if (!nested_vmx_check_exception(vcpu, &exit_qual))
3812 			goto no_vmexit;
3813 		nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
3814 		return 0;
3815 	}
3816 
3817 	if (nested_vmx_preemption_timer_pending(vcpu)) {
3818 		if (block_nested_events)
3819 			return -EBUSY;
3820 		nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
3821 		return 0;
3822 	}
3823 
3824 	if (vcpu->arch.smi_pending && !is_smm(vcpu)) {
3825 		if (block_nested_events)
3826 			return -EBUSY;
3827 		goto no_vmexit;
3828 	}
3829 
3830 	if (vcpu->arch.nmi_pending && !vmx_nmi_blocked(vcpu)) {
3831 		if (block_nested_events)
3832 			return -EBUSY;
3833 		if (!nested_exit_on_nmi(vcpu))
3834 			goto no_vmexit;
3835 
3836 		nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
3837 				  NMI_VECTOR | INTR_TYPE_NMI_INTR |
3838 				  INTR_INFO_VALID_MASK, 0);
3839 		/*
3840 		 * The NMI-triggered VM exit counts as injection:
3841 		 * clear this one and block further NMIs.
3842 		 */
3843 		vcpu->arch.nmi_pending = 0;
3844 		vmx_set_nmi_mask(vcpu, true);
3845 		return 0;
3846 	}
3847 
3848 	if (kvm_cpu_has_interrupt(vcpu) && !vmx_interrupt_blocked(vcpu)) {
3849 		if (block_nested_events)
3850 			return -EBUSY;
3851 		if (!nested_exit_on_intr(vcpu))
3852 			goto no_vmexit;
3853 		nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
3854 		return 0;
3855 	}
3856 
3857 no_vmexit:
3858 	vmx_complete_nested_posted_interrupt(vcpu);
3859 	return 0;
3860 }
3861 
3862 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
3863 {
3864 	ktime_t remaining =
3865 		hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
3866 	u64 value;
3867 
3868 	if (ktime_to_ns(remaining) <= 0)
3869 		return 0;
3870 
3871 	value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
3872 	do_div(value, 1000000);
3873 	return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
3874 }
3875 
3876 static bool is_vmcs12_ext_field(unsigned long field)
3877 {
3878 	switch (field) {
3879 	case GUEST_ES_SELECTOR:
3880 	case GUEST_CS_SELECTOR:
3881 	case GUEST_SS_SELECTOR:
3882 	case GUEST_DS_SELECTOR:
3883 	case GUEST_FS_SELECTOR:
3884 	case GUEST_GS_SELECTOR:
3885 	case GUEST_LDTR_SELECTOR:
3886 	case GUEST_TR_SELECTOR:
3887 	case GUEST_ES_LIMIT:
3888 	case GUEST_CS_LIMIT:
3889 	case GUEST_SS_LIMIT:
3890 	case GUEST_DS_LIMIT:
3891 	case GUEST_FS_LIMIT:
3892 	case GUEST_GS_LIMIT:
3893 	case GUEST_LDTR_LIMIT:
3894 	case GUEST_TR_LIMIT:
3895 	case GUEST_GDTR_LIMIT:
3896 	case GUEST_IDTR_LIMIT:
3897 	case GUEST_ES_AR_BYTES:
3898 	case GUEST_DS_AR_BYTES:
3899 	case GUEST_FS_AR_BYTES:
3900 	case GUEST_GS_AR_BYTES:
3901 	case GUEST_LDTR_AR_BYTES:
3902 	case GUEST_TR_AR_BYTES:
3903 	case GUEST_ES_BASE:
3904 	case GUEST_CS_BASE:
3905 	case GUEST_SS_BASE:
3906 	case GUEST_DS_BASE:
3907 	case GUEST_FS_BASE:
3908 	case GUEST_GS_BASE:
3909 	case GUEST_LDTR_BASE:
3910 	case GUEST_TR_BASE:
3911 	case GUEST_GDTR_BASE:
3912 	case GUEST_IDTR_BASE:
3913 	case GUEST_PENDING_DBG_EXCEPTIONS:
3914 	case GUEST_BNDCFGS:
3915 		return true;
3916 	default:
3917 		break;
3918 	}
3919 
3920 	return false;
3921 }
3922 
3923 static void sync_vmcs02_to_vmcs12_rare(struct kvm_vcpu *vcpu,
3924 				       struct vmcs12 *vmcs12)
3925 {
3926 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3927 
3928 	vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
3929 	vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
3930 	vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
3931 	vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
3932 	vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
3933 	vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
3934 	vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
3935 	vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
3936 	vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
3937 	vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
3938 	vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
3939 	vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
3940 	vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
3941 	vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
3942 	vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
3943 	vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
3944 	vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
3945 	vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
3946 	vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
3947 	vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
3948 	vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
3949 	vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
3950 	vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
3951 	vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
3952 	vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
3953 	vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
3954 	vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
3955 	vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
3956 	vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
3957 	vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
3958 	vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
3959 	vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
3960 	vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
3961 	vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
3962 	vmcs12->guest_pending_dbg_exceptions =
3963 		vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
3964 	if (kvm_mpx_supported())
3965 		vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
3966 
3967 	vmx->nested.need_sync_vmcs02_to_vmcs12_rare = false;
3968 }
3969 
3970 static void copy_vmcs02_to_vmcs12_rare(struct kvm_vcpu *vcpu,
3971 				       struct vmcs12 *vmcs12)
3972 {
3973 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3974 	int cpu;
3975 
3976 	if (!vmx->nested.need_sync_vmcs02_to_vmcs12_rare)
3977 		return;
3978 
3979 
3980 	WARN_ON_ONCE(vmx->loaded_vmcs != &vmx->vmcs01);
3981 
3982 	cpu = get_cpu();
3983 	vmx->loaded_vmcs = &vmx->nested.vmcs02;
3984 	vmx_vcpu_load_vmcs(vcpu, cpu, &vmx->vmcs01);
3985 
3986 	sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
3987 
3988 	vmx->loaded_vmcs = &vmx->vmcs01;
3989 	vmx_vcpu_load_vmcs(vcpu, cpu, &vmx->nested.vmcs02);
3990 	put_cpu();
3991 }
3992 
3993 /*
3994  * Update the guest state fields of vmcs12 to reflect changes that
3995  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
3996  * VM-entry controls is also updated, since this is really a guest
3997  * state bit.)
3998  */
3999 static void sync_vmcs02_to_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
4000 {
4001 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4002 
4003 	if (vmx->nested.hv_evmcs)
4004 		sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
4005 
4006 	vmx->nested.need_sync_vmcs02_to_vmcs12_rare = !vmx->nested.hv_evmcs;
4007 
4008 	vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
4009 	vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
4010 
4011 	vmcs12->guest_rsp = kvm_rsp_read(vcpu);
4012 	vmcs12->guest_rip = kvm_rip_read(vcpu);
4013 	vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
4014 
4015 	vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
4016 	vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
4017 
4018 	vmcs12->guest_interruptibility_info =
4019 		vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
4020 
4021 	if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
4022 		vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
4023 	else
4024 		vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
4025 
4026 	if (nested_cpu_has_preemption_timer(vmcs12) &&
4027 	    vmcs12->vm_exit_controls & VM_EXIT_SAVE_VMX_PREEMPTION_TIMER &&
4028 	    !vmx->nested.nested_run_pending)
4029 		vmcs12->vmx_preemption_timer_value =
4030 			vmx_get_preemption_timer_value(vcpu);
4031 
4032 	/*
4033 	 * In some cases (usually, nested EPT), L2 is allowed to change its
4034 	 * own CR3 without exiting. If it has changed it, we must keep it.
4035 	 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
4036 	 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
4037 	 *
4038 	 * Additionally, restore L2's PDPTR to vmcs12.
4039 	 */
4040 	if (enable_ept) {
4041 		vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
4042 		if (nested_cpu_has_ept(vmcs12) && is_pae_paging(vcpu)) {
4043 			vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
4044 			vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
4045 			vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
4046 			vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
4047 		}
4048 	}
4049 
4050 	vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
4051 
4052 	if (nested_cpu_has_vid(vmcs12))
4053 		vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
4054 
4055 	vmcs12->vm_entry_controls =
4056 		(vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
4057 		(vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
4058 
4059 	if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS)
4060 		kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
4061 
4062 	if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
4063 		vmcs12->guest_ia32_efer = vcpu->arch.efer;
4064 }
4065 
4066 /*
4067  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
4068  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
4069  * and this function updates it to reflect the changes to the guest state while
4070  * L2 was running (and perhaps made some exits which were handled directly by L0
4071  * without going back to L1), and to reflect the exit reason.
4072  * Note that we do not have to copy here all VMCS fields, just those that
4073  * could have changed by the L2 guest or the exit - i.e., the guest-state and
4074  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
4075  * which already writes to vmcs12 directly.
4076  */
4077 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
4078 			   u32 vm_exit_reason, u32 exit_intr_info,
4079 			   unsigned long exit_qualification)
4080 {
4081 	/* update exit information fields: */
4082 	vmcs12->vm_exit_reason = vm_exit_reason;
4083 	vmcs12->exit_qualification = exit_qualification;
4084 	vmcs12->vm_exit_intr_info = exit_intr_info;
4085 
4086 	vmcs12->idt_vectoring_info_field = 0;
4087 	vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4088 	vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
4089 
4090 	if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
4091 		vmcs12->launch_state = 1;
4092 
4093 		/* vm_entry_intr_info_field is cleared on exit. Emulate this
4094 		 * instead of reading the real value. */
4095 		vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
4096 
4097 		/*
4098 		 * Transfer the event that L0 or L1 may wanted to inject into
4099 		 * L2 to IDT_VECTORING_INFO_FIELD.
4100 		 */
4101 		vmcs12_save_pending_event(vcpu, vmcs12);
4102 
4103 		/*
4104 		 * According to spec, there's no need to store the guest's
4105 		 * MSRs if the exit is due to a VM-entry failure that occurs
4106 		 * during or after loading the guest state. Since this exit
4107 		 * does not fall in that category, we need to save the MSRs.
4108 		 */
4109 		if (nested_vmx_store_msr(vcpu,
4110 					 vmcs12->vm_exit_msr_store_addr,
4111 					 vmcs12->vm_exit_msr_store_count))
4112 			nested_vmx_abort(vcpu,
4113 					 VMX_ABORT_SAVE_GUEST_MSR_FAIL);
4114 	}
4115 
4116 	/*
4117 	 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
4118 	 * preserved above and would only end up incorrectly in L1.
4119 	 */
4120 	vcpu->arch.nmi_injected = false;
4121 	kvm_clear_exception_queue(vcpu);
4122 	kvm_clear_interrupt_queue(vcpu);
4123 }
4124 
4125 /*
4126  * A part of what we need to when the nested L2 guest exits and we want to
4127  * run its L1 parent, is to reset L1's guest state to the host state specified
4128  * in vmcs12.
4129  * This function is to be called not only on normal nested exit, but also on
4130  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
4131  * Failures During or After Loading Guest State").
4132  * This function should be called when the active VMCS is L1's (vmcs01).
4133  */
4134 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
4135 				   struct vmcs12 *vmcs12)
4136 {
4137 	enum vm_entry_failure_code ignored;
4138 	struct kvm_segment seg;
4139 
4140 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
4141 		vcpu->arch.efer = vmcs12->host_ia32_efer;
4142 	else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
4143 		vcpu->arch.efer |= (EFER_LMA | EFER_LME);
4144 	else
4145 		vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
4146 	vmx_set_efer(vcpu, vcpu->arch.efer);
4147 
4148 	kvm_rsp_write(vcpu, vmcs12->host_rsp);
4149 	kvm_rip_write(vcpu, vmcs12->host_rip);
4150 	vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
4151 	vmx_set_interrupt_shadow(vcpu, 0);
4152 
4153 	/*
4154 	 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
4155 	 * actually changed, because vmx_set_cr0 refers to efer set above.
4156 	 *
4157 	 * CR0_GUEST_HOST_MASK is already set in the original vmcs01
4158 	 * (KVM doesn't change it);
4159 	 */
4160 	vcpu->arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4161 	vmx_set_cr0(vcpu, vmcs12->host_cr0);
4162 
4163 	/* Same as above - no reason to call set_cr4_guest_host_mask().  */
4164 	vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
4165 	vmx_set_cr4(vcpu, vmcs12->host_cr4);
4166 
4167 	nested_ept_uninit_mmu_context(vcpu);
4168 
4169 	/*
4170 	 * Only PDPTE load can fail as the value of cr3 was checked on entry and
4171 	 * couldn't have changed.
4172 	 */
4173 	if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &ignored))
4174 		nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
4175 
4176 	if (!enable_ept)
4177 		vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
4178 
4179 	nested_vmx_transition_tlb_flush(vcpu, vmcs12, false);
4180 
4181 	vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
4182 	vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
4183 	vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
4184 	vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
4185 	vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
4186 	vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
4187 	vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
4188 
4189 	/* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
4190 	if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
4191 		vmcs_write64(GUEST_BNDCFGS, 0);
4192 
4193 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
4194 		vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
4195 		vcpu->arch.pat = vmcs12->host_ia32_pat;
4196 	}
4197 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
4198 		WARN_ON_ONCE(kvm_set_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
4199 					 vmcs12->host_ia32_perf_global_ctrl));
4200 
4201 	/* Set L1 segment info according to Intel SDM
4202 	    27.5.2 Loading Host Segment and Descriptor-Table Registers */
4203 	seg = (struct kvm_segment) {
4204 		.base = 0,
4205 		.limit = 0xFFFFFFFF,
4206 		.selector = vmcs12->host_cs_selector,
4207 		.type = 11,
4208 		.present = 1,
4209 		.s = 1,
4210 		.g = 1
4211 	};
4212 	if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
4213 		seg.l = 1;
4214 	else
4215 		seg.db = 1;
4216 	vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
4217 	seg = (struct kvm_segment) {
4218 		.base = 0,
4219 		.limit = 0xFFFFFFFF,
4220 		.type = 3,
4221 		.present = 1,
4222 		.s = 1,
4223 		.db = 1,
4224 		.g = 1
4225 	};
4226 	seg.selector = vmcs12->host_ds_selector;
4227 	vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
4228 	seg.selector = vmcs12->host_es_selector;
4229 	vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
4230 	seg.selector = vmcs12->host_ss_selector;
4231 	vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
4232 	seg.selector = vmcs12->host_fs_selector;
4233 	seg.base = vmcs12->host_fs_base;
4234 	vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
4235 	seg.selector = vmcs12->host_gs_selector;
4236 	seg.base = vmcs12->host_gs_base;
4237 	vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
4238 	seg = (struct kvm_segment) {
4239 		.base = vmcs12->host_tr_base,
4240 		.limit = 0x67,
4241 		.selector = vmcs12->host_tr_selector,
4242 		.type = 11,
4243 		.present = 1
4244 	};
4245 	vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
4246 
4247 	kvm_set_dr(vcpu, 7, 0x400);
4248 	vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4249 
4250 	if (cpu_has_vmx_msr_bitmap())
4251 		vmx_update_msr_bitmap(vcpu);
4252 
4253 	if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
4254 				vmcs12->vm_exit_msr_load_count))
4255 		nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
4256 }
4257 
4258 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
4259 {
4260 	struct shared_msr_entry *efer_msr;
4261 	unsigned int i;
4262 
4263 	if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
4264 		return vmcs_read64(GUEST_IA32_EFER);
4265 
4266 	if (cpu_has_load_ia32_efer())
4267 		return host_efer;
4268 
4269 	for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
4270 		if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
4271 			return vmx->msr_autoload.guest.val[i].value;
4272 	}
4273 
4274 	efer_msr = find_msr_entry(vmx, MSR_EFER);
4275 	if (efer_msr)
4276 		return efer_msr->data;
4277 
4278 	return host_efer;
4279 }
4280 
4281 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
4282 {
4283 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4284 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4285 	struct vmx_msr_entry g, h;
4286 	gpa_t gpa;
4287 	u32 i, j;
4288 
4289 	vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
4290 
4291 	if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
4292 		/*
4293 		 * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
4294 		 * as vmcs01.GUEST_DR7 contains a userspace defined value
4295 		 * and vcpu->arch.dr7 is not squirreled away before the
4296 		 * nested VMENTER (not worth adding a variable in nested_vmx).
4297 		 */
4298 		if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
4299 			kvm_set_dr(vcpu, 7, DR7_FIXED_1);
4300 		else
4301 			WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
4302 	}
4303 
4304 	/*
4305 	 * Note that calling vmx_set_{efer,cr0,cr4} is important as they
4306 	 * handle a variety of side effects to KVM's software model.
4307 	 */
4308 	vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
4309 
4310 	vcpu->arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4311 	vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
4312 
4313 	vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
4314 	vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
4315 
4316 	nested_ept_uninit_mmu_context(vcpu);
4317 	vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4318 	kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
4319 
4320 	/*
4321 	 * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
4322 	 * from vmcs01 (if necessary).  The PDPTRs are not loaded on
4323 	 * VMFail, like everything else we just need to ensure our
4324 	 * software model is up-to-date.
4325 	 */
4326 	if (enable_ept && is_pae_paging(vcpu))
4327 		ept_save_pdptrs(vcpu);
4328 
4329 	kvm_mmu_reset_context(vcpu);
4330 
4331 	if (cpu_has_vmx_msr_bitmap())
4332 		vmx_update_msr_bitmap(vcpu);
4333 
4334 	/*
4335 	 * This nasty bit of open coding is a compromise between blindly
4336 	 * loading L1's MSRs using the exit load lists (incorrect emulation
4337 	 * of VMFail), leaving the nested VM's MSRs in the software model
4338 	 * (incorrect behavior) and snapshotting the modified MSRs (too
4339 	 * expensive since the lists are unbound by hardware).  For each
4340 	 * MSR that was (prematurely) loaded from the nested VMEntry load
4341 	 * list, reload it from the exit load list if it exists and differs
4342 	 * from the guest value.  The intent is to stuff host state as
4343 	 * silently as possible, not to fully process the exit load list.
4344 	 */
4345 	for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
4346 		gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
4347 		if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
4348 			pr_debug_ratelimited(
4349 				"%s read MSR index failed (%u, 0x%08llx)\n",
4350 				__func__, i, gpa);
4351 			goto vmabort;
4352 		}
4353 
4354 		for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
4355 			gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
4356 			if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
4357 				pr_debug_ratelimited(
4358 					"%s read MSR failed (%u, 0x%08llx)\n",
4359 					__func__, j, gpa);
4360 				goto vmabort;
4361 			}
4362 			if (h.index != g.index)
4363 				continue;
4364 			if (h.value == g.value)
4365 				break;
4366 
4367 			if (nested_vmx_load_msr_check(vcpu, &h)) {
4368 				pr_debug_ratelimited(
4369 					"%s check failed (%u, 0x%x, 0x%x)\n",
4370 					__func__, j, h.index, h.reserved);
4371 				goto vmabort;
4372 			}
4373 
4374 			if (kvm_set_msr(vcpu, h.index, h.value)) {
4375 				pr_debug_ratelimited(
4376 					"%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
4377 					__func__, j, h.index, h.value);
4378 				goto vmabort;
4379 			}
4380 		}
4381 	}
4382 
4383 	return;
4384 
4385 vmabort:
4386 	nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
4387 }
4388 
4389 /*
4390  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
4391  * and modify vmcs12 to make it see what it would expect to see there if
4392  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
4393  */
4394 void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
4395 		       u32 exit_intr_info, unsigned long exit_qualification)
4396 {
4397 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4398 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4399 
4400 	/* trying to cancel vmlaunch/vmresume is a bug */
4401 	WARN_ON_ONCE(vmx->nested.nested_run_pending);
4402 
4403 	/* Service the TLB flush request for L2 before switching to L1. */
4404 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
4405 		kvm_vcpu_flush_tlb_current(vcpu);
4406 
4407 	leave_guest_mode(vcpu);
4408 
4409 	if (nested_cpu_has_preemption_timer(vmcs12))
4410 		hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
4411 
4412 	if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
4413 		vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
4414 
4415 	if (likely(!vmx->fail)) {
4416 		sync_vmcs02_to_vmcs12(vcpu, vmcs12);
4417 
4418 		if (vm_exit_reason != -1)
4419 			prepare_vmcs12(vcpu, vmcs12, vm_exit_reason,
4420 				       exit_intr_info, exit_qualification);
4421 
4422 		/*
4423 		 * Must happen outside of sync_vmcs02_to_vmcs12() as it will
4424 		 * also be used to capture vmcs12 cache as part of
4425 		 * capturing nVMX state for snapshot (migration).
4426 		 *
4427 		 * Otherwise, this flush will dirty guest memory at a
4428 		 * point it is already assumed by user-space to be
4429 		 * immutable.
4430 		 */
4431 		nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
4432 	} else {
4433 		/*
4434 		 * The only expected VM-instruction error is "VM entry with
4435 		 * invalid control field(s)." Anything else indicates a
4436 		 * problem with L0.  And we should never get here with a
4437 		 * VMFail of any type if early consistency checks are enabled.
4438 		 */
4439 		WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
4440 			     VMXERR_ENTRY_INVALID_CONTROL_FIELD);
4441 		WARN_ON_ONCE(nested_early_check);
4442 	}
4443 
4444 	vmx_switch_vmcs(vcpu, &vmx->vmcs01);
4445 
4446 	/* Update any VMCS fields that might have changed while L2 ran */
4447 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
4448 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
4449 	vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
4450 	if (vmx->nested.l1_tpr_threshold != -1)
4451 		vmcs_write32(TPR_THRESHOLD, vmx->nested.l1_tpr_threshold);
4452 
4453 	if (kvm_has_tsc_control)
4454 		decache_tsc_multiplier(vmx);
4455 
4456 	if (vmx->nested.change_vmcs01_virtual_apic_mode) {
4457 		vmx->nested.change_vmcs01_virtual_apic_mode = false;
4458 		vmx_set_virtual_apic_mode(vcpu);
4459 	}
4460 
4461 	/* Unpin physical memory we referred to in vmcs02 */
4462 	if (vmx->nested.apic_access_page) {
4463 		kvm_release_page_clean(vmx->nested.apic_access_page);
4464 		vmx->nested.apic_access_page = NULL;
4465 	}
4466 	kvm_vcpu_unmap(vcpu, &vmx->nested.virtual_apic_map, true);
4467 	kvm_vcpu_unmap(vcpu, &vmx->nested.pi_desc_map, true);
4468 	vmx->nested.pi_desc = NULL;
4469 
4470 	if (vmx->nested.reload_vmcs01_apic_access_page) {
4471 		vmx->nested.reload_vmcs01_apic_access_page = false;
4472 		kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4473 	}
4474 
4475 	if ((vm_exit_reason != -1) &&
4476 	    (enable_shadow_vmcs || vmx->nested.hv_evmcs))
4477 		vmx->nested.need_vmcs12_to_shadow_sync = true;
4478 
4479 	/* in case we halted in L2 */
4480 	vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4481 
4482 	if (likely(!vmx->fail)) {
4483 		if ((u16)vm_exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
4484 		    nested_exit_intr_ack_set(vcpu)) {
4485 			int irq = kvm_cpu_get_interrupt(vcpu);
4486 			WARN_ON(irq < 0);
4487 			vmcs12->vm_exit_intr_info = irq |
4488 				INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
4489 		}
4490 
4491 		if (vm_exit_reason != -1)
4492 			trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
4493 						       vmcs12->exit_qualification,
4494 						       vmcs12->idt_vectoring_info_field,
4495 						       vmcs12->vm_exit_intr_info,
4496 						       vmcs12->vm_exit_intr_error_code,
4497 						       KVM_ISA_VMX);
4498 
4499 		load_vmcs12_host_state(vcpu, vmcs12);
4500 
4501 		return;
4502 	}
4503 
4504 	/*
4505 	 * After an early L2 VM-entry failure, we're now back
4506 	 * in L1 which thinks it just finished a VMLAUNCH or
4507 	 * VMRESUME instruction, so we need to set the failure
4508 	 * flag and the VM-instruction error field of the VMCS
4509 	 * accordingly, and skip the emulated instruction.
4510 	 */
4511 	(void)nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
4512 
4513 	/*
4514 	 * Restore L1's host state to KVM's software model.  We're here
4515 	 * because a consistency check was caught by hardware, which
4516 	 * means some amount of guest state has been propagated to KVM's
4517 	 * model and needs to be unwound to the host's state.
4518 	 */
4519 	nested_vmx_restore_host_state(vcpu);
4520 
4521 	vmx->fail = 0;
4522 }
4523 
4524 /*
4525  * Decode the memory-address operand of a vmx instruction, as recorded on an
4526  * exit caused by such an instruction (run by a guest hypervisor).
4527  * On success, returns 0. When the operand is invalid, returns 1 and throws
4528  * #UD, #GP, or #SS.
4529  */
4530 int get_vmx_mem_address(struct kvm_vcpu *vcpu, unsigned long exit_qualification,
4531 			u32 vmx_instruction_info, bool wr, int len, gva_t *ret)
4532 {
4533 	gva_t off;
4534 	bool exn;
4535 	struct kvm_segment s;
4536 
4537 	/*
4538 	 * According to Vol. 3B, "Information for VM Exits Due to Instruction
4539 	 * Execution", on an exit, vmx_instruction_info holds most of the
4540 	 * addressing components of the operand. Only the displacement part
4541 	 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
4542 	 * For how an actual address is calculated from all these components,
4543 	 * refer to Vol. 1, "Operand Addressing".
4544 	 */
4545 	int  scaling = vmx_instruction_info & 3;
4546 	int  addr_size = (vmx_instruction_info >> 7) & 7;
4547 	bool is_reg = vmx_instruction_info & (1u << 10);
4548 	int  seg_reg = (vmx_instruction_info >> 15) & 7;
4549 	int  index_reg = (vmx_instruction_info >> 18) & 0xf;
4550 	bool index_is_valid = !(vmx_instruction_info & (1u << 22));
4551 	int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
4552 	bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
4553 
4554 	if (is_reg) {
4555 		kvm_queue_exception(vcpu, UD_VECTOR);
4556 		return 1;
4557 	}
4558 
4559 	/* Addr = segment_base + offset */
4560 	/* offset = base + [index * scale] + displacement */
4561 	off = exit_qualification; /* holds the displacement */
4562 	if (addr_size == 1)
4563 		off = (gva_t)sign_extend64(off, 31);
4564 	else if (addr_size == 0)
4565 		off = (gva_t)sign_extend64(off, 15);
4566 	if (base_is_valid)
4567 		off += kvm_register_read(vcpu, base_reg);
4568 	if (index_is_valid)
4569 		off += kvm_register_read(vcpu, index_reg) << scaling;
4570 	vmx_get_segment(vcpu, &s, seg_reg);
4571 
4572 	/*
4573 	 * The effective address, i.e. @off, of a memory operand is truncated
4574 	 * based on the address size of the instruction.  Note that this is
4575 	 * the *effective address*, i.e. the address prior to accounting for
4576 	 * the segment's base.
4577 	 */
4578 	if (addr_size == 1) /* 32 bit */
4579 		off &= 0xffffffff;
4580 	else if (addr_size == 0) /* 16 bit */
4581 		off &= 0xffff;
4582 
4583 	/* Checks for #GP/#SS exceptions. */
4584 	exn = false;
4585 	if (is_long_mode(vcpu)) {
4586 		/*
4587 		 * The virtual/linear address is never truncated in 64-bit
4588 		 * mode, e.g. a 32-bit address size can yield a 64-bit virtual
4589 		 * address when using FS/GS with a non-zero base.
4590 		 */
4591 		if (seg_reg == VCPU_SREG_FS || seg_reg == VCPU_SREG_GS)
4592 			*ret = s.base + off;
4593 		else
4594 			*ret = off;
4595 
4596 		/* Long mode: #GP(0)/#SS(0) if the memory address is in a
4597 		 * non-canonical form. This is the only check on the memory
4598 		 * destination for long mode!
4599 		 */
4600 		exn = is_noncanonical_address(*ret, vcpu);
4601 	} else {
4602 		/*
4603 		 * When not in long mode, the virtual/linear address is
4604 		 * unconditionally truncated to 32 bits regardless of the
4605 		 * address size.
4606 		 */
4607 		*ret = (s.base + off) & 0xffffffff;
4608 
4609 		/* Protected mode: apply checks for segment validity in the
4610 		 * following order:
4611 		 * - segment type check (#GP(0) may be thrown)
4612 		 * - usability check (#GP(0)/#SS(0))
4613 		 * - limit check (#GP(0)/#SS(0))
4614 		 */
4615 		if (wr)
4616 			/* #GP(0) if the destination operand is located in a
4617 			 * read-only data segment or any code segment.
4618 			 */
4619 			exn = ((s.type & 0xa) == 0 || (s.type & 8));
4620 		else
4621 			/* #GP(0) if the source operand is located in an
4622 			 * execute-only code segment
4623 			 */
4624 			exn = ((s.type & 0xa) == 8);
4625 		if (exn) {
4626 			kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
4627 			return 1;
4628 		}
4629 		/* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
4630 		 */
4631 		exn = (s.unusable != 0);
4632 
4633 		/*
4634 		 * Protected mode: #GP(0)/#SS(0) if the memory operand is
4635 		 * outside the segment limit.  All CPUs that support VMX ignore
4636 		 * limit checks for flat segments, i.e. segments with base==0,
4637 		 * limit==0xffffffff and of type expand-up data or code.
4638 		 */
4639 		if (!(s.base == 0 && s.limit == 0xffffffff &&
4640 		     ((s.type & 8) || !(s.type & 4))))
4641 			exn = exn || ((u64)off + len - 1 > s.limit);
4642 	}
4643 	if (exn) {
4644 		kvm_queue_exception_e(vcpu,
4645 				      seg_reg == VCPU_SREG_SS ?
4646 						SS_VECTOR : GP_VECTOR,
4647 				      0);
4648 		return 1;
4649 	}
4650 
4651 	return 0;
4652 }
4653 
4654 void nested_vmx_pmu_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
4655 {
4656 	struct vcpu_vmx *vmx;
4657 
4658 	if (!nested_vmx_allowed(vcpu))
4659 		return;
4660 
4661 	vmx = to_vmx(vcpu);
4662 	if (kvm_x86_ops.pmu_ops->is_valid_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL)) {
4663 		vmx->nested.msrs.entry_ctls_high |=
4664 				VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4665 		vmx->nested.msrs.exit_ctls_high |=
4666 				VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
4667 	} else {
4668 		vmx->nested.msrs.entry_ctls_high &=
4669 				~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4670 		vmx->nested.msrs.exit_ctls_high &=
4671 				~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4672 	}
4673 }
4674 
4675 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer,
4676 				int *ret)
4677 {
4678 	gva_t gva;
4679 	struct x86_exception e;
4680 	int r;
4681 
4682 	if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
4683 				vmcs_read32(VMX_INSTRUCTION_INFO), false,
4684 				sizeof(*vmpointer), &gva)) {
4685 		*ret = 1;
4686 		return -EINVAL;
4687 	}
4688 
4689 	r = kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e);
4690 	if (r != X86EMUL_CONTINUE) {
4691 		*ret = vmx_handle_memory_failure(vcpu, r, &e);
4692 		return -EINVAL;
4693 	}
4694 
4695 	return 0;
4696 }
4697 
4698 /*
4699  * Allocate a shadow VMCS and associate it with the currently loaded
4700  * VMCS, unless such a shadow VMCS already exists. The newly allocated
4701  * VMCS is also VMCLEARed, so that it is ready for use.
4702  */
4703 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
4704 {
4705 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4706 	struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
4707 
4708 	/*
4709 	 * We should allocate a shadow vmcs for vmcs01 only when L1
4710 	 * executes VMXON and free it when L1 executes VMXOFF.
4711 	 * As it is invalid to execute VMXON twice, we shouldn't reach
4712 	 * here when vmcs01 already have an allocated shadow vmcs.
4713 	 */
4714 	WARN_ON(loaded_vmcs == &vmx->vmcs01 && loaded_vmcs->shadow_vmcs);
4715 
4716 	if (!loaded_vmcs->shadow_vmcs) {
4717 		loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
4718 		if (loaded_vmcs->shadow_vmcs)
4719 			vmcs_clear(loaded_vmcs->shadow_vmcs);
4720 	}
4721 	return loaded_vmcs->shadow_vmcs;
4722 }
4723 
4724 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
4725 {
4726 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4727 	int r;
4728 
4729 	r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
4730 	if (r < 0)
4731 		goto out_vmcs02;
4732 
4733 	vmx->nested.cached_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL_ACCOUNT);
4734 	if (!vmx->nested.cached_vmcs12)
4735 		goto out_cached_vmcs12;
4736 
4737 	vmx->nested.cached_shadow_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL_ACCOUNT);
4738 	if (!vmx->nested.cached_shadow_vmcs12)
4739 		goto out_cached_shadow_vmcs12;
4740 
4741 	if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
4742 		goto out_shadow_vmcs;
4743 
4744 	hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
4745 		     HRTIMER_MODE_ABS_PINNED);
4746 	vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
4747 
4748 	vmx->nested.vpid02 = allocate_vpid();
4749 
4750 	vmx->nested.vmcs02_initialized = false;
4751 	vmx->nested.vmxon = true;
4752 
4753 	if (vmx_pt_mode_is_host_guest()) {
4754 		vmx->pt_desc.guest.ctl = 0;
4755 		pt_update_intercept_for_msr(vmx);
4756 	}
4757 
4758 	return 0;
4759 
4760 out_shadow_vmcs:
4761 	kfree(vmx->nested.cached_shadow_vmcs12);
4762 
4763 out_cached_shadow_vmcs12:
4764 	kfree(vmx->nested.cached_vmcs12);
4765 
4766 out_cached_vmcs12:
4767 	free_loaded_vmcs(&vmx->nested.vmcs02);
4768 
4769 out_vmcs02:
4770 	return -ENOMEM;
4771 }
4772 
4773 /*
4774  * Emulate the VMXON instruction.
4775  * Currently, we just remember that VMX is active, and do not save or even
4776  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
4777  * do not currently need to store anything in that guest-allocated memory
4778  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
4779  * argument is different from the VMXON pointer (which the spec says they do).
4780  */
4781 static int handle_vmon(struct kvm_vcpu *vcpu)
4782 {
4783 	int ret;
4784 	gpa_t vmptr;
4785 	uint32_t revision;
4786 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4787 	const u64 VMXON_NEEDED_FEATURES = FEAT_CTL_LOCKED
4788 		| FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
4789 
4790 	/*
4791 	 * The Intel VMX Instruction Reference lists a bunch of bits that are
4792 	 * prerequisite to running VMXON, most notably cr4.VMXE must be set to
4793 	 * 1 (see vmx_set_cr4() for when we allow the guest to set this).
4794 	 * Otherwise, we should fail with #UD.  But most faulting conditions
4795 	 * have already been checked by hardware, prior to the VM-exit for
4796 	 * VMXON.  We do test guest cr4.VMXE because processor CR4 always has
4797 	 * that bit set to 1 in non-root mode.
4798 	 */
4799 	if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
4800 		kvm_queue_exception(vcpu, UD_VECTOR);
4801 		return 1;
4802 	}
4803 
4804 	/* CPL=0 must be checked manually. */
4805 	if (vmx_get_cpl(vcpu)) {
4806 		kvm_inject_gp(vcpu, 0);
4807 		return 1;
4808 	}
4809 
4810 	if (vmx->nested.vmxon)
4811 		return nested_vmx_fail(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
4812 
4813 	if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
4814 			!= VMXON_NEEDED_FEATURES) {
4815 		kvm_inject_gp(vcpu, 0);
4816 		return 1;
4817 	}
4818 
4819 	if (nested_vmx_get_vmptr(vcpu, &vmptr, &ret))
4820 		return ret;
4821 
4822 	/*
4823 	 * SDM 3: 24.11.5
4824 	 * The first 4 bytes of VMXON region contain the supported
4825 	 * VMCS revision identifier
4826 	 *
4827 	 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
4828 	 * which replaces physical address width with 32
4829 	 */
4830 	if (!page_address_valid(vcpu, vmptr))
4831 		return nested_vmx_failInvalid(vcpu);
4832 
4833 	if (kvm_read_guest(vcpu->kvm, vmptr, &revision, sizeof(revision)) ||
4834 	    revision != VMCS12_REVISION)
4835 		return nested_vmx_failInvalid(vcpu);
4836 
4837 	vmx->nested.vmxon_ptr = vmptr;
4838 	ret = enter_vmx_operation(vcpu);
4839 	if (ret)
4840 		return ret;
4841 
4842 	return nested_vmx_succeed(vcpu);
4843 }
4844 
4845 static inline void nested_release_vmcs12(struct kvm_vcpu *vcpu)
4846 {
4847 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4848 
4849 	if (vmx->nested.current_vmptr == -1ull)
4850 		return;
4851 
4852 	copy_vmcs02_to_vmcs12_rare(vcpu, get_vmcs12(vcpu));
4853 
4854 	if (enable_shadow_vmcs) {
4855 		/* copy to memory all shadowed fields in case
4856 		   they were modified */
4857 		copy_shadow_to_vmcs12(vmx);
4858 		vmx_disable_shadow_vmcs(vmx);
4859 	}
4860 	vmx->nested.posted_intr_nv = -1;
4861 
4862 	/* Flush VMCS12 to guest memory */
4863 	kvm_vcpu_write_guest_page(vcpu,
4864 				  vmx->nested.current_vmptr >> PAGE_SHIFT,
4865 				  vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
4866 
4867 	kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
4868 
4869 	vmx->nested.current_vmptr = -1ull;
4870 }
4871 
4872 /* Emulate the VMXOFF instruction */
4873 static int handle_vmoff(struct kvm_vcpu *vcpu)
4874 {
4875 	if (!nested_vmx_check_permission(vcpu))
4876 		return 1;
4877 
4878 	free_nested(vcpu);
4879 
4880 	/* Process a latched INIT during time CPU was in VMX operation */
4881 	kvm_make_request(KVM_REQ_EVENT, vcpu);
4882 
4883 	return nested_vmx_succeed(vcpu);
4884 }
4885 
4886 /* Emulate the VMCLEAR instruction */
4887 static int handle_vmclear(struct kvm_vcpu *vcpu)
4888 {
4889 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4890 	u32 zero = 0;
4891 	gpa_t vmptr;
4892 	u64 evmcs_gpa;
4893 	int r;
4894 
4895 	if (!nested_vmx_check_permission(vcpu))
4896 		return 1;
4897 
4898 	if (nested_vmx_get_vmptr(vcpu, &vmptr, &r))
4899 		return r;
4900 
4901 	if (!page_address_valid(vcpu, vmptr))
4902 		return nested_vmx_fail(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
4903 
4904 	if (vmptr == vmx->nested.vmxon_ptr)
4905 		return nested_vmx_fail(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
4906 
4907 	/*
4908 	 * When Enlightened VMEntry is enabled on the calling CPU we treat
4909 	 * memory area pointer by vmptr as Enlightened VMCS (as there's no good
4910 	 * way to distinguish it from VMCS12) and we must not corrupt it by
4911 	 * writing to the non-existent 'launch_state' field. The area doesn't
4912 	 * have to be the currently active EVMCS on the calling CPU and there's
4913 	 * nothing KVM has to do to transition it from 'active' to 'non-active'
4914 	 * state. It is possible that the area will stay mapped as
4915 	 * vmx->nested.hv_evmcs but this shouldn't be a problem.
4916 	 */
4917 	if (likely(!vmx->nested.enlightened_vmcs_enabled ||
4918 		   !nested_enlightened_vmentry(vcpu, &evmcs_gpa))) {
4919 		if (vmptr == vmx->nested.current_vmptr)
4920 			nested_release_vmcs12(vcpu);
4921 
4922 		kvm_vcpu_write_guest(vcpu,
4923 				     vmptr + offsetof(struct vmcs12,
4924 						      launch_state),
4925 				     &zero, sizeof(zero));
4926 	}
4927 
4928 	return nested_vmx_succeed(vcpu);
4929 }
4930 
4931 /* Emulate the VMLAUNCH instruction */
4932 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
4933 {
4934 	return nested_vmx_run(vcpu, true);
4935 }
4936 
4937 /* Emulate the VMRESUME instruction */
4938 static int handle_vmresume(struct kvm_vcpu *vcpu)
4939 {
4940 
4941 	return nested_vmx_run(vcpu, false);
4942 }
4943 
4944 static int handle_vmread(struct kvm_vcpu *vcpu)
4945 {
4946 	struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
4947 						    : get_vmcs12(vcpu);
4948 	unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
4949 	u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
4950 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4951 	struct x86_exception e;
4952 	unsigned long field;
4953 	u64 value;
4954 	gva_t gva = 0;
4955 	short offset;
4956 	int len, r;
4957 
4958 	if (!nested_vmx_check_permission(vcpu))
4959 		return 1;
4960 
4961 	/*
4962 	 * In VMX non-root operation, when the VMCS-link pointer is -1ull,
4963 	 * any VMREAD sets the ALU flags for VMfailInvalid.
4964 	 */
4965 	if (vmx->nested.current_vmptr == -1ull ||
4966 	    (is_guest_mode(vcpu) &&
4967 	     get_vmcs12(vcpu)->vmcs_link_pointer == -1ull))
4968 		return nested_vmx_failInvalid(vcpu);
4969 
4970 	/* Decode instruction info and find the field to read */
4971 	field = kvm_register_readl(vcpu, (((instr_info) >> 28) & 0xf));
4972 
4973 	offset = vmcs_field_to_offset(field);
4974 	if (offset < 0)
4975 		return nested_vmx_fail(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
4976 
4977 	if (!is_guest_mode(vcpu) && is_vmcs12_ext_field(field))
4978 		copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
4979 
4980 	/* Read the field, zero-extended to a u64 value */
4981 	value = vmcs12_read_any(vmcs12, field, offset);
4982 
4983 	/*
4984 	 * Now copy part of this value to register or memory, as requested.
4985 	 * Note that the number of bits actually copied is 32 or 64 depending
4986 	 * on the guest's mode (32 or 64 bit), not on the given field's length.
4987 	 */
4988 	if (instr_info & BIT(10)) {
4989 		kvm_register_writel(vcpu, (((instr_info) >> 3) & 0xf), value);
4990 	} else {
4991 		len = is_64_bit_mode(vcpu) ? 8 : 4;
4992 		if (get_vmx_mem_address(vcpu, exit_qualification,
4993 					instr_info, true, len, &gva))
4994 			return 1;
4995 		/* _system ok, nested_vmx_check_permission has verified cpl=0 */
4996 		r = kvm_write_guest_virt_system(vcpu, gva, &value, len, &e);
4997 		if (r != X86EMUL_CONTINUE)
4998 			return vmx_handle_memory_failure(vcpu, r, &e);
4999 	}
5000 
5001 	return nested_vmx_succeed(vcpu);
5002 }
5003 
5004 static bool is_shadow_field_rw(unsigned long field)
5005 {
5006 	switch (field) {
5007 #define SHADOW_FIELD_RW(x, y) case x:
5008 #include "vmcs_shadow_fields.h"
5009 		return true;
5010 	default:
5011 		break;
5012 	}
5013 	return false;
5014 }
5015 
5016 static bool is_shadow_field_ro(unsigned long field)
5017 {
5018 	switch (field) {
5019 #define SHADOW_FIELD_RO(x, y) case x:
5020 #include "vmcs_shadow_fields.h"
5021 		return true;
5022 	default:
5023 		break;
5024 	}
5025 	return false;
5026 }
5027 
5028 static int handle_vmwrite(struct kvm_vcpu *vcpu)
5029 {
5030 	struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
5031 						    : get_vmcs12(vcpu);
5032 	unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5033 	u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5034 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5035 	struct x86_exception e;
5036 	unsigned long field;
5037 	short offset;
5038 	gva_t gva;
5039 	int len, r;
5040 
5041 	/*
5042 	 * The value to write might be 32 or 64 bits, depending on L1's long
5043 	 * mode, and eventually we need to write that into a field of several
5044 	 * possible lengths. The code below first zero-extends the value to 64
5045 	 * bit (value), and then copies only the appropriate number of
5046 	 * bits into the vmcs12 field.
5047 	 */
5048 	u64 value = 0;
5049 
5050 	if (!nested_vmx_check_permission(vcpu))
5051 		return 1;
5052 
5053 	/*
5054 	 * In VMX non-root operation, when the VMCS-link pointer is -1ull,
5055 	 * any VMWRITE sets the ALU flags for VMfailInvalid.
5056 	 */
5057 	if (vmx->nested.current_vmptr == -1ull ||
5058 	    (is_guest_mode(vcpu) &&
5059 	     get_vmcs12(vcpu)->vmcs_link_pointer == -1ull))
5060 		return nested_vmx_failInvalid(vcpu);
5061 
5062 	if (instr_info & BIT(10))
5063 		value = kvm_register_readl(vcpu, (((instr_info) >> 3) & 0xf));
5064 	else {
5065 		len = is_64_bit_mode(vcpu) ? 8 : 4;
5066 		if (get_vmx_mem_address(vcpu, exit_qualification,
5067 					instr_info, false, len, &gva))
5068 			return 1;
5069 		r = kvm_read_guest_virt(vcpu, gva, &value, len, &e);
5070 		if (r != X86EMUL_CONTINUE)
5071 			return vmx_handle_memory_failure(vcpu, r, &e);
5072 	}
5073 
5074 	field = kvm_register_readl(vcpu, (((instr_info) >> 28) & 0xf));
5075 
5076 	offset = vmcs_field_to_offset(field);
5077 	if (offset < 0)
5078 		return nested_vmx_fail(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5079 
5080 	/*
5081 	 * If the vCPU supports "VMWRITE to any supported field in the
5082 	 * VMCS," then the "read-only" fields are actually read/write.
5083 	 */
5084 	if (vmcs_field_readonly(field) &&
5085 	    !nested_cpu_has_vmwrite_any_field(vcpu))
5086 		return nested_vmx_fail(vcpu, VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
5087 
5088 	/*
5089 	 * Ensure vmcs12 is up-to-date before any VMWRITE that dirties
5090 	 * vmcs12, else we may crush a field or consume a stale value.
5091 	 */
5092 	if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field))
5093 		copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
5094 
5095 	/*
5096 	 * Some Intel CPUs intentionally drop the reserved bits of the AR byte
5097 	 * fields on VMWRITE.  Emulate this behavior to ensure consistent KVM
5098 	 * behavior regardless of the underlying hardware, e.g. if an AR_BYTE
5099 	 * field is intercepted for VMWRITE but not VMREAD (in L1), then VMREAD
5100 	 * from L1 will return a different value than VMREAD from L2 (L1 sees
5101 	 * the stripped down value, L2 sees the full value as stored by KVM).
5102 	 */
5103 	if (field >= GUEST_ES_AR_BYTES && field <= GUEST_TR_AR_BYTES)
5104 		value &= 0x1f0ff;
5105 
5106 	vmcs12_write_any(vmcs12, field, offset, value);
5107 
5108 	/*
5109 	 * Do not track vmcs12 dirty-state if in guest-mode as we actually
5110 	 * dirty shadow vmcs12 instead of vmcs12.  Fields that can be updated
5111 	 * by L1 without a vmexit are always updated in the vmcs02, i.e. don't
5112 	 * "dirty" vmcs12, all others go down the prepare_vmcs02() slow path.
5113 	 */
5114 	if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field)) {
5115 		/*
5116 		 * L1 can read these fields without exiting, ensure the
5117 		 * shadow VMCS is up-to-date.
5118 		 */
5119 		if (enable_shadow_vmcs && is_shadow_field_ro(field)) {
5120 			preempt_disable();
5121 			vmcs_load(vmx->vmcs01.shadow_vmcs);
5122 
5123 			__vmcs_writel(field, value);
5124 
5125 			vmcs_clear(vmx->vmcs01.shadow_vmcs);
5126 			vmcs_load(vmx->loaded_vmcs->vmcs);
5127 			preempt_enable();
5128 		}
5129 		vmx->nested.dirty_vmcs12 = true;
5130 	}
5131 
5132 	return nested_vmx_succeed(vcpu);
5133 }
5134 
5135 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
5136 {
5137 	vmx->nested.current_vmptr = vmptr;
5138 	if (enable_shadow_vmcs) {
5139 		secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_SHADOW_VMCS);
5140 		vmcs_write64(VMCS_LINK_POINTER,
5141 			     __pa(vmx->vmcs01.shadow_vmcs));
5142 		vmx->nested.need_vmcs12_to_shadow_sync = true;
5143 	}
5144 	vmx->nested.dirty_vmcs12 = true;
5145 }
5146 
5147 /* Emulate the VMPTRLD instruction */
5148 static int handle_vmptrld(struct kvm_vcpu *vcpu)
5149 {
5150 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5151 	gpa_t vmptr;
5152 	int r;
5153 
5154 	if (!nested_vmx_check_permission(vcpu))
5155 		return 1;
5156 
5157 	if (nested_vmx_get_vmptr(vcpu, &vmptr, &r))
5158 		return r;
5159 
5160 	if (!page_address_valid(vcpu, vmptr))
5161 		return nested_vmx_fail(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
5162 
5163 	if (vmptr == vmx->nested.vmxon_ptr)
5164 		return nested_vmx_fail(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
5165 
5166 	/* Forbid normal VMPTRLD if Enlightened version was used */
5167 	if (vmx->nested.hv_evmcs)
5168 		return 1;
5169 
5170 	if (vmx->nested.current_vmptr != vmptr) {
5171 		struct kvm_host_map map;
5172 		struct vmcs12 *new_vmcs12;
5173 
5174 		if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmptr), &map)) {
5175 			/*
5176 			 * Reads from an unbacked page return all 1s,
5177 			 * which means that the 32 bits located at the
5178 			 * given physical address won't match the required
5179 			 * VMCS12_REVISION identifier.
5180 			 */
5181 			return nested_vmx_fail(vcpu,
5182 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5183 		}
5184 
5185 		new_vmcs12 = map.hva;
5186 
5187 		if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
5188 		    (new_vmcs12->hdr.shadow_vmcs &&
5189 		     !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
5190 			kvm_vcpu_unmap(vcpu, &map, false);
5191 			return nested_vmx_fail(vcpu,
5192 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5193 		}
5194 
5195 		nested_release_vmcs12(vcpu);
5196 
5197 		/*
5198 		 * Load VMCS12 from guest memory since it is not already
5199 		 * cached.
5200 		 */
5201 		memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
5202 		kvm_vcpu_unmap(vcpu, &map, false);
5203 
5204 		set_current_vmptr(vmx, vmptr);
5205 	}
5206 
5207 	return nested_vmx_succeed(vcpu);
5208 }
5209 
5210 /* Emulate the VMPTRST instruction */
5211 static int handle_vmptrst(struct kvm_vcpu *vcpu)
5212 {
5213 	unsigned long exit_qual = vmx_get_exit_qual(vcpu);
5214 	u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5215 	gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
5216 	struct x86_exception e;
5217 	gva_t gva;
5218 	int r;
5219 
5220 	if (!nested_vmx_check_permission(vcpu))
5221 		return 1;
5222 
5223 	if (unlikely(to_vmx(vcpu)->nested.hv_evmcs))
5224 		return 1;
5225 
5226 	if (get_vmx_mem_address(vcpu, exit_qual, instr_info,
5227 				true, sizeof(gpa_t), &gva))
5228 		return 1;
5229 	/* *_system ok, nested_vmx_check_permission has verified cpl=0 */
5230 	r = kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
5231 					sizeof(gpa_t), &e);
5232 	if (r != X86EMUL_CONTINUE)
5233 		return vmx_handle_memory_failure(vcpu, r, &e);
5234 
5235 	return nested_vmx_succeed(vcpu);
5236 }
5237 
5238 #define EPTP_PA_MASK   GENMASK_ULL(51, 12)
5239 
5240 static bool nested_ept_root_matches(hpa_t root_hpa, u64 root_eptp, u64 eptp)
5241 {
5242 	return VALID_PAGE(root_hpa) &&
5243 		((root_eptp & EPTP_PA_MASK) == (eptp & EPTP_PA_MASK));
5244 }
5245 
5246 /* Emulate the INVEPT instruction */
5247 static int handle_invept(struct kvm_vcpu *vcpu)
5248 {
5249 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5250 	u32 vmx_instruction_info, types;
5251 	unsigned long type, roots_to_free;
5252 	struct kvm_mmu *mmu;
5253 	gva_t gva;
5254 	struct x86_exception e;
5255 	struct {
5256 		u64 eptp, gpa;
5257 	} operand;
5258 	int i, r;
5259 
5260 	if (!(vmx->nested.msrs.secondary_ctls_high &
5261 	      SECONDARY_EXEC_ENABLE_EPT) ||
5262 	    !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
5263 		kvm_queue_exception(vcpu, UD_VECTOR);
5264 		return 1;
5265 	}
5266 
5267 	if (!nested_vmx_check_permission(vcpu))
5268 		return 1;
5269 
5270 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5271 	type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5272 
5273 	types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
5274 
5275 	if (type >= 32 || !(types & (1 << type)))
5276 		return nested_vmx_fail(vcpu, VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5277 
5278 	/* According to the Intel VMX instruction reference, the memory
5279 	 * operand is read even if it isn't needed (e.g., for type==global)
5280 	 */
5281 	if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5282 			vmx_instruction_info, false, sizeof(operand), &gva))
5283 		return 1;
5284 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
5285 	if (r != X86EMUL_CONTINUE)
5286 		return vmx_handle_memory_failure(vcpu, r, &e);
5287 
5288 	/*
5289 	 * Nested EPT roots are always held through guest_mmu,
5290 	 * not root_mmu.
5291 	 */
5292 	mmu = &vcpu->arch.guest_mmu;
5293 
5294 	switch (type) {
5295 	case VMX_EPT_EXTENT_CONTEXT:
5296 		if (!nested_vmx_check_eptp(vcpu, operand.eptp))
5297 			return nested_vmx_fail(vcpu,
5298 				VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5299 
5300 		roots_to_free = 0;
5301 		if (nested_ept_root_matches(mmu->root_hpa, mmu->root_pgd,
5302 					    operand.eptp))
5303 			roots_to_free |= KVM_MMU_ROOT_CURRENT;
5304 
5305 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5306 			if (nested_ept_root_matches(mmu->prev_roots[i].hpa,
5307 						    mmu->prev_roots[i].pgd,
5308 						    operand.eptp))
5309 				roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5310 		}
5311 		break;
5312 	case VMX_EPT_EXTENT_GLOBAL:
5313 		roots_to_free = KVM_MMU_ROOTS_ALL;
5314 		break;
5315 	default:
5316 		BUG();
5317 		break;
5318 	}
5319 
5320 	if (roots_to_free)
5321 		kvm_mmu_free_roots(vcpu, mmu, roots_to_free);
5322 
5323 	return nested_vmx_succeed(vcpu);
5324 }
5325 
5326 static int handle_invvpid(struct kvm_vcpu *vcpu)
5327 {
5328 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5329 	u32 vmx_instruction_info;
5330 	unsigned long type, types;
5331 	gva_t gva;
5332 	struct x86_exception e;
5333 	struct {
5334 		u64 vpid;
5335 		u64 gla;
5336 	} operand;
5337 	u16 vpid02;
5338 	int r;
5339 
5340 	if (!(vmx->nested.msrs.secondary_ctls_high &
5341 	      SECONDARY_EXEC_ENABLE_VPID) ||
5342 			!(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
5343 		kvm_queue_exception(vcpu, UD_VECTOR);
5344 		return 1;
5345 	}
5346 
5347 	if (!nested_vmx_check_permission(vcpu))
5348 		return 1;
5349 
5350 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5351 	type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5352 
5353 	types = (vmx->nested.msrs.vpid_caps &
5354 			VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
5355 
5356 	if (type >= 32 || !(types & (1 << type)))
5357 		return nested_vmx_fail(vcpu,
5358 			VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5359 
5360 	/* according to the intel vmx instruction reference, the memory
5361 	 * operand is read even if it isn't needed (e.g., for type==global)
5362 	 */
5363 	if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5364 			vmx_instruction_info, false, sizeof(operand), &gva))
5365 		return 1;
5366 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
5367 	if (r != X86EMUL_CONTINUE)
5368 		return vmx_handle_memory_failure(vcpu, r, &e);
5369 
5370 	if (operand.vpid >> 16)
5371 		return nested_vmx_fail(vcpu,
5372 			VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5373 
5374 	vpid02 = nested_get_vpid02(vcpu);
5375 	switch (type) {
5376 	case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
5377 		if (!operand.vpid ||
5378 		    is_noncanonical_address(operand.gla, vcpu))
5379 			return nested_vmx_fail(vcpu,
5380 				VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5381 		vpid_sync_vcpu_addr(vpid02, operand.gla);
5382 		break;
5383 	case VMX_VPID_EXTENT_SINGLE_CONTEXT:
5384 	case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
5385 		if (!operand.vpid)
5386 			return nested_vmx_fail(vcpu,
5387 				VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5388 		vpid_sync_context(vpid02);
5389 		break;
5390 	case VMX_VPID_EXTENT_ALL_CONTEXT:
5391 		vpid_sync_context(vpid02);
5392 		break;
5393 	default:
5394 		WARN_ON_ONCE(1);
5395 		return kvm_skip_emulated_instruction(vcpu);
5396 	}
5397 
5398 	/*
5399 	 * Sync the shadow page tables if EPT is disabled, L1 is invalidating
5400 	 * linear mappings for L2 (tagged with L2's VPID).  Free all roots as
5401 	 * VPIDs are not tracked in the MMU role.
5402 	 *
5403 	 * Note, this operates on root_mmu, not guest_mmu, as L1 and L2 share
5404 	 * an MMU when EPT is disabled.
5405 	 *
5406 	 * TODO: sync only the affected SPTEs for INVDIVIDUAL_ADDR.
5407 	 */
5408 	if (!enable_ept)
5409 		kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu,
5410 				   KVM_MMU_ROOTS_ALL);
5411 
5412 	return nested_vmx_succeed(vcpu);
5413 }
5414 
5415 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
5416 				     struct vmcs12 *vmcs12)
5417 {
5418 	u32 index = kvm_rcx_read(vcpu);
5419 	u64 new_eptp;
5420 	bool accessed_dirty;
5421 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5422 
5423 	if (!nested_cpu_has_eptp_switching(vmcs12) ||
5424 	    !nested_cpu_has_ept(vmcs12))
5425 		return 1;
5426 
5427 	if (index >= VMFUNC_EPTP_ENTRIES)
5428 		return 1;
5429 
5430 
5431 	if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
5432 				     &new_eptp, index * 8, 8))
5433 		return 1;
5434 
5435 	accessed_dirty = !!(new_eptp & VMX_EPTP_AD_ENABLE_BIT);
5436 
5437 	/*
5438 	 * If the (L2) guest does a vmfunc to the currently
5439 	 * active ept pointer, we don't have to do anything else
5440 	 */
5441 	if (vmcs12->ept_pointer != new_eptp) {
5442 		if (!nested_vmx_check_eptp(vcpu, new_eptp))
5443 			return 1;
5444 
5445 		kvm_mmu_unload(vcpu);
5446 		mmu->ept_ad = accessed_dirty;
5447 		mmu->mmu_role.base.ad_disabled = !accessed_dirty;
5448 		vmcs12->ept_pointer = new_eptp;
5449 		/*
5450 		 * TODO: Check what's the correct approach in case
5451 		 * mmu reload fails. Currently, we just let the next
5452 		 * reload potentially fail
5453 		 */
5454 		kvm_mmu_reload(vcpu);
5455 	}
5456 
5457 	return 0;
5458 }
5459 
5460 static int handle_vmfunc(struct kvm_vcpu *vcpu)
5461 {
5462 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5463 	struct vmcs12 *vmcs12;
5464 	u32 function = kvm_rax_read(vcpu);
5465 
5466 	/*
5467 	 * VMFUNC is only supported for nested guests, but we always enable the
5468 	 * secondary control for simplicity; for non-nested mode, fake that we
5469 	 * didn't by injecting #UD.
5470 	 */
5471 	if (!is_guest_mode(vcpu)) {
5472 		kvm_queue_exception(vcpu, UD_VECTOR);
5473 		return 1;
5474 	}
5475 
5476 	vmcs12 = get_vmcs12(vcpu);
5477 	if ((vmcs12->vm_function_control & (1 << function)) == 0)
5478 		goto fail;
5479 
5480 	switch (function) {
5481 	case 0:
5482 		if (nested_vmx_eptp_switching(vcpu, vmcs12))
5483 			goto fail;
5484 		break;
5485 	default:
5486 		goto fail;
5487 	}
5488 	return kvm_skip_emulated_instruction(vcpu);
5489 
5490 fail:
5491 	nested_vmx_vmexit(vcpu, vmx->exit_reason,
5492 			  vmx_get_intr_info(vcpu),
5493 			  vmx_get_exit_qual(vcpu));
5494 	return 1;
5495 }
5496 
5497 /*
5498  * Return true if an IO instruction with the specified port and size should cause
5499  * a VM-exit into L1.
5500  */
5501 bool nested_vmx_check_io_bitmaps(struct kvm_vcpu *vcpu, unsigned int port,
5502 				 int size)
5503 {
5504 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5505 	gpa_t bitmap, last_bitmap;
5506 	u8 b;
5507 
5508 	last_bitmap = (gpa_t)-1;
5509 	b = -1;
5510 
5511 	while (size > 0) {
5512 		if (port < 0x8000)
5513 			bitmap = vmcs12->io_bitmap_a;
5514 		else if (port < 0x10000)
5515 			bitmap = vmcs12->io_bitmap_b;
5516 		else
5517 			return true;
5518 		bitmap += (port & 0x7fff) / 8;
5519 
5520 		if (last_bitmap != bitmap)
5521 			if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
5522 				return true;
5523 		if (b & (1 << (port & 7)))
5524 			return true;
5525 
5526 		port++;
5527 		size--;
5528 		last_bitmap = bitmap;
5529 	}
5530 
5531 	return false;
5532 }
5533 
5534 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
5535 				       struct vmcs12 *vmcs12)
5536 {
5537 	unsigned long exit_qualification;
5538 	unsigned short port;
5539 	int size;
5540 
5541 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
5542 		return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
5543 
5544 	exit_qualification = vmx_get_exit_qual(vcpu);
5545 
5546 	port = exit_qualification >> 16;
5547 	size = (exit_qualification & 7) + 1;
5548 
5549 	return nested_vmx_check_io_bitmaps(vcpu, port, size);
5550 }
5551 
5552 /*
5553  * Return 1 if we should exit from L2 to L1 to handle an MSR access,
5554  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
5555  * disinterest in the current event (read or write a specific MSR) by using an
5556  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
5557  */
5558 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
5559 	struct vmcs12 *vmcs12, u32 exit_reason)
5560 {
5561 	u32 msr_index = kvm_rcx_read(vcpu);
5562 	gpa_t bitmap;
5563 
5564 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
5565 		return true;
5566 
5567 	/*
5568 	 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
5569 	 * for the four combinations of read/write and low/high MSR numbers.
5570 	 * First we need to figure out which of the four to use:
5571 	 */
5572 	bitmap = vmcs12->msr_bitmap;
5573 	if (exit_reason == EXIT_REASON_MSR_WRITE)
5574 		bitmap += 2048;
5575 	if (msr_index >= 0xc0000000) {
5576 		msr_index -= 0xc0000000;
5577 		bitmap += 1024;
5578 	}
5579 
5580 	/* Then read the msr_index'th bit from this bitmap: */
5581 	if (msr_index < 1024*8) {
5582 		unsigned char b;
5583 		if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
5584 			return true;
5585 		return 1 & (b >> (msr_index & 7));
5586 	} else
5587 		return true; /* let L1 handle the wrong parameter */
5588 }
5589 
5590 /*
5591  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
5592  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
5593  * intercept (via guest_host_mask etc.) the current event.
5594  */
5595 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
5596 	struct vmcs12 *vmcs12)
5597 {
5598 	unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5599 	int cr = exit_qualification & 15;
5600 	int reg;
5601 	unsigned long val;
5602 
5603 	switch ((exit_qualification >> 4) & 3) {
5604 	case 0: /* mov to cr */
5605 		reg = (exit_qualification >> 8) & 15;
5606 		val = kvm_register_readl(vcpu, reg);
5607 		switch (cr) {
5608 		case 0:
5609 			if (vmcs12->cr0_guest_host_mask &
5610 			    (val ^ vmcs12->cr0_read_shadow))
5611 				return true;
5612 			break;
5613 		case 3:
5614 			if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
5615 				return true;
5616 			break;
5617 		case 4:
5618 			if (vmcs12->cr4_guest_host_mask &
5619 			    (vmcs12->cr4_read_shadow ^ val))
5620 				return true;
5621 			break;
5622 		case 8:
5623 			if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
5624 				return true;
5625 			break;
5626 		}
5627 		break;
5628 	case 2: /* clts */
5629 		if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
5630 		    (vmcs12->cr0_read_shadow & X86_CR0_TS))
5631 			return true;
5632 		break;
5633 	case 1: /* mov from cr */
5634 		switch (cr) {
5635 		case 3:
5636 			if (vmcs12->cpu_based_vm_exec_control &
5637 			    CPU_BASED_CR3_STORE_EXITING)
5638 				return true;
5639 			break;
5640 		case 8:
5641 			if (vmcs12->cpu_based_vm_exec_control &
5642 			    CPU_BASED_CR8_STORE_EXITING)
5643 				return true;
5644 			break;
5645 		}
5646 		break;
5647 	case 3: /* lmsw */
5648 		/*
5649 		 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
5650 		 * cr0. Other attempted changes are ignored, with no exit.
5651 		 */
5652 		val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5653 		if (vmcs12->cr0_guest_host_mask & 0xe &
5654 		    (val ^ vmcs12->cr0_read_shadow))
5655 			return true;
5656 		if ((vmcs12->cr0_guest_host_mask & 0x1) &&
5657 		    !(vmcs12->cr0_read_shadow & 0x1) &&
5658 		    (val & 0x1))
5659 			return true;
5660 		break;
5661 	}
5662 	return false;
5663 }
5664 
5665 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
5666 	struct vmcs12 *vmcs12, gpa_t bitmap)
5667 {
5668 	u32 vmx_instruction_info;
5669 	unsigned long field;
5670 	u8 b;
5671 
5672 	if (!nested_cpu_has_shadow_vmcs(vmcs12))
5673 		return true;
5674 
5675 	/* Decode instruction info and find the field to access */
5676 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5677 	field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
5678 
5679 	/* Out-of-range fields always cause a VM exit from L2 to L1 */
5680 	if (field >> 15)
5681 		return true;
5682 
5683 	if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
5684 		return true;
5685 
5686 	return 1 & (b >> (field & 7));
5687 }
5688 
5689 static bool nested_vmx_exit_handled_mtf(struct vmcs12 *vmcs12)
5690 {
5691 	u32 entry_intr_info = vmcs12->vm_entry_intr_info_field;
5692 
5693 	if (nested_cpu_has_mtf(vmcs12))
5694 		return true;
5695 
5696 	/*
5697 	 * An MTF VM-exit may be injected into the guest by setting the
5698 	 * interruption-type to 7 (other event) and the vector field to 0. Such
5699 	 * is the case regardless of the 'monitor trap flag' VM-execution
5700 	 * control.
5701 	 */
5702 	return entry_intr_info == (INTR_INFO_VALID_MASK
5703 				   | INTR_TYPE_OTHER_EVENT);
5704 }
5705 
5706 /*
5707  * Return true if L0 wants to handle an exit from L2 regardless of whether or not
5708  * L1 wants the exit.  Only call this when in is_guest_mode (L2).
5709  */
5710 static bool nested_vmx_l0_wants_exit(struct kvm_vcpu *vcpu, u32 exit_reason)
5711 {
5712 	u32 intr_info;
5713 
5714 	switch ((u16)exit_reason) {
5715 	case EXIT_REASON_EXCEPTION_NMI:
5716 		intr_info = vmx_get_intr_info(vcpu);
5717 		if (is_nmi(intr_info))
5718 			return true;
5719 		else if (is_page_fault(intr_info))
5720 			return vcpu->arch.apf.host_apf_flags || !enable_ept;
5721 		else if (is_debug(intr_info) &&
5722 			 vcpu->guest_debug &
5723 			 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
5724 			return true;
5725 		else if (is_breakpoint(intr_info) &&
5726 			 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5727 			return true;
5728 		return false;
5729 	case EXIT_REASON_EXTERNAL_INTERRUPT:
5730 		return true;
5731 	case EXIT_REASON_MCE_DURING_VMENTRY:
5732 		return true;
5733 	case EXIT_REASON_EPT_VIOLATION:
5734 		/*
5735 		 * L0 always deals with the EPT violation. If nested EPT is
5736 		 * used, and the nested mmu code discovers that the address is
5737 		 * missing in the guest EPT table (EPT12), the EPT violation
5738 		 * will be injected with nested_ept_inject_page_fault()
5739 		 */
5740 		return true;
5741 	case EXIT_REASON_EPT_MISCONFIG:
5742 		/*
5743 		 * L2 never uses directly L1's EPT, but rather L0's own EPT
5744 		 * table (shadow on EPT) or a merged EPT table that L0 built
5745 		 * (EPT on EPT). So any problems with the structure of the
5746 		 * table is L0's fault.
5747 		 */
5748 		return true;
5749 	case EXIT_REASON_PREEMPTION_TIMER:
5750 		return true;
5751 	case EXIT_REASON_PML_FULL:
5752 		/* We emulate PML support to L1. */
5753 		return true;
5754 	case EXIT_REASON_VMFUNC:
5755 		/* VM functions are emulated through L2->L0 vmexits. */
5756 		return true;
5757 	case EXIT_REASON_ENCLS:
5758 		/* SGX is never exposed to L1 */
5759 		return true;
5760 	default:
5761 		break;
5762 	}
5763 	return false;
5764 }
5765 
5766 /*
5767  * Return 1 if L1 wants to intercept an exit from L2.  Only call this when in
5768  * is_guest_mode (L2).
5769  */
5770 static bool nested_vmx_l1_wants_exit(struct kvm_vcpu *vcpu, u32 exit_reason)
5771 {
5772 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5773 	u32 intr_info;
5774 
5775 	switch ((u16)exit_reason) {
5776 	case EXIT_REASON_EXCEPTION_NMI:
5777 		intr_info = vmx_get_intr_info(vcpu);
5778 		if (is_nmi(intr_info))
5779 			return true;
5780 		else if (is_page_fault(intr_info))
5781 			return true;
5782 		return vmcs12->exception_bitmap &
5783 				(1u << (intr_info & INTR_INFO_VECTOR_MASK));
5784 	case EXIT_REASON_EXTERNAL_INTERRUPT:
5785 		return nested_exit_on_intr(vcpu);
5786 	case EXIT_REASON_TRIPLE_FAULT:
5787 		return true;
5788 	case EXIT_REASON_INTERRUPT_WINDOW:
5789 		return nested_cpu_has(vmcs12, CPU_BASED_INTR_WINDOW_EXITING);
5790 	case EXIT_REASON_NMI_WINDOW:
5791 		return nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING);
5792 	case EXIT_REASON_TASK_SWITCH:
5793 		return true;
5794 	case EXIT_REASON_CPUID:
5795 		return true;
5796 	case EXIT_REASON_HLT:
5797 		return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
5798 	case EXIT_REASON_INVD:
5799 		return true;
5800 	case EXIT_REASON_INVLPG:
5801 		return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
5802 	case EXIT_REASON_RDPMC:
5803 		return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
5804 	case EXIT_REASON_RDRAND:
5805 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
5806 	case EXIT_REASON_RDSEED:
5807 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
5808 	case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
5809 		return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
5810 	case EXIT_REASON_VMREAD:
5811 		return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
5812 			vmcs12->vmread_bitmap);
5813 	case EXIT_REASON_VMWRITE:
5814 		return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
5815 			vmcs12->vmwrite_bitmap);
5816 	case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
5817 	case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
5818 	case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
5819 	case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
5820 	case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
5821 		/*
5822 		 * VMX instructions trap unconditionally. This allows L1 to
5823 		 * emulate them for its L2 guest, i.e., allows 3-level nesting!
5824 		 */
5825 		return true;
5826 	case EXIT_REASON_CR_ACCESS:
5827 		return nested_vmx_exit_handled_cr(vcpu, vmcs12);
5828 	case EXIT_REASON_DR_ACCESS:
5829 		return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
5830 	case EXIT_REASON_IO_INSTRUCTION:
5831 		return nested_vmx_exit_handled_io(vcpu, vmcs12);
5832 	case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
5833 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
5834 	case EXIT_REASON_MSR_READ:
5835 	case EXIT_REASON_MSR_WRITE:
5836 		return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
5837 	case EXIT_REASON_INVALID_STATE:
5838 		return true;
5839 	case EXIT_REASON_MWAIT_INSTRUCTION:
5840 		return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
5841 	case EXIT_REASON_MONITOR_TRAP_FLAG:
5842 		return nested_vmx_exit_handled_mtf(vmcs12);
5843 	case EXIT_REASON_MONITOR_INSTRUCTION:
5844 		return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
5845 	case EXIT_REASON_PAUSE_INSTRUCTION:
5846 		return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
5847 			nested_cpu_has2(vmcs12,
5848 				SECONDARY_EXEC_PAUSE_LOOP_EXITING);
5849 	case EXIT_REASON_MCE_DURING_VMENTRY:
5850 		return true;
5851 	case EXIT_REASON_TPR_BELOW_THRESHOLD:
5852 		return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
5853 	case EXIT_REASON_APIC_ACCESS:
5854 	case EXIT_REASON_APIC_WRITE:
5855 	case EXIT_REASON_EOI_INDUCED:
5856 		/*
5857 		 * The controls for "virtualize APIC accesses," "APIC-
5858 		 * register virtualization," and "virtual-interrupt
5859 		 * delivery" only come from vmcs12.
5860 		 */
5861 		return true;
5862 	case EXIT_REASON_INVPCID:
5863 		return
5864 			nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
5865 			nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
5866 	case EXIT_REASON_WBINVD:
5867 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
5868 	case EXIT_REASON_XSETBV:
5869 		return true;
5870 	case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
5871 		/*
5872 		 * This should never happen, since it is not possible to
5873 		 * set XSS to a non-zero value---neither in L1 nor in L2.
5874 		 * If if it were, XSS would have to be checked against
5875 		 * the XSS exit bitmap in vmcs12.
5876 		 */
5877 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
5878 	case EXIT_REASON_UMWAIT:
5879 	case EXIT_REASON_TPAUSE:
5880 		return nested_cpu_has2(vmcs12,
5881 			SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE);
5882 	default:
5883 		return true;
5884 	}
5885 }
5886 
5887 /*
5888  * Conditionally reflect a VM-Exit into L1.  Returns %true if the VM-Exit was
5889  * reflected into L1.
5890  */
5891 bool nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu)
5892 {
5893 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5894 	u32 exit_reason = vmx->exit_reason;
5895 	unsigned long exit_qual;
5896 	u32 exit_intr_info;
5897 
5898 	WARN_ON_ONCE(vmx->nested.nested_run_pending);
5899 
5900 	/*
5901 	 * Late nested VM-Fail shares the same flow as nested VM-Exit since KVM
5902 	 * has already loaded L2's state.
5903 	 */
5904 	if (unlikely(vmx->fail)) {
5905 		trace_kvm_nested_vmenter_failed(
5906 			"hardware VM-instruction error: ",
5907 			vmcs_read32(VM_INSTRUCTION_ERROR));
5908 		exit_intr_info = 0;
5909 		exit_qual = 0;
5910 		goto reflect_vmexit;
5911 	}
5912 
5913 	exit_intr_info = vmx_get_intr_info(vcpu);
5914 	exit_qual = vmx_get_exit_qual(vcpu);
5915 
5916 	trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason, exit_qual,
5917 				vmx->idt_vectoring_info, exit_intr_info,
5918 				vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5919 				KVM_ISA_VMX);
5920 
5921 	/* If L0 (KVM) wants the exit, it trumps L1's desires. */
5922 	if (nested_vmx_l0_wants_exit(vcpu, exit_reason))
5923 		return false;
5924 
5925 	/* If L1 doesn't want the exit, handle it in L0. */
5926 	if (!nested_vmx_l1_wants_exit(vcpu, exit_reason))
5927 		return false;
5928 
5929 	/*
5930 	 * vmcs.VM_EXIT_INTR_INFO is only valid for EXCEPTION_NMI exits.  For
5931 	 * EXTERNAL_INTERRUPT, the value for vmcs12->vm_exit_intr_info would
5932 	 * need to be synthesized by querying the in-kernel LAPIC, but external
5933 	 * interrupts are never reflected to L1 so it's a non-issue.
5934 	 */
5935 	if ((exit_intr_info &
5936 	     (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
5937 	    (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
5938 		struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5939 
5940 		vmcs12->vm_exit_intr_error_code =
5941 			vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5942 	}
5943 
5944 reflect_vmexit:
5945 	nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info, exit_qual);
5946 	return true;
5947 }
5948 
5949 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
5950 				struct kvm_nested_state __user *user_kvm_nested_state,
5951 				u32 user_data_size)
5952 {
5953 	struct vcpu_vmx *vmx;
5954 	struct vmcs12 *vmcs12;
5955 	struct kvm_nested_state kvm_state = {
5956 		.flags = 0,
5957 		.format = KVM_STATE_NESTED_FORMAT_VMX,
5958 		.size = sizeof(kvm_state),
5959 		.hdr.vmx.flags = 0,
5960 		.hdr.vmx.vmxon_pa = -1ull,
5961 		.hdr.vmx.vmcs12_pa = -1ull,
5962 		.hdr.vmx.preemption_timer_deadline = 0,
5963 	};
5964 	struct kvm_vmx_nested_state_data __user *user_vmx_nested_state =
5965 		&user_kvm_nested_state->data.vmx[0];
5966 
5967 	if (!vcpu)
5968 		return kvm_state.size + sizeof(*user_vmx_nested_state);
5969 
5970 	vmx = to_vmx(vcpu);
5971 	vmcs12 = get_vmcs12(vcpu);
5972 
5973 	if (nested_vmx_allowed(vcpu) &&
5974 	    (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
5975 		kvm_state.hdr.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
5976 		kvm_state.hdr.vmx.vmcs12_pa = vmx->nested.current_vmptr;
5977 
5978 		if (vmx_has_valid_vmcs12(vcpu)) {
5979 			kvm_state.size += sizeof(user_vmx_nested_state->vmcs12);
5980 
5981 			if (vmx->nested.hv_evmcs)
5982 				kvm_state.flags |= KVM_STATE_NESTED_EVMCS;
5983 
5984 			if (is_guest_mode(vcpu) &&
5985 			    nested_cpu_has_shadow_vmcs(vmcs12) &&
5986 			    vmcs12->vmcs_link_pointer != -1ull)
5987 				kvm_state.size += sizeof(user_vmx_nested_state->shadow_vmcs12);
5988 		}
5989 
5990 		if (vmx->nested.smm.vmxon)
5991 			kvm_state.hdr.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
5992 
5993 		if (vmx->nested.smm.guest_mode)
5994 			kvm_state.hdr.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
5995 
5996 		if (is_guest_mode(vcpu)) {
5997 			kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
5998 
5999 			if (vmx->nested.nested_run_pending)
6000 				kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
6001 
6002 			if (vmx->nested.mtf_pending)
6003 				kvm_state.flags |= KVM_STATE_NESTED_MTF_PENDING;
6004 
6005 			if (nested_cpu_has_preemption_timer(vmcs12) &&
6006 			    vmx->nested.has_preemption_timer_deadline) {
6007 				kvm_state.hdr.vmx.flags |=
6008 					KVM_STATE_VMX_PREEMPTION_TIMER_DEADLINE;
6009 				kvm_state.hdr.vmx.preemption_timer_deadline =
6010 					vmx->nested.preemption_timer_deadline;
6011 			}
6012 		}
6013 	}
6014 
6015 	if (user_data_size < kvm_state.size)
6016 		goto out;
6017 
6018 	if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
6019 		return -EFAULT;
6020 
6021 	if (!vmx_has_valid_vmcs12(vcpu))
6022 		goto out;
6023 
6024 	/*
6025 	 * When running L2, the authoritative vmcs12 state is in the
6026 	 * vmcs02. When running L1, the authoritative vmcs12 state is
6027 	 * in the shadow or enlightened vmcs linked to vmcs01, unless
6028 	 * need_vmcs12_to_shadow_sync is set, in which case, the authoritative
6029 	 * vmcs12 state is in the vmcs12 already.
6030 	 */
6031 	if (is_guest_mode(vcpu)) {
6032 		sync_vmcs02_to_vmcs12(vcpu, vmcs12);
6033 		sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
6034 	} else if (!vmx->nested.need_vmcs12_to_shadow_sync) {
6035 		if (vmx->nested.hv_evmcs)
6036 			copy_enlightened_to_vmcs12(vmx);
6037 		else if (enable_shadow_vmcs)
6038 			copy_shadow_to_vmcs12(vmx);
6039 	}
6040 
6041 	BUILD_BUG_ON(sizeof(user_vmx_nested_state->vmcs12) < VMCS12_SIZE);
6042 	BUILD_BUG_ON(sizeof(user_vmx_nested_state->shadow_vmcs12) < VMCS12_SIZE);
6043 
6044 	/*
6045 	 * Copy over the full allocated size of vmcs12 rather than just the size
6046 	 * of the struct.
6047 	 */
6048 	if (copy_to_user(user_vmx_nested_state->vmcs12, vmcs12, VMCS12_SIZE))
6049 		return -EFAULT;
6050 
6051 	if (nested_cpu_has_shadow_vmcs(vmcs12) &&
6052 	    vmcs12->vmcs_link_pointer != -1ull) {
6053 		if (copy_to_user(user_vmx_nested_state->shadow_vmcs12,
6054 				 get_shadow_vmcs12(vcpu), VMCS12_SIZE))
6055 			return -EFAULT;
6056 	}
6057 out:
6058 	return kvm_state.size;
6059 }
6060 
6061 /*
6062  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
6063  */
6064 void vmx_leave_nested(struct kvm_vcpu *vcpu)
6065 {
6066 	if (is_guest_mode(vcpu)) {
6067 		to_vmx(vcpu)->nested.nested_run_pending = 0;
6068 		nested_vmx_vmexit(vcpu, -1, 0, 0);
6069 	}
6070 	free_nested(vcpu);
6071 }
6072 
6073 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
6074 				struct kvm_nested_state __user *user_kvm_nested_state,
6075 				struct kvm_nested_state *kvm_state)
6076 {
6077 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6078 	struct vmcs12 *vmcs12;
6079 	enum vm_entry_failure_code ignored;
6080 	struct kvm_vmx_nested_state_data __user *user_vmx_nested_state =
6081 		&user_kvm_nested_state->data.vmx[0];
6082 	int ret;
6083 
6084 	if (kvm_state->format != KVM_STATE_NESTED_FORMAT_VMX)
6085 		return -EINVAL;
6086 
6087 	if (kvm_state->hdr.vmx.vmxon_pa == -1ull) {
6088 		if (kvm_state->hdr.vmx.smm.flags)
6089 			return -EINVAL;
6090 
6091 		if (kvm_state->hdr.vmx.vmcs12_pa != -1ull)
6092 			return -EINVAL;
6093 
6094 		/*
6095 		 * KVM_STATE_NESTED_EVMCS used to signal that KVM should
6096 		 * enable eVMCS capability on vCPU. However, since then
6097 		 * code was changed such that flag signals vmcs12 should
6098 		 * be copied into eVMCS in guest memory.
6099 		 *
6100 		 * To preserve backwards compatability, allow user
6101 		 * to set this flag even when there is no VMXON region.
6102 		 */
6103 		if (kvm_state->flags & ~KVM_STATE_NESTED_EVMCS)
6104 			return -EINVAL;
6105 	} else {
6106 		if (!nested_vmx_allowed(vcpu))
6107 			return -EINVAL;
6108 
6109 		if (!page_address_valid(vcpu, kvm_state->hdr.vmx.vmxon_pa))
6110 			return -EINVAL;
6111 	}
6112 
6113 	if ((kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
6114 	    (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
6115 		return -EINVAL;
6116 
6117 	if (kvm_state->hdr.vmx.smm.flags &
6118 	    ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
6119 		return -EINVAL;
6120 
6121 	if (kvm_state->hdr.vmx.flags & ~KVM_STATE_VMX_PREEMPTION_TIMER_DEADLINE)
6122 		return -EINVAL;
6123 
6124 	/*
6125 	 * SMM temporarily disables VMX, so we cannot be in guest mode,
6126 	 * nor can VMLAUNCH/VMRESUME be pending.  Outside SMM, SMM flags
6127 	 * must be zero.
6128 	 */
6129 	if (is_smm(vcpu) ?
6130 		(kvm_state->flags &
6131 		 (KVM_STATE_NESTED_GUEST_MODE | KVM_STATE_NESTED_RUN_PENDING))
6132 		: kvm_state->hdr.vmx.smm.flags)
6133 		return -EINVAL;
6134 
6135 	if ((kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
6136 	    !(kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
6137 		return -EINVAL;
6138 
6139 	if ((kvm_state->flags & KVM_STATE_NESTED_EVMCS) &&
6140 		(!nested_vmx_allowed(vcpu) || !vmx->nested.enlightened_vmcs_enabled))
6141 			return -EINVAL;
6142 
6143 	vmx_leave_nested(vcpu);
6144 
6145 	if (kvm_state->hdr.vmx.vmxon_pa == -1ull)
6146 		return 0;
6147 
6148 	vmx->nested.vmxon_ptr = kvm_state->hdr.vmx.vmxon_pa;
6149 	ret = enter_vmx_operation(vcpu);
6150 	if (ret)
6151 		return ret;
6152 
6153 	/* Empty 'VMXON' state is permitted if no VMCS loaded */
6154 	if (kvm_state->size < sizeof(*kvm_state) + sizeof(*vmcs12)) {
6155 		/* See vmx_has_valid_vmcs12.  */
6156 		if ((kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE) ||
6157 		    (kvm_state->flags & KVM_STATE_NESTED_EVMCS) ||
6158 		    (kvm_state->hdr.vmx.vmcs12_pa != -1ull))
6159 			return -EINVAL;
6160 		else
6161 			return 0;
6162 	}
6163 
6164 	if (kvm_state->hdr.vmx.vmcs12_pa != -1ull) {
6165 		if (kvm_state->hdr.vmx.vmcs12_pa == kvm_state->hdr.vmx.vmxon_pa ||
6166 		    !page_address_valid(vcpu, kvm_state->hdr.vmx.vmcs12_pa))
6167 			return -EINVAL;
6168 
6169 		set_current_vmptr(vmx, kvm_state->hdr.vmx.vmcs12_pa);
6170 	} else if (kvm_state->flags & KVM_STATE_NESTED_EVMCS) {
6171 		/*
6172 		 * nested_vmx_handle_enlightened_vmptrld() cannot be called
6173 		 * directly from here as HV_X64_MSR_VP_ASSIST_PAGE may not be
6174 		 * restored yet. EVMCS will be mapped from
6175 		 * nested_get_vmcs12_pages().
6176 		 */
6177 		kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
6178 	} else {
6179 		return -EINVAL;
6180 	}
6181 
6182 	if (kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
6183 		vmx->nested.smm.vmxon = true;
6184 		vmx->nested.vmxon = false;
6185 
6186 		if (kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
6187 			vmx->nested.smm.guest_mode = true;
6188 	}
6189 
6190 	vmcs12 = get_vmcs12(vcpu);
6191 	if (copy_from_user(vmcs12, user_vmx_nested_state->vmcs12, sizeof(*vmcs12)))
6192 		return -EFAULT;
6193 
6194 	if (vmcs12->hdr.revision_id != VMCS12_REVISION)
6195 		return -EINVAL;
6196 
6197 	if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
6198 		return 0;
6199 
6200 	vmx->nested.nested_run_pending =
6201 		!!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
6202 
6203 	vmx->nested.mtf_pending =
6204 		!!(kvm_state->flags & KVM_STATE_NESTED_MTF_PENDING);
6205 
6206 	ret = -EINVAL;
6207 	if (nested_cpu_has_shadow_vmcs(vmcs12) &&
6208 	    vmcs12->vmcs_link_pointer != -1ull) {
6209 		struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
6210 
6211 		if (kvm_state->size <
6212 		    sizeof(*kvm_state) +
6213 		    sizeof(user_vmx_nested_state->vmcs12) + sizeof(*shadow_vmcs12))
6214 			goto error_guest_mode;
6215 
6216 		if (copy_from_user(shadow_vmcs12,
6217 				   user_vmx_nested_state->shadow_vmcs12,
6218 				   sizeof(*shadow_vmcs12))) {
6219 			ret = -EFAULT;
6220 			goto error_guest_mode;
6221 		}
6222 
6223 		if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
6224 		    !shadow_vmcs12->hdr.shadow_vmcs)
6225 			goto error_guest_mode;
6226 	}
6227 
6228 	vmx->nested.has_preemption_timer_deadline = false;
6229 	if (kvm_state->hdr.vmx.flags & KVM_STATE_VMX_PREEMPTION_TIMER_DEADLINE) {
6230 		vmx->nested.has_preemption_timer_deadline = true;
6231 		vmx->nested.preemption_timer_deadline =
6232 			kvm_state->hdr.vmx.preemption_timer_deadline;
6233 	}
6234 
6235 	if (nested_vmx_check_controls(vcpu, vmcs12) ||
6236 	    nested_vmx_check_host_state(vcpu, vmcs12) ||
6237 	    nested_vmx_check_guest_state(vcpu, vmcs12, &ignored))
6238 		goto error_guest_mode;
6239 
6240 	vmx->nested.dirty_vmcs12 = true;
6241 	ret = nested_vmx_enter_non_root_mode(vcpu, false);
6242 	if (ret)
6243 		goto error_guest_mode;
6244 
6245 	return 0;
6246 
6247 error_guest_mode:
6248 	vmx->nested.nested_run_pending = 0;
6249 	return ret;
6250 }
6251 
6252 void nested_vmx_set_vmcs_shadowing_bitmap(void)
6253 {
6254 	if (enable_shadow_vmcs) {
6255 		vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
6256 		vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
6257 	}
6258 }
6259 
6260 /*
6261  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
6262  * returned for the various VMX controls MSRs when nested VMX is enabled.
6263  * The same values should also be used to verify that vmcs12 control fields are
6264  * valid during nested entry from L1 to L2.
6265  * Each of these control msrs has a low and high 32-bit half: A low bit is on
6266  * if the corresponding bit in the (32-bit) control field *must* be on, and a
6267  * bit in the high half is on if the corresponding bit in the control field
6268  * may be on. See also vmx_control_verify().
6269  */
6270 void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs, u32 ept_caps)
6271 {
6272 	/*
6273 	 * Note that as a general rule, the high half of the MSRs (bits in
6274 	 * the control fields which may be 1) should be initialized by the
6275 	 * intersection of the underlying hardware's MSR (i.e., features which
6276 	 * can be supported) and the list of features we want to expose -
6277 	 * because they are known to be properly supported in our code.
6278 	 * Also, usually, the low half of the MSRs (bits which must be 1) can
6279 	 * be set to 0, meaning that L1 may turn off any of these bits. The
6280 	 * reason is that if one of these bits is necessary, it will appear
6281 	 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
6282 	 * fields of vmcs01 and vmcs02, will turn these bits off - and
6283 	 * nested_vmx_l1_wants_exit() will not pass related exits to L1.
6284 	 * These rules have exceptions below.
6285 	 */
6286 
6287 	/* pin-based controls */
6288 	rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
6289 		msrs->pinbased_ctls_low,
6290 		msrs->pinbased_ctls_high);
6291 	msrs->pinbased_ctls_low |=
6292 		PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
6293 	msrs->pinbased_ctls_high &=
6294 		PIN_BASED_EXT_INTR_MASK |
6295 		PIN_BASED_NMI_EXITING |
6296 		PIN_BASED_VIRTUAL_NMIS |
6297 		(enable_apicv ? PIN_BASED_POSTED_INTR : 0);
6298 	msrs->pinbased_ctls_high |=
6299 		PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
6300 		PIN_BASED_VMX_PREEMPTION_TIMER;
6301 
6302 	/* exit controls */
6303 	rdmsr(MSR_IA32_VMX_EXIT_CTLS,
6304 		msrs->exit_ctls_low,
6305 		msrs->exit_ctls_high);
6306 	msrs->exit_ctls_low =
6307 		VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
6308 
6309 	msrs->exit_ctls_high &=
6310 #ifdef CONFIG_X86_64
6311 		VM_EXIT_HOST_ADDR_SPACE_SIZE |
6312 #endif
6313 		VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
6314 	msrs->exit_ctls_high |=
6315 		VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
6316 		VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
6317 		VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
6318 
6319 	/* We support free control of debug control saving. */
6320 	msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
6321 
6322 	/* entry controls */
6323 	rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
6324 		msrs->entry_ctls_low,
6325 		msrs->entry_ctls_high);
6326 	msrs->entry_ctls_low =
6327 		VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
6328 	msrs->entry_ctls_high &=
6329 #ifdef CONFIG_X86_64
6330 		VM_ENTRY_IA32E_MODE |
6331 #endif
6332 		VM_ENTRY_LOAD_IA32_PAT;
6333 	msrs->entry_ctls_high |=
6334 		(VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
6335 
6336 	/* We support free control of debug control loading. */
6337 	msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
6338 
6339 	/* cpu-based controls */
6340 	rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
6341 		msrs->procbased_ctls_low,
6342 		msrs->procbased_ctls_high);
6343 	msrs->procbased_ctls_low =
6344 		CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
6345 	msrs->procbased_ctls_high &=
6346 		CPU_BASED_INTR_WINDOW_EXITING |
6347 		CPU_BASED_NMI_WINDOW_EXITING | CPU_BASED_USE_TSC_OFFSETTING |
6348 		CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
6349 		CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
6350 		CPU_BASED_CR3_STORE_EXITING |
6351 #ifdef CONFIG_X86_64
6352 		CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
6353 #endif
6354 		CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
6355 		CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
6356 		CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
6357 		CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
6358 		CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
6359 	/*
6360 	 * We can allow some features even when not supported by the
6361 	 * hardware. For example, L1 can specify an MSR bitmap - and we
6362 	 * can use it to avoid exits to L1 - even when L0 runs L2
6363 	 * without MSR bitmaps.
6364 	 */
6365 	msrs->procbased_ctls_high |=
6366 		CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
6367 		CPU_BASED_USE_MSR_BITMAPS;
6368 
6369 	/* We support free control of CR3 access interception. */
6370 	msrs->procbased_ctls_low &=
6371 		~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
6372 
6373 	/*
6374 	 * secondary cpu-based controls.  Do not include those that
6375 	 * depend on CPUID bits, they are added later by
6376 	 * vmx_vcpu_after_set_cpuid.
6377 	 */
6378 	if (msrs->procbased_ctls_high & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)
6379 		rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
6380 		      msrs->secondary_ctls_low,
6381 		      msrs->secondary_ctls_high);
6382 
6383 	msrs->secondary_ctls_low = 0;
6384 	msrs->secondary_ctls_high &=
6385 		SECONDARY_EXEC_DESC |
6386 		SECONDARY_EXEC_RDTSCP |
6387 		SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
6388 		SECONDARY_EXEC_WBINVD_EXITING |
6389 		SECONDARY_EXEC_APIC_REGISTER_VIRT |
6390 		SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
6391 		SECONDARY_EXEC_RDRAND_EXITING |
6392 		SECONDARY_EXEC_ENABLE_INVPCID |
6393 		SECONDARY_EXEC_RDSEED_EXITING |
6394 		SECONDARY_EXEC_XSAVES;
6395 
6396 	/*
6397 	 * We can emulate "VMCS shadowing," even if the hardware
6398 	 * doesn't support it.
6399 	 */
6400 	msrs->secondary_ctls_high |=
6401 		SECONDARY_EXEC_SHADOW_VMCS;
6402 
6403 	if (enable_ept) {
6404 		/* nested EPT: emulate EPT also to L1 */
6405 		msrs->secondary_ctls_high |=
6406 			SECONDARY_EXEC_ENABLE_EPT;
6407 		msrs->ept_caps =
6408 			VMX_EPT_PAGE_WALK_4_BIT |
6409 			VMX_EPT_PAGE_WALK_5_BIT |
6410 			VMX_EPTP_WB_BIT |
6411 			VMX_EPT_INVEPT_BIT |
6412 			VMX_EPT_EXECUTE_ONLY_BIT;
6413 
6414 		msrs->ept_caps &= ept_caps;
6415 		msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
6416 			VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
6417 			VMX_EPT_1GB_PAGE_BIT;
6418 		if (enable_ept_ad_bits) {
6419 			msrs->secondary_ctls_high |=
6420 				SECONDARY_EXEC_ENABLE_PML;
6421 			msrs->ept_caps |= VMX_EPT_AD_BIT;
6422 		}
6423 	}
6424 
6425 	if (cpu_has_vmx_vmfunc()) {
6426 		msrs->secondary_ctls_high |=
6427 			SECONDARY_EXEC_ENABLE_VMFUNC;
6428 		/*
6429 		 * Advertise EPTP switching unconditionally
6430 		 * since we emulate it
6431 		 */
6432 		if (enable_ept)
6433 			msrs->vmfunc_controls =
6434 				VMX_VMFUNC_EPTP_SWITCHING;
6435 	}
6436 
6437 	/*
6438 	 * Old versions of KVM use the single-context version without
6439 	 * checking for support, so declare that it is supported even
6440 	 * though it is treated as global context.  The alternative is
6441 	 * not failing the single-context invvpid, and it is worse.
6442 	 */
6443 	if (enable_vpid) {
6444 		msrs->secondary_ctls_high |=
6445 			SECONDARY_EXEC_ENABLE_VPID;
6446 		msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
6447 			VMX_VPID_EXTENT_SUPPORTED_MASK;
6448 	}
6449 
6450 	if (enable_unrestricted_guest)
6451 		msrs->secondary_ctls_high |=
6452 			SECONDARY_EXEC_UNRESTRICTED_GUEST;
6453 
6454 	if (flexpriority_enabled)
6455 		msrs->secondary_ctls_high |=
6456 			SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6457 
6458 	/* miscellaneous data */
6459 	rdmsr(MSR_IA32_VMX_MISC,
6460 		msrs->misc_low,
6461 		msrs->misc_high);
6462 	msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
6463 	msrs->misc_low |=
6464 		MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
6465 		VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
6466 		VMX_MISC_ACTIVITY_HLT;
6467 	msrs->misc_high = 0;
6468 
6469 	/*
6470 	 * This MSR reports some information about VMX support. We
6471 	 * should return information about the VMX we emulate for the
6472 	 * guest, and the VMCS structure we give it - not about the
6473 	 * VMX support of the underlying hardware.
6474 	 */
6475 	msrs->basic =
6476 		VMCS12_REVISION |
6477 		VMX_BASIC_TRUE_CTLS |
6478 		((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
6479 		(VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
6480 
6481 	if (cpu_has_vmx_basic_inout())
6482 		msrs->basic |= VMX_BASIC_INOUT;
6483 
6484 	/*
6485 	 * These MSRs specify bits which the guest must keep fixed on
6486 	 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
6487 	 * We picked the standard core2 setting.
6488 	 */
6489 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
6490 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
6491 	msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
6492 	msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
6493 
6494 	/* These MSRs specify bits which the guest must keep fixed off. */
6495 	rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
6496 	rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
6497 
6498 	/* highest index: VMX_PREEMPTION_TIMER_VALUE */
6499 	msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
6500 }
6501 
6502 void nested_vmx_hardware_unsetup(void)
6503 {
6504 	int i;
6505 
6506 	if (enable_shadow_vmcs) {
6507 		for (i = 0; i < VMX_BITMAP_NR; i++)
6508 			free_page((unsigned long)vmx_bitmap[i]);
6509 	}
6510 }
6511 
6512 __init int nested_vmx_hardware_setup(int (*exit_handlers[])(struct kvm_vcpu *))
6513 {
6514 	int i;
6515 
6516 	if (!cpu_has_vmx_shadow_vmcs())
6517 		enable_shadow_vmcs = 0;
6518 	if (enable_shadow_vmcs) {
6519 		for (i = 0; i < VMX_BITMAP_NR; i++) {
6520 			/*
6521 			 * The vmx_bitmap is not tied to a VM and so should
6522 			 * not be charged to a memcg.
6523 			 */
6524 			vmx_bitmap[i] = (unsigned long *)
6525 				__get_free_page(GFP_KERNEL);
6526 			if (!vmx_bitmap[i]) {
6527 				nested_vmx_hardware_unsetup();
6528 				return -ENOMEM;
6529 			}
6530 		}
6531 
6532 		init_vmcs_shadow_fields();
6533 	}
6534 
6535 	exit_handlers[EXIT_REASON_VMCLEAR]	= handle_vmclear;
6536 	exit_handlers[EXIT_REASON_VMLAUNCH]	= handle_vmlaunch;
6537 	exit_handlers[EXIT_REASON_VMPTRLD]	= handle_vmptrld;
6538 	exit_handlers[EXIT_REASON_VMPTRST]	= handle_vmptrst;
6539 	exit_handlers[EXIT_REASON_VMREAD]	= handle_vmread;
6540 	exit_handlers[EXIT_REASON_VMRESUME]	= handle_vmresume;
6541 	exit_handlers[EXIT_REASON_VMWRITE]	= handle_vmwrite;
6542 	exit_handlers[EXIT_REASON_VMOFF]	= handle_vmoff;
6543 	exit_handlers[EXIT_REASON_VMON]		= handle_vmon;
6544 	exit_handlers[EXIT_REASON_INVEPT]	= handle_invept;
6545 	exit_handlers[EXIT_REASON_INVVPID]	= handle_invvpid;
6546 	exit_handlers[EXIT_REASON_VMFUNC]	= handle_vmfunc;
6547 
6548 	return 0;
6549 }
6550 
6551 struct kvm_x86_nested_ops vmx_nested_ops = {
6552 	.check_events = vmx_check_nested_events,
6553 	.hv_timer_pending = nested_vmx_preemption_timer_pending,
6554 	.get_state = vmx_get_nested_state,
6555 	.set_state = vmx_set_nested_state,
6556 	.get_vmcs12_pages = nested_get_vmcs12_pages,
6557 	.write_log_dirty = nested_vmx_write_pml_buffer,
6558 	.enable_evmcs = nested_enable_evmcs,
6559 	.get_evmcs_version = nested_get_evmcs_version,
6560 };
6561