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