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