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