xref: /linux/arch/x86/kvm/svm/svm.c (revision 031ef175269d11b6368a9bff71a6a14aaa52b3f4)
1 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
2 
3 #include <linux/kvm_host.h>
4 
5 #include "irq.h"
6 #include "mmu.h"
7 #include "regs.h"
8 #include "x86.h"
9 #include "smm.h"
10 #include "cpuid.h"
11 #include "pmu.h"
12 
13 #include <linux/module.h>
14 #include <linux/kernel.h>
15 #include <linux/vmalloc.h>
16 #include <linux/highmem.h>
17 #include <linux/amd-iommu.h>
18 #include <linux/sched.h>
19 #include <linux/trace_events.h>
20 #include <linux/slab.h>
21 #include <linux/hashtable.h>
22 #include <linux/objtool.h>
23 #include <linux/psp-sev.h>
24 #include <linux/file.h>
25 #include <linux/pagemap.h>
26 #include <linux/swap.h>
27 #include <linux/rwsem.h>
28 #include <linux/cc_platform.h>
29 #include <linux/smp.h>
30 #include <linux/string_choices.h>
31 #include <linux/mutex.h>
32 
33 #include <asm/apic.h>
34 #include <asm/msr.h>
35 #include <asm/perf_event.h>
36 #include <asm/tlbflush.h>
37 #include <asm/desc.h>
38 #include <asm/debugreg.h>
39 #include <asm/kvm_para.h>
40 #include <asm/irq_remapping.h>
41 #include <asm/spec-ctrl.h>
42 #include <asm/cpu_device_id.h>
43 #include <asm/cpuid/api.h>
44 #include <asm/traps.h>
45 #include <asm/reboot.h>
46 #include <asm/fpu/api.h>
47 #include <asm/virt.h>
48 
49 #include <trace/events/ipi.h>
50 
51 #include "trace.h"
52 
53 #include "vmenter.h"
54 #include "svm.h"
55 #include "svm_ops.h"
56 
57 #include "hyperv.h"
58 #include "kvm_onhyperv.h"
59 #include "svm_onhyperv.h"
60 
61 MODULE_AUTHOR("Qumranet");
62 MODULE_DESCRIPTION("KVM support for SVM (AMD-V) extensions");
63 MODULE_LICENSE("GPL");
64 
65 #ifdef MODULE
66 static const struct x86_cpu_id svm_cpu_id[] = {
67 	X86_MATCH_FEATURE(X86_FEATURE_SVM, NULL),
68 	{}
69 };
70 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
71 #endif
72 
73 #define SEG_TYPE_LDT 2
74 #define SEG_TYPE_BUSY_TSS16 3
75 
76 static bool erratum_383_found __read_mostly;
77 
78 /*
79  * Set osvw_len to higher value when updated Revision Guides
80  * are published and we know what the new status bits are
81  */
82 static uint64_t osvw_len = 4, osvw_status;
83 static DEFINE_SPINLOCK(osvw_lock);
84 
85 static DEFINE_PER_CPU(u64, current_tsc_ratio);
86 
87 /*
88  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
89  * pause_filter_count: On processors that support Pause filtering(indicated
90  *	by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
91  *	count value. On VMRUN this value is loaded into an internal counter.
92  *	Each time a pause instruction is executed, this counter is decremented
93  *	until it reaches zero at which time a #VMEXIT is generated if pause
94  *	intercept is enabled. Refer to  AMD APM Vol 2 Section 15.14.4 Pause
95  *	Intercept Filtering for more details.
96  *	This also indicate if ple logic enabled.
97  *
98  * pause_filter_thresh: In addition, some processor families support advanced
99  *	pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
100  *	the amount of time a guest is allowed to execute in a pause loop.
101  *	In this mode, a 16-bit pause filter threshold field is added in the
102  *	VMCB. The threshold value is a cycle count that is used to reset the
103  *	pause counter. As with simple pause filtering, VMRUN loads the pause
104  *	count value from VMCB into an internal counter. Then, on each pause
105  *	instruction the hardware checks the elapsed number of cycles since
106  *	the most recent pause instruction against the pause filter threshold.
107  *	If the elapsed cycle count is greater than the pause filter threshold,
108  *	then the internal pause count is reloaded from the VMCB and execution
109  *	continues. If the elapsed cycle count is less than the pause filter
110  *	threshold, then the internal pause count is decremented. If the count
111  *	value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
112  *	triggered. If advanced pause filtering is supported and pause filter
113  *	threshold field is set to zero, the filter will operate in the simpler,
114  *	count only mode.
115  */
116 
117 static unsigned short __ro_after_init pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
118 module_param(pause_filter_thresh, ushort, 0444);
119 
120 static unsigned short __ro_after_init pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
121 module_param(pause_filter_count, ushort, 0444);
122 
123 /* Default doubles per-vcpu window every exit. */
124 static unsigned short __ro_after_init pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
125 module_param(pause_filter_count_grow, ushort, 0444);
126 
127 /* Default resets per-vcpu window every exit to pause_filter_count. */
128 static unsigned short __ro_after_init pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
129 module_param(pause_filter_count_shrink, ushort, 0444);
130 
131 /* Default is to compute the maximum so we can never overflow. */
132 static unsigned short __ro_after_init pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
133 module_param(pause_filter_count_max, ushort, 0444);
134 
135 /*
136  * Use nested page tables by default.  Note, NPT may get forced off by
137  * svm_hardware_setup() if it's unsupported by hardware or the host kernel.
138  */
139 bool __ro_after_init npt_enabled = true;
140 module_param_named(npt, npt_enabled, bool, 0444);
141 
142 bool gmet_enabled = true;
143 module_param_named(gmet, gmet_enabled, bool, 0444);
144 
145 /* allow nested virtualization in KVM/SVM */
146 static int __ro_after_init nested = true;
147 module_param(nested, int, 0444);
148 
149 /* enable/disable Next RIP Save */
150 int __ro_after_init nrips = true;
151 module_param(nrips, int, 0444);
152 
153 /* enable/disable Virtual VMLOAD VMSAVE */
154 static int __ro_after_init vls = true;
155 module_param(vls, int, 0444);
156 
157 /* enable/disable Virtual GIF */
158 int __ro_after_init vgif = true;
159 module_param(vgif, int, 0444);
160 
161 /* enable/disable LBR virtualization */
162 int __ro_after_init lbrv = true;
163 module_param(lbrv, int, 0444);
164 
165 static int __ro_after_init tsc_scaling = true;
166 module_param(tsc_scaling, int, 0444);
167 
168 module_param(enable_device_posted_irqs, bool, 0444);
169 
170 bool __read_mostly dump_invalid_vmcb;
171 module_param(dump_invalid_vmcb, bool, 0644);
172 
173 
174 bool __ro_after_init intercept_smi = true;
175 module_param(intercept_smi, bool, 0444);
176 
177 bool __ro_after_init vnmi = true;
178 module_param(vnmi, bool, 0444);
179 
180 module_param(enable_mediated_pmu, bool, 0444);
181 
182 bool __ro_after_init pml = true;
183 module_param(pml, bool, 0444);
184 
185 static bool __ro_after_init svm_gp_erratum_intercept = true;
186 
187 static u8 rsm_ins_bytes[] = "\x0f\xaa";
188 
189 static unsigned long __read_mostly iopm_base;
190 
191 DEFINE_PER_CPU(struct svm_cpu_data, svm_data);
192 
193 static DEFINE_MUTEX(vmcb_dump_mutex);
194 
195 /*
196  * Only MSR_TSC_AUX is switched via the user return hook.  EFER is switched via
197  * the VMCB, and the SYSCALL/SYSENTER MSRs are handled by VMLOAD/VMSAVE.
198  *
199  * RDTSCP and RDPID are not used in the kernel, specifically to allow KVM to
200  * defer the restoration of TSC_AUX until the CPU returns to userspace.
201  */
202 int tsc_aux_uret_slot __ro_after_init = -1;
203 
204 static int get_npt_level(void)
205 {
206 #ifdef CONFIG_X86_64
207 	return pgtable_l5_enabled() ? PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
208 #else
209 	return PT32E_ROOT_LEVEL;
210 #endif
211 }
212 
213 int svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
214 {
215 	struct vcpu_svm *svm = to_svm(vcpu);
216 	u64 old_efer = vcpu->arch.efer;
217 	vcpu->arch.efer = efer;
218 
219 	if (!npt_enabled) {
220 		/* Shadow paging assumes NX to be available.  */
221 		efer |= EFER_NX;
222 
223 		if (!(efer & EFER_LMA))
224 			efer &= ~EFER_LME;
225 	}
226 
227 	if ((old_efer & EFER_SVME) != (efer & EFER_SVME)) {
228 		if (!(efer & EFER_SVME)) {
229 			/*
230 			 * Architecturally, clearing EFER.SVME while a guest is
231 			 * running yields undefined behavior, i.e. KVM can do
232 			 * literally anything.  Force the vCPU back into L1 as
233 			 * that is the safest option for KVM, but synthesize a
234 			 * triple fault (for L1!) so that KVM at least doesn't
235 			 * run random L2 code in the context of L1.  Do so if
236 			 * and only if the vCPU is actively running, e.g. to
237 			 * avoid positives if userspace is stuffing state.
238 			 */
239 			if (is_guest_mode(vcpu) && vcpu->wants_to_run)
240 				kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
241 
242 			svm_leave_nested(vcpu);
243 			/* #GP intercept is still needed for vmware backdoor */
244 			if (!enable_vmware_backdoor)
245 				clr_exception_intercept(svm, GP_VECTOR);
246 
247 			/*
248 			 * Free the nested guest state, unless we are in SMM.
249 			 * In this case we will return to the nested guest
250 			 * as soon as we leave SMM.
251 			 */
252 			if (!is_smm(vcpu))
253 				svm_free_nested(svm);
254 
255 		} else {
256 			int ret = svm_allocate_nested(svm);
257 
258 			if (ret) {
259 				vcpu->arch.efer = old_efer;
260 				return ret;
261 			}
262 
263 			/*
264 			 * Never intercept #GP for SEV guests, KVM can't
265 			 * decrypt guest memory to workaround the erratum.
266 			 */
267 			if (svm_gp_erratum_intercept && !is_sev_guest(vcpu))
268 				set_exception_intercept(svm, GP_VECTOR);
269 		}
270 
271 		svm_pmu_handle_nested_transition(svm);
272 		kvm_make_request(KVM_REQ_RECALC_INTERCEPTS, vcpu);
273 	}
274 
275 	svm->vmcb->save.efer = efer | EFER_SVME;
276 	vmcb_mark_dirty(svm->vmcb, VMCB_CR);
277 	return 0;
278 }
279 
280 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
281 {
282 	struct vcpu_svm *svm = to_svm(vcpu);
283 	u32 ret = 0;
284 
285 	if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
286 		ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
287 	return ret;
288 }
289 
290 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
291 {
292 	struct vcpu_svm *svm = to_svm(vcpu);
293 
294 	if (mask == 0)
295 		svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
296 	else
297 		svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
298 
299 }
300 
301 static int __svm_skip_emulated_instruction(struct kvm_vcpu *vcpu,
302 					   int emul_type,
303 					   bool commit_side_effects)
304 {
305 	struct vcpu_svm *svm = to_svm(vcpu);
306 	unsigned long old_rflags;
307 
308 	/*
309 	 * SEV-ES does not expose the next RIP. The RIP update is controlled by
310 	 * the type of exit and the #VC handler in the guest.
311 	 */
312 	if (is_sev_es_guest(vcpu))
313 		goto done;
314 
315 	if (nrips && svm->vmcb->control.next_rip != 0) {
316 		WARN_ON_ONCE(!cpu_feature_enabled(X86_FEATURE_NRIPS));
317 		svm->next_rip = svm->vmcb->control.next_rip;
318 	}
319 
320 	if (!svm->next_rip) {
321 		if (unlikely(!commit_side_effects))
322 			old_rflags = svm->vmcb->save.rflags;
323 
324 		if (!kvm_emulate_instruction(vcpu, emul_type))
325 			return 0;
326 
327 		if (unlikely(!commit_side_effects))
328 			svm->vmcb->save.rflags = old_rflags;
329 	} else {
330 		kvm_rip_write(vcpu, svm->next_rip);
331 	}
332 
333 done:
334 	if (likely(commit_side_effects))
335 		svm_set_interrupt_shadow(vcpu, 0);
336 
337 	return 1;
338 }
339 
340 int svm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
341 {
342 	return __svm_skip_emulated_instruction(vcpu, EMULTYPE_SKIP, true);
343 }
344 
345 static int svm_update_soft_interrupt_rip(struct kvm_vcpu *vcpu, u8 vector)
346 {
347 	const int emul_type = EMULTYPE_SKIP | EMULTYPE_SKIP_SOFT_INT |
348 			      EMULTYPE_SET_SOFT_INT_VECTOR(vector);
349 	unsigned long rip, old_rip = kvm_rip_read(vcpu);
350 	struct vcpu_svm *svm = to_svm(vcpu);
351 
352 	/*
353 	 * Due to architectural shortcomings, the CPU doesn't always provide
354 	 * NextRIP, e.g. if KVM intercepted an exception that occurred while
355 	 * the CPU was vectoring an INTO/INT3 in the guest.  Temporarily skip
356 	 * the instruction even if NextRIP is supported to acquire the next
357 	 * RIP so that it can be shoved into the NextRIP field, otherwise
358 	 * hardware will fail to advance guest RIP during event injection.
359 	 * Drop the exception/interrupt if emulation fails and effectively
360 	 * retry the instruction, it's the least awful option.  If NRIPS is
361 	 * in use, the skip must not commit any side effects such as clearing
362 	 * the interrupt shadow or RFLAGS.RF.
363 	 */
364 	if (!__svm_skip_emulated_instruction(vcpu, emul_type, !nrips))
365 		return -EIO;
366 
367 	rip = kvm_rip_read(vcpu);
368 
369 	/*
370 	 * Save the injection information, even when using next_rip, as the
371 	 * VMCB's next_rip will be lost (cleared on VM-Exit) if the injection
372 	 * doesn't complete due to a VM-Exit occurring while the CPU is
373 	 * vectoring the event.   Decoding the instruction isn't guaranteed to
374 	 * work as there may be no backing instruction, e.g. if the event is
375 	 * being injected by L1 for L2, or if the guest is patching INT3 into
376 	 * a different instruction.
377 	 */
378 	svm->soft_int_injected = true;
379 	svm->soft_int_csbase = svm->vmcb->save.cs.base;
380 	svm->soft_int_old_rip = old_rip;
381 	svm->soft_int_next_rip = rip;
382 
383 	if (nrips)
384 		kvm_rip_write(vcpu, old_rip);
385 
386 	if (cpu_feature_enabled(X86_FEATURE_NRIPS))
387 		svm->vmcb->control.next_rip = rip;
388 
389 	return 0;
390 }
391 
392 static void svm_inject_exception(struct kvm_vcpu *vcpu)
393 {
394 	struct kvm_queued_exception *ex = &vcpu->arch.exception;
395 	struct vcpu_svm *svm = to_svm(vcpu);
396 
397 	kvm_deliver_exception_payload(vcpu, ex);
398 
399 	if (kvm_exception_is_soft(ex->vector) &&
400 	    svm_update_soft_interrupt_rip(vcpu, ex->vector))
401 		return;
402 
403 	svm->vmcb->control.event_inj = ex->vector
404 		| SVM_EVTINJ_VALID
405 		| (ex->has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
406 		| SVM_EVTINJ_TYPE_EXEPT;
407 	svm->vmcb->control.event_inj_err = ex->error_code;
408 }
409 
410 static void svm_init_erratum_383(void)
411 {
412 	u64 val;
413 
414 	if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
415 		return;
416 
417 	/* Use _safe variants to not break nested virtualization */
418 	if (native_read_msr_safe(MSR_AMD64_DC_CFG, &val))
419 		return;
420 
421 	val |= (1ULL << 47);
422 
423 	native_write_msr_safe(MSR_AMD64_DC_CFG, val);
424 
425 	erratum_383_found = true;
426 }
427 
428 static void svm_init_osvw(struct kvm_vcpu *vcpu)
429 {
430 	/*
431 	 * Guests should see errata 400 and 415 as fixed (assuming that
432 	 * HLT and IO instructions are intercepted).
433 	 */
434 	vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
435 	vcpu->arch.osvw.status = osvw_status & ~(6ULL);
436 
437 	/*
438 	 * By increasing VCPU's osvw.length to 3 we are telling the guest that
439 	 * all osvw.status bits inside that length, including bit 0 (which is
440 	 * reserved for erratum 298), are valid. However, if host processor's
441 	 * osvw_len is 0 then osvw_status[0] carries no information. We need to
442 	 * be conservative here and therefore we tell the guest that erratum 298
443 	 * is present (because we really don't know).
444 	 */
445 	if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
446 		vcpu->arch.osvw.status |= 1;
447 }
448 
449 static void svm_init_os_visible_workarounds(void)
450 {
451 	u64 len, status;
452 
453 	/*
454 	 * Get OS-Visible Workarounds (OSVW) bits.
455 	 *
456 	 * Note that it is possible to have a system with mixed processor
457 	 * revisions and therefore different OSVW bits. If bits are not the same
458 	 * on different processors then choose the worst case (i.e. if erratum
459 	 * is present on one processor and not on another then assume that the
460 	 * erratum is present everywhere).
461 	 *
462 	 * Note #2!  The OSVW MSRs are used to communciate that an erratum is
463 	 * NOT present!  Software must assume erratum as present if its bit is
464 	 * set in OSVW_STATUS *or* the bit number exceeds OSVW_ID_LENGTH.  If
465 	 * either RDMSR fails, simply zero out the length to treat all errata
466 	 * as being present.  Similarly, use the *minimum* length across all
467 	 * CPUs, not the maximum length.
468 	 *
469 	 * If the length is zero, then is KVM already treating all errata as
470 	 * being present and there's nothing left to do.
471 	 */
472 	if (!osvw_len)
473 		return;
474 
475 	if (!this_cpu_has(X86_FEATURE_OSVW) ||
476 	    native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &len) ||
477 	    native_read_msr_safe(MSR_AMD64_OSVW_STATUS, &status))
478 		len = status = 0;
479 
480 	if (status == READ_ONCE(osvw_status) && len >= READ_ONCE(osvw_len))
481 		return;
482 
483 	guard(spinlock)(&osvw_lock);
484 
485 	if (len < osvw_len)
486 		osvw_len = len;
487 	osvw_status |= status;
488 	osvw_status &= (1ULL << osvw_len) - 1;
489 }
490 
491 static bool __kvm_is_svm_supported(void)
492 {
493 	int cpu = smp_processor_id();
494 	struct cpuinfo_x86 *c = &cpu_data(cpu);
495 
496 	if (c->x86_vendor != X86_VENDOR_AMD &&
497 	    c->x86_vendor != X86_VENDOR_HYGON) {
498 		pr_err("CPU %d isn't AMD or Hygon\n", cpu);
499 		return false;
500 	}
501 
502 	if (!cpu_has(c, X86_FEATURE_SVM)) {
503 		pr_err("SVM not supported by CPU %d\n", cpu);
504 		return false;
505 	}
506 
507 	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) {
508 		pr_info("KVM is unsupported when running as an SEV guest\n");
509 		return false;
510 	}
511 
512 	return true;
513 }
514 
515 static bool kvm_is_svm_supported(void)
516 {
517 	bool supported;
518 
519 	migrate_disable();
520 	supported = __kvm_is_svm_supported();
521 	migrate_enable();
522 
523 	return supported;
524 }
525 
526 static int svm_check_processor_compat(void)
527 {
528 	if (!__kvm_is_svm_supported())
529 		return -EIO;
530 
531 	return 0;
532 }
533 
534 static void __svm_write_tsc_multiplier(u64 multiplier)
535 {
536 	/*
537 	 * Fallback to the default ratio if KVM is buggy and tries to program
538 	 * an unsupported scaling ratio, e.g. so that the guest has a chance of
539 	 * surviving, so that the cache isn't stale/corrupted, and so that KVM
540 	 * doesn't leak state across VMs.
541 	 */
542 	if (WARN_ON_ONCE(multiplier & SVM_TSC_RATIO_RSVD))
543 		multiplier = SVM_TSC_RATIO_DEFAULT;
544 
545 	if (multiplier == __this_cpu_read(current_tsc_ratio))
546 		return;
547 
548 	wrmsrq(MSR_AMD64_TSC_RATIO, multiplier);
549 	__this_cpu_write(current_tsc_ratio, multiplier);
550 }
551 
552 static __always_inline struct sev_es_save_area *sev_es_host_save_area(struct svm_cpu_data *sd)
553 {
554 	return &sd->save_area->host_sev_es_save;
555 }
556 
557 static void svm_emergency_disable_virtualization_cpu(void)
558 {
559 	wrmsrq(MSR_VM_HSAVE_PA, 0);
560 }
561 
562 static void svm_disable_virtualization_cpu(void)
563 {
564 	/* Make sure we clean up behind us */
565 	if (tsc_scaling)
566 		__svm_write_tsc_multiplier(SVM_TSC_RATIO_DEFAULT);
567 
568 	x86_virt_put_ref(X86_FEATURE_SVM);
569 	wrmsrq(MSR_VM_HSAVE_PA, 0);
570 
571 	amd_pmu_disable_virt();
572 }
573 
574 static int svm_enable_virtualization_cpu(void)
575 {
576 
577 	struct svm_cpu_data *sd;
578 	int me = raw_smp_processor_id();
579 	int r;
580 
581 	r = x86_virt_get_ref(X86_FEATURE_SVM);
582 	if (r)
583 		return r;
584 
585 	sd = per_cpu_ptr(&svm_data, me);
586 	/*
587 	 * Bump the current asid_generation value to ensure any vCPU that
588 	 * previously ran on this CPU sees a stale generation and is forced
589 	 * to acquire a new ASID, preventing a latent ASID collision.
590 	 */
591 	sd->asid_generation++;
592 	sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
593 	sd->next_asid = sd->max_asid + 1;
594 	sd->min_asid = max_sev_asid + 1;
595 
596 	wrmsrq(MSR_VM_HSAVE_PA, sd->save_area_pa);
597 
598 	if (cpu_feature_enabled(X86_FEATURE_TSCRATEMSR)) {
599 		/*
600 		 * Set the default value, even if we don't use TSC scaling
601 		 * to avoid having stale value in the msr
602 		 */
603 		__svm_write_tsc_multiplier(SVM_TSC_RATIO_DEFAULT);
604 	}
605 
606 	svm_init_os_visible_workarounds();
607 
608 	svm_init_erratum_383();
609 
610 	amd_pmu_enable_virt();
611 
612 	return 0;
613 }
614 
615 static void svm_cpu_uninit(int cpu)
616 {
617 	struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
618 
619 	if (!sd->save_area)
620 		return;
621 
622 	kfree(sd->sev_vmcbs);
623 	__free_page(__sme_pa_to_page(sd->save_area_pa));
624 	sd->save_area_pa = 0;
625 	sd->save_area = NULL;
626 }
627 
628 static int svm_cpu_init(int cpu)
629 {
630 	struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
631 	struct page *save_area_page;
632 	int ret = -ENOMEM;
633 
634 	memset(sd, 0, sizeof(struct svm_cpu_data));
635 	save_area_page = snp_safe_alloc_page_node(cpu_to_node(cpu), GFP_KERNEL);
636 	if (!save_area_page)
637 		return ret;
638 
639 	ret = sev_cpu_init(sd);
640 	if (ret)
641 		goto free_save_area;
642 
643 	sd->save_area = page_address(save_area_page);
644 	sd->save_area_pa = __sme_page_pa(save_area_page);
645 	return 0;
646 
647 free_save_area:
648 	__free_page(save_area_page);
649 	return ret;
650 
651 }
652 
653 static void set_dr_intercepts(struct vcpu_svm *svm)
654 {
655 	struct vmcb *vmcb = svm->vmcb01.ptr;
656 
657 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR0_READ);
658 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR1_READ);
659 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR2_READ);
660 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR3_READ);
661 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR4_READ);
662 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR5_READ);
663 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR6_READ);
664 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR0_WRITE);
665 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR1_WRITE);
666 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR2_WRITE);
667 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR3_WRITE);
668 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR4_WRITE);
669 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR5_WRITE);
670 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR6_WRITE);
671 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_READ);
672 	vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_WRITE);
673 
674 	svm_mark_intercepts_dirty(svm);
675 }
676 
677 static void clr_dr_intercepts(struct vcpu_svm *svm)
678 {
679 	struct vmcb *vmcb = svm->vmcb01.ptr;
680 
681 	vmcb->control.intercepts[INTERCEPT_DR] = 0;
682 
683 	svm_mark_intercepts_dirty(svm);
684 }
685 
686 static bool msr_write_intercepted(struct vcpu_svm *svm, u32 msr)
687 {
688 	void *msrpm = __va(__sme_clr(svm->vmcb->control.msrpm_base_pa));
689 
690 	return svm_test_msr_bitmap_write(msrpm, msr);
691 }
692 
693 void svm_set_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type, bool set)
694 {
695 	struct vcpu_svm *svm = to_svm(vcpu);
696 	void *msrpm = svm->msrpm;
697 
698 	/* Don't disable interception for MSRs userspace wants to handle. */
699 	if (type & MSR_TYPE_R) {
700 		if (!set && kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ))
701 			svm_clear_msr_bitmap_read(msrpm, msr);
702 		else
703 			svm_set_msr_bitmap_read(msrpm, msr);
704 	}
705 
706 	if (type & MSR_TYPE_W) {
707 		if (!set && kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE))
708 			svm_clear_msr_bitmap_write(msrpm, msr);
709 		else
710 			svm_set_msr_bitmap_write(msrpm, msr);
711 	}
712 
713 	svm_hv_vmcb_dirty_nested_enlightenments(vcpu);
714 	svm->nested.force_msr_bitmap_recalc = true;
715 }
716 
717 void *svm_alloc_permissions_map(unsigned long size, gfp_t gfp_mask)
718 {
719 	unsigned int order = get_order(size);
720 	struct page *pages = alloc_pages(gfp_mask, order);
721 	void *pm;
722 
723 	if (!pages)
724 		return NULL;
725 
726 	/*
727 	 * Set all bits in the permissions map so that all MSR and I/O accesses
728 	 * are intercepted by default.
729 	 */
730 	pm = page_address(pages);
731 	memset(pm, 0xff, PAGE_SIZE * (1 << order));
732 
733 	return pm;
734 }
735 
736 static void svm_recalc_lbr_msr_intercepts(struct kvm_vcpu *vcpu)
737 {
738 	struct vcpu_svm *svm = to_svm(vcpu);
739 	bool intercept = !(svm->vmcb->control.misc_ctl2 & SVM_MISC2_ENABLE_V_LBR);
740 
741 	if (intercept == svm->lbr_msrs_intercepted)
742 		return;
743 
744 	svm_set_intercept_for_msr(vcpu, MSR_IA32_LASTBRANCHFROMIP, MSR_TYPE_RW, intercept);
745 	svm_set_intercept_for_msr(vcpu, MSR_IA32_LASTBRANCHTOIP, MSR_TYPE_RW, intercept);
746 	svm_set_intercept_for_msr(vcpu, MSR_IA32_LASTINTFROMIP, MSR_TYPE_RW, intercept);
747 	svm_set_intercept_for_msr(vcpu, MSR_IA32_LASTINTTOIP, MSR_TYPE_RW, intercept);
748 
749 	if (is_sev_es_guest(vcpu))
750 		svm_set_intercept_for_msr(vcpu, MSR_IA32_DEBUGCTLMSR, MSR_TYPE_RW, intercept);
751 
752 	svm->lbr_msrs_intercepted = intercept;
753 }
754 
755 void svm_vcpu_free_msrpm(void *msrpm)
756 {
757 	__free_pages(virt_to_page(msrpm), get_order(MSRPM_SIZE));
758 }
759 
760 static void svm_recalc_pmu_msr_intercepts(struct kvm_vcpu *vcpu)
761 {
762 	bool intercept = !kvm_vcpu_has_mediated_pmu(vcpu);
763 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
764 	int i;
765 
766 	if (!enable_mediated_pmu)
767 		return;
768 
769 	/* Legacy counters are always available for AMD CPUs with a PMU. */
770 	for (i = 0; i < min(pmu->nr_arch_gp_counters, AMD64_NUM_COUNTERS); i++)
771 		svm_set_intercept_for_msr(vcpu, MSR_K7_PERFCTR0 + i,
772 					  MSR_TYPE_RW, intercept);
773 
774 	intercept |= !guest_cpu_cap_has(vcpu, X86_FEATURE_PERFCTR_CORE);
775 	for (i = 0; i < pmu->nr_arch_gp_counters; i++)
776 		svm_set_intercept_for_msr(vcpu, MSR_F15H_PERF_CTR + 2 * i,
777 					  MSR_TYPE_RW, intercept);
778 
779 	for ( ; i < kvm_pmu_cap.num_counters_gp; i++)
780 		svm_enable_intercept_for_msr(vcpu, MSR_F15H_PERF_CTR + 2 * i,
781 					     MSR_TYPE_RW);
782 
783 	intercept = kvm_need_perf_global_ctrl_intercept(vcpu);
784 	svm_set_intercept_for_msr(vcpu, MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
785 				  MSR_TYPE_RW, intercept);
786 	svm_set_intercept_for_msr(vcpu, MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
787 				  MSR_TYPE_RW, intercept);
788 	svm_set_intercept_for_msr(vcpu, MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
789 				  MSR_TYPE_RW, intercept);
790 	svm_set_intercept_for_msr(vcpu, MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET,
791 				  MSR_TYPE_RW, intercept);
792 }
793 
794 static void svm_recalc_msr_intercepts(struct kvm_vcpu *vcpu)
795 {
796 	struct vcpu_svm *svm = to_svm(vcpu);
797 
798 	svm_disable_intercept_for_msr(vcpu, MSR_STAR, MSR_TYPE_RW);
799 	svm_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
800 
801 #ifdef CONFIG_X86_64
802 	svm_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
803 	svm_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
804 	svm_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
805 	svm_disable_intercept_for_msr(vcpu, MSR_LSTAR, MSR_TYPE_RW);
806 	svm_disable_intercept_for_msr(vcpu, MSR_CSTAR, MSR_TYPE_RW);
807 	svm_disable_intercept_for_msr(vcpu, MSR_SYSCALL_MASK, MSR_TYPE_RW);
808 #endif
809 
810 	if (lbrv)
811 		svm_recalc_lbr_msr_intercepts(vcpu);
812 
813 	if (cpu_feature_enabled(X86_FEATURE_IBPB))
814 		svm_set_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W,
815 					  !guest_has_pred_cmd_msr(vcpu));
816 
817 	if (cpu_feature_enabled(X86_FEATURE_FLUSH_L1D))
818 		svm_set_intercept_for_msr(vcpu, MSR_IA32_FLUSH_CMD, MSR_TYPE_W,
819 					  !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D));
820 
821 	/*
822 	 * Disable interception of SPEC_CTRL if KVM doesn't need to manually
823 	 * context switch the MSR (SPEC_CTRL is virtualized by the CPU), or if
824 	 * the guest has a non-zero SPEC_CTRL value, i.e. is likely actively
825 	 * using SPEC_CTRL.
826 	 */
827 	if (cpu_feature_enabled(X86_FEATURE_V_SPEC_CTRL))
828 		svm_set_intercept_for_msr(vcpu, MSR_IA32_SPEC_CTRL, MSR_TYPE_RW,
829 					  !guest_has_spec_ctrl_msr(vcpu));
830 	else
831 		svm_set_intercept_for_msr(vcpu, MSR_IA32_SPEC_CTRL, MSR_TYPE_RW,
832 					  !svm->spec_ctrl);
833 
834 	/*
835 	 * Intercept SYSENTER_EIP and SYSENTER_ESP when emulating an Intel CPU,
836 	 * as AMD hardware only store 32 bits, whereas Intel CPUs track 64 bits.
837 	 */
838 	svm_set_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW,
839 				  guest_cpuid_is_intel_compatible(vcpu));
840 	svm_set_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW,
841 				  guest_cpuid_is_intel_compatible(vcpu));
842 
843 	if (kvm_aperfmperf_in_guest(vcpu->kvm)) {
844 		svm_disable_intercept_for_msr(vcpu, MSR_IA32_APERF, MSR_TYPE_R);
845 		svm_disable_intercept_for_msr(vcpu, MSR_IA32_MPERF, MSR_TYPE_R);
846 	}
847 
848 	if (kvm_cpu_cap_has(X86_FEATURE_SHSTK)) {
849 		bool shstk_enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK);
850 
851 		svm_set_intercept_for_msr(vcpu, MSR_IA32_U_CET, MSR_TYPE_RW, !shstk_enabled);
852 		svm_set_intercept_for_msr(vcpu, MSR_IA32_S_CET, MSR_TYPE_RW, !shstk_enabled);
853 		svm_set_intercept_for_msr(vcpu, MSR_IA32_PL0_SSP, MSR_TYPE_RW, !shstk_enabled);
854 		svm_set_intercept_for_msr(vcpu, MSR_IA32_PL1_SSP, MSR_TYPE_RW, !shstk_enabled);
855 		svm_set_intercept_for_msr(vcpu, MSR_IA32_PL2_SSP, MSR_TYPE_RW, !shstk_enabled);
856 		svm_set_intercept_for_msr(vcpu, MSR_IA32_PL3_SSP, MSR_TYPE_RW, !shstk_enabled);
857 	}
858 
859 	if (is_sev_es_guest(vcpu))
860 		sev_es_recalc_msr_intercepts(vcpu);
861 
862 	svm_recalc_pmu_msr_intercepts(vcpu);
863 
864 	/*
865 	 * x2APIC intercepts are modified on-demand and cannot be filtered by
866 	 * userspace.
867 	 */
868 }
869 
870 static void __svm_enable_lbrv(struct kvm_vcpu *vcpu)
871 {
872 	to_svm(vcpu)->vmcb->control.misc_ctl2 |= SVM_MISC2_ENABLE_V_LBR;
873 }
874 
875 void svm_enable_lbrv(struct kvm_vcpu *vcpu)
876 {
877 	__svm_enable_lbrv(vcpu);
878 	svm_recalc_lbr_msr_intercepts(vcpu);
879 }
880 
881 static void __svm_disable_lbrv(struct kvm_vcpu *vcpu)
882 {
883 	KVM_BUG_ON(is_sev_es_guest(vcpu), vcpu->kvm);
884 	to_svm(vcpu)->vmcb->control.misc_ctl2 &= ~SVM_MISC2_ENABLE_V_LBR;
885 }
886 
887 static bool svm_need_lbr_virtualization(struct kvm_vcpu *vcpu)
888 {
889 	struct vcpu_svm *svm = to_svm(vcpu);
890 
891 	if (svm->vmcb->save.dbgctl & (DEBUGCTLMSR_LBR | DEBUGCTLMSR_BUS_LOCK_DETECT))
892 		return true;
893 
894 	return is_guest_mode(vcpu) &&
895 	       (svm->nested.ctl.misc_ctl2 & SVM_MISC2_ENABLE_V_LBR);
896 }
897 
898 void svm_update_lbrv(struct kvm_vcpu *vcpu)
899 {
900 	struct vcpu_svm *svm = to_svm(vcpu);
901 	bool current_enable_lbrv = svm->vmcb->control.misc_ctl2 & SVM_MISC2_ENABLE_V_LBR;
902 	bool enable_lbrv = svm_need_lbr_virtualization(vcpu);
903 
904 	if (enable_lbrv && !current_enable_lbrv)
905 		__svm_enable_lbrv(vcpu);
906 	else if (!enable_lbrv && current_enable_lbrv)
907 		__svm_disable_lbrv(vcpu);
908 
909 	/*
910 	 * During nested transitions, it is possible that the current VMCB has
911 	 * LBR_CTL set, but the previous LBR_CTL had it cleared (or vice versa).
912 	 * In this case, even though LBR_CTL does not need an update, intercepts
913 	 * do, so always recalculate the intercepts here.
914 	 */
915 	svm_recalc_lbr_msr_intercepts(vcpu);
916 }
917 
918 void disable_nmi_singlestep(struct vcpu_svm *svm)
919 {
920 	svm->nmi_singlestep = false;
921 
922 	if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
923 		/* Clear our flags if they were not set by the guest */
924 		if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
925 			svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
926 		if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
927 			svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
928 	}
929 }
930 
931 static void grow_ple_window(struct kvm_vcpu *vcpu)
932 {
933 	struct vcpu_svm *svm = to_svm(vcpu);
934 	struct vmcb_control_area *control = &svm->vmcb->control;
935 	int old = control->pause_filter_count;
936 
937 	/* Adjusting pause_filter_count makes no sense if PLE is disabled.  */
938 	WARN_ON_ONCE(kvm_pause_in_guest(vcpu->kvm));
939 
940 	/*
941 	 * While running L2, KVM should intercept PAUSE if and only if L1 wants
942 	 * to intercept PAUSE, and L1's intercept should take priority, i.e.
943 	 * KVM should never handle a PAUSE intercept from L2.
944 	 */
945 	if (WARN_ON_ONCE(is_guest_mode(vcpu)))
946 		return;
947 
948 	control->pause_filter_count = __grow_ple_window(old,
949 							pause_filter_count,
950 							pause_filter_count_grow,
951 							pause_filter_count_max);
952 
953 	if (control->pause_filter_count != old) {
954 		vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
955 		trace_kvm_ple_window_update(vcpu->vcpu_id,
956 					    control->pause_filter_count, old);
957 	}
958 }
959 
960 static void shrink_ple_window(struct kvm_vcpu *vcpu)
961 {
962 	struct vcpu_svm *svm = to_svm(vcpu);
963 	struct vmcb_control_area *control = &svm->vmcb->control;
964 	int old = control->pause_filter_count;
965 
966 	/* Adjusting pause_filter_count makes no sense if PLE is disabled.  */
967 	WARN_ON_ONCE(kvm_pause_in_guest(vcpu->kvm));
968 
969 	if (is_guest_mode(vcpu))
970 		return;
971 
972 	control->pause_filter_count =
973 				__shrink_ple_window(old,
974 						    pause_filter_count,
975 						    pause_filter_count_shrink,
976 						    pause_filter_count);
977 	if (control->pause_filter_count != old) {
978 		vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
979 		trace_kvm_ple_window_update(vcpu->vcpu_id,
980 					    control->pause_filter_count, old);
981 	}
982 }
983 
984 static void svm_hardware_unsetup(void)
985 {
986 	int cpu;
987 
988 	avic_hardware_unsetup();
989 
990 	sev_hardware_unsetup();
991 
992 	for_each_possible_cpu(cpu)
993 		svm_cpu_uninit(cpu);
994 
995 	__free_pages(__sme_pa_to_page(iopm_base), get_order(IOPM_SIZE));
996 	iopm_base = 0;
997 }
998 
999 static void init_seg(struct vmcb_seg *seg)
1000 {
1001 	seg->selector = 0;
1002 	seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1003 		      SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1004 	seg->limit = 0xffff;
1005 	seg->base = 0;
1006 }
1007 
1008 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1009 {
1010 	seg->selector = 0;
1011 	seg->attrib = SVM_SELECTOR_P_MASK | type;
1012 	seg->limit = 0xffff;
1013 	seg->base = 0;
1014 }
1015 
1016 static u64 svm_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1017 {
1018 	struct vcpu_svm *svm = to_svm(vcpu);
1019 
1020 	return svm->nested.ctl.tsc_offset;
1021 }
1022 
1023 static u64 svm_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1024 {
1025 	struct vcpu_svm *svm = to_svm(vcpu);
1026 
1027 	return svm->tsc_ratio_msr;
1028 }
1029 
1030 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu)
1031 {
1032 	struct vcpu_svm *svm = to_svm(vcpu);
1033 
1034 	svm->vmcb01.ptr->control.tsc_offset = vcpu->arch.l1_tsc_offset;
1035 	svm->vmcb->control.tsc_offset = vcpu->arch.tsc_offset;
1036 	vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1037 }
1038 
1039 void svm_write_tsc_multiplier(struct kvm_vcpu *vcpu)
1040 {
1041 	preempt_disable();
1042 	if (to_svm(vcpu)->guest_state_loaded)
1043 		__svm_write_tsc_multiplier(vcpu->arch.tsc_scaling_ratio);
1044 	preempt_enable();
1045 }
1046 
1047 static bool svm_has_pending_gif_event(struct vcpu_svm *svm)
1048 {
1049 	return svm->vcpu.arch.smi_pending ||
1050 	       svm->vcpu.arch.nmi_pending ||
1051 	       kvm_cpu_has_injectable_intr(&svm->vcpu) ||
1052 	       kvm_apic_has_pending_init_or_sipi(&svm->vcpu);
1053 }
1054 
1055 /* Evaluate instruction intercepts that depend on guest CPUID features. */
1056 static void svm_recalc_instruction_intercepts(struct kvm_vcpu *vcpu)
1057 {
1058 	struct vcpu_svm *svm = to_svm(vcpu);
1059 
1060 	/*
1061 	 * Intercept INVPCID if shadow paging is enabled to sync/free shadow
1062 	 * roots, or if INVPCID is disabled in the guest to inject #UD.
1063 	 */
1064 	if (kvm_cpu_cap_has(X86_FEATURE_INVPCID)) {
1065 		if (!npt_enabled ||
1066 		    !guest_cpu_cap_has(&svm->vcpu, X86_FEATURE_INVPCID))
1067 			svm_set_intercept(svm, INTERCEPT_INVPCID);
1068 		else
1069 			svm_clr_intercept(svm, INTERCEPT_INVPCID);
1070 	}
1071 
1072 	if (kvm_cpu_cap_has(X86_FEATURE_RDTSCP)) {
1073 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP))
1074 			svm_clr_intercept(svm, INTERCEPT_RDTSCP);
1075 		else
1076 			svm_set_intercept(svm, INTERCEPT_RDTSCP);
1077 	}
1078 
1079 	/*
1080 	 * Intercept instructions that #UD if EFER.SVME=0, as SVME must be set
1081 	 * even when running the guest, i.e. hardware will only ever see
1082 	 * EFER.SVME=1.
1083 	 *
1084 	 * No need to toggle any of the vgif/vls/etc. enable bits here, as they
1085 	 * are set when the VMCB is initialized and never cleared (if the
1086 	 * relevant intercepts are set, the enablements are meaningless anyway).
1087 	 *
1088 	 * FIXME: When #GP is not intercepted, a #GP on these instructions (e.g.
1089 	 * due to CPL > 0) could be injected by hardware before the instruction
1090 	 * is intercepted, leading to #GP taking precedence over #UD from the
1091 	 * guest's perspective.
1092 	 */
1093 	if (!(vcpu->arch.efer & EFER_SVME)) {
1094 		svm_set_intercept(svm, INTERCEPT_VMLOAD);
1095 		svm_set_intercept(svm, INTERCEPT_VMSAVE);
1096 		svm_set_intercept(svm, INTERCEPT_CLGI);
1097 		svm_set_intercept(svm, INTERCEPT_STGI);
1098 	} else {
1099 		/*
1100 		 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1101 		 * in VMCB and clear intercepts to avoid #VMEXIT.
1102 		 */
1103 		if (guest_cpuid_is_intel_compatible(vcpu)) {
1104 			svm_set_intercept(svm, INTERCEPT_VMLOAD);
1105 			svm_set_intercept(svm, INTERCEPT_VMSAVE);
1106 		} else if (vls) {
1107 			svm_clr_intercept(svm, INTERCEPT_VMLOAD);
1108 			svm_clr_intercept(svm, INTERCEPT_VMSAVE);
1109 		}
1110 
1111 		/*
1112 		 * Process pending events when clearing STGI/CLGI intercepts if
1113 		 * there's at least one pending event that is masked by GIF, so
1114 		 * that KVM re-evaluates if the intercept needs to be set again
1115 		 * to track when GIF is re-enabled (e.g. for NMI injection).
1116 		 */
1117 		if (vgif) {
1118 			svm_clr_intercept(svm, INTERCEPT_CLGI);
1119 			svm_clr_intercept(svm, INTERCEPT_STGI);
1120 
1121 			if (svm_has_pending_gif_event(svm))
1122 				kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
1123 		}
1124 	}
1125 
1126 	if (kvm_need_rdpmc_intercept(vcpu))
1127 		svm_set_intercept(svm, INTERCEPT_RDPMC);
1128 	else
1129 		svm_clr_intercept(svm, INTERCEPT_RDPMC);
1130 }
1131 
1132 static void svm_recalc_intercepts(struct kvm_vcpu *vcpu)
1133 {
1134 	svm_recalc_instruction_intercepts(vcpu);
1135 	svm_recalc_msr_intercepts(vcpu);
1136 }
1137 
1138 static void init_vmcb(struct kvm_vcpu *vcpu, bool init_event)
1139 {
1140 	struct vcpu_svm *svm = to_svm(vcpu);
1141 	struct vmcb *vmcb = svm->vmcb01.ptr;
1142 	struct vmcb_control_area *control = &vmcb->control;
1143 	struct vmcb_save_area *save = &vmcb->save;
1144 
1145 	svm_set_intercept(svm, INTERCEPT_CR0_READ);
1146 	svm_set_intercept(svm, INTERCEPT_CR3_READ);
1147 	svm_set_intercept(svm, INTERCEPT_CR4_READ);
1148 	svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1149 	svm_set_intercept(svm, INTERCEPT_CR3_WRITE);
1150 	svm_set_intercept(svm, INTERCEPT_CR4_WRITE);
1151 	svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
1152 
1153 	set_dr_intercepts(svm);
1154 
1155 	set_exception_intercept(svm, PF_VECTOR);
1156 	set_exception_intercept(svm, UD_VECTOR);
1157 	set_exception_intercept(svm, MC_VECTOR);
1158 	set_exception_intercept(svm, AC_VECTOR);
1159 	set_exception_intercept(svm, DB_VECTOR);
1160 	/*
1161 	 * Guest access to VMware backdoor ports could legitimately
1162 	 * trigger #GP because of TSS I/O permission bitmap.
1163 	 * We intercept those #GP and allow access to them anyway
1164 	 * as VMware does.
1165 	 */
1166 	if (enable_vmware_backdoor)
1167 		set_exception_intercept(svm, GP_VECTOR);
1168 
1169 	svm_set_intercept(svm, INTERCEPT_INTR);
1170 	svm_set_intercept(svm, INTERCEPT_NMI);
1171 
1172 	if (intercept_smi)
1173 		svm_set_intercept(svm, INTERCEPT_SMI);
1174 
1175 	svm_set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1176 	svm_set_intercept(svm, INTERCEPT_RDPMC);
1177 	svm_set_intercept(svm, INTERCEPT_CPUID);
1178 	svm_set_intercept(svm, INTERCEPT_INVD);
1179 	svm_set_intercept(svm, INTERCEPT_INVLPG);
1180 	svm_set_intercept(svm, INTERCEPT_INVLPGA);
1181 	svm_set_intercept(svm, INTERCEPT_IOIO_PROT);
1182 	svm_set_intercept(svm, INTERCEPT_MSR_PROT);
1183 	svm_set_intercept(svm, INTERCEPT_TASK_SWITCH);
1184 	svm_set_intercept(svm, INTERCEPT_SHUTDOWN);
1185 	svm_set_intercept(svm, INTERCEPT_VMRUN);
1186 	svm_set_intercept(svm, INTERCEPT_VMMCALL);
1187 	svm_set_intercept(svm, INTERCEPT_VMLOAD);
1188 	svm_set_intercept(svm, INTERCEPT_VMSAVE);
1189 	svm_set_intercept(svm, INTERCEPT_STGI);
1190 	svm_set_intercept(svm, INTERCEPT_CLGI);
1191 	svm_set_intercept(svm, INTERCEPT_SKINIT);
1192 	svm_set_intercept(svm, INTERCEPT_WBINVD);
1193 	svm_set_intercept(svm, INTERCEPT_XSETBV);
1194 	svm_set_intercept(svm, INTERCEPT_ICEBP);
1195 	svm_set_intercept(svm, INTERCEPT_RDPRU);
1196 	svm_set_intercept(svm, INTERCEPT_RSM);
1197 
1198 	if (!kvm_mwait_in_guest(vcpu->kvm)) {
1199 		svm_set_intercept(svm, INTERCEPT_MONITOR);
1200 		svm_set_intercept(svm, INTERCEPT_MWAIT);
1201 	}
1202 
1203 	if (!kvm_hlt_in_guest(vcpu->kvm)) {
1204 		if (cpu_feature_enabled(X86_FEATURE_IDLE_HLT))
1205 			svm_set_intercept(svm, INTERCEPT_IDLE_HLT);
1206 		else
1207 			svm_set_intercept(svm, INTERCEPT_HLT);
1208 	}
1209 
1210 	control->iopm_base_pa = iopm_base;
1211 	control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1212 	control->int_ctl = V_INTR_MASKING_MASK;
1213 
1214 	init_seg(&save->es);
1215 	init_seg(&save->ss);
1216 	init_seg(&save->ds);
1217 	init_seg(&save->fs);
1218 	init_seg(&save->gs);
1219 
1220 	save->cs.selector = 0xf000;
1221 	save->cs.base = 0xffff0000;
1222 	/* Executable/Readable Code Segment */
1223 	save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1224 		SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1225 	save->cs.limit = 0xffff;
1226 
1227 	save->gdtr.base = 0;
1228 	save->gdtr.limit = 0xffff;
1229 	save->idtr.base = 0;
1230 	save->idtr.limit = 0xffff;
1231 
1232 	init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1233 	init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1234 
1235 	if (npt_enabled) {
1236 		/* Setup VMCB for Nested Paging */
1237 		control->misc_ctl |= SVM_MISC_ENABLE_NP;
1238 		svm_clr_intercept(svm, INTERCEPT_INVLPG);
1239 		clr_exception_intercept(svm, PF_VECTOR);
1240 		svm_clr_intercept(svm, INTERCEPT_CR3_READ);
1241 		svm_clr_intercept(svm, INTERCEPT_CR3_WRITE);
1242 		save->g_pat = vcpu->arch.pat;
1243 		save->cr3 = 0;
1244 	}
1245 
1246 	if (gmet_enabled)
1247 		control->misc_ctl |= SVM_MISC_ENABLE_GMET;
1248 
1249 	svm->current_vmcb->asid_generation = 0;
1250 	svm->asid = 0;
1251 
1252 	svm->nested.vmcb12_gpa = INVALID_GPA;
1253 	svm->nested.last_vmcb12_gpa = INVALID_GPA;
1254 
1255 	if (!kvm_pause_in_guest(vcpu->kvm)) {
1256 		control->pause_filter_count = pause_filter_count;
1257 		if (pause_filter_thresh)
1258 			control->pause_filter_thresh = pause_filter_thresh;
1259 		svm_set_intercept(svm, INTERCEPT_PAUSE);
1260 	} else {
1261 		svm_clr_intercept(svm, INTERCEPT_PAUSE);
1262 	}
1263 
1264 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_ERAPS))
1265 		svm->vmcb->control.erap_ctl |= ERAP_CONTROL_ALLOW_LARGER_RAP;
1266 
1267 	if (enable_apicv && irqchip_in_kernel(vcpu->kvm))
1268 		avic_init_vmcb(svm, vmcb);
1269 
1270 	if (vnmi)
1271 		svm->vmcb->control.int_ctl |= V_NMI_ENABLE_MASK;
1272 
1273 	if (vgif)
1274 		svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1275 
1276 	if (vls)
1277 		svm->vmcb->control.misc_ctl2 |= SVM_MISC2_ENABLE_V_VMLOAD_VMSAVE;
1278 
1279 	if (vcpu->kvm->arch.bus_lock_detection_enabled)
1280 		svm_set_intercept(svm, INTERCEPT_BUSLOCK);
1281 
1282 	if (pml) {
1283 		/*
1284 		 * Populate the page address and index here, PML is enabled
1285 		 * when dirty logging is enabled on the memslot through
1286 		 * svm_update_cpu_dirty_logging()
1287 		 */
1288 		control->pml_addr = (u64)__sme_set(page_to_phys(vcpu->arch.pml_page));
1289 
1290 		/*
1291 		 * The VMCB control area remains valid after an intercepted SHUTDOWN
1292 		 * (AMD APM Rev 3.45+), so only initialize PML index on reset to avoid
1293 		 * discarding already-logged entries that haven't been flushed.
1294 		 */
1295 		if (!init_event)
1296 			control->pml_index = PML_HEAD_INDEX;
1297 	}
1298 
1299 	if (is_sev_guest(vcpu))
1300 		sev_init_vmcb(svm, init_event);
1301 
1302 	svm_hv_init_vmcb(vmcb);
1303 
1304 	kvm_make_request(KVM_REQ_RECALC_INTERCEPTS, vcpu);
1305 
1306 	vmcb_mark_all_dirty(vmcb);
1307 
1308 	enable_gif(svm);
1309 }
1310 
1311 static void __svm_vcpu_reset(struct kvm_vcpu *vcpu)
1312 {
1313 	struct vcpu_svm *svm = to_svm(vcpu);
1314 
1315 	svm_init_osvw(vcpu);
1316 
1317 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS))
1318 		vcpu->arch.microcode_version = 0x01000065;
1319 	svm->tsc_ratio_msr = kvm_caps.default_tsc_scaling_ratio;
1320 
1321 	svm->nmi_masked = false;
1322 	svm->awaiting_iret_completion = false;
1323 }
1324 
1325 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1326 {
1327 	struct vcpu_svm *svm = to_svm(vcpu);
1328 
1329 	svm->spec_ctrl = 0;
1330 	svm->virt_spec_ctrl = 0;
1331 
1332 	init_vmcb(vcpu, init_event);
1333 
1334 	if (!init_event)
1335 		__svm_vcpu_reset(vcpu);
1336 }
1337 
1338 void svm_switch_vmcb(struct vcpu_svm *svm, struct kvm_vmcb_info *target_vmcb)
1339 {
1340 	svm->current_vmcb = target_vmcb;
1341 	svm->vmcb = target_vmcb->ptr;
1342 }
1343 
1344 static int svm_vcpu_create(struct kvm_vcpu *vcpu)
1345 {
1346 	struct vcpu_svm *svm;
1347 	struct page *vmcb01_page;
1348 	int err;
1349 
1350 	BUILD_BUG_ON(offsetof(struct vcpu_svm, vcpu) != 0);
1351 	svm = to_svm(vcpu);
1352 
1353 	err = -ENOMEM;
1354 	vmcb01_page = snp_safe_alloc_page();
1355 	if (!vmcb01_page)
1356 		goto out;
1357 
1358 	if (pml) {
1359 		vcpu->arch.pml_page = snp_safe_alloc_page();
1360 		if (!vcpu->arch.pml_page)
1361 			goto error_free_vmcb_page;
1362 	}
1363 
1364 	err = sev_vcpu_create(vcpu);
1365 	if (err)
1366 		goto error_free_pml_page;
1367 
1368 	err = avic_init_vcpu(svm);
1369 	if (err)
1370 		goto error_free_sev;
1371 
1372 	svm->msrpm = svm_vcpu_alloc_msrpm();
1373 	if (!svm->msrpm) {
1374 		err = -ENOMEM;
1375 		goto error_free_avic;
1376 	}
1377 
1378 	svm->x2avic_msrs_intercepted = true;
1379 	svm->lbr_msrs_intercepted = true;
1380 
1381 	svm->vmcb01.ptr = page_address(vmcb01_page);
1382 	svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
1383 	svm_switch_vmcb(svm, &svm->vmcb01);
1384 
1385 	svm->guest_state_loaded = false;
1386 
1387 	return 0;
1388 
1389 error_free_avic:
1390 	avic_vcpu_free(vcpu);
1391 error_free_sev:
1392 	sev_free_vcpu(vcpu);
1393 error_free_pml_page:
1394 	if (vcpu->arch.pml_page)
1395 		__free_page(vcpu->arch.pml_page);
1396 error_free_vmcb_page:
1397 	__free_page(vmcb01_page);
1398 out:
1399 	return err;
1400 }
1401 
1402 static void svm_vcpu_free(struct kvm_vcpu *vcpu)
1403 {
1404 	struct vcpu_svm *svm = to_svm(vcpu);
1405 
1406 	WARN_ON_ONCE(!list_empty(&svm->ir_list));
1407 
1408 	avic_vcpu_free(vcpu);
1409 
1410 	svm_leave_nested(vcpu);
1411 	svm_free_nested(svm);
1412 
1413 	sev_free_vcpu(vcpu);
1414 
1415 	if (pml && vcpu->arch.pml_page)
1416 		__free_page(vcpu->arch.pml_page);
1417 
1418 	__free_page(__sme_pa_to_page(svm->vmcb01.pa));
1419 	svm_vcpu_free_msrpm(svm->msrpm);
1420 }
1421 
1422 #ifdef CONFIG_CPU_MITIGATIONS
1423 static DEFINE_SPINLOCK(srso_lock);
1424 static atomic_t srso_nr_vms;
1425 
1426 static void svm_srso_clear_bp_spec_reduce(void *ign)
1427 {
1428 	struct svm_cpu_data *sd = this_cpu_ptr(&svm_data);
1429 
1430 	if (!sd->bp_spec_reduce_set)
1431 		return;
1432 
1433 	msr_clear_bit(MSR_ZEN4_BP_CFG, MSR_ZEN4_BP_CFG_BP_SPEC_REDUCE_BIT);
1434 	sd->bp_spec_reduce_set = false;
1435 }
1436 
1437 static void svm_srso_vm_destroy(void)
1438 {
1439 	if (!cpu_feature_enabled(X86_FEATURE_SRSO_BP_SPEC_REDUCE))
1440 		return;
1441 
1442 	if (atomic_dec_return(&srso_nr_vms))
1443 		return;
1444 
1445 	guard(spinlock)(&srso_lock);
1446 
1447 	/*
1448 	 * Verify a new VM didn't come along, acquire the lock, and increment
1449 	 * the count before this task acquired the lock.
1450 	 */
1451 	if (atomic_read(&srso_nr_vms))
1452 		return;
1453 
1454 	on_each_cpu(svm_srso_clear_bp_spec_reduce, NULL, 1);
1455 }
1456 
1457 static void svm_srso_vm_init(void)
1458 {
1459 	if (!cpu_feature_enabled(X86_FEATURE_SRSO_BP_SPEC_REDUCE))
1460 		return;
1461 
1462 	/*
1463 	 * Acquire the lock on 0 => 1 transitions to ensure a potential 1 => 0
1464 	 * transition, i.e. destroying the last VM, is fully complete, e.g. so
1465 	 * that a delayed IPI doesn't clear BP_SPEC_REDUCE after a vCPU runs.
1466 	 */
1467 	if (atomic_inc_not_zero(&srso_nr_vms))
1468 		return;
1469 
1470 	guard(spinlock)(&srso_lock);
1471 
1472 	atomic_inc(&srso_nr_vms);
1473 }
1474 #else
1475 static void svm_srso_vm_init(void) { }
1476 static void svm_srso_vm_destroy(void) { }
1477 #endif
1478 
1479 static void svm_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1480 {
1481 	struct vcpu_svm *svm = to_svm(vcpu);
1482 	struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, vcpu->cpu);
1483 
1484 	if (is_sev_es_guest(vcpu))
1485 		sev_es_unmap_ghcb(svm);
1486 
1487 	if (svm->guest_state_loaded)
1488 		return;
1489 
1490 	/*
1491 	 * Save additional host state that will be restored on VMEXIT (sev-es)
1492 	 * or subsequent vmload of host save area.
1493 	 */
1494 	vmsave(sd->save_area_pa);
1495 	if (is_sev_es_guest(vcpu))
1496 		sev_es_prepare_switch_to_guest(svm, sev_es_host_save_area(sd));
1497 
1498 	if (tsc_scaling)
1499 		__svm_write_tsc_multiplier(vcpu->arch.tsc_scaling_ratio);
1500 
1501 	/*
1502 	 * TSC_AUX is always virtualized (context switched by hardware) for
1503 	 * SEV-ES guests when the feature is available.  For non-SEV-ES guests,
1504 	 * context switch TSC_AUX via the user_return MSR infrastructure (not
1505 	 * all CPUs support TSC_AUX virtualization).
1506 	 */
1507 	if (likely(tsc_aux_uret_slot >= 0) &&
1508 	    (!boot_cpu_has(X86_FEATURE_V_TSC_AUX) || !is_sev_es_guest(vcpu)))
1509 		kvm_set_user_return_msr(tsc_aux_uret_slot, svm->tsc_aux, -1ull);
1510 
1511 	if (cpu_feature_enabled(X86_FEATURE_SRSO_BP_SPEC_REDUCE) &&
1512 	    !sd->bp_spec_reduce_set) {
1513 		sd->bp_spec_reduce_set = true;
1514 		msr_set_bit(MSR_ZEN4_BP_CFG, MSR_ZEN4_BP_CFG_BP_SPEC_REDUCE_BIT);
1515 	}
1516 	svm->guest_state_loaded = true;
1517 }
1518 
1519 static void svm_prepare_host_switch(struct kvm_vcpu *vcpu)
1520 {
1521 	to_svm(vcpu)->guest_state_loaded = false;
1522 }
1523 
1524 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1525 {
1526 	if (vcpu->scheduled_out && !kvm_pause_in_guest(vcpu->kvm))
1527 		shrink_ple_window(vcpu);
1528 
1529 	if (kvm_vcpu_apicv_active(vcpu))
1530 		avic_vcpu_load(vcpu, cpu);
1531 }
1532 
1533 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
1534 {
1535 	if (kvm_vcpu_apicv_active(vcpu))
1536 		avic_vcpu_put(vcpu);
1537 
1538 	svm_prepare_host_switch(vcpu);
1539 
1540 	++vcpu->stat.host_state_reload;
1541 }
1542 
1543 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
1544 {
1545 	struct vcpu_svm *svm = to_svm(vcpu);
1546 	unsigned long rflags = svm->vmcb->save.rflags;
1547 
1548 	if (svm->nmi_singlestep) {
1549 		/* Hide our flags if they were not set by the guest */
1550 		if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1551 			rflags &= ~X86_EFLAGS_TF;
1552 		if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1553 			rflags &= ~X86_EFLAGS_RF;
1554 	}
1555 	return rflags;
1556 }
1557 
1558 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1559 {
1560 	if (to_svm(vcpu)->nmi_singlestep)
1561 		rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
1562 
1563        /*
1564         * Any change of EFLAGS.VM is accompanied by a reload of SS
1565         * (caused by either a task switch or an inter-privilege IRET),
1566         * so we do not need to update the CPL here.
1567         */
1568 	to_svm(vcpu)->vmcb->save.rflags = rflags;
1569 }
1570 
1571 static bool svm_get_if_flag(struct kvm_vcpu *vcpu)
1572 {
1573 	struct vmcb *vmcb = to_svm(vcpu)->vmcb;
1574 
1575 	return is_sev_es_guest(vcpu)
1576 		? vmcb->control.int_state & SVM_GUEST_INTERRUPT_MASK
1577 		: kvm_get_rflags(vcpu) & X86_EFLAGS_IF;
1578 }
1579 
1580 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1581 {
1582 	kvm_register_mark_available(vcpu, reg);
1583 
1584 	switch (reg) {
1585 	case VCPU_REG_PDPTR:
1586 		/*
1587 		 * When !npt_enabled, vcpu->pdptrs[] is already available since
1588 		 * it is always updated per SDM when moving to CRs.
1589 		 */
1590 		if (npt_enabled)
1591 			load_pdptrs(vcpu, kvm_read_cr3(vcpu));
1592 		break;
1593 	default:
1594 		KVM_BUG_ON(1, vcpu->kvm);
1595 	}
1596 }
1597 
1598 static void svm_set_vintr(struct vcpu_svm *svm)
1599 {
1600 	struct vmcb_control_area *control;
1601 
1602 	/*
1603 	 * The following fields are ignored when AVIC is enabled
1604 	 */
1605 	WARN_ON(kvm_vcpu_apicv_activated(&svm->vcpu));
1606 
1607 	svm_set_intercept(svm, INTERCEPT_VINTR);
1608 
1609 	/*
1610 	 * Recalculating intercepts may have cleared the VINTR intercept.  If
1611 	 * V_INTR_MASKING is enabled in vmcb12, then the effective RFLAGS.IF
1612 	 * for L1 physical interrupts is L1's RFLAGS.IF at the time of VMRUN.
1613 	 * Requesting an interrupt window if save.RFLAGS.IF=0 is pointless as
1614 	 * interrupts will never be unblocked while L2 is running.
1615 	 */
1616 	if (!svm_is_intercept(svm, INTERCEPT_VINTR))
1617 		return;
1618 
1619 	/*
1620 	 * This is just a dummy VINTR to actually cause a vmexit to happen.
1621 	 * Actual injection of virtual interrupts happens through EVENTINJ.
1622 	 */
1623 	control = &svm->vmcb->control;
1624 	control->int_vector = 0x0;
1625 	control->int_ctl &= ~V_INTR_PRIO_MASK;
1626 	control->int_ctl |= V_IRQ_MASK |
1627 		((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
1628 	vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1629 }
1630 
1631 static void svm_clear_vintr(struct vcpu_svm *svm)
1632 {
1633 	svm_clr_intercept(svm, INTERCEPT_VINTR);
1634 
1635 	/* Drop int_ctl fields related to VINTR injection.  */
1636 	svm->vmcb->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1637 	if (is_guest_mode(&svm->vcpu)) {
1638 		svm->vmcb01.ptr->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1639 
1640 		WARN_ON((svm->vmcb->control.int_ctl & V_TPR_MASK) !=
1641 			(svm->nested.ctl.int_ctl & V_TPR_MASK));
1642 
1643 		svm->vmcb->control.int_ctl |= svm->nested.ctl.int_ctl &
1644 			V_IRQ_INJECTION_BITS_MASK;
1645 
1646 		svm->vmcb->control.int_vector = svm->nested.ctl.int_vector;
1647 	}
1648 
1649 	vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1650 }
1651 
1652 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
1653 {
1654 	struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1655 	struct vmcb_save_area *save01 = &to_svm(vcpu)->vmcb01.ptr->save;
1656 
1657 	switch (seg) {
1658 	case VCPU_SREG_CS: return &save->cs;
1659 	case VCPU_SREG_DS: return &save->ds;
1660 	case VCPU_SREG_ES: return &save->es;
1661 	case VCPU_SREG_FS: return &save01->fs;
1662 	case VCPU_SREG_GS: return &save01->gs;
1663 	case VCPU_SREG_SS: return &save->ss;
1664 	case VCPU_SREG_TR: return &save01->tr;
1665 	case VCPU_SREG_LDTR: return &save01->ldtr;
1666 	}
1667 	BUG();
1668 	return NULL;
1669 }
1670 
1671 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1672 {
1673 	struct vmcb_seg *s = svm_seg(vcpu, seg);
1674 
1675 	return s->base;
1676 }
1677 
1678 static void svm_get_segment(struct kvm_vcpu *vcpu,
1679 			    struct kvm_segment *var, int seg)
1680 {
1681 	struct vmcb_seg *s = svm_seg(vcpu, seg);
1682 
1683 	var->base = s->base;
1684 	var->limit = s->limit;
1685 	var->selector = s->selector;
1686 	var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
1687 	var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
1688 	var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
1689 	var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
1690 	var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
1691 	var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
1692 	var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
1693 
1694 	/*
1695 	 * AMD CPUs circa 2014 track the G bit for all segments except CS.
1696 	 * However, the SVM spec states that the G bit is not observed by the
1697 	 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
1698 	 * So let's synthesize a legal G bit for all segments, this helps
1699 	 * running KVM nested. It also helps cross-vendor migration, because
1700 	 * Intel's vmentry has a check on the 'G' bit.
1701 	 */
1702 	var->g = s->limit > 0xfffff;
1703 
1704 	/*
1705 	 * AMD's VMCB does not have an explicit unusable field, so emulate it
1706 	 * for cross vendor migration purposes by "not present"
1707 	 */
1708 	var->unusable = !var->present;
1709 
1710 	switch (seg) {
1711 	case VCPU_SREG_TR:
1712 		/*
1713 		 * Work around a bug where the busy flag in the tr selector
1714 		 * isn't exposed
1715 		 */
1716 		var->type |= 0x2;
1717 		break;
1718 	case VCPU_SREG_DS:
1719 	case VCPU_SREG_ES:
1720 	case VCPU_SREG_FS:
1721 	case VCPU_SREG_GS:
1722 		/*
1723 		 * The accessed bit must always be set in the segment
1724 		 * descriptor cache, although it can be cleared in the
1725 		 * descriptor, the cached bit always remains at 1. Since
1726 		 * Intel has a check on this, set it here to support
1727 		 * cross-vendor migration.
1728 		 */
1729 		if (!var->unusable)
1730 			var->type |= 0x1;
1731 		break;
1732 	case VCPU_SREG_SS:
1733 		/*
1734 		 * On AMD CPUs sometimes the DB bit in the segment
1735 		 * descriptor is left as 1, although the whole segment has
1736 		 * been made unusable. Clear it here to pass an Intel VMX
1737 		 * entry check when cross vendor migrating.
1738 		 */
1739 		if (var->unusable)
1740 			var->db = 0;
1741 		/* This is symmetric with svm_set_segment() */
1742 		var->dpl = to_svm(vcpu)->vmcb->save.cpl;
1743 		break;
1744 	}
1745 }
1746 
1747 static int svm_get_cpl(struct kvm_vcpu *vcpu)
1748 {
1749 	struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1750 
1751 	return save->cpl;
1752 }
1753 
1754 static void svm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
1755 {
1756 	struct kvm_segment cs;
1757 
1758 	svm_get_segment(vcpu, &cs, VCPU_SREG_CS);
1759 	*db = cs.db;
1760 	*l = cs.l;
1761 }
1762 
1763 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1764 {
1765 	struct vcpu_svm *svm = to_svm(vcpu);
1766 
1767 	dt->size = svm->vmcb->save.idtr.limit;
1768 	dt->address = svm->vmcb->save.idtr.base;
1769 }
1770 
1771 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1772 {
1773 	struct vcpu_svm *svm = to_svm(vcpu);
1774 
1775 	svm->vmcb->save.idtr.limit = dt->size;
1776 	svm->vmcb->save.idtr.base = dt->address ;
1777 	vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1778 }
1779 
1780 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1781 {
1782 	struct vcpu_svm *svm = to_svm(vcpu);
1783 
1784 	dt->size = svm->vmcb->save.gdtr.limit;
1785 	dt->address = svm->vmcb->save.gdtr.base;
1786 }
1787 
1788 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1789 {
1790 	struct vcpu_svm *svm = to_svm(vcpu);
1791 
1792 	svm->vmcb->save.gdtr.limit = dt->size;
1793 	svm->vmcb->save.gdtr.base = dt->address ;
1794 	vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1795 }
1796 
1797 static void sev_post_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1798 {
1799 	struct vcpu_svm *svm = to_svm(vcpu);
1800 
1801 	/*
1802 	 * For guests that don't set guest_state_protected, the cr3 update is
1803 	 * handled via kvm_mmu_load() while entering the guest. For guests
1804 	 * that do (SEV-ES/SEV-SNP), the cr3 update needs to be written to
1805 	 * VMCB save area now, since the save area will become the initial
1806 	 * contents of the VMSA, and future VMCB save area updates won't be
1807 	 * seen.
1808 	 */
1809 	if (is_sev_es_guest(vcpu)) {
1810 		svm->vmcb->save.cr3 = cr3;
1811 		vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1812 	}
1813 }
1814 
1815 static bool svm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1816 {
1817 	return true;
1818 }
1819 
1820 void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1821 {
1822 	struct vcpu_svm *svm = to_svm(vcpu);
1823 	u64 hcr0 = cr0;
1824 	bool old_paging = is_paging(vcpu);
1825 
1826 #ifdef CONFIG_X86_64
1827 	if (vcpu->arch.efer & EFER_LME) {
1828 		if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
1829 			vcpu->arch.efer |= EFER_LMA;
1830 			if (!vcpu->arch.guest_state_protected)
1831 				svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
1832 		}
1833 
1834 		if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
1835 			vcpu->arch.efer &= ~EFER_LMA;
1836 			if (!vcpu->arch.guest_state_protected)
1837 				svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
1838 		}
1839 	}
1840 #endif
1841 	vcpu->arch.cr0 = cr0;
1842 
1843 	if (!npt_enabled) {
1844 		hcr0 |= X86_CR0_PG | X86_CR0_WP;
1845 		if (old_paging != is_paging(vcpu))
1846 			svm_set_cr4(vcpu, kvm_read_cr4(vcpu));
1847 	}
1848 
1849 	/*
1850 	 * re-enable caching here because the QEMU bios
1851 	 * does not do it - this results in some delay at
1852 	 * reboot
1853 	 */
1854 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
1855 		hcr0 &= ~(X86_CR0_CD | X86_CR0_NW);
1856 
1857 	svm->vmcb->save.cr0 = hcr0;
1858 	vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1859 
1860 	/*
1861 	 * SEV-ES guests must always keep the CR intercepts cleared. CR
1862 	 * tracking is done using the CR write traps.
1863 	 */
1864 	if (is_sev_es_guest(vcpu))
1865 		return;
1866 
1867 	if (hcr0 == cr0) {
1868 		/* Selective CR0 write remains on.  */
1869 		svm_clr_intercept(svm, INTERCEPT_CR0_READ);
1870 		svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
1871 	} else {
1872 		svm_set_intercept(svm, INTERCEPT_CR0_READ);
1873 		svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1874 	}
1875 }
1876 
1877 static bool svm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1878 {
1879 	return true;
1880 }
1881 
1882 void svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1883 {
1884 	unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
1885 	unsigned long old_cr4 = vcpu->arch.cr4;
1886 
1887 	vcpu->arch.cr4 = cr4;
1888 	if (!npt_enabled) {
1889 		cr4 |= X86_CR4_PAE;
1890 
1891 		if (!is_paging(vcpu))
1892 			cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
1893 	}
1894 	cr4 |= host_cr4_mce;
1895 	to_svm(vcpu)->vmcb->save.cr4 = cr4;
1896 	vmcb_mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
1897 
1898 	if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
1899 		vcpu->arch.cpuid_dynamic_bits_dirty = true;
1900 }
1901 
1902 static void svm_set_segment(struct kvm_vcpu *vcpu,
1903 			    struct kvm_segment *var, int seg)
1904 {
1905 	struct vcpu_svm *svm = to_svm(vcpu);
1906 	struct vmcb_seg *s = svm_seg(vcpu, seg);
1907 
1908 	s->base = var->base;
1909 	s->limit = var->limit;
1910 	s->selector = var->selector;
1911 	s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
1912 	s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
1913 	s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
1914 	s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
1915 	s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
1916 	s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
1917 	s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
1918 	s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
1919 
1920 	/*
1921 	 * This is always accurate, except if SYSRET returned to a segment
1922 	 * with SS.DPL != 3.  Intel does not have this quirk, and always
1923 	 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
1924 	 * would entail passing the CPL to userspace and back.
1925 	 */
1926 	if (seg == VCPU_SREG_SS)
1927 		/* This is symmetric with svm_get_segment() */
1928 		svm->vmcb->save.cpl = (var->dpl & 3);
1929 
1930 	vmcb_mark_dirty(svm->vmcb, VMCB_SEG);
1931 }
1932 
1933 static void svm_update_exception_bitmap(struct kvm_vcpu *vcpu)
1934 {
1935 	struct vcpu_svm *svm = to_svm(vcpu);
1936 
1937 	clr_exception_intercept(svm, BP_VECTOR);
1938 
1939 	if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
1940 		if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
1941 			set_exception_intercept(svm, BP_VECTOR);
1942 	}
1943 }
1944 
1945 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
1946 {
1947 	if (sd->next_asid > sd->max_asid) {
1948 		++sd->asid_generation;
1949 		sd->next_asid = sd->min_asid;
1950 		sd->flush_all_asids = true;
1951 	}
1952 
1953 	svm->current_vmcb->asid_generation = sd->asid_generation;
1954 	svm->asid = sd->next_asid++;
1955 }
1956 
1957 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
1958 {
1959 	struct vmcb *vmcb = to_svm(vcpu)->vmcb;
1960 
1961 	if (vcpu->arch.guest_state_protected)
1962 		return;
1963 
1964 	if (unlikely(value != vmcb->save.dr6)) {
1965 		vmcb->save.dr6 = value;
1966 		vmcb_mark_dirty(vmcb, VMCB_DR);
1967 	}
1968 }
1969 
1970 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
1971 {
1972 	struct vcpu_svm *svm = to_svm(vcpu);
1973 
1974 	if (WARN_ON_ONCE(is_sev_es_guest(vcpu)))
1975 		return;
1976 
1977 	get_debugreg(vcpu->arch.db[0], 0);
1978 	get_debugreg(vcpu->arch.db[1], 1);
1979 	get_debugreg(vcpu->arch.db[2], 2);
1980 	get_debugreg(vcpu->arch.db[3], 3);
1981 	/*
1982 	 * We cannot reset svm->vmcb->save.dr6 to DR6_ACTIVE_LOW here,
1983 	 * because db_interception might need it.  We can do it before vmentry.
1984 	 */
1985 	vcpu->arch.dr6 = svm->vmcb->save.dr6;
1986 	vcpu->arch.dr7 = svm->vmcb->save.dr7;
1987 	vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
1988 	set_dr_intercepts(svm);
1989 }
1990 
1991 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
1992 {
1993 	struct vcpu_svm *svm = to_svm(vcpu);
1994 
1995 	if (vcpu->arch.guest_state_protected)
1996 		return;
1997 
1998 	svm->vmcb->save.dr7 = value;
1999 	vmcb_mark_dirty(svm->vmcb, VMCB_DR);
2000 }
2001 
2002 static int pf_interception(struct kvm_vcpu *vcpu)
2003 {
2004 	struct vcpu_svm *svm = to_svm(vcpu);
2005 
2006 	u64 fault_address = svm->vmcb->control.exit_info_2;
2007 	u64 error_code = svm->vmcb->control.exit_info_1;
2008 
2009 	return kvm_handle_page_fault(vcpu, error_code, fault_address,
2010 			cpu_feature_enabled(X86_FEATURE_DECODEASSISTS) ?
2011 			svm->vmcb->control.insn_bytes : NULL,
2012 			svm->vmcb->control.insn_len);
2013 }
2014 
2015 static int svm_check_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
2016 					 void *insn, int insn_len);
2017 
2018 static int npf_interception(struct kvm_vcpu *vcpu)
2019 {
2020 	struct vcpu_svm *svm = to_svm(vcpu);
2021 	int rc;
2022 
2023 	u64 error_code = svm->vmcb->control.exit_info_1;
2024 	gpa_t gpa = svm->vmcb->control.exit_info_2;
2025 
2026 	/*
2027 	 * WARN if hardware generates a fault with an error code that collides
2028 	 * with KVM-defined sythentic flags.  Clear the flags and continue on,
2029 	 * i.e. don't terminate the VM, as KVM can't possibly be relying on a
2030 	 * flag that KVM doesn't know about.
2031 	 */
2032 	if (WARN_ON_ONCE(error_code & PFERR_SYNTHETIC_MASK))
2033 		error_code &= ~PFERR_SYNTHETIC_MASK;
2034 
2035 	/*
2036 	 * Expedite fast MMIO kicks if the next RIP is known and KVM is allowed
2037 	 * emulate a page fault, e.g. skipping the current instruction is wrong
2038 	 * if the #NPF occurred while vectoring an event.
2039 	 */
2040 	if ((error_code & PFERR_RSVD_MASK) && !is_guest_mode(vcpu)) {
2041 		const int emul_type = EMULTYPE_PF | EMULTYPE_NO_DECODE;
2042 
2043 		if (svm_check_emulate_instruction(vcpu, emul_type, NULL, 0))
2044 			return 1;
2045 
2046 		if (nrips && svm->vmcb->control.next_rip &&
2047 		    !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
2048 			trace_kvm_fast_mmio(gpa);
2049 			return kvm_skip_emulated_instruction(vcpu);
2050 		}
2051 	}
2052 
2053 	if (!is_sev_es_guest(vcpu) &&
2054 	    (svm->vmcb->control.misc_ctl & SVM_MISC_ENABLE_GMET) &&
2055 	    (error_code & PFERR_FETCH_MASK)) {
2056 		/*
2057 		 * Work around errata 1218: EXITINFO1[2] May Be Incorrectly Set
2058 		 * When GMET (Guest Mode Execute Trap extension) is Enabled
2059 		 */
2060 		error_code |= PFERR_USER_MASK;
2061 		if (svm_get_cpl(vcpu) != 3)
2062 			error_code &= ~PFERR_USER_MASK;
2063 	}
2064 
2065 	if (is_sev_snp_guest(vcpu) && (error_code & PFERR_GUEST_ENC_MASK))
2066 		error_code |= PFERR_PRIVATE_ACCESS;
2067 
2068 	trace_kvm_page_fault(vcpu, gpa, error_code);
2069 	rc = kvm_mmu_page_fault(vcpu, gpa, error_code,
2070 				cpu_feature_enabled(X86_FEATURE_DECODEASSISTS) ?
2071 				svm->vmcb->control.insn_bytes : NULL,
2072 				svm->vmcb->control.insn_len);
2073 
2074 	if (rc > 0 && error_code & PFERR_GUEST_RMP_MASK)
2075 		sev_handle_rmp_fault(vcpu, gpa, error_code);
2076 
2077 	return rc;
2078 }
2079 
2080 static int db_interception(struct kvm_vcpu *vcpu)
2081 {
2082 	struct kvm_run *kvm_run = vcpu->run;
2083 	struct vcpu_svm *svm = to_svm(vcpu);
2084 
2085 	if (!(vcpu->guest_debug &
2086 	      (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2087 		!svm->nmi_singlestep) {
2088 		u32 payload = svm->vmcb->save.dr6 ^ DR6_ACTIVE_LOW;
2089 		kvm_queue_exception_p(vcpu, DB_VECTOR, payload);
2090 		return 1;
2091 	}
2092 
2093 	if (svm->nmi_singlestep) {
2094 		disable_nmi_singlestep(svm);
2095 		/* Make sure we check for pending NMIs upon entry */
2096 		kvm_make_request(KVM_REQ_EVENT, vcpu);
2097 	}
2098 
2099 	if (vcpu->guest_debug &
2100 	    (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2101 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
2102 		kvm_run->debug.arch.dr6 = svm->vmcb->save.dr6;
2103 		kvm_run->debug.arch.dr7 = svm->vmcb->save.dr7;
2104 		kvm_run->debug.arch.pc =
2105 			svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2106 		kvm_run->debug.arch.exception = DB_VECTOR;
2107 		return 0;
2108 	}
2109 
2110 	return 1;
2111 }
2112 
2113 static int bp_interception(struct kvm_vcpu *vcpu)
2114 {
2115 	struct vcpu_svm *svm = to_svm(vcpu);
2116 	struct kvm_run *kvm_run = vcpu->run;
2117 
2118 	kvm_run->exit_reason = KVM_EXIT_DEBUG;
2119 	kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2120 	kvm_run->debug.arch.exception = BP_VECTOR;
2121 	return 0;
2122 }
2123 
2124 static int icebp_interception(struct kvm_vcpu *vcpu)
2125 {
2126 	/*
2127 	 * Intercept and emulate ICEBP (INT1, opcode 0xF1) instead of allowing
2128 	 * the guest to natively take the #DB trap, so that RIP is advanced
2129 	 * past the instruction *before* #DB is injected.  This is necessary
2130 	 * because SVM reports the wrong RIP for ICEBP-induced #DB when #DBs
2131 	 * are delivered via a task gate: RIP points at the ICEBP instruction
2132 	 * instead of after it (and SVM doesn't provide enough information for
2133 	 * KVM to detect and manually advance the pre-#DB RIP).
2134 	 */
2135 	svm_skip_emulated_instruction(vcpu);
2136 	kvm_queue_exception(vcpu, DB_VECTOR);
2137 	return 1;
2138 }
2139 
2140 static int ud_interception(struct kvm_vcpu *vcpu)
2141 {
2142 	return handle_ud(vcpu);
2143 }
2144 
2145 static int ac_interception(struct kvm_vcpu *vcpu)
2146 {
2147 	kvm_queue_exception_e(vcpu, AC_VECTOR, 0);
2148 	return 1;
2149 }
2150 
2151 static bool is_erratum_383(void)
2152 {
2153 	int i;
2154 	u64 value;
2155 
2156 	if (!erratum_383_found)
2157 		return false;
2158 
2159 	if (native_read_msr_safe(MSR_IA32_MC0_STATUS, &value))
2160 		return false;
2161 
2162 	/* Bit 62 may or may not be set for this mce */
2163 	value &= ~(1ULL << 62);
2164 
2165 	if (value != 0xb600000000010015ULL)
2166 		return false;
2167 
2168 	/* Clear MCi_STATUS registers */
2169 	for (i = 0; i < 6; ++i)
2170 		native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0);
2171 
2172 	if (!native_read_msr_safe(MSR_IA32_MCG_STATUS, &value)) {
2173 		value &= ~(1ULL << 2);
2174 		native_write_msr_safe(MSR_IA32_MCG_STATUS, value);
2175 	}
2176 
2177 	/* Flush tlb to evict multi-match entries */
2178 	__flush_tlb_all();
2179 
2180 	return true;
2181 }
2182 
2183 static void svm_handle_mce(struct kvm_vcpu *vcpu)
2184 {
2185 	if (is_erratum_383()) {
2186 		/*
2187 		 * Erratum 383 triggered. Guest state is corrupt so kill the
2188 		 * guest.
2189 		 */
2190 		pr_err("Guest triggered AMD Erratum 383\n");
2191 
2192 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2193 
2194 		return;
2195 	}
2196 
2197 	/*
2198 	 * On an #MC intercept the MCE handler is not called automatically in
2199 	 * the host. So do it by hand here.
2200 	 */
2201 	kvm_machine_check();
2202 }
2203 
2204 static int mc_interception(struct kvm_vcpu *vcpu)
2205 {
2206 	return 1;
2207 }
2208 
2209 static int shutdown_interception(struct kvm_vcpu *vcpu)
2210 {
2211 	struct kvm_run *kvm_run = vcpu->run;
2212 	struct vcpu_svm *svm = to_svm(vcpu);
2213 
2214 
2215 	/*
2216 	 * The VMCB save area is undefined after a SHUTDOWN intercept, as are
2217 	 * control area offsets 60h, 61h, and 68h (int_ctl[15:0] and int_state).
2218 	 * INIT the vCPU to put the VMCB in a known good state.  Unfortunately,
2219 	 * KVM doesn't have KVM_MP_STATE_SHUTDOWN and can't add it without
2220 	 * potentially breaking userspace.  At a platform view, INIT is
2221 	 * acceptable behavior as there exist bare metal platforms that
2222 	 * automatically INIT the CPU in response to shutdown.
2223 	 *
2224 	 * The VM save area for SEV-ES guests has already been encrypted so it
2225 	 * cannot be reinitialized, i.e. synthesizing INIT is futile.
2226 	 */
2227 	if (!is_sev_es_guest(vcpu)) {
2228 		struct vmcb_control_area *control = &svm->vmcb->control;
2229 
2230 		memset(&svm->vmcb->save, 0, sizeof(svm->vmcb->save));
2231 		control->int_ctl &= ~GENMASK(15, 0);
2232 		control->int_state = 0;
2233 
2234 		/*
2235 		 * EVENTINJ is cleared on #VMEXIT, but only if VMRUN fully
2236 		 * entered the guest.  Manually clear the fields even though it
2237 		 * should be redundant, as there is no downside to doing so.
2238 		 */
2239 		control->event_inj = 0;
2240 		control->event_inj_err = 0;
2241 #ifdef CONFIG_KVM_SMM
2242 		if (is_smm(vcpu))
2243 			kvm_smm_changed(vcpu, false);
2244 #endif
2245 		kvm_vcpu_reset(vcpu, true);
2246 	}
2247 
2248 	kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2249 	return 0;
2250 }
2251 
2252 static int io_interception(struct kvm_vcpu *vcpu)
2253 {
2254 	struct vcpu_svm *svm = to_svm(vcpu);
2255 	u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2256 	int size, in, string;
2257 	unsigned port;
2258 
2259 	++vcpu->stat.io_exits;
2260 	string = (io_info & SVM_IOIO_STR_MASK) != 0;
2261 	in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2262 	port = io_info >> 16;
2263 	size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2264 
2265 	if (string) {
2266 		if (is_sev_es_guest(vcpu))
2267 			return sev_es_string_io(svm, size, port, in);
2268 		else
2269 			return kvm_emulate_instruction(vcpu, 0);
2270 	}
2271 
2272 	svm->next_rip = svm->vmcb->control.exit_info_2;
2273 
2274 	return kvm_fast_pio(vcpu, size, port, in);
2275 }
2276 
2277 static int nmi_interception(struct kvm_vcpu *vcpu)
2278 {
2279 	return 1;
2280 }
2281 
2282 static int smi_interception(struct kvm_vcpu *vcpu)
2283 {
2284 	return 1;
2285 }
2286 
2287 static int intr_interception(struct kvm_vcpu *vcpu)
2288 {
2289 	++vcpu->stat.irq_exits;
2290 	return 1;
2291 }
2292 
2293 static int vmload_vmsave_interception(struct kvm_vcpu *vcpu, bool vmload)
2294 {
2295 	u64 vmcb12_gpa = kvm_rax_read(vcpu);
2296 	struct vcpu_svm *svm = to_svm(vcpu);
2297 	struct vmcb *vmcb12;
2298 	int ret;
2299 
2300 	if (nested_svm_check_permissions(vcpu))
2301 		return 1;
2302 
2303 	if (!page_address_valid(vcpu, vmcb12_gpa)) {
2304 		kvm_inject_gp(vcpu, 0);
2305 		return 1;
2306 	}
2307 
2308 	CLASS(kvm_vcpu_map_local, m)(vcpu, gpa_to_gfn(vmcb12_gpa));
2309 	if (m.ret)
2310 		return kvm_handle_memory_failure(vcpu, X86EMUL_IO_NEEDED, NULL);
2311 
2312 	vmcb12 = m.map.hva;
2313 
2314 	ret = kvm_skip_emulated_instruction(vcpu);
2315 
2316 	/* KVM always performs VMLOAD/VMSAVE on VMCB01 (see __svm_vcpu_run()) */
2317 	if (vmload) {
2318 		svm_copy_vmloadsave_state(svm->vmcb01.ptr, vmcb12);
2319 		svm->sysenter_eip_hi = 0;
2320 		svm->sysenter_esp_hi = 0;
2321 	} else {
2322 		svm_copy_vmloadsave_state(vmcb12, svm->vmcb01.ptr);
2323 	}
2324 
2325 	return ret;
2326 }
2327 
2328 static int vmload_interception(struct kvm_vcpu *vcpu)
2329 {
2330 	return vmload_vmsave_interception(vcpu, true);
2331 }
2332 
2333 static int vmsave_interception(struct kvm_vcpu *vcpu)
2334 {
2335 	return vmload_vmsave_interception(vcpu, false);
2336 }
2337 
2338 static int vmrun_interception(struct kvm_vcpu *vcpu)
2339 {
2340 	if (nested_svm_check_permissions(vcpu))
2341 		return 1;
2342 
2343 	return nested_svm_vmrun(vcpu);
2344 }
2345 
2346 /* Return 0 if not SVM instr, otherwise return associated exit_code */
2347 static u64 svm_get_decoded_instr_exit_code(struct kvm_vcpu *vcpu)
2348 {
2349 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
2350 
2351 	if (ctxt->b != 0x1 || ctxt->opcode_len != 2)
2352 		return 0;
2353 
2354 	BUILD_BUG_ON(!SVM_EXIT_VMRUN || !SVM_EXIT_VMLOAD || !SVM_EXIT_VMSAVE);
2355 
2356 	switch (ctxt->modrm) {
2357 	case 0xd8: /* VMRUN */
2358 		return SVM_EXIT_VMRUN;
2359 	case 0xda: /* VMLOAD */
2360 		return SVM_EXIT_VMLOAD;
2361 	case 0xdb: /* VMSAVE */
2362 		return SVM_EXIT_VMSAVE;
2363 	default:
2364 		break;
2365 	}
2366 
2367 	return 0;
2368 }
2369 
2370 /*
2371  * #GP handling code. Note that #GP can be triggered under the following two
2372  * cases:
2373  *   1) SVM VM-related instructions (VMRUN/VMSAVE/VMLOAD) that trigger #GP on
2374  *      some AMD CPUs when EAX of these instructions are in the reserved memory
2375  *      regions (e.g. SMM memory on host).
2376  *   2) VMware backdoor
2377  */
2378 static int gp_interception(struct kvm_vcpu *vcpu)
2379 {
2380 	struct vcpu_svm *svm = to_svm(vcpu);
2381 	u32 error_code = svm->vmcb->control.exit_info_1;
2382 	u64 svm_exit_code;
2383 
2384 	/* Both #GP cases have zero error_code */
2385 	if (error_code)
2386 		goto reinject;
2387 
2388 	/* Decode the instruction for usage later */
2389 	if (x86_decode_emulated_instruction(vcpu, 0, NULL, 0) != EMULATION_OK)
2390 		goto reinject;
2391 
2392 	/* FIXME: Handle SVM instructions through the emulator */
2393 	svm_exit_code = svm_get_decoded_instr_exit_code(vcpu);
2394 	if (svm_exit_code) {
2395 		if (!is_guest_mode(vcpu))
2396 			return svm_invoke_exit_handler(vcpu, svm_exit_code);
2397 
2398 		if (nested_svm_check_permissions(vcpu))
2399 			return 1;
2400 
2401 		if (!page_address_valid(vcpu, kvm_rax_read(vcpu)))
2402 			goto reinject;
2403 
2404 		/*
2405 		 * FIXME: Only synthesize a #VMEXIT if L1 sets the intercept,
2406 		 * but only after the VMLOAD/VMSAVE exit handlers can properly
2407 		 * handle VMLOAD/VMSAVE from L2 with VLS enabled in L1 (i.e.
2408 		 * RAX is an L2 GPA that needs translation through L1's NPT).
2409 		 */
2410 		nested_svm_simple_vmexit(svm, svm_exit_code);
2411 		return 1;
2412 	}
2413 
2414 	/*
2415 	 * VMware backdoor emulation on #GP interception only handles
2416 	 * IN{S}, OUT{S}, and RDPMC, and only for L1.
2417 	 */
2418 	if (!enable_vmware_backdoor || is_guest_mode(vcpu))
2419 		goto reinject;
2420 
2421 	return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP | EMULTYPE_NO_DECODE);
2422 
2423 reinject:
2424 	kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2425 	return 1;
2426 }
2427 
2428 void svm_set_gif(struct vcpu_svm *svm, bool value)
2429 {
2430 	if (value) {
2431 		/*
2432 		 * If VGIF is enabled, the STGI intercept is only added to
2433 		 * detect the opening of the SMI/NMI window; remove it now.
2434 		 * Likewise, clear the VINTR intercept, we will set it
2435 		 * again while processing KVM_REQ_EVENT if needed.
2436 		 */
2437 		if (vgif)
2438 			svm_clr_intercept(svm, INTERCEPT_STGI);
2439 		if (svm_is_intercept(svm, INTERCEPT_VINTR))
2440 			svm_clear_vintr(svm);
2441 
2442 		enable_gif(svm);
2443 		if (svm_has_pending_gif_event(svm))
2444 			kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
2445 	} else {
2446 		disable_gif(svm);
2447 
2448 		/*
2449 		 * After a CLGI no interrupts should come.  But if vGIF is
2450 		 * in use, we still rely on the VINTR intercept (rather than
2451 		 * STGI) to detect an open interrupt window.
2452 		*/
2453 		if (!vgif)
2454 			svm_clear_vintr(svm);
2455 	}
2456 }
2457 
2458 static int stgi_interception(struct kvm_vcpu *vcpu)
2459 {
2460 	int ret;
2461 
2462 	if (nested_svm_check_permissions(vcpu))
2463 		return 1;
2464 
2465 	ret = kvm_skip_emulated_instruction(vcpu);
2466 	svm_set_gif(to_svm(vcpu), true);
2467 	return ret;
2468 }
2469 
2470 static int clgi_interception(struct kvm_vcpu *vcpu)
2471 {
2472 	int ret;
2473 
2474 	if (nested_svm_check_permissions(vcpu))
2475 		return 1;
2476 
2477 	ret = kvm_skip_emulated_instruction(vcpu);
2478 	svm_set_gif(to_svm(vcpu), false);
2479 	return ret;
2480 }
2481 
2482 static int invlpga_interception(struct kvm_vcpu *vcpu)
2483 {
2484 	/* FIXME: Handle an address size prefix. */
2485 	gva_t gva = kvm_rax_read(vcpu);
2486 	u32 asid = kvm_ecx_read(vcpu);
2487 
2488 	if (nested_svm_check_permissions(vcpu))
2489 		return 1;
2490 
2491 	trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
2492 
2493 	/* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
2494 	kvm_mmu_invlpg(vcpu, gva);
2495 
2496 	return kvm_skip_emulated_instruction(vcpu);
2497 }
2498 
2499 static int skinit_interception(struct kvm_vcpu *vcpu)
2500 {
2501 	trace_kvm_skinit(to_svm(vcpu)->vmcb->save.rip, kvm_rax_read(vcpu));
2502 
2503 	kvm_queue_exception(vcpu, UD_VECTOR);
2504 	return 1;
2505 }
2506 
2507 static int task_switch_interception(struct kvm_vcpu *vcpu)
2508 {
2509 	struct vcpu_svm *svm = to_svm(vcpu);
2510 	u16 tss_selector;
2511 	int reason;
2512 	int int_type = svm->vmcb->control.exit_int_info &
2513 		SVM_EXITINTINFO_TYPE_MASK;
2514 	int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
2515 	uint32_t type =
2516 		svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
2517 	uint32_t idt_v =
2518 		svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
2519 	bool has_error_code = false;
2520 	u32 error_code = 0;
2521 
2522 	tss_selector = (u16)svm->vmcb->control.exit_info_1;
2523 
2524 	if (svm->vmcb->control.exit_info_2 &
2525 	    (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
2526 		reason = TASK_SWITCH_IRET;
2527 	else if (svm->vmcb->control.exit_info_2 &
2528 		 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
2529 		reason = TASK_SWITCH_JMP;
2530 	else if (idt_v)
2531 		reason = TASK_SWITCH_GATE;
2532 	else
2533 		reason = TASK_SWITCH_CALL;
2534 
2535 	if (reason == TASK_SWITCH_GATE) {
2536 		switch (type) {
2537 		case SVM_EXITINTINFO_TYPE_NMI:
2538 			vcpu->arch.nmi_injected = false;
2539 			break;
2540 		case SVM_EXITINTINFO_TYPE_EXEPT:
2541 			if (svm->vmcb->control.exit_info_2 &
2542 			    (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
2543 				has_error_code = true;
2544 				error_code =
2545 					(u32)svm->vmcb->control.exit_info_2;
2546 			}
2547 			kvm_clear_exception_queue(vcpu);
2548 			break;
2549 		case SVM_EXITINTINFO_TYPE_INTR:
2550 		case SVM_EXITINTINFO_TYPE_SOFT:
2551 			kvm_clear_interrupt_queue(vcpu);
2552 			break;
2553 		default:
2554 			break;
2555 		}
2556 	}
2557 
2558 	if (reason != TASK_SWITCH_GATE ||
2559 	    int_type == SVM_EXITINTINFO_TYPE_SOFT ||
2560 	    (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
2561 	     (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
2562 		if (!svm_skip_emulated_instruction(vcpu))
2563 			return 0;
2564 	}
2565 
2566 	if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
2567 		int_vec = -1;
2568 
2569 	return kvm_task_switch(vcpu, tss_selector, int_vec, reason,
2570 			       has_error_code, error_code);
2571 }
2572 
2573 static void svm_clr_iret_intercept(struct vcpu_svm *svm)
2574 {
2575 	if (!is_sev_es_guest(&svm->vcpu))
2576 		svm_clr_intercept(svm, INTERCEPT_IRET);
2577 }
2578 
2579 static void svm_set_iret_intercept(struct vcpu_svm *svm)
2580 {
2581 	if (!is_sev_es_guest(&svm->vcpu))
2582 		svm_set_intercept(svm, INTERCEPT_IRET);
2583 }
2584 
2585 static int iret_interception(struct kvm_vcpu *vcpu)
2586 {
2587 	struct vcpu_svm *svm = to_svm(vcpu);
2588 
2589 	WARN_ON_ONCE(is_sev_es_guest(vcpu));
2590 
2591 	++vcpu->stat.nmi_window_exits;
2592 	svm->awaiting_iret_completion = true;
2593 
2594 	svm_clr_iret_intercept(svm);
2595 	svm->nmi_iret_rip = kvm_rip_read(vcpu);
2596 
2597 	kvm_make_request(KVM_REQ_EVENT, vcpu);
2598 	return 1;
2599 }
2600 
2601 static int invlpg_interception(struct kvm_vcpu *vcpu)
2602 {
2603 	if (!cpu_feature_enabled(X86_FEATURE_DECODEASSISTS))
2604 		return kvm_emulate_instruction(vcpu, 0);
2605 
2606 	kvm_mmu_invlpg(vcpu, to_svm(vcpu)->vmcb->control.exit_info_1);
2607 	return kvm_skip_emulated_instruction(vcpu);
2608 }
2609 
2610 static int emulate_on_interception(struct kvm_vcpu *vcpu)
2611 {
2612 	return kvm_emulate_instruction(vcpu, 0);
2613 }
2614 
2615 static int rsm_interception(struct kvm_vcpu *vcpu)
2616 {
2617 	return kvm_emulate_instruction_from_buffer(vcpu, rsm_ins_bytes, 2);
2618 }
2619 
2620 static bool check_selective_cr0_intercepted(struct kvm_vcpu *vcpu,
2621 					    unsigned long val)
2622 {
2623 	struct vcpu_svm *svm = to_svm(vcpu);
2624 	unsigned long cr0 = vcpu->arch.cr0;
2625 	bool ret = false;
2626 
2627 	if (!is_guest_mode(vcpu) ||
2628 	    (!(vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_SELECTIVE_CR0))))
2629 		return false;
2630 
2631 	cr0 &= ~SVM_CR0_SELECTIVE_MASK;
2632 	val &= ~SVM_CR0_SELECTIVE_MASK;
2633 
2634 	if (cr0 ^ val) {
2635 		svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
2636 		ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
2637 	}
2638 
2639 	return ret;
2640 }
2641 
2642 #define CR_VALID (1ULL << 63)
2643 
2644 static int cr_interception(struct kvm_vcpu *vcpu)
2645 {
2646 	struct vcpu_svm *svm = to_svm(vcpu);
2647 	int reg, cr;
2648 	unsigned long val;
2649 	int err;
2650 
2651 	if (!cpu_feature_enabled(X86_FEATURE_DECODEASSISTS))
2652 		return emulate_on_interception(vcpu);
2653 
2654 	if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
2655 		return emulate_on_interception(vcpu);
2656 
2657 	reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2658 	if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
2659 		cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
2660 	else
2661 		cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
2662 
2663 	err = 0;
2664 	if (cr >= 16) { /* mov to cr */
2665 		cr -= 16;
2666 		val = kvm_register_read(vcpu, reg);
2667 		trace_kvm_cr_write(cr, val);
2668 		switch (cr) {
2669 		case 0:
2670 			if (!check_selective_cr0_intercepted(vcpu, val))
2671 				err = kvm_set_cr0(vcpu, val);
2672 			else
2673 				return 1;
2674 
2675 			break;
2676 		case 3:
2677 			err = kvm_set_cr3(vcpu, val);
2678 			break;
2679 		case 4:
2680 			err = kvm_set_cr4(vcpu, val);
2681 			break;
2682 		case 8:
2683 			err = kvm_set_cr8(vcpu, val);
2684 			break;
2685 		default:
2686 			WARN(1, "unhandled write to CR%d", cr);
2687 			kvm_queue_exception(vcpu, UD_VECTOR);
2688 			return 1;
2689 		}
2690 	} else { /* mov from cr */
2691 		switch (cr) {
2692 		case 0:
2693 			val = kvm_read_cr0(vcpu);
2694 			break;
2695 		case 2:
2696 			val = vcpu->arch.cr2;
2697 			break;
2698 		case 3:
2699 			val = kvm_read_cr3(vcpu);
2700 			break;
2701 		case 4:
2702 			val = kvm_read_cr4(vcpu);
2703 			break;
2704 		case 8:
2705 			val = kvm_get_cr8(vcpu);
2706 			break;
2707 		default:
2708 			WARN(1, "unhandled read from CR%d", cr);
2709 			kvm_queue_exception(vcpu, UD_VECTOR);
2710 			return 1;
2711 		}
2712 		kvm_register_write(vcpu, reg, val);
2713 		trace_kvm_cr_read(cr, val);
2714 	}
2715 	return kvm_complete_insn_gp(vcpu, err);
2716 }
2717 
2718 static int cr_trap(struct kvm_vcpu *vcpu)
2719 {
2720 	struct vcpu_svm *svm = to_svm(vcpu);
2721 	unsigned long old_value, new_value;
2722 	unsigned int cr;
2723 	int ret = 0;
2724 
2725 	new_value = (unsigned long)svm->vmcb->control.exit_info_1;
2726 
2727 	cr = svm->vmcb->control.exit_code - SVM_EXIT_CR0_WRITE_TRAP;
2728 	switch (cr) {
2729 	case 0:
2730 		old_value = kvm_read_cr0(vcpu);
2731 		svm_set_cr0(vcpu, new_value);
2732 
2733 		kvm_post_set_cr0(vcpu, old_value, new_value);
2734 		break;
2735 	case 4:
2736 		old_value = kvm_read_cr4(vcpu);
2737 		svm_set_cr4(vcpu, new_value);
2738 
2739 		kvm_post_set_cr4(vcpu, old_value, new_value);
2740 		break;
2741 	case 8:
2742 		ret = kvm_set_cr8(vcpu, new_value);
2743 		break;
2744 	default:
2745 		WARN(1, "unhandled CR%d write trap", cr);
2746 		kvm_queue_exception(vcpu, UD_VECTOR);
2747 		return 1;
2748 	}
2749 
2750 	return kvm_complete_insn_gp(vcpu, ret);
2751 }
2752 
2753 static int dr_interception(struct kvm_vcpu *vcpu)
2754 {
2755 	struct vcpu_svm *svm = to_svm(vcpu);
2756 	int reg, dr;
2757 	int err = 0;
2758 
2759 	/*
2760 	 * SEV-ES intercepts DR7 only to disable guest debugging and the guest issues a VMGEXIT
2761 	 * for DR7 write only. KVM cannot change DR7 (always swapped as type 'A') so return early.
2762 	 */
2763 	if (is_sev_es_guest(vcpu))
2764 		return 1;
2765 
2766 	if (vcpu->guest_debug == 0) {
2767 		/*
2768 		 * No more DR vmexits; force a reload of the debug registers
2769 		 * and reenter on this instruction.  The next vmexit will
2770 		 * retrieve the full state of the debug registers.
2771 		 */
2772 		clr_dr_intercepts(svm);
2773 		vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
2774 		return 1;
2775 	}
2776 
2777 	if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
2778 		return emulate_on_interception(vcpu);
2779 
2780 	reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2781 	dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
2782 	if (dr >= 16) { /* mov to DRn  */
2783 		dr -= 16;
2784 		err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
2785 	} else {
2786 		kvm_register_write(vcpu, reg, kvm_get_dr(vcpu, dr));
2787 	}
2788 
2789 	return kvm_complete_insn_gp(vcpu, err);
2790 }
2791 
2792 static int cr8_write_interception(struct kvm_vcpu *vcpu)
2793 {
2794 	u8 cr8_prev = kvm_get_cr8(vcpu);
2795 	int r;
2796 
2797 	WARN_ON_ONCE(kvm_vcpu_apicv_active(vcpu));
2798 
2799 	/* instruction emulation calls kvm_set_cr8() */
2800 	r = cr_interception(vcpu);
2801 	if (lapic_in_kernel(vcpu))
2802 		return r;
2803 	if (cr8_prev <= kvm_get_cr8(vcpu))
2804 		return r;
2805 	vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
2806 	return 0;
2807 }
2808 
2809 static int efer_trap(struct kvm_vcpu *vcpu)
2810 {
2811 	struct msr_data msr_info;
2812 	int ret;
2813 
2814 	/*
2815 	 * Clear the EFER_SVME bit from EFER. The SVM code always sets this
2816 	 * bit in svm_set_efer(), but __kvm_valid_efer() checks it against
2817 	 * whether the guest has X86_FEATURE_SVM - this avoids a failure if
2818 	 * the guest doesn't have X86_FEATURE_SVM.
2819 	 *
2820 	 * Clear EFER_LMSLE for a related reason: EFER writes are *trapped*,
2821 	 * not intercepted, i.e. hardware has already committed the write by
2822 	 * the time KVM gains control, and the trap is enabled if and only if
2823 	 * the guest is SEV-ES, whose EFER lives in the encrypted VMSA and so
2824 	 * can't be fixed up by KVM.  Rejecting EFER.LMSLE=1 would inject a #GP
2825 	 * *and* leave EFER.LMSLE set in the guest, which is strictly worse
2826 	 * than honoring a write that hardware itself allowed.
2827 	 */
2828 	msr_info.host_initiated = false;
2829 	msr_info.index = MSR_EFER;
2830 	msr_info.data = to_svm(vcpu)->vmcb->control.exit_info_1 &
2831 			~(EFER_SVME | EFER_LMSLE);
2832 	ret = kvm_set_msr_common(vcpu, &msr_info);
2833 
2834 	return kvm_complete_insn_gp(vcpu, ret);
2835 }
2836 
2837 static int svm_get_feature_msr(u32 msr, u64 *data)
2838 {
2839 	*data = 0;
2840 
2841 	switch (msr) {
2842 	case MSR_AMD64_DE_CFG:
2843 		if (cpu_feature_enabled(X86_FEATURE_LFENCE_RDTSC))
2844 			*data |= MSR_AMD64_DE_CFG_LFENCE_SERIALIZE;
2845 		break;
2846 	default:
2847 		return KVM_MSR_RET_UNSUPPORTED;
2848 	}
2849 
2850 	return 0;
2851 }
2852 
2853 static u64 *svm_vmcb_lbr(struct vcpu_svm *svm, u32 msr)
2854 {
2855 	switch (msr) {
2856 	case MSR_IA32_LASTBRANCHFROMIP:
2857 		return &svm->vmcb->save.br_from;
2858 	case MSR_IA32_LASTBRANCHTOIP:
2859 		return &svm->vmcb->save.br_to;
2860 	case MSR_IA32_LASTINTFROMIP:
2861 		return &svm->vmcb->save.last_excp_from;
2862 	case MSR_IA32_LASTINTTOIP:
2863 		return &svm->vmcb->save.last_excp_to;
2864 	default:
2865 		break;
2866 	}
2867 	KVM_BUG_ON(1, svm->vcpu.kvm);
2868 	return &svm->vmcb->save.br_from;
2869 }
2870 
2871 static bool sev_es_prevent_msr_access(struct kvm_vcpu *vcpu,
2872 				      struct msr_data *msr_info)
2873 {
2874 	return is_sev_es_guest(vcpu) && vcpu->arch.guest_state_protected &&
2875 	       msr_info->index != MSR_IA32_XSS &&
2876 	       !msr_write_intercepted(to_svm(vcpu), msr_info->index);
2877 }
2878 
2879 static bool svm_pat_accesses_gpat(struct kvm_vcpu *vcpu, bool from_host)
2880 {
2881 	/*
2882 	 * When KVM_X86_QUIRK_NESTED_SVM_SHARED_PAT is disabled and nested
2883 	 * NPT is enabled, L2 has a separate PAT from L1.  Guest accesses
2884 	 * to IA32_PAT while running L2 target L2's gPAT; host-initiated
2885 	 * accesses always target L1's hPAT so that KVM_GET/SET_MSRS and
2886 	 * KVM_GET/SET_NESTED_STATE are independent of each other and can
2887 	 * be ordered arbitrarily during save and restore.
2888 	 */
2889 	WARN_ON_ONCE(from_host && vcpu->wants_to_run);
2890 	return !from_host && is_guest_mode(vcpu) && l2_has_separate_pat(vcpu);
2891 }
2892 
2893 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2894 {
2895 	struct vcpu_svm *svm = to_svm(vcpu);
2896 
2897 	if (sev_es_prevent_msr_access(vcpu, msr_info)) {
2898 		msr_info->data = 0;
2899 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
2900 	}
2901 
2902 	switch (msr_info->index) {
2903 	case MSR_AMD64_TSC_RATIO:
2904 		if (!msr_info->host_initiated &&
2905 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_TSCRATEMSR))
2906 			return 1;
2907 		msr_info->data = svm->tsc_ratio_msr;
2908 		break;
2909 	case MSR_STAR:
2910 		msr_info->data = svm->vmcb01.ptr->save.star;
2911 		break;
2912 #ifdef CONFIG_X86_64
2913 	case MSR_LSTAR:
2914 		msr_info->data = svm->vmcb01.ptr->save.lstar;
2915 		break;
2916 	case MSR_CSTAR:
2917 		msr_info->data = svm->vmcb01.ptr->save.cstar;
2918 		break;
2919 	case MSR_GS_BASE:
2920 		msr_info->data = svm->vmcb01.ptr->save.gs.base;
2921 		break;
2922 	case MSR_FS_BASE:
2923 		msr_info->data = svm->vmcb01.ptr->save.fs.base;
2924 		break;
2925 	case MSR_KERNEL_GS_BASE:
2926 		msr_info->data = svm->vmcb01.ptr->save.kernel_gs_base;
2927 		break;
2928 	case MSR_SYSCALL_MASK:
2929 		msr_info->data = svm->vmcb01.ptr->save.sfmask;
2930 		break;
2931 #endif
2932 	case MSR_IA32_SYSENTER_CS:
2933 		msr_info->data = svm->vmcb01.ptr->save.sysenter_cs;
2934 		break;
2935 	case MSR_IA32_SYSENTER_EIP:
2936 		msr_info->data = (u32)svm->vmcb01.ptr->save.sysenter_eip;
2937 		if (guest_cpuid_is_intel_compatible(vcpu))
2938 			msr_info->data |= (u64)svm->sysenter_eip_hi << 32;
2939 		break;
2940 	case MSR_IA32_SYSENTER_ESP:
2941 		msr_info->data = svm->vmcb01.ptr->save.sysenter_esp;
2942 		if (guest_cpuid_is_intel_compatible(vcpu))
2943 			msr_info->data |= (u64)svm->sysenter_esp_hi << 32;
2944 		break;
2945 	case MSR_IA32_S_CET:
2946 		msr_info->data = svm->vmcb->save.s_cet;
2947 		break;
2948 	case MSR_IA32_INT_SSP_TAB:
2949 		msr_info->data = svm->vmcb->save.isst_addr;
2950 		break;
2951 	case MSR_KVM_INTERNAL_GUEST_SSP:
2952 		msr_info->data = svm->vmcb->save.ssp;
2953 		break;
2954 	case MSR_TSC_AUX:
2955 		msr_info->data = svm->tsc_aux;
2956 		break;
2957 	case MSR_IA32_DEBUGCTLMSR:
2958 		msr_info->data = lbrv ? svm->vmcb->save.dbgctl : 0;
2959 		break;
2960 	case MSR_IA32_LASTBRANCHFROMIP:
2961 	case MSR_IA32_LASTBRANCHTOIP:
2962 	case MSR_IA32_LASTINTFROMIP:
2963 	case MSR_IA32_LASTINTTOIP:
2964 		msr_info->data = lbrv ? *svm_vmcb_lbr(svm, msr_info->index) : 0;
2965 		break;
2966 	case MSR_VM_HSAVE_PA:
2967 		msr_info->data = svm->nested.hsave_msr;
2968 		break;
2969 	case MSR_VM_CR:
2970 		msr_info->data = svm->nested.vm_cr_msr;
2971 		break;
2972 	case MSR_IA32_SPEC_CTRL:
2973 		if (!msr_info->host_initiated &&
2974 		    !guest_has_spec_ctrl_msr(vcpu))
2975 			return 1;
2976 
2977 		if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2978 			msr_info->data = svm->vmcb->save.spec_ctrl;
2979 		else
2980 			msr_info->data = svm->spec_ctrl;
2981 		break;
2982 	case MSR_AMD64_VIRT_SPEC_CTRL:
2983 		if (!msr_info->host_initiated &&
2984 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_VIRT_SSBD))
2985 			return 1;
2986 
2987 		msr_info->data = svm->virt_spec_ctrl;
2988 		break;
2989 	case MSR_F15H_IC_CFG: {
2990 
2991 		int family, model;
2992 
2993 		family = guest_cpuid_family(vcpu);
2994 		model  = guest_cpuid_model(vcpu);
2995 
2996 		if (family < 0 || model < 0)
2997 			return kvm_get_msr_common(vcpu, msr_info);
2998 
2999 		msr_info->data = 0;
3000 
3001 		if (family == 0x15 &&
3002 		    (model >= 0x2 && model < 0x20))
3003 			msr_info->data = 0x1E;
3004 		}
3005 		break;
3006 	case MSR_AMD64_DE_CFG:
3007 		msr_info->data = svm->msr_decfg;
3008 		break;
3009 	case MSR_IA32_CR_PAT:
3010 		if (svm_pat_accesses_gpat(vcpu, msr_info->host_initiated)) {
3011 			msr_info->data = svm->vmcb->save.g_pat;
3012 			break;
3013 		}
3014 		return kvm_get_msr_common(vcpu, msr_info);
3015 	default:
3016 		return kvm_get_msr_common(vcpu, msr_info);
3017 	}
3018 	return 0;
3019 }
3020 
3021 static int svm_complete_emulated_msr(struct kvm_vcpu *vcpu, int err)
3022 {
3023 	struct vcpu_svm *svm = to_svm(vcpu);
3024 	if (!err || !is_sev_es_guest(vcpu) || WARN_ON_ONCE(!svm->sev_es.ghcb))
3025 		return kvm_complete_insn_gp(vcpu, err);
3026 
3027 	svm_vmgexit_inject_exception(svm, X86_TRAP_GP);
3028 	return 1;
3029 }
3030 
3031 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
3032 {
3033 	struct vcpu_svm *svm = to_svm(vcpu);
3034 	int svm_dis, chg_mask;
3035 
3036 	if (data & ~SVM_VM_CR_VALID_MASK)
3037 		return 1;
3038 
3039 	chg_mask = SVM_VM_CR_VALID_MASK;
3040 
3041 	if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
3042 		chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
3043 
3044 	svm->nested.vm_cr_msr &= ~chg_mask;
3045 	svm->nested.vm_cr_msr |= (data & chg_mask);
3046 
3047 	svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
3048 
3049 	/* check for svm_disable while efer.svme is set */
3050 	if (svm_dis && (vcpu->arch.efer & EFER_SVME))
3051 		return 1;
3052 
3053 	return 0;
3054 }
3055 
3056 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
3057 {
3058 	struct vcpu_svm *svm = to_svm(vcpu);
3059 	int ret = 0;
3060 
3061 	u32 ecx = msr->index;
3062 	u64 data = msr->data;
3063 
3064 	if (sev_es_prevent_msr_access(vcpu, msr))
3065 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
3066 
3067 	switch (ecx) {
3068 	case MSR_AMD64_TSC_RATIO:
3069 
3070 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_TSCRATEMSR)) {
3071 
3072 			if (!msr->host_initiated)
3073 				return 1;
3074 			/*
3075 			 * In case TSC scaling is not enabled, always
3076 			 * leave this MSR at the default value.
3077 			 *
3078 			 * Due to bug in qemu 6.2.0, it would try to set
3079 			 * this msr to 0 if tsc scaling is not enabled.
3080 			 * Ignore this value as well.
3081 			 */
3082 			if (data != 0 && data != svm->tsc_ratio_msr)
3083 				return 1;
3084 			break;
3085 		}
3086 
3087 		if (data & SVM_TSC_RATIO_RSVD)
3088 			return 1;
3089 
3090 		svm->tsc_ratio_msr = data;
3091 
3092 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_TSCRATEMSR) &&
3093 		    is_guest_mode(vcpu))
3094 			nested_svm_update_tsc_ratio_msr(vcpu);
3095 
3096 		break;
3097 	case MSR_IA32_CR_PAT:
3098 		if (svm_pat_accesses_gpat(vcpu, msr->host_initiated)) {
3099 			if (!kvm_pat_valid(data))
3100 				return 1;
3101 
3102 			vmcb_set_gpat(svm->vmcb, data);
3103 			break;
3104 		}
3105 
3106 		ret = kvm_set_msr_common(vcpu, msr);
3107 		if (ret)
3108 			break;
3109 
3110 		if (npt_enabled) {
3111 			vmcb_set_gpat(svm->vmcb01.ptr, data);
3112 			if (is_guest_mode(vcpu) && !l2_has_separate_pat(vcpu))
3113 				vmcb_set_gpat(svm->vmcb, data);
3114 		}
3115 		break;
3116 	case MSR_IA32_SPEC_CTRL:
3117 		if (!msr->host_initiated &&
3118 		    !guest_has_spec_ctrl_msr(vcpu))
3119 			return 1;
3120 
3121 		if (kvm_spec_ctrl_test_value(data))
3122 			return 1;
3123 
3124 		if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3125 			svm->vmcb->save.spec_ctrl = data;
3126 		else
3127 			svm->spec_ctrl = data;
3128 		if (!data)
3129 			break;
3130 
3131 		/*
3132 		 * For non-nested:
3133 		 * When it's written (to non-zero) for the first time, pass
3134 		 * it through.
3135 		 *
3136 		 * For nested:
3137 		 * The handling of the MSR bitmap for L2 guests is done in
3138 		 * nested_svm_merge_msrpm().
3139 		 * We update the L1 MSR bit as well since it will end up
3140 		 * touching the MSR anyway now.
3141 		 */
3142 		svm_disable_intercept_for_msr(vcpu, MSR_IA32_SPEC_CTRL, MSR_TYPE_RW);
3143 		break;
3144 	case MSR_AMD64_VIRT_SPEC_CTRL:
3145 		if (!msr->host_initiated &&
3146 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_VIRT_SSBD))
3147 			return 1;
3148 
3149 		if (data & ~SPEC_CTRL_SSBD)
3150 			return 1;
3151 
3152 		svm->virt_spec_ctrl = data;
3153 		break;
3154 	case MSR_STAR:
3155 		svm->vmcb01.ptr->save.star = data;
3156 		break;
3157 #ifdef CONFIG_X86_64
3158 	case MSR_LSTAR:
3159 		svm->vmcb01.ptr->save.lstar = data;
3160 		break;
3161 	case MSR_CSTAR:
3162 		svm->vmcb01.ptr->save.cstar = data;
3163 		break;
3164 	case MSR_GS_BASE:
3165 		svm->vmcb01.ptr->save.gs.base = data;
3166 		break;
3167 	case MSR_FS_BASE:
3168 		svm->vmcb01.ptr->save.fs.base = data;
3169 		break;
3170 	case MSR_KERNEL_GS_BASE:
3171 		svm->vmcb01.ptr->save.kernel_gs_base = data;
3172 		break;
3173 	case MSR_SYSCALL_MASK:
3174 		svm->vmcb01.ptr->save.sfmask = data;
3175 		break;
3176 #endif
3177 	case MSR_IA32_SYSENTER_CS:
3178 		svm->vmcb01.ptr->save.sysenter_cs = data;
3179 		break;
3180 	case MSR_IA32_SYSENTER_EIP:
3181 		svm->vmcb01.ptr->save.sysenter_eip = (u32)data;
3182 		/*
3183 		 * We only intercept the MSR_IA32_SYSENTER_{EIP|ESP} msrs
3184 		 * when we spoof an Intel vendor ID (for cross vendor migration).
3185 		 * In this case we use this intercept to track the high
3186 		 * 32 bit part of these msrs to support Intel's
3187 		 * implementation of SYSENTER/SYSEXIT.
3188 		 */
3189 		svm->sysenter_eip_hi = guest_cpuid_is_intel_compatible(vcpu) ? (data >> 32) : 0;
3190 		break;
3191 	case MSR_IA32_SYSENTER_ESP:
3192 		svm->vmcb01.ptr->save.sysenter_esp = (u32)data;
3193 		svm->sysenter_esp_hi = guest_cpuid_is_intel_compatible(vcpu) ? (data >> 32) : 0;
3194 		break;
3195 	case MSR_IA32_S_CET:
3196 		svm->vmcb->save.s_cet = data;
3197 		vmcb_mark_dirty(svm->vmcb01.ptr, VMCB_CET);
3198 		break;
3199 	case MSR_IA32_INT_SSP_TAB:
3200 		svm->vmcb->save.isst_addr = data;
3201 		vmcb_mark_dirty(svm->vmcb01.ptr, VMCB_CET);
3202 		break;
3203 	case MSR_KVM_INTERNAL_GUEST_SSP:
3204 		svm->vmcb->save.ssp = data;
3205 		vmcb_mark_dirty(svm->vmcb01.ptr, VMCB_CET);
3206 		break;
3207 	case MSR_TSC_AUX:
3208 		/*
3209 		 * TSC_AUX is always virtualized for SEV-ES guests when the
3210 		 * feature is available. The user return MSR support is not
3211 		 * required in this case because TSC_AUX is restored on #VMEXIT
3212 		 * from the host save area.
3213 		 */
3214 		if (boot_cpu_has(X86_FEATURE_V_TSC_AUX) && is_sev_es_guest(vcpu))
3215 			break;
3216 
3217 		/*
3218 		 * TSC_AUX is usually changed only during boot and never read
3219 		 * directly.  Intercept TSC_AUX and switch it via user return.
3220 		 */
3221 		preempt_disable();
3222 		ret = kvm_set_user_return_msr(tsc_aux_uret_slot, data, -1ull);
3223 		preempt_enable();
3224 		if (ret)
3225 			break;
3226 
3227 		svm->tsc_aux = data;
3228 		break;
3229 	case MSR_IA32_DEBUGCTLMSR:
3230 		if (!lbrv) {
3231 			kvm_pr_unimpl_wrmsr(vcpu, ecx, data);
3232 			break;
3233 		}
3234 
3235 		/*
3236 		 * Suppress BTF as KVM doesn't virtualize BTF, but there's no
3237 		 * way to communicate lack of support to the guest.
3238 		 */
3239 		if (data & DEBUGCTLMSR_BTF) {
3240 			kvm_pr_unimpl_wrmsr(vcpu, MSR_IA32_DEBUGCTLMSR, data);
3241 			data &= ~DEBUGCTLMSR_BTF;
3242 		}
3243 
3244 		if (data & ~svm_get_supported_debugctl(vcpu))
3245 			return 1;
3246 
3247 		if (svm->vmcb->save.dbgctl == data)
3248 			break;
3249 
3250 		svm->vmcb->save.dbgctl = data;
3251 		vmcb_mark_dirty(svm->vmcb, VMCB_LBR);
3252 		svm_update_lbrv(vcpu);
3253 		break;
3254 	case MSR_IA32_LASTBRANCHFROMIP:
3255 	case MSR_IA32_LASTBRANCHTOIP:
3256 	case MSR_IA32_LASTINTFROMIP:
3257 	case MSR_IA32_LASTINTTOIP:
3258 		if (!lbrv)
3259 			return KVM_MSR_RET_UNSUPPORTED;
3260 		if (!msr->host_initiated)
3261 			return 1;
3262 		*svm_vmcb_lbr(svm, ecx) = data;
3263 		vmcb_mark_dirty(svm->vmcb, VMCB_LBR);
3264 		break;
3265 	case MSR_VM_HSAVE_PA:
3266 		/*
3267 		 * Old kernels did not validate the value written to
3268 		 * MSR_VM_HSAVE_PA.  Allow KVM_SET_MSR to set an invalid
3269 		 * value to allow live migrating buggy or malicious guests
3270 		 * originating from those kernels.
3271 		 */
3272 		if (!msr->host_initiated && !page_address_valid(vcpu, data))
3273 			return 1;
3274 
3275 		svm->nested.hsave_msr = data & PAGE_MASK;
3276 		break;
3277 	case MSR_VM_CR:
3278 		return svm_set_vm_cr(vcpu, data);
3279 	case MSR_VM_IGNNE:
3280 		kvm_pr_unimpl_wrmsr(vcpu, ecx, data);
3281 		break;
3282 	case MSR_AMD64_DE_CFG: {
3283 		u64 supported_de_cfg;
3284 
3285 		if (svm_get_feature_msr(ecx, &supported_de_cfg))
3286 			return 1;
3287 
3288 		if (data & ~supported_de_cfg)
3289 			return 1;
3290 
3291 		svm->msr_decfg = data;
3292 		break;
3293 	}
3294 	default:
3295 		return kvm_set_msr_common(vcpu, msr);
3296 	}
3297 	return ret;
3298 }
3299 
3300 static int msr_interception(struct kvm_vcpu *vcpu)
3301 {
3302 	if (to_svm(vcpu)->vmcb->control.exit_info_1)
3303 		return kvm_emulate_wrmsr(vcpu);
3304 	else
3305 		return kvm_emulate_rdmsr(vcpu);
3306 }
3307 
3308 static int interrupt_window_interception(struct kvm_vcpu *vcpu)
3309 {
3310 	kvm_make_request(KVM_REQ_EVENT, vcpu);
3311 	svm_clear_vintr(to_svm(vcpu));
3312 
3313 	++vcpu->stat.irq_window_exits;
3314 	return 1;
3315 }
3316 
3317 static int pause_interception(struct kvm_vcpu *vcpu)
3318 {
3319 	bool in_kernel;
3320 	/*
3321 	 * CPL is not made available for an SEV-ES guest, therefore
3322 	 * vcpu->arch.preempted_in_kernel can never be true.  Just
3323 	 * set in_kernel to false as well.
3324 	 */
3325 	in_kernel = !is_sev_es_guest(vcpu) && svm_get_cpl(vcpu) == 0;
3326 
3327 	grow_ple_window(vcpu);
3328 
3329 	kvm_vcpu_on_spin(vcpu, in_kernel);
3330 	return kvm_skip_emulated_instruction(vcpu);
3331 }
3332 
3333 static int invpcid_interception(struct kvm_vcpu *vcpu)
3334 {
3335 	struct vcpu_svm *svm = to_svm(vcpu);
3336 	unsigned long type;
3337 	gva_t gva;
3338 
3339 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_INVPCID)) {
3340 		kvm_queue_exception(vcpu, UD_VECTOR);
3341 		return 1;
3342 	}
3343 
3344 	/*
3345 	 * For an INVPCID intercept:
3346 	 * EXITINFO1 provides the linear address of the memory operand.
3347 	 * EXITINFO2 provides the contents of the register operand.
3348 	 */
3349 	type = svm->vmcb->control.exit_info_2;
3350 	gva = svm->vmcb->control.exit_info_1;
3351 
3352 	/*
3353 	 * FIXME: Perform segment checks for 32-bit mode, and inject #SS if the
3354 	 *        stack segment is used.  The intercept takes priority over all
3355 	 *        #GP checks except CPL>0, but somehow still generates a linear
3356 	 *        address?  The APM is sorely lacking.
3357 	 */
3358 	if (is_noncanonical_address(gva, vcpu, 0)) {
3359 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
3360 		return 1;
3361 	}
3362 
3363 	return kvm_handle_invpcid(vcpu, type, gva);
3364 }
3365 
3366 static inline int complete_userspace_buslock(struct kvm_vcpu *vcpu)
3367 {
3368 	struct vcpu_svm *svm = to_svm(vcpu);
3369 
3370 	/*
3371 	 * If userspace has NOT changed RIP, then KVM's ABI is to let the guest
3372 	 * execute the bus-locking instruction.  Set the bus lock counter to '1'
3373 	 * to effectively step past the bus lock.
3374 	 */
3375 	if (kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip))
3376 		svm->vmcb->control.bus_lock_counter = 1;
3377 
3378 	return 1;
3379 }
3380 
3381 static int bus_lock_exit(struct kvm_vcpu *vcpu)
3382 {
3383 	struct vcpu_svm *svm = to_svm(vcpu);
3384 
3385 	vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
3386 	vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
3387 
3388 	vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
3389 	vcpu->arch.complete_userspace_io = complete_userspace_buslock;
3390 
3391 	if (is_guest_mode(vcpu))
3392 		svm->nested.last_bus_lock_rip = vcpu->arch.cui_linear_rip;
3393 
3394 	return 0;
3395 }
3396 
3397 static int vmmcall_interception(struct kvm_vcpu *vcpu)
3398 {
3399 	/*
3400 	 * Inject a #UD if L2 is active and the VMMCALL isn't a Hyper-V TLB
3401 	 * hypercall, as VMMCALL #UDs if it's not intercepted, and this path is
3402 	 * reachable if and only if L1 doesn't want to intercept VMMCALL or has
3403 	 * enabled L0 (KVM) handling of Hyper-V L2 TLB flush hypercalls.
3404 	 */
3405 	if (is_guest_mode(vcpu) && !nested_svm_is_l2_tlb_flush_hcall(vcpu)) {
3406 		kvm_queue_exception(vcpu, UD_VECTOR);
3407 		return 1;
3408 	}
3409 
3410 	return kvm_emulate_hypercall(vcpu);
3411 }
3412 
3413 static void svm_update_cpu_dirty_logging(struct kvm_vcpu *vcpu, bool enable)
3414 {
3415 	struct vcpu_svm *svm = to_svm(vcpu);
3416 	struct vmcb *vmcb01 = svm->vmcb01.ptr;
3417 
3418 	if (enable)
3419 		vmcb01->control.misc_ctl |= SVM_MISC_ENABLE_PML;
3420 	else
3421 		vmcb01->control.misc_ctl &= ~SVM_MISC_ENABLE_PML;
3422 
3423 	vmcb_mark_dirty(vmcb01, VMCB_NPT);
3424 }
3425 
3426 static void svm_flush_pml_buffer(struct kvm_vcpu *vcpu)
3427 {
3428 	struct vcpu_svm *svm = to_svm(vcpu);
3429 	struct vmcb_control_area *control = &svm->vmcb->control;
3430 
3431 	/* Do nothing if PML buffer is empty */
3432 	if (control->pml_index == PML_HEAD_INDEX)
3433 		return;
3434 
3435 	kvm_flush_pml_buffer(vcpu, control->pml_index);
3436 
3437 	/* Reset the PML index */
3438 	control->pml_index = PML_HEAD_INDEX;
3439 }
3440 
3441 static int pml_full_interception(struct kvm_vcpu *vcpu)
3442 {
3443 	trace_kvm_pml_full(vcpu->vcpu_id);
3444 
3445 	/*
3446 	 * PML buffer is already flushed at the beginning of svm_handle_exit().
3447 	 * Nothing to do here.
3448 	 */
3449 	return 1;
3450 }
3451 
3452 static int (*const svm_exit_handlers[])(struct kvm_vcpu *vcpu) = {
3453 	[SVM_EXIT_READ_CR0]			= cr_interception,
3454 	[SVM_EXIT_READ_CR3]			= cr_interception,
3455 	[SVM_EXIT_READ_CR4]			= cr_interception,
3456 	[SVM_EXIT_READ_CR8]			= cr_interception,
3457 	[SVM_EXIT_CR0_SEL_WRITE]		= cr_interception,
3458 	[SVM_EXIT_WRITE_CR0]			= cr_interception,
3459 	[SVM_EXIT_WRITE_CR3]			= cr_interception,
3460 	[SVM_EXIT_WRITE_CR4]			= cr_interception,
3461 	[SVM_EXIT_WRITE_CR8]			= cr8_write_interception,
3462 	[SVM_EXIT_READ_DR0]			= dr_interception,
3463 	[SVM_EXIT_READ_DR1]			= dr_interception,
3464 	[SVM_EXIT_READ_DR2]			= dr_interception,
3465 	[SVM_EXIT_READ_DR3]			= dr_interception,
3466 	[SVM_EXIT_READ_DR4]			= dr_interception,
3467 	[SVM_EXIT_READ_DR5]			= dr_interception,
3468 	[SVM_EXIT_READ_DR6]			= dr_interception,
3469 	[SVM_EXIT_READ_DR7]			= dr_interception,
3470 	[SVM_EXIT_WRITE_DR0]			= dr_interception,
3471 	[SVM_EXIT_WRITE_DR1]			= dr_interception,
3472 	[SVM_EXIT_WRITE_DR2]			= dr_interception,
3473 	[SVM_EXIT_WRITE_DR3]			= dr_interception,
3474 	[SVM_EXIT_WRITE_DR4]			= dr_interception,
3475 	[SVM_EXIT_WRITE_DR5]			= dr_interception,
3476 	[SVM_EXIT_WRITE_DR6]			= dr_interception,
3477 	[SVM_EXIT_WRITE_DR7]			= dr_interception,
3478 	[SVM_EXIT_EXCP_BASE + DB_VECTOR]	= db_interception,
3479 	[SVM_EXIT_EXCP_BASE + BP_VECTOR]	= bp_interception,
3480 	[SVM_EXIT_EXCP_BASE + UD_VECTOR]	= ud_interception,
3481 	[SVM_EXIT_EXCP_BASE + PF_VECTOR]	= pf_interception,
3482 	[SVM_EXIT_EXCP_BASE + MC_VECTOR]	= mc_interception,
3483 	[SVM_EXIT_EXCP_BASE + AC_VECTOR]	= ac_interception,
3484 	[SVM_EXIT_EXCP_BASE + GP_VECTOR]	= gp_interception,
3485 	[SVM_EXIT_INTR]				= intr_interception,
3486 	[SVM_EXIT_NMI]				= nmi_interception,
3487 	[SVM_EXIT_SMI]				= smi_interception,
3488 	[SVM_EXIT_VINTR]			= interrupt_window_interception,
3489 	[SVM_EXIT_RDPMC]			= kvm_emulate_rdpmc,
3490 	[SVM_EXIT_CPUID]			= kvm_emulate_cpuid,
3491 	[SVM_EXIT_IRET]                         = iret_interception,
3492 	[SVM_EXIT_INVD]                         = kvm_emulate_invd,
3493 	[SVM_EXIT_PAUSE]			= pause_interception,
3494 	[SVM_EXIT_HLT]				= kvm_emulate_halt,
3495 	[SVM_EXIT_INVLPG]			= invlpg_interception,
3496 	[SVM_EXIT_INVLPGA]			= invlpga_interception,
3497 	[SVM_EXIT_IOIO]				= io_interception,
3498 	[SVM_EXIT_MSR]				= msr_interception,
3499 	[SVM_EXIT_TASK_SWITCH]			= task_switch_interception,
3500 	[SVM_EXIT_SHUTDOWN]			= shutdown_interception,
3501 	[SVM_EXIT_VMRUN]			= vmrun_interception,
3502 	[SVM_EXIT_VMMCALL]			= vmmcall_interception,
3503 	[SVM_EXIT_VMLOAD]			= vmload_interception,
3504 	[SVM_EXIT_VMSAVE]			= vmsave_interception,
3505 	[SVM_EXIT_STGI]				= stgi_interception,
3506 	[SVM_EXIT_CLGI]				= clgi_interception,
3507 	[SVM_EXIT_SKINIT]			= skinit_interception,
3508 	[SVM_EXIT_RDTSCP]			= kvm_handle_invalid_op,
3509 	[SVM_EXIT_WBINVD]                       = kvm_emulate_wbinvd,
3510 	[SVM_EXIT_MONITOR]			= kvm_emulate_monitor,
3511 	[SVM_EXIT_MWAIT]			= kvm_emulate_mwait,
3512 	[SVM_EXIT_XSETBV]			= kvm_emulate_xsetbv,
3513 	[SVM_EXIT_ICEBP]			= icebp_interception,
3514 	[SVM_EXIT_RDPRU]			= kvm_handle_invalid_op,
3515 	[SVM_EXIT_EFER_WRITE_TRAP]		= efer_trap,
3516 	[SVM_EXIT_CR0_WRITE_TRAP]		= cr_trap,
3517 	[SVM_EXIT_CR4_WRITE_TRAP]		= cr_trap,
3518 	[SVM_EXIT_CR8_WRITE_TRAP]		= cr_trap,
3519 	[SVM_EXIT_INVPCID]                      = invpcid_interception,
3520 	[SVM_EXIT_IDLE_HLT]			= kvm_emulate_halt,
3521 	[SVM_EXIT_NPF]				= npf_interception,
3522 	[SVM_EXIT_BUS_LOCK]			= bus_lock_exit,
3523 	[SVM_EXIT_RSM]                          = rsm_interception,
3524 	[SVM_EXIT_AVIC_INCOMPLETE_IPI]		= avic_incomplete_ipi_interception,
3525 	[SVM_EXIT_AVIC_UNACCELERATED_ACCESS]	= avic_unaccelerated_access_interception,
3526 #ifdef CONFIG_KVM_AMD_SEV
3527 	[SVM_EXIT_VMGEXIT]			= sev_handle_vmgexit,
3528 #endif
3529 	[SVM_EXIT_PML_FULL]			= pml_full_interception,
3530 };
3531 
3532 static void dump_vmcb(struct kvm_vcpu *vcpu)
3533 {
3534 	struct vcpu_svm *svm = to_svm(vcpu);
3535 	struct vmcb_control_area *control = &svm->vmcb->control;
3536 	struct vmcb_save_area *save = &svm->vmcb->save;
3537 	struct vmcb_save_area *save01 = &svm->vmcb01.ptr->save;
3538 	char *vm_type;
3539 
3540 	if (!dump_invalid_vmcb) {
3541 		pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
3542 		return;
3543 	}
3544 
3545 	guard(mutex)(&vmcb_dump_mutex);
3546 
3547 	vm_type = is_sev_snp_guest(vcpu) ? "SEV-SNP" :
3548 		  is_sev_es_guest(vcpu) ? "SEV-ES" :
3549 		  is_sev_guest(vcpu) ? "SEV" : "SVM";
3550 
3551 	pr_err("%s vCPU%u VMCB %p, last attempted VMRUN on CPU %d\n",
3552 	       vm_type, vcpu->vcpu_id, svm->current_vmcb->ptr, vcpu->arch.last_vmentry_cpu);
3553 	pr_err("VMCB Control Area:\n");
3554 	pr_err("%-20s%04x\n", "cr_read:", control->intercepts[INTERCEPT_CR] & 0xffff);
3555 	pr_err("%-20s%04x\n", "cr_write:", control->intercepts[INTERCEPT_CR] >> 16);
3556 	pr_err("%-20s%04x\n", "dr_read:", control->intercepts[INTERCEPT_DR] & 0xffff);
3557 	pr_err("%-20s%04x\n", "dr_write:", control->intercepts[INTERCEPT_DR] >> 16);
3558 	pr_err("%-20s%08x\n", "exceptions:", control->intercepts[INTERCEPT_EXCEPTION]);
3559 	pr_err("%-20s%08x %08x\n", "intercepts:",
3560               control->intercepts[INTERCEPT_WORD3],
3561 	       control->intercepts[INTERCEPT_WORD4]);
3562 	pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
3563 	pr_err("%-20s%d\n", "pause filter threshold:",
3564 	       control->pause_filter_thresh);
3565 	pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
3566 	pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
3567 	pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
3568 	pr_err("%-20s%d\n", "asid:", control->asid);
3569 	pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
3570 	pr_err("%-20s%d\n", "erap_ctl:", control->erap_ctl);
3571 	pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
3572 	pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
3573 	pr_err("%-20s%08x\n", "int_state:", control->int_state);
3574 	pr_err("%-20s%016llx\n", "exit_code:", control->exit_code);
3575 	pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
3576 	pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
3577 	pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
3578 	pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
3579 	pr_err("%-20s%llx\n", "misc_ctl:", control->misc_ctl);
3580 	pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
3581 
3582 	if (pml) {
3583 		pr_err("%-20s%016llx\n", "pml_addr:", control->pml_addr);
3584 		pr_err("%-20s%04x\n", "pml_index:", control->pml_index);
3585 	}
3586 
3587 	pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
3588 	pr_err("%-20s%016llx\n", "ghcb:", control->ghcb_gpa);
3589 	pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
3590 	pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
3591 	pr_err("%-20s%lld\n", "misc_ctl2:", control->misc_ctl2);
3592 	pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
3593 	pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
3594 	pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
3595 	pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
3596 	pr_err("%-20s%016llx\n", "vmsa_pa:", control->vmsa_pa);
3597 	pr_err("%-20s%016llx\n", "allowed_sev_features:", control->allowed_sev_features);
3598 	pr_err("%-20s%016llx\n", "guest_sev_features:", control->guest_sev_features);
3599 
3600 	if (is_sev_es_guest(vcpu)) {
3601 		save = sev_decrypt_vmsa(vcpu);
3602 		if (!save)
3603 			goto no_vmsa;
3604 
3605 		save01 = save;
3606 	}
3607 
3608 	pr_err("VMCB State Save Area:\n");
3609 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3610 	       "es:",
3611 	       save->es.selector, save->es.attrib,
3612 	       save->es.limit, save->es.base);
3613 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3614 	       "cs:",
3615 	       save->cs.selector, save->cs.attrib,
3616 	       save->cs.limit, save->cs.base);
3617 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3618 	       "ss:",
3619 	       save->ss.selector, save->ss.attrib,
3620 	       save->ss.limit, save->ss.base);
3621 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3622 	       "ds:",
3623 	       save->ds.selector, save->ds.attrib,
3624 	       save->ds.limit, save->ds.base);
3625 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3626 	       "fs:",
3627 	       save01->fs.selector, save01->fs.attrib,
3628 	       save01->fs.limit, save01->fs.base);
3629 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3630 	       "gs:",
3631 	       save01->gs.selector, save01->gs.attrib,
3632 	       save01->gs.limit, save01->gs.base);
3633 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3634 	       "gdtr:",
3635 	       save->gdtr.selector, save->gdtr.attrib,
3636 	       save->gdtr.limit, save->gdtr.base);
3637 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3638 	       "ldtr:",
3639 	       save01->ldtr.selector, save01->ldtr.attrib,
3640 	       save01->ldtr.limit, save01->ldtr.base);
3641 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3642 	       "idtr:",
3643 	       save->idtr.selector, save->idtr.attrib,
3644 	       save->idtr.limit, save->idtr.base);
3645 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3646 	       "tr:",
3647 	       save01->tr.selector, save01->tr.attrib,
3648 	       save01->tr.limit, save01->tr.base);
3649 	pr_err("vmpl: %d   cpl:  %d               efer:          %016llx\n",
3650 	       save->vmpl, save->cpl, save->efer);
3651 	pr_err("%-15s %016llx %-13s %016llx\n",
3652 	       "cr0:", save->cr0, "cr2:", save->cr2);
3653 	pr_err("%-15s %016llx %-13s %016llx\n",
3654 	       "cr3:", save->cr3, "cr4:", save->cr4);
3655 	pr_err("%-15s %016llx %-13s %016llx\n",
3656 	       "dr6:", save->dr6, "dr7:", save->dr7);
3657 	pr_err("%-15s %016llx %-13s %016llx\n",
3658 	       "rip:", save->rip, "rflags:", save->rflags);
3659 	pr_err("%-15s %016llx %-13s %016llx\n",
3660 	       "rsp:", save->rsp, "rax:", save->rax);
3661 	pr_err("%-15s %016llx %-13s %016llx\n",
3662 	       "s_cet:", save->s_cet, "ssp:", save->ssp);
3663 	pr_err("%-15s %016llx\n",
3664 	       "isst_addr:", save->isst_addr);
3665 	pr_err("%-15s %016llx %-13s %016llx\n",
3666 	       "star:", save01->star, "lstar:", save01->lstar);
3667 	pr_err("%-15s %016llx %-13s %016llx\n",
3668 	       "cstar:", save01->cstar, "sfmask:", save01->sfmask);
3669 	pr_err("%-15s %016llx %-13s %016llx\n",
3670 	       "kernel_gs_base:", save01->kernel_gs_base,
3671 	       "sysenter_cs:", save01->sysenter_cs);
3672 	pr_err("%-15s %016llx %-13s %016llx\n",
3673 	       "sysenter_esp:", save01->sysenter_esp,
3674 	       "sysenter_eip:", save01->sysenter_eip);
3675 	pr_err("%-15s %016llx %-13s %016llx\n",
3676 	       "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
3677 	pr_err("%-15s %016llx %-13s %016llx\n",
3678 	       "br_from:", save->br_from, "br_to:", save->br_to);
3679 	pr_err("%-15s %016llx %-13s %016llx\n",
3680 	       "excp_from:", save->last_excp_from,
3681 	       "excp_to:", save->last_excp_to);
3682 
3683 	if (is_sev_es_guest(vcpu)) {
3684 		struct sev_es_save_area *vmsa = (struct sev_es_save_area *)save;
3685 
3686 		pr_err("%-15s %016llx\n",
3687 		       "sev_features", vmsa->sev_features);
3688 
3689 		pr_err("%-15s %016llx %-13s %016llx\n",
3690 		       "pl0_ssp:", vmsa->pl0_ssp, "pl1_ssp:", vmsa->pl1_ssp);
3691 		pr_err("%-15s %016llx %-13s %016llx\n",
3692 		       "pl2_ssp:", vmsa->pl2_ssp, "pl3_ssp:", vmsa->pl3_ssp);
3693 		pr_err("%-15s %016llx\n",
3694 		       "u_cet:", vmsa->u_cet);
3695 
3696 		pr_err("%-15s %016llx %-13s %016llx\n",
3697 		       "rax:", vmsa->rax, "rbx:", vmsa->rbx);
3698 		pr_err("%-15s %016llx %-13s %016llx\n",
3699 		       "rcx:", vmsa->rcx, "rdx:", vmsa->rdx);
3700 		pr_err("%-15s %016llx %-13s %016llx\n",
3701 		       "rsi:", vmsa->rsi, "rdi:", vmsa->rdi);
3702 		pr_err("%-15s %016llx %-13s %016llx\n",
3703 		       "rbp:", vmsa->rbp, "rsp:", vmsa->rsp);
3704 		pr_err("%-15s %016llx %-13s %016llx\n",
3705 		       "r8:", vmsa->r8, "r9:", vmsa->r9);
3706 		pr_err("%-15s %016llx %-13s %016llx\n",
3707 		       "r10:", vmsa->r10, "r11:", vmsa->r11);
3708 		pr_err("%-15s %016llx %-13s %016llx\n",
3709 		       "r12:", vmsa->r12, "r13:", vmsa->r13);
3710 		pr_err("%-15s %016llx %-13s %016llx\n",
3711 		       "r14:", vmsa->r14, "r15:", vmsa->r15);
3712 		pr_err("%-15s %016llx %-13s %016llx\n",
3713 		       "xcr0:", vmsa->xcr0, "xss:", vmsa->xss);
3714 	} else {
3715 		pr_err("%-15s %016llx %-13s %016lx\n",
3716 		       "rax:", save->rax, "rbx:",
3717 		       vcpu->arch.regs[VCPU_REGS_RBX]);
3718 		pr_err("%-15s %016lx %-13s %016lx\n",
3719 		       "rcx:", vcpu->arch.regs[VCPU_REGS_RCX],
3720 		       "rdx:", vcpu->arch.regs[VCPU_REGS_RDX]);
3721 		pr_err("%-15s %016lx %-13s %016lx\n",
3722 		       "rsi:", vcpu->arch.regs[VCPU_REGS_RSI],
3723 		       "rdi:", vcpu->arch.regs[VCPU_REGS_RDI]);
3724 		pr_err("%-15s %016lx %-13s %016llx\n",
3725 		       "rbp:", vcpu->arch.regs[VCPU_REGS_RBP],
3726 		       "rsp:", save->rsp);
3727 #ifdef CONFIG_X86_64
3728 		pr_err("%-15s %016lx %-13s %016lx\n",
3729 		       "r8:", vcpu->arch.regs[VCPU_REGS_R8],
3730 		       "r9:", vcpu->arch.regs[VCPU_REGS_R9]);
3731 		pr_err("%-15s %016lx %-13s %016lx\n",
3732 		       "r10:", vcpu->arch.regs[VCPU_REGS_R10],
3733 		       "r11:", vcpu->arch.regs[VCPU_REGS_R11]);
3734 		pr_err("%-15s %016lx %-13s %016lx\n",
3735 		       "r12:", vcpu->arch.regs[VCPU_REGS_R12],
3736 		       "r13:", vcpu->arch.regs[VCPU_REGS_R13]);
3737 		pr_err("%-15s %016lx %-13s %016lx\n",
3738 		       "r14:", vcpu->arch.regs[VCPU_REGS_R14],
3739 		       "r15:", vcpu->arch.regs[VCPU_REGS_R15]);
3740 #endif
3741 	}
3742 
3743 no_vmsa:
3744 	if (is_sev_es_guest(vcpu))
3745 		sev_free_decrypted_vmsa(vcpu, save);
3746 }
3747 
3748 int svm_invoke_exit_handler(struct kvm_vcpu *vcpu, u64 __exit_code)
3749 {
3750 	u32 exit_code = __exit_code;
3751 
3752 	/*
3753 	 * SVM uses negative values, i.e. 64-bit values, to indicate that VMRUN
3754 	 * failed.  Report all such errors to userspace (note, VMEXIT_INVALID,
3755 	 * a.k.a. SVM_EXIT_ERR, is special cased by svm_handle_exit()).  Skip
3756 	 * the check when running as a VM, as KVM has historically left garbage
3757 	 * in bits 63:32, i.e. running KVM-on-KVM would hit false positives if
3758 	 * the underlying kernel is buggy.
3759 	 */
3760 	if (!cpu_feature_enabled(X86_FEATURE_HYPERVISOR) &&
3761 	    (u64)exit_code != __exit_code)
3762 		goto unexpected_vmexit;
3763 
3764 	/*
3765 	 * PML is never enabled when running L2, bail immediately if a PML full
3766 	 * exit occurs as something is horribly wrong.
3767 	 */
3768 	if (unlikely(is_guest_mode(vcpu) && exit_code == SVM_EXIT_PML_FULL))
3769 		goto unexpected_vmexit;
3770 
3771 #ifdef CONFIG_MITIGATION_RETPOLINE
3772 	if (exit_code == SVM_EXIT_MSR)
3773 		return msr_interception(vcpu);
3774 	else if (exit_code == SVM_EXIT_VINTR)
3775 		return interrupt_window_interception(vcpu);
3776 	else if (exit_code == SVM_EXIT_INTR)
3777 		return intr_interception(vcpu);
3778 	else if (exit_code == SVM_EXIT_HLT || exit_code == SVM_EXIT_IDLE_HLT)
3779 		return kvm_emulate_halt(vcpu);
3780 	else if (exit_code == SVM_EXIT_NPF)
3781 		return npf_interception(vcpu);
3782 #ifdef CONFIG_KVM_AMD_SEV
3783 	else if (exit_code == SVM_EXIT_VMGEXIT)
3784 		return sev_handle_vmgexit(vcpu);
3785 #endif
3786 #endif
3787 	if (exit_code >= ARRAY_SIZE(svm_exit_handlers))
3788 		goto unexpected_vmexit;
3789 
3790 	exit_code = array_index_nospec(exit_code, ARRAY_SIZE(svm_exit_handlers));
3791 	if (!svm_exit_handlers[exit_code])
3792 		goto unexpected_vmexit;
3793 
3794 	return svm_exit_handlers[exit_code](vcpu);
3795 
3796 unexpected_vmexit:
3797 	dump_vmcb(vcpu);
3798 	kvm_prepare_unexpected_reason_exit(vcpu, __exit_code);
3799 	return 0;
3800 }
3801 
3802 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
3803 			      u64 *info1, u64 *info2,
3804 			      u32 *intr_info, u32 *error_code)
3805 {
3806 	struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3807 
3808 	*reason = control->exit_code;
3809 	*info1 = control->exit_info_1;
3810 	*info2 = control->exit_info_2;
3811 	*intr_info = control->exit_int_info;
3812 	if ((*intr_info & SVM_EXITINTINFO_VALID) &&
3813 	    (*intr_info & SVM_EXITINTINFO_VALID_ERR))
3814 		*error_code = control->exit_int_info_err;
3815 	else
3816 		*error_code = 0;
3817 }
3818 
3819 static void svm_get_entry_info(struct kvm_vcpu *vcpu, u32 *intr_info,
3820 			       u32 *error_code)
3821 {
3822 	struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3823 
3824 	*intr_info = control->event_inj;
3825 
3826 	if ((*intr_info & SVM_EXITINTINFO_VALID) &&
3827 	    (*intr_info & SVM_EXITINTINFO_VALID_ERR))
3828 		*error_code = control->event_inj_err;
3829 	else
3830 		*error_code = 0;
3831 
3832 }
3833 
3834 static int svm_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
3835 {
3836 	struct vcpu_svm *svm = to_svm(vcpu);
3837 	struct kvm_run *kvm_run = vcpu->run;
3838 
3839 	/*
3840 	 * Opportunistically flush the PML buffer on VM exit. This keeps the
3841 	 * dirty bitmap current by processing logged GPAs rather than waiting for
3842 	 * PML_FULL exit.
3843 	 */
3844 	if (vcpu->kvm->arch.cpu_dirty_log_size && !is_guest_mode(vcpu))
3845 		svm_flush_pml_buffer(vcpu);
3846 
3847 	if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
3848 		return 0;
3849 
3850 	if (is_guest_mode(vcpu)) {
3851 		int vmexit;
3852 
3853 		trace_kvm_nested_vmexit(vcpu, KVM_ISA_SVM);
3854 
3855 		vmexit = nested_svm_exit_special(svm);
3856 
3857 		if (vmexit == NESTED_EXIT_CONTINUE)
3858 			vmexit = nested_svm_exit_handled(svm);
3859 
3860 		if (vmexit == NESTED_EXIT_DONE)
3861 			return 1;
3862 	}
3863 
3864 	if (svm_is_vmrun_failure(svm->vmcb->control.exit_code)) {
3865 		kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3866 		kvm_run->fail_entry.hardware_entry_failure_reason
3867 			= svm->vmcb->control.exit_code;
3868 		kvm_run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
3869 		dump_vmcb(vcpu);
3870 		return 0;
3871 	}
3872 
3873 	if (exit_fastpath != EXIT_FASTPATH_NONE)
3874 		return 1;
3875 
3876 	return svm_invoke_exit_handler(vcpu, svm->vmcb->control.exit_code);
3877 }
3878 
3879 static void svm_set_nested_run_soft_int_state(struct kvm_vcpu *vcpu)
3880 {
3881 	struct vcpu_svm *svm = to_svm(vcpu);
3882 
3883 	svm->soft_int_csbase = svm->vmcb->save.cs.base;
3884 	svm->soft_int_old_rip = kvm_rip_read(vcpu);
3885 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_NRIPS))
3886 		svm->soft_int_next_rip = kvm_rip_read(vcpu);
3887 }
3888 
3889 static int pre_svm_run(struct kvm_vcpu *vcpu)
3890 {
3891 	struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, vcpu->cpu);
3892 	struct vcpu_svm *svm = to_svm(vcpu);
3893 
3894 	/*
3895 	 * If the previous VMRUN of the VMCB occurred on a different physical
3896 	 * cpu, mark the VMCB dirty and reset the ASID generation, as hardware's
3897 	 * clean bits and ASIDs are per pCPU.
3898 	 *
3899 	 * Reset the ASID generation in both VMCBs. This will lead to assigning
3900 	 * a new ASID now, and then again when switching to the other VMCB.
3901 	 * However, this is needed as the ASID is shared between the VMCBs, and
3902 	 * otherwise it would be possible to use an ASID allocated on one pCPU
3903 	 * on another, for example:
3904 	 * - vCPU migrates from pCPU A to pCPU B, allocates a new ASID.
3905 	 * - vCPU migrates back to pCPU A, and then switches the VMCB.
3906 	 * - The new VMCB does not detect a pCPU change and runs on pCPU A with
3907 	 *   the new ASID allocated on pCPU B, which is potentially used by
3908 	 *   another vCPU/VM.
3909 	 */
3910 	if (unlikely(svm->current_vmcb->cpu != vcpu->cpu)) {
3911 		vmcb_mark_all_dirty(svm->vmcb01.ptr);
3912 		svm->vmcb01.cpu = vcpu->cpu;
3913 		svm->vmcb01.asid_generation = 0;
3914 
3915 		if (svm->nested.initialized) {
3916 			svm->nested.vmcb02.cpu = vcpu->cpu;
3917 			svm->nested.vmcb02.asid_generation = 0;
3918 			vmcb_mark_all_dirty(svm->nested.vmcb02.ptr);
3919 		}
3920 	}
3921 
3922 	if (is_sev_guest(vcpu))
3923 		return pre_sev_run(svm, vcpu->cpu);
3924 
3925 	/* FIXME: handle wraparound of asid_generation */
3926 	if (svm->current_vmcb->asid_generation != sd->asid_generation)
3927 		new_asid(svm, sd);
3928 
3929 	return 0;
3930 }
3931 
3932 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
3933 {
3934 	struct vcpu_svm *svm = to_svm(vcpu);
3935 
3936 	svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
3937 
3938 	if (svm->nmi_l1_to_l2)
3939 		return;
3940 
3941 	/*
3942 	 * No need to manually track NMI masking when vNMI is enabled, hardware
3943 	 * automatically sets V_NMI_BLOCKING_MASK as appropriate, including the
3944 	 * case where software directly injects an NMI.
3945 	 */
3946 	if (!is_vnmi_enabled(svm)) {
3947 		svm->nmi_masked = true;
3948 		svm_set_iret_intercept(svm);
3949 	}
3950 	++vcpu->stat.nmi_injections;
3951 }
3952 
3953 static bool svm_is_vnmi_pending(struct kvm_vcpu *vcpu)
3954 {
3955 	struct vcpu_svm *svm = to_svm(vcpu);
3956 
3957 	if (!is_vnmi_enabled(svm))
3958 		return false;
3959 
3960 	return !!(svm->vmcb->control.int_ctl & V_NMI_PENDING_MASK);
3961 }
3962 
3963 static bool svm_set_vnmi_pending(struct kvm_vcpu *vcpu)
3964 {
3965 	struct vcpu_svm *svm = to_svm(vcpu);
3966 
3967 	if (!is_vnmi_enabled(svm))
3968 		return false;
3969 
3970 	if (svm->vmcb->control.int_ctl & V_NMI_PENDING_MASK)
3971 		return false;
3972 
3973 	svm->vmcb->control.int_ctl |= V_NMI_PENDING_MASK;
3974 	vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
3975 
3976 	/*
3977 	 * Because the pending NMI is serviced by hardware, KVM can't know when
3978 	 * the NMI is "injected", but for all intents and purposes, passing the
3979 	 * NMI off to hardware counts as injection.
3980 	 */
3981 	++vcpu->stat.nmi_injections;
3982 
3983 	return true;
3984 }
3985 
3986 static void svm_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
3987 {
3988 	struct kvm_queued_interrupt *intr = &vcpu->arch.interrupt;
3989 	struct vcpu_svm *svm = to_svm(vcpu);
3990 	u32 type;
3991 
3992 	if (intr->soft) {
3993 		if (svm_update_soft_interrupt_rip(vcpu, intr->nr))
3994 			return;
3995 
3996 		type = SVM_EVTINJ_TYPE_SOFT;
3997 	} else {
3998 		type = SVM_EVTINJ_TYPE_INTR;
3999 	}
4000 
4001 	/*
4002 	 * If AVIC was inhibited in order to detect an IRQ window, and there's
4003 	 * no other injectable interrupts pending or L2 is active (see below),
4004 	 * then drop the inhibit as the window has served its purpose.
4005 	 *
4006 	 * If L2 is active, this path is reachable if L1 is not intercepting
4007 	 * IRQs, i.e. if KVM is injecting L1 IRQs into L2.  AVIC is locally
4008 	 * inhibited while L2 is active; drop the VM-wide inhibit to optimize
4009 	 * the case in which the interrupt window was requested while L1 was
4010 	 * active (the vCPU was not running nested).
4011 	 */
4012 	if (svm->avic_irq_window &&
4013 	    (!kvm_cpu_has_injectable_intr(vcpu) || is_guest_mode(vcpu))) {
4014 		svm->avic_irq_window = false;
4015 		kvm_dec_apicv_irq_window_req(svm->vcpu.kvm);
4016 	}
4017 
4018 	trace_kvm_inj_virq(intr->nr, intr->soft, reinjected);
4019 	++vcpu->stat.irq_injections;
4020 
4021 	svm->vmcb->control.event_inj = intr->nr | SVM_EVTINJ_VALID | type;
4022 }
4023 
4024 static void svm_fixup_nested_rips(struct kvm_vcpu *vcpu)
4025 {
4026 	struct vcpu_svm *svm = to_svm(vcpu);
4027 
4028 	if (!is_guest_mode(vcpu) || !vcpu->arch.nested_run_pending)
4029 		return;
4030 
4031 	/*
4032 	 * If nrips is supported in hardware but not exposed to L1, stuff the
4033 	 * actual L2 RIP to emulate what a nrips=0 CPU would do (L1 is
4034 	 * responsible for advancing RIP prior to injecting the event). Once L2
4035 	 * runs after L1 executes VMRUN, NextRIP is updated by the CPU and/or
4036 	 * KVM, and this is no longer needed.
4037 	 *
4038 	 * This is done here (as opposed to when preparing vmcb02) to use the
4039 	 * most up-to-date value of RIP regardless of the order of restoring
4040 	 * registers and nested state in the vCPU save+restore path.
4041 	 */
4042 	if (boot_cpu_has(X86_FEATURE_NRIPS) &&
4043 	    !guest_cpu_cap_has(vcpu, X86_FEATURE_NRIPS))
4044 		svm->vmcb->control.next_rip = kvm_rip_read(vcpu);
4045 
4046 	/*
4047 	 * Simiarly, initialize the soft int metadata here to use the most
4048 	 * up-to-date values of RIP and CS base, regardless of restore order.
4049 	 */
4050 	if (svm->soft_int_injected)
4051 		svm_set_nested_run_soft_int_state(vcpu);
4052 }
4053 
4054 void svm_complete_interrupt_delivery(struct kvm_vcpu *vcpu, int delivery_mode,
4055 				     int trig_mode, int vector)
4056 {
4057 	/*
4058 	 * apic->apicv_active must be read after vcpu->mode.
4059 	 * Pairs with smp_store_release in vcpu_enter_guest.
4060 	 */
4061 	bool in_guest_mode = (smp_load_acquire(&vcpu->mode) == IN_GUEST_MODE);
4062 
4063 	/* Note, this is called iff the local APIC is in-kernel. */
4064 	if (!READ_ONCE(vcpu->arch.apic->apicv_active)) {
4065 		/* Process the interrupt via kvm_check_and_inject_events(). */
4066 		kvm_make_request(KVM_REQ_EVENT, vcpu);
4067 		kvm_vcpu_kick(vcpu);
4068 		return;
4069 	}
4070 
4071 	trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode, trig_mode, vector);
4072 	if (in_guest_mode) {
4073 		/*
4074 		 * Signal the doorbell to tell hardware to inject the IRQ.  If
4075 		 * the vCPU exits the guest before the doorbell chimes, hardware
4076 		 * will automatically process AVIC interrupts at the next VMRUN.
4077 		 */
4078 		avic_ring_doorbell(vcpu);
4079 	} else {
4080 		/*
4081 		 * Wake the vCPU if it was blocking.  KVM will then detect the
4082 		 * pending IRQ when checking if the vCPU has a wake event.
4083 		 */
4084 		kvm_vcpu_wake_up(vcpu);
4085 	}
4086 }
4087 
4088 static void svm_deliver_interrupt(struct kvm_lapic *apic,  int delivery_mode,
4089 				  int trig_mode, int vector)
4090 {
4091 	kvm_lapic_set_irr(vector, apic);
4092 
4093 	/*
4094 	 * Pairs with the smp_mb_*() after setting vcpu->guest_mode in
4095 	 * vcpu_enter_guest() to ensure the write to the vIRR is ordered before
4096 	 * the read of guest_mode.  This guarantees that either VMRUN will see
4097 	 * and process the new vIRR entry, or that svm_complete_interrupt_delivery
4098 	 * will signal the doorbell if the CPU has already entered the guest.
4099 	 */
4100 	smp_mb__after_atomic();
4101 	svm_complete_interrupt_delivery(apic->vcpu, delivery_mode, trig_mode, vector);
4102 }
4103 
4104 static void svm_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
4105 {
4106 	struct vcpu_svm *svm = to_svm(vcpu);
4107 
4108 	/*
4109 	 * SEV-ES guests must always keep the CR intercepts cleared. CR
4110 	 * tracking is done using the CR write traps.
4111 	 */
4112 	if (is_sev_es_guest(vcpu))
4113 		return;
4114 
4115 	if (nested_svm_virtualize_tpr(vcpu))
4116 		return;
4117 
4118 	svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
4119 
4120 	if (irr == -1)
4121 		return;
4122 
4123 	if (tpr >= irr)
4124 		svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
4125 }
4126 
4127 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
4128 {
4129 	struct vcpu_svm *svm = to_svm(vcpu);
4130 
4131 	if (is_vnmi_enabled(svm))
4132 		return svm->vmcb->control.int_ctl & V_NMI_BLOCKING_MASK;
4133 	else
4134 		return svm->nmi_masked;
4135 }
4136 
4137 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4138 {
4139 	struct vcpu_svm *svm = to_svm(vcpu);
4140 
4141 	if (is_vnmi_enabled(svm)) {
4142 		if (masked)
4143 			svm->vmcb->control.int_ctl |= V_NMI_BLOCKING_MASK;
4144 		else
4145 			svm->vmcb->control.int_ctl &= ~V_NMI_BLOCKING_MASK;
4146 
4147 	} else {
4148 		svm->nmi_masked = masked;
4149 		if (masked)
4150 			svm_set_iret_intercept(svm);
4151 		else
4152 			svm_clr_iret_intercept(svm);
4153 	}
4154 }
4155 
4156 bool svm_nmi_blocked(struct kvm_vcpu *vcpu)
4157 {
4158 	struct vcpu_svm *svm = to_svm(vcpu);
4159 	struct vmcb *vmcb = svm->vmcb;
4160 
4161 	if (!gif_set(svm))
4162 		return true;
4163 
4164 	if (is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
4165 		return false;
4166 
4167 	if (svm_get_nmi_mask(vcpu))
4168 		return true;
4169 
4170 	return vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK;
4171 }
4172 
4173 static int svm_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4174 {
4175 	struct vcpu_svm *svm = to_svm(vcpu);
4176 	if (vcpu->arch.nested_run_pending)
4177 		return -EBUSY;
4178 
4179 	if (svm_nmi_blocked(vcpu))
4180 		return 0;
4181 
4182 	/* An NMI must not be injected into L2 if it's supposed to VM-Exit.  */
4183 	if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
4184 		return -EBUSY;
4185 	return 1;
4186 }
4187 
4188 bool svm_interrupt_blocked(struct kvm_vcpu *vcpu)
4189 {
4190 	struct vcpu_svm *svm = to_svm(vcpu);
4191 	struct vmcb *vmcb = svm->vmcb;
4192 
4193 	if (!gif_set(svm))
4194 		return true;
4195 
4196 	if (is_guest_mode(vcpu)) {
4197 		/* As long as interrupts are being delivered...  */
4198 		if ((svm->nested.ctl.int_ctl & V_INTR_MASKING_MASK)
4199 		    ? !(svm->vmcb01.ptr->save.rflags & X86_EFLAGS_IF)
4200 		    : !(kvm_get_rflags(vcpu) & X86_EFLAGS_IF))
4201 			return true;
4202 
4203 		/* ... vmexits aren't blocked by the interrupt shadow  */
4204 		if (nested_exit_on_intr(svm))
4205 			return false;
4206 	} else {
4207 		if (!svm_get_if_flag(vcpu))
4208 			return true;
4209 	}
4210 
4211 	return (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK);
4212 }
4213 
4214 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4215 {
4216 	struct vcpu_svm *svm = to_svm(vcpu);
4217 
4218 	if (svm_interrupt_blocked(vcpu))
4219 		return 0;
4220 
4221 	if (vcpu->arch.nested_run_pending)
4222 		return -EBUSY;
4223 
4224 	/*
4225 	 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4226 	 * e.g. if the IRQ arrived asynchronously after checking nested events.
4227 	 */
4228 	if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(svm))
4229 		return -EBUSY;
4230 
4231 	return 1;
4232 }
4233 
4234 static void svm_enable_irq_window(struct kvm_vcpu *vcpu)
4235 {
4236 	struct vcpu_svm *svm = to_svm(vcpu);
4237 
4238 	/*
4239 	 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
4240 	 * 1, because that's a separate STGI/VMRUN intercept.  The next time we
4241 	 * get that intercept, this function will be called again though and
4242 	 * we'll get the vintr intercept. However, if the vGIF feature is
4243 	 * enabled, the STGI interception will not occur. Enable the irq
4244 	 * window under the assumption that the hardware will set the GIF.
4245 	 */
4246 	if (vgif || gif_set(svm)) {
4247 		/*
4248 		 * KVM only enables IRQ windows when AVIC is enabled if there's
4249 		 * pending ExtINT since it cannot be injected via AVIC (ExtINT
4250 		 * bypasses the local APIC).  V_IRQ is ignored by hardware when
4251 		 * AVIC is enabled, and so KVM needs to temporarily disable
4252 		 * AVIC in order to detect when it's ok to inject the ExtINT.
4253 		 *
4254 		 * If running nested, AVIC is already locally inhibited on this
4255 		 * vCPU (L2 vCPUs use a different MMU that never maps the AVIC
4256 		 * backing page), therefore there is no need to increment the
4257 		 * VM-wide AVIC inhibit.  KVM will re-evaluate events when the
4258 		 * vCPU exits to L1 and enable an IRQ window if the ExtINT is
4259 		 * still pending.
4260 		 *
4261 		 * Note, the IRQ window inhibit needs to be updated even if
4262 		 * AVIC is inhibited for a different reason, as KVM needs to
4263 		 * keep AVIC inhibited if the other reason is cleared and there
4264 		 * is still an injectable interrupt pending.
4265 		 */
4266 		if (enable_apicv && !svm->avic_irq_window && !is_guest_mode(vcpu)) {
4267 			svm->avic_irq_window = true;
4268 			kvm_inc_apicv_irq_window_req(vcpu->kvm);
4269 		}
4270 
4271 		svm_set_vintr(svm);
4272 	}
4273 }
4274 
4275 static void svm_enable_nmi_window(struct kvm_vcpu *vcpu)
4276 {
4277 	struct vcpu_svm *svm = to_svm(vcpu);
4278 
4279 	/*
4280 	 * If NMIs are outright masked, i.e. the vCPU is already handling an
4281 	 * NMI, and KVM has not yet intercepted an IRET, then there is nothing
4282 	 * more to do at this time as KVM has already enabled IRET intercepts.
4283 	 * If KVM has already intercepted IRET, then single-step over the IRET,
4284 	 * as NMIs aren't architecturally unmasked until the IRET completes.
4285 	 *
4286 	 * If vNMI is enabled, KVM should never request an NMI window if NMIs
4287 	 * are masked, as KVM allows at most one to-be-injected NMI and one
4288 	 * pending NMI.  If two NMIs arrive simultaneously, KVM will inject one
4289 	 * NMI and set V_NMI_PENDING for the other, but if and only if NMIs are
4290 	 * unmasked.  KVM _will_ request an NMI window in some situations, e.g.
4291 	 * if the vCPU is in an STI shadow or if GIF=0, KVM can't immediately
4292 	 * inject the NMI.  In those situations, KVM needs to single-step over
4293 	 * the STI shadow or intercept STGI.
4294 	 */
4295 	if (svm_get_nmi_mask(vcpu)) {
4296 		WARN_ON_ONCE(is_vnmi_enabled(svm));
4297 
4298 		if (!svm->awaiting_iret_completion)
4299 			return; /* IRET will cause a vm exit */
4300 	}
4301 
4302 	/*
4303 	 * SEV-ES guests are responsible for signaling when a vCPU is ready to
4304 	 * receive a new NMI, as SEV-ES guests can't be single-stepped, i.e.
4305 	 * KVM can't intercept and single-step IRET to detect when NMIs are
4306 	 * unblocked (architecturally speaking).  See SVM_VMGEXIT_NMI_COMPLETE.
4307 	 *
4308 	 * Note, GIF is guaranteed to be '1' for SEV-ES guests as hardware
4309 	 * ignores SEV-ES guest writes to EFER.SVME *and* CLGI/STGI are not
4310 	 * supported NAEs in the GHCB protocol.
4311 	 */
4312 	if (is_sev_es_guest(vcpu))
4313 		return;
4314 
4315 	if (!gif_set(svm)) {
4316 		if (vgif)
4317 			svm_set_intercept(svm, INTERCEPT_STGI);
4318 		return; /* STGI will cause a vm exit */
4319 	}
4320 
4321 	/*
4322 	 * Something prevents NMI from been injected. Single step over possible
4323 	 * problem (IRET or exception injection or interrupt shadow)
4324 	 */
4325 	svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
4326 	svm->nmi_singlestep = true;
4327 	svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
4328 }
4329 
4330 static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu)
4331 {
4332 	struct vcpu_svm *svm = to_svm(vcpu);
4333 
4334 	/*
4335 	 * Unlike VMX, SVM doesn't provide a way to flush only NPT TLB entries.
4336 	 * A TLB flush for the current ASID flushes both "host" and "guest" TLB
4337 	 * entries, and thus is a superset of Hyper-V's fine grained flushing.
4338 	 */
4339 	kvm_hv_vcpu_purge_flush_tlb(vcpu);
4340 
4341 	/*
4342 	 * Flush only the current ASID even if the TLB flush was invoked via
4343 	 * kvm_flush_remote_tlbs().  Although flushing remote TLBs requires all
4344 	 * ASIDs to be flushed, KVM uses a single ASID for L1 and L2, and
4345 	 * unconditionally does a TLB flush on both nested VM-Enter and nested
4346 	 * VM-Exit (via kvm_mmu_reset_context()).
4347 	 */
4348 	if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
4349 		svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
4350 	else
4351 		svm->current_vmcb->asid_generation--;
4352 }
4353 
4354 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu)
4355 {
4356 	hpa_t root_tdp = vcpu->arch.mmu->root.hpa;
4357 
4358 	/*
4359 	 * When running on Hyper-V with EnlightenedNptTlb enabled, explicitly
4360 	 * flush the NPT mappings via hypercall as flushing the ASID only
4361 	 * affects virtual to physical mappings, it does not invalidate guest
4362 	 * physical to host physical mappings.
4363 	 */
4364 	if (svm_hv_is_enlightened_tlb_enabled(vcpu) && VALID_PAGE(root_tdp))
4365 		hyperv_flush_guest_mapping(root_tdp);
4366 
4367 	svm_flush_tlb_asid(vcpu);
4368 }
4369 
4370 static void svm_flush_tlb_all(struct kvm_vcpu *vcpu)
4371 {
4372 	/*
4373 	 * When running on Hyper-V with EnlightenedNptTlb enabled, remote TLB
4374 	 * flushes should be routed to hv_flush_remote_tlbs() without requesting
4375 	 * a "regular" remote flush.  Reaching this point means either there's
4376 	 * a KVM bug or a prior hv_flush_remote_tlbs() call failed, both of
4377 	 * which might be fatal to the guest.  Yell, but try to recover.
4378 	 */
4379 	if (WARN_ON_ONCE(svm_hv_is_enlightened_tlb_enabled(vcpu)))
4380 		hv_flush_remote_tlbs(vcpu->kvm);
4381 
4382 	svm_flush_tlb_asid(vcpu);
4383 }
4384 
4385 static void svm_flush_tlb_guest(struct kvm_vcpu *vcpu)
4386 {
4387 	kvm_register_mark_dirty(vcpu, VCPU_REG_ERAPS);
4388 
4389 	svm_flush_tlb_asid(vcpu);
4390 }
4391 
4392 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
4393 {
4394 	struct vcpu_svm *svm = to_svm(vcpu);
4395 
4396 	/*
4397 	 * INVLPGA has had errata on Genoa and Turin, and even on older
4398 	 * generations there were reports of Windows BSODs if INVLPGA
4399 	 * was used for Hyper-V tlbflush.  Use it only for shadow paging
4400 	 * where it seems to be okay.
4401 	 */
4402 	if (!npt_enabled) {
4403 		invlpga(gva, svm->vmcb->control.asid);
4404 		return;
4405 	}
4406 
4407 	svm_flush_tlb_guest(vcpu);
4408 }
4409 
4410 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
4411 {
4412 	struct vcpu_svm *svm = to_svm(vcpu);
4413 
4414 	if (nested_svm_virtualize_tpr(vcpu))
4415 		return;
4416 
4417 	if (!svm_is_intercept(svm, INTERCEPT_CR8_WRITE)) {
4418 		int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
4419 		kvm_set_cr8(vcpu, cr8);
4420 	}
4421 }
4422 
4423 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
4424 {
4425 	struct vcpu_svm *svm = to_svm(vcpu);
4426 	u64 cr8;
4427 
4428 	if (nested_svm_virtualize_tpr(vcpu))
4429 		return;
4430 
4431 	cr8 = kvm_get_cr8(vcpu);
4432 	svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
4433 	svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
4434 }
4435 
4436 static void svm_complete_soft_interrupt(struct kvm_vcpu *vcpu, u8 vector,
4437 					int type)
4438 {
4439 	bool is_exception = (type == SVM_EXITINTINFO_TYPE_EXEPT);
4440 	bool is_soft = (type == SVM_EXITINTINFO_TYPE_SOFT);
4441 	struct vcpu_svm *svm = to_svm(vcpu);
4442 
4443 	/*
4444 	 * Initialize the soft int fields *before* reading them below if KVM
4445 	 * aborted entry to the guest with a nested VMRUN pending.  To ensure
4446 	 * KVM uses up-to-date values for RIP and CS base across save/restore,
4447 	 * regardless of restore order, KVM waits to set the soft int fields
4448 	 * until VMRUN is imminent.  But when canceling injection, KVM requeues
4449 	 * the soft int and will reinject it via the standard injection flow,
4450 	 * and so KVM needs to grab the state from the pending nested VMRUN.
4451 	 */
4452 	if (is_guest_mode(vcpu) && vcpu->arch.nested_run_pending)
4453 		svm_set_nested_run_soft_int_state(vcpu);
4454 
4455 	/*
4456 	 * If NRIPS is enabled, KVM must snapshot the pre-VMRUN next_rip that's
4457 	 * associated with the original soft exception/interrupt.  next_rip is
4458 	 * cleared on all exits that can occur while vectoring an event, so KVM
4459 	 * needs to manually set next_rip for re-injection.  Unlike the !nrips
4460 	 * case below, this needs to be done if and only if KVM is re-injecting
4461 	 * the same event, i.e. if the event is a soft exception/interrupt,
4462 	 * otherwise next_rip is unused on VMRUN.
4463 	 */
4464 	if (nrips && (is_soft || (is_exception && kvm_exception_is_soft(vector))) &&
4465 	    kvm_is_linear_rip(vcpu, svm->soft_int_old_rip + svm->soft_int_csbase))
4466 		svm->vmcb->control.next_rip = svm->soft_int_next_rip;
4467 	/*
4468 	 * If NRIPS isn't enabled, KVM must manually advance RIP prior to
4469 	 * injecting the soft exception/interrupt.  That advancement needs to
4470 	 * be unwound if vectoring didn't complete.  Note, the new event may
4471 	 * not be the injected event, e.g. if KVM injected an INTn, the INTn
4472 	 * hit a #NP in the guest, and the #NP encountered a #PF, the #NP will
4473 	 * be the reported vectored event, but RIP still needs to be unwound.
4474 	 */
4475 	else if (!nrips && (is_soft || is_exception) &&
4476 		 kvm_is_linear_rip(vcpu, svm->soft_int_next_rip + svm->soft_int_csbase))
4477 		kvm_rip_write(vcpu, svm->soft_int_old_rip);
4478 }
4479 
4480 static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
4481 {
4482 	struct vcpu_svm *svm = to_svm(vcpu);
4483 	u8 vector;
4484 	int type;
4485 	u32 exitintinfo = svm->vmcb->control.exit_int_info;
4486 	bool nmi_l1_to_l2 = svm->nmi_l1_to_l2;
4487 	bool soft_int_injected = svm->soft_int_injected;
4488 
4489 	svm->nmi_l1_to_l2 = false;
4490 	svm->soft_int_injected = false;
4491 
4492 	/*
4493 	 * If we've made progress since setting awaiting_iret_completion, we've
4494 	 * executed an IRET and can allow NMI injection.
4495 	 */
4496 	if (svm->awaiting_iret_completion &&
4497 	    kvm_rip_read(vcpu) != svm->nmi_iret_rip) {
4498 		svm->awaiting_iret_completion = false;
4499 		svm->nmi_masked = false;
4500 		kvm_make_request(KVM_REQ_EVENT, vcpu);
4501 	}
4502 
4503 	vcpu->arch.nmi_injected = false;
4504 	kvm_clear_exception_queue(vcpu);
4505 	kvm_clear_interrupt_queue(vcpu);
4506 
4507 	if (!(exitintinfo & SVM_EXITINTINFO_VALID))
4508 		return;
4509 
4510 	kvm_make_request(KVM_REQ_EVENT, vcpu);
4511 
4512 	vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
4513 	type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
4514 
4515 	if (soft_int_injected)
4516 		svm_complete_soft_interrupt(vcpu, vector, type);
4517 
4518 	switch (type) {
4519 	case SVM_EXITINTINFO_TYPE_NMI:
4520 		vcpu->arch.nmi_injected = true;
4521 		svm->nmi_l1_to_l2 = nmi_l1_to_l2;
4522 		break;
4523 	case SVM_EXITINTINFO_TYPE_EXEPT: {
4524 		u32 error_code = 0;
4525 
4526 		/*
4527 		 * Never re-inject a #VC exception.
4528 		 */
4529 		if (vector == X86_TRAP_VC)
4530 			break;
4531 
4532 		if (exitintinfo & SVM_EXITINTINFO_VALID_ERR)
4533 			error_code = svm->vmcb->control.exit_int_info_err;
4534 
4535 		kvm_requeue_exception(vcpu, vector,
4536 				      exitintinfo & SVM_EXITINTINFO_VALID_ERR,
4537 				      error_code);
4538 		break;
4539 	}
4540 	case SVM_EXITINTINFO_TYPE_INTR:
4541 		kvm_queue_interrupt(vcpu, vector, false);
4542 		break;
4543 	case SVM_EXITINTINFO_TYPE_SOFT:
4544 		kvm_queue_interrupt(vcpu, vector, true);
4545 		break;
4546 	default:
4547 		break;
4548 	}
4549 
4550 }
4551 
4552 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
4553 {
4554 	struct vcpu_svm *svm = to_svm(vcpu);
4555 	struct vmcb_control_area *control = &svm->vmcb->control;
4556 
4557 	control->exit_int_info = control->event_inj;
4558 	control->exit_int_info_err = control->event_inj_err;
4559 	control->event_inj = 0;
4560 	svm_complete_interrupts(vcpu);
4561 }
4562 
4563 static fastpath_t svm_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
4564 {
4565 	struct vcpu_svm *svm = to_svm(vcpu);
4566 	struct vmcb_control_area *control = &svm->vmcb->control;
4567 
4568 	/*
4569 	 * Next RIP must be provided as IRQs are disabled, and accessing guest
4570 	 * memory to decode the instruction might fault, i.e. might sleep.
4571 	 */
4572 	if (!nrips || !control->next_rip)
4573 		return EXIT_FASTPATH_NONE;
4574 
4575 	if (is_guest_mode(vcpu))
4576 		return EXIT_FASTPATH_NONE;
4577 
4578 	switch (control->exit_code) {
4579 	case SVM_EXIT_MSR:
4580 		if (!control->exit_info_1)
4581 			break;
4582 		return handle_fastpath_wrmsr(vcpu);
4583 	case SVM_EXIT_HLT:
4584 		return handle_fastpath_hlt(vcpu);
4585 	case SVM_EXIT_INVD:
4586 		return handle_fastpath_invd(vcpu);
4587 	default:
4588 		break;
4589 	}
4590 
4591 	return EXIT_FASTPATH_NONE;
4592 }
4593 
4594 static noinstr void svm_vcpu_enter_exit(struct kvm_vcpu *vcpu, unsigned enter_flags)
4595 {
4596 	struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, vcpu->cpu);
4597 	struct vcpu_svm *svm = to_svm(vcpu);
4598 
4599 	guest_state_enter_irqoff();
4600 
4601 	/*
4602 	 * Set RFLAGS.IF prior to VMRUN, as the host's RFLAGS.IF at the time of
4603 	 * VMRUN controls whether or not physical IRQs are masked (KVM always
4604 	 * runs with V_INTR_MASKING_MASK).  Toggle RFLAGS.IF here to avoid the
4605 	 * temptation to do STI+VMRUN+CLI, as AMD CPUs bleed the STI shadow
4606 	 * into guest state if delivery of an event during VMRUN triggers a
4607 	 * #VMEXIT, and the guest_state transitions already tell lockdep that
4608 	 * IRQs are being enabled/disabled.  Note!  GIF=0 for the entirety of
4609 	 * this path, so IRQs aren't actually unmasked while running host code.
4610 	 */
4611 	raw_local_irq_enable();
4612 
4613 	amd_clear_divider();
4614 
4615 	if (is_sev_es_guest(vcpu))
4616 		__svm_sev_es_vcpu_run(svm, enter_flags,
4617 				      sev_es_host_save_area(sd));
4618 	else
4619 		__svm_vcpu_run(svm, enter_flags);
4620 
4621 	raw_local_irq_disable();
4622 
4623 	guest_state_exit_irqoff();
4624 }
4625 
4626 static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu, u64 run_flags)
4627 {
4628 	bool force_immediate_exit = run_flags & KVM_RUN_FORCE_IMMEDIATE_EXIT;
4629 	struct vcpu_svm *svm = to_svm(vcpu);
4630 	unsigned enter_flags = 0;
4631 
4632 	if (!msr_write_intercepted(svm, MSR_IA32_SPEC_CTRL))
4633 		enter_flags |= KVM_ENTER_SAVE_SPEC_CTRL;
4634 
4635 	trace_kvm_entry(vcpu, force_immediate_exit);
4636 
4637 	svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
4638 	svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
4639 	svm->vmcb->save.rip = vcpu->arch.rip;
4640 
4641 	/*
4642 	 * Disable singlestep if we're injecting an interrupt/exception.
4643 	 * We don't want our modified rflags to be pushed on the stack where
4644 	 * we might not be able to easily reset them if we disabled NMI
4645 	 * singlestep later.
4646 	 */
4647 	if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
4648 		/*
4649 		 * Event injection happens before external interrupts cause a
4650 		 * vmexit and interrupts are disabled here, so smp_send_reschedule
4651 		 * is enough to force an immediate vmexit.
4652 		 */
4653 		disable_nmi_singlestep(svm);
4654 		force_immediate_exit = true;
4655 	}
4656 
4657 	if (force_immediate_exit)
4658 		smp_send_reschedule(vcpu->cpu);
4659 
4660 	if (pre_svm_run(vcpu)) {
4661 		vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4662 		vcpu->run->fail_entry.hardware_entry_failure_reason = SVM_EXIT_ERR;
4663 		vcpu->run->fail_entry.cpu = vcpu->cpu;
4664 		return EXIT_FASTPATH_EXIT_USERSPACE;
4665 	}
4666 
4667 	sync_lapic_to_cr8(vcpu);
4668 
4669 	if (unlikely(svm->asid != svm->vmcb->control.asid)) {
4670 		svm->vmcb->control.asid = svm->asid;
4671 		vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
4672 	}
4673 	if (this_cpu_ptr(&svm_data)->flush_all_asids)
4674 		svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
4675 
4676 	svm->vmcb->save.cr2 = vcpu->arch.cr2;
4677 
4678 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_ERAPS) &&
4679 	    kvm_register_is_dirty(vcpu, VCPU_REG_ERAPS))
4680 		svm->vmcb->control.erap_ctl |= ERAP_CONTROL_CLEAR_RAP;
4681 
4682 	svm_fixup_nested_rips(vcpu);
4683 
4684 	svm_hv_update_vp_id(svm->vmcb, vcpu);
4685 
4686 	/*
4687 	 * Run with all-zero DR6 unless the guest can write DR6 freely, so that
4688 	 * KVM can get the exact cause of a #DB.  Note, loading guest DR6 from
4689 	 * KVM's snapshot is only necessary when DR accesses won't exit.
4690 	 */
4691 	if (unlikely(run_flags & KVM_RUN_LOAD_GUEST_DR6))
4692 		svm_set_dr6(vcpu, vcpu->arch.dr6);
4693 	else if (likely(!(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)))
4694 		svm_set_dr6(vcpu, DR6_ACTIVE_LOW);
4695 
4696 	clgi();
4697 
4698 	/*
4699 	 * Hardware only context switches DEBUGCTL if LBR virtualization is
4700 	 * enabled.  Manually load DEBUGCTL if necessary (and restore it after
4701 	 * VM-Exit), as running with the host's DEBUGCTL can negatively affect
4702 	 * guest state and can even be fatal, e.g. due to Bus Lock Detect.
4703 	 */
4704 	if (!(svm->vmcb->control.misc_ctl2 & SVM_MISC2_ENABLE_V_LBR) &&
4705 	    vcpu->arch.host_debugctl != svm->vmcb->save.dbgctl)
4706 		update_debugctlmsr(svm->vmcb->save.dbgctl);
4707 
4708 	kvm_wait_lapic_expire(vcpu);
4709 
4710 	/*
4711 	 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
4712 	 * it's non-zero. Since vmentry is serialising on affected CPUs, there
4713 	 * is no need to worry about the conditional branch over the wrmsr
4714 	 * being speculatively taken.
4715 	 */
4716 	if (!cpu_feature_enabled(X86_FEATURE_V_SPEC_CTRL))
4717 		x86_spec_ctrl_set_guest(svm->virt_spec_ctrl);
4718 
4719 	svm_vcpu_enter_exit(vcpu, enter_flags);
4720 
4721 	if (!cpu_feature_enabled(X86_FEATURE_V_SPEC_CTRL))
4722 		x86_spec_ctrl_restore_host(svm->virt_spec_ctrl);
4723 
4724 	/* SEV-ES guests must use the CR write traps to track CR registers. */
4725 	if (!is_sev_es_guest(vcpu)) {
4726 		vcpu->arch.cr2 = svm->vmcb->save.cr2;
4727 		vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
4728 		vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
4729 		vcpu->arch.rip = svm->vmcb->save.rip;
4730 
4731 		if (!svm_is_intercept(svm, INTERCEPT_CR0_WRITE))
4732 			vcpu->arch.cr0 = svm->vmcb->save.cr0;
4733 		if (npt_enabled)
4734 			vcpu->arch.cr3 = svm->vmcb->save.cr3;
4735 	}
4736 	kvm_reset_dirty_registers(vcpu);
4737 
4738 	if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
4739 		kvm_before_interrupt(vcpu, KVM_HANDLING_NMI);
4740 
4741 	if (!(svm->vmcb->control.misc_ctl2 & SVM_MISC2_ENABLE_V_LBR) &&
4742 	    vcpu->arch.host_debugctl != svm->vmcb->save.dbgctl)
4743 		update_debugctlmsr(vcpu->arch.host_debugctl);
4744 
4745 	stgi();
4746 
4747 	/* Any pending NMI will happen here */
4748 
4749 	if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
4750 		kvm_after_interrupt(vcpu);
4751 
4752 	sync_cr8_to_lapic(vcpu);
4753 
4754 	svm->next_rip = 0;
4755 	if (is_guest_mode(vcpu)) {
4756 		nested_sync_control_from_vmcb02(svm);
4757 
4758 		/* Track VMRUNs that have made past consistency checking */
4759 		if (vcpu->arch.nested_run_pending &&
4760 		    !svm_is_vmrun_failure(svm->vmcb->control.exit_code))
4761                         ++vcpu->stat.nested_run;
4762 
4763 		vcpu->arch.nested_run_pending = 0;
4764 	}
4765 
4766 	if (!svm_is_vmrun_failure(svm->vmcb->control.exit_code)) {
4767 		this_cpu_ptr(&svm_data)->flush_all_asids = false;
4768 		svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
4769 
4770 		/*
4771 		 * Unconditionally mask off the CLEAR_RAP bit, the AND is just
4772 		 * as cheap as the TEST+Jcc to avoid it.
4773 		 */
4774 		if (cpu_feature_enabled(X86_FEATURE_ERAPS))
4775 			svm->vmcb->control.erap_ctl &= ~ERAP_CONTROL_CLEAR_RAP;
4776 
4777 		vmcb_mark_all_clean(svm->vmcb);
4778 
4779 		if (!msr_write_intercepted(svm, MSR_AMD64_PERF_CNTR_GLOBAL_CTL))
4780 			rdmsrq(MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
4781 			       vcpu_to_pmu(vcpu)->global_ctrl);
4782 	}
4783 
4784 	/* if exit due to PF check for async PF */
4785 	if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
4786 		vcpu->arch.apf.host_apf_flags =
4787 			kvm_read_and_reset_apf_flags();
4788 
4789 	kvm_clear_available_registers(vcpu, SVM_REGS_LAZY_LOAD_SET);
4790 
4791 	trace_kvm_exit(vcpu, KVM_ISA_SVM);
4792 
4793 	svm_complete_interrupts(vcpu);
4794 
4795 	/*
4796 	 * Update the cache after completing interrupts to get an accurate
4797 	 * NextRIP, e.g. when re-injecting a soft interrupt.
4798 	 *
4799 	 * FIXME: Rework svm_get_nested_state() to not pull data from the
4800 	 *        cache (except for maybe int_ctl).
4801 	 */
4802 	if (is_guest_mode(vcpu))
4803 		svm->nested.ctl.next_rip = svm->vmcb->control.next_rip;
4804 
4805 	return svm_exit_handlers_fastpath(vcpu);
4806 }
4807 
4808 static void svm_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
4809 			     int root_level)
4810 {
4811 	struct vcpu_svm *svm = to_svm(vcpu);
4812 	unsigned long cr3;
4813 
4814 	if (npt_enabled) {
4815 		svm->vmcb->control.nested_cr3 = __sme_set(root_hpa);
4816 		vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
4817 
4818 		hv_track_root_tdp(vcpu, root_hpa);
4819 
4820 		cr3 = vcpu->arch.cr3;
4821 	} else if (root_level >= PT64_ROOT_4LEVEL) {
4822 		cr3 = __sme_set(root_hpa) | kvm_get_active_pcid(vcpu);
4823 	} else {
4824 		/* PCID in the guest should be impossible with a 32-bit MMU. */
4825 		WARN_ON_ONCE(kvm_get_active_pcid(vcpu));
4826 		cr3 = root_hpa;
4827 	}
4828 
4829 	svm->vmcb->save.cr3 = cr3;
4830 	vmcb_mark_dirty(svm->vmcb, VMCB_CR);
4831 }
4832 
4833 static void
4834 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4835 {
4836 	/*
4837 	 * Patch in the VMMCALL instruction:
4838 	 */
4839 	hypercall[0] = 0x0f;
4840 	hypercall[1] = 0x01;
4841 	hypercall[2] = 0xd9;
4842 }
4843 
4844 static bool svm_tdp_has_smep(struct kvm *kvm)
4845 {
4846 	return gmet_enabled;
4847 }
4848 
4849 /*
4850  * The kvm parameter can be NULL (module initialization, or invocation before
4851  * VM creation). Be sure to check the kvm parameter before using it.
4852  */
4853 static bool svm_has_emulated_msr(struct kvm *kvm, u32 index)
4854 {
4855 	switch (index) {
4856 	case MSR_IA32_MCG_EXT_CTL:
4857 	case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR:
4858 		return false;
4859 	case MSR_IA32_SMBASE:
4860 		if (!IS_ENABLED(CONFIG_KVM_SMM))
4861 			return false;
4862 
4863 #ifdef CONFIG_KVM_AMD_SEV
4864 		/*
4865 		 * KVM can't access register state to emulate SMM for SEV-ES
4866 		 * guests.  Conusming stale data here is "fine", as KVM only
4867 		 * checks for MSR_IA32_SMBASE support without a vCPU when
4868 		 * userspace is querying KVM_CAP_X86_SMM.
4869 		 */
4870 		if (kvm && ____sev_es_guest(kvm))
4871 			return false;
4872 #endif
4873 		break;
4874 	default:
4875 		break;
4876 	}
4877 
4878 	return true;
4879 }
4880 
4881 static void svm_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
4882 {
4883 	struct vcpu_svm *svm = to_svm(vcpu);
4884 
4885 	/*
4886 	 * SVM doesn't provide a way to disable just XSAVES in the guest, KVM
4887 	 * can only disable all variants of by disallowing CR4.OSXSAVE from
4888 	 * being set.  As a result, if the host has XSAVE and XSAVES, and the
4889 	 * guest has XSAVE enabled, the guest can execute XSAVES without
4890 	 * faulting.  Treat XSAVES as enabled in this case regardless of
4891 	 * whether it's advertised to the guest so that KVM context switches
4892 	 * XSS on VM-Enter/VM-Exit.  Failure to do so would effectively give
4893 	 * the guest read/write access to the host's XSS.
4894 	 */
4895 	guest_cpu_cap_change(vcpu, X86_FEATURE_XSAVES,
4896 			     boot_cpu_has(X86_FEATURE_XSAVES) &&
4897 			     guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVE));
4898 
4899 	/*
4900 	 * Intercept VMLOAD if the vCPU model is Intel in order to emulate that
4901 	 * VMLOAD drops bits 63:32 of SYSENTER (ignoring the fact that exposing
4902 	 * SVM on Intel is bonkers and extremely unlikely to work).
4903 	 */
4904 	if (guest_cpuid_is_intel_compatible(vcpu))
4905 		guest_cpu_cap_clear(vcpu, X86_FEATURE_V_VMSAVE_VMLOAD);
4906 
4907 	if (is_sev_guest(vcpu))
4908 		sev_vcpu_after_set_cpuid(svm);
4909 }
4910 
4911 static bool svm_has_wbinvd_exit(void)
4912 {
4913 	return true;
4914 }
4915 
4916 #define PRE_EX(exit)  { .exit_code = (exit), \
4917 			.stage = X86_ICPT_PRE_EXCEPT, }
4918 #define POST_EX(exit) { .exit_code = (exit), \
4919 			.stage = X86_ICPT_POST_EXCEPT, }
4920 #define POST_MEM(exit) { .exit_code = (exit), \
4921 			.stage = X86_ICPT_POST_MEMACCESS, }
4922 
4923 static const struct __x86_intercept {
4924 	u32 exit_code;
4925 	enum x86_intercept_stage stage;
4926 } x86_intercept_map[] = {
4927 	[x86_intercept_cr_read]		= POST_EX(SVM_EXIT_READ_CR0),
4928 	[x86_intercept_cr_write]	= POST_EX(SVM_EXIT_WRITE_CR0),
4929 	[x86_intercept_clts]		= POST_EX(SVM_EXIT_WRITE_CR0),
4930 	[x86_intercept_lmsw]		= POST_EX(SVM_EXIT_WRITE_CR0),
4931 	[x86_intercept_smsw]		= POST_EX(SVM_EXIT_READ_CR0),
4932 	[x86_intercept_dr_read]		= POST_EX(SVM_EXIT_READ_DR0),
4933 	[x86_intercept_dr_write]	= POST_EX(SVM_EXIT_WRITE_DR0),
4934 	[x86_intercept_sldt]		= POST_EX(SVM_EXIT_LDTR_READ),
4935 	[x86_intercept_str]		= POST_EX(SVM_EXIT_TR_READ),
4936 	[x86_intercept_lldt]		= POST_EX(SVM_EXIT_LDTR_WRITE),
4937 	[x86_intercept_ltr]		= POST_EX(SVM_EXIT_TR_WRITE),
4938 	[x86_intercept_sgdt]		= POST_EX(SVM_EXIT_GDTR_READ),
4939 	[x86_intercept_sidt]		= POST_EX(SVM_EXIT_IDTR_READ),
4940 	[x86_intercept_lgdt]		= POST_EX(SVM_EXIT_GDTR_WRITE),
4941 	[x86_intercept_lidt]		= POST_EX(SVM_EXIT_IDTR_WRITE),
4942 	[x86_intercept_vmrun]		= POST_EX(SVM_EXIT_VMRUN),
4943 	[x86_intercept_vmmcall]		= POST_EX(SVM_EXIT_VMMCALL),
4944 	[x86_intercept_vmload]		= POST_EX(SVM_EXIT_VMLOAD),
4945 	[x86_intercept_vmsave]		= POST_EX(SVM_EXIT_VMSAVE),
4946 	[x86_intercept_stgi]		= POST_EX(SVM_EXIT_STGI),
4947 	[x86_intercept_clgi]		= POST_EX(SVM_EXIT_CLGI),
4948 	[x86_intercept_skinit]		= POST_EX(SVM_EXIT_SKINIT),
4949 	[x86_intercept_invlpga]		= POST_EX(SVM_EXIT_INVLPGA),
4950 	[x86_intercept_rdtscp]		= POST_EX(SVM_EXIT_RDTSCP),
4951 	[x86_intercept_monitor]		= POST_MEM(SVM_EXIT_MONITOR),
4952 	[x86_intercept_mwait]		= POST_EX(SVM_EXIT_MWAIT),
4953 	[x86_intercept_invlpg]		= POST_EX(SVM_EXIT_INVLPG),
4954 	[x86_intercept_invd]		= POST_EX(SVM_EXIT_INVD),
4955 	[x86_intercept_wbinvd]		= POST_EX(SVM_EXIT_WBINVD),
4956 	[x86_intercept_wrmsr]		= POST_EX(SVM_EXIT_MSR),
4957 	[x86_intercept_rdtsc]		= POST_EX(SVM_EXIT_RDTSC),
4958 	[x86_intercept_rdmsr]		= POST_EX(SVM_EXIT_MSR),
4959 	[x86_intercept_rdpmc]		= POST_EX(SVM_EXIT_RDPMC),
4960 	[x86_intercept_cpuid]		= PRE_EX(SVM_EXIT_CPUID),
4961 	[x86_intercept_rsm]		= PRE_EX(SVM_EXIT_RSM),
4962 	[x86_intercept_pause]		= PRE_EX(SVM_EXIT_PAUSE),
4963 	[x86_intercept_pushf]		= PRE_EX(SVM_EXIT_PUSHF),
4964 	[x86_intercept_popf]		= PRE_EX(SVM_EXIT_POPF),
4965 	[x86_intercept_intn]		= PRE_EX(SVM_EXIT_SWINT),
4966 	[x86_intercept_iret]		= PRE_EX(SVM_EXIT_IRET),
4967 	[x86_intercept_icebp]		= PRE_EX(SVM_EXIT_ICEBP),
4968 	[x86_intercept_hlt]		= POST_EX(SVM_EXIT_HLT),
4969 	[x86_intercept_in]		= POST_EX(SVM_EXIT_IOIO),
4970 	[x86_intercept_ins]		= POST_EX(SVM_EXIT_IOIO),
4971 	[x86_intercept_out]		= POST_EX(SVM_EXIT_IOIO),
4972 	[x86_intercept_outs]		= POST_EX(SVM_EXIT_IOIO),
4973 	[x86_intercept_xsetbv]		= PRE_EX(SVM_EXIT_XSETBV),
4974 };
4975 
4976 #undef PRE_EX
4977 #undef POST_EX
4978 #undef POST_MEM
4979 
4980 static int svm_check_intercept(struct kvm_vcpu *vcpu,
4981 			       struct x86_instruction_info *info,
4982 			       enum x86_intercept_stage stage,
4983 			       struct x86_exception *exception)
4984 {
4985 	struct vcpu_svm *svm = to_svm(vcpu);
4986 	int vmexit, ret = X86EMUL_CONTINUE;
4987 	struct __x86_intercept icpt_info;
4988 	struct vmcb *vmcb = svm->vmcb;
4989 
4990 	if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
4991 		goto out;
4992 
4993 	icpt_info = x86_intercept_map[info->intercept];
4994 
4995 	if (stage != icpt_info.stage)
4996 		goto out;
4997 
4998 	switch (icpt_info.exit_code) {
4999 	case SVM_EXIT_READ_CR0:
5000 		if (info->intercept == x86_intercept_cr_read)
5001 			icpt_info.exit_code += info->modrm_reg;
5002 		break;
5003 	case SVM_EXIT_WRITE_CR0: {
5004 		unsigned long cr0, val;
5005 
5006 		/*
5007 		 * Adjust the exit code accordingly if a CR other than CR0 is
5008 		 * being written, and skip straight to the common handling as
5009 		 * only CR0 has an additional selective intercept.
5010 		 */
5011 		if (info->intercept == x86_intercept_cr_write && info->modrm_reg) {
5012 			icpt_info.exit_code += info->modrm_reg;
5013 			break;
5014 		}
5015 
5016 		/*
5017 		 * Convert the exit_code to SVM_EXIT_CR0_SEL_WRITE if a
5018 		 * selective CR0 intercept is triggered (the common logic will
5019 		 * treat the selective intercept as being enabled).  Note, the
5020 		 * unconditional intercept has higher priority, i.e. this is
5021 		 * only relevant if *only* the selective intercept is enabled.
5022 		 */
5023 		if (vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_CR0_WRITE) ||
5024 		    !(vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_SELECTIVE_CR0)))
5025 			break;
5026 
5027 		/* CLTS never triggers INTERCEPT_SELECTIVE_CR0 */
5028 		if (info->intercept == x86_intercept_clts)
5029 			break;
5030 
5031 		/* LMSW always triggers INTERCEPT_SELECTIVE_CR0 */
5032 		if (info->intercept == x86_intercept_lmsw) {
5033 			icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
5034 			break;
5035 		}
5036 
5037 		/*
5038 		 * MOV-to-CR0 only triggers INTERCEPT_SELECTIVE_CR0 if any bit
5039 		 * other than SVM_CR0_SELECTIVE_MASK is changed.
5040 		 */
5041 		cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
5042 		val = info->src_val  & ~SVM_CR0_SELECTIVE_MASK;
5043 		if (cr0 ^ val)
5044 			icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
5045 		break;
5046 	}
5047 	case SVM_EXIT_READ_DR0:
5048 	case SVM_EXIT_WRITE_DR0:
5049 		icpt_info.exit_code += info->modrm_reg;
5050 		break;
5051 	case SVM_EXIT_MSR:
5052 		if (info->intercept == x86_intercept_wrmsr)
5053 			vmcb->control.exit_info_1 = 1;
5054 		else
5055 			vmcb->control.exit_info_1 = 0;
5056 		break;
5057 	case SVM_EXIT_PAUSE:
5058 		/*
5059 		 * We get this for NOP only, but pause
5060 		 * is rep not, check this here
5061 		 */
5062 		if (info->rep_prefix != REPE_PREFIX)
5063 			goto out;
5064 		break;
5065 	case SVM_EXIT_IOIO: {
5066 		u64 exit_info;
5067 		u32 bytes;
5068 
5069 		if (info->intercept == x86_intercept_in ||
5070 		    info->intercept == x86_intercept_ins) {
5071 			exit_info = ((info->src_val & 0xffff) << 16) |
5072 				SVM_IOIO_TYPE_MASK;
5073 			bytes = info->dst_bytes;
5074 		} else {
5075 			exit_info = (info->dst_val & 0xffff) << 16;
5076 			bytes = info->src_bytes;
5077 		}
5078 
5079 		if (info->intercept == x86_intercept_outs ||
5080 		    info->intercept == x86_intercept_ins)
5081 			exit_info |= SVM_IOIO_STR_MASK;
5082 
5083 		if (info->rep_prefix)
5084 			exit_info |= SVM_IOIO_REP_MASK;
5085 
5086 		bytes = min(bytes, 4u);
5087 
5088 		exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
5089 
5090 		exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
5091 
5092 		vmcb->control.exit_info_1 = exit_info;
5093 		vmcb->control.exit_info_2 = info->next_rip;
5094 
5095 		break;
5096 	}
5097 	default:
5098 		break;
5099 	}
5100 
5101 	/* TODO: Advertise NRIPS to guest hypervisor unconditionally */
5102 	if (cpu_feature_enabled(X86_FEATURE_NRIPS))
5103 		vmcb->control.next_rip  = info->next_rip;
5104 	vmcb->control.exit_code = icpt_info.exit_code;
5105 	vmexit = nested_svm_exit_handled(svm);
5106 
5107 	ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
5108 					   : X86EMUL_CONTINUE;
5109 
5110 out:
5111 	return ret;
5112 }
5113 
5114 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu)
5115 {
5116 	switch (to_svm(vcpu)->vmcb->control.exit_code) {
5117 	case SVM_EXIT_EXCP_BASE + MC_VECTOR:
5118 		svm_handle_mce(vcpu);
5119 		break;
5120 	case SVM_EXIT_INTR:
5121 		vcpu->arch.at_instruction_boundary = true;
5122 		break;
5123 	default:
5124 		break;
5125 	}
5126 }
5127 
5128 static void svm_setup_mce(struct kvm_vcpu *vcpu)
5129 {
5130 	/* [63:9] are reserved. */
5131 	vcpu->arch.mcg_cap &= 0x1ff;
5132 }
5133 
5134 #ifdef CONFIG_KVM_SMM
5135 bool svm_smi_blocked(struct kvm_vcpu *vcpu)
5136 {
5137 	struct vcpu_svm *svm = to_svm(vcpu);
5138 
5139 	/* Per APM Vol.2 15.22.2 "Response to SMI" */
5140 	if (!gif_set(svm))
5141 		return true;
5142 
5143 	return is_smm(vcpu);
5144 }
5145 
5146 static int svm_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
5147 {
5148 	struct vcpu_svm *svm = to_svm(vcpu);
5149 	if (vcpu->arch.nested_run_pending)
5150 		return -EBUSY;
5151 
5152 	if (svm_smi_blocked(vcpu))
5153 		return 0;
5154 
5155 	/* An SMI must not be injected into L2 if it's supposed to VM-Exit.  */
5156 	if (for_injection && is_guest_mode(vcpu) && nested_exit_on_smi(svm))
5157 		return -EBUSY;
5158 
5159 	return 1;
5160 }
5161 
5162 static int svm_enter_smm(struct kvm_vcpu *vcpu, union kvm_smram *smram)
5163 {
5164 	struct vcpu_svm *svm = to_svm(vcpu);
5165 
5166 	if (!is_guest_mode(vcpu))
5167 		return 0;
5168 
5169 	/*
5170 	 * 32-bit SMRAM format doesn't preserve EFER and SVM state.  Userspace is
5171 	 * responsible for ensuring nested SVM and SMIs are mutually exclusive.
5172 	 */
5173 
5174 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
5175 		return 1;
5176 
5177 	smram->smram64.svm_guest_flag = 1;
5178 	smram->smram64.svm_guest_vmcb_gpa = svm->nested.vmcb12_gpa;
5179 
5180 	svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5181 	svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5182 	svm->vmcb->save.rip = vcpu->arch.rip;
5183 
5184 	nested_svm_simple_vmexit(svm, SVM_EXIT_SW);
5185 
5186 	/*
5187 	 * KVM uses VMCB01 to store L1 host state while L2 runs but
5188 	 * VMCB01 is going to be used during SMM and thus the state will
5189 	 * be lost. Temporary save non-VMLOAD/VMSAVE state to the host save
5190 	 * area pointed to by MSR_VM_HSAVE_PA. APM guarantees that the
5191 	 * format of the area is identical to guest save area offsetted
5192 	 * by 0x400 (matches the offset of 'struct vmcb_save_area'
5193 	 * within 'struct vmcb'). Note: HSAVE area may also be used by
5194 	 * L1 hypervisor to save additional host context (e.g. KVM does
5195 	 * that, see svm_prepare_switch_to_guest()) which must be
5196 	 * preserved.
5197 	 */
5198 	CLASS(kvm_vcpu_map_local, m_save)(vcpu, gpa_to_gfn(svm->nested.hsave_msr));
5199 	if (m_save.ret)
5200 		return 1;
5201 
5202 	BUILD_BUG_ON(offsetof(struct vmcb, save) != 0x400);
5203 
5204 	svm_copy_vmrun_state(vcpu, m_save.map.hva + 0x400, &svm->vmcb01.ptr->save);
5205 	return 0;
5206 }
5207 
5208 static int svm_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram)
5209 {
5210 	struct vcpu_svm *svm = to_svm(vcpu);
5211 	struct vmcb *vmcb12;
5212 
5213 	const struct kvm_smram_state_64 *smram64 = &smram->smram64;
5214 
5215 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
5216 		return 0;
5217 
5218 	/* Non-zero if SMI arrived while vCPU was in guest mode. */
5219 	if (!smram64->svm_guest_flag)
5220 		return 0;
5221 
5222 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SVM))
5223 		return 1;
5224 
5225 	if (!(smram64->efer & EFER_SVME))
5226 		return 1;
5227 
5228 	CLASS(kvm_vcpu_map_local, m)(vcpu, gpa_to_gfn(smram64->svm_guest_vmcb_gpa));
5229 	if (m.ret)
5230 		return 1;
5231 
5232 	CLASS(kvm_vcpu_map_local, m_save)(vcpu, gpa_to_gfn(svm->nested.hsave_msr));
5233 	if (m_save.ret)
5234 		return 1;
5235 
5236 	if (svm_allocate_nested(svm))
5237 		return 1;
5238 
5239 	/*
5240 	 * Restore L1 host state from L1 HSAVE area as VMCB01 was
5241 	 * used during SMM (see svm_enter_smm())
5242 	 */
5243 
5244 	svm_copy_vmrun_state(vcpu, &svm->vmcb01.ptr->save, m_save.map.hva + 0x400);
5245 	if (!nested_svm_check_vmcb01_save(vcpu, &svm->vmcb01.ptr->save))
5246 		return 1;
5247 
5248 	/*
5249 	 * Enter the nested guest now
5250 	 */
5251 
5252 	vmcb_mark_all_dirty(svm->vmcb01.ptr);
5253 
5254 	vmcb12 = m.map.hva;
5255 	nested_copy_vmcb_control_to_cache(svm, &vmcb12->control);
5256 	nested_copy_vmcb_save_to_cache(svm, &vmcb12->save);
5257 
5258 	if (nested_svm_check_cached_vmcb12(vcpu) < 0)
5259 		return 1;
5260 
5261 	if (enter_svm_guest_mode(vcpu, smram64->svm_guest_vmcb_gpa, false) != 0)
5262 		return 1;
5263 
5264 	vcpu->arch.nested_run_pending = KVM_NESTED_RUN_PENDING;
5265 	return 0;
5266 }
5267 
5268 static void svm_enable_smi_window(struct kvm_vcpu *vcpu)
5269 {
5270 	struct vcpu_svm *svm = to_svm(vcpu);
5271 
5272 	if (!gif_set(svm)) {
5273 		if (vgif)
5274 			svm_set_intercept(svm, INTERCEPT_STGI);
5275 		/* STGI will cause a vm exit */
5276 	} else {
5277 		/* We must be in SMM; RSM will cause a vmexit anyway.  */
5278 	}
5279 }
5280 #endif
5281 
5282 static int svm_check_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
5283 					 void *insn, int insn_len)
5284 {
5285 	struct vcpu_svm *svm = to_svm(vcpu);
5286 	bool smep, smap, is_user;
5287 	u64 error_code;
5288 
5289 	/* Check that emulation is possible during event vectoring */
5290 	if ((svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK) &&
5291 	    !kvm_can_emulate_event_vectoring(emul_type))
5292 		return X86EMUL_UNHANDLEABLE_VECTORING;
5293 
5294 	/* Emulation is always possible when KVM has access to all guest state. */
5295 	if (!is_sev_guest(vcpu))
5296 		return X86EMUL_CONTINUE;
5297 
5298 	/* #UD and #GP should never be intercepted for SEV guests. */
5299 	WARN_ON_ONCE(emul_type & (EMULTYPE_TRAP_UD |
5300 				  EMULTYPE_TRAP_UD_FORCED |
5301 				  EMULTYPE_VMWARE_GP));
5302 
5303 	/*
5304 	 * Emulation is impossible for SEV-ES guests as KVM doesn't have access
5305 	 * to guest register state.
5306 	 */
5307 	if (is_sev_es_guest(vcpu))
5308 		return X86EMUL_RETRY_INSTR;
5309 
5310 	/*
5311 	 * Emulation is possible if the instruction is already decoded, e.g.
5312 	 * when completing I/O after returning from userspace.
5313 	 */
5314 	if (emul_type & EMULTYPE_NO_DECODE)
5315 		return X86EMUL_CONTINUE;
5316 
5317 	/*
5318 	 * Emulation is possible for SEV guests if and only if a prefilled
5319 	 * buffer containing the bytes of the intercepted instruction is
5320 	 * available. SEV guest memory is encrypted with a guest specific key
5321 	 * and cannot be decrypted by KVM, i.e. KVM would read ciphertext and
5322 	 * decode garbage.
5323 	 *
5324 	 * If KVM is NOT trying to simply skip an instruction, inject #UD if
5325 	 * KVM reached this point without an instruction buffer.  In practice,
5326 	 * this path should never be hit by a well-behaved guest, e.g. KVM
5327 	 * doesn't intercept #UD or #GP for SEV guests, but this path is still
5328 	 * theoretically reachable, e.g. via unaccelerated fault-like AVIC
5329 	 * access, and needs to be handled by KVM to avoid putting the guest
5330 	 * into an infinite loop.   Injecting #UD is somewhat arbitrary, but
5331 	 * its the least awful option given lack of insight into the guest.
5332 	 *
5333 	 * If KVM is trying to skip an instruction, simply resume the guest.
5334 	 * If a #NPF occurs while the guest is vectoring an INT3/INTO, then KVM
5335 	 * will attempt to re-inject the INT3/INTO and skip the instruction.
5336 	 * In that scenario, retrying the INT3/INTO and hoping the guest will
5337 	 * make forward progress is the only option that has a chance of
5338 	 * success (and in practice it will work the vast majority of the time).
5339 	 */
5340 	if (unlikely(!insn)) {
5341 		if (emul_type & EMULTYPE_SKIP)
5342 			return X86EMUL_UNHANDLEABLE;
5343 
5344 		kvm_queue_exception(vcpu, UD_VECTOR);
5345 		return X86EMUL_PROPAGATE_FAULT;
5346 	}
5347 
5348 	/*
5349 	 * Under SEV, page tables are encrypted and cannot be read by the
5350 	 * hypervisor, so there is no way to resolve a fault on page tables.
5351 	 */
5352 	error_code = svm->vmcb->control.exit_info_1;
5353 	if (error_code & PFERR_GUEST_PAGE_MASK)
5354 		goto resume_guest;
5355 
5356 	if (likely(insn_len))
5357 		return X86EMUL_CONTINUE;
5358 
5359 	/*
5360 	 * The insn buffer was empty; the DecodeAssist microcode could not fetch
5361 	 * bytes for the faulting instruction because the code fetch itself faulted,
5362 	 * e.g. the guest attempted to fetch from emulated MMIO or a guest page
5363 	 * table used to translate CS:RIP resides in emulated MMIO.
5364 	 *
5365 	 * A data fault instead could be Errata 1096 Fam_17h_00_0Fh, so only
5366 	 * retry for a fetch fault and otherwise try to workaround it.
5367 	 */
5368 	if (error_code & PFERR_FETCH_MASK)
5369 		goto resume_guest;
5370 
5371 	/*
5372 	 * When CPU raises #NPF on guest data access and vCPU CR4.SMAP=1, it is
5373 	 * possible that CPU microcode implementing DecodeAssist will fail to
5374 	 * read guest memory at CS:RIP and vmcb.GuestIntrBytes will incorrectly
5375 	 * be '0'.  This happens because microcode reads CS:RIP using a _data_
5376 	 * loap uop with CPL=0 privileges.  If the load hits a SMAP #PF, ucode
5377 	 * gives up and does not fill the instruction bytes buffer.
5378 	 *
5379 	 * As above, KVM reaches this point iff the VM is an SEV guest, the CPU
5380 	 * supports DecodeAssist, a #NPF was raised, KVM's page fault handler
5381 	 * triggered emulation (e.g. for MMIO), and the CPU returned 0 in the
5382 	 * GuestIntrBytes field of the VMCB.
5383 	 *
5384 	 * This does _not_ mean that the erratum has been encountered, as the
5385 	 * DecodeAssist will also fail if the load for CS:RIP hits a legitimate
5386 	 * #PF, e.g. if the guest attempt to execute from emulated MMIO and
5387 	 * encountered a reserved/not-present #PF.
5388 	 *
5389 	 * To hit the erratum, the following conditions must be true:
5390 	 *    1. CR4.SMAP=1 (obviously).
5391 	 *    2. CR4.SMEP=0 || CPL=3.  If SMEP=1 and CPL<3, the erratum cannot
5392 	 *       have been hit as the guest would have encountered a SMEP
5393 	 *       violation #PF, not a #NPF.
5394 	 *    3. The #NPF is not due to a code fetch, in which case failure to
5395 	 *       retrieve the instruction bytes is legitimate (see abvoe).
5396 	 *
5397 	 * In addition, don't apply the erratum workaround if the #NPF occurred
5398 	 * while translating guest page tables (see above).
5399 	 */
5400 	smep = kvm_is_cr4_bit_set(vcpu, X86_CR4_SMEP);
5401 	smap = kvm_is_cr4_bit_set(vcpu, X86_CR4_SMAP);
5402 	is_user = svm_get_cpl(vcpu) == 3;
5403 	if (smap && (!smep || is_user)) {
5404 		pr_err_ratelimited("SEV Guest triggered AMD Erratum 1096\n");
5405 
5406 		/*
5407 		 * If the fault occurred in userspace, arbitrarily inject #GP
5408 		 * to avoid killing the guest and to hopefully avoid confusing
5409 		 * the guest kernel too much, e.g. injecting #PF would not be
5410 		 * coherent with respect to the guest's page tables.  Request
5411 		 * triple fault if the fault occurred in the kernel as there's
5412 		 * no fault that KVM can inject without confusing the guest.
5413 		 * In practice, the triple fault is moot as no sane SEV kernel
5414 		 * will execute from user memory while also running with SMAP=1.
5415 		 */
5416 		if (is_user)
5417 			kvm_inject_gp(vcpu, 0);
5418 		else
5419 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5420 		return X86EMUL_PROPAGATE_FAULT;
5421 	}
5422 
5423 resume_guest:
5424 	/*
5425 	 * If the erratum was not hit, simply resume the guest and let it fault
5426 	 * again.  While awful, e.g. the vCPU may get stuck in an infinite loop
5427 	 * if the fault is at CPL=0, it's the lesser of all evils.  Exiting to
5428 	 * userspace will kill the guest, and letting the emulator read garbage
5429 	 * will yield random behavior and potentially corrupt the guest.
5430 	 *
5431 	 * Simply resuming the guest is technically not a violation of the SEV
5432 	 * architecture.  AMD's APM states that all code fetches and page table
5433 	 * accesses for SEV guest are encrypted, regardless of the C-Bit.  The
5434 	 * APM also states that encrypted accesses to MMIO are "ignored", but
5435 	 * doesn't explicitly define "ignored", i.e. doing nothing and letting
5436 	 * the guest spin is technically "ignoring" the access.
5437 	 */
5438 	return X86EMUL_RETRY_INSTR;
5439 }
5440 
5441 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
5442 {
5443 	struct vcpu_svm *svm = to_svm(vcpu);
5444 
5445 	return !gif_set(svm);
5446 }
5447 
5448 static void svm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
5449 {
5450 	if (!is_sev_es_guest(vcpu))
5451 		return kvm_vcpu_deliver_sipi_vector(vcpu, vector);
5452 
5453 	sev_vcpu_deliver_sipi_vector(vcpu, vector);
5454 }
5455 
5456 static void svm_vm_destroy(struct kvm *kvm)
5457 {
5458 	avic_vm_destroy(kvm);
5459 	sev_vm_destroy(kvm);
5460 
5461 	svm_srso_vm_destroy();
5462 }
5463 
5464 static int svm_vm_init(struct kvm *kvm)
5465 {
5466 	sev_vm_init(kvm);
5467 
5468 	if (!pause_filter_count || !pause_filter_thresh)
5469 		kvm_disable_exits(kvm, KVM_X86_DISABLE_EXITS_PAUSE);
5470 
5471 	if (pml)
5472 		kvm->arch.cpu_dirty_log_size = PML_LOG_NR_ENTRIES;
5473 
5474 	svm_srso_vm_init();
5475 	return 0;
5476 }
5477 
5478 static void *svm_alloc_apic_backing_page(struct kvm_vcpu *vcpu)
5479 {
5480 	struct page *page = snp_safe_alloc_page();
5481 
5482 	if (!page)
5483 		return NULL;
5484 
5485 	return page_address(page);
5486 }
5487 
5488 struct kvm_x86_ops svm_x86_ops __initdata = {
5489 	.name = KBUILD_MODNAME,
5490 
5491 	.check_processor_compatibility = svm_check_processor_compat,
5492 
5493 	.hardware_unsetup = svm_hardware_unsetup,
5494 	.enable_virtualization_cpu = svm_enable_virtualization_cpu,
5495 	.disable_virtualization_cpu = svm_disable_virtualization_cpu,
5496 	.emergency_disable_virtualization_cpu = svm_emergency_disable_virtualization_cpu,
5497 	.has_emulated_msr = svm_has_emulated_msr,
5498 
5499 	.vcpu_precreate = avic_vcpu_precreate,
5500 	.vcpu_create = svm_vcpu_create,
5501 	.vcpu_free = svm_vcpu_free,
5502 	.vcpu_reset = svm_vcpu_reset,
5503 
5504 	.vm_size = sizeof(struct kvm_svm),
5505 	.vm_init = svm_vm_init,
5506 	.vm_pre_destroy = avic_vm_pre_destroy,
5507 	.vm_destroy = svm_vm_destroy,
5508 
5509 	.prepare_switch_to_guest = svm_prepare_switch_to_guest,
5510 	.vcpu_load = svm_vcpu_load,
5511 	.vcpu_put = svm_vcpu_put,
5512 	.vcpu_blocking = avic_vcpu_blocking,
5513 	.vcpu_unblocking = avic_vcpu_unblocking,
5514 
5515 	.update_exception_bitmap = svm_update_exception_bitmap,
5516 	.get_feature_msr = svm_get_feature_msr,
5517 	.get_msr = svm_get_msr,
5518 	.set_msr = svm_set_msr,
5519 	.get_segment_base = svm_get_segment_base,
5520 	.get_segment = svm_get_segment,
5521 	.set_segment = svm_set_segment,
5522 	.get_cpl = svm_get_cpl,
5523 	.get_cpl_no_cache = svm_get_cpl,
5524 	.get_cs_db_l_bits = svm_get_cs_db_l_bits,
5525 	.is_valid_cr0 = svm_is_valid_cr0,
5526 	.set_cr0 = svm_set_cr0,
5527 	.post_set_cr3 = sev_post_set_cr3,
5528 	.is_valid_cr4 = svm_is_valid_cr4,
5529 	.set_cr4 = svm_set_cr4,
5530 	.set_efer = svm_set_efer,
5531 	.get_idt = svm_get_idt,
5532 	.set_idt = svm_set_idt,
5533 	.get_gdt = svm_get_gdt,
5534 	.set_gdt = svm_set_gdt,
5535 	.set_dr7 = svm_set_dr7,
5536 	.sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
5537 	.cache_reg = svm_cache_reg,
5538 	.get_rflags = svm_get_rflags,
5539 	.set_rflags = svm_set_rflags,
5540 	.get_if_flag = svm_get_if_flag,
5541 
5542 	.flush_tlb_all = svm_flush_tlb_all,
5543 	.flush_tlb_current = svm_flush_tlb_current,
5544 	.flush_tlb_gva = svm_flush_tlb_gva,
5545 	.flush_tlb_guest = svm_flush_tlb_guest,
5546 
5547 	.vcpu_run = svm_vcpu_run,
5548 	.handle_exit = svm_handle_exit,
5549 	.skip_emulated_instruction = svm_skip_emulated_instruction,
5550 	.update_emulated_instruction = NULL,
5551 	.set_interrupt_shadow = svm_set_interrupt_shadow,
5552 	.get_interrupt_shadow = svm_get_interrupt_shadow,
5553 	.patch_hypercall = svm_patch_hypercall,
5554 	.inject_irq = svm_inject_irq,
5555 	.inject_nmi = svm_inject_nmi,
5556 	.is_vnmi_pending = svm_is_vnmi_pending,
5557 	.set_vnmi_pending = svm_set_vnmi_pending,
5558 	.inject_exception = svm_inject_exception,
5559 	.cancel_injection = svm_cancel_injection,
5560 	.interrupt_allowed = svm_interrupt_allowed,
5561 	.nmi_allowed = svm_nmi_allowed,
5562 	.get_nmi_mask = svm_get_nmi_mask,
5563 	.set_nmi_mask = svm_set_nmi_mask,
5564 	.enable_nmi_window = svm_enable_nmi_window,
5565 	.enable_irq_window = svm_enable_irq_window,
5566 	.update_cr8_intercept = svm_update_cr8_intercept,
5567 
5568 	.x2apic_icr_is_split = true,
5569 	.set_virtual_apic_mode = avic_refresh_virtual_apic_mode,
5570 	.refresh_apicv_exec_ctrl = avic_refresh_apicv_exec_ctrl,
5571 	.apicv_post_state_restore = avic_apicv_post_state_restore,
5572 	.required_apicv_inhibits = AVIC_REQUIRED_APICV_INHIBITS,
5573 
5574 	.get_exit_info = svm_get_exit_info,
5575 	.get_entry_info = svm_get_entry_info,
5576 
5577 	.vcpu_after_set_cpuid = svm_vcpu_after_set_cpuid,
5578 
5579 	.has_wbinvd_exit = svm_has_wbinvd_exit,
5580 
5581 	.get_l2_tsc_offset = svm_get_l2_tsc_offset,
5582 	.get_l2_tsc_multiplier = svm_get_l2_tsc_multiplier,
5583 	.write_tsc_offset = svm_write_tsc_offset,
5584 	.write_tsc_multiplier = svm_write_tsc_multiplier,
5585 
5586 	.load_mmu_pgd = svm_load_mmu_pgd,
5587 	.tdp_has_smep = svm_tdp_has_smep,
5588 
5589 	.check_intercept = svm_check_intercept,
5590 	.handle_exit_irqoff = svm_handle_exit_irqoff,
5591 
5592 	.update_cpu_dirty_logging = svm_update_cpu_dirty_logging,
5593 
5594 	.deliver_interrupt = svm_deliver_interrupt,
5595 	.pi_update_irte = avic_pi_update_irte,
5596 	.setup_mce = svm_setup_mce,
5597 
5598 #ifdef CONFIG_KVM_SMM
5599 	.smi_allowed = svm_smi_allowed,
5600 	.enter_smm = svm_enter_smm,
5601 	.leave_smm = svm_leave_smm,
5602 	.enable_smi_window = svm_enable_smi_window,
5603 #endif
5604 
5605 #ifdef CONFIG_KVM_AMD_SEV
5606 	.vcpu_needs_initialization = sev_vcpu_needs_initialization,
5607 	.dev_get_attr = sev_dev_get_attr,
5608 	.mem_enc_ioctl = sev_mem_enc_ioctl,
5609 	.mem_enc_register_region = sev_mem_enc_register_region,
5610 	.mem_enc_unregister_region = sev_mem_enc_unregister_region,
5611 	.guest_memory_reclaimed = sev_guest_memory_reclaimed,
5612 	.reload_vmsa = sev_snp_reload_vmsa,
5613 
5614 	.vm_copy_enc_context_from = sev_vm_copy_enc_context_from,
5615 	.vm_move_enc_context_from = sev_vm_move_enc_context_from,
5616 
5617 	.gmem_make_private = sev_gmem_make_private,
5618 	.gmem_make_shared = sev_gmem_make_shared,
5619 	.gmem_invalidate_range = sev_gmem_invalidate_range,
5620 	.gmem_max_mapping_level = sev_gmem_max_mapping_level,
5621 #endif
5622 	.check_emulate_instruction = svm_check_emulate_instruction,
5623 
5624 	.apic_init_signal_blocked = svm_apic_init_signal_blocked,
5625 
5626 	.recalc_intercepts = svm_recalc_intercepts,
5627 	.complete_emulated_msr = svm_complete_emulated_msr,
5628 
5629 	.vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector,
5630 	.vcpu_get_apicv_inhibit_reasons = avic_vcpu_get_apicv_inhibit_reasons,
5631 	.alloc_apic_backing_page = svm_alloc_apic_backing_page,
5632 };
5633 
5634 /*
5635  * The default MMIO mask is a single bit (excluding the present bit),
5636  * which could conflict with the memory encryption bit. Check for
5637  * memory encryption support and override the default MMIO mask if
5638  * memory encryption is enabled.
5639  */
5640 static __init void svm_adjust_mmio_mask(void)
5641 {
5642 	unsigned int enc_bit, mask_bit;
5643 	u64 msr, mask;
5644 
5645 	/* If there is no memory encryption support, use existing mask */
5646 	if (cpuid_eax(0x80000000) < 0x8000001f)
5647 		return;
5648 
5649 	/* If memory encryption is not enabled, use existing mask */
5650 	rdmsrq(MSR_AMD64_SYSCFG, msr);
5651 	if (!(msr & MSR_AMD64_SYSCFG_MEM_ENCRYPT))
5652 		return;
5653 
5654 	enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
5655 	mask_bit = boot_cpu_data.x86_phys_bits;
5656 
5657 	/* Increment the mask bit if it is the same as the encryption bit */
5658 	if (enc_bit == mask_bit)
5659 		mask_bit++;
5660 
5661 	/*
5662 	 * If the mask bit location is below 52, then some bits above the
5663 	 * physical addressing limit will always be reserved, so use the
5664 	 * rsvd_bits() function to generate the mask. This mask, along with
5665 	 * the present bit, will be used to generate a page fault with
5666 	 * PFER.RSV = 1.
5667 	 *
5668 	 * If the mask bit location is 52 (or above), then clear the mask.
5669 	 */
5670 	mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
5671 
5672 	kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
5673 }
5674 
5675 static __init void svm_set_cpu_caps(void)
5676 {
5677 	kvm_initialize_cpu_caps();
5678 
5679 	kvm_caps.supported_perf_cap = 0;
5680 
5681 	kvm_cpu_cap_clear(X86_FEATURE_IBT);
5682 
5683 	/* CPUID 0x80000001 and 0x8000000A (SVM features) */
5684 	if (nested) {
5685 		kvm_cpu_cap_set(X86_FEATURE_SVM);
5686 		kvm_cpu_cap_set(X86_FEATURE_VMCBCLEAN);
5687 
5688 		/*
5689 		 * KVM currently flushes TLBs on *every* nested SVM transition,
5690 		 * and so for all intents and purposes KVM supports flushing by
5691 		 * ASID, i.e. KVM is guaranteed to honor every L1 ASID flush.
5692 		 */
5693 		kvm_cpu_cap_set(X86_FEATURE_FLUSHBYASID);
5694 
5695 		if (nrips)
5696 			kvm_cpu_cap_set(X86_FEATURE_NRIPS);
5697 
5698 		if (npt_enabled)
5699 			kvm_cpu_cap_set(X86_FEATURE_NPT);
5700 
5701 		if (tsc_scaling)
5702 			kvm_cpu_cap_set(X86_FEATURE_TSCRATEMSR);
5703 
5704 		if (vls)
5705 			kvm_cpu_cap_set(X86_FEATURE_V_VMSAVE_VMLOAD);
5706 		if (lbrv)
5707 			kvm_cpu_cap_set(X86_FEATURE_LBRV);
5708 
5709 		if (boot_cpu_has(X86_FEATURE_PAUSEFILTER))
5710 			kvm_cpu_cap_set(X86_FEATURE_PAUSEFILTER);
5711 
5712 		if (boot_cpu_has(X86_FEATURE_PFTHRESHOLD))
5713 			kvm_cpu_cap_set(X86_FEATURE_PFTHRESHOLD);
5714 
5715 		if (gmet_enabled)
5716 			kvm_cpu_cap_set(X86_FEATURE_GMET);
5717 
5718 		if (vgif)
5719 			kvm_cpu_cap_set(X86_FEATURE_VGIF);
5720 
5721 		if (vnmi)
5722 			kvm_cpu_cap_set(X86_FEATURE_VNMI);
5723 
5724 		/* Nested VM can receive #VMEXIT instead of triggering #GP */
5725 		kvm_cpu_cap_set(X86_FEATURE_SVME_ADDR_CHK);
5726 	}
5727 
5728 	if (cpu_feature_enabled(X86_FEATURE_BUS_LOCK_THRESHOLD))
5729 		kvm_caps.has_bus_lock_exit = true;
5730 
5731 	/* CPUID 0x80000008 */
5732 	if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
5733 	    boot_cpu_has(X86_FEATURE_AMD_SSBD))
5734 		kvm_cpu_cap_set(X86_FEATURE_VIRT_SSBD);
5735 
5736 	/*
5737 	 * Tell userspace that EFER.LMSLE must be zero if nested SVM is
5738 	 * disabled, as KVM allows EFER.LMSLE if and only if nested SVM is
5739 	 * supported (a historical artifact of commit eec4b140c924 ("KVM: SVM:
5740 	 * Allow EFER.LMSLE to be set with nested svm"), not an architectural
5741 	 * requirement).
5742 	 */
5743 	if (!nested)
5744 		kvm_cpu_cap_set(X86_FEATURE_EFER_LMSLE_MBZ);
5745 
5746 	if (enable_pmu) {
5747 		/*
5748 		 * Enumerate support for PERFCTR_CORE if and only if KVM has
5749 		 * access to enough counters to virtualize "core" support,
5750 		 * otherwise limit vPMU support to the legacy number of counters.
5751 		 */
5752 		if (kvm_pmu_cap.num_counters_gp < AMD64_NUM_COUNTERS_CORE)
5753 			kvm_pmu_cap.num_counters_gp = min(AMD64_NUM_COUNTERS,
5754 							  kvm_pmu_cap.num_counters_gp);
5755 		else
5756 			kvm_cpu_cap_check_and_set(X86_FEATURE_PERFCTR_CORE);
5757 
5758 		if (kvm_pmu_cap.version != 2 ||
5759 		    !kvm_cpu_cap_has(X86_FEATURE_PERFCTR_CORE))
5760 			kvm_cpu_cap_clear(X86_FEATURE_PERFMON_V2);
5761 	}
5762 
5763 	/* CPUID 0x8000001F (SME/SEV features) */
5764 	sev_set_cpu_caps();
5765 
5766 	/*
5767 	 * Clear capabilities that are automatically configured by common code,
5768 	 * but that require explicit SVM support (that isn't yet implemented).
5769 	 */
5770 	kvm_cpu_cap_clear(X86_FEATURE_MSR_IMM);
5771 
5772 	/*
5773 	 * LBR Virtualization must be enabled to support BusLockTrap inside the
5774 	 * guest, since BusLockTrap is enabled through MSR_IA32_DEBUGCTLMSR and
5775 	 * MSR_IA32_DEBUGCTLMSR is virtualized only if LBR Virtualization is
5776 	 * enabled.
5777 	 */
5778 	if (!lbrv)
5779 		kvm_cpu_cap_clear(X86_FEATURE_BUS_LOCK_DETECT);
5780 
5781 	kvm_setup_xss_caps();
5782 	kvm_finalize_cpu_caps();
5783 }
5784 
5785 static __init int svm_hardware_setup(void)
5786 {
5787 	void *iopm_va;
5788 	int cpu, r;
5789 
5790 	/*
5791 	 * NX is required for shadow paging and for NPT if the NX huge pages
5792 	 * mitigation is enabled.
5793 	 */
5794 	if (!boot_cpu_has(X86_FEATURE_NX)) {
5795 		pr_err_ratelimited("NX (Execute Disable) not supported\n");
5796 		return -EOPNOTSUPP;
5797 	}
5798 
5799 	kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
5800 				     XFEATURE_MASK_BNDCSR);
5801 
5802 	if (tsc_scaling) {
5803 		if (!boot_cpu_has(X86_FEATURE_TSCRATEMSR) ||
5804 		    !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5805 			tsc_scaling = false;
5806 		} else {
5807 			pr_info("TSC scaling supported\n");
5808 			kvm_caps.has_tsc_control = true;
5809 		}
5810 	}
5811 	kvm_caps.max_tsc_scaling_ratio = SVM_TSC_RATIO_MAX;
5812 	kvm_caps.tsc_scaling_ratio_frac_bits = 32;
5813 
5814 	tsc_aux_uret_slot = kvm_add_user_return_msr(MSR_TSC_AUX);
5815 
5816 	/* Check for pause filtering support */
5817 	if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
5818 		pause_filter_count = 0;
5819 		pause_filter_thresh = 0;
5820 	} else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
5821 		pause_filter_thresh = 0;
5822 	}
5823 
5824 	if (nested) {
5825 		pr_info("Nested Virtualization enabled\n");
5826 		r = nested_svm_init_msrpm_merge_offsets();
5827 		if (r)
5828 			return r;
5829 	}
5830 	svm_nested_ops.enabled = nested;
5831 
5832 	/*
5833 	 * KVM's MMU doesn't support using 2-level paging for itself, and thus
5834 	 * NPT isn't supported if the host is using 2-level paging since host
5835 	 * CR4 is unchanged on VMRUN.
5836 	 */
5837 	if (!IS_ENABLED(CONFIG_X86_64) && !IS_ENABLED(CONFIG_X86_PAE))
5838 		npt_enabled = false;
5839 
5840 	if (!boot_cpu_has(X86_FEATURE_NPT))
5841 		npt_enabled = false;
5842 
5843 	if (!npt_enabled || !boot_cpu_has(X86_FEATURE_GMET))
5844 		gmet_enabled = false;
5845 
5846 	/* Force VM NPT level equal to the host's paging level */
5847 	kvm_configure_mmu(npt_enabled, get_npt_level(),
5848 			  get_npt_level(), PG_LEVEL_1G);
5849 	pr_info("Nested Paging %s\n", str_enabled_disabled(npt_enabled));
5850 
5851 	/*
5852 	 * It seems that on AMD processors PTE's accessed bit is
5853 	 * being set by the CPU hardware before the NPF vmexit.
5854 	 * This is not expected behaviour and our tests fail because
5855 	 * of it.
5856 	 * A workaround here is to disable support for
5857 	 * GUEST_MAXPHYADDR < HOST_MAXPHYADDR if NPT is enabled.
5858 	 * In this case userspace can know if there is support using
5859 	 * KVM_CAP_SMALLER_MAXPHYADDR extension and decide how to handle
5860 	 * it
5861 	 * If future AMD CPU models change the behaviour described above,
5862 	 * this variable can be changed accordingly
5863 	 */
5864 	allow_smaller_maxphyaddr = !npt_enabled;
5865 
5866 	/* Setup shadow_me_value and shadow_me_mask */
5867 	kvm_mmu_set_me_spte_mask(sme_me_mask, sme_me_mask);
5868 
5869 	svm_adjust_mmio_mask();
5870 
5871 	nrips = nrips && boot_cpu_has(X86_FEATURE_NRIPS);
5872 
5873 	pml = pml && npt_enabled && cpu_feature_enabled(X86_FEATURE_PML);
5874 	if (pml)
5875 		pr_info("Page modification logging supported\n");
5876 
5877 	if (lbrv) {
5878 		if (!boot_cpu_has(X86_FEATURE_LBRV))
5879 			lbrv = false;
5880 		else
5881 			pr_info("LBR virtualization supported\n");
5882 	}
5883 
5884 	iopm_va = svm_alloc_permissions_map(IOPM_SIZE, GFP_KERNEL);
5885 	if (!iopm_va)
5886 		return -ENOMEM;
5887 
5888 	iopm_base = __sme_set(__pa(iopm_va));
5889 
5890 	/*
5891 	 * Note, SEV setup consumes npt_enabled and enable_mmio_caching (which
5892 	 * may be modified by svm_adjust_mmio_mask()), as well as nrips.
5893 	 */
5894 	sev_hardware_setup();
5895 
5896 	svm_hv_hardware_setup();
5897 
5898 	enable_apicv = avic_hardware_setup();
5899 	if (!enable_apicv) {
5900 		enable_ipiv = false;
5901 		svm_x86_ops.vcpu_precreate = NULL;
5902 		svm_x86_ops.vm_pre_destroy = NULL;
5903 		svm_x86_ops.vcpu_blocking = NULL;
5904 		svm_x86_ops.vcpu_unblocking = NULL;
5905 		svm_x86_ops.vcpu_get_apicv_inhibit_reasons = NULL;
5906 	}
5907 
5908 	if (vls) {
5909 		if (!npt_enabled ||
5910 		    !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
5911 		    !IS_ENABLED(CONFIG_X86_64)) {
5912 			vls = false;
5913 		} else {
5914 			pr_info("Virtual VMLOAD VMSAVE supported\n");
5915 		}
5916 	}
5917 
5918 	if (boot_cpu_has(X86_FEATURE_SVME_ADDR_CHK))
5919 		svm_gp_erratum_intercept = false;
5920 
5921 	if (vgif) {
5922 		if (!boot_cpu_has(X86_FEATURE_VGIF))
5923 			vgif = false;
5924 		else
5925 			pr_info("Virtual GIF supported\n");
5926 	}
5927 
5928 	vnmi = vgif && vnmi && boot_cpu_has(X86_FEATURE_VNMI);
5929 	if (vnmi)
5930 		pr_info("Virtual NMI enabled\n");
5931 
5932 	if (!vnmi) {
5933 		svm_x86_ops.is_vnmi_pending = NULL;
5934 		svm_x86_ops.set_vnmi_pending = NULL;
5935 	}
5936 
5937 	if (!enable_pmu)
5938 		pr_info("PMU virtualization is disabled\n");
5939 
5940 	svm_set_cpu_caps();
5941 
5942 	kvm_caps.inapplicable_quirks &= ~KVM_X86_QUIRK_CD_NW_CLEARED;
5943 
5944 	for_each_possible_cpu(cpu) {
5945 		r = svm_cpu_init(cpu);
5946 		if (r)
5947 			goto err;
5948 	}
5949 
5950 	return 0;
5951 
5952 err:
5953 	svm_hardware_unsetup();
5954 	return r;
5955 }
5956 
5957 
5958 static struct kvm_x86_init_ops svm_init_ops __initdata = {
5959 	.hardware_setup = svm_hardware_setup,
5960 
5961 	.runtime_ops = &svm_x86_ops,
5962 	.pmu_ops = &amd_pmu_ops,
5963 	.nested_ops = &svm_nested_ops,
5964 };
5965 
5966 static void __svm_exit(void)
5967 {
5968 	kvm_x86_vendor_exit();
5969 }
5970 
5971 static int __init svm_init(void)
5972 {
5973 	int r;
5974 
5975 	KVM_SANITY_CHECK_VM_STRUCT_SIZE(kvm_svm);
5976 
5977 	__unused_size_checks();
5978 
5979 	if (!kvm_is_svm_supported())
5980 		return -EOPNOTSUPP;
5981 
5982 	r = kvm_x86_vendor_init(&svm_init_ops);
5983 	if (r)
5984 		return r;
5985 
5986 	/*
5987 	 * Common KVM initialization _must_ come last, after this, /dev/kvm is
5988 	 * exposed to userspace!
5989 	 */
5990 	r = kvm_init(sizeof(struct vcpu_svm), __alignof__(struct vcpu_svm),
5991 		     THIS_MODULE);
5992 	if (r)
5993 		goto err_kvm_init;
5994 
5995 	return 0;
5996 
5997 err_kvm_init:
5998 	__svm_exit();
5999 	return r;
6000 }
6001 
6002 static void __exit svm_exit(void)
6003 {
6004 	kvm_exit();
6005 	__svm_exit();
6006 }
6007 
6008 module_init(svm_init)
6009 module_exit(svm_exit)
6010