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