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