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