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