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