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