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