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