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