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