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