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