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