• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * AMD SVM support
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
8  *
9  * Authors:
10  *   Yaniv Kamay  <yaniv@qumranet.com>
11  *   Avi Kivity   <avi@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17 
18 #define pr_fmt(fmt) "SVM: " fmt
19 
20 #include <linux/kvm_host.h>
21 
22 #include "irq.h"
23 #include "mmu.h"
24 #include "kvm_cache_regs.h"
25 #include "x86.h"
26 #include "cpuid.h"
27 #include "pmu.h"
28 
29 #include <linux/module.h>
30 #include <linux/mod_devicetable.h>
31 #include <linux/kernel.h>
32 #include <linux/vmalloc.h>
33 #include <linux/highmem.h>
34 #include <linux/sched.h>
35 #include <linux/trace_events.h>
36 #include <linux/slab.h>
37 #include <linux/amd-iommu.h>
38 #include <linux/hashtable.h>
39 #include <linux/frame.h>
40 #include <linux/psp-sev.h>
41 #include <linux/file.h>
42 #include <linux/pagemap.h>
43 #include <linux/swap.h>
44 
45 #include <asm/apic.h>
46 #include <asm/perf_event.h>
47 #include <asm/tlbflush.h>
48 #include <asm/desc.h>
49 #include <asm/debugreg.h>
50 #include <asm/kvm_para.h>
51 #include <asm/irq_remapping.h>
52 #include <asm/spec-ctrl.h>
53 
54 #include <asm/virtext.h>
55 #include "trace.h"
56 
57 #define __ex(x) __kvm_handle_fault_on_reboot(x)
58 
59 MODULE_AUTHOR("Qumranet");
60 MODULE_LICENSE("GPL");
61 
62 static const struct x86_cpu_id svm_cpu_id[] = {
63 	X86_FEATURE_MATCH(X86_FEATURE_SVM),
64 	{}
65 };
66 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
67 
68 #define IOPM_ALLOC_ORDER 2
69 #define MSRPM_ALLOC_ORDER 1
70 
71 #define SEG_TYPE_LDT 2
72 #define SEG_TYPE_BUSY_TSS16 3
73 
74 #define SVM_FEATURE_NPT            (1 <<  0)
75 #define SVM_FEATURE_LBRV           (1 <<  1)
76 #define SVM_FEATURE_SVML           (1 <<  2)
77 #define SVM_FEATURE_NRIP           (1 <<  3)
78 #define SVM_FEATURE_TSC_RATE       (1 <<  4)
79 #define SVM_FEATURE_VMCB_CLEAN     (1 <<  5)
80 #define SVM_FEATURE_FLUSH_ASID     (1 <<  6)
81 #define SVM_FEATURE_DECODE_ASSIST  (1 <<  7)
82 #define SVM_FEATURE_PAUSE_FILTER   (1 << 10)
83 
84 #define SVM_AVIC_DOORBELL	0xc001011b
85 
86 #define NESTED_EXIT_HOST	0	/* Exit handled on host level */
87 #define NESTED_EXIT_DONE	1	/* Exit caused nested vmexit  */
88 #define NESTED_EXIT_CONTINUE	2	/* Further checks needed      */
89 
90 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
91 
92 #define TSC_RATIO_RSVD          0xffffff0000000000ULL
93 #define TSC_RATIO_MIN		0x0000000000000001ULL
94 #define TSC_RATIO_MAX		0x000000ffffffffffULL
95 
96 #define AVIC_HPA_MASK	~((0xFFFULL << 52) | 0xFFF)
97 
98 /*
99  * 0xff is broadcast, so the max index allowed for physical APIC ID
100  * table is 0xfe.  APIC IDs above 0xff are reserved.
101  */
102 #define AVIC_MAX_PHYSICAL_ID_COUNT	255
103 
104 #define AVIC_UNACCEL_ACCESS_WRITE_MASK		1
105 #define AVIC_UNACCEL_ACCESS_OFFSET_MASK		0xFF0
106 #define AVIC_UNACCEL_ACCESS_VECTOR_MASK		0xFFFFFFFF
107 
108 /* AVIC GATAG is encoded using VM and VCPU IDs */
109 #define AVIC_VCPU_ID_BITS		8
110 #define AVIC_VCPU_ID_MASK		((1 << AVIC_VCPU_ID_BITS) - 1)
111 
112 #define AVIC_VM_ID_BITS			24
113 #define AVIC_VM_ID_NR			(1 << AVIC_VM_ID_BITS)
114 #define AVIC_VM_ID_MASK			((1 << AVIC_VM_ID_BITS) - 1)
115 
116 #define AVIC_GATAG(x, y)		(((x & AVIC_VM_ID_MASK) << AVIC_VCPU_ID_BITS) | \
117 						(y & AVIC_VCPU_ID_MASK))
118 #define AVIC_GATAG_TO_VMID(x)		((x >> AVIC_VCPU_ID_BITS) & AVIC_VM_ID_MASK)
119 #define AVIC_GATAG_TO_VCPUID(x)		(x & AVIC_VCPU_ID_MASK)
120 
121 static bool erratum_383_found __read_mostly;
122 
123 static const u32 host_save_user_msrs[] = {
124 #ifdef CONFIG_X86_64
125 	MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
126 	MSR_FS_BASE,
127 #endif
128 	MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
129 	MSR_TSC_AUX,
130 };
131 
132 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
133 
134 struct kvm_sev_info {
135 	bool active;		/* SEV enabled guest */
136 	unsigned int asid;	/* ASID used for this guest */
137 	unsigned int handle;	/* SEV firmware handle */
138 	int fd;			/* SEV device fd */
139 	unsigned long pages_locked; /* Number of pages locked */
140 	struct list_head regions_list;  /* List of registered regions */
141 };
142 
143 struct kvm_svm {
144 	struct kvm kvm;
145 
146 	/* Struct members for AVIC */
147 	u32 avic_vm_id;
148 	u32 ldr_mode;
149 	struct page *avic_logical_id_table_page;
150 	struct page *avic_physical_id_table_page;
151 	struct hlist_node hnode;
152 
153 	struct kvm_sev_info sev_info;
154 };
155 
156 struct kvm_vcpu;
157 
158 struct nested_state {
159 	struct vmcb *hsave;
160 	u64 hsave_msr;
161 	u64 vm_cr_msr;
162 	u64 vmcb;
163 
164 	/* These are the merged vectors */
165 	u32 *msrpm;
166 
167 	/* gpa pointers to the real vectors */
168 	u64 vmcb_msrpm;
169 	u64 vmcb_iopm;
170 
171 	/* A VMEXIT is required but not yet emulated */
172 	bool exit_required;
173 
174 	/* cache for intercepts of the guest */
175 	u32 intercept_cr;
176 	u32 intercept_dr;
177 	u32 intercept_exceptions;
178 	u64 intercept;
179 
180 	/* Nested Paging related state */
181 	u64 nested_cr3;
182 };
183 
184 #define MSRPM_OFFSETS	16
185 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
186 
187 /*
188  * Set osvw_len to higher value when updated Revision Guides
189  * are published and we know what the new status bits are
190  */
191 static uint64_t osvw_len = 4, osvw_status;
192 
193 struct vcpu_svm {
194 	struct kvm_vcpu vcpu;
195 	struct vmcb *vmcb;
196 	unsigned long vmcb_pa;
197 	struct svm_cpu_data *svm_data;
198 	uint64_t asid_generation;
199 	uint64_t sysenter_esp;
200 	uint64_t sysenter_eip;
201 	uint64_t tsc_aux;
202 
203 	u64 msr_decfg;
204 
205 	u64 next_rip;
206 
207 	u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
208 	struct {
209 		u16 fs;
210 		u16 gs;
211 		u16 ldt;
212 		u64 gs_base;
213 	} host;
214 
215 	u64 spec_ctrl;
216 	/*
217 	 * Contains guest-controlled bits of VIRT_SPEC_CTRL, which will be
218 	 * translated into the appropriate L2_CFG bits on the host to
219 	 * perform speculative control.
220 	 */
221 	u64 virt_spec_ctrl;
222 
223 	u32 *msrpm;
224 
225 	ulong nmi_iret_rip;
226 
227 	struct nested_state nested;
228 
229 	bool nmi_singlestep;
230 	u64 nmi_singlestep_guest_rflags;
231 
232 	unsigned int3_injected;
233 	unsigned long int3_rip;
234 
235 	/* cached guest cpuid flags for faster access */
236 	bool nrips_enabled	: 1;
237 
238 	u32 ldr_reg;
239 	struct page *avic_backing_page;
240 	u64 *avic_physical_id_cache;
241 	bool avic_is_running;
242 
243 	/*
244 	 * Per-vcpu list of struct amd_svm_iommu_ir:
245 	 * This is used mainly to store interrupt remapping information used
246 	 * when update the vcpu affinity. This avoids the need to scan for
247 	 * IRTE and try to match ga_tag in the IOMMU driver.
248 	 */
249 	struct list_head ir_list;
250 	spinlock_t ir_list_lock;
251 
252 	/* which host CPU was used for running this vcpu */
253 	unsigned int last_cpu;
254 };
255 
256 /*
257  * This is a wrapper of struct amd_iommu_ir_data.
258  */
259 struct amd_svm_iommu_ir {
260 	struct list_head node;	/* Used by SVM for per-vcpu ir_list */
261 	void *data;		/* Storing pointer to struct amd_ir_data */
262 };
263 
264 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK	(0xFF)
265 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK		(1 << 31)
266 
267 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK	(0xFFULL)
268 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK	(0xFFFFFFFFFFULL << 12)
269 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK		(1ULL << 62)
270 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK		(1ULL << 63)
271 
272 static DEFINE_PER_CPU(u64, current_tsc_ratio);
273 #define TSC_RATIO_DEFAULT	0x0100000000ULL
274 
275 #define MSR_INVALID			0xffffffffU
276 
277 static const struct svm_direct_access_msrs {
278 	u32 index;   /* Index of the MSR */
279 	bool always; /* True if intercept is always on */
280 } direct_access_msrs[] = {
281 	{ .index = MSR_STAR,				.always = true  },
282 	{ .index = MSR_IA32_SYSENTER_CS,		.always = true  },
283 #ifdef CONFIG_X86_64
284 	{ .index = MSR_GS_BASE,				.always = true  },
285 	{ .index = MSR_FS_BASE,				.always = true  },
286 	{ .index = MSR_KERNEL_GS_BASE,			.always = true  },
287 	{ .index = MSR_LSTAR,				.always = true  },
288 	{ .index = MSR_CSTAR,				.always = true  },
289 	{ .index = MSR_SYSCALL_MASK,			.always = true  },
290 #endif
291 	{ .index = MSR_IA32_SPEC_CTRL,			.always = false },
292 	{ .index = MSR_IA32_PRED_CMD,			.always = false },
293 	{ .index = MSR_IA32_LASTBRANCHFROMIP,		.always = false },
294 	{ .index = MSR_IA32_LASTBRANCHTOIP,		.always = false },
295 	{ .index = MSR_IA32_LASTINTFROMIP,		.always = false },
296 	{ .index = MSR_IA32_LASTINTTOIP,		.always = false },
297 	{ .index = MSR_INVALID,				.always = false },
298 };
299 
300 /* enable NPT for AMD64 and X86 with PAE */
301 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
302 static bool npt_enabled = true;
303 #else
304 static bool npt_enabled;
305 #endif
306 
307 /*
308  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
309  * pause_filter_count: On processors that support Pause filtering(indicated
310  *	by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
311  *	count value. On VMRUN this value is loaded into an internal counter.
312  *	Each time a pause instruction is executed, this counter is decremented
313  *	until it reaches zero at which time a #VMEXIT is generated if pause
314  *	intercept is enabled. Refer to  AMD APM Vol 2 Section 15.14.4 Pause
315  *	Intercept Filtering for more details.
316  *	This also indicate if ple logic enabled.
317  *
318  * pause_filter_thresh: In addition, some processor families support advanced
319  *	pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
320  *	the amount of time a guest is allowed to execute in a pause loop.
321  *	In this mode, a 16-bit pause filter threshold field is added in the
322  *	VMCB. The threshold value is a cycle count that is used to reset the
323  *	pause counter. As with simple pause filtering, VMRUN loads the pause
324  *	count value from VMCB into an internal counter. Then, on each pause
325  *	instruction the hardware checks the elapsed number of cycles since
326  *	the most recent pause instruction against the pause filter threshold.
327  *	If the elapsed cycle count is greater than the pause filter threshold,
328  *	then the internal pause count is reloaded from the VMCB and execution
329  *	continues. If the elapsed cycle count is less than the pause filter
330  *	threshold, then the internal pause count is decremented. If the count
331  *	value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
332  *	triggered. If advanced pause filtering is supported and pause filter
333  *	threshold field is set to zero, the filter will operate in the simpler,
334  *	count only mode.
335  */
336 
337 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
338 module_param(pause_filter_thresh, ushort, 0444);
339 
340 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
341 module_param(pause_filter_count, ushort, 0444);
342 
343 /* Default doubles per-vcpu window every exit. */
344 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
345 module_param(pause_filter_count_grow, ushort, 0444);
346 
347 /* Default resets per-vcpu window every exit to pause_filter_count. */
348 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
349 module_param(pause_filter_count_shrink, ushort, 0444);
350 
351 /* Default is to compute the maximum so we can never overflow. */
352 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
353 module_param(pause_filter_count_max, ushort, 0444);
354 
355 /* allow nested paging (virtualized MMU) for all guests */
356 static int npt = true;
357 module_param(npt, int, S_IRUGO);
358 
359 /* allow nested virtualization in KVM/SVM */
360 static int nested = true;
361 module_param(nested, int, S_IRUGO);
362 
363 /* enable / disable AVIC */
364 static int avic;
365 #ifdef CONFIG_X86_LOCAL_APIC
366 module_param(avic, int, S_IRUGO);
367 #endif
368 
369 /* enable/disable Virtual VMLOAD VMSAVE */
370 static int vls = true;
371 module_param(vls, int, 0444);
372 
373 /* enable/disable Virtual GIF */
374 static int vgif = true;
375 module_param(vgif, int, 0444);
376 
377 /* enable/disable SEV support */
378 static int sev = IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT);
379 module_param(sev, int, 0444);
380 
381 static u8 rsm_ins_bytes[] = "\x0f\xaa";
382 
383 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
384 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
385 static void svm_complete_interrupts(struct vcpu_svm *svm);
386 
387 static int nested_svm_exit_handled(struct vcpu_svm *svm);
388 static int nested_svm_intercept(struct vcpu_svm *svm);
389 static int nested_svm_vmexit(struct vcpu_svm *svm);
390 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
391 				      bool has_error_code, u32 error_code);
392 
393 enum {
394 	VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
395 			    pause filter count */
396 	VMCB_PERM_MAP,   /* IOPM Base and MSRPM Base */
397 	VMCB_ASID,	 /* ASID */
398 	VMCB_INTR,	 /* int_ctl, int_vector */
399 	VMCB_NPT,        /* npt_en, nCR3, gPAT */
400 	VMCB_CR,	 /* CR0, CR3, CR4, EFER */
401 	VMCB_DR,         /* DR6, DR7 */
402 	VMCB_DT,         /* GDT, IDT */
403 	VMCB_SEG,        /* CS, DS, SS, ES, CPL */
404 	VMCB_CR2,        /* CR2 only */
405 	VMCB_LBR,        /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
406 	VMCB_AVIC,       /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
407 			  * AVIC PHYSICAL_TABLE pointer,
408 			  * AVIC LOGICAL_TABLE pointer
409 			  */
410 	VMCB_DIRTY_MAX,
411 };
412 
413 /* TPR and CR2 are always written before VMRUN */
414 #define VMCB_ALWAYS_DIRTY_MASK	((1U << VMCB_INTR) | (1U << VMCB_CR2))
415 
416 #define VMCB_AVIC_APIC_BAR_MASK		0xFFFFFFFFFF000ULL
417 
418 static unsigned int max_sev_asid;
419 static unsigned int min_sev_asid;
420 static unsigned long *sev_asid_bitmap;
421 #define __sme_page_pa(x) __sme_set(page_to_pfn(x) << PAGE_SHIFT)
422 
423 struct enc_region {
424 	struct list_head list;
425 	unsigned long npages;
426 	struct page **pages;
427 	unsigned long uaddr;
428 	unsigned long size;
429 };
430 
431 
to_kvm_svm(struct kvm * kvm)432 static inline struct kvm_svm *to_kvm_svm(struct kvm *kvm)
433 {
434 	return container_of(kvm, struct kvm_svm, kvm);
435 }
436 
svm_sev_enabled(void)437 static inline bool svm_sev_enabled(void)
438 {
439 	return IS_ENABLED(CONFIG_KVM_AMD_SEV) ? max_sev_asid : 0;
440 }
441 
sev_guest(struct kvm * kvm)442 static inline bool sev_guest(struct kvm *kvm)
443 {
444 #ifdef CONFIG_KVM_AMD_SEV
445 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
446 
447 	return sev->active;
448 #else
449 	return false;
450 #endif
451 }
452 
sev_get_asid(struct kvm * kvm)453 static inline int sev_get_asid(struct kvm *kvm)
454 {
455 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
456 
457 	return sev->asid;
458 }
459 
mark_all_dirty(struct vmcb * vmcb)460 static inline void mark_all_dirty(struct vmcb *vmcb)
461 {
462 	vmcb->control.clean = 0;
463 }
464 
mark_all_clean(struct vmcb * vmcb)465 static inline void mark_all_clean(struct vmcb *vmcb)
466 {
467 	vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
468 			       & ~VMCB_ALWAYS_DIRTY_MASK;
469 }
470 
mark_dirty(struct vmcb * vmcb,int bit)471 static inline void mark_dirty(struct vmcb *vmcb, int bit)
472 {
473 	vmcb->control.clean &= ~(1 << bit);
474 }
475 
to_svm(struct kvm_vcpu * vcpu)476 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
477 {
478 	return container_of(vcpu, struct vcpu_svm, vcpu);
479 }
480 
avic_update_vapic_bar(struct vcpu_svm * svm,u64 data)481 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
482 {
483 	svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
484 	mark_dirty(svm->vmcb, VMCB_AVIC);
485 }
486 
avic_vcpu_is_running(struct kvm_vcpu * vcpu)487 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
488 {
489 	struct vcpu_svm *svm = to_svm(vcpu);
490 	u64 *entry = svm->avic_physical_id_cache;
491 
492 	if (!entry)
493 		return false;
494 
495 	return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
496 }
497 
recalc_intercepts(struct vcpu_svm * svm)498 static void recalc_intercepts(struct vcpu_svm *svm)
499 {
500 	struct vmcb_control_area *c, *h;
501 	struct nested_state *g;
502 
503 	mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
504 
505 	if (!is_guest_mode(&svm->vcpu))
506 		return;
507 
508 	c = &svm->vmcb->control;
509 	h = &svm->nested.hsave->control;
510 	g = &svm->nested;
511 
512 	c->intercept_cr = h->intercept_cr | g->intercept_cr;
513 	c->intercept_dr = h->intercept_dr | g->intercept_dr;
514 	c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
515 	c->intercept = h->intercept | g->intercept;
516 
517 	c->intercept |= (1ULL << INTERCEPT_VMLOAD);
518 	c->intercept |= (1ULL << INTERCEPT_VMSAVE);
519 }
520 
get_host_vmcb(struct vcpu_svm * svm)521 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
522 {
523 	if (is_guest_mode(&svm->vcpu))
524 		return svm->nested.hsave;
525 	else
526 		return svm->vmcb;
527 }
528 
set_cr_intercept(struct vcpu_svm * svm,int bit)529 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
530 {
531 	struct vmcb *vmcb = get_host_vmcb(svm);
532 
533 	vmcb->control.intercept_cr |= (1U << bit);
534 
535 	recalc_intercepts(svm);
536 }
537 
clr_cr_intercept(struct vcpu_svm * svm,int bit)538 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
539 {
540 	struct vmcb *vmcb = get_host_vmcb(svm);
541 
542 	vmcb->control.intercept_cr &= ~(1U << bit);
543 
544 	recalc_intercepts(svm);
545 }
546 
is_cr_intercept(struct vcpu_svm * svm,int bit)547 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
548 {
549 	struct vmcb *vmcb = get_host_vmcb(svm);
550 
551 	return vmcb->control.intercept_cr & (1U << bit);
552 }
553 
set_dr_intercepts(struct vcpu_svm * svm)554 static inline void set_dr_intercepts(struct vcpu_svm *svm)
555 {
556 	struct vmcb *vmcb = get_host_vmcb(svm);
557 
558 	vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
559 		| (1 << INTERCEPT_DR1_READ)
560 		| (1 << INTERCEPT_DR2_READ)
561 		| (1 << INTERCEPT_DR3_READ)
562 		| (1 << INTERCEPT_DR4_READ)
563 		| (1 << INTERCEPT_DR5_READ)
564 		| (1 << INTERCEPT_DR6_READ)
565 		| (1 << INTERCEPT_DR7_READ)
566 		| (1 << INTERCEPT_DR0_WRITE)
567 		| (1 << INTERCEPT_DR1_WRITE)
568 		| (1 << INTERCEPT_DR2_WRITE)
569 		| (1 << INTERCEPT_DR3_WRITE)
570 		| (1 << INTERCEPT_DR4_WRITE)
571 		| (1 << INTERCEPT_DR5_WRITE)
572 		| (1 << INTERCEPT_DR6_WRITE)
573 		| (1 << INTERCEPT_DR7_WRITE);
574 
575 	recalc_intercepts(svm);
576 }
577 
clr_dr_intercepts(struct vcpu_svm * svm)578 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
579 {
580 	struct vmcb *vmcb = get_host_vmcb(svm);
581 
582 	vmcb->control.intercept_dr = 0;
583 
584 	recalc_intercepts(svm);
585 }
586 
set_exception_intercept(struct vcpu_svm * svm,int bit)587 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
588 {
589 	struct vmcb *vmcb = get_host_vmcb(svm);
590 
591 	vmcb->control.intercept_exceptions |= (1U << bit);
592 
593 	recalc_intercepts(svm);
594 }
595 
clr_exception_intercept(struct vcpu_svm * svm,int bit)596 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
597 {
598 	struct vmcb *vmcb = get_host_vmcb(svm);
599 
600 	vmcb->control.intercept_exceptions &= ~(1U << bit);
601 
602 	recalc_intercepts(svm);
603 }
604 
set_intercept(struct vcpu_svm * svm,int bit)605 static inline void set_intercept(struct vcpu_svm *svm, int bit)
606 {
607 	struct vmcb *vmcb = get_host_vmcb(svm);
608 
609 	vmcb->control.intercept |= (1ULL << bit);
610 
611 	recalc_intercepts(svm);
612 }
613 
clr_intercept(struct vcpu_svm * svm,int bit)614 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
615 {
616 	struct vmcb *vmcb = get_host_vmcb(svm);
617 
618 	vmcb->control.intercept &= ~(1ULL << bit);
619 
620 	recalc_intercepts(svm);
621 }
622 
vgif_enabled(struct vcpu_svm * svm)623 static inline bool vgif_enabled(struct vcpu_svm *svm)
624 {
625 	return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
626 }
627 
enable_gif(struct vcpu_svm * svm)628 static inline void enable_gif(struct vcpu_svm *svm)
629 {
630 	if (vgif_enabled(svm))
631 		svm->vmcb->control.int_ctl |= V_GIF_MASK;
632 	else
633 		svm->vcpu.arch.hflags |= HF_GIF_MASK;
634 }
635 
disable_gif(struct vcpu_svm * svm)636 static inline void disable_gif(struct vcpu_svm *svm)
637 {
638 	if (vgif_enabled(svm))
639 		svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
640 	else
641 		svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
642 }
643 
gif_set(struct vcpu_svm * svm)644 static inline bool gif_set(struct vcpu_svm *svm)
645 {
646 	if (vgif_enabled(svm))
647 		return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
648 	else
649 		return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
650 }
651 
652 static unsigned long iopm_base;
653 
654 struct kvm_ldttss_desc {
655 	u16 limit0;
656 	u16 base0;
657 	unsigned base1:8, type:5, dpl:2, p:1;
658 	unsigned limit1:4, zero0:3, g:1, base2:8;
659 	u32 base3;
660 	u32 zero1;
661 } __attribute__((packed));
662 
663 struct svm_cpu_data {
664 	int cpu;
665 
666 	u64 asid_generation;
667 	u32 max_asid;
668 	u32 next_asid;
669 	u32 min_asid;
670 	struct kvm_ldttss_desc *tss_desc;
671 
672 	struct page *save_area;
673 	struct vmcb *current_vmcb;
674 
675 	/* index = sev_asid, value = vmcb pointer */
676 	struct vmcb **sev_vmcbs;
677 };
678 
679 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
680 
681 struct svm_init_data {
682 	int cpu;
683 	int r;
684 };
685 
686 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
687 
688 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
689 #define MSRS_RANGE_SIZE 2048
690 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
691 
svm_msrpm_offset(u32 msr)692 static u32 svm_msrpm_offset(u32 msr)
693 {
694 	u32 offset;
695 	int i;
696 
697 	for (i = 0; i < NUM_MSR_MAPS; i++) {
698 		if (msr < msrpm_ranges[i] ||
699 		    msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
700 			continue;
701 
702 		offset  = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
703 		offset += (i * MSRS_RANGE_SIZE);       /* add range offset */
704 
705 		/* Now we have the u8 offset - but need the u32 offset */
706 		return offset / 4;
707 	}
708 
709 	/* MSR not in any range */
710 	return MSR_INVALID;
711 }
712 
713 #define MAX_INST_SIZE 15
714 
clgi(void)715 static inline void clgi(void)
716 {
717 	asm volatile (__ex(SVM_CLGI));
718 }
719 
stgi(void)720 static inline void stgi(void)
721 {
722 	asm volatile (__ex(SVM_STGI));
723 }
724 
invlpga(unsigned long addr,u32 asid)725 static inline void invlpga(unsigned long addr, u32 asid)
726 {
727 	asm volatile (__ex(SVM_INVLPGA) : : "a"(addr), "c"(asid));
728 }
729 
get_npt_level(struct kvm_vcpu * vcpu)730 static int get_npt_level(struct kvm_vcpu *vcpu)
731 {
732 #ifdef CONFIG_X86_64
733 	return PT64_ROOT_4LEVEL;
734 #else
735 	return PT32E_ROOT_LEVEL;
736 #endif
737 }
738 
svm_set_efer(struct kvm_vcpu * vcpu,u64 efer)739 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
740 {
741 	vcpu->arch.efer = efer;
742 
743 	if (!npt_enabled) {
744 		/* Shadow paging assumes NX to be available.  */
745 		efer |= EFER_NX;
746 
747 		if (!(efer & EFER_LMA))
748 			efer &= ~EFER_LME;
749 	}
750 
751 	to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
752 	mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
753 }
754 
is_external_interrupt(u32 info)755 static int is_external_interrupt(u32 info)
756 {
757 	info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
758 	return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
759 }
760 
svm_get_interrupt_shadow(struct kvm_vcpu * vcpu)761 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
762 {
763 	struct vcpu_svm *svm = to_svm(vcpu);
764 	u32 ret = 0;
765 
766 	if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
767 		ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
768 	return ret;
769 }
770 
svm_set_interrupt_shadow(struct kvm_vcpu * vcpu,int mask)771 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
772 {
773 	struct vcpu_svm *svm = to_svm(vcpu);
774 
775 	if (mask == 0)
776 		svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
777 	else
778 		svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
779 
780 }
781 
skip_emulated_instruction(struct kvm_vcpu * vcpu)782 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
783 {
784 	struct vcpu_svm *svm = to_svm(vcpu);
785 
786 	if (svm->vmcb->control.next_rip != 0) {
787 		WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
788 		svm->next_rip = svm->vmcb->control.next_rip;
789 	}
790 
791 	if (!svm->next_rip) {
792 		if (kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) !=
793 				EMULATE_DONE)
794 			printk(KERN_DEBUG "%s: NOP\n", __func__);
795 		return;
796 	}
797 	if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
798 		printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
799 		       __func__, kvm_rip_read(vcpu), svm->next_rip);
800 
801 	kvm_rip_write(vcpu, svm->next_rip);
802 	svm_set_interrupt_shadow(vcpu, 0);
803 }
804 
svm_queue_exception(struct kvm_vcpu * vcpu)805 static void svm_queue_exception(struct kvm_vcpu *vcpu)
806 {
807 	struct vcpu_svm *svm = to_svm(vcpu);
808 	unsigned nr = vcpu->arch.exception.nr;
809 	bool has_error_code = vcpu->arch.exception.has_error_code;
810 	bool reinject = vcpu->arch.exception.injected;
811 	u32 error_code = vcpu->arch.exception.error_code;
812 
813 	/*
814 	 * If we are within a nested VM we'd better #VMEXIT and let the guest
815 	 * handle the exception
816 	 */
817 	if (!reinject &&
818 	    nested_svm_check_exception(svm, nr, has_error_code, error_code))
819 		return;
820 
821 	if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
822 		unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
823 
824 		/*
825 		 * For guest debugging where we have to reinject #BP if some
826 		 * INT3 is guest-owned:
827 		 * Emulate nRIP by moving RIP forward. Will fail if injection
828 		 * raises a fault that is not intercepted. Still better than
829 		 * failing in all cases.
830 		 */
831 		skip_emulated_instruction(&svm->vcpu);
832 		rip = kvm_rip_read(&svm->vcpu);
833 		svm->int3_rip = rip + svm->vmcb->save.cs.base;
834 		svm->int3_injected = rip - old_rip;
835 	}
836 
837 	svm->vmcb->control.event_inj = nr
838 		| SVM_EVTINJ_VALID
839 		| (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
840 		| SVM_EVTINJ_TYPE_EXEPT;
841 	svm->vmcb->control.event_inj_err = error_code;
842 }
843 
svm_init_erratum_383(void)844 static void svm_init_erratum_383(void)
845 {
846 	u32 low, high;
847 	int err;
848 	u64 val;
849 
850 	if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
851 		return;
852 
853 	/* Use _safe variants to not break nested virtualization */
854 	val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
855 	if (err)
856 		return;
857 
858 	val |= (1ULL << 47);
859 
860 	low  = lower_32_bits(val);
861 	high = upper_32_bits(val);
862 
863 	native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
864 
865 	erratum_383_found = true;
866 }
867 
svm_init_osvw(struct kvm_vcpu * vcpu)868 static void svm_init_osvw(struct kvm_vcpu *vcpu)
869 {
870 	/*
871 	 * Guests should see errata 400 and 415 as fixed (assuming that
872 	 * HLT and IO instructions are intercepted).
873 	 */
874 	vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
875 	vcpu->arch.osvw.status = osvw_status & ~(6ULL);
876 
877 	/*
878 	 * By increasing VCPU's osvw.length to 3 we are telling the guest that
879 	 * all osvw.status bits inside that length, including bit 0 (which is
880 	 * reserved for erratum 298), are valid. However, if host processor's
881 	 * osvw_len is 0 then osvw_status[0] carries no information. We need to
882 	 * be conservative here and therefore we tell the guest that erratum 298
883 	 * is present (because we really don't know).
884 	 */
885 	if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
886 		vcpu->arch.osvw.status |= 1;
887 }
888 
has_svm(void)889 static int has_svm(void)
890 {
891 	const char *msg;
892 
893 	if (!cpu_has_svm(&msg)) {
894 		printk(KERN_INFO "has_svm: %s\n", msg);
895 		return 0;
896 	}
897 
898 	return 1;
899 }
900 
svm_hardware_disable(void)901 static void svm_hardware_disable(void)
902 {
903 	/* Make sure we clean up behind us */
904 	if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
905 		wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
906 
907 	cpu_svm_disable();
908 
909 	amd_pmu_disable_virt();
910 }
911 
svm_hardware_enable(void)912 static int svm_hardware_enable(void)
913 {
914 
915 	struct svm_cpu_data *sd;
916 	uint64_t efer;
917 	struct desc_struct *gdt;
918 	int me = raw_smp_processor_id();
919 
920 	rdmsrl(MSR_EFER, efer);
921 	if (efer & EFER_SVME)
922 		return -EBUSY;
923 
924 	if (!has_svm()) {
925 		pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
926 		return -EINVAL;
927 	}
928 	sd = per_cpu(svm_data, me);
929 	if (!sd) {
930 		pr_err("%s: svm_data is NULL on %d\n", __func__, me);
931 		return -EINVAL;
932 	}
933 
934 	sd->asid_generation = 1;
935 	sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
936 	sd->next_asid = sd->max_asid + 1;
937 	sd->min_asid = max_sev_asid + 1;
938 
939 	gdt = get_current_gdt_rw();
940 	sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
941 
942 	wrmsrl(MSR_EFER, efer | EFER_SVME);
943 
944 	wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
945 
946 	if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
947 		wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
948 		__this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
949 	}
950 
951 
952 	/*
953 	 * Get OSVW bits.
954 	 *
955 	 * Note that it is possible to have a system with mixed processor
956 	 * revisions and therefore different OSVW bits. If bits are not the same
957 	 * on different processors then choose the worst case (i.e. if erratum
958 	 * is present on one processor and not on another then assume that the
959 	 * erratum is present everywhere).
960 	 */
961 	if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
962 		uint64_t len, status = 0;
963 		int err;
964 
965 		len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
966 		if (!err)
967 			status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
968 						      &err);
969 
970 		if (err)
971 			osvw_status = osvw_len = 0;
972 		else {
973 			if (len < osvw_len)
974 				osvw_len = len;
975 			osvw_status |= status;
976 			osvw_status &= (1ULL << osvw_len) - 1;
977 		}
978 	} else
979 		osvw_status = osvw_len = 0;
980 
981 	svm_init_erratum_383();
982 
983 	amd_pmu_enable_virt();
984 
985 	return 0;
986 }
987 
svm_cpu_uninit(int cpu)988 static void svm_cpu_uninit(int cpu)
989 {
990 	struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
991 
992 	if (!sd)
993 		return;
994 
995 	per_cpu(svm_data, raw_smp_processor_id()) = NULL;
996 	kfree(sd->sev_vmcbs);
997 	__free_page(sd->save_area);
998 	kfree(sd);
999 }
1000 
svm_cpu_init(int cpu)1001 static int svm_cpu_init(int cpu)
1002 {
1003 	struct svm_cpu_data *sd;
1004 
1005 	sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
1006 	if (!sd)
1007 		return -ENOMEM;
1008 	sd->cpu = cpu;
1009 	sd->save_area = alloc_page(GFP_KERNEL);
1010 	if (!sd->save_area)
1011 		goto free_cpu_data;
1012 
1013 	if (svm_sev_enabled()) {
1014 		sd->sev_vmcbs = kmalloc_array(max_sev_asid + 1,
1015 					      sizeof(void *),
1016 					      GFP_KERNEL);
1017 		if (!sd->sev_vmcbs)
1018 			goto free_save_area;
1019 	}
1020 
1021 	per_cpu(svm_data, cpu) = sd;
1022 
1023 	return 0;
1024 
1025 free_save_area:
1026 	__free_page(sd->save_area);
1027 free_cpu_data:
1028 	kfree(sd);
1029 	return -ENOMEM;
1030 
1031 }
1032 
valid_msr_intercept(u32 index)1033 static bool valid_msr_intercept(u32 index)
1034 {
1035 	int i;
1036 
1037 	for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
1038 		if (direct_access_msrs[i].index == index)
1039 			return true;
1040 
1041 	return false;
1042 }
1043 
msr_write_intercepted(struct kvm_vcpu * vcpu,unsigned msr)1044 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
1045 {
1046 	u8 bit_write;
1047 	unsigned long tmp;
1048 	u32 offset;
1049 	u32 *msrpm;
1050 
1051 	msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
1052 				      to_svm(vcpu)->msrpm;
1053 
1054 	offset    = svm_msrpm_offset(msr);
1055 	bit_write = 2 * (msr & 0x0f) + 1;
1056 	tmp       = msrpm[offset];
1057 
1058 	BUG_ON(offset == MSR_INVALID);
1059 
1060 	return !!test_bit(bit_write,  &tmp);
1061 }
1062 
set_msr_interception(u32 * msrpm,unsigned msr,int read,int write)1063 static void set_msr_interception(u32 *msrpm, unsigned msr,
1064 				 int read, int write)
1065 {
1066 	u8 bit_read, bit_write;
1067 	unsigned long tmp;
1068 	u32 offset;
1069 
1070 	/*
1071 	 * If this warning triggers extend the direct_access_msrs list at the
1072 	 * beginning of the file
1073 	 */
1074 	WARN_ON(!valid_msr_intercept(msr));
1075 
1076 	offset    = svm_msrpm_offset(msr);
1077 	bit_read  = 2 * (msr & 0x0f);
1078 	bit_write = 2 * (msr & 0x0f) + 1;
1079 	tmp       = msrpm[offset];
1080 
1081 	BUG_ON(offset == MSR_INVALID);
1082 
1083 	read  ? clear_bit(bit_read,  &tmp) : set_bit(bit_read,  &tmp);
1084 	write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
1085 
1086 	msrpm[offset] = tmp;
1087 }
1088 
svm_vcpu_init_msrpm(u32 * msrpm)1089 static void svm_vcpu_init_msrpm(u32 *msrpm)
1090 {
1091 	int i;
1092 
1093 	memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
1094 
1095 	for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1096 		if (!direct_access_msrs[i].always)
1097 			continue;
1098 
1099 		set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
1100 	}
1101 }
1102 
add_msr_offset(u32 offset)1103 static void add_msr_offset(u32 offset)
1104 {
1105 	int i;
1106 
1107 	for (i = 0; i < MSRPM_OFFSETS; ++i) {
1108 
1109 		/* Offset already in list? */
1110 		if (msrpm_offsets[i] == offset)
1111 			return;
1112 
1113 		/* Slot used by another offset? */
1114 		if (msrpm_offsets[i] != MSR_INVALID)
1115 			continue;
1116 
1117 		/* Add offset to list */
1118 		msrpm_offsets[i] = offset;
1119 
1120 		return;
1121 	}
1122 
1123 	/*
1124 	 * If this BUG triggers the msrpm_offsets table has an overflow. Just
1125 	 * increase MSRPM_OFFSETS in this case.
1126 	 */
1127 	BUG();
1128 }
1129 
init_msrpm_offsets(void)1130 static void init_msrpm_offsets(void)
1131 {
1132 	int i;
1133 
1134 	memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
1135 
1136 	for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1137 		u32 offset;
1138 
1139 		offset = svm_msrpm_offset(direct_access_msrs[i].index);
1140 		BUG_ON(offset == MSR_INVALID);
1141 
1142 		add_msr_offset(offset);
1143 	}
1144 }
1145 
svm_enable_lbrv(struct vcpu_svm * svm)1146 static void svm_enable_lbrv(struct vcpu_svm *svm)
1147 {
1148 	u32 *msrpm = svm->msrpm;
1149 
1150 	svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1151 	set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1152 	set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1153 	set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1154 	set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1155 }
1156 
svm_disable_lbrv(struct vcpu_svm * svm)1157 static void svm_disable_lbrv(struct vcpu_svm *svm)
1158 {
1159 	u32 *msrpm = svm->msrpm;
1160 
1161 	svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1162 	set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1163 	set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1164 	set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1165 	set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1166 }
1167 
disable_nmi_singlestep(struct vcpu_svm * svm)1168 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1169 {
1170 	svm->nmi_singlestep = false;
1171 
1172 	if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1173 		/* Clear our flags if they were not set by the guest */
1174 		if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1175 			svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1176 		if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1177 			svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1178 	}
1179 }
1180 
1181 /* Note:
1182  * This hash table is used to map VM_ID to a struct kvm_svm,
1183  * when handling AMD IOMMU GALOG notification to schedule in
1184  * a particular vCPU.
1185  */
1186 #define SVM_VM_DATA_HASH_BITS	8
1187 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1188 static u32 next_vm_id = 0;
1189 static bool next_vm_id_wrapped = 0;
1190 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1191 
1192 /* Note:
1193  * This function is called from IOMMU driver to notify
1194  * SVM to schedule in a particular vCPU of a particular VM.
1195  */
avic_ga_log_notifier(u32 ga_tag)1196 static int avic_ga_log_notifier(u32 ga_tag)
1197 {
1198 	unsigned long flags;
1199 	struct kvm_svm *kvm_svm;
1200 	struct kvm_vcpu *vcpu = NULL;
1201 	u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1202 	u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1203 
1204 	pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1205 
1206 	spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1207 	hash_for_each_possible(svm_vm_data_hash, kvm_svm, hnode, vm_id) {
1208 		if (kvm_svm->avic_vm_id != vm_id)
1209 			continue;
1210 		vcpu = kvm_get_vcpu_by_id(&kvm_svm->kvm, vcpu_id);
1211 		break;
1212 	}
1213 	spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1214 
1215 	/* Note:
1216 	 * At this point, the IOMMU should have already set the pending
1217 	 * bit in the vAPIC backing page. So, we just need to schedule
1218 	 * in the vcpu.
1219 	 */
1220 	if (vcpu)
1221 		kvm_vcpu_wake_up(vcpu);
1222 
1223 	return 0;
1224 }
1225 
sev_hardware_setup(void)1226 static __init int sev_hardware_setup(void)
1227 {
1228 	struct sev_user_data_status *status;
1229 	int rc;
1230 
1231 	/* Maximum number of encrypted guests supported simultaneously */
1232 	max_sev_asid = cpuid_ecx(0x8000001F);
1233 
1234 	if (!max_sev_asid)
1235 		return 1;
1236 
1237 	/* Minimum ASID value that should be used for SEV guest */
1238 	min_sev_asid = cpuid_edx(0x8000001F);
1239 
1240 	/* Initialize SEV ASID bitmap */
1241 	sev_asid_bitmap = bitmap_zalloc(max_sev_asid, GFP_KERNEL);
1242 	if (!sev_asid_bitmap)
1243 		return 1;
1244 
1245 	status = kmalloc(sizeof(*status), GFP_KERNEL);
1246 	if (!status)
1247 		return 1;
1248 
1249 	/*
1250 	 * Check SEV platform status.
1251 	 *
1252 	 * PLATFORM_STATUS can be called in any state, if we failed to query
1253 	 * the PLATFORM status then either PSP firmware does not support SEV
1254 	 * feature or SEV firmware is dead.
1255 	 */
1256 	rc = sev_platform_status(status, NULL);
1257 	if (rc)
1258 		goto err;
1259 
1260 	pr_info("SEV supported\n");
1261 
1262 err:
1263 	kfree(status);
1264 	return rc;
1265 }
1266 
grow_ple_window(struct kvm_vcpu * vcpu)1267 static void grow_ple_window(struct kvm_vcpu *vcpu)
1268 {
1269 	struct vcpu_svm *svm = to_svm(vcpu);
1270 	struct vmcb_control_area *control = &svm->vmcb->control;
1271 	int old = control->pause_filter_count;
1272 
1273 	control->pause_filter_count = __grow_ple_window(old,
1274 							pause_filter_count,
1275 							pause_filter_count_grow,
1276 							pause_filter_count_max);
1277 
1278 	if (control->pause_filter_count != old)
1279 		mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1280 
1281 	trace_kvm_ple_window_grow(vcpu->vcpu_id,
1282 				  control->pause_filter_count, old);
1283 }
1284 
shrink_ple_window(struct kvm_vcpu * vcpu)1285 static void shrink_ple_window(struct kvm_vcpu *vcpu)
1286 {
1287 	struct vcpu_svm *svm = to_svm(vcpu);
1288 	struct vmcb_control_area *control = &svm->vmcb->control;
1289 	int old = control->pause_filter_count;
1290 
1291 	control->pause_filter_count =
1292 				__shrink_ple_window(old,
1293 						    pause_filter_count,
1294 						    pause_filter_count_shrink,
1295 						    pause_filter_count);
1296 	if (control->pause_filter_count != old)
1297 		mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1298 
1299 	trace_kvm_ple_window_shrink(vcpu->vcpu_id,
1300 				    control->pause_filter_count, old);
1301 }
1302 
1303 /*
1304  * The default MMIO mask is a single bit (excluding the present bit),
1305  * which could conflict with the memory encryption bit. Check for
1306  * memory encryption support and override the default MMIO mask if
1307  * memory encryption is enabled.
1308  */
svm_adjust_mmio_mask(void)1309 static __init void svm_adjust_mmio_mask(void)
1310 {
1311 	unsigned int enc_bit, mask_bit;
1312 	u64 msr, mask;
1313 
1314 	/* If there is no memory encryption support, use existing mask */
1315 	if (cpuid_eax(0x80000000) < 0x8000001f)
1316 		return;
1317 
1318 	/* If memory encryption is not enabled, use existing mask */
1319 	rdmsrl(MSR_K8_SYSCFG, msr);
1320 	if (!(msr & MSR_K8_SYSCFG_MEM_ENCRYPT))
1321 		return;
1322 
1323 	enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
1324 	mask_bit = boot_cpu_data.x86_phys_bits;
1325 
1326 	/* Increment the mask bit if it is the same as the encryption bit */
1327 	if (enc_bit == mask_bit)
1328 		mask_bit++;
1329 
1330 	/*
1331 	 * If the mask bit location is below 52, then some bits above the
1332 	 * physical addressing limit will always be reserved, so use the
1333 	 * rsvd_bits() function to generate the mask. This mask, along with
1334 	 * the present bit, will be used to generate a page fault with
1335 	 * PFER.RSV = 1.
1336 	 *
1337 	 * If the mask bit location is 52 (or above), then clear the mask.
1338 	 */
1339 	mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
1340 
1341 	kvm_mmu_set_mmio_spte_mask(mask, mask);
1342 }
1343 
svm_hardware_setup(void)1344 static __init int svm_hardware_setup(void)
1345 {
1346 	int cpu;
1347 	struct page *iopm_pages;
1348 	void *iopm_va;
1349 	int r;
1350 
1351 	iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1352 
1353 	if (!iopm_pages)
1354 		return -ENOMEM;
1355 
1356 	iopm_va = page_address(iopm_pages);
1357 	memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1358 	iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1359 
1360 	init_msrpm_offsets();
1361 
1362 	if (boot_cpu_has(X86_FEATURE_NX))
1363 		kvm_enable_efer_bits(EFER_NX);
1364 
1365 	if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1366 		kvm_enable_efer_bits(EFER_FFXSR);
1367 
1368 	if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1369 		kvm_has_tsc_control = true;
1370 		kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1371 		kvm_tsc_scaling_ratio_frac_bits = 32;
1372 	}
1373 
1374 	/* Check for pause filtering support */
1375 	if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1376 		pause_filter_count = 0;
1377 		pause_filter_thresh = 0;
1378 	} else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
1379 		pause_filter_thresh = 0;
1380 	}
1381 
1382 	if (nested) {
1383 		printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1384 		kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1385 	}
1386 
1387 	if (sev) {
1388 		if (boot_cpu_has(X86_FEATURE_SEV) &&
1389 		    IS_ENABLED(CONFIG_KVM_AMD_SEV)) {
1390 			r = sev_hardware_setup();
1391 			if (r)
1392 				sev = false;
1393 		} else {
1394 			sev = false;
1395 		}
1396 	}
1397 
1398 	svm_adjust_mmio_mask();
1399 
1400 	for_each_possible_cpu(cpu) {
1401 		r = svm_cpu_init(cpu);
1402 		if (r)
1403 			goto err;
1404 	}
1405 
1406 	if (!boot_cpu_has(X86_FEATURE_NPT))
1407 		npt_enabled = false;
1408 
1409 	if (npt_enabled && !npt) {
1410 		printk(KERN_INFO "kvm: Nested Paging disabled\n");
1411 		npt_enabled = false;
1412 	}
1413 
1414 	if (npt_enabled) {
1415 		printk(KERN_INFO "kvm: Nested Paging enabled\n");
1416 		kvm_enable_tdp();
1417 	} else
1418 		kvm_disable_tdp();
1419 
1420 	if (avic) {
1421 		if (!npt_enabled ||
1422 		    !boot_cpu_has(X86_FEATURE_AVIC) ||
1423 		    !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1424 			avic = false;
1425 		} else {
1426 			pr_info("AVIC enabled\n");
1427 
1428 			amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1429 		}
1430 	}
1431 
1432 	if (vls) {
1433 		if (!npt_enabled ||
1434 		    !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1435 		    !IS_ENABLED(CONFIG_X86_64)) {
1436 			vls = false;
1437 		} else {
1438 			pr_info("Virtual VMLOAD VMSAVE supported\n");
1439 		}
1440 	}
1441 
1442 	vgif = false; /* Disabled for CVE-2021-3653 */
1443 
1444 	return 0;
1445 
1446 err:
1447 	__free_pages(iopm_pages, IOPM_ALLOC_ORDER);
1448 	iopm_base = 0;
1449 	return r;
1450 }
1451 
svm_hardware_unsetup(void)1452 static __exit void svm_hardware_unsetup(void)
1453 {
1454 	int cpu;
1455 
1456 	if (svm_sev_enabled())
1457 		bitmap_free(sev_asid_bitmap);
1458 
1459 	for_each_possible_cpu(cpu)
1460 		svm_cpu_uninit(cpu);
1461 
1462 	__free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1463 	iopm_base = 0;
1464 }
1465 
init_seg(struct vmcb_seg * seg)1466 static void init_seg(struct vmcb_seg *seg)
1467 {
1468 	seg->selector = 0;
1469 	seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1470 		      SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1471 	seg->limit = 0xffff;
1472 	seg->base = 0;
1473 }
1474 
init_sys_seg(struct vmcb_seg * seg,uint32_t type)1475 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1476 {
1477 	seg->selector = 0;
1478 	seg->attrib = SVM_SELECTOR_P_MASK | type;
1479 	seg->limit = 0xffff;
1480 	seg->base = 0;
1481 }
1482 
svm_read_l1_tsc_offset(struct kvm_vcpu * vcpu)1483 static u64 svm_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1484 {
1485 	struct vcpu_svm *svm = to_svm(vcpu);
1486 
1487 	if (is_guest_mode(vcpu))
1488 		return svm->nested.hsave->control.tsc_offset;
1489 
1490 	return vcpu->arch.tsc_offset;
1491 }
1492 
svm_write_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 offset)1493 static u64 svm_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1494 {
1495 	struct vcpu_svm *svm = to_svm(vcpu);
1496 	u64 g_tsc_offset = 0;
1497 
1498 	if (is_guest_mode(vcpu)) {
1499 		/* Write L1's TSC offset.  */
1500 		g_tsc_offset = svm->vmcb->control.tsc_offset -
1501 			       svm->nested.hsave->control.tsc_offset;
1502 		svm->nested.hsave->control.tsc_offset = offset;
1503 	} else
1504 		trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1505 					   svm->vmcb->control.tsc_offset,
1506 					   offset);
1507 
1508 	svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1509 
1510 	mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1511 	return svm->vmcb->control.tsc_offset;
1512 }
1513 
avic_init_vmcb(struct vcpu_svm * svm)1514 static void avic_init_vmcb(struct vcpu_svm *svm)
1515 {
1516 	struct vmcb *vmcb = svm->vmcb;
1517 	struct kvm_svm *kvm_svm = to_kvm_svm(svm->vcpu.kvm);
1518 	phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1519 	phys_addr_t lpa = __sme_set(page_to_phys(kvm_svm->avic_logical_id_table_page));
1520 	phys_addr_t ppa = __sme_set(page_to_phys(kvm_svm->avic_physical_id_table_page));
1521 
1522 	vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1523 	vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1524 	vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1525 	vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1526 	vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1527 }
1528 
init_vmcb(struct vcpu_svm * svm)1529 static void init_vmcb(struct vcpu_svm *svm)
1530 {
1531 	struct vmcb_control_area *control = &svm->vmcb->control;
1532 	struct vmcb_save_area *save = &svm->vmcb->save;
1533 
1534 	svm->vcpu.arch.hflags = 0;
1535 
1536 	set_cr_intercept(svm, INTERCEPT_CR0_READ);
1537 	set_cr_intercept(svm, INTERCEPT_CR3_READ);
1538 	set_cr_intercept(svm, INTERCEPT_CR4_READ);
1539 	set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1540 	set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1541 	set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1542 	if (!kvm_vcpu_apicv_active(&svm->vcpu))
1543 		set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1544 
1545 	set_dr_intercepts(svm);
1546 
1547 	set_exception_intercept(svm, PF_VECTOR);
1548 	set_exception_intercept(svm, UD_VECTOR);
1549 	set_exception_intercept(svm, MC_VECTOR);
1550 	set_exception_intercept(svm, AC_VECTOR);
1551 	set_exception_intercept(svm, DB_VECTOR);
1552 	/*
1553 	 * Guest access to VMware backdoor ports could legitimately
1554 	 * trigger #GP because of TSS I/O permission bitmap.
1555 	 * We intercept those #GP and allow access to them anyway
1556 	 * as VMware does.
1557 	 */
1558 	if (enable_vmware_backdoor)
1559 		set_exception_intercept(svm, GP_VECTOR);
1560 
1561 	set_intercept(svm, INTERCEPT_INTR);
1562 	set_intercept(svm, INTERCEPT_NMI);
1563 	set_intercept(svm, INTERCEPT_SMI);
1564 	set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1565 	set_intercept(svm, INTERCEPT_RDPMC);
1566 	set_intercept(svm, INTERCEPT_CPUID);
1567 	set_intercept(svm, INTERCEPT_INVD);
1568 	set_intercept(svm, INTERCEPT_INVLPG);
1569 	set_intercept(svm, INTERCEPT_INVLPGA);
1570 	set_intercept(svm, INTERCEPT_IOIO_PROT);
1571 	set_intercept(svm, INTERCEPT_MSR_PROT);
1572 	set_intercept(svm, INTERCEPT_TASK_SWITCH);
1573 	set_intercept(svm, INTERCEPT_SHUTDOWN);
1574 	set_intercept(svm, INTERCEPT_VMRUN);
1575 	set_intercept(svm, INTERCEPT_VMMCALL);
1576 	set_intercept(svm, INTERCEPT_VMLOAD);
1577 	set_intercept(svm, INTERCEPT_VMSAVE);
1578 	set_intercept(svm, INTERCEPT_STGI);
1579 	set_intercept(svm, INTERCEPT_CLGI);
1580 	set_intercept(svm, INTERCEPT_SKINIT);
1581 	set_intercept(svm, INTERCEPT_WBINVD);
1582 	set_intercept(svm, INTERCEPT_XSETBV);
1583 	set_intercept(svm, INTERCEPT_RSM);
1584 
1585 	if (!kvm_mwait_in_guest(svm->vcpu.kvm)) {
1586 		set_intercept(svm, INTERCEPT_MONITOR);
1587 		set_intercept(svm, INTERCEPT_MWAIT);
1588 	}
1589 
1590 	if (!kvm_hlt_in_guest(svm->vcpu.kvm))
1591 		set_intercept(svm, INTERCEPT_HLT);
1592 
1593 	control->iopm_base_pa = __sme_set(iopm_base);
1594 	control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1595 	control->int_ctl = V_INTR_MASKING_MASK;
1596 
1597 	init_seg(&save->es);
1598 	init_seg(&save->ss);
1599 	init_seg(&save->ds);
1600 	init_seg(&save->fs);
1601 	init_seg(&save->gs);
1602 
1603 	save->cs.selector = 0xf000;
1604 	save->cs.base = 0xffff0000;
1605 	/* Executable/Readable Code Segment */
1606 	save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1607 		SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1608 	save->cs.limit = 0xffff;
1609 
1610 	save->gdtr.limit = 0xffff;
1611 	save->idtr.limit = 0xffff;
1612 
1613 	init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1614 	init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1615 
1616 	svm_set_efer(&svm->vcpu, 0);
1617 	save->dr6 = 0xffff0ff0;
1618 	kvm_set_rflags(&svm->vcpu, 2);
1619 	save->rip = 0x0000fff0;
1620 	svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1621 
1622 	/*
1623 	 * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1624 	 * It also updates the guest-visible cr0 value.
1625 	 */
1626 	svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1627 	kvm_mmu_reset_context(&svm->vcpu);
1628 
1629 	save->cr4 = X86_CR4_PAE;
1630 	/* rdx = ?? */
1631 
1632 	if (npt_enabled) {
1633 		/* Setup VMCB for Nested Paging */
1634 		control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1635 		clr_intercept(svm, INTERCEPT_INVLPG);
1636 		clr_exception_intercept(svm, PF_VECTOR);
1637 		clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1638 		clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1639 		save->g_pat = svm->vcpu.arch.pat;
1640 		save->cr3 = 0;
1641 		save->cr4 = 0;
1642 	}
1643 	svm->asid_generation = 0;
1644 
1645 	svm->nested.vmcb = 0;
1646 	svm->vcpu.arch.hflags = 0;
1647 
1648 	if (pause_filter_count) {
1649 		control->pause_filter_count = pause_filter_count;
1650 		if (pause_filter_thresh)
1651 			control->pause_filter_thresh = pause_filter_thresh;
1652 		set_intercept(svm, INTERCEPT_PAUSE);
1653 	} else {
1654 		clr_intercept(svm, INTERCEPT_PAUSE);
1655 	}
1656 
1657 	if (kvm_vcpu_apicv_active(&svm->vcpu))
1658 		avic_init_vmcb(svm);
1659 
1660 	/*
1661 	 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1662 	 * in VMCB and clear intercepts to avoid #VMEXIT.
1663 	 */
1664 	if (vls) {
1665 		clr_intercept(svm, INTERCEPT_VMLOAD);
1666 		clr_intercept(svm, INTERCEPT_VMSAVE);
1667 		svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1668 	}
1669 
1670 	if (vgif) {
1671 		clr_intercept(svm, INTERCEPT_STGI);
1672 		clr_intercept(svm, INTERCEPT_CLGI);
1673 		svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1674 	}
1675 
1676 	if (sev_guest(svm->vcpu.kvm)) {
1677 		svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1678 		clr_exception_intercept(svm, UD_VECTOR);
1679 	}
1680 
1681 	mark_all_dirty(svm->vmcb);
1682 
1683 	enable_gif(svm);
1684 
1685 }
1686 
avic_get_physical_id_entry(struct kvm_vcpu * vcpu,unsigned int index)1687 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1688 				       unsigned int index)
1689 {
1690 	u64 *avic_physical_id_table;
1691 	struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
1692 
1693 	if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1694 		return NULL;
1695 
1696 	avic_physical_id_table = page_address(kvm_svm->avic_physical_id_table_page);
1697 
1698 	return &avic_physical_id_table[index];
1699 }
1700 
1701 /**
1702  * Note:
1703  * AVIC hardware walks the nested page table to check permissions,
1704  * but does not use the SPA address specified in the leaf page
1705  * table entry since it uses  address in the AVIC_BACKING_PAGE pointer
1706  * field of the VMCB. Therefore, we set up the
1707  * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1708  */
avic_init_access_page(struct kvm_vcpu * vcpu)1709 static int avic_init_access_page(struct kvm_vcpu *vcpu)
1710 {
1711 	struct kvm *kvm = vcpu->kvm;
1712 	int ret = 0;
1713 
1714 	mutex_lock(&kvm->slots_lock);
1715 	if (kvm->arch.apic_access_page_done)
1716 		goto out;
1717 
1718 	ret = __x86_set_memory_region(kvm,
1719 				      APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1720 				      APIC_DEFAULT_PHYS_BASE,
1721 				      PAGE_SIZE);
1722 	if (ret)
1723 		goto out;
1724 
1725 	kvm->arch.apic_access_page_done = true;
1726 out:
1727 	mutex_unlock(&kvm->slots_lock);
1728 	return ret;
1729 }
1730 
avic_init_backing_page(struct kvm_vcpu * vcpu)1731 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1732 {
1733 	int ret;
1734 	u64 *entry, new_entry;
1735 	int id = vcpu->vcpu_id;
1736 	struct vcpu_svm *svm = to_svm(vcpu);
1737 
1738 	ret = avic_init_access_page(vcpu);
1739 	if (ret)
1740 		return ret;
1741 
1742 	if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1743 		return -EINVAL;
1744 
1745 	if (!svm->vcpu.arch.apic->regs)
1746 		return -EINVAL;
1747 
1748 	svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1749 
1750 	/* Setting AVIC backing page address in the phy APIC ID table */
1751 	entry = avic_get_physical_id_entry(vcpu, id);
1752 	if (!entry)
1753 		return -EINVAL;
1754 
1755 	new_entry = READ_ONCE(*entry);
1756 	new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1757 			      AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1758 			      AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1759 	WRITE_ONCE(*entry, new_entry);
1760 
1761 	svm->avic_physical_id_cache = entry;
1762 
1763 	return 0;
1764 }
1765 
__sev_asid_free(int asid)1766 static void __sev_asid_free(int asid)
1767 {
1768 	struct svm_cpu_data *sd;
1769 	int cpu, pos;
1770 
1771 	pos = asid - 1;
1772 	clear_bit(pos, sev_asid_bitmap);
1773 
1774 	for_each_possible_cpu(cpu) {
1775 		sd = per_cpu(svm_data, cpu);
1776 		sd->sev_vmcbs[pos] = NULL;
1777 	}
1778 }
1779 
sev_asid_free(struct kvm * kvm)1780 static void sev_asid_free(struct kvm *kvm)
1781 {
1782 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1783 
1784 	__sev_asid_free(sev->asid);
1785 }
1786 
sev_unbind_asid(struct kvm * kvm,unsigned int handle)1787 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
1788 {
1789 	struct sev_data_decommission *decommission;
1790 	struct sev_data_deactivate *data;
1791 
1792 	if (!handle)
1793 		return;
1794 
1795 	data = kzalloc(sizeof(*data), GFP_KERNEL);
1796 	if (!data)
1797 		return;
1798 
1799 	/* deactivate handle */
1800 	data->handle = handle;
1801 	sev_guest_deactivate(data, NULL);
1802 
1803 	wbinvd_on_all_cpus();
1804 	sev_guest_df_flush(NULL);
1805 	kfree(data);
1806 
1807 	decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
1808 	if (!decommission)
1809 		return;
1810 
1811 	/* decommission handle */
1812 	decommission->handle = handle;
1813 	sev_guest_decommission(decommission, NULL);
1814 
1815 	kfree(decommission);
1816 }
1817 
sev_pin_memory(struct kvm * kvm,unsigned long uaddr,unsigned long ulen,unsigned long * n,int write)1818 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
1819 				    unsigned long ulen, unsigned long *n,
1820 				    int write)
1821 {
1822 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1823 	unsigned long npages, npinned, size;
1824 	unsigned long locked, lock_limit;
1825 	struct page **pages;
1826 	unsigned long first, last;
1827 
1828 	if (ulen == 0 || uaddr + ulen < uaddr)
1829 		return NULL;
1830 
1831 	/* Calculate number of pages. */
1832 	first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
1833 	last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
1834 	npages = (last - first + 1);
1835 
1836 	locked = sev->pages_locked + npages;
1837 	lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1838 	if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1839 		pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
1840 		return NULL;
1841 	}
1842 
1843 	/* Avoid using vmalloc for smaller buffers. */
1844 	size = npages * sizeof(struct page *);
1845 	if (size > PAGE_SIZE)
1846 		pages = vmalloc(size);
1847 	else
1848 		pages = kmalloc(size, GFP_KERNEL);
1849 
1850 	if (!pages)
1851 		return NULL;
1852 
1853 	/* Pin the user virtual address. */
1854 	npinned = get_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
1855 	if (npinned != npages) {
1856 		pr_err("SEV: Failure locking %lu pages.\n", npages);
1857 		goto err;
1858 	}
1859 
1860 	*n = npages;
1861 	sev->pages_locked = locked;
1862 
1863 	return pages;
1864 
1865 err:
1866 	if (npinned > 0)
1867 		release_pages(pages, npinned);
1868 
1869 	kvfree(pages);
1870 	return NULL;
1871 }
1872 
sev_unpin_memory(struct kvm * kvm,struct page ** pages,unsigned long npages)1873 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
1874 			     unsigned long npages)
1875 {
1876 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1877 
1878 	release_pages(pages, npages);
1879 	kvfree(pages);
1880 	sev->pages_locked -= npages;
1881 }
1882 
sev_clflush_pages(struct page * pages[],unsigned long npages)1883 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
1884 {
1885 	uint8_t *page_virtual;
1886 	unsigned long i;
1887 
1888 	if (npages == 0 || pages == NULL)
1889 		return;
1890 
1891 	for (i = 0; i < npages; i++) {
1892 		page_virtual = kmap_atomic(pages[i]);
1893 		clflush_cache_range(page_virtual, PAGE_SIZE);
1894 		kunmap_atomic(page_virtual);
1895 	}
1896 }
1897 
__unregister_enc_region_locked(struct kvm * kvm,struct enc_region * region)1898 static void __unregister_enc_region_locked(struct kvm *kvm,
1899 					   struct enc_region *region)
1900 {
1901 	/*
1902 	 * The guest may change the memory encryption attribute from C=0 -> C=1
1903 	 * or vice versa for this memory range. Lets make sure caches are
1904 	 * flushed to ensure that guest data gets written into memory with
1905 	 * correct C-bit.
1906 	 */
1907 	sev_clflush_pages(region->pages, region->npages);
1908 
1909 	sev_unpin_memory(kvm, region->pages, region->npages);
1910 	list_del(&region->list);
1911 	kfree(region);
1912 }
1913 
svm_vm_alloc(void)1914 static struct kvm *svm_vm_alloc(void)
1915 {
1916 	struct kvm_svm *kvm_svm = vzalloc(sizeof(struct kvm_svm));
1917 
1918 	if (!kvm_svm)
1919 		return NULL;
1920 
1921 	return &kvm_svm->kvm;
1922 }
1923 
svm_vm_free(struct kvm * kvm)1924 static void svm_vm_free(struct kvm *kvm)
1925 {
1926 	vfree(to_kvm_svm(kvm));
1927 }
1928 
sev_vm_destroy(struct kvm * kvm)1929 static void sev_vm_destroy(struct kvm *kvm)
1930 {
1931 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1932 	struct list_head *head = &sev->regions_list;
1933 	struct list_head *pos, *q;
1934 
1935 	if (!sev_guest(kvm))
1936 		return;
1937 
1938 	mutex_lock(&kvm->lock);
1939 
1940 	/*
1941 	 * if userspace was terminated before unregistering the memory regions
1942 	 * then lets unpin all the registered memory.
1943 	 */
1944 	if (!list_empty(head)) {
1945 		list_for_each_safe(pos, q, head) {
1946 			__unregister_enc_region_locked(kvm,
1947 				list_entry(pos, struct enc_region, list));
1948 				cond_resched();
1949 		}
1950 	}
1951 
1952 	mutex_unlock(&kvm->lock);
1953 
1954 	sev_unbind_asid(kvm, sev->handle);
1955 	sev_asid_free(kvm);
1956 }
1957 
avic_vm_destroy(struct kvm * kvm)1958 static void avic_vm_destroy(struct kvm *kvm)
1959 {
1960 	unsigned long flags;
1961 	struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1962 
1963 	if (!avic)
1964 		return;
1965 
1966 	if (kvm_svm->avic_logical_id_table_page)
1967 		__free_page(kvm_svm->avic_logical_id_table_page);
1968 	if (kvm_svm->avic_physical_id_table_page)
1969 		__free_page(kvm_svm->avic_physical_id_table_page);
1970 
1971 	spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1972 	hash_del(&kvm_svm->hnode);
1973 	spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1974 }
1975 
svm_vm_destroy(struct kvm * kvm)1976 static void svm_vm_destroy(struct kvm *kvm)
1977 {
1978 	avic_vm_destroy(kvm);
1979 	sev_vm_destroy(kvm);
1980 }
1981 
avic_vm_init(struct kvm * kvm)1982 static int avic_vm_init(struct kvm *kvm)
1983 {
1984 	unsigned long flags;
1985 	int err = -ENOMEM;
1986 	struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1987 	struct kvm_svm *k2;
1988 	struct page *p_page;
1989 	struct page *l_page;
1990 	u32 vm_id;
1991 
1992 	if (!avic)
1993 		return 0;
1994 
1995 	/* Allocating physical APIC ID table (4KB) */
1996 	p_page = alloc_page(GFP_KERNEL);
1997 	if (!p_page)
1998 		goto free_avic;
1999 
2000 	kvm_svm->avic_physical_id_table_page = p_page;
2001 	clear_page(page_address(p_page));
2002 
2003 	/* Allocating logical APIC ID table (4KB) */
2004 	l_page = alloc_page(GFP_KERNEL);
2005 	if (!l_page)
2006 		goto free_avic;
2007 
2008 	kvm_svm->avic_logical_id_table_page = l_page;
2009 	clear_page(page_address(l_page));
2010 
2011 	spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
2012  again:
2013 	vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
2014 	if (vm_id == 0) { /* id is 1-based, zero is not okay */
2015 		next_vm_id_wrapped = 1;
2016 		goto again;
2017 	}
2018 	/* Is it still in use? Only possible if wrapped at least once */
2019 	if (next_vm_id_wrapped) {
2020 		hash_for_each_possible(svm_vm_data_hash, k2, hnode, vm_id) {
2021 			if (k2->avic_vm_id == vm_id)
2022 				goto again;
2023 		}
2024 	}
2025 	kvm_svm->avic_vm_id = vm_id;
2026 	hash_add(svm_vm_data_hash, &kvm_svm->hnode, kvm_svm->avic_vm_id);
2027 	spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
2028 
2029 	return 0;
2030 
2031 free_avic:
2032 	avic_vm_destroy(kvm);
2033 	return err;
2034 }
2035 
2036 static inline int
avic_update_iommu_vcpu_affinity(struct kvm_vcpu * vcpu,int cpu,bool r)2037 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
2038 {
2039 	int ret = 0;
2040 	unsigned long flags;
2041 	struct amd_svm_iommu_ir *ir;
2042 	struct vcpu_svm *svm = to_svm(vcpu);
2043 
2044 	if (!kvm_arch_has_assigned_device(vcpu->kvm))
2045 		return 0;
2046 
2047 	/*
2048 	 * Here, we go through the per-vcpu ir_list to update all existing
2049 	 * interrupt remapping table entry targeting this vcpu.
2050 	 */
2051 	spin_lock_irqsave(&svm->ir_list_lock, flags);
2052 
2053 	if (list_empty(&svm->ir_list))
2054 		goto out;
2055 
2056 	list_for_each_entry(ir, &svm->ir_list, node) {
2057 		ret = amd_iommu_update_ga(cpu, r, ir->data);
2058 		if (ret)
2059 			break;
2060 	}
2061 out:
2062 	spin_unlock_irqrestore(&svm->ir_list_lock, flags);
2063 	return ret;
2064 }
2065 
avic_vcpu_load(struct kvm_vcpu * vcpu,int cpu)2066 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2067 {
2068 	u64 entry;
2069 	/* ID = 0xff (broadcast), ID > 0xff (reserved) */
2070 	int h_physical_id = kvm_cpu_get_apicid(cpu);
2071 	struct vcpu_svm *svm = to_svm(vcpu);
2072 
2073 	if (!kvm_vcpu_apicv_active(vcpu))
2074 		return;
2075 
2076 	/*
2077 	 * Since the host physical APIC id is 8 bits,
2078 	 * we can support host APIC ID upto 255.
2079 	 */
2080 	if (WARN_ON(h_physical_id > AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK))
2081 		return;
2082 
2083 	entry = READ_ONCE(*(svm->avic_physical_id_cache));
2084 	WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
2085 
2086 	entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
2087 	entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
2088 
2089 	entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2090 	if (svm->avic_is_running)
2091 		entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2092 
2093 	WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2094 	avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
2095 					svm->avic_is_running);
2096 }
2097 
avic_vcpu_put(struct kvm_vcpu * vcpu)2098 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
2099 {
2100 	u64 entry;
2101 	struct vcpu_svm *svm = to_svm(vcpu);
2102 
2103 	if (!kvm_vcpu_apicv_active(vcpu))
2104 		return;
2105 
2106 	entry = READ_ONCE(*(svm->avic_physical_id_cache));
2107 	if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
2108 		avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
2109 
2110 	entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2111 	WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2112 }
2113 
2114 /**
2115  * This function is called during VCPU halt/unhalt.
2116  */
avic_set_running(struct kvm_vcpu * vcpu,bool is_run)2117 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
2118 {
2119 	struct vcpu_svm *svm = to_svm(vcpu);
2120 
2121 	svm->avic_is_running = is_run;
2122 	if (is_run)
2123 		avic_vcpu_load(vcpu, vcpu->cpu);
2124 	else
2125 		avic_vcpu_put(vcpu);
2126 }
2127 
svm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)2128 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
2129 {
2130 	struct vcpu_svm *svm = to_svm(vcpu);
2131 	u32 dummy;
2132 	u32 eax = 1;
2133 
2134 	vcpu->arch.microcode_version = 0x01000065;
2135 	svm->spec_ctrl = 0;
2136 	svm->virt_spec_ctrl = 0;
2137 
2138 	if (!init_event) {
2139 		svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
2140 					   MSR_IA32_APICBASE_ENABLE;
2141 		if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
2142 			svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
2143 	}
2144 	init_vmcb(svm);
2145 
2146 	kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
2147 	kvm_register_write(vcpu, VCPU_REGS_RDX, eax);
2148 
2149 	if (kvm_vcpu_apicv_active(vcpu) && !init_event)
2150 		avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
2151 }
2152 
avic_init_vcpu(struct vcpu_svm * svm)2153 static int avic_init_vcpu(struct vcpu_svm *svm)
2154 {
2155 	int ret;
2156 
2157 	if (!kvm_vcpu_apicv_active(&svm->vcpu))
2158 		return 0;
2159 
2160 	ret = avic_init_backing_page(&svm->vcpu);
2161 	if (ret)
2162 		return ret;
2163 
2164 	INIT_LIST_HEAD(&svm->ir_list);
2165 	spin_lock_init(&svm->ir_list_lock);
2166 
2167 	return ret;
2168 }
2169 
svm_create_vcpu(struct kvm * kvm,unsigned int id)2170 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
2171 {
2172 	struct vcpu_svm *svm;
2173 	struct page *page;
2174 	struct page *msrpm_pages;
2175 	struct page *hsave_page;
2176 	struct page *nested_msrpm_pages;
2177 	int err;
2178 
2179 	svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
2180 	if (!svm) {
2181 		err = -ENOMEM;
2182 		goto out;
2183 	}
2184 
2185 	err = kvm_vcpu_init(&svm->vcpu, kvm, id);
2186 	if (err)
2187 		goto free_svm;
2188 
2189 	err = -ENOMEM;
2190 	page = alloc_page(GFP_KERNEL);
2191 	if (!page)
2192 		goto uninit;
2193 
2194 	msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
2195 	if (!msrpm_pages)
2196 		goto free_page1;
2197 
2198 	nested_msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
2199 	if (!nested_msrpm_pages)
2200 		goto free_page2;
2201 
2202 	hsave_page = alloc_page(GFP_KERNEL);
2203 	if (!hsave_page)
2204 		goto free_page3;
2205 
2206 	err = avic_init_vcpu(svm);
2207 	if (err)
2208 		goto free_page4;
2209 
2210 	/* We initialize this flag to true to make sure that the is_running
2211 	 * bit would be set the first time the vcpu is loaded.
2212 	 */
2213 	svm->avic_is_running = true;
2214 
2215 	svm->nested.hsave = page_address(hsave_page);
2216 
2217 	svm->msrpm = page_address(msrpm_pages);
2218 	svm_vcpu_init_msrpm(svm->msrpm);
2219 
2220 	svm->nested.msrpm = page_address(nested_msrpm_pages);
2221 	svm_vcpu_init_msrpm(svm->nested.msrpm);
2222 
2223 	svm->vmcb = page_address(page);
2224 	clear_page(svm->vmcb);
2225 	svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
2226 	svm->asid_generation = 0;
2227 	init_vmcb(svm);
2228 
2229 	svm_init_osvw(&svm->vcpu);
2230 
2231 	return &svm->vcpu;
2232 
2233 free_page4:
2234 	__free_page(hsave_page);
2235 free_page3:
2236 	__free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2237 free_page2:
2238 	__free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2239 free_page1:
2240 	__free_page(page);
2241 uninit:
2242 	kvm_vcpu_uninit(&svm->vcpu);
2243 free_svm:
2244 	kmem_cache_free(kvm_vcpu_cache, svm);
2245 out:
2246 	return ERR_PTR(err);
2247 }
2248 
svm_clear_current_vmcb(struct vmcb * vmcb)2249 static void svm_clear_current_vmcb(struct vmcb *vmcb)
2250 {
2251 	int i;
2252 
2253 	for_each_online_cpu(i)
2254 		cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
2255 }
2256 
svm_free_vcpu(struct kvm_vcpu * vcpu)2257 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2258 {
2259 	struct vcpu_svm *svm = to_svm(vcpu);
2260 
2261 	/*
2262 	 * The vmcb page can be recycled, causing a false negative in
2263 	 * svm_vcpu_load(). So, ensure that no logical CPU has this
2264 	 * vmcb page recorded as its current vmcb.
2265 	 */
2266 	svm_clear_current_vmcb(svm->vmcb);
2267 
2268 	__free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2269 	__free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2270 	__free_page(virt_to_page(svm->nested.hsave));
2271 	__free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2272 	kvm_vcpu_uninit(vcpu);
2273 	kmem_cache_free(kvm_vcpu_cache, svm);
2274 }
2275 
svm_vcpu_load(struct kvm_vcpu * vcpu,int cpu)2276 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2277 {
2278 	struct vcpu_svm *svm = to_svm(vcpu);
2279 	struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2280 	int i;
2281 
2282 	if (unlikely(cpu != vcpu->cpu)) {
2283 		svm->asid_generation = 0;
2284 		mark_all_dirty(svm->vmcb);
2285 	}
2286 
2287 #ifdef CONFIG_X86_64
2288 	rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2289 #endif
2290 	savesegment(fs, svm->host.fs);
2291 	savesegment(gs, svm->host.gs);
2292 	svm->host.ldt = kvm_read_ldt();
2293 
2294 	for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2295 		rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2296 
2297 	if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2298 		u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2299 		if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2300 			__this_cpu_write(current_tsc_ratio, tsc_ratio);
2301 			wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2302 		}
2303 	}
2304 	/* This assumes that the kernel never uses MSR_TSC_AUX */
2305 	if (static_cpu_has(X86_FEATURE_RDTSCP))
2306 		wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2307 
2308 	if (sd->current_vmcb != svm->vmcb) {
2309 		sd->current_vmcb = svm->vmcb;
2310 		indirect_branch_prediction_barrier();
2311 	}
2312 	avic_vcpu_load(vcpu, cpu);
2313 }
2314 
svm_vcpu_put(struct kvm_vcpu * vcpu)2315 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2316 {
2317 	struct vcpu_svm *svm = to_svm(vcpu);
2318 	int i;
2319 
2320 	avic_vcpu_put(vcpu);
2321 
2322 	++vcpu->stat.host_state_reload;
2323 	kvm_load_ldt(svm->host.ldt);
2324 #ifdef CONFIG_X86_64
2325 	loadsegment(fs, svm->host.fs);
2326 	wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2327 	load_gs_index(svm->host.gs);
2328 #else
2329 #ifdef CONFIG_X86_32_LAZY_GS
2330 	loadsegment(gs, svm->host.gs);
2331 #endif
2332 #endif
2333 	for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2334 		wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2335 }
2336 
svm_vcpu_blocking(struct kvm_vcpu * vcpu)2337 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2338 {
2339 	avic_set_running(vcpu, false);
2340 }
2341 
svm_vcpu_unblocking(struct kvm_vcpu * vcpu)2342 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2343 {
2344 	avic_set_running(vcpu, true);
2345 }
2346 
svm_get_rflags(struct kvm_vcpu * vcpu)2347 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2348 {
2349 	struct vcpu_svm *svm = to_svm(vcpu);
2350 	unsigned long rflags = svm->vmcb->save.rflags;
2351 
2352 	if (svm->nmi_singlestep) {
2353 		/* Hide our flags if they were not set by the guest */
2354 		if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2355 			rflags &= ~X86_EFLAGS_TF;
2356 		if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2357 			rflags &= ~X86_EFLAGS_RF;
2358 	}
2359 	return rflags;
2360 }
2361 
svm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)2362 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2363 {
2364 	if (to_svm(vcpu)->nmi_singlestep)
2365 		rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2366 
2367        /*
2368         * Any change of EFLAGS.VM is accompanied by a reload of SS
2369         * (caused by either a task switch or an inter-privilege IRET),
2370         * so we do not need to update the CPL here.
2371         */
2372 	to_svm(vcpu)->vmcb->save.rflags = rflags;
2373 }
2374 
svm_cache_reg(struct kvm_vcpu * vcpu,enum kvm_reg reg)2375 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2376 {
2377 	switch (reg) {
2378 	case VCPU_EXREG_PDPTR:
2379 		BUG_ON(!npt_enabled);
2380 		load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2381 		break;
2382 	default:
2383 		BUG();
2384 	}
2385 }
2386 
svm_set_vintr(struct vcpu_svm * svm)2387 static void svm_set_vintr(struct vcpu_svm *svm)
2388 {
2389 	set_intercept(svm, INTERCEPT_VINTR);
2390 }
2391 
svm_clear_vintr(struct vcpu_svm * svm)2392 static void svm_clear_vintr(struct vcpu_svm *svm)
2393 {
2394 	clr_intercept(svm, INTERCEPT_VINTR);
2395 }
2396 
svm_seg(struct kvm_vcpu * vcpu,int seg)2397 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2398 {
2399 	struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2400 
2401 	switch (seg) {
2402 	case VCPU_SREG_CS: return &save->cs;
2403 	case VCPU_SREG_DS: return &save->ds;
2404 	case VCPU_SREG_ES: return &save->es;
2405 	case VCPU_SREG_FS: return &save->fs;
2406 	case VCPU_SREG_GS: return &save->gs;
2407 	case VCPU_SREG_SS: return &save->ss;
2408 	case VCPU_SREG_TR: return &save->tr;
2409 	case VCPU_SREG_LDTR: return &save->ldtr;
2410 	}
2411 	BUG();
2412 	return NULL;
2413 }
2414 
svm_get_segment_base(struct kvm_vcpu * vcpu,int seg)2415 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2416 {
2417 	struct vmcb_seg *s = svm_seg(vcpu, seg);
2418 
2419 	return s->base;
2420 }
2421 
svm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)2422 static void svm_get_segment(struct kvm_vcpu *vcpu,
2423 			    struct kvm_segment *var, int seg)
2424 {
2425 	struct vmcb_seg *s = svm_seg(vcpu, seg);
2426 
2427 	var->base = s->base;
2428 	var->limit = s->limit;
2429 	var->selector = s->selector;
2430 	var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2431 	var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2432 	var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2433 	var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2434 	var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2435 	var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2436 	var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2437 
2438 	/*
2439 	 * AMD CPUs circa 2014 track the G bit for all segments except CS.
2440 	 * However, the SVM spec states that the G bit is not observed by the
2441 	 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2442 	 * So let's synthesize a legal G bit for all segments, this helps
2443 	 * running KVM nested. It also helps cross-vendor migration, because
2444 	 * Intel's vmentry has a check on the 'G' bit.
2445 	 */
2446 	var->g = s->limit > 0xfffff;
2447 
2448 	/*
2449 	 * AMD's VMCB does not have an explicit unusable field, so emulate it
2450 	 * for cross vendor migration purposes by "not present"
2451 	 */
2452 	var->unusable = !var->present;
2453 
2454 	switch (seg) {
2455 	case VCPU_SREG_TR:
2456 		/*
2457 		 * Work around a bug where the busy flag in the tr selector
2458 		 * isn't exposed
2459 		 */
2460 		var->type |= 0x2;
2461 		break;
2462 	case VCPU_SREG_DS:
2463 	case VCPU_SREG_ES:
2464 	case VCPU_SREG_FS:
2465 	case VCPU_SREG_GS:
2466 		/*
2467 		 * The accessed bit must always be set in the segment
2468 		 * descriptor cache, although it can be cleared in the
2469 		 * descriptor, the cached bit always remains at 1. Since
2470 		 * Intel has a check on this, set it here to support
2471 		 * cross-vendor migration.
2472 		 */
2473 		if (!var->unusable)
2474 			var->type |= 0x1;
2475 		break;
2476 	case VCPU_SREG_SS:
2477 		/*
2478 		 * On AMD CPUs sometimes the DB bit in the segment
2479 		 * descriptor is left as 1, although the whole segment has
2480 		 * been made unusable. Clear it here to pass an Intel VMX
2481 		 * entry check when cross vendor migrating.
2482 		 */
2483 		if (var->unusable)
2484 			var->db = 0;
2485 		/* This is symmetric with svm_set_segment() */
2486 		var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2487 		break;
2488 	}
2489 }
2490 
svm_get_cpl(struct kvm_vcpu * vcpu)2491 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2492 {
2493 	struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2494 
2495 	return save->cpl;
2496 }
2497 
svm_get_idt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)2498 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2499 {
2500 	struct vcpu_svm *svm = to_svm(vcpu);
2501 
2502 	dt->size = svm->vmcb->save.idtr.limit;
2503 	dt->address = svm->vmcb->save.idtr.base;
2504 }
2505 
svm_set_idt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)2506 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2507 {
2508 	struct vcpu_svm *svm = to_svm(vcpu);
2509 
2510 	svm->vmcb->save.idtr.limit = dt->size;
2511 	svm->vmcb->save.idtr.base = dt->address ;
2512 	mark_dirty(svm->vmcb, VMCB_DT);
2513 }
2514 
svm_get_gdt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)2515 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2516 {
2517 	struct vcpu_svm *svm = to_svm(vcpu);
2518 
2519 	dt->size = svm->vmcb->save.gdtr.limit;
2520 	dt->address = svm->vmcb->save.gdtr.base;
2521 }
2522 
svm_set_gdt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)2523 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2524 {
2525 	struct vcpu_svm *svm = to_svm(vcpu);
2526 
2527 	svm->vmcb->save.gdtr.limit = dt->size;
2528 	svm->vmcb->save.gdtr.base = dt->address ;
2529 	mark_dirty(svm->vmcb, VMCB_DT);
2530 }
2531 
svm_decache_cr0_guest_bits(struct kvm_vcpu * vcpu)2532 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2533 {
2534 }
2535 
svm_decache_cr3(struct kvm_vcpu * vcpu)2536 static void svm_decache_cr3(struct kvm_vcpu *vcpu)
2537 {
2538 }
2539 
svm_decache_cr4_guest_bits(struct kvm_vcpu * vcpu)2540 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2541 {
2542 }
2543 
update_cr0_intercept(struct vcpu_svm * svm)2544 static void update_cr0_intercept(struct vcpu_svm *svm)
2545 {
2546 	ulong gcr0 = svm->vcpu.arch.cr0;
2547 	u64 *hcr0 = &svm->vmcb->save.cr0;
2548 
2549 	*hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2550 		| (gcr0 & SVM_CR0_SELECTIVE_MASK);
2551 
2552 	mark_dirty(svm->vmcb, VMCB_CR);
2553 
2554 	if (gcr0 == *hcr0) {
2555 		clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2556 		clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2557 	} else {
2558 		set_cr_intercept(svm, INTERCEPT_CR0_READ);
2559 		set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2560 	}
2561 }
2562 
svm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)2563 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2564 {
2565 	struct vcpu_svm *svm = to_svm(vcpu);
2566 
2567 #ifdef CONFIG_X86_64
2568 	if (vcpu->arch.efer & EFER_LME) {
2569 		if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2570 			vcpu->arch.efer |= EFER_LMA;
2571 			svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2572 		}
2573 
2574 		if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2575 			vcpu->arch.efer &= ~EFER_LMA;
2576 			svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2577 		}
2578 	}
2579 #endif
2580 	vcpu->arch.cr0 = cr0;
2581 
2582 	if (!npt_enabled)
2583 		cr0 |= X86_CR0_PG | X86_CR0_WP;
2584 
2585 	/*
2586 	 * re-enable caching here because the QEMU bios
2587 	 * does not do it - this results in some delay at
2588 	 * reboot
2589 	 */
2590 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2591 		cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2592 	svm->vmcb->save.cr0 = cr0;
2593 	mark_dirty(svm->vmcb, VMCB_CR);
2594 	update_cr0_intercept(svm);
2595 }
2596 
svm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)2597 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2598 {
2599 	unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2600 	unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2601 
2602 	if (cr4 & X86_CR4_VMXE)
2603 		return 1;
2604 
2605 	if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2606 		svm_flush_tlb(vcpu, true);
2607 
2608 	vcpu->arch.cr4 = cr4;
2609 	if (!npt_enabled)
2610 		cr4 |= X86_CR4_PAE;
2611 	cr4 |= host_cr4_mce;
2612 	to_svm(vcpu)->vmcb->save.cr4 = cr4;
2613 	mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2614 	return 0;
2615 }
2616 
svm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)2617 static void svm_set_segment(struct kvm_vcpu *vcpu,
2618 			    struct kvm_segment *var, int seg)
2619 {
2620 	struct vcpu_svm *svm = to_svm(vcpu);
2621 	struct vmcb_seg *s = svm_seg(vcpu, seg);
2622 
2623 	s->base = var->base;
2624 	s->limit = var->limit;
2625 	s->selector = var->selector;
2626 	s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2627 	s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2628 	s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2629 	s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2630 	s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2631 	s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2632 	s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2633 	s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2634 
2635 	/*
2636 	 * This is always accurate, except if SYSRET returned to a segment
2637 	 * with SS.DPL != 3.  Intel does not have this quirk, and always
2638 	 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2639 	 * would entail passing the CPL to userspace and back.
2640 	 */
2641 	if (seg == VCPU_SREG_SS)
2642 		/* This is symmetric with svm_get_segment() */
2643 		svm->vmcb->save.cpl = (var->dpl & 3);
2644 
2645 	mark_dirty(svm->vmcb, VMCB_SEG);
2646 }
2647 
update_bp_intercept(struct kvm_vcpu * vcpu)2648 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2649 {
2650 	struct vcpu_svm *svm = to_svm(vcpu);
2651 
2652 	clr_exception_intercept(svm, BP_VECTOR);
2653 
2654 	if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2655 		if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2656 			set_exception_intercept(svm, BP_VECTOR);
2657 	} else
2658 		vcpu->guest_debug = 0;
2659 }
2660 
new_asid(struct vcpu_svm * svm,struct svm_cpu_data * sd)2661 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2662 {
2663 	if (sd->next_asid > sd->max_asid) {
2664 		++sd->asid_generation;
2665 		sd->next_asid = sd->min_asid;
2666 		svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2667 	}
2668 
2669 	svm->asid_generation = sd->asid_generation;
2670 	svm->vmcb->control.asid = sd->next_asid++;
2671 
2672 	mark_dirty(svm->vmcb, VMCB_ASID);
2673 }
2674 
svm_get_dr6(struct kvm_vcpu * vcpu)2675 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2676 {
2677 	return to_svm(vcpu)->vmcb->save.dr6;
2678 }
2679 
svm_set_dr6(struct kvm_vcpu * vcpu,unsigned long value)2680 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2681 {
2682 	struct vcpu_svm *svm = to_svm(vcpu);
2683 
2684 	svm->vmcb->save.dr6 = value;
2685 	mark_dirty(svm->vmcb, VMCB_DR);
2686 }
2687 
svm_sync_dirty_debug_regs(struct kvm_vcpu * vcpu)2688 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2689 {
2690 	struct vcpu_svm *svm = to_svm(vcpu);
2691 
2692 	get_debugreg(vcpu->arch.db[0], 0);
2693 	get_debugreg(vcpu->arch.db[1], 1);
2694 	get_debugreg(vcpu->arch.db[2], 2);
2695 	get_debugreg(vcpu->arch.db[3], 3);
2696 	vcpu->arch.dr6 = svm_get_dr6(vcpu);
2697 	vcpu->arch.dr7 = svm->vmcb->save.dr7;
2698 
2699 	vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2700 	set_dr_intercepts(svm);
2701 }
2702 
svm_set_dr7(struct kvm_vcpu * vcpu,unsigned long value)2703 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2704 {
2705 	struct vcpu_svm *svm = to_svm(vcpu);
2706 
2707 	svm->vmcb->save.dr7 = value;
2708 	mark_dirty(svm->vmcb, VMCB_DR);
2709 }
2710 
pf_interception(struct vcpu_svm * svm)2711 static int pf_interception(struct vcpu_svm *svm)
2712 {
2713 	u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2714 	u64 error_code = svm->vmcb->control.exit_info_1;
2715 
2716 	return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2717 			static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2718 			svm->vmcb->control.insn_bytes : NULL,
2719 			svm->vmcb->control.insn_len);
2720 }
2721 
npf_interception(struct vcpu_svm * svm)2722 static int npf_interception(struct vcpu_svm *svm)
2723 {
2724 	u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2725 	u64 error_code = svm->vmcb->control.exit_info_1;
2726 
2727 	trace_kvm_page_fault(fault_address, error_code);
2728 	return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2729 			static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2730 			svm->vmcb->control.insn_bytes : NULL,
2731 			svm->vmcb->control.insn_len);
2732 }
2733 
db_interception(struct vcpu_svm * svm)2734 static int db_interception(struct vcpu_svm *svm)
2735 {
2736 	struct kvm_run *kvm_run = svm->vcpu.run;
2737 	struct kvm_vcpu *vcpu = &svm->vcpu;
2738 
2739 	if (!(svm->vcpu.guest_debug &
2740 	      (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2741 		!svm->nmi_singlestep) {
2742 		kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2743 		return 1;
2744 	}
2745 
2746 	if (svm->nmi_singlestep) {
2747 		disable_nmi_singlestep(svm);
2748 		/* Make sure we check for pending NMIs upon entry */
2749 		kvm_make_request(KVM_REQ_EVENT, vcpu);
2750 	}
2751 
2752 	if (svm->vcpu.guest_debug &
2753 	    (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2754 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
2755 		kvm_run->debug.arch.pc =
2756 			svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2757 		kvm_run->debug.arch.exception = DB_VECTOR;
2758 		return 0;
2759 	}
2760 
2761 	return 1;
2762 }
2763 
bp_interception(struct vcpu_svm * svm)2764 static int bp_interception(struct vcpu_svm *svm)
2765 {
2766 	struct kvm_run *kvm_run = svm->vcpu.run;
2767 
2768 	kvm_run->exit_reason = KVM_EXIT_DEBUG;
2769 	kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2770 	kvm_run->debug.arch.exception = BP_VECTOR;
2771 	return 0;
2772 }
2773 
ud_interception(struct vcpu_svm * svm)2774 static int ud_interception(struct vcpu_svm *svm)
2775 {
2776 	return handle_ud(&svm->vcpu);
2777 }
2778 
ac_interception(struct vcpu_svm * svm)2779 static int ac_interception(struct vcpu_svm *svm)
2780 {
2781 	kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2782 	return 1;
2783 }
2784 
gp_interception(struct vcpu_svm * svm)2785 static int gp_interception(struct vcpu_svm *svm)
2786 {
2787 	struct kvm_vcpu *vcpu = &svm->vcpu;
2788 	u32 error_code = svm->vmcb->control.exit_info_1;
2789 	int er;
2790 
2791 	WARN_ON_ONCE(!enable_vmware_backdoor);
2792 
2793 	er = kvm_emulate_instruction(vcpu,
2794 		EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
2795 	if (er == EMULATE_USER_EXIT)
2796 		return 0;
2797 	else if (er != EMULATE_DONE)
2798 		kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2799 	return 1;
2800 }
2801 
is_erratum_383(void)2802 static bool is_erratum_383(void)
2803 {
2804 	int err, i;
2805 	u64 value;
2806 
2807 	if (!erratum_383_found)
2808 		return false;
2809 
2810 	value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2811 	if (err)
2812 		return false;
2813 
2814 	/* Bit 62 may or may not be set for this mce */
2815 	value &= ~(1ULL << 62);
2816 
2817 	if (value != 0xb600000000010015ULL)
2818 		return false;
2819 
2820 	/* Clear MCi_STATUS registers */
2821 	for (i = 0; i < 6; ++i)
2822 		native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2823 
2824 	value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2825 	if (!err) {
2826 		u32 low, high;
2827 
2828 		value &= ~(1ULL << 2);
2829 		low    = lower_32_bits(value);
2830 		high   = upper_32_bits(value);
2831 
2832 		native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2833 	}
2834 
2835 	/* Flush tlb to evict multi-match entries */
2836 	__flush_tlb_all();
2837 
2838 	return true;
2839 }
2840 
svm_handle_mce(struct vcpu_svm * svm)2841 static void svm_handle_mce(struct vcpu_svm *svm)
2842 {
2843 	if (is_erratum_383()) {
2844 		/*
2845 		 * Erratum 383 triggered. Guest state is corrupt so kill the
2846 		 * guest.
2847 		 */
2848 		pr_err("KVM: Guest triggered AMD Erratum 383\n");
2849 
2850 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2851 
2852 		return;
2853 	}
2854 
2855 	/*
2856 	 * On an #MC intercept the MCE handler is not called automatically in
2857 	 * the host. So do it by hand here.
2858 	 */
2859 	asm volatile (
2860 		"int $0x12\n");
2861 	/* not sure if we ever come back to this point */
2862 
2863 	return;
2864 }
2865 
mc_interception(struct vcpu_svm * svm)2866 static int mc_interception(struct vcpu_svm *svm)
2867 {
2868 	return 1;
2869 }
2870 
shutdown_interception(struct vcpu_svm * svm)2871 static int shutdown_interception(struct vcpu_svm *svm)
2872 {
2873 	struct kvm_run *kvm_run = svm->vcpu.run;
2874 
2875 	/*
2876 	 * VMCB is undefined after a SHUTDOWN intercept
2877 	 * so reinitialize it.
2878 	 */
2879 	clear_page(svm->vmcb);
2880 	init_vmcb(svm);
2881 
2882 	kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2883 	return 0;
2884 }
2885 
io_interception(struct vcpu_svm * svm)2886 static int io_interception(struct vcpu_svm *svm)
2887 {
2888 	struct kvm_vcpu *vcpu = &svm->vcpu;
2889 	u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2890 	int size, in, string;
2891 	unsigned port;
2892 
2893 	++svm->vcpu.stat.io_exits;
2894 	string = (io_info & SVM_IOIO_STR_MASK) != 0;
2895 	in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2896 	if (string)
2897 		return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
2898 
2899 	port = io_info >> 16;
2900 	size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2901 	svm->next_rip = svm->vmcb->control.exit_info_2;
2902 
2903 	return kvm_fast_pio(&svm->vcpu, size, port, in);
2904 }
2905 
nmi_interception(struct vcpu_svm * svm)2906 static int nmi_interception(struct vcpu_svm *svm)
2907 {
2908 	return 1;
2909 }
2910 
intr_interception(struct vcpu_svm * svm)2911 static int intr_interception(struct vcpu_svm *svm)
2912 {
2913 	++svm->vcpu.stat.irq_exits;
2914 	return 1;
2915 }
2916 
nop_on_interception(struct vcpu_svm * svm)2917 static int nop_on_interception(struct vcpu_svm *svm)
2918 {
2919 	return 1;
2920 }
2921 
halt_interception(struct vcpu_svm * svm)2922 static int halt_interception(struct vcpu_svm *svm)
2923 {
2924 	svm->next_rip = kvm_rip_read(&svm->vcpu) + 1;
2925 	return kvm_emulate_halt(&svm->vcpu);
2926 }
2927 
vmmcall_interception(struct vcpu_svm * svm)2928 static int vmmcall_interception(struct vcpu_svm *svm)
2929 {
2930 	svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2931 	return kvm_emulate_hypercall(&svm->vcpu);
2932 }
2933 
nested_svm_get_tdp_cr3(struct kvm_vcpu * vcpu)2934 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2935 {
2936 	struct vcpu_svm *svm = to_svm(vcpu);
2937 
2938 	return svm->nested.nested_cr3;
2939 }
2940 
nested_svm_get_tdp_pdptr(struct kvm_vcpu * vcpu,int index)2941 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2942 {
2943 	struct vcpu_svm *svm = to_svm(vcpu);
2944 	u64 cr3 = svm->nested.nested_cr3;
2945 	u64 pdpte;
2946 	int ret;
2947 
2948 	ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2949 				       offset_in_page(cr3) + index * 8, 8);
2950 	if (ret)
2951 		return 0;
2952 	return pdpte;
2953 }
2954 
nested_svm_set_tdp_cr3(struct kvm_vcpu * vcpu,unsigned long root)2955 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2956 				   unsigned long root)
2957 {
2958 	struct vcpu_svm *svm = to_svm(vcpu);
2959 
2960 	svm->vmcb->control.nested_cr3 = __sme_set(root);
2961 	mark_dirty(svm->vmcb, VMCB_NPT);
2962 }
2963 
nested_svm_inject_npf_exit(struct kvm_vcpu * vcpu,struct x86_exception * fault)2964 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2965 				       struct x86_exception *fault)
2966 {
2967 	struct vcpu_svm *svm = to_svm(vcpu);
2968 
2969 	if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
2970 		/*
2971 		 * TODO: track the cause of the nested page fault, and
2972 		 * correctly fill in the high bits of exit_info_1.
2973 		 */
2974 		svm->vmcb->control.exit_code = SVM_EXIT_NPF;
2975 		svm->vmcb->control.exit_code_hi = 0;
2976 		svm->vmcb->control.exit_info_1 = (1ULL << 32);
2977 		svm->vmcb->control.exit_info_2 = fault->address;
2978 	}
2979 
2980 	svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
2981 	svm->vmcb->control.exit_info_1 |= fault->error_code;
2982 
2983 	/*
2984 	 * The present bit is always zero for page structure faults on real
2985 	 * hardware.
2986 	 */
2987 	if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
2988 		svm->vmcb->control.exit_info_1 &= ~1;
2989 
2990 	nested_svm_vmexit(svm);
2991 }
2992 
nested_svm_init_mmu_context(struct kvm_vcpu * vcpu)2993 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
2994 {
2995 	WARN_ON(mmu_is_nested(vcpu));
2996 	kvm_init_shadow_mmu(vcpu);
2997 	vcpu->arch.mmu.set_cr3           = nested_svm_set_tdp_cr3;
2998 	vcpu->arch.mmu.get_cr3           = nested_svm_get_tdp_cr3;
2999 	vcpu->arch.mmu.get_pdptr         = nested_svm_get_tdp_pdptr;
3000 	vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit;
3001 	vcpu->arch.mmu.shadow_root_level = get_npt_level(vcpu);
3002 	reset_shadow_zero_bits_mask(vcpu, &vcpu->arch.mmu);
3003 	vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
3004 }
3005 
nested_svm_uninit_mmu_context(struct kvm_vcpu * vcpu)3006 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
3007 {
3008 	vcpu->arch.walk_mmu = &vcpu->arch.mmu;
3009 }
3010 
nested_svm_check_permissions(struct vcpu_svm * svm)3011 static int nested_svm_check_permissions(struct vcpu_svm *svm)
3012 {
3013 	if (!(svm->vcpu.arch.efer & EFER_SVME) ||
3014 	    !is_paging(&svm->vcpu)) {
3015 		kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3016 		return 1;
3017 	}
3018 
3019 	if (svm->vmcb->save.cpl) {
3020 		kvm_inject_gp(&svm->vcpu, 0);
3021 		return 1;
3022 	}
3023 
3024 	return 0;
3025 }
3026 
nested_svm_check_exception(struct vcpu_svm * svm,unsigned nr,bool has_error_code,u32 error_code)3027 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
3028 				      bool has_error_code, u32 error_code)
3029 {
3030 	int vmexit;
3031 
3032 	if (!is_guest_mode(&svm->vcpu))
3033 		return 0;
3034 
3035 	vmexit = nested_svm_intercept(svm);
3036 	if (vmexit != NESTED_EXIT_DONE)
3037 		return 0;
3038 
3039 	svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
3040 	svm->vmcb->control.exit_code_hi = 0;
3041 	svm->vmcb->control.exit_info_1 = error_code;
3042 
3043 	/*
3044 	 * FIXME: we should not write CR2 when L1 intercepts an L2 #PF exception.
3045 	 * The fix is to add the ancillary datum (CR2 or DR6) to structs
3046 	 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6 can be
3047 	 * written only when inject_pending_event runs (DR6 would written here
3048 	 * too).  This should be conditional on a new capability---if the
3049 	 * capability is disabled, kvm_multiple_exception would write the
3050 	 * ancillary information to CR2 or DR6, for backwards ABI-compatibility.
3051 	 */
3052 	if (svm->vcpu.arch.exception.nested_apf)
3053 		svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
3054 	else
3055 		svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
3056 
3057 	svm->nested.exit_required = true;
3058 	return vmexit;
3059 }
3060 
3061 /* This function returns true if it is save to enable the irq window */
nested_svm_intr(struct vcpu_svm * svm)3062 static inline bool nested_svm_intr(struct vcpu_svm *svm)
3063 {
3064 	if (!is_guest_mode(&svm->vcpu))
3065 		return true;
3066 
3067 	if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3068 		return true;
3069 
3070 	if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
3071 		return false;
3072 
3073 	/*
3074 	 * if vmexit was already requested (by intercepted exception
3075 	 * for instance) do not overwrite it with "external interrupt"
3076 	 * vmexit.
3077 	 */
3078 	if (svm->nested.exit_required)
3079 		return false;
3080 
3081 	svm->vmcb->control.exit_code   = SVM_EXIT_INTR;
3082 	svm->vmcb->control.exit_info_1 = 0;
3083 	svm->vmcb->control.exit_info_2 = 0;
3084 
3085 	if (svm->nested.intercept & 1ULL) {
3086 		/*
3087 		 * The #vmexit can't be emulated here directly because this
3088 		 * code path runs with irqs and preemption disabled. A
3089 		 * #vmexit emulation might sleep. Only signal request for
3090 		 * the #vmexit here.
3091 		 */
3092 		svm->nested.exit_required = true;
3093 		trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
3094 		return false;
3095 	}
3096 
3097 	return true;
3098 }
3099 
3100 /* This function returns true if it is save to enable the nmi window */
nested_svm_nmi(struct vcpu_svm * svm)3101 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
3102 {
3103 	if (!is_guest_mode(&svm->vcpu))
3104 		return true;
3105 
3106 	if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
3107 		return true;
3108 
3109 	svm->vmcb->control.exit_code = SVM_EXIT_NMI;
3110 	svm->nested.exit_required = true;
3111 
3112 	return false;
3113 }
3114 
nested_svm_map(struct vcpu_svm * svm,u64 gpa,struct page ** _page)3115 static void *nested_svm_map(struct vcpu_svm *svm, u64 gpa, struct page **_page)
3116 {
3117 	struct page *page;
3118 
3119 	might_sleep();
3120 
3121 	page = kvm_vcpu_gfn_to_page(&svm->vcpu, gpa >> PAGE_SHIFT);
3122 	if (is_error_page(page))
3123 		goto error;
3124 
3125 	*_page = page;
3126 
3127 	return kmap(page);
3128 
3129 error:
3130 	kvm_inject_gp(&svm->vcpu, 0);
3131 
3132 	return NULL;
3133 }
3134 
nested_svm_unmap(struct page * page)3135 static void nested_svm_unmap(struct page *page)
3136 {
3137 	kunmap(page);
3138 	kvm_release_page_dirty(page);
3139 }
3140 
nested_svm_intercept_ioio(struct vcpu_svm * svm)3141 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
3142 {
3143 	unsigned port, size, iopm_len;
3144 	u16 val, mask;
3145 	u8 start_bit;
3146 	u64 gpa;
3147 
3148 	if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
3149 		return NESTED_EXIT_HOST;
3150 
3151 	port = svm->vmcb->control.exit_info_1 >> 16;
3152 	size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
3153 		SVM_IOIO_SIZE_SHIFT;
3154 	gpa  = svm->nested.vmcb_iopm + (port / 8);
3155 	start_bit = port % 8;
3156 	iopm_len = (start_bit + size > 8) ? 2 : 1;
3157 	mask = (0xf >> (4 - size)) << start_bit;
3158 	val = 0;
3159 
3160 	if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
3161 		return NESTED_EXIT_DONE;
3162 
3163 	return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3164 }
3165 
nested_svm_exit_handled_msr(struct vcpu_svm * svm)3166 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
3167 {
3168 	u32 offset, msr, value;
3169 	int write, mask;
3170 
3171 	if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3172 		return NESTED_EXIT_HOST;
3173 
3174 	msr    = svm->vcpu.arch.regs[VCPU_REGS_RCX];
3175 	offset = svm_msrpm_offset(msr);
3176 	write  = svm->vmcb->control.exit_info_1 & 1;
3177 	mask   = 1 << ((2 * (msr & 0xf)) + write);
3178 
3179 	if (offset == MSR_INVALID)
3180 		return NESTED_EXIT_DONE;
3181 
3182 	/* Offset is in 32 bit units but need in 8 bit units */
3183 	offset *= 4;
3184 
3185 	if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
3186 		return NESTED_EXIT_DONE;
3187 
3188 	return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3189 }
3190 
3191 /* DB exceptions for our internal use must not cause vmexit */
nested_svm_intercept_db(struct vcpu_svm * svm)3192 static int nested_svm_intercept_db(struct vcpu_svm *svm)
3193 {
3194 	unsigned long dr6;
3195 
3196 	/* if we're not singlestepping, it's not ours */
3197 	if (!svm->nmi_singlestep)
3198 		return NESTED_EXIT_DONE;
3199 
3200 	/* if it's not a singlestep exception, it's not ours */
3201 	if (kvm_get_dr(&svm->vcpu, 6, &dr6))
3202 		return NESTED_EXIT_DONE;
3203 	if (!(dr6 & DR6_BS))
3204 		return NESTED_EXIT_DONE;
3205 
3206 	/* if the guest is singlestepping, it should get the vmexit */
3207 	if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
3208 		disable_nmi_singlestep(svm);
3209 		return NESTED_EXIT_DONE;
3210 	}
3211 
3212 	/* it's ours, the nested hypervisor must not see this one */
3213 	return NESTED_EXIT_HOST;
3214 }
3215 
nested_svm_exit_special(struct vcpu_svm * svm)3216 static int nested_svm_exit_special(struct vcpu_svm *svm)
3217 {
3218 	u32 exit_code = svm->vmcb->control.exit_code;
3219 
3220 	switch (exit_code) {
3221 	case SVM_EXIT_INTR:
3222 	case SVM_EXIT_NMI:
3223 	case SVM_EXIT_EXCP_BASE + MC_VECTOR:
3224 		return NESTED_EXIT_HOST;
3225 	case SVM_EXIT_NPF:
3226 		/* For now we are always handling NPFs when using them */
3227 		if (npt_enabled)
3228 			return NESTED_EXIT_HOST;
3229 		break;
3230 	case SVM_EXIT_EXCP_BASE + PF_VECTOR:
3231 		/* Trap async PF even if not shadowing */
3232 		if (!npt_enabled || svm->vcpu.arch.apf.host_apf_reason)
3233 			return NESTED_EXIT_HOST;
3234 		break;
3235 	default:
3236 		break;
3237 	}
3238 
3239 	return NESTED_EXIT_CONTINUE;
3240 }
3241 
3242 /*
3243  * If this function returns true, this #vmexit was already handled
3244  */
nested_svm_intercept(struct vcpu_svm * svm)3245 static int nested_svm_intercept(struct vcpu_svm *svm)
3246 {
3247 	u32 exit_code = svm->vmcb->control.exit_code;
3248 	int vmexit = NESTED_EXIT_HOST;
3249 
3250 	switch (exit_code) {
3251 	case SVM_EXIT_MSR:
3252 		vmexit = nested_svm_exit_handled_msr(svm);
3253 		break;
3254 	case SVM_EXIT_IOIO:
3255 		vmexit = nested_svm_intercept_ioio(svm);
3256 		break;
3257 	case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3258 		u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3259 		if (svm->nested.intercept_cr & bit)
3260 			vmexit = NESTED_EXIT_DONE;
3261 		break;
3262 	}
3263 	case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3264 		u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3265 		if (svm->nested.intercept_dr & bit)
3266 			vmexit = NESTED_EXIT_DONE;
3267 		break;
3268 	}
3269 	case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3270 		u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3271 		if (svm->nested.intercept_exceptions & excp_bits) {
3272 			if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3273 				vmexit = nested_svm_intercept_db(svm);
3274 			else
3275 				vmexit = NESTED_EXIT_DONE;
3276 		}
3277 		/* async page fault always cause vmexit */
3278 		else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3279 			 svm->vcpu.arch.exception.nested_apf != 0)
3280 			vmexit = NESTED_EXIT_DONE;
3281 		break;
3282 	}
3283 	case SVM_EXIT_ERR: {
3284 		vmexit = NESTED_EXIT_DONE;
3285 		break;
3286 	}
3287 	default: {
3288 		u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3289 		if (svm->nested.intercept & exit_bits)
3290 			vmexit = NESTED_EXIT_DONE;
3291 	}
3292 	}
3293 
3294 	return vmexit;
3295 }
3296 
nested_svm_exit_handled(struct vcpu_svm * svm)3297 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3298 {
3299 	int vmexit;
3300 
3301 	vmexit = nested_svm_intercept(svm);
3302 
3303 	if (vmexit == NESTED_EXIT_DONE)
3304 		nested_svm_vmexit(svm);
3305 
3306 	return vmexit;
3307 }
3308 
copy_vmcb_control_area(struct vmcb * dst_vmcb,struct vmcb * from_vmcb)3309 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3310 {
3311 	struct vmcb_control_area *dst  = &dst_vmcb->control;
3312 	struct vmcb_control_area *from = &from_vmcb->control;
3313 
3314 	dst->intercept_cr         = from->intercept_cr;
3315 	dst->intercept_dr         = from->intercept_dr;
3316 	dst->intercept_exceptions = from->intercept_exceptions;
3317 	dst->intercept            = from->intercept;
3318 	dst->iopm_base_pa         = from->iopm_base_pa;
3319 	dst->msrpm_base_pa        = from->msrpm_base_pa;
3320 	dst->tsc_offset           = from->tsc_offset;
3321 	/* asid not copied, it is handled manually for svm->vmcb.  */
3322 	dst->tlb_ctl              = from->tlb_ctl;
3323 	dst->int_ctl              = from->int_ctl;
3324 	dst->int_vector           = from->int_vector;
3325 	dst->int_state            = from->int_state;
3326 	dst->exit_code            = from->exit_code;
3327 	dst->exit_code_hi         = from->exit_code_hi;
3328 	dst->exit_info_1          = from->exit_info_1;
3329 	dst->exit_info_2          = from->exit_info_2;
3330 	dst->exit_int_info        = from->exit_int_info;
3331 	dst->exit_int_info_err    = from->exit_int_info_err;
3332 	dst->nested_ctl           = from->nested_ctl;
3333 	dst->event_inj            = from->event_inj;
3334 	dst->event_inj_err        = from->event_inj_err;
3335 	dst->nested_cr3           = from->nested_cr3;
3336 	dst->virt_ext              = from->virt_ext;
3337 }
3338 
nested_svm_vmexit(struct vcpu_svm * svm)3339 static int nested_svm_vmexit(struct vcpu_svm *svm)
3340 {
3341 	struct vmcb *nested_vmcb;
3342 	struct vmcb *hsave = svm->nested.hsave;
3343 	struct vmcb *vmcb = svm->vmcb;
3344 	struct page *page;
3345 
3346 	trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3347 				       vmcb->control.exit_info_1,
3348 				       vmcb->control.exit_info_2,
3349 				       vmcb->control.exit_int_info,
3350 				       vmcb->control.exit_int_info_err,
3351 				       KVM_ISA_SVM);
3352 
3353 	nested_vmcb = nested_svm_map(svm, svm->nested.vmcb, &page);
3354 	if (!nested_vmcb)
3355 		return 1;
3356 
3357 	/* Exit Guest-Mode */
3358 	leave_guest_mode(&svm->vcpu);
3359 	svm->nested.vmcb = 0;
3360 
3361 	/* Give the current vmcb to the guest */
3362 	disable_gif(svm);
3363 
3364 	nested_vmcb->save.es     = vmcb->save.es;
3365 	nested_vmcb->save.cs     = vmcb->save.cs;
3366 	nested_vmcb->save.ss     = vmcb->save.ss;
3367 	nested_vmcb->save.ds     = vmcb->save.ds;
3368 	nested_vmcb->save.gdtr   = vmcb->save.gdtr;
3369 	nested_vmcb->save.idtr   = vmcb->save.idtr;
3370 	nested_vmcb->save.efer   = svm->vcpu.arch.efer;
3371 	nested_vmcb->save.cr0    = kvm_read_cr0(&svm->vcpu);
3372 	nested_vmcb->save.cr3    = kvm_read_cr3(&svm->vcpu);
3373 	nested_vmcb->save.cr2    = vmcb->save.cr2;
3374 	nested_vmcb->save.cr4    = svm->vcpu.arch.cr4;
3375 	nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3376 	nested_vmcb->save.rip    = vmcb->save.rip;
3377 	nested_vmcb->save.rsp    = vmcb->save.rsp;
3378 	nested_vmcb->save.rax    = vmcb->save.rax;
3379 	nested_vmcb->save.dr7    = vmcb->save.dr7;
3380 	nested_vmcb->save.dr6    = vmcb->save.dr6;
3381 	nested_vmcb->save.cpl    = vmcb->save.cpl;
3382 
3383 	nested_vmcb->control.int_ctl           = vmcb->control.int_ctl;
3384 	nested_vmcb->control.int_vector        = vmcb->control.int_vector;
3385 	nested_vmcb->control.int_state         = vmcb->control.int_state;
3386 	nested_vmcb->control.exit_code         = vmcb->control.exit_code;
3387 	nested_vmcb->control.exit_code_hi      = vmcb->control.exit_code_hi;
3388 	nested_vmcb->control.exit_info_1       = vmcb->control.exit_info_1;
3389 	nested_vmcb->control.exit_info_2       = vmcb->control.exit_info_2;
3390 	nested_vmcb->control.exit_int_info     = vmcb->control.exit_int_info;
3391 	nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3392 
3393 	if (svm->nrips_enabled)
3394 		nested_vmcb->control.next_rip  = vmcb->control.next_rip;
3395 
3396 	/*
3397 	 * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3398 	 * to make sure that we do not lose injected events. So check event_inj
3399 	 * here and copy it to exit_int_info if it is valid.
3400 	 * Exit_int_info and event_inj can't be both valid because the case
3401 	 * below only happens on a VMRUN instruction intercept which has
3402 	 * no valid exit_int_info set.
3403 	 */
3404 	if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3405 		struct vmcb_control_area *nc = &nested_vmcb->control;
3406 
3407 		nc->exit_int_info     = vmcb->control.event_inj;
3408 		nc->exit_int_info_err = vmcb->control.event_inj_err;
3409 	}
3410 
3411 	nested_vmcb->control.tlb_ctl           = 0;
3412 	nested_vmcb->control.event_inj         = 0;
3413 	nested_vmcb->control.event_inj_err     = 0;
3414 
3415 	/* We always set V_INTR_MASKING and remember the old value in hflags */
3416 	if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3417 		nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3418 
3419 	/* Restore the original control entries */
3420 	copy_vmcb_control_area(vmcb, hsave);
3421 
3422 	svm->vcpu.arch.tsc_offset = svm->vmcb->control.tsc_offset;
3423 	kvm_clear_exception_queue(&svm->vcpu);
3424 	kvm_clear_interrupt_queue(&svm->vcpu);
3425 
3426 	svm->nested.nested_cr3 = 0;
3427 
3428 	/* Restore selected save entries */
3429 	svm->vmcb->save.es = hsave->save.es;
3430 	svm->vmcb->save.cs = hsave->save.cs;
3431 	svm->vmcb->save.ss = hsave->save.ss;
3432 	svm->vmcb->save.ds = hsave->save.ds;
3433 	svm->vmcb->save.gdtr = hsave->save.gdtr;
3434 	svm->vmcb->save.idtr = hsave->save.idtr;
3435 	kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3436 	svm_set_efer(&svm->vcpu, hsave->save.efer);
3437 	svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3438 	svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3439 	if (npt_enabled) {
3440 		svm->vmcb->save.cr3 = hsave->save.cr3;
3441 		svm->vcpu.arch.cr3 = hsave->save.cr3;
3442 	} else {
3443 		(void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3444 	}
3445 	kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, hsave->save.rax);
3446 	kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, hsave->save.rsp);
3447 	kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, hsave->save.rip);
3448 	svm->vmcb->save.dr7 = 0;
3449 	svm->vmcb->save.cpl = 0;
3450 	svm->vmcb->control.exit_int_info = 0;
3451 
3452 	mark_all_dirty(svm->vmcb);
3453 
3454 	nested_svm_unmap(page);
3455 
3456 	nested_svm_uninit_mmu_context(&svm->vcpu);
3457 	kvm_mmu_reset_context(&svm->vcpu);
3458 	kvm_mmu_load(&svm->vcpu);
3459 
3460 	/*
3461 	 * Drop what we picked up for L2 via svm_complete_interrupts() so it
3462 	 * doesn't end up in L1.
3463 	 */
3464 	svm->vcpu.arch.nmi_injected = false;
3465 	kvm_clear_exception_queue(&svm->vcpu);
3466 	kvm_clear_interrupt_queue(&svm->vcpu);
3467 
3468 	return 0;
3469 }
3470 
nested_svm_vmrun_msrpm(struct vcpu_svm * svm)3471 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3472 {
3473 	/*
3474 	 * This function merges the msr permission bitmaps of kvm and the
3475 	 * nested vmcb. It is optimized in that it only merges the parts where
3476 	 * the kvm msr permission bitmap may contain zero bits
3477 	 */
3478 	int i;
3479 
3480 	if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3481 		return true;
3482 
3483 	for (i = 0; i < MSRPM_OFFSETS; i++) {
3484 		u32 value, p;
3485 		u64 offset;
3486 
3487 		if (msrpm_offsets[i] == 0xffffffff)
3488 			break;
3489 
3490 		p      = msrpm_offsets[i];
3491 		offset = svm->nested.vmcb_msrpm + (p * 4);
3492 
3493 		if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3494 			return false;
3495 
3496 		svm->nested.msrpm[p] = svm->msrpm[p] | value;
3497 	}
3498 
3499 	svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3500 
3501 	return true;
3502 }
3503 
nested_vmcb_checks(struct vmcb * vmcb)3504 static bool nested_vmcb_checks(struct vmcb *vmcb)
3505 {
3506 	if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3507 		return false;
3508 
3509 	if (vmcb->control.asid == 0)
3510 		return false;
3511 
3512 	if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3513 	    !npt_enabled)
3514 		return false;
3515 
3516 	return true;
3517 }
3518 
enter_svm_guest_mode(struct vcpu_svm * svm,u64 vmcb_gpa,struct vmcb * nested_vmcb,struct page * page)3519 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3520 				 struct vmcb *nested_vmcb, struct page *page)
3521 {
3522 	if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3523 		svm->vcpu.arch.hflags |= HF_HIF_MASK;
3524 	else
3525 		svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3526 
3527 	if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3528 		kvm_mmu_unload(&svm->vcpu);
3529 		svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3530 		nested_svm_init_mmu_context(&svm->vcpu);
3531 	}
3532 
3533 	/* Load the nested guest state */
3534 	svm->vmcb->save.es = nested_vmcb->save.es;
3535 	svm->vmcb->save.cs = nested_vmcb->save.cs;
3536 	svm->vmcb->save.ss = nested_vmcb->save.ss;
3537 	svm->vmcb->save.ds = nested_vmcb->save.ds;
3538 	svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3539 	svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3540 	kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3541 	svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3542 	svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3543 	svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3544 	if (npt_enabled) {
3545 		svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3546 		svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3547 	} else
3548 		(void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3549 
3550 	/* Guest paging mode is active - reset mmu */
3551 	kvm_mmu_reset_context(&svm->vcpu);
3552 
3553 	svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3554 	kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, nested_vmcb->save.rax);
3555 	kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, nested_vmcb->save.rsp);
3556 	kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, nested_vmcb->save.rip);
3557 
3558 	/* In case we don't even reach vcpu_run, the fields are not updated */
3559 	svm->vmcb->save.rax = nested_vmcb->save.rax;
3560 	svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3561 	svm->vmcb->save.rip = nested_vmcb->save.rip;
3562 	svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3563 	svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3564 	svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3565 
3566 	svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3567 	svm->nested.vmcb_iopm  = nested_vmcb->control.iopm_base_pa  & ~0x0fffULL;
3568 
3569 	/* cache intercepts */
3570 	svm->nested.intercept_cr         = nested_vmcb->control.intercept_cr;
3571 	svm->nested.intercept_dr         = nested_vmcb->control.intercept_dr;
3572 	svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3573 	svm->nested.intercept            = nested_vmcb->control.intercept;
3574 
3575 	svm_flush_tlb(&svm->vcpu, true);
3576 
3577 	svm->vmcb->control.int_ctl &=
3578 			V_INTR_MASKING_MASK | V_GIF_ENABLE_MASK | V_GIF_MASK;
3579 
3580 	svm->vmcb->control.int_ctl |= nested_vmcb->control.int_ctl &
3581 			(V_TPR_MASK | V_IRQ_INJECTION_BITS_MASK);
3582 
3583 	if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3584 		svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3585 	else
3586 		svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3587 
3588 	if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3589 		/* We only want the cr8 intercept bits of the guest */
3590 		clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3591 		clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3592 	}
3593 
3594 	/* We don't want to see VMMCALLs from a nested guest */
3595 	clr_intercept(svm, INTERCEPT_VMMCALL);
3596 
3597 	svm->vcpu.arch.tsc_offset += nested_vmcb->control.tsc_offset;
3598 	svm->vmcb->control.tsc_offset = svm->vcpu.arch.tsc_offset;
3599 
3600 	svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3601 	svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3602 	svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3603 	svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3604 	svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3605 
3606 	nested_svm_unmap(page);
3607 
3608 	/* Enter Guest-Mode */
3609 	enter_guest_mode(&svm->vcpu);
3610 
3611 	/*
3612 	 * Merge guest and host intercepts - must be called  with vcpu in
3613 	 * guest-mode to take affect here
3614 	 */
3615 	recalc_intercepts(svm);
3616 
3617 	svm->nested.vmcb = vmcb_gpa;
3618 
3619 	enable_gif(svm);
3620 
3621 	mark_all_dirty(svm->vmcb);
3622 }
3623 
nested_svm_vmrun(struct vcpu_svm * svm)3624 static bool nested_svm_vmrun(struct vcpu_svm *svm)
3625 {
3626 	struct vmcb *nested_vmcb;
3627 	struct vmcb *hsave = svm->nested.hsave;
3628 	struct vmcb *vmcb = svm->vmcb;
3629 	struct page *page;
3630 	u64 vmcb_gpa;
3631 
3632 	vmcb_gpa = svm->vmcb->save.rax;
3633 
3634 	nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3635 	if (!nested_vmcb)
3636 		return false;
3637 
3638 	if (!nested_vmcb_checks(nested_vmcb)) {
3639 		nested_vmcb->control.exit_code    = SVM_EXIT_ERR;
3640 		nested_vmcb->control.exit_code_hi = 0;
3641 		nested_vmcb->control.exit_info_1  = 0;
3642 		nested_vmcb->control.exit_info_2  = 0;
3643 
3644 		nested_svm_unmap(page);
3645 
3646 		return false;
3647 	}
3648 
3649 	trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3650 			       nested_vmcb->save.rip,
3651 			       nested_vmcb->control.int_ctl,
3652 			       nested_vmcb->control.event_inj,
3653 			       nested_vmcb->control.nested_ctl);
3654 
3655 	trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3656 				    nested_vmcb->control.intercept_cr >> 16,
3657 				    nested_vmcb->control.intercept_exceptions,
3658 				    nested_vmcb->control.intercept);
3659 
3660 	/* Clear internal status */
3661 	kvm_clear_exception_queue(&svm->vcpu);
3662 	kvm_clear_interrupt_queue(&svm->vcpu);
3663 
3664 	/*
3665 	 * Save the old vmcb, so we don't need to pick what we save, but can
3666 	 * restore everything when a VMEXIT occurs
3667 	 */
3668 	hsave->save.es     = vmcb->save.es;
3669 	hsave->save.cs     = vmcb->save.cs;
3670 	hsave->save.ss     = vmcb->save.ss;
3671 	hsave->save.ds     = vmcb->save.ds;
3672 	hsave->save.gdtr   = vmcb->save.gdtr;
3673 	hsave->save.idtr   = vmcb->save.idtr;
3674 	hsave->save.efer   = svm->vcpu.arch.efer;
3675 	hsave->save.cr0    = kvm_read_cr0(&svm->vcpu);
3676 	hsave->save.cr4    = svm->vcpu.arch.cr4;
3677 	hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3678 	hsave->save.rip    = kvm_rip_read(&svm->vcpu);
3679 	hsave->save.rsp    = vmcb->save.rsp;
3680 	hsave->save.rax    = vmcb->save.rax;
3681 	if (npt_enabled)
3682 		hsave->save.cr3    = vmcb->save.cr3;
3683 	else
3684 		hsave->save.cr3    = kvm_read_cr3(&svm->vcpu);
3685 
3686 	copy_vmcb_control_area(hsave, vmcb);
3687 
3688 	enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, page);
3689 
3690 	return true;
3691 }
3692 
nested_svm_vmloadsave(struct vmcb * from_vmcb,struct vmcb * to_vmcb)3693 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3694 {
3695 	to_vmcb->save.fs = from_vmcb->save.fs;
3696 	to_vmcb->save.gs = from_vmcb->save.gs;
3697 	to_vmcb->save.tr = from_vmcb->save.tr;
3698 	to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3699 	to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3700 	to_vmcb->save.star = from_vmcb->save.star;
3701 	to_vmcb->save.lstar = from_vmcb->save.lstar;
3702 	to_vmcb->save.cstar = from_vmcb->save.cstar;
3703 	to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3704 	to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3705 	to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3706 	to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3707 }
3708 
vmload_interception(struct vcpu_svm * svm)3709 static int vmload_interception(struct vcpu_svm *svm)
3710 {
3711 	struct vmcb *nested_vmcb;
3712 	struct page *page;
3713 	int ret;
3714 
3715 	if (nested_svm_check_permissions(svm))
3716 		return 1;
3717 
3718 	nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3719 	if (!nested_vmcb)
3720 		return 1;
3721 
3722 	svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3723 	ret = kvm_skip_emulated_instruction(&svm->vcpu);
3724 
3725 	nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3726 	nested_svm_unmap(page);
3727 
3728 	return ret;
3729 }
3730 
vmsave_interception(struct vcpu_svm * svm)3731 static int vmsave_interception(struct vcpu_svm *svm)
3732 {
3733 	struct vmcb *nested_vmcb;
3734 	struct page *page;
3735 	int ret;
3736 
3737 	if (nested_svm_check_permissions(svm))
3738 		return 1;
3739 
3740 	nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3741 	if (!nested_vmcb)
3742 		return 1;
3743 
3744 	svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3745 	ret = kvm_skip_emulated_instruction(&svm->vcpu);
3746 
3747 	nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3748 	nested_svm_unmap(page);
3749 
3750 	return ret;
3751 }
3752 
vmrun_interception(struct vcpu_svm * svm)3753 static int vmrun_interception(struct vcpu_svm *svm)
3754 {
3755 	if (nested_svm_check_permissions(svm))
3756 		return 1;
3757 
3758 	/* Save rip after vmrun instruction */
3759 	kvm_rip_write(&svm->vcpu, kvm_rip_read(&svm->vcpu) + 3);
3760 
3761 	if (!nested_svm_vmrun(svm))
3762 		return 1;
3763 
3764 	if (!nested_svm_vmrun_msrpm(svm))
3765 		goto failed;
3766 
3767 	return 1;
3768 
3769 failed:
3770 
3771 	svm->vmcb->control.exit_code    = SVM_EXIT_ERR;
3772 	svm->vmcb->control.exit_code_hi = 0;
3773 	svm->vmcb->control.exit_info_1  = 0;
3774 	svm->vmcb->control.exit_info_2  = 0;
3775 
3776 	nested_svm_vmexit(svm);
3777 
3778 	return 1;
3779 }
3780 
stgi_interception(struct vcpu_svm * svm)3781 static int stgi_interception(struct vcpu_svm *svm)
3782 {
3783 	int ret;
3784 
3785 	if (nested_svm_check_permissions(svm))
3786 		return 1;
3787 
3788 	/*
3789 	 * If VGIF is enabled, the STGI intercept is only added to
3790 	 * detect the opening of the SMI/NMI window; remove it now.
3791 	 */
3792 	if (vgif_enabled(svm))
3793 		clr_intercept(svm, INTERCEPT_STGI);
3794 
3795 	svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3796 	ret = kvm_skip_emulated_instruction(&svm->vcpu);
3797 	kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3798 
3799 	enable_gif(svm);
3800 
3801 	return ret;
3802 }
3803 
clgi_interception(struct vcpu_svm * svm)3804 static int clgi_interception(struct vcpu_svm *svm)
3805 {
3806 	int ret;
3807 
3808 	if (nested_svm_check_permissions(svm))
3809 		return 1;
3810 
3811 	svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3812 	ret = kvm_skip_emulated_instruction(&svm->vcpu);
3813 
3814 	disable_gif(svm);
3815 
3816 	/* After a CLGI no interrupts should come */
3817 	if (!kvm_vcpu_apicv_active(&svm->vcpu)) {
3818 		svm_clear_vintr(svm);
3819 		svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3820 		mark_dirty(svm->vmcb, VMCB_INTR);
3821 	}
3822 
3823 	return ret;
3824 }
3825 
invlpga_interception(struct vcpu_svm * svm)3826 static int invlpga_interception(struct vcpu_svm *svm)
3827 {
3828 	struct kvm_vcpu *vcpu = &svm->vcpu;
3829 
3830 	trace_kvm_invlpga(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RCX),
3831 			  kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3832 
3833 	/* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3834 	kvm_mmu_invlpg(vcpu, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3835 
3836 	svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3837 	return kvm_skip_emulated_instruction(&svm->vcpu);
3838 }
3839 
skinit_interception(struct vcpu_svm * svm)3840 static int skinit_interception(struct vcpu_svm *svm)
3841 {
3842 	trace_kvm_skinit(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3843 
3844 	kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3845 	return 1;
3846 }
3847 
wbinvd_interception(struct vcpu_svm * svm)3848 static int wbinvd_interception(struct vcpu_svm *svm)
3849 {
3850 	return kvm_emulate_wbinvd(&svm->vcpu);
3851 }
3852 
xsetbv_interception(struct vcpu_svm * svm)3853 static int xsetbv_interception(struct vcpu_svm *svm)
3854 {
3855 	u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3856 	u32 index = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3857 
3858 	if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3859 		svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3860 		return kvm_skip_emulated_instruction(&svm->vcpu);
3861 	}
3862 
3863 	return 1;
3864 }
3865 
task_switch_interception(struct vcpu_svm * svm)3866 static int task_switch_interception(struct vcpu_svm *svm)
3867 {
3868 	u16 tss_selector;
3869 	int reason;
3870 	int int_type = svm->vmcb->control.exit_int_info &
3871 		SVM_EXITINTINFO_TYPE_MASK;
3872 	int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3873 	uint32_t type =
3874 		svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3875 	uint32_t idt_v =
3876 		svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3877 	bool has_error_code = false;
3878 	u32 error_code = 0;
3879 
3880 	tss_selector = (u16)svm->vmcb->control.exit_info_1;
3881 
3882 	if (svm->vmcb->control.exit_info_2 &
3883 	    (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3884 		reason = TASK_SWITCH_IRET;
3885 	else if (svm->vmcb->control.exit_info_2 &
3886 		 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3887 		reason = TASK_SWITCH_JMP;
3888 	else if (idt_v)
3889 		reason = TASK_SWITCH_GATE;
3890 	else
3891 		reason = TASK_SWITCH_CALL;
3892 
3893 	if (reason == TASK_SWITCH_GATE) {
3894 		switch (type) {
3895 		case SVM_EXITINTINFO_TYPE_NMI:
3896 			svm->vcpu.arch.nmi_injected = false;
3897 			break;
3898 		case SVM_EXITINTINFO_TYPE_EXEPT:
3899 			if (svm->vmcb->control.exit_info_2 &
3900 			    (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3901 				has_error_code = true;
3902 				error_code =
3903 					(u32)svm->vmcb->control.exit_info_2;
3904 			}
3905 			kvm_clear_exception_queue(&svm->vcpu);
3906 			break;
3907 		case SVM_EXITINTINFO_TYPE_INTR:
3908 			kvm_clear_interrupt_queue(&svm->vcpu);
3909 			break;
3910 		default:
3911 			break;
3912 		}
3913 	}
3914 
3915 	if (reason != TASK_SWITCH_GATE ||
3916 	    int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3917 	    (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3918 	     (int_vec == OF_VECTOR || int_vec == BP_VECTOR)))
3919 		skip_emulated_instruction(&svm->vcpu);
3920 
3921 	if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3922 		int_vec = -1;
3923 
3924 	if (kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
3925 				has_error_code, error_code) == EMULATE_FAIL) {
3926 		svm->vcpu.run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3927 		svm->vcpu.run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3928 		svm->vcpu.run->internal.ndata = 0;
3929 		return 0;
3930 	}
3931 	return 1;
3932 }
3933 
cpuid_interception(struct vcpu_svm * svm)3934 static int cpuid_interception(struct vcpu_svm *svm)
3935 {
3936 	svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3937 	return kvm_emulate_cpuid(&svm->vcpu);
3938 }
3939 
iret_interception(struct vcpu_svm * svm)3940 static int iret_interception(struct vcpu_svm *svm)
3941 {
3942 	++svm->vcpu.stat.nmi_window_exits;
3943 	clr_intercept(svm, INTERCEPT_IRET);
3944 	svm->vcpu.arch.hflags |= HF_IRET_MASK;
3945 	svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
3946 	kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3947 	return 1;
3948 }
3949 
invd_interception(struct vcpu_svm * svm)3950 static int invd_interception(struct vcpu_svm *svm)
3951 {
3952 	/* Treat an INVD instruction as a NOP and just skip it. */
3953 	return kvm_skip_emulated_instruction(&svm->vcpu);
3954 }
3955 
invlpg_interception(struct vcpu_svm * svm)3956 static int invlpg_interception(struct vcpu_svm *svm)
3957 {
3958 	if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3959 		return kvm_emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3960 
3961 	kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
3962 	return kvm_skip_emulated_instruction(&svm->vcpu);
3963 }
3964 
emulate_on_interception(struct vcpu_svm * svm)3965 static int emulate_on_interception(struct vcpu_svm *svm)
3966 {
3967 	return kvm_emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3968 }
3969 
rsm_interception(struct vcpu_svm * svm)3970 static int rsm_interception(struct vcpu_svm *svm)
3971 {
3972 	return kvm_emulate_instruction_from_buffer(&svm->vcpu,
3973 					rsm_ins_bytes, 2) == EMULATE_DONE;
3974 }
3975 
rdpmc_interception(struct vcpu_svm * svm)3976 static int rdpmc_interception(struct vcpu_svm *svm)
3977 {
3978 	int err;
3979 
3980 	if (!static_cpu_has(X86_FEATURE_NRIPS))
3981 		return emulate_on_interception(svm);
3982 
3983 	err = kvm_rdpmc(&svm->vcpu);
3984 	return kvm_complete_insn_gp(&svm->vcpu, err);
3985 }
3986 
check_selective_cr0_intercepted(struct vcpu_svm * svm,unsigned long val)3987 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
3988 					    unsigned long val)
3989 {
3990 	unsigned long cr0 = svm->vcpu.arch.cr0;
3991 	bool ret = false;
3992 	u64 intercept;
3993 
3994 	intercept = svm->nested.intercept;
3995 
3996 	if (!is_guest_mode(&svm->vcpu) ||
3997 	    (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
3998 		return false;
3999 
4000 	cr0 &= ~SVM_CR0_SELECTIVE_MASK;
4001 	val &= ~SVM_CR0_SELECTIVE_MASK;
4002 
4003 	if (cr0 ^ val) {
4004 		svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4005 		ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
4006 	}
4007 
4008 	return ret;
4009 }
4010 
4011 #define CR_VALID (1ULL << 63)
4012 
cr_interception(struct vcpu_svm * svm)4013 static int cr_interception(struct vcpu_svm *svm)
4014 {
4015 	int reg, cr;
4016 	unsigned long val;
4017 	int err;
4018 
4019 	if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
4020 		return emulate_on_interception(svm);
4021 
4022 	if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
4023 		return emulate_on_interception(svm);
4024 
4025 	reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
4026 	if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
4027 		cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
4028 	else
4029 		cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
4030 
4031 	err = 0;
4032 	if (cr >= 16) { /* mov to cr */
4033 		cr -= 16;
4034 		val = kvm_register_read(&svm->vcpu, reg);
4035 		switch (cr) {
4036 		case 0:
4037 			if (!check_selective_cr0_intercepted(svm, val))
4038 				err = kvm_set_cr0(&svm->vcpu, val);
4039 			else
4040 				return 1;
4041 
4042 			break;
4043 		case 3:
4044 			err = kvm_set_cr3(&svm->vcpu, val);
4045 			break;
4046 		case 4:
4047 			err = kvm_set_cr4(&svm->vcpu, val);
4048 			break;
4049 		case 8:
4050 			err = kvm_set_cr8(&svm->vcpu, val);
4051 			break;
4052 		default:
4053 			WARN(1, "unhandled write to CR%d", cr);
4054 			kvm_queue_exception(&svm->vcpu, UD_VECTOR);
4055 			return 1;
4056 		}
4057 	} else { /* mov from cr */
4058 		switch (cr) {
4059 		case 0:
4060 			val = kvm_read_cr0(&svm->vcpu);
4061 			break;
4062 		case 2:
4063 			val = svm->vcpu.arch.cr2;
4064 			break;
4065 		case 3:
4066 			val = kvm_read_cr3(&svm->vcpu);
4067 			break;
4068 		case 4:
4069 			val = kvm_read_cr4(&svm->vcpu);
4070 			break;
4071 		case 8:
4072 			val = kvm_get_cr8(&svm->vcpu);
4073 			break;
4074 		default:
4075 			WARN(1, "unhandled read from CR%d", cr);
4076 			kvm_queue_exception(&svm->vcpu, UD_VECTOR);
4077 			return 1;
4078 		}
4079 		kvm_register_write(&svm->vcpu, reg, val);
4080 	}
4081 	return kvm_complete_insn_gp(&svm->vcpu, err);
4082 }
4083 
dr_interception(struct vcpu_svm * svm)4084 static int dr_interception(struct vcpu_svm *svm)
4085 {
4086 	int reg, dr;
4087 	unsigned long val;
4088 
4089 	if (svm->vcpu.guest_debug == 0) {
4090 		/*
4091 		 * No more DR vmexits; force a reload of the debug registers
4092 		 * and reenter on this instruction.  The next vmexit will
4093 		 * retrieve the full state of the debug registers.
4094 		 */
4095 		clr_dr_intercepts(svm);
4096 		svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4097 		return 1;
4098 	}
4099 
4100 	if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
4101 		return emulate_on_interception(svm);
4102 
4103 	reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
4104 	dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
4105 
4106 	if (dr >= 16) { /* mov to DRn */
4107 		if (!kvm_require_dr(&svm->vcpu, dr - 16))
4108 			return 1;
4109 		val = kvm_register_read(&svm->vcpu, reg);
4110 		kvm_set_dr(&svm->vcpu, dr - 16, val);
4111 	} else {
4112 		if (!kvm_require_dr(&svm->vcpu, dr))
4113 			return 1;
4114 		kvm_get_dr(&svm->vcpu, dr, &val);
4115 		kvm_register_write(&svm->vcpu, reg, val);
4116 	}
4117 
4118 	return kvm_skip_emulated_instruction(&svm->vcpu);
4119 }
4120 
cr8_write_interception(struct vcpu_svm * svm)4121 static int cr8_write_interception(struct vcpu_svm *svm)
4122 {
4123 	struct kvm_run *kvm_run = svm->vcpu.run;
4124 	int r;
4125 
4126 	u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
4127 	/* instruction emulation calls kvm_set_cr8() */
4128 	r = cr_interception(svm);
4129 	if (lapic_in_kernel(&svm->vcpu))
4130 		return r;
4131 	if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
4132 		return r;
4133 	kvm_run->exit_reason = KVM_EXIT_SET_TPR;
4134 	return 0;
4135 }
4136 
svm_get_msr_feature(struct kvm_msr_entry * msr)4137 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
4138 {
4139 	msr->data = 0;
4140 
4141 	switch (msr->index) {
4142 	case MSR_F10H_DECFG:
4143 		if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
4144 			msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
4145 		break;
4146 	default:
4147 		return 1;
4148 	}
4149 
4150 	return 0;
4151 }
4152 
svm_get_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4153 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4154 {
4155 	struct vcpu_svm *svm = to_svm(vcpu);
4156 
4157 	switch (msr_info->index) {
4158 	case MSR_STAR:
4159 		msr_info->data = svm->vmcb->save.star;
4160 		break;
4161 #ifdef CONFIG_X86_64
4162 	case MSR_LSTAR:
4163 		msr_info->data = svm->vmcb->save.lstar;
4164 		break;
4165 	case MSR_CSTAR:
4166 		msr_info->data = svm->vmcb->save.cstar;
4167 		break;
4168 	case MSR_KERNEL_GS_BASE:
4169 		msr_info->data = svm->vmcb->save.kernel_gs_base;
4170 		break;
4171 	case MSR_SYSCALL_MASK:
4172 		msr_info->data = svm->vmcb->save.sfmask;
4173 		break;
4174 #endif
4175 	case MSR_IA32_SYSENTER_CS:
4176 		msr_info->data = svm->vmcb->save.sysenter_cs;
4177 		break;
4178 	case MSR_IA32_SYSENTER_EIP:
4179 		msr_info->data = svm->sysenter_eip;
4180 		break;
4181 	case MSR_IA32_SYSENTER_ESP:
4182 		msr_info->data = svm->sysenter_esp;
4183 		break;
4184 	case MSR_TSC_AUX:
4185 		if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4186 			return 1;
4187 		msr_info->data = svm->tsc_aux;
4188 		break;
4189 	/*
4190 	 * Nobody will change the following 5 values in the VMCB so we can
4191 	 * safely return them on rdmsr. They will always be 0 until LBRV is
4192 	 * implemented.
4193 	 */
4194 	case MSR_IA32_DEBUGCTLMSR:
4195 		msr_info->data = svm->vmcb->save.dbgctl;
4196 		break;
4197 	case MSR_IA32_LASTBRANCHFROMIP:
4198 		msr_info->data = svm->vmcb->save.br_from;
4199 		break;
4200 	case MSR_IA32_LASTBRANCHTOIP:
4201 		msr_info->data = svm->vmcb->save.br_to;
4202 		break;
4203 	case MSR_IA32_LASTINTFROMIP:
4204 		msr_info->data = svm->vmcb->save.last_excp_from;
4205 		break;
4206 	case MSR_IA32_LASTINTTOIP:
4207 		msr_info->data = svm->vmcb->save.last_excp_to;
4208 		break;
4209 	case MSR_VM_HSAVE_PA:
4210 		msr_info->data = svm->nested.hsave_msr;
4211 		break;
4212 	case MSR_VM_CR:
4213 		msr_info->data = svm->nested.vm_cr_msr;
4214 		break;
4215 	case MSR_IA32_SPEC_CTRL:
4216 		if (!msr_info->host_initiated &&
4217 		    !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4218 		    !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4219 			return 1;
4220 
4221 		msr_info->data = svm->spec_ctrl;
4222 		break;
4223 	case MSR_AMD64_VIRT_SPEC_CTRL:
4224 		if (!msr_info->host_initiated &&
4225 		    !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4226 			return 1;
4227 
4228 		msr_info->data = svm->virt_spec_ctrl;
4229 		break;
4230 	case MSR_F15H_IC_CFG: {
4231 
4232 		int family, model;
4233 
4234 		family = guest_cpuid_family(vcpu);
4235 		model  = guest_cpuid_model(vcpu);
4236 
4237 		if (family < 0 || model < 0)
4238 			return kvm_get_msr_common(vcpu, msr_info);
4239 
4240 		msr_info->data = 0;
4241 
4242 		if (family == 0x15 &&
4243 		    (model >= 0x2 && model < 0x20))
4244 			msr_info->data = 0x1E;
4245 		}
4246 		break;
4247 	case MSR_F10H_DECFG:
4248 		msr_info->data = svm->msr_decfg;
4249 		break;
4250 	default:
4251 		return kvm_get_msr_common(vcpu, msr_info);
4252 	}
4253 	return 0;
4254 }
4255 
rdmsr_interception(struct vcpu_svm * svm)4256 static int rdmsr_interception(struct vcpu_svm *svm)
4257 {
4258 	u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
4259 	struct msr_data msr_info;
4260 
4261 	msr_info.index = ecx;
4262 	msr_info.host_initiated = false;
4263 	if (svm_get_msr(&svm->vcpu, &msr_info)) {
4264 		trace_kvm_msr_read_ex(ecx);
4265 		kvm_inject_gp(&svm->vcpu, 0);
4266 		return 1;
4267 	} else {
4268 		trace_kvm_msr_read(ecx, msr_info.data);
4269 
4270 		kvm_register_write(&svm->vcpu, VCPU_REGS_RAX,
4271 				   msr_info.data & 0xffffffff);
4272 		kvm_register_write(&svm->vcpu, VCPU_REGS_RDX,
4273 				   msr_info.data >> 32);
4274 		svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
4275 		return kvm_skip_emulated_instruction(&svm->vcpu);
4276 	}
4277 }
4278 
svm_set_vm_cr(struct kvm_vcpu * vcpu,u64 data)4279 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
4280 {
4281 	struct vcpu_svm *svm = to_svm(vcpu);
4282 	int svm_dis, chg_mask;
4283 
4284 	if (data & ~SVM_VM_CR_VALID_MASK)
4285 		return 1;
4286 
4287 	chg_mask = SVM_VM_CR_VALID_MASK;
4288 
4289 	if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
4290 		chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
4291 
4292 	svm->nested.vm_cr_msr &= ~chg_mask;
4293 	svm->nested.vm_cr_msr |= (data & chg_mask);
4294 
4295 	svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
4296 
4297 	/* check for svm_disable while efer.svme is set */
4298 	if (svm_dis && (vcpu->arch.efer & EFER_SVME))
4299 		return 1;
4300 
4301 	return 0;
4302 }
4303 
svm_set_msr(struct kvm_vcpu * vcpu,struct msr_data * msr)4304 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
4305 {
4306 	struct vcpu_svm *svm = to_svm(vcpu);
4307 
4308 	u32 ecx = msr->index;
4309 	u64 data = msr->data;
4310 	switch (ecx) {
4311 	case MSR_IA32_CR_PAT:
4312 		if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4313 			return 1;
4314 		vcpu->arch.pat = data;
4315 		svm->vmcb->save.g_pat = data;
4316 		mark_dirty(svm->vmcb, VMCB_NPT);
4317 		break;
4318 	case MSR_IA32_SPEC_CTRL:
4319 		if (!msr->host_initiated &&
4320 		    !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4321 		    !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4322 			return 1;
4323 
4324 		/* The STIBP bit doesn't fault even if it's not advertised */
4325 		if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
4326 			return 1;
4327 
4328 		svm->spec_ctrl = data;
4329 
4330 		if (!data)
4331 			break;
4332 
4333 		/*
4334 		 * For non-nested:
4335 		 * When it's written (to non-zero) for the first time, pass
4336 		 * it through.
4337 		 *
4338 		 * For nested:
4339 		 * The handling of the MSR bitmap for L2 guests is done in
4340 		 * nested_svm_vmrun_msrpm.
4341 		 * We update the L1 MSR bit as well since it will end up
4342 		 * touching the MSR anyway now.
4343 		 */
4344 		set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
4345 		break;
4346 	case MSR_IA32_PRED_CMD:
4347 		if (!msr->host_initiated &&
4348 		    !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBPB))
4349 			return 1;
4350 
4351 		if (data & ~PRED_CMD_IBPB)
4352 			return 1;
4353 
4354 		if (!data)
4355 			break;
4356 
4357 		wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4358 		if (is_guest_mode(vcpu))
4359 			break;
4360 		set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
4361 		break;
4362 	case MSR_AMD64_VIRT_SPEC_CTRL:
4363 		if (!msr->host_initiated &&
4364 		    !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4365 			return 1;
4366 
4367 		if (data & ~SPEC_CTRL_SSBD)
4368 			return 1;
4369 
4370 		svm->virt_spec_ctrl = data;
4371 		break;
4372 	case MSR_STAR:
4373 		svm->vmcb->save.star = data;
4374 		break;
4375 #ifdef CONFIG_X86_64
4376 	case MSR_LSTAR:
4377 		svm->vmcb->save.lstar = data;
4378 		break;
4379 	case MSR_CSTAR:
4380 		svm->vmcb->save.cstar = data;
4381 		break;
4382 	case MSR_KERNEL_GS_BASE:
4383 		svm->vmcb->save.kernel_gs_base = data;
4384 		break;
4385 	case MSR_SYSCALL_MASK:
4386 		svm->vmcb->save.sfmask = data;
4387 		break;
4388 #endif
4389 	case MSR_IA32_SYSENTER_CS:
4390 		svm->vmcb->save.sysenter_cs = data;
4391 		break;
4392 	case MSR_IA32_SYSENTER_EIP:
4393 		svm->sysenter_eip = data;
4394 		svm->vmcb->save.sysenter_eip = data;
4395 		break;
4396 	case MSR_IA32_SYSENTER_ESP:
4397 		svm->sysenter_esp = data;
4398 		svm->vmcb->save.sysenter_esp = data;
4399 		break;
4400 	case MSR_TSC_AUX:
4401 		if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4402 			return 1;
4403 
4404 		/*
4405 		 * This is rare, so we update the MSR here instead of using
4406 		 * direct_access_msrs.  Doing that would require a rdmsr in
4407 		 * svm_vcpu_put.
4408 		 */
4409 		svm->tsc_aux = data;
4410 		wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
4411 		break;
4412 	case MSR_IA32_DEBUGCTLMSR:
4413 		if (!boot_cpu_has(X86_FEATURE_LBRV)) {
4414 			vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
4415 				    __func__, data);
4416 			break;
4417 		}
4418 		if (data & DEBUGCTL_RESERVED_BITS)
4419 			return 1;
4420 
4421 		svm->vmcb->save.dbgctl = data;
4422 		mark_dirty(svm->vmcb, VMCB_LBR);
4423 		if (data & (1ULL<<0))
4424 			svm_enable_lbrv(svm);
4425 		else
4426 			svm_disable_lbrv(svm);
4427 		break;
4428 	case MSR_VM_HSAVE_PA:
4429 		svm->nested.hsave_msr = data;
4430 		break;
4431 	case MSR_VM_CR:
4432 		return svm_set_vm_cr(vcpu, data);
4433 	case MSR_VM_IGNNE:
4434 		vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
4435 		break;
4436 	case MSR_F10H_DECFG: {
4437 		struct kvm_msr_entry msr_entry;
4438 
4439 		msr_entry.index = msr->index;
4440 		if (svm_get_msr_feature(&msr_entry))
4441 			return 1;
4442 
4443 		/* Check the supported bits */
4444 		if (data & ~msr_entry.data)
4445 			return 1;
4446 
4447 		/* Don't allow the guest to change a bit, #GP */
4448 		if (!msr->host_initiated && (data ^ msr_entry.data))
4449 			return 1;
4450 
4451 		svm->msr_decfg = data;
4452 		break;
4453 	}
4454 	case MSR_IA32_APICBASE:
4455 		if (kvm_vcpu_apicv_active(vcpu))
4456 			avic_update_vapic_bar(to_svm(vcpu), data);
4457 		/* Follow through */
4458 	default:
4459 		return kvm_set_msr_common(vcpu, msr);
4460 	}
4461 	return 0;
4462 }
4463 
wrmsr_interception(struct vcpu_svm * svm)4464 static int wrmsr_interception(struct vcpu_svm *svm)
4465 {
4466 	struct msr_data msr;
4467 	u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
4468 	u64 data = kvm_read_edx_eax(&svm->vcpu);
4469 
4470 	msr.data = data;
4471 	msr.index = ecx;
4472 	msr.host_initiated = false;
4473 
4474 	svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
4475 	if (kvm_set_msr(&svm->vcpu, &msr)) {
4476 		trace_kvm_msr_write_ex(ecx, data);
4477 		kvm_inject_gp(&svm->vcpu, 0);
4478 		return 1;
4479 	} else {
4480 		trace_kvm_msr_write(ecx, data);
4481 		return kvm_skip_emulated_instruction(&svm->vcpu);
4482 	}
4483 }
4484 
msr_interception(struct vcpu_svm * svm)4485 static int msr_interception(struct vcpu_svm *svm)
4486 {
4487 	if (svm->vmcb->control.exit_info_1)
4488 		return wrmsr_interception(svm);
4489 	else
4490 		return rdmsr_interception(svm);
4491 }
4492 
interrupt_window_interception(struct vcpu_svm * svm)4493 static int interrupt_window_interception(struct vcpu_svm *svm)
4494 {
4495 	kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4496 	svm_clear_vintr(svm);
4497 	svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4498 	mark_dirty(svm->vmcb, VMCB_INTR);
4499 	++svm->vcpu.stat.irq_window_exits;
4500 	return 1;
4501 }
4502 
pause_interception(struct vcpu_svm * svm)4503 static int pause_interception(struct vcpu_svm *svm)
4504 {
4505 	struct kvm_vcpu *vcpu = &svm->vcpu;
4506 	bool in_kernel = (svm_get_cpl(vcpu) == 0);
4507 
4508 	if (pause_filter_thresh)
4509 		grow_ple_window(vcpu);
4510 
4511 	kvm_vcpu_on_spin(vcpu, in_kernel);
4512 	return 1;
4513 }
4514 
nop_interception(struct vcpu_svm * svm)4515 static int nop_interception(struct vcpu_svm *svm)
4516 {
4517 	return kvm_skip_emulated_instruction(&(svm->vcpu));
4518 }
4519 
monitor_interception(struct vcpu_svm * svm)4520 static int monitor_interception(struct vcpu_svm *svm)
4521 {
4522 	printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4523 	return nop_interception(svm);
4524 }
4525 
mwait_interception(struct vcpu_svm * svm)4526 static int mwait_interception(struct vcpu_svm *svm)
4527 {
4528 	printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4529 	return nop_interception(svm);
4530 }
4531 
4532 enum avic_ipi_failure_cause {
4533 	AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4534 	AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4535 	AVIC_IPI_FAILURE_INVALID_TARGET,
4536 	AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4537 };
4538 
avic_incomplete_ipi_interception(struct vcpu_svm * svm)4539 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4540 {
4541 	u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4542 	u32 icrl = svm->vmcb->control.exit_info_1;
4543 	u32 id = svm->vmcb->control.exit_info_2 >> 32;
4544 	u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4545 	struct kvm_lapic *apic = svm->vcpu.arch.apic;
4546 
4547 	trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4548 
4549 	switch (id) {
4550 	case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4551 		/*
4552 		 * AVIC hardware handles the generation of
4553 		 * IPIs when the specified Message Type is Fixed
4554 		 * (also known as fixed delivery mode) and
4555 		 * the Trigger Mode is edge-triggered. The hardware
4556 		 * also supports self and broadcast delivery modes
4557 		 * specified via the Destination Shorthand(DSH)
4558 		 * field of the ICRL. Logical and physical APIC ID
4559 		 * formats are supported. All other IPI types cause
4560 		 * a #VMEXIT, which needs to emulated.
4561 		 */
4562 		kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4563 		kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4564 		break;
4565 	case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4566 		int i;
4567 		struct kvm_vcpu *vcpu;
4568 		struct kvm *kvm = svm->vcpu.kvm;
4569 		struct kvm_lapic *apic = svm->vcpu.arch.apic;
4570 
4571 		/*
4572 		 * At this point, we expect that the AVIC HW has already
4573 		 * set the appropriate IRR bits on the valid target
4574 		 * vcpus. So, we just need to kick the appropriate vcpu.
4575 		 */
4576 		kvm_for_each_vcpu(i, vcpu, kvm) {
4577 			bool m = kvm_apic_match_dest(vcpu, apic,
4578 						     icrl & KVM_APIC_SHORT_MASK,
4579 						     GET_APIC_DEST_FIELD(icrh),
4580 						     icrl & KVM_APIC_DEST_MASK);
4581 
4582 			if (m && !avic_vcpu_is_running(vcpu))
4583 				kvm_vcpu_wake_up(vcpu);
4584 		}
4585 		break;
4586 	}
4587 	case AVIC_IPI_FAILURE_INVALID_TARGET:
4588 		break;
4589 	case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4590 		WARN_ONCE(1, "Invalid backing page\n");
4591 		break;
4592 	default:
4593 		pr_err("Unknown IPI interception\n");
4594 	}
4595 
4596 	return 1;
4597 }
4598 
avic_get_logical_id_entry(struct kvm_vcpu * vcpu,u32 ldr,bool flat)4599 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4600 {
4601 	struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
4602 	int index;
4603 	u32 *logical_apic_id_table;
4604 	int dlid = GET_APIC_LOGICAL_ID(ldr);
4605 
4606 	if (!dlid)
4607 		return NULL;
4608 
4609 	if (flat) { /* flat */
4610 		index = ffs(dlid) - 1;
4611 		if (index > 7)
4612 			return NULL;
4613 	} else { /* cluster */
4614 		int cluster = (dlid & 0xf0) >> 4;
4615 		int apic = ffs(dlid & 0x0f) - 1;
4616 
4617 		if ((apic < 0) || (apic > 7) ||
4618 		    (cluster >= 0xf))
4619 			return NULL;
4620 		index = (cluster << 2) + apic;
4621 	}
4622 
4623 	logical_apic_id_table = (u32 *) page_address(kvm_svm->avic_logical_id_table_page);
4624 
4625 	return &logical_apic_id_table[index];
4626 }
4627 
avic_ldr_write(struct kvm_vcpu * vcpu,u8 g_physical_id,u32 ldr,bool valid)4628 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr,
4629 			  bool valid)
4630 {
4631 	bool flat;
4632 	u32 *entry, new_entry;
4633 
4634 	flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4635 	entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4636 	if (!entry)
4637 		return -EINVAL;
4638 
4639 	new_entry = READ_ONCE(*entry);
4640 	new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4641 	new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4642 	if (valid)
4643 		new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4644 	else
4645 		new_entry &= ~AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4646 	WRITE_ONCE(*entry, new_entry);
4647 
4648 	return 0;
4649 }
4650 
avic_handle_ldr_update(struct kvm_vcpu * vcpu)4651 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4652 {
4653 	int ret;
4654 	struct vcpu_svm *svm = to_svm(vcpu);
4655 	u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4656 
4657 	if (!ldr)
4658 		return 1;
4659 
4660 	ret = avic_ldr_write(vcpu, vcpu->vcpu_id, ldr, true);
4661 	if (ret && svm->ldr_reg) {
4662 		avic_ldr_write(vcpu, 0, svm->ldr_reg, false);
4663 		svm->ldr_reg = 0;
4664 	} else {
4665 		svm->ldr_reg = ldr;
4666 	}
4667 	return ret;
4668 }
4669 
avic_handle_apic_id_update(struct kvm_vcpu * vcpu)4670 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4671 {
4672 	u64 *old, *new;
4673 	struct vcpu_svm *svm = to_svm(vcpu);
4674 	u32 apic_id_reg = kvm_lapic_get_reg(vcpu->arch.apic, APIC_ID);
4675 	u32 id = (apic_id_reg >> 24) & 0xff;
4676 
4677 	if (vcpu->vcpu_id == id)
4678 		return 0;
4679 
4680 	old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4681 	new = avic_get_physical_id_entry(vcpu, id);
4682 	if (!new || !old)
4683 		return 1;
4684 
4685 	/* We need to move physical_id_entry to new offset */
4686 	*new = *old;
4687 	*old = 0ULL;
4688 	to_svm(vcpu)->avic_physical_id_cache = new;
4689 
4690 	/*
4691 	 * Also update the guest physical APIC ID in the logical
4692 	 * APIC ID table entry if already setup the LDR.
4693 	 */
4694 	if (svm->ldr_reg)
4695 		avic_handle_ldr_update(vcpu);
4696 
4697 	return 0;
4698 }
4699 
avic_handle_dfr_update(struct kvm_vcpu * vcpu)4700 static int avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4701 {
4702 	struct vcpu_svm *svm = to_svm(vcpu);
4703 	struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
4704 	u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4705 	u32 mod = (dfr >> 28) & 0xf;
4706 
4707 	/*
4708 	 * We assume that all local APICs are using the same type.
4709 	 * If this changes, we need to flush the AVIC logical
4710 	 * APID id table.
4711 	 */
4712 	if (kvm_svm->ldr_mode == mod)
4713 		return 0;
4714 
4715 	clear_page(page_address(kvm_svm->avic_logical_id_table_page));
4716 	kvm_svm->ldr_mode = mod;
4717 
4718 	if (svm->ldr_reg)
4719 		avic_handle_ldr_update(vcpu);
4720 	return 0;
4721 }
4722 
avic_unaccel_trap_write(struct vcpu_svm * svm)4723 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4724 {
4725 	struct kvm_lapic *apic = svm->vcpu.arch.apic;
4726 	u32 offset = svm->vmcb->control.exit_info_1 &
4727 				AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4728 
4729 	switch (offset) {
4730 	case APIC_ID:
4731 		if (avic_handle_apic_id_update(&svm->vcpu))
4732 			return 0;
4733 		break;
4734 	case APIC_LDR:
4735 		if (avic_handle_ldr_update(&svm->vcpu))
4736 			return 0;
4737 		break;
4738 	case APIC_DFR:
4739 		avic_handle_dfr_update(&svm->vcpu);
4740 		break;
4741 	default:
4742 		break;
4743 	}
4744 
4745 	kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4746 
4747 	return 1;
4748 }
4749 
is_avic_unaccelerated_access_trap(u32 offset)4750 static bool is_avic_unaccelerated_access_trap(u32 offset)
4751 {
4752 	bool ret = false;
4753 
4754 	switch (offset) {
4755 	case APIC_ID:
4756 	case APIC_EOI:
4757 	case APIC_RRR:
4758 	case APIC_LDR:
4759 	case APIC_DFR:
4760 	case APIC_SPIV:
4761 	case APIC_ESR:
4762 	case APIC_ICR:
4763 	case APIC_LVTT:
4764 	case APIC_LVTTHMR:
4765 	case APIC_LVTPC:
4766 	case APIC_LVT0:
4767 	case APIC_LVT1:
4768 	case APIC_LVTERR:
4769 	case APIC_TMICT:
4770 	case APIC_TDCR:
4771 		ret = true;
4772 		break;
4773 	default:
4774 		break;
4775 	}
4776 	return ret;
4777 }
4778 
avic_unaccelerated_access_interception(struct vcpu_svm * svm)4779 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4780 {
4781 	int ret = 0;
4782 	u32 offset = svm->vmcb->control.exit_info_1 &
4783 		     AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4784 	u32 vector = svm->vmcb->control.exit_info_2 &
4785 		     AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4786 	bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4787 		     AVIC_UNACCEL_ACCESS_WRITE_MASK;
4788 	bool trap = is_avic_unaccelerated_access_trap(offset);
4789 
4790 	trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4791 					    trap, write, vector);
4792 	if (trap) {
4793 		/* Handling Trap */
4794 		WARN_ONCE(!write, "svm: Handling trap read.\n");
4795 		ret = avic_unaccel_trap_write(svm);
4796 	} else {
4797 		/* Handling Fault */
4798 		ret = (kvm_emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE);
4799 	}
4800 
4801 	return ret;
4802 }
4803 
4804 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4805 	[SVM_EXIT_READ_CR0]			= cr_interception,
4806 	[SVM_EXIT_READ_CR3]			= cr_interception,
4807 	[SVM_EXIT_READ_CR4]			= cr_interception,
4808 	[SVM_EXIT_READ_CR8]			= cr_interception,
4809 	[SVM_EXIT_CR0_SEL_WRITE]		= cr_interception,
4810 	[SVM_EXIT_WRITE_CR0]			= cr_interception,
4811 	[SVM_EXIT_WRITE_CR3]			= cr_interception,
4812 	[SVM_EXIT_WRITE_CR4]			= cr_interception,
4813 	[SVM_EXIT_WRITE_CR8]			= cr8_write_interception,
4814 	[SVM_EXIT_READ_DR0]			= dr_interception,
4815 	[SVM_EXIT_READ_DR1]			= dr_interception,
4816 	[SVM_EXIT_READ_DR2]			= dr_interception,
4817 	[SVM_EXIT_READ_DR3]			= dr_interception,
4818 	[SVM_EXIT_READ_DR4]			= dr_interception,
4819 	[SVM_EXIT_READ_DR5]			= dr_interception,
4820 	[SVM_EXIT_READ_DR6]			= dr_interception,
4821 	[SVM_EXIT_READ_DR7]			= dr_interception,
4822 	[SVM_EXIT_WRITE_DR0]			= dr_interception,
4823 	[SVM_EXIT_WRITE_DR1]			= dr_interception,
4824 	[SVM_EXIT_WRITE_DR2]			= dr_interception,
4825 	[SVM_EXIT_WRITE_DR3]			= dr_interception,
4826 	[SVM_EXIT_WRITE_DR4]			= dr_interception,
4827 	[SVM_EXIT_WRITE_DR5]			= dr_interception,
4828 	[SVM_EXIT_WRITE_DR6]			= dr_interception,
4829 	[SVM_EXIT_WRITE_DR7]			= dr_interception,
4830 	[SVM_EXIT_EXCP_BASE + DB_VECTOR]	= db_interception,
4831 	[SVM_EXIT_EXCP_BASE + BP_VECTOR]	= bp_interception,
4832 	[SVM_EXIT_EXCP_BASE + UD_VECTOR]	= ud_interception,
4833 	[SVM_EXIT_EXCP_BASE + PF_VECTOR]	= pf_interception,
4834 	[SVM_EXIT_EXCP_BASE + MC_VECTOR]	= mc_interception,
4835 	[SVM_EXIT_EXCP_BASE + AC_VECTOR]	= ac_interception,
4836 	[SVM_EXIT_EXCP_BASE + GP_VECTOR]	= gp_interception,
4837 	[SVM_EXIT_INTR]				= intr_interception,
4838 	[SVM_EXIT_NMI]				= nmi_interception,
4839 	[SVM_EXIT_SMI]				= nop_on_interception,
4840 	[SVM_EXIT_INIT]				= nop_on_interception,
4841 	[SVM_EXIT_VINTR]			= interrupt_window_interception,
4842 	[SVM_EXIT_RDPMC]			= rdpmc_interception,
4843 	[SVM_EXIT_CPUID]			= cpuid_interception,
4844 	[SVM_EXIT_IRET]                         = iret_interception,
4845 	[SVM_EXIT_INVD]                         = invd_interception,
4846 	[SVM_EXIT_PAUSE]			= pause_interception,
4847 	[SVM_EXIT_HLT]				= halt_interception,
4848 	[SVM_EXIT_INVLPG]			= invlpg_interception,
4849 	[SVM_EXIT_INVLPGA]			= invlpga_interception,
4850 	[SVM_EXIT_IOIO]				= io_interception,
4851 	[SVM_EXIT_MSR]				= msr_interception,
4852 	[SVM_EXIT_TASK_SWITCH]			= task_switch_interception,
4853 	[SVM_EXIT_SHUTDOWN]			= shutdown_interception,
4854 	[SVM_EXIT_VMRUN]			= vmrun_interception,
4855 	[SVM_EXIT_VMMCALL]			= vmmcall_interception,
4856 	[SVM_EXIT_VMLOAD]			= vmload_interception,
4857 	[SVM_EXIT_VMSAVE]			= vmsave_interception,
4858 	[SVM_EXIT_STGI]				= stgi_interception,
4859 	[SVM_EXIT_CLGI]				= clgi_interception,
4860 	[SVM_EXIT_SKINIT]			= skinit_interception,
4861 	[SVM_EXIT_WBINVD]                       = wbinvd_interception,
4862 	[SVM_EXIT_MONITOR]			= monitor_interception,
4863 	[SVM_EXIT_MWAIT]			= mwait_interception,
4864 	[SVM_EXIT_XSETBV]			= xsetbv_interception,
4865 	[SVM_EXIT_NPF]				= npf_interception,
4866 	[SVM_EXIT_RSM]                          = rsm_interception,
4867 	[SVM_EXIT_AVIC_INCOMPLETE_IPI]		= avic_incomplete_ipi_interception,
4868 	[SVM_EXIT_AVIC_UNACCELERATED_ACCESS]	= avic_unaccelerated_access_interception,
4869 };
4870 
dump_vmcb(struct kvm_vcpu * vcpu)4871 static void dump_vmcb(struct kvm_vcpu *vcpu)
4872 {
4873 	struct vcpu_svm *svm = to_svm(vcpu);
4874 	struct vmcb_control_area *control = &svm->vmcb->control;
4875 	struct vmcb_save_area *save = &svm->vmcb->save;
4876 
4877 	pr_err("VMCB Control Area:\n");
4878 	pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4879 	pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4880 	pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4881 	pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4882 	pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4883 	pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4884 	pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4885 	pr_err("%-20s%d\n", "pause filter threshold:",
4886 	       control->pause_filter_thresh);
4887 	pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4888 	pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4889 	pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4890 	pr_err("%-20s%d\n", "asid:", control->asid);
4891 	pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4892 	pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4893 	pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4894 	pr_err("%-20s%08x\n", "int_state:", control->int_state);
4895 	pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4896 	pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4897 	pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4898 	pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4899 	pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4900 	pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4901 	pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4902 	pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4903 	pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4904 	pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4905 	pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4906 	pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4907 	pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4908 	pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4909 	pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4910 	pr_err("VMCB State Save Area:\n");
4911 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4912 	       "es:",
4913 	       save->es.selector, save->es.attrib,
4914 	       save->es.limit, save->es.base);
4915 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4916 	       "cs:",
4917 	       save->cs.selector, save->cs.attrib,
4918 	       save->cs.limit, save->cs.base);
4919 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4920 	       "ss:",
4921 	       save->ss.selector, save->ss.attrib,
4922 	       save->ss.limit, save->ss.base);
4923 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4924 	       "ds:",
4925 	       save->ds.selector, save->ds.attrib,
4926 	       save->ds.limit, save->ds.base);
4927 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4928 	       "fs:",
4929 	       save->fs.selector, save->fs.attrib,
4930 	       save->fs.limit, save->fs.base);
4931 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4932 	       "gs:",
4933 	       save->gs.selector, save->gs.attrib,
4934 	       save->gs.limit, save->gs.base);
4935 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4936 	       "gdtr:",
4937 	       save->gdtr.selector, save->gdtr.attrib,
4938 	       save->gdtr.limit, save->gdtr.base);
4939 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4940 	       "ldtr:",
4941 	       save->ldtr.selector, save->ldtr.attrib,
4942 	       save->ldtr.limit, save->ldtr.base);
4943 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4944 	       "idtr:",
4945 	       save->idtr.selector, save->idtr.attrib,
4946 	       save->idtr.limit, save->idtr.base);
4947 	pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4948 	       "tr:",
4949 	       save->tr.selector, save->tr.attrib,
4950 	       save->tr.limit, save->tr.base);
4951 	pr_err("cpl:            %d                efer:         %016llx\n",
4952 		save->cpl, save->efer);
4953 	pr_err("%-15s %016llx %-13s %016llx\n",
4954 	       "cr0:", save->cr0, "cr2:", save->cr2);
4955 	pr_err("%-15s %016llx %-13s %016llx\n",
4956 	       "cr3:", save->cr3, "cr4:", save->cr4);
4957 	pr_err("%-15s %016llx %-13s %016llx\n",
4958 	       "dr6:", save->dr6, "dr7:", save->dr7);
4959 	pr_err("%-15s %016llx %-13s %016llx\n",
4960 	       "rip:", save->rip, "rflags:", save->rflags);
4961 	pr_err("%-15s %016llx %-13s %016llx\n",
4962 	       "rsp:", save->rsp, "rax:", save->rax);
4963 	pr_err("%-15s %016llx %-13s %016llx\n",
4964 	       "star:", save->star, "lstar:", save->lstar);
4965 	pr_err("%-15s %016llx %-13s %016llx\n",
4966 	       "cstar:", save->cstar, "sfmask:", save->sfmask);
4967 	pr_err("%-15s %016llx %-13s %016llx\n",
4968 	       "kernel_gs_base:", save->kernel_gs_base,
4969 	       "sysenter_cs:", save->sysenter_cs);
4970 	pr_err("%-15s %016llx %-13s %016llx\n",
4971 	       "sysenter_esp:", save->sysenter_esp,
4972 	       "sysenter_eip:", save->sysenter_eip);
4973 	pr_err("%-15s %016llx %-13s %016llx\n",
4974 	       "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
4975 	pr_err("%-15s %016llx %-13s %016llx\n",
4976 	       "br_from:", save->br_from, "br_to:", save->br_to);
4977 	pr_err("%-15s %016llx %-13s %016llx\n",
4978 	       "excp_from:", save->last_excp_from,
4979 	       "excp_to:", save->last_excp_to);
4980 }
4981 
svm_get_exit_info(struct kvm_vcpu * vcpu,u64 * info1,u64 * info2)4982 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
4983 {
4984 	struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
4985 
4986 	*info1 = control->exit_info_1;
4987 	*info2 = control->exit_info_2;
4988 }
4989 
handle_exit(struct kvm_vcpu * vcpu)4990 static int handle_exit(struct kvm_vcpu *vcpu)
4991 {
4992 	struct vcpu_svm *svm = to_svm(vcpu);
4993 	struct kvm_run *kvm_run = vcpu->run;
4994 	u32 exit_code = svm->vmcb->control.exit_code;
4995 
4996 	trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
4997 
4998 	if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
4999 		vcpu->arch.cr0 = svm->vmcb->save.cr0;
5000 	if (npt_enabled)
5001 		vcpu->arch.cr3 = svm->vmcb->save.cr3;
5002 
5003 	if (unlikely(svm->nested.exit_required)) {
5004 		nested_svm_vmexit(svm);
5005 		svm->nested.exit_required = false;
5006 
5007 		return 1;
5008 	}
5009 
5010 	if (is_guest_mode(vcpu)) {
5011 		int vmexit;
5012 
5013 		trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
5014 					svm->vmcb->control.exit_info_1,
5015 					svm->vmcb->control.exit_info_2,
5016 					svm->vmcb->control.exit_int_info,
5017 					svm->vmcb->control.exit_int_info_err,
5018 					KVM_ISA_SVM);
5019 
5020 		vmexit = nested_svm_exit_special(svm);
5021 
5022 		if (vmexit == NESTED_EXIT_CONTINUE)
5023 			vmexit = nested_svm_exit_handled(svm);
5024 
5025 		if (vmexit == NESTED_EXIT_DONE)
5026 			return 1;
5027 	}
5028 
5029 	svm_complete_interrupts(svm);
5030 
5031 	if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
5032 		kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5033 		kvm_run->fail_entry.hardware_entry_failure_reason
5034 			= svm->vmcb->control.exit_code;
5035 		pr_err("KVM: FAILED VMRUN WITH VMCB:\n");
5036 		dump_vmcb(vcpu);
5037 		return 0;
5038 	}
5039 
5040 	if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
5041 	    exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
5042 	    exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
5043 	    exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
5044 		printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
5045 		       "exit_code 0x%x\n",
5046 		       __func__, svm->vmcb->control.exit_int_info,
5047 		       exit_code);
5048 
5049 	if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
5050 	    || !svm_exit_handlers[exit_code]) {
5051 		WARN_ONCE(1, "svm: unexpected exit reason 0x%x\n", exit_code);
5052 		kvm_queue_exception(vcpu, UD_VECTOR);
5053 		return 1;
5054 	}
5055 
5056 	return svm_exit_handlers[exit_code](svm);
5057 }
5058 
reload_tss(struct kvm_vcpu * vcpu)5059 static void reload_tss(struct kvm_vcpu *vcpu)
5060 {
5061 	int cpu = raw_smp_processor_id();
5062 
5063 	struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5064 	sd->tss_desc->type = 9; /* available 32/64-bit TSS */
5065 	load_TR_desc();
5066 }
5067 
pre_sev_run(struct vcpu_svm * svm,int cpu)5068 static void pre_sev_run(struct vcpu_svm *svm, int cpu)
5069 {
5070 	struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5071 	int asid = sev_get_asid(svm->vcpu.kvm);
5072 
5073 	/* Assign the asid allocated with this SEV guest */
5074 	svm->vmcb->control.asid = asid;
5075 
5076 	/*
5077 	 * Flush guest TLB:
5078 	 *
5079 	 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
5080 	 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
5081 	 */
5082 	if (sd->sev_vmcbs[asid] == svm->vmcb &&
5083 	    svm->last_cpu == cpu)
5084 		return;
5085 
5086 	svm->last_cpu = cpu;
5087 	sd->sev_vmcbs[asid] = svm->vmcb;
5088 	svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5089 	mark_dirty(svm->vmcb, VMCB_ASID);
5090 }
5091 
pre_svm_run(struct vcpu_svm * svm)5092 static void pre_svm_run(struct vcpu_svm *svm)
5093 {
5094 	int cpu = raw_smp_processor_id();
5095 
5096 	struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5097 
5098 	if (sev_guest(svm->vcpu.kvm))
5099 		return pre_sev_run(svm, cpu);
5100 
5101 	/* FIXME: handle wraparound of asid_generation */
5102 	if (svm->asid_generation != sd->asid_generation)
5103 		new_asid(svm, sd);
5104 }
5105 
svm_inject_nmi(struct kvm_vcpu * vcpu)5106 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
5107 {
5108 	struct vcpu_svm *svm = to_svm(vcpu);
5109 
5110 	svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
5111 	vcpu->arch.hflags |= HF_NMI_MASK;
5112 	set_intercept(svm, INTERCEPT_IRET);
5113 	++vcpu->stat.nmi_injections;
5114 }
5115 
svm_inject_irq(struct vcpu_svm * svm,int irq)5116 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
5117 {
5118 	struct vmcb_control_area *control;
5119 
5120 	/* The following fields are ignored when AVIC is enabled */
5121 	control = &svm->vmcb->control;
5122 	control->int_vector = irq;
5123 	control->int_ctl &= ~V_INTR_PRIO_MASK;
5124 	control->int_ctl |= V_IRQ_MASK |
5125 		((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
5126 	mark_dirty(svm->vmcb, VMCB_INTR);
5127 }
5128 
svm_set_irq(struct kvm_vcpu * vcpu)5129 static void svm_set_irq(struct kvm_vcpu *vcpu)
5130 {
5131 	struct vcpu_svm *svm = to_svm(vcpu);
5132 
5133 	BUG_ON(!(gif_set(svm)));
5134 
5135 	trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
5136 	++vcpu->stat.irq_injections;
5137 
5138 	svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
5139 		SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
5140 }
5141 
svm_nested_virtualize_tpr(struct kvm_vcpu * vcpu)5142 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
5143 {
5144 	return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
5145 }
5146 
update_cr8_intercept(struct kvm_vcpu * vcpu,int tpr,int irr)5147 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5148 {
5149 	struct vcpu_svm *svm = to_svm(vcpu);
5150 
5151 	if (svm_nested_virtualize_tpr(vcpu) ||
5152 	    kvm_vcpu_apicv_active(vcpu))
5153 		return;
5154 
5155 	clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5156 
5157 	if (irr == -1)
5158 		return;
5159 
5160 	if (tpr >= irr)
5161 		set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5162 }
5163 
svm_set_virtual_apic_mode(struct kvm_vcpu * vcpu)5164 static void svm_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5165 {
5166 	return;
5167 }
5168 
svm_get_enable_apicv(struct kvm_vcpu * vcpu)5169 static bool svm_get_enable_apicv(struct kvm_vcpu *vcpu)
5170 {
5171 	return avic && irqchip_split(vcpu->kvm);
5172 }
5173 
svm_hwapic_irr_update(struct kvm_vcpu * vcpu,int max_irr)5174 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
5175 {
5176 }
5177 
svm_hwapic_isr_update(struct kvm_vcpu * vcpu,int max_isr)5178 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
5179 {
5180 }
5181 
5182 /* Note: Currently only used by Hyper-V. */
svm_refresh_apicv_exec_ctrl(struct kvm_vcpu * vcpu)5183 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5184 {
5185 	struct vcpu_svm *svm = to_svm(vcpu);
5186 	struct vmcb *vmcb = svm->vmcb;
5187 
5188 	if (!kvm_vcpu_apicv_active(&svm->vcpu))
5189 		return;
5190 
5191 	vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
5192 	mark_dirty(vmcb, VMCB_INTR);
5193 }
5194 
svm_load_eoi_exitmap(struct kvm_vcpu * vcpu,u64 * eoi_exit_bitmap)5195 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
5196 {
5197 	return;
5198 }
5199 
svm_deliver_avic_intr(struct kvm_vcpu * vcpu,int vec)5200 static int svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
5201 {
5202 	if (!vcpu->arch.apicv_active)
5203 		return -1;
5204 
5205 	kvm_lapic_set_irr(vec, vcpu->arch.apic);
5206 	smp_mb__after_atomic();
5207 
5208 	if (avic_vcpu_is_running(vcpu))
5209 		wrmsrl(SVM_AVIC_DOORBELL,
5210 		       kvm_cpu_get_apicid(vcpu->cpu));
5211 	else
5212 		kvm_vcpu_wake_up(vcpu);
5213 
5214 	return 0;
5215 }
5216 
svm_dy_apicv_has_pending_interrupt(struct kvm_vcpu * vcpu)5217 static bool svm_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
5218 {
5219 	return false;
5220 }
5221 
svm_ir_list_del(struct vcpu_svm * svm,struct amd_iommu_pi_data * pi)5222 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5223 {
5224 	unsigned long flags;
5225 	struct amd_svm_iommu_ir *cur;
5226 
5227 	spin_lock_irqsave(&svm->ir_list_lock, flags);
5228 	list_for_each_entry(cur, &svm->ir_list, node) {
5229 		if (cur->data != pi->ir_data)
5230 			continue;
5231 		list_del(&cur->node);
5232 		kfree(cur);
5233 		break;
5234 	}
5235 	spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5236 }
5237 
svm_ir_list_add(struct vcpu_svm * svm,struct amd_iommu_pi_data * pi)5238 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5239 {
5240 	int ret = 0;
5241 	unsigned long flags;
5242 	struct amd_svm_iommu_ir *ir;
5243 
5244 	/**
5245 	 * In some cases, the existing irte is updaed and re-set,
5246 	 * so we need to check here if it's already been * added
5247 	 * to the ir_list.
5248 	 */
5249 	if (pi->ir_data && (pi->prev_ga_tag != 0)) {
5250 		struct kvm *kvm = svm->vcpu.kvm;
5251 		u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
5252 		struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
5253 		struct vcpu_svm *prev_svm;
5254 
5255 		if (!prev_vcpu) {
5256 			ret = -EINVAL;
5257 			goto out;
5258 		}
5259 
5260 		prev_svm = to_svm(prev_vcpu);
5261 		svm_ir_list_del(prev_svm, pi);
5262 	}
5263 
5264 	/**
5265 	 * Allocating new amd_iommu_pi_data, which will get
5266 	 * add to the per-vcpu ir_list.
5267 	 */
5268 	ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL);
5269 	if (!ir) {
5270 		ret = -ENOMEM;
5271 		goto out;
5272 	}
5273 	ir->data = pi->ir_data;
5274 
5275 	spin_lock_irqsave(&svm->ir_list_lock, flags);
5276 	list_add(&ir->node, &svm->ir_list);
5277 	spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5278 out:
5279 	return ret;
5280 }
5281 
5282 /**
5283  * Note:
5284  * The HW cannot support posting multicast/broadcast
5285  * interrupts to a vCPU. So, we still use legacy interrupt
5286  * remapping for these kind of interrupts.
5287  *
5288  * For lowest-priority interrupts, we only support
5289  * those with single CPU as the destination, e.g. user
5290  * configures the interrupts via /proc/irq or uses
5291  * irqbalance to make the interrupts single-CPU.
5292  */
5293 static int
get_pi_vcpu_info(struct kvm * kvm,struct kvm_kernel_irq_routing_entry * e,struct vcpu_data * vcpu_info,struct vcpu_svm ** svm)5294 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
5295 		 struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
5296 {
5297 	struct kvm_lapic_irq irq;
5298 	struct kvm_vcpu *vcpu = NULL;
5299 
5300 	kvm_set_msi_irq(kvm, e, &irq);
5301 
5302 	if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
5303 		pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
5304 			 __func__, irq.vector);
5305 		return -1;
5306 	}
5307 
5308 	pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
5309 		 irq.vector);
5310 	*svm = to_svm(vcpu);
5311 	vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
5312 	vcpu_info->vector = irq.vector;
5313 
5314 	return 0;
5315 }
5316 
5317 /*
5318  * svm_update_pi_irte - set IRTE for Posted-Interrupts
5319  *
5320  * @kvm: kvm
5321  * @host_irq: host irq of the interrupt
5322  * @guest_irq: gsi of the interrupt
5323  * @set: set or unset PI
5324  * returns 0 on success, < 0 on failure
5325  */
svm_update_pi_irte(struct kvm * kvm,unsigned int host_irq,uint32_t guest_irq,bool set)5326 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
5327 			      uint32_t guest_irq, bool set)
5328 {
5329 	struct kvm_kernel_irq_routing_entry *e;
5330 	struct kvm_irq_routing_table *irq_rt;
5331 	int idx, ret = -EINVAL;
5332 
5333 	if (!kvm_arch_has_assigned_device(kvm) ||
5334 	    !irq_remapping_cap(IRQ_POSTING_CAP))
5335 		return 0;
5336 
5337 	pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
5338 		 __func__, host_irq, guest_irq, set);
5339 
5340 	idx = srcu_read_lock(&kvm->irq_srcu);
5341 	irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
5342 	WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
5343 
5344 	hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
5345 		struct vcpu_data vcpu_info;
5346 		struct vcpu_svm *svm = NULL;
5347 
5348 		if (e->type != KVM_IRQ_ROUTING_MSI)
5349 			continue;
5350 
5351 		/**
5352 		 * Here, we setup with legacy mode in the following cases:
5353 		 * 1. When cannot target interrupt to a specific vcpu.
5354 		 * 2. Unsetting posted interrupt.
5355 		 * 3. APIC virtialization is disabled for the vcpu.
5356 		 */
5357 		if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
5358 		    kvm_vcpu_apicv_active(&svm->vcpu)) {
5359 			struct amd_iommu_pi_data pi;
5360 
5361 			/* Try to enable guest_mode in IRTE */
5362 			pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
5363 					    AVIC_HPA_MASK);
5364 			pi.ga_tag = AVIC_GATAG(to_kvm_svm(kvm)->avic_vm_id,
5365 						     svm->vcpu.vcpu_id);
5366 			pi.is_guest_mode = true;
5367 			pi.vcpu_data = &vcpu_info;
5368 			ret = irq_set_vcpu_affinity(host_irq, &pi);
5369 
5370 			/**
5371 			 * Here, we successfully setting up vcpu affinity in
5372 			 * IOMMU guest mode. Now, we need to store the posted
5373 			 * interrupt information in a per-vcpu ir_list so that
5374 			 * we can reference to them directly when we update vcpu
5375 			 * scheduling information in IOMMU irte.
5376 			 */
5377 			if (!ret && pi.is_guest_mode)
5378 				svm_ir_list_add(svm, &pi);
5379 		} else {
5380 			/* Use legacy mode in IRTE */
5381 			struct amd_iommu_pi_data pi;
5382 
5383 			/**
5384 			 * Here, pi is used to:
5385 			 * - Tell IOMMU to use legacy mode for this interrupt.
5386 			 * - Retrieve ga_tag of prior interrupt remapping data.
5387 			 */
5388 			pi.prev_ga_tag = 0;
5389 			pi.is_guest_mode = false;
5390 			ret = irq_set_vcpu_affinity(host_irq, &pi);
5391 
5392 			/**
5393 			 * Check if the posted interrupt was previously
5394 			 * setup with the guest_mode by checking if the ga_tag
5395 			 * was cached. If so, we need to clean up the per-vcpu
5396 			 * ir_list.
5397 			 */
5398 			if (!ret && pi.prev_ga_tag) {
5399 				int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
5400 				struct kvm_vcpu *vcpu;
5401 
5402 				vcpu = kvm_get_vcpu_by_id(kvm, id);
5403 				if (vcpu)
5404 					svm_ir_list_del(to_svm(vcpu), &pi);
5405 			}
5406 		}
5407 
5408 		if (!ret && svm) {
5409 			trace_kvm_pi_irte_update(host_irq, svm->vcpu.vcpu_id,
5410 						 e->gsi, vcpu_info.vector,
5411 						 vcpu_info.pi_desc_addr, set);
5412 		}
5413 
5414 		if (ret < 0) {
5415 			pr_err("%s: failed to update PI IRTE\n", __func__);
5416 			goto out;
5417 		}
5418 	}
5419 
5420 	ret = 0;
5421 out:
5422 	srcu_read_unlock(&kvm->irq_srcu, idx);
5423 	return ret;
5424 }
5425 
svm_nmi_allowed(struct kvm_vcpu * vcpu)5426 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
5427 {
5428 	struct vcpu_svm *svm = to_svm(vcpu);
5429 	struct vmcb *vmcb = svm->vmcb;
5430 	int ret;
5431 	ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
5432 	      !(svm->vcpu.arch.hflags & HF_NMI_MASK);
5433 	ret = ret && gif_set(svm) && nested_svm_nmi(svm);
5434 
5435 	return ret;
5436 }
5437 
svm_get_nmi_mask(struct kvm_vcpu * vcpu)5438 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
5439 {
5440 	struct vcpu_svm *svm = to_svm(vcpu);
5441 
5442 	return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
5443 }
5444 
svm_set_nmi_mask(struct kvm_vcpu * vcpu,bool masked)5445 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5446 {
5447 	struct vcpu_svm *svm = to_svm(vcpu);
5448 
5449 	if (masked) {
5450 		svm->vcpu.arch.hflags |= HF_NMI_MASK;
5451 		set_intercept(svm, INTERCEPT_IRET);
5452 	} else {
5453 		svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
5454 		clr_intercept(svm, INTERCEPT_IRET);
5455 	}
5456 }
5457 
svm_interrupt_allowed(struct kvm_vcpu * vcpu)5458 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
5459 {
5460 	struct vcpu_svm *svm = to_svm(vcpu);
5461 	struct vmcb *vmcb = svm->vmcb;
5462 	int ret;
5463 
5464 	if (!gif_set(svm) ||
5465 	     (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
5466 		return 0;
5467 
5468 	ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
5469 
5470 	if (is_guest_mode(vcpu))
5471 		return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
5472 
5473 	return ret;
5474 }
5475 
enable_irq_window(struct kvm_vcpu * vcpu)5476 static void enable_irq_window(struct kvm_vcpu *vcpu)
5477 {
5478 	struct vcpu_svm *svm = to_svm(vcpu);
5479 
5480 	if (kvm_vcpu_apicv_active(vcpu))
5481 		return;
5482 
5483 	/*
5484 	 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
5485 	 * 1, because that's a separate STGI/VMRUN intercept.  The next time we
5486 	 * get that intercept, this function will be called again though and
5487 	 * we'll get the vintr intercept. However, if the vGIF feature is
5488 	 * enabled, the STGI interception will not occur. Enable the irq
5489 	 * window under the assumption that the hardware will set the GIF.
5490 	 */
5491 	if ((vgif_enabled(svm) || gif_set(svm)) && nested_svm_intr(svm)) {
5492 		svm_set_vintr(svm);
5493 		svm_inject_irq(svm, 0x0);
5494 	}
5495 }
5496 
enable_nmi_window(struct kvm_vcpu * vcpu)5497 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5498 {
5499 	struct vcpu_svm *svm = to_svm(vcpu);
5500 
5501 	if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
5502 	    == HF_NMI_MASK)
5503 		return; /* IRET will cause a vm exit */
5504 
5505 	if (!gif_set(svm)) {
5506 		if (vgif_enabled(svm))
5507 			set_intercept(svm, INTERCEPT_STGI);
5508 		return; /* STGI will cause a vm exit */
5509 	}
5510 
5511 	if (svm->nested.exit_required)
5512 		return; /* we're not going to run the guest yet */
5513 
5514 	/*
5515 	 * Something prevents NMI from been injected. Single step over possible
5516 	 * problem (IRET or exception injection or interrupt shadow)
5517 	 */
5518 	svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5519 	svm->nmi_singlestep = true;
5520 	svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5521 }
5522 
svm_set_tss_addr(struct kvm * kvm,unsigned int addr)5523 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5524 {
5525 	return 0;
5526 }
5527 
svm_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)5528 static int svm_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5529 {
5530 	return 0;
5531 }
5532 
svm_flush_tlb(struct kvm_vcpu * vcpu,bool invalidate_gpa)5533 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5534 {
5535 	struct vcpu_svm *svm = to_svm(vcpu);
5536 
5537 	if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5538 		svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5539 	else
5540 		svm->asid_generation--;
5541 }
5542 
svm_flush_tlb_gva(struct kvm_vcpu * vcpu,gva_t gva)5543 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
5544 {
5545 	struct vcpu_svm *svm = to_svm(vcpu);
5546 
5547 	invlpga(gva, svm->vmcb->control.asid);
5548 }
5549 
svm_prepare_guest_switch(struct kvm_vcpu * vcpu)5550 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5551 {
5552 }
5553 
sync_cr8_to_lapic(struct kvm_vcpu * vcpu)5554 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5555 {
5556 	struct vcpu_svm *svm = to_svm(vcpu);
5557 
5558 	if (svm_nested_virtualize_tpr(vcpu))
5559 		return;
5560 
5561 	if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5562 		int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5563 		kvm_set_cr8(vcpu, cr8);
5564 	}
5565 }
5566 
sync_lapic_to_cr8(struct kvm_vcpu * vcpu)5567 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5568 {
5569 	struct vcpu_svm *svm = to_svm(vcpu);
5570 	u64 cr8;
5571 
5572 	if (svm_nested_virtualize_tpr(vcpu) ||
5573 	    kvm_vcpu_apicv_active(vcpu))
5574 		return;
5575 
5576 	cr8 = kvm_get_cr8(vcpu);
5577 	svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5578 	svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5579 }
5580 
svm_complete_interrupts(struct vcpu_svm * svm)5581 static void svm_complete_interrupts(struct vcpu_svm *svm)
5582 {
5583 	u8 vector;
5584 	int type;
5585 	u32 exitintinfo = svm->vmcb->control.exit_int_info;
5586 	unsigned int3_injected = svm->int3_injected;
5587 
5588 	svm->int3_injected = 0;
5589 
5590 	/*
5591 	 * If we've made progress since setting HF_IRET_MASK, we've
5592 	 * executed an IRET and can allow NMI injection.
5593 	 */
5594 	if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5595 	    && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5596 		svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5597 		kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5598 	}
5599 
5600 	svm->vcpu.arch.nmi_injected = false;
5601 	kvm_clear_exception_queue(&svm->vcpu);
5602 	kvm_clear_interrupt_queue(&svm->vcpu);
5603 
5604 	if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5605 		return;
5606 
5607 	kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5608 
5609 	vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5610 	type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5611 
5612 	switch (type) {
5613 	case SVM_EXITINTINFO_TYPE_NMI:
5614 		svm->vcpu.arch.nmi_injected = true;
5615 		break;
5616 	case SVM_EXITINTINFO_TYPE_EXEPT:
5617 		/*
5618 		 * In case of software exceptions, do not reinject the vector,
5619 		 * but re-execute the instruction instead. Rewind RIP first
5620 		 * if we emulated INT3 before.
5621 		 */
5622 		if (kvm_exception_is_soft(vector)) {
5623 			if (vector == BP_VECTOR && int3_injected &&
5624 			    kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5625 				kvm_rip_write(&svm->vcpu,
5626 					      kvm_rip_read(&svm->vcpu) -
5627 					      int3_injected);
5628 			break;
5629 		}
5630 		if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5631 			u32 err = svm->vmcb->control.exit_int_info_err;
5632 			kvm_requeue_exception_e(&svm->vcpu, vector, err);
5633 
5634 		} else
5635 			kvm_requeue_exception(&svm->vcpu, vector);
5636 		break;
5637 	case SVM_EXITINTINFO_TYPE_INTR:
5638 		kvm_queue_interrupt(&svm->vcpu, vector, false);
5639 		break;
5640 	default:
5641 		break;
5642 	}
5643 }
5644 
svm_cancel_injection(struct kvm_vcpu * vcpu)5645 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5646 {
5647 	struct vcpu_svm *svm = to_svm(vcpu);
5648 	struct vmcb_control_area *control = &svm->vmcb->control;
5649 
5650 	control->exit_int_info = control->event_inj;
5651 	control->exit_int_info_err = control->event_inj_err;
5652 	control->event_inj = 0;
5653 	svm_complete_interrupts(svm);
5654 }
5655 
svm_vcpu_run(struct kvm_vcpu * vcpu)5656 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5657 {
5658 	struct vcpu_svm *svm = to_svm(vcpu);
5659 
5660 	svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5661 	svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5662 	svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5663 
5664 	/*
5665 	 * A vmexit emulation is required before the vcpu can be executed
5666 	 * again.
5667 	 */
5668 	if (unlikely(svm->nested.exit_required))
5669 		return;
5670 
5671 	/*
5672 	 * Disable singlestep if we're injecting an interrupt/exception.
5673 	 * We don't want our modified rflags to be pushed on the stack where
5674 	 * we might not be able to easily reset them if we disabled NMI
5675 	 * singlestep later.
5676 	 */
5677 	if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5678 		/*
5679 		 * Event injection happens before external interrupts cause a
5680 		 * vmexit and interrupts are disabled here, so smp_send_reschedule
5681 		 * is enough to force an immediate vmexit.
5682 		 */
5683 		disable_nmi_singlestep(svm);
5684 		smp_send_reschedule(vcpu->cpu);
5685 	}
5686 
5687 	pre_svm_run(svm);
5688 
5689 	sync_lapic_to_cr8(vcpu);
5690 
5691 	svm->vmcb->save.cr2 = vcpu->arch.cr2;
5692 
5693 	clgi();
5694 	kvm_load_guest_xcr0(vcpu);
5695 
5696 	/*
5697 	 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5698 	 * it's non-zero. Since vmentry is serialising on affected CPUs, there
5699 	 * is no need to worry about the conditional branch over the wrmsr
5700 	 * being speculatively taken.
5701 	 */
5702 	x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
5703 
5704 	local_irq_enable();
5705 
5706 	asm volatile (
5707 		"push %%" _ASM_BP "; \n\t"
5708 		"mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5709 		"mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5710 		"mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5711 		"mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5712 		"mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5713 		"mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5714 #ifdef CONFIG_X86_64
5715 		"mov %c[r8](%[svm]),  %%r8  \n\t"
5716 		"mov %c[r9](%[svm]),  %%r9  \n\t"
5717 		"mov %c[r10](%[svm]), %%r10 \n\t"
5718 		"mov %c[r11](%[svm]), %%r11 \n\t"
5719 		"mov %c[r12](%[svm]), %%r12 \n\t"
5720 		"mov %c[r13](%[svm]), %%r13 \n\t"
5721 		"mov %c[r14](%[svm]), %%r14 \n\t"
5722 		"mov %c[r15](%[svm]), %%r15 \n\t"
5723 #endif
5724 
5725 		/* Enter guest mode */
5726 		"push %%" _ASM_AX " \n\t"
5727 		"mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5728 		__ex(SVM_VMLOAD) "\n\t"
5729 		__ex(SVM_VMRUN) "\n\t"
5730 		__ex(SVM_VMSAVE) "\n\t"
5731 		"pop %%" _ASM_AX " \n\t"
5732 
5733 		/* Save guest registers, load host registers */
5734 		"mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5735 		"mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5736 		"mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5737 		"mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5738 		"mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5739 		"mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5740 #ifdef CONFIG_X86_64
5741 		"mov %%r8,  %c[r8](%[svm]) \n\t"
5742 		"mov %%r9,  %c[r9](%[svm]) \n\t"
5743 		"mov %%r10, %c[r10](%[svm]) \n\t"
5744 		"mov %%r11, %c[r11](%[svm]) \n\t"
5745 		"mov %%r12, %c[r12](%[svm]) \n\t"
5746 		"mov %%r13, %c[r13](%[svm]) \n\t"
5747 		"mov %%r14, %c[r14](%[svm]) \n\t"
5748 		"mov %%r15, %c[r15](%[svm]) \n\t"
5749 #endif
5750 		/*
5751 		* Clear host registers marked as clobbered to prevent
5752 		* speculative use.
5753 		*/
5754 		"xor %%" _ASM_BX ", %%" _ASM_BX " \n\t"
5755 		"xor %%" _ASM_CX ", %%" _ASM_CX " \n\t"
5756 		"xor %%" _ASM_DX ", %%" _ASM_DX " \n\t"
5757 		"xor %%" _ASM_SI ", %%" _ASM_SI " \n\t"
5758 		"xor %%" _ASM_DI ", %%" _ASM_DI " \n\t"
5759 #ifdef CONFIG_X86_64
5760 		"xor %%r8, %%r8 \n\t"
5761 		"xor %%r9, %%r9 \n\t"
5762 		"xor %%r10, %%r10 \n\t"
5763 		"xor %%r11, %%r11 \n\t"
5764 		"xor %%r12, %%r12 \n\t"
5765 		"xor %%r13, %%r13 \n\t"
5766 		"xor %%r14, %%r14 \n\t"
5767 		"xor %%r15, %%r15 \n\t"
5768 #endif
5769 		"pop %%" _ASM_BP
5770 		:
5771 		: [svm]"a"(svm),
5772 		  [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5773 		  [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5774 		  [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5775 		  [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5776 		  [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5777 		  [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5778 		  [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5779 #ifdef CONFIG_X86_64
5780 		  , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5781 		  [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5782 		  [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5783 		  [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5784 		  [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5785 		  [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5786 		  [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5787 		  [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5788 #endif
5789 		: "cc", "memory"
5790 #ifdef CONFIG_X86_64
5791 		, "rbx", "rcx", "rdx", "rsi", "rdi"
5792 		, "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5793 #else
5794 		, "ebx", "ecx", "edx", "esi", "edi"
5795 #endif
5796 		);
5797 
5798 	/* Eliminate branch target predictions from guest mode */
5799 	vmexit_fill_RSB();
5800 
5801 #ifdef CONFIG_X86_64
5802 	wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5803 #else
5804 	loadsegment(fs, svm->host.fs);
5805 #ifndef CONFIG_X86_32_LAZY_GS
5806 	loadsegment(gs, svm->host.gs);
5807 #endif
5808 #endif
5809 
5810 	/*
5811 	 * We do not use IBRS in the kernel. If this vCPU has used the
5812 	 * SPEC_CTRL MSR it may have left it on; save the value and
5813 	 * turn it off. This is much more efficient than blindly adding
5814 	 * it to the atomic save/restore list. Especially as the former
5815 	 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5816 	 *
5817 	 * For non-nested case:
5818 	 * If the L01 MSR bitmap does not intercept the MSR, then we need to
5819 	 * save it.
5820 	 *
5821 	 * For nested case:
5822 	 * If the L02 MSR bitmap does not intercept the MSR, then we need to
5823 	 * save it.
5824 	 */
5825 	if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
5826 		svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
5827 
5828 	reload_tss(vcpu);
5829 
5830 	local_irq_disable();
5831 
5832 	x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
5833 
5834 	vcpu->arch.cr2 = svm->vmcb->save.cr2;
5835 	vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5836 	vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5837 	vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5838 
5839 	if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5840 		kvm_before_interrupt(&svm->vcpu);
5841 
5842 	kvm_put_guest_xcr0(vcpu);
5843 	stgi();
5844 
5845 	/* Any pending NMI will happen here */
5846 
5847 	if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5848 		kvm_after_interrupt(&svm->vcpu);
5849 
5850 	sync_cr8_to_lapic(vcpu);
5851 
5852 	svm->next_rip = 0;
5853 
5854 	svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5855 
5856 	/* if exit due to PF check for async PF */
5857 	if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5858 		svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5859 
5860 	if (npt_enabled) {
5861 		vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
5862 		vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
5863 	}
5864 
5865 	/*
5866 	 * We need to handle MC intercepts here before the vcpu has a chance to
5867 	 * change the physical cpu
5868 	 */
5869 	if (unlikely(svm->vmcb->control.exit_code ==
5870 		     SVM_EXIT_EXCP_BASE + MC_VECTOR))
5871 		svm_handle_mce(svm);
5872 
5873 	mark_all_clean(svm->vmcb);
5874 }
5875 STACK_FRAME_NON_STANDARD(svm_vcpu_run);
5876 
svm_set_cr3(struct kvm_vcpu * vcpu,unsigned long root)5877 static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5878 {
5879 	struct vcpu_svm *svm = to_svm(vcpu);
5880 
5881 	svm->vmcb->save.cr3 = __sme_set(root);
5882 	mark_dirty(svm->vmcb, VMCB_CR);
5883 }
5884 
set_tdp_cr3(struct kvm_vcpu * vcpu,unsigned long root)5885 static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5886 {
5887 	struct vcpu_svm *svm = to_svm(vcpu);
5888 
5889 	svm->vmcb->control.nested_cr3 = __sme_set(root);
5890 	mark_dirty(svm->vmcb, VMCB_NPT);
5891 
5892 	/* Also sync guest cr3 here in case we live migrate */
5893 	svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
5894 	mark_dirty(svm->vmcb, VMCB_CR);
5895 }
5896 
is_disabled(void)5897 static int is_disabled(void)
5898 {
5899 	u64 vm_cr;
5900 
5901 	rdmsrl(MSR_VM_CR, vm_cr);
5902 	if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
5903 		return 1;
5904 
5905 	return 0;
5906 }
5907 
5908 static void
svm_patch_hypercall(struct kvm_vcpu * vcpu,unsigned char * hypercall)5909 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5910 {
5911 	/*
5912 	 * Patch in the VMMCALL instruction:
5913 	 */
5914 	hypercall[0] = 0x0f;
5915 	hypercall[1] = 0x01;
5916 	hypercall[2] = 0xd9;
5917 }
5918 
svm_check_processor_compat(void * rtn)5919 static void svm_check_processor_compat(void *rtn)
5920 {
5921 	*(int *)rtn = 0;
5922 }
5923 
svm_cpu_has_accelerated_tpr(void)5924 static bool svm_cpu_has_accelerated_tpr(void)
5925 {
5926 	return false;
5927 }
5928 
svm_has_emulated_msr(int index)5929 static bool svm_has_emulated_msr(int index)
5930 {
5931 	switch (index) {
5932 	case MSR_IA32_MCG_EXT_CTL:
5933 		return false;
5934 	default:
5935 		break;
5936 	}
5937 
5938 	return true;
5939 }
5940 
svm_get_mt_mask(struct kvm_vcpu * vcpu,gfn_t gfn,bool is_mmio)5941 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
5942 {
5943 	return 0;
5944 }
5945 
svm_cpuid_update(struct kvm_vcpu * vcpu)5946 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
5947 {
5948 	struct vcpu_svm *svm = to_svm(vcpu);
5949 
5950 	/* Update nrips enabled cache */
5951 	svm->nrips_enabled = !!guest_cpuid_has(&svm->vcpu, X86_FEATURE_NRIPS);
5952 
5953 	if (!kvm_vcpu_apicv_active(vcpu))
5954 		return;
5955 
5956 	guest_cpuid_clear(vcpu, X86_FEATURE_X2APIC);
5957 }
5958 
svm_set_supported_cpuid(u32 func,struct kvm_cpuid_entry2 * entry)5959 static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
5960 {
5961 	switch (func) {
5962 	case 0x1:
5963 		if (avic)
5964 			entry->ecx &= ~bit(X86_FEATURE_X2APIC);
5965 		break;
5966 	case 0x80000001:
5967 		if (nested)
5968 			entry->ecx |= (1 << 2); /* Set SVM bit */
5969 		break;
5970 	case 0x8000000A:
5971 		entry->eax = 1; /* SVM revision 1 */
5972 		entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
5973 				   ASID emulation to nested SVM */
5974 		entry->ecx = 0; /* Reserved */
5975 		entry->edx = 0; /* Per default do not support any
5976 				   additional features */
5977 
5978 		/* Support next_rip if host supports it */
5979 		if (boot_cpu_has(X86_FEATURE_NRIPS))
5980 			entry->edx |= SVM_FEATURE_NRIP;
5981 
5982 		/* Support NPT for the guest if enabled */
5983 		if (npt_enabled)
5984 			entry->edx |= SVM_FEATURE_NPT;
5985 
5986 		break;
5987 	case 0x8000001F:
5988 		/* Support memory encryption cpuid if host supports it */
5989 		if (boot_cpu_has(X86_FEATURE_SEV))
5990 			cpuid(0x8000001f, &entry->eax, &entry->ebx,
5991 				&entry->ecx, &entry->edx);
5992 
5993 	}
5994 }
5995 
svm_get_lpage_level(void)5996 static int svm_get_lpage_level(void)
5997 {
5998 	return PT_PDPE_LEVEL;
5999 }
6000 
svm_rdtscp_supported(void)6001 static bool svm_rdtscp_supported(void)
6002 {
6003 	return boot_cpu_has(X86_FEATURE_RDTSCP);
6004 }
6005 
svm_invpcid_supported(void)6006 static bool svm_invpcid_supported(void)
6007 {
6008 	return false;
6009 }
6010 
svm_mpx_supported(void)6011 static bool svm_mpx_supported(void)
6012 {
6013 	return false;
6014 }
6015 
svm_xsaves_supported(void)6016 static bool svm_xsaves_supported(void)
6017 {
6018 	return false;
6019 }
6020 
svm_umip_emulated(void)6021 static bool svm_umip_emulated(void)
6022 {
6023 	return false;
6024 }
6025 
svm_has_wbinvd_exit(void)6026 static bool svm_has_wbinvd_exit(void)
6027 {
6028 	return true;
6029 }
6030 
6031 #define PRE_EX(exit)  { .exit_code = (exit), \
6032 			.stage = X86_ICPT_PRE_EXCEPT, }
6033 #define POST_EX(exit) { .exit_code = (exit), \
6034 			.stage = X86_ICPT_POST_EXCEPT, }
6035 #define POST_MEM(exit) { .exit_code = (exit), \
6036 			.stage = X86_ICPT_POST_MEMACCESS, }
6037 
6038 static const struct __x86_intercept {
6039 	u32 exit_code;
6040 	enum x86_intercept_stage stage;
6041 } x86_intercept_map[] = {
6042 	[x86_intercept_cr_read]		= POST_EX(SVM_EXIT_READ_CR0),
6043 	[x86_intercept_cr_write]	= POST_EX(SVM_EXIT_WRITE_CR0),
6044 	[x86_intercept_clts]		= POST_EX(SVM_EXIT_WRITE_CR0),
6045 	[x86_intercept_lmsw]		= POST_EX(SVM_EXIT_WRITE_CR0),
6046 	[x86_intercept_smsw]		= POST_EX(SVM_EXIT_READ_CR0),
6047 	[x86_intercept_dr_read]		= POST_EX(SVM_EXIT_READ_DR0),
6048 	[x86_intercept_dr_write]	= POST_EX(SVM_EXIT_WRITE_DR0),
6049 	[x86_intercept_sldt]		= POST_EX(SVM_EXIT_LDTR_READ),
6050 	[x86_intercept_str]		= POST_EX(SVM_EXIT_TR_READ),
6051 	[x86_intercept_lldt]		= POST_EX(SVM_EXIT_LDTR_WRITE),
6052 	[x86_intercept_ltr]		= POST_EX(SVM_EXIT_TR_WRITE),
6053 	[x86_intercept_sgdt]		= POST_EX(SVM_EXIT_GDTR_READ),
6054 	[x86_intercept_sidt]		= POST_EX(SVM_EXIT_IDTR_READ),
6055 	[x86_intercept_lgdt]		= POST_EX(SVM_EXIT_GDTR_WRITE),
6056 	[x86_intercept_lidt]		= POST_EX(SVM_EXIT_IDTR_WRITE),
6057 	[x86_intercept_vmrun]		= POST_EX(SVM_EXIT_VMRUN),
6058 	[x86_intercept_vmmcall]		= POST_EX(SVM_EXIT_VMMCALL),
6059 	[x86_intercept_vmload]		= POST_EX(SVM_EXIT_VMLOAD),
6060 	[x86_intercept_vmsave]		= POST_EX(SVM_EXIT_VMSAVE),
6061 	[x86_intercept_stgi]		= POST_EX(SVM_EXIT_STGI),
6062 	[x86_intercept_clgi]		= POST_EX(SVM_EXIT_CLGI),
6063 	[x86_intercept_skinit]		= POST_EX(SVM_EXIT_SKINIT),
6064 	[x86_intercept_invlpga]		= POST_EX(SVM_EXIT_INVLPGA),
6065 	[x86_intercept_rdtscp]		= POST_EX(SVM_EXIT_RDTSCP),
6066 	[x86_intercept_monitor]		= POST_MEM(SVM_EXIT_MONITOR),
6067 	[x86_intercept_mwait]		= POST_EX(SVM_EXIT_MWAIT),
6068 	[x86_intercept_invlpg]		= POST_EX(SVM_EXIT_INVLPG),
6069 	[x86_intercept_invd]		= POST_EX(SVM_EXIT_INVD),
6070 	[x86_intercept_wbinvd]		= POST_EX(SVM_EXIT_WBINVD),
6071 	[x86_intercept_wrmsr]		= POST_EX(SVM_EXIT_MSR),
6072 	[x86_intercept_rdtsc]		= POST_EX(SVM_EXIT_RDTSC),
6073 	[x86_intercept_rdmsr]		= POST_EX(SVM_EXIT_MSR),
6074 	[x86_intercept_rdpmc]		= POST_EX(SVM_EXIT_RDPMC),
6075 	[x86_intercept_cpuid]		= PRE_EX(SVM_EXIT_CPUID),
6076 	[x86_intercept_rsm]		= PRE_EX(SVM_EXIT_RSM),
6077 	[x86_intercept_pause]		= PRE_EX(SVM_EXIT_PAUSE),
6078 	[x86_intercept_pushf]		= PRE_EX(SVM_EXIT_PUSHF),
6079 	[x86_intercept_popf]		= PRE_EX(SVM_EXIT_POPF),
6080 	[x86_intercept_intn]		= PRE_EX(SVM_EXIT_SWINT),
6081 	[x86_intercept_iret]		= PRE_EX(SVM_EXIT_IRET),
6082 	[x86_intercept_icebp]		= PRE_EX(SVM_EXIT_ICEBP),
6083 	[x86_intercept_hlt]		= POST_EX(SVM_EXIT_HLT),
6084 	[x86_intercept_in]		= POST_EX(SVM_EXIT_IOIO),
6085 	[x86_intercept_ins]		= POST_EX(SVM_EXIT_IOIO),
6086 	[x86_intercept_out]		= POST_EX(SVM_EXIT_IOIO),
6087 	[x86_intercept_outs]		= POST_EX(SVM_EXIT_IOIO),
6088 };
6089 
6090 #undef PRE_EX
6091 #undef POST_EX
6092 #undef POST_MEM
6093 
svm_check_intercept(struct kvm_vcpu * vcpu,struct x86_instruction_info * info,enum x86_intercept_stage stage)6094 static int svm_check_intercept(struct kvm_vcpu *vcpu,
6095 			       struct x86_instruction_info *info,
6096 			       enum x86_intercept_stage stage)
6097 {
6098 	struct vcpu_svm *svm = to_svm(vcpu);
6099 	int vmexit, ret = X86EMUL_CONTINUE;
6100 	struct __x86_intercept icpt_info;
6101 	struct vmcb *vmcb = svm->vmcb;
6102 
6103 	if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
6104 		goto out;
6105 
6106 	icpt_info = x86_intercept_map[info->intercept];
6107 
6108 	if (stage != icpt_info.stage)
6109 		goto out;
6110 
6111 	switch (icpt_info.exit_code) {
6112 	case SVM_EXIT_READ_CR0:
6113 		if (info->intercept == x86_intercept_cr_read)
6114 			icpt_info.exit_code += info->modrm_reg;
6115 		break;
6116 	case SVM_EXIT_WRITE_CR0: {
6117 		unsigned long cr0, val;
6118 		u64 intercept;
6119 
6120 		if (info->intercept == x86_intercept_cr_write)
6121 			icpt_info.exit_code += info->modrm_reg;
6122 
6123 		if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
6124 		    info->intercept == x86_intercept_clts)
6125 			break;
6126 
6127 		intercept = svm->nested.intercept;
6128 
6129 		if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
6130 			break;
6131 
6132 		cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
6133 		val = info->src_val  & ~SVM_CR0_SELECTIVE_MASK;
6134 
6135 		if (info->intercept == x86_intercept_lmsw) {
6136 			cr0 &= 0xfUL;
6137 			val &= 0xfUL;
6138 			/* lmsw can't clear PE - catch this here */
6139 			if (cr0 & X86_CR0_PE)
6140 				val |= X86_CR0_PE;
6141 		}
6142 
6143 		if (cr0 ^ val)
6144 			icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
6145 
6146 		break;
6147 	}
6148 	case SVM_EXIT_READ_DR0:
6149 	case SVM_EXIT_WRITE_DR0:
6150 		icpt_info.exit_code += info->modrm_reg;
6151 		break;
6152 	case SVM_EXIT_MSR:
6153 		if (info->intercept == x86_intercept_wrmsr)
6154 			vmcb->control.exit_info_1 = 1;
6155 		else
6156 			vmcb->control.exit_info_1 = 0;
6157 		break;
6158 	case SVM_EXIT_PAUSE:
6159 		/*
6160 		 * We get this for NOP only, but pause
6161 		 * is rep not, check this here
6162 		 */
6163 		if (info->rep_prefix != REPE_PREFIX)
6164 			goto out;
6165 		break;
6166 	case SVM_EXIT_IOIO: {
6167 		u64 exit_info;
6168 		u32 bytes;
6169 
6170 		if (info->intercept == x86_intercept_in ||
6171 		    info->intercept == x86_intercept_ins) {
6172 			exit_info = ((info->src_val & 0xffff) << 16) |
6173 				SVM_IOIO_TYPE_MASK;
6174 			bytes = info->dst_bytes;
6175 		} else {
6176 			exit_info = (info->dst_val & 0xffff) << 16;
6177 			bytes = info->src_bytes;
6178 		}
6179 
6180 		if (info->intercept == x86_intercept_outs ||
6181 		    info->intercept == x86_intercept_ins)
6182 			exit_info |= SVM_IOIO_STR_MASK;
6183 
6184 		if (info->rep_prefix)
6185 			exit_info |= SVM_IOIO_REP_MASK;
6186 
6187 		bytes = min(bytes, 4u);
6188 
6189 		exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
6190 
6191 		exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
6192 
6193 		vmcb->control.exit_info_1 = exit_info;
6194 		vmcb->control.exit_info_2 = info->next_rip;
6195 
6196 		break;
6197 	}
6198 	default:
6199 		break;
6200 	}
6201 
6202 	/* TODO: Advertise NRIPS to guest hypervisor unconditionally */
6203 	if (static_cpu_has(X86_FEATURE_NRIPS))
6204 		vmcb->control.next_rip  = info->next_rip;
6205 	vmcb->control.exit_code = icpt_info.exit_code;
6206 	vmexit = nested_svm_exit_handled(svm);
6207 
6208 	ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
6209 					   : X86EMUL_CONTINUE;
6210 
6211 out:
6212 	return ret;
6213 }
6214 
svm_handle_external_intr(struct kvm_vcpu * vcpu)6215 static void svm_handle_external_intr(struct kvm_vcpu *vcpu)
6216 {
6217 	local_irq_enable();
6218 	/*
6219 	 * We must have an instruction with interrupts enabled, so
6220 	 * the timer interrupt isn't delayed by the interrupt shadow.
6221 	 */
6222 	asm("nop");
6223 	local_irq_disable();
6224 }
6225 
svm_sched_in(struct kvm_vcpu * vcpu,int cpu)6226 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
6227 {
6228 	if (pause_filter_thresh)
6229 		shrink_ple_window(vcpu);
6230 }
6231 
avic_post_state_restore(struct kvm_vcpu * vcpu)6232 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu)
6233 {
6234 	if (avic_handle_apic_id_update(vcpu) != 0)
6235 		return;
6236 	if (avic_handle_dfr_update(vcpu) != 0)
6237 		return;
6238 	avic_handle_ldr_update(vcpu);
6239 }
6240 
svm_setup_mce(struct kvm_vcpu * vcpu)6241 static void svm_setup_mce(struct kvm_vcpu *vcpu)
6242 {
6243 	/* [63:9] are reserved. */
6244 	vcpu->arch.mcg_cap &= 0x1ff;
6245 }
6246 
svm_smi_allowed(struct kvm_vcpu * vcpu)6247 static int svm_smi_allowed(struct kvm_vcpu *vcpu)
6248 {
6249 	struct vcpu_svm *svm = to_svm(vcpu);
6250 
6251 	/* Per APM Vol.2 15.22.2 "Response to SMI" */
6252 	if (!gif_set(svm))
6253 		return 0;
6254 
6255 	if (is_guest_mode(&svm->vcpu) &&
6256 	    svm->nested.intercept & (1ULL << INTERCEPT_SMI)) {
6257 		/* TODO: Might need to set exit_info_1 and exit_info_2 here */
6258 		svm->vmcb->control.exit_code = SVM_EXIT_SMI;
6259 		svm->nested.exit_required = true;
6260 		return 0;
6261 	}
6262 
6263 	return 1;
6264 }
6265 
svm_pre_enter_smm(struct kvm_vcpu * vcpu,char * smstate)6266 static int svm_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
6267 {
6268 	struct vcpu_svm *svm = to_svm(vcpu);
6269 	int ret;
6270 
6271 	if (is_guest_mode(vcpu)) {
6272 		/* FED8h - SVM Guest */
6273 		put_smstate(u64, smstate, 0x7ed8, 1);
6274 		/* FEE0h - SVM Guest VMCB Physical Address */
6275 		put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb);
6276 
6277 		svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
6278 		svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
6279 		svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
6280 
6281 		ret = nested_svm_vmexit(svm);
6282 		if (ret)
6283 			return ret;
6284 	}
6285 	return 0;
6286 }
6287 
svm_pre_leave_smm(struct kvm_vcpu * vcpu,u64 smbase)6288 static int svm_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
6289 {
6290 	struct vcpu_svm *svm = to_svm(vcpu);
6291 	struct vmcb *nested_vmcb;
6292 	struct page *page;
6293 	struct {
6294 		u64 guest;
6295 		u64 vmcb;
6296 	} svm_state_save;
6297 	int ret;
6298 
6299 	ret = kvm_vcpu_read_guest(vcpu, smbase + 0xfed8, &svm_state_save,
6300 				  sizeof(svm_state_save));
6301 	if (ret)
6302 		return ret;
6303 
6304 	if (svm_state_save.guest) {
6305 		vcpu->arch.hflags &= ~HF_SMM_MASK;
6306 		nested_vmcb = nested_svm_map(svm, svm_state_save.vmcb, &page);
6307 		if (nested_vmcb)
6308 			enter_svm_guest_mode(svm, svm_state_save.vmcb, nested_vmcb, page);
6309 		else
6310 			ret = 1;
6311 		vcpu->arch.hflags |= HF_SMM_MASK;
6312 	}
6313 	return ret;
6314 }
6315 
enable_smi_window(struct kvm_vcpu * vcpu)6316 static int enable_smi_window(struct kvm_vcpu *vcpu)
6317 {
6318 	struct vcpu_svm *svm = to_svm(vcpu);
6319 
6320 	if (!gif_set(svm)) {
6321 		if (vgif_enabled(svm))
6322 			set_intercept(svm, INTERCEPT_STGI);
6323 		/* STGI will cause a vm exit */
6324 		return 1;
6325 	}
6326 	return 0;
6327 }
6328 
sev_asid_new(void)6329 static int sev_asid_new(void)
6330 {
6331 	int pos;
6332 
6333 	/*
6334 	 * SEV-enabled guest must use asid from min_sev_asid to max_sev_asid.
6335 	 */
6336 	pos = find_next_zero_bit(sev_asid_bitmap, max_sev_asid, min_sev_asid - 1);
6337 	if (pos >= max_sev_asid)
6338 		return -EBUSY;
6339 
6340 	set_bit(pos, sev_asid_bitmap);
6341 	return pos + 1;
6342 }
6343 
sev_guest_init(struct kvm * kvm,struct kvm_sev_cmd * argp)6344 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
6345 {
6346 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6347 	int asid, ret;
6348 
6349 	ret = -EBUSY;
6350 	if (unlikely(sev->active))
6351 		return ret;
6352 
6353 	asid = sev_asid_new();
6354 	if (asid < 0)
6355 		return ret;
6356 
6357 	ret = sev_platform_init(&argp->error);
6358 	if (ret)
6359 		goto e_free;
6360 
6361 	sev->active = true;
6362 	sev->asid = asid;
6363 	INIT_LIST_HEAD(&sev->regions_list);
6364 
6365 	return 0;
6366 
6367 e_free:
6368 	__sev_asid_free(asid);
6369 	return ret;
6370 }
6371 
sev_bind_asid(struct kvm * kvm,unsigned int handle,int * error)6372 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
6373 {
6374 	struct sev_data_activate *data;
6375 	int asid = sev_get_asid(kvm);
6376 	int ret;
6377 
6378 	wbinvd_on_all_cpus();
6379 
6380 	ret = sev_guest_df_flush(error);
6381 	if (ret)
6382 		return ret;
6383 
6384 	data = kzalloc(sizeof(*data), GFP_KERNEL);
6385 	if (!data)
6386 		return -ENOMEM;
6387 
6388 	/* activate ASID on the given handle */
6389 	data->handle = handle;
6390 	data->asid   = asid;
6391 	ret = sev_guest_activate(data, error);
6392 	kfree(data);
6393 
6394 	return ret;
6395 }
6396 
__sev_issue_cmd(int fd,int id,void * data,int * error)6397 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
6398 {
6399 	struct fd f;
6400 	int ret;
6401 
6402 	f = fdget(fd);
6403 	if (!f.file)
6404 		return -EBADF;
6405 
6406 	ret = sev_issue_cmd_external_user(f.file, id, data, error);
6407 
6408 	fdput(f);
6409 	return ret;
6410 }
6411 
sev_issue_cmd(struct kvm * kvm,int id,void * data,int * error)6412 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
6413 {
6414 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6415 
6416 	return __sev_issue_cmd(sev->fd, id, data, error);
6417 }
6418 
sev_launch_start(struct kvm * kvm,struct kvm_sev_cmd * argp)6419 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
6420 {
6421 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6422 	struct sev_data_launch_start *start;
6423 	struct kvm_sev_launch_start params;
6424 	void *dh_blob, *session_blob;
6425 	int *error = &argp->error;
6426 	int ret;
6427 
6428 	if (!sev_guest(kvm))
6429 		return -ENOTTY;
6430 
6431 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6432 		return -EFAULT;
6433 
6434 	start = kzalloc(sizeof(*start), GFP_KERNEL);
6435 	if (!start)
6436 		return -ENOMEM;
6437 
6438 	dh_blob = NULL;
6439 	if (params.dh_uaddr) {
6440 		dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
6441 		if (IS_ERR(dh_blob)) {
6442 			ret = PTR_ERR(dh_blob);
6443 			goto e_free;
6444 		}
6445 
6446 		start->dh_cert_address = __sme_set(__pa(dh_blob));
6447 		start->dh_cert_len = params.dh_len;
6448 	}
6449 
6450 	session_blob = NULL;
6451 	if (params.session_uaddr) {
6452 		session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
6453 		if (IS_ERR(session_blob)) {
6454 			ret = PTR_ERR(session_blob);
6455 			goto e_free_dh;
6456 		}
6457 
6458 		start->session_address = __sme_set(__pa(session_blob));
6459 		start->session_len = params.session_len;
6460 	}
6461 
6462 	start->handle = params.handle;
6463 	start->policy = params.policy;
6464 
6465 	/* create memory encryption context */
6466 	ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, start, error);
6467 	if (ret)
6468 		goto e_free_session;
6469 
6470 	/* Bind ASID to this guest */
6471 	ret = sev_bind_asid(kvm, start->handle, error);
6472 	if (ret)
6473 		goto e_free_session;
6474 
6475 	/* return handle to userspace */
6476 	params.handle = start->handle;
6477 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params))) {
6478 		sev_unbind_asid(kvm, start->handle);
6479 		ret = -EFAULT;
6480 		goto e_free_session;
6481 	}
6482 
6483 	sev->handle = start->handle;
6484 	sev->fd = argp->sev_fd;
6485 
6486 e_free_session:
6487 	kfree(session_blob);
6488 e_free_dh:
6489 	kfree(dh_blob);
6490 e_free:
6491 	kfree(start);
6492 	return ret;
6493 }
6494 
get_num_contig_pages(unsigned long idx,struct page ** inpages,unsigned long npages)6495 static unsigned long get_num_contig_pages(unsigned long idx,
6496 				struct page **inpages, unsigned long npages)
6497 {
6498 	unsigned long paddr, next_paddr;
6499 	unsigned long i = idx + 1, pages = 1;
6500 
6501 	/* find the number of contiguous pages starting from idx */
6502 	paddr = __sme_page_pa(inpages[idx]);
6503 	while (i < npages) {
6504 		next_paddr = __sme_page_pa(inpages[i++]);
6505 		if ((paddr + PAGE_SIZE) == next_paddr) {
6506 			pages++;
6507 			paddr = next_paddr;
6508 			continue;
6509 		}
6510 		break;
6511 	}
6512 
6513 	return pages;
6514 }
6515 
sev_launch_update_data(struct kvm * kvm,struct kvm_sev_cmd * argp)6516 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
6517 {
6518 	unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i;
6519 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6520 	struct kvm_sev_launch_update_data params;
6521 	struct sev_data_launch_update_data *data;
6522 	struct page **inpages;
6523 	int ret;
6524 
6525 	if (!sev_guest(kvm))
6526 		return -ENOTTY;
6527 
6528 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6529 		return -EFAULT;
6530 
6531 	data = kzalloc(sizeof(*data), GFP_KERNEL);
6532 	if (!data)
6533 		return -ENOMEM;
6534 
6535 	vaddr = params.uaddr;
6536 	size = params.len;
6537 	vaddr_end = vaddr + size;
6538 
6539 	/* Lock the user memory. */
6540 	inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
6541 	if (!inpages) {
6542 		ret = -ENOMEM;
6543 		goto e_free;
6544 	}
6545 
6546 	/*
6547 	 * The LAUNCH_UPDATE command will perform in-place encryption of the
6548 	 * memory content (i.e it will write the same memory region with C=1).
6549 	 * It's possible that the cache may contain the data with C=0, i.e.,
6550 	 * unencrypted so invalidate it first.
6551 	 */
6552 	sev_clflush_pages(inpages, npages);
6553 
6554 	for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
6555 		int offset, len;
6556 
6557 		/*
6558 		 * If the user buffer is not page-aligned, calculate the offset
6559 		 * within the page.
6560 		 */
6561 		offset = vaddr & (PAGE_SIZE - 1);
6562 
6563 		/* Calculate the number of pages that can be encrypted in one go. */
6564 		pages = get_num_contig_pages(i, inpages, npages);
6565 
6566 		len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
6567 
6568 		data->handle = sev->handle;
6569 		data->len = len;
6570 		data->address = __sme_page_pa(inpages[i]) + offset;
6571 		ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, data, &argp->error);
6572 		if (ret)
6573 			goto e_unpin;
6574 
6575 		size -= len;
6576 		next_vaddr = vaddr + len;
6577 	}
6578 
6579 e_unpin:
6580 	/* content of memory is updated, mark pages dirty */
6581 	for (i = 0; i < npages; i++) {
6582 		set_page_dirty_lock(inpages[i]);
6583 		mark_page_accessed(inpages[i]);
6584 	}
6585 	/* unlock the user pages */
6586 	sev_unpin_memory(kvm, inpages, npages);
6587 e_free:
6588 	kfree(data);
6589 	return ret;
6590 }
6591 
sev_launch_measure(struct kvm * kvm,struct kvm_sev_cmd * argp)6592 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
6593 {
6594 	void __user *measure = (void __user *)(uintptr_t)argp->data;
6595 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6596 	struct sev_data_launch_measure *data;
6597 	struct kvm_sev_launch_measure params;
6598 	void __user *p = NULL;
6599 	void *blob = NULL;
6600 	int ret;
6601 
6602 	if (!sev_guest(kvm))
6603 		return -ENOTTY;
6604 
6605 	if (copy_from_user(&params, measure, sizeof(params)))
6606 		return -EFAULT;
6607 
6608 	data = kzalloc(sizeof(*data), GFP_KERNEL);
6609 	if (!data)
6610 		return -ENOMEM;
6611 
6612 	/* User wants to query the blob length */
6613 	if (!params.len)
6614 		goto cmd;
6615 
6616 	p = (void __user *)(uintptr_t)params.uaddr;
6617 	if (p) {
6618 		if (params.len > SEV_FW_BLOB_MAX_SIZE) {
6619 			ret = -EINVAL;
6620 			goto e_free;
6621 		}
6622 
6623 		ret = -ENOMEM;
6624 		blob = kmalloc(params.len, GFP_KERNEL);
6625 		if (!blob)
6626 			goto e_free;
6627 
6628 		data->address = __psp_pa(blob);
6629 		data->len = params.len;
6630 	}
6631 
6632 cmd:
6633 	data->handle = sev->handle;
6634 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, data, &argp->error);
6635 
6636 	/*
6637 	 * If we query the session length, FW responded with expected data.
6638 	 */
6639 	if (!params.len)
6640 		goto done;
6641 
6642 	if (ret)
6643 		goto e_free_blob;
6644 
6645 	if (blob) {
6646 		if (copy_to_user(p, blob, params.len))
6647 			ret = -EFAULT;
6648 	}
6649 
6650 done:
6651 	params.len = data->len;
6652 	if (copy_to_user(measure, &params, sizeof(params)))
6653 		ret = -EFAULT;
6654 e_free_blob:
6655 	kfree(blob);
6656 e_free:
6657 	kfree(data);
6658 	return ret;
6659 }
6660 
sev_launch_finish(struct kvm * kvm,struct kvm_sev_cmd * argp)6661 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
6662 {
6663 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6664 	struct sev_data_launch_finish *data;
6665 	int ret;
6666 
6667 	if (!sev_guest(kvm))
6668 		return -ENOTTY;
6669 
6670 	data = kzalloc(sizeof(*data), GFP_KERNEL);
6671 	if (!data)
6672 		return -ENOMEM;
6673 
6674 	data->handle = sev->handle;
6675 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, data, &argp->error);
6676 
6677 	kfree(data);
6678 	return ret;
6679 }
6680 
sev_guest_status(struct kvm * kvm,struct kvm_sev_cmd * argp)6681 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
6682 {
6683 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6684 	struct kvm_sev_guest_status params;
6685 	struct sev_data_guest_status *data;
6686 	int ret;
6687 
6688 	if (!sev_guest(kvm))
6689 		return -ENOTTY;
6690 
6691 	data = kzalloc(sizeof(*data), GFP_KERNEL);
6692 	if (!data)
6693 		return -ENOMEM;
6694 
6695 	data->handle = sev->handle;
6696 	ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, data, &argp->error);
6697 	if (ret)
6698 		goto e_free;
6699 
6700 	params.policy = data->policy;
6701 	params.state = data->state;
6702 	params.handle = data->handle;
6703 
6704 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params)))
6705 		ret = -EFAULT;
6706 e_free:
6707 	kfree(data);
6708 	return ret;
6709 }
6710 
__sev_issue_dbg_cmd(struct kvm * kvm,unsigned long src,unsigned long dst,int size,int * error,bool enc)6711 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
6712 			       unsigned long dst, int size,
6713 			       int *error, bool enc)
6714 {
6715 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6716 	struct sev_data_dbg *data;
6717 	int ret;
6718 
6719 	data = kzalloc(sizeof(*data), GFP_KERNEL);
6720 	if (!data)
6721 		return -ENOMEM;
6722 
6723 	data->handle = sev->handle;
6724 	data->dst_addr = dst;
6725 	data->src_addr = src;
6726 	data->len = size;
6727 
6728 	ret = sev_issue_cmd(kvm,
6729 			    enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
6730 			    data, error);
6731 	kfree(data);
6732 	return ret;
6733 }
6734 
__sev_dbg_decrypt(struct kvm * kvm,unsigned long src_paddr,unsigned long dst_paddr,int sz,int * err)6735 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
6736 			     unsigned long dst_paddr, int sz, int *err)
6737 {
6738 	int offset;
6739 
6740 	/*
6741 	 * Its safe to read more than we are asked, caller should ensure that
6742 	 * destination has enough space.
6743 	 */
6744 	src_paddr = round_down(src_paddr, 16);
6745 	offset = src_paddr & 15;
6746 	sz = round_up(sz + offset, 16);
6747 
6748 	return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
6749 }
6750 
__sev_dbg_decrypt_user(struct kvm * kvm,unsigned long paddr,unsigned long __user dst_uaddr,unsigned long dst_paddr,int size,int * err)6751 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
6752 				  unsigned long __user dst_uaddr,
6753 				  unsigned long dst_paddr,
6754 				  int size, int *err)
6755 {
6756 	struct page *tpage = NULL;
6757 	int ret, offset;
6758 
6759 	/* if inputs are not 16-byte then use intermediate buffer */
6760 	if (!IS_ALIGNED(dst_paddr, 16) ||
6761 	    !IS_ALIGNED(paddr,     16) ||
6762 	    !IS_ALIGNED(size,      16)) {
6763 		tpage = (void *)alloc_page(GFP_KERNEL);
6764 		if (!tpage)
6765 			return -ENOMEM;
6766 
6767 		dst_paddr = __sme_page_pa(tpage);
6768 	}
6769 
6770 	ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
6771 	if (ret)
6772 		goto e_free;
6773 
6774 	if (tpage) {
6775 		offset = paddr & 15;
6776 		if (copy_to_user((void __user *)(uintptr_t)dst_uaddr,
6777 				 page_address(tpage) + offset, size))
6778 			ret = -EFAULT;
6779 	}
6780 
6781 e_free:
6782 	if (tpage)
6783 		__free_page(tpage);
6784 
6785 	return ret;
6786 }
6787 
__sev_dbg_encrypt_user(struct kvm * kvm,unsigned long paddr,unsigned long __user vaddr,unsigned long dst_paddr,unsigned long __user dst_vaddr,int size,int * error)6788 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
6789 				  unsigned long __user vaddr,
6790 				  unsigned long dst_paddr,
6791 				  unsigned long __user dst_vaddr,
6792 				  int size, int *error)
6793 {
6794 	struct page *src_tpage = NULL;
6795 	struct page *dst_tpage = NULL;
6796 	int ret, len = size;
6797 
6798 	/* If source buffer is not aligned then use an intermediate buffer */
6799 	if (!IS_ALIGNED(vaddr, 16)) {
6800 		src_tpage = alloc_page(GFP_KERNEL);
6801 		if (!src_tpage)
6802 			return -ENOMEM;
6803 
6804 		if (copy_from_user(page_address(src_tpage),
6805 				(void __user *)(uintptr_t)vaddr, size)) {
6806 			__free_page(src_tpage);
6807 			return -EFAULT;
6808 		}
6809 
6810 		paddr = __sme_page_pa(src_tpage);
6811 	}
6812 
6813 	/*
6814 	 *  If destination buffer or length is not aligned then do read-modify-write:
6815 	 *   - decrypt destination in an intermediate buffer
6816 	 *   - copy the source buffer in an intermediate buffer
6817 	 *   - use the intermediate buffer as source buffer
6818 	 */
6819 	if (!IS_ALIGNED(dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
6820 		int dst_offset;
6821 
6822 		dst_tpage = alloc_page(GFP_KERNEL);
6823 		if (!dst_tpage) {
6824 			ret = -ENOMEM;
6825 			goto e_free;
6826 		}
6827 
6828 		ret = __sev_dbg_decrypt(kvm, dst_paddr,
6829 					__sme_page_pa(dst_tpage), size, error);
6830 		if (ret)
6831 			goto e_free;
6832 
6833 		/*
6834 		 *  If source is kernel buffer then use memcpy() otherwise
6835 		 *  copy_from_user().
6836 		 */
6837 		dst_offset = dst_paddr & 15;
6838 
6839 		if (src_tpage)
6840 			memcpy(page_address(dst_tpage) + dst_offset,
6841 			       page_address(src_tpage), size);
6842 		else {
6843 			if (copy_from_user(page_address(dst_tpage) + dst_offset,
6844 					   (void __user *)(uintptr_t)vaddr, size)) {
6845 				ret = -EFAULT;
6846 				goto e_free;
6847 			}
6848 		}
6849 
6850 		paddr = __sme_page_pa(dst_tpage);
6851 		dst_paddr = round_down(dst_paddr, 16);
6852 		len = round_up(size, 16);
6853 	}
6854 
6855 	ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
6856 
6857 e_free:
6858 	if (src_tpage)
6859 		__free_page(src_tpage);
6860 	if (dst_tpage)
6861 		__free_page(dst_tpage);
6862 	return ret;
6863 }
6864 
sev_dbg_crypt(struct kvm * kvm,struct kvm_sev_cmd * argp,bool dec)6865 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
6866 {
6867 	unsigned long vaddr, vaddr_end, next_vaddr;
6868 	unsigned long dst_vaddr;
6869 	struct page **src_p, **dst_p;
6870 	struct kvm_sev_dbg debug;
6871 	unsigned long n;
6872 	unsigned int size;
6873 	int ret;
6874 
6875 	if (!sev_guest(kvm))
6876 		return -ENOTTY;
6877 
6878 	if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
6879 		return -EFAULT;
6880 
6881 	if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr)
6882 		return -EINVAL;
6883 	if (!debug.dst_uaddr)
6884 		return -EINVAL;
6885 
6886 	vaddr = debug.src_uaddr;
6887 	size = debug.len;
6888 	vaddr_end = vaddr + size;
6889 	dst_vaddr = debug.dst_uaddr;
6890 
6891 	for (; vaddr < vaddr_end; vaddr = next_vaddr) {
6892 		int len, s_off, d_off;
6893 
6894 		/* lock userspace source and destination page */
6895 		src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
6896 		if (!src_p)
6897 			return -EFAULT;
6898 
6899 		dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
6900 		if (!dst_p) {
6901 			sev_unpin_memory(kvm, src_p, n);
6902 			return -EFAULT;
6903 		}
6904 
6905 		/*
6906 		 * The DBG_{DE,EN}CRYPT commands will perform {dec,en}cryption of the
6907 		 * memory content (i.e it will write the same memory region with C=1).
6908 		 * It's possible that the cache may contain the data with C=0, i.e.,
6909 		 * unencrypted so invalidate it first.
6910 		 */
6911 		sev_clflush_pages(src_p, 1);
6912 		sev_clflush_pages(dst_p, 1);
6913 
6914 		/*
6915 		 * Since user buffer may not be page aligned, calculate the
6916 		 * offset within the page.
6917 		 */
6918 		s_off = vaddr & ~PAGE_MASK;
6919 		d_off = dst_vaddr & ~PAGE_MASK;
6920 		len = min_t(size_t, (PAGE_SIZE - s_off), size);
6921 
6922 		if (dec)
6923 			ret = __sev_dbg_decrypt_user(kvm,
6924 						     __sme_page_pa(src_p[0]) + s_off,
6925 						     dst_vaddr,
6926 						     __sme_page_pa(dst_p[0]) + d_off,
6927 						     len, &argp->error);
6928 		else
6929 			ret = __sev_dbg_encrypt_user(kvm,
6930 						     __sme_page_pa(src_p[0]) + s_off,
6931 						     vaddr,
6932 						     __sme_page_pa(dst_p[0]) + d_off,
6933 						     dst_vaddr,
6934 						     len, &argp->error);
6935 
6936 		sev_unpin_memory(kvm, src_p, n);
6937 		sev_unpin_memory(kvm, dst_p, n);
6938 
6939 		if (ret)
6940 			goto err;
6941 
6942 		next_vaddr = vaddr + len;
6943 		dst_vaddr = dst_vaddr + len;
6944 		size -= len;
6945 	}
6946 err:
6947 	return ret;
6948 }
6949 
sev_launch_secret(struct kvm * kvm,struct kvm_sev_cmd * argp)6950 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
6951 {
6952 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6953 	struct sev_data_launch_secret *data;
6954 	struct kvm_sev_launch_secret params;
6955 	struct page **pages;
6956 	void *blob, *hdr;
6957 	unsigned long n;
6958 	int ret, offset;
6959 
6960 	if (!sev_guest(kvm))
6961 		return -ENOTTY;
6962 
6963 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6964 		return -EFAULT;
6965 
6966 	pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
6967 	if (!pages)
6968 		return -ENOMEM;
6969 
6970 	/*
6971 	 * The secret must be copied into contiguous memory region, lets verify
6972 	 * that userspace memory pages are contiguous before we issue command.
6973 	 */
6974 	if (get_num_contig_pages(0, pages, n) != n) {
6975 		ret = -EINVAL;
6976 		goto e_unpin_memory;
6977 	}
6978 
6979 	ret = -ENOMEM;
6980 	data = kzalloc(sizeof(*data), GFP_KERNEL);
6981 	if (!data)
6982 		goto e_unpin_memory;
6983 
6984 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
6985 	data->guest_address = __sme_page_pa(pages[0]) + offset;
6986 	data->guest_len = params.guest_len;
6987 
6988 	blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
6989 	if (IS_ERR(blob)) {
6990 		ret = PTR_ERR(blob);
6991 		goto e_free;
6992 	}
6993 
6994 	data->trans_address = __psp_pa(blob);
6995 	data->trans_len = params.trans_len;
6996 
6997 	hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
6998 	if (IS_ERR(hdr)) {
6999 		ret = PTR_ERR(hdr);
7000 		goto e_free_blob;
7001 	}
7002 	data->hdr_address = __psp_pa(hdr);
7003 	data->hdr_len = params.hdr_len;
7004 
7005 	data->handle = sev->handle;
7006 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, data, &argp->error);
7007 
7008 	kfree(hdr);
7009 
7010 e_free_blob:
7011 	kfree(blob);
7012 e_free:
7013 	kfree(data);
7014 e_unpin_memory:
7015 	sev_unpin_memory(kvm, pages, n);
7016 	return ret;
7017 }
7018 
svm_mem_enc_op(struct kvm * kvm,void __user * argp)7019 static int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
7020 {
7021 	struct kvm_sev_cmd sev_cmd;
7022 	int r;
7023 
7024 	if (!svm_sev_enabled())
7025 		return -ENOTTY;
7026 
7027 	if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
7028 		return -EFAULT;
7029 
7030 	mutex_lock(&kvm->lock);
7031 
7032 	switch (sev_cmd.id) {
7033 	case KVM_SEV_INIT:
7034 		r = sev_guest_init(kvm, &sev_cmd);
7035 		break;
7036 	case KVM_SEV_LAUNCH_START:
7037 		r = sev_launch_start(kvm, &sev_cmd);
7038 		break;
7039 	case KVM_SEV_LAUNCH_UPDATE_DATA:
7040 		r = sev_launch_update_data(kvm, &sev_cmd);
7041 		break;
7042 	case KVM_SEV_LAUNCH_MEASURE:
7043 		r = sev_launch_measure(kvm, &sev_cmd);
7044 		break;
7045 	case KVM_SEV_LAUNCH_FINISH:
7046 		r = sev_launch_finish(kvm, &sev_cmd);
7047 		break;
7048 	case KVM_SEV_GUEST_STATUS:
7049 		r = sev_guest_status(kvm, &sev_cmd);
7050 		break;
7051 	case KVM_SEV_DBG_DECRYPT:
7052 		r = sev_dbg_crypt(kvm, &sev_cmd, true);
7053 		break;
7054 	case KVM_SEV_DBG_ENCRYPT:
7055 		r = sev_dbg_crypt(kvm, &sev_cmd, false);
7056 		break;
7057 	case KVM_SEV_LAUNCH_SECRET:
7058 		r = sev_launch_secret(kvm, &sev_cmd);
7059 		break;
7060 	default:
7061 		r = -EINVAL;
7062 		goto out;
7063 	}
7064 
7065 	if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
7066 		r = -EFAULT;
7067 
7068 out:
7069 	mutex_unlock(&kvm->lock);
7070 	return r;
7071 }
7072 
svm_register_enc_region(struct kvm * kvm,struct kvm_enc_region * range)7073 static int svm_register_enc_region(struct kvm *kvm,
7074 				   struct kvm_enc_region *range)
7075 {
7076 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7077 	struct enc_region *region;
7078 	int ret = 0;
7079 
7080 	if (!sev_guest(kvm))
7081 		return -ENOTTY;
7082 
7083 	if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
7084 		return -EINVAL;
7085 
7086 	region = kzalloc(sizeof(*region), GFP_KERNEL);
7087 	if (!region)
7088 		return -ENOMEM;
7089 
7090 	region->pages = sev_pin_memory(kvm, range->addr, range->size, &region->npages, 1);
7091 	if (!region->pages) {
7092 		ret = -ENOMEM;
7093 		goto e_free;
7094 	}
7095 
7096 	/*
7097 	 * The guest may change the memory encryption attribute from C=0 -> C=1
7098 	 * or vice versa for this memory range. Lets make sure caches are
7099 	 * flushed to ensure that guest data gets written into memory with
7100 	 * correct C-bit.
7101 	 */
7102 	sev_clflush_pages(region->pages, region->npages);
7103 
7104 	region->uaddr = range->addr;
7105 	region->size = range->size;
7106 
7107 	mutex_lock(&kvm->lock);
7108 	list_add_tail(&region->list, &sev->regions_list);
7109 	mutex_unlock(&kvm->lock);
7110 
7111 	return ret;
7112 
7113 e_free:
7114 	kfree(region);
7115 	return ret;
7116 }
7117 
7118 static struct enc_region *
find_enc_region(struct kvm * kvm,struct kvm_enc_region * range)7119 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
7120 {
7121 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7122 	struct list_head *head = &sev->regions_list;
7123 	struct enc_region *i;
7124 
7125 	list_for_each_entry(i, head, list) {
7126 		if (i->uaddr == range->addr &&
7127 		    i->size == range->size)
7128 			return i;
7129 	}
7130 
7131 	return NULL;
7132 }
7133 
7134 
svm_unregister_enc_region(struct kvm * kvm,struct kvm_enc_region * range)7135 static int svm_unregister_enc_region(struct kvm *kvm,
7136 				     struct kvm_enc_region *range)
7137 {
7138 	struct enc_region *region;
7139 	int ret;
7140 
7141 	mutex_lock(&kvm->lock);
7142 
7143 	if (!sev_guest(kvm)) {
7144 		ret = -ENOTTY;
7145 		goto failed;
7146 	}
7147 
7148 	region = find_enc_region(kvm, range);
7149 	if (!region) {
7150 		ret = -EINVAL;
7151 		goto failed;
7152 	}
7153 
7154 	__unregister_enc_region_locked(kvm, region);
7155 
7156 	mutex_unlock(&kvm->lock);
7157 	return 0;
7158 
7159 failed:
7160 	mutex_unlock(&kvm->lock);
7161 	return ret;
7162 }
7163 
7164 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
7165 	.cpu_has_kvm_support = has_svm,
7166 	.disabled_by_bios = is_disabled,
7167 	.hardware_setup = svm_hardware_setup,
7168 	.hardware_unsetup = svm_hardware_unsetup,
7169 	.check_processor_compatibility = svm_check_processor_compat,
7170 	.hardware_enable = svm_hardware_enable,
7171 	.hardware_disable = svm_hardware_disable,
7172 	.cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
7173 	.has_emulated_msr = svm_has_emulated_msr,
7174 
7175 	.vcpu_create = svm_create_vcpu,
7176 	.vcpu_free = svm_free_vcpu,
7177 	.vcpu_reset = svm_vcpu_reset,
7178 
7179 	.vm_alloc = svm_vm_alloc,
7180 	.vm_free = svm_vm_free,
7181 	.vm_init = avic_vm_init,
7182 	.vm_destroy = svm_vm_destroy,
7183 
7184 	.prepare_guest_switch = svm_prepare_guest_switch,
7185 	.vcpu_load = svm_vcpu_load,
7186 	.vcpu_put = svm_vcpu_put,
7187 	.vcpu_blocking = svm_vcpu_blocking,
7188 	.vcpu_unblocking = svm_vcpu_unblocking,
7189 
7190 	.update_bp_intercept = update_bp_intercept,
7191 	.get_msr_feature = svm_get_msr_feature,
7192 	.get_msr = svm_get_msr,
7193 	.set_msr = svm_set_msr,
7194 	.get_segment_base = svm_get_segment_base,
7195 	.get_segment = svm_get_segment,
7196 	.set_segment = svm_set_segment,
7197 	.get_cpl = svm_get_cpl,
7198 	.get_cs_db_l_bits = kvm_get_cs_db_l_bits,
7199 	.decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
7200 	.decache_cr3 = svm_decache_cr3,
7201 	.decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
7202 	.set_cr0 = svm_set_cr0,
7203 	.set_cr3 = svm_set_cr3,
7204 	.set_cr4 = svm_set_cr4,
7205 	.set_efer = svm_set_efer,
7206 	.get_idt = svm_get_idt,
7207 	.set_idt = svm_set_idt,
7208 	.get_gdt = svm_get_gdt,
7209 	.set_gdt = svm_set_gdt,
7210 	.get_dr6 = svm_get_dr6,
7211 	.set_dr6 = svm_set_dr6,
7212 	.set_dr7 = svm_set_dr7,
7213 	.sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
7214 	.cache_reg = svm_cache_reg,
7215 	.get_rflags = svm_get_rflags,
7216 	.set_rflags = svm_set_rflags,
7217 
7218 	.tlb_flush = svm_flush_tlb,
7219 	.tlb_flush_gva = svm_flush_tlb_gva,
7220 
7221 	.run = svm_vcpu_run,
7222 	.handle_exit = handle_exit,
7223 	.skip_emulated_instruction = skip_emulated_instruction,
7224 	.set_interrupt_shadow = svm_set_interrupt_shadow,
7225 	.get_interrupt_shadow = svm_get_interrupt_shadow,
7226 	.patch_hypercall = svm_patch_hypercall,
7227 	.set_irq = svm_set_irq,
7228 	.set_nmi = svm_inject_nmi,
7229 	.queue_exception = svm_queue_exception,
7230 	.cancel_injection = svm_cancel_injection,
7231 	.interrupt_allowed = svm_interrupt_allowed,
7232 	.nmi_allowed = svm_nmi_allowed,
7233 	.get_nmi_mask = svm_get_nmi_mask,
7234 	.set_nmi_mask = svm_set_nmi_mask,
7235 	.enable_nmi_window = enable_nmi_window,
7236 	.enable_irq_window = enable_irq_window,
7237 	.update_cr8_intercept = update_cr8_intercept,
7238 	.set_virtual_apic_mode = svm_set_virtual_apic_mode,
7239 	.get_enable_apicv = svm_get_enable_apicv,
7240 	.refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
7241 	.load_eoi_exitmap = svm_load_eoi_exitmap,
7242 	.hwapic_irr_update = svm_hwapic_irr_update,
7243 	.hwapic_isr_update = svm_hwapic_isr_update,
7244 	.sync_pir_to_irr = kvm_lapic_find_highest_irr,
7245 	.apicv_post_state_restore = avic_post_state_restore,
7246 
7247 	.set_tss_addr = svm_set_tss_addr,
7248 	.set_identity_map_addr = svm_set_identity_map_addr,
7249 	.get_tdp_level = get_npt_level,
7250 	.get_mt_mask = svm_get_mt_mask,
7251 
7252 	.get_exit_info = svm_get_exit_info,
7253 
7254 	.get_lpage_level = svm_get_lpage_level,
7255 
7256 	.cpuid_update = svm_cpuid_update,
7257 
7258 	.rdtscp_supported = svm_rdtscp_supported,
7259 	.invpcid_supported = svm_invpcid_supported,
7260 	.mpx_supported = svm_mpx_supported,
7261 	.xsaves_supported = svm_xsaves_supported,
7262 	.umip_emulated = svm_umip_emulated,
7263 
7264 	.set_supported_cpuid = svm_set_supported_cpuid,
7265 
7266 	.has_wbinvd_exit = svm_has_wbinvd_exit,
7267 
7268 	.read_l1_tsc_offset = svm_read_l1_tsc_offset,
7269 	.write_l1_tsc_offset = svm_write_l1_tsc_offset,
7270 
7271 	.set_tdp_cr3 = set_tdp_cr3,
7272 
7273 	.check_intercept = svm_check_intercept,
7274 	.handle_external_intr = svm_handle_external_intr,
7275 
7276 	.request_immediate_exit = __kvm_request_immediate_exit,
7277 
7278 	.sched_in = svm_sched_in,
7279 
7280 	.pmu_ops = &amd_pmu_ops,
7281 	.deliver_posted_interrupt = svm_deliver_avic_intr,
7282 	.dy_apicv_has_pending_interrupt = svm_dy_apicv_has_pending_interrupt,
7283 	.update_pi_irte = svm_update_pi_irte,
7284 	.setup_mce = svm_setup_mce,
7285 
7286 	.smi_allowed = svm_smi_allowed,
7287 	.pre_enter_smm = svm_pre_enter_smm,
7288 	.pre_leave_smm = svm_pre_leave_smm,
7289 	.enable_smi_window = enable_smi_window,
7290 
7291 	.mem_enc_op = svm_mem_enc_op,
7292 	.mem_enc_reg_region = svm_register_enc_region,
7293 	.mem_enc_unreg_region = svm_unregister_enc_region,
7294 };
7295 
svm_init(void)7296 static int __init svm_init(void)
7297 {
7298 	return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
7299 			__alignof__(struct vcpu_svm), THIS_MODULE);
7300 }
7301 
svm_exit(void)7302 static void __exit svm_exit(void)
7303 {
7304 	kvm_exit();
7305 }
7306 
7307 module_init(svm_init)
7308 module_exit(svm_exit)
7309