1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * derived from drivers/kvm/kvm_main.c
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright (C) 2008 Qumranet, Inc.
9  * Copyright IBM Corporation, 2008
10  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11  *
12  * Authors:
13  *   Avi Kivity   <avi@qumranet.com>
14  *   Yaniv Kamay  <yaniv@qumranet.com>
15  *   Amit Shah    <amit.shah@qumranet.com>
16  *   Ben-Ami Yassour <benami@il.ibm.com>
17  */
18 
19 #include <linux/kvm_host.h>
20 #include "irq.h"
21 #include "ioapic.h"
22 #include "mmu.h"
23 #include "i8254.h"
24 #include "tss.h"
25 #include "kvm_cache_regs.h"
26 #include "kvm_emulate.h"
27 #include "x86.h"
28 #include "cpuid.h"
29 #include "pmu.h"
30 #include "hyperv.h"
31 #include "lapic.h"
32 #include "xen.h"
33 
34 #include <linux/clocksource.h>
35 #include <linux/interrupt.h>
36 #include <linux/kvm.h>
37 #include <linux/fs.h>
38 #include <linux/vmalloc.h>
39 #include <linux/export.h>
40 #include <linux/moduleparam.h>
41 #include <linux/mman.h>
42 #include <linux/highmem.h>
43 #include <linux/iommu.h>
44 #include <linux/intel-iommu.h>
45 #include <linux/cpufreq.h>
46 #include <linux/user-return-notifier.h>
47 #include <linux/srcu.h>
48 #include <linux/slab.h>
49 #include <linux/perf_event.h>
50 #include <linux/uaccess.h>
51 #include <linux/hash.h>
52 #include <linux/pci.h>
53 #include <linux/timekeeper_internal.h>
54 #include <linux/pvclock_gtod.h>
55 #include <linux/kvm_irqfd.h>
56 #include <linux/irqbypass.h>
57 #include <linux/sched/stat.h>
58 #include <linux/sched/isolation.h>
59 #include <linux/mem_encrypt.h>
60 #include <linux/entry-kvm.h>
61 #include <linux/suspend.h>
62 
63 #include <trace/events/kvm.h>
64 
65 #include <asm/debugreg.h>
66 #include <asm/msr.h>
67 #include <asm/desc.h>
68 #include <asm/mce.h>
69 #include <asm/pkru.h>
70 #include <linux/kernel_stat.h>
71 #include <asm/fpu/api.h>
72 #include <asm/fpu/xcr.h>
73 #include <asm/fpu/xstate.h>
74 #include <asm/pvclock.h>
75 #include <asm/div64.h>
76 #include <asm/irq_remapping.h>
77 #include <asm/mshyperv.h>
78 #include <asm/hypervisor.h>
79 #include <asm/tlbflush.h>
80 #include <asm/intel_pt.h>
81 #include <asm/emulate_prefix.h>
82 #include <asm/sgx.h>
83 #include <clocksource/hyperv_timer.h>
84 
85 #define CREATE_TRACE_POINTS
86 #include "trace.h"
87 
88 #define MAX_IO_MSRS 256
89 #define KVM_MAX_MCE_BANKS 32
90 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
91 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
92 
93 #define  ERR_PTR_USR(e)  ((void __user *)ERR_PTR(e))
94 
95 #define emul_to_vcpu(ctxt) \
96 	((struct kvm_vcpu *)(ctxt)->vcpu)
97 
98 /* EFER defaults:
99  * - enable syscall per default because its emulated by KVM
100  * - enable LME and LMA per default on 64 bit KVM
101  */
102 #ifdef CONFIG_X86_64
103 static
104 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
105 #else
106 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
107 #endif
108 
109 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
110 
111 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
112 
113 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
114 
115 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
116                                     KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
117 
118 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
119 static void process_nmi(struct kvm_vcpu *vcpu);
120 static void process_smi(struct kvm_vcpu *vcpu);
121 static void enter_smm(struct kvm_vcpu *vcpu);
122 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
123 static void store_regs(struct kvm_vcpu *vcpu);
124 static int sync_regs(struct kvm_vcpu *vcpu);
125 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
126 
127 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
128 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
129 
130 struct kvm_x86_ops kvm_x86_ops __read_mostly;
131 
132 #define KVM_X86_OP(func)					     \
133 	DEFINE_STATIC_CALL_NULL(kvm_x86_##func,			     \
134 				*(((struct kvm_x86_ops *)0)->func));
135 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
136 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
137 #include <asm/kvm-x86-ops.h>
138 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
139 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
140 
141 static bool __read_mostly ignore_msrs = 0;
142 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
143 
144 bool __read_mostly report_ignored_msrs = true;
145 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
146 EXPORT_SYMBOL_GPL(report_ignored_msrs);
147 
148 unsigned int min_timer_period_us = 200;
149 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
150 
151 static bool __read_mostly kvmclock_periodic_sync = true;
152 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
153 
154 bool __read_mostly kvm_has_tsc_control;
155 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
156 u32  __read_mostly kvm_max_guest_tsc_khz;
157 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
158 u8   __read_mostly kvm_tsc_scaling_ratio_frac_bits;
159 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
160 u64  __read_mostly kvm_max_tsc_scaling_ratio;
161 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
162 u64 __read_mostly kvm_default_tsc_scaling_ratio;
163 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
164 bool __read_mostly kvm_has_bus_lock_exit;
165 EXPORT_SYMBOL_GPL(kvm_has_bus_lock_exit);
166 
167 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
168 static u32 __read_mostly tsc_tolerance_ppm = 250;
169 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
170 
171 /*
172  * lapic timer advance (tscdeadline mode only) in nanoseconds.  '-1' enables
173  * adaptive tuning starting from default advancement of 1000ns.  '0' disables
174  * advancement entirely.  Any other value is used as-is and disables adaptive
175  * tuning, i.e. allows privileged userspace to set an exact advancement time.
176  */
177 static int __read_mostly lapic_timer_advance_ns = -1;
178 module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
179 
180 static bool __read_mostly vector_hashing = true;
181 module_param(vector_hashing, bool, S_IRUGO);
182 
183 bool __read_mostly enable_vmware_backdoor = false;
184 module_param(enable_vmware_backdoor, bool, S_IRUGO);
185 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
186 
187 static bool __read_mostly force_emulation_prefix = false;
188 module_param(force_emulation_prefix, bool, S_IRUGO);
189 
190 int __read_mostly pi_inject_timer = -1;
191 module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
192 
193 /* Enable/disable PMU virtualization */
194 bool __read_mostly enable_pmu = true;
195 EXPORT_SYMBOL_GPL(enable_pmu);
196 module_param(enable_pmu, bool, 0444);
197 
198 bool __read_mostly eager_page_split = true;
199 module_param(eager_page_split, bool, 0644);
200 
201 /*
202  * Restoring the host value for MSRs that are only consumed when running in
203  * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
204  * returns to userspace, i.e. the kernel can run with the guest's value.
205  */
206 #define KVM_MAX_NR_USER_RETURN_MSRS 16
207 
208 struct kvm_user_return_msrs {
209 	struct user_return_notifier urn;
210 	bool registered;
211 	struct kvm_user_return_msr_values {
212 		u64 host;
213 		u64 curr;
214 	} values[KVM_MAX_NR_USER_RETURN_MSRS];
215 };
216 
217 u32 __read_mostly kvm_nr_uret_msrs;
218 EXPORT_SYMBOL_GPL(kvm_nr_uret_msrs);
219 static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
220 static struct kvm_user_return_msrs __percpu *user_return_msrs;
221 
222 #define KVM_SUPPORTED_XCR0     (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
223 				| XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
224 				| XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
225 				| XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
226 
227 u64 __read_mostly host_efer;
228 EXPORT_SYMBOL_GPL(host_efer);
229 
230 bool __read_mostly allow_smaller_maxphyaddr = 0;
231 EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
232 
233 bool __read_mostly enable_apicv = true;
234 EXPORT_SYMBOL_GPL(enable_apicv);
235 
236 u64 __read_mostly host_xss;
237 EXPORT_SYMBOL_GPL(host_xss);
238 u64 __read_mostly supported_xss;
239 EXPORT_SYMBOL_GPL(supported_xss);
240 
241 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
242 	KVM_GENERIC_VM_STATS(),
243 	STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
244 	STATS_DESC_COUNTER(VM, mmu_pte_write),
245 	STATS_DESC_COUNTER(VM, mmu_pde_zapped),
246 	STATS_DESC_COUNTER(VM, mmu_flooded),
247 	STATS_DESC_COUNTER(VM, mmu_recycled),
248 	STATS_DESC_COUNTER(VM, mmu_cache_miss),
249 	STATS_DESC_ICOUNTER(VM, mmu_unsync),
250 	STATS_DESC_ICOUNTER(VM, pages_4k),
251 	STATS_DESC_ICOUNTER(VM, pages_2m),
252 	STATS_DESC_ICOUNTER(VM, pages_1g),
253 	STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
254 	STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
255 	STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
256 };
257 
258 const struct kvm_stats_header kvm_vm_stats_header = {
259 	.name_size = KVM_STATS_NAME_SIZE,
260 	.num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
261 	.id_offset = sizeof(struct kvm_stats_header),
262 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
263 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
264 		       sizeof(kvm_vm_stats_desc),
265 };
266 
267 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
268 	KVM_GENERIC_VCPU_STATS(),
269 	STATS_DESC_COUNTER(VCPU, pf_taken),
270 	STATS_DESC_COUNTER(VCPU, pf_fixed),
271 	STATS_DESC_COUNTER(VCPU, pf_emulate),
272 	STATS_DESC_COUNTER(VCPU, pf_spurious),
273 	STATS_DESC_COUNTER(VCPU, pf_fast),
274 	STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
275 	STATS_DESC_COUNTER(VCPU, pf_guest),
276 	STATS_DESC_COUNTER(VCPU, tlb_flush),
277 	STATS_DESC_COUNTER(VCPU, invlpg),
278 	STATS_DESC_COUNTER(VCPU, exits),
279 	STATS_DESC_COUNTER(VCPU, io_exits),
280 	STATS_DESC_COUNTER(VCPU, mmio_exits),
281 	STATS_DESC_COUNTER(VCPU, signal_exits),
282 	STATS_DESC_COUNTER(VCPU, irq_window_exits),
283 	STATS_DESC_COUNTER(VCPU, nmi_window_exits),
284 	STATS_DESC_COUNTER(VCPU, l1d_flush),
285 	STATS_DESC_COUNTER(VCPU, halt_exits),
286 	STATS_DESC_COUNTER(VCPU, request_irq_exits),
287 	STATS_DESC_COUNTER(VCPU, irq_exits),
288 	STATS_DESC_COUNTER(VCPU, host_state_reload),
289 	STATS_DESC_COUNTER(VCPU, fpu_reload),
290 	STATS_DESC_COUNTER(VCPU, insn_emulation),
291 	STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
292 	STATS_DESC_COUNTER(VCPU, hypercalls),
293 	STATS_DESC_COUNTER(VCPU, irq_injections),
294 	STATS_DESC_COUNTER(VCPU, nmi_injections),
295 	STATS_DESC_COUNTER(VCPU, req_event),
296 	STATS_DESC_COUNTER(VCPU, nested_run),
297 	STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
298 	STATS_DESC_COUNTER(VCPU, directed_yield_successful),
299 	STATS_DESC_COUNTER(VCPU, preemption_reported),
300 	STATS_DESC_COUNTER(VCPU, preemption_other),
301 	STATS_DESC_IBOOLEAN(VCPU, guest_mode)
302 };
303 
304 const struct kvm_stats_header kvm_vcpu_stats_header = {
305 	.name_size = KVM_STATS_NAME_SIZE,
306 	.num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
307 	.id_offset = sizeof(struct kvm_stats_header),
308 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
309 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
310 		       sizeof(kvm_vcpu_stats_desc),
311 };
312 
313 u64 __read_mostly host_xcr0;
314 u64 __read_mostly supported_xcr0;
315 EXPORT_SYMBOL_GPL(supported_xcr0);
316 
317 static struct kmem_cache *x86_emulator_cache;
318 
319 /*
320  * When called, it means the previous get/set msr reached an invalid msr.
321  * Return true if we want to ignore/silent this failed msr access.
322  */
kvm_msr_ignored_check(u32 msr,u64 data,bool write)323 static bool kvm_msr_ignored_check(u32 msr, u64 data, bool write)
324 {
325 	const char *op = write ? "wrmsr" : "rdmsr";
326 
327 	if (ignore_msrs) {
328 		if (report_ignored_msrs)
329 			kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n",
330 				      op, msr, data);
331 		/* Mask the error */
332 		return true;
333 	} else {
334 		kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
335 				      op, msr, data);
336 		return false;
337 	}
338 }
339 
kvm_alloc_emulator_cache(void)340 static struct kmem_cache *kvm_alloc_emulator_cache(void)
341 {
342 	unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
343 	unsigned int size = sizeof(struct x86_emulate_ctxt);
344 
345 	return kmem_cache_create_usercopy("x86_emulator", size,
346 					  __alignof__(struct x86_emulate_ctxt),
347 					  SLAB_ACCOUNT, useroffset,
348 					  size - useroffset, NULL);
349 }
350 
351 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
352 
kvm_async_pf_hash_reset(struct kvm_vcpu * vcpu)353 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
354 {
355 	int i;
356 	for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
357 		vcpu->arch.apf.gfns[i] = ~0;
358 }
359 
kvm_on_user_return(struct user_return_notifier * urn)360 static void kvm_on_user_return(struct user_return_notifier *urn)
361 {
362 	unsigned slot;
363 	struct kvm_user_return_msrs *msrs
364 		= container_of(urn, struct kvm_user_return_msrs, urn);
365 	struct kvm_user_return_msr_values *values;
366 	unsigned long flags;
367 
368 	/*
369 	 * Disabling irqs at this point since the following code could be
370 	 * interrupted and executed through kvm_arch_hardware_disable()
371 	 */
372 	local_irq_save(flags);
373 	if (msrs->registered) {
374 		msrs->registered = false;
375 		user_return_notifier_unregister(urn);
376 	}
377 	local_irq_restore(flags);
378 	for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
379 		values = &msrs->values[slot];
380 		if (values->host != values->curr) {
381 			wrmsrl(kvm_uret_msrs_list[slot], values->host);
382 			values->curr = values->host;
383 		}
384 	}
385 }
386 
kvm_probe_user_return_msr(u32 msr)387 static int kvm_probe_user_return_msr(u32 msr)
388 {
389 	u64 val;
390 	int ret;
391 
392 	preempt_disable();
393 	ret = rdmsrl_safe(msr, &val);
394 	if (ret)
395 		goto out;
396 	ret = wrmsrl_safe(msr, val);
397 out:
398 	preempt_enable();
399 	return ret;
400 }
401 
kvm_add_user_return_msr(u32 msr)402 int kvm_add_user_return_msr(u32 msr)
403 {
404 	BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
405 
406 	if (kvm_probe_user_return_msr(msr))
407 		return -1;
408 
409 	kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
410 	return kvm_nr_uret_msrs++;
411 }
412 EXPORT_SYMBOL_GPL(kvm_add_user_return_msr);
413 
kvm_find_user_return_msr(u32 msr)414 int kvm_find_user_return_msr(u32 msr)
415 {
416 	int i;
417 
418 	for (i = 0; i < kvm_nr_uret_msrs; ++i) {
419 		if (kvm_uret_msrs_list[i] == msr)
420 			return i;
421 	}
422 	return -1;
423 }
424 EXPORT_SYMBOL_GPL(kvm_find_user_return_msr);
425 
kvm_user_return_msr_cpu_online(void)426 static void kvm_user_return_msr_cpu_online(void)
427 {
428 	unsigned int cpu = smp_processor_id();
429 	struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
430 	u64 value;
431 	int i;
432 
433 	for (i = 0; i < kvm_nr_uret_msrs; ++i) {
434 		rdmsrl_safe(kvm_uret_msrs_list[i], &value);
435 		msrs->values[i].host = value;
436 		msrs->values[i].curr = value;
437 	}
438 }
439 
kvm_set_user_return_msr(unsigned slot,u64 value,u64 mask)440 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
441 {
442 	unsigned int cpu = smp_processor_id();
443 	struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
444 	int err;
445 
446 	value = (value & mask) | (msrs->values[slot].host & ~mask);
447 	if (value == msrs->values[slot].curr)
448 		return 0;
449 	err = wrmsrl_safe(kvm_uret_msrs_list[slot], value);
450 	if (err)
451 		return 1;
452 
453 	msrs->values[slot].curr = value;
454 	if (!msrs->registered) {
455 		msrs->urn.on_user_return = kvm_on_user_return;
456 		user_return_notifier_register(&msrs->urn);
457 		msrs->registered = true;
458 	}
459 	return 0;
460 }
461 EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
462 
drop_user_return_notifiers(void)463 static void drop_user_return_notifiers(void)
464 {
465 	unsigned int cpu = smp_processor_id();
466 	struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
467 
468 	if (msrs->registered)
469 		kvm_on_user_return(&msrs->urn);
470 }
471 
kvm_get_apic_base(struct kvm_vcpu * vcpu)472 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
473 {
474 	return vcpu->arch.apic_base;
475 }
476 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
477 
kvm_get_apic_mode(struct kvm_vcpu * vcpu)478 enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
479 {
480 	return kvm_apic_mode(kvm_get_apic_base(vcpu));
481 }
482 EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
483 
kvm_set_apic_base(struct kvm_vcpu * vcpu,struct msr_data * msr_info)484 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
485 {
486 	enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
487 	enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
488 	u64 reserved_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu) | 0x2ff |
489 		(guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
490 
491 	if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
492 		return 1;
493 	if (!msr_info->host_initiated) {
494 		if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
495 			return 1;
496 		if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
497 			return 1;
498 	}
499 
500 	kvm_lapic_set_base(vcpu, msr_info->data);
501 	kvm_recalculate_apic_map(vcpu->kvm);
502 	return 0;
503 }
504 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
505 
506 /*
507  * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
508  *
509  * Hardware virtualization extension instructions may fault if a reboot turns
510  * off virtualization while processes are running.  Usually after catching the
511  * fault we just panic; during reboot instead the instruction is ignored.
512  */
kvm_spurious_fault(void)513 noinstr void kvm_spurious_fault(void)
514 {
515 	/* Fault while not rebooting.  We want the trace. */
516 	BUG_ON(!kvm_rebooting);
517 }
518 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
519 
520 #define EXCPT_BENIGN		0
521 #define EXCPT_CONTRIBUTORY	1
522 #define EXCPT_PF		2
523 
exception_class(int vector)524 static int exception_class(int vector)
525 {
526 	switch (vector) {
527 	case PF_VECTOR:
528 		return EXCPT_PF;
529 	case DE_VECTOR:
530 	case TS_VECTOR:
531 	case NP_VECTOR:
532 	case SS_VECTOR:
533 	case GP_VECTOR:
534 		return EXCPT_CONTRIBUTORY;
535 	default:
536 		break;
537 	}
538 	return EXCPT_BENIGN;
539 }
540 
541 #define EXCPT_FAULT		0
542 #define EXCPT_TRAP		1
543 #define EXCPT_ABORT		2
544 #define EXCPT_INTERRUPT		3
545 
exception_type(int vector)546 static int exception_type(int vector)
547 {
548 	unsigned int mask;
549 
550 	if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
551 		return EXCPT_INTERRUPT;
552 
553 	mask = 1 << vector;
554 
555 	/* #DB is trap, as instruction watchpoints are handled elsewhere */
556 	if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
557 		return EXCPT_TRAP;
558 
559 	if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
560 		return EXCPT_ABORT;
561 
562 	/* Reserved exceptions will result in fault */
563 	return EXCPT_FAULT;
564 }
565 
kvm_deliver_exception_payload(struct kvm_vcpu * vcpu)566 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
567 {
568 	unsigned nr = vcpu->arch.exception.nr;
569 	bool has_payload = vcpu->arch.exception.has_payload;
570 	unsigned long payload = vcpu->arch.exception.payload;
571 
572 	if (!has_payload)
573 		return;
574 
575 	switch (nr) {
576 	case DB_VECTOR:
577 		/*
578 		 * "Certain debug exceptions may clear bit 0-3.  The
579 		 * remaining contents of the DR6 register are never
580 		 * cleared by the processor".
581 		 */
582 		vcpu->arch.dr6 &= ~DR_TRAP_BITS;
583 		/*
584 		 * In order to reflect the #DB exception payload in guest
585 		 * dr6, three components need to be considered: active low
586 		 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
587 		 * DR6_BS and DR6_BT)
588 		 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
589 		 * In the target guest dr6:
590 		 * FIXED_1 bits should always be set.
591 		 * Active low bits should be cleared if 1-setting in payload.
592 		 * Active high bits should be set if 1-setting in payload.
593 		 *
594 		 * Note, the payload is compatible with the pending debug
595 		 * exceptions/exit qualification under VMX, that active_low bits
596 		 * are active high in payload.
597 		 * So they need to be flipped for DR6.
598 		 */
599 		vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
600 		vcpu->arch.dr6 |= payload;
601 		vcpu->arch.dr6 ^= payload & DR6_ACTIVE_LOW;
602 
603 		/*
604 		 * The #DB payload is defined as compatible with the 'pending
605 		 * debug exceptions' field under VMX, not DR6. While bit 12 is
606 		 * defined in the 'pending debug exceptions' field (enabled
607 		 * breakpoint), it is reserved and must be zero in DR6.
608 		 */
609 		vcpu->arch.dr6 &= ~BIT(12);
610 		break;
611 	case PF_VECTOR:
612 		vcpu->arch.cr2 = payload;
613 		break;
614 	}
615 
616 	vcpu->arch.exception.has_payload = false;
617 	vcpu->arch.exception.payload = 0;
618 }
619 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
620 
kvm_multiple_exception(struct kvm_vcpu * vcpu,unsigned nr,bool has_error,u32 error_code,bool has_payload,unsigned long payload,bool reinject)621 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
622 		unsigned nr, bool has_error, u32 error_code,
623 	        bool has_payload, unsigned long payload, bool reinject)
624 {
625 	u32 prev_nr;
626 	int class1, class2;
627 
628 	kvm_make_request(KVM_REQ_EVENT, vcpu);
629 
630 	if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
631 	queue:
632 		if (reinject) {
633 			/*
634 			 * On vmentry, vcpu->arch.exception.pending is only
635 			 * true if an event injection was blocked by
636 			 * nested_run_pending.  In that case, however,
637 			 * vcpu_enter_guest requests an immediate exit,
638 			 * and the guest shouldn't proceed far enough to
639 			 * need reinjection.
640 			 */
641 			WARN_ON_ONCE(vcpu->arch.exception.pending);
642 			vcpu->arch.exception.injected = true;
643 			if (WARN_ON_ONCE(has_payload)) {
644 				/*
645 				 * A reinjected event has already
646 				 * delivered its payload.
647 				 */
648 				has_payload = false;
649 				payload = 0;
650 			}
651 		} else {
652 			vcpu->arch.exception.pending = true;
653 			vcpu->arch.exception.injected = false;
654 		}
655 		vcpu->arch.exception.has_error_code = has_error;
656 		vcpu->arch.exception.nr = nr;
657 		vcpu->arch.exception.error_code = error_code;
658 		vcpu->arch.exception.has_payload = has_payload;
659 		vcpu->arch.exception.payload = payload;
660 		if (!is_guest_mode(vcpu))
661 			kvm_deliver_exception_payload(vcpu);
662 		return;
663 	}
664 
665 	/* to check exception */
666 	prev_nr = vcpu->arch.exception.nr;
667 	if (prev_nr == DF_VECTOR) {
668 		/* triple fault -> shutdown */
669 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
670 		return;
671 	}
672 	class1 = exception_class(prev_nr);
673 	class2 = exception_class(nr);
674 	if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
675 		|| (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
676 		/*
677 		 * Generate double fault per SDM Table 5-5.  Set
678 		 * exception.pending = true so that the double fault
679 		 * can trigger a nested vmexit.
680 		 */
681 		vcpu->arch.exception.pending = true;
682 		vcpu->arch.exception.injected = false;
683 		vcpu->arch.exception.has_error_code = true;
684 		vcpu->arch.exception.nr = DF_VECTOR;
685 		vcpu->arch.exception.error_code = 0;
686 		vcpu->arch.exception.has_payload = false;
687 		vcpu->arch.exception.payload = 0;
688 	} else
689 		/* replace previous exception with a new one in a hope
690 		   that instruction re-execution will regenerate lost
691 		   exception */
692 		goto queue;
693 }
694 
kvm_queue_exception(struct kvm_vcpu * vcpu,unsigned nr)695 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
696 {
697 	kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
698 }
699 EXPORT_SYMBOL_GPL(kvm_queue_exception);
700 
kvm_requeue_exception(struct kvm_vcpu * vcpu,unsigned nr)701 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
702 {
703 	kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
704 }
705 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
706 
kvm_queue_exception_p(struct kvm_vcpu * vcpu,unsigned nr,unsigned long payload)707 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
708 			   unsigned long payload)
709 {
710 	kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
711 }
712 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
713 
kvm_queue_exception_e_p(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code,unsigned long payload)714 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
715 				    u32 error_code, unsigned long payload)
716 {
717 	kvm_multiple_exception(vcpu, nr, true, error_code,
718 			       true, payload, false);
719 }
720 
kvm_complete_insn_gp(struct kvm_vcpu * vcpu,int err)721 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
722 {
723 	if (err)
724 		kvm_inject_gp(vcpu, 0);
725 	else
726 		return kvm_skip_emulated_instruction(vcpu);
727 
728 	return 1;
729 }
730 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
731 
complete_emulated_insn_gp(struct kvm_vcpu * vcpu,int err)732 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
733 {
734 	if (err) {
735 		kvm_inject_gp(vcpu, 0);
736 		return 1;
737 	}
738 
739 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
740 				       EMULTYPE_COMPLETE_USER_EXIT);
741 }
742 
kvm_inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)743 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
744 {
745 	++vcpu->stat.pf_guest;
746 	vcpu->arch.exception.nested_apf =
747 		is_guest_mode(vcpu) && fault->async_page_fault;
748 	if (vcpu->arch.exception.nested_apf) {
749 		vcpu->arch.apf.nested_apf_token = fault->address;
750 		kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
751 	} else {
752 		kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
753 					fault->address);
754 	}
755 }
756 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
757 
758 /* Returns true if the page fault was immediately morphed into a VM-Exit. */
kvm_inject_emulated_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)759 bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
760 				    struct x86_exception *fault)
761 {
762 	struct kvm_mmu *fault_mmu;
763 	WARN_ON_ONCE(fault->vector != PF_VECTOR);
764 
765 	fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
766 					       vcpu->arch.walk_mmu;
767 
768 	/*
769 	 * Invalidate the TLB entry for the faulting address, if it exists,
770 	 * else the access will fault indefinitely (and to emulate hardware).
771 	 */
772 	if ((fault->error_code & PFERR_PRESENT_MASK) &&
773 	    !(fault->error_code & PFERR_RSVD_MASK))
774 		kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
775 				       fault_mmu->root.hpa);
776 
777 	/*
778 	 * A workaround for KVM's bad exception handling.  If KVM injected an
779 	 * exception into L2, and L2 encountered a #PF while vectoring the
780 	 * injected exception, manually check to see if L1 wants to intercept
781 	 * #PF, otherwise queuing the #PF will lead to #DF or a lost exception.
782 	 * In all other cases, defer the check to nested_ops->check_events(),
783 	 * which will correctly handle priority (this does not).  Note, other
784 	 * exceptions, e.g. #GP, are theoretically affected, #PF is simply the
785 	 * most problematic, e.g. when L0 and L1 are both intercepting #PF for
786 	 * shadow paging.
787 	 *
788 	 * TODO: Rewrite exception handling to track injected and pending
789 	 *       (VM-Exit) exceptions separately.
790 	 */
791 	if (unlikely(vcpu->arch.exception.injected && is_guest_mode(vcpu)) &&
792 	    kvm_x86_ops.nested_ops->handle_page_fault_workaround(vcpu, fault))
793 		return true;
794 
795 	fault_mmu->inject_page_fault(vcpu, fault);
796 	return false;
797 }
798 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
799 
kvm_inject_nmi(struct kvm_vcpu * vcpu)800 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
801 {
802 	atomic_inc(&vcpu->arch.nmi_queued);
803 	kvm_make_request(KVM_REQ_NMI, vcpu);
804 }
805 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
806 
kvm_queue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)807 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
808 {
809 	kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
810 }
811 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
812 
kvm_requeue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)813 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
814 {
815 	kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
816 }
817 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
818 
819 /*
820  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
821  * a #GP and return false.
822  */
kvm_require_cpl(struct kvm_vcpu * vcpu,int required_cpl)823 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
824 {
825 	if (static_call(kvm_x86_get_cpl)(vcpu) <= required_cpl)
826 		return true;
827 	kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
828 	return false;
829 }
830 EXPORT_SYMBOL_GPL(kvm_require_cpl);
831 
kvm_require_dr(struct kvm_vcpu * vcpu,int dr)832 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
833 {
834 	if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
835 		return true;
836 
837 	kvm_queue_exception(vcpu, UD_VECTOR);
838 	return false;
839 }
840 EXPORT_SYMBOL_GPL(kvm_require_dr);
841 
pdptr_rsvd_bits(struct kvm_vcpu * vcpu)842 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
843 {
844 	return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
845 }
846 
847 /*
848  * Load the pae pdptrs.  Return 1 if they are all valid, 0 otherwise.
849  */
load_pdptrs(struct kvm_vcpu * vcpu,unsigned long cr3)850 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
851 {
852 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
853 	gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
854 	gpa_t real_gpa;
855 	int i;
856 	int ret;
857 	u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
858 
859 	/*
860 	 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
861 	 * to an L1 GPA.
862 	 */
863 	real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
864 				     PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
865 	if (real_gpa == UNMAPPED_GVA)
866 		return 0;
867 
868 	/* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
869 	ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
870 				       cr3 & GENMASK(11, 5), sizeof(pdpte));
871 	if (ret < 0)
872 		return 0;
873 
874 	for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
875 		if ((pdpte[i] & PT_PRESENT_MASK) &&
876 		    (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
877 			return 0;
878 		}
879 	}
880 
881 	/*
882 	 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
883 	 * Shadow page roots need to be reconstructed instead.
884 	 */
885 	if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
886 		kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
887 
888 	memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
889 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
890 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
891 	vcpu->arch.pdptrs_from_userspace = false;
892 
893 	return 1;
894 }
895 EXPORT_SYMBOL_GPL(load_pdptrs);
896 
kvm_post_set_cr0(struct kvm_vcpu * vcpu,unsigned long old_cr0,unsigned long cr0)897 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
898 {
899 	if ((cr0 ^ old_cr0) & X86_CR0_PG) {
900 		kvm_clear_async_pf_completion_queue(vcpu);
901 		kvm_async_pf_hash_reset(vcpu);
902 
903 		/*
904 		 * Clearing CR0.PG is defined to flush the TLB from the guest's
905 		 * perspective.
906 		 */
907 		if (!(cr0 & X86_CR0_PG))
908 			kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
909 	}
910 
911 	if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
912 		kvm_mmu_reset_context(vcpu);
913 
914 	if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
915 	    kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
916 	    !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
917 		kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
918 }
919 EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
920 
kvm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)921 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
922 {
923 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
924 
925 	cr0 |= X86_CR0_ET;
926 
927 #ifdef CONFIG_X86_64
928 	if (cr0 & 0xffffffff00000000UL)
929 		return 1;
930 #endif
931 
932 	cr0 &= ~CR0_RESERVED_BITS;
933 
934 	if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
935 		return 1;
936 
937 	if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
938 		return 1;
939 
940 #ifdef CONFIG_X86_64
941 	if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
942 	    (cr0 & X86_CR0_PG)) {
943 		int cs_db, cs_l;
944 
945 		if (!is_pae(vcpu))
946 			return 1;
947 		static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
948 		if (cs_l)
949 			return 1;
950 	}
951 #endif
952 	if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
953 	    is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
954 	    !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
955 		return 1;
956 
957 	if (!(cr0 & X86_CR0_PG) &&
958 	    (is_64_bit_mode(vcpu) || kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)))
959 		return 1;
960 
961 	static_call(kvm_x86_set_cr0)(vcpu, cr0);
962 
963 	kvm_post_set_cr0(vcpu, old_cr0, cr0);
964 
965 	return 0;
966 }
967 EXPORT_SYMBOL_GPL(kvm_set_cr0);
968 
kvm_lmsw(struct kvm_vcpu * vcpu,unsigned long msw)969 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
970 {
971 	(void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
972 }
973 EXPORT_SYMBOL_GPL(kvm_lmsw);
974 
kvm_load_guest_xsave_state(struct kvm_vcpu * vcpu)975 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
976 {
977 	if (vcpu->arch.guest_state_protected)
978 		return;
979 
980 	if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
981 
982 		if (vcpu->arch.xcr0 != host_xcr0)
983 			xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
984 
985 		if (vcpu->arch.xsaves_enabled &&
986 		    vcpu->arch.ia32_xss != host_xss)
987 			wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
988 	}
989 
990 #ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
991 	if (static_cpu_has(X86_FEATURE_PKU) &&
992 	    vcpu->arch.pkru != vcpu->arch.host_pkru &&
993 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
994 	     kvm_read_cr4_bits(vcpu, X86_CR4_PKE)))
995 		write_pkru(vcpu->arch.pkru);
996 #endif /* CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS */
997 }
998 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
999 
kvm_load_host_xsave_state(struct kvm_vcpu * vcpu)1000 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
1001 {
1002 	if (vcpu->arch.guest_state_protected)
1003 		return;
1004 
1005 #ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
1006 	if (static_cpu_has(X86_FEATURE_PKU) &&
1007 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1008 	     kvm_read_cr4_bits(vcpu, X86_CR4_PKE))) {
1009 		vcpu->arch.pkru = rdpkru();
1010 		if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1011 			write_pkru(vcpu->arch.host_pkru);
1012 	}
1013 #endif /* CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS */
1014 
1015 	if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
1016 
1017 		if (vcpu->arch.xcr0 != host_xcr0)
1018 			xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
1019 
1020 		if (vcpu->arch.xsaves_enabled &&
1021 		    vcpu->arch.ia32_xss != host_xss)
1022 			wrmsrl(MSR_IA32_XSS, host_xss);
1023 	}
1024 
1025 }
1026 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
1027 
kvm_guest_supported_xcr0(struct kvm_vcpu * vcpu)1028 static inline u64 kvm_guest_supported_xcr0(struct kvm_vcpu *vcpu)
1029 {
1030 	return vcpu->arch.guest_fpu.fpstate->user_xfeatures;
1031 }
1032 
1033 #ifdef CONFIG_X86_64
kvm_guest_supported_xfd(struct kvm_vcpu * vcpu)1034 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1035 {
1036 	return kvm_guest_supported_xcr0(vcpu) & XFEATURE_MASK_USER_DYNAMIC;
1037 }
1038 #endif
1039 
__kvm_set_xcr(struct kvm_vcpu * vcpu,u32 index,u64 xcr)1040 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1041 {
1042 	u64 xcr0 = xcr;
1043 	u64 old_xcr0 = vcpu->arch.xcr0;
1044 	u64 valid_bits;
1045 
1046 	/* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
1047 	if (index != XCR_XFEATURE_ENABLED_MASK)
1048 		return 1;
1049 	if (!(xcr0 & XFEATURE_MASK_FP))
1050 		return 1;
1051 	if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1052 		return 1;
1053 
1054 	/*
1055 	 * Do not allow the guest to set bits that we do not support
1056 	 * saving.  However, xcr0 bit 0 is always set, even if the
1057 	 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1058 	 */
1059 	valid_bits = kvm_guest_supported_xcr0(vcpu) | XFEATURE_MASK_FP;
1060 	if (xcr0 & ~valid_bits)
1061 		return 1;
1062 
1063 	if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1064 	    (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1065 		return 1;
1066 
1067 	if (xcr0 & XFEATURE_MASK_AVX512) {
1068 		if (!(xcr0 & XFEATURE_MASK_YMM))
1069 			return 1;
1070 		if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1071 			return 1;
1072 	}
1073 
1074 	if ((xcr0 & XFEATURE_MASK_XTILE) &&
1075 	    ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1076 		return 1;
1077 
1078 	vcpu->arch.xcr0 = xcr0;
1079 
1080 	if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1081 		kvm_update_cpuid_runtime(vcpu);
1082 	return 0;
1083 }
1084 
kvm_emulate_xsetbv(struct kvm_vcpu * vcpu)1085 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1086 {
1087 	if (static_call(kvm_x86_get_cpl)(vcpu) != 0 ||
1088 	    __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1089 		kvm_inject_gp(vcpu, 0);
1090 		return 1;
1091 	}
1092 
1093 	return kvm_skip_emulated_instruction(vcpu);
1094 }
1095 EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
1096 
__kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1097 bool __kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1098 {
1099 	if (cr4 & cr4_reserved_bits)
1100 		return false;
1101 
1102 	if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
1103 		return false;
1104 
1105 	return true;
1106 }
1107 EXPORT_SYMBOL_GPL(__kvm_is_valid_cr4);
1108 
kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1109 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1110 {
1111 	return __kvm_is_valid_cr4(vcpu, cr4) &&
1112 	       static_call(kvm_x86_is_valid_cr4)(vcpu, cr4);
1113 }
1114 
kvm_post_set_cr4(struct kvm_vcpu * vcpu,unsigned long old_cr4,unsigned long cr4)1115 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1116 {
1117 	if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1118 		kvm_mmu_reset_context(vcpu);
1119 
1120 	/*
1121 	 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1122 	 * according to the SDM; however, stale prev_roots could be reused
1123 	 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1124 	 * free them all.  This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1125 	 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1126 	 * so fall through.
1127 	 */
1128 	if (!tdp_enabled &&
1129 	    (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1130 		kvm_mmu_unload(vcpu);
1131 
1132 	/*
1133 	 * The TLB has to be flushed for all PCIDs if any of the following
1134 	 * (architecturally required) changes happen:
1135 	 * - CR4.PCIDE is changed from 1 to 0
1136 	 * - CR4.PGE is toggled
1137 	 *
1138 	 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1139 	 */
1140 	if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1141 	    (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1142 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1143 
1144 	/*
1145 	 * The TLB has to be flushed for the current PCID if any of the
1146 	 * following (architecturally required) changes happen:
1147 	 * - CR4.SMEP is changed from 0 to 1
1148 	 * - CR4.PAE is toggled
1149 	 */
1150 	else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1151 		 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1152 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1153 
1154 }
1155 EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
1156 
kvm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1157 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1158 {
1159 	unsigned long old_cr4 = kvm_read_cr4(vcpu);
1160 
1161 	if (!kvm_is_valid_cr4(vcpu, cr4))
1162 		return 1;
1163 
1164 	if (is_long_mode(vcpu)) {
1165 		if (!(cr4 & X86_CR4_PAE))
1166 			return 1;
1167 		if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1168 			return 1;
1169 	} else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1170 		   && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1171 		   && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1172 		return 1;
1173 
1174 	if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1175 		if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
1176 			return 1;
1177 
1178 		/* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1179 		if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1180 			return 1;
1181 	}
1182 
1183 	static_call(kvm_x86_set_cr4)(vcpu, cr4);
1184 
1185 	kvm_post_set_cr4(vcpu, old_cr4, cr4);
1186 
1187 	return 0;
1188 }
1189 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1190 
kvm_invalidate_pcid(struct kvm_vcpu * vcpu,unsigned long pcid)1191 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1192 {
1193 	struct kvm_mmu *mmu = vcpu->arch.mmu;
1194 	unsigned long roots_to_free = 0;
1195 	int i;
1196 
1197 	/*
1198 	 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1199 	 * this is reachable when running EPT=1 and unrestricted_guest=0,  and
1200 	 * also via the emulator.  KVM's TDP page tables are not in the scope of
1201 	 * the invalidation, but the guest's TLB entries need to be flushed as
1202 	 * the CPU may have cached entries in its TLB for the target PCID.
1203 	 */
1204 	if (unlikely(tdp_enabled)) {
1205 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1206 		return;
1207 	}
1208 
1209 	/*
1210 	 * If neither the current CR3 nor any of the prev_roots use the given
1211 	 * PCID, then nothing needs to be done here because a resync will
1212 	 * happen anyway before switching to any other CR3.
1213 	 */
1214 	if (kvm_get_active_pcid(vcpu) == pcid) {
1215 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1216 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1217 	}
1218 
1219 	/*
1220 	 * If PCID is disabled, there is no need to free prev_roots even if the
1221 	 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1222 	 * with PCIDE=0.
1223 	 */
1224 	if (!kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
1225 		return;
1226 
1227 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1228 		if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1229 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1230 
1231 	kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1232 }
1233 
kvm_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)1234 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1235 {
1236 	bool skip_tlb_flush = false;
1237 	unsigned long pcid = 0;
1238 #ifdef CONFIG_X86_64
1239 	bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1240 
1241 	if (pcid_enabled) {
1242 		skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1243 		cr3 &= ~X86_CR3_PCID_NOFLUSH;
1244 		pcid = cr3 & X86_CR3_PCID_MASK;
1245 	}
1246 #endif
1247 
1248 	/* PDPTRs are always reloaded for PAE paging. */
1249 	if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1250 		goto handle_tlb_flush;
1251 
1252 	/*
1253 	 * Do not condition the GPA check on long mode, this helper is used to
1254 	 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1255 	 * the current vCPU mode is accurate.
1256 	 */
1257 	if (kvm_vcpu_is_illegal_gpa(vcpu, cr3))
1258 		return 1;
1259 
1260 	if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1261 		return 1;
1262 
1263 	if (cr3 != kvm_read_cr3(vcpu))
1264 		kvm_mmu_new_pgd(vcpu, cr3);
1265 
1266 	vcpu->arch.cr3 = cr3;
1267 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1268 	/* Do not call post_set_cr3, we do not get here for confidential guests.  */
1269 
1270 handle_tlb_flush:
1271 	/*
1272 	 * A load of CR3 that flushes the TLB flushes only the current PCID,
1273 	 * even if PCID is disabled, in which case PCID=0 is flushed.  It's a
1274 	 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1275 	 * and it's impossible to use a non-zero PCID when PCID is disabled,
1276 	 * i.e. only PCID=0 can be relevant.
1277 	 */
1278 	if (!skip_tlb_flush)
1279 		kvm_invalidate_pcid(vcpu, pcid);
1280 
1281 	return 0;
1282 }
1283 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1284 
kvm_set_cr8(struct kvm_vcpu * vcpu,unsigned long cr8)1285 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1286 {
1287 	if (cr8 & CR8_RESERVED_BITS)
1288 		return 1;
1289 	if (lapic_in_kernel(vcpu))
1290 		kvm_lapic_set_tpr(vcpu, cr8);
1291 	else
1292 		vcpu->arch.cr8 = cr8;
1293 	return 0;
1294 }
1295 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1296 
kvm_get_cr8(struct kvm_vcpu * vcpu)1297 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1298 {
1299 	if (lapic_in_kernel(vcpu))
1300 		return kvm_lapic_get_cr8(vcpu);
1301 	else
1302 		return vcpu->arch.cr8;
1303 }
1304 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1305 
kvm_update_dr0123(struct kvm_vcpu * vcpu)1306 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1307 {
1308 	int i;
1309 
1310 	if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1311 		for (i = 0; i < KVM_NR_DB_REGS; i++)
1312 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1313 	}
1314 }
1315 
kvm_update_dr7(struct kvm_vcpu * vcpu)1316 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1317 {
1318 	unsigned long dr7;
1319 
1320 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1321 		dr7 = vcpu->arch.guest_debug_dr7;
1322 	else
1323 		dr7 = vcpu->arch.dr7;
1324 	static_call(kvm_x86_set_dr7)(vcpu, dr7);
1325 	vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1326 	if (dr7 & DR7_BP_EN_MASK)
1327 		vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1328 }
1329 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1330 
kvm_dr6_fixed(struct kvm_vcpu * vcpu)1331 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1332 {
1333 	u64 fixed = DR6_FIXED_1;
1334 
1335 	if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1336 		fixed |= DR6_RTM;
1337 
1338 	if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1339 		fixed |= DR6_BUS_LOCK;
1340 	return fixed;
1341 }
1342 
kvm_set_dr(struct kvm_vcpu * vcpu,int dr,unsigned long val)1343 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1344 {
1345 	size_t size = ARRAY_SIZE(vcpu->arch.db);
1346 
1347 	switch (dr) {
1348 	case 0 ... 3:
1349 		vcpu->arch.db[array_index_nospec(dr, size)] = val;
1350 		if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1351 			vcpu->arch.eff_db[dr] = val;
1352 		break;
1353 	case 4:
1354 	case 6:
1355 		if (!kvm_dr6_valid(val))
1356 			return 1; /* #GP */
1357 		vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1358 		break;
1359 	case 5:
1360 	default: /* 7 */
1361 		if (!kvm_dr7_valid(val))
1362 			return 1; /* #GP */
1363 		vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1364 		kvm_update_dr7(vcpu);
1365 		break;
1366 	}
1367 
1368 	return 0;
1369 }
1370 EXPORT_SYMBOL_GPL(kvm_set_dr);
1371 
kvm_get_dr(struct kvm_vcpu * vcpu,int dr,unsigned long * val)1372 void kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1373 {
1374 	size_t size = ARRAY_SIZE(vcpu->arch.db);
1375 
1376 	switch (dr) {
1377 	case 0 ... 3:
1378 		*val = vcpu->arch.db[array_index_nospec(dr, size)];
1379 		break;
1380 	case 4:
1381 	case 6:
1382 		*val = vcpu->arch.dr6;
1383 		break;
1384 	case 5:
1385 	default: /* 7 */
1386 		*val = vcpu->arch.dr7;
1387 		break;
1388 	}
1389 }
1390 EXPORT_SYMBOL_GPL(kvm_get_dr);
1391 
kvm_emulate_rdpmc(struct kvm_vcpu * vcpu)1392 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1393 {
1394 	u32 ecx = kvm_rcx_read(vcpu);
1395 	u64 data;
1396 
1397 	if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1398 		kvm_inject_gp(vcpu, 0);
1399 		return 1;
1400 	}
1401 
1402 	kvm_rax_write(vcpu, (u32)data);
1403 	kvm_rdx_write(vcpu, data >> 32);
1404 	return kvm_skip_emulated_instruction(vcpu);
1405 }
1406 EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
1407 
1408 /*
1409  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1410  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1411  *
1412  * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1413  * extract the supported MSRs from the related const lists.
1414  * msrs_to_save is selected from the msrs_to_save_all to reflect the
1415  * capabilities of the host cpu. This capabilities test skips MSRs that are
1416  * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
1417  * may depend on host virtualization features rather than host cpu features.
1418  */
1419 
1420 static const u32 msrs_to_save_all[] = {
1421 	MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1422 	MSR_STAR,
1423 #ifdef CONFIG_X86_64
1424 	MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1425 #endif
1426 	MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1427 	MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1428 	MSR_IA32_SPEC_CTRL,
1429 	MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1430 	MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1431 	MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1432 	MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1433 	MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1434 	MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1435 	MSR_IA32_UMWAIT_CONTROL,
1436 
1437 	MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
1438 	MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
1439 	MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1440 	MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1441 	MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1442 	MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1443 	MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1444 	MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1445 	MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1446 	MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1447 	MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1448 	MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1449 	MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1450 	MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1451 	MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1452 	MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1453 	MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1454 	MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1455 	MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1456 	MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1457 	MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1458 	MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
1459 
1460 	MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
1461 	MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
1462 	MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
1463 	MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
1464 	MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
1465 	MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
1466 	MSR_IA32_XFD, MSR_IA32_XFD_ERR,
1467 };
1468 
1469 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
1470 static unsigned num_msrs_to_save;
1471 
1472 static const u32 emulated_msrs_all[] = {
1473 	MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1474 	MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1475 	HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1476 	HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1477 	HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1478 	HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1479 	HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1480 	HV_X64_MSR_RESET,
1481 	HV_X64_MSR_VP_INDEX,
1482 	HV_X64_MSR_VP_RUNTIME,
1483 	HV_X64_MSR_SCONTROL,
1484 	HV_X64_MSR_STIMER0_CONFIG,
1485 	HV_X64_MSR_VP_ASSIST_PAGE,
1486 	HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1487 	HV_X64_MSR_TSC_EMULATION_STATUS,
1488 	HV_X64_MSR_SYNDBG_OPTIONS,
1489 	HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1490 	HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1491 	HV_X64_MSR_SYNDBG_PENDING_BUFFER,
1492 
1493 	MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1494 	MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
1495 
1496 	MSR_IA32_TSC_ADJUST,
1497 	MSR_IA32_TSC_DEADLINE,
1498 	MSR_IA32_ARCH_CAPABILITIES,
1499 	MSR_IA32_PERF_CAPABILITIES,
1500 	MSR_IA32_MISC_ENABLE,
1501 	MSR_IA32_MCG_STATUS,
1502 	MSR_IA32_MCG_CTL,
1503 	MSR_IA32_MCG_EXT_CTL,
1504 	MSR_IA32_SMBASE,
1505 	MSR_SMI_COUNT,
1506 	MSR_PLATFORM_INFO,
1507 	MSR_MISC_FEATURES_ENABLES,
1508 	MSR_AMD64_VIRT_SPEC_CTRL,
1509 	MSR_AMD64_TSC_RATIO,
1510 	MSR_IA32_POWER_CTL,
1511 	MSR_IA32_UCODE_REV,
1512 
1513 	/*
1514 	 * The following list leaves out MSRs whose values are determined
1515 	 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1516 	 * We always support the "true" VMX control MSRs, even if the host
1517 	 * processor does not, so I am putting these registers here rather
1518 	 * than in msrs_to_save_all.
1519 	 */
1520 	MSR_IA32_VMX_BASIC,
1521 	MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1522 	MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1523 	MSR_IA32_VMX_TRUE_EXIT_CTLS,
1524 	MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1525 	MSR_IA32_VMX_MISC,
1526 	MSR_IA32_VMX_CR0_FIXED0,
1527 	MSR_IA32_VMX_CR4_FIXED0,
1528 	MSR_IA32_VMX_VMCS_ENUM,
1529 	MSR_IA32_VMX_PROCBASED_CTLS2,
1530 	MSR_IA32_VMX_EPT_VPID_CAP,
1531 	MSR_IA32_VMX_VMFUNC,
1532 
1533 	MSR_K7_HWCR,
1534 	MSR_KVM_POLL_CONTROL,
1535 };
1536 
1537 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
1538 static unsigned num_emulated_msrs;
1539 
1540 /*
1541  * List of msr numbers which are used to expose MSR-based features that
1542  * can be used by a hypervisor to validate requested CPU features.
1543  */
1544 static const u32 msr_based_features_all[] = {
1545 	MSR_IA32_VMX_BASIC,
1546 	MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1547 	MSR_IA32_VMX_PINBASED_CTLS,
1548 	MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1549 	MSR_IA32_VMX_PROCBASED_CTLS,
1550 	MSR_IA32_VMX_TRUE_EXIT_CTLS,
1551 	MSR_IA32_VMX_EXIT_CTLS,
1552 	MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1553 	MSR_IA32_VMX_ENTRY_CTLS,
1554 	MSR_IA32_VMX_MISC,
1555 	MSR_IA32_VMX_CR0_FIXED0,
1556 	MSR_IA32_VMX_CR0_FIXED1,
1557 	MSR_IA32_VMX_CR4_FIXED0,
1558 	MSR_IA32_VMX_CR4_FIXED1,
1559 	MSR_IA32_VMX_VMCS_ENUM,
1560 	MSR_IA32_VMX_PROCBASED_CTLS2,
1561 	MSR_IA32_VMX_EPT_VPID_CAP,
1562 	MSR_IA32_VMX_VMFUNC,
1563 
1564 	MSR_F10H_DECFG,
1565 	MSR_IA32_UCODE_REV,
1566 	MSR_IA32_ARCH_CAPABILITIES,
1567 	MSR_IA32_PERF_CAPABILITIES,
1568 };
1569 
1570 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
1571 static unsigned int num_msr_based_features;
1572 
1573 /*
1574  * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1575  * does not yet virtualize. These include:
1576  *   10 - MISC_PACKAGE_CTRLS
1577  *   11 - ENERGY_FILTERING_CTL
1578  *   12 - DOITM
1579  *   18 - FB_CLEAR_CTRL
1580  *   21 - XAPIC_DISABLE_STATUS
1581  *   23 - OVERCLOCKING_STATUS
1582  */
1583 
1584 #define KVM_SUPPORTED_ARCH_CAP \
1585 	(ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1586 	 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1587 	 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1588 	 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1589 	 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO)
1590 
kvm_get_arch_capabilities(void)1591 static u64 kvm_get_arch_capabilities(void)
1592 {
1593 	u64 data = 0;
1594 
1595 	if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
1596 		rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
1597 		data &= KVM_SUPPORTED_ARCH_CAP;
1598 	}
1599 
1600 	/*
1601 	 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1602 	 * the nested hypervisor runs with NX huge pages.  If it is not,
1603 	 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1604 	 * L1 guests, so it need not worry about its own (L2) guests.
1605 	 */
1606 	data |= ARCH_CAP_PSCHANGE_MC_NO;
1607 
1608 	/*
1609 	 * If we're doing cache flushes (either "always" or "cond")
1610 	 * we will do one whenever the guest does a vmlaunch/vmresume.
1611 	 * If an outer hypervisor is doing the cache flush for us
1612 	 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1613 	 * capability to the guest too, and if EPT is disabled we're not
1614 	 * vulnerable.  Overall, only VMENTER_L1D_FLUSH_NEVER will
1615 	 * require a nested hypervisor to do a flush of its own.
1616 	 */
1617 	if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1618 		data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1619 
1620 	if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1621 		data |= ARCH_CAP_RDCL_NO;
1622 	if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1623 		data |= ARCH_CAP_SSB_NO;
1624 	if (!boot_cpu_has_bug(X86_BUG_MDS))
1625 		data |= ARCH_CAP_MDS_NO;
1626 
1627 	if (!boot_cpu_has(X86_FEATURE_RTM)) {
1628 		/*
1629 		 * If RTM=0 because the kernel has disabled TSX, the host might
1630 		 * have TAA_NO or TSX_CTRL.  Clear TAA_NO (the guest sees RTM=0
1631 		 * and therefore knows that there cannot be TAA) but keep
1632 		 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1633 		 * and we want to allow migrating those guests to tsx=off hosts.
1634 		 */
1635 		data &= ~ARCH_CAP_TAA_NO;
1636 	} else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1637 		data |= ARCH_CAP_TAA_NO;
1638 	} else {
1639 		/*
1640 		 * Nothing to do here; we emulate TSX_CTRL if present on the
1641 		 * host so the guest can choose between disabling TSX or
1642 		 * using VERW to clear CPU buffers.
1643 		 */
1644 	}
1645 
1646 	return data;
1647 }
1648 
kvm_get_msr_feature(struct kvm_msr_entry * msr)1649 static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1650 {
1651 	switch (msr->index) {
1652 	case MSR_IA32_ARCH_CAPABILITIES:
1653 		msr->data = kvm_get_arch_capabilities();
1654 		break;
1655 	case MSR_IA32_UCODE_REV:
1656 		rdmsrl_safe(msr->index, &msr->data);
1657 		break;
1658 	default:
1659 		return static_call(kvm_x86_get_msr_feature)(msr);
1660 	}
1661 	return 0;
1662 }
1663 
do_get_msr_feature(struct kvm_vcpu * vcpu,unsigned index,u64 * data)1664 static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1665 {
1666 	struct kvm_msr_entry msr;
1667 	int r;
1668 
1669 	msr.index = index;
1670 	r = kvm_get_msr_feature(&msr);
1671 
1672 	if (r == KVM_MSR_RET_INVALID) {
1673 		/* Unconditionally clear the output for simplicity */
1674 		*data = 0;
1675 		if (kvm_msr_ignored_check(index, 0, false))
1676 			r = 0;
1677 	}
1678 
1679 	if (r)
1680 		return r;
1681 
1682 	*data = msr.data;
1683 
1684 	return 0;
1685 }
1686 
__kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1687 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1688 {
1689 	if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1690 		return false;
1691 
1692 	if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1693 		return false;
1694 
1695 	if (efer & (EFER_LME | EFER_LMA) &&
1696 	    !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1697 		return false;
1698 
1699 	if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1700 		return false;
1701 
1702 	return true;
1703 
1704 }
kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1705 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1706 {
1707 	if (efer & efer_reserved_bits)
1708 		return false;
1709 
1710 	return __kvm_valid_efer(vcpu, efer);
1711 }
1712 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1713 
set_efer(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1714 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1715 {
1716 	u64 old_efer = vcpu->arch.efer;
1717 	u64 efer = msr_info->data;
1718 	int r;
1719 
1720 	if (efer & efer_reserved_bits)
1721 		return 1;
1722 
1723 	if (!msr_info->host_initiated) {
1724 		if (!__kvm_valid_efer(vcpu, efer))
1725 			return 1;
1726 
1727 		if (is_paging(vcpu) &&
1728 		    (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1729 			return 1;
1730 	}
1731 
1732 	efer &= ~EFER_LMA;
1733 	efer |= vcpu->arch.efer & EFER_LMA;
1734 
1735 	r = static_call(kvm_x86_set_efer)(vcpu, efer);
1736 	if (r) {
1737 		WARN_ON(r > 0);
1738 		return r;
1739 	}
1740 
1741 	if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1742 		kvm_mmu_reset_context(vcpu);
1743 
1744 	return 0;
1745 }
1746 
kvm_enable_efer_bits(u64 mask)1747 void kvm_enable_efer_bits(u64 mask)
1748 {
1749        efer_reserved_bits &= ~mask;
1750 }
1751 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1752 
kvm_msr_allowed(struct kvm_vcpu * vcpu,u32 index,u32 type)1753 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1754 {
1755 	struct kvm_x86_msr_filter *msr_filter;
1756 	struct msr_bitmap_range *ranges;
1757 	struct kvm *kvm = vcpu->kvm;
1758 	bool allowed;
1759 	int idx;
1760 	u32 i;
1761 
1762 	/* x2APIC MSRs do not support filtering. */
1763 	if (index >= 0x800 && index <= 0x8ff)
1764 		return true;
1765 
1766 	idx = srcu_read_lock(&kvm->srcu);
1767 
1768 	msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1769 	if (!msr_filter) {
1770 		allowed = true;
1771 		goto out;
1772 	}
1773 
1774 	allowed = msr_filter->default_allow;
1775 	ranges = msr_filter->ranges;
1776 
1777 	for (i = 0; i < msr_filter->count; i++) {
1778 		u32 start = ranges[i].base;
1779 		u32 end = start + ranges[i].nmsrs;
1780 		u32 flags = ranges[i].flags;
1781 		unsigned long *bitmap = ranges[i].bitmap;
1782 
1783 		if ((index >= start) && (index < end) && (flags & type)) {
1784 			allowed = !!test_bit(index - start, bitmap);
1785 			break;
1786 		}
1787 	}
1788 
1789 out:
1790 	srcu_read_unlock(&kvm->srcu, idx);
1791 
1792 	return allowed;
1793 }
1794 EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1795 
1796 /*
1797  * Write @data into the MSR specified by @index.  Select MSR specific fault
1798  * checks are bypassed if @host_initiated is %true.
1799  * Returns 0 on success, non-0 otherwise.
1800  * Assumes vcpu_load() was already called.
1801  */
__kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1802 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1803 			 bool host_initiated)
1804 {
1805 	struct msr_data msr;
1806 
1807 	switch (index) {
1808 	case MSR_FS_BASE:
1809 	case MSR_GS_BASE:
1810 	case MSR_KERNEL_GS_BASE:
1811 	case MSR_CSTAR:
1812 	case MSR_LSTAR:
1813 		if (is_noncanonical_address(data, vcpu))
1814 			return 1;
1815 		break;
1816 	case MSR_IA32_SYSENTER_EIP:
1817 	case MSR_IA32_SYSENTER_ESP:
1818 		/*
1819 		 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1820 		 * non-canonical address is written on Intel but not on
1821 		 * AMD (which ignores the top 32-bits, because it does
1822 		 * not implement 64-bit SYSENTER).
1823 		 *
1824 		 * 64-bit code should hence be able to write a non-canonical
1825 		 * value on AMD.  Making the address canonical ensures that
1826 		 * vmentry does not fail on Intel after writing a non-canonical
1827 		 * value, and that something deterministic happens if the guest
1828 		 * invokes 64-bit SYSENTER.
1829 		 */
1830 		data = __canonical_address(data, vcpu_virt_addr_bits(vcpu));
1831 		break;
1832 	case MSR_TSC_AUX:
1833 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1834 			return 1;
1835 
1836 		if (!host_initiated &&
1837 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1838 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1839 			return 1;
1840 
1841 		/*
1842 		 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1843 		 * incomplete and conflicting architectural behavior.  Current
1844 		 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1845 		 * reserved and always read as zeros.  Enforce Intel's reserved
1846 		 * bits check if and only if the guest CPU is Intel, and clear
1847 		 * the bits in all other cases.  This ensures cross-vendor
1848 		 * migration will provide consistent behavior for the guest.
1849 		 */
1850 		if (guest_cpuid_is_intel(vcpu) && (data >> 32) != 0)
1851 			return 1;
1852 
1853 		data = (u32)data;
1854 		break;
1855 	}
1856 
1857 	msr.data = data;
1858 	msr.index = index;
1859 	msr.host_initiated = host_initiated;
1860 
1861 	return static_call(kvm_x86_set_msr)(vcpu, &msr);
1862 }
1863 
kvm_set_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1864 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1865 				     u32 index, u64 data, bool host_initiated)
1866 {
1867 	int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1868 
1869 	if (ret == KVM_MSR_RET_INVALID)
1870 		if (kvm_msr_ignored_check(index, data, true))
1871 			ret = 0;
1872 
1873 	return ret;
1874 }
1875 
1876 /*
1877  * Read the MSR specified by @index into @data.  Select MSR specific fault
1878  * checks are bypassed if @host_initiated is %true.
1879  * Returns 0 on success, non-0 otherwise.
1880  * Assumes vcpu_load() was already called.
1881  */
__kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1882 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1883 		  bool host_initiated)
1884 {
1885 	struct msr_data msr;
1886 	int ret;
1887 
1888 	switch (index) {
1889 	case MSR_TSC_AUX:
1890 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1891 			return 1;
1892 
1893 		if (!host_initiated &&
1894 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1895 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1896 			return 1;
1897 		break;
1898 	}
1899 
1900 	msr.index = index;
1901 	msr.host_initiated = host_initiated;
1902 
1903 	ret = static_call(kvm_x86_get_msr)(vcpu, &msr);
1904 	if (!ret)
1905 		*data = msr.data;
1906 	return ret;
1907 }
1908 
kvm_get_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1909 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1910 				     u32 index, u64 *data, bool host_initiated)
1911 {
1912 	int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1913 
1914 	if (ret == KVM_MSR_RET_INVALID) {
1915 		/* Unconditionally clear *data for simplicity */
1916 		*data = 0;
1917 		if (kvm_msr_ignored_check(index, 0, false))
1918 			ret = 0;
1919 	}
1920 
1921 	return ret;
1922 }
1923 
kvm_get_msr_with_filter(struct kvm_vcpu * vcpu,u32 index,u64 * data)1924 static int kvm_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1925 {
1926 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1927 		return KVM_MSR_RET_FILTERED;
1928 	return kvm_get_msr_ignored_check(vcpu, index, data, false);
1929 }
1930 
kvm_set_msr_with_filter(struct kvm_vcpu * vcpu,u32 index,u64 data)1931 static int kvm_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 data)
1932 {
1933 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1934 		return KVM_MSR_RET_FILTERED;
1935 	return kvm_set_msr_ignored_check(vcpu, index, data, false);
1936 }
1937 
kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data)1938 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1939 {
1940 	return kvm_get_msr_ignored_check(vcpu, index, data, false);
1941 }
1942 EXPORT_SYMBOL_GPL(kvm_get_msr);
1943 
kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data)1944 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1945 {
1946 	return kvm_set_msr_ignored_check(vcpu, index, data, false);
1947 }
1948 EXPORT_SYMBOL_GPL(kvm_set_msr);
1949 
complete_userspace_rdmsr(struct kvm_vcpu * vcpu)1950 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
1951 {
1952 	if (!vcpu->run->msr.error) {
1953 		kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1954 		kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1955 	}
1956 }
1957 
complete_emulated_msr_access(struct kvm_vcpu * vcpu)1958 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
1959 {
1960 	return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
1961 }
1962 
complete_emulated_rdmsr(struct kvm_vcpu * vcpu)1963 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1964 {
1965 	complete_userspace_rdmsr(vcpu);
1966 	return complete_emulated_msr_access(vcpu);
1967 }
1968 
complete_fast_msr_access(struct kvm_vcpu * vcpu)1969 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
1970 {
1971 	return static_call(kvm_x86_complete_emulated_msr)(vcpu, vcpu->run->msr.error);
1972 }
1973 
complete_fast_rdmsr(struct kvm_vcpu * vcpu)1974 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
1975 {
1976 	complete_userspace_rdmsr(vcpu);
1977 	return complete_fast_msr_access(vcpu);
1978 }
1979 
kvm_msr_reason(int r)1980 static u64 kvm_msr_reason(int r)
1981 {
1982 	switch (r) {
1983 	case KVM_MSR_RET_INVALID:
1984 		return KVM_MSR_EXIT_REASON_UNKNOWN;
1985 	case KVM_MSR_RET_FILTERED:
1986 		return KVM_MSR_EXIT_REASON_FILTER;
1987 	default:
1988 		return KVM_MSR_EXIT_REASON_INVAL;
1989 	}
1990 }
1991 
kvm_msr_user_space(struct kvm_vcpu * vcpu,u32 index,u32 exit_reason,u64 data,int (* completion)(struct kvm_vcpu * vcpu),int r)1992 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
1993 			      u32 exit_reason, u64 data,
1994 			      int (*completion)(struct kvm_vcpu *vcpu),
1995 			      int r)
1996 {
1997 	u64 msr_reason = kvm_msr_reason(r);
1998 
1999 	/* Check if the user wanted to know about this MSR fault */
2000 	if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2001 		return 0;
2002 
2003 	vcpu->run->exit_reason = exit_reason;
2004 	vcpu->run->msr.error = 0;
2005 	memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2006 	vcpu->run->msr.reason = msr_reason;
2007 	vcpu->run->msr.index = index;
2008 	vcpu->run->msr.data = data;
2009 	vcpu->arch.complete_userspace_io = completion;
2010 
2011 	return 1;
2012 }
2013 
kvm_emulate_rdmsr(struct kvm_vcpu * vcpu)2014 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2015 {
2016 	u32 ecx = kvm_rcx_read(vcpu);
2017 	u64 data;
2018 	int r;
2019 
2020 	r = kvm_get_msr_with_filter(vcpu, ecx, &data);
2021 
2022 	if (!r) {
2023 		trace_kvm_msr_read(ecx, data);
2024 
2025 		kvm_rax_write(vcpu, data & -1u);
2026 		kvm_rdx_write(vcpu, (data >> 32) & -1u);
2027 	} else {
2028 		/* MSR read failed? See if we should ask user space */
2029 		if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
2030 				       complete_fast_rdmsr, r))
2031 			return 0;
2032 		trace_kvm_msr_read_ex(ecx);
2033 	}
2034 
2035 	return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
2036 }
2037 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
2038 
kvm_emulate_wrmsr(struct kvm_vcpu * vcpu)2039 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2040 {
2041 	u32 ecx = kvm_rcx_read(vcpu);
2042 	u64 data = kvm_read_edx_eax(vcpu);
2043 	int r;
2044 
2045 	r = kvm_set_msr_with_filter(vcpu, ecx, data);
2046 
2047 	if (!r) {
2048 		trace_kvm_msr_write(ecx, data);
2049 	} else {
2050 		/* MSR write failed? See if we should ask user space */
2051 		if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
2052 				       complete_fast_msr_access, r))
2053 			return 0;
2054 		/* Signal all other negative errors to userspace */
2055 		if (r < 0)
2056 			return r;
2057 		trace_kvm_msr_write_ex(ecx, data);
2058 	}
2059 
2060 	return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
2061 }
2062 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
2063 
kvm_emulate_as_nop(struct kvm_vcpu * vcpu)2064 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2065 {
2066 	return kvm_skip_emulated_instruction(vcpu);
2067 }
2068 EXPORT_SYMBOL_GPL(kvm_emulate_as_nop);
2069 
kvm_emulate_invd(struct kvm_vcpu * vcpu)2070 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2071 {
2072 	/* Treat an INVD instruction as a NOP and just skip it. */
2073 	return kvm_emulate_as_nop(vcpu);
2074 }
2075 EXPORT_SYMBOL_GPL(kvm_emulate_invd);
2076 
kvm_emulate_mwait(struct kvm_vcpu * vcpu)2077 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2078 {
2079 	pr_warn_once("kvm: MWAIT instruction emulated as NOP!\n");
2080 	return kvm_emulate_as_nop(vcpu);
2081 }
2082 EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
2083 
kvm_handle_invalid_op(struct kvm_vcpu * vcpu)2084 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2085 {
2086 	kvm_queue_exception(vcpu, UD_VECTOR);
2087 	return 1;
2088 }
2089 EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
2090 
kvm_emulate_monitor(struct kvm_vcpu * vcpu)2091 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2092 {
2093 	pr_warn_once("kvm: MONITOR instruction emulated as NOP!\n");
2094 	return kvm_emulate_as_nop(vcpu);
2095 }
2096 EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
2097 
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu)2098 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2099 {
2100 	xfer_to_guest_mode_prepare();
2101 	return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
2102 		xfer_to_guest_mode_work_pending();
2103 }
2104 
2105 /*
2106  * The fast path for frequent and performance sensitive wrmsr emulation,
2107  * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
2108  * the latency of virtual IPI by avoiding the expensive bits of transitioning
2109  * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
2110  * other cases which must be called after interrupts are enabled on the host.
2111  */
handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu * vcpu,u64 data)2112 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
2113 {
2114 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
2115 		return 1;
2116 
2117 	if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
2118 	    ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
2119 	    ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
2120 	    ((u32)(data >> 32) != X2APIC_BROADCAST))
2121 		return kvm_x2apic_icr_write(vcpu->arch.apic, data);
2122 
2123 	return 1;
2124 }
2125 
handle_fastpath_set_tscdeadline(struct kvm_vcpu * vcpu,u64 data)2126 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
2127 {
2128 	if (!kvm_can_use_hv_timer(vcpu))
2129 		return 1;
2130 
2131 	kvm_set_lapic_tscdeadline_msr(vcpu, data);
2132 	return 0;
2133 }
2134 
handle_fastpath_set_msr_irqoff(struct kvm_vcpu * vcpu)2135 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
2136 {
2137 	u32 msr = kvm_rcx_read(vcpu);
2138 	u64 data;
2139 	fastpath_t ret = EXIT_FASTPATH_NONE;
2140 
2141 	switch (msr) {
2142 	case APIC_BASE_MSR + (APIC_ICR >> 4):
2143 		data = kvm_read_edx_eax(vcpu);
2144 		if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
2145 			kvm_skip_emulated_instruction(vcpu);
2146 			ret = EXIT_FASTPATH_EXIT_HANDLED;
2147 		}
2148 		break;
2149 	case MSR_IA32_TSC_DEADLINE:
2150 		data = kvm_read_edx_eax(vcpu);
2151 		if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
2152 			kvm_skip_emulated_instruction(vcpu);
2153 			ret = EXIT_FASTPATH_REENTER_GUEST;
2154 		}
2155 		break;
2156 	default:
2157 		break;
2158 	}
2159 
2160 	if (ret != EXIT_FASTPATH_NONE)
2161 		trace_kvm_msr_write(msr, data);
2162 
2163 	return ret;
2164 }
2165 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
2166 
2167 /*
2168  * Adapt set_msr() to msr_io()'s calling convention
2169  */
do_get_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2170 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2171 {
2172 	return kvm_get_msr_ignored_check(vcpu, index, data, true);
2173 }
2174 
do_set_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2175 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2176 {
2177 	return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2178 }
2179 
2180 #ifdef CONFIG_X86_64
2181 struct pvclock_clock {
2182 	int vclock_mode;
2183 	u64 cycle_last;
2184 	u64 mask;
2185 	u32 mult;
2186 	u32 shift;
2187 	u64 base_cycles;
2188 	u64 offset;
2189 };
2190 
2191 struct pvclock_gtod_data {
2192 	seqcount_t	seq;
2193 
2194 	struct pvclock_clock clock; /* extract of a clocksource struct */
2195 	struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2196 
2197 	ktime_t		offs_boot;
2198 	u64		wall_time_sec;
2199 };
2200 
2201 static struct pvclock_gtod_data pvclock_gtod_data;
2202 
update_pvclock_gtod(struct timekeeper * tk)2203 static void update_pvclock_gtod(struct timekeeper *tk)
2204 {
2205 	struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2206 
2207 	write_seqcount_begin(&vdata->seq);
2208 
2209 	/* copy pvclock gtod data */
2210 	vdata->clock.vclock_mode	= tk->tkr_mono.clock->vdso_clock_mode;
2211 	vdata->clock.cycle_last		= tk->tkr_mono.cycle_last;
2212 	vdata->clock.mask		= tk->tkr_mono.mask;
2213 	vdata->clock.mult		= tk->tkr_mono.mult;
2214 	vdata->clock.shift		= tk->tkr_mono.shift;
2215 	vdata->clock.base_cycles	= tk->tkr_mono.xtime_nsec;
2216 	vdata->clock.offset		= tk->tkr_mono.base;
2217 
2218 	vdata->raw_clock.vclock_mode	= tk->tkr_raw.clock->vdso_clock_mode;
2219 	vdata->raw_clock.cycle_last	= tk->tkr_raw.cycle_last;
2220 	vdata->raw_clock.mask		= tk->tkr_raw.mask;
2221 	vdata->raw_clock.mult		= tk->tkr_raw.mult;
2222 	vdata->raw_clock.shift		= tk->tkr_raw.shift;
2223 	vdata->raw_clock.base_cycles	= tk->tkr_raw.xtime_nsec;
2224 	vdata->raw_clock.offset		= tk->tkr_raw.base;
2225 
2226 	vdata->wall_time_sec            = tk->xtime_sec;
2227 
2228 	vdata->offs_boot		= tk->offs_boot;
2229 
2230 	write_seqcount_end(&vdata->seq);
2231 }
2232 
get_kvmclock_base_ns(void)2233 static s64 get_kvmclock_base_ns(void)
2234 {
2235 	/* Count up from boot time, but with the frequency of the raw clock.  */
2236 	return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2237 }
2238 #else
get_kvmclock_base_ns(void)2239 static s64 get_kvmclock_base_ns(void)
2240 {
2241 	/* Master clock not used, so we can just use CLOCK_BOOTTIME.  */
2242 	return ktime_get_boottime_ns();
2243 }
2244 #endif
2245 
kvm_write_wall_clock(struct kvm * kvm,gpa_t wall_clock,int sec_hi_ofs)2246 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2247 {
2248 	int version;
2249 	int r;
2250 	struct pvclock_wall_clock wc;
2251 	u32 wc_sec_hi;
2252 	u64 wall_nsec;
2253 
2254 	if (!wall_clock)
2255 		return;
2256 
2257 	r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2258 	if (r)
2259 		return;
2260 
2261 	if (version & 1)
2262 		++version;  /* first time write, random junk */
2263 
2264 	++version;
2265 
2266 	if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2267 		return;
2268 
2269 	/*
2270 	 * The guest calculates current wall clock time by adding
2271 	 * system time (updated by kvm_guest_time_update below) to the
2272 	 * wall clock specified here.  We do the reverse here.
2273 	 */
2274 	wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
2275 
2276 	wc.nsec = do_div(wall_nsec, 1000000000);
2277 	wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2278 	wc.version = version;
2279 
2280 	kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2281 
2282 	if (sec_hi_ofs) {
2283 		wc_sec_hi = wall_nsec >> 32;
2284 		kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2285 				&wc_sec_hi, sizeof(wc_sec_hi));
2286 	}
2287 
2288 	version++;
2289 	kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2290 }
2291 
kvm_write_system_time(struct kvm_vcpu * vcpu,gpa_t system_time,bool old_msr,bool host_initiated)2292 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2293 				  bool old_msr, bool host_initiated)
2294 {
2295 	struct kvm_arch *ka = &vcpu->kvm->arch;
2296 
2297 	if (vcpu->vcpu_id == 0 && !host_initiated) {
2298 		if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2299 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2300 
2301 		ka->boot_vcpu_runs_old_kvmclock = old_msr;
2302 	}
2303 
2304 	vcpu->arch.time = system_time;
2305 	kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2306 
2307 	/* we verify if the enable bit is set... */
2308 	if (system_time & 1) {
2309 		kvm_gfn_to_pfn_cache_init(vcpu->kvm, &vcpu->arch.pv_time, vcpu,
2310 					  KVM_HOST_USES_PFN, system_time & ~1ULL,
2311 					  sizeof(struct pvclock_vcpu_time_info));
2312 	} else {
2313 		kvm_gfn_to_pfn_cache_destroy(vcpu->kvm, &vcpu->arch.pv_time);
2314 	}
2315 
2316 	return;
2317 }
2318 
div_frac(uint32_t dividend,uint32_t divisor)2319 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2320 {
2321 	do_shl32_div32(dividend, divisor);
2322 	return dividend;
2323 }
2324 
kvm_get_time_scale(uint64_t scaled_hz,uint64_t base_hz,s8 * pshift,u32 * pmultiplier)2325 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2326 			       s8 *pshift, u32 *pmultiplier)
2327 {
2328 	uint64_t scaled64;
2329 	int32_t  shift = 0;
2330 	uint64_t tps64;
2331 	uint32_t tps32;
2332 
2333 	tps64 = base_hz;
2334 	scaled64 = scaled_hz;
2335 	while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2336 		tps64 >>= 1;
2337 		shift--;
2338 	}
2339 
2340 	tps32 = (uint32_t)tps64;
2341 	while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2342 		if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2343 			scaled64 >>= 1;
2344 		else
2345 			tps32 <<= 1;
2346 		shift++;
2347 	}
2348 
2349 	*pshift = shift;
2350 	*pmultiplier = div_frac(scaled64, tps32);
2351 }
2352 
2353 #ifdef CONFIG_X86_64
2354 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2355 #endif
2356 
2357 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2358 static unsigned long max_tsc_khz;
2359 
adjust_tsc_khz(u32 khz,s32 ppm)2360 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2361 {
2362 	u64 v = (u64)khz * (1000000 + ppm);
2363 	do_div(v, 1000000);
2364 	return v;
2365 }
2366 
2367 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2368 
set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz,bool scale)2369 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2370 {
2371 	u64 ratio;
2372 
2373 	/* Guest TSC same frequency as host TSC? */
2374 	if (!scale) {
2375 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_default_tsc_scaling_ratio);
2376 		return 0;
2377 	}
2378 
2379 	/* TSC scaling supported? */
2380 	if (!kvm_has_tsc_control) {
2381 		if (user_tsc_khz > tsc_khz) {
2382 			vcpu->arch.tsc_catchup = 1;
2383 			vcpu->arch.tsc_always_catchup = 1;
2384 			return 0;
2385 		} else {
2386 			pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2387 			return -1;
2388 		}
2389 	}
2390 
2391 	/* TSC scaling required  - calculate ratio */
2392 	ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
2393 				user_tsc_khz, tsc_khz);
2394 
2395 	if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
2396 		pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2397 			            user_tsc_khz);
2398 		return -1;
2399 	}
2400 
2401 	kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2402 	return 0;
2403 }
2404 
kvm_set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz)2405 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2406 {
2407 	u32 thresh_lo, thresh_hi;
2408 	int use_scaling = 0;
2409 
2410 	/* tsc_khz can be zero if TSC calibration fails */
2411 	if (user_tsc_khz == 0) {
2412 		/* set tsc_scaling_ratio to a safe value */
2413 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_default_tsc_scaling_ratio);
2414 		return -1;
2415 	}
2416 
2417 	/* Compute a scale to convert nanoseconds in TSC cycles */
2418 	kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2419 			   &vcpu->arch.virtual_tsc_shift,
2420 			   &vcpu->arch.virtual_tsc_mult);
2421 	vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2422 
2423 	/*
2424 	 * Compute the variation in TSC rate which is acceptable
2425 	 * within the range of tolerance and decide if the
2426 	 * rate being applied is within that bounds of the hardware
2427 	 * rate.  If so, no scaling or compensation need be done.
2428 	 */
2429 	thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2430 	thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2431 	if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2432 		pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
2433 		use_scaling = 1;
2434 	}
2435 	return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2436 }
2437 
compute_guest_tsc(struct kvm_vcpu * vcpu,s64 kernel_ns)2438 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2439 {
2440 	u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2441 				      vcpu->arch.virtual_tsc_mult,
2442 				      vcpu->arch.virtual_tsc_shift);
2443 	tsc += vcpu->arch.this_tsc_write;
2444 	return tsc;
2445 }
2446 
2447 #ifdef CONFIG_X86_64
gtod_is_based_on_tsc(int mode)2448 static inline int gtod_is_based_on_tsc(int mode)
2449 {
2450 	return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2451 }
2452 #endif
2453 
kvm_track_tsc_matching(struct kvm_vcpu * vcpu)2454 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
2455 {
2456 #ifdef CONFIG_X86_64
2457 	bool vcpus_matched;
2458 	struct kvm_arch *ka = &vcpu->kvm->arch;
2459 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2460 
2461 	vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2462 			 atomic_read(&vcpu->kvm->online_vcpus));
2463 
2464 	/*
2465 	 * Once the masterclock is enabled, always perform request in
2466 	 * order to update it.
2467 	 *
2468 	 * In order to enable masterclock, the host clocksource must be TSC
2469 	 * and the vcpus need to have matched TSCs.  When that happens,
2470 	 * perform request to enable masterclock.
2471 	 */
2472 	if (ka->use_master_clock ||
2473 	    (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
2474 		kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2475 
2476 	trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2477 			    atomic_read(&vcpu->kvm->online_vcpus),
2478 		            ka->use_master_clock, gtod->clock.vclock_mode);
2479 #endif
2480 }
2481 
2482 /*
2483  * Multiply tsc by a fixed point number represented by ratio.
2484  *
2485  * The most significant 64-N bits (mult) of ratio represent the
2486  * integral part of the fixed point number; the remaining N bits
2487  * (frac) represent the fractional part, ie. ratio represents a fixed
2488  * point number (mult + frac * 2^(-N)).
2489  *
2490  * N equals to kvm_tsc_scaling_ratio_frac_bits.
2491  */
__scale_tsc(u64 ratio,u64 tsc)2492 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2493 {
2494 	return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
2495 }
2496 
kvm_scale_tsc(u64 tsc,u64 ratio)2497 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2498 {
2499 	u64 _tsc = tsc;
2500 
2501 	if (ratio != kvm_default_tsc_scaling_ratio)
2502 		_tsc = __scale_tsc(ratio, tsc);
2503 
2504 	return _tsc;
2505 }
2506 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
2507 
kvm_compute_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 target_tsc)2508 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2509 {
2510 	u64 tsc;
2511 
2512 	tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2513 
2514 	return target_tsc - tsc;
2515 }
2516 
kvm_read_l1_tsc(struct kvm_vcpu * vcpu,u64 host_tsc)2517 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2518 {
2519 	return vcpu->arch.l1_tsc_offset +
2520 		kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2521 }
2522 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2523 
kvm_calc_nested_tsc_offset(u64 l1_offset,u64 l2_offset,u64 l2_multiplier)2524 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2525 {
2526 	u64 nested_offset;
2527 
2528 	if (l2_multiplier == kvm_default_tsc_scaling_ratio)
2529 		nested_offset = l1_offset;
2530 	else
2531 		nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2532 						kvm_tsc_scaling_ratio_frac_bits);
2533 
2534 	nested_offset += l2_offset;
2535 	return nested_offset;
2536 }
2537 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
2538 
kvm_calc_nested_tsc_multiplier(u64 l1_multiplier,u64 l2_multiplier)2539 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2540 {
2541 	if (l2_multiplier != kvm_default_tsc_scaling_ratio)
2542 		return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2543 				       kvm_tsc_scaling_ratio_frac_bits);
2544 
2545 	return l1_multiplier;
2546 }
2547 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
2548 
kvm_vcpu_write_tsc_offset(struct kvm_vcpu * vcpu,u64 l1_offset)2549 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2550 {
2551 	trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2552 				   vcpu->arch.l1_tsc_offset,
2553 				   l1_offset);
2554 
2555 	vcpu->arch.l1_tsc_offset = l1_offset;
2556 
2557 	/*
2558 	 * If we are here because L1 chose not to trap WRMSR to TSC then
2559 	 * according to the spec this should set L1's TSC (as opposed to
2560 	 * setting L1's offset for L2).
2561 	 */
2562 	if (is_guest_mode(vcpu))
2563 		vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2564 			l1_offset,
2565 			static_call(kvm_x86_get_l2_tsc_offset)(vcpu),
2566 			static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
2567 	else
2568 		vcpu->arch.tsc_offset = l1_offset;
2569 
2570 	static_call(kvm_x86_write_tsc_offset)(vcpu, vcpu->arch.tsc_offset);
2571 }
2572 
kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu * vcpu,u64 l1_multiplier)2573 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2574 {
2575 	vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2576 
2577 	/* Userspace is changing the multiplier while L2 is active */
2578 	if (is_guest_mode(vcpu))
2579 		vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2580 			l1_multiplier,
2581 			static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
2582 	else
2583 		vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2584 
2585 	if (kvm_has_tsc_control)
2586 		static_call(kvm_x86_write_tsc_multiplier)(
2587 			vcpu, vcpu->arch.tsc_scaling_ratio);
2588 }
2589 
kvm_check_tsc_unstable(void)2590 static inline bool kvm_check_tsc_unstable(void)
2591 {
2592 #ifdef CONFIG_X86_64
2593 	/*
2594 	 * TSC is marked unstable when we're running on Hyper-V,
2595 	 * 'TSC page' clocksource is good.
2596 	 */
2597 	if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2598 		return false;
2599 #endif
2600 	return check_tsc_unstable();
2601 }
2602 
2603 /*
2604  * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2605  * offset for the vcpu and tracks the TSC matching generation that the vcpu
2606  * participates in.
2607  */
__kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 offset,u64 tsc,u64 ns,bool matched)2608 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2609 				  u64 ns, bool matched)
2610 {
2611 	struct kvm *kvm = vcpu->kvm;
2612 
2613 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
2614 
2615 	/*
2616 	 * We also track th most recent recorded KHZ, write and time to
2617 	 * allow the matching interval to be extended at each write.
2618 	 */
2619 	kvm->arch.last_tsc_nsec = ns;
2620 	kvm->arch.last_tsc_write = tsc;
2621 	kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2622 	kvm->arch.last_tsc_offset = offset;
2623 
2624 	vcpu->arch.last_guest_tsc = tsc;
2625 
2626 	kvm_vcpu_write_tsc_offset(vcpu, offset);
2627 
2628 	if (!matched) {
2629 		/*
2630 		 * We split periods of matched TSC writes into generations.
2631 		 * For each generation, we track the original measured
2632 		 * nanosecond time, offset, and write, so if TSCs are in
2633 		 * sync, we can match exact offset, and if not, we can match
2634 		 * exact software computation in compute_guest_tsc()
2635 		 *
2636 		 * These values are tracked in kvm->arch.cur_xxx variables.
2637 		 */
2638 		kvm->arch.cur_tsc_generation++;
2639 		kvm->arch.cur_tsc_nsec = ns;
2640 		kvm->arch.cur_tsc_write = tsc;
2641 		kvm->arch.cur_tsc_offset = offset;
2642 		kvm->arch.nr_vcpus_matched_tsc = 0;
2643 	} else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2644 		kvm->arch.nr_vcpus_matched_tsc++;
2645 	}
2646 
2647 	/* Keep track of which generation this VCPU has synchronized to */
2648 	vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2649 	vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2650 	vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2651 
2652 	kvm_track_tsc_matching(vcpu);
2653 }
2654 
kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 data)2655 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 data)
2656 {
2657 	struct kvm *kvm = vcpu->kvm;
2658 	u64 offset, ns, elapsed;
2659 	unsigned long flags;
2660 	bool matched = false;
2661 	bool synchronizing = false;
2662 
2663 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2664 	offset = kvm_compute_l1_tsc_offset(vcpu, data);
2665 	ns = get_kvmclock_base_ns();
2666 	elapsed = ns - kvm->arch.last_tsc_nsec;
2667 
2668 	if (vcpu->arch.virtual_tsc_khz) {
2669 		if (data == 0) {
2670 			/*
2671 			 * detection of vcpu initialization -- need to sync
2672 			 * with other vCPUs. This particularly helps to keep
2673 			 * kvm_clock stable after CPU hotplug
2674 			 */
2675 			synchronizing = true;
2676 		} else {
2677 			u64 tsc_exp = kvm->arch.last_tsc_write +
2678 						nsec_to_cycles(vcpu, elapsed);
2679 			u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2680 			/*
2681 			 * Special case: TSC write with a small delta (1 second)
2682 			 * of virtual cycle time against real time is
2683 			 * interpreted as an attempt to synchronize the CPU.
2684 			 */
2685 			synchronizing = data < tsc_exp + tsc_hz &&
2686 					data + tsc_hz > tsc_exp;
2687 		}
2688 	}
2689 
2690 	/*
2691 	 * For a reliable TSC, we can match TSC offsets, and for an unstable
2692 	 * TSC, we add elapsed time in this computation.  We could let the
2693 	 * compensation code attempt to catch up if we fall behind, but
2694 	 * it's better to try to match offsets from the beginning.
2695          */
2696 	if (synchronizing &&
2697 	    vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2698 		if (!kvm_check_tsc_unstable()) {
2699 			offset = kvm->arch.cur_tsc_offset;
2700 		} else {
2701 			u64 delta = nsec_to_cycles(vcpu, elapsed);
2702 			data += delta;
2703 			offset = kvm_compute_l1_tsc_offset(vcpu, data);
2704 		}
2705 		matched = true;
2706 	}
2707 
2708 	__kvm_synchronize_tsc(vcpu, offset, data, ns, matched);
2709 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2710 }
2711 
adjust_tsc_offset_guest(struct kvm_vcpu * vcpu,s64 adjustment)2712 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2713 					   s64 adjustment)
2714 {
2715 	u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2716 	kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2717 }
2718 
adjust_tsc_offset_host(struct kvm_vcpu * vcpu,s64 adjustment)2719 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2720 {
2721 	if (vcpu->arch.l1_tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2722 		WARN_ON(adjustment < 0);
2723 	adjustment = kvm_scale_tsc((u64) adjustment,
2724 				   vcpu->arch.l1_tsc_scaling_ratio);
2725 	adjust_tsc_offset_guest(vcpu, adjustment);
2726 }
2727 
2728 #ifdef CONFIG_X86_64
2729 
read_tsc(void)2730 static u64 read_tsc(void)
2731 {
2732 	u64 ret = (u64)rdtsc_ordered();
2733 	u64 last = pvclock_gtod_data.clock.cycle_last;
2734 
2735 	if (likely(ret >= last))
2736 		return ret;
2737 
2738 	/*
2739 	 * GCC likes to generate cmov here, but this branch is extremely
2740 	 * predictable (it's just a function of time and the likely is
2741 	 * very likely) and there's a data dependence, so force GCC
2742 	 * to generate a branch instead.  I don't barrier() because
2743 	 * we don't actually need a barrier, and if this function
2744 	 * ever gets inlined it will generate worse code.
2745 	 */
2746 	asm volatile ("");
2747 	return last;
2748 }
2749 
vgettsc(struct pvclock_clock * clock,u64 * tsc_timestamp,int * mode)2750 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2751 			  int *mode)
2752 {
2753 	long v;
2754 	u64 tsc_pg_val;
2755 
2756 	switch (clock->vclock_mode) {
2757 	case VDSO_CLOCKMODE_HVCLOCK:
2758 		tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2759 						  tsc_timestamp);
2760 		if (tsc_pg_val != U64_MAX) {
2761 			/* TSC page valid */
2762 			*mode = VDSO_CLOCKMODE_HVCLOCK;
2763 			v = (tsc_pg_val - clock->cycle_last) &
2764 				clock->mask;
2765 		} else {
2766 			/* TSC page invalid */
2767 			*mode = VDSO_CLOCKMODE_NONE;
2768 		}
2769 		break;
2770 	case VDSO_CLOCKMODE_TSC:
2771 		*mode = VDSO_CLOCKMODE_TSC;
2772 		*tsc_timestamp = read_tsc();
2773 		v = (*tsc_timestamp - clock->cycle_last) &
2774 			clock->mask;
2775 		break;
2776 	default:
2777 		*mode = VDSO_CLOCKMODE_NONE;
2778 	}
2779 
2780 	if (*mode == VDSO_CLOCKMODE_NONE)
2781 		*tsc_timestamp = v = 0;
2782 
2783 	return v * clock->mult;
2784 }
2785 
do_monotonic_raw(s64 * t,u64 * tsc_timestamp)2786 static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
2787 {
2788 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2789 	unsigned long seq;
2790 	int mode;
2791 	u64 ns;
2792 
2793 	do {
2794 		seq = read_seqcount_begin(&gtod->seq);
2795 		ns = gtod->raw_clock.base_cycles;
2796 		ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
2797 		ns >>= gtod->raw_clock.shift;
2798 		ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2799 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2800 	*t = ns;
2801 
2802 	return mode;
2803 }
2804 
do_realtime(struct timespec64 * ts,u64 * tsc_timestamp)2805 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2806 {
2807 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2808 	unsigned long seq;
2809 	int mode;
2810 	u64 ns;
2811 
2812 	do {
2813 		seq = read_seqcount_begin(&gtod->seq);
2814 		ts->tv_sec = gtod->wall_time_sec;
2815 		ns = gtod->clock.base_cycles;
2816 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2817 		ns >>= gtod->clock.shift;
2818 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2819 
2820 	ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2821 	ts->tv_nsec = ns;
2822 
2823 	return mode;
2824 }
2825 
2826 /* returns true if host is using TSC based clocksource */
kvm_get_time_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)2827 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2828 {
2829 	/* checked again under seqlock below */
2830 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2831 		return false;
2832 
2833 	return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
2834 						      tsc_timestamp));
2835 }
2836 
2837 /* returns true if host is using TSC based clocksource */
kvm_get_walltime_and_clockread(struct timespec64 * ts,u64 * tsc_timestamp)2838 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2839 					   u64 *tsc_timestamp)
2840 {
2841 	/* checked again under seqlock below */
2842 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2843 		return false;
2844 
2845 	return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2846 }
2847 #endif
2848 
2849 /*
2850  *
2851  * Assuming a stable TSC across physical CPUS, and a stable TSC
2852  * across virtual CPUs, the following condition is possible.
2853  * Each numbered line represents an event visible to both
2854  * CPUs at the next numbered event.
2855  *
2856  * "timespecX" represents host monotonic time. "tscX" represents
2857  * RDTSC value.
2858  *
2859  * 		VCPU0 on CPU0		|	VCPU1 on CPU1
2860  *
2861  * 1.  read timespec0,tsc0
2862  * 2.					| timespec1 = timespec0 + N
2863  * 					| tsc1 = tsc0 + M
2864  * 3. transition to guest		| transition to guest
2865  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2866  * 5.				        | ret1 = timespec1 + (rdtsc - tsc1)
2867  * 				        | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2868  *
2869  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2870  *
2871  * 	- ret0 < ret1
2872  *	- timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2873  *		...
2874  *	- 0 < N - M => M < N
2875  *
2876  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2877  * always the case (the difference between two distinct xtime instances
2878  * might be smaller then the difference between corresponding TSC reads,
2879  * when updating guest vcpus pvclock areas).
2880  *
2881  * To avoid that problem, do not allow visibility of distinct
2882  * system_timestamp/tsc_timestamp values simultaneously: use a master
2883  * copy of host monotonic time values. Update that master copy
2884  * in lockstep.
2885  *
2886  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2887  *
2888  */
2889 
pvclock_update_vm_gtod_copy(struct kvm * kvm)2890 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2891 {
2892 #ifdef CONFIG_X86_64
2893 	struct kvm_arch *ka = &kvm->arch;
2894 	int vclock_mode;
2895 	bool host_tsc_clocksource, vcpus_matched;
2896 
2897 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
2898 	vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2899 			atomic_read(&kvm->online_vcpus));
2900 
2901 	/*
2902 	 * If the host uses TSC clock, then passthrough TSC as stable
2903 	 * to the guest.
2904 	 */
2905 	host_tsc_clocksource = kvm_get_time_and_clockread(
2906 					&ka->master_kernel_ns,
2907 					&ka->master_cycle_now);
2908 
2909 	ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2910 				&& !ka->backwards_tsc_observed
2911 				&& !ka->boot_vcpu_runs_old_kvmclock;
2912 
2913 	if (ka->use_master_clock)
2914 		atomic_set(&kvm_guest_has_master_clock, 1);
2915 
2916 	vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2917 	trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2918 					vcpus_matched);
2919 #endif
2920 }
2921 
kvm_make_mclock_inprogress_request(struct kvm * kvm)2922 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2923 {
2924 	kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2925 }
2926 
__kvm_start_pvclock_update(struct kvm * kvm)2927 static void __kvm_start_pvclock_update(struct kvm *kvm)
2928 {
2929 	raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
2930 	write_seqcount_begin(&kvm->arch.pvclock_sc);
2931 }
2932 
kvm_start_pvclock_update(struct kvm * kvm)2933 static void kvm_start_pvclock_update(struct kvm *kvm)
2934 {
2935 	kvm_make_mclock_inprogress_request(kvm);
2936 
2937 	/* no guest entries from this point */
2938 	__kvm_start_pvclock_update(kvm);
2939 }
2940 
kvm_end_pvclock_update(struct kvm * kvm)2941 static void kvm_end_pvclock_update(struct kvm *kvm)
2942 {
2943 	struct kvm_arch *ka = &kvm->arch;
2944 	struct kvm_vcpu *vcpu;
2945 	unsigned long i;
2946 
2947 	write_seqcount_end(&ka->pvclock_sc);
2948 	raw_spin_unlock_irq(&ka->tsc_write_lock);
2949 	kvm_for_each_vcpu(i, vcpu, kvm)
2950 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2951 
2952 	/* guest entries allowed */
2953 	kvm_for_each_vcpu(i, vcpu, kvm)
2954 		kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2955 }
2956 
kvm_update_masterclock(struct kvm * kvm)2957 static void kvm_update_masterclock(struct kvm *kvm)
2958 {
2959 	kvm_hv_request_tsc_page_update(kvm);
2960 	kvm_start_pvclock_update(kvm);
2961 	pvclock_update_vm_gtod_copy(kvm);
2962 	kvm_end_pvclock_update(kvm);
2963 }
2964 
2965 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc.  */
__get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)2966 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
2967 {
2968 	struct kvm_arch *ka = &kvm->arch;
2969 	struct pvclock_vcpu_time_info hv_clock;
2970 
2971 	/* both __this_cpu_read() and rdtsc() should be on the same cpu */
2972 	get_cpu();
2973 
2974 	data->flags = 0;
2975 	if (ka->use_master_clock && __this_cpu_read(cpu_tsc_khz)) {
2976 #ifdef CONFIG_X86_64
2977 		struct timespec64 ts;
2978 
2979 		if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
2980 			data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
2981 			data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
2982 		} else
2983 #endif
2984 		data->host_tsc = rdtsc();
2985 
2986 		data->flags |= KVM_CLOCK_TSC_STABLE;
2987 		hv_clock.tsc_timestamp = ka->master_cycle_now;
2988 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2989 		kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2990 				   &hv_clock.tsc_shift,
2991 				   &hv_clock.tsc_to_system_mul);
2992 		data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
2993 	} else {
2994 		data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
2995 	}
2996 
2997 	put_cpu();
2998 }
2999 
get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3000 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3001 {
3002 	struct kvm_arch *ka = &kvm->arch;
3003 	unsigned seq;
3004 
3005 	do {
3006 		seq = read_seqcount_begin(&ka->pvclock_sc);
3007 		__get_kvmclock(kvm, data);
3008 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3009 }
3010 
get_kvmclock_ns(struct kvm * kvm)3011 u64 get_kvmclock_ns(struct kvm *kvm)
3012 {
3013 	struct kvm_clock_data data;
3014 
3015 	get_kvmclock(kvm, &data);
3016 	return data.clock;
3017 }
3018 
kvm_setup_guest_pvclock(struct kvm_vcpu * v,struct gfn_to_pfn_cache * gpc,unsigned int offset)3019 static void kvm_setup_guest_pvclock(struct kvm_vcpu *v,
3020 				    struct gfn_to_pfn_cache *gpc,
3021 				    unsigned int offset)
3022 {
3023 	struct kvm_vcpu_arch *vcpu = &v->arch;
3024 	struct pvclock_vcpu_time_info *guest_hv_clock;
3025 	unsigned long flags;
3026 
3027 	read_lock_irqsave(&gpc->lock, flags);
3028 	while (!kvm_gfn_to_pfn_cache_check(v->kvm, gpc, gpc->gpa,
3029 					   offset + sizeof(*guest_hv_clock))) {
3030 		read_unlock_irqrestore(&gpc->lock, flags);
3031 
3032 		if (kvm_gfn_to_pfn_cache_refresh(v->kvm, gpc, gpc->gpa,
3033 						 offset + sizeof(*guest_hv_clock)))
3034 			return;
3035 
3036 		read_lock_irqsave(&gpc->lock, flags);
3037 	}
3038 
3039 	guest_hv_clock = (void *)(gpc->khva + offset);
3040 
3041 	/*
3042 	 * This VCPU is paused, but it's legal for a guest to read another
3043 	 * VCPU's kvmclock, so we really have to follow the specification where
3044 	 * it says that version is odd if data is being modified, and even after
3045 	 * it is consistent.
3046 	 */
3047 
3048 	guest_hv_clock->version = vcpu->hv_clock.version = (guest_hv_clock->version + 1) | 1;
3049 	smp_wmb();
3050 
3051 	/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3052 	vcpu->hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3053 
3054 	if (vcpu->pvclock_set_guest_stopped_request) {
3055 		vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3056 		vcpu->pvclock_set_guest_stopped_request = false;
3057 	}
3058 
3059 	memcpy(guest_hv_clock, &vcpu->hv_clock, sizeof(*guest_hv_clock));
3060 	smp_wmb();
3061 
3062 	guest_hv_clock->version = ++vcpu->hv_clock.version;
3063 
3064 	mark_page_dirty_in_slot(v->kvm, gpc->memslot, gpc->gpa >> PAGE_SHIFT);
3065 	read_unlock_irqrestore(&gpc->lock, flags);
3066 
3067 	trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
3068 }
3069 
kvm_guest_time_update(struct kvm_vcpu * v)3070 static int kvm_guest_time_update(struct kvm_vcpu *v)
3071 {
3072 	unsigned long flags, tgt_tsc_khz;
3073 	unsigned seq;
3074 	struct kvm_vcpu_arch *vcpu = &v->arch;
3075 	struct kvm_arch *ka = &v->kvm->arch;
3076 	s64 kernel_ns;
3077 	u64 tsc_timestamp, host_tsc;
3078 	u8 pvclock_flags;
3079 	bool use_master_clock;
3080 
3081 	kernel_ns = 0;
3082 	host_tsc = 0;
3083 
3084 	/*
3085 	 * If the host uses TSC clock, then passthrough TSC as stable
3086 	 * to the guest.
3087 	 */
3088 	do {
3089 		seq = read_seqcount_begin(&ka->pvclock_sc);
3090 		use_master_clock = ka->use_master_clock;
3091 		if (use_master_clock) {
3092 			host_tsc = ka->master_cycle_now;
3093 			kernel_ns = ka->master_kernel_ns;
3094 		}
3095 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3096 
3097 	/* Keep irq disabled to prevent changes to the clock */
3098 	local_irq_save(flags);
3099 	tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
3100 	if (unlikely(tgt_tsc_khz == 0)) {
3101 		local_irq_restore(flags);
3102 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3103 		return 1;
3104 	}
3105 	if (!use_master_clock) {
3106 		host_tsc = rdtsc();
3107 		kernel_ns = get_kvmclock_base_ns();
3108 	}
3109 
3110 	tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3111 
3112 	/*
3113 	 * We may have to catch up the TSC to match elapsed wall clock
3114 	 * time for two reasons, even if kvmclock is used.
3115 	 *   1) CPU could have been running below the maximum TSC rate
3116 	 *   2) Broken TSC compensation resets the base at each VCPU
3117 	 *      entry to avoid unknown leaps of TSC even when running
3118 	 *      again on the same CPU.  This may cause apparent elapsed
3119 	 *      time to disappear, and the guest to stand still or run
3120 	 *	very slowly.
3121 	 */
3122 	if (vcpu->tsc_catchup) {
3123 		u64 tsc = compute_guest_tsc(v, kernel_ns);
3124 		if (tsc > tsc_timestamp) {
3125 			adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3126 			tsc_timestamp = tsc;
3127 		}
3128 	}
3129 
3130 	local_irq_restore(flags);
3131 
3132 	/* With all the info we got, fill in the values */
3133 
3134 	if (kvm_has_tsc_control)
3135 		tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3136 					    v->arch.l1_tsc_scaling_ratio);
3137 
3138 	if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3139 		kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3140 				   &vcpu->hv_clock.tsc_shift,
3141 				   &vcpu->hv_clock.tsc_to_system_mul);
3142 		vcpu->hw_tsc_khz = tgt_tsc_khz;
3143 	}
3144 
3145 	vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
3146 	vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3147 	vcpu->last_guest_tsc = tsc_timestamp;
3148 
3149 	/* If the host uses TSC clocksource, then it is stable */
3150 	pvclock_flags = 0;
3151 	if (use_master_clock)
3152 		pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
3153 
3154 	vcpu->hv_clock.flags = pvclock_flags;
3155 
3156 	if (vcpu->pv_time.active)
3157 		kvm_setup_guest_pvclock(v, &vcpu->pv_time, 0);
3158 	if (vcpu->xen.vcpu_info_cache.active)
3159 		kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_info_cache,
3160 					offsetof(struct compat_vcpu_info, time));
3161 	if (vcpu->xen.vcpu_time_info_cache.active)
3162 		kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_time_info_cache, 0);
3163 	kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
3164 	return 0;
3165 }
3166 
3167 /*
3168  * kvmclock updates which are isolated to a given vcpu, such as
3169  * vcpu->cpu migration, should not allow system_timestamp from
3170  * the rest of the vcpus to remain static. Otherwise ntp frequency
3171  * correction applies to one vcpu's system_timestamp but not
3172  * the others.
3173  *
3174  * So in those cases, request a kvmclock update for all vcpus.
3175  * We need to rate-limit these requests though, as they can
3176  * considerably slow guests that have a large number of vcpus.
3177  * The time for a remote vcpu to update its kvmclock is bound
3178  * by the delay we use to rate-limit the updates.
3179  */
3180 
3181 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3182 
kvmclock_update_fn(struct work_struct * work)3183 static void kvmclock_update_fn(struct work_struct *work)
3184 {
3185 	unsigned long i;
3186 	struct delayed_work *dwork = to_delayed_work(work);
3187 	struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3188 					   kvmclock_update_work);
3189 	struct kvm *kvm = container_of(ka, struct kvm, arch);
3190 	struct kvm_vcpu *vcpu;
3191 
3192 	kvm_for_each_vcpu(i, vcpu, kvm) {
3193 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3194 		kvm_vcpu_kick(vcpu);
3195 	}
3196 }
3197 
kvm_gen_kvmclock_update(struct kvm_vcpu * v)3198 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3199 {
3200 	struct kvm *kvm = v->kvm;
3201 
3202 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3203 	schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3204 					KVMCLOCK_UPDATE_DELAY);
3205 }
3206 
3207 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3208 
kvmclock_sync_fn(struct work_struct * work)3209 static void kvmclock_sync_fn(struct work_struct *work)
3210 {
3211 	struct delayed_work *dwork = to_delayed_work(work);
3212 	struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3213 					   kvmclock_sync_work);
3214 	struct kvm *kvm = container_of(ka, struct kvm, arch);
3215 
3216 	if (!kvmclock_periodic_sync)
3217 		return;
3218 
3219 	schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3220 	schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3221 					KVMCLOCK_SYNC_PERIOD);
3222 }
3223 
3224 /*
3225  * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3226  */
can_set_mci_status(struct kvm_vcpu * vcpu)3227 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3228 {
3229 	/* McStatusWrEn enabled? */
3230 	if (guest_cpuid_is_amd_or_hygon(vcpu))
3231 		return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3232 
3233 	return false;
3234 }
3235 
set_msr_mce(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3236 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3237 {
3238 	u64 mcg_cap = vcpu->arch.mcg_cap;
3239 	unsigned bank_num = mcg_cap & 0xff;
3240 	u32 msr = msr_info->index;
3241 	u64 data = msr_info->data;
3242 
3243 	switch (msr) {
3244 	case MSR_IA32_MCG_STATUS:
3245 		vcpu->arch.mcg_status = data;
3246 		break;
3247 	case MSR_IA32_MCG_CTL:
3248 		if (!(mcg_cap & MCG_CTL_P) &&
3249 		    (data || !msr_info->host_initiated))
3250 			return 1;
3251 		if (data != 0 && data != ~(u64)0)
3252 			return 1;
3253 		vcpu->arch.mcg_ctl = data;
3254 		break;
3255 	default:
3256 		if (msr >= MSR_IA32_MC0_CTL &&
3257 		    msr < MSR_IA32_MCx_CTL(bank_num)) {
3258 			u32 offset = array_index_nospec(
3259 				msr - MSR_IA32_MC0_CTL,
3260 				MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3261 
3262 			/* only 0 or all 1s can be written to IA32_MCi_CTL
3263 			 * some Linux kernels though clear bit 10 in bank 4 to
3264 			 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
3265 			 * this to avoid an uncatched #GP in the guest.
3266 			 *
3267 			 * UNIXWARE clears bit 0 of MC1_CTL to ignore
3268 			 * correctable, single-bit ECC data errors.
3269 			 */
3270 			if ((offset & 0x3) == 0 &&
3271 			    data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3272 				return 1;
3273 
3274 			/* MCi_STATUS */
3275 			if (!msr_info->host_initiated &&
3276 			    (offset & 0x3) == 1 && data != 0) {
3277 				if (!can_set_mci_status(vcpu))
3278 					return 1;
3279 			}
3280 
3281 			vcpu->arch.mce_banks[offset] = data;
3282 			break;
3283 		}
3284 		return 1;
3285 	}
3286 	return 0;
3287 }
3288 
kvm_pv_async_pf_enabled(struct kvm_vcpu * vcpu)3289 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3290 {
3291 	u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3292 
3293 	return (vcpu->arch.apf.msr_en_val & mask) == mask;
3294 }
3295 
kvm_pv_enable_async_pf(struct kvm_vcpu * vcpu,u64 data)3296 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3297 {
3298 	gpa_t gpa = data & ~0x3f;
3299 
3300 	/* Bits 4:5 are reserved, Should be zero */
3301 	if (data & 0x30)
3302 		return 1;
3303 
3304 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3305 	    (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3306 		return 1;
3307 
3308 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3309 	    (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3310 		return 1;
3311 
3312 	if (!lapic_in_kernel(vcpu))
3313 		return data ? 1 : 0;
3314 
3315 	vcpu->arch.apf.msr_en_val = data;
3316 
3317 	if (!kvm_pv_async_pf_enabled(vcpu)) {
3318 		kvm_clear_async_pf_completion_queue(vcpu);
3319 		kvm_async_pf_hash_reset(vcpu);
3320 		return 0;
3321 	}
3322 
3323 	if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3324 					sizeof(u64)))
3325 		return 1;
3326 
3327 	vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
3328 	vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3329 
3330 	kvm_async_pf_wakeup_all(vcpu);
3331 
3332 	return 0;
3333 }
3334 
kvm_pv_enable_async_pf_int(struct kvm_vcpu * vcpu,u64 data)3335 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3336 {
3337 	/* Bits 8-63 are reserved */
3338 	if (data >> 8)
3339 		return 1;
3340 
3341 	if (!lapic_in_kernel(vcpu))
3342 		return 1;
3343 
3344 	vcpu->arch.apf.msr_int_val = data;
3345 
3346 	vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3347 
3348 	return 0;
3349 }
3350 
kvmclock_reset(struct kvm_vcpu * vcpu)3351 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3352 {
3353 	kvm_gfn_to_pfn_cache_destroy(vcpu->kvm, &vcpu->arch.pv_time);
3354 	vcpu->arch.time = 0;
3355 }
3356 
kvm_vcpu_flush_tlb_all(struct kvm_vcpu * vcpu)3357 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3358 {
3359 	++vcpu->stat.tlb_flush;
3360 	static_call(kvm_x86_flush_tlb_all)(vcpu);
3361 }
3362 
kvm_vcpu_flush_tlb_guest(struct kvm_vcpu * vcpu)3363 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3364 {
3365 	++vcpu->stat.tlb_flush;
3366 
3367 	if (!tdp_enabled) {
3368 		/*
3369 		 * A TLB flush on behalf of the guest is equivalent to
3370 		 * INVPCID(all), toggling CR4.PGE, etc., which requires
3371 		 * a forced sync of the shadow page tables.  Ensure all the
3372 		 * roots are synced and the guest TLB in hardware is clean.
3373 		 */
3374 		kvm_mmu_sync_roots(vcpu);
3375 		kvm_mmu_sync_prev_roots(vcpu);
3376 	}
3377 
3378 	static_call(kvm_x86_flush_tlb_guest)(vcpu);
3379 }
3380 
3381 
kvm_vcpu_flush_tlb_current(struct kvm_vcpu * vcpu)3382 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3383 {
3384 	++vcpu->stat.tlb_flush;
3385 	static_call(kvm_x86_flush_tlb_current)(vcpu);
3386 }
3387 
3388 /*
3389  * Service "local" TLB flush requests, which are specific to the current MMU
3390  * context.  In addition to the generic event handling in vcpu_enter_guest(),
3391  * TLB flushes that are targeted at an MMU context also need to be serviced
3392  * prior before nested VM-Enter/VM-Exit.
3393  */
kvm_service_local_tlb_flush_requests(struct kvm_vcpu * vcpu)3394 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3395 {
3396 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3397 		kvm_vcpu_flush_tlb_current(vcpu);
3398 
3399 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3400 		kvm_vcpu_flush_tlb_guest(vcpu);
3401 }
3402 EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
3403 
record_steal_time(struct kvm_vcpu * vcpu)3404 static void record_steal_time(struct kvm_vcpu *vcpu)
3405 {
3406 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3407 	struct kvm_steal_time __user *st;
3408 	struct kvm_memslots *slots;
3409 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3410 	u64 steal;
3411 	u32 version;
3412 
3413 	if (kvm_xen_msr_enabled(vcpu->kvm)) {
3414 		kvm_xen_runstate_set_running(vcpu);
3415 		return;
3416 	}
3417 
3418 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3419 		return;
3420 
3421 	if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3422 		return;
3423 
3424 	slots = kvm_memslots(vcpu->kvm);
3425 
3426 	if (unlikely(slots->generation != ghc->generation ||
3427 		     gpa != ghc->gpa ||
3428 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3429 		/* We rely on the fact that it fits in a single page. */
3430 		BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3431 
3432 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3433 		    kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3434 			return;
3435 	}
3436 
3437 	st = (struct kvm_steal_time __user *)ghc->hva;
3438 	/*
3439 	 * Doing a TLB flush here, on the guest's behalf, can avoid
3440 	 * expensive IPIs.
3441 	 */
3442 	if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3443 		u8 st_preempted = 0;
3444 		int err = -EFAULT;
3445 
3446 		if (!user_access_begin(st, sizeof(*st)))
3447 			return;
3448 
3449 		asm volatile("1: xchgb %0, %2\n"
3450 			     "xor %1, %1\n"
3451 			     "2:\n"
3452 			     _ASM_EXTABLE_UA(1b, 2b)
3453 			     : "+q" (st_preempted),
3454 			       "+&r" (err),
3455 			       "+m" (st->preempted));
3456 		if (err)
3457 			goto out;
3458 
3459 		user_access_end();
3460 
3461 		vcpu->arch.st.preempted = 0;
3462 
3463 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3464 				       st_preempted & KVM_VCPU_FLUSH_TLB);
3465 		if (st_preempted & KVM_VCPU_FLUSH_TLB)
3466 			kvm_vcpu_flush_tlb_guest(vcpu);
3467 
3468 		if (!user_access_begin(st, sizeof(*st)))
3469 			goto dirty;
3470 	} else {
3471 		if (!user_access_begin(st, sizeof(*st)))
3472 			return;
3473 
3474 		unsafe_put_user(0, &st->preempted, out);
3475 		vcpu->arch.st.preempted = 0;
3476 	}
3477 
3478 	unsafe_get_user(version, &st->version, out);
3479 	if (version & 1)
3480 		version += 1;  /* first time write, random junk */
3481 
3482 	version += 1;
3483 	unsafe_put_user(version, &st->version, out);
3484 
3485 	smp_wmb();
3486 
3487 	unsafe_get_user(steal, &st->steal, out);
3488 	steal += current->sched_info.run_delay -
3489 		vcpu->arch.st.last_steal;
3490 	vcpu->arch.st.last_steal = current->sched_info.run_delay;
3491 	unsafe_put_user(steal, &st->steal, out);
3492 
3493 	version += 1;
3494 	unsafe_put_user(version, &st->version, out);
3495 
3496  out:
3497 	user_access_end();
3498  dirty:
3499 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3500 }
3501 
kvm_set_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3502 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3503 {
3504 	bool pr = false;
3505 	u32 msr = msr_info->index;
3506 	u64 data = msr_info->data;
3507 
3508 	if (msr && msr == vcpu->kvm->arch.xen_hvm_config.msr)
3509 		return kvm_xen_write_hypercall_page(vcpu, data);
3510 
3511 	switch (msr) {
3512 	case MSR_AMD64_NB_CFG:
3513 	case MSR_IA32_UCODE_WRITE:
3514 	case MSR_VM_HSAVE_PA:
3515 	case MSR_AMD64_PATCH_LOADER:
3516 	case MSR_AMD64_BU_CFG2:
3517 	case MSR_AMD64_DC_CFG:
3518 	case MSR_F15H_EX_CFG:
3519 		break;
3520 
3521 	case MSR_IA32_UCODE_REV:
3522 		if (msr_info->host_initiated)
3523 			vcpu->arch.microcode_version = data;
3524 		break;
3525 	case MSR_IA32_ARCH_CAPABILITIES:
3526 		if (!msr_info->host_initiated)
3527 			return 1;
3528 		vcpu->arch.arch_capabilities = data;
3529 		break;
3530 	case MSR_IA32_PERF_CAPABILITIES: {
3531 		struct kvm_msr_entry msr_ent = {.index = msr, .data = 0};
3532 
3533 		if (!msr_info->host_initiated)
3534 			return 1;
3535 		if (kvm_get_msr_feature(&msr_ent))
3536 			return 1;
3537 		if (data & ~msr_ent.data)
3538 			return 1;
3539 
3540 		vcpu->arch.perf_capabilities = data;
3541 
3542 		return 0;
3543 		}
3544 	case MSR_EFER:
3545 		return set_efer(vcpu, msr_info);
3546 	case MSR_K7_HWCR:
3547 		data &= ~(u64)0x40;	/* ignore flush filter disable */
3548 		data &= ~(u64)0x100;	/* ignore ignne emulation enable */
3549 		data &= ~(u64)0x8;	/* ignore TLB cache disable */
3550 
3551 		/* Handle McStatusWrEn */
3552 		if (data == BIT_ULL(18)) {
3553 			vcpu->arch.msr_hwcr = data;
3554 		} else if (data != 0) {
3555 			vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
3556 				    data);
3557 			return 1;
3558 		}
3559 		break;
3560 	case MSR_FAM10H_MMIO_CONF_BASE:
3561 		if (data != 0) {
3562 			vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
3563 				    "0x%llx\n", data);
3564 			return 1;
3565 		}
3566 		break;
3567 	case 0x200 ... 0x2ff:
3568 		return kvm_mtrr_set_msr(vcpu, msr, data);
3569 	case MSR_IA32_APICBASE:
3570 		return kvm_set_apic_base(vcpu, msr_info);
3571 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3572 		return kvm_x2apic_msr_write(vcpu, msr, data);
3573 	case MSR_IA32_TSC_DEADLINE:
3574 		kvm_set_lapic_tscdeadline_msr(vcpu, data);
3575 		break;
3576 	case MSR_IA32_TSC_ADJUST:
3577 		if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3578 			if (!msr_info->host_initiated) {
3579 				s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3580 				adjust_tsc_offset_guest(vcpu, adj);
3581 				/* Before back to guest, tsc_timestamp must be adjusted
3582 				 * as well, otherwise guest's percpu pvclock time could jump.
3583 				 */
3584 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3585 			}
3586 			vcpu->arch.ia32_tsc_adjust_msr = data;
3587 		}
3588 		break;
3589 	case MSR_IA32_MISC_ENABLE:
3590 		if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3591 		    ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
3592 			if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
3593 				return 1;
3594 			vcpu->arch.ia32_misc_enable_msr = data;
3595 			kvm_update_cpuid_runtime(vcpu);
3596 		} else {
3597 			vcpu->arch.ia32_misc_enable_msr = data;
3598 		}
3599 		break;
3600 	case MSR_IA32_SMBASE:
3601 		if (!msr_info->host_initiated)
3602 			return 1;
3603 		vcpu->arch.smbase = data;
3604 		break;
3605 	case MSR_IA32_POWER_CTL:
3606 		vcpu->arch.msr_ia32_power_ctl = data;
3607 		break;
3608 	case MSR_IA32_TSC:
3609 		if (msr_info->host_initiated) {
3610 			kvm_synchronize_tsc(vcpu, data);
3611 		} else {
3612 			u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3613 			adjust_tsc_offset_guest(vcpu, adj);
3614 			vcpu->arch.ia32_tsc_adjust_msr += adj;
3615 		}
3616 		break;
3617 	case MSR_IA32_XSS:
3618 		if (!msr_info->host_initiated &&
3619 		    !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3620 			return 1;
3621 		/*
3622 		 * KVM supports exposing PT to the guest, but does not support
3623 		 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3624 		 * XSAVES/XRSTORS to save/restore PT MSRs.
3625 		 */
3626 		if (data & ~supported_xss)
3627 			return 1;
3628 		vcpu->arch.ia32_xss = data;
3629 		kvm_update_cpuid_runtime(vcpu);
3630 		break;
3631 	case MSR_SMI_COUNT:
3632 		if (!msr_info->host_initiated)
3633 			return 1;
3634 		vcpu->arch.smi_count = data;
3635 		break;
3636 	case MSR_KVM_WALL_CLOCK_NEW:
3637 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3638 			return 1;
3639 
3640 		vcpu->kvm->arch.wall_clock = data;
3641 		kvm_write_wall_clock(vcpu->kvm, data, 0);
3642 		break;
3643 	case MSR_KVM_WALL_CLOCK:
3644 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3645 			return 1;
3646 
3647 		vcpu->kvm->arch.wall_clock = data;
3648 		kvm_write_wall_clock(vcpu->kvm, data, 0);
3649 		break;
3650 	case MSR_KVM_SYSTEM_TIME_NEW:
3651 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3652 			return 1;
3653 
3654 		kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3655 		break;
3656 	case MSR_KVM_SYSTEM_TIME:
3657 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3658 			return 1;
3659 
3660 		kvm_write_system_time(vcpu, data, true,  msr_info->host_initiated);
3661 		break;
3662 	case MSR_KVM_ASYNC_PF_EN:
3663 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3664 			return 1;
3665 
3666 		if (kvm_pv_enable_async_pf(vcpu, data))
3667 			return 1;
3668 		break;
3669 	case MSR_KVM_ASYNC_PF_INT:
3670 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3671 			return 1;
3672 
3673 		if (kvm_pv_enable_async_pf_int(vcpu, data))
3674 			return 1;
3675 		break;
3676 	case MSR_KVM_ASYNC_PF_ACK:
3677 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3678 			return 1;
3679 		if (data & 0x1) {
3680 			vcpu->arch.apf.pageready_pending = false;
3681 			kvm_check_async_pf_completion(vcpu);
3682 		}
3683 		break;
3684 	case MSR_KVM_STEAL_TIME:
3685 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3686 			return 1;
3687 
3688 		if (unlikely(!sched_info_on()))
3689 			return 1;
3690 
3691 		if (data & KVM_STEAL_RESERVED_MASK)
3692 			return 1;
3693 
3694 		vcpu->arch.st.msr_val = data;
3695 
3696 		if (!(data & KVM_MSR_ENABLED))
3697 			break;
3698 
3699 		kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3700 
3701 		break;
3702 	case MSR_KVM_PV_EOI_EN:
3703 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3704 			return 1;
3705 
3706 		if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
3707 			return 1;
3708 		break;
3709 
3710 	case MSR_KVM_POLL_CONTROL:
3711 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3712 			return 1;
3713 
3714 		/* only enable bit supported */
3715 		if (data & (-1ULL << 1))
3716 			return 1;
3717 
3718 		vcpu->arch.msr_kvm_poll_control = data;
3719 		break;
3720 
3721 	case MSR_IA32_MCG_CTL:
3722 	case MSR_IA32_MCG_STATUS:
3723 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3724 		return set_msr_mce(vcpu, msr_info);
3725 
3726 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3727 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3728 		pr = true;
3729 		fallthrough;
3730 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3731 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3732 		if (kvm_pmu_is_valid_msr(vcpu, msr))
3733 			return kvm_pmu_set_msr(vcpu, msr_info);
3734 
3735 		if (pr || data != 0)
3736 			vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3737 				    "0x%x data 0x%llx\n", msr, data);
3738 		break;
3739 	case MSR_K7_CLK_CTL:
3740 		/*
3741 		 * Ignore all writes to this no longer documented MSR.
3742 		 * Writes are only relevant for old K7 processors,
3743 		 * all pre-dating SVM, but a recommended workaround from
3744 		 * AMD for these chips. It is possible to specify the
3745 		 * affected processor models on the command line, hence
3746 		 * the need to ignore the workaround.
3747 		 */
3748 		break;
3749 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3750 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3751 	case HV_X64_MSR_SYNDBG_OPTIONS:
3752 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3753 	case HV_X64_MSR_CRASH_CTL:
3754 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3755 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3756 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
3757 	case HV_X64_MSR_TSC_EMULATION_STATUS:
3758 		return kvm_hv_set_msr_common(vcpu, msr, data,
3759 					     msr_info->host_initiated);
3760 	case MSR_IA32_BBL_CR_CTL3:
3761 		/* Drop writes to this legacy MSR -- see rdmsr
3762 		 * counterpart for further detail.
3763 		 */
3764 		if (report_ignored_msrs)
3765 			vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3766 				msr, data);
3767 		break;
3768 	case MSR_AMD64_OSVW_ID_LENGTH:
3769 		if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3770 			return 1;
3771 		vcpu->arch.osvw.length = data;
3772 		break;
3773 	case MSR_AMD64_OSVW_STATUS:
3774 		if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3775 			return 1;
3776 		vcpu->arch.osvw.status = data;
3777 		break;
3778 	case MSR_PLATFORM_INFO:
3779 		if (!msr_info->host_initiated ||
3780 		    (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3781 		     cpuid_fault_enabled(vcpu)))
3782 			return 1;
3783 		vcpu->arch.msr_platform_info = data;
3784 		break;
3785 	case MSR_MISC_FEATURES_ENABLES:
3786 		if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3787 		    (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3788 		     !supports_cpuid_fault(vcpu)))
3789 			return 1;
3790 		vcpu->arch.msr_misc_features_enables = data;
3791 		break;
3792 #ifdef CONFIG_X86_64
3793 	case MSR_IA32_XFD:
3794 		if (!msr_info->host_initiated &&
3795 		    !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
3796 			return 1;
3797 
3798 		if (data & ~kvm_guest_supported_xfd(vcpu))
3799 			return 1;
3800 
3801 		fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
3802 		break;
3803 	case MSR_IA32_XFD_ERR:
3804 		if (!msr_info->host_initiated &&
3805 		    !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
3806 			return 1;
3807 
3808 		if (data & ~kvm_guest_supported_xfd(vcpu))
3809 			return 1;
3810 
3811 		vcpu->arch.guest_fpu.xfd_err = data;
3812 		break;
3813 #endif
3814 	default:
3815 		if (kvm_pmu_is_valid_msr(vcpu, msr))
3816 			return kvm_pmu_set_msr(vcpu, msr_info);
3817 		return KVM_MSR_RET_INVALID;
3818 	}
3819 	return 0;
3820 }
3821 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3822 
get_msr_mce(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)3823 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3824 {
3825 	u64 data;
3826 	u64 mcg_cap = vcpu->arch.mcg_cap;
3827 	unsigned bank_num = mcg_cap & 0xff;
3828 
3829 	switch (msr) {
3830 	case MSR_IA32_P5_MC_ADDR:
3831 	case MSR_IA32_P5_MC_TYPE:
3832 		data = 0;
3833 		break;
3834 	case MSR_IA32_MCG_CAP:
3835 		data = vcpu->arch.mcg_cap;
3836 		break;
3837 	case MSR_IA32_MCG_CTL:
3838 		if (!(mcg_cap & MCG_CTL_P) && !host)
3839 			return 1;
3840 		data = vcpu->arch.mcg_ctl;
3841 		break;
3842 	case MSR_IA32_MCG_STATUS:
3843 		data = vcpu->arch.mcg_status;
3844 		break;
3845 	default:
3846 		if (msr >= MSR_IA32_MC0_CTL &&
3847 		    msr < MSR_IA32_MCx_CTL(bank_num)) {
3848 			u32 offset = array_index_nospec(
3849 				msr - MSR_IA32_MC0_CTL,
3850 				MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3851 
3852 			data = vcpu->arch.mce_banks[offset];
3853 			break;
3854 		}
3855 		return 1;
3856 	}
3857 	*pdata = data;
3858 	return 0;
3859 }
3860 
kvm_get_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3861 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3862 {
3863 	switch (msr_info->index) {
3864 	case MSR_IA32_PLATFORM_ID:
3865 	case MSR_IA32_EBL_CR_POWERON:
3866 	case MSR_IA32_LASTBRANCHFROMIP:
3867 	case MSR_IA32_LASTBRANCHTOIP:
3868 	case MSR_IA32_LASTINTFROMIP:
3869 	case MSR_IA32_LASTINTTOIP:
3870 	case MSR_AMD64_SYSCFG:
3871 	case MSR_K8_TSEG_ADDR:
3872 	case MSR_K8_TSEG_MASK:
3873 	case MSR_VM_HSAVE_PA:
3874 	case MSR_K8_INT_PENDING_MSG:
3875 	case MSR_AMD64_NB_CFG:
3876 	case MSR_FAM10H_MMIO_CONF_BASE:
3877 	case MSR_AMD64_BU_CFG2:
3878 	case MSR_IA32_PERF_CTL:
3879 	case MSR_AMD64_DC_CFG:
3880 	case MSR_F15H_EX_CFG:
3881 	/*
3882 	 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3883 	 * limit) MSRs. Just return 0, as we do not want to expose the host
3884 	 * data here. Do not conditionalize this on CPUID, as KVM does not do
3885 	 * so for existing CPU-specific MSRs.
3886 	 */
3887 	case MSR_RAPL_POWER_UNIT:
3888 	case MSR_PP0_ENERGY_STATUS:	/* Power plane 0 (core) */
3889 	case MSR_PP1_ENERGY_STATUS:	/* Power plane 1 (graphics uncore) */
3890 	case MSR_PKG_ENERGY_STATUS:	/* Total package */
3891 	case MSR_DRAM_ENERGY_STATUS:	/* DRAM controller */
3892 		msr_info->data = 0;
3893 		break;
3894 	case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3895 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3896 			return kvm_pmu_get_msr(vcpu, msr_info);
3897 		if (!msr_info->host_initiated)
3898 			return 1;
3899 		msr_info->data = 0;
3900 		break;
3901 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3902 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3903 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3904 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3905 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3906 			return kvm_pmu_get_msr(vcpu, msr_info);
3907 		msr_info->data = 0;
3908 		break;
3909 	case MSR_IA32_UCODE_REV:
3910 		msr_info->data = vcpu->arch.microcode_version;
3911 		break;
3912 	case MSR_IA32_ARCH_CAPABILITIES:
3913 		if (!msr_info->host_initiated &&
3914 		    !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3915 			return 1;
3916 		msr_info->data = vcpu->arch.arch_capabilities;
3917 		break;
3918 	case MSR_IA32_PERF_CAPABILITIES:
3919 		if (!msr_info->host_initiated &&
3920 		    !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
3921 			return 1;
3922 		msr_info->data = vcpu->arch.perf_capabilities;
3923 		break;
3924 	case MSR_IA32_POWER_CTL:
3925 		msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3926 		break;
3927 	case MSR_IA32_TSC: {
3928 		/*
3929 		 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
3930 		 * even when not intercepted. AMD manual doesn't explicitly
3931 		 * state this but appears to behave the same.
3932 		 *
3933 		 * On userspace reads and writes, however, we unconditionally
3934 		 * return L1's TSC value to ensure backwards-compatible
3935 		 * behavior for migration.
3936 		 */
3937 		u64 offset, ratio;
3938 
3939 		if (msr_info->host_initiated) {
3940 			offset = vcpu->arch.l1_tsc_offset;
3941 			ratio = vcpu->arch.l1_tsc_scaling_ratio;
3942 		} else {
3943 			offset = vcpu->arch.tsc_offset;
3944 			ratio = vcpu->arch.tsc_scaling_ratio;
3945 		}
3946 
3947 		msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
3948 		break;
3949 	}
3950 	case MSR_MTRRcap:
3951 	case 0x200 ... 0x2ff:
3952 		return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3953 	case 0xcd: /* fsb frequency */
3954 		msr_info->data = 3;
3955 		break;
3956 		/*
3957 		 * MSR_EBC_FREQUENCY_ID
3958 		 * Conservative value valid for even the basic CPU models.
3959 		 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3960 		 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3961 		 * and 266MHz for model 3, or 4. Set Core Clock
3962 		 * Frequency to System Bus Frequency Ratio to 1 (bits
3963 		 * 31:24) even though these are only valid for CPU
3964 		 * models > 2, however guests may end up dividing or
3965 		 * multiplying by zero otherwise.
3966 		 */
3967 	case MSR_EBC_FREQUENCY_ID:
3968 		msr_info->data = 1 << 24;
3969 		break;
3970 	case MSR_IA32_APICBASE:
3971 		msr_info->data = kvm_get_apic_base(vcpu);
3972 		break;
3973 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3974 		return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3975 	case MSR_IA32_TSC_DEADLINE:
3976 		msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3977 		break;
3978 	case MSR_IA32_TSC_ADJUST:
3979 		msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3980 		break;
3981 	case MSR_IA32_MISC_ENABLE:
3982 		msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3983 		break;
3984 	case MSR_IA32_SMBASE:
3985 		if (!msr_info->host_initiated)
3986 			return 1;
3987 		msr_info->data = vcpu->arch.smbase;
3988 		break;
3989 	case MSR_SMI_COUNT:
3990 		msr_info->data = vcpu->arch.smi_count;
3991 		break;
3992 	case MSR_IA32_PERF_STATUS:
3993 		/* TSC increment by tick */
3994 		msr_info->data = 1000ULL;
3995 		/* CPU multiplier */
3996 		msr_info->data |= (((uint64_t)4ULL) << 40);
3997 		break;
3998 	case MSR_EFER:
3999 		msr_info->data = vcpu->arch.efer;
4000 		break;
4001 	case MSR_KVM_WALL_CLOCK:
4002 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4003 			return 1;
4004 
4005 		msr_info->data = vcpu->kvm->arch.wall_clock;
4006 		break;
4007 	case MSR_KVM_WALL_CLOCK_NEW:
4008 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4009 			return 1;
4010 
4011 		msr_info->data = vcpu->kvm->arch.wall_clock;
4012 		break;
4013 	case MSR_KVM_SYSTEM_TIME:
4014 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4015 			return 1;
4016 
4017 		msr_info->data = vcpu->arch.time;
4018 		break;
4019 	case MSR_KVM_SYSTEM_TIME_NEW:
4020 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4021 			return 1;
4022 
4023 		msr_info->data = vcpu->arch.time;
4024 		break;
4025 	case MSR_KVM_ASYNC_PF_EN:
4026 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4027 			return 1;
4028 
4029 		msr_info->data = vcpu->arch.apf.msr_en_val;
4030 		break;
4031 	case MSR_KVM_ASYNC_PF_INT:
4032 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4033 			return 1;
4034 
4035 		msr_info->data = vcpu->arch.apf.msr_int_val;
4036 		break;
4037 	case MSR_KVM_ASYNC_PF_ACK:
4038 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4039 			return 1;
4040 
4041 		msr_info->data = 0;
4042 		break;
4043 	case MSR_KVM_STEAL_TIME:
4044 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4045 			return 1;
4046 
4047 		msr_info->data = vcpu->arch.st.msr_val;
4048 		break;
4049 	case MSR_KVM_PV_EOI_EN:
4050 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4051 			return 1;
4052 
4053 		msr_info->data = vcpu->arch.pv_eoi.msr_val;
4054 		break;
4055 	case MSR_KVM_POLL_CONTROL:
4056 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4057 			return 1;
4058 
4059 		msr_info->data = vcpu->arch.msr_kvm_poll_control;
4060 		break;
4061 	case MSR_IA32_P5_MC_ADDR:
4062 	case MSR_IA32_P5_MC_TYPE:
4063 	case MSR_IA32_MCG_CAP:
4064 	case MSR_IA32_MCG_CTL:
4065 	case MSR_IA32_MCG_STATUS:
4066 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4067 		return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4068 				   msr_info->host_initiated);
4069 	case MSR_IA32_XSS:
4070 		if (!msr_info->host_initiated &&
4071 		    !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4072 			return 1;
4073 		msr_info->data = vcpu->arch.ia32_xss;
4074 		break;
4075 	case MSR_K7_CLK_CTL:
4076 		/*
4077 		 * Provide expected ramp-up count for K7. All other
4078 		 * are set to zero, indicating minimum divisors for
4079 		 * every field.
4080 		 *
4081 		 * This prevents guest kernels on AMD host with CPU
4082 		 * type 6, model 8 and higher from exploding due to
4083 		 * the rdmsr failing.
4084 		 */
4085 		msr_info->data = 0x20000000;
4086 		break;
4087 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4088 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4089 	case HV_X64_MSR_SYNDBG_OPTIONS:
4090 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4091 	case HV_X64_MSR_CRASH_CTL:
4092 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4093 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4094 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4095 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4096 		return kvm_hv_get_msr_common(vcpu,
4097 					     msr_info->index, &msr_info->data,
4098 					     msr_info->host_initiated);
4099 	case MSR_IA32_BBL_CR_CTL3:
4100 		/* This legacy MSR exists but isn't fully documented in current
4101 		 * silicon.  It is however accessed by winxp in very narrow
4102 		 * scenarios where it sets bit #19, itself documented as
4103 		 * a "reserved" bit.  Best effort attempt to source coherent
4104 		 * read data here should the balance of the register be
4105 		 * interpreted by the guest:
4106 		 *
4107 		 * L2 cache control register 3: 64GB range, 256KB size,
4108 		 * enabled, latency 0x1, configured
4109 		 */
4110 		msr_info->data = 0xbe702111;
4111 		break;
4112 	case MSR_AMD64_OSVW_ID_LENGTH:
4113 		if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4114 			return 1;
4115 		msr_info->data = vcpu->arch.osvw.length;
4116 		break;
4117 	case MSR_AMD64_OSVW_STATUS:
4118 		if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4119 			return 1;
4120 		msr_info->data = vcpu->arch.osvw.status;
4121 		break;
4122 	case MSR_PLATFORM_INFO:
4123 		if (!msr_info->host_initiated &&
4124 		    !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4125 			return 1;
4126 		msr_info->data = vcpu->arch.msr_platform_info;
4127 		break;
4128 	case MSR_MISC_FEATURES_ENABLES:
4129 		msr_info->data = vcpu->arch.msr_misc_features_enables;
4130 		break;
4131 	case MSR_K7_HWCR:
4132 		msr_info->data = vcpu->arch.msr_hwcr;
4133 		break;
4134 #ifdef CONFIG_X86_64
4135 	case MSR_IA32_XFD:
4136 		if (!msr_info->host_initiated &&
4137 		    !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4138 			return 1;
4139 
4140 		msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4141 		break;
4142 	case MSR_IA32_XFD_ERR:
4143 		if (!msr_info->host_initiated &&
4144 		    !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4145 			return 1;
4146 
4147 		msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4148 		break;
4149 #endif
4150 	default:
4151 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4152 			return kvm_pmu_get_msr(vcpu, msr_info);
4153 		return KVM_MSR_RET_INVALID;
4154 	}
4155 	return 0;
4156 }
4157 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
4158 
4159 /*
4160  * Read or write a bunch of msrs. All parameters are kernel addresses.
4161  *
4162  * @return number of msrs set successfully.
4163  */
__msr_io(struct kvm_vcpu * vcpu,struct kvm_msrs * msrs,struct kvm_msr_entry * entries,int (* do_msr)(struct kvm_vcpu * vcpu,unsigned index,u64 * data))4164 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4165 		    struct kvm_msr_entry *entries,
4166 		    int (*do_msr)(struct kvm_vcpu *vcpu,
4167 				  unsigned index, u64 *data))
4168 {
4169 	int i;
4170 
4171 	for (i = 0; i < msrs->nmsrs; ++i)
4172 		if (do_msr(vcpu, entries[i].index, &entries[i].data))
4173 			break;
4174 
4175 	return i;
4176 }
4177 
4178 /*
4179  * Read or write a bunch of msrs. Parameters are user addresses.
4180  *
4181  * @return number of msrs set successfully.
4182  */
msr_io(struct kvm_vcpu * vcpu,struct kvm_msrs __user * user_msrs,int (* do_msr)(struct kvm_vcpu * vcpu,unsigned index,u64 * data),int writeback)4183 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4184 		  int (*do_msr)(struct kvm_vcpu *vcpu,
4185 				unsigned index, u64 *data),
4186 		  int writeback)
4187 {
4188 	struct kvm_msrs msrs;
4189 	struct kvm_msr_entry *entries;
4190 	int r, n;
4191 	unsigned size;
4192 
4193 	r = -EFAULT;
4194 	if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4195 		goto out;
4196 
4197 	r = -E2BIG;
4198 	if (msrs.nmsrs >= MAX_IO_MSRS)
4199 		goto out;
4200 
4201 	size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4202 	entries = memdup_user(user_msrs->entries, size);
4203 	if (IS_ERR(entries)) {
4204 		r = PTR_ERR(entries);
4205 		goto out;
4206 	}
4207 
4208 	r = n = __msr_io(vcpu, &msrs, entries, do_msr);
4209 	if (r < 0)
4210 		goto out_free;
4211 
4212 	r = -EFAULT;
4213 	if (writeback && copy_to_user(user_msrs->entries, entries, size))
4214 		goto out_free;
4215 
4216 	r = n;
4217 
4218 out_free:
4219 	kfree(entries);
4220 out:
4221 	return r;
4222 }
4223 
kvm_can_mwait_in_guest(void)4224 static inline bool kvm_can_mwait_in_guest(void)
4225 {
4226 	return boot_cpu_has(X86_FEATURE_MWAIT) &&
4227 		!boot_cpu_has_bug(X86_BUG_MONITOR) &&
4228 		boot_cpu_has(X86_FEATURE_ARAT);
4229 }
4230 
kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 __user * cpuid_arg)4231 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4232 					    struct kvm_cpuid2 __user *cpuid_arg)
4233 {
4234 	struct kvm_cpuid2 cpuid;
4235 	int r;
4236 
4237 	r = -EFAULT;
4238 	if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4239 		return r;
4240 
4241 	r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4242 	if (r)
4243 		return r;
4244 
4245 	r = -EFAULT;
4246 	if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4247 		return r;
4248 
4249 	return 0;
4250 }
4251 
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)4252 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4253 {
4254 	int r = 0;
4255 
4256 	switch (ext) {
4257 	case KVM_CAP_IRQCHIP:
4258 	case KVM_CAP_HLT:
4259 	case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4260 	case KVM_CAP_SET_TSS_ADDR:
4261 	case KVM_CAP_EXT_CPUID:
4262 	case KVM_CAP_EXT_EMUL_CPUID:
4263 	case KVM_CAP_CLOCKSOURCE:
4264 	case KVM_CAP_PIT:
4265 	case KVM_CAP_NOP_IO_DELAY:
4266 	case KVM_CAP_MP_STATE:
4267 	case KVM_CAP_SYNC_MMU:
4268 	case KVM_CAP_USER_NMI:
4269 	case KVM_CAP_REINJECT_CONTROL:
4270 	case KVM_CAP_IRQ_INJECT_STATUS:
4271 	case KVM_CAP_IOEVENTFD:
4272 	case KVM_CAP_IOEVENTFD_NO_LENGTH:
4273 	case KVM_CAP_PIT2:
4274 	case KVM_CAP_PIT_STATE2:
4275 	case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4276 	case KVM_CAP_VCPU_EVENTS:
4277 	case KVM_CAP_HYPERV:
4278 	case KVM_CAP_HYPERV_VAPIC:
4279 	case KVM_CAP_HYPERV_SPIN:
4280 	case KVM_CAP_HYPERV_SYNIC:
4281 	case KVM_CAP_HYPERV_SYNIC2:
4282 	case KVM_CAP_HYPERV_VP_INDEX:
4283 	case KVM_CAP_HYPERV_EVENTFD:
4284 	case KVM_CAP_HYPERV_TLBFLUSH:
4285 	case KVM_CAP_HYPERV_SEND_IPI:
4286 	case KVM_CAP_HYPERV_CPUID:
4287 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
4288 	case KVM_CAP_SYS_HYPERV_CPUID:
4289 	case KVM_CAP_PCI_SEGMENT:
4290 	case KVM_CAP_DEBUGREGS:
4291 	case KVM_CAP_X86_ROBUST_SINGLESTEP:
4292 	case KVM_CAP_XSAVE:
4293 	case KVM_CAP_ASYNC_PF:
4294 	case KVM_CAP_ASYNC_PF_INT:
4295 	case KVM_CAP_GET_TSC_KHZ:
4296 	case KVM_CAP_KVMCLOCK_CTRL:
4297 	case KVM_CAP_READONLY_MEM:
4298 	case KVM_CAP_HYPERV_TIME:
4299 	case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4300 	case KVM_CAP_TSC_DEADLINE_TIMER:
4301 	case KVM_CAP_DISABLE_QUIRKS:
4302 	case KVM_CAP_SET_BOOT_CPU_ID:
4303  	case KVM_CAP_SPLIT_IRQCHIP:
4304 	case KVM_CAP_IMMEDIATE_EXIT:
4305 	case KVM_CAP_PMU_EVENT_FILTER:
4306 	case KVM_CAP_GET_MSR_FEATURES:
4307 	case KVM_CAP_MSR_PLATFORM_INFO:
4308 	case KVM_CAP_EXCEPTION_PAYLOAD:
4309 	case KVM_CAP_SET_GUEST_DEBUG:
4310 	case KVM_CAP_LAST_CPU:
4311 	case KVM_CAP_X86_USER_SPACE_MSR:
4312 	case KVM_CAP_X86_MSR_FILTER:
4313 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4314 #ifdef CONFIG_X86_SGX_KVM
4315 	case KVM_CAP_SGX_ATTRIBUTE:
4316 #endif
4317 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4318 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4319 	case KVM_CAP_SREGS2:
4320 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4321 	case KVM_CAP_VCPU_ATTRIBUTES:
4322 	case KVM_CAP_SYS_ATTRIBUTES:
4323 	case KVM_CAP_VAPIC:
4324 	case KVM_CAP_ENABLE_CAP:
4325 		r = 1;
4326 		break;
4327 	case KVM_CAP_EXIT_HYPERCALL:
4328 		r = KVM_EXIT_HYPERCALL_VALID_MASK;
4329 		break;
4330 	case KVM_CAP_SET_GUEST_DEBUG2:
4331 		return KVM_GUESTDBG_VALID_MASK;
4332 #ifdef CONFIG_KVM_XEN
4333 	case KVM_CAP_XEN_HVM:
4334 		r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4335 		    KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4336 		    KVM_XEN_HVM_CONFIG_SHARED_INFO |
4337 		    KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4338 		    KVM_XEN_HVM_CONFIG_EVTCHN_SEND;
4339 		if (sched_info_on())
4340 			r |= KVM_XEN_HVM_CONFIG_RUNSTATE;
4341 		break;
4342 #endif
4343 	case KVM_CAP_SYNC_REGS:
4344 		r = KVM_SYNC_X86_VALID_FIELDS;
4345 		break;
4346 	case KVM_CAP_ADJUST_CLOCK:
4347 		r = KVM_CLOCK_VALID_FLAGS;
4348 		break;
4349 	case KVM_CAP_X86_DISABLE_EXITS:
4350 		r |=  KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
4351 		      KVM_X86_DISABLE_EXITS_CSTATE;
4352 		if(kvm_can_mwait_in_guest())
4353 			r |= KVM_X86_DISABLE_EXITS_MWAIT;
4354 		break;
4355 	case KVM_CAP_X86_SMM:
4356 		/* SMBASE is usually relocated above 1M on modern chipsets,
4357 		 * and SMM handlers might indeed rely on 4G segment limits,
4358 		 * so do not report SMM to be available if real mode is
4359 		 * emulated via vm86 mode.  Still, do not go to great lengths
4360 		 * to avoid userspace's usage of the feature, because it is a
4361 		 * fringe case that is not enabled except via specific settings
4362 		 * of the module parameters.
4363 		 */
4364 		r = static_call(kvm_x86_has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4365 		break;
4366 	case KVM_CAP_NR_VCPUS:
4367 		r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4368 		break;
4369 	case KVM_CAP_MAX_VCPUS:
4370 		r = KVM_MAX_VCPUS;
4371 		break;
4372 	case KVM_CAP_MAX_VCPU_ID:
4373 		r = KVM_MAX_VCPU_IDS;
4374 		break;
4375 	case KVM_CAP_PV_MMU:	/* obsolete */
4376 		r = 0;
4377 		break;
4378 	case KVM_CAP_MCE:
4379 		r = KVM_MAX_MCE_BANKS;
4380 		break;
4381 	case KVM_CAP_XCRS:
4382 		r = boot_cpu_has(X86_FEATURE_XSAVE);
4383 		break;
4384 	case KVM_CAP_TSC_CONTROL:
4385 	case KVM_CAP_VM_TSC_CONTROL:
4386 		r = kvm_has_tsc_control;
4387 		break;
4388 	case KVM_CAP_X2APIC_API:
4389 		r = KVM_X2APIC_API_VALID_FLAGS;
4390 		break;
4391 	case KVM_CAP_NESTED_STATE:
4392 		r = kvm_x86_ops.nested_ops->get_state ?
4393 			kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4394 		break;
4395 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4396 		r = kvm_x86_ops.enable_direct_tlbflush != NULL;
4397 		break;
4398 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4399 		r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4400 		break;
4401 	case KVM_CAP_SMALLER_MAXPHYADDR:
4402 		r = (int) allow_smaller_maxphyaddr;
4403 		break;
4404 	case KVM_CAP_STEAL_TIME:
4405 		r = sched_info_on();
4406 		break;
4407 	case KVM_CAP_X86_BUS_LOCK_EXIT:
4408 		if (kvm_has_bus_lock_exit)
4409 			r = KVM_BUS_LOCK_DETECTION_OFF |
4410 			    KVM_BUS_LOCK_DETECTION_EXIT;
4411 		else
4412 			r = 0;
4413 		break;
4414 	case KVM_CAP_XSAVE2: {
4415 		u64 guest_perm = xstate_get_guest_group_perm();
4416 
4417 		r = xstate_required_size(supported_xcr0 & guest_perm, false);
4418 		if (r < sizeof(struct kvm_xsave))
4419 			r = sizeof(struct kvm_xsave);
4420 		break;
4421 	}
4422 	case KVM_CAP_PMU_CAPABILITY:
4423 		r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4424 		break;
4425 	case KVM_CAP_DISABLE_QUIRKS2:
4426 		r = KVM_X86_VALID_QUIRKS;
4427 		break;
4428 	default:
4429 		break;
4430 	}
4431 	return r;
4432 }
4433 
kvm_get_attr_addr(struct kvm_device_attr * attr)4434 static inline void __user *kvm_get_attr_addr(struct kvm_device_attr *attr)
4435 {
4436 	void __user *uaddr = (void __user*)(unsigned long)attr->addr;
4437 
4438 	if ((u64)(unsigned long)uaddr != attr->addr)
4439 		return ERR_PTR_USR(-EFAULT);
4440 	return uaddr;
4441 }
4442 
kvm_x86_dev_get_attr(struct kvm_device_attr * attr)4443 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
4444 {
4445 	u64 __user *uaddr = kvm_get_attr_addr(attr);
4446 
4447 	if (attr->group)
4448 		return -ENXIO;
4449 
4450 	if (IS_ERR(uaddr))
4451 		return PTR_ERR(uaddr);
4452 
4453 	switch (attr->attr) {
4454 	case KVM_X86_XCOMP_GUEST_SUPP:
4455 		if (put_user(supported_xcr0, uaddr))
4456 			return -EFAULT;
4457 		return 0;
4458 	default:
4459 		return -ENXIO;
4460 		break;
4461 	}
4462 }
4463 
kvm_x86_dev_has_attr(struct kvm_device_attr * attr)4464 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
4465 {
4466 	if (attr->group)
4467 		return -ENXIO;
4468 
4469 	switch (attr->attr) {
4470 	case KVM_X86_XCOMP_GUEST_SUPP:
4471 		return 0;
4472 	default:
4473 		return -ENXIO;
4474 	}
4475 }
4476 
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4477 long kvm_arch_dev_ioctl(struct file *filp,
4478 			unsigned int ioctl, unsigned long arg)
4479 {
4480 	void __user *argp = (void __user *)arg;
4481 	long r;
4482 
4483 	switch (ioctl) {
4484 	case KVM_GET_MSR_INDEX_LIST: {
4485 		struct kvm_msr_list __user *user_msr_list = argp;
4486 		struct kvm_msr_list msr_list;
4487 		unsigned n;
4488 
4489 		r = -EFAULT;
4490 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4491 			goto out;
4492 		n = msr_list.nmsrs;
4493 		msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
4494 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4495 			goto out;
4496 		r = -E2BIG;
4497 		if (n < msr_list.nmsrs)
4498 			goto out;
4499 		r = -EFAULT;
4500 		if (copy_to_user(user_msr_list->indices, &msrs_to_save,
4501 				 num_msrs_to_save * sizeof(u32)))
4502 			goto out;
4503 		if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
4504 				 &emulated_msrs,
4505 				 num_emulated_msrs * sizeof(u32)))
4506 			goto out;
4507 		r = 0;
4508 		break;
4509 	}
4510 	case KVM_GET_SUPPORTED_CPUID:
4511 	case KVM_GET_EMULATED_CPUID: {
4512 		struct kvm_cpuid2 __user *cpuid_arg = argp;
4513 		struct kvm_cpuid2 cpuid;
4514 
4515 		r = -EFAULT;
4516 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4517 			goto out;
4518 
4519 		r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
4520 					    ioctl);
4521 		if (r)
4522 			goto out;
4523 
4524 		r = -EFAULT;
4525 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4526 			goto out;
4527 		r = 0;
4528 		break;
4529 	}
4530 	case KVM_X86_GET_MCE_CAP_SUPPORTED:
4531 		r = -EFAULT;
4532 		if (copy_to_user(argp, &kvm_mce_cap_supported,
4533 				 sizeof(kvm_mce_cap_supported)))
4534 			goto out;
4535 		r = 0;
4536 		break;
4537 	case KVM_GET_MSR_FEATURE_INDEX_LIST: {
4538 		struct kvm_msr_list __user *user_msr_list = argp;
4539 		struct kvm_msr_list msr_list;
4540 		unsigned int n;
4541 
4542 		r = -EFAULT;
4543 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4544 			goto out;
4545 		n = msr_list.nmsrs;
4546 		msr_list.nmsrs = num_msr_based_features;
4547 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4548 			goto out;
4549 		r = -E2BIG;
4550 		if (n < msr_list.nmsrs)
4551 			goto out;
4552 		r = -EFAULT;
4553 		if (copy_to_user(user_msr_list->indices, &msr_based_features,
4554 				 num_msr_based_features * sizeof(u32)))
4555 			goto out;
4556 		r = 0;
4557 		break;
4558 	}
4559 	case KVM_GET_MSRS:
4560 		r = msr_io(NULL, argp, do_get_msr_feature, 1);
4561 		break;
4562 	case KVM_GET_SUPPORTED_HV_CPUID:
4563 		r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
4564 		break;
4565 	case KVM_GET_DEVICE_ATTR: {
4566 		struct kvm_device_attr attr;
4567 		r = -EFAULT;
4568 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4569 			break;
4570 		r = kvm_x86_dev_get_attr(&attr);
4571 		break;
4572 	}
4573 	case KVM_HAS_DEVICE_ATTR: {
4574 		struct kvm_device_attr attr;
4575 		r = -EFAULT;
4576 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4577 			break;
4578 		r = kvm_x86_dev_has_attr(&attr);
4579 		break;
4580 	}
4581 	default:
4582 		r = -EINVAL;
4583 		break;
4584 	}
4585 out:
4586 	return r;
4587 }
4588 
wbinvd_ipi(void * garbage)4589 static void wbinvd_ipi(void *garbage)
4590 {
4591 	wbinvd();
4592 }
4593 
need_emulate_wbinvd(struct kvm_vcpu * vcpu)4594 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
4595 {
4596 	return kvm_arch_has_noncoherent_dma(vcpu->kvm);
4597 }
4598 
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)4599 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4600 {
4601 	/* Address WBINVD may be executed by guest */
4602 	if (need_emulate_wbinvd(vcpu)) {
4603 		if (static_call(kvm_x86_has_wbinvd_exit)())
4604 			cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4605 		else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
4606 			smp_call_function_single(vcpu->cpu,
4607 					wbinvd_ipi, NULL, 1);
4608 	}
4609 
4610 	static_call(kvm_x86_vcpu_load)(vcpu, cpu);
4611 
4612 	/* Save host pkru register if supported */
4613 	vcpu->arch.host_pkru = read_pkru();
4614 
4615 	/* Apply any externally detected TSC adjustments (due to suspend) */
4616 	if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
4617 		adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
4618 		vcpu->arch.tsc_offset_adjustment = 0;
4619 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4620 	}
4621 
4622 	if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
4623 		s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
4624 				rdtsc() - vcpu->arch.last_host_tsc;
4625 		if (tsc_delta < 0)
4626 			mark_tsc_unstable("KVM discovered backwards TSC");
4627 
4628 		if (kvm_check_tsc_unstable()) {
4629 			u64 offset = kvm_compute_l1_tsc_offset(vcpu,
4630 						vcpu->arch.last_guest_tsc);
4631 			kvm_vcpu_write_tsc_offset(vcpu, offset);
4632 			vcpu->arch.tsc_catchup = 1;
4633 		}
4634 
4635 		if (kvm_lapic_hv_timer_in_use(vcpu))
4636 			kvm_lapic_restart_hv_timer(vcpu);
4637 
4638 		/*
4639 		 * On a host with synchronized TSC, there is no need to update
4640 		 * kvmclock on vcpu->cpu migration
4641 		 */
4642 		if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
4643 			kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
4644 		if (vcpu->cpu != cpu)
4645 			kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
4646 		vcpu->cpu = cpu;
4647 	}
4648 
4649 	kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4650 }
4651 
kvm_steal_time_set_preempted(struct kvm_vcpu * vcpu)4652 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
4653 {
4654 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
4655 	struct kvm_steal_time __user *st;
4656 	struct kvm_memslots *slots;
4657 	static const u8 preempted = KVM_VCPU_PREEMPTED;
4658 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
4659 
4660 	/*
4661 	 * The vCPU can be marked preempted if and only if the VM-Exit was on
4662 	 * an instruction boundary and will not trigger guest emulation of any
4663 	 * kind (see vcpu_run).  Vendor specific code controls (conservatively)
4664 	 * when this is true, for example allowing the vCPU to be marked
4665 	 * preempted if and only if the VM-Exit was due to a host interrupt.
4666 	 */
4667 	if (!vcpu->arch.at_instruction_boundary) {
4668 		vcpu->stat.preemption_other++;
4669 		return;
4670 	}
4671 
4672 	vcpu->stat.preemption_reported++;
4673 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
4674 		return;
4675 
4676 	if (vcpu->arch.st.preempted)
4677 		return;
4678 
4679 	/* This happens on process exit */
4680 	if (unlikely(current->mm != vcpu->kvm->mm))
4681 		return;
4682 
4683 	slots = kvm_memslots(vcpu->kvm);
4684 
4685 	if (unlikely(slots->generation != ghc->generation ||
4686 		     gpa != ghc->gpa ||
4687 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot))
4688 		return;
4689 
4690 	st = (struct kvm_steal_time __user *)ghc->hva;
4691 	BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
4692 
4693 	if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
4694 		vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
4695 
4696 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
4697 }
4698 
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)4699 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
4700 {
4701 	int idx;
4702 
4703 	if (vcpu->preempted) {
4704 		if (!vcpu->arch.guest_state_protected)
4705 			vcpu->arch.preempted_in_kernel = !static_call(kvm_x86_get_cpl)(vcpu);
4706 
4707 		/*
4708 		 * Take the srcu lock as memslots will be accessed to check the gfn
4709 		 * cache generation against the memslots generation.
4710 		 */
4711 		idx = srcu_read_lock(&vcpu->kvm->srcu);
4712 		if (kvm_xen_msr_enabled(vcpu->kvm))
4713 			kvm_xen_runstate_set_preempted(vcpu);
4714 		else
4715 			kvm_steal_time_set_preempted(vcpu);
4716 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
4717 	}
4718 
4719 	static_call(kvm_x86_vcpu_put)(vcpu);
4720 	vcpu->arch.last_host_tsc = rdtsc();
4721 }
4722 
kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)4723 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
4724 				    struct kvm_lapic_state *s)
4725 {
4726 	static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
4727 
4728 	return kvm_apic_get_state(vcpu, s);
4729 }
4730 
kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)4731 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
4732 				    struct kvm_lapic_state *s)
4733 {
4734 	int r;
4735 
4736 	r = kvm_apic_set_state(vcpu, s);
4737 	if (r)
4738 		return r;
4739 	update_cr8_intercept(vcpu);
4740 
4741 	return 0;
4742 }
4743 
kvm_cpu_accept_dm_intr(struct kvm_vcpu * vcpu)4744 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
4745 {
4746 	/*
4747 	 * We can accept userspace's request for interrupt injection
4748 	 * as long as we have a place to store the interrupt number.
4749 	 * The actual injection will happen when the CPU is able to
4750 	 * deliver the interrupt.
4751 	 */
4752 	if (kvm_cpu_has_extint(vcpu))
4753 		return false;
4754 
4755 	/* Acknowledging ExtINT does not happen if LINT0 is masked.  */
4756 	return (!lapic_in_kernel(vcpu) ||
4757 		kvm_apic_accept_pic_intr(vcpu));
4758 }
4759 
kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu * vcpu)4760 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
4761 {
4762 	/*
4763 	 * Do not cause an interrupt window exit if an exception
4764 	 * is pending or an event needs reinjection; userspace
4765 	 * might want to inject the interrupt manually using KVM_SET_REGS
4766 	 * or KVM_SET_SREGS.  For that to work, we must be at an
4767 	 * instruction boundary and with no events half-injected.
4768 	 */
4769 	return (kvm_arch_interrupt_allowed(vcpu) &&
4770 		kvm_cpu_accept_dm_intr(vcpu) &&
4771 		!kvm_event_needs_reinjection(vcpu) &&
4772 		!vcpu->arch.exception.pending);
4773 }
4774 
kvm_vcpu_ioctl_interrupt(struct kvm_vcpu * vcpu,struct kvm_interrupt * irq)4775 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
4776 				    struct kvm_interrupt *irq)
4777 {
4778 	if (irq->irq >= KVM_NR_INTERRUPTS)
4779 		return -EINVAL;
4780 
4781 	if (!irqchip_in_kernel(vcpu->kvm)) {
4782 		kvm_queue_interrupt(vcpu, irq->irq, false);
4783 		kvm_make_request(KVM_REQ_EVENT, vcpu);
4784 		return 0;
4785 	}
4786 
4787 	/*
4788 	 * With in-kernel LAPIC, we only use this to inject EXTINT, so
4789 	 * fail for in-kernel 8259.
4790 	 */
4791 	if (pic_in_kernel(vcpu->kvm))
4792 		return -ENXIO;
4793 
4794 	if (vcpu->arch.pending_external_vector != -1)
4795 		return -EEXIST;
4796 
4797 	vcpu->arch.pending_external_vector = irq->irq;
4798 	kvm_make_request(KVM_REQ_EVENT, vcpu);
4799 	return 0;
4800 }
4801 
kvm_vcpu_ioctl_nmi(struct kvm_vcpu * vcpu)4802 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
4803 {
4804 	kvm_inject_nmi(vcpu);
4805 
4806 	return 0;
4807 }
4808 
kvm_vcpu_ioctl_smi(struct kvm_vcpu * vcpu)4809 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
4810 {
4811 	kvm_make_request(KVM_REQ_SMI, vcpu);
4812 
4813 	return 0;
4814 }
4815 
vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu * vcpu,struct kvm_tpr_access_ctl * tac)4816 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
4817 					   struct kvm_tpr_access_ctl *tac)
4818 {
4819 	if (tac->flags)
4820 		return -EINVAL;
4821 	vcpu->arch.tpr_access_reporting = !!tac->enabled;
4822 	return 0;
4823 }
4824 
kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu * vcpu,u64 mcg_cap)4825 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
4826 					u64 mcg_cap)
4827 {
4828 	int r;
4829 	unsigned bank_num = mcg_cap & 0xff, bank;
4830 
4831 	r = -EINVAL;
4832 	if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
4833 		goto out;
4834 	if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
4835 		goto out;
4836 	r = 0;
4837 	vcpu->arch.mcg_cap = mcg_cap;
4838 	/* Init IA32_MCG_CTL to all 1s */
4839 	if (mcg_cap & MCG_CTL_P)
4840 		vcpu->arch.mcg_ctl = ~(u64)0;
4841 	/* Init IA32_MCi_CTL to all 1s */
4842 	for (bank = 0; bank < bank_num; bank++)
4843 		vcpu->arch.mce_banks[bank*4] = ~(u64)0;
4844 
4845 	static_call(kvm_x86_setup_mce)(vcpu);
4846 out:
4847 	return r;
4848 }
4849 
kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce)4850 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
4851 				      struct kvm_x86_mce *mce)
4852 {
4853 	u64 mcg_cap = vcpu->arch.mcg_cap;
4854 	unsigned bank_num = mcg_cap & 0xff;
4855 	u64 *banks = vcpu->arch.mce_banks;
4856 
4857 	if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
4858 		return -EINVAL;
4859 	/*
4860 	 * if IA32_MCG_CTL is not all 1s, the uncorrected error
4861 	 * reporting is disabled
4862 	 */
4863 	if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
4864 	    vcpu->arch.mcg_ctl != ~(u64)0)
4865 		return 0;
4866 	banks += 4 * mce->bank;
4867 	/*
4868 	 * if IA32_MCi_CTL is not all 1s, the uncorrected error
4869 	 * reporting is disabled for the bank
4870 	 */
4871 	if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
4872 		return 0;
4873 	if (mce->status & MCI_STATUS_UC) {
4874 		if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
4875 		    !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
4876 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4877 			return 0;
4878 		}
4879 		if (banks[1] & MCI_STATUS_VAL)
4880 			mce->status |= MCI_STATUS_OVER;
4881 		banks[2] = mce->addr;
4882 		banks[3] = mce->misc;
4883 		vcpu->arch.mcg_status = mce->mcg_status;
4884 		banks[1] = mce->status;
4885 		kvm_queue_exception(vcpu, MC_VECTOR);
4886 	} else if (!(banks[1] & MCI_STATUS_VAL)
4887 		   || !(banks[1] & MCI_STATUS_UC)) {
4888 		if (banks[1] & MCI_STATUS_VAL)
4889 			mce->status |= MCI_STATUS_OVER;
4890 		banks[2] = mce->addr;
4891 		banks[3] = mce->misc;
4892 		banks[1] = mce->status;
4893 	} else
4894 		banks[1] |= MCI_STATUS_OVER;
4895 	return 0;
4896 }
4897 
kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)4898 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
4899 					       struct kvm_vcpu_events *events)
4900 {
4901 	process_nmi(vcpu);
4902 
4903 	if (kvm_check_request(KVM_REQ_SMI, vcpu))
4904 		process_smi(vcpu);
4905 
4906 	/*
4907 	 * In guest mode, payload delivery should be deferred,
4908 	 * so that the L1 hypervisor can intercept #PF before
4909 	 * CR2 is modified (or intercept #DB before DR6 is
4910 	 * modified under nVMX). Unless the per-VM capability,
4911 	 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
4912 	 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
4913 	 * opportunistically defer the exception payload, deliver it if the
4914 	 * capability hasn't been requested before processing a
4915 	 * KVM_GET_VCPU_EVENTS.
4916 	 */
4917 	if (!vcpu->kvm->arch.exception_payload_enabled &&
4918 	    vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
4919 		kvm_deliver_exception_payload(vcpu);
4920 
4921 	/*
4922 	 * The API doesn't provide the instruction length for software
4923 	 * exceptions, so don't report them. As long as the guest RIP
4924 	 * isn't advanced, we should expect to encounter the exception
4925 	 * again.
4926 	 */
4927 	if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
4928 		events->exception.injected = 0;
4929 		events->exception.pending = 0;
4930 	} else {
4931 		events->exception.injected = vcpu->arch.exception.injected;
4932 		events->exception.pending = vcpu->arch.exception.pending;
4933 		/*
4934 		 * For ABI compatibility, deliberately conflate
4935 		 * pending and injected exceptions when
4936 		 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
4937 		 */
4938 		if (!vcpu->kvm->arch.exception_payload_enabled)
4939 			events->exception.injected |=
4940 				vcpu->arch.exception.pending;
4941 	}
4942 	events->exception.nr = vcpu->arch.exception.nr;
4943 	events->exception.has_error_code = vcpu->arch.exception.has_error_code;
4944 	events->exception.error_code = vcpu->arch.exception.error_code;
4945 	events->exception_has_payload = vcpu->arch.exception.has_payload;
4946 	events->exception_payload = vcpu->arch.exception.payload;
4947 
4948 	events->interrupt.injected =
4949 		vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
4950 	events->interrupt.nr = vcpu->arch.interrupt.nr;
4951 	events->interrupt.soft = 0;
4952 	events->interrupt.shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
4953 
4954 	events->nmi.injected = vcpu->arch.nmi_injected;
4955 	events->nmi.pending = vcpu->arch.nmi_pending != 0;
4956 	events->nmi.masked = static_call(kvm_x86_get_nmi_mask)(vcpu);
4957 	events->nmi.pad = 0;
4958 
4959 	events->sipi_vector = 0; /* never valid when reporting to user space */
4960 
4961 	events->smi.smm = is_smm(vcpu);
4962 	events->smi.pending = vcpu->arch.smi_pending;
4963 	events->smi.smm_inside_nmi =
4964 		!!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
4965 	events->smi.latched_init = kvm_lapic_latched_init(vcpu);
4966 
4967 	events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
4968 			 | KVM_VCPUEVENT_VALID_SHADOW
4969 			 | KVM_VCPUEVENT_VALID_SMM);
4970 	if (vcpu->kvm->arch.exception_payload_enabled)
4971 		events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4972 
4973 	memset(&events->reserved, 0, sizeof(events->reserved));
4974 }
4975 
4976 static void kvm_smm_changed(struct kvm_vcpu *vcpu, bool entering_smm);
4977 
kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)4978 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4979 					      struct kvm_vcpu_events *events)
4980 {
4981 	if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
4982 			      | KVM_VCPUEVENT_VALID_SIPI_VECTOR
4983 			      | KVM_VCPUEVENT_VALID_SHADOW
4984 			      | KVM_VCPUEVENT_VALID_SMM
4985 			      | KVM_VCPUEVENT_VALID_PAYLOAD))
4986 		return -EINVAL;
4987 
4988 	if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4989 		if (!vcpu->kvm->arch.exception_payload_enabled)
4990 			return -EINVAL;
4991 		if (events->exception.pending)
4992 			events->exception.injected = 0;
4993 		else
4994 			events->exception_has_payload = 0;
4995 	} else {
4996 		events->exception.pending = 0;
4997 		events->exception_has_payload = 0;
4998 	}
4999 
5000 	if ((events->exception.injected || events->exception.pending) &&
5001 	    (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5002 		return -EINVAL;
5003 
5004 	/* INITs are latched while in SMM */
5005 	if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
5006 	    (events->smi.smm || events->smi.pending) &&
5007 	    vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
5008 		return -EINVAL;
5009 
5010 	process_nmi(vcpu);
5011 	vcpu->arch.exception.injected = events->exception.injected;
5012 	vcpu->arch.exception.pending = events->exception.pending;
5013 	vcpu->arch.exception.nr = events->exception.nr;
5014 	vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5015 	vcpu->arch.exception.error_code = events->exception.error_code;
5016 	vcpu->arch.exception.has_payload = events->exception_has_payload;
5017 	vcpu->arch.exception.payload = events->exception_payload;
5018 
5019 	vcpu->arch.interrupt.injected = events->interrupt.injected;
5020 	vcpu->arch.interrupt.nr = events->interrupt.nr;
5021 	vcpu->arch.interrupt.soft = events->interrupt.soft;
5022 	if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5023 		static_call(kvm_x86_set_interrupt_shadow)(vcpu,
5024 						events->interrupt.shadow);
5025 
5026 	vcpu->arch.nmi_injected = events->nmi.injected;
5027 	if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
5028 		vcpu->arch.nmi_pending = events->nmi.pending;
5029 	static_call(kvm_x86_set_nmi_mask)(vcpu, events->nmi.masked);
5030 
5031 	if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5032 	    lapic_in_kernel(vcpu))
5033 		vcpu->arch.apic->sipi_vector = events->sipi_vector;
5034 
5035 	if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5036 		if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5037 			kvm_x86_ops.nested_ops->leave_nested(vcpu);
5038 			kvm_smm_changed(vcpu, events->smi.smm);
5039 		}
5040 
5041 		vcpu->arch.smi_pending = events->smi.pending;
5042 
5043 		if (events->smi.smm) {
5044 			if (events->smi.smm_inside_nmi)
5045 				vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5046 			else
5047 				vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5048 		}
5049 
5050 		if (lapic_in_kernel(vcpu)) {
5051 			if (events->smi.latched_init)
5052 				set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5053 			else
5054 				clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5055 		}
5056 	}
5057 
5058 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5059 
5060 	return 0;
5061 }
5062 
kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5063 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5064 					     struct kvm_debugregs *dbgregs)
5065 {
5066 	unsigned long val;
5067 
5068 	memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
5069 	kvm_get_dr(vcpu, 6, &val);
5070 	dbgregs->dr6 = val;
5071 	dbgregs->dr7 = vcpu->arch.dr7;
5072 	dbgregs->flags = 0;
5073 	memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
5074 }
5075 
kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5076 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5077 					    struct kvm_debugregs *dbgregs)
5078 {
5079 	if (dbgregs->flags)
5080 		return -EINVAL;
5081 
5082 	if (!kvm_dr6_valid(dbgregs->dr6))
5083 		return -EINVAL;
5084 	if (!kvm_dr7_valid(dbgregs->dr7))
5085 		return -EINVAL;
5086 
5087 	memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
5088 	kvm_update_dr0123(vcpu);
5089 	vcpu->arch.dr6 = dbgregs->dr6;
5090 	vcpu->arch.dr7 = dbgregs->dr7;
5091 	kvm_update_dr7(vcpu);
5092 
5093 	return 0;
5094 }
5095 
kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5096 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5097 					 struct kvm_xsave *guest_xsave)
5098 {
5099 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5100 		return;
5101 
5102 	fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu,
5103 				       guest_xsave->region,
5104 				       sizeof(guest_xsave->region),
5105 				       vcpu->arch.pkru);
5106 }
5107 
kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu * vcpu,u8 * state,unsigned int size)5108 static void kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5109 					  u8 *state, unsigned int size)
5110 {
5111 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5112 		return;
5113 
5114 	fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu,
5115 				       state, size, vcpu->arch.pkru);
5116 }
5117 
kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5118 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5119 					struct kvm_xsave *guest_xsave)
5120 {
5121 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5122 		return 0;
5123 
5124 	return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5125 					      guest_xsave->region,
5126 					      supported_xcr0, &vcpu->arch.pkru);
5127 }
5128 
kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5129 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5130 					struct kvm_xcrs *guest_xcrs)
5131 {
5132 	if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5133 		guest_xcrs->nr_xcrs = 0;
5134 		return;
5135 	}
5136 
5137 	guest_xcrs->nr_xcrs = 1;
5138 	guest_xcrs->flags = 0;
5139 	guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5140 	guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5141 }
5142 
kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5143 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5144 				       struct kvm_xcrs *guest_xcrs)
5145 {
5146 	int i, r = 0;
5147 
5148 	if (!boot_cpu_has(X86_FEATURE_XSAVE))
5149 		return -EINVAL;
5150 
5151 	if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5152 		return -EINVAL;
5153 
5154 	for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5155 		/* Only support XCR0 currently */
5156 		if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5157 			r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5158 				guest_xcrs->xcrs[i].value);
5159 			break;
5160 		}
5161 	if (r)
5162 		r = -EINVAL;
5163 	return r;
5164 }
5165 
5166 /*
5167  * kvm_set_guest_paused() indicates to the guest kernel that it has been
5168  * stopped by the hypervisor.  This function will be called from the host only.
5169  * EINVAL is returned when the host attempts to set the flag for a guest that
5170  * does not support pv clocks.
5171  */
kvm_set_guest_paused(struct kvm_vcpu * vcpu)5172 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5173 {
5174 	if (!vcpu->arch.pv_time.active)
5175 		return -EINVAL;
5176 	vcpu->arch.pvclock_set_guest_stopped_request = true;
5177 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5178 	return 0;
5179 }
5180 
kvm_arch_tsc_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5181 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5182 				 struct kvm_device_attr *attr)
5183 {
5184 	int r;
5185 
5186 	switch (attr->attr) {
5187 	case KVM_VCPU_TSC_OFFSET:
5188 		r = 0;
5189 		break;
5190 	default:
5191 		r = -ENXIO;
5192 	}
5193 
5194 	return r;
5195 }
5196 
kvm_arch_tsc_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5197 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5198 				 struct kvm_device_attr *attr)
5199 {
5200 	u64 __user *uaddr = kvm_get_attr_addr(attr);
5201 	int r;
5202 
5203 	if (IS_ERR(uaddr))
5204 		return PTR_ERR(uaddr);
5205 
5206 	switch (attr->attr) {
5207 	case KVM_VCPU_TSC_OFFSET:
5208 		r = -EFAULT;
5209 		if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5210 			break;
5211 		r = 0;
5212 		break;
5213 	default:
5214 		r = -ENXIO;
5215 	}
5216 
5217 	return r;
5218 }
5219 
kvm_arch_tsc_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5220 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5221 				 struct kvm_device_attr *attr)
5222 {
5223 	u64 __user *uaddr = kvm_get_attr_addr(attr);
5224 	struct kvm *kvm = vcpu->kvm;
5225 	int r;
5226 
5227 	if (IS_ERR(uaddr))
5228 		return PTR_ERR(uaddr);
5229 
5230 	switch (attr->attr) {
5231 	case KVM_VCPU_TSC_OFFSET: {
5232 		u64 offset, tsc, ns;
5233 		unsigned long flags;
5234 		bool matched;
5235 
5236 		r = -EFAULT;
5237 		if (get_user(offset, uaddr))
5238 			break;
5239 
5240 		raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5241 
5242 		matched = (vcpu->arch.virtual_tsc_khz &&
5243 			   kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5244 			   kvm->arch.last_tsc_offset == offset);
5245 
5246 		tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5247 		ns = get_kvmclock_base_ns();
5248 
5249 		__kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched);
5250 		raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5251 
5252 		r = 0;
5253 		break;
5254 	}
5255 	default:
5256 		r = -ENXIO;
5257 	}
5258 
5259 	return r;
5260 }
5261 
kvm_vcpu_ioctl_device_attr(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)5262 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5263 				      unsigned int ioctl,
5264 				      void __user *argp)
5265 {
5266 	struct kvm_device_attr attr;
5267 	int r;
5268 
5269 	if (copy_from_user(&attr, argp, sizeof(attr)))
5270 		return -EFAULT;
5271 
5272 	if (attr.group != KVM_VCPU_TSC_CTRL)
5273 		return -ENXIO;
5274 
5275 	switch (ioctl) {
5276 	case KVM_HAS_DEVICE_ATTR:
5277 		r = kvm_arch_tsc_has_attr(vcpu, &attr);
5278 		break;
5279 	case KVM_GET_DEVICE_ATTR:
5280 		r = kvm_arch_tsc_get_attr(vcpu, &attr);
5281 		break;
5282 	case KVM_SET_DEVICE_ATTR:
5283 		r = kvm_arch_tsc_set_attr(vcpu, &attr);
5284 		break;
5285 	}
5286 
5287 	return r;
5288 }
5289 
kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu * vcpu,struct kvm_enable_cap * cap)5290 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5291 				     struct kvm_enable_cap *cap)
5292 {
5293 	int r;
5294 	uint16_t vmcs_version;
5295 	void __user *user_ptr;
5296 
5297 	if (cap->flags)
5298 		return -EINVAL;
5299 
5300 	switch (cap->cap) {
5301 	case KVM_CAP_HYPERV_SYNIC2:
5302 		if (cap->args[0])
5303 			return -EINVAL;
5304 		fallthrough;
5305 
5306 	case KVM_CAP_HYPERV_SYNIC:
5307 		if (!irqchip_in_kernel(vcpu->kvm))
5308 			return -EINVAL;
5309 		return kvm_hv_activate_synic(vcpu, cap->cap ==
5310 					     KVM_CAP_HYPERV_SYNIC2);
5311 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
5312 		if (!kvm_x86_ops.nested_ops->enable_evmcs)
5313 			return -ENOTTY;
5314 		r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
5315 		if (!r) {
5316 			user_ptr = (void __user *)(uintptr_t)cap->args[0];
5317 			if (copy_to_user(user_ptr, &vmcs_version,
5318 					 sizeof(vmcs_version)))
5319 				r = -EFAULT;
5320 		}
5321 		return r;
5322 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
5323 		if (!kvm_x86_ops.enable_direct_tlbflush)
5324 			return -ENOTTY;
5325 
5326 		return static_call(kvm_x86_enable_direct_tlbflush)(vcpu);
5327 
5328 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
5329 		return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
5330 
5331 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5332 		vcpu->arch.pv_cpuid.enforce = cap->args[0];
5333 		if (vcpu->arch.pv_cpuid.enforce)
5334 			kvm_update_pv_runtime(vcpu);
5335 
5336 		return 0;
5337 	default:
5338 		return -EINVAL;
5339 	}
5340 }
5341 
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5342 long kvm_arch_vcpu_ioctl(struct file *filp,
5343 			 unsigned int ioctl, unsigned long arg)
5344 {
5345 	struct kvm_vcpu *vcpu = filp->private_data;
5346 	void __user *argp = (void __user *)arg;
5347 	int r;
5348 	union {
5349 		struct kvm_sregs2 *sregs2;
5350 		struct kvm_lapic_state *lapic;
5351 		struct kvm_xsave *xsave;
5352 		struct kvm_xcrs *xcrs;
5353 		void *buffer;
5354 	} u;
5355 
5356 	vcpu_load(vcpu);
5357 
5358 	u.buffer = NULL;
5359 	switch (ioctl) {
5360 	case KVM_GET_LAPIC: {
5361 		r = -EINVAL;
5362 		if (!lapic_in_kernel(vcpu))
5363 			goto out;
5364 		u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
5365 				GFP_KERNEL_ACCOUNT);
5366 
5367 		r = -ENOMEM;
5368 		if (!u.lapic)
5369 			goto out;
5370 		r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
5371 		if (r)
5372 			goto out;
5373 		r = -EFAULT;
5374 		if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
5375 			goto out;
5376 		r = 0;
5377 		break;
5378 	}
5379 	case KVM_SET_LAPIC: {
5380 		r = -EINVAL;
5381 		if (!lapic_in_kernel(vcpu))
5382 			goto out;
5383 		u.lapic = memdup_user(argp, sizeof(*u.lapic));
5384 		if (IS_ERR(u.lapic)) {
5385 			r = PTR_ERR(u.lapic);
5386 			goto out_nofree;
5387 		}
5388 
5389 		r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
5390 		break;
5391 	}
5392 	case KVM_INTERRUPT: {
5393 		struct kvm_interrupt irq;
5394 
5395 		r = -EFAULT;
5396 		if (copy_from_user(&irq, argp, sizeof(irq)))
5397 			goto out;
5398 		r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
5399 		break;
5400 	}
5401 	case KVM_NMI: {
5402 		r = kvm_vcpu_ioctl_nmi(vcpu);
5403 		break;
5404 	}
5405 	case KVM_SMI: {
5406 		r = kvm_vcpu_ioctl_smi(vcpu);
5407 		break;
5408 	}
5409 	case KVM_SET_CPUID: {
5410 		struct kvm_cpuid __user *cpuid_arg = argp;
5411 		struct kvm_cpuid cpuid;
5412 
5413 		r = -EFAULT;
5414 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5415 			goto out;
5416 		r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
5417 		break;
5418 	}
5419 	case KVM_SET_CPUID2: {
5420 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5421 		struct kvm_cpuid2 cpuid;
5422 
5423 		r = -EFAULT;
5424 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5425 			goto out;
5426 		r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
5427 					      cpuid_arg->entries);
5428 		break;
5429 	}
5430 	case KVM_GET_CPUID2: {
5431 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5432 		struct kvm_cpuid2 cpuid;
5433 
5434 		r = -EFAULT;
5435 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5436 			goto out;
5437 		r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
5438 					      cpuid_arg->entries);
5439 		if (r)
5440 			goto out;
5441 		r = -EFAULT;
5442 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5443 			goto out;
5444 		r = 0;
5445 		break;
5446 	}
5447 	case KVM_GET_MSRS: {
5448 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
5449 		r = msr_io(vcpu, argp, do_get_msr, 1);
5450 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5451 		break;
5452 	}
5453 	case KVM_SET_MSRS: {
5454 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
5455 		r = msr_io(vcpu, argp, do_set_msr, 0);
5456 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5457 		break;
5458 	}
5459 	case KVM_TPR_ACCESS_REPORTING: {
5460 		struct kvm_tpr_access_ctl tac;
5461 
5462 		r = -EFAULT;
5463 		if (copy_from_user(&tac, argp, sizeof(tac)))
5464 			goto out;
5465 		r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
5466 		if (r)
5467 			goto out;
5468 		r = -EFAULT;
5469 		if (copy_to_user(argp, &tac, sizeof(tac)))
5470 			goto out;
5471 		r = 0;
5472 		break;
5473 	};
5474 	case KVM_SET_VAPIC_ADDR: {
5475 		struct kvm_vapic_addr va;
5476 		int idx;
5477 
5478 		r = -EINVAL;
5479 		if (!lapic_in_kernel(vcpu))
5480 			goto out;
5481 		r = -EFAULT;
5482 		if (copy_from_user(&va, argp, sizeof(va)))
5483 			goto out;
5484 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5485 		r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
5486 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5487 		break;
5488 	}
5489 	case KVM_X86_SETUP_MCE: {
5490 		u64 mcg_cap;
5491 
5492 		r = -EFAULT;
5493 		if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
5494 			goto out;
5495 		r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
5496 		break;
5497 	}
5498 	case KVM_X86_SET_MCE: {
5499 		struct kvm_x86_mce mce;
5500 
5501 		r = -EFAULT;
5502 		if (copy_from_user(&mce, argp, sizeof(mce)))
5503 			goto out;
5504 		r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
5505 		break;
5506 	}
5507 	case KVM_GET_VCPU_EVENTS: {
5508 		struct kvm_vcpu_events events;
5509 
5510 		kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
5511 
5512 		r = -EFAULT;
5513 		if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
5514 			break;
5515 		r = 0;
5516 		break;
5517 	}
5518 	case KVM_SET_VCPU_EVENTS: {
5519 		struct kvm_vcpu_events events;
5520 
5521 		r = -EFAULT;
5522 		if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
5523 			break;
5524 
5525 		r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
5526 		break;
5527 	}
5528 	case KVM_GET_DEBUGREGS: {
5529 		struct kvm_debugregs dbgregs;
5530 
5531 		kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
5532 
5533 		r = -EFAULT;
5534 		if (copy_to_user(argp, &dbgregs,
5535 				 sizeof(struct kvm_debugregs)))
5536 			break;
5537 		r = 0;
5538 		break;
5539 	}
5540 	case KVM_SET_DEBUGREGS: {
5541 		struct kvm_debugregs dbgregs;
5542 
5543 		r = -EFAULT;
5544 		if (copy_from_user(&dbgregs, argp,
5545 				   sizeof(struct kvm_debugregs)))
5546 			break;
5547 
5548 		r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
5549 		break;
5550 	}
5551 	case KVM_GET_XSAVE: {
5552 		r = -EINVAL;
5553 		if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
5554 			break;
5555 
5556 		u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
5557 		r = -ENOMEM;
5558 		if (!u.xsave)
5559 			break;
5560 
5561 		kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
5562 
5563 		r = -EFAULT;
5564 		if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
5565 			break;
5566 		r = 0;
5567 		break;
5568 	}
5569 	case KVM_SET_XSAVE: {
5570 		int size = vcpu->arch.guest_fpu.uabi_size;
5571 
5572 		u.xsave = memdup_user(argp, size);
5573 		if (IS_ERR(u.xsave)) {
5574 			r = PTR_ERR(u.xsave);
5575 			goto out_nofree;
5576 		}
5577 
5578 		r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
5579 		break;
5580 	}
5581 
5582 	case KVM_GET_XSAVE2: {
5583 		int size = vcpu->arch.guest_fpu.uabi_size;
5584 
5585 		u.xsave = kzalloc(size, GFP_KERNEL_ACCOUNT);
5586 		r = -ENOMEM;
5587 		if (!u.xsave)
5588 			break;
5589 
5590 		kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
5591 
5592 		r = -EFAULT;
5593 		if (copy_to_user(argp, u.xsave, size))
5594 			break;
5595 
5596 		r = 0;
5597 		break;
5598 	}
5599 
5600 	case KVM_GET_XCRS: {
5601 		u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
5602 		r = -ENOMEM;
5603 		if (!u.xcrs)
5604 			break;
5605 
5606 		kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
5607 
5608 		r = -EFAULT;
5609 		if (copy_to_user(argp, u.xcrs,
5610 				 sizeof(struct kvm_xcrs)))
5611 			break;
5612 		r = 0;
5613 		break;
5614 	}
5615 	case KVM_SET_XCRS: {
5616 		u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
5617 		if (IS_ERR(u.xcrs)) {
5618 			r = PTR_ERR(u.xcrs);
5619 			goto out_nofree;
5620 		}
5621 
5622 		r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
5623 		break;
5624 	}
5625 	case KVM_SET_TSC_KHZ: {
5626 		u32 user_tsc_khz;
5627 
5628 		r = -EINVAL;
5629 		user_tsc_khz = (u32)arg;
5630 
5631 		if (kvm_has_tsc_control &&
5632 		    user_tsc_khz >= kvm_max_guest_tsc_khz)
5633 			goto out;
5634 
5635 		if (user_tsc_khz == 0)
5636 			user_tsc_khz = tsc_khz;
5637 
5638 		if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
5639 			r = 0;
5640 
5641 		goto out;
5642 	}
5643 	case KVM_GET_TSC_KHZ: {
5644 		r = vcpu->arch.virtual_tsc_khz;
5645 		goto out;
5646 	}
5647 	case KVM_KVMCLOCK_CTRL: {
5648 		r = kvm_set_guest_paused(vcpu);
5649 		goto out;
5650 	}
5651 	case KVM_ENABLE_CAP: {
5652 		struct kvm_enable_cap cap;
5653 
5654 		r = -EFAULT;
5655 		if (copy_from_user(&cap, argp, sizeof(cap)))
5656 			goto out;
5657 		r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
5658 		break;
5659 	}
5660 	case KVM_GET_NESTED_STATE: {
5661 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
5662 		u32 user_data_size;
5663 
5664 		r = -EINVAL;
5665 		if (!kvm_x86_ops.nested_ops->get_state)
5666 			break;
5667 
5668 		BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
5669 		r = -EFAULT;
5670 		if (get_user(user_data_size, &user_kvm_nested_state->size))
5671 			break;
5672 
5673 		r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
5674 						     user_data_size);
5675 		if (r < 0)
5676 			break;
5677 
5678 		if (r > user_data_size) {
5679 			if (put_user(r, &user_kvm_nested_state->size))
5680 				r = -EFAULT;
5681 			else
5682 				r = -E2BIG;
5683 			break;
5684 		}
5685 
5686 		r = 0;
5687 		break;
5688 	}
5689 	case KVM_SET_NESTED_STATE: {
5690 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
5691 		struct kvm_nested_state kvm_state;
5692 		int idx;
5693 
5694 		r = -EINVAL;
5695 		if (!kvm_x86_ops.nested_ops->set_state)
5696 			break;
5697 
5698 		r = -EFAULT;
5699 		if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
5700 			break;
5701 
5702 		r = -EINVAL;
5703 		if (kvm_state.size < sizeof(kvm_state))
5704 			break;
5705 
5706 		if (kvm_state.flags &
5707 		    ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
5708 		      | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
5709 		      | KVM_STATE_NESTED_GIF_SET))
5710 			break;
5711 
5712 		/* nested_run_pending implies guest_mode.  */
5713 		if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
5714 		    && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
5715 			break;
5716 
5717 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5718 		r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
5719 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5720 		break;
5721 	}
5722 	case KVM_GET_SUPPORTED_HV_CPUID:
5723 		r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
5724 		break;
5725 #ifdef CONFIG_KVM_XEN
5726 	case KVM_XEN_VCPU_GET_ATTR: {
5727 		struct kvm_xen_vcpu_attr xva;
5728 
5729 		r = -EFAULT;
5730 		if (copy_from_user(&xva, argp, sizeof(xva)))
5731 			goto out;
5732 		r = kvm_xen_vcpu_get_attr(vcpu, &xva);
5733 		if (!r && copy_to_user(argp, &xva, sizeof(xva)))
5734 			r = -EFAULT;
5735 		break;
5736 	}
5737 	case KVM_XEN_VCPU_SET_ATTR: {
5738 		struct kvm_xen_vcpu_attr xva;
5739 
5740 		r = -EFAULT;
5741 		if (copy_from_user(&xva, argp, sizeof(xva)))
5742 			goto out;
5743 		r = kvm_xen_vcpu_set_attr(vcpu, &xva);
5744 		break;
5745 	}
5746 #endif
5747 	case KVM_GET_SREGS2: {
5748 		u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
5749 		r = -ENOMEM;
5750 		if (!u.sregs2)
5751 			goto out;
5752 		__get_sregs2(vcpu, u.sregs2);
5753 		r = -EFAULT;
5754 		if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
5755 			goto out;
5756 		r = 0;
5757 		break;
5758 	}
5759 	case KVM_SET_SREGS2: {
5760 		u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
5761 		if (IS_ERR(u.sregs2)) {
5762 			r = PTR_ERR(u.sregs2);
5763 			u.sregs2 = NULL;
5764 			goto out;
5765 		}
5766 		r = __set_sregs2(vcpu, u.sregs2);
5767 		break;
5768 	}
5769 	case KVM_HAS_DEVICE_ATTR:
5770 	case KVM_GET_DEVICE_ATTR:
5771 	case KVM_SET_DEVICE_ATTR:
5772 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
5773 		break;
5774 	default:
5775 		r = -EINVAL;
5776 	}
5777 out:
5778 	kfree(u.buffer);
5779 out_nofree:
5780 	vcpu_put(vcpu);
5781 	return r;
5782 }
5783 
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)5784 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
5785 {
5786 	return VM_FAULT_SIGBUS;
5787 }
5788 
kvm_vm_ioctl_set_tss_addr(struct kvm * kvm,unsigned long addr)5789 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
5790 {
5791 	int ret;
5792 
5793 	if (addr > (unsigned int)(-3 * PAGE_SIZE))
5794 		return -EINVAL;
5795 	ret = static_call(kvm_x86_set_tss_addr)(kvm, addr);
5796 	return ret;
5797 }
5798 
kvm_vm_ioctl_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)5799 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
5800 					      u64 ident_addr)
5801 {
5802 	return static_call(kvm_x86_set_identity_map_addr)(kvm, ident_addr);
5803 }
5804 
kvm_vm_ioctl_set_nr_mmu_pages(struct kvm * kvm,unsigned long kvm_nr_mmu_pages)5805 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
5806 					 unsigned long kvm_nr_mmu_pages)
5807 {
5808 	if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
5809 		return -EINVAL;
5810 
5811 	mutex_lock(&kvm->slots_lock);
5812 
5813 	kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
5814 	kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
5815 
5816 	mutex_unlock(&kvm->slots_lock);
5817 	return 0;
5818 }
5819 
kvm_vm_ioctl_get_nr_mmu_pages(struct kvm * kvm)5820 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
5821 {
5822 	return kvm->arch.n_max_mmu_pages;
5823 }
5824 
kvm_vm_ioctl_get_irqchip(struct kvm * kvm,struct kvm_irqchip * chip)5825 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5826 {
5827 	struct kvm_pic *pic = kvm->arch.vpic;
5828 	int r;
5829 
5830 	r = 0;
5831 	switch (chip->chip_id) {
5832 	case KVM_IRQCHIP_PIC_MASTER:
5833 		memcpy(&chip->chip.pic, &pic->pics[0],
5834 			sizeof(struct kvm_pic_state));
5835 		break;
5836 	case KVM_IRQCHIP_PIC_SLAVE:
5837 		memcpy(&chip->chip.pic, &pic->pics[1],
5838 			sizeof(struct kvm_pic_state));
5839 		break;
5840 	case KVM_IRQCHIP_IOAPIC:
5841 		kvm_get_ioapic(kvm, &chip->chip.ioapic);
5842 		break;
5843 	default:
5844 		r = -EINVAL;
5845 		break;
5846 	}
5847 	return r;
5848 }
5849 
kvm_vm_ioctl_set_irqchip(struct kvm * kvm,struct kvm_irqchip * chip)5850 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5851 {
5852 	struct kvm_pic *pic = kvm->arch.vpic;
5853 	int r;
5854 
5855 	r = 0;
5856 	switch (chip->chip_id) {
5857 	case KVM_IRQCHIP_PIC_MASTER:
5858 		spin_lock(&pic->lock);
5859 		memcpy(&pic->pics[0], &chip->chip.pic,
5860 			sizeof(struct kvm_pic_state));
5861 		spin_unlock(&pic->lock);
5862 		break;
5863 	case KVM_IRQCHIP_PIC_SLAVE:
5864 		spin_lock(&pic->lock);
5865 		memcpy(&pic->pics[1], &chip->chip.pic,
5866 			sizeof(struct kvm_pic_state));
5867 		spin_unlock(&pic->lock);
5868 		break;
5869 	case KVM_IRQCHIP_IOAPIC:
5870 		kvm_set_ioapic(kvm, &chip->chip.ioapic);
5871 		break;
5872 	default:
5873 		r = -EINVAL;
5874 		break;
5875 	}
5876 	kvm_pic_update_irq(pic);
5877 	return r;
5878 }
5879 
kvm_vm_ioctl_get_pit(struct kvm * kvm,struct kvm_pit_state * ps)5880 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5881 {
5882 	struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
5883 
5884 	BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
5885 
5886 	mutex_lock(&kps->lock);
5887 	memcpy(ps, &kps->channels, sizeof(*ps));
5888 	mutex_unlock(&kps->lock);
5889 	return 0;
5890 }
5891 
kvm_vm_ioctl_set_pit(struct kvm * kvm,struct kvm_pit_state * ps)5892 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5893 {
5894 	int i;
5895 	struct kvm_pit *pit = kvm->arch.vpit;
5896 
5897 	mutex_lock(&pit->pit_state.lock);
5898 	memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
5899 	for (i = 0; i < 3; i++)
5900 		kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
5901 	mutex_unlock(&pit->pit_state.lock);
5902 	return 0;
5903 }
5904 
kvm_vm_ioctl_get_pit2(struct kvm * kvm,struct kvm_pit_state2 * ps)5905 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5906 {
5907 	mutex_lock(&kvm->arch.vpit->pit_state.lock);
5908 	memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
5909 		sizeof(ps->channels));
5910 	ps->flags = kvm->arch.vpit->pit_state.flags;
5911 	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
5912 	memset(&ps->reserved, 0, sizeof(ps->reserved));
5913 	return 0;
5914 }
5915 
kvm_vm_ioctl_set_pit2(struct kvm * kvm,struct kvm_pit_state2 * ps)5916 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5917 {
5918 	int start = 0;
5919 	int i;
5920 	u32 prev_legacy, cur_legacy;
5921 	struct kvm_pit *pit = kvm->arch.vpit;
5922 
5923 	mutex_lock(&pit->pit_state.lock);
5924 	prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
5925 	cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
5926 	if (!prev_legacy && cur_legacy)
5927 		start = 1;
5928 	memcpy(&pit->pit_state.channels, &ps->channels,
5929 	       sizeof(pit->pit_state.channels));
5930 	pit->pit_state.flags = ps->flags;
5931 	for (i = 0; i < 3; i++)
5932 		kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
5933 				   start && i == 0);
5934 	mutex_unlock(&pit->pit_state.lock);
5935 	return 0;
5936 }
5937 
kvm_vm_ioctl_reinject(struct kvm * kvm,struct kvm_reinject_control * control)5938 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
5939 				 struct kvm_reinject_control *control)
5940 {
5941 	struct kvm_pit *pit = kvm->arch.vpit;
5942 
5943 	/* pit->pit_state.lock was overloaded to prevent userspace from getting
5944 	 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
5945 	 * ioctls in parallel.  Use a separate lock if that ioctl isn't rare.
5946 	 */
5947 	mutex_lock(&pit->pit_state.lock);
5948 	kvm_pit_set_reinject(pit, control->pit_reinject);
5949 	mutex_unlock(&pit->pit_state.lock);
5950 
5951 	return 0;
5952 }
5953 
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)5954 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
5955 {
5956 
5957 	/*
5958 	 * Flush all CPUs' dirty log buffers to the  dirty_bitmap.  Called
5959 	 * before reporting dirty_bitmap to userspace.  KVM flushes the buffers
5960 	 * on all VM-Exits, thus we only need to kick running vCPUs to force a
5961 	 * VM-Exit.
5962 	 */
5963 	struct kvm_vcpu *vcpu;
5964 	unsigned long i;
5965 
5966 	kvm_for_each_vcpu(i, vcpu, kvm)
5967 		kvm_vcpu_kick(vcpu);
5968 }
5969 
kvm_vm_ioctl_irq_line(struct kvm * kvm,struct kvm_irq_level * irq_event,bool line_status)5970 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
5971 			bool line_status)
5972 {
5973 	if (!irqchip_in_kernel(kvm))
5974 		return -ENXIO;
5975 
5976 	irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
5977 					irq_event->irq, irq_event->level,
5978 					line_status);
5979 	return 0;
5980 }
5981 
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)5982 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
5983 			    struct kvm_enable_cap *cap)
5984 {
5985 	int r;
5986 
5987 	if (cap->flags)
5988 		return -EINVAL;
5989 
5990 	switch (cap->cap) {
5991 	case KVM_CAP_DISABLE_QUIRKS2:
5992 		r = -EINVAL;
5993 		if (cap->args[0] & ~KVM_X86_VALID_QUIRKS)
5994 			break;
5995 		fallthrough;
5996 	case KVM_CAP_DISABLE_QUIRKS:
5997 		kvm->arch.disabled_quirks = cap->args[0];
5998 		r = 0;
5999 		break;
6000 	case KVM_CAP_SPLIT_IRQCHIP: {
6001 		mutex_lock(&kvm->lock);
6002 		r = -EINVAL;
6003 		if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6004 			goto split_irqchip_unlock;
6005 		r = -EEXIST;
6006 		if (irqchip_in_kernel(kvm))
6007 			goto split_irqchip_unlock;
6008 		if (kvm->created_vcpus)
6009 			goto split_irqchip_unlock;
6010 		r = kvm_setup_empty_irq_routing(kvm);
6011 		if (r)
6012 			goto split_irqchip_unlock;
6013 		/* Pairs with irqchip_in_kernel. */
6014 		smp_wmb();
6015 		kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6016 		kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6017 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6018 		r = 0;
6019 split_irqchip_unlock:
6020 		mutex_unlock(&kvm->lock);
6021 		break;
6022 	}
6023 	case KVM_CAP_X2APIC_API:
6024 		r = -EINVAL;
6025 		if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6026 			break;
6027 
6028 		if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6029 			kvm->arch.x2apic_format = true;
6030 		if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6031 			kvm->arch.x2apic_broadcast_quirk_disabled = true;
6032 
6033 		r = 0;
6034 		break;
6035 	case KVM_CAP_X86_DISABLE_EXITS:
6036 		r = -EINVAL;
6037 		if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
6038 			break;
6039 
6040 		if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
6041 			kvm_can_mwait_in_guest())
6042 			kvm->arch.mwait_in_guest = true;
6043 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
6044 			kvm->arch.hlt_in_guest = true;
6045 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
6046 			kvm->arch.pause_in_guest = true;
6047 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
6048 			kvm->arch.cstate_in_guest = true;
6049 		r = 0;
6050 		break;
6051 	case KVM_CAP_MSR_PLATFORM_INFO:
6052 		kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6053 		r = 0;
6054 		break;
6055 	case KVM_CAP_EXCEPTION_PAYLOAD:
6056 		kvm->arch.exception_payload_enabled = cap->args[0];
6057 		r = 0;
6058 		break;
6059 	case KVM_CAP_X86_USER_SPACE_MSR:
6060 		r = -EINVAL;
6061 		if (cap->args[0] & ~(KVM_MSR_EXIT_REASON_INVAL |
6062 				     KVM_MSR_EXIT_REASON_UNKNOWN |
6063 				     KVM_MSR_EXIT_REASON_FILTER))
6064 			break;
6065 		kvm->arch.user_space_msr_mask = cap->args[0];
6066 		r = 0;
6067 		break;
6068 	case KVM_CAP_X86_BUS_LOCK_EXIT:
6069 		r = -EINVAL;
6070 		if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6071 			break;
6072 
6073 		if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6074 		    (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6075 			break;
6076 
6077 		if (kvm_has_bus_lock_exit &&
6078 		    cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6079 			kvm->arch.bus_lock_detection_enabled = true;
6080 		r = 0;
6081 		break;
6082 #ifdef CONFIG_X86_SGX_KVM
6083 	case KVM_CAP_SGX_ATTRIBUTE: {
6084 		unsigned long allowed_attributes = 0;
6085 
6086 		r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6087 		if (r)
6088 			break;
6089 
6090 		/* KVM only supports the PROVISIONKEY privileged attribute. */
6091 		if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6092 		    !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6093 			kvm->arch.sgx_provisioning_allowed = true;
6094 		else
6095 			r = -EINVAL;
6096 		break;
6097 	}
6098 #endif
6099 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6100 		r = -EINVAL;
6101 		if (!kvm_x86_ops.vm_copy_enc_context_from)
6102 			break;
6103 
6104 		r = static_call(kvm_x86_vm_copy_enc_context_from)(kvm, cap->args[0]);
6105 		break;
6106 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6107 		r = -EINVAL;
6108 		if (!kvm_x86_ops.vm_move_enc_context_from)
6109 			break;
6110 
6111 		r = static_call(kvm_x86_vm_move_enc_context_from)(kvm, cap->args[0]);
6112 		break;
6113 	case KVM_CAP_EXIT_HYPERCALL:
6114 		if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6115 			r = -EINVAL;
6116 			break;
6117 		}
6118 		kvm->arch.hypercall_exit_enabled = cap->args[0];
6119 		r = 0;
6120 		break;
6121 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6122 		r = -EINVAL;
6123 		if (cap->args[0] & ~1)
6124 			break;
6125 		kvm->arch.exit_on_emulation_error = cap->args[0];
6126 		r = 0;
6127 		break;
6128 	case KVM_CAP_PMU_CAPABILITY:
6129 		r = -EINVAL;
6130 		if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6131 			break;
6132 
6133 		mutex_lock(&kvm->lock);
6134 		if (!kvm->created_vcpus) {
6135 			kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6136 			r = 0;
6137 		}
6138 		mutex_unlock(&kvm->lock);
6139 		break;
6140 	default:
6141 		r = -EINVAL;
6142 		break;
6143 	}
6144 	return r;
6145 }
6146 
kvm_alloc_msr_filter(bool default_allow)6147 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6148 {
6149 	struct kvm_x86_msr_filter *msr_filter;
6150 
6151 	msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6152 	if (!msr_filter)
6153 		return NULL;
6154 
6155 	msr_filter->default_allow = default_allow;
6156 	return msr_filter;
6157 }
6158 
kvm_free_msr_filter(struct kvm_x86_msr_filter * msr_filter)6159 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
6160 {
6161 	u32 i;
6162 
6163 	if (!msr_filter)
6164 		return;
6165 
6166 	for (i = 0; i < msr_filter->count; i++)
6167 		kfree(msr_filter->ranges[i].bitmap);
6168 
6169 	kfree(msr_filter);
6170 }
6171 
kvm_add_msr_filter(struct kvm_x86_msr_filter * msr_filter,struct kvm_msr_filter_range * user_range)6172 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6173 			      struct kvm_msr_filter_range *user_range)
6174 {
6175 	unsigned long *bitmap = NULL;
6176 	size_t bitmap_size;
6177 
6178 	if (!user_range->nmsrs)
6179 		return 0;
6180 
6181 	if (user_range->flags & ~(KVM_MSR_FILTER_READ | KVM_MSR_FILTER_WRITE))
6182 		return -EINVAL;
6183 
6184 	if (!user_range->flags)
6185 		return -EINVAL;
6186 
6187 	bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6188 	if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6189 		return -EINVAL;
6190 
6191 	bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6192 	if (IS_ERR(bitmap))
6193 		return PTR_ERR(bitmap);
6194 
6195 	msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
6196 		.flags = user_range->flags,
6197 		.base = user_range->base,
6198 		.nmsrs = user_range->nmsrs,
6199 		.bitmap = bitmap,
6200 	};
6201 
6202 	msr_filter->count++;
6203 	return 0;
6204 }
6205 
kvm_vm_ioctl_set_msr_filter(struct kvm * kvm,void __user * argp)6206 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm, void __user *argp)
6207 {
6208 	struct kvm_msr_filter __user *user_msr_filter = argp;
6209 	struct kvm_x86_msr_filter *new_filter, *old_filter;
6210 	struct kvm_msr_filter filter;
6211 	bool default_allow;
6212 	bool empty = true;
6213 	int r = 0;
6214 	u32 i;
6215 
6216 	if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
6217 		return -EFAULT;
6218 
6219 	if (filter.flags & ~KVM_MSR_FILTER_DEFAULT_DENY)
6220 		return -EINVAL;
6221 
6222 	for (i = 0; i < ARRAY_SIZE(filter.ranges); i++)
6223 		empty &= !filter.ranges[i].nmsrs;
6224 
6225 	default_allow = !(filter.flags & KVM_MSR_FILTER_DEFAULT_DENY);
6226 	if (empty && !default_allow)
6227 		return -EINVAL;
6228 
6229 	new_filter = kvm_alloc_msr_filter(default_allow);
6230 	if (!new_filter)
6231 		return -ENOMEM;
6232 
6233 	for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
6234 		r = kvm_add_msr_filter(new_filter, &filter.ranges[i]);
6235 		if (r) {
6236 			kvm_free_msr_filter(new_filter);
6237 			return r;
6238 		}
6239 	}
6240 
6241 	mutex_lock(&kvm->lock);
6242 
6243 	/* The per-VM filter is protected by kvm->lock... */
6244 	old_filter = srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1);
6245 
6246 	rcu_assign_pointer(kvm->arch.msr_filter, new_filter);
6247 	synchronize_srcu(&kvm->srcu);
6248 
6249 	kvm_free_msr_filter(old_filter);
6250 
6251 	kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
6252 	mutex_unlock(&kvm->lock);
6253 
6254 	return 0;
6255 }
6256 
6257 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_arch_suspend_notifier(struct kvm * kvm)6258 static int kvm_arch_suspend_notifier(struct kvm *kvm)
6259 {
6260 	struct kvm_vcpu *vcpu;
6261 	unsigned long i;
6262 	int ret = 0;
6263 
6264 	mutex_lock(&kvm->lock);
6265 	kvm_for_each_vcpu(i, vcpu, kvm) {
6266 		if (!vcpu->arch.pv_time.active)
6267 			continue;
6268 
6269 		ret = kvm_set_guest_paused(vcpu);
6270 		if (ret) {
6271 			kvm_err("Failed to pause guest VCPU%d: %d\n",
6272 				vcpu->vcpu_id, ret);
6273 			break;
6274 		}
6275 	}
6276 	mutex_unlock(&kvm->lock);
6277 
6278 	return ret ? NOTIFY_BAD : NOTIFY_DONE;
6279 }
6280 
kvm_arch_pm_notifier(struct kvm * kvm,unsigned long state)6281 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6282 {
6283 	switch (state) {
6284 	case PM_HIBERNATION_PREPARE:
6285 	case PM_SUSPEND_PREPARE:
6286 		return kvm_arch_suspend_notifier(kvm);
6287 	}
6288 
6289 	return NOTIFY_DONE;
6290 }
6291 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
6292 
kvm_vm_ioctl_get_clock(struct kvm * kvm,void __user * argp)6293 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
6294 {
6295 	struct kvm_clock_data data = { 0 };
6296 
6297 	get_kvmclock(kvm, &data);
6298 	if (copy_to_user(argp, &data, sizeof(data)))
6299 		return -EFAULT;
6300 
6301 	return 0;
6302 }
6303 
kvm_vm_ioctl_set_clock(struct kvm * kvm,void __user * argp)6304 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
6305 {
6306 	struct kvm_arch *ka = &kvm->arch;
6307 	struct kvm_clock_data data;
6308 	u64 now_raw_ns;
6309 
6310 	if (copy_from_user(&data, argp, sizeof(data)))
6311 		return -EFAULT;
6312 
6313 	/*
6314 	 * Only KVM_CLOCK_REALTIME is used, but allow passing the
6315 	 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
6316 	 */
6317 	if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
6318 		return -EINVAL;
6319 
6320 	kvm_hv_request_tsc_page_update(kvm);
6321 	kvm_start_pvclock_update(kvm);
6322 	pvclock_update_vm_gtod_copy(kvm);
6323 
6324 	/*
6325 	 * This pairs with kvm_guest_time_update(): when masterclock is
6326 	 * in use, we use master_kernel_ns + kvmclock_offset to set
6327 	 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
6328 	 * is slightly ahead) here we risk going negative on unsigned
6329 	 * 'system_time' when 'data.clock' is very small.
6330 	 */
6331 	if (data.flags & KVM_CLOCK_REALTIME) {
6332 		u64 now_real_ns = ktime_get_real_ns();
6333 
6334 		/*
6335 		 * Avoid stepping the kvmclock backwards.
6336 		 */
6337 		if (now_real_ns > data.realtime)
6338 			data.clock += now_real_ns - data.realtime;
6339 	}
6340 
6341 	if (ka->use_master_clock)
6342 		now_raw_ns = ka->master_kernel_ns;
6343 	else
6344 		now_raw_ns = get_kvmclock_base_ns();
6345 	ka->kvmclock_offset = data.clock - now_raw_ns;
6346 	kvm_end_pvclock_update(kvm);
6347 	return 0;
6348 }
6349 
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)6350 long kvm_arch_vm_ioctl(struct file *filp,
6351 		       unsigned int ioctl, unsigned long arg)
6352 {
6353 	struct kvm *kvm = filp->private_data;
6354 	void __user *argp = (void __user *)arg;
6355 	int r = -ENOTTY;
6356 	/*
6357 	 * This union makes it completely explicit to gcc-3.x
6358 	 * that these two variables' stack usage should be
6359 	 * combined, not added together.
6360 	 */
6361 	union {
6362 		struct kvm_pit_state ps;
6363 		struct kvm_pit_state2 ps2;
6364 		struct kvm_pit_config pit_config;
6365 	} u;
6366 
6367 	switch (ioctl) {
6368 	case KVM_SET_TSS_ADDR:
6369 		r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
6370 		break;
6371 	case KVM_SET_IDENTITY_MAP_ADDR: {
6372 		u64 ident_addr;
6373 
6374 		mutex_lock(&kvm->lock);
6375 		r = -EINVAL;
6376 		if (kvm->created_vcpus)
6377 			goto set_identity_unlock;
6378 		r = -EFAULT;
6379 		if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
6380 			goto set_identity_unlock;
6381 		r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
6382 set_identity_unlock:
6383 		mutex_unlock(&kvm->lock);
6384 		break;
6385 	}
6386 	case KVM_SET_NR_MMU_PAGES:
6387 		r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
6388 		break;
6389 	case KVM_GET_NR_MMU_PAGES:
6390 		r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
6391 		break;
6392 	case KVM_CREATE_IRQCHIP: {
6393 		mutex_lock(&kvm->lock);
6394 
6395 		r = -EEXIST;
6396 		if (irqchip_in_kernel(kvm))
6397 			goto create_irqchip_unlock;
6398 
6399 		r = -EINVAL;
6400 		if (kvm->created_vcpus)
6401 			goto create_irqchip_unlock;
6402 
6403 		r = kvm_pic_init(kvm);
6404 		if (r)
6405 			goto create_irqchip_unlock;
6406 
6407 		r = kvm_ioapic_init(kvm);
6408 		if (r) {
6409 			kvm_pic_destroy(kvm);
6410 			goto create_irqchip_unlock;
6411 		}
6412 
6413 		r = kvm_setup_default_irq_routing(kvm);
6414 		if (r) {
6415 			kvm_ioapic_destroy(kvm);
6416 			kvm_pic_destroy(kvm);
6417 			goto create_irqchip_unlock;
6418 		}
6419 		/* Write kvm->irq_routing before enabling irqchip_in_kernel. */
6420 		smp_wmb();
6421 		kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
6422 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6423 	create_irqchip_unlock:
6424 		mutex_unlock(&kvm->lock);
6425 		break;
6426 	}
6427 	case KVM_CREATE_PIT:
6428 		u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
6429 		goto create_pit;
6430 	case KVM_CREATE_PIT2:
6431 		r = -EFAULT;
6432 		if (copy_from_user(&u.pit_config, argp,
6433 				   sizeof(struct kvm_pit_config)))
6434 			goto out;
6435 	create_pit:
6436 		mutex_lock(&kvm->lock);
6437 		r = -EEXIST;
6438 		if (kvm->arch.vpit)
6439 			goto create_pit_unlock;
6440 		r = -ENOMEM;
6441 		kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
6442 		if (kvm->arch.vpit)
6443 			r = 0;
6444 	create_pit_unlock:
6445 		mutex_unlock(&kvm->lock);
6446 		break;
6447 	case KVM_GET_IRQCHIP: {
6448 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
6449 		struct kvm_irqchip *chip;
6450 
6451 		chip = memdup_user(argp, sizeof(*chip));
6452 		if (IS_ERR(chip)) {
6453 			r = PTR_ERR(chip);
6454 			goto out;
6455 		}
6456 
6457 		r = -ENXIO;
6458 		if (!irqchip_kernel(kvm))
6459 			goto get_irqchip_out;
6460 		r = kvm_vm_ioctl_get_irqchip(kvm, chip);
6461 		if (r)
6462 			goto get_irqchip_out;
6463 		r = -EFAULT;
6464 		if (copy_to_user(argp, chip, sizeof(*chip)))
6465 			goto get_irqchip_out;
6466 		r = 0;
6467 	get_irqchip_out:
6468 		kfree(chip);
6469 		break;
6470 	}
6471 	case KVM_SET_IRQCHIP: {
6472 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
6473 		struct kvm_irqchip *chip;
6474 
6475 		chip = memdup_user(argp, sizeof(*chip));
6476 		if (IS_ERR(chip)) {
6477 			r = PTR_ERR(chip);
6478 			goto out;
6479 		}
6480 
6481 		r = -ENXIO;
6482 		if (!irqchip_kernel(kvm))
6483 			goto set_irqchip_out;
6484 		r = kvm_vm_ioctl_set_irqchip(kvm, chip);
6485 	set_irqchip_out:
6486 		kfree(chip);
6487 		break;
6488 	}
6489 	case KVM_GET_PIT: {
6490 		r = -EFAULT;
6491 		if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
6492 			goto out;
6493 		r = -ENXIO;
6494 		if (!kvm->arch.vpit)
6495 			goto out;
6496 		r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
6497 		if (r)
6498 			goto out;
6499 		r = -EFAULT;
6500 		if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
6501 			goto out;
6502 		r = 0;
6503 		break;
6504 	}
6505 	case KVM_SET_PIT: {
6506 		r = -EFAULT;
6507 		if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
6508 			goto out;
6509 		mutex_lock(&kvm->lock);
6510 		r = -ENXIO;
6511 		if (!kvm->arch.vpit)
6512 			goto set_pit_out;
6513 		r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
6514 set_pit_out:
6515 		mutex_unlock(&kvm->lock);
6516 		break;
6517 	}
6518 	case KVM_GET_PIT2: {
6519 		r = -ENXIO;
6520 		if (!kvm->arch.vpit)
6521 			goto out;
6522 		r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
6523 		if (r)
6524 			goto out;
6525 		r = -EFAULT;
6526 		if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
6527 			goto out;
6528 		r = 0;
6529 		break;
6530 	}
6531 	case KVM_SET_PIT2: {
6532 		r = -EFAULT;
6533 		if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
6534 			goto out;
6535 		mutex_lock(&kvm->lock);
6536 		r = -ENXIO;
6537 		if (!kvm->arch.vpit)
6538 			goto set_pit2_out;
6539 		r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
6540 set_pit2_out:
6541 		mutex_unlock(&kvm->lock);
6542 		break;
6543 	}
6544 	case KVM_REINJECT_CONTROL: {
6545 		struct kvm_reinject_control control;
6546 		r =  -EFAULT;
6547 		if (copy_from_user(&control, argp, sizeof(control)))
6548 			goto out;
6549 		r = -ENXIO;
6550 		if (!kvm->arch.vpit)
6551 			goto out;
6552 		r = kvm_vm_ioctl_reinject(kvm, &control);
6553 		break;
6554 	}
6555 	case KVM_SET_BOOT_CPU_ID:
6556 		r = 0;
6557 		mutex_lock(&kvm->lock);
6558 		if (kvm->created_vcpus)
6559 			r = -EBUSY;
6560 		else
6561 			kvm->arch.bsp_vcpu_id = arg;
6562 		mutex_unlock(&kvm->lock);
6563 		break;
6564 #ifdef CONFIG_KVM_XEN
6565 	case KVM_XEN_HVM_CONFIG: {
6566 		struct kvm_xen_hvm_config xhc;
6567 		r = -EFAULT;
6568 		if (copy_from_user(&xhc, argp, sizeof(xhc)))
6569 			goto out;
6570 		r = kvm_xen_hvm_config(kvm, &xhc);
6571 		break;
6572 	}
6573 	case KVM_XEN_HVM_GET_ATTR: {
6574 		struct kvm_xen_hvm_attr xha;
6575 
6576 		r = -EFAULT;
6577 		if (copy_from_user(&xha, argp, sizeof(xha)))
6578 			goto out;
6579 		r = kvm_xen_hvm_get_attr(kvm, &xha);
6580 		if (!r && copy_to_user(argp, &xha, sizeof(xha)))
6581 			r = -EFAULT;
6582 		break;
6583 	}
6584 	case KVM_XEN_HVM_SET_ATTR: {
6585 		struct kvm_xen_hvm_attr xha;
6586 
6587 		r = -EFAULT;
6588 		if (copy_from_user(&xha, argp, sizeof(xha)))
6589 			goto out;
6590 		r = kvm_xen_hvm_set_attr(kvm, &xha);
6591 		break;
6592 	}
6593 	case KVM_XEN_HVM_EVTCHN_SEND: {
6594 		struct kvm_irq_routing_xen_evtchn uxe;
6595 
6596 		r = -EFAULT;
6597 		if (copy_from_user(&uxe, argp, sizeof(uxe)))
6598 			goto out;
6599 		r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
6600 		break;
6601 	}
6602 #endif
6603 	case KVM_SET_CLOCK:
6604 		r = kvm_vm_ioctl_set_clock(kvm, argp);
6605 		break;
6606 	case KVM_GET_CLOCK:
6607 		r = kvm_vm_ioctl_get_clock(kvm, argp);
6608 		break;
6609 	case KVM_SET_TSC_KHZ: {
6610 		u32 user_tsc_khz;
6611 
6612 		r = -EINVAL;
6613 		user_tsc_khz = (u32)arg;
6614 
6615 		if (kvm_has_tsc_control &&
6616 		    user_tsc_khz >= kvm_max_guest_tsc_khz)
6617 			goto out;
6618 
6619 		if (user_tsc_khz == 0)
6620 			user_tsc_khz = tsc_khz;
6621 
6622 		WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
6623 		r = 0;
6624 
6625 		goto out;
6626 	}
6627 	case KVM_GET_TSC_KHZ: {
6628 		r = READ_ONCE(kvm->arch.default_tsc_khz);
6629 		goto out;
6630 	}
6631 	case KVM_MEMORY_ENCRYPT_OP: {
6632 		r = -ENOTTY;
6633 		if (!kvm_x86_ops.mem_enc_ioctl)
6634 			goto out;
6635 
6636 		r = static_call(kvm_x86_mem_enc_ioctl)(kvm, argp);
6637 		break;
6638 	}
6639 	case KVM_MEMORY_ENCRYPT_REG_REGION: {
6640 		struct kvm_enc_region region;
6641 
6642 		r = -EFAULT;
6643 		if (copy_from_user(&region, argp, sizeof(region)))
6644 			goto out;
6645 
6646 		r = -ENOTTY;
6647 		if (!kvm_x86_ops.mem_enc_register_region)
6648 			goto out;
6649 
6650 		r = static_call(kvm_x86_mem_enc_register_region)(kvm, &region);
6651 		break;
6652 	}
6653 	case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
6654 		struct kvm_enc_region region;
6655 
6656 		r = -EFAULT;
6657 		if (copy_from_user(&region, argp, sizeof(region)))
6658 			goto out;
6659 
6660 		r = -ENOTTY;
6661 		if (!kvm_x86_ops.mem_enc_unregister_region)
6662 			goto out;
6663 
6664 		r = static_call(kvm_x86_mem_enc_unregister_region)(kvm, &region);
6665 		break;
6666 	}
6667 	case KVM_HYPERV_EVENTFD: {
6668 		struct kvm_hyperv_eventfd hvevfd;
6669 
6670 		r = -EFAULT;
6671 		if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
6672 			goto out;
6673 		r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
6674 		break;
6675 	}
6676 	case KVM_SET_PMU_EVENT_FILTER:
6677 		r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
6678 		break;
6679 	case KVM_X86_SET_MSR_FILTER:
6680 		r = kvm_vm_ioctl_set_msr_filter(kvm, argp);
6681 		break;
6682 	default:
6683 		r = -ENOTTY;
6684 	}
6685 out:
6686 	return r;
6687 }
6688 
kvm_init_msr_list(void)6689 static void kvm_init_msr_list(void)
6690 {
6691 	struct x86_pmu_capability x86_pmu;
6692 	u32 dummy[2];
6693 	unsigned i;
6694 
6695 	BUILD_BUG_ON_MSG(KVM_PMC_MAX_FIXED != 3,
6696 			 "Please update the fixed PMCs in msrs_to_saved_all[]");
6697 
6698 	perf_get_x86_pmu_capability(&x86_pmu);
6699 
6700 	num_msrs_to_save = 0;
6701 	num_emulated_msrs = 0;
6702 	num_msr_based_features = 0;
6703 
6704 	for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
6705 		if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
6706 			continue;
6707 
6708 		/*
6709 		 * Even MSRs that are valid in the host may not be exposed
6710 		 * to the guests in some cases.
6711 		 */
6712 		switch (msrs_to_save_all[i]) {
6713 		case MSR_IA32_BNDCFGS:
6714 			if (!kvm_mpx_supported())
6715 				continue;
6716 			break;
6717 		case MSR_TSC_AUX:
6718 			if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
6719 			    !kvm_cpu_cap_has(X86_FEATURE_RDPID))
6720 				continue;
6721 			break;
6722 		case MSR_IA32_UMWAIT_CONTROL:
6723 			if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
6724 				continue;
6725 			break;
6726 		case MSR_IA32_RTIT_CTL:
6727 		case MSR_IA32_RTIT_STATUS:
6728 			if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
6729 				continue;
6730 			break;
6731 		case MSR_IA32_RTIT_CR3_MATCH:
6732 			if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
6733 			    !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
6734 				continue;
6735 			break;
6736 		case MSR_IA32_RTIT_OUTPUT_BASE:
6737 		case MSR_IA32_RTIT_OUTPUT_MASK:
6738 			if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
6739 				(!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
6740 				 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
6741 				continue;
6742 			break;
6743 		case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
6744 			if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
6745 				msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
6746 				intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
6747 				continue;
6748 			break;
6749 		case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
6750 			if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
6751 			    min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
6752 				continue;
6753 			break;
6754 		case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
6755 			if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
6756 			    min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
6757 				continue;
6758 			break;
6759 		case MSR_IA32_XFD:
6760 		case MSR_IA32_XFD_ERR:
6761 			if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
6762 				continue;
6763 			break;
6764 		default:
6765 			break;
6766 		}
6767 
6768 		msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
6769 	}
6770 
6771 	for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
6772 		if (!static_call(kvm_x86_has_emulated_msr)(NULL, emulated_msrs_all[i]))
6773 			continue;
6774 
6775 		emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
6776 	}
6777 
6778 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
6779 		struct kvm_msr_entry msr;
6780 
6781 		msr.index = msr_based_features_all[i];
6782 		if (kvm_get_msr_feature(&msr))
6783 			continue;
6784 
6785 		msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
6786 	}
6787 }
6788 
vcpu_mmio_write(struct kvm_vcpu * vcpu,gpa_t addr,int len,const void * v)6789 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
6790 			   const void *v)
6791 {
6792 	int handled = 0;
6793 	int n;
6794 
6795 	do {
6796 		n = min(len, 8);
6797 		if (!(lapic_in_kernel(vcpu) &&
6798 		      !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
6799 		    && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
6800 			break;
6801 		handled += n;
6802 		addr += n;
6803 		len -= n;
6804 		v += n;
6805 	} while (len);
6806 
6807 	return handled;
6808 }
6809 
vcpu_mmio_read(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * v)6810 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
6811 {
6812 	int handled = 0;
6813 	int n;
6814 
6815 	do {
6816 		n = min(len, 8);
6817 		if (!(lapic_in_kernel(vcpu) &&
6818 		      !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
6819 					 addr, n, v))
6820 		    && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
6821 			break;
6822 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
6823 		handled += n;
6824 		addr += n;
6825 		len -= n;
6826 		v += n;
6827 	} while (len);
6828 
6829 	return handled;
6830 }
6831 
kvm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)6832 static void kvm_set_segment(struct kvm_vcpu *vcpu,
6833 			struct kvm_segment *var, int seg)
6834 {
6835 	static_call(kvm_x86_set_segment)(vcpu, var, seg);
6836 }
6837 
kvm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)6838 void kvm_get_segment(struct kvm_vcpu *vcpu,
6839 		     struct kvm_segment *var, int seg)
6840 {
6841 	static_call(kvm_x86_get_segment)(vcpu, var, seg);
6842 }
6843 
translate_nested_gpa(struct kvm_vcpu * vcpu,gpa_t gpa,u64 access,struct x86_exception * exception)6844 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
6845 			   struct x86_exception *exception)
6846 {
6847 	struct kvm_mmu *mmu = vcpu->arch.mmu;
6848 	gpa_t t_gpa;
6849 
6850 	BUG_ON(!mmu_is_nested(vcpu));
6851 
6852 	/* NPT walks are always user-walks */
6853 	access |= PFERR_USER_MASK;
6854 	t_gpa  = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
6855 
6856 	return t_gpa;
6857 }
6858 
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)6859 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
6860 			      struct x86_exception *exception)
6861 {
6862 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
6863 
6864 	u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6865 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
6866 }
6867 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
6868 
kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)6869  gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
6870 				struct x86_exception *exception)
6871 {
6872 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
6873 
6874 	u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6875 	access |= PFERR_FETCH_MASK;
6876 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
6877 }
6878 
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)6879 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
6880 			       struct x86_exception *exception)
6881 {
6882 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
6883 
6884 	u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6885 	access |= PFERR_WRITE_MASK;
6886 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
6887 }
6888 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
6889 
6890 /* uses this to access any guest's mapped memory without checking CPL */
kvm_mmu_gva_to_gpa_system(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)6891 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
6892 				struct x86_exception *exception)
6893 {
6894 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
6895 
6896 	return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
6897 }
6898 
kvm_read_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)6899 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
6900 				      struct kvm_vcpu *vcpu, u64 access,
6901 				      struct x86_exception *exception)
6902 {
6903 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
6904 	void *data = val;
6905 	int r = X86EMUL_CONTINUE;
6906 
6907 	while (bytes) {
6908 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
6909 		unsigned offset = addr & (PAGE_SIZE-1);
6910 		unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
6911 		int ret;
6912 
6913 		if (gpa == UNMAPPED_GVA)
6914 			return X86EMUL_PROPAGATE_FAULT;
6915 		ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
6916 					       offset, toread);
6917 		if (ret < 0) {
6918 			r = X86EMUL_IO_NEEDED;
6919 			goto out;
6920 		}
6921 
6922 		bytes -= toread;
6923 		data += toread;
6924 		addr += toread;
6925 	}
6926 out:
6927 	return r;
6928 }
6929 
6930 /* used for instruction fetching */
kvm_fetch_guest_virt(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)6931 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
6932 				gva_t addr, void *val, unsigned int bytes,
6933 				struct x86_exception *exception)
6934 {
6935 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6936 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
6937 	u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6938 	unsigned offset;
6939 	int ret;
6940 
6941 	/* Inline kvm_read_guest_virt_helper for speed.  */
6942 	gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
6943 				    exception);
6944 	if (unlikely(gpa == UNMAPPED_GVA))
6945 		return X86EMUL_PROPAGATE_FAULT;
6946 
6947 	offset = addr & (PAGE_SIZE-1);
6948 	if (WARN_ON(offset + bytes > PAGE_SIZE))
6949 		bytes = (unsigned)PAGE_SIZE - offset;
6950 	ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
6951 				       offset, bytes);
6952 	if (unlikely(ret < 0))
6953 		return X86EMUL_IO_NEEDED;
6954 
6955 	return X86EMUL_CONTINUE;
6956 }
6957 
kvm_read_guest_virt(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)6958 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
6959 			       gva_t addr, void *val, unsigned int bytes,
6960 			       struct x86_exception *exception)
6961 {
6962 	u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
6963 
6964 	/*
6965 	 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
6966 	 * is returned, but our callers are not ready for that and they blindly
6967 	 * call kvm_inject_page_fault.  Ensure that they at least do not leak
6968 	 * uninitialized kernel stack memory into cr2 and error code.
6969 	 */
6970 	memset(exception, 0, sizeof(*exception));
6971 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
6972 					  exception);
6973 }
6974 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
6975 
emulator_read_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)6976 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
6977 			     gva_t addr, void *val, unsigned int bytes,
6978 			     struct x86_exception *exception, bool system)
6979 {
6980 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6981 	u64 access = 0;
6982 
6983 	if (system)
6984 		access |= PFERR_IMPLICIT_ACCESS;
6985 	else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
6986 		access |= PFERR_USER_MASK;
6987 
6988 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
6989 }
6990 
kvm_read_guest_phys_system(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes)6991 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
6992 		unsigned long addr, void *val, unsigned int bytes)
6993 {
6994 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6995 	int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
6996 
6997 	return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
6998 }
6999 
kvm_write_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7000 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7001 				      struct kvm_vcpu *vcpu, u64 access,
7002 				      struct x86_exception *exception)
7003 {
7004 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7005 	void *data = val;
7006 	int r = X86EMUL_CONTINUE;
7007 
7008 	while (bytes) {
7009 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7010 		unsigned offset = addr & (PAGE_SIZE-1);
7011 		unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7012 		int ret;
7013 
7014 		if (gpa == UNMAPPED_GVA)
7015 			return X86EMUL_PROPAGATE_FAULT;
7016 		ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7017 		if (ret < 0) {
7018 			r = X86EMUL_IO_NEEDED;
7019 			goto out;
7020 		}
7021 
7022 		bytes -= towrite;
7023 		data += towrite;
7024 		addr += towrite;
7025 	}
7026 out:
7027 	return r;
7028 }
7029 
emulator_write_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7030 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7031 			      unsigned int bytes, struct x86_exception *exception,
7032 			      bool system)
7033 {
7034 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7035 	u64 access = PFERR_WRITE_MASK;
7036 
7037 	if (system)
7038 		access |= PFERR_IMPLICIT_ACCESS;
7039 	else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
7040 		access |= PFERR_USER_MASK;
7041 
7042 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7043 					   access, exception);
7044 }
7045 
kvm_write_guest_virt_system(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7046 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7047 				unsigned int bytes, struct x86_exception *exception)
7048 {
7049 	/* kvm_write_guest_virt_system can pull in tons of pages. */
7050 	vcpu->arch.l1tf_flush_l1d = true;
7051 
7052 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7053 					   PFERR_WRITE_MASK, exception);
7054 }
7055 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
7056 
kvm_can_emulate_insn(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)7057 static int kvm_can_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7058 				void *insn, int insn_len)
7059 {
7060 	return static_call(kvm_x86_can_emulate_instruction)(vcpu, emul_type,
7061 							    insn, insn_len);
7062 }
7063 
handle_ud(struct kvm_vcpu * vcpu)7064 int handle_ud(struct kvm_vcpu *vcpu)
7065 {
7066 	static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
7067 	int emul_type = EMULTYPE_TRAP_UD;
7068 	char sig[5]; /* ud2; .ascii "kvm" */
7069 	struct x86_exception e;
7070 
7071 	if (unlikely(!kvm_can_emulate_insn(vcpu, emul_type, NULL, 0)))
7072 		return 1;
7073 
7074 	if (force_emulation_prefix &&
7075 	    kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
7076 				sig, sizeof(sig), &e) == 0 &&
7077 	    memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
7078 		kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
7079 		emul_type = EMULTYPE_TRAP_UD_FORCED;
7080 	}
7081 
7082 	return kvm_emulate_instruction(vcpu, emul_type);
7083 }
7084 EXPORT_SYMBOL_GPL(handle_ud);
7085 
vcpu_is_mmio_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t gpa,bool write)7086 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7087 			    gpa_t gpa, bool write)
7088 {
7089 	/* For APIC access vmexit */
7090 	if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7091 		return 1;
7092 
7093 	if (vcpu_match_mmio_gpa(vcpu, gpa)) {
7094 		trace_vcpu_match_mmio(gva, gpa, write, true);
7095 		return 1;
7096 	}
7097 
7098 	return 0;
7099 }
7100 
vcpu_mmio_gva_to_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t * gpa,struct x86_exception * exception,bool write)7101 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7102 				gpa_t *gpa, struct x86_exception *exception,
7103 				bool write)
7104 {
7105 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7106 	u64 access = ((static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
7107 		| (write ? PFERR_WRITE_MASK : 0);
7108 
7109 	/*
7110 	 * currently PKRU is only applied to ept enabled guest so
7111 	 * there is no pkey in EPT page table for L1 guest or EPT
7112 	 * shadow page table for L2 guest.
7113 	 */
7114 	if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
7115 	    !permission_fault(vcpu, vcpu->arch.walk_mmu,
7116 			      vcpu->arch.mmio_access, 0, access))) {
7117 		*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
7118 					(gva & (PAGE_SIZE - 1));
7119 		trace_vcpu_match_mmio(gva, *gpa, write, false);
7120 		return 1;
7121 	}
7122 
7123 	*gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7124 
7125 	if (*gpa == UNMAPPED_GVA)
7126 		return -1;
7127 
7128 	return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
7129 }
7130 
emulator_write_phys(struct kvm_vcpu * vcpu,gpa_t gpa,const void * val,int bytes)7131 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
7132 			const void *val, int bytes)
7133 {
7134 	int ret;
7135 
7136 	ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
7137 	if (ret < 0)
7138 		return 0;
7139 	kvm_page_track_write(vcpu, gpa, val, bytes);
7140 	return 1;
7141 }
7142 
7143 struct read_write_emulator_ops {
7144 	int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
7145 				  int bytes);
7146 	int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
7147 				  void *val, int bytes);
7148 	int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7149 			       int bytes, void *val);
7150 	int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7151 				    void *val, int bytes);
7152 	bool write;
7153 };
7154 
read_prepare(struct kvm_vcpu * vcpu,void * val,int bytes)7155 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
7156 {
7157 	if (vcpu->mmio_read_completed) {
7158 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
7159 			       vcpu->mmio_fragments[0].gpa, val);
7160 		vcpu->mmio_read_completed = 0;
7161 		return 1;
7162 	}
7163 
7164 	return 0;
7165 }
7166 
read_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7167 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7168 			void *val, int bytes)
7169 {
7170 	return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
7171 }
7172 
write_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7173 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7174 			 void *val, int bytes)
7175 {
7176 	return emulator_write_phys(vcpu, gpa, val, bytes);
7177 }
7178 
write_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,int bytes,void * val)7179 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7180 {
7181 	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
7182 	return vcpu_mmio_write(vcpu, gpa, bytes, val);
7183 }
7184 
read_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7185 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7186 			  void *val, int bytes)
7187 {
7188 	trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
7189 	return X86EMUL_IO_NEEDED;
7190 }
7191 
write_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7192 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7193 			   void *val, int bytes)
7194 {
7195 	struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7196 
7197 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
7198 	return X86EMUL_CONTINUE;
7199 }
7200 
7201 static const struct read_write_emulator_ops read_emultor = {
7202 	.read_write_prepare = read_prepare,
7203 	.read_write_emulate = read_emulate,
7204 	.read_write_mmio = vcpu_mmio_read,
7205 	.read_write_exit_mmio = read_exit_mmio,
7206 };
7207 
7208 static const struct read_write_emulator_ops write_emultor = {
7209 	.read_write_emulate = write_emulate,
7210 	.read_write_mmio = write_mmio,
7211 	.read_write_exit_mmio = write_exit_mmio,
7212 	.write = true,
7213 };
7214 
emulator_read_write_onepage(unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception,struct kvm_vcpu * vcpu,const struct read_write_emulator_ops * ops)7215 static int emulator_read_write_onepage(unsigned long addr, void *val,
7216 				       unsigned int bytes,
7217 				       struct x86_exception *exception,
7218 				       struct kvm_vcpu *vcpu,
7219 				       const struct read_write_emulator_ops *ops)
7220 {
7221 	gpa_t gpa;
7222 	int handled, ret;
7223 	bool write = ops->write;
7224 	struct kvm_mmio_fragment *frag;
7225 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7226 
7227 	/*
7228 	 * If the exit was due to a NPF we may already have a GPA.
7229 	 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7230 	 * Note, this cannot be used on string operations since string
7231 	 * operation using rep will only have the initial GPA from the NPF
7232 	 * occurred.
7233 	 */
7234 	if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7235 	    (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7236 		gpa = ctxt->gpa_val;
7237 		ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7238 	} else {
7239 		ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7240 		if (ret < 0)
7241 			return X86EMUL_PROPAGATE_FAULT;
7242 	}
7243 
7244 	if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
7245 		return X86EMUL_CONTINUE;
7246 
7247 	/*
7248 	 * Is this MMIO handled locally?
7249 	 */
7250 	handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
7251 	if (handled == bytes)
7252 		return X86EMUL_CONTINUE;
7253 
7254 	gpa += handled;
7255 	bytes -= handled;
7256 	val += handled;
7257 
7258 	WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
7259 	frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
7260 	frag->gpa = gpa;
7261 	frag->data = val;
7262 	frag->len = bytes;
7263 	return X86EMUL_CONTINUE;
7264 }
7265 
emulator_read_write(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception,const struct read_write_emulator_ops * ops)7266 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
7267 			unsigned long addr,
7268 			void *val, unsigned int bytes,
7269 			struct x86_exception *exception,
7270 			const struct read_write_emulator_ops *ops)
7271 {
7272 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7273 	gpa_t gpa;
7274 	int rc;
7275 
7276 	if (ops->read_write_prepare &&
7277 		  ops->read_write_prepare(vcpu, val, bytes))
7278 		return X86EMUL_CONTINUE;
7279 
7280 	vcpu->mmio_nr_fragments = 0;
7281 
7282 	/* Crossing a page boundary? */
7283 	if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
7284 		int now;
7285 
7286 		now = -addr & ~PAGE_MASK;
7287 		rc = emulator_read_write_onepage(addr, val, now, exception,
7288 						 vcpu, ops);
7289 
7290 		if (rc != X86EMUL_CONTINUE)
7291 			return rc;
7292 		addr += now;
7293 		if (ctxt->mode != X86EMUL_MODE_PROT64)
7294 			addr = (u32)addr;
7295 		val += now;
7296 		bytes -= now;
7297 	}
7298 
7299 	rc = emulator_read_write_onepage(addr, val, bytes, exception,
7300 					 vcpu, ops);
7301 	if (rc != X86EMUL_CONTINUE)
7302 		return rc;
7303 
7304 	if (!vcpu->mmio_nr_fragments)
7305 		return rc;
7306 
7307 	gpa = vcpu->mmio_fragments[0].gpa;
7308 
7309 	vcpu->mmio_needed = 1;
7310 	vcpu->mmio_cur_fragment = 0;
7311 
7312 	vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
7313 	vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
7314 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
7315 	vcpu->run->mmio.phys_addr = gpa;
7316 
7317 	return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
7318 }
7319 
emulator_read_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception)7320 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
7321 				  unsigned long addr,
7322 				  void *val,
7323 				  unsigned int bytes,
7324 				  struct x86_exception *exception)
7325 {
7326 	return emulator_read_write(ctxt, addr, val, bytes,
7327 				   exception, &read_emultor);
7328 }
7329 
emulator_write_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * val,unsigned int bytes,struct x86_exception * exception)7330 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
7331 			    unsigned long addr,
7332 			    const void *val,
7333 			    unsigned int bytes,
7334 			    struct x86_exception *exception)
7335 {
7336 	return emulator_read_write(ctxt, addr, (void *)val, bytes,
7337 				   exception, &write_emultor);
7338 }
7339 
7340 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
7341 	(__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
7342 
emulator_cmpxchg_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * old,const void * new,unsigned int bytes,struct x86_exception * exception)7343 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
7344 				     unsigned long addr,
7345 				     const void *old,
7346 				     const void *new,
7347 				     unsigned int bytes,
7348 				     struct x86_exception *exception)
7349 {
7350 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7351 	u64 page_line_mask;
7352 	unsigned long hva;
7353 	gpa_t gpa;
7354 	int r;
7355 
7356 	/* guests cmpxchg8b have to be emulated atomically */
7357 	if (bytes > 8 || (bytes & (bytes - 1)))
7358 		goto emul_write;
7359 
7360 	gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
7361 
7362 	if (gpa == UNMAPPED_GVA ||
7363 	    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7364 		goto emul_write;
7365 
7366 	/*
7367 	 * Emulate the atomic as a straight write to avoid #AC if SLD is
7368 	 * enabled in the host and the access splits a cache line.
7369 	 */
7370 	if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
7371 		page_line_mask = ~(cache_line_size() - 1);
7372 	else
7373 		page_line_mask = PAGE_MASK;
7374 
7375 	if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
7376 		goto emul_write;
7377 
7378 	hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
7379 	if (kvm_is_error_hva(hva))
7380 		goto emul_write;
7381 
7382 	hva += offset_in_page(gpa);
7383 
7384 	switch (bytes) {
7385 	case 1:
7386 		r = emulator_try_cmpxchg_user(u8, hva, old, new);
7387 		break;
7388 	case 2:
7389 		r = emulator_try_cmpxchg_user(u16, hva, old, new);
7390 		break;
7391 	case 4:
7392 		r = emulator_try_cmpxchg_user(u32, hva, old, new);
7393 		break;
7394 	case 8:
7395 		r = emulator_try_cmpxchg_user(u64, hva, old, new);
7396 		break;
7397 	default:
7398 		BUG();
7399 	}
7400 
7401 	if (r < 0)
7402 		return X86EMUL_UNHANDLEABLE;
7403 	if (r)
7404 		return X86EMUL_CMPXCHG_FAILED;
7405 
7406 	kvm_page_track_write(vcpu, gpa, new, bytes);
7407 
7408 	return X86EMUL_CONTINUE;
7409 
7410 emul_write:
7411 	printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
7412 
7413 	return emulator_write_emulated(ctxt, addr, new, bytes, exception);
7414 }
7415 
kernel_pio(struct kvm_vcpu * vcpu,void * pd)7416 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
7417 {
7418 	int r = 0, i;
7419 
7420 	for (i = 0; i < vcpu->arch.pio.count; i++) {
7421 		if (vcpu->arch.pio.in)
7422 			r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
7423 					    vcpu->arch.pio.size, pd);
7424 		else
7425 			r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
7426 					     vcpu->arch.pio.port, vcpu->arch.pio.size,
7427 					     pd);
7428 		if (r)
7429 			break;
7430 		pd += vcpu->arch.pio.size;
7431 	}
7432 	return r;
7433 }
7434 
emulator_pio_in_out(struct kvm_vcpu * vcpu,int size,unsigned short port,unsigned int count,bool in)7435 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
7436 			       unsigned short port,
7437 			       unsigned int count, bool in)
7438 {
7439 	vcpu->arch.pio.port = port;
7440 	vcpu->arch.pio.in = in;
7441 	vcpu->arch.pio.count  = count;
7442 	vcpu->arch.pio.size = size;
7443 
7444 	if (!kernel_pio(vcpu, vcpu->arch.pio_data))
7445 		return 1;
7446 
7447 	vcpu->run->exit_reason = KVM_EXIT_IO;
7448 	vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
7449 	vcpu->run->io.size = size;
7450 	vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
7451 	vcpu->run->io.count = count;
7452 	vcpu->run->io.port = port;
7453 
7454 	return 0;
7455 }
7456 
__emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,unsigned int count)7457 static int __emulator_pio_in(struct kvm_vcpu *vcpu, int size,
7458 			     unsigned short port, unsigned int count)
7459 {
7460 	WARN_ON(vcpu->arch.pio.count);
7461 	memset(vcpu->arch.pio_data, 0, size * count);
7462 	return emulator_pio_in_out(vcpu, size, port, count, true);
7463 }
7464 
complete_emulator_pio_in(struct kvm_vcpu * vcpu,void * val)7465 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
7466 {
7467 	int size = vcpu->arch.pio.size;
7468 	unsigned count = vcpu->arch.pio.count;
7469 	memcpy(val, vcpu->arch.pio_data, size * count);
7470 	trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
7471 	vcpu->arch.pio.count = 0;
7472 }
7473 
emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,void * val,unsigned int count)7474 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
7475 			   unsigned short port, void *val, unsigned int count)
7476 {
7477 	if (vcpu->arch.pio.count) {
7478 		/*
7479 		 * Complete a previous iteration that required userspace I/O.
7480 		 * Note, @count isn't guaranteed to match pio.count as userspace
7481 		 * can modify ECX before rerunning the vCPU.  Ignore any such
7482 		 * shenanigans as KVM doesn't support modifying the rep count,
7483 		 * and the emulator ensures @count doesn't overflow the buffer.
7484 		 */
7485 	} else {
7486 		int r = __emulator_pio_in(vcpu, size, port, count);
7487 		if (!r)
7488 			return r;
7489 
7490 		/* Results already available, fall through.  */
7491 	}
7492 
7493 	complete_emulator_pio_in(vcpu, val);
7494 	return 1;
7495 }
7496 
emulator_pio_in_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,void * val,unsigned int count)7497 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
7498 				    int size, unsigned short port, void *val,
7499 				    unsigned int count)
7500 {
7501 	return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
7502 
7503 }
7504 
emulator_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port,const void * val,unsigned int count)7505 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
7506 			    unsigned short port, const void *val,
7507 			    unsigned int count)
7508 {
7509 	int ret;
7510 
7511 	memcpy(vcpu->arch.pio_data, val, size * count);
7512 	trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
7513 	ret = emulator_pio_in_out(vcpu, size, port, count, false);
7514 	if (ret)
7515                 vcpu->arch.pio.count = 0;
7516 
7517         return ret;
7518 }
7519 
emulator_pio_out_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,const void * val,unsigned int count)7520 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
7521 				     int size, unsigned short port,
7522 				     const void *val, unsigned int count)
7523 {
7524 	return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
7525 }
7526 
get_segment_base(struct kvm_vcpu * vcpu,int seg)7527 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
7528 {
7529 	return static_call(kvm_x86_get_segment_base)(vcpu, seg);
7530 }
7531 
emulator_invlpg(struct x86_emulate_ctxt * ctxt,ulong address)7532 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
7533 {
7534 	kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
7535 }
7536 
kvm_emulate_wbinvd_noskip(struct kvm_vcpu * vcpu)7537 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
7538 {
7539 	if (!need_emulate_wbinvd(vcpu))
7540 		return X86EMUL_CONTINUE;
7541 
7542 	if (static_call(kvm_x86_has_wbinvd_exit)()) {
7543 		int cpu = get_cpu();
7544 
7545 		cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
7546 		on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
7547 				wbinvd_ipi, NULL, 1);
7548 		put_cpu();
7549 		cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
7550 	} else
7551 		wbinvd();
7552 	return X86EMUL_CONTINUE;
7553 }
7554 
kvm_emulate_wbinvd(struct kvm_vcpu * vcpu)7555 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
7556 {
7557 	kvm_emulate_wbinvd_noskip(vcpu);
7558 	return kvm_skip_emulated_instruction(vcpu);
7559 }
7560 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
7561 
7562 
7563 
emulator_wbinvd(struct x86_emulate_ctxt * ctxt)7564 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
7565 {
7566 	kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
7567 }
7568 
emulator_get_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long * dest)7569 static void emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
7570 			    unsigned long *dest)
7571 {
7572 	kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
7573 }
7574 
emulator_set_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long value)7575 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
7576 			   unsigned long value)
7577 {
7578 
7579 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
7580 }
7581 
mk_cr_64(u64 curr_cr,u32 new_val)7582 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
7583 {
7584 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
7585 }
7586 
emulator_get_cr(struct x86_emulate_ctxt * ctxt,int cr)7587 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
7588 {
7589 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7590 	unsigned long value;
7591 
7592 	switch (cr) {
7593 	case 0:
7594 		value = kvm_read_cr0(vcpu);
7595 		break;
7596 	case 2:
7597 		value = vcpu->arch.cr2;
7598 		break;
7599 	case 3:
7600 		value = kvm_read_cr3(vcpu);
7601 		break;
7602 	case 4:
7603 		value = kvm_read_cr4(vcpu);
7604 		break;
7605 	case 8:
7606 		value = kvm_get_cr8(vcpu);
7607 		break;
7608 	default:
7609 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
7610 		return 0;
7611 	}
7612 
7613 	return value;
7614 }
7615 
emulator_set_cr(struct x86_emulate_ctxt * ctxt,int cr,ulong val)7616 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
7617 {
7618 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7619 	int res = 0;
7620 
7621 	switch (cr) {
7622 	case 0:
7623 		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
7624 		break;
7625 	case 2:
7626 		vcpu->arch.cr2 = val;
7627 		break;
7628 	case 3:
7629 		res = kvm_set_cr3(vcpu, val);
7630 		break;
7631 	case 4:
7632 		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
7633 		break;
7634 	case 8:
7635 		res = kvm_set_cr8(vcpu, val);
7636 		break;
7637 	default:
7638 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
7639 		res = -1;
7640 	}
7641 
7642 	return res;
7643 }
7644 
emulator_get_cpl(struct x86_emulate_ctxt * ctxt)7645 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
7646 {
7647 	return static_call(kvm_x86_get_cpl)(emul_to_vcpu(ctxt));
7648 }
7649 
emulator_get_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)7650 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7651 {
7652 	static_call(kvm_x86_get_gdt)(emul_to_vcpu(ctxt), dt);
7653 }
7654 
emulator_get_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)7655 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7656 {
7657 	static_call(kvm_x86_get_idt)(emul_to_vcpu(ctxt), dt);
7658 }
7659 
emulator_set_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)7660 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7661 {
7662 	static_call(kvm_x86_set_gdt)(emul_to_vcpu(ctxt), dt);
7663 }
7664 
emulator_set_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)7665 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7666 {
7667 	static_call(kvm_x86_set_idt)(emul_to_vcpu(ctxt), dt);
7668 }
7669 
emulator_get_cached_segment_base(struct x86_emulate_ctxt * ctxt,int seg)7670 static unsigned long emulator_get_cached_segment_base(
7671 	struct x86_emulate_ctxt *ctxt, int seg)
7672 {
7673 	return get_segment_base(emul_to_vcpu(ctxt), seg);
7674 }
7675 
emulator_get_segment(struct x86_emulate_ctxt * ctxt,u16 * selector,struct desc_struct * desc,u32 * base3,int seg)7676 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
7677 				 struct desc_struct *desc, u32 *base3,
7678 				 int seg)
7679 {
7680 	struct kvm_segment var;
7681 
7682 	kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
7683 	*selector = var.selector;
7684 
7685 	if (var.unusable) {
7686 		memset(desc, 0, sizeof(*desc));
7687 		if (base3)
7688 			*base3 = 0;
7689 		return false;
7690 	}
7691 
7692 	if (var.g)
7693 		var.limit >>= 12;
7694 	set_desc_limit(desc, var.limit);
7695 	set_desc_base(desc, (unsigned long)var.base);
7696 #ifdef CONFIG_X86_64
7697 	if (base3)
7698 		*base3 = var.base >> 32;
7699 #endif
7700 	desc->type = var.type;
7701 	desc->s = var.s;
7702 	desc->dpl = var.dpl;
7703 	desc->p = var.present;
7704 	desc->avl = var.avl;
7705 	desc->l = var.l;
7706 	desc->d = var.db;
7707 	desc->g = var.g;
7708 
7709 	return true;
7710 }
7711 
emulator_set_segment(struct x86_emulate_ctxt * ctxt,u16 selector,struct desc_struct * desc,u32 base3,int seg)7712 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
7713 				 struct desc_struct *desc, u32 base3,
7714 				 int seg)
7715 {
7716 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7717 	struct kvm_segment var;
7718 
7719 	var.selector = selector;
7720 	var.base = get_desc_base(desc);
7721 #ifdef CONFIG_X86_64
7722 	var.base |= ((u64)base3) << 32;
7723 #endif
7724 	var.limit = get_desc_limit(desc);
7725 	if (desc->g)
7726 		var.limit = (var.limit << 12) | 0xfff;
7727 	var.type = desc->type;
7728 	var.dpl = desc->dpl;
7729 	var.db = desc->d;
7730 	var.s = desc->s;
7731 	var.l = desc->l;
7732 	var.g = desc->g;
7733 	var.avl = desc->avl;
7734 	var.present = desc->p;
7735 	var.unusable = !var.present;
7736 	var.padding = 0;
7737 
7738 	kvm_set_segment(vcpu, &var, seg);
7739 	return;
7740 }
7741 
emulator_get_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)7742 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
7743 					u32 msr_index, u64 *pdata)
7744 {
7745 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7746 	int r;
7747 
7748 	r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
7749 
7750 	if (r && kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
7751 				    complete_emulated_rdmsr, r)) {
7752 		/* Bounce to user space */
7753 		return X86EMUL_IO_NEEDED;
7754 	}
7755 
7756 	return r;
7757 }
7758 
emulator_set_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)7759 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
7760 					u32 msr_index, u64 data)
7761 {
7762 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7763 	int r;
7764 
7765 	r = kvm_set_msr_with_filter(vcpu, msr_index, data);
7766 
7767 	if (r && kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
7768 				    complete_emulated_msr_access, r)) {
7769 		/* Bounce to user space */
7770 		return X86EMUL_IO_NEEDED;
7771 	}
7772 
7773 	return r;
7774 }
7775 
emulator_get_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)7776 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
7777 			    u32 msr_index, u64 *pdata)
7778 {
7779 	return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
7780 }
7781 
emulator_set_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)7782 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
7783 			    u32 msr_index, u64 data)
7784 {
7785 	return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
7786 }
7787 
emulator_get_smbase(struct x86_emulate_ctxt * ctxt)7788 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
7789 {
7790 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7791 
7792 	return vcpu->arch.smbase;
7793 }
7794 
emulator_set_smbase(struct x86_emulate_ctxt * ctxt,u64 smbase)7795 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
7796 {
7797 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7798 
7799 	vcpu->arch.smbase = smbase;
7800 }
7801 
emulator_check_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc)7802 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
7803 			      u32 pmc)
7804 {
7805 	if (kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc))
7806 		return 0;
7807 	return -EINVAL;
7808 }
7809 
emulator_read_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc,u64 * pdata)7810 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
7811 			     u32 pmc, u64 *pdata)
7812 {
7813 	return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
7814 }
7815 
emulator_halt(struct x86_emulate_ctxt * ctxt)7816 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
7817 {
7818 	emul_to_vcpu(ctxt)->arch.halt_request = 1;
7819 }
7820 
emulator_intercept(struct x86_emulate_ctxt * ctxt,struct x86_instruction_info * info,enum x86_intercept_stage stage)7821 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
7822 			      struct x86_instruction_info *info,
7823 			      enum x86_intercept_stage stage)
7824 {
7825 	return static_call(kvm_x86_check_intercept)(emul_to_vcpu(ctxt), info, stage,
7826 					    &ctxt->exception);
7827 }
7828 
emulator_get_cpuid(struct x86_emulate_ctxt * ctxt,u32 * eax,u32 * ebx,u32 * ecx,u32 * edx,bool exact_only)7829 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
7830 			      u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
7831 			      bool exact_only)
7832 {
7833 	return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
7834 }
7835 
emulator_guest_has_long_mode(struct x86_emulate_ctxt * ctxt)7836 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
7837 {
7838 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
7839 }
7840 
emulator_guest_has_movbe(struct x86_emulate_ctxt * ctxt)7841 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
7842 {
7843 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
7844 }
7845 
emulator_guest_has_fxsr(struct x86_emulate_ctxt * ctxt)7846 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
7847 {
7848 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
7849 }
7850 
emulator_guest_has_rdpid(struct x86_emulate_ctxt * ctxt)7851 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
7852 {
7853 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
7854 }
7855 
emulator_read_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg)7856 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
7857 {
7858 	return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
7859 }
7860 
emulator_write_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg,ulong val)7861 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
7862 {
7863 	kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
7864 }
7865 
emulator_set_nmi_mask(struct x86_emulate_ctxt * ctxt,bool masked)7866 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
7867 {
7868 	static_call(kvm_x86_set_nmi_mask)(emul_to_vcpu(ctxt), masked);
7869 }
7870 
emulator_get_hflags(struct x86_emulate_ctxt * ctxt)7871 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
7872 {
7873 	return emul_to_vcpu(ctxt)->arch.hflags;
7874 }
7875 
emulator_exiting_smm(struct x86_emulate_ctxt * ctxt)7876 static void emulator_exiting_smm(struct x86_emulate_ctxt *ctxt)
7877 {
7878 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7879 
7880 	kvm_smm_changed(vcpu, false);
7881 }
7882 
emulator_leave_smm(struct x86_emulate_ctxt * ctxt,const char * smstate)7883 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt,
7884 				  const char *smstate)
7885 {
7886 	return static_call(kvm_x86_leave_smm)(emul_to_vcpu(ctxt), smstate);
7887 }
7888 
emulator_triple_fault(struct x86_emulate_ctxt * ctxt)7889 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
7890 {
7891 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
7892 }
7893 
emulator_set_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 xcr)7894 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
7895 {
7896 	return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
7897 }
7898 
7899 static const struct x86_emulate_ops emulate_ops = {
7900 	.read_gpr            = emulator_read_gpr,
7901 	.write_gpr           = emulator_write_gpr,
7902 	.read_std            = emulator_read_std,
7903 	.write_std           = emulator_write_std,
7904 	.read_phys           = kvm_read_guest_phys_system,
7905 	.fetch               = kvm_fetch_guest_virt,
7906 	.read_emulated       = emulator_read_emulated,
7907 	.write_emulated      = emulator_write_emulated,
7908 	.cmpxchg_emulated    = emulator_cmpxchg_emulated,
7909 	.invlpg              = emulator_invlpg,
7910 	.pio_in_emulated     = emulator_pio_in_emulated,
7911 	.pio_out_emulated    = emulator_pio_out_emulated,
7912 	.get_segment         = emulator_get_segment,
7913 	.set_segment         = emulator_set_segment,
7914 	.get_cached_segment_base = emulator_get_cached_segment_base,
7915 	.get_gdt             = emulator_get_gdt,
7916 	.get_idt	     = emulator_get_idt,
7917 	.set_gdt             = emulator_set_gdt,
7918 	.set_idt	     = emulator_set_idt,
7919 	.get_cr              = emulator_get_cr,
7920 	.set_cr              = emulator_set_cr,
7921 	.cpl                 = emulator_get_cpl,
7922 	.get_dr              = emulator_get_dr,
7923 	.set_dr              = emulator_set_dr,
7924 	.get_smbase          = emulator_get_smbase,
7925 	.set_smbase          = emulator_set_smbase,
7926 	.set_msr_with_filter = emulator_set_msr_with_filter,
7927 	.get_msr_with_filter = emulator_get_msr_with_filter,
7928 	.set_msr             = emulator_set_msr,
7929 	.get_msr             = emulator_get_msr,
7930 	.check_pmc	     = emulator_check_pmc,
7931 	.read_pmc            = emulator_read_pmc,
7932 	.halt                = emulator_halt,
7933 	.wbinvd              = emulator_wbinvd,
7934 	.fix_hypercall       = emulator_fix_hypercall,
7935 	.intercept           = emulator_intercept,
7936 	.get_cpuid           = emulator_get_cpuid,
7937 	.guest_has_long_mode = emulator_guest_has_long_mode,
7938 	.guest_has_movbe     = emulator_guest_has_movbe,
7939 	.guest_has_fxsr      = emulator_guest_has_fxsr,
7940 	.guest_has_rdpid     = emulator_guest_has_rdpid,
7941 	.set_nmi_mask        = emulator_set_nmi_mask,
7942 	.get_hflags          = emulator_get_hflags,
7943 	.exiting_smm         = emulator_exiting_smm,
7944 	.leave_smm           = emulator_leave_smm,
7945 	.triple_fault        = emulator_triple_fault,
7946 	.set_xcr             = emulator_set_xcr,
7947 };
7948 
toggle_interruptibility(struct kvm_vcpu * vcpu,u32 mask)7949 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
7950 {
7951 	u32 int_shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
7952 	/*
7953 	 * an sti; sti; sequence only disable interrupts for the first
7954 	 * instruction. So, if the last instruction, be it emulated or
7955 	 * not, left the system with the INT_STI flag enabled, it
7956 	 * means that the last instruction is an sti. We should not
7957 	 * leave the flag on in this case. The same goes for mov ss
7958 	 */
7959 	if (int_shadow & mask)
7960 		mask = 0;
7961 	if (unlikely(int_shadow || mask)) {
7962 		static_call(kvm_x86_set_interrupt_shadow)(vcpu, mask);
7963 		if (!mask)
7964 			kvm_make_request(KVM_REQ_EVENT, vcpu);
7965 	}
7966 }
7967 
inject_emulated_exception(struct kvm_vcpu * vcpu)7968 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
7969 {
7970 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7971 	if (ctxt->exception.vector == PF_VECTOR)
7972 		return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
7973 
7974 	if (ctxt->exception.error_code_valid)
7975 		kvm_queue_exception_e(vcpu, ctxt->exception.vector,
7976 				      ctxt->exception.error_code);
7977 	else
7978 		kvm_queue_exception(vcpu, ctxt->exception.vector);
7979 	return false;
7980 }
7981 
alloc_emulate_ctxt(struct kvm_vcpu * vcpu)7982 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
7983 {
7984 	struct x86_emulate_ctxt *ctxt;
7985 
7986 	ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
7987 	if (!ctxt) {
7988 		pr_err("kvm: failed to allocate vcpu's emulator\n");
7989 		return NULL;
7990 	}
7991 
7992 	ctxt->vcpu = vcpu;
7993 	ctxt->ops = &emulate_ops;
7994 	vcpu->arch.emulate_ctxt = ctxt;
7995 
7996 	return ctxt;
7997 }
7998 
init_emulate_ctxt(struct kvm_vcpu * vcpu)7999 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8000 {
8001 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8002 	int cs_db, cs_l;
8003 
8004 	static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8005 
8006 	ctxt->gpa_available = false;
8007 	ctxt->eflags = kvm_get_rflags(vcpu);
8008 	ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8009 
8010 	ctxt->eip = kvm_rip_read(vcpu);
8011 	ctxt->mode = (!is_protmode(vcpu))		? X86EMUL_MODE_REAL :
8012 		     (ctxt->eflags & X86_EFLAGS_VM)	? X86EMUL_MODE_VM86 :
8013 		     (cs_l && is_long_mode(vcpu))	? X86EMUL_MODE_PROT64 :
8014 		     cs_db				? X86EMUL_MODE_PROT32 :
8015 							  X86EMUL_MODE_PROT16;
8016 	BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
8017 	BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
8018 	BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
8019 
8020 	ctxt->interruptibility = 0;
8021 	ctxt->have_exception = false;
8022 	ctxt->exception.vector = -1;
8023 	ctxt->perm_ok = false;
8024 
8025 	init_decode_cache(ctxt);
8026 	vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8027 }
8028 
kvm_inject_realmode_interrupt(struct kvm_vcpu * vcpu,int irq,int inc_eip)8029 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8030 {
8031 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8032 	int ret;
8033 
8034 	init_emulate_ctxt(vcpu);
8035 
8036 	ctxt->op_bytes = 2;
8037 	ctxt->ad_bytes = 2;
8038 	ctxt->_eip = ctxt->eip + inc_eip;
8039 	ret = emulate_int_real(ctxt, irq);
8040 
8041 	if (ret != X86EMUL_CONTINUE) {
8042 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8043 	} else {
8044 		ctxt->eip = ctxt->_eip;
8045 		kvm_rip_write(vcpu, ctxt->eip);
8046 		kvm_set_rflags(vcpu, ctxt->eflags);
8047 	}
8048 }
8049 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
8050 
prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata,u8 * insn_bytes,u8 insn_size)8051 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8052 					   u8 ndata, u8 *insn_bytes, u8 insn_size)
8053 {
8054 	struct kvm_run *run = vcpu->run;
8055 	u64 info[5];
8056 	u8 info_start;
8057 
8058 	/*
8059 	 * Zero the whole array used to retrieve the exit info, as casting to
8060 	 * u32 for select entries will leave some chunks uninitialized.
8061 	 */
8062 	memset(&info, 0, sizeof(info));
8063 
8064 	static_call(kvm_x86_get_exit_info)(vcpu, (u32 *)&info[0], &info[1],
8065 					   &info[2], (u32 *)&info[3],
8066 					   (u32 *)&info[4]);
8067 
8068 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8069 	run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
8070 
8071 	/*
8072 	 * There's currently space for 13 entries, but 5 are used for the exit
8073 	 * reason and info.  Restrict to 4 to reduce the maintenance burden
8074 	 * when expanding kvm_run.emulation_failure in the future.
8075 	 */
8076 	if (WARN_ON_ONCE(ndata > 4))
8077 		ndata = 4;
8078 
8079 	/* Always include the flags as a 'data' entry. */
8080 	info_start = 1;
8081 	run->emulation_failure.flags = 0;
8082 
8083 	if (insn_size) {
8084 		BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
8085 			      sizeof(run->emulation_failure.insn_bytes) != 16));
8086 		info_start += 2;
8087 		run->emulation_failure.flags |=
8088 			KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
8089 		run->emulation_failure.insn_size = insn_size;
8090 		memset(run->emulation_failure.insn_bytes, 0x90,
8091 		       sizeof(run->emulation_failure.insn_bytes));
8092 		memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
8093 	}
8094 
8095 	memcpy(&run->internal.data[info_start], info, sizeof(info));
8096 	memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
8097 	       ndata * sizeof(data[0]));
8098 
8099 	run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
8100 }
8101 
prepare_emulation_ctxt_failure_exit(struct kvm_vcpu * vcpu)8102 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
8103 {
8104 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8105 
8106 	prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
8107 				       ctxt->fetch.end - ctxt->fetch.data);
8108 }
8109 
__kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata)8110 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8111 					  u8 ndata)
8112 {
8113 	prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
8114 }
8115 EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
8116 
kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu)8117 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
8118 {
8119 	__kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
8120 }
8121 EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
8122 
handle_emulation_failure(struct kvm_vcpu * vcpu,int emulation_type)8123 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
8124 {
8125 	struct kvm *kvm = vcpu->kvm;
8126 
8127 	++vcpu->stat.insn_emulation_fail;
8128 	trace_kvm_emulate_insn_failed(vcpu);
8129 
8130 	if (emulation_type & EMULTYPE_VMWARE_GP) {
8131 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8132 		return 1;
8133 	}
8134 
8135 	if (kvm->arch.exit_on_emulation_error ||
8136 	    (emulation_type & EMULTYPE_SKIP)) {
8137 		prepare_emulation_ctxt_failure_exit(vcpu);
8138 		return 0;
8139 	}
8140 
8141 	kvm_queue_exception(vcpu, UD_VECTOR);
8142 
8143 	if (!is_guest_mode(vcpu) && static_call(kvm_x86_get_cpl)(vcpu) == 0) {
8144 		prepare_emulation_ctxt_failure_exit(vcpu);
8145 		return 0;
8146 	}
8147 
8148 	return 1;
8149 }
8150 
reexecute_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,bool write_fault_to_shadow_pgtable,int emulation_type)8151 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
8152 				  bool write_fault_to_shadow_pgtable,
8153 				  int emulation_type)
8154 {
8155 	gpa_t gpa = cr2_or_gpa;
8156 	kvm_pfn_t pfn;
8157 
8158 	if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8159 		return false;
8160 
8161 	if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8162 	    WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
8163 		return false;
8164 
8165 	if (!vcpu->arch.mmu->root_role.direct) {
8166 		/*
8167 		 * Write permission should be allowed since only
8168 		 * write access need to be emulated.
8169 		 */
8170 		gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
8171 
8172 		/*
8173 		 * If the mapping is invalid in guest, let cpu retry
8174 		 * it to generate fault.
8175 		 */
8176 		if (gpa == UNMAPPED_GVA)
8177 			return true;
8178 	}
8179 
8180 	/*
8181 	 * Do not retry the unhandleable instruction if it faults on the
8182 	 * readonly host memory, otherwise it will goto a infinite loop:
8183 	 * retry instruction -> write #PF -> emulation fail -> retry
8184 	 * instruction -> ...
8185 	 */
8186 	pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
8187 
8188 	/*
8189 	 * If the instruction failed on the error pfn, it can not be fixed,
8190 	 * report the error to userspace.
8191 	 */
8192 	if (is_error_noslot_pfn(pfn))
8193 		return false;
8194 
8195 	kvm_release_pfn_clean(pfn);
8196 
8197 	/* The instructions are well-emulated on direct mmu. */
8198 	if (vcpu->arch.mmu->root_role.direct) {
8199 		unsigned int indirect_shadow_pages;
8200 
8201 		write_lock(&vcpu->kvm->mmu_lock);
8202 		indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
8203 		write_unlock(&vcpu->kvm->mmu_lock);
8204 
8205 		if (indirect_shadow_pages)
8206 			kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8207 
8208 		return true;
8209 	}
8210 
8211 	/*
8212 	 * if emulation was due to access to shadowed page table
8213 	 * and it failed try to unshadow page and re-enter the
8214 	 * guest to let CPU execute the instruction.
8215 	 */
8216 	kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8217 
8218 	/*
8219 	 * If the access faults on its page table, it can not
8220 	 * be fixed by unprotecting shadow page and it should
8221 	 * be reported to userspace.
8222 	 */
8223 	return !write_fault_to_shadow_pgtable;
8224 }
8225 
retry_instruction(struct x86_emulate_ctxt * ctxt,gpa_t cr2_or_gpa,int emulation_type)8226 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
8227 			      gpa_t cr2_or_gpa,  int emulation_type)
8228 {
8229 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8230 	unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
8231 
8232 	last_retry_eip = vcpu->arch.last_retry_eip;
8233 	last_retry_addr = vcpu->arch.last_retry_addr;
8234 
8235 	/*
8236 	 * If the emulation is caused by #PF and it is non-page_table
8237 	 * writing instruction, it means the VM-EXIT is caused by shadow
8238 	 * page protected, we can zap the shadow page and retry this
8239 	 * instruction directly.
8240 	 *
8241 	 * Note: if the guest uses a non-page-table modifying instruction
8242 	 * on the PDE that points to the instruction, then we will unmap
8243 	 * the instruction and go to an infinite loop. So, we cache the
8244 	 * last retried eip and the last fault address, if we meet the eip
8245 	 * and the address again, we can break out of the potential infinite
8246 	 * loop.
8247 	 */
8248 	vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
8249 
8250 	if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8251 		return false;
8252 
8253 	if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8254 	    WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
8255 		return false;
8256 
8257 	if (x86_page_table_writing_insn(ctxt))
8258 		return false;
8259 
8260 	if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
8261 		return false;
8262 
8263 	vcpu->arch.last_retry_eip = ctxt->eip;
8264 	vcpu->arch.last_retry_addr = cr2_or_gpa;
8265 
8266 	if (!vcpu->arch.mmu->root_role.direct)
8267 		gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
8268 
8269 	kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8270 
8271 	return true;
8272 }
8273 
8274 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8275 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8276 
kvm_smm_changed(struct kvm_vcpu * vcpu,bool entering_smm)8277 static void kvm_smm_changed(struct kvm_vcpu *vcpu, bool entering_smm)
8278 {
8279 	trace_kvm_smm_transition(vcpu->vcpu_id, vcpu->arch.smbase, entering_smm);
8280 
8281 	if (entering_smm) {
8282 		vcpu->arch.hflags |= HF_SMM_MASK;
8283 	} else {
8284 		vcpu->arch.hflags &= ~(HF_SMM_MASK | HF_SMM_INSIDE_NMI_MASK);
8285 
8286 		/* Process a latched INIT or SMI, if any.  */
8287 		kvm_make_request(KVM_REQ_EVENT, vcpu);
8288 
8289 		/*
8290 		 * Even if KVM_SET_SREGS2 loaded PDPTRs out of band,
8291 		 * on SMM exit we still need to reload them from
8292 		 * guest memory
8293 		 */
8294 		vcpu->arch.pdptrs_from_userspace = false;
8295 	}
8296 
8297 	kvm_mmu_reset_context(vcpu);
8298 }
8299 
kvm_vcpu_check_hw_bp(unsigned long addr,u32 type,u32 dr7,unsigned long * db)8300 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8301 				unsigned long *db)
8302 {
8303 	u32 dr6 = 0;
8304 	int i;
8305 	u32 enable, rwlen;
8306 
8307 	enable = dr7;
8308 	rwlen = dr7 >> 16;
8309 	for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8310 		if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8311 			dr6 |= (1 << i);
8312 	return dr6;
8313 }
8314 
kvm_vcpu_do_singlestep(struct kvm_vcpu * vcpu)8315 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
8316 {
8317 	struct kvm_run *kvm_run = vcpu->run;
8318 
8319 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
8320 		kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
8321 		kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
8322 		kvm_run->debug.arch.exception = DB_VECTOR;
8323 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
8324 		return 0;
8325 	}
8326 	kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
8327 	return 1;
8328 }
8329 
kvm_skip_emulated_instruction(struct kvm_vcpu * vcpu)8330 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8331 {
8332 	unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
8333 	int r;
8334 
8335 	r = static_call(kvm_x86_skip_emulated_instruction)(vcpu);
8336 	if (unlikely(!r))
8337 		return 0;
8338 
8339 	kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
8340 
8341 	/*
8342 	 * rflags is the old, "raw" value of the flags.  The new value has
8343 	 * not been saved yet.
8344 	 *
8345 	 * This is correct even for TF set by the guest, because "the
8346 	 * processor will not generate this exception after the instruction
8347 	 * that sets the TF flag".
8348 	 */
8349 	if (unlikely(rflags & X86_EFLAGS_TF))
8350 		r = kvm_vcpu_do_singlestep(vcpu);
8351 	return r;
8352 }
8353 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
8354 
kvm_vcpu_check_code_breakpoint(struct kvm_vcpu * vcpu,int * r)8355 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu, int *r)
8356 {
8357 	if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
8358 	    (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
8359 		struct kvm_run *kvm_run = vcpu->run;
8360 		unsigned long eip = kvm_get_linear_rip(vcpu);
8361 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
8362 					   vcpu->arch.guest_debug_dr7,
8363 					   vcpu->arch.eff_db);
8364 
8365 		if (dr6 != 0) {
8366 			kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
8367 			kvm_run->debug.arch.pc = eip;
8368 			kvm_run->debug.arch.exception = DB_VECTOR;
8369 			kvm_run->exit_reason = KVM_EXIT_DEBUG;
8370 			*r = 0;
8371 			return true;
8372 		}
8373 	}
8374 
8375 	if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
8376 	    !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
8377 		unsigned long eip = kvm_get_linear_rip(vcpu);
8378 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
8379 					   vcpu->arch.dr7,
8380 					   vcpu->arch.db);
8381 
8382 		if (dr6 != 0) {
8383 			kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
8384 			*r = 1;
8385 			return true;
8386 		}
8387 	}
8388 
8389 	return false;
8390 }
8391 
is_vmware_backdoor_opcode(struct x86_emulate_ctxt * ctxt)8392 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
8393 {
8394 	switch (ctxt->opcode_len) {
8395 	case 1:
8396 		switch (ctxt->b) {
8397 		case 0xe4:	/* IN */
8398 		case 0xe5:
8399 		case 0xec:
8400 		case 0xed:
8401 		case 0xe6:	/* OUT */
8402 		case 0xe7:
8403 		case 0xee:
8404 		case 0xef:
8405 		case 0x6c:	/* INS */
8406 		case 0x6d:
8407 		case 0x6e:	/* OUTS */
8408 		case 0x6f:
8409 			return true;
8410 		}
8411 		break;
8412 	case 2:
8413 		switch (ctxt->b) {
8414 		case 0x33:	/* RDPMC */
8415 			return true;
8416 		}
8417 		break;
8418 	}
8419 
8420 	return false;
8421 }
8422 
8423 /*
8424  * Decode an instruction for emulation.  The caller is responsible for handling
8425  * code breakpoints.  Note, manually detecting code breakpoints is unnecessary
8426  * (and wrong) when emulating on an intercepted fault-like exception[*], as
8427  * code breakpoints have higher priority and thus have already been done by
8428  * hardware.
8429  *
8430  * [*] Except #MC, which is higher priority, but KVM should never emulate in
8431  *     response to a machine check.
8432  */
x86_decode_emulated_instruction(struct kvm_vcpu * vcpu,int emulation_type,void * insn,int insn_len)8433 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
8434 				    void *insn, int insn_len)
8435 {
8436 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8437 	int r;
8438 
8439 	init_emulate_ctxt(vcpu);
8440 
8441 	r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
8442 
8443 	trace_kvm_emulate_insn_start(vcpu);
8444 	++vcpu->stat.insn_emulation;
8445 
8446 	return r;
8447 }
8448 EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
8449 
x86_emulate_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type,void * insn,int insn_len)8450 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
8451 			    int emulation_type, void *insn, int insn_len)
8452 {
8453 	int r;
8454 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8455 	bool writeback = true;
8456 	bool write_fault_to_spt;
8457 
8458 	if (unlikely(!kvm_can_emulate_insn(vcpu, emulation_type, insn, insn_len)))
8459 		return 1;
8460 
8461 	vcpu->arch.l1tf_flush_l1d = true;
8462 
8463 	/*
8464 	 * Clear write_fault_to_shadow_pgtable here to ensure it is
8465 	 * never reused.
8466 	 */
8467 	write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
8468 	vcpu->arch.write_fault_to_shadow_pgtable = false;
8469 
8470 	if (!(emulation_type & EMULTYPE_NO_DECODE)) {
8471 		kvm_clear_exception_queue(vcpu);
8472 
8473 		/*
8474 		 * Return immediately if RIP hits a code breakpoint, such #DBs
8475 		 * are fault-like and are higher priority than any faults on
8476 		 * the code fetch itself.
8477 		 */
8478 		if (!(emulation_type & EMULTYPE_SKIP) &&
8479 		    kvm_vcpu_check_code_breakpoint(vcpu, &r))
8480 			return r;
8481 
8482 		r = x86_decode_emulated_instruction(vcpu, emulation_type,
8483 						    insn, insn_len);
8484 		if (r != EMULATION_OK)  {
8485 			if ((emulation_type & EMULTYPE_TRAP_UD) ||
8486 			    (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
8487 				kvm_queue_exception(vcpu, UD_VECTOR);
8488 				return 1;
8489 			}
8490 			if (reexecute_instruction(vcpu, cr2_or_gpa,
8491 						  write_fault_to_spt,
8492 						  emulation_type))
8493 				return 1;
8494 			if (ctxt->have_exception) {
8495 				/*
8496 				 * #UD should result in just EMULATION_FAILED, and trap-like
8497 				 * exception should not be encountered during decode.
8498 				 */
8499 				WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
8500 					     exception_type(ctxt->exception.vector) == EXCPT_TRAP);
8501 				inject_emulated_exception(vcpu);
8502 				return 1;
8503 			}
8504 			return handle_emulation_failure(vcpu, emulation_type);
8505 		}
8506 	}
8507 
8508 	if ((emulation_type & EMULTYPE_VMWARE_GP) &&
8509 	    !is_vmware_backdoor_opcode(ctxt)) {
8510 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8511 		return 1;
8512 	}
8513 
8514 	/*
8515 	 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
8516 	 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
8517 	 * The caller is responsible for updating interruptibility state and
8518 	 * injecting single-step #DBs.
8519 	 */
8520 	if (emulation_type & EMULTYPE_SKIP) {
8521 		if (ctxt->mode != X86EMUL_MODE_PROT64)
8522 			ctxt->eip = (u32)ctxt->_eip;
8523 		else
8524 			ctxt->eip = ctxt->_eip;
8525 
8526 		if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
8527 			r = 1;
8528 			goto writeback;
8529 		}
8530 
8531 		kvm_rip_write(vcpu, ctxt->eip);
8532 		if (ctxt->eflags & X86_EFLAGS_RF)
8533 			kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
8534 		return 1;
8535 	}
8536 
8537 	if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
8538 		return 1;
8539 
8540 	/* this is needed for vmware backdoor interface to work since it
8541 	   changes registers values  during IO operation */
8542 	if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
8543 		vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8544 		emulator_invalidate_register_cache(ctxt);
8545 	}
8546 
8547 restart:
8548 	if (emulation_type & EMULTYPE_PF) {
8549 		/* Save the faulting GPA (cr2) in the address field */
8550 		ctxt->exception.address = cr2_or_gpa;
8551 
8552 		/* With shadow page tables, cr2 contains a GVA or nGPA. */
8553 		if (vcpu->arch.mmu->root_role.direct) {
8554 			ctxt->gpa_available = true;
8555 			ctxt->gpa_val = cr2_or_gpa;
8556 		}
8557 	} else {
8558 		/* Sanitize the address out of an abundance of paranoia. */
8559 		ctxt->exception.address = 0;
8560 	}
8561 
8562 	r = x86_emulate_insn(ctxt);
8563 
8564 	if (r == EMULATION_INTERCEPTED)
8565 		return 1;
8566 
8567 	if (r == EMULATION_FAILED) {
8568 		if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
8569 					emulation_type))
8570 			return 1;
8571 
8572 		return handle_emulation_failure(vcpu, emulation_type);
8573 	}
8574 
8575 	if (ctxt->have_exception) {
8576 		r = 1;
8577 		if (inject_emulated_exception(vcpu))
8578 			return r;
8579 	} else if (vcpu->arch.pio.count) {
8580 		if (!vcpu->arch.pio.in) {
8581 			/* FIXME: return into emulator if single-stepping.  */
8582 			vcpu->arch.pio.count = 0;
8583 		} else {
8584 			writeback = false;
8585 			vcpu->arch.complete_userspace_io = complete_emulated_pio;
8586 		}
8587 		r = 0;
8588 	} else if (vcpu->mmio_needed) {
8589 		++vcpu->stat.mmio_exits;
8590 
8591 		if (!vcpu->mmio_is_write)
8592 			writeback = false;
8593 		r = 0;
8594 		vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8595 	} else if (vcpu->arch.complete_userspace_io) {
8596 		writeback = false;
8597 		r = 0;
8598 	} else if (r == EMULATION_RESTART)
8599 		goto restart;
8600 	else
8601 		r = 1;
8602 
8603 writeback:
8604 	if (writeback) {
8605 		unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
8606 		toggle_interruptibility(vcpu, ctxt->interruptibility);
8607 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8608 		if (!ctxt->have_exception ||
8609 		    exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
8610 			kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
8611 			if (ctxt->is_branch)
8612 				kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
8613 			kvm_rip_write(vcpu, ctxt->eip);
8614 			if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
8615 				r = kvm_vcpu_do_singlestep(vcpu);
8616 			static_call_cond(kvm_x86_update_emulated_instruction)(vcpu);
8617 			__kvm_set_rflags(vcpu, ctxt->eflags);
8618 		}
8619 
8620 		/*
8621 		 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
8622 		 * do nothing, and it will be requested again as soon as
8623 		 * the shadow expires.  But we still need to check here,
8624 		 * because POPF has no interrupt shadow.
8625 		 */
8626 		if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
8627 			kvm_make_request(KVM_REQ_EVENT, vcpu);
8628 	} else
8629 		vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
8630 
8631 	return r;
8632 }
8633 
kvm_emulate_instruction(struct kvm_vcpu * vcpu,int emulation_type)8634 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
8635 {
8636 	return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
8637 }
8638 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
8639 
kvm_emulate_instruction_from_buffer(struct kvm_vcpu * vcpu,void * insn,int insn_len)8640 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
8641 					void *insn, int insn_len)
8642 {
8643 	return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
8644 }
8645 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
8646 
complete_fast_pio_out_port_0x7e(struct kvm_vcpu * vcpu)8647 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
8648 {
8649 	vcpu->arch.pio.count = 0;
8650 	return 1;
8651 }
8652 
complete_fast_pio_out(struct kvm_vcpu * vcpu)8653 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
8654 {
8655 	vcpu->arch.pio.count = 0;
8656 
8657 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
8658 		return 1;
8659 
8660 	return kvm_skip_emulated_instruction(vcpu);
8661 }
8662 
kvm_fast_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port)8663 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
8664 			    unsigned short port)
8665 {
8666 	unsigned long val = kvm_rax_read(vcpu);
8667 	int ret = emulator_pio_out(vcpu, size, port, &val, 1);
8668 
8669 	if (ret)
8670 		return ret;
8671 
8672 	/*
8673 	 * Workaround userspace that relies on old KVM behavior of %rip being
8674 	 * incremented prior to exiting to userspace to handle "OUT 0x7e".
8675 	 */
8676 	if (port == 0x7e &&
8677 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
8678 		vcpu->arch.complete_userspace_io =
8679 			complete_fast_pio_out_port_0x7e;
8680 		kvm_skip_emulated_instruction(vcpu);
8681 	} else {
8682 		vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
8683 		vcpu->arch.complete_userspace_io = complete_fast_pio_out;
8684 	}
8685 	return 0;
8686 }
8687 
complete_fast_pio_in(struct kvm_vcpu * vcpu)8688 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
8689 {
8690 	unsigned long val;
8691 
8692 	/* We should only ever be called with arch.pio.count equal to 1 */
8693 	BUG_ON(vcpu->arch.pio.count != 1);
8694 
8695 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
8696 		vcpu->arch.pio.count = 0;
8697 		return 1;
8698 	}
8699 
8700 	/* For size less than 4 we merge, else we zero extend */
8701 	val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
8702 
8703 	/*
8704 	 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
8705 	 * the copy and tracing
8706 	 */
8707 	emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
8708 	kvm_rax_write(vcpu, val);
8709 
8710 	return kvm_skip_emulated_instruction(vcpu);
8711 }
8712 
kvm_fast_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port)8713 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
8714 			   unsigned short port)
8715 {
8716 	unsigned long val;
8717 	int ret;
8718 
8719 	/* For size less than 4 we merge, else we zero extend */
8720 	val = (size < 4) ? kvm_rax_read(vcpu) : 0;
8721 
8722 	ret = emulator_pio_in(vcpu, size, port, &val, 1);
8723 	if (ret) {
8724 		kvm_rax_write(vcpu, val);
8725 		return ret;
8726 	}
8727 
8728 	vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
8729 	vcpu->arch.complete_userspace_io = complete_fast_pio_in;
8730 
8731 	return 0;
8732 }
8733 
kvm_fast_pio(struct kvm_vcpu * vcpu,int size,unsigned short port,int in)8734 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
8735 {
8736 	int ret;
8737 
8738 	if (in)
8739 		ret = kvm_fast_pio_in(vcpu, size, port);
8740 	else
8741 		ret = kvm_fast_pio_out(vcpu, size, port);
8742 	return ret && kvm_skip_emulated_instruction(vcpu);
8743 }
8744 EXPORT_SYMBOL_GPL(kvm_fast_pio);
8745 
kvmclock_cpu_down_prep(unsigned int cpu)8746 static int kvmclock_cpu_down_prep(unsigned int cpu)
8747 {
8748 	__this_cpu_write(cpu_tsc_khz, 0);
8749 	return 0;
8750 }
8751 
tsc_khz_changed(void * data)8752 static void tsc_khz_changed(void *data)
8753 {
8754 	struct cpufreq_freqs *freq = data;
8755 	unsigned long khz = 0;
8756 
8757 	if (data)
8758 		khz = freq->new;
8759 	else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
8760 		khz = cpufreq_quick_get(raw_smp_processor_id());
8761 	if (!khz)
8762 		khz = tsc_khz;
8763 	__this_cpu_write(cpu_tsc_khz, khz);
8764 }
8765 
8766 #ifdef CONFIG_X86_64
kvm_hyperv_tsc_notifier(void)8767 static void kvm_hyperv_tsc_notifier(void)
8768 {
8769 	struct kvm *kvm;
8770 	int cpu;
8771 
8772 	mutex_lock(&kvm_lock);
8773 	list_for_each_entry(kvm, &vm_list, vm_list)
8774 		kvm_make_mclock_inprogress_request(kvm);
8775 
8776 	/* no guest entries from this point */
8777 	hyperv_stop_tsc_emulation();
8778 
8779 	/* TSC frequency always matches when on Hyper-V */
8780 	for_each_present_cpu(cpu)
8781 		per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
8782 	kvm_max_guest_tsc_khz = tsc_khz;
8783 
8784 	list_for_each_entry(kvm, &vm_list, vm_list) {
8785 		__kvm_start_pvclock_update(kvm);
8786 		pvclock_update_vm_gtod_copy(kvm);
8787 		kvm_end_pvclock_update(kvm);
8788 	}
8789 
8790 	mutex_unlock(&kvm_lock);
8791 }
8792 #endif
8793 
__kvmclock_cpufreq_notifier(struct cpufreq_freqs * freq,int cpu)8794 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
8795 {
8796 	struct kvm *kvm;
8797 	struct kvm_vcpu *vcpu;
8798 	int send_ipi = 0;
8799 	unsigned long i;
8800 
8801 	/*
8802 	 * We allow guests to temporarily run on slowing clocks,
8803 	 * provided we notify them after, or to run on accelerating
8804 	 * clocks, provided we notify them before.  Thus time never
8805 	 * goes backwards.
8806 	 *
8807 	 * However, we have a problem.  We can't atomically update
8808 	 * the frequency of a given CPU from this function; it is
8809 	 * merely a notifier, which can be called from any CPU.
8810 	 * Changing the TSC frequency at arbitrary points in time
8811 	 * requires a recomputation of local variables related to
8812 	 * the TSC for each VCPU.  We must flag these local variables
8813 	 * to be updated and be sure the update takes place with the
8814 	 * new frequency before any guests proceed.
8815 	 *
8816 	 * Unfortunately, the combination of hotplug CPU and frequency
8817 	 * change creates an intractable locking scenario; the order
8818 	 * of when these callouts happen is undefined with respect to
8819 	 * CPU hotplug, and they can race with each other.  As such,
8820 	 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
8821 	 * undefined; you can actually have a CPU frequency change take
8822 	 * place in between the computation of X and the setting of the
8823 	 * variable.  To protect against this problem, all updates of
8824 	 * the per_cpu tsc_khz variable are done in an interrupt
8825 	 * protected IPI, and all callers wishing to update the value
8826 	 * must wait for a synchronous IPI to complete (which is trivial
8827 	 * if the caller is on the CPU already).  This establishes the
8828 	 * necessary total order on variable updates.
8829 	 *
8830 	 * Note that because a guest time update may take place
8831 	 * anytime after the setting of the VCPU's request bit, the
8832 	 * correct TSC value must be set before the request.  However,
8833 	 * to ensure the update actually makes it to any guest which
8834 	 * starts running in hardware virtualization between the set
8835 	 * and the acquisition of the spinlock, we must also ping the
8836 	 * CPU after setting the request bit.
8837 	 *
8838 	 */
8839 
8840 	smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
8841 
8842 	mutex_lock(&kvm_lock);
8843 	list_for_each_entry(kvm, &vm_list, vm_list) {
8844 		kvm_for_each_vcpu(i, vcpu, kvm) {
8845 			if (vcpu->cpu != cpu)
8846 				continue;
8847 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8848 			if (vcpu->cpu != raw_smp_processor_id())
8849 				send_ipi = 1;
8850 		}
8851 	}
8852 	mutex_unlock(&kvm_lock);
8853 
8854 	if (freq->old < freq->new && send_ipi) {
8855 		/*
8856 		 * We upscale the frequency.  Must make the guest
8857 		 * doesn't see old kvmclock values while running with
8858 		 * the new frequency, otherwise we risk the guest sees
8859 		 * time go backwards.
8860 		 *
8861 		 * In case we update the frequency for another cpu
8862 		 * (which might be in guest context) send an interrupt
8863 		 * to kick the cpu out of guest context.  Next time
8864 		 * guest context is entered kvmclock will be updated,
8865 		 * so the guest will not see stale values.
8866 		 */
8867 		smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
8868 	}
8869 }
8870 
kvmclock_cpufreq_notifier(struct notifier_block * nb,unsigned long val,void * data)8871 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
8872 				     void *data)
8873 {
8874 	struct cpufreq_freqs *freq = data;
8875 	int cpu;
8876 
8877 	if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
8878 		return 0;
8879 	if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
8880 		return 0;
8881 
8882 	for_each_cpu(cpu, freq->policy->cpus)
8883 		__kvmclock_cpufreq_notifier(freq, cpu);
8884 
8885 	return 0;
8886 }
8887 
8888 static struct notifier_block kvmclock_cpufreq_notifier_block = {
8889 	.notifier_call  = kvmclock_cpufreq_notifier
8890 };
8891 
kvmclock_cpu_online(unsigned int cpu)8892 static int kvmclock_cpu_online(unsigned int cpu)
8893 {
8894 	tsc_khz_changed(NULL);
8895 	return 0;
8896 }
8897 
kvm_timer_init(void)8898 static void kvm_timer_init(void)
8899 {
8900 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
8901 		max_tsc_khz = tsc_khz;
8902 
8903 		if (IS_ENABLED(CONFIG_CPU_FREQ)) {
8904 			struct cpufreq_policy *policy;
8905 			int cpu;
8906 
8907 			cpu = get_cpu();
8908 			policy = cpufreq_cpu_get(cpu);
8909 			if (policy) {
8910 				if (policy->cpuinfo.max_freq)
8911 					max_tsc_khz = policy->cpuinfo.max_freq;
8912 				cpufreq_cpu_put(policy);
8913 			}
8914 			put_cpu();
8915 		}
8916 		cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
8917 					  CPUFREQ_TRANSITION_NOTIFIER);
8918 	}
8919 
8920 	cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
8921 			  kvmclock_cpu_online, kvmclock_cpu_down_prep);
8922 }
8923 
8924 #ifdef CONFIG_X86_64
pvclock_gtod_update_fn(struct work_struct * work)8925 static void pvclock_gtod_update_fn(struct work_struct *work)
8926 {
8927 	struct kvm *kvm;
8928 	struct kvm_vcpu *vcpu;
8929 	unsigned long i;
8930 
8931 	mutex_lock(&kvm_lock);
8932 	list_for_each_entry(kvm, &vm_list, vm_list)
8933 		kvm_for_each_vcpu(i, vcpu, kvm)
8934 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
8935 	atomic_set(&kvm_guest_has_master_clock, 0);
8936 	mutex_unlock(&kvm_lock);
8937 }
8938 
8939 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
8940 
8941 /*
8942  * Indirection to move queue_work() out of the tk_core.seq write held
8943  * region to prevent possible deadlocks against time accessors which
8944  * are invoked with work related locks held.
8945  */
pvclock_irq_work_fn(struct irq_work * w)8946 static void pvclock_irq_work_fn(struct irq_work *w)
8947 {
8948 	queue_work(system_long_wq, &pvclock_gtod_work);
8949 }
8950 
8951 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
8952 
8953 /*
8954  * Notification about pvclock gtod data update.
8955  */
pvclock_gtod_notify(struct notifier_block * nb,unsigned long unused,void * priv)8956 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
8957 			       void *priv)
8958 {
8959 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
8960 	struct timekeeper *tk = priv;
8961 
8962 	update_pvclock_gtod(tk);
8963 
8964 	/*
8965 	 * Disable master clock if host does not trust, or does not use,
8966 	 * TSC based clocksource. Delegate queue_work() to irq_work as
8967 	 * this is invoked with tk_core.seq write held.
8968 	 */
8969 	if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
8970 	    atomic_read(&kvm_guest_has_master_clock) != 0)
8971 		irq_work_queue(&pvclock_irq_work);
8972 	return 0;
8973 }
8974 
8975 static struct notifier_block pvclock_gtod_notifier = {
8976 	.notifier_call = pvclock_gtod_notify,
8977 };
8978 #endif
8979 
kvm_arch_init(void * opaque)8980 int kvm_arch_init(void *opaque)
8981 {
8982 	struct kvm_x86_init_ops *ops = opaque;
8983 	int r;
8984 
8985 	if (kvm_x86_ops.hardware_enable) {
8986 		pr_err("kvm: already loaded vendor module '%s'\n", kvm_x86_ops.name);
8987 		r = -EEXIST;
8988 		goto out;
8989 	}
8990 
8991 	if (!ops->cpu_has_kvm_support()) {
8992 		pr_err_ratelimited("kvm: no hardware support for '%s'\n",
8993 				   ops->runtime_ops->name);
8994 		r = -EOPNOTSUPP;
8995 		goto out;
8996 	}
8997 	if (ops->disabled_by_bios()) {
8998 		pr_err_ratelimited("kvm: support for '%s' disabled by bios\n",
8999 				   ops->runtime_ops->name);
9000 		r = -EOPNOTSUPP;
9001 		goto out;
9002 	}
9003 
9004 	/*
9005 	 * KVM explicitly assumes that the guest has an FPU and
9006 	 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9007 	 * vCPU's FPU state as a fxregs_state struct.
9008 	 */
9009 	if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9010 		printk(KERN_ERR "kvm: inadequate fpu\n");
9011 		r = -EOPNOTSUPP;
9012 		goto out;
9013 	}
9014 
9015 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9016 		pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
9017 		r = -EOPNOTSUPP;
9018 		goto out;
9019 	}
9020 
9021 	r = -ENOMEM;
9022 
9023 	x86_emulator_cache = kvm_alloc_emulator_cache();
9024 	if (!x86_emulator_cache) {
9025 		pr_err("kvm: failed to allocate cache for x86 emulator\n");
9026 		goto out;
9027 	}
9028 
9029 	user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
9030 	if (!user_return_msrs) {
9031 		printk(KERN_ERR "kvm: failed to allocate percpu kvm_user_return_msrs\n");
9032 		goto out_free_x86_emulator_cache;
9033 	}
9034 	kvm_nr_uret_msrs = 0;
9035 
9036 	r = kvm_mmu_vendor_module_init();
9037 	if (r)
9038 		goto out_free_percpu;
9039 
9040 	kvm_timer_init();
9041 
9042 	if (boot_cpu_has(X86_FEATURE_XSAVE)) {
9043 		host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
9044 		supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
9045 	}
9046 
9047 	if (pi_inject_timer == -1)
9048 		pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
9049 #ifdef CONFIG_X86_64
9050 	pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
9051 
9052 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9053 		set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
9054 #endif
9055 
9056 	return 0;
9057 
9058 out_free_percpu:
9059 	free_percpu(user_return_msrs);
9060 out_free_x86_emulator_cache:
9061 	kmem_cache_destroy(x86_emulator_cache);
9062 out:
9063 	return r;
9064 }
9065 
kvm_arch_exit(void)9066 void kvm_arch_exit(void)
9067 {
9068 #ifdef CONFIG_X86_64
9069 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9070 		clear_hv_tscchange_cb();
9071 #endif
9072 	kvm_lapic_exit();
9073 
9074 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
9075 		cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
9076 					    CPUFREQ_TRANSITION_NOTIFIER);
9077 	cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
9078 #ifdef CONFIG_X86_64
9079 	pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
9080 	irq_work_sync(&pvclock_irq_work);
9081 	cancel_work_sync(&pvclock_gtod_work);
9082 #endif
9083 	kvm_x86_ops.hardware_enable = NULL;
9084 	kvm_mmu_vendor_module_exit();
9085 	free_percpu(user_return_msrs);
9086 	kmem_cache_destroy(x86_emulator_cache);
9087 #ifdef CONFIG_KVM_XEN
9088 	static_key_deferred_flush(&kvm_xen_enabled);
9089 	WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
9090 #endif
9091 }
9092 
__kvm_emulate_halt(struct kvm_vcpu * vcpu,int state,int reason)9093 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
9094 {
9095 	/*
9096 	 * The vCPU has halted, e.g. executed HLT.  Update the run state if the
9097 	 * local APIC is in-kernel, the run loop will detect the non-runnable
9098 	 * state and halt the vCPU.  Exit to userspace if the local APIC is
9099 	 * managed by userspace, in which case userspace is responsible for
9100 	 * handling wake events.
9101 	 */
9102 	++vcpu->stat.halt_exits;
9103 	if (lapic_in_kernel(vcpu)) {
9104 		vcpu->arch.mp_state = state;
9105 		return 1;
9106 	} else {
9107 		vcpu->run->exit_reason = reason;
9108 		return 0;
9109 	}
9110 }
9111 
kvm_emulate_halt_noskip(struct kvm_vcpu * vcpu)9112 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
9113 {
9114 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
9115 }
9116 EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
9117 
kvm_emulate_halt(struct kvm_vcpu * vcpu)9118 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
9119 {
9120 	int ret = kvm_skip_emulated_instruction(vcpu);
9121 	/*
9122 	 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
9123 	 * KVM_EXIT_DEBUG here.
9124 	 */
9125 	return kvm_emulate_halt_noskip(vcpu) && ret;
9126 }
9127 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
9128 
kvm_emulate_ap_reset_hold(struct kvm_vcpu * vcpu)9129 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
9130 {
9131 	int ret = kvm_skip_emulated_instruction(vcpu);
9132 
9133 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
9134 					KVM_EXIT_AP_RESET_HOLD) && ret;
9135 }
9136 EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
9137 
9138 #ifdef CONFIG_X86_64
kvm_pv_clock_pairing(struct kvm_vcpu * vcpu,gpa_t paddr,unsigned long clock_type)9139 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
9140 			        unsigned long clock_type)
9141 {
9142 	struct kvm_clock_pairing clock_pairing;
9143 	struct timespec64 ts;
9144 	u64 cycle;
9145 	int ret;
9146 
9147 	if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
9148 		return -KVM_EOPNOTSUPP;
9149 
9150 	/*
9151 	 * When tsc is in permanent catchup mode guests won't be able to use
9152 	 * pvclock_read_retry loop to get consistent view of pvclock
9153 	 */
9154 	if (vcpu->arch.tsc_always_catchup)
9155 		return -KVM_EOPNOTSUPP;
9156 
9157 	if (!kvm_get_walltime_and_clockread(&ts, &cycle))
9158 		return -KVM_EOPNOTSUPP;
9159 
9160 	clock_pairing.sec = ts.tv_sec;
9161 	clock_pairing.nsec = ts.tv_nsec;
9162 	clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
9163 	clock_pairing.flags = 0;
9164 	memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
9165 
9166 	ret = 0;
9167 	if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
9168 			    sizeof(struct kvm_clock_pairing)))
9169 		ret = -KVM_EFAULT;
9170 
9171 	return ret;
9172 }
9173 #endif
9174 
9175 /*
9176  * kvm_pv_kick_cpu_op:  Kick a vcpu.
9177  *
9178  * @apicid - apicid of vcpu to be kicked.
9179  */
kvm_pv_kick_cpu_op(struct kvm * kvm,int apicid)9180 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
9181 {
9182 	/*
9183 	 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
9184 	 * common code, e.g. for tracing. Defer initialization to the compiler.
9185 	 */
9186 	struct kvm_lapic_irq lapic_irq = {
9187 		.delivery_mode = APIC_DM_REMRD,
9188 		.dest_mode = APIC_DEST_PHYSICAL,
9189 		.shorthand = APIC_DEST_NOSHORT,
9190 		.dest_id = apicid,
9191 	};
9192 
9193 	kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
9194 }
9195 
kvm_apicv_activated(struct kvm * kvm)9196 bool kvm_apicv_activated(struct kvm *kvm)
9197 {
9198 	return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
9199 }
9200 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
9201 
kvm_vcpu_apicv_activated(struct kvm_vcpu * vcpu)9202 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
9203 {
9204 	ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
9205 	ulong vcpu_reasons = static_call(kvm_x86_vcpu_get_apicv_inhibit_reasons)(vcpu);
9206 
9207 	return (vm_reasons | vcpu_reasons) == 0;
9208 }
9209 EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
9210 
set_or_clear_apicv_inhibit(unsigned long * inhibits,enum kvm_apicv_inhibit reason,bool set)9211 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
9212 				       enum kvm_apicv_inhibit reason, bool set)
9213 {
9214 	if (set)
9215 		__set_bit(reason, inhibits);
9216 	else
9217 		__clear_bit(reason, inhibits);
9218 
9219 	trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
9220 }
9221 
kvm_apicv_init(struct kvm * kvm)9222 static void kvm_apicv_init(struct kvm *kvm)
9223 {
9224 	unsigned long *inhibits = &kvm->arch.apicv_inhibit_reasons;
9225 
9226 	init_rwsem(&kvm->arch.apicv_update_lock);
9227 
9228 	set_or_clear_apicv_inhibit(inhibits, APICV_INHIBIT_REASON_ABSENT, true);
9229 
9230 	if (!enable_apicv)
9231 		set_or_clear_apicv_inhibit(inhibits,
9232 					   APICV_INHIBIT_REASON_DISABLE, true);
9233 }
9234 
kvm_sched_yield(struct kvm_vcpu * vcpu,unsigned long dest_id)9235 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
9236 {
9237 	struct kvm_vcpu *target = NULL;
9238 	struct kvm_apic_map *map;
9239 
9240 	vcpu->stat.directed_yield_attempted++;
9241 
9242 	if (single_task_running())
9243 		goto no_yield;
9244 
9245 	rcu_read_lock();
9246 	map = rcu_dereference(vcpu->kvm->arch.apic_map);
9247 
9248 	if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
9249 		target = map->phys_map[dest_id]->vcpu;
9250 
9251 	rcu_read_unlock();
9252 
9253 	if (!target || !READ_ONCE(target->ready))
9254 		goto no_yield;
9255 
9256 	/* Ignore requests to yield to self */
9257 	if (vcpu == target)
9258 		goto no_yield;
9259 
9260 	if (kvm_vcpu_yield_to(target) <= 0)
9261 		goto no_yield;
9262 
9263 	vcpu->stat.directed_yield_successful++;
9264 
9265 no_yield:
9266 	return;
9267 }
9268 
complete_hypercall_exit(struct kvm_vcpu * vcpu)9269 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
9270 {
9271 	u64 ret = vcpu->run->hypercall.ret;
9272 
9273 	if (!is_64_bit_mode(vcpu))
9274 		ret = (u32)ret;
9275 	kvm_rax_write(vcpu, ret);
9276 	++vcpu->stat.hypercalls;
9277 	return kvm_skip_emulated_instruction(vcpu);
9278 }
9279 
kvm_emulate_hypercall(struct kvm_vcpu * vcpu)9280 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
9281 {
9282 	unsigned long nr, a0, a1, a2, a3, ret;
9283 	int op_64_bit;
9284 
9285 	if (kvm_xen_hypercall_enabled(vcpu->kvm))
9286 		return kvm_xen_hypercall(vcpu);
9287 
9288 	if (kvm_hv_hypercall_enabled(vcpu))
9289 		return kvm_hv_hypercall(vcpu);
9290 
9291 	nr = kvm_rax_read(vcpu);
9292 	a0 = kvm_rbx_read(vcpu);
9293 	a1 = kvm_rcx_read(vcpu);
9294 	a2 = kvm_rdx_read(vcpu);
9295 	a3 = kvm_rsi_read(vcpu);
9296 
9297 	trace_kvm_hypercall(nr, a0, a1, a2, a3);
9298 
9299 	op_64_bit = is_64_bit_hypercall(vcpu);
9300 	if (!op_64_bit) {
9301 		nr &= 0xFFFFFFFF;
9302 		a0 &= 0xFFFFFFFF;
9303 		a1 &= 0xFFFFFFFF;
9304 		a2 &= 0xFFFFFFFF;
9305 		a3 &= 0xFFFFFFFF;
9306 	}
9307 
9308 	if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
9309 		ret = -KVM_EPERM;
9310 		goto out;
9311 	}
9312 
9313 	ret = -KVM_ENOSYS;
9314 
9315 	switch (nr) {
9316 	case KVM_HC_VAPIC_POLL_IRQ:
9317 		ret = 0;
9318 		break;
9319 	case KVM_HC_KICK_CPU:
9320 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
9321 			break;
9322 
9323 		kvm_pv_kick_cpu_op(vcpu->kvm, a1);
9324 		kvm_sched_yield(vcpu, a1);
9325 		ret = 0;
9326 		break;
9327 #ifdef CONFIG_X86_64
9328 	case KVM_HC_CLOCK_PAIRING:
9329 		ret = kvm_pv_clock_pairing(vcpu, a0, a1);
9330 		break;
9331 #endif
9332 	case KVM_HC_SEND_IPI:
9333 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
9334 			break;
9335 
9336 		ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
9337 		break;
9338 	case KVM_HC_SCHED_YIELD:
9339 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
9340 			break;
9341 
9342 		kvm_sched_yield(vcpu, a0);
9343 		ret = 0;
9344 		break;
9345 	case KVM_HC_MAP_GPA_RANGE: {
9346 		u64 gpa = a0, npages = a1, attrs = a2;
9347 
9348 		ret = -KVM_ENOSYS;
9349 		if (!(vcpu->kvm->arch.hypercall_exit_enabled & (1 << KVM_HC_MAP_GPA_RANGE)))
9350 			break;
9351 
9352 		if (!PAGE_ALIGNED(gpa) || !npages ||
9353 		    gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
9354 			ret = -KVM_EINVAL;
9355 			break;
9356 		}
9357 
9358 		vcpu->run->exit_reason        = KVM_EXIT_HYPERCALL;
9359 		vcpu->run->hypercall.nr       = KVM_HC_MAP_GPA_RANGE;
9360 		vcpu->run->hypercall.args[0]  = gpa;
9361 		vcpu->run->hypercall.args[1]  = npages;
9362 		vcpu->run->hypercall.args[2]  = attrs;
9363 		vcpu->run->hypercall.longmode = op_64_bit;
9364 		vcpu->arch.complete_userspace_io = complete_hypercall_exit;
9365 		return 0;
9366 	}
9367 	default:
9368 		ret = -KVM_ENOSYS;
9369 		break;
9370 	}
9371 out:
9372 	if (!op_64_bit)
9373 		ret = (u32)ret;
9374 	kvm_rax_write(vcpu, ret);
9375 
9376 	++vcpu->stat.hypercalls;
9377 	return kvm_skip_emulated_instruction(vcpu);
9378 }
9379 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
9380 
emulator_fix_hypercall(struct x86_emulate_ctxt * ctxt)9381 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
9382 {
9383 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
9384 	char instruction[3];
9385 	unsigned long rip = kvm_rip_read(vcpu);
9386 
9387 	/*
9388 	 * If the quirk is disabled, synthesize a #UD and let the guest pick up
9389 	 * the pieces.
9390 	 */
9391 	if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
9392 		ctxt->exception.error_code_valid = false;
9393 		ctxt->exception.vector = UD_VECTOR;
9394 		ctxt->have_exception = true;
9395 		return X86EMUL_PROPAGATE_FAULT;
9396 	}
9397 
9398 	static_call(kvm_x86_patch_hypercall)(vcpu, instruction);
9399 
9400 	return emulator_write_emulated(ctxt, rip, instruction, 3,
9401 		&ctxt->exception);
9402 }
9403 
dm_request_for_irq_injection(struct kvm_vcpu * vcpu)9404 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
9405 {
9406 	return vcpu->run->request_interrupt_window &&
9407 		likely(!pic_in_kernel(vcpu->kvm));
9408 }
9409 
9410 /* Called within kvm->srcu read side.  */
post_kvm_run_save(struct kvm_vcpu * vcpu)9411 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
9412 {
9413 	struct kvm_run *kvm_run = vcpu->run;
9414 
9415 	kvm_run->if_flag = static_call(kvm_x86_get_if_flag)(vcpu);
9416 	kvm_run->cr8 = kvm_get_cr8(vcpu);
9417 	kvm_run->apic_base = kvm_get_apic_base(vcpu);
9418 
9419 	kvm_run->ready_for_interrupt_injection =
9420 		pic_in_kernel(vcpu->kvm) ||
9421 		kvm_vcpu_ready_for_interrupt_injection(vcpu);
9422 
9423 	if (is_smm(vcpu))
9424 		kvm_run->flags |= KVM_RUN_X86_SMM;
9425 }
9426 
update_cr8_intercept(struct kvm_vcpu * vcpu)9427 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
9428 {
9429 	int max_irr, tpr;
9430 
9431 	if (!kvm_x86_ops.update_cr8_intercept)
9432 		return;
9433 
9434 	if (!lapic_in_kernel(vcpu))
9435 		return;
9436 
9437 	if (vcpu->arch.apicv_active)
9438 		return;
9439 
9440 	if (!vcpu->arch.apic->vapic_addr)
9441 		max_irr = kvm_lapic_find_highest_irr(vcpu);
9442 	else
9443 		max_irr = -1;
9444 
9445 	if (max_irr != -1)
9446 		max_irr >>= 4;
9447 
9448 	tpr = kvm_lapic_get_cr8(vcpu);
9449 
9450 	static_call(kvm_x86_update_cr8_intercept)(vcpu, tpr, max_irr);
9451 }
9452 
9453 
kvm_check_nested_events(struct kvm_vcpu * vcpu)9454 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
9455 {
9456 	if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
9457 		kvm_x86_ops.nested_ops->triple_fault(vcpu);
9458 		return 1;
9459 	}
9460 
9461 	return kvm_x86_ops.nested_ops->check_events(vcpu);
9462 }
9463 
kvm_inject_exception(struct kvm_vcpu * vcpu)9464 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
9465 {
9466 	if (vcpu->arch.exception.error_code && !is_protmode(vcpu))
9467 		vcpu->arch.exception.error_code = false;
9468 	static_call(kvm_x86_queue_exception)(vcpu);
9469 }
9470 
inject_pending_event(struct kvm_vcpu * vcpu,bool * req_immediate_exit)9471 static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
9472 {
9473 	int r;
9474 	bool can_inject = true;
9475 
9476 	/* try to reinject previous events if any */
9477 
9478 	if (vcpu->arch.exception.injected) {
9479 		kvm_inject_exception(vcpu);
9480 		can_inject = false;
9481 	}
9482 	/*
9483 	 * Do not inject an NMI or interrupt if there is a pending
9484 	 * exception.  Exceptions and interrupts are recognized at
9485 	 * instruction boundaries, i.e. the start of an instruction.
9486 	 * Trap-like exceptions, e.g. #DB, have higher priority than
9487 	 * NMIs and interrupts, i.e. traps are recognized before an
9488 	 * NMI/interrupt that's pending on the same instruction.
9489 	 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
9490 	 * priority, but are only generated (pended) during instruction
9491 	 * execution, i.e. a pending fault-like exception means the
9492 	 * fault occurred on the *previous* instruction and must be
9493 	 * serviced prior to recognizing any new events in order to
9494 	 * fully complete the previous instruction.
9495 	 */
9496 	else if (!vcpu->arch.exception.pending) {
9497 		if (vcpu->arch.nmi_injected) {
9498 			static_call(kvm_x86_inject_nmi)(vcpu);
9499 			can_inject = false;
9500 		} else if (vcpu->arch.interrupt.injected) {
9501 			static_call(kvm_x86_inject_irq)(vcpu);
9502 			can_inject = false;
9503 		}
9504 	}
9505 
9506 	WARN_ON_ONCE(vcpu->arch.exception.injected &&
9507 		     vcpu->arch.exception.pending);
9508 
9509 	/*
9510 	 * Call check_nested_events() even if we reinjected a previous event
9511 	 * in order for caller to determine if it should require immediate-exit
9512 	 * from L2 to L1 due to pending L1 events which require exit
9513 	 * from L2 to L1.
9514 	 */
9515 	if (is_guest_mode(vcpu)) {
9516 		r = kvm_check_nested_events(vcpu);
9517 		if (r < 0)
9518 			goto out;
9519 	}
9520 
9521 	/* try to inject new event if pending */
9522 	if (vcpu->arch.exception.pending) {
9523 		trace_kvm_inj_exception(vcpu->arch.exception.nr,
9524 					vcpu->arch.exception.has_error_code,
9525 					vcpu->arch.exception.error_code);
9526 
9527 		vcpu->arch.exception.pending = false;
9528 		vcpu->arch.exception.injected = true;
9529 
9530 		if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
9531 			__kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
9532 					     X86_EFLAGS_RF);
9533 
9534 		if (vcpu->arch.exception.nr == DB_VECTOR) {
9535 			kvm_deliver_exception_payload(vcpu);
9536 			if (vcpu->arch.dr7 & DR7_GD) {
9537 				vcpu->arch.dr7 &= ~DR7_GD;
9538 				kvm_update_dr7(vcpu);
9539 			}
9540 		}
9541 
9542 		kvm_inject_exception(vcpu);
9543 		can_inject = false;
9544 	}
9545 
9546 	/* Don't inject interrupts if the user asked to avoid doing so */
9547 	if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
9548 		return 0;
9549 
9550 	/*
9551 	 * Finally, inject interrupt events.  If an event cannot be injected
9552 	 * due to architectural conditions (e.g. IF=0) a window-open exit
9553 	 * will re-request KVM_REQ_EVENT.  Sometimes however an event is pending
9554 	 * and can architecturally be injected, but we cannot do it right now:
9555 	 * an interrupt could have arrived just now and we have to inject it
9556 	 * as a vmexit, or there could already an event in the queue, which is
9557 	 * indicated by can_inject.  In that case we request an immediate exit
9558 	 * in order to make progress and get back here for another iteration.
9559 	 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
9560 	 */
9561 	if (vcpu->arch.smi_pending) {
9562 		r = can_inject ? static_call(kvm_x86_smi_allowed)(vcpu, true) : -EBUSY;
9563 		if (r < 0)
9564 			goto out;
9565 		if (r) {
9566 			vcpu->arch.smi_pending = false;
9567 			++vcpu->arch.smi_count;
9568 			enter_smm(vcpu);
9569 			can_inject = false;
9570 		} else
9571 			static_call(kvm_x86_enable_smi_window)(vcpu);
9572 	}
9573 
9574 	if (vcpu->arch.nmi_pending) {
9575 		r = can_inject ? static_call(kvm_x86_nmi_allowed)(vcpu, true) : -EBUSY;
9576 		if (r < 0)
9577 			goto out;
9578 		if (r) {
9579 			--vcpu->arch.nmi_pending;
9580 			vcpu->arch.nmi_injected = true;
9581 			static_call(kvm_x86_inject_nmi)(vcpu);
9582 			can_inject = false;
9583 			WARN_ON(static_call(kvm_x86_nmi_allowed)(vcpu, true) < 0);
9584 		}
9585 		if (vcpu->arch.nmi_pending)
9586 			static_call(kvm_x86_enable_nmi_window)(vcpu);
9587 	}
9588 
9589 	if (kvm_cpu_has_injectable_intr(vcpu)) {
9590 		r = can_inject ? static_call(kvm_x86_interrupt_allowed)(vcpu, true) : -EBUSY;
9591 		if (r < 0)
9592 			goto out;
9593 		if (r) {
9594 			kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
9595 			static_call(kvm_x86_inject_irq)(vcpu);
9596 			WARN_ON(static_call(kvm_x86_interrupt_allowed)(vcpu, true) < 0);
9597 		}
9598 		if (kvm_cpu_has_injectable_intr(vcpu))
9599 			static_call(kvm_x86_enable_irq_window)(vcpu);
9600 	}
9601 
9602 	if (is_guest_mode(vcpu) &&
9603 	    kvm_x86_ops.nested_ops->hv_timer_pending &&
9604 	    kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
9605 		*req_immediate_exit = true;
9606 
9607 	WARN_ON(vcpu->arch.exception.pending);
9608 	return 0;
9609 
9610 out:
9611 	if (r == -EBUSY) {
9612 		*req_immediate_exit = true;
9613 		r = 0;
9614 	}
9615 	return r;
9616 }
9617 
process_nmi(struct kvm_vcpu * vcpu)9618 static void process_nmi(struct kvm_vcpu *vcpu)
9619 {
9620 	unsigned limit = 2;
9621 
9622 	/*
9623 	 * x86 is limited to one NMI running, and one NMI pending after it.
9624 	 * If an NMI is already in progress, limit further NMIs to just one.
9625 	 * Otherwise, allow two (and we'll inject the first one immediately).
9626 	 */
9627 	if (static_call(kvm_x86_get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
9628 		limit = 1;
9629 
9630 	vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
9631 	vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
9632 	kvm_make_request(KVM_REQ_EVENT, vcpu);
9633 }
9634 
enter_smm_get_segment_flags(struct kvm_segment * seg)9635 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
9636 {
9637 	u32 flags = 0;
9638 	flags |= seg->g       << 23;
9639 	flags |= seg->db      << 22;
9640 	flags |= seg->l       << 21;
9641 	flags |= seg->avl     << 20;
9642 	flags |= seg->present << 15;
9643 	flags |= seg->dpl     << 13;
9644 	flags |= seg->s       << 12;
9645 	flags |= seg->type    << 8;
9646 	return flags;
9647 }
9648 
enter_smm_save_seg_32(struct kvm_vcpu * vcpu,char * buf,int n)9649 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
9650 {
9651 	struct kvm_segment seg;
9652 	int offset;
9653 
9654 	kvm_get_segment(vcpu, &seg, n);
9655 	put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
9656 
9657 	if (n < 3)
9658 		offset = 0x7f84 + n * 12;
9659 	else
9660 		offset = 0x7f2c + (n - 3) * 12;
9661 
9662 	put_smstate(u32, buf, offset + 8, seg.base);
9663 	put_smstate(u32, buf, offset + 4, seg.limit);
9664 	put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
9665 }
9666 
9667 #ifdef CONFIG_X86_64
enter_smm_save_seg_64(struct kvm_vcpu * vcpu,char * buf,int n)9668 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
9669 {
9670 	struct kvm_segment seg;
9671 	int offset;
9672 	u16 flags;
9673 
9674 	kvm_get_segment(vcpu, &seg, n);
9675 	offset = 0x7e00 + n * 16;
9676 
9677 	flags = enter_smm_get_segment_flags(&seg) >> 8;
9678 	put_smstate(u16, buf, offset, seg.selector);
9679 	put_smstate(u16, buf, offset + 2, flags);
9680 	put_smstate(u32, buf, offset + 4, seg.limit);
9681 	put_smstate(u64, buf, offset + 8, seg.base);
9682 }
9683 #endif
9684 
enter_smm_save_state_32(struct kvm_vcpu * vcpu,char * buf)9685 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
9686 {
9687 	struct desc_ptr dt;
9688 	struct kvm_segment seg;
9689 	unsigned long val;
9690 	int i;
9691 
9692 	put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
9693 	put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
9694 	put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
9695 	put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
9696 
9697 	for (i = 0; i < 8; i++)
9698 		put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read_raw(vcpu, i));
9699 
9700 	kvm_get_dr(vcpu, 6, &val);
9701 	put_smstate(u32, buf, 0x7fcc, (u32)val);
9702 	kvm_get_dr(vcpu, 7, &val);
9703 	put_smstate(u32, buf, 0x7fc8, (u32)val);
9704 
9705 	kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
9706 	put_smstate(u32, buf, 0x7fc4, seg.selector);
9707 	put_smstate(u32, buf, 0x7f64, seg.base);
9708 	put_smstate(u32, buf, 0x7f60, seg.limit);
9709 	put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
9710 
9711 	kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
9712 	put_smstate(u32, buf, 0x7fc0, seg.selector);
9713 	put_smstate(u32, buf, 0x7f80, seg.base);
9714 	put_smstate(u32, buf, 0x7f7c, seg.limit);
9715 	put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
9716 
9717 	static_call(kvm_x86_get_gdt)(vcpu, &dt);
9718 	put_smstate(u32, buf, 0x7f74, dt.address);
9719 	put_smstate(u32, buf, 0x7f70, dt.size);
9720 
9721 	static_call(kvm_x86_get_idt)(vcpu, &dt);
9722 	put_smstate(u32, buf, 0x7f58, dt.address);
9723 	put_smstate(u32, buf, 0x7f54, dt.size);
9724 
9725 	for (i = 0; i < 6; i++)
9726 		enter_smm_save_seg_32(vcpu, buf, i);
9727 
9728 	put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
9729 
9730 	/* revision id */
9731 	put_smstate(u32, buf, 0x7efc, 0x00020000);
9732 	put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
9733 }
9734 
9735 #ifdef CONFIG_X86_64
enter_smm_save_state_64(struct kvm_vcpu * vcpu,char * buf)9736 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
9737 {
9738 	struct desc_ptr dt;
9739 	struct kvm_segment seg;
9740 	unsigned long val;
9741 	int i;
9742 
9743 	for (i = 0; i < 16; i++)
9744 		put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read_raw(vcpu, i));
9745 
9746 	put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
9747 	put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
9748 
9749 	kvm_get_dr(vcpu, 6, &val);
9750 	put_smstate(u64, buf, 0x7f68, val);
9751 	kvm_get_dr(vcpu, 7, &val);
9752 	put_smstate(u64, buf, 0x7f60, val);
9753 
9754 	put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
9755 	put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
9756 	put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
9757 
9758 	put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
9759 
9760 	/* revision id */
9761 	put_smstate(u32, buf, 0x7efc, 0x00020064);
9762 
9763 	put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
9764 
9765 	kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
9766 	put_smstate(u16, buf, 0x7e90, seg.selector);
9767 	put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
9768 	put_smstate(u32, buf, 0x7e94, seg.limit);
9769 	put_smstate(u64, buf, 0x7e98, seg.base);
9770 
9771 	static_call(kvm_x86_get_idt)(vcpu, &dt);
9772 	put_smstate(u32, buf, 0x7e84, dt.size);
9773 	put_smstate(u64, buf, 0x7e88, dt.address);
9774 
9775 	kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
9776 	put_smstate(u16, buf, 0x7e70, seg.selector);
9777 	put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
9778 	put_smstate(u32, buf, 0x7e74, seg.limit);
9779 	put_smstate(u64, buf, 0x7e78, seg.base);
9780 
9781 	static_call(kvm_x86_get_gdt)(vcpu, &dt);
9782 	put_smstate(u32, buf, 0x7e64, dt.size);
9783 	put_smstate(u64, buf, 0x7e68, dt.address);
9784 
9785 	for (i = 0; i < 6; i++)
9786 		enter_smm_save_seg_64(vcpu, buf, i);
9787 }
9788 #endif
9789 
enter_smm(struct kvm_vcpu * vcpu)9790 static void enter_smm(struct kvm_vcpu *vcpu)
9791 {
9792 	struct kvm_segment cs, ds;
9793 	struct desc_ptr dt;
9794 	unsigned long cr0;
9795 	char buf[512];
9796 
9797 	memset(buf, 0, 512);
9798 #ifdef CONFIG_X86_64
9799 	if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
9800 		enter_smm_save_state_64(vcpu, buf);
9801 	else
9802 #endif
9803 		enter_smm_save_state_32(vcpu, buf);
9804 
9805 	/*
9806 	 * Give enter_smm() a chance to make ISA-specific changes to the vCPU
9807 	 * state (e.g. leave guest mode) after we've saved the state into the
9808 	 * SMM state-save area.
9809 	 */
9810 	static_call(kvm_x86_enter_smm)(vcpu, buf);
9811 
9812 	kvm_smm_changed(vcpu, true);
9813 	kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
9814 
9815 	if (static_call(kvm_x86_get_nmi_mask)(vcpu))
9816 		vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
9817 	else
9818 		static_call(kvm_x86_set_nmi_mask)(vcpu, true);
9819 
9820 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
9821 	kvm_rip_write(vcpu, 0x8000);
9822 
9823 	cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
9824 	static_call(kvm_x86_set_cr0)(vcpu, cr0);
9825 	vcpu->arch.cr0 = cr0;
9826 
9827 	static_call(kvm_x86_set_cr4)(vcpu, 0);
9828 
9829 	/* Undocumented: IDT limit is set to zero on entry to SMM.  */
9830 	dt.address = dt.size = 0;
9831 	static_call(kvm_x86_set_idt)(vcpu, &dt);
9832 
9833 	kvm_set_dr(vcpu, 7, DR7_FIXED_1);
9834 
9835 	cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
9836 	cs.base = vcpu->arch.smbase;
9837 
9838 	ds.selector = 0;
9839 	ds.base = 0;
9840 
9841 	cs.limit    = ds.limit = 0xffffffff;
9842 	cs.type     = ds.type = 0x3;
9843 	cs.dpl      = ds.dpl = 0;
9844 	cs.db       = ds.db = 0;
9845 	cs.s        = ds.s = 1;
9846 	cs.l        = ds.l = 0;
9847 	cs.g        = ds.g = 1;
9848 	cs.avl      = ds.avl = 0;
9849 	cs.present  = ds.present = 1;
9850 	cs.unusable = ds.unusable = 0;
9851 	cs.padding  = ds.padding = 0;
9852 
9853 	kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9854 	kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
9855 	kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
9856 	kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
9857 	kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
9858 	kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
9859 
9860 #ifdef CONFIG_X86_64
9861 	if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
9862 		static_call(kvm_x86_set_efer)(vcpu, 0);
9863 #endif
9864 
9865 	kvm_update_cpuid_runtime(vcpu);
9866 	kvm_mmu_reset_context(vcpu);
9867 }
9868 
process_smi(struct kvm_vcpu * vcpu)9869 static void process_smi(struct kvm_vcpu *vcpu)
9870 {
9871 	vcpu->arch.smi_pending = true;
9872 	kvm_make_request(KVM_REQ_EVENT, vcpu);
9873 }
9874 
kvm_make_scan_ioapic_request_mask(struct kvm * kvm,unsigned long * vcpu_bitmap)9875 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
9876 				       unsigned long *vcpu_bitmap)
9877 {
9878 	kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
9879 }
9880 
kvm_make_scan_ioapic_request(struct kvm * kvm)9881 void kvm_make_scan_ioapic_request(struct kvm *kvm)
9882 {
9883 	kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
9884 }
9885 
kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)9886 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
9887 {
9888 	bool activate;
9889 
9890 	if (!lapic_in_kernel(vcpu))
9891 		return;
9892 
9893 	down_read(&vcpu->kvm->arch.apicv_update_lock);
9894 	preempt_disable();
9895 
9896 	activate = kvm_vcpu_apicv_activated(vcpu);
9897 
9898 	if (vcpu->arch.apicv_active == activate)
9899 		goto out;
9900 
9901 	vcpu->arch.apicv_active = activate;
9902 	kvm_apic_update_apicv(vcpu);
9903 	static_call(kvm_x86_refresh_apicv_exec_ctrl)(vcpu);
9904 
9905 	/*
9906 	 * When APICv gets disabled, we may still have injected interrupts
9907 	 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
9908 	 * still active when the interrupt got accepted. Make sure
9909 	 * inject_pending_event() is called to check for that.
9910 	 */
9911 	if (!vcpu->arch.apicv_active)
9912 		kvm_make_request(KVM_REQ_EVENT, vcpu);
9913 
9914 out:
9915 	preempt_enable();
9916 	up_read(&vcpu->kvm->arch.apicv_update_lock);
9917 }
9918 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
9919 
__kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)9920 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
9921 				      enum kvm_apicv_inhibit reason, bool set)
9922 {
9923 	unsigned long old, new;
9924 
9925 	lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
9926 
9927 	if (!static_call(kvm_x86_check_apicv_inhibit_reasons)(reason))
9928 		return;
9929 
9930 	old = new = kvm->arch.apicv_inhibit_reasons;
9931 
9932 	set_or_clear_apicv_inhibit(&new, reason, set);
9933 
9934 	if (!!old != !!new) {
9935 		/*
9936 		 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
9937 		 * false positives in the sanity check WARN in svm_vcpu_run().
9938 		 * This task will wait for all vCPUs to ack the kick IRQ before
9939 		 * updating apicv_inhibit_reasons, and all other vCPUs will
9940 		 * block on acquiring apicv_update_lock so that vCPUs can't
9941 		 * redo svm_vcpu_run() without seeing the new inhibit state.
9942 		 *
9943 		 * Note, holding apicv_update_lock and taking it in the read
9944 		 * side (handling the request) also prevents other vCPUs from
9945 		 * servicing the request with a stale apicv_inhibit_reasons.
9946 		 */
9947 		kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
9948 		kvm->arch.apicv_inhibit_reasons = new;
9949 		if (new) {
9950 			unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
9951 			kvm_zap_gfn_range(kvm, gfn, gfn+1);
9952 		}
9953 	} else {
9954 		kvm->arch.apicv_inhibit_reasons = new;
9955 	}
9956 }
9957 
kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)9958 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
9959 				    enum kvm_apicv_inhibit reason, bool set)
9960 {
9961 	if (!enable_apicv)
9962 		return;
9963 
9964 	down_write(&kvm->arch.apicv_update_lock);
9965 	__kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
9966 	up_write(&kvm->arch.apicv_update_lock);
9967 }
9968 EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
9969 
vcpu_scan_ioapic(struct kvm_vcpu * vcpu)9970 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
9971 {
9972 	if (!kvm_apic_present(vcpu))
9973 		return;
9974 
9975 	bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
9976 
9977 	if (irqchip_split(vcpu->kvm))
9978 		kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
9979 	else {
9980 		static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
9981 		if (ioapic_in_kernel(vcpu->kvm))
9982 			kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
9983 	}
9984 
9985 	if (is_guest_mode(vcpu))
9986 		vcpu->arch.load_eoi_exitmap_pending = true;
9987 	else
9988 		kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
9989 }
9990 
vcpu_load_eoi_exitmap(struct kvm_vcpu * vcpu)9991 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
9992 {
9993 	u64 eoi_exit_bitmap[4];
9994 
9995 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
9996 		return;
9997 
9998 	if (to_hv_vcpu(vcpu)) {
9999 		bitmap_or((ulong *)eoi_exit_bitmap,
10000 			  vcpu->arch.ioapic_handled_vectors,
10001 			  to_hv_synic(vcpu)->vec_bitmap, 256);
10002 		static_call_cond(kvm_x86_load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
10003 		return;
10004 	}
10005 
10006 	static_call_cond(kvm_x86_load_eoi_exitmap)(
10007 		vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
10008 }
10009 
kvm_arch_mmu_notifier_invalidate_range(struct kvm * kvm,unsigned long start,unsigned long end)10010 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
10011 					    unsigned long start, unsigned long end)
10012 {
10013 	unsigned long apic_address;
10014 
10015 	/*
10016 	 * The physical address of apic access page is stored in the VMCS.
10017 	 * Update it when it becomes invalid.
10018 	 */
10019 	apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
10020 	if (start <= apic_address && apic_address < end)
10021 		kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
10022 }
10023 
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)10024 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
10025 {
10026 	static_call_cond(kvm_x86_guest_memory_reclaimed)(kvm);
10027 }
10028 
kvm_vcpu_reload_apic_access_page(struct kvm_vcpu * vcpu)10029 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
10030 {
10031 	if (!lapic_in_kernel(vcpu))
10032 		return;
10033 
10034 	static_call_cond(kvm_x86_set_apic_access_page_addr)(vcpu);
10035 }
10036 
__kvm_request_immediate_exit(struct kvm_vcpu * vcpu)10037 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
10038 {
10039 	smp_send_reschedule(vcpu->cpu);
10040 }
10041 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
10042 
10043 /*
10044  * Called within kvm->srcu read side.
10045  * Returns 1 to let vcpu_run() continue the guest execution loop without
10046  * exiting to the userspace.  Otherwise, the value will be returned to the
10047  * userspace.
10048  */
vcpu_enter_guest(struct kvm_vcpu * vcpu)10049 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
10050 {
10051 	int r;
10052 	bool req_int_win =
10053 		dm_request_for_irq_injection(vcpu) &&
10054 		kvm_cpu_accept_dm_intr(vcpu);
10055 	fastpath_t exit_fastpath;
10056 
10057 	bool req_immediate_exit = false;
10058 
10059 	/* Forbid vmenter if vcpu dirty ring is soft-full */
10060 	if (unlikely(vcpu->kvm->dirty_ring_size &&
10061 		     kvm_dirty_ring_soft_full(&vcpu->dirty_ring))) {
10062 		vcpu->run->exit_reason = KVM_EXIT_DIRTY_RING_FULL;
10063 		trace_kvm_dirty_ring_exit(vcpu);
10064 		r = 0;
10065 		goto out;
10066 	}
10067 
10068 	if (kvm_request_pending(vcpu)) {
10069 		if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
10070 			r = -EIO;
10071 			goto out;
10072 		}
10073 		if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
10074 			if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
10075 				r = 0;
10076 				goto out;
10077 			}
10078 		}
10079 		if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
10080 			kvm_mmu_free_obsolete_roots(vcpu);
10081 		if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
10082 			__kvm_migrate_timers(vcpu);
10083 		if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
10084 			kvm_update_masterclock(vcpu->kvm);
10085 		if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
10086 			kvm_gen_kvmclock_update(vcpu);
10087 		if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
10088 			r = kvm_guest_time_update(vcpu);
10089 			if (unlikely(r))
10090 				goto out;
10091 		}
10092 		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
10093 			kvm_mmu_sync_roots(vcpu);
10094 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
10095 			kvm_mmu_load_pgd(vcpu);
10096 		if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
10097 			kvm_vcpu_flush_tlb_all(vcpu);
10098 
10099 			/* Flushing all ASIDs flushes the current ASID... */
10100 			kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
10101 		}
10102 		kvm_service_local_tlb_flush_requests(vcpu);
10103 
10104 		if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
10105 			vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
10106 			r = 0;
10107 			goto out;
10108 		}
10109 		if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10110 			if (is_guest_mode(vcpu)) {
10111 				kvm_x86_ops.nested_ops->triple_fault(vcpu);
10112 			} else {
10113 				vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
10114 				vcpu->mmio_needed = 0;
10115 				r = 0;
10116 				goto out;
10117 			}
10118 		}
10119 		if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
10120 			/* Page is swapped out. Do synthetic halt */
10121 			vcpu->arch.apf.halted = true;
10122 			r = 1;
10123 			goto out;
10124 		}
10125 		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
10126 			record_steal_time(vcpu);
10127 		if (kvm_check_request(KVM_REQ_SMI, vcpu))
10128 			process_smi(vcpu);
10129 		if (kvm_check_request(KVM_REQ_NMI, vcpu))
10130 			process_nmi(vcpu);
10131 		if (kvm_check_request(KVM_REQ_PMU, vcpu))
10132 			kvm_pmu_handle_event(vcpu);
10133 		if (kvm_check_request(KVM_REQ_PMI, vcpu))
10134 			kvm_pmu_deliver_pmi(vcpu);
10135 		if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
10136 			BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
10137 			if (test_bit(vcpu->arch.pending_ioapic_eoi,
10138 				     vcpu->arch.ioapic_handled_vectors)) {
10139 				vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
10140 				vcpu->run->eoi.vector =
10141 						vcpu->arch.pending_ioapic_eoi;
10142 				r = 0;
10143 				goto out;
10144 			}
10145 		}
10146 		if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
10147 			vcpu_scan_ioapic(vcpu);
10148 		if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
10149 			vcpu_load_eoi_exitmap(vcpu);
10150 		if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
10151 			kvm_vcpu_reload_apic_access_page(vcpu);
10152 		if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
10153 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10154 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
10155 			vcpu->run->system_event.ndata = 0;
10156 			r = 0;
10157 			goto out;
10158 		}
10159 		if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
10160 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10161 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
10162 			vcpu->run->system_event.ndata = 0;
10163 			r = 0;
10164 			goto out;
10165 		}
10166 		if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
10167 			struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
10168 
10169 			vcpu->run->exit_reason = KVM_EXIT_HYPERV;
10170 			vcpu->run->hyperv = hv_vcpu->exit;
10171 			r = 0;
10172 			goto out;
10173 		}
10174 
10175 		/*
10176 		 * KVM_REQ_HV_STIMER has to be processed after
10177 		 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
10178 		 * depend on the guest clock being up-to-date
10179 		 */
10180 		if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
10181 			kvm_hv_process_stimers(vcpu);
10182 		if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
10183 			kvm_vcpu_update_apicv(vcpu);
10184 		if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
10185 			kvm_check_async_pf_completion(vcpu);
10186 		if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
10187 			static_call(kvm_x86_msr_filter_changed)(vcpu);
10188 
10189 		if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
10190 			static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
10191 	}
10192 
10193 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
10194 	    kvm_xen_has_interrupt(vcpu)) {
10195 		++vcpu->stat.req_event;
10196 		r = kvm_apic_accept_events(vcpu);
10197 		if (r < 0) {
10198 			r = 0;
10199 			goto out;
10200 		}
10201 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
10202 			r = 1;
10203 			goto out;
10204 		}
10205 
10206 		r = inject_pending_event(vcpu, &req_immediate_exit);
10207 		if (r < 0) {
10208 			r = 0;
10209 			goto out;
10210 		}
10211 		if (req_int_win)
10212 			static_call(kvm_x86_enable_irq_window)(vcpu);
10213 
10214 		if (kvm_lapic_enabled(vcpu)) {
10215 			update_cr8_intercept(vcpu);
10216 			kvm_lapic_sync_to_vapic(vcpu);
10217 		}
10218 	}
10219 
10220 	r = kvm_mmu_reload(vcpu);
10221 	if (unlikely(r)) {
10222 		goto cancel_injection;
10223 	}
10224 
10225 	preempt_disable();
10226 
10227 	static_call(kvm_x86_prepare_switch_to_guest)(vcpu);
10228 
10229 	/*
10230 	 * Disable IRQs before setting IN_GUEST_MODE.  Posted interrupt
10231 	 * IPI are then delayed after guest entry, which ensures that they
10232 	 * result in virtual interrupt delivery.
10233 	 */
10234 	local_irq_disable();
10235 
10236 	/* Store vcpu->apicv_active before vcpu->mode.  */
10237 	smp_store_release(&vcpu->mode, IN_GUEST_MODE);
10238 
10239 	kvm_vcpu_srcu_read_unlock(vcpu);
10240 
10241 	/*
10242 	 * 1) We should set ->mode before checking ->requests.  Please see
10243 	 * the comment in kvm_vcpu_exiting_guest_mode().
10244 	 *
10245 	 * 2) For APICv, we should set ->mode before checking PID.ON. This
10246 	 * pairs with the memory barrier implicit in pi_test_and_set_on
10247 	 * (see vmx_deliver_posted_interrupt).
10248 	 *
10249 	 * 3) This also orders the write to mode from any reads to the page
10250 	 * tables done while the VCPU is running.  Please see the comment
10251 	 * in kvm_flush_remote_tlbs.
10252 	 */
10253 	smp_mb__after_srcu_read_unlock();
10254 
10255 	/*
10256 	 * Process pending posted interrupts to handle the case where the
10257 	 * notification IRQ arrived in the host, or was never sent (because the
10258 	 * target vCPU wasn't running).  Do this regardless of the vCPU's APICv
10259 	 * status, KVM doesn't update assigned devices when APICv is inhibited,
10260 	 * i.e. they can post interrupts even if APICv is temporarily disabled.
10261 	 */
10262 	if (kvm_lapic_enabled(vcpu))
10263 		static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
10264 
10265 	if (kvm_vcpu_exit_request(vcpu)) {
10266 		vcpu->mode = OUTSIDE_GUEST_MODE;
10267 		smp_wmb();
10268 		local_irq_enable();
10269 		preempt_enable();
10270 		kvm_vcpu_srcu_read_lock(vcpu);
10271 		r = 1;
10272 		goto cancel_injection;
10273 	}
10274 
10275 	if (req_immediate_exit) {
10276 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10277 		static_call(kvm_x86_request_immediate_exit)(vcpu);
10278 	}
10279 
10280 	fpregs_assert_state_consistent();
10281 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
10282 		switch_fpu_return();
10283 
10284 	if (vcpu->arch.guest_fpu.xfd_err)
10285 		wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
10286 
10287 	if (unlikely(vcpu->arch.switch_db_regs)) {
10288 		set_debugreg(0, 7);
10289 		set_debugreg(vcpu->arch.eff_db[0], 0);
10290 		set_debugreg(vcpu->arch.eff_db[1], 1);
10291 		set_debugreg(vcpu->arch.eff_db[2], 2);
10292 		set_debugreg(vcpu->arch.eff_db[3], 3);
10293 	} else if (unlikely(hw_breakpoint_active())) {
10294 		set_debugreg(0, 7);
10295 	}
10296 
10297 	guest_timing_enter_irqoff();
10298 
10299 	for (;;) {
10300 		/*
10301 		 * Assert that vCPU vs. VM APICv state is consistent.  An APICv
10302 		 * update must kick and wait for all vCPUs before toggling the
10303 		 * per-VM state, and responsing vCPUs must wait for the update
10304 		 * to complete before servicing KVM_REQ_APICV_UPDATE.
10305 		 */
10306 		WARN_ON_ONCE(kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu));
10307 
10308 		exit_fastpath = static_call(kvm_x86_vcpu_run)(vcpu);
10309 		if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
10310 			break;
10311 
10312 		if (kvm_lapic_enabled(vcpu))
10313 			static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
10314 
10315 		if (unlikely(kvm_vcpu_exit_request(vcpu))) {
10316 			exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
10317 			break;
10318 		}
10319 	}
10320 
10321 	/*
10322 	 * Do this here before restoring debug registers on the host.  And
10323 	 * since we do this before handling the vmexit, a DR access vmexit
10324 	 * can (a) read the correct value of the debug registers, (b) set
10325 	 * KVM_DEBUGREG_WONT_EXIT again.
10326 	 */
10327 	if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
10328 		WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
10329 		static_call(kvm_x86_sync_dirty_debug_regs)(vcpu);
10330 		kvm_update_dr0123(vcpu);
10331 		kvm_update_dr7(vcpu);
10332 	}
10333 
10334 	/*
10335 	 * If the guest has used debug registers, at least dr7
10336 	 * will be disabled while returning to the host.
10337 	 * If we don't have active breakpoints in the host, we don't
10338 	 * care about the messed up debug address registers. But if
10339 	 * we have some of them active, restore the old state.
10340 	 */
10341 	if (hw_breakpoint_active())
10342 		hw_breakpoint_restore();
10343 
10344 	vcpu->arch.last_vmentry_cpu = vcpu->cpu;
10345 	vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
10346 
10347 	vcpu->mode = OUTSIDE_GUEST_MODE;
10348 	smp_wmb();
10349 
10350 	/*
10351 	 * Sync xfd before calling handle_exit_irqoff() which may
10352 	 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
10353 	 * in #NM irqoff handler).
10354 	 */
10355 	if (vcpu->arch.xfd_no_write_intercept)
10356 		fpu_sync_guest_vmexit_xfd_state();
10357 
10358 	static_call(kvm_x86_handle_exit_irqoff)(vcpu);
10359 
10360 	if (vcpu->arch.guest_fpu.xfd_err)
10361 		wrmsrl(MSR_IA32_XFD_ERR, 0);
10362 
10363 	/*
10364 	 * Consume any pending interrupts, including the possible source of
10365 	 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
10366 	 * An instruction is required after local_irq_enable() to fully unblock
10367 	 * interrupts on processors that implement an interrupt shadow, the
10368 	 * stat.exits increment will do nicely.
10369 	 */
10370 	kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
10371 	local_irq_enable();
10372 	++vcpu->stat.exits;
10373 	local_irq_disable();
10374 	kvm_after_interrupt(vcpu);
10375 
10376 	/*
10377 	 * Wait until after servicing IRQs to account guest time so that any
10378 	 * ticks that occurred while running the guest are properly accounted
10379 	 * to the guest.  Waiting until IRQs are enabled degrades the accuracy
10380 	 * of accounting via context tracking, but the loss of accuracy is
10381 	 * acceptable for all known use cases.
10382 	 */
10383 	guest_timing_exit_irqoff();
10384 
10385 	local_irq_enable();
10386 	preempt_enable();
10387 
10388 	kvm_vcpu_srcu_read_lock(vcpu);
10389 
10390 	/*
10391 	 * Profile KVM exit RIPs:
10392 	 */
10393 	if (unlikely(prof_on == KVM_PROFILING)) {
10394 		unsigned long rip = kvm_rip_read(vcpu);
10395 		profile_hit(KVM_PROFILING, (void *)rip);
10396 	}
10397 
10398 	if (unlikely(vcpu->arch.tsc_always_catchup))
10399 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
10400 
10401 	if (vcpu->arch.apic_attention)
10402 		kvm_lapic_sync_from_vapic(vcpu);
10403 
10404 	r = static_call(kvm_x86_handle_exit)(vcpu, exit_fastpath);
10405 	return r;
10406 
10407 cancel_injection:
10408 	if (req_immediate_exit)
10409 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10410 	static_call(kvm_x86_cancel_injection)(vcpu);
10411 	if (unlikely(vcpu->arch.apic_attention))
10412 		kvm_lapic_sync_from_vapic(vcpu);
10413 out:
10414 	return r;
10415 }
10416 
10417 /* Called within kvm->srcu read side.  */
vcpu_block(struct kvm_vcpu * vcpu)10418 static inline int vcpu_block(struct kvm_vcpu *vcpu)
10419 {
10420 	bool hv_timer;
10421 
10422 	if (!kvm_arch_vcpu_runnable(vcpu)) {
10423 		/*
10424 		 * Switch to the software timer before halt-polling/blocking as
10425 		 * the guest's timer may be a break event for the vCPU, and the
10426 		 * hypervisor timer runs only when the CPU is in guest mode.
10427 		 * Switch before halt-polling so that KVM recognizes an expired
10428 		 * timer before blocking.
10429 		 */
10430 		hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
10431 		if (hv_timer)
10432 			kvm_lapic_switch_to_sw_timer(vcpu);
10433 
10434 		kvm_vcpu_srcu_read_unlock(vcpu);
10435 		if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
10436 			kvm_vcpu_halt(vcpu);
10437 		else
10438 			kvm_vcpu_block(vcpu);
10439 		kvm_vcpu_srcu_read_lock(vcpu);
10440 
10441 		if (hv_timer)
10442 			kvm_lapic_switch_to_hv_timer(vcpu);
10443 
10444 		if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
10445 			return 1;
10446 	}
10447 
10448 	if (kvm_apic_accept_events(vcpu) < 0)
10449 		return 0;
10450 	switch(vcpu->arch.mp_state) {
10451 	case KVM_MP_STATE_HALTED:
10452 	case KVM_MP_STATE_AP_RESET_HOLD:
10453 		vcpu->arch.pv.pv_unhalted = false;
10454 		vcpu->arch.mp_state =
10455 			KVM_MP_STATE_RUNNABLE;
10456 		fallthrough;
10457 	case KVM_MP_STATE_RUNNABLE:
10458 		vcpu->arch.apf.halted = false;
10459 		break;
10460 	case KVM_MP_STATE_INIT_RECEIVED:
10461 		break;
10462 	default:
10463 		return -EINTR;
10464 	}
10465 	return 1;
10466 }
10467 
kvm_vcpu_running(struct kvm_vcpu * vcpu)10468 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
10469 {
10470 	if (is_guest_mode(vcpu))
10471 		kvm_check_nested_events(vcpu);
10472 
10473 	return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
10474 		!vcpu->arch.apf.halted);
10475 }
10476 
10477 /* Called within kvm->srcu read side.  */
vcpu_run(struct kvm_vcpu * vcpu)10478 static int vcpu_run(struct kvm_vcpu *vcpu)
10479 {
10480 	int r;
10481 
10482 	vcpu->arch.l1tf_flush_l1d = true;
10483 
10484 	for (;;) {
10485 		/*
10486 		 * If another guest vCPU requests a PV TLB flush in the middle
10487 		 * of instruction emulation, the rest of the emulation could
10488 		 * use a stale page translation. Assume that any code after
10489 		 * this point can start executing an instruction.
10490 		 */
10491 		vcpu->arch.at_instruction_boundary = false;
10492 		if (kvm_vcpu_running(vcpu)) {
10493 			r = vcpu_enter_guest(vcpu);
10494 		} else {
10495 			r = vcpu_block(vcpu);
10496 		}
10497 
10498 		if (r <= 0)
10499 			break;
10500 
10501 		kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
10502 		if (kvm_xen_has_pending_events(vcpu))
10503 			kvm_xen_inject_pending_events(vcpu);
10504 
10505 		if (kvm_cpu_has_pending_timer(vcpu))
10506 			kvm_inject_pending_timer_irqs(vcpu);
10507 
10508 		if (dm_request_for_irq_injection(vcpu) &&
10509 			kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
10510 			r = 0;
10511 			vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
10512 			++vcpu->stat.request_irq_exits;
10513 			break;
10514 		}
10515 
10516 		if (__xfer_to_guest_mode_work_pending()) {
10517 			kvm_vcpu_srcu_read_unlock(vcpu);
10518 			r = xfer_to_guest_mode_handle_work(vcpu);
10519 			kvm_vcpu_srcu_read_lock(vcpu);
10520 			if (r)
10521 				return r;
10522 		}
10523 	}
10524 
10525 	return r;
10526 }
10527 
complete_emulated_io(struct kvm_vcpu * vcpu)10528 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
10529 {
10530 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
10531 }
10532 
complete_emulated_pio(struct kvm_vcpu * vcpu)10533 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
10534 {
10535 	BUG_ON(!vcpu->arch.pio.count);
10536 
10537 	return complete_emulated_io(vcpu);
10538 }
10539 
10540 /*
10541  * Implements the following, as a state machine:
10542  *
10543  * read:
10544  *   for each fragment
10545  *     for each mmio piece in the fragment
10546  *       write gpa, len
10547  *       exit
10548  *       copy data
10549  *   execute insn
10550  *
10551  * write:
10552  *   for each fragment
10553  *     for each mmio piece in the fragment
10554  *       write gpa, len
10555  *       copy data
10556  *       exit
10557  */
complete_emulated_mmio(struct kvm_vcpu * vcpu)10558 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
10559 {
10560 	struct kvm_run *run = vcpu->run;
10561 	struct kvm_mmio_fragment *frag;
10562 	unsigned len;
10563 
10564 	BUG_ON(!vcpu->mmio_needed);
10565 
10566 	/* Complete previous fragment */
10567 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
10568 	len = min(8u, frag->len);
10569 	if (!vcpu->mmio_is_write)
10570 		memcpy(frag->data, run->mmio.data, len);
10571 
10572 	if (frag->len <= 8) {
10573 		/* Switch to the next fragment. */
10574 		frag++;
10575 		vcpu->mmio_cur_fragment++;
10576 	} else {
10577 		/* Go forward to the next mmio piece. */
10578 		frag->data += len;
10579 		frag->gpa += len;
10580 		frag->len -= len;
10581 	}
10582 
10583 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
10584 		vcpu->mmio_needed = 0;
10585 
10586 		/* FIXME: return into emulator if single-stepping.  */
10587 		if (vcpu->mmio_is_write)
10588 			return 1;
10589 		vcpu->mmio_read_completed = 1;
10590 		return complete_emulated_io(vcpu);
10591 	}
10592 
10593 	run->exit_reason = KVM_EXIT_MMIO;
10594 	run->mmio.phys_addr = frag->gpa;
10595 	if (vcpu->mmio_is_write)
10596 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
10597 	run->mmio.len = min(8u, frag->len);
10598 	run->mmio.is_write = vcpu->mmio_is_write;
10599 	vcpu->arch.complete_userspace_io = complete_emulated_mmio;
10600 	return 0;
10601 }
10602 
10603 /* Swap (qemu) user FPU context for the guest FPU context. */
kvm_load_guest_fpu(struct kvm_vcpu * vcpu)10604 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
10605 {
10606 	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
10607 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
10608 	trace_kvm_fpu(1);
10609 }
10610 
10611 /* When vcpu_run ends, restore user space FPU context. */
kvm_put_guest_fpu(struct kvm_vcpu * vcpu)10612 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
10613 {
10614 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
10615 	++vcpu->stat.fpu_reload;
10616 	trace_kvm_fpu(0);
10617 }
10618 
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)10619 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
10620 {
10621 	struct kvm_run *kvm_run = vcpu->run;
10622 	int r;
10623 
10624 	vcpu_load(vcpu);
10625 	kvm_sigset_activate(vcpu);
10626 	kvm_run->flags = 0;
10627 	kvm_load_guest_fpu(vcpu);
10628 
10629 	kvm_vcpu_srcu_read_lock(vcpu);
10630 	if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
10631 		if (kvm_run->immediate_exit) {
10632 			r = -EINTR;
10633 			goto out;
10634 		}
10635 		/*
10636 		 * It should be impossible for the hypervisor timer to be in
10637 		 * use before KVM has ever run the vCPU.
10638 		 */
10639 		WARN_ON_ONCE(kvm_lapic_hv_timer_in_use(vcpu));
10640 
10641 		kvm_vcpu_srcu_read_unlock(vcpu);
10642 		kvm_vcpu_block(vcpu);
10643 		kvm_vcpu_srcu_read_lock(vcpu);
10644 
10645 		if (kvm_apic_accept_events(vcpu) < 0) {
10646 			r = 0;
10647 			goto out;
10648 		}
10649 		kvm_clear_request(KVM_REQ_UNHALT, vcpu);
10650 		r = -EAGAIN;
10651 		if (signal_pending(current)) {
10652 			r = -EINTR;
10653 			kvm_run->exit_reason = KVM_EXIT_INTR;
10654 			++vcpu->stat.signal_exits;
10655 		}
10656 		goto out;
10657 	}
10658 
10659 	if ((kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) ||
10660 	    (kvm_run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)) {
10661 		r = -EINVAL;
10662 		goto out;
10663 	}
10664 
10665 	if (kvm_run->kvm_dirty_regs) {
10666 		r = sync_regs(vcpu);
10667 		if (r != 0)
10668 			goto out;
10669 	}
10670 
10671 	/* re-sync apic's tpr */
10672 	if (!lapic_in_kernel(vcpu)) {
10673 		if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
10674 			r = -EINVAL;
10675 			goto out;
10676 		}
10677 	}
10678 
10679 	if (unlikely(vcpu->arch.complete_userspace_io)) {
10680 		int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
10681 		vcpu->arch.complete_userspace_io = NULL;
10682 		r = cui(vcpu);
10683 		if (r <= 0)
10684 			goto out;
10685 	} else
10686 		WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
10687 
10688 	if (kvm_run->immediate_exit) {
10689 		r = -EINTR;
10690 		goto out;
10691 	}
10692 
10693 	r = static_call(kvm_x86_vcpu_pre_run)(vcpu);
10694 	if (r <= 0)
10695 		goto out;
10696 
10697 	r = vcpu_run(vcpu);
10698 
10699 out:
10700 	kvm_put_guest_fpu(vcpu);
10701 	if (kvm_run->kvm_valid_regs)
10702 		store_regs(vcpu);
10703 	post_kvm_run_save(vcpu);
10704 	kvm_vcpu_srcu_read_unlock(vcpu);
10705 
10706 	kvm_sigset_deactivate(vcpu);
10707 	vcpu_put(vcpu);
10708 	return r;
10709 }
10710 
__get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)10711 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10712 {
10713 	if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
10714 		/*
10715 		 * We are here if userspace calls get_regs() in the middle of
10716 		 * instruction emulation. Registers state needs to be copied
10717 		 * back from emulation context to vcpu. Userspace shouldn't do
10718 		 * that usually, but some bad designed PV devices (vmware
10719 		 * backdoor interface) need this to work
10720 		 */
10721 		emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
10722 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
10723 	}
10724 	regs->rax = kvm_rax_read(vcpu);
10725 	regs->rbx = kvm_rbx_read(vcpu);
10726 	regs->rcx = kvm_rcx_read(vcpu);
10727 	regs->rdx = kvm_rdx_read(vcpu);
10728 	regs->rsi = kvm_rsi_read(vcpu);
10729 	regs->rdi = kvm_rdi_read(vcpu);
10730 	regs->rsp = kvm_rsp_read(vcpu);
10731 	regs->rbp = kvm_rbp_read(vcpu);
10732 #ifdef CONFIG_X86_64
10733 	regs->r8 = kvm_r8_read(vcpu);
10734 	regs->r9 = kvm_r9_read(vcpu);
10735 	regs->r10 = kvm_r10_read(vcpu);
10736 	regs->r11 = kvm_r11_read(vcpu);
10737 	regs->r12 = kvm_r12_read(vcpu);
10738 	regs->r13 = kvm_r13_read(vcpu);
10739 	regs->r14 = kvm_r14_read(vcpu);
10740 	regs->r15 = kvm_r15_read(vcpu);
10741 #endif
10742 
10743 	regs->rip = kvm_rip_read(vcpu);
10744 	regs->rflags = kvm_get_rflags(vcpu);
10745 }
10746 
kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)10747 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10748 {
10749 	vcpu_load(vcpu);
10750 	__get_regs(vcpu, regs);
10751 	vcpu_put(vcpu);
10752 	return 0;
10753 }
10754 
__set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)10755 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10756 {
10757 	vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
10758 	vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
10759 
10760 	kvm_rax_write(vcpu, regs->rax);
10761 	kvm_rbx_write(vcpu, regs->rbx);
10762 	kvm_rcx_write(vcpu, regs->rcx);
10763 	kvm_rdx_write(vcpu, regs->rdx);
10764 	kvm_rsi_write(vcpu, regs->rsi);
10765 	kvm_rdi_write(vcpu, regs->rdi);
10766 	kvm_rsp_write(vcpu, regs->rsp);
10767 	kvm_rbp_write(vcpu, regs->rbp);
10768 #ifdef CONFIG_X86_64
10769 	kvm_r8_write(vcpu, regs->r8);
10770 	kvm_r9_write(vcpu, regs->r9);
10771 	kvm_r10_write(vcpu, regs->r10);
10772 	kvm_r11_write(vcpu, regs->r11);
10773 	kvm_r12_write(vcpu, regs->r12);
10774 	kvm_r13_write(vcpu, regs->r13);
10775 	kvm_r14_write(vcpu, regs->r14);
10776 	kvm_r15_write(vcpu, regs->r15);
10777 #endif
10778 
10779 	kvm_rip_write(vcpu, regs->rip);
10780 	kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
10781 
10782 	vcpu->arch.exception.pending = false;
10783 
10784 	kvm_make_request(KVM_REQ_EVENT, vcpu);
10785 }
10786 
kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)10787 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10788 {
10789 	vcpu_load(vcpu);
10790 	__set_regs(vcpu, regs);
10791 	vcpu_put(vcpu);
10792 	return 0;
10793 }
10794 
__get_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)10795 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
10796 {
10797 	struct desc_ptr dt;
10798 
10799 	if (vcpu->arch.guest_state_protected)
10800 		goto skip_protected_regs;
10801 
10802 	kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
10803 	kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
10804 	kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
10805 	kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
10806 	kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
10807 	kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
10808 
10809 	kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
10810 	kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
10811 
10812 	static_call(kvm_x86_get_idt)(vcpu, &dt);
10813 	sregs->idt.limit = dt.size;
10814 	sregs->idt.base = dt.address;
10815 	static_call(kvm_x86_get_gdt)(vcpu, &dt);
10816 	sregs->gdt.limit = dt.size;
10817 	sregs->gdt.base = dt.address;
10818 
10819 	sregs->cr2 = vcpu->arch.cr2;
10820 	sregs->cr3 = kvm_read_cr3(vcpu);
10821 
10822 skip_protected_regs:
10823 	sregs->cr0 = kvm_read_cr0(vcpu);
10824 	sregs->cr4 = kvm_read_cr4(vcpu);
10825 	sregs->cr8 = kvm_get_cr8(vcpu);
10826 	sregs->efer = vcpu->arch.efer;
10827 	sregs->apic_base = kvm_get_apic_base(vcpu);
10828 }
10829 
__get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)10830 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
10831 {
10832 	__get_sregs_common(vcpu, sregs);
10833 
10834 	if (vcpu->arch.guest_state_protected)
10835 		return;
10836 
10837 	if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
10838 		set_bit(vcpu->arch.interrupt.nr,
10839 			(unsigned long *)sregs->interrupt_bitmap);
10840 }
10841 
__get_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)10842 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
10843 {
10844 	int i;
10845 
10846 	__get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
10847 
10848 	if (vcpu->arch.guest_state_protected)
10849 		return;
10850 
10851 	if (is_pae_paging(vcpu)) {
10852 		for (i = 0 ; i < 4 ; i++)
10853 			sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
10854 		sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
10855 	}
10856 }
10857 
kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)10858 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
10859 				  struct kvm_sregs *sregs)
10860 {
10861 	vcpu_load(vcpu);
10862 	__get_sregs(vcpu, sregs);
10863 	vcpu_put(vcpu);
10864 	return 0;
10865 }
10866 
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)10867 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
10868 				    struct kvm_mp_state *mp_state)
10869 {
10870 	int r;
10871 
10872 	vcpu_load(vcpu);
10873 	if (kvm_mpx_supported())
10874 		kvm_load_guest_fpu(vcpu);
10875 
10876 	r = kvm_apic_accept_events(vcpu);
10877 	if (r < 0)
10878 		goto out;
10879 	r = 0;
10880 
10881 	if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
10882 	     vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
10883 	    vcpu->arch.pv.pv_unhalted)
10884 		mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
10885 	else
10886 		mp_state->mp_state = vcpu->arch.mp_state;
10887 
10888 out:
10889 	if (kvm_mpx_supported())
10890 		kvm_put_guest_fpu(vcpu);
10891 	vcpu_put(vcpu);
10892 	return r;
10893 }
10894 
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)10895 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
10896 				    struct kvm_mp_state *mp_state)
10897 {
10898 	int ret = -EINVAL;
10899 
10900 	vcpu_load(vcpu);
10901 
10902 	if (!lapic_in_kernel(vcpu) &&
10903 	    mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
10904 		goto out;
10905 
10906 	/*
10907 	 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
10908 	 * INIT state; latched init should be reported using
10909 	 * KVM_SET_VCPU_EVENTS, so reject it here.
10910 	 */
10911 	if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
10912 	    (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
10913 	     mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
10914 		goto out;
10915 
10916 	if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
10917 		vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
10918 		set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
10919 	} else
10920 		vcpu->arch.mp_state = mp_state->mp_state;
10921 	kvm_make_request(KVM_REQ_EVENT, vcpu);
10922 
10923 	ret = 0;
10924 out:
10925 	vcpu_put(vcpu);
10926 	return ret;
10927 }
10928 
kvm_task_switch(struct kvm_vcpu * vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code)10929 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
10930 		    int reason, bool has_error_code, u32 error_code)
10931 {
10932 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
10933 	int ret;
10934 
10935 	init_emulate_ctxt(vcpu);
10936 
10937 	ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
10938 				   has_error_code, error_code);
10939 	if (ret) {
10940 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10941 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
10942 		vcpu->run->internal.ndata = 0;
10943 		return 0;
10944 	}
10945 
10946 	kvm_rip_write(vcpu, ctxt->eip);
10947 	kvm_set_rflags(vcpu, ctxt->eflags);
10948 	return 1;
10949 }
10950 EXPORT_SYMBOL_GPL(kvm_task_switch);
10951 
kvm_is_valid_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)10952 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
10953 {
10954 	if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
10955 		/*
10956 		 * When EFER.LME and CR0.PG are set, the processor is in
10957 		 * 64-bit mode (though maybe in a 32-bit code segment).
10958 		 * CR4.PAE and EFER.LMA must be set.
10959 		 */
10960 		if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
10961 			return false;
10962 		if (kvm_vcpu_is_illegal_gpa(vcpu, sregs->cr3))
10963 			return false;
10964 	} else {
10965 		/*
10966 		 * Not in 64-bit mode: EFER.LMA is clear and the code
10967 		 * segment cannot be 64-bit.
10968 		 */
10969 		if (sregs->efer & EFER_LMA || sregs->cs.l)
10970 			return false;
10971 	}
10972 
10973 	return kvm_is_valid_cr4(vcpu, sregs->cr4);
10974 }
10975 
__set_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs,int * mmu_reset_needed,bool update_pdptrs)10976 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
10977 		int *mmu_reset_needed, bool update_pdptrs)
10978 {
10979 	struct msr_data apic_base_msr;
10980 	int idx;
10981 	struct desc_ptr dt;
10982 
10983 	if (!kvm_is_valid_sregs(vcpu, sregs))
10984 		return -EINVAL;
10985 
10986 	apic_base_msr.data = sregs->apic_base;
10987 	apic_base_msr.host_initiated = true;
10988 	if (kvm_set_apic_base(vcpu, &apic_base_msr))
10989 		return -EINVAL;
10990 
10991 	if (vcpu->arch.guest_state_protected)
10992 		return 0;
10993 
10994 	dt.size = sregs->idt.limit;
10995 	dt.address = sregs->idt.base;
10996 	static_call(kvm_x86_set_idt)(vcpu, &dt);
10997 	dt.size = sregs->gdt.limit;
10998 	dt.address = sregs->gdt.base;
10999 	static_call(kvm_x86_set_gdt)(vcpu, &dt);
11000 
11001 	vcpu->arch.cr2 = sregs->cr2;
11002 	*mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
11003 	vcpu->arch.cr3 = sregs->cr3;
11004 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11005 	static_call_cond(kvm_x86_post_set_cr3)(vcpu, sregs->cr3);
11006 
11007 	kvm_set_cr8(vcpu, sregs->cr8);
11008 
11009 	*mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
11010 	static_call(kvm_x86_set_efer)(vcpu, sregs->efer);
11011 
11012 	*mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
11013 	static_call(kvm_x86_set_cr0)(vcpu, sregs->cr0);
11014 	vcpu->arch.cr0 = sregs->cr0;
11015 
11016 	*mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
11017 	static_call(kvm_x86_set_cr4)(vcpu, sregs->cr4);
11018 
11019 	if (update_pdptrs) {
11020 		idx = srcu_read_lock(&vcpu->kvm->srcu);
11021 		if (is_pae_paging(vcpu)) {
11022 			load_pdptrs(vcpu, kvm_read_cr3(vcpu));
11023 			*mmu_reset_needed = 1;
11024 		}
11025 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
11026 	}
11027 
11028 	kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11029 	kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11030 	kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11031 	kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11032 	kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11033 	kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11034 
11035 	kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11036 	kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11037 
11038 	update_cr8_intercept(vcpu);
11039 
11040 	/* Older userspace won't unhalt the vcpu on reset. */
11041 	if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
11042 	    sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
11043 	    !is_protmode(vcpu))
11044 		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11045 
11046 	return 0;
11047 }
11048 
__set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11049 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11050 {
11051 	int pending_vec, max_bits;
11052 	int mmu_reset_needed = 0;
11053 	int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
11054 
11055 	if (ret)
11056 		return ret;
11057 
11058 	if (mmu_reset_needed)
11059 		kvm_mmu_reset_context(vcpu);
11060 
11061 	max_bits = KVM_NR_INTERRUPTS;
11062 	pending_vec = find_first_bit(
11063 		(const unsigned long *)sregs->interrupt_bitmap, max_bits);
11064 
11065 	if (pending_vec < max_bits) {
11066 		kvm_queue_interrupt(vcpu, pending_vec, false);
11067 		pr_debug("Set back pending irq %d\n", pending_vec);
11068 		kvm_make_request(KVM_REQ_EVENT, vcpu);
11069 	}
11070 	return 0;
11071 }
11072 
__set_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)11073 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11074 {
11075 	int mmu_reset_needed = 0;
11076 	bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
11077 	bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
11078 		!(sregs2->efer & EFER_LMA);
11079 	int i, ret;
11080 
11081 	if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
11082 		return -EINVAL;
11083 
11084 	if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
11085 		return -EINVAL;
11086 
11087 	ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
11088 				 &mmu_reset_needed, !valid_pdptrs);
11089 	if (ret)
11090 		return ret;
11091 
11092 	if (valid_pdptrs) {
11093 		for (i = 0; i < 4 ; i++)
11094 			kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
11095 
11096 		kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
11097 		mmu_reset_needed = 1;
11098 		vcpu->arch.pdptrs_from_userspace = true;
11099 	}
11100 	if (mmu_reset_needed)
11101 		kvm_mmu_reset_context(vcpu);
11102 	return 0;
11103 }
11104 
kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11105 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
11106 				  struct kvm_sregs *sregs)
11107 {
11108 	int ret;
11109 
11110 	vcpu_load(vcpu);
11111 	ret = __set_sregs(vcpu, sregs);
11112 	vcpu_put(vcpu);
11113 	return ret;
11114 }
11115 
kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm * kvm)11116 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
11117 {
11118 	bool set = false;
11119 	struct kvm_vcpu *vcpu;
11120 	unsigned long i;
11121 
11122 	if (!enable_apicv)
11123 		return;
11124 
11125 	down_write(&kvm->arch.apicv_update_lock);
11126 
11127 	kvm_for_each_vcpu(i, vcpu, kvm) {
11128 		if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
11129 			set = true;
11130 			break;
11131 		}
11132 	}
11133 	__kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
11134 	up_write(&kvm->arch.apicv_update_lock);
11135 }
11136 
kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu * vcpu,struct kvm_guest_debug * dbg)11137 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
11138 					struct kvm_guest_debug *dbg)
11139 {
11140 	unsigned long rflags;
11141 	int i, r;
11142 
11143 	if (vcpu->arch.guest_state_protected)
11144 		return -EINVAL;
11145 
11146 	vcpu_load(vcpu);
11147 
11148 	if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
11149 		r = -EBUSY;
11150 		if (vcpu->arch.exception.pending)
11151 			goto out;
11152 		if (dbg->control & KVM_GUESTDBG_INJECT_DB)
11153 			kvm_queue_exception(vcpu, DB_VECTOR);
11154 		else
11155 			kvm_queue_exception(vcpu, BP_VECTOR);
11156 	}
11157 
11158 	/*
11159 	 * Read rflags as long as potentially injected trace flags are still
11160 	 * filtered out.
11161 	 */
11162 	rflags = kvm_get_rflags(vcpu);
11163 
11164 	vcpu->guest_debug = dbg->control;
11165 	if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
11166 		vcpu->guest_debug = 0;
11167 
11168 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
11169 		for (i = 0; i < KVM_NR_DB_REGS; ++i)
11170 			vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
11171 		vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
11172 	} else {
11173 		for (i = 0; i < KVM_NR_DB_REGS; i++)
11174 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
11175 	}
11176 	kvm_update_dr7(vcpu);
11177 
11178 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
11179 		vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
11180 
11181 	/*
11182 	 * Trigger an rflags update that will inject or remove the trace
11183 	 * flags.
11184 	 */
11185 	kvm_set_rflags(vcpu, rflags);
11186 
11187 	static_call(kvm_x86_update_exception_bitmap)(vcpu);
11188 
11189 	kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
11190 
11191 	r = 0;
11192 
11193 out:
11194 	vcpu_put(vcpu);
11195 	return r;
11196 }
11197 
11198 /*
11199  * Translate a guest virtual address to a guest physical address.
11200  */
kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu * vcpu,struct kvm_translation * tr)11201 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
11202 				    struct kvm_translation *tr)
11203 {
11204 	unsigned long vaddr = tr->linear_address;
11205 	gpa_t gpa;
11206 	int idx;
11207 
11208 	vcpu_load(vcpu);
11209 
11210 	idx = srcu_read_lock(&vcpu->kvm->srcu);
11211 	gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
11212 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
11213 	tr->physical_address = gpa;
11214 	tr->valid = gpa != UNMAPPED_GVA;
11215 	tr->writeable = 1;
11216 	tr->usermode = 0;
11217 
11218 	vcpu_put(vcpu);
11219 	return 0;
11220 }
11221 
kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)11222 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
11223 {
11224 	struct fxregs_state *fxsave;
11225 
11226 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
11227 		return 0;
11228 
11229 	vcpu_load(vcpu);
11230 
11231 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
11232 	memcpy(fpu->fpr, fxsave->st_space, 128);
11233 	fpu->fcw = fxsave->cwd;
11234 	fpu->fsw = fxsave->swd;
11235 	fpu->ftwx = fxsave->twd;
11236 	fpu->last_opcode = fxsave->fop;
11237 	fpu->last_ip = fxsave->rip;
11238 	fpu->last_dp = fxsave->rdp;
11239 	memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
11240 
11241 	vcpu_put(vcpu);
11242 	return 0;
11243 }
11244 
kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)11245 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
11246 {
11247 	struct fxregs_state *fxsave;
11248 
11249 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
11250 		return 0;
11251 
11252 	vcpu_load(vcpu);
11253 
11254 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
11255 
11256 	memcpy(fxsave->st_space, fpu->fpr, 128);
11257 	fxsave->cwd = fpu->fcw;
11258 	fxsave->swd = fpu->fsw;
11259 	fxsave->twd = fpu->ftwx;
11260 	fxsave->fop = fpu->last_opcode;
11261 	fxsave->rip = fpu->last_ip;
11262 	fxsave->rdp = fpu->last_dp;
11263 	memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
11264 
11265 	vcpu_put(vcpu);
11266 	return 0;
11267 }
11268 
store_regs(struct kvm_vcpu * vcpu)11269 static void store_regs(struct kvm_vcpu *vcpu)
11270 {
11271 	BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
11272 
11273 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
11274 		__get_regs(vcpu, &vcpu->run->s.regs.regs);
11275 
11276 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
11277 		__get_sregs(vcpu, &vcpu->run->s.regs.sregs);
11278 
11279 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
11280 		kvm_vcpu_ioctl_x86_get_vcpu_events(
11281 				vcpu, &vcpu->run->s.regs.events);
11282 }
11283 
sync_regs(struct kvm_vcpu * vcpu)11284 static int sync_regs(struct kvm_vcpu *vcpu)
11285 {
11286 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
11287 		__set_regs(vcpu, &vcpu->run->s.regs.regs);
11288 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
11289 	}
11290 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
11291 		if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
11292 			return -EINVAL;
11293 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
11294 	}
11295 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
11296 		if (kvm_vcpu_ioctl_x86_set_vcpu_events(
11297 				vcpu, &vcpu->run->s.regs.events))
11298 			return -EINVAL;
11299 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
11300 	}
11301 
11302 	return 0;
11303 }
11304 
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)11305 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
11306 {
11307 	if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
11308 		pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
11309 			     "guest TSC will not be reliable\n");
11310 
11311 	return 0;
11312 }
11313 
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)11314 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
11315 {
11316 	struct page *page;
11317 	int r;
11318 
11319 	vcpu->arch.last_vmentry_cpu = -1;
11320 	vcpu->arch.regs_avail = ~0;
11321 	vcpu->arch.regs_dirty = ~0;
11322 
11323 	if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
11324 		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11325 	else
11326 		vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
11327 
11328 	r = kvm_mmu_create(vcpu);
11329 	if (r < 0)
11330 		return r;
11331 
11332 	if (irqchip_in_kernel(vcpu->kvm)) {
11333 		r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
11334 		if (r < 0)
11335 			goto fail_mmu_destroy;
11336 
11337 		/*
11338 		 * Defer evaluating inhibits until the vCPU is first run, as
11339 		 * this vCPU will not get notified of any changes until this
11340 		 * vCPU is visible to other vCPUs (marked online and added to
11341 		 * the set of vCPUs).  Opportunistically mark APICv active as
11342 		 * VMX in particularly is highly unlikely to have inhibits.
11343 		 * Ignore the current per-VM APICv state so that vCPU creation
11344 		 * is guaranteed to run with a deterministic value, the request
11345 		 * will ensure the vCPU gets the correct state before VM-Entry.
11346 		 */
11347 		if (enable_apicv) {
11348 			vcpu->arch.apicv_active = true;
11349 			kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
11350 		}
11351 	} else
11352 		static_branch_inc(&kvm_has_noapic_vcpu);
11353 
11354 	r = -ENOMEM;
11355 
11356 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
11357 	if (!page)
11358 		goto fail_free_lapic;
11359 	vcpu->arch.pio_data = page_address(page);
11360 
11361 	vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
11362 				       GFP_KERNEL_ACCOUNT);
11363 	if (!vcpu->arch.mce_banks)
11364 		goto fail_free_pio_data;
11365 	vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
11366 
11367 	if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
11368 				GFP_KERNEL_ACCOUNT))
11369 		goto fail_free_mce_banks;
11370 
11371 	if (!alloc_emulate_ctxt(vcpu))
11372 		goto free_wbinvd_dirty_mask;
11373 
11374 	if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
11375 		pr_err("kvm: failed to allocate vcpu's fpu\n");
11376 		goto free_emulate_ctxt;
11377 	}
11378 
11379 	vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
11380 	vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
11381 
11382 	vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
11383 
11384 	kvm_async_pf_hash_reset(vcpu);
11385 	kvm_pmu_init(vcpu);
11386 
11387 	vcpu->arch.pending_external_vector = -1;
11388 	vcpu->arch.preempted_in_kernel = false;
11389 
11390 #if IS_ENABLED(CONFIG_HYPERV)
11391 	vcpu->arch.hv_root_tdp = INVALID_PAGE;
11392 #endif
11393 
11394 	r = static_call(kvm_x86_vcpu_create)(vcpu);
11395 	if (r)
11396 		goto free_guest_fpu;
11397 
11398 	vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
11399 	vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
11400 	kvm_xen_init_vcpu(vcpu);
11401 	kvm_vcpu_mtrr_init(vcpu);
11402 	vcpu_load(vcpu);
11403 	kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
11404 	kvm_vcpu_reset(vcpu, false);
11405 	kvm_init_mmu(vcpu);
11406 	vcpu_put(vcpu);
11407 	return 0;
11408 
11409 free_guest_fpu:
11410 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
11411 free_emulate_ctxt:
11412 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
11413 free_wbinvd_dirty_mask:
11414 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
11415 fail_free_mce_banks:
11416 	kfree(vcpu->arch.mce_banks);
11417 fail_free_pio_data:
11418 	free_page((unsigned long)vcpu->arch.pio_data);
11419 fail_free_lapic:
11420 	kvm_free_lapic(vcpu);
11421 fail_mmu_destroy:
11422 	kvm_mmu_destroy(vcpu);
11423 	return r;
11424 }
11425 
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)11426 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
11427 {
11428 	struct kvm *kvm = vcpu->kvm;
11429 
11430 	if (mutex_lock_killable(&vcpu->mutex))
11431 		return;
11432 	vcpu_load(vcpu);
11433 	kvm_synchronize_tsc(vcpu, 0);
11434 	vcpu_put(vcpu);
11435 
11436 	/* poll control enabled by default */
11437 	vcpu->arch.msr_kvm_poll_control = 1;
11438 
11439 	mutex_unlock(&vcpu->mutex);
11440 
11441 	if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
11442 		schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
11443 						KVMCLOCK_SYNC_PERIOD);
11444 }
11445 
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)11446 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
11447 {
11448 	int idx;
11449 
11450 	kvmclock_reset(vcpu);
11451 
11452 	static_call(kvm_x86_vcpu_free)(vcpu);
11453 
11454 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
11455 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
11456 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
11457 
11458 	kvm_xen_destroy_vcpu(vcpu);
11459 	kvm_hv_vcpu_uninit(vcpu);
11460 	kvm_pmu_destroy(vcpu);
11461 	kfree(vcpu->arch.mce_banks);
11462 	kvm_free_lapic(vcpu);
11463 	idx = srcu_read_lock(&vcpu->kvm->srcu);
11464 	kvm_mmu_destroy(vcpu);
11465 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
11466 	free_page((unsigned long)vcpu->arch.pio_data);
11467 	kvfree(vcpu->arch.cpuid_entries);
11468 	if (!lapic_in_kernel(vcpu))
11469 		static_branch_dec(&kvm_has_noapic_vcpu);
11470 }
11471 
kvm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)11472 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
11473 {
11474 	struct kvm_cpuid_entry2 *cpuid_0x1;
11475 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
11476 	unsigned long new_cr0;
11477 
11478 	/*
11479 	 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
11480 	 * to handle side effects.  RESET emulation hits those flows and relies
11481 	 * on emulated/virtualized registers, including those that are loaded
11482 	 * into hardware, to be zeroed at vCPU creation.  Use CRs as a sentinel
11483 	 * to detect improper or missing initialization.
11484 	 */
11485 	WARN_ON_ONCE(!init_event &&
11486 		     (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
11487 
11488 	kvm_lapic_reset(vcpu, init_event);
11489 
11490 	vcpu->arch.hflags = 0;
11491 
11492 	vcpu->arch.smi_pending = 0;
11493 	vcpu->arch.smi_count = 0;
11494 	atomic_set(&vcpu->arch.nmi_queued, 0);
11495 	vcpu->arch.nmi_pending = 0;
11496 	vcpu->arch.nmi_injected = false;
11497 	kvm_clear_interrupt_queue(vcpu);
11498 	kvm_clear_exception_queue(vcpu);
11499 
11500 	memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
11501 	kvm_update_dr0123(vcpu);
11502 	vcpu->arch.dr6 = DR6_ACTIVE_LOW;
11503 	vcpu->arch.dr7 = DR7_FIXED_1;
11504 	kvm_update_dr7(vcpu);
11505 
11506 	vcpu->arch.cr2 = 0;
11507 
11508 	kvm_make_request(KVM_REQ_EVENT, vcpu);
11509 	vcpu->arch.apf.msr_en_val = 0;
11510 	vcpu->arch.apf.msr_int_val = 0;
11511 	vcpu->arch.st.msr_val = 0;
11512 
11513 	kvmclock_reset(vcpu);
11514 
11515 	kvm_clear_async_pf_completion_queue(vcpu);
11516 	kvm_async_pf_hash_reset(vcpu);
11517 	vcpu->arch.apf.halted = false;
11518 
11519 	if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
11520 		struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
11521 
11522 		/*
11523 		 * To avoid have the INIT path from kvm_apic_has_events() that be
11524 		 * called with loaded FPU and does not let userspace fix the state.
11525 		 */
11526 		if (init_event)
11527 			kvm_put_guest_fpu(vcpu);
11528 
11529 		fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
11530 		fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
11531 
11532 		if (init_event)
11533 			kvm_load_guest_fpu(vcpu);
11534 	}
11535 
11536 	if (!init_event) {
11537 		kvm_pmu_reset(vcpu);
11538 		vcpu->arch.smbase = 0x30000;
11539 
11540 		vcpu->arch.msr_misc_features_enables = 0;
11541 
11542 		__kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
11543 		__kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
11544 	}
11545 
11546 	/* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
11547 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
11548 	kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
11549 
11550 	/*
11551 	 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
11552 	 * if no CPUID match is found.  Note, it's impossible to get a match at
11553 	 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
11554 	 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
11555 	 * on RESET.  But, go through the motions in case that's ever remedied.
11556 	 */
11557 	cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1, 0);
11558 	kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
11559 
11560 	static_call(kvm_x86_vcpu_reset)(vcpu, init_event);
11561 
11562 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
11563 	kvm_rip_write(vcpu, 0xfff0);
11564 
11565 	vcpu->arch.cr3 = 0;
11566 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11567 
11568 	/*
11569 	 * CR0.CD/NW are set on RESET, preserved on INIT.  Note, some versions
11570 	 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
11571 	 * (or qualify) that with a footnote stating that CD/NW are preserved.
11572 	 */
11573 	new_cr0 = X86_CR0_ET;
11574 	if (init_event)
11575 		new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
11576 	else
11577 		new_cr0 |= X86_CR0_NW | X86_CR0_CD;
11578 
11579 	static_call(kvm_x86_set_cr0)(vcpu, new_cr0);
11580 	static_call(kvm_x86_set_cr4)(vcpu, 0);
11581 	static_call(kvm_x86_set_efer)(vcpu, 0);
11582 	static_call(kvm_x86_update_exception_bitmap)(vcpu);
11583 
11584 	/*
11585 	 * On the standard CR0/CR4/EFER modification paths, there are several
11586 	 * complex conditions determining whether the MMU has to be reset and/or
11587 	 * which PCIDs have to be flushed.  However, CR0.WP and the paging-related
11588 	 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
11589 	 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
11590 	 * CR0 will be '0' prior to RESET).  So we only need to check CR0.PG here.
11591 	 */
11592 	if (old_cr0 & X86_CR0_PG) {
11593 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
11594 		kvm_mmu_reset_context(vcpu);
11595 	}
11596 
11597 	/*
11598 	 * Intel's SDM states that all TLB entries are flushed on INIT.  AMD's
11599 	 * APM states the TLBs are untouched by INIT, but it also states that
11600 	 * the TLBs are flushed on "External initialization of the processor."
11601 	 * Flush the guest TLB regardless of vendor, there is no meaningful
11602 	 * benefit in relying on the guest to flush the TLB immediately after
11603 	 * INIT.  A spurious TLB flush is benign and likely negligible from a
11604 	 * performance perspective.
11605 	 */
11606 	if (init_event)
11607 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
11608 }
11609 EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
11610 
kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)11611 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
11612 {
11613 	struct kvm_segment cs;
11614 
11615 	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
11616 	cs.selector = vector << 8;
11617 	cs.base = vector << 12;
11618 	kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
11619 	kvm_rip_write(vcpu, 0);
11620 }
11621 EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
11622 
kvm_arch_hardware_enable(void)11623 int kvm_arch_hardware_enable(void)
11624 {
11625 	struct kvm *kvm;
11626 	struct kvm_vcpu *vcpu;
11627 	unsigned long i;
11628 	int ret;
11629 	u64 local_tsc;
11630 	u64 max_tsc = 0;
11631 	bool stable, backwards_tsc = false;
11632 
11633 	kvm_user_return_msr_cpu_online();
11634 	ret = static_call(kvm_x86_hardware_enable)();
11635 	if (ret != 0)
11636 		return ret;
11637 
11638 	local_tsc = rdtsc();
11639 	stable = !kvm_check_tsc_unstable();
11640 	list_for_each_entry(kvm, &vm_list, vm_list) {
11641 		kvm_for_each_vcpu(i, vcpu, kvm) {
11642 			if (!stable && vcpu->cpu == smp_processor_id())
11643 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11644 			if (stable && vcpu->arch.last_host_tsc > local_tsc) {
11645 				backwards_tsc = true;
11646 				if (vcpu->arch.last_host_tsc > max_tsc)
11647 					max_tsc = vcpu->arch.last_host_tsc;
11648 			}
11649 		}
11650 	}
11651 
11652 	/*
11653 	 * Sometimes, even reliable TSCs go backwards.  This happens on
11654 	 * platforms that reset TSC during suspend or hibernate actions, but
11655 	 * maintain synchronization.  We must compensate.  Fortunately, we can
11656 	 * detect that condition here, which happens early in CPU bringup,
11657 	 * before any KVM threads can be running.  Unfortunately, we can't
11658 	 * bring the TSCs fully up to date with real time, as we aren't yet far
11659 	 * enough into CPU bringup that we know how much real time has actually
11660 	 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
11661 	 * variables that haven't been updated yet.
11662 	 *
11663 	 * So we simply find the maximum observed TSC above, then record the
11664 	 * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
11665 	 * the adjustment will be applied.  Note that we accumulate
11666 	 * adjustments, in case multiple suspend cycles happen before some VCPU
11667 	 * gets a chance to run again.  In the event that no KVM threads get a
11668 	 * chance to run, we will miss the entire elapsed period, as we'll have
11669 	 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
11670 	 * loose cycle time.  This isn't too big a deal, since the loss will be
11671 	 * uniform across all VCPUs (not to mention the scenario is extremely
11672 	 * unlikely). It is possible that a second hibernate recovery happens
11673 	 * much faster than a first, causing the observed TSC here to be
11674 	 * smaller; this would require additional padding adjustment, which is
11675 	 * why we set last_host_tsc to the local tsc observed here.
11676 	 *
11677 	 * N.B. - this code below runs only on platforms with reliable TSC,
11678 	 * as that is the only way backwards_tsc is set above.  Also note
11679 	 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
11680 	 * have the same delta_cyc adjustment applied if backwards_tsc
11681 	 * is detected.  Note further, this adjustment is only done once,
11682 	 * as we reset last_host_tsc on all VCPUs to stop this from being
11683 	 * called multiple times (one for each physical CPU bringup).
11684 	 *
11685 	 * Platforms with unreliable TSCs don't have to deal with this, they
11686 	 * will be compensated by the logic in vcpu_load, which sets the TSC to
11687 	 * catchup mode.  This will catchup all VCPUs to real time, but cannot
11688 	 * guarantee that they stay in perfect synchronization.
11689 	 */
11690 	if (backwards_tsc) {
11691 		u64 delta_cyc = max_tsc - local_tsc;
11692 		list_for_each_entry(kvm, &vm_list, vm_list) {
11693 			kvm->arch.backwards_tsc_observed = true;
11694 			kvm_for_each_vcpu(i, vcpu, kvm) {
11695 				vcpu->arch.tsc_offset_adjustment += delta_cyc;
11696 				vcpu->arch.last_host_tsc = local_tsc;
11697 				kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
11698 			}
11699 
11700 			/*
11701 			 * We have to disable TSC offset matching.. if you were
11702 			 * booting a VM while issuing an S4 host suspend....
11703 			 * you may have some problem.  Solving this issue is
11704 			 * left as an exercise to the reader.
11705 			 */
11706 			kvm->arch.last_tsc_nsec = 0;
11707 			kvm->arch.last_tsc_write = 0;
11708 		}
11709 
11710 	}
11711 	return 0;
11712 }
11713 
kvm_arch_hardware_disable(void)11714 void kvm_arch_hardware_disable(void)
11715 {
11716 	static_call(kvm_x86_hardware_disable)();
11717 	drop_user_return_notifiers();
11718 }
11719 
kvm_ops_update(struct kvm_x86_init_ops * ops)11720 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
11721 {
11722 	memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
11723 
11724 #define __KVM_X86_OP(func) \
11725 	static_call_update(kvm_x86_##func, kvm_x86_ops.func);
11726 #define KVM_X86_OP(func) \
11727 	WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
11728 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
11729 #define KVM_X86_OP_OPTIONAL_RET0(func) \
11730 	static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
11731 					   (void *)__static_call_return0);
11732 #include <asm/kvm-x86-ops.h>
11733 #undef __KVM_X86_OP
11734 
11735 	kvm_pmu_ops_update(ops->pmu_ops);
11736 }
11737 
kvm_arch_hardware_setup(void * opaque)11738 int kvm_arch_hardware_setup(void *opaque)
11739 {
11740 	struct kvm_x86_init_ops *ops = opaque;
11741 	int r;
11742 
11743 	rdmsrl_safe(MSR_EFER, &host_efer);
11744 
11745 	if (boot_cpu_has(X86_FEATURE_XSAVES))
11746 		rdmsrl(MSR_IA32_XSS, host_xss);
11747 
11748 	r = ops->hardware_setup();
11749 	if (r != 0)
11750 		return r;
11751 
11752 	kvm_ops_update(ops);
11753 
11754 	kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
11755 
11756 	if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
11757 		supported_xss = 0;
11758 
11759 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
11760 	cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
11761 #undef __kvm_cpu_cap_has
11762 
11763 	if (kvm_has_tsc_control) {
11764 		/*
11765 		 * Make sure the user can only configure tsc_khz values that
11766 		 * fit into a signed integer.
11767 		 * A min value is not calculated because it will always
11768 		 * be 1 on all machines.
11769 		 */
11770 		u64 max = min(0x7fffffffULL,
11771 			      __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
11772 		kvm_max_guest_tsc_khz = max;
11773 	}
11774 	kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
11775 	kvm_init_msr_list();
11776 	return 0;
11777 }
11778 
kvm_arch_hardware_unsetup(void)11779 void kvm_arch_hardware_unsetup(void)
11780 {
11781 	kvm_unregister_perf_callbacks();
11782 
11783 	static_call(kvm_x86_hardware_unsetup)();
11784 }
11785 
kvm_arch_check_processor_compat(void * opaque)11786 int kvm_arch_check_processor_compat(void *opaque)
11787 {
11788 	struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
11789 	struct kvm_x86_init_ops *ops = opaque;
11790 
11791 	WARN_ON(!irqs_disabled());
11792 
11793 	if (__cr4_reserved_bits(cpu_has, c) !=
11794 	    __cr4_reserved_bits(cpu_has, &boot_cpu_data))
11795 		return -EIO;
11796 
11797 	return ops->check_processor_compatibility();
11798 }
11799 
kvm_vcpu_is_reset_bsp(struct kvm_vcpu * vcpu)11800 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
11801 {
11802 	return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
11803 }
11804 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
11805 
kvm_vcpu_is_bsp(struct kvm_vcpu * vcpu)11806 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
11807 {
11808 	return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
11809 }
11810 
11811 __read_mostly DEFINE_STATIC_KEY_FALSE(kvm_has_noapic_vcpu);
11812 EXPORT_SYMBOL_GPL(kvm_has_noapic_vcpu);
11813 
kvm_arch_sched_in(struct kvm_vcpu * vcpu,int cpu)11814 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
11815 {
11816 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
11817 
11818 	vcpu->arch.l1tf_flush_l1d = true;
11819 	if (pmu->version && unlikely(pmu->event_count)) {
11820 		pmu->need_cleanup = true;
11821 		kvm_make_request(KVM_REQ_PMU, vcpu);
11822 	}
11823 	static_call(kvm_x86_sched_in)(vcpu, cpu);
11824 }
11825 
kvm_arch_free_vm(struct kvm * kvm)11826 void kvm_arch_free_vm(struct kvm *kvm)
11827 {
11828 	kfree(to_kvm_hv(kvm)->hv_pa_pg);
11829 	__kvm_arch_free_vm(kvm);
11830 }
11831 
11832 
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)11833 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
11834 {
11835 	int ret;
11836 	unsigned long flags;
11837 
11838 	if (type)
11839 		return -EINVAL;
11840 
11841 	ret = kvm_page_track_init(kvm);
11842 	if (ret)
11843 		goto out;
11844 
11845 	ret = kvm_mmu_init_vm(kvm);
11846 	if (ret)
11847 		goto out_page_track;
11848 
11849 	INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
11850 	INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
11851 	atomic_set(&kvm->arch.noncoherent_dma_count, 0);
11852 
11853 	/* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
11854 	set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
11855 	/* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
11856 	set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
11857 		&kvm->arch.irq_sources_bitmap);
11858 
11859 	raw_spin_lock_init(&kvm->arch.tsc_write_lock);
11860 	mutex_init(&kvm->arch.apic_map_lock);
11861 	seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
11862 	kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
11863 
11864 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
11865 	pvclock_update_vm_gtod_copy(kvm);
11866 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
11867 
11868 	kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
11869 	kvm->arch.guest_can_read_msr_platform_info = true;
11870 	kvm->arch.enable_pmu = enable_pmu;
11871 
11872 #if IS_ENABLED(CONFIG_HYPERV)
11873 	spin_lock_init(&kvm->arch.hv_root_tdp_lock);
11874 	kvm->arch.hv_root_tdp = INVALID_PAGE;
11875 #endif
11876 
11877 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
11878 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
11879 
11880 	kvm_apicv_init(kvm);
11881 	kvm_hv_init_vm(kvm);
11882 	kvm_xen_init_vm(kvm);
11883 
11884 	return static_call(kvm_x86_vm_init)(kvm);
11885 
11886 out_page_track:
11887 	kvm_page_track_cleanup(kvm);
11888 out:
11889 	return ret;
11890 }
11891 
kvm_arch_post_init_vm(struct kvm * kvm)11892 int kvm_arch_post_init_vm(struct kvm *kvm)
11893 {
11894 	return kvm_mmu_post_init_vm(kvm);
11895 }
11896 
kvm_unload_vcpu_mmu(struct kvm_vcpu * vcpu)11897 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
11898 {
11899 	vcpu_load(vcpu);
11900 	kvm_mmu_unload(vcpu);
11901 	vcpu_put(vcpu);
11902 }
11903 
kvm_unload_vcpu_mmus(struct kvm * kvm)11904 static void kvm_unload_vcpu_mmus(struct kvm *kvm)
11905 {
11906 	unsigned long i;
11907 	struct kvm_vcpu *vcpu;
11908 
11909 	kvm_for_each_vcpu(i, vcpu, kvm) {
11910 		kvm_clear_async_pf_completion_queue(vcpu);
11911 		kvm_unload_vcpu_mmu(vcpu);
11912 	}
11913 }
11914 
kvm_arch_sync_events(struct kvm * kvm)11915 void kvm_arch_sync_events(struct kvm *kvm)
11916 {
11917 	cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
11918 	cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
11919 	kvm_free_pit(kvm);
11920 }
11921 
11922 /**
11923  * __x86_set_memory_region: Setup KVM internal memory slot
11924  *
11925  * @kvm: the kvm pointer to the VM.
11926  * @id: the slot ID to setup.
11927  * @gpa: the GPA to install the slot (unused when @size == 0).
11928  * @size: the size of the slot. Set to zero to uninstall a slot.
11929  *
11930  * This function helps to setup a KVM internal memory slot.  Specify
11931  * @size > 0 to install a new slot, while @size == 0 to uninstall a
11932  * slot.  The return code can be one of the following:
11933  *
11934  *   HVA:           on success (uninstall will return a bogus HVA)
11935  *   -errno:        on error
11936  *
11937  * The caller should always use IS_ERR() to check the return value
11938  * before use.  Note, the KVM internal memory slots are guaranteed to
11939  * remain valid and unchanged until the VM is destroyed, i.e., the
11940  * GPA->HVA translation will not change.  However, the HVA is a user
11941  * address, i.e. its accessibility is not guaranteed, and must be
11942  * accessed via __copy_{to,from}_user().
11943  */
__x86_set_memory_region(struct kvm * kvm,int id,gpa_t gpa,u32 size)11944 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
11945 				      u32 size)
11946 {
11947 	int i, r;
11948 	unsigned long hva, old_npages;
11949 	struct kvm_memslots *slots = kvm_memslots(kvm);
11950 	struct kvm_memory_slot *slot;
11951 
11952 	/* Called with kvm->slots_lock held.  */
11953 	if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
11954 		return ERR_PTR_USR(-EINVAL);
11955 
11956 	slot = id_to_memslot(slots, id);
11957 	if (size) {
11958 		if (slot && slot->npages)
11959 			return ERR_PTR_USR(-EEXIST);
11960 
11961 		/*
11962 		 * MAP_SHARED to prevent internal slot pages from being moved
11963 		 * by fork()/COW.
11964 		 */
11965 		hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
11966 			      MAP_SHARED | MAP_ANONYMOUS, 0);
11967 		if (IS_ERR((void *)hva))
11968 			return (void __user *)hva;
11969 	} else {
11970 		if (!slot || !slot->npages)
11971 			return NULL;
11972 
11973 		old_npages = slot->npages;
11974 		hva = slot->userspace_addr;
11975 	}
11976 
11977 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
11978 		struct kvm_userspace_memory_region m;
11979 
11980 		m.slot = id | (i << 16);
11981 		m.flags = 0;
11982 		m.guest_phys_addr = gpa;
11983 		m.userspace_addr = hva;
11984 		m.memory_size = size;
11985 		r = __kvm_set_memory_region(kvm, &m);
11986 		if (r < 0)
11987 			return ERR_PTR_USR(r);
11988 	}
11989 
11990 	if (!size)
11991 		vm_munmap(hva, old_npages * PAGE_SIZE);
11992 
11993 	return (void __user *)hva;
11994 }
11995 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
11996 
kvm_arch_pre_destroy_vm(struct kvm * kvm)11997 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
11998 {
11999 	kvm_mmu_pre_destroy_vm(kvm);
12000 }
12001 
kvm_arch_destroy_vm(struct kvm * kvm)12002 void kvm_arch_destroy_vm(struct kvm *kvm)
12003 {
12004 	if (current->mm == kvm->mm) {
12005 		/*
12006 		 * Free memory regions allocated on behalf of userspace,
12007 		 * unless the memory map has changed due to process exit
12008 		 * or fd copying.
12009 		 */
12010 		mutex_lock(&kvm->slots_lock);
12011 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
12012 					0, 0);
12013 		__x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
12014 					0, 0);
12015 		__x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
12016 		mutex_unlock(&kvm->slots_lock);
12017 	}
12018 	kvm_unload_vcpu_mmus(kvm);
12019 	static_call_cond(kvm_x86_vm_destroy)(kvm);
12020 	kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
12021 	kvm_pic_destroy(kvm);
12022 	kvm_ioapic_destroy(kvm);
12023 	kvm_destroy_vcpus(kvm);
12024 	kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
12025 	kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
12026 	kvm_mmu_uninit_vm(kvm);
12027 	kvm_page_track_cleanup(kvm);
12028 	kvm_xen_destroy_vm(kvm);
12029 	kvm_hv_destroy_vm(kvm);
12030 }
12031 
memslot_rmap_free(struct kvm_memory_slot * slot)12032 static void memslot_rmap_free(struct kvm_memory_slot *slot)
12033 {
12034 	int i;
12035 
12036 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12037 		kvfree(slot->arch.rmap[i]);
12038 		slot->arch.rmap[i] = NULL;
12039 	}
12040 }
12041 
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)12042 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
12043 {
12044 	int i;
12045 
12046 	memslot_rmap_free(slot);
12047 
12048 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12049 		kvfree(slot->arch.lpage_info[i - 1]);
12050 		slot->arch.lpage_info[i - 1] = NULL;
12051 	}
12052 
12053 	kvm_page_track_free_memslot(slot);
12054 }
12055 
memslot_rmap_alloc(struct kvm_memory_slot * slot,unsigned long npages)12056 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
12057 {
12058 	const int sz = sizeof(*slot->arch.rmap[0]);
12059 	int i;
12060 
12061 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12062 		int level = i + 1;
12063 		int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12064 
12065 		if (slot->arch.rmap[i])
12066 			continue;
12067 
12068 		slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
12069 		if (!slot->arch.rmap[i]) {
12070 			memslot_rmap_free(slot);
12071 			return -ENOMEM;
12072 		}
12073 	}
12074 
12075 	return 0;
12076 }
12077 
kvm_alloc_memslot_metadata(struct kvm * kvm,struct kvm_memory_slot * slot)12078 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
12079 				      struct kvm_memory_slot *slot)
12080 {
12081 	unsigned long npages = slot->npages;
12082 	int i, r;
12083 
12084 	/*
12085 	 * Clear out the previous array pointers for the KVM_MR_MOVE case.  The
12086 	 * old arrays will be freed by __kvm_set_memory_region() if installing
12087 	 * the new memslot is successful.
12088 	 */
12089 	memset(&slot->arch, 0, sizeof(slot->arch));
12090 
12091 	if (kvm_memslots_have_rmaps(kvm)) {
12092 		r = memslot_rmap_alloc(slot, npages);
12093 		if (r)
12094 			return r;
12095 	}
12096 
12097 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12098 		struct kvm_lpage_info *linfo;
12099 		unsigned long ugfn;
12100 		int lpages;
12101 		int level = i + 1;
12102 
12103 		lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12104 
12105 		linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
12106 		if (!linfo)
12107 			goto out_free;
12108 
12109 		slot->arch.lpage_info[i - 1] = linfo;
12110 
12111 		if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
12112 			linfo[0].disallow_lpage = 1;
12113 		if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
12114 			linfo[lpages - 1].disallow_lpage = 1;
12115 		ugfn = slot->userspace_addr >> PAGE_SHIFT;
12116 		/*
12117 		 * If the gfn and userspace address are not aligned wrt each
12118 		 * other, disable large page support for this slot.
12119 		 */
12120 		if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
12121 			unsigned long j;
12122 
12123 			for (j = 0; j < lpages; ++j)
12124 				linfo[j].disallow_lpage = 1;
12125 		}
12126 	}
12127 
12128 	if (kvm_page_track_create_memslot(kvm, slot, npages))
12129 		goto out_free;
12130 
12131 	return 0;
12132 
12133 out_free:
12134 	memslot_rmap_free(slot);
12135 
12136 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12137 		kvfree(slot->arch.lpage_info[i - 1]);
12138 		slot->arch.lpage_info[i - 1] = NULL;
12139 	}
12140 	return -ENOMEM;
12141 }
12142 
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)12143 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
12144 {
12145 	struct kvm_vcpu *vcpu;
12146 	unsigned long i;
12147 
12148 	/*
12149 	 * memslots->generation has been incremented.
12150 	 * mmio generation may have reached its maximum value.
12151 	 */
12152 	kvm_mmu_invalidate_mmio_sptes(kvm, gen);
12153 
12154 	/* Force re-initialization of steal_time cache */
12155 	kvm_for_each_vcpu(i, vcpu, kvm)
12156 		kvm_vcpu_kick(vcpu);
12157 }
12158 
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)12159 int kvm_arch_prepare_memory_region(struct kvm *kvm,
12160 				   const struct kvm_memory_slot *old,
12161 				   struct kvm_memory_slot *new,
12162 				   enum kvm_mr_change change)
12163 {
12164 	if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
12165 		if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
12166 			return -EINVAL;
12167 
12168 		return kvm_alloc_memslot_metadata(kvm, new);
12169 	}
12170 
12171 	if (change == KVM_MR_FLAGS_ONLY)
12172 		memcpy(&new->arch, &old->arch, sizeof(old->arch));
12173 	else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
12174 		return -EIO;
12175 
12176 	return 0;
12177 }
12178 
12179 
kvm_mmu_update_cpu_dirty_logging(struct kvm * kvm,bool enable)12180 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
12181 {
12182 	struct kvm_arch *ka = &kvm->arch;
12183 
12184 	if (!kvm_x86_ops.cpu_dirty_log_size)
12185 		return;
12186 
12187 	if ((enable && ++ka->cpu_dirty_logging_count == 1) ||
12188 	    (!enable && --ka->cpu_dirty_logging_count == 0))
12189 		kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
12190 
12191 	WARN_ON_ONCE(ka->cpu_dirty_logging_count < 0);
12192 }
12193 
kvm_mmu_slot_apply_flags(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)12194 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
12195 				     struct kvm_memory_slot *old,
12196 				     const struct kvm_memory_slot *new,
12197 				     enum kvm_mr_change change)
12198 {
12199 	u32 old_flags = old ? old->flags : 0;
12200 	u32 new_flags = new ? new->flags : 0;
12201 	bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
12202 
12203 	/*
12204 	 * Update CPU dirty logging if dirty logging is being toggled.  This
12205 	 * applies to all operations.
12206 	 */
12207 	if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
12208 		kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
12209 
12210 	/*
12211 	 * Nothing more to do for RO slots (which can't be dirtied and can't be
12212 	 * made writable) or CREATE/MOVE/DELETE of a slot.
12213 	 *
12214 	 * For a memslot with dirty logging disabled:
12215 	 * CREATE:      No dirty mappings will already exist.
12216 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
12217 	 *		kvm_arch_flush_shadow_memslot()
12218 	 *
12219 	 * For a memslot with dirty logging enabled:
12220 	 * CREATE:      No shadow pages exist, thus nothing to write-protect
12221 	 *		and no dirty bits to clear.
12222 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
12223 	 *		kvm_arch_flush_shadow_memslot().
12224 	 */
12225 	if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
12226 		return;
12227 
12228 	/*
12229 	 * READONLY and non-flags changes were filtered out above, and the only
12230 	 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
12231 	 * logging isn't being toggled on or off.
12232 	 */
12233 	if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
12234 		return;
12235 
12236 	if (!log_dirty_pages) {
12237 		/*
12238 		 * Dirty logging tracks sptes in 4k granularity, meaning that
12239 		 * large sptes have to be split.  If live migration succeeds,
12240 		 * the guest in the source machine will be destroyed and large
12241 		 * sptes will be created in the destination.  However, if the
12242 		 * guest continues to run in the source machine (for example if
12243 		 * live migration fails), small sptes will remain around and
12244 		 * cause bad performance.
12245 		 *
12246 		 * Scan sptes if dirty logging has been stopped, dropping those
12247 		 * which can be collapsed into a single large-page spte.  Later
12248 		 * page faults will create the large-page sptes.
12249 		 */
12250 		kvm_mmu_zap_collapsible_sptes(kvm, new);
12251 	} else {
12252 		/*
12253 		 * Initially-all-set does not require write protecting any page,
12254 		 * because they're all assumed to be dirty.
12255 		 */
12256 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
12257 			return;
12258 
12259 		if (READ_ONCE(eager_page_split))
12260 			kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
12261 
12262 		if (kvm_x86_ops.cpu_dirty_log_size) {
12263 			kvm_mmu_slot_leaf_clear_dirty(kvm, new);
12264 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
12265 		} else {
12266 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
12267 		}
12268 
12269 		/*
12270 		 * Unconditionally flush the TLBs after enabling dirty logging.
12271 		 * A flush is almost always going to be necessary (see below),
12272 		 * and unconditionally flushing allows the helpers to omit
12273 		 * the subtly complex checks when removing write access.
12274 		 *
12275 		 * Do the flush outside of mmu_lock to reduce the amount of
12276 		 * time mmu_lock is held.  Flushing after dropping mmu_lock is
12277 		 * safe as KVM only needs to guarantee the slot is fully
12278 		 * write-protected before returning to userspace, i.e. before
12279 		 * userspace can consume the dirty status.
12280 		 *
12281 		 * Flushing outside of mmu_lock requires KVM to be careful when
12282 		 * making decisions based on writable status of an SPTE, e.g. a
12283 		 * !writable SPTE doesn't guarantee a CPU can't perform writes.
12284 		 *
12285 		 * Specifically, KVM also write-protects guest page tables to
12286 		 * monitor changes when using shadow paging, and must guarantee
12287 		 * no CPUs can write to those page before mmu_lock is dropped.
12288 		 * Because CPUs may have stale TLB entries at this point, a
12289 		 * !writable SPTE doesn't guarantee CPUs can't perform writes.
12290 		 *
12291 		 * KVM also allows making SPTES writable outside of mmu_lock,
12292 		 * e.g. to allow dirty logging without taking mmu_lock.
12293 		 *
12294 		 * To handle these scenarios, KVM uses a separate software-only
12295 		 * bit (MMU-writable) to track if a SPTE is !writable due to
12296 		 * a guest page table being write-protected (KVM clears the
12297 		 * MMU-writable flag when write-protecting for shadow paging).
12298 		 *
12299 		 * The use of MMU-writable is also the primary motivation for
12300 		 * the unconditional flush.  Because KVM must guarantee that a
12301 		 * CPU doesn't contain stale, writable TLB entries for a
12302 		 * !MMU-writable SPTE, KVM must flush if it encounters any
12303 		 * MMU-writable SPTE regardless of whether the actual hardware
12304 		 * writable bit was set.  I.e. KVM is almost guaranteed to need
12305 		 * to flush, while unconditionally flushing allows the "remove
12306 		 * write access" helpers to ignore MMU-writable entirely.
12307 		 *
12308 		 * See is_writable_pte() for more details (the case involving
12309 		 * access-tracked SPTEs is particularly relevant).
12310 		 */
12311 		kvm_arch_flush_remote_tlbs_memslot(kvm, new);
12312 	}
12313 }
12314 
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)12315 void kvm_arch_commit_memory_region(struct kvm *kvm,
12316 				struct kvm_memory_slot *old,
12317 				const struct kvm_memory_slot *new,
12318 				enum kvm_mr_change change)
12319 {
12320 	if (!kvm->arch.n_requested_mmu_pages &&
12321 	    (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
12322 		unsigned long nr_mmu_pages;
12323 
12324 		nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
12325 		nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
12326 		kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
12327 	}
12328 
12329 	kvm_mmu_slot_apply_flags(kvm, old, new, change);
12330 
12331 	/* Free the arrays associated with the old memslot. */
12332 	if (change == KVM_MR_MOVE)
12333 		kvm_arch_free_memslot(kvm, old);
12334 }
12335 
kvm_arch_flush_shadow_all(struct kvm * kvm)12336 void kvm_arch_flush_shadow_all(struct kvm *kvm)
12337 {
12338 	kvm_mmu_zap_all(kvm);
12339 }
12340 
kvm_arch_flush_shadow_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)12341 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
12342 				   struct kvm_memory_slot *slot)
12343 {
12344 	kvm_page_track_flush_slot(kvm, slot);
12345 }
12346 
kvm_guest_apic_has_interrupt(struct kvm_vcpu * vcpu)12347 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
12348 {
12349 	return (is_guest_mode(vcpu) &&
12350 		static_call(kvm_x86_guest_apic_has_interrupt)(vcpu));
12351 }
12352 
kvm_vcpu_has_events(struct kvm_vcpu * vcpu)12353 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
12354 {
12355 	if (!list_empty_careful(&vcpu->async_pf.done))
12356 		return true;
12357 
12358 	if (kvm_apic_has_events(vcpu))
12359 		return true;
12360 
12361 	if (vcpu->arch.pv.pv_unhalted)
12362 		return true;
12363 
12364 	if (vcpu->arch.exception.pending)
12365 		return true;
12366 
12367 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
12368 	    (vcpu->arch.nmi_pending &&
12369 	     static_call(kvm_x86_nmi_allowed)(vcpu, false)))
12370 		return true;
12371 
12372 	if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
12373 	    (vcpu->arch.smi_pending &&
12374 	     static_call(kvm_x86_smi_allowed)(vcpu, false)))
12375 		return true;
12376 
12377 	if (kvm_arch_interrupt_allowed(vcpu) &&
12378 	    (kvm_cpu_has_interrupt(vcpu) ||
12379 	    kvm_guest_apic_has_interrupt(vcpu)))
12380 		return true;
12381 
12382 	if (kvm_hv_has_stimer_pending(vcpu))
12383 		return true;
12384 
12385 	if (is_guest_mode(vcpu) &&
12386 	    kvm_x86_ops.nested_ops->hv_timer_pending &&
12387 	    kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
12388 		return true;
12389 
12390 	if (kvm_xen_has_pending_events(vcpu))
12391 		return true;
12392 
12393 	if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu))
12394 		return true;
12395 
12396 	return false;
12397 }
12398 
kvm_arch_vcpu_runnable(struct kvm_vcpu * vcpu)12399 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
12400 {
12401 	return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
12402 }
12403 
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)12404 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
12405 {
12406 	if (vcpu->arch.apicv_active && static_call(kvm_x86_dy_apicv_has_pending_interrupt)(vcpu))
12407 		return true;
12408 
12409 	return false;
12410 }
12411 
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)12412 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
12413 {
12414 	if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
12415 		return true;
12416 
12417 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
12418 		kvm_test_request(KVM_REQ_SMI, vcpu) ||
12419 		 kvm_test_request(KVM_REQ_EVENT, vcpu))
12420 		return true;
12421 
12422 	return kvm_arch_dy_has_pending_interrupt(vcpu);
12423 }
12424 
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)12425 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
12426 {
12427 	if (vcpu->arch.guest_state_protected)
12428 		return true;
12429 
12430 	return vcpu->arch.preempted_in_kernel;
12431 }
12432 
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)12433 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
12434 {
12435 	return kvm_rip_read(vcpu);
12436 }
12437 
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)12438 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
12439 {
12440 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
12441 }
12442 
kvm_arch_interrupt_allowed(struct kvm_vcpu * vcpu)12443 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
12444 {
12445 	return static_call(kvm_x86_interrupt_allowed)(vcpu, false);
12446 }
12447 
kvm_get_linear_rip(struct kvm_vcpu * vcpu)12448 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
12449 {
12450 	/* Can't read the RIP when guest state is protected, just return 0 */
12451 	if (vcpu->arch.guest_state_protected)
12452 		return 0;
12453 
12454 	if (is_64_bit_mode(vcpu))
12455 		return kvm_rip_read(vcpu);
12456 	return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
12457 		     kvm_rip_read(vcpu));
12458 }
12459 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
12460 
kvm_is_linear_rip(struct kvm_vcpu * vcpu,unsigned long linear_rip)12461 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
12462 {
12463 	return kvm_get_linear_rip(vcpu) == linear_rip;
12464 }
12465 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
12466 
kvm_get_rflags(struct kvm_vcpu * vcpu)12467 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
12468 {
12469 	unsigned long rflags;
12470 
12471 	rflags = static_call(kvm_x86_get_rflags)(vcpu);
12472 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12473 		rflags &= ~X86_EFLAGS_TF;
12474 	return rflags;
12475 }
12476 EXPORT_SYMBOL_GPL(kvm_get_rflags);
12477 
__kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)12478 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
12479 {
12480 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
12481 	    kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
12482 		rflags |= X86_EFLAGS_TF;
12483 	static_call(kvm_x86_set_rflags)(vcpu, rflags);
12484 }
12485 
kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)12486 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
12487 {
12488 	__kvm_set_rflags(vcpu, rflags);
12489 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12490 }
12491 EXPORT_SYMBOL_GPL(kvm_set_rflags);
12492 
kvm_async_pf_hash_fn(gfn_t gfn)12493 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
12494 {
12495 	BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
12496 
12497 	return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
12498 }
12499 
kvm_async_pf_next_probe(u32 key)12500 static inline u32 kvm_async_pf_next_probe(u32 key)
12501 {
12502 	return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
12503 }
12504 
kvm_add_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)12505 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12506 {
12507 	u32 key = kvm_async_pf_hash_fn(gfn);
12508 
12509 	while (vcpu->arch.apf.gfns[key] != ~0)
12510 		key = kvm_async_pf_next_probe(key);
12511 
12512 	vcpu->arch.apf.gfns[key] = gfn;
12513 }
12514 
kvm_async_pf_gfn_slot(struct kvm_vcpu * vcpu,gfn_t gfn)12515 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
12516 {
12517 	int i;
12518 	u32 key = kvm_async_pf_hash_fn(gfn);
12519 
12520 	for (i = 0; i < ASYNC_PF_PER_VCPU &&
12521 		     (vcpu->arch.apf.gfns[key] != gfn &&
12522 		      vcpu->arch.apf.gfns[key] != ~0); i++)
12523 		key = kvm_async_pf_next_probe(key);
12524 
12525 	return key;
12526 }
12527 
kvm_find_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)12528 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12529 {
12530 	return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
12531 }
12532 
kvm_del_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)12533 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12534 {
12535 	u32 i, j, k;
12536 
12537 	i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
12538 
12539 	if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
12540 		return;
12541 
12542 	while (true) {
12543 		vcpu->arch.apf.gfns[i] = ~0;
12544 		do {
12545 			j = kvm_async_pf_next_probe(j);
12546 			if (vcpu->arch.apf.gfns[j] == ~0)
12547 				return;
12548 			k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
12549 			/*
12550 			 * k lies cyclically in ]i,j]
12551 			 * |    i.k.j |
12552 			 * |....j i.k.| or  |.k..j i...|
12553 			 */
12554 		} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
12555 		vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
12556 		i = j;
12557 	}
12558 }
12559 
apf_put_user_notpresent(struct kvm_vcpu * vcpu)12560 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
12561 {
12562 	u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
12563 
12564 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
12565 				      sizeof(reason));
12566 }
12567 
apf_put_user_ready(struct kvm_vcpu * vcpu,u32 token)12568 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
12569 {
12570 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
12571 
12572 	return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
12573 					     &token, offset, sizeof(token));
12574 }
12575 
apf_pageready_slot_free(struct kvm_vcpu * vcpu)12576 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
12577 {
12578 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
12579 	u32 val;
12580 
12581 	if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
12582 					 &val, offset, sizeof(val)))
12583 		return false;
12584 
12585 	return !val;
12586 }
12587 
kvm_can_deliver_async_pf(struct kvm_vcpu * vcpu)12588 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
12589 {
12590 
12591 	if (!kvm_pv_async_pf_enabled(vcpu))
12592 		return false;
12593 
12594 	if (vcpu->arch.apf.send_user_only &&
12595 	    static_call(kvm_x86_get_cpl)(vcpu) == 0)
12596 		return false;
12597 
12598 	if (is_guest_mode(vcpu)) {
12599 		/*
12600 		 * L1 needs to opt into the special #PF vmexits that are
12601 		 * used to deliver async page faults.
12602 		 */
12603 		return vcpu->arch.apf.delivery_as_pf_vmexit;
12604 	} else {
12605 		/*
12606 		 * Play it safe in case the guest temporarily disables paging.
12607 		 * The real mode IDT in particular is unlikely to have a #PF
12608 		 * exception setup.
12609 		 */
12610 		return is_paging(vcpu);
12611 	}
12612 }
12613 
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)12614 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
12615 {
12616 	if (unlikely(!lapic_in_kernel(vcpu) ||
12617 		     kvm_event_needs_reinjection(vcpu) ||
12618 		     vcpu->arch.exception.pending))
12619 		return false;
12620 
12621 	if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
12622 		return false;
12623 
12624 	/*
12625 	 * If interrupts are off we cannot even use an artificial
12626 	 * halt state.
12627 	 */
12628 	return kvm_arch_interrupt_allowed(vcpu);
12629 }
12630 
kvm_arch_async_page_not_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)12631 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
12632 				     struct kvm_async_pf *work)
12633 {
12634 	struct x86_exception fault;
12635 
12636 	trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
12637 	kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
12638 
12639 	if (kvm_can_deliver_async_pf(vcpu) &&
12640 	    !apf_put_user_notpresent(vcpu)) {
12641 		fault.vector = PF_VECTOR;
12642 		fault.error_code_valid = true;
12643 		fault.error_code = 0;
12644 		fault.nested_page_fault = false;
12645 		fault.address = work->arch.token;
12646 		fault.async_page_fault = true;
12647 		kvm_inject_page_fault(vcpu, &fault);
12648 		return true;
12649 	} else {
12650 		/*
12651 		 * It is not possible to deliver a paravirtualized asynchronous
12652 		 * page fault, but putting the guest in an artificial halt state
12653 		 * can be beneficial nevertheless: if an interrupt arrives, we
12654 		 * can deliver it timely and perhaps the guest will schedule
12655 		 * another process.  When the instruction that triggered a page
12656 		 * fault is retried, hopefully the page will be ready in the host.
12657 		 */
12658 		kvm_make_request(KVM_REQ_APF_HALT, vcpu);
12659 		return false;
12660 	}
12661 }
12662 
kvm_arch_async_page_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)12663 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
12664 				 struct kvm_async_pf *work)
12665 {
12666 	struct kvm_lapic_irq irq = {
12667 		.delivery_mode = APIC_DM_FIXED,
12668 		.vector = vcpu->arch.apf.vec
12669 	};
12670 
12671 	if (work->wakeup_all)
12672 		work->arch.token = ~0; /* broadcast wakeup */
12673 	else
12674 		kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
12675 	trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
12676 
12677 	if ((work->wakeup_all || work->notpresent_injected) &&
12678 	    kvm_pv_async_pf_enabled(vcpu) &&
12679 	    !apf_put_user_ready(vcpu, work->arch.token)) {
12680 		vcpu->arch.apf.pageready_pending = true;
12681 		kvm_apic_set_irq(vcpu, &irq, NULL);
12682 	}
12683 
12684 	vcpu->arch.apf.halted = false;
12685 	vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
12686 }
12687 
kvm_arch_async_page_present_queued(struct kvm_vcpu * vcpu)12688 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
12689 {
12690 	kvm_make_request(KVM_REQ_APF_READY, vcpu);
12691 	if (!vcpu->arch.apf.pageready_pending)
12692 		kvm_vcpu_kick(vcpu);
12693 }
12694 
kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu * vcpu)12695 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
12696 {
12697 	if (!kvm_pv_async_pf_enabled(vcpu))
12698 		return true;
12699 	else
12700 		return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
12701 }
12702 
kvm_arch_start_assignment(struct kvm * kvm)12703 void kvm_arch_start_assignment(struct kvm *kvm)
12704 {
12705 	if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
12706 		static_call_cond(kvm_x86_pi_start_assignment)(kvm);
12707 }
12708 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
12709 
kvm_arch_end_assignment(struct kvm * kvm)12710 void kvm_arch_end_assignment(struct kvm *kvm)
12711 {
12712 	atomic_dec(&kvm->arch.assigned_device_count);
12713 }
12714 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
12715 
kvm_arch_has_assigned_device(struct kvm * kvm)12716 bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
12717 {
12718 	return arch_atomic_read(&kvm->arch.assigned_device_count);
12719 }
12720 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
12721 
kvm_arch_register_noncoherent_dma(struct kvm * kvm)12722 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
12723 {
12724 	atomic_inc(&kvm->arch.noncoherent_dma_count);
12725 }
12726 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
12727 
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)12728 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
12729 {
12730 	atomic_dec(&kvm->arch.noncoherent_dma_count);
12731 }
12732 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
12733 
kvm_arch_has_noncoherent_dma(struct kvm * kvm)12734 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
12735 {
12736 	return atomic_read(&kvm->arch.noncoherent_dma_count);
12737 }
12738 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
12739 
kvm_arch_has_irq_bypass(void)12740 bool kvm_arch_has_irq_bypass(void)
12741 {
12742 	return true;
12743 }
12744 
kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)12745 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
12746 				      struct irq_bypass_producer *prod)
12747 {
12748 	struct kvm_kernel_irqfd *irqfd =
12749 		container_of(cons, struct kvm_kernel_irqfd, consumer);
12750 	int ret;
12751 
12752 	irqfd->producer = prod;
12753 	kvm_arch_start_assignment(irqfd->kvm);
12754 	ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm,
12755 					 prod->irq, irqfd->gsi, 1);
12756 
12757 	if (ret)
12758 		kvm_arch_end_assignment(irqfd->kvm);
12759 
12760 	return ret;
12761 }
12762 
kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)12763 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
12764 				      struct irq_bypass_producer *prod)
12765 {
12766 	int ret;
12767 	struct kvm_kernel_irqfd *irqfd =
12768 		container_of(cons, struct kvm_kernel_irqfd, consumer);
12769 
12770 	WARN_ON(irqfd->producer != prod);
12771 	irqfd->producer = NULL;
12772 
12773 	/*
12774 	 * When producer of consumer is unregistered, we change back to
12775 	 * remapped mode, so we can re-use the current implementation
12776 	 * when the irq is masked/disabled or the consumer side (KVM
12777 	 * int this case doesn't want to receive the interrupts.
12778 	*/
12779 	ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm, prod->irq, irqfd->gsi, 0);
12780 	if (ret)
12781 		printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
12782 		       " fails: %d\n", irqfd->consumer.token, ret);
12783 
12784 	kvm_arch_end_assignment(irqfd->kvm);
12785 }
12786 
kvm_arch_update_irqfd_routing(struct kvm * kvm,unsigned int host_irq,uint32_t guest_irq,bool set)12787 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
12788 				   uint32_t guest_irq, bool set)
12789 {
12790 	return static_call(kvm_x86_pi_update_irte)(kvm, host_irq, guest_irq, set);
12791 }
12792 
kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry * old,struct kvm_kernel_irq_routing_entry * new)12793 bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
12794 				  struct kvm_kernel_irq_routing_entry *new)
12795 {
12796 	if (new->type != KVM_IRQ_ROUTING_MSI)
12797 		return true;
12798 
12799 	return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
12800 }
12801 
kvm_vector_hashing_enabled(void)12802 bool kvm_vector_hashing_enabled(void)
12803 {
12804 	return vector_hashing;
12805 }
12806 
kvm_arch_no_poll(struct kvm_vcpu * vcpu)12807 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
12808 {
12809 	return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
12810 }
12811 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
12812 
12813 
kvm_spec_ctrl_test_value(u64 value)12814 int kvm_spec_ctrl_test_value(u64 value)
12815 {
12816 	/*
12817 	 * test that setting IA32_SPEC_CTRL to given value
12818 	 * is allowed by the host processor
12819 	 */
12820 
12821 	u64 saved_value;
12822 	unsigned long flags;
12823 	int ret = 0;
12824 
12825 	local_irq_save(flags);
12826 
12827 	if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
12828 		ret = 1;
12829 	else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
12830 		ret = 1;
12831 	else
12832 		wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
12833 
12834 	local_irq_restore(flags);
12835 
12836 	return ret;
12837 }
12838 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
12839 
kvm_fixup_and_inject_pf_error(struct kvm_vcpu * vcpu,gva_t gva,u16 error_code)12840 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
12841 {
12842 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
12843 	struct x86_exception fault;
12844 	u64 access = error_code &
12845 		(PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
12846 
12847 	if (!(error_code & PFERR_PRESENT_MASK) ||
12848 	    mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != UNMAPPED_GVA) {
12849 		/*
12850 		 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
12851 		 * tables probably do not match the TLB.  Just proceed
12852 		 * with the error code that the processor gave.
12853 		 */
12854 		fault.vector = PF_VECTOR;
12855 		fault.error_code_valid = true;
12856 		fault.error_code = error_code;
12857 		fault.nested_page_fault = false;
12858 		fault.address = gva;
12859 	}
12860 	vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
12861 }
12862 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
12863 
12864 /*
12865  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
12866  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
12867  * indicates whether exit to userspace is needed.
12868  */
kvm_handle_memory_failure(struct kvm_vcpu * vcpu,int r,struct x86_exception * e)12869 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
12870 			      struct x86_exception *e)
12871 {
12872 	if (r == X86EMUL_PROPAGATE_FAULT) {
12873 		kvm_inject_emulated_page_fault(vcpu, e);
12874 		return 1;
12875 	}
12876 
12877 	/*
12878 	 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
12879 	 * while handling a VMX instruction KVM could've handled the request
12880 	 * correctly by exiting to userspace and performing I/O but there
12881 	 * doesn't seem to be a real use-case behind such requests, just return
12882 	 * KVM_EXIT_INTERNAL_ERROR for now.
12883 	 */
12884 	kvm_prepare_emulation_failure_exit(vcpu);
12885 
12886 	return 0;
12887 }
12888 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
12889 
kvm_handle_invpcid(struct kvm_vcpu * vcpu,unsigned long type,gva_t gva)12890 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
12891 {
12892 	bool pcid_enabled;
12893 	struct x86_exception e;
12894 	struct {
12895 		u64 pcid;
12896 		u64 gla;
12897 	} operand;
12898 	int r;
12899 
12900 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
12901 	if (r != X86EMUL_CONTINUE)
12902 		return kvm_handle_memory_failure(vcpu, r, &e);
12903 
12904 	if (operand.pcid >> 12 != 0) {
12905 		kvm_inject_gp(vcpu, 0);
12906 		return 1;
12907 	}
12908 
12909 	pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
12910 
12911 	switch (type) {
12912 	case INVPCID_TYPE_INDIV_ADDR:
12913 		if ((!pcid_enabled && (operand.pcid != 0)) ||
12914 		    is_noncanonical_address(operand.gla, vcpu)) {
12915 			kvm_inject_gp(vcpu, 0);
12916 			return 1;
12917 		}
12918 		kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
12919 		return kvm_skip_emulated_instruction(vcpu);
12920 
12921 	case INVPCID_TYPE_SINGLE_CTXT:
12922 		if (!pcid_enabled && (operand.pcid != 0)) {
12923 			kvm_inject_gp(vcpu, 0);
12924 			return 1;
12925 		}
12926 
12927 		kvm_invalidate_pcid(vcpu, operand.pcid);
12928 		return kvm_skip_emulated_instruction(vcpu);
12929 
12930 	case INVPCID_TYPE_ALL_NON_GLOBAL:
12931 		/*
12932 		 * Currently, KVM doesn't mark global entries in the shadow
12933 		 * page tables, so a non-global flush just degenerates to a
12934 		 * global flush. If needed, we could optimize this later by
12935 		 * keeping track of global entries in shadow page tables.
12936 		 */
12937 
12938 		fallthrough;
12939 	case INVPCID_TYPE_ALL_INCL_GLOBAL:
12940 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12941 		return kvm_skip_emulated_instruction(vcpu);
12942 
12943 	default:
12944 		kvm_inject_gp(vcpu, 0);
12945 		return 1;
12946 	}
12947 }
12948 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
12949 
complete_sev_es_emulated_mmio(struct kvm_vcpu * vcpu)12950 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
12951 {
12952 	struct kvm_run *run = vcpu->run;
12953 	struct kvm_mmio_fragment *frag;
12954 	unsigned int len;
12955 
12956 	BUG_ON(!vcpu->mmio_needed);
12957 
12958 	/* Complete previous fragment */
12959 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
12960 	len = min(8u, frag->len);
12961 	if (!vcpu->mmio_is_write)
12962 		memcpy(frag->data, run->mmio.data, len);
12963 
12964 	if (frag->len <= 8) {
12965 		/* Switch to the next fragment. */
12966 		frag++;
12967 		vcpu->mmio_cur_fragment++;
12968 	} else {
12969 		/* Go forward to the next mmio piece. */
12970 		frag->data += len;
12971 		frag->gpa += len;
12972 		frag->len -= len;
12973 	}
12974 
12975 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
12976 		vcpu->mmio_needed = 0;
12977 
12978 		// VMG change, at this point, we're always done
12979 		// RIP has already been advanced
12980 		return 1;
12981 	}
12982 
12983 	// More MMIO is needed
12984 	run->mmio.phys_addr = frag->gpa;
12985 	run->mmio.len = min(8u, frag->len);
12986 	run->mmio.is_write = vcpu->mmio_is_write;
12987 	if (run->mmio.is_write)
12988 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
12989 	run->exit_reason = KVM_EXIT_MMIO;
12990 
12991 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
12992 
12993 	return 0;
12994 }
12995 
kvm_sev_es_mmio_write(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)12996 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
12997 			  void *data)
12998 {
12999 	int handled;
13000 	struct kvm_mmio_fragment *frag;
13001 
13002 	if (!data)
13003 		return -EINVAL;
13004 
13005 	handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13006 	if (handled == bytes)
13007 		return 1;
13008 
13009 	bytes -= handled;
13010 	gpa += handled;
13011 	data += handled;
13012 
13013 	/*TODO: Check if need to increment number of frags */
13014 	frag = vcpu->mmio_fragments;
13015 	vcpu->mmio_nr_fragments = 1;
13016 	frag->len = bytes;
13017 	frag->gpa = gpa;
13018 	frag->data = data;
13019 
13020 	vcpu->mmio_needed = 1;
13021 	vcpu->mmio_cur_fragment = 0;
13022 
13023 	vcpu->run->mmio.phys_addr = gpa;
13024 	vcpu->run->mmio.len = min(8u, frag->len);
13025 	vcpu->run->mmio.is_write = 1;
13026 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
13027 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
13028 
13029 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13030 
13031 	return 0;
13032 }
13033 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
13034 
kvm_sev_es_mmio_read(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)13035 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13036 			 void *data)
13037 {
13038 	int handled;
13039 	struct kvm_mmio_fragment *frag;
13040 
13041 	if (!data)
13042 		return -EINVAL;
13043 
13044 	handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13045 	if (handled == bytes)
13046 		return 1;
13047 
13048 	bytes -= handled;
13049 	gpa += handled;
13050 	data += handled;
13051 
13052 	/*TODO: Check if need to increment number of frags */
13053 	frag = vcpu->mmio_fragments;
13054 	vcpu->mmio_nr_fragments = 1;
13055 	frag->len = bytes;
13056 	frag->gpa = gpa;
13057 	frag->data = data;
13058 
13059 	vcpu->mmio_needed = 1;
13060 	vcpu->mmio_cur_fragment = 0;
13061 
13062 	vcpu->run->mmio.phys_addr = gpa;
13063 	vcpu->run->mmio.len = min(8u, frag->len);
13064 	vcpu->run->mmio.is_write = 0;
13065 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
13066 
13067 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13068 
13069 	return 0;
13070 }
13071 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
13072 
13073 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13074 			   unsigned int port);
13075 
complete_sev_es_emulated_outs(struct kvm_vcpu * vcpu)13076 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
13077 {
13078 	int size = vcpu->arch.pio.size;
13079 	int port = vcpu->arch.pio.port;
13080 
13081 	vcpu->arch.pio.count = 0;
13082 	if (vcpu->arch.sev_pio_count)
13083 		return kvm_sev_es_outs(vcpu, size, port);
13084 	return 1;
13085 }
13086 
kvm_sev_es_outs(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)13087 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13088 			   unsigned int port)
13089 {
13090 	for (;;) {
13091 		unsigned int count =
13092 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13093 		int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
13094 
13095 		/* memcpy done already by emulator_pio_out.  */
13096 		vcpu->arch.sev_pio_count -= count;
13097 		vcpu->arch.sev_pio_data += count * vcpu->arch.pio.size;
13098 		if (!ret)
13099 			break;
13100 
13101 		/* Emulation done by the kernel.  */
13102 		if (!vcpu->arch.sev_pio_count)
13103 			return 1;
13104 	}
13105 
13106 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
13107 	return 0;
13108 }
13109 
13110 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13111 			  unsigned int port);
13112 
advance_sev_es_emulated_ins(struct kvm_vcpu * vcpu)13113 static void advance_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
13114 {
13115 	unsigned count = vcpu->arch.pio.count;
13116 	complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
13117 	vcpu->arch.sev_pio_count -= count;
13118 	vcpu->arch.sev_pio_data += count * vcpu->arch.pio.size;
13119 }
13120 
complete_sev_es_emulated_ins(struct kvm_vcpu * vcpu)13121 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
13122 {
13123 	int size = vcpu->arch.pio.size;
13124 	int port = vcpu->arch.pio.port;
13125 
13126 	advance_sev_es_emulated_ins(vcpu);
13127 	if (vcpu->arch.sev_pio_count)
13128 		return kvm_sev_es_ins(vcpu, size, port);
13129 	return 1;
13130 }
13131 
kvm_sev_es_ins(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)13132 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13133 			  unsigned int port)
13134 {
13135 	for (;;) {
13136 		unsigned int count =
13137 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13138 		if (!__emulator_pio_in(vcpu, size, port, count))
13139 			break;
13140 
13141 		/* Emulation done by the kernel.  */
13142 		advance_sev_es_emulated_ins(vcpu);
13143 		if (!vcpu->arch.sev_pio_count)
13144 			return 1;
13145 	}
13146 
13147 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
13148 	return 0;
13149 }
13150 
kvm_sev_es_string_io(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port,void * data,unsigned int count,int in)13151 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
13152 			 unsigned int port, void *data,  unsigned int count,
13153 			 int in)
13154 {
13155 	vcpu->arch.sev_pio_data = data;
13156 	vcpu->arch.sev_pio_count = count;
13157 	return in ? kvm_sev_es_ins(vcpu, size, port)
13158 		  : kvm_sev_es_outs(vcpu, size, port);
13159 }
13160 EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
13161 
13162 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
13163 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
13164 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
13165 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
13166 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
13167 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
13168 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
13169 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
13170 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
13171 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
13172 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
13173 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
13174 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
13175 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
13176 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
13177 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
13178 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
13179 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
13180 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
13181 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
13182 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
13183 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
13184 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
13185 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
13186 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
13187 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
13188 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
13189 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
13190 
kvm_x86_init(void)13191 static int __init kvm_x86_init(void)
13192 {
13193 	kvm_mmu_x86_module_init();
13194 	return 0;
13195 }
13196 module_init(kvm_x86_init);
13197 
kvm_x86_exit(void)13198 static void __exit kvm_x86_exit(void)
13199 {
13200 	/*
13201 	 * If module_init() is implemented, module_exit() must also be
13202 	 * implemented to allow module unload.
13203 	 */
13204 }
13205 module_exit(kvm_x86_exit);
13206