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