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