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