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