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