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