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