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