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