xref: /openbmc/linux/arch/x86/kvm/svm/nested.c (revision 8d81cd1a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * AMD SVM support
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *   Avi Kivity   <avi@qumranet.com>
13  */
14 
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16 
17 #include <linux/kvm_types.h>
18 #include <linux/kvm_host.h>
19 #include <linux/kernel.h>
20 
21 #include <asm/msr-index.h>
22 #include <asm/debugreg.h>
23 
24 #include "kvm_emulate.h"
25 #include "trace.h"
26 #include "mmu.h"
27 #include "x86.h"
28 #include "smm.h"
29 #include "cpuid.h"
30 #include "lapic.h"
31 #include "svm.h"
32 #include "hyperv.h"
33 
34 #define CC KVM_NESTED_VMENTER_CONSISTENCY_CHECK
35 
36 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
37 				       struct x86_exception *fault)
38 {
39 	struct vcpu_svm *svm = to_svm(vcpu);
40 	struct vmcb *vmcb = svm->vmcb;
41 
42 	if (vmcb->control.exit_code != SVM_EXIT_NPF) {
43 		/*
44 		 * TODO: track the cause of the nested page fault, and
45 		 * correctly fill in the high bits of exit_info_1.
46 		 */
47 		vmcb->control.exit_code = SVM_EXIT_NPF;
48 		vmcb->control.exit_code_hi = 0;
49 		vmcb->control.exit_info_1 = (1ULL << 32);
50 		vmcb->control.exit_info_2 = fault->address;
51 	}
52 
53 	vmcb->control.exit_info_1 &= ~0xffffffffULL;
54 	vmcb->control.exit_info_1 |= fault->error_code;
55 
56 	nested_svm_vmexit(svm);
57 }
58 
59 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
60 {
61 	struct vcpu_svm *svm = to_svm(vcpu);
62 	u64 cr3 = svm->nested.ctl.nested_cr3;
63 	u64 pdpte;
64 	int ret;
65 
66 	ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(cr3), &pdpte,
67 				       offset_in_page(cr3) + index * 8, 8);
68 	if (ret)
69 		return 0;
70 	return pdpte;
71 }
72 
73 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
74 {
75 	struct vcpu_svm *svm = to_svm(vcpu);
76 
77 	return svm->nested.ctl.nested_cr3;
78 }
79 
80 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
81 {
82 	struct vcpu_svm *svm = to_svm(vcpu);
83 
84 	WARN_ON(mmu_is_nested(vcpu));
85 
86 	vcpu->arch.mmu = &vcpu->arch.guest_mmu;
87 
88 	/*
89 	 * The NPT format depends on L1's CR4 and EFER, which is in vmcb01.  Note,
90 	 * when called via KVM_SET_NESTED_STATE, that state may _not_ match current
91 	 * vCPU state.  CR0.WP is explicitly ignored, while CR0.PG is required.
92 	 */
93 	kvm_init_shadow_npt_mmu(vcpu, X86_CR0_PG, svm->vmcb01.ptr->save.cr4,
94 				svm->vmcb01.ptr->save.efer,
95 				svm->nested.ctl.nested_cr3);
96 	vcpu->arch.mmu->get_guest_pgd     = nested_svm_get_tdp_cr3;
97 	vcpu->arch.mmu->get_pdptr         = nested_svm_get_tdp_pdptr;
98 	vcpu->arch.mmu->inject_page_fault = nested_svm_inject_npf_exit;
99 	vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
100 }
101 
102 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
103 {
104 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
105 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
106 }
107 
108 static bool nested_vmcb_needs_vls_intercept(struct vcpu_svm *svm)
109 {
110 	if (!guest_can_use(&svm->vcpu, X86_FEATURE_V_VMSAVE_VMLOAD))
111 		return true;
112 
113 	if (!nested_npt_enabled(svm))
114 		return true;
115 
116 	if (!(svm->nested.ctl.virt_ext & VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK))
117 		return true;
118 
119 	return false;
120 }
121 
122 void recalc_intercepts(struct vcpu_svm *svm)
123 {
124 	struct vmcb_control_area *c, *h;
125 	struct vmcb_ctrl_area_cached *g;
126 	unsigned int i;
127 
128 	vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
129 
130 	if (!is_guest_mode(&svm->vcpu))
131 		return;
132 
133 	c = &svm->vmcb->control;
134 	h = &svm->vmcb01.ptr->control;
135 	g = &svm->nested.ctl;
136 
137 	for (i = 0; i < MAX_INTERCEPT; i++)
138 		c->intercepts[i] = h->intercepts[i];
139 
140 	if (g->int_ctl & V_INTR_MASKING_MASK) {
141 		/*
142 		 * If L2 is active and V_INTR_MASKING is enabled in vmcb12,
143 		 * disable intercept of CR8 writes as L2's CR8 does not affect
144 		 * any interrupt KVM may want to inject.
145 		 *
146 		 * Similarly, disable intercept of virtual interrupts (used to
147 		 * detect interrupt windows) if the saved RFLAGS.IF is '0', as
148 		 * the effective RFLAGS.IF for L1 interrupts will never be set
149 		 * while L2 is running (L2's RFLAGS.IF doesn't affect L1 IRQs).
150 		 */
151 		vmcb_clr_intercept(c, INTERCEPT_CR8_WRITE);
152 		if (!(svm->vmcb01.ptr->save.rflags & X86_EFLAGS_IF))
153 			vmcb_clr_intercept(c, INTERCEPT_VINTR);
154 	}
155 
156 	/*
157 	 * We want to see VMMCALLs from a nested guest only when Hyper-V L2 TLB
158 	 * flush feature is enabled.
159 	 */
160 	if (!nested_svm_l2_tlb_flush_enabled(&svm->vcpu))
161 		vmcb_clr_intercept(c, INTERCEPT_VMMCALL);
162 
163 	for (i = 0; i < MAX_INTERCEPT; i++)
164 		c->intercepts[i] |= g->intercepts[i];
165 
166 	/* If SMI is not intercepted, ignore guest SMI intercept as well  */
167 	if (!intercept_smi)
168 		vmcb_clr_intercept(c, INTERCEPT_SMI);
169 
170 	if (nested_vmcb_needs_vls_intercept(svm)) {
171 		/*
172 		 * If the virtual VMLOAD/VMSAVE is not enabled for the L2,
173 		 * we must intercept these instructions to correctly
174 		 * emulate them in case L1 doesn't intercept them.
175 		 */
176 		vmcb_set_intercept(c, INTERCEPT_VMLOAD);
177 		vmcb_set_intercept(c, INTERCEPT_VMSAVE);
178 	} else {
179 		WARN_ON(!(c->virt_ext & VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK));
180 	}
181 }
182 
183 /*
184  * Merge L0's (KVM) and L1's (Nested VMCB) MSR permission bitmaps. The function
185  * is optimized in that it only merges the parts where KVM MSR permission bitmap
186  * may contain zero bits.
187  */
188 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
189 {
190 	struct hv_vmcb_enlightenments *hve = &svm->nested.ctl.hv_enlightenments;
191 	int i;
192 
193 	/*
194 	 * MSR bitmap update can be skipped when:
195 	 * - MSR bitmap for L1 hasn't changed.
196 	 * - Nested hypervisor (L1) is attempting to launch the same L2 as
197 	 *   before.
198 	 * - Nested hypervisor (L1) is using Hyper-V emulation interface and
199 	 * tells KVM (L0) there were no changes in MSR bitmap for L2.
200 	 */
201 	if (!svm->nested.force_msr_bitmap_recalc &&
202 	    kvm_hv_hypercall_enabled(&svm->vcpu) &&
203 	    hve->hv_enlightenments_control.msr_bitmap &&
204 	    (svm->nested.ctl.clean & BIT(HV_VMCB_NESTED_ENLIGHTENMENTS)))
205 		goto set_msrpm_base_pa;
206 
207 	if (!(vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_MSR_PROT)))
208 		return true;
209 
210 	for (i = 0; i < MSRPM_OFFSETS; i++) {
211 		u32 value, p;
212 		u64 offset;
213 
214 		if (msrpm_offsets[i] == 0xffffffff)
215 			break;
216 
217 		p      = msrpm_offsets[i];
218 
219 		/* x2apic msrs are intercepted always for the nested guest */
220 		if (is_x2apic_msrpm_offset(p))
221 			continue;
222 
223 		offset = svm->nested.ctl.msrpm_base_pa + (p * 4);
224 
225 		if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
226 			return false;
227 
228 		svm->nested.msrpm[p] = svm->msrpm[p] | value;
229 	}
230 
231 	svm->nested.force_msr_bitmap_recalc = false;
232 
233 set_msrpm_base_pa:
234 	svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
235 
236 	return true;
237 }
238 
239 /*
240  * Bits 11:0 of bitmap address are ignored by hardware
241  */
242 static bool nested_svm_check_bitmap_pa(struct kvm_vcpu *vcpu, u64 pa, u32 size)
243 {
244 	u64 addr = PAGE_ALIGN(pa);
245 
246 	return kvm_vcpu_is_legal_gpa(vcpu, addr) &&
247 	    kvm_vcpu_is_legal_gpa(vcpu, addr + size - 1);
248 }
249 
250 static bool __nested_vmcb_check_controls(struct kvm_vcpu *vcpu,
251 					 struct vmcb_ctrl_area_cached *control)
252 {
253 	if (CC(!vmcb12_is_intercept(control, INTERCEPT_VMRUN)))
254 		return false;
255 
256 	if (CC(control->asid == 0))
257 		return false;
258 
259 	if (CC((control->nested_ctl & SVM_NESTED_CTL_NP_ENABLE) && !npt_enabled))
260 		return false;
261 
262 	if (CC(!nested_svm_check_bitmap_pa(vcpu, control->msrpm_base_pa,
263 					   MSRPM_SIZE)))
264 		return false;
265 	if (CC(!nested_svm_check_bitmap_pa(vcpu, control->iopm_base_pa,
266 					   IOPM_SIZE)))
267 		return false;
268 
269 	if (CC((control->int_ctl & V_NMI_ENABLE_MASK) &&
270 	       !vmcb12_is_intercept(control, INTERCEPT_NMI))) {
271 		return false;
272 	}
273 
274 	return true;
275 }
276 
277 /* Common checks that apply to both L1 and L2 state.  */
278 static bool __nested_vmcb_check_save(struct kvm_vcpu *vcpu,
279 				     struct vmcb_save_area_cached *save)
280 {
281 	if (CC(!(save->efer & EFER_SVME)))
282 		return false;
283 
284 	if (CC((save->cr0 & X86_CR0_CD) == 0 && (save->cr0 & X86_CR0_NW)) ||
285 	    CC(save->cr0 & ~0xffffffffULL))
286 		return false;
287 
288 	if (CC(!kvm_dr6_valid(save->dr6)) || CC(!kvm_dr7_valid(save->dr7)))
289 		return false;
290 
291 	/*
292 	 * These checks are also performed by KVM_SET_SREGS,
293 	 * except that EFER.LMA is not checked by SVM against
294 	 * CR0.PG && EFER.LME.
295 	 */
296 	if ((save->efer & EFER_LME) && (save->cr0 & X86_CR0_PG)) {
297 		if (CC(!(save->cr4 & X86_CR4_PAE)) ||
298 		    CC(!(save->cr0 & X86_CR0_PE)) ||
299 		    CC(kvm_vcpu_is_illegal_gpa(vcpu, save->cr3)))
300 			return false;
301 	}
302 
303 	/* Note, SVM doesn't have any additional restrictions on CR4. */
304 	if (CC(!__kvm_is_valid_cr4(vcpu, save->cr4)))
305 		return false;
306 
307 	if (CC(!kvm_valid_efer(vcpu, save->efer)))
308 		return false;
309 
310 	return true;
311 }
312 
313 static bool nested_vmcb_check_save(struct kvm_vcpu *vcpu)
314 {
315 	struct vcpu_svm *svm = to_svm(vcpu);
316 	struct vmcb_save_area_cached *save = &svm->nested.save;
317 
318 	return __nested_vmcb_check_save(vcpu, save);
319 }
320 
321 static bool nested_vmcb_check_controls(struct kvm_vcpu *vcpu)
322 {
323 	struct vcpu_svm *svm = to_svm(vcpu);
324 	struct vmcb_ctrl_area_cached *ctl = &svm->nested.ctl;
325 
326 	return __nested_vmcb_check_controls(vcpu, ctl);
327 }
328 
329 static
330 void __nested_copy_vmcb_control_to_cache(struct kvm_vcpu *vcpu,
331 					 struct vmcb_ctrl_area_cached *to,
332 					 struct vmcb_control_area *from)
333 {
334 	unsigned int i;
335 
336 	for (i = 0; i < MAX_INTERCEPT; i++)
337 		to->intercepts[i] = from->intercepts[i];
338 
339 	to->iopm_base_pa        = from->iopm_base_pa;
340 	to->msrpm_base_pa       = from->msrpm_base_pa;
341 	to->tsc_offset          = from->tsc_offset;
342 	to->tlb_ctl             = from->tlb_ctl;
343 	to->int_ctl             = from->int_ctl;
344 	to->int_vector          = from->int_vector;
345 	to->int_state           = from->int_state;
346 	to->exit_code           = from->exit_code;
347 	to->exit_code_hi        = from->exit_code_hi;
348 	to->exit_info_1         = from->exit_info_1;
349 	to->exit_info_2         = from->exit_info_2;
350 	to->exit_int_info       = from->exit_int_info;
351 	to->exit_int_info_err   = from->exit_int_info_err;
352 	to->nested_ctl          = from->nested_ctl;
353 	to->event_inj           = from->event_inj;
354 	to->event_inj_err       = from->event_inj_err;
355 	to->next_rip            = from->next_rip;
356 	to->nested_cr3          = from->nested_cr3;
357 	to->virt_ext            = from->virt_ext;
358 	to->pause_filter_count  = from->pause_filter_count;
359 	to->pause_filter_thresh = from->pause_filter_thresh;
360 
361 	/* Copy asid here because nested_vmcb_check_controls will check it.  */
362 	to->asid           = from->asid;
363 	to->msrpm_base_pa &= ~0x0fffULL;
364 	to->iopm_base_pa  &= ~0x0fffULL;
365 
366 	/* Hyper-V extensions (Enlightened VMCB) */
367 	if (kvm_hv_hypercall_enabled(vcpu)) {
368 		to->clean = from->clean;
369 		memcpy(&to->hv_enlightenments, &from->hv_enlightenments,
370 		       sizeof(to->hv_enlightenments));
371 	}
372 }
373 
374 void nested_copy_vmcb_control_to_cache(struct vcpu_svm *svm,
375 				       struct vmcb_control_area *control)
376 {
377 	__nested_copy_vmcb_control_to_cache(&svm->vcpu, &svm->nested.ctl, control);
378 }
379 
380 static void __nested_copy_vmcb_save_to_cache(struct vmcb_save_area_cached *to,
381 					     struct vmcb_save_area *from)
382 {
383 	/*
384 	 * Copy only fields that are validated, as we need them
385 	 * to avoid TOC/TOU races.
386 	 */
387 	to->efer = from->efer;
388 	to->cr0 = from->cr0;
389 	to->cr3 = from->cr3;
390 	to->cr4 = from->cr4;
391 
392 	to->dr6 = from->dr6;
393 	to->dr7 = from->dr7;
394 }
395 
396 void nested_copy_vmcb_save_to_cache(struct vcpu_svm *svm,
397 				    struct vmcb_save_area *save)
398 {
399 	__nested_copy_vmcb_save_to_cache(&svm->nested.save, save);
400 }
401 
402 /*
403  * Synchronize fields that are written by the processor, so that
404  * they can be copied back into the vmcb12.
405  */
406 void nested_sync_control_from_vmcb02(struct vcpu_svm *svm)
407 {
408 	u32 mask;
409 	svm->nested.ctl.event_inj      = svm->vmcb->control.event_inj;
410 	svm->nested.ctl.event_inj_err  = svm->vmcb->control.event_inj_err;
411 
412 	/* Only a few fields of int_ctl are written by the processor.  */
413 	mask = V_IRQ_MASK | V_TPR_MASK;
414 	/*
415 	 * Don't sync vmcb02 V_IRQ back to vmcb12 if KVM (L0) is intercepting
416 	 * virtual interrupts in order to request an interrupt window, as KVM
417 	 * has usurped vmcb02's int_ctl.  If an interrupt window opens before
418 	 * the next VM-Exit, svm_clear_vintr() will restore vmcb12's int_ctl.
419 	 * If no window opens, V_IRQ will be correctly preserved in vmcb12's
420 	 * int_ctl (because it was never recognized while L2 was running).
421 	 */
422 	if (svm_is_intercept(svm, INTERCEPT_VINTR) &&
423 	    !test_bit(INTERCEPT_VINTR, (unsigned long *)svm->nested.ctl.intercepts))
424 		mask &= ~V_IRQ_MASK;
425 
426 	if (nested_vgif_enabled(svm))
427 		mask |= V_GIF_MASK;
428 
429 	if (nested_vnmi_enabled(svm))
430 		mask |= V_NMI_BLOCKING_MASK | V_NMI_PENDING_MASK;
431 
432 	svm->nested.ctl.int_ctl        &= ~mask;
433 	svm->nested.ctl.int_ctl        |= svm->vmcb->control.int_ctl & mask;
434 }
435 
436 /*
437  * Transfer any event that L0 or L1 wanted to inject into L2 to
438  * EXIT_INT_INFO.
439  */
440 static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
441 						struct vmcb *vmcb12)
442 {
443 	struct kvm_vcpu *vcpu = &svm->vcpu;
444 	u32 exit_int_info = 0;
445 	unsigned int nr;
446 
447 	if (vcpu->arch.exception.injected) {
448 		nr = vcpu->arch.exception.vector;
449 		exit_int_info = nr | SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_EXEPT;
450 
451 		if (vcpu->arch.exception.has_error_code) {
452 			exit_int_info |= SVM_EVTINJ_VALID_ERR;
453 			vmcb12->control.exit_int_info_err =
454 				vcpu->arch.exception.error_code;
455 		}
456 
457 	} else if (vcpu->arch.nmi_injected) {
458 		exit_int_info = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
459 
460 	} else if (vcpu->arch.interrupt.injected) {
461 		nr = vcpu->arch.interrupt.nr;
462 		exit_int_info = nr | SVM_EVTINJ_VALID;
463 
464 		if (vcpu->arch.interrupt.soft)
465 			exit_int_info |= SVM_EVTINJ_TYPE_SOFT;
466 		else
467 			exit_int_info |= SVM_EVTINJ_TYPE_INTR;
468 	}
469 
470 	vmcb12->control.exit_int_info = exit_int_info;
471 }
472 
473 static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
474 {
475 	/*
476 	 * KVM_REQ_HV_TLB_FLUSH flushes entries from either L1's VP_ID or
477 	 * L2's VP_ID upon request from the guest. Make sure we check for
478 	 * pending entries in the right FIFO upon L1/L2 transition as these
479 	 * requests are put by other vCPUs asynchronously.
480 	 */
481 	if (to_hv_vcpu(vcpu) && npt_enabled)
482 		kvm_make_request(KVM_REQ_HV_TLB_FLUSH, vcpu);
483 
484 	/*
485 	 * TODO: optimize unconditional TLB flush/MMU sync.  A partial list of
486 	 * things to fix before this can be conditional:
487 	 *
488 	 *  - Flush TLBs for both L1 and L2 remote TLB flush
489 	 *  - Honor L1's request to flush an ASID on nested VMRUN
490 	 *  - Sync nested NPT MMU on VMRUN that flushes L2's ASID[*]
491 	 *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
492 	 *  - Flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST
493 	 *
494 	 * [*] Unlike nested EPT, SVM's ASID management can invalidate nested
495 	 *     NPT guest-physical mappings on VMRUN.
496 	 */
497 	kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
498 	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
499 }
500 
501 /*
502  * Load guest's/host's cr3 on nested vmentry or vmexit. @nested_npt is true
503  * if we are emulating VM-Entry into a guest with NPT enabled.
504  */
505 static int nested_svm_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3,
506 			       bool nested_npt, bool reload_pdptrs)
507 {
508 	if (CC(kvm_vcpu_is_illegal_gpa(vcpu, cr3)))
509 		return -EINVAL;
510 
511 	if (reload_pdptrs && !nested_npt && is_pae_paging(vcpu) &&
512 	    CC(!load_pdptrs(vcpu, cr3)))
513 		return -EINVAL;
514 
515 	vcpu->arch.cr3 = cr3;
516 
517 	/* Re-initialize the MMU, e.g. to pick up CR4 MMU role changes. */
518 	kvm_init_mmu(vcpu);
519 
520 	if (!nested_npt)
521 		kvm_mmu_new_pgd(vcpu, cr3);
522 
523 	return 0;
524 }
525 
526 void nested_vmcb02_compute_g_pat(struct vcpu_svm *svm)
527 {
528 	if (!svm->nested.vmcb02.ptr)
529 		return;
530 
531 	/* FIXME: merge g_pat from vmcb01 and vmcb12.  */
532 	svm->nested.vmcb02.ptr->save.g_pat = svm->vmcb01.ptr->save.g_pat;
533 }
534 
535 static void nested_vmcb02_prepare_save(struct vcpu_svm *svm, struct vmcb *vmcb12)
536 {
537 	bool new_vmcb12 = false;
538 	struct vmcb *vmcb01 = svm->vmcb01.ptr;
539 	struct vmcb *vmcb02 = svm->nested.vmcb02.ptr;
540 	struct kvm_vcpu *vcpu = &svm->vcpu;
541 
542 	nested_vmcb02_compute_g_pat(svm);
543 
544 	/* Load the nested guest state */
545 	if (svm->nested.vmcb12_gpa != svm->nested.last_vmcb12_gpa) {
546 		new_vmcb12 = true;
547 		svm->nested.last_vmcb12_gpa = svm->nested.vmcb12_gpa;
548 		svm->nested.force_msr_bitmap_recalc = true;
549 	}
550 
551 	if (unlikely(new_vmcb12 || vmcb_is_dirty(vmcb12, VMCB_SEG))) {
552 		vmcb02->save.es = vmcb12->save.es;
553 		vmcb02->save.cs = vmcb12->save.cs;
554 		vmcb02->save.ss = vmcb12->save.ss;
555 		vmcb02->save.ds = vmcb12->save.ds;
556 		vmcb02->save.cpl = vmcb12->save.cpl;
557 		vmcb_mark_dirty(vmcb02, VMCB_SEG);
558 	}
559 
560 	if (unlikely(new_vmcb12 || vmcb_is_dirty(vmcb12, VMCB_DT))) {
561 		vmcb02->save.gdtr = vmcb12->save.gdtr;
562 		vmcb02->save.idtr = vmcb12->save.idtr;
563 		vmcb_mark_dirty(vmcb02, VMCB_DT);
564 	}
565 
566 	kvm_set_rflags(vcpu, vmcb12->save.rflags | X86_EFLAGS_FIXED);
567 
568 	svm_set_efer(vcpu, svm->nested.save.efer);
569 
570 	svm_set_cr0(vcpu, svm->nested.save.cr0);
571 	svm_set_cr4(vcpu, svm->nested.save.cr4);
572 
573 	svm->vcpu.arch.cr2 = vmcb12->save.cr2;
574 
575 	kvm_rax_write(vcpu, vmcb12->save.rax);
576 	kvm_rsp_write(vcpu, vmcb12->save.rsp);
577 	kvm_rip_write(vcpu, vmcb12->save.rip);
578 
579 	/* In case we don't even reach vcpu_run, the fields are not updated */
580 	vmcb02->save.rax = vmcb12->save.rax;
581 	vmcb02->save.rsp = vmcb12->save.rsp;
582 	vmcb02->save.rip = vmcb12->save.rip;
583 
584 	/* These bits will be set properly on the first execution when new_vmc12 is true */
585 	if (unlikely(new_vmcb12 || vmcb_is_dirty(vmcb12, VMCB_DR))) {
586 		vmcb02->save.dr7 = svm->nested.save.dr7 | DR7_FIXED_1;
587 		svm->vcpu.arch.dr6  = svm->nested.save.dr6 | DR6_ACTIVE_LOW;
588 		vmcb_mark_dirty(vmcb02, VMCB_DR);
589 	}
590 
591 	if (unlikely(guest_can_use(vcpu, X86_FEATURE_LBRV) &&
592 		     (svm->nested.ctl.virt_ext & LBR_CTL_ENABLE_MASK))) {
593 		/*
594 		 * Reserved bits of DEBUGCTL are ignored.  Be consistent with
595 		 * svm_set_msr's definition of reserved bits.
596 		 */
597 		svm_copy_lbrs(vmcb02, vmcb12);
598 		vmcb02->save.dbgctl &= ~DEBUGCTL_RESERVED_BITS;
599 		svm_update_lbrv(&svm->vcpu);
600 
601 	} else if (unlikely(vmcb01->control.virt_ext & LBR_CTL_ENABLE_MASK)) {
602 		svm_copy_lbrs(vmcb02, vmcb01);
603 	}
604 }
605 
606 static inline bool is_evtinj_soft(u32 evtinj)
607 {
608 	u32 type = evtinj & SVM_EVTINJ_TYPE_MASK;
609 	u8 vector = evtinj & SVM_EVTINJ_VEC_MASK;
610 
611 	if (!(evtinj & SVM_EVTINJ_VALID))
612 		return false;
613 
614 	if (type == SVM_EVTINJ_TYPE_SOFT)
615 		return true;
616 
617 	return type == SVM_EVTINJ_TYPE_EXEPT && kvm_exception_is_soft(vector);
618 }
619 
620 static bool is_evtinj_nmi(u32 evtinj)
621 {
622 	u32 type = evtinj & SVM_EVTINJ_TYPE_MASK;
623 
624 	if (!(evtinj & SVM_EVTINJ_VALID))
625 		return false;
626 
627 	return type == SVM_EVTINJ_TYPE_NMI;
628 }
629 
630 static void nested_vmcb02_prepare_control(struct vcpu_svm *svm,
631 					  unsigned long vmcb12_rip,
632 					  unsigned long vmcb12_csbase)
633 {
634 	u32 int_ctl_vmcb01_bits = V_INTR_MASKING_MASK;
635 	u32 int_ctl_vmcb12_bits = V_TPR_MASK | V_IRQ_INJECTION_BITS_MASK;
636 
637 	struct kvm_vcpu *vcpu = &svm->vcpu;
638 	struct vmcb *vmcb01 = svm->vmcb01.ptr;
639 	struct vmcb *vmcb02 = svm->nested.vmcb02.ptr;
640 	u32 pause_count12;
641 	u32 pause_thresh12;
642 
643 	/*
644 	 * Filled at exit: exit_code, exit_code_hi, exit_info_1, exit_info_2,
645 	 * exit_int_info, exit_int_info_err, next_rip, insn_len, insn_bytes.
646 	 */
647 
648 	if (guest_can_use(vcpu, X86_FEATURE_VGIF) &&
649 	    (svm->nested.ctl.int_ctl & V_GIF_ENABLE_MASK))
650 		int_ctl_vmcb12_bits |= (V_GIF_MASK | V_GIF_ENABLE_MASK);
651 	else
652 		int_ctl_vmcb01_bits |= (V_GIF_MASK | V_GIF_ENABLE_MASK);
653 
654 	if (vnmi) {
655 		if (vmcb01->control.int_ctl & V_NMI_PENDING_MASK) {
656 			svm->vcpu.arch.nmi_pending++;
657 			kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
658 		}
659 		if (nested_vnmi_enabled(svm))
660 			int_ctl_vmcb12_bits |= (V_NMI_PENDING_MASK |
661 						V_NMI_ENABLE_MASK |
662 						V_NMI_BLOCKING_MASK);
663 	}
664 
665 	/* Copied from vmcb01.  msrpm_base can be overwritten later.  */
666 	vmcb02->control.nested_ctl = vmcb01->control.nested_ctl;
667 	vmcb02->control.iopm_base_pa = vmcb01->control.iopm_base_pa;
668 	vmcb02->control.msrpm_base_pa = vmcb01->control.msrpm_base_pa;
669 
670 	/* Done at vmrun: asid.  */
671 
672 	/* Also overwritten later if necessary.  */
673 	vmcb02->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
674 
675 	/* nested_cr3.  */
676 	if (nested_npt_enabled(svm))
677 		nested_svm_init_mmu_context(vcpu);
678 
679 	vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
680 			vcpu->arch.l1_tsc_offset,
681 			svm->nested.ctl.tsc_offset,
682 			svm->tsc_ratio_msr);
683 
684 	vmcb02->control.tsc_offset = vcpu->arch.tsc_offset;
685 
686 	if (guest_can_use(vcpu, X86_FEATURE_TSCRATEMSR) &&
687 	    svm->tsc_ratio_msr != kvm_caps.default_tsc_scaling_ratio)
688 		nested_svm_update_tsc_ratio_msr(vcpu);
689 
690 	vmcb02->control.int_ctl             =
691 		(svm->nested.ctl.int_ctl & int_ctl_vmcb12_bits) |
692 		(vmcb01->control.int_ctl & int_ctl_vmcb01_bits);
693 
694 	vmcb02->control.int_vector          = svm->nested.ctl.int_vector;
695 	vmcb02->control.int_state           = svm->nested.ctl.int_state;
696 	vmcb02->control.event_inj           = svm->nested.ctl.event_inj;
697 	vmcb02->control.event_inj_err       = svm->nested.ctl.event_inj_err;
698 
699 	/*
700 	 * next_rip is consumed on VMRUN as the return address pushed on the
701 	 * stack for injected soft exceptions/interrupts.  If nrips is exposed
702 	 * to L1, take it verbatim from vmcb12.  If nrips is supported in
703 	 * hardware but not exposed to L1, stuff the actual L2 RIP to emulate
704 	 * what a nrips=0 CPU would do (L1 is responsible for advancing RIP
705 	 * prior to injecting the event).
706 	 */
707 	if (guest_can_use(vcpu, X86_FEATURE_NRIPS))
708 		vmcb02->control.next_rip    = svm->nested.ctl.next_rip;
709 	else if (boot_cpu_has(X86_FEATURE_NRIPS))
710 		vmcb02->control.next_rip    = vmcb12_rip;
711 
712 	svm->nmi_l1_to_l2 = is_evtinj_nmi(vmcb02->control.event_inj);
713 	if (is_evtinj_soft(vmcb02->control.event_inj)) {
714 		svm->soft_int_injected = true;
715 		svm->soft_int_csbase = vmcb12_csbase;
716 		svm->soft_int_old_rip = vmcb12_rip;
717 		if (guest_can_use(vcpu, X86_FEATURE_NRIPS))
718 			svm->soft_int_next_rip = svm->nested.ctl.next_rip;
719 		else
720 			svm->soft_int_next_rip = vmcb12_rip;
721 	}
722 
723 	vmcb02->control.virt_ext            = vmcb01->control.virt_ext &
724 					      LBR_CTL_ENABLE_MASK;
725 	if (guest_can_use(vcpu, X86_FEATURE_LBRV))
726 		vmcb02->control.virt_ext  |=
727 			(svm->nested.ctl.virt_ext & LBR_CTL_ENABLE_MASK);
728 
729 	if (!nested_vmcb_needs_vls_intercept(svm))
730 		vmcb02->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
731 
732 	if (guest_can_use(vcpu, X86_FEATURE_PAUSEFILTER))
733 		pause_count12 = svm->nested.ctl.pause_filter_count;
734 	else
735 		pause_count12 = 0;
736 	if (guest_can_use(vcpu, X86_FEATURE_PFTHRESHOLD))
737 		pause_thresh12 = svm->nested.ctl.pause_filter_thresh;
738 	else
739 		pause_thresh12 = 0;
740 	if (kvm_pause_in_guest(svm->vcpu.kvm)) {
741 		/* use guest values since host doesn't intercept PAUSE */
742 		vmcb02->control.pause_filter_count = pause_count12;
743 		vmcb02->control.pause_filter_thresh = pause_thresh12;
744 
745 	} else {
746 		/* start from host values otherwise */
747 		vmcb02->control.pause_filter_count = vmcb01->control.pause_filter_count;
748 		vmcb02->control.pause_filter_thresh = vmcb01->control.pause_filter_thresh;
749 
750 		/* ... but ensure filtering is disabled if so requested.  */
751 		if (vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_PAUSE)) {
752 			if (!pause_count12)
753 				vmcb02->control.pause_filter_count = 0;
754 			if (!pause_thresh12)
755 				vmcb02->control.pause_filter_thresh = 0;
756 		}
757 	}
758 
759 	nested_svm_transition_tlb_flush(vcpu);
760 
761 	/* Enter Guest-Mode */
762 	enter_guest_mode(vcpu);
763 
764 	/*
765 	 * Merge guest and host intercepts - must be called with vcpu in
766 	 * guest-mode to take effect.
767 	 */
768 	recalc_intercepts(svm);
769 }
770 
771 static void nested_svm_copy_common_state(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
772 {
773 	/*
774 	 * Some VMCB state is shared between L1 and L2 and thus has to be
775 	 * moved at the time of nested vmrun and vmexit.
776 	 *
777 	 * VMLOAD/VMSAVE state would also belong in this category, but KVM
778 	 * always performs VMLOAD and VMSAVE from the VMCB01.
779 	 */
780 	to_vmcb->save.spec_ctrl = from_vmcb->save.spec_ctrl;
781 }
782 
783 int enter_svm_guest_mode(struct kvm_vcpu *vcpu, u64 vmcb12_gpa,
784 			 struct vmcb *vmcb12, bool from_vmrun)
785 {
786 	struct vcpu_svm *svm = to_svm(vcpu);
787 	int ret;
788 
789 	trace_kvm_nested_vmenter(svm->vmcb->save.rip,
790 				 vmcb12_gpa,
791 				 vmcb12->save.rip,
792 				 vmcb12->control.int_ctl,
793 				 vmcb12->control.event_inj,
794 				 vmcb12->control.nested_ctl,
795 				 vmcb12->control.nested_cr3,
796 				 vmcb12->save.cr3,
797 				 KVM_ISA_SVM);
798 
799 	trace_kvm_nested_intercepts(vmcb12->control.intercepts[INTERCEPT_CR] & 0xffff,
800 				    vmcb12->control.intercepts[INTERCEPT_CR] >> 16,
801 				    vmcb12->control.intercepts[INTERCEPT_EXCEPTION],
802 				    vmcb12->control.intercepts[INTERCEPT_WORD3],
803 				    vmcb12->control.intercepts[INTERCEPT_WORD4],
804 				    vmcb12->control.intercepts[INTERCEPT_WORD5]);
805 
806 
807 	svm->nested.vmcb12_gpa = vmcb12_gpa;
808 
809 	WARN_ON(svm->vmcb == svm->nested.vmcb02.ptr);
810 
811 	nested_svm_copy_common_state(svm->vmcb01.ptr, svm->nested.vmcb02.ptr);
812 
813 	svm_switch_vmcb(svm, &svm->nested.vmcb02);
814 	nested_vmcb02_prepare_control(svm, vmcb12->save.rip, vmcb12->save.cs.base);
815 	nested_vmcb02_prepare_save(svm, vmcb12);
816 
817 	ret = nested_svm_load_cr3(&svm->vcpu, svm->nested.save.cr3,
818 				  nested_npt_enabled(svm), from_vmrun);
819 	if (ret)
820 		return ret;
821 
822 	if (!from_vmrun)
823 		kvm_make_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
824 
825 	svm_set_gif(svm, true);
826 
827 	if (kvm_vcpu_apicv_active(vcpu))
828 		kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
829 
830 	nested_svm_hv_update_vm_vp_ids(vcpu);
831 
832 	return 0;
833 }
834 
835 int nested_svm_vmrun(struct kvm_vcpu *vcpu)
836 {
837 	struct vcpu_svm *svm = to_svm(vcpu);
838 	int ret;
839 	struct vmcb *vmcb12;
840 	struct kvm_host_map map;
841 	u64 vmcb12_gpa;
842 	struct vmcb *vmcb01 = svm->vmcb01.ptr;
843 
844 	if (!svm->nested.hsave_msr) {
845 		kvm_inject_gp(vcpu, 0);
846 		return 1;
847 	}
848 
849 	if (is_smm(vcpu)) {
850 		kvm_queue_exception(vcpu, UD_VECTOR);
851 		return 1;
852 	}
853 
854 	/* This fails when VP assist page is enabled but the supplied GPA is bogus */
855 	ret = kvm_hv_verify_vp_assist(vcpu);
856 	if (ret) {
857 		kvm_inject_gp(vcpu, 0);
858 		return ret;
859 	}
860 
861 	vmcb12_gpa = svm->vmcb->save.rax;
862 	ret = kvm_vcpu_map(vcpu, gpa_to_gfn(vmcb12_gpa), &map);
863 	if (ret == -EINVAL) {
864 		kvm_inject_gp(vcpu, 0);
865 		return 1;
866 	} else if (ret) {
867 		return kvm_skip_emulated_instruction(vcpu);
868 	}
869 
870 	ret = kvm_skip_emulated_instruction(vcpu);
871 
872 	vmcb12 = map.hva;
873 
874 	if (WARN_ON_ONCE(!svm->nested.initialized))
875 		return -EINVAL;
876 
877 	nested_copy_vmcb_control_to_cache(svm, &vmcb12->control);
878 	nested_copy_vmcb_save_to_cache(svm, &vmcb12->save);
879 
880 	if (!nested_vmcb_check_save(vcpu) ||
881 	    !nested_vmcb_check_controls(vcpu)) {
882 		vmcb12->control.exit_code    = SVM_EXIT_ERR;
883 		vmcb12->control.exit_code_hi = 0;
884 		vmcb12->control.exit_info_1  = 0;
885 		vmcb12->control.exit_info_2  = 0;
886 		goto out;
887 	}
888 
889 	/*
890 	 * Since vmcb01 is not in use, we can use it to store some of the L1
891 	 * state.
892 	 */
893 	vmcb01->save.efer   = vcpu->arch.efer;
894 	vmcb01->save.cr0    = kvm_read_cr0(vcpu);
895 	vmcb01->save.cr4    = vcpu->arch.cr4;
896 	vmcb01->save.rflags = kvm_get_rflags(vcpu);
897 	vmcb01->save.rip    = kvm_rip_read(vcpu);
898 
899 	if (!npt_enabled)
900 		vmcb01->save.cr3 = kvm_read_cr3(vcpu);
901 
902 	svm->nested.nested_run_pending = 1;
903 
904 	if (enter_svm_guest_mode(vcpu, vmcb12_gpa, vmcb12, true))
905 		goto out_exit_err;
906 
907 	if (nested_svm_vmrun_msrpm(svm))
908 		goto out;
909 
910 out_exit_err:
911 	svm->nested.nested_run_pending = 0;
912 	svm->nmi_l1_to_l2 = false;
913 	svm->soft_int_injected = false;
914 
915 	svm->vmcb->control.exit_code    = SVM_EXIT_ERR;
916 	svm->vmcb->control.exit_code_hi = 0;
917 	svm->vmcb->control.exit_info_1  = 0;
918 	svm->vmcb->control.exit_info_2  = 0;
919 
920 	nested_svm_vmexit(svm);
921 
922 out:
923 	kvm_vcpu_unmap(vcpu, &map, true);
924 
925 	return ret;
926 }
927 
928 /* Copy state save area fields which are handled by VMRUN */
929 void svm_copy_vmrun_state(struct vmcb_save_area *to_save,
930 			  struct vmcb_save_area *from_save)
931 {
932 	to_save->es = from_save->es;
933 	to_save->cs = from_save->cs;
934 	to_save->ss = from_save->ss;
935 	to_save->ds = from_save->ds;
936 	to_save->gdtr = from_save->gdtr;
937 	to_save->idtr = from_save->idtr;
938 	to_save->rflags = from_save->rflags | X86_EFLAGS_FIXED;
939 	to_save->efer = from_save->efer;
940 	to_save->cr0 = from_save->cr0;
941 	to_save->cr3 = from_save->cr3;
942 	to_save->cr4 = from_save->cr4;
943 	to_save->rax = from_save->rax;
944 	to_save->rsp = from_save->rsp;
945 	to_save->rip = from_save->rip;
946 	to_save->cpl = 0;
947 }
948 
949 void svm_copy_vmloadsave_state(struct vmcb *to_vmcb, struct vmcb *from_vmcb)
950 {
951 	to_vmcb->save.fs = from_vmcb->save.fs;
952 	to_vmcb->save.gs = from_vmcb->save.gs;
953 	to_vmcb->save.tr = from_vmcb->save.tr;
954 	to_vmcb->save.ldtr = from_vmcb->save.ldtr;
955 	to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
956 	to_vmcb->save.star = from_vmcb->save.star;
957 	to_vmcb->save.lstar = from_vmcb->save.lstar;
958 	to_vmcb->save.cstar = from_vmcb->save.cstar;
959 	to_vmcb->save.sfmask = from_vmcb->save.sfmask;
960 	to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
961 	to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
962 	to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
963 }
964 
965 int nested_svm_vmexit(struct vcpu_svm *svm)
966 {
967 	struct kvm_vcpu *vcpu = &svm->vcpu;
968 	struct vmcb *vmcb01 = svm->vmcb01.ptr;
969 	struct vmcb *vmcb02 = svm->nested.vmcb02.ptr;
970 	struct vmcb *vmcb12;
971 	struct kvm_host_map map;
972 	int rc;
973 
974 	rc = kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.vmcb12_gpa), &map);
975 	if (rc) {
976 		if (rc == -EINVAL)
977 			kvm_inject_gp(vcpu, 0);
978 		return 1;
979 	}
980 
981 	vmcb12 = map.hva;
982 
983 	/* Exit Guest-Mode */
984 	leave_guest_mode(vcpu);
985 	svm->nested.vmcb12_gpa = 0;
986 	WARN_ON_ONCE(svm->nested.nested_run_pending);
987 
988 	kvm_clear_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
989 
990 	/* in case we halted in L2 */
991 	svm->vcpu.arch.mp_state = KVM_MP_STATE_RUNNABLE;
992 
993 	/* Give the current vmcb to the guest */
994 
995 	vmcb12->save.es     = vmcb02->save.es;
996 	vmcb12->save.cs     = vmcb02->save.cs;
997 	vmcb12->save.ss     = vmcb02->save.ss;
998 	vmcb12->save.ds     = vmcb02->save.ds;
999 	vmcb12->save.gdtr   = vmcb02->save.gdtr;
1000 	vmcb12->save.idtr   = vmcb02->save.idtr;
1001 	vmcb12->save.efer   = svm->vcpu.arch.efer;
1002 	vmcb12->save.cr0    = kvm_read_cr0(vcpu);
1003 	vmcb12->save.cr3    = kvm_read_cr3(vcpu);
1004 	vmcb12->save.cr2    = vmcb02->save.cr2;
1005 	vmcb12->save.cr4    = svm->vcpu.arch.cr4;
1006 	vmcb12->save.rflags = kvm_get_rflags(vcpu);
1007 	vmcb12->save.rip    = kvm_rip_read(vcpu);
1008 	vmcb12->save.rsp    = kvm_rsp_read(vcpu);
1009 	vmcb12->save.rax    = kvm_rax_read(vcpu);
1010 	vmcb12->save.dr7    = vmcb02->save.dr7;
1011 	vmcb12->save.dr6    = svm->vcpu.arch.dr6;
1012 	vmcb12->save.cpl    = vmcb02->save.cpl;
1013 
1014 	vmcb12->control.int_state         = vmcb02->control.int_state;
1015 	vmcb12->control.exit_code         = vmcb02->control.exit_code;
1016 	vmcb12->control.exit_code_hi      = vmcb02->control.exit_code_hi;
1017 	vmcb12->control.exit_info_1       = vmcb02->control.exit_info_1;
1018 	vmcb12->control.exit_info_2       = vmcb02->control.exit_info_2;
1019 
1020 	if (vmcb12->control.exit_code != SVM_EXIT_ERR)
1021 		nested_save_pending_event_to_vmcb12(svm, vmcb12);
1022 
1023 	if (guest_can_use(vcpu, X86_FEATURE_NRIPS))
1024 		vmcb12->control.next_rip  = vmcb02->control.next_rip;
1025 
1026 	vmcb12->control.int_ctl           = svm->nested.ctl.int_ctl;
1027 	vmcb12->control.event_inj         = svm->nested.ctl.event_inj;
1028 	vmcb12->control.event_inj_err     = svm->nested.ctl.event_inj_err;
1029 
1030 	if (!kvm_pause_in_guest(vcpu->kvm)) {
1031 		vmcb01->control.pause_filter_count = vmcb02->control.pause_filter_count;
1032 		vmcb_mark_dirty(vmcb01, VMCB_INTERCEPTS);
1033 
1034 	}
1035 
1036 	nested_svm_copy_common_state(svm->nested.vmcb02.ptr, svm->vmcb01.ptr);
1037 
1038 	svm_switch_vmcb(svm, &svm->vmcb01);
1039 
1040 	/*
1041 	 * Rules for synchronizing int_ctl bits from vmcb02 to vmcb01:
1042 	 *
1043 	 * V_IRQ, V_IRQ_VECTOR, V_INTR_PRIO_MASK, V_IGN_TPR:  If L1 doesn't
1044 	 * intercept interrupts, then KVM will use vmcb02's V_IRQ (and related
1045 	 * flags) to detect interrupt windows for L1 IRQs (even if L1 uses
1046 	 * virtual interrupt masking).  Raise KVM_REQ_EVENT to ensure that
1047 	 * KVM re-requests an interrupt window if necessary, which implicitly
1048 	 * copies this bits from vmcb02 to vmcb01.
1049 	 *
1050 	 * V_TPR: If L1 doesn't use virtual interrupt masking, then L1's vTPR
1051 	 * is stored in vmcb02, but its value doesn't need to be copied from/to
1052 	 * vmcb01 because it is copied from/to the virtual APIC's TPR register
1053 	 * on each VM entry/exit.
1054 	 *
1055 	 * V_GIF: If nested vGIF is not used, KVM uses vmcb02's V_GIF for L1's
1056 	 * V_GIF.  However, GIF is architecturally clear on each VM exit, thus
1057 	 * there is no need to copy V_GIF from vmcb02 to vmcb01.
1058 	 */
1059 	if (!nested_exit_on_intr(svm))
1060 		kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
1061 
1062 	if (unlikely(guest_can_use(vcpu, X86_FEATURE_LBRV) &&
1063 		     (svm->nested.ctl.virt_ext & LBR_CTL_ENABLE_MASK))) {
1064 		svm_copy_lbrs(vmcb12, vmcb02);
1065 		svm_update_lbrv(vcpu);
1066 	} else if (unlikely(vmcb01->control.virt_ext & LBR_CTL_ENABLE_MASK)) {
1067 		svm_copy_lbrs(vmcb01, vmcb02);
1068 		svm_update_lbrv(vcpu);
1069 	}
1070 
1071 	if (vnmi) {
1072 		if (vmcb02->control.int_ctl & V_NMI_BLOCKING_MASK)
1073 			vmcb01->control.int_ctl |= V_NMI_BLOCKING_MASK;
1074 		else
1075 			vmcb01->control.int_ctl &= ~V_NMI_BLOCKING_MASK;
1076 
1077 		if (vcpu->arch.nmi_pending) {
1078 			vcpu->arch.nmi_pending--;
1079 			vmcb01->control.int_ctl |= V_NMI_PENDING_MASK;
1080 		} else {
1081 			vmcb01->control.int_ctl &= ~V_NMI_PENDING_MASK;
1082 		}
1083 	}
1084 
1085 	/*
1086 	 * On vmexit the  GIF is set to false and
1087 	 * no event can be injected in L1.
1088 	 */
1089 	svm_set_gif(svm, false);
1090 	vmcb01->control.exit_int_info = 0;
1091 
1092 	svm->vcpu.arch.tsc_offset = svm->vcpu.arch.l1_tsc_offset;
1093 	if (vmcb01->control.tsc_offset != svm->vcpu.arch.tsc_offset) {
1094 		vmcb01->control.tsc_offset = svm->vcpu.arch.tsc_offset;
1095 		vmcb_mark_dirty(vmcb01, VMCB_INTERCEPTS);
1096 	}
1097 
1098 	if (kvm_caps.has_tsc_control &&
1099 	    vcpu->arch.tsc_scaling_ratio != vcpu->arch.l1_tsc_scaling_ratio) {
1100 		vcpu->arch.tsc_scaling_ratio = vcpu->arch.l1_tsc_scaling_ratio;
1101 		svm_write_tsc_multiplier(vcpu);
1102 	}
1103 
1104 	svm->nested.ctl.nested_cr3 = 0;
1105 
1106 	/*
1107 	 * Restore processor state that had been saved in vmcb01
1108 	 */
1109 	kvm_set_rflags(vcpu, vmcb01->save.rflags);
1110 	svm_set_efer(vcpu, vmcb01->save.efer);
1111 	svm_set_cr0(vcpu, vmcb01->save.cr0 | X86_CR0_PE);
1112 	svm_set_cr4(vcpu, vmcb01->save.cr4);
1113 	kvm_rax_write(vcpu, vmcb01->save.rax);
1114 	kvm_rsp_write(vcpu, vmcb01->save.rsp);
1115 	kvm_rip_write(vcpu, vmcb01->save.rip);
1116 
1117 	svm->vcpu.arch.dr7 = DR7_FIXED_1;
1118 	kvm_update_dr7(&svm->vcpu);
1119 
1120 	trace_kvm_nested_vmexit_inject(vmcb12->control.exit_code,
1121 				       vmcb12->control.exit_info_1,
1122 				       vmcb12->control.exit_info_2,
1123 				       vmcb12->control.exit_int_info,
1124 				       vmcb12->control.exit_int_info_err,
1125 				       KVM_ISA_SVM);
1126 
1127 	kvm_vcpu_unmap(vcpu, &map, true);
1128 
1129 	nested_svm_transition_tlb_flush(vcpu);
1130 
1131 	nested_svm_uninit_mmu_context(vcpu);
1132 
1133 	rc = nested_svm_load_cr3(vcpu, vmcb01->save.cr3, false, true);
1134 	if (rc)
1135 		return 1;
1136 
1137 	/*
1138 	 * Drop what we picked up for L2 via svm_complete_interrupts() so it
1139 	 * doesn't end up in L1.
1140 	 */
1141 	svm->vcpu.arch.nmi_injected = false;
1142 	kvm_clear_exception_queue(vcpu);
1143 	kvm_clear_interrupt_queue(vcpu);
1144 
1145 	/*
1146 	 * If we are here following the completion of a VMRUN that
1147 	 * is being single-stepped, queue the pending #DB intercept
1148 	 * right now so that it an be accounted for before we execute
1149 	 * L1's next instruction.
1150 	 */
1151 	if (unlikely(vmcb01->save.rflags & X86_EFLAGS_TF))
1152 		kvm_queue_exception(&(svm->vcpu), DB_VECTOR);
1153 
1154 	/*
1155 	 * Un-inhibit the AVIC right away, so that other vCPUs can start
1156 	 * to benefit from it right away.
1157 	 */
1158 	if (kvm_apicv_activated(vcpu->kvm))
1159 		__kvm_vcpu_update_apicv(vcpu);
1160 
1161 	return 0;
1162 }
1163 
1164 static void nested_svm_triple_fault(struct kvm_vcpu *vcpu)
1165 {
1166 	struct vcpu_svm *svm = to_svm(vcpu);
1167 
1168 	if (!vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_SHUTDOWN))
1169 		return;
1170 
1171 	kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1172 	nested_svm_simple_vmexit(to_svm(vcpu), SVM_EXIT_SHUTDOWN);
1173 }
1174 
1175 int svm_allocate_nested(struct vcpu_svm *svm)
1176 {
1177 	struct page *vmcb02_page;
1178 
1179 	if (svm->nested.initialized)
1180 		return 0;
1181 
1182 	vmcb02_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1183 	if (!vmcb02_page)
1184 		return -ENOMEM;
1185 	svm->nested.vmcb02.ptr = page_address(vmcb02_page);
1186 	svm->nested.vmcb02.pa = __sme_set(page_to_pfn(vmcb02_page) << PAGE_SHIFT);
1187 
1188 	svm->nested.msrpm = svm_vcpu_alloc_msrpm();
1189 	if (!svm->nested.msrpm)
1190 		goto err_free_vmcb02;
1191 	svm_vcpu_init_msrpm(&svm->vcpu, svm->nested.msrpm);
1192 
1193 	svm->nested.initialized = true;
1194 	return 0;
1195 
1196 err_free_vmcb02:
1197 	__free_page(vmcb02_page);
1198 	return -ENOMEM;
1199 }
1200 
1201 void svm_free_nested(struct vcpu_svm *svm)
1202 {
1203 	if (!svm->nested.initialized)
1204 		return;
1205 
1206 	if (WARN_ON_ONCE(svm->vmcb != svm->vmcb01.ptr))
1207 		svm_switch_vmcb(svm, &svm->vmcb01);
1208 
1209 	svm_vcpu_free_msrpm(svm->nested.msrpm);
1210 	svm->nested.msrpm = NULL;
1211 
1212 	__free_page(virt_to_page(svm->nested.vmcb02.ptr));
1213 	svm->nested.vmcb02.ptr = NULL;
1214 
1215 	/*
1216 	 * When last_vmcb12_gpa matches the current vmcb12 gpa,
1217 	 * some vmcb12 fields are not loaded if they are marked clean
1218 	 * in the vmcb12, since in this case they are up to date already.
1219 	 *
1220 	 * When the vmcb02 is freed, this optimization becomes invalid.
1221 	 */
1222 	svm->nested.last_vmcb12_gpa = INVALID_GPA;
1223 
1224 	svm->nested.initialized = false;
1225 }
1226 
1227 void svm_leave_nested(struct kvm_vcpu *vcpu)
1228 {
1229 	struct vcpu_svm *svm = to_svm(vcpu);
1230 
1231 	if (is_guest_mode(vcpu)) {
1232 		svm->nested.nested_run_pending = 0;
1233 		svm->nested.vmcb12_gpa = INVALID_GPA;
1234 
1235 		leave_guest_mode(vcpu);
1236 
1237 		svm_switch_vmcb(svm, &svm->vmcb01);
1238 
1239 		nested_svm_uninit_mmu_context(vcpu);
1240 		vmcb_mark_all_dirty(svm->vmcb);
1241 
1242 		if (kvm_apicv_activated(vcpu->kvm))
1243 			kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
1244 	}
1245 
1246 	kvm_clear_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
1247 }
1248 
1249 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
1250 {
1251 	u32 offset, msr, value;
1252 	int write, mask;
1253 
1254 	if (!(vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_MSR_PROT)))
1255 		return NESTED_EXIT_HOST;
1256 
1257 	msr    = svm->vcpu.arch.regs[VCPU_REGS_RCX];
1258 	offset = svm_msrpm_offset(msr);
1259 	write  = svm->vmcb->control.exit_info_1 & 1;
1260 	mask   = 1 << ((2 * (msr & 0xf)) + write);
1261 
1262 	if (offset == MSR_INVALID)
1263 		return NESTED_EXIT_DONE;
1264 
1265 	/* Offset is in 32 bit units but need in 8 bit units */
1266 	offset *= 4;
1267 
1268 	if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.ctl.msrpm_base_pa + offset, &value, 4))
1269 		return NESTED_EXIT_DONE;
1270 
1271 	return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
1272 }
1273 
1274 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
1275 {
1276 	unsigned port, size, iopm_len;
1277 	u16 val, mask;
1278 	u8 start_bit;
1279 	u64 gpa;
1280 
1281 	if (!(vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_IOIO_PROT)))
1282 		return NESTED_EXIT_HOST;
1283 
1284 	port = svm->vmcb->control.exit_info_1 >> 16;
1285 	size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
1286 		SVM_IOIO_SIZE_SHIFT;
1287 	gpa  = svm->nested.ctl.iopm_base_pa + (port / 8);
1288 	start_bit = port % 8;
1289 	iopm_len = (start_bit + size > 8) ? 2 : 1;
1290 	mask = (0xf >> (4 - size)) << start_bit;
1291 	val = 0;
1292 
1293 	if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
1294 		return NESTED_EXIT_DONE;
1295 
1296 	return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
1297 }
1298 
1299 static int nested_svm_intercept(struct vcpu_svm *svm)
1300 {
1301 	u32 exit_code = svm->vmcb->control.exit_code;
1302 	int vmexit = NESTED_EXIT_HOST;
1303 
1304 	switch (exit_code) {
1305 	case SVM_EXIT_MSR:
1306 		vmexit = nested_svm_exit_handled_msr(svm);
1307 		break;
1308 	case SVM_EXIT_IOIO:
1309 		vmexit = nested_svm_intercept_ioio(svm);
1310 		break;
1311 	case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
1312 		if (vmcb12_is_intercept(&svm->nested.ctl, exit_code))
1313 			vmexit = NESTED_EXIT_DONE;
1314 		break;
1315 	}
1316 	case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
1317 		if (vmcb12_is_intercept(&svm->nested.ctl, exit_code))
1318 			vmexit = NESTED_EXIT_DONE;
1319 		break;
1320 	}
1321 	case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
1322 		/*
1323 		 * Host-intercepted exceptions have been checked already in
1324 		 * nested_svm_exit_special.  There is nothing to do here,
1325 		 * the vmexit is injected by svm_check_nested_events.
1326 		 */
1327 		vmexit = NESTED_EXIT_DONE;
1328 		break;
1329 	}
1330 	case SVM_EXIT_ERR: {
1331 		vmexit = NESTED_EXIT_DONE;
1332 		break;
1333 	}
1334 	default: {
1335 		if (vmcb12_is_intercept(&svm->nested.ctl, exit_code))
1336 			vmexit = NESTED_EXIT_DONE;
1337 	}
1338 	}
1339 
1340 	return vmexit;
1341 }
1342 
1343 int nested_svm_exit_handled(struct vcpu_svm *svm)
1344 {
1345 	int vmexit;
1346 
1347 	vmexit = nested_svm_intercept(svm);
1348 
1349 	if (vmexit == NESTED_EXIT_DONE)
1350 		nested_svm_vmexit(svm);
1351 
1352 	return vmexit;
1353 }
1354 
1355 int nested_svm_check_permissions(struct kvm_vcpu *vcpu)
1356 {
1357 	if (!(vcpu->arch.efer & EFER_SVME) || !is_paging(vcpu)) {
1358 		kvm_queue_exception(vcpu, UD_VECTOR);
1359 		return 1;
1360 	}
1361 
1362 	if (to_svm(vcpu)->vmcb->save.cpl) {
1363 		kvm_inject_gp(vcpu, 0);
1364 		return 1;
1365 	}
1366 
1367 	return 0;
1368 }
1369 
1370 static bool nested_svm_is_exception_vmexit(struct kvm_vcpu *vcpu, u8 vector,
1371 					   u32 error_code)
1372 {
1373 	struct vcpu_svm *svm = to_svm(vcpu);
1374 
1375 	return (svm->nested.ctl.intercepts[INTERCEPT_EXCEPTION] & BIT(vector));
1376 }
1377 
1378 static void nested_svm_inject_exception_vmexit(struct kvm_vcpu *vcpu)
1379 {
1380 	struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
1381 	struct vcpu_svm *svm = to_svm(vcpu);
1382 	struct vmcb *vmcb = svm->vmcb;
1383 
1384 	vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + ex->vector;
1385 	vmcb->control.exit_code_hi = 0;
1386 
1387 	if (ex->has_error_code)
1388 		vmcb->control.exit_info_1 = ex->error_code;
1389 
1390 	/*
1391 	 * EXITINFO2 is undefined for all exception intercepts other
1392 	 * than #PF.
1393 	 */
1394 	if (ex->vector == PF_VECTOR) {
1395 		if (ex->has_payload)
1396 			vmcb->control.exit_info_2 = ex->payload;
1397 		else
1398 			vmcb->control.exit_info_2 = vcpu->arch.cr2;
1399 	} else if (ex->vector == DB_VECTOR) {
1400 		/* See kvm_check_and_inject_events().  */
1401 		kvm_deliver_exception_payload(vcpu, ex);
1402 
1403 		if (vcpu->arch.dr7 & DR7_GD) {
1404 			vcpu->arch.dr7 &= ~DR7_GD;
1405 			kvm_update_dr7(vcpu);
1406 		}
1407 	} else {
1408 		WARN_ON(ex->has_payload);
1409 	}
1410 
1411 	nested_svm_vmexit(svm);
1412 }
1413 
1414 static inline bool nested_exit_on_init(struct vcpu_svm *svm)
1415 {
1416 	return vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_INIT);
1417 }
1418 
1419 static int svm_check_nested_events(struct kvm_vcpu *vcpu)
1420 {
1421 	struct kvm_lapic *apic = vcpu->arch.apic;
1422 	struct vcpu_svm *svm = to_svm(vcpu);
1423 	/*
1424 	 * Only a pending nested run blocks a pending exception.  If there is a
1425 	 * previously injected event, the pending exception occurred while said
1426 	 * event was being delivered and thus needs to be handled.
1427 	 */
1428 	bool block_nested_exceptions = svm->nested.nested_run_pending;
1429 	/*
1430 	 * New events (not exceptions) are only recognized at instruction
1431 	 * boundaries.  If an event needs reinjection, then KVM is handling a
1432 	 * VM-Exit that occurred _during_ instruction execution; new events are
1433 	 * blocked until the instruction completes.
1434 	 */
1435 	bool block_nested_events = block_nested_exceptions ||
1436 				   kvm_event_needs_reinjection(vcpu);
1437 
1438 	if (lapic_in_kernel(vcpu) &&
1439 	    test_bit(KVM_APIC_INIT, &apic->pending_events)) {
1440 		if (block_nested_events)
1441 			return -EBUSY;
1442 		if (!nested_exit_on_init(svm))
1443 			return 0;
1444 		nested_svm_simple_vmexit(svm, SVM_EXIT_INIT);
1445 		return 0;
1446 	}
1447 
1448 	if (vcpu->arch.exception_vmexit.pending) {
1449 		if (block_nested_exceptions)
1450                         return -EBUSY;
1451 		nested_svm_inject_exception_vmexit(vcpu);
1452 		return 0;
1453 	}
1454 
1455 	if (vcpu->arch.exception.pending) {
1456 		if (block_nested_exceptions)
1457 			return -EBUSY;
1458 		return 0;
1459 	}
1460 
1461 #ifdef CONFIG_KVM_SMM
1462 	if (vcpu->arch.smi_pending && !svm_smi_blocked(vcpu)) {
1463 		if (block_nested_events)
1464 			return -EBUSY;
1465 		if (!nested_exit_on_smi(svm))
1466 			return 0;
1467 		nested_svm_simple_vmexit(svm, SVM_EXIT_SMI);
1468 		return 0;
1469 	}
1470 #endif
1471 
1472 	if (vcpu->arch.nmi_pending && !svm_nmi_blocked(vcpu)) {
1473 		if (block_nested_events)
1474 			return -EBUSY;
1475 		if (!nested_exit_on_nmi(svm))
1476 			return 0;
1477 		nested_svm_simple_vmexit(svm, SVM_EXIT_NMI);
1478 		return 0;
1479 	}
1480 
1481 	if (kvm_cpu_has_interrupt(vcpu) && !svm_interrupt_blocked(vcpu)) {
1482 		if (block_nested_events)
1483 			return -EBUSY;
1484 		if (!nested_exit_on_intr(svm))
1485 			return 0;
1486 		trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
1487 		nested_svm_simple_vmexit(svm, SVM_EXIT_INTR);
1488 		return 0;
1489 	}
1490 
1491 	return 0;
1492 }
1493 
1494 int nested_svm_exit_special(struct vcpu_svm *svm)
1495 {
1496 	u32 exit_code = svm->vmcb->control.exit_code;
1497 	struct kvm_vcpu *vcpu = &svm->vcpu;
1498 
1499 	switch (exit_code) {
1500 	case SVM_EXIT_INTR:
1501 	case SVM_EXIT_NMI:
1502 	case SVM_EXIT_NPF:
1503 		return NESTED_EXIT_HOST;
1504 	case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
1505 		u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
1506 
1507 		if (svm->vmcb01.ptr->control.intercepts[INTERCEPT_EXCEPTION] &
1508 		    excp_bits)
1509 			return NESTED_EXIT_HOST;
1510 		else if (exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR &&
1511 			 svm->vcpu.arch.apf.host_apf_flags)
1512 			/* Trap async PF even if not shadowing */
1513 			return NESTED_EXIT_HOST;
1514 		break;
1515 	}
1516 	case SVM_EXIT_VMMCALL:
1517 		/* Hyper-V L2 TLB flush hypercall is handled by L0 */
1518 		if (guest_hv_cpuid_has_l2_tlb_flush(vcpu) &&
1519 		    nested_svm_l2_tlb_flush_enabled(vcpu) &&
1520 		    kvm_hv_is_tlb_flush_hcall(vcpu))
1521 			return NESTED_EXIT_HOST;
1522 		break;
1523 	default:
1524 		break;
1525 	}
1526 
1527 	return NESTED_EXIT_CONTINUE;
1528 }
1529 
1530 void nested_svm_update_tsc_ratio_msr(struct kvm_vcpu *vcpu)
1531 {
1532 	struct vcpu_svm *svm = to_svm(vcpu);
1533 
1534 	vcpu->arch.tsc_scaling_ratio =
1535 		kvm_calc_nested_tsc_multiplier(vcpu->arch.l1_tsc_scaling_ratio,
1536 					       svm->tsc_ratio_msr);
1537 	svm_write_tsc_multiplier(vcpu);
1538 }
1539 
1540 /* Inverse operation of nested_copy_vmcb_control_to_cache(). asid is copied too. */
1541 static void nested_copy_vmcb_cache_to_control(struct vmcb_control_area *dst,
1542 					      struct vmcb_ctrl_area_cached *from)
1543 {
1544 	unsigned int i;
1545 
1546 	memset(dst, 0, sizeof(struct vmcb_control_area));
1547 
1548 	for (i = 0; i < MAX_INTERCEPT; i++)
1549 		dst->intercepts[i] = from->intercepts[i];
1550 
1551 	dst->iopm_base_pa         = from->iopm_base_pa;
1552 	dst->msrpm_base_pa        = from->msrpm_base_pa;
1553 	dst->tsc_offset           = from->tsc_offset;
1554 	dst->asid                 = from->asid;
1555 	dst->tlb_ctl              = from->tlb_ctl;
1556 	dst->int_ctl              = from->int_ctl;
1557 	dst->int_vector           = from->int_vector;
1558 	dst->int_state            = from->int_state;
1559 	dst->exit_code            = from->exit_code;
1560 	dst->exit_code_hi         = from->exit_code_hi;
1561 	dst->exit_info_1          = from->exit_info_1;
1562 	dst->exit_info_2          = from->exit_info_2;
1563 	dst->exit_int_info        = from->exit_int_info;
1564 	dst->exit_int_info_err    = from->exit_int_info_err;
1565 	dst->nested_ctl           = from->nested_ctl;
1566 	dst->event_inj            = from->event_inj;
1567 	dst->event_inj_err        = from->event_inj_err;
1568 	dst->next_rip             = from->next_rip;
1569 	dst->nested_cr3           = from->nested_cr3;
1570 	dst->virt_ext              = from->virt_ext;
1571 	dst->pause_filter_count   = from->pause_filter_count;
1572 	dst->pause_filter_thresh  = from->pause_filter_thresh;
1573 	/* 'clean' and 'hv_enlightenments' are not changed by KVM */
1574 }
1575 
1576 static int svm_get_nested_state(struct kvm_vcpu *vcpu,
1577 				struct kvm_nested_state __user *user_kvm_nested_state,
1578 				u32 user_data_size)
1579 {
1580 	struct vcpu_svm *svm;
1581 	struct vmcb_control_area *ctl;
1582 	unsigned long r;
1583 	struct kvm_nested_state kvm_state = {
1584 		.flags = 0,
1585 		.format = KVM_STATE_NESTED_FORMAT_SVM,
1586 		.size = sizeof(kvm_state),
1587 	};
1588 	struct vmcb __user *user_vmcb = (struct vmcb __user *)
1589 		&user_kvm_nested_state->data.svm[0];
1590 
1591 	if (!vcpu)
1592 		return kvm_state.size + KVM_STATE_NESTED_SVM_VMCB_SIZE;
1593 
1594 	svm = to_svm(vcpu);
1595 
1596 	if (user_data_size < kvm_state.size)
1597 		goto out;
1598 
1599 	/* First fill in the header and copy it out.  */
1600 	if (is_guest_mode(vcpu)) {
1601 		kvm_state.hdr.svm.vmcb_pa = svm->nested.vmcb12_gpa;
1602 		kvm_state.size += KVM_STATE_NESTED_SVM_VMCB_SIZE;
1603 		kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
1604 
1605 		if (svm->nested.nested_run_pending)
1606 			kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
1607 	}
1608 
1609 	if (gif_set(svm))
1610 		kvm_state.flags |= KVM_STATE_NESTED_GIF_SET;
1611 
1612 	if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
1613 		return -EFAULT;
1614 
1615 	if (!is_guest_mode(vcpu))
1616 		goto out;
1617 
1618 	/*
1619 	 * Copy over the full size of the VMCB rather than just the size
1620 	 * of the structs.
1621 	 */
1622 	if (clear_user(user_vmcb, KVM_STATE_NESTED_SVM_VMCB_SIZE))
1623 		return -EFAULT;
1624 
1625 	ctl = kzalloc(sizeof(*ctl), GFP_KERNEL);
1626 	if (!ctl)
1627 		return -ENOMEM;
1628 
1629 	nested_copy_vmcb_cache_to_control(ctl, &svm->nested.ctl);
1630 	r = copy_to_user(&user_vmcb->control, ctl,
1631 			 sizeof(user_vmcb->control));
1632 	kfree(ctl);
1633 	if (r)
1634 		return -EFAULT;
1635 
1636 	if (copy_to_user(&user_vmcb->save, &svm->vmcb01.ptr->save,
1637 			 sizeof(user_vmcb->save)))
1638 		return -EFAULT;
1639 out:
1640 	return kvm_state.size;
1641 }
1642 
1643 static int svm_set_nested_state(struct kvm_vcpu *vcpu,
1644 				struct kvm_nested_state __user *user_kvm_nested_state,
1645 				struct kvm_nested_state *kvm_state)
1646 {
1647 	struct vcpu_svm *svm = to_svm(vcpu);
1648 	struct vmcb __user *user_vmcb = (struct vmcb __user *)
1649 		&user_kvm_nested_state->data.svm[0];
1650 	struct vmcb_control_area *ctl;
1651 	struct vmcb_save_area *save;
1652 	struct vmcb_save_area_cached save_cached;
1653 	struct vmcb_ctrl_area_cached ctl_cached;
1654 	unsigned long cr0;
1655 	int ret;
1656 
1657 	BUILD_BUG_ON(sizeof(struct vmcb_control_area) + sizeof(struct vmcb_save_area) >
1658 		     KVM_STATE_NESTED_SVM_VMCB_SIZE);
1659 
1660 	if (kvm_state->format != KVM_STATE_NESTED_FORMAT_SVM)
1661 		return -EINVAL;
1662 
1663 	if (kvm_state->flags & ~(KVM_STATE_NESTED_GUEST_MODE |
1664 				 KVM_STATE_NESTED_RUN_PENDING |
1665 				 KVM_STATE_NESTED_GIF_SET))
1666 		return -EINVAL;
1667 
1668 	/*
1669 	 * If in guest mode, vcpu->arch.efer actually refers to the L2 guest's
1670 	 * EFER.SVME, but EFER.SVME still has to be 1 for VMRUN to succeed.
1671 	 */
1672 	if (!(vcpu->arch.efer & EFER_SVME)) {
1673 		/* GIF=1 and no guest mode are required if SVME=0.  */
1674 		if (kvm_state->flags != KVM_STATE_NESTED_GIF_SET)
1675 			return -EINVAL;
1676 	}
1677 
1678 	/* SMM temporarily disables SVM, so we cannot be in guest mode.  */
1679 	if (is_smm(vcpu) && (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
1680 		return -EINVAL;
1681 
1682 	if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE)) {
1683 		svm_leave_nested(vcpu);
1684 		svm_set_gif(svm, !!(kvm_state->flags & KVM_STATE_NESTED_GIF_SET));
1685 		return 0;
1686 	}
1687 
1688 	if (!page_address_valid(vcpu, kvm_state->hdr.svm.vmcb_pa))
1689 		return -EINVAL;
1690 	if (kvm_state->size < sizeof(*kvm_state) + KVM_STATE_NESTED_SVM_VMCB_SIZE)
1691 		return -EINVAL;
1692 
1693 	ret  = -ENOMEM;
1694 	ctl  = kzalloc(sizeof(*ctl),  GFP_KERNEL_ACCOUNT);
1695 	save = kzalloc(sizeof(*save), GFP_KERNEL_ACCOUNT);
1696 	if (!ctl || !save)
1697 		goto out_free;
1698 
1699 	ret = -EFAULT;
1700 	if (copy_from_user(ctl, &user_vmcb->control, sizeof(*ctl)))
1701 		goto out_free;
1702 	if (copy_from_user(save, &user_vmcb->save, sizeof(*save)))
1703 		goto out_free;
1704 
1705 	ret = -EINVAL;
1706 	__nested_copy_vmcb_control_to_cache(vcpu, &ctl_cached, ctl);
1707 	if (!__nested_vmcb_check_controls(vcpu, &ctl_cached))
1708 		goto out_free;
1709 
1710 	/*
1711 	 * Processor state contains L2 state.  Check that it is
1712 	 * valid for guest mode (see nested_vmcb_check_save).
1713 	 */
1714 	cr0 = kvm_read_cr0(vcpu);
1715         if (((cr0 & X86_CR0_CD) == 0) && (cr0 & X86_CR0_NW))
1716 		goto out_free;
1717 
1718 	/*
1719 	 * Validate host state saved from before VMRUN (see
1720 	 * nested_svm_check_permissions).
1721 	 */
1722 	__nested_copy_vmcb_save_to_cache(&save_cached, save);
1723 	if (!(save->cr0 & X86_CR0_PG) ||
1724 	    !(save->cr0 & X86_CR0_PE) ||
1725 	    (save->rflags & X86_EFLAGS_VM) ||
1726 	    !__nested_vmcb_check_save(vcpu, &save_cached))
1727 		goto out_free;
1728 
1729 
1730 	/*
1731 	 * All checks done, we can enter guest mode. Userspace provides
1732 	 * vmcb12.control, which will be combined with L1 and stored into
1733 	 * vmcb02, and the L1 save state which we store in vmcb01.
1734 	 * L2 registers if needed are moved from the current VMCB to VMCB02.
1735 	 */
1736 
1737 	if (is_guest_mode(vcpu))
1738 		svm_leave_nested(vcpu);
1739 	else
1740 		svm->nested.vmcb02.ptr->save = svm->vmcb01.ptr->save;
1741 
1742 	svm_set_gif(svm, !!(kvm_state->flags & KVM_STATE_NESTED_GIF_SET));
1743 
1744 	svm->nested.nested_run_pending =
1745 		!!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
1746 
1747 	svm->nested.vmcb12_gpa = kvm_state->hdr.svm.vmcb_pa;
1748 
1749 	svm_copy_vmrun_state(&svm->vmcb01.ptr->save, save);
1750 	nested_copy_vmcb_control_to_cache(svm, ctl);
1751 
1752 	svm_switch_vmcb(svm, &svm->nested.vmcb02);
1753 	nested_vmcb02_prepare_control(svm, svm->vmcb->save.rip, svm->vmcb->save.cs.base);
1754 
1755 	/*
1756 	 * While the nested guest CR3 is already checked and set by
1757 	 * KVM_SET_SREGS, it was set when nested state was yet loaded,
1758 	 * thus MMU might not be initialized correctly.
1759 	 * Set it again to fix this.
1760 	 */
1761 
1762 	ret = nested_svm_load_cr3(&svm->vcpu, vcpu->arch.cr3,
1763 				  nested_npt_enabled(svm), false);
1764 	if (WARN_ON_ONCE(ret))
1765 		goto out_free;
1766 
1767 	svm->nested.force_msr_bitmap_recalc = true;
1768 
1769 	kvm_make_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
1770 	ret = 0;
1771 out_free:
1772 	kfree(save);
1773 	kfree(ctl);
1774 
1775 	return ret;
1776 }
1777 
1778 static bool svm_get_nested_state_pages(struct kvm_vcpu *vcpu)
1779 {
1780 	struct vcpu_svm *svm = to_svm(vcpu);
1781 
1782 	if (WARN_ON(!is_guest_mode(vcpu)))
1783 		return true;
1784 
1785 	if (!vcpu->arch.pdptrs_from_userspace &&
1786 	    !nested_npt_enabled(svm) && is_pae_paging(vcpu))
1787 		/*
1788 		 * Reload the guest's PDPTRs since after a migration
1789 		 * the guest CR3 might be restored prior to setting the nested
1790 		 * state which can lead to a load of wrong PDPTRs.
1791 		 */
1792 		if (CC(!load_pdptrs(vcpu, vcpu->arch.cr3)))
1793 			return false;
1794 
1795 	if (!nested_svm_vmrun_msrpm(svm)) {
1796 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
1797 		vcpu->run->internal.suberror =
1798 			KVM_INTERNAL_ERROR_EMULATION;
1799 		vcpu->run->internal.ndata = 0;
1800 		return false;
1801 	}
1802 
1803 	if (kvm_hv_verify_vp_assist(vcpu))
1804 		return false;
1805 
1806 	return true;
1807 }
1808 
1809 struct kvm_x86_nested_ops svm_nested_ops = {
1810 	.leave_nested = svm_leave_nested,
1811 	.is_exception_vmexit = nested_svm_is_exception_vmexit,
1812 	.check_events = svm_check_nested_events,
1813 	.triple_fault = nested_svm_triple_fault,
1814 	.get_nested_state_pages = svm_get_nested_state_pages,
1815 	.get_state = svm_get_nested_state,
1816 	.set_state = svm_set_nested_state,
1817 	.hv_inject_synthetic_vmexit_post_tlb_flush = svm_hv_inject_synthetic_vmexit_post_tlb_flush,
1818 };
1819