xref: /openbmc/linux/arch/x86/kvm/x86.c (revision 85672346)
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 	memset(events, 0, sizeof(*events));
5061 
5062 	/*
5063 	 * The API doesn't provide the instruction length for software
5064 	 * exceptions, so don't report them. As long as the guest RIP
5065 	 * isn't advanced, we should expect to encounter the exception
5066 	 * again.
5067 	 */
5068 	if (!kvm_exception_is_soft(ex->vector)) {
5069 		events->exception.injected = ex->injected;
5070 		events->exception.pending = ex->pending;
5071 		/*
5072 		 * For ABI compatibility, deliberately conflate
5073 		 * pending and injected exceptions when
5074 		 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5075 		 */
5076 		if (!vcpu->kvm->arch.exception_payload_enabled)
5077 			events->exception.injected |= ex->pending;
5078 	}
5079 	events->exception.nr = ex->vector;
5080 	events->exception.has_error_code = ex->has_error_code;
5081 	events->exception.error_code = ex->error_code;
5082 	events->exception_has_payload = ex->has_payload;
5083 	events->exception_payload = ex->payload;
5084 
5085 	events->interrupt.injected =
5086 		vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5087 	events->interrupt.nr = vcpu->arch.interrupt.nr;
5088 	events->interrupt.shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
5089 
5090 	events->nmi.injected = vcpu->arch.nmi_injected;
5091 	events->nmi.pending = vcpu->arch.nmi_pending != 0;
5092 	events->nmi.masked = static_call(kvm_x86_get_nmi_mask)(vcpu);
5093 
5094 	/* events->sipi_vector is never valid when reporting to user space */
5095 
5096 	events->smi.smm = is_smm(vcpu);
5097 	events->smi.pending = vcpu->arch.smi_pending;
5098 	events->smi.smm_inside_nmi =
5099 		!!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5100 	events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5101 
5102 	events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5103 			 | KVM_VCPUEVENT_VALID_SHADOW
5104 			 | KVM_VCPUEVENT_VALID_SMM);
5105 	if (vcpu->kvm->arch.exception_payload_enabled)
5106 		events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5107 	if (vcpu->kvm->arch.triple_fault_event) {
5108 		events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5109 		events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5110 	}
5111 }
5112 
5113 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5114 					      struct kvm_vcpu_events *events)
5115 {
5116 	if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5117 			      | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5118 			      | KVM_VCPUEVENT_VALID_SHADOW
5119 			      | KVM_VCPUEVENT_VALID_SMM
5120 			      | KVM_VCPUEVENT_VALID_PAYLOAD
5121 			      | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5122 		return -EINVAL;
5123 
5124 	if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5125 		if (!vcpu->kvm->arch.exception_payload_enabled)
5126 			return -EINVAL;
5127 		if (events->exception.pending)
5128 			events->exception.injected = 0;
5129 		else
5130 			events->exception_has_payload = 0;
5131 	} else {
5132 		events->exception.pending = 0;
5133 		events->exception_has_payload = 0;
5134 	}
5135 
5136 	if ((events->exception.injected || events->exception.pending) &&
5137 	    (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5138 		return -EINVAL;
5139 
5140 	/* INITs are latched while in SMM */
5141 	if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
5142 	    (events->smi.smm || events->smi.pending) &&
5143 	    vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
5144 		return -EINVAL;
5145 
5146 	process_nmi(vcpu);
5147 
5148 	/*
5149 	 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5150 	 * morph the exception to a VM-Exit if appropriate.  Do this only for
5151 	 * pending exceptions, already-injected exceptions are not subject to
5152 	 * intercpetion.  Note, userspace that conflates pending and injected
5153 	 * is hosed, and will incorrectly convert an injected exception into a
5154 	 * pending exception, which in turn may cause a spurious VM-Exit.
5155 	 */
5156 	vcpu->arch.exception_from_userspace = events->exception.pending;
5157 
5158 	vcpu->arch.exception_vmexit.pending = false;
5159 
5160 	vcpu->arch.exception.injected = events->exception.injected;
5161 	vcpu->arch.exception.pending = events->exception.pending;
5162 	vcpu->arch.exception.vector = events->exception.nr;
5163 	vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5164 	vcpu->arch.exception.error_code = events->exception.error_code;
5165 	vcpu->arch.exception.has_payload = events->exception_has_payload;
5166 	vcpu->arch.exception.payload = events->exception_payload;
5167 
5168 	vcpu->arch.interrupt.injected = events->interrupt.injected;
5169 	vcpu->arch.interrupt.nr = events->interrupt.nr;
5170 	vcpu->arch.interrupt.soft = events->interrupt.soft;
5171 	if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5172 		static_call(kvm_x86_set_interrupt_shadow)(vcpu,
5173 						events->interrupt.shadow);
5174 
5175 	vcpu->arch.nmi_injected = events->nmi.injected;
5176 	if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
5177 		vcpu->arch.nmi_pending = events->nmi.pending;
5178 	static_call(kvm_x86_set_nmi_mask)(vcpu, events->nmi.masked);
5179 
5180 	if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5181 	    lapic_in_kernel(vcpu))
5182 		vcpu->arch.apic->sipi_vector = events->sipi_vector;
5183 
5184 	if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5185 #ifdef CONFIG_KVM_SMM
5186 		if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5187 			kvm_x86_ops.nested_ops->leave_nested(vcpu);
5188 			kvm_smm_changed(vcpu, events->smi.smm);
5189 		}
5190 
5191 		vcpu->arch.smi_pending = events->smi.pending;
5192 
5193 		if (events->smi.smm) {
5194 			if (events->smi.smm_inside_nmi)
5195 				vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5196 			else
5197 				vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5198 		}
5199 
5200 #else
5201 		if (events->smi.smm || events->smi.pending ||
5202 		    events->smi.smm_inside_nmi)
5203 			return -EINVAL;
5204 #endif
5205 
5206 		if (lapic_in_kernel(vcpu)) {
5207 			if (events->smi.latched_init)
5208 				set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5209 			else
5210 				clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5211 		}
5212 	}
5213 
5214 	if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5215 		if (!vcpu->kvm->arch.triple_fault_event)
5216 			return -EINVAL;
5217 		if (events->triple_fault.pending)
5218 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5219 		else
5220 			kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5221 	}
5222 
5223 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5224 
5225 	return 0;
5226 }
5227 
5228 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5229 					     struct kvm_debugregs *dbgregs)
5230 {
5231 	unsigned long val;
5232 
5233 	memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
5234 	kvm_get_dr(vcpu, 6, &val);
5235 	dbgregs->dr6 = val;
5236 	dbgregs->dr7 = vcpu->arch.dr7;
5237 	dbgregs->flags = 0;
5238 	memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
5239 }
5240 
5241 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5242 					    struct kvm_debugregs *dbgregs)
5243 {
5244 	if (dbgregs->flags)
5245 		return -EINVAL;
5246 
5247 	if (!kvm_dr6_valid(dbgregs->dr6))
5248 		return -EINVAL;
5249 	if (!kvm_dr7_valid(dbgregs->dr7))
5250 		return -EINVAL;
5251 
5252 	memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
5253 	kvm_update_dr0123(vcpu);
5254 	vcpu->arch.dr6 = dbgregs->dr6;
5255 	vcpu->arch.dr7 = dbgregs->dr7;
5256 	kvm_update_dr7(vcpu);
5257 
5258 	return 0;
5259 }
5260 
5261 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5262 					 struct kvm_xsave *guest_xsave)
5263 {
5264 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5265 		return;
5266 
5267 	fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu,
5268 				       guest_xsave->region,
5269 				       sizeof(guest_xsave->region),
5270 				       vcpu->arch.pkru);
5271 }
5272 
5273 static void kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5274 					  u8 *state, unsigned int size)
5275 {
5276 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5277 		return;
5278 
5279 	fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu,
5280 				       state, size, vcpu->arch.pkru);
5281 }
5282 
5283 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5284 					struct kvm_xsave *guest_xsave)
5285 {
5286 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5287 		return 0;
5288 
5289 	return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5290 					      guest_xsave->region,
5291 					      kvm_caps.supported_xcr0,
5292 					      &vcpu->arch.pkru);
5293 }
5294 
5295 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5296 					struct kvm_xcrs *guest_xcrs)
5297 {
5298 	if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5299 		guest_xcrs->nr_xcrs = 0;
5300 		return;
5301 	}
5302 
5303 	guest_xcrs->nr_xcrs = 1;
5304 	guest_xcrs->flags = 0;
5305 	guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5306 	guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5307 }
5308 
5309 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5310 				       struct kvm_xcrs *guest_xcrs)
5311 {
5312 	int i, r = 0;
5313 
5314 	if (!boot_cpu_has(X86_FEATURE_XSAVE))
5315 		return -EINVAL;
5316 
5317 	if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5318 		return -EINVAL;
5319 
5320 	for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5321 		/* Only support XCR0 currently */
5322 		if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5323 			r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5324 				guest_xcrs->xcrs[i].value);
5325 			break;
5326 		}
5327 	if (r)
5328 		r = -EINVAL;
5329 	return r;
5330 }
5331 
5332 /*
5333  * kvm_set_guest_paused() indicates to the guest kernel that it has been
5334  * stopped by the hypervisor.  This function will be called from the host only.
5335  * EINVAL is returned when the host attempts to set the flag for a guest that
5336  * does not support pv clocks.
5337  */
5338 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5339 {
5340 	if (!vcpu->arch.pv_time.active)
5341 		return -EINVAL;
5342 	vcpu->arch.pvclock_set_guest_stopped_request = true;
5343 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5344 	return 0;
5345 }
5346 
5347 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5348 				 struct kvm_device_attr *attr)
5349 {
5350 	int r;
5351 
5352 	switch (attr->attr) {
5353 	case KVM_VCPU_TSC_OFFSET:
5354 		r = 0;
5355 		break;
5356 	default:
5357 		r = -ENXIO;
5358 	}
5359 
5360 	return r;
5361 }
5362 
5363 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5364 				 struct kvm_device_attr *attr)
5365 {
5366 	u64 __user *uaddr = kvm_get_attr_addr(attr);
5367 	int r;
5368 
5369 	if (IS_ERR(uaddr))
5370 		return PTR_ERR(uaddr);
5371 
5372 	switch (attr->attr) {
5373 	case KVM_VCPU_TSC_OFFSET:
5374 		r = -EFAULT;
5375 		if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5376 			break;
5377 		r = 0;
5378 		break;
5379 	default:
5380 		r = -ENXIO;
5381 	}
5382 
5383 	return r;
5384 }
5385 
5386 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5387 				 struct kvm_device_attr *attr)
5388 {
5389 	u64 __user *uaddr = kvm_get_attr_addr(attr);
5390 	struct kvm *kvm = vcpu->kvm;
5391 	int r;
5392 
5393 	if (IS_ERR(uaddr))
5394 		return PTR_ERR(uaddr);
5395 
5396 	switch (attr->attr) {
5397 	case KVM_VCPU_TSC_OFFSET: {
5398 		u64 offset, tsc, ns;
5399 		unsigned long flags;
5400 		bool matched;
5401 
5402 		r = -EFAULT;
5403 		if (get_user(offset, uaddr))
5404 			break;
5405 
5406 		raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5407 
5408 		matched = (vcpu->arch.virtual_tsc_khz &&
5409 			   kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5410 			   kvm->arch.last_tsc_offset == offset);
5411 
5412 		tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5413 		ns = get_kvmclock_base_ns();
5414 
5415 		__kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched);
5416 		raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5417 
5418 		r = 0;
5419 		break;
5420 	}
5421 	default:
5422 		r = -ENXIO;
5423 	}
5424 
5425 	return r;
5426 }
5427 
5428 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5429 				      unsigned int ioctl,
5430 				      void __user *argp)
5431 {
5432 	struct kvm_device_attr attr;
5433 	int r;
5434 
5435 	if (copy_from_user(&attr, argp, sizeof(attr)))
5436 		return -EFAULT;
5437 
5438 	if (attr.group != KVM_VCPU_TSC_CTRL)
5439 		return -ENXIO;
5440 
5441 	switch (ioctl) {
5442 	case KVM_HAS_DEVICE_ATTR:
5443 		r = kvm_arch_tsc_has_attr(vcpu, &attr);
5444 		break;
5445 	case KVM_GET_DEVICE_ATTR:
5446 		r = kvm_arch_tsc_get_attr(vcpu, &attr);
5447 		break;
5448 	case KVM_SET_DEVICE_ATTR:
5449 		r = kvm_arch_tsc_set_attr(vcpu, &attr);
5450 		break;
5451 	}
5452 
5453 	return r;
5454 }
5455 
5456 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5457 				     struct kvm_enable_cap *cap)
5458 {
5459 	int r;
5460 	uint16_t vmcs_version;
5461 	void __user *user_ptr;
5462 
5463 	if (cap->flags)
5464 		return -EINVAL;
5465 
5466 	switch (cap->cap) {
5467 	case KVM_CAP_HYPERV_SYNIC2:
5468 		if (cap->args[0])
5469 			return -EINVAL;
5470 		fallthrough;
5471 
5472 	case KVM_CAP_HYPERV_SYNIC:
5473 		if (!irqchip_in_kernel(vcpu->kvm))
5474 			return -EINVAL;
5475 		return kvm_hv_activate_synic(vcpu, cap->cap ==
5476 					     KVM_CAP_HYPERV_SYNIC2);
5477 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
5478 		if (!kvm_x86_ops.nested_ops->enable_evmcs)
5479 			return -ENOTTY;
5480 		r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
5481 		if (!r) {
5482 			user_ptr = (void __user *)(uintptr_t)cap->args[0];
5483 			if (copy_to_user(user_ptr, &vmcs_version,
5484 					 sizeof(vmcs_version)))
5485 				r = -EFAULT;
5486 		}
5487 		return r;
5488 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
5489 		if (!kvm_x86_ops.enable_direct_tlbflush)
5490 			return -ENOTTY;
5491 
5492 		return static_call(kvm_x86_enable_direct_tlbflush)(vcpu);
5493 
5494 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
5495 		return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
5496 
5497 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5498 		vcpu->arch.pv_cpuid.enforce = cap->args[0];
5499 		if (vcpu->arch.pv_cpuid.enforce)
5500 			kvm_update_pv_runtime(vcpu);
5501 
5502 		return 0;
5503 	default:
5504 		return -EINVAL;
5505 	}
5506 }
5507 
5508 long kvm_arch_vcpu_ioctl(struct file *filp,
5509 			 unsigned int ioctl, unsigned long arg)
5510 {
5511 	struct kvm_vcpu *vcpu = filp->private_data;
5512 	void __user *argp = (void __user *)arg;
5513 	int r;
5514 	union {
5515 		struct kvm_sregs2 *sregs2;
5516 		struct kvm_lapic_state *lapic;
5517 		struct kvm_xsave *xsave;
5518 		struct kvm_xcrs *xcrs;
5519 		void *buffer;
5520 	} u;
5521 
5522 	vcpu_load(vcpu);
5523 
5524 	u.buffer = NULL;
5525 	switch (ioctl) {
5526 	case KVM_GET_LAPIC: {
5527 		r = -EINVAL;
5528 		if (!lapic_in_kernel(vcpu))
5529 			goto out;
5530 		u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
5531 				GFP_KERNEL_ACCOUNT);
5532 
5533 		r = -ENOMEM;
5534 		if (!u.lapic)
5535 			goto out;
5536 		r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
5537 		if (r)
5538 			goto out;
5539 		r = -EFAULT;
5540 		if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
5541 			goto out;
5542 		r = 0;
5543 		break;
5544 	}
5545 	case KVM_SET_LAPIC: {
5546 		r = -EINVAL;
5547 		if (!lapic_in_kernel(vcpu))
5548 			goto out;
5549 		u.lapic = memdup_user(argp, sizeof(*u.lapic));
5550 		if (IS_ERR(u.lapic)) {
5551 			r = PTR_ERR(u.lapic);
5552 			goto out_nofree;
5553 		}
5554 
5555 		r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
5556 		break;
5557 	}
5558 	case KVM_INTERRUPT: {
5559 		struct kvm_interrupt irq;
5560 
5561 		r = -EFAULT;
5562 		if (copy_from_user(&irq, argp, sizeof(irq)))
5563 			goto out;
5564 		r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
5565 		break;
5566 	}
5567 	case KVM_NMI: {
5568 		r = kvm_vcpu_ioctl_nmi(vcpu);
5569 		break;
5570 	}
5571 	case KVM_SMI: {
5572 		r = kvm_inject_smi(vcpu);
5573 		break;
5574 	}
5575 	case KVM_SET_CPUID: {
5576 		struct kvm_cpuid __user *cpuid_arg = argp;
5577 		struct kvm_cpuid cpuid;
5578 
5579 		r = -EFAULT;
5580 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5581 			goto out;
5582 		r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
5583 		break;
5584 	}
5585 	case KVM_SET_CPUID2: {
5586 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5587 		struct kvm_cpuid2 cpuid;
5588 
5589 		r = -EFAULT;
5590 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5591 			goto out;
5592 		r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
5593 					      cpuid_arg->entries);
5594 		break;
5595 	}
5596 	case KVM_GET_CPUID2: {
5597 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5598 		struct kvm_cpuid2 cpuid;
5599 
5600 		r = -EFAULT;
5601 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5602 			goto out;
5603 		r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
5604 					      cpuid_arg->entries);
5605 		if (r)
5606 			goto out;
5607 		r = -EFAULT;
5608 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5609 			goto out;
5610 		r = 0;
5611 		break;
5612 	}
5613 	case KVM_GET_MSRS: {
5614 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
5615 		r = msr_io(vcpu, argp, do_get_msr, 1);
5616 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5617 		break;
5618 	}
5619 	case KVM_SET_MSRS: {
5620 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
5621 		r = msr_io(vcpu, argp, do_set_msr, 0);
5622 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5623 		break;
5624 	}
5625 	case KVM_TPR_ACCESS_REPORTING: {
5626 		struct kvm_tpr_access_ctl tac;
5627 
5628 		r = -EFAULT;
5629 		if (copy_from_user(&tac, argp, sizeof(tac)))
5630 			goto out;
5631 		r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
5632 		if (r)
5633 			goto out;
5634 		r = -EFAULT;
5635 		if (copy_to_user(argp, &tac, sizeof(tac)))
5636 			goto out;
5637 		r = 0;
5638 		break;
5639 	};
5640 	case KVM_SET_VAPIC_ADDR: {
5641 		struct kvm_vapic_addr va;
5642 		int idx;
5643 
5644 		r = -EINVAL;
5645 		if (!lapic_in_kernel(vcpu))
5646 			goto out;
5647 		r = -EFAULT;
5648 		if (copy_from_user(&va, argp, sizeof(va)))
5649 			goto out;
5650 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5651 		r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
5652 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5653 		break;
5654 	}
5655 	case KVM_X86_SETUP_MCE: {
5656 		u64 mcg_cap;
5657 
5658 		r = -EFAULT;
5659 		if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
5660 			goto out;
5661 		r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
5662 		break;
5663 	}
5664 	case KVM_X86_SET_MCE: {
5665 		struct kvm_x86_mce mce;
5666 
5667 		r = -EFAULT;
5668 		if (copy_from_user(&mce, argp, sizeof(mce)))
5669 			goto out;
5670 		r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
5671 		break;
5672 	}
5673 	case KVM_GET_VCPU_EVENTS: {
5674 		struct kvm_vcpu_events events;
5675 
5676 		kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
5677 
5678 		r = -EFAULT;
5679 		if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
5680 			break;
5681 		r = 0;
5682 		break;
5683 	}
5684 	case KVM_SET_VCPU_EVENTS: {
5685 		struct kvm_vcpu_events events;
5686 
5687 		r = -EFAULT;
5688 		if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
5689 			break;
5690 
5691 		r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
5692 		break;
5693 	}
5694 	case KVM_GET_DEBUGREGS: {
5695 		struct kvm_debugregs dbgregs;
5696 
5697 		kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
5698 
5699 		r = -EFAULT;
5700 		if (copy_to_user(argp, &dbgregs,
5701 				 sizeof(struct kvm_debugregs)))
5702 			break;
5703 		r = 0;
5704 		break;
5705 	}
5706 	case KVM_SET_DEBUGREGS: {
5707 		struct kvm_debugregs dbgregs;
5708 
5709 		r = -EFAULT;
5710 		if (copy_from_user(&dbgregs, argp,
5711 				   sizeof(struct kvm_debugregs)))
5712 			break;
5713 
5714 		r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
5715 		break;
5716 	}
5717 	case KVM_GET_XSAVE: {
5718 		r = -EINVAL;
5719 		if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
5720 			break;
5721 
5722 		u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
5723 		r = -ENOMEM;
5724 		if (!u.xsave)
5725 			break;
5726 
5727 		kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
5728 
5729 		r = -EFAULT;
5730 		if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
5731 			break;
5732 		r = 0;
5733 		break;
5734 	}
5735 	case KVM_SET_XSAVE: {
5736 		int size = vcpu->arch.guest_fpu.uabi_size;
5737 
5738 		u.xsave = memdup_user(argp, size);
5739 		if (IS_ERR(u.xsave)) {
5740 			r = PTR_ERR(u.xsave);
5741 			goto out_nofree;
5742 		}
5743 
5744 		r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
5745 		break;
5746 	}
5747 
5748 	case KVM_GET_XSAVE2: {
5749 		int size = vcpu->arch.guest_fpu.uabi_size;
5750 
5751 		u.xsave = kzalloc(size, GFP_KERNEL_ACCOUNT);
5752 		r = -ENOMEM;
5753 		if (!u.xsave)
5754 			break;
5755 
5756 		kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
5757 
5758 		r = -EFAULT;
5759 		if (copy_to_user(argp, u.xsave, size))
5760 			break;
5761 
5762 		r = 0;
5763 		break;
5764 	}
5765 
5766 	case KVM_GET_XCRS: {
5767 		u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
5768 		r = -ENOMEM;
5769 		if (!u.xcrs)
5770 			break;
5771 
5772 		kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
5773 
5774 		r = -EFAULT;
5775 		if (copy_to_user(argp, u.xcrs,
5776 				 sizeof(struct kvm_xcrs)))
5777 			break;
5778 		r = 0;
5779 		break;
5780 	}
5781 	case KVM_SET_XCRS: {
5782 		u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
5783 		if (IS_ERR(u.xcrs)) {
5784 			r = PTR_ERR(u.xcrs);
5785 			goto out_nofree;
5786 		}
5787 
5788 		r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
5789 		break;
5790 	}
5791 	case KVM_SET_TSC_KHZ: {
5792 		u32 user_tsc_khz;
5793 
5794 		r = -EINVAL;
5795 		user_tsc_khz = (u32)arg;
5796 
5797 		if (kvm_caps.has_tsc_control &&
5798 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
5799 			goto out;
5800 
5801 		if (user_tsc_khz == 0)
5802 			user_tsc_khz = tsc_khz;
5803 
5804 		if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
5805 			r = 0;
5806 
5807 		goto out;
5808 	}
5809 	case KVM_GET_TSC_KHZ: {
5810 		r = vcpu->arch.virtual_tsc_khz;
5811 		goto out;
5812 	}
5813 	case KVM_KVMCLOCK_CTRL: {
5814 		r = kvm_set_guest_paused(vcpu);
5815 		goto out;
5816 	}
5817 	case KVM_ENABLE_CAP: {
5818 		struct kvm_enable_cap cap;
5819 
5820 		r = -EFAULT;
5821 		if (copy_from_user(&cap, argp, sizeof(cap)))
5822 			goto out;
5823 		r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
5824 		break;
5825 	}
5826 	case KVM_GET_NESTED_STATE: {
5827 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
5828 		u32 user_data_size;
5829 
5830 		r = -EINVAL;
5831 		if (!kvm_x86_ops.nested_ops->get_state)
5832 			break;
5833 
5834 		BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
5835 		r = -EFAULT;
5836 		if (get_user(user_data_size, &user_kvm_nested_state->size))
5837 			break;
5838 
5839 		r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
5840 						     user_data_size);
5841 		if (r < 0)
5842 			break;
5843 
5844 		if (r > user_data_size) {
5845 			if (put_user(r, &user_kvm_nested_state->size))
5846 				r = -EFAULT;
5847 			else
5848 				r = -E2BIG;
5849 			break;
5850 		}
5851 
5852 		r = 0;
5853 		break;
5854 	}
5855 	case KVM_SET_NESTED_STATE: {
5856 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
5857 		struct kvm_nested_state kvm_state;
5858 		int idx;
5859 
5860 		r = -EINVAL;
5861 		if (!kvm_x86_ops.nested_ops->set_state)
5862 			break;
5863 
5864 		r = -EFAULT;
5865 		if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
5866 			break;
5867 
5868 		r = -EINVAL;
5869 		if (kvm_state.size < sizeof(kvm_state))
5870 			break;
5871 
5872 		if (kvm_state.flags &
5873 		    ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
5874 		      | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
5875 		      | KVM_STATE_NESTED_GIF_SET))
5876 			break;
5877 
5878 		/* nested_run_pending implies guest_mode.  */
5879 		if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
5880 		    && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
5881 			break;
5882 
5883 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5884 		r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
5885 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5886 		break;
5887 	}
5888 	case KVM_GET_SUPPORTED_HV_CPUID:
5889 		r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
5890 		break;
5891 #ifdef CONFIG_KVM_XEN
5892 	case KVM_XEN_VCPU_GET_ATTR: {
5893 		struct kvm_xen_vcpu_attr xva;
5894 
5895 		r = -EFAULT;
5896 		if (copy_from_user(&xva, argp, sizeof(xva)))
5897 			goto out;
5898 		r = kvm_xen_vcpu_get_attr(vcpu, &xva);
5899 		if (!r && copy_to_user(argp, &xva, sizeof(xva)))
5900 			r = -EFAULT;
5901 		break;
5902 	}
5903 	case KVM_XEN_VCPU_SET_ATTR: {
5904 		struct kvm_xen_vcpu_attr xva;
5905 
5906 		r = -EFAULT;
5907 		if (copy_from_user(&xva, argp, sizeof(xva)))
5908 			goto out;
5909 		r = kvm_xen_vcpu_set_attr(vcpu, &xva);
5910 		break;
5911 	}
5912 #endif
5913 	case KVM_GET_SREGS2: {
5914 		u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
5915 		r = -ENOMEM;
5916 		if (!u.sregs2)
5917 			goto out;
5918 		__get_sregs2(vcpu, u.sregs2);
5919 		r = -EFAULT;
5920 		if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
5921 			goto out;
5922 		r = 0;
5923 		break;
5924 	}
5925 	case KVM_SET_SREGS2: {
5926 		u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
5927 		if (IS_ERR(u.sregs2)) {
5928 			r = PTR_ERR(u.sregs2);
5929 			u.sregs2 = NULL;
5930 			goto out;
5931 		}
5932 		r = __set_sregs2(vcpu, u.sregs2);
5933 		break;
5934 	}
5935 	case KVM_HAS_DEVICE_ATTR:
5936 	case KVM_GET_DEVICE_ATTR:
5937 	case KVM_SET_DEVICE_ATTR:
5938 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
5939 		break;
5940 	default:
5941 		r = -EINVAL;
5942 	}
5943 out:
5944 	kfree(u.buffer);
5945 out_nofree:
5946 	vcpu_put(vcpu);
5947 	return r;
5948 }
5949 
5950 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
5951 {
5952 	return VM_FAULT_SIGBUS;
5953 }
5954 
5955 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
5956 {
5957 	int ret;
5958 
5959 	if (addr > (unsigned int)(-3 * PAGE_SIZE))
5960 		return -EINVAL;
5961 	ret = static_call(kvm_x86_set_tss_addr)(kvm, addr);
5962 	return ret;
5963 }
5964 
5965 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
5966 					      u64 ident_addr)
5967 {
5968 	return static_call(kvm_x86_set_identity_map_addr)(kvm, ident_addr);
5969 }
5970 
5971 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
5972 					 unsigned long kvm_nr_mmu_pages)
5973 {
5974 	if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
5975 		return -EINVAL;
5976 
5977 	mutex_lock(&kvm->slots_lock);
5978 
5979 	kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
5980 	kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
5981 
5982 	mutex_unlock(&kvm->slots_lock);
5983 	return 0;
5984 }
5985 
5986 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
5987 {
5988 	return kvm->arch.n_max_mmu_pages;
5989 }
5990 
5991 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5992 {
5993 	struct kvm_pic *pic = kvm->arch.vpic;
5994 	int r;
5995 
5996 	r = 0;
5997 	switch (chip->chip_id) {
5998 	case KVM_IRQCHIP_PIC_MASTER:
5999 		memcpy(&chip->chip.pic, &pic->pics[0],
6000 			sizeof(struct kvm_pic_state));
6001 		break;
6002 	case KVM_IRQCHIP_PIC_SLAVE:
6003 		memcpy(&chip->chip.pic, &pic->pics[1],
6004 			sizeof(struct kvm_pic_state));
6005 		break;
6006 	case KVM_IRQCHIP_IOAPIC:
6007 		kvm_get_ioapic(kvm, &chip->chip.ioapic);
6008 		break;
6009 	default:
6010 		r = -EINVAL;
6011 		break;
6012 	}
6013 	return r;
6014 }
6015 
6016 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6017 {
6018 	struct kvm_pic *pic = kvm->arch.vpic;
6019 	int r;
6020 
6021 	r = 0;
6022 	switch (chip->chip_id) {
6023 	case KVM_IRQCHIP_PIC_MASTER:
6024 		spin_lock(&pic->lock);
6025 		memcpy(&pic->pics[0], &chip->chip.pic,
6026 			sizeof(struct kvm_pic_state));
6027 		spin_unlock(&pic->lock);
6028 		break;
6029 	case KVM_IRQCHIP_PIC_SLAVE:
6030 		spin_lock(&pic->lock);
6031 		memcpy(&pic->pics[1], &chip->chip.pic,
6032 			sizeof(struct kvm_pic_state));
6033 		spin_unlock(&pic->lock);
6034 		break;
6035 	case KVM_IRQCHIP_IOAPIC:
6036 		kvm_set_ioapic(kvm, &chip->chip.ioapic);
6037 		break;
6038 	default:
6039 		r = -EINVAL;
6040 		break;
6041 	}
6042 	kvm_pic_update_irq(pic);
6043 	return r;
6044 }
6045 
6046 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6047 {
6048 	struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
6049 
6050 	BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
6051 
6052 	mutex_lock(&kps->lock);
6053 	memcpy(ps, &kps->channels, sizeof(*ps));
6054 	mutex_unlock(&kps->lock);
6055 	return 0;
6056 }
6057 
6058 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6059 {
6060 	int i;
6061 	struct kvm_pit *pit = kvm->arch.vpit;
6062 
6063 	mutex_lock(&pit->pit_state.lock);
6064 	memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
6065 	for (i = 0; i < 3; i++)
6066 		kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
6067 	mutex_unlock(&pit->pit_state.lock);
6068 	return 0;
6069 }
6070 
6071 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6072 {
6073 	mutex_lock(&kvm->arch.vpit->pit_state.lock);
6074 	memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
6075 		sizeof(ps->channels));
6076 	ps->flags = kvm->arch.vpit->pit_state.flags;
6077 	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
6078 	memset(&ps->reserved, 0, sizeof(ps->reserved));
6079 	return 0;
6080 }
6081 
6082 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6083 {
6084 	int start = 0;
6085 	int i;
6086 	u32 prev_legacy, cur_legacy;
6087 	struct kvm_pit *pit = kvm->arch.vpit;
6088 
6089 	mutex_lock(&pit->pit_state.lock);
6090 	prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
6091 	cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
6092 	if (!prev_legacy && cur_legacy)
6093 		start = 1;
6094 	memcpy(&pit->pit_state.channels, &ps->channels,
6095 	       sizeof(pit->pit_state.channels));
6096 	pit->pit_state.flags = ps->flags;
6097 	for (i = 0; i < 3; i++)
6098 		kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
6099 				   start && i == 0);
6100 	mutex_unlock(&pit->pit_state.lock);
6101 	return 0;
6102 }
6103 
6104 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
6105 				 struct kvm_reinject_control *control)
6106 {
6107 	struct kvm_pit *pit = kvm->arch.vpit;
6108 
6109 	/* pit->pit_state.lock was overloaded to prevent userspace from getting
6110 	 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
6111 	 * ioctls in parallel.  Use a separate lock if that ioctl isn't rare.
6112 	 */
6113 	mutex_lock(&pit->pit_state.lock);
6114 	kvm_pit_set_reinject(pit, control->pit_reinject);
6115 	mutex_unlock(&pit->pit_state.lock);
6116 
6117 	return 0;
6118 }
6119 
6120 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6121 {
6122 
6123 	/*
6124 	 * Flush all CPUs' dirty log buffers to the  dirty_bitmap.  Called
6125 	 * before reporting dirty_bitmap to userspace.  KVM flushes the buffers
6126 	 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6127 	 * VM-Exit.
6128 	 */
6129 	struct kvm_vcpu *vcpu;
6130 	unsigned long i;
6131 
6132 	kvm_for_each_vcpu(i, vcpu, kvm)
6133 		kvm_vcpu_kick(vcpu);
6134 }
6135 
6136 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
6137 			bool line_status)
6138 {
6139 	if (!irqchip_in_kernel(kvm))
6140 		return -ENXIO;
6141 
6142 	irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
6143 					irq_event->irq, irq_event->level,
6144 					line_status);
6145 	return 0;
6146 }
6147 
6148 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6149 			    struct kvm_enable_cap *cap)
6150 {
6151 	int r;
6152 
6153 	if (cap->flags)
6154 		return -EINVAL;
6155 
6156 	switch (cap->cap) {
6157 	case KVM_CAP_DISABLE_QUIRKS2:
6158 		r = -EINVAL;
6159 		if (cap->args[0] & ~KVM_X86_VALID_QUIRKS)
6160 			break;
6161 		fallthrough;
6162 	case KVM_CAP_DISABLE_QUIRKS:
6163 		kvm->arch.disabled_quirks = cap->args[0];
6164 		r = 0;
6165 		break;
6166 	case KVM_CAP_SPLIT_IRQCHIP: {
6167 		mutex_lock(&kvm->lock);
6168 		r = -EINVAL;
6169 		if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6170 			goto split_irqchip_unlock;
6171 		r = -EEXIST;
6172 		if (irqchip_in_kernel(kvm))
6173 			goto split_irqchip_unlock;
6174 		if (kvm->created_vcpus)
6175 			goto split_irqchip_unlock;
6176 		r = kvm_setup_empty_irq_routing(kvm);
6177 		if (r)
6178 			goto split_irqchip_unlock;
6179 		/* Pairs with irqchip_in_kernel. */
6180 		smp_wmb();
6181 		kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6182 		kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6183 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6184 		r = 0;
6185 split_irqchip_unlock:
6186 		mutex_unlock(&kvm->lock);
6187 		break;
6188 	}
6189 	case KVM_CAP_X2APIC_API:
6190 		r = -EINVAL;
6191 		if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6192 			break;
6193 
6194 		if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6195 			kvm->arch.x2apic_format = true;
6196 		if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6197 			kvm->arch.x2apic_broadcast_quirk_disabled = true;
6198 
6199 		r = 0;
6200 		break;
6201 	case KVM_CAP_X86_DISABLE_EXITS:
6202 		r = -EINVAL;
6203 		if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
6204 			break;
6205 
6206 		if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
6207 			kvm_can_mwait_in_guest())
6208 			kvm->arch.mwait_in_guest = true;
6209 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
6210 			kvm->arch.hlt_in_guest = true;
6211 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
6212 			kvm->arch.pause_in_guest = true;
6213 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
6214 			kvm->arch.cstate_in_guest = true;
6215 		r = 0;
6216 		break;
6217 	case KVM_CAP_MSR_PLATFORM_INFO:
6218 		kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6219 		r = 0;
6220 		break;
6221 	case KVM_CAP_EXCEPTION_PAYLOAD:
6222 		kvm->arch.exception_payload_enabled = cap->args[0];
6223 		r = 0;
6224 		break;
6225 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6226 		kvm->arch.triple_fault_event = cap->args[0];
6227 		r = 0;
6228 		break;
6229 	case KVM_CAP_X86_USER_SPACE_MSR:
6230 		r = -EINVAL;
6231 		if (cap->args[0] & ~(KVM_MSR_EXIT_REASON_INVAL |
6232 				     KVM_MSR_EXIT_REASON_UNKNOWN |
6233 				     KVM_MSR_EXIT_REASON_FILTER))
6234 			break;
6235 		kvm->arch.user_space_msr_mask = cap->args[0];
6236 		r = 0;
6237 		break;
6238 	case KVM_CAP_X86_BUS_LOCK_EXIT:
6239 		r = -EINVAL;
6240 		if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6241 			break;
6242 
6243 		if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6244 		    (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6245 			break;
6246 
6247 		if (kvm_caps.has_bus_lock_exit &&
6248 		    cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6249 			kvm->arch.bus_lock_detection_enabled = true;
6250 		r = 0;
6251 		break;
6252 #ifdef CONFIG_X86_SGX_KVM
6253 	case KVM_CAP_SGX_ATTRIBUTE: {
6254 		unsigned long allowed_attributes = 0;
6255 
6256 		r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6257 		if (r)
6258 			break;
6259 
6260 		/* KVM only supports the PROVISIONKEY privileged attribute. */
6261 		if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6262 		    !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6263 			kvm->arch.sgx_provisioning_allowed = true;
6264 		else
6265 			r = -EINVAL;
6266 		break;
6267 	}
6268 #endif
6269 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6270 		r = -EINVAL;
6271 		if (!kvm_x86_ops.vm_copy_enc_context_from)
6272 			break;
6273 
6274 		r = static_call(kvm_x86_vm_copy_enc_context_from)(kvm, cap->args[0]);
6275 		break;
6276 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6277 		r = -EINVAL;
6278 		if (!kvm_x86_ops.vm_move_enc_context_from)
6279 			break;
6280 
6281 		r = static_call(kvm_x86_vm_move_enc_context_from)(kvm, cap->args[0]);
6282 		break;
6283 	case KVM_CAP_EXIT_HYPERCALL:
6284 		if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6285 			r = -EINVAL;
6286 			break;
6287 		}
6288 		kvm->arch.hypercall_exit_enabled = cap->args[0];
6289 		r = 0;
6290 		break;
6291 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6292 		r = -EINVAL;
6293 		if (cap->args[0] & ~1)
6294 			break;
6295 		kvm->arch.exit_on_emulation_error = cap->args[0];
6296 		r = 0;
6297 		break;
6298 	case KVM_CAP_PMU_CAPABILITY:
6299 		r = -EINVAL;
6300 		if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6301 			break;
6302 
6303 		mutex_lock(&kvm->lock);
6304 		if (!kvm->created_vcpus) {
6305 			kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6306 			r = 0;
6307 		}
6308 		mutex_unlock(&kvm->lock);
6309 		break;
6310 	case KVM_CAP_MAX_VCPU_ID:
6311 		r = -EINVAL;
6312 		if (cap->args[0] > KVM_MAX_VCPU_IDS)
6313 			break;
6314 
6315 		mutex_lock(&kvm->lock);
6316 		if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6317 			r = 0;
6318 		} else if (!kvm->arch.max_vcpu_ids) {
6319 			kvm->arch.max_vcpu_ids = cap->args[0];
6320 			r = 0;
6321 		}
6322 		mutex_unlock(&kvm->lock);
6323 		break;
6324 	case KVM_CAP_X86_NOTIFY_VMEXIT:
6325 		r = -EINVAL;
6326 		if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6327 			break;
6328 		if (!kvm_caps.has_notify_vmexit)
6329 			break;
6330 		if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6331 			break;
6332 		mutex_lock(&kvm->lock);
6333 		if (!kvm->created_vcpus) {
6334 			kvm->arch.notify_window = cap->args[0] >> 32;
6335 			kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6336 			r = 0;
6337 		}
6338 		mutex_unlock(&kvm->lock);
6339 		break;
6340 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6341 		r = -EINVAL;
6342 
6343 		/*
6344 		 * Since the risk of disabling NX hugepages is a guest crashing
6345 		 * the system, ensure the userspace process has permission to
6346 		 * reboot the system.
6347 		 *
6348 		 * Note that unlike the reboot() syscall, the process must have
6349 		 * this capability in the root namespace because exposing
6350 		 * /dev/kvm into a container does not limit the scope of the
6351 		 * iTLB multihit bug to that container. In other words,
6352 		 * this must use capable(), not ns_capable().
6353 		 */
6354 		if (!capable(CAP_SYS_BOOT)) {
6355 			r = -EPERM;
6356 			break;
6357 		}
6358 
6359 		if (cap->args[0])
6360 			break;
6361 
6362 		mutex_lock(&kvm->lock);
6363 		if (!kvm->created_vcpus) {
6364 			kvm->arch.disable_nx_huge_pages = true;
6365 			r = 0;
6366 		}
6367 		mutex_unlock(&kvm->lock);
6368 		break;
6369 	default:
6370 		r = -EINVAL;
6371 		break;
6372 	}
6373 	return r;
6374 }
6375 
6376 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6377 {
6378 	struct kvm_x86_msr_filter *msr_filter;
6379 
6380 	msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6381 	if (!msr_filter)
6382 		return NULL;
6383 
6384 	msr_filter->default_allow = default_allow;
6385 	return msr_filter;
6386 }
6387 
6388 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
6389 {
6390 	u32 i;
6391 
6392 	if (!msr_filter)
6393 		return;
6394 
6395 	for (i = 0; i < msr_filter->count; i++)
6396 		kfree(msr_filter->ranges[i].bitmap);
6397 
6398 	kfree(msr_filter);
6399 }
6400 
6401 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6402 			      struct kvm_msr_filter_range *user_range)
6403 {
6404 	unsigned long *bitmap = NULL;
6405 	size_t bitmap_size;
6406 
6407 	if (!user_range->nmsrs)
6408 		return 0;
6409 
6410 	if (user_range->flags & ~(KVM_MSR_FILTER_READ | KVM_MSR_FILTER_WRITE))
6411 		return -EINVAL;
6412 
6413 	if (!user_range->flags)
6414 		return -EINVAL;
6415 
6416 	bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6417 	if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6418 		return -EINVAL;
6419 
6420 	bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6421 	if (IS_ERR(bitmap))
6422 		return PTR_ERR(bitmap);
6423 
6424 	msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
6425 		.flags = user_range->flags,
6426 		.base = user_range->base,
6427 		.nmsrs = user_range->nmsrs,
6428 		.bitmap = bitmap,
6429 	};
6430 
6431 	msr_filter->count++;
6432 	return 0;
6433 }
6434 
6435 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
6436 				       struct kvm_msr_filter *filter)
6437 {
6438 	struct kvm_x86_msr_filter *new_filter, *old_filter;
6439 	bool default_allow;
6440 	bool empty = true;
6441 	int r = 0;
6442 	u32 i;
6443 
6444 	if (filter->flags & ~KVM_MSR_FILTER_DEFAULT_DENY)
6445 		return -EINVAL;
6446 
6447 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
6448 		empty &= !filter->ranges[i].nmsrs;
6449 
6450 	default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
6451 	if (empty && !default_allow)
6452 		return -EINVAL;
6453 
6454 	new_filter = kvm_alloc_msr_filter(default_allow);
6455 	if (!new_filter)
6456 		return -ENOMEM;
6457 
6458 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
6459 		r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
6460 		if (r) {
6461 			kvm_free_msr_filter(new_filter);
6462 			return r;
6463 		}
6464 	}
6465 
6466 	mutex_lock(&kvm->lock);
6467 
6468 	/* The per-VM filter is protected by kvm->lock... */
6469 	old_filter = srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1);
6470 
6471 	rcu_assign_pointer(kvm->arch.msr_filter, new_filter);
6472 	synchronize_srcu(&kvm->srcu);
6473 
6474 	kvm_free_msr_filter(old_filter);
6475 
6476 	kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
6477 	mutex_unlock(&kvm->lock);
6478 
6479 	return 0;
6480 }
6481 
6482 #ifdef CONFIG_KVM_COMPAT
6483 /* for KVM_X86_SET_MSR_FILTER */
6484 struct kvm_msr_filter_range_compat {
6485 	__u32 flags;
6486 	__u32 nmsrs;
6487 	__u32 base;
6488 	__u32 bitmap;
6489 };
6490 
6491 struct kvm_msr_filter_compat {
6492 	__u32 flags;
6493 	struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
6494 };
6495 
6496 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
6497 
6498 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
6499 			      unsigned long arg)
6500 {
6501 	void __user *argp = (void __user *)arg;
6502 	struct kvm *kvm = filp->private_data;
6503 	long r = -ENOTTY;
6504 
6505 	switch (ioctl) {
6506 	case KVM_X86_SET_MSR_FILTER_COMPAT: {
6507 		struct kvm_msr_filter __user *user_msr_filter = argp;
6508 		struct kvm_msr_filter_compat filter_compat;
6509 		struct kvm_msr_filter filter;
6510 		int i;
6511 
6512 		if (copy_from_user(&filter_compat, user_msr_filter,
6513 				   sizeof(filter_compat)))
6514 			return -EFAULT;
6515 
6516 		filter.flags = filter_compat.flags;
6517 		for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
6518 			struct kvm_msr_filter_range_compat *cr;
6519 
6520 			cr = &filter_compat.ranges[i];
6521 			filter.ranges[i] = (struct kvm_msr_filter_range) {
6522 				.flags = cr->flags,
6523 				.nmsrs = cr->nmsrs,
6524 				.base = cr->base,
6525 				.bitmap = (__u8 *)(ulong)cr->bitmap,
6526 			};
6527 		}
6528 
6529 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
6530 		break;
6531 	}
6532 	}
6533 
6534 	return r;
6535 }
6536 #endif
6537 
6538 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
6539 static int kvm_arch_suspend_notifier(struct kvm *kvm)
6540 {
6541 	struct kvm_vcpu *vcpu;
6542 	unsigned long i;
6543 	int ret = 0;
6544 
6545 	mutex_lock(&kvm->lock);
6546 	kvm_for_each_vcpu(i, vcpu, kvm) {
6547 		if (!vcpu->arch.pv_time.active)
6548 			continue;
6549 
6550 		ret = kvm_set_guest_paused(vcpu);
6551 		if (ret) {
6552 			kvm_err("Failed to pause guest VCPU%d: %d\n",
6553 				vcpu->vcpu_id, ret);
6554 			break;
6555 		}
6556 	}
6557 	mutex_unlock(&kvm->lock);
6558 
6559 	return ret ? NOTIFY_BAD : NOTIFY_DONE;
6560 }
6561 
6562 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6563 {
6564 	switch (state) {
6565 	case PM_HIBERNATION_PREPARE:
6566 	case PM_SUSPEND_PREPARE:
6567 		return kvm_arch_suspend_notifier(kvm);
6568 	}
6569 
6570 	return NOTIFY_DONE;
6571 }
6572 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
6573 
6574 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
6575 {
6576 	struct kvm_clock_data data = { 0 };
6577 
6578 	get_kvmclock(kvm, &data);
6579 	if (copy_to_user(argp, &data, sizeof(data)))
6580 		return -EFAULT;
6581 
6582 	return 0;
6583 }
6584 
6585 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
6586 {
6587 	struct kvm_arch *ka = &kvm->arch;
6588 	struct kvm_clock_data data;
6589 	u64 now_raw_ns;
6590 
6591 	if (copy_from_user(&data, argp, sizeof(data)))
6592 		return -EFAULT;
6593 
6594 	/*
6595 	 * Only KVM_CLOCK_REALTIME is used, but allow passing the
6596 	 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
6597 	 */
6598 	if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
6599 		return -EINVAL;
6600 
6601 	kvm_hv_request_tsc_page_update(kvm);
6602 	kvm_start_pvclock_update(kvm);
6603 	pvclock_update_vm_gtod_copy(kvm);
6604 
6605 	/*
6606 	 * This pairs with kvm_guest_time_update(): when masterclock is
6607 	 * in use, we use master_kernel_ns + kvmclock_offset to set
6608 	 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
6609 	 * is slightly ahead) here we risk going negative on unsigned
6610 	 * 'system_time' when 'data.clock' is very small.
6611 	 */
6612 	if (data.flags & KVM_CLOCK_REALTIME) {
6613 		u64 now_real_ns = ktime_get_real_ns();
6614 
6615 		/*
6616 		 * Avoid stepping the kvmclock backwards.
6617 		 */
6618 		if (now_real_ns > data.realtime)
6619 			data.clock += now_real_ns - data.realtime;
6620 	}
6621 
6622 	if (ka->use_master_clock)
6623 		now_raw_ns = ka->master_kernel_ns;
6624 	else
6625 		now_raw_ns = get_kvmclock_base_ns();
6626 	ka->kvmclock_offset = data.clock - now_raw_ns;
6627 	kvm_end_pvclock_update(kvm);
6628 	return 0;
6629 }
6630 
6631 long kvm_arch_vm_ioctl(struct file *filp,
6632 		       unsigned int ioctl, unsigned long arg)
6633 {
6634 	struct kvm *kvm = filp->private_data;
6635 	void __user *argp = (void __user *)arg;
6636 	int r = -ENOTTY;
6637 	/*
6638 	 * This union makes it completely explicit to gcc-3.x
6639 	 * that these two variables' stack usage should be
6640 	 * combined, not added together.
6641 	 */
6642 	union {
6643 		struct kvm_pit_state ps;
6644 		struct kvm_pit_state2 ps2;
6645 		struct kvm_pit_config pit_config;
6646 	} u;
6647 
6648 	switch (ioctl) {
6649 	case KVM_SET_TSS_ADDR:
6650 		r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
6651 		break;
6652 	case KVM_SET_IDENTITY_MAP_ADDR: {
6653 		u64 ident_addr;
6654 
6655 		mutex_lock(&kvm->lock);
6656 		r = -EINVAL;
6657 		if (kvm->created_vcpus)
6658 			goto set_identity_unlock;
6659 		r = -EFAULT;
6660 		if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
6661 			goto set_identity_unlock;
6662 		r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
6663 set_identity_unlock:
6664 		mutex_unlock(&kvm->lock);
6665 		break;
6666 	}
6667 	case KVM_SET_NR_MMU_PAGES:
6668 		r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
6669 		break;
6670 	case KVM_GET_NR_MMU_PAGES:
6671 		r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
6672 		break;
6673 	case KVM_CREATE_IRQCHIP: {
6674 		mutex_lock(&kvm->lock);
6675 
6676 		r = -EEXIST;
6677 		if (irqchip_in_kernel(kvm))
6678 			goto create_irqchip_unlock;
6679 
6680 		r = -EINVAL;
6681 		if (kvm->created_vcpus)
6682 			goto create_irqchip_unlock;
6683 
6684 		r = kvm_pic_init(kvm);
6685 		if (r)
6686 			goto create_irqchip_unlock;
6687 
6688 		r = kvm_ioapic_init(kvm);
6689 		if (r) {
6690 			kvm_pic_destroy(kvm);
6691 			goto create_irqchip_unlock;
6692 		}
6693 
6694 		r = kvm_setup_default_irq_routing(kvm);
6695 		if (r) {
6696 			kvm_ioapic_destroy(kvm);
6697 			kvm_pic_destroy(kvm);
6698 			goto create_irqchip_unlock;
6699 		}
6700 		/* Write kvm->irq_routing before enabling irqchip_in_kernel. */
6701 		smp_wmb();
6702 		kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
6703 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6704 	create_irqchip_unlock:
6705 		mutex_unlock(&kvm->lock);
6706 		break;
6707 	}
6708 	case KVM_CREATE_PIT:
6709 		u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
6710 		goto create_pit;
6711 	case KVM_CREATE_PIT2:
6712 		r = -EFAULT;
6713 		if (copy_from_user(&u.pit_config, argp,
6714 				   sizeof(struct kvm_pit_config)))
6715 			goto out;
6716 	create_pit:
6717 		mutex_lock(&kvm->lock);
6718 		r = -EEXIST;
6719 		if (kvm->arch.vpit)
6720 			goto create_pit_unlock;
6721 		r = -ENOMEM;
6722 		kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
6723 		if (kvm->arch.vpit)
6724 			r = 0;
6725 	create_pit_unlock:
6726 		mutex_unlock(&kvm->lock);
6727 		break;
6728 	case KVM_GET_IRQCHIP: {
6729 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
6730 		struct kvm_irqchip *chip;
6731 
6732 		chip = memdup_user(argp, sizeof(*chip));
6733 		if (IS_ERR(chip)) {
6734 			r = PTR_ERR(chip);
6735 			goto out;
6736 		}
6737 
6738 		r = -ENXIO;
6739 		if (!irqchip_kernel(kvm))
6740 			goto get_irqchip_out;
6741 		r = kvm_vm_ioctl_get_irqchip(kvm, chip);
6742 		if (r)
6743 			goto get_irqchip_out;
6744 		r = -EFAULT;
6745 		if (copy_to_user(argp, chip, sizeof(*chip)))
6746 			goto get_irqchip_out;
6747 		r = 0;
6748 	get_irqchip_out:
6749 		kfree(chip);
6750 		break;
6751 	}
6752 	case KVM_SET_IRQCHIP: {
6753 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
6754 		struct kvm_irqchip *chip;
6755 
6756 		chip = memdup_user(argp, sizeof(*chip));
6757 		if (IS_ERR(chip)) {
6758 			r = PTR_ERR(chip);
6759 			goto out;
6760 		}
6761 
6762 		r = -ENXIO;
6763 		if (!irqchip_kernel(kvm))
6764 			goto set_irqchip_out;
6765 		r = kvm_vm_ioctl_set_irqchip(kvm, chip);
6766 	set_irqchip_out:
6767 		kfree(chip);
6768 		break;
6769 	}
6770 	case KVM_GET_PIT: {
6771 		r = -EFAULT;
6772 		if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
6773 			goto out;
6774 		r = -ENXIO;
6775 		if (!kvm->arch.vpit)
6776 			goto out;
6777 		r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
6778 		if (r)
6779 			goto out;
6780 		r = -EFAULT;
6781 		if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
6782 			goto out;
6783 		r = 0;
6784 		break;
6785 	}
6786 	case KVM_SET_PIT: {
6787 		r = -EFAULT;
6788 		if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
6789 			goto out;
6790 		mutex_lock(&kvm->lock);
6791 		r = -ENXIO;
6792 		if (!kvm->arch.vpit)
6793 			goto set_pit_out;
6794 		r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
6795 set_pit_out:
6796 		mutex_unlock(&kvm->lock);
6797 		break;
6798 	}
6799 	case KVM_GET_PIT2: {
6800 		r = -ENXIO;
6801 		if (!kvm->arch.vpit)
6802 			goto out;
6803 		r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
6804 		if (r)
6805 			goto out;
6806 		r = -EFAULT;
6807 		if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
6808 			goto out;
6809 		r = 0;
6810 		break;
6811 	}
6812 	case KVM_SET_PIT2: {
6813 		r = -EFAULT;
6814 		if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
6815 			goto out;
6816 		mutex_lock(&kvm->lock);
6817 		r = -ENXIO;
6818 		if (!kvm->arch.vpit)
6819 			goto set_pit2_out;
6820 		r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
6821 set_pit2_out:
6822 		mutex_unlock(&kvm->lock);
6823 		break;
6824 	}
6825 	case KVM_REINJECT_CONTROL: {
6826 		struct kvm_reinject_control control;
6827 		r =  -EFAULT;
6828 		if (copy_from_user(&control, argp, sizeof(control)))
6829 			goto out;
6830 		r = -ENXIO;
6831 		if (!kvm->arch.vpit)
6832 			goto out;
6833 		r = kvm_vm_ioctl_reinject(kvm, &control);
6834 		break;
6835 	}
6836 	case KVM_SET_BOOT_CPU_ID:
6837 		r = 0;
6838 		mutex_lock(&kvm->lock);
6839 		if (kvm->created_vcpus)
6840 			r = -EBUSY;
6841 		else
6842 			kvm->arch.bsp_vcpu_id = arg;
6843 		mutex_unlock(&kvm->lock);
6844 		break;
6845 #ifdef CONFIG_KVM_XEN
6846 	case KVM_XEN_HVM_CONFIG: {
6847 		struct kvm_xen_hvm_config xhc;
6848 		r = -EFAULT;
6849 		if (copy_from_user(&xhc, argp, sizeof(xhc)))
6850 			goto out;
6851 		r = kvm_xen_hvm_config(kvm, &xhc);
6852 		break;
6853 	}
6854 	case KVM_XEN_HVM_GET_ATTR: {
6855 		struct kvm_xen_hvm_attr xha;
6856 
6857 		r = -EFAULT;
6858 		if (copy_from_user(&xha, argp, sizeof(xha)))
6859 			goto out;
6860 		r = kvm_xen_hvm_get_attr(kvm, &xha);
6861 		if (!r && copy_to_user(argp, &xha, sizeof(xha)))
6862 			r = -EFAULT;
6863 		break;
6864 	}
6865 	case KVM_XEN_HVM_SET_ATTR: {
6866 		struct kvm_xen_hvm_attr xha;
6867 
6868 		r = -EFAULT;
6869 		if (copy_from_user(&xha, argp, sizeof(xha)))
6870 			goto out;
6871 		r = kvm_xen_hvm_set_attr(kvm, &xha);
6872 		break;
6873 	}
6874 	case KVM_XEN_HVM_EVTCHN_SEND: {
6875 		struct kvm_irq_routing_xen_evtchn uxe;
6876 
6877 		r = -EFAULT;
6878 		if (copy_from_user(&uxe, argp, sizeof(uxe)))
6879 			goto out;
6880 		r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
6881 		break;
6882 	}
6883 #endif
6884 	case KVM_SET_CLOCK:
6885 		r = kvm_vm_ioctl_set_clock(kvm, argp);
6886 		break;
6887 	case KVM_GET_CLOCK:
6888 		r = kvm_vm_ioctl_get_clock(kvm, argp);
6889 		break;
6890 	case KVM_SET_TSC_KHZ: {
6891 		u32 user_tsc_khz;
6892 
6893 		r = -EINVAL;
6894 		user_tsc_khz = (u32)arg;
6895 
6896 		if (kvm_caps.has_tsc_control &&
6897 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6898 			goto out;
6899 
6900 		if (user_tsc_khz == 0)
6901 			user_tsc_khz = tsc_khz;
6902 
6903 		WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
6904 		r = 0;
6905 
6906 		goto out;
6907 	}
6908 	case KVM_GET_TSC_KHZ: {
6909 		r = READ_ONCE(kvm->arch.default_tsc_khz);
6910 		goto out;
6911 	}
6912 	case KVM_MEMORY_ENCRYPT_OP: {
6913 		r = -ENOTTY;
6914 		if (!kvm_x86_ops.mem_enc_ioctl)
6915 			goto out;
6916 
6917 		r = static_call(kvm_x86_mem_enc_ioctl)(kvm, argp);
6918 		break;
6919 	}
6920 	case KVM_MEMORY_ENCRYPT_REG_REGION: {
6921 		struct kvm_enc_region region;
6922 
6923 		r = -EFAULT;
6924 		if (copy_from_user(&region, argp, sizeof(region)))
6925 			goto out;
6926 
6927 		r = -ENOTTY;
6928 		if (!kvm_x86_ops.mem_enc_register_region)
6929 			goto out;
6930 
6931 		r = static_call(kvm_x86_mem_enc_register_region)(kvm, &region);
6932 		break;
6933 	}
6934 	case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
6935 		struct kvm_enc_region region;
6936 
6937 		r = -EFAULT;
6938 		if (copy_from_user(&region, argp, sizeof(region)))
6939 			goto out;
6940 
6941 		r = -ENOTTY;
6942 		if (!kvm_x86_ops.mem_enc_unregister_region)
6943 			goto out;
6944 
6945 		r = static_call(kvm_x86_mem_enc_unregister_region)(kvm, &region);
6946 		break;
6947 	}
6948 	case KVM_HYPERV_EVENTFD: {
6949 		struct kvm_hyperv_eventfd hvevfd;
6950 
6951 		r = -EFAULT;
6952 		if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
6953 			goto out;
6954 		r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
6955 		break;
6956 	}
6957 	case KVM_SET_PMU_EVENT_FILTER:
6958 		r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
6959 		break;
6960 	case KVM_X86_SET_MSR_FILTER: {
6961 		struct kvm_msr_filter __user *user_msr_filter = argp;
6962 		struct kvm_msr_filter filter;
6963 
6964 		if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
6965 			return -EFAULT;
6966 
6967 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
6968 		break;
6969 	}
6970 	default:
6971 		r = -ENOTTY;
6972 	}
6973 out:
6974 	return r;
6975 }
6976 
6977 static void kvm_init_msr_list(void)
6978 {
6979 	u32 dummy[2];
6980 	unsigned i;
6981 
6982 	BUILD_BUG_ON_MSG(KVM_PMC_MAX_FIXED != 3,
6983 			 "Please update the fixed PMCs in msrs_to_saved_all[]");
6984 
6985 	num_msrs_to_save = 0;
6986 	num_emulated_msrs = 0;
6987 	num_msr_based_features = 0;
6988 
6989 	for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
6990 		if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
6991 			continue;
6992 
6993 		/*
6994 		 * Even MSRs that are valid in the host may not be exposed
6995 		 * to the guests in some cases.
6996 		 */
6997 		switch (msrs_to_save_all[i]) {
6998 		case MSR_IA32_BNDCFGS:
6999 			if (!kvm_mpx_supported())
7000 				continue;
7001 			break;
7002 		case MSR_TSC_AUX:
7003 			if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7004 			    !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7005 				continue;
7006 			break;
7007 		case MSR_IA32_UMWAIT_CONTROL:
7008 			if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7009 				continue;
7010 			break;
7011 		case MSR_IA32_RTIT_CTL:
7012 		case MSR_IA32_RTIT_STATUS:
7013 			if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7014 				continue;
7015 			break;
7016 		case MSR_IA32_RTIT_CR3_MATCH:
7017 			if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7018 			    !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7019 				continue;
7020 			break;
7021 		case MSR_IA32_RTIT_OUTPUT_BASE:
7022 		case MSR_IA32_RTIT_OUTPUT_MASK:
7023 			if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7024 				(!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7025 				 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7026 				continue;
7027 			break;
7028 		case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7029 			if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7030 				msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
7031 				intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
7032 				continue;
7033 			break;
7034 		case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR_MAX:
7035 			if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
7036 			    min(KVM_INTEL_PMC_MAX_GENERIC, kvm_pmu_cap.num_counters_gp))
7037 				continue;
7038 			break;
7039 		case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL_MAX:
7040 			if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
7041 			    min(KVM_INTEL_PMC_MAX_GENERIC, kvm_pmu_cap.num_counters_gp))
7042 				continue;
7043 			break;
7044 		case MSR_IA32_XFD:
7045 		case MSR_IA32_XFD_ERR:
7046 			if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7047 				continue;
7048 			break;
7049 		default:
7050 			break;
7051 		}
7052 
7053 		msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
7054 	}
7055 
7056 	for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7057 		if (!static_call(kvm_x86_has_emulated_msr)(NULL, emulated_msrs_all[i]))
7058 			continue;
7059 
7060 		emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7061 	}
7062 
7063 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
7064 		struct kvm_msr_entry msr;
7065 
7066 		msr.index = msr_based_features_all[i];
7067 		if (kvm_get_msr_feature(&msr))
7068 			continue;
7069 
7070 		msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
7071 	}
7072 }
7073 
7074 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7075 			   const void *v)
7076 {
7077 	int handled = 0;
7078 	int n;
7079 
7080 	do {
7081 		n = min(len, 8);
7082 		if (!(lapic_in_kernel(vcpu) &&
7083 		      !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7084 		    && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7085 			break;
7086 		handled += n;
7087 		addr += n;
7088 		len -= n;
7089 		v += n;
7090 	} while (len);
7091 
7092 	return handled;
7093 }
7094 
7095 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7096 {
7097 	int handled = 0;
7098 	int n;
7099 
7100 	do {
7101 		n = min(len, 8);
7102 		if (!(lapic_in_kernel(vcpu) &&
7103 		      !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7104 					 addr, n, v))
7105 		    && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7106 			break;
7107 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7108 		handled += n;
7109 		addr += n;
7110 		len -= n;
7111 		v += n;
7112 	} while (len);
7113 
7114 	return handled;
7115 }
7116 
7117 void kvm_set_segment(struct kvm_vcpu *vcpu,
7118 		     struct kvm_segment *var, int seg)
7119 {
7120 	static_call(kvm_x86_set_segment)(vcpu, var, seg);
7121 }
7122 
7123 void kvm_get_segment(struct kvm_vcpu *vcpu,
7124 		     struct kvm_segment *var, int seg)
7125 {
7126 	static_call(kvm_x86_get_segment)(vcpu, var, seg);
7127 }
7128 
7129 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7130 			   struct x86_exception *exception)
7131 {
7132 	struct kvm_mmu *mmu = vcpu->arch.mmu;
7133 	gpa_t t_gpa;
7134 
7135 	BUG_ON(!mmu_is_nested(vcpu));
7136 
7137 	/* NPT walks are always user-walks */
7138 	access |= PFERR_USER_MASK;
7139 	t_gpa  = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7140 
7141 	return t_gpa;
7142 }
7143 
7144 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7145 			      struct x86_exception *exception)
7146 {
7147 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7148 
7149 	u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7150 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7151 }
7152 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
7153 
7154 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7155 			       struct x86_exception *exception)
7156 {
7157 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7158 
7159 	u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7160 	access |= PFERR_WRITE_MASK;
7161 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7162 }
7163 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
7164 
7165 /* uses this to access any guest's mapped memory without checking CPL */
7166 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7167 				struct x86_exception *exception)
7168 {
7169 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7170 
7171 	return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7172 }
7173 
7174 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7175 				      struct kvm_vcpu *vcpu, u64 access,
7176 				      struct x86_exception *exception)
7177 {
7178 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7179 	void *data = val;
7180 	int r = X86EMUL_CONTINUE;
7181 
7182 	while (bytes) {
7183 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7184 		unsigned offset = addr & (PAGE_SIZE-1);
7185 		unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7186 		int ret;
7187 
7188 		if (gpa == INVALID_GPA)
7189 			return X86EMUL_PROPAGATE_FAULT;
7190 		ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7191 					       offset, toread);
7192 		if (ret < 0) {
7193 			r = X86EMUL_IO_NEEDED;
7194 			goto out;
7195 		}
7196 
7197 		bytes -= toread;
7198 		data += toread;
7199 		addr += toread;
7200 	}
7201 out:
7202 	return r;
7203 }
7204 
7205 /* used for instruction fetching */
7206 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7207 				gva_t addr, void *val, unsigned int bytes,
7208 				struct x86_exception *exception)
7209 {
7210 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7211 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7212 	u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7213 	unsigned offset;
7214 	int ret;
7215 
7216 	/* Inline kvm_read_guest_virt_helper for speed.  */
7217 	gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7218 				    exception);
7219 	if (unlikely(gpa == INVALID_GPA))
7220 		return X86EMUL_PROPAGATE_FAULT;
7221 
7222 	offset = addr & (PAGE_SIZE-1);
7223 	if (WARN_ON(offset + bytes > PAGE_SIZE))
7224 		bytes = (unsigned)PAGE_SIZE - offset;
7225 	ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7226 				       offset, bytes);
7227 	if (unlikely(ret < 0))
7228 		return X86EMUL_IO_NEEDED;
7229 
7230 	return X86EMUL_CONTINUE;
7231 }
7232 
7233 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7234 			       gva_t addr, void *val, unsigned int bytes,
7235 			       struct x86_exception *exception)
7236 {
7237 	u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7238 
7239 	/*
7240 	 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7241 	 * is returned, but our callers are not ready for that and they blindly
7242 	 * call kvm_inject_page_fault.  Ensure that they at least do not leak
7243 	 * uninitialized kernel stack memory into cr2 and error code.
7244 	 */
7245 	memset(exception, 0, sizeof(*exception));
7246 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7247 					  exception);
7248 }
7249 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
7250 
7251 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7252 			     gva_t addr, void *val, unsigned int bytes,
7253 			     struct x86_exception *exception, bool system)
7254 {
7255 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7256 	u64 access = 0;
7257 
7258 	if (system)
7259 		access |= PFERR_IMPLICIT_ACCESS;
7260 	else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
7261 		access |= PFERR_USER_MASK;
7262 
7263 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7264 }
7265 
7266 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7267 				      struct kvm_vcpu *vcpu, u64 access,
7268 				      struct x86_exception *exception)
7269 {
7270 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7271 	void *data = val;
7272 	int r = X86EMUL_CONTINUE;
7273 
7274 	while (bytes) {
7275 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7276 		unsigned offset = addr & (PAGE_SIZE-1);
7277 		unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7278 		int ret;
7279 
7280 		if (gpa == INVALID_GPA)
7281 			return X86EMUL_PROPAGATE_FAULT;
7282 		ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7283 		if (ret < 0) {
7284 			r = X86EMUL_IO_NEEDED;
7285 			goto out;
7286 		}
7287 
7288 		bytes -= towrite;
7289 		data += towrite;
7290 		addr += towrite;
7291 	}
7292 out:
7293 	return r;
7294 }
7295 
7296 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7297 			      unsigned int bytes, struct x86_exception *exception,
7298 			      bool system)
7299 {
7300 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7301 	u64 access = PFERR_WRITE_MASK;
7302 
7303 	if (system)
7304 		access |= PFERR_IMPLICIT_ACCESS;
7305 	else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
7306 		access |= PFERR_USER_MASK;
7307 
7308 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7309 					   access, exception);
7310 }
7311 
7312 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7313 				unsigned int bytes, struct x86_exception *exception)
7314 {
7315 	/* kvm_write_guest_virt_system can pull in tons of pages. */
7316 	vcpu->arch.l1tf_flush_l1d = true;
7317 
7318 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7319 					   PFERR_WRITE_MASK, exception);
7320 }
7321 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
7322 
7323 static int kvm_can_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7324 				void *insn, int insn_len)
7325 {
7326 	return static_call(kvm_x86_can_emulate_instruction)(vcpu, emul_type,
7327 							    insn, insn_len);
7328 }
7329 
7330 int handle_ud(struct kvm_vcpu *vcpu)
7331 {
7332 	static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
7333 	int fep_flags = READ_ONCE(force_emulation_prefix);
7334 	int emul_type = EMULTYPE_TRAP_UD;
7335 	char sig[5]; /* ud2; .ascii "kvm" */
7336 	struct x86_exception e;
7337 
7338 	if (unlikely(!kvm_can_emulate_insn(vcpu, emul_type, NULL, 0)))
7339 		return 1;
7340 
7341 	if (fep_flags &&
7342 	    kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
7343 				sig, sizeof(sig), &e) == 0 &&
7344 	    memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
7345 		if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
7346 			kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
7347 		kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
7348 		emul_type = EMULTYPE_TRAP_UD_FORCED;
7349 	}
7350 
7351 	return kvm_emulate_instruction(vcpu, emul_type);
7352 }
7353 EXPORT_SYMBOL_GPL(handle_ud);
7354 
7355 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7356 			    gpa_t gpa, bool write)
7357 {
7358 	/* For APIC access vmexit */
7359 	if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7360 		return 1;
7361 
7362 	if (vcpu_match_mmio_gpa(vcpu, gpa)) {
7363 		trace_vcpu_match_mmio(gva, gpa, write, true);
7364 		return 1;
7365 	}
7366 
7367 	return 0;
7368 }
7369 
7370 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7371 				gpa_t *gpa, struct x86_exception *exception,
7372 				bool write)
7373 {
7374 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7375 	u64 access = ((static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
7376 		| (write ? PFERR_WRITE_MASK : 0);
7377 
7378 	/*
7379 	 * currently PKRU is only applied to ept enabled guest so
7380 	 * there is no pkey in EPT page table for L1 guest or EPT
7381 	 * shadow page table for L2 guest.
7382 	 */
7383 	if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
7384 	    !permission_fault(vcpu, vcpu->arch.walk_mmu,
7385 			      vcpu->arch.mmio_access, 0, access))) {
7386 		*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
7387 					(gva & (PAGE_SIZE - 1));
7388 		trace_vcpu_match_mmio(gva, *gpa, write, false);
7389 		return 1;
7390 	}
7391 
7392 	*gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7393 
7394 	if (*gpa == INVALID_GPA)
7395 		return -1;
7396 
7397 	return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
7398 }
7399 
7400 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
7401 			const void *val, int bytes)
7402 {
7403 	int ret;
7404 
7405 	ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
7406 	if (ret < 0)
7407 		return 0;
7408 	kvm_page_track_write(vcpu, gpa, val, bytes);
7409 	return 1;
7410 }
7411 
7412 struct read_write_emulator_ops {
7413 	int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
7414 				  int bytes);
7415 	int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
7416 				  void *val, int bytes);
7417 	int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7418 			       int bytes, void *val);
7419 	int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7420 				    void *val, int bytes);
7421 	bool write;
7422 };
7423 
7424 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
7425 {
7426 	if (vcpu->mmio_read_completed) {
7427 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
7428 			       vcpu->mmio_fragments[0].gpa, val);
7429 		vcpu->mmio_read_completed = 0;
7430 		return 1;
7431 	}
7432 
7433 	return 0;
7434 }
7435 
7436 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7437 			void *val, int bytes)
7438 {
7439 	return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
7440 }
7441 
7442 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7443 			 void *val, int bytes)
7444 {
7445 	return emulator_write_phys(vcpu, gpa, val, bytes);
7446 }
7447 
7448 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7449 {
7450 	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
7451 	return vcpu_mmio_write(vcpu, gpa, bytes, val);
7452 }
7453 
7454 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7455 			  void *val, int bytes)
7456 {
7457 	trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
7458 	return X86EMUL_IO_NEEDED;
7459 }
7460 
7461 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7462 			   void *val, int bytes)
7463 {
7464 	struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7465 
7466 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
7467 	return X86EMUL_CONTINUE;
7468 }
7469 
7470 static const struct read_write_emulator_ops read_emultor = {
7471 	.read_write_prepare = read_prepare,
7472 	.read_write_emulate = read_emulate,
7473 	.read_write_mmio = vcpu_mmio_read,
7474 	.read_write_exit_mmio = read_exit_mmio,
7475 };
7476 
7477 static const struct read_write_emulator_ops write_emultor = {
7478 	.read_write_emulate = write_emulate,
7479 	.read_write_mmio = write_mmio,
7480 	.read_write_exit_mmio = write_exit_mmio,
7481 	.write = true,
7482 };
7483 
7484 static int emulator_read_write_onepage(unsigned long addr, void *val,
7485 				       unsigned int bytes,
7486 				       struct x86_exception *exception,
7487 				       struct kvm_vcpu *vcpu,
7488 				       const struct read_write_emulator_ops *ops)
7489 {
7490 	gpa_t gpa;
7491 	int handled, ret;
7492 	bool write = ops->write;
7493 	struct kvm_mmio_fragment *frag;
7494 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7495 
7496 	/*
7497 	 * If the exit was due to a NPF we may already have a GPA.
7498 	 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7499 	 * Note, this cannot be used on string operations since string
7500 	 * operation using rep will only have the initial GPA from the NPF
7501 	 * occurred.
7502 	 */
7503 	if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7504 	    (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7505 		gpa = ctxt->gpa_val;
7506 		ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7507 	} else {
7508 		ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7509 		if (ret < 0)
7510 			return X86EMUL_PROPAGATE_FAULT;
7511 	}
7512 
7513 	if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
7514 		return X86EMUL_CONTINUE;
7515 
7516 	/*
7517 	 * Is this MMIO handled locally?
7518 	 */
7519 	handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
7520 	if (handled == bytes)
7521 		return X86EMUL_CONTINUE;
7522 
7523 	gpa += handled;
7524 	bytes -= handled;
7525 	val += handled;
7526 
7527 	WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
7528 	frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
7529 	frag->gpa = gpa;
7530 	frag->data = val;
7531 	frag->len = bytes;
7532 	return X86EMUL_CONTINUE;
7533 }
7534 
7535 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
7536 			unsigned long addr,
7537 			void *val, unsigned int bytes,
7538 			struct x86_exception *exception,
7539 			const struct read_write_emulator_ops *ops)
7540 {
7541 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7542 	gpa_t gpa;
7543 	int rc;
7544 
7545 	if (ops->read_write_prepare &&
7546 		  ops->read_write_prepare(vcpu, val, bytes))
7547 		return X86EMUL_CONTINUE;
7548 
7549 	vcpu->mmio_nr_fragments = 0;
7550 
7551 	/* Crossing a page boundary? */
7552 	if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
7553 		int now;
7554 
7555 		now = -addr & ~PAGE_MASK;
7556 		rc = emulator_read_write_onepage(addr, val, now, exception,
7557 						 vcpu, ops);
7558 
7559 		if (rc != X86EMUL_CONTINUE)
7560 			return rc;
7561 		addr += now;
7562 		if (ctxt->mode != X86EMUL_MODE_PROT64)
7563 			addr = (u32)addr;
7564 		val += now;
7565 		bytes -= now;
7566 	}
7567 
7568 	rc = emulator_read_write_onepage(addr, val, bytes, exception,
7569 					 vcpu, ops);
7570 	if (rc != X86EMUL_CONTINUE)
7571 		return rc;
7572 
7573 	if (!vcpu->mmio_nr_fragments)
7574 		return rc;
7575 
7576 	gpa = vcpu->mmio_fragments[0].gpa;
7577 
7578 	vcpu->mmio_needed = 1;
7579 	vcpu->mmio_cur_fragment = 0;
7580 
7581 	vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
7582 	vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
7583 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
7584 	vcpu->run->mmio.phys_addr = gpa;
7585 
7586 	return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
7587 }
7588 
7589 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
7590 				  unsigned long addr,
7591 				  void *val,
7592 				  unsigned int bytes,
7593 				  struct x86_exception *exception)
7594 {
7595 	return emulator_read_write(ctxt, addr, val, bytes,
7596 				   exception, &read_emultor);
7597 }
7598 
7599 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
7600 			    unsigned long addr,
7601 			    const void *val,
7602 			    unsigned int bytes,
7603 			    struct x86_exception *exception)
7604 {
7605 	return emulator_read_write(ctxt, addr, (void *)val, bytes,
7606 				   exception, &write_emultor);
7607 }
7608 
7609 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
7610 	(__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
7611 
7612 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
7613 				     unsigned long addr,
7614 				     const void *old,
7615 				     const void *new,
7616 				     unsigned int bytes,
7617 				     struct x86_exception *exception)
7618 {
7619 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7620 	u64 page_line_mask;
7621 	unsigned long hva;
7622 	gpa_t gpa;
7623 	int r;
7624 
7625 	/* guests cmpxchg8b have to be emulated atomically */
7626 	if (bytes > 8 || (bytes & (bytes - 1)))
7627 		goto emul_write;
7628 
7629 	gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
7630 
7631 	if (gpa == INVALID_GPA ||
7632 	    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7633 		goto emul_write;
7634 
7635 	/*
7636 	 * Emulate the atomic as a straight write to avoid #AC if SLD is
7637 	 * enabled in the host and the access splits a cache line.
7638 	 */
7639 	if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
7640 		page_line_mask = ~(cache_line_size() - 1);
7641 	else
7642 		page_line_mask = PAGE_MASK;
7643 
7644 	if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
7645 		goto emul_write;
7646 
7647 	hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
7648 	if (kvm_is_error_hva(hva))
7649 		goto emul_write;
7650 
7651 	hva += offset_in_page(gpa);
7652 
7653 	switch (bytes) {
7654 	case 1:
7655 		r = emulator_try_cmpxchg_user(u8, hva, old, new);
7656 		break;
7657 	case 2:
7658 		r = emulator_try_cmpxchg_user(u16, hva, old, new);
7659 		break;
7660 	case 4:
7661 		r = emulator_try_cmpxchg_user(u32, hva, old, new);
7662 		break;
7663 	case 8:
7664 		r = emulator_try_cmpxchg_user(u64, hva, old, new);
7665 		break;
7666 	default:
7667 		BUG();
7668 	}
7669 
7670 	if (r < 0)
7671 		return X86EMUL_UNHANDLEABLE;
7672 	if (r)
7673 		return X86EMUL_CMPXCHG_FAILED;
7674 
7675 	kvm_page_track_write(vcpu, gpa, new, bytes);
7676 
7677 	return X86EMUL_CONTINUE;
7678 
7679 emul_write:
7680 	printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
7681 
7682 	return emulator_write_emulated(ctxt, addr, new, bytes, exception);
7683 }
7684 
7685 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
7686 			       unsigned short port, void *data,
7687 			       unsigned int count, bool in)
7688 {
7689 	unsigned i;
7690 	int r;
7691 
7692 	WARN_ON_ONCE(vcpu->arch.pio.count);
7693 	for (i = 0; i < count; i++) {
7694 		if (in)
7695 			r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
7696 		else
7697 			r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
7698 
7699 		if (r) {
7700 			if (i == 0)
7701 				goto userspace_io;
7702 
7703 			/*
7704 			 * Userspace must have unregistered the device while PIO
7705 			 * was running.  Drop writes / read as 0.
7706 			 */
7707 			if (in)
7708 				memset(data, 0, size * (count - i));
7709 			break;
7710 		}
7711 
7712 		data += size;
7713 	}
7714 	return 1;
7715 
7716 userspace_io:
7717 	vcpu->arch.pio.port = port;
7718 	vcpu->arch.pio.in = in;
7719 	vcpu->arch.pio.count = count;
7720 	vcpu->arch.pio.size = size;
7721 
7722 	if (in)
7723 		memset(vcpu->arch.pio_data, 0, size * count);
7724 	else
7725 		memcpy(vcpu->arch.pio_data, data, size * count);
7726 
7727 	vcpu->run->exit_reason = KVM_EXIT_IO;
7728 	vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
7729 	vcpu->run->io.size = size;
7730 	vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
7731 	vcpu->run->io.count = count;
7732 	vcpu->run->io.port = port;
7733 	return 0;
7734 }
7735 
7736 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
7737       			   unsigned short port, void *val, unsigned int count)
7738 {
7739 	int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
7740 	if (r)
7741 		trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
7742 
7743 	return r;
7744 }
7745 
7746 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
7747 {
7748 	int size = vcpu->arch.pio.size;
7749 	unsigned int count = vcpu->arch.pio.count;
7750 	memcpy(val, vcpu->arch.pio_data, size * count);
7751 	trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
7752 	vcpu->arch.pio.count = 0;
7753 }
7754 
7755 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
7756 				    int size, unsigned short port, void *val,
7757 				    unsigned int count)
7758 {
7759 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7760 	if (vcpu->arch.pio.count) {
7761 		/*
7762 		 * Complete a previous iteration that required userspace I/O.
7763 		 * Note, @count isn't guaranteed to match pio.count as userspace
7764 		 * can modify ECX before rerunning the vCPU.  Ignore any such
7765 		 * shenanigans as KVM doesn't support modifying the rep count,
7766 		 * and the emulator ensures @count doesn't overflow the buffer.
7767 		 */
7768 		complete_emulator_pio_in(vcpu, val);
7769 		return 1;
7770 	}
7771 
7772 	return emulator_pio_in(vcpu, size, port, val, count);
7773 }
7774 
7775 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
7776 			    unsigned short port, const void *val,
7777 			    unsigned int count)
7778 {
7779 	trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
7780 	return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
7781 }
7782 
7783 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
7784 				     int size, unsigned short port,
7785 				     const void *val, unsigned int count)
7786 {
7787 	return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
7788 }
7789 
7790 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
7791 {
7792 	return static_call(kvm_x86_get_segment_base)(vcpu, seg);
7793 }
7794 
7795 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
7796 {
7797 	kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
7798 }
7799 
7800 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
7801 {
7802 	if (!need_emulate_wbinvd(vcpu))
7803 		return X86EMUL_CONTINUE;
7804 
7805 	if (static_call(kvm_x86_has_wbinvd_exit)()) {
7806 		int cpu = get_cpu();
7807 
7808 		cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
7809 		on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
7810 				wbinvd_ipi, NULL, 1);
7811 		put_cpu();
7812 		cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
7813 	} else
7814 		wbinvd();
7815 	return X86EMUL_CONTINUE;
7816 }
7817 
7818 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
7819 {
7820 	kvm_emulate_wbinvd_noskip(vcpu);
7821 	return kvm_skip_emulated_instruction(vcpu);
7822 }
7823 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
7824 
7825 
7826 
7827 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
7828 {
7829 	kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
7830 }
7831 
7832 static void emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
7833 			    unsigned long *dest)
7834 {
7835 	kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
7836 }
7837 
7838 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
7839 			   unsigned long value)
7840 {
7841 
7842 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
7843 }
7844 
7845 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
7846 {
7847 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
7848 }
7849 
7850 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
7851 {
7852 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7853 	unsigned long value;
7854 
7855 	switch (cr) {
7856 	case 0:
7857 		value = kvm_read_cr0(vcpu);
7858 		break;
7859 	case 2:
7860 		value = vcpu->arch.cr2;
7861 		break;
7862 	case 3:
7863 		value = kvm_read_cr3(vcpu);
7864 		break;
7865 	case 4:
7866 		value = kvm_read_cr4(vcpu);
7867 		break;
7868 	case 8:
7869 		value = kvm_get_cr8(vcpu);
7870 		break;
7871 	default:
7872 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
7873 		return 0;
7874 	}
7875 
7876 	return value;
7877 }
7878 
7879 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
7880 {
7881 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7882 	int res = 0;
7883 
7884 	switch (cr) {
7885 	case 0:
7886 		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
7887 		break;
7888 	case 2:
7889 		vcpu->arch.cr2 = val;
7890 		break;
7891 	case 3:
7892 		res = kvm_set_cr3(vcpu, val);
7893 		break;
7894 	case 4:
7895 		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
7896 		break;
7897 	case 8:
7898 		res = kvm_set_cr8(vcpu, val);
7899 		break;
7900 	default:
7901 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
7902 		res = -1;
7903 	}
7904 
7905 	return res;
7906 }
7907 
7908 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
7909 {
7910 	return static_call(kvm_x86_get_cpl)(emul_to_vcpu(ctxt));
7911 }
7912 
7913 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7914 {
7915 	static_call(kvm_x86_get_gdt)(emul_to_vcpu(ctxt), dt);
7916 }
7917 
7918 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7919 {
7920 	static_call(kvm_x86_get_idt)(emul_to_vcpu(ctxt), dt);
7921 }
7922 
7923 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7924 {
7925 	static_call(kvm_x86_set_gdt)(emul_to_vcpu(ctxt), dt);
7926 }
7927 
7928 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7929 {
7930 	static_call(kvm_x86_set_idt)(emul_to_vcpu(ctxt), dt);
7931 }
7932 
7933 static unsigned long emulator_get_cached_segment_base(
7934 	struct x86_emulate_ctxt *ctxt, int seg)
7935 {
7936 	return get_segment_base(emul_to_vcpu(ctxt), seg);
7937 }
7938 
7939 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
7940 				 struct desc_struct *desc, u32 *base3,
7941 				 int seg)
7942 {
7943 	struct kvm_segment var;
7944 
7945 	kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
7946 	*selector = var.selector;
7947 
7948 	if (var.unusable) {
7949 		memset(desc, 0, sizeof(*desc));
7950 		if (base3)
7951 			*base3 = 0;
7952 		return false;
7953 	}
7954 
7955 	if (var.g)
7956 		var.limit >>= 12;
7957 	set_desc_limit(desc, var.limit);
7958 	set_desc_base(desc, (unsigned long)var.base);
7959 #ifdef CONFIG_X86_64
7960 	if (base3)
7961 		*base3 = var.base >> 32;
7962 #endif
7963 	desc->type = var.type;
7964 	desc->s = var.s;
7965 	desc->dpl = var.dpl;
7966 	desc->p = var.present;
7967 	desc->avl = var.avl;
7968 	desc->l = var.l;
7969 	desc->d = var.db;
7970 	desc->g = var.g;
7971 
7972 	return true;
7973 }
7974 
7975 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
7976 				 struct desc_struct *desc, u32 base3,
7977 				 int seg)
7978 {
7979 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7980 	struct kvm_segment var;
7981 
7982 	var.selector = selector;
7983 	var.base = get_desc_base(desc);
7984 #ifdef CONFIG_X86_64
7985 	var.base |= ((u64)base3) << 32;
7986 #endif
7987 	var.limit = get_desc_limit(desc);
7988 	if (desc->g)
7989 		var.limit = (var.limit << 12) | 0xfff;
7990 	var.type = desc->type;
7991 	var.dpl = desc->dpl;
7992 	var.db = desc->d;
7993 	var.s = desc->s;
7994 	var.l = desc->l;
7995 	var.g = desc->g;
7996 	var.avl = desc->avl;
7997 	var.present = desc->p;
7998 	var.unusable = !var.present;
7999 	var.padding = 0;
8000 
8001 	kvm_set_segment(vcpu, &var, seg);
8002 	return;
8003 }
8004 
8005 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8006 					u32 msr_index, u64 *pdata)
8007 {
8008 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8009 	int r;
8010 
8011 	r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
8012 	if (r < 0)
8013 		return X86EMUL_UNHANDLEABLE;
8014 
8015 	if (r) {
8016 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8017 				       complete_emulated_rdmsr, r))
8018 			return X86EMUL_IO_NEEDED;
8019 
8020 		trace_kvm_msr_read_ex(msr_index);
8021 		return X86EMUL_PROPAGATE_FAULT;
8022 	}
8023 
8024 	trace_kvm_msr_read(msr_index, *pdata);
8025 	return X86EMUL_CONTINUE;
8026 }
8027 
8028 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8029 					u32 msr_index, u64 data)
8030 {
8031 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8032 	int r;
8033 
8034 	r = kvm_set_msr_with_filter(vcpu, msr_index, data);
8035 	if (r < 0)
8036 		return X86EMUL_UNHANDLEABLE;
8037 
8038 	if (r) {
8039 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8040 				       complete_emulated_msr_access, r))
8041 			return X86EMUL_IO_NEEDED;
8042 
8043 		trace_kvm_msr_write_ex(msr_index, data);
8044 		return X86EMUL_PROPAGATE_FAULT;
8045 	}
8046 
8047 	trace_kvm_msr_write(msr_index, data);
8048 	return X86EMUL_CONTINUE;
8049 }
8050 
8051 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8052 			    u32 msr_index, u64 *pdata)
8053 {
8054 	return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
8055 }
8056 
8057 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
8058 			      u32 pmc)
8059 {
8060 	if (kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc))
8061 		return 0;
8062 	return -EINVAL;
8063 }
8064 
8065 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8066 			     u32 pmc, u64 *pdata)
8067 {
8068 	return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8069 }
8070 
8071 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8072 {
8073 	emul_to_vcpu(ctxt)->arch.halt_request = 1;
8074 }
8075 
8076 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8077 			      struct x86_instruction_info *info,
8078 			      enum x86_intercept_stage stage)
8079 {
8080 	return static_call(kvm_x86_check_intercept)(emul_to_vcpu(ctxt), info, stage,
8081 					    &ctxt->exception);
8082 }
8083 
8084 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8085 			      u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8086 			      bool exact_only)
8087 {
8088 	return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8089 }
8090 
8091 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
8092 {
8093 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
8094 }
8095 
8096 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8097 {
8098 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8099 }
8100 
8101 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8102 {
8103 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8104 }
8105 
8106 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8107 {
8108 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8109 }
8110 
8111 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8112 {
8113 	return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8114 }
8115 
8116 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8117 {
8118 	kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8119 }
8120 
8121 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8122 {
8123 	static_call(kvm_x86_set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8124 }
8125 
8126 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
8127 {
8128 	return emul_to_vcpu(ctxt)->arch.hflags;
8129 }
8130 
8131 #ifndef CONFIG_KVM_SMM
8132 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8133 {
8134 	WARN_ON_ONCE(1);
8135 	return X86EMUL_UNHANDLEABLE;
8136 }
8137 #endif
8138 
8139 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8140 {
8141 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8142 }
8143 
8144 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8145 {
8146 	return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8147 }
8148 
8149 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8150 {
8151 	struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8152 
8153 	if (!kvm->vm_bugged)
8154 		kvm_vm_bugged(kvm);
8155 }
8156 
8157 static const struct x86_emulate_ops emulate_ops = {
8158 	.vm_bugged           = emulator_vm_bugged,
8159 	.read_gpr            = emulator_read_gpr,
8160 	.write_gpr           = emulator_write_gpr,
8161 	.read_std            = emulator_read_std,
8162 	.write_std           = emulator_write_std,
8163 	.fetch               = kvm_fetch_guest_virt,
8164 	.read_emulated       = emulator_read_emulated,
8165 	.write_emulated      = emulator_write_emulated,
8166 	.cmpxchg_emulated    = emulator_cmpxchg_emulated,
8167 	.invlpg              = emulator_invlpg,
8168 	.pio_in_emulated     = emulator_pio_in_emulated,
8169 	.pio_out_emulated    = emulator_pio_out_emulated,
8170 	.get_segment         = emulator_get_segment,
8171 	.set_segment         = emulator_set_segment,
8172 	.get_cached_segment_base = emulator_get_cached_segment_base,
8173 	.get_gdt             = emulator_get_gdt,
8174 	.get_idt	     = emulator_get_idt,
8175 	.set_gdt             = emulator_set_gdt,
8176 	.set_idt	     = emulator_set_idt,
8177 	.get_cr              = emulator_get_cr,
8178 	.set_cr              = emulator_set_cr,
8179 	.cpl                 = emulator_get_cpl,
8180 	.get_dr              = emulator_get_dr,
8181 	.set_dr              = emulator_set_dr,
8182 	.set_msr_with_filter = emulator_set_msr_with_filter,
8183 	.get_msr_with_filter = emulator_get_msr_with_filter,
8184 	.get_msr             = emulator_get_msr,
8185 	.check_pmc	     = emulator_check_pmc,
8186 	.read_pmc            = emulator_read_pmc,
8187 	.halt                = emulator_halt,
8188 	.wbinvd              = emulator_wbinvd,
8189 	.fix_hypercall       = emulator_fix_hypercall,
8190 	.intercept           = emulator_intercept,
8191 	.get_cpuid           = emulator_get_cpuid,
8192 	.guest_has_long_mode = emulator_guest_has_long_mode,
8193 	.guest_has_movbe     = emulator_guest_has_movbe,
8194 	.guest_has_fxsr      = emulator_guest_has_fxsr,
8195 	.guest_has_rdpid     = emulator_guest_has_rdpid,
8196 	.set_nmi_mask        = emulator_set_nmi_mask,
8197 	.get_hflags          = emulator_get_hflags,
8198 	.leave_smm           = emulator_leave_smm,
8199 	.triple_fault        = emulator_triple_fault,
8200 	.set_xcr             = emulator_set_xcr,
8201 };
8202 
8203 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8204 {
8205 	u32 int_shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
8206 	/*
8207 	 * an sti; sti; sequence only disable interrupts for the first
8208 	 * instruction. So, if the last instruction, be it emulated or
8209 	 * not, left the system with the INT_STI flag enabled, it
8210 	 * means that the last instruction is an sti. We should not
8211 	 * leave the flag on in this case. The same goes for mov ss
8212 	 */
8213 	if (int_shadow & mask)
8214 		mask = 0;
8215 	if (unlikely(int_shadow || mask)) {
8216 		static_call(kvm_x86_set_interrupt_shadow)(vcpu, mask);
8217 		if (!mask)
8218 			kvm_make_request(KVM_REQ_EVENT, vcpu);
8219 	}
8220 }
8221 
8222 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8223 {
8224 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8225 
8226 	if (ctxt->exception.vector == PF_VECTOR)
8227 		kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8228 	else if (ctxt->exception.error_code_valid)
8229 		kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8230 				      ctxt->exception.error_code);
8231 	else
8232 		kvm_queue_exception(vcpu, ctxt->exception.vector);
8233 }
8234 
8235 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8236 {
8237 	struct x86_emulate_ctxt *ctxt;
8238 
8239 	ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8240 	if (!ctxt) {
8241 		pr_err("kvm: failed to allocate vcpu's emulator\n");
8242 		return NULL;
8243 	}
8244 
8245 	ctxt->vcpu = vcpu;
8246 	ctxt->ops = &emulate_ops;
8247 	vcpu->arch.emulate_ctxt = ctxt;
8248 
8249 	return ctxt;
8250 }
8251 
8252 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8253 {
8254 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8255 	int cs_db, cs_l;
8256 
8257 	static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8258 
8259 	ctxt->gpa_available = false;
8260 	ctxt->eflags = kvm_get_rflags(vcpu);
8261 	ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8262 
8263 	ctxt->eip = kvm_rip_read(vcpu);
8264 	ctxt->mode = (!is_protmode(vcpu))		? X86EMUL_MODE_REAL :
8265 		     (ctxt->eflags & X86_EFLAGS_VM)	? X86EMUL_MODE_VM86 :
8266 		     (cs_l && is_long_mode(vcpu))	? X86EMUL_MODE_PROT64 :
8267 		     cs_db				? X86EMUL_MODE_PROT32 :
8268 							  X86EMUL_MODE_PROT16;
8269 	BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
8270 	BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
8271 	BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
8272 
8273 	ctxt->interruptibility = 0;
8274 	ctxt->have_exception = false;
8275 	ctxt->exception.vector = -1;
8276 	ctxt->perm_ok = false;
8277 
8278 	init_decode_cache(ctxt);
8279 	vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8280 }
8281 
8282 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8283 {
8284 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8285 	int ret;
8286 
8287 	init_emulate_ctxt(vcpu);
8288 
8289 	ctxt->op_bytes = 2;
8290 	ctxt->ad_bytes = 2;
8291 	ctxt->_eip = ctxt->eip + inc_eip;
8292 	ret = emulate_int_real(ctxt, irq);
8293 
8294 	if (ret != X86EMUL_CONTINUE) {
8295 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8296 	} else {
8297 		ctxt->eip = ctxt->_eip;
8298 		kvm_rip_write(vcpu, ctxt->eip);
8299 		kvm_set_rflags(vcpu, ctxt->eflags);
8300 	}
8301 }
8302 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
8303 
8304 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8305 					   u8 ndata, u8 *insn_bytes, u8 insn_size)
8306 {
8307 	struct kvm_run *run = vcpu->run;
8308 	u64 info[5];
8309 	u8 info_start;
8310 
8311 	/*
8312 	 * Zero the whole array used to retrieve the exit info, as casting to
8313 	 * u32 for select entries will leave some chunks uninitialized.
8314 	 */
8315 	memset(&info, 0, sizeof(info));
8316 
8317 	static_call(kvm_x86_get_exit_info)(vcpu, (u32 *)&info[0], &info[1],
8318 					   &info[2], (u32 *)&info[3],
8319 					   (u32 *)&info[4]);
8320 
8321 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8322 	run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
8323 
8324 	/*
8325 	 * There's currently space for 13 entries, but 5 are used for the exit
8326 	 * reason and info.  Restrict to 4 to reduce the maintenance burden
8327 	 * when expanding kvm_run.emulation_failure in the future.
8328 	 */
8329 	if (WARN_ON_ONCE(ndata > 4))
8330 		ndata = 4;
8331 
8332 	/* Always include the flags as a 'data' entry. */
8333 	info_start = 1;
8334 	run->emulation_failure.flags = 0;
8335 
8336 	if (insn_size) {
8337 		BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
8338 			      sizeof(run->emulation_failure.insn_bytes) != 16));
8339 		info_start += 2;
8340 		run->emulation_failure.flags |=
8341 			KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
8342 		run->emulation_failure.insn_size = insn_size;
8343 		memset(run->emulation_failure.insn_bytes, 0x90,
8344 		       sizeof(run->emulation_failure.insn_bytes));
8345 		memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
8346 	}
8347 
8348 	memcpy(&run->internal.data[info_start], info, sizeof(info));
8349 	memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
8350 	       ndata * sizeof(data[0]));
8351 
8352 	run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
8353 }
8354 
8355 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
8356 {
8357 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8358 
8359 	prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
8360 				       ctxt->fetch.end - ctxt->fetch.data);
8361 }
8362 
8363 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8364 					  u8 ndata)
8365 {
8366 	prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
8367 }
8368 EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
8369 
8370 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
8371 {
8372 	__kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
8373 }
8374 EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
8375 
8376 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
8377 {
8378 	struct kvm *kvm = vcpu->kvm;
8379 
8380 	++vcpu->stat.insn_emulation_fail;
8381 	trace_kvm_emulate_insn_failed(vcpu);
8382 
8383 	if (emulation_type & EMULTYPE_VMWARE_GP) {
8384 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8385 		return 1;
8386 	}
8387 
8388 	if (kvm->arch.exit_on_emulation_error ||
8389 	    (emulation_type & EMULTYPE_SKIP)) {
8390 		prepare_emulation_ctxt_failure_exit(vcpu);
8391 		return 0;
8392 	}
8393 
8394 	kvm_queue_exception(vcpu, UD_VECTOR);
8395 
8396 	if (!is_guest_mode(vcpu) && static_call(kvm_x86_get_cpl)(vcpu) == 0) {
8397 		prepare_emulation_ctxt_failure_exit(vcpu);
8398 		return 0;
8399 	}
8400 
8401 	return 1;
8402 }
8403 
8404 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
8405 				  bool write_fault_to_shadow_pgtable,
8406 				  int emulation_type)
8407 {
8408 	gpa_t gpa = cr2_or_gpa;
8409 	kvm_pfn_t pfn;
8410 
8411 	if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8412 		return false;
8413 
8414 	if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8415 	    WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
8416 		return false;
8417 
8418 	if (!vcpu->arch.mmu->root_role.direct) {
8419 		/*
8420 		 * Write permission should be allowed since only
8421 		 * write access need to be emulated.
8422 		 */
8423 		gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
8424 
8425 		/*
8426 		 * If the mapping is invalid in guest, let cpu retry
8427 		 * it to generate fault.
8428 		 */
8429 		if (gpa == INVALID_GPA)
8430 			return true;
8431 	}
8432 
8433 	/*
8434 	 * Do not retry the unhandleable instruction if it faults on the
8435 	 * readonly host memory, otherwise it will goto a infinite loop:
8436 	 * retry instruction -> write #PF -> emulation fail -> retry
8437 	 * instruction -> ...
8438 	 */
8439 	pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
8440 
8441 	/*
8442 	 * If the instruction failed on the error pfn, it can not be fixed,
8443 	 * report the error to userspace.
8444 	 */
8445 	if (is_error_noslot_pfn(pfn))
8446 		return false;
8447 
8448 	kvm_release_pfn_clean(pfn);
8449 
8450 	/* The instructions are well-emulated on direct mmu. */
8451 	if (vcpu->arch.mmu->root_role.direct) {
8452 		unsigned int indirect_shadow_pages;
8453 
8454 		write_lock(&vcpu->kvm->mmu_lock);
8455 		indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
8456 		write_unlock(&vcpu->kvm->mmu_lock);
8457 
8458 		if (indirect_shadow_pages)
8459 			kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8460 
8461 		return true;
8462 	}
8463 
8464 	/*
8465 	 * if emulation was due to access to shadowed page table
8466 	 * and it failed try to unshadow page and re-enter the
8467 	 * guest to let CPU execute the instruction.
8468 	 */
8469 	kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8470 
8471 	/*
8472 	 * If the access faults on its page table, it can not
8473 	 * be fixed by unprotecting shadow page and it should
8474 	 * be reported to userspace.
8475 	 */
8476 	return !write_fault_to_shadow_pgtable;
8477 }
8478 
8479 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
8480 			      gpa_t cr2_or_gpa,  int emulation_type)
8481 {
8482 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8483 	unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
8484 
8485 	last_retry_eip = vcpu->arch.last_retry_eip;
8486 	last_retry_addr = vcpu->arch.last_retry_addr;
8487 
8488 	/*
8489 	 * If the emulation is caused by #PF and it is non-page_table
8490 	 * writing instruction, it means the VM-EXIT is caused by shadow
8491 	 * page protected, we can zap the shadow page and retry this
8492 	 * instruction directly.
8493 	 *
8494 	 * Note: if the guest uses a non-page-table modifying instruction
8495 	 * on the PDE that points to the instruction, then we will unmap
8496 	 * the instruction and go to an infinite loop. So, we cache the
8497 	 * last retried eip and the last fault address, if we meet the eip
8498 	 * and the address again, we can break out of the potential infinite
8499 	 * loop.
8500 	 */
8501 	vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
8502 
8503 	if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8504 		return false;
8505 
8506 	if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8507 	    WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
8508 		return false;
8509 
8510 	if (x86_page_table_writing_insn(ctxt))
8511 		return false;
8512 
8513 	if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
8514 		return false;
8515 
8516 	vcpu->arch.last_retry_eip = ctxt->eip;
8517 	vcpu->arch.last_retry_addr = cr2_or_gpa;
8518 
8519 	if (!vcpu->arch.mmu->root_role.direct)
8520 		gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
8521 
8522 	kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8523 
8524 	return true;
8525 }
8526 
8527 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8528 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8529 
8530 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8531 				unsigned long *db)
8532 {
8533 	u32 dr6 = 0;
8534 	int i;
8535 	u32 enable, rwlen;
8536 
8537 	enable = dr7;
8538 	rwlen = dr7 >> 16;
8539 	for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8540 		if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8541 			dr6 |= (1 << i);
8542 	return dr6;
8543 }
8544 
8545 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
8546 {
8547 	struct kvm_run *kvm_run = vcpu->run;
8548 
8549 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
8550 		kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
8551 		kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
8552 		kvm_run->debug.arch.exception = DB_VECTOR;
8553 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
8554 		return 0;
8555 	}
8556 	kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
8557 	return 1;
8558 }
8559 
8560 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8561 {
8562 	unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
8563 	int r;
8564 
8565 	r = static_call(kvm_x86_skip_emulated_instruction)(vcpu);
8566 	if (unlikely(!r))
8567 		return 0;
8568 
8569 	kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
8570 
8571 	/*
8572 	 * rflags is the old, "raw" value of the flags.  The new value has
8573 	 * not been saved yet.
8574 	 *
8575 	 * This is correct even for TF set by the guest, because "the
8576 	 * processor will not generate this exception after the instruction
8577 	 * that sets the TF flag".
8578 	 */
8579 	if (unlikely(rflags & X86_EFLAGS_TF))
8580 		r = kvm_vcpu_do_singlestep(vcpu);
8581 	return r;
8582 }
8583 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
8584 
8585 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
8586 {
8587 	u32 shadow;
8588 
8589 	if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
8590 		return true;
8591 
8592 	/*
8593 	 * Intel CPUs inhibit code #DBs when MOV/POP SS blocking is active,
8594 	 * but AMD CPUs do not.  MOV/POP SS blocking is rare, check that first
8595 	 * to avoid the relatively expensive CPUID lookup.
8596 	 */
8597 	shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
8598 	return (shadow & KVM_X86_SHADOW_INT_MOV_SS) &&
8599 	       guest_cpuid_is_intel(vcpu);
8600 }
8601 
8602 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
8603 					   int emulation_type, int *r)
8604 {
8605 	WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
8606 
8607 	/*
8608 	 * Do not check for code breakpoints if hardware has already done the
8609 	 * checks, as inferred from the emulation type.  On NO_DECODE and SKIP,
8610 	 * the instruction has passed all exception checks, and all intercepted
8611 	 * exceptions that trigger emulation have lower priority than code
8612 	 * breakpoints, i.e. the fact that the intercepted exception occurred
8613 	 * means any code breakpoints have already been serviced.
8614 	 *
8615 	 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
8616 	 * hardware has checked the RIP of the magic prefix, but not the RIP of
8617 	 * the instruction being emulated.  The intent of forced emulation is
8618 	 * to behave as if KVM intercepted the instruction without an exception
8619 	 * and without a prefix.
8620 	 */
8621 	if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
8622 			      EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
8623 		return false;
8624 
8625 	if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
8626 	    (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
8627 		struct kvm_run *kvm_run = vcpu->run;
8628 		unsigned long eip = kvm_get_linear_rip(vcpu);
8629 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
8630 					   vcpu->arch.guest_debug_dr7,
8631 					   vcpu->arch.eff_db);
8632 
8633 		if (dr6 != 0) {
8634 			kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
8635 			kvm_run->debug.arch.pc = eip;
8636 			kvm_run->debug.arch.exception = DB_VECTOR;
8637 			kvm_run->exit_reason = KVM_EXIT_DEBUG;
8638 			*r = 0;
8639 			return true;
8640 		}
8641 	}
8642 
8643 	if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
8644 	    !kvm_is_code_breakpoint_inhibited(vcpu)) {
8645 		unsigned long eip = kvm_get_linear_rip(vcpu);
8646 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
8647 					   vcpu->arch.dr7,
8648 					   vcpu->arch.db);
8649 
8650 		if (dr6 != 0) {
8651 			kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
8652 			*r = 1;
8653 			return true;
8654 		}
8655 	}
8656 
8657 	return false;
8658 }
8659 
8660 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
8661 {
8662 	switch (ctxt->opcode_len) {
8663 	case 1:
8664 		switch (ctxt->b) {
8665 		case 0xe4:	/* IN */
8666 		case 0xe5:
8667 		case 0xec:
8668 		case 0xed:
8669 		case 0xe6:	/* OUT */
8670 		case 0xe7:
8671 		case 0xee:
8672 		case 0xef:
8673 		case 0x6c:	/* INS */
8674 		case 0x6d:
8675 		case 0x6e:	/* OUTS */
8676 		case 0x6f:
8677 			return true;
8678 		}
8679 		break;
8680 	case 2:
8681 		switch (ctxt->b) {
8682 		case 0x33:	/* RDPMC */
8683 			return true;
8684 		}
8685 		break;
8686 	}
8687 
8688 	return false;
8689 }
8690 
8691 /*
8692  * Decode an instruction for emulation.  The caller is responsible for handling
8693  * code breakpoints.  Note, manually detecting code breakpoints is unnecessary
8694  * (and wrong) when emulating on an intercepted fault-like exception[*], as
8695  * code breakpoints have higher priority and thus have already been done by
8696  * hardware.
8697  *
8698  * [*] Except #MC, which is higher priority, but KVM should never emulate in
8699  *     response to a machine check.
8700  */
8701 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
8702 				    void *insn, int insn_len)
8703 {
8704 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8705 	int r;
8706 
8707 	init_emulate_ctxt(vcpu);
8708 
8709 	r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
8710 
8711 	trace_kvm_emulate_insn_start(vcpu);
8712 	++vcpu->stat.insn_emulation;
8713 
8714 	return r;
8715 }
8716 EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
8717 
8718 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
8719 			    int emulation_type, void *insn, int insn_len)
8720 {
8721 	int r;
8722 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8723 	bool writeback = true;
8724 	bool write_fault_to_spt;
8725 
8726 	if (unlikely(!kvm_can_emulate_insn(vcpu, emulation_type, insn, insn_len)))
8727 		return 1;
8728 
8729 	vcpu->arch.l1tf_flush_l1d = true;
8730 
8731 	/*
8732 	 * Clear write_fault_to_shadow_pgtable here to ensure it is
8733 	 * never reused.
8734 	 */
8735 	write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
8736 	vcpu->arch.write_fault_to_shadow_pgtable = false;
8737 
8738 	if (!(emulation_type & EMULTYPE_NO_DECODE)) {
8739 		kvm_clear_exception_queue(vcpu);
8740 
8741 		/*
8742 		 * Return immediately if RIP hits a code breakpoint, such #DBs
8743 		 * are fault-like and are higher priority than any faults on
8744 		 * the code fetch itself.
8745 		 */
8746 		if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
8747 			return r;
8748 
8749 		r = x86_decode_emulated_instruction(vcpu, emulation_type,
8750 						    insn, insn_len);
8751 		if (r != EMULATION_OK)  {
8752 			if ((emulation_type & EMULTYPE_TRAP_UD) ||
8753 			    (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
8754 				kvm_queue_exception(vcpu, UD_VECTOR);
8755 				return 1;
8756 			}
8757 			if (reexecute_instruction(vcpu, cr2_or_gpa,
8758 						  write_fault_to_spt,
8759 						  emulation_type))
8760 				return 1;
8761 			if (ctxt->have_exception) {
8762 				/*
8763 				 * #UD should result in just EMULATION_FAILED, and trap-like
8764 				 * exception should not be encountered during decode.
8765 				 */
8766 				WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
8767 					     exception_type(ctxt->exception.vector) == EXCPT_TRAP);
8768 				inject_emulated_exception(vcpu);
8769 				return 1;
8770 			}
8771 			return handle_emulation_failure(vcpu, emulation_type);
8772 		}
8773 	}
8774 
8775 	if ((emulation_type & EMULTYPE_VMWARE_GP) &&
8776 	    !is_vmware_backdoor_opcode(ctxt)) {
8777 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8778 		return 1;
8779 	}
8780 
8781 	/*
8782 	 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
8783 	 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
8784 	 * The caller is responsible for updating interruptibility state and
8785 	 * injecting single-step #DBs.
8786 	 */
8787 	if (emulation_type & EMULTYPE_SKIP) {
8788 		if (ctxt->mode != X86EMUL_MODE_PROT64)
8789 			ctxt->eip = (u32)ctxt->_eip;
8790 		else
8791 			ctxt->eip = ctxt->_eip;
8792 
8793 		if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
8794 			r = 1;
8795 			goto writeback;
8796 		}
8797 
8798 		kvm_rip_write(vcpu, ctxt->eip);
8799 		if (ctxt->eflags & X86_EFLAGS_RF)
8800 			kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
8801 		return 1;
8802 	}
8803 
8804 	if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
8805 		return 1;
8806 
8807 	/* this is needed for vmware backdoor interface to work since it
8808 	   changes registers values  during IO operation */
8809 	if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
8810 		vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8811 		emulator_invalidate_register_cache(ctxt);
8812 	}
8813 
8814 restart:
8815 	if (emulation_type & EMULTYPE_PF) {
8816 		/* Save the faulting GPA (cr2) in the address field */
8817 		ctxt->exception.address = cr2_or_gpa;
8818 
8819 		/* With shadow page tables, cr2 contains a GVA or nGPA. */
8820 		if (vcpu->arch.mmu->root_role.direct) {
8821 			ctxt->gpa_available = true;
8822 			ctxt->gpa_val = cr2_or_gpa;
8823 		}
8824 	} else {
8825 		/* Sanitize the address out of an abundance of paranoia. */
8826 		ctxt->exception.address = 0;
8827 	}
8828 
8829 	r = x86_emulate_insn(ctxt);
8830 
8831 	if (r == EMULATION_INTERCEPTED)
8832 		return 1;
8833 
8834 	if (r == EMULATION_FAILED) {
8835 		if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
8836 					emulation_type))
8837 			return 1;
8838 
8839 		return handle_emulation_failure(vcpu, emulation_type);
8840 	}
8841 
8842 	if (ctxt->have_exception) {
8843 		r = 1;
8844 		inject_emulated_exception(vcpu);
8845 	} else if (vcpu->arch.pio.count) {
8846 		if (!vcpu->arch.pio.in) {
8847 			/* FIXME: return into emulator if single-stepping.  */
8848 			vcpu->arch.pio.count = 0;
8849 		} else {
8850 			writeback = false;
8851 			vcpu->arch.complete_userspace_io = complete_emulated_pio;
8852 		}
8853 		r = 0;
8854 	} else if (vcpu->mmio_needed) {
8855 		++vcpu->stat.mmio_exits;
8856 
8857 		if (!vcpu->mmio_is_write)
8858 			writeback = false;
8859 		r = 0;
8860 		vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8861 	} else if (vcpu->arch.complete_userspace_io) {
8862 		writeback = false;
8863 		r = 0;
8864 	} else if (r == EMULATION_RESTART)
8865 		goto restart;
8866 	else
8867 		r = 1;
8868 
8869 writeback:
8870 	if (writeback) {
8871 		unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
8872 		toggle_interruptibility(vcpu, ctxt->interruptibility);
8873 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8874 
8875 		/*
8876 		 * Note, EXCPT_DB is assumed to be fault-like as the emulator
8877 		 * only supports code breakpoints and general detect #DB, both
8878 		 * of which are fault-like.
8879 		 */
8880 		if (!ctxt->have_exception ||
8881 		    exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
8882 			kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
8883 			if (ctxt->is_branch)
8884 				kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
8885 			kvm_rip_write(vcpu, ctxt->eip);
8886 			if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
8887 				r = kvm_vcpu_do_singlestep(vcpu);
8888 			static_call_cond(kvm_x86_update_emulated_instruction)(vcpu);
8889 			__kvm_set_rflags(vcpu, ctxt->eflags);
8890 		}
8891 
8892 		/*
8893 		 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
8894 		 * do nothing, and it will be requested again as soon as
8895 		 * the shadow expires.  But we still need to check here,
8896 		 * because POPF has no interrupt shadow.
8897 		 */
8898 		if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
8899 			kvm_make_request(KVM_REQ_EVENT, vcpu);
8900 	} else
8901 		vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
8902 
8903 	return r;
8904 }
8905 
8906 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
8907 {
8908 	return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
8909 }
8910 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
8911 
8912 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
8913 					void *insn, int insn_len)
8914 {
8915 	return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
8916 }
8917 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
8918 
8919 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
8920 {
8921 	vcpu->arch.pio.count = 0;
8922 	return 1;
8923 }
8924 
8925 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
8926 {
8927 	vcpu->arch.pio.count = 0;
8928 
8929 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
8930 		return 1;
8931 
8932 	return kvm_skip_emulated_instruction(vcpu);
8933 }
8934 
8935 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
8936 			    unsigned short port)
8937 {
8938 	unsigned long val = kvm_rax_read(vcpu);
8939 	int ret = emulator_pio_out(vcpu, size, port, &val, 1);
8940 
8941 	if (ret)
8942 		return ret;
8943 
8944 	/*
8945 	 * Workaround userspace that relies on old KVM behavior of %rip being
8946 	 * incremented prior to exiting to userspace to handle "OUT 0x7e".
8947 	 */
8948 	if (port == 0x7e &&
8949 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
8950 		vcpu->arch.complete_userspace_io =
8951 			complete_fast_pio_out_port_0x7e;
8952 		kvm_skip_emulated_instruction(vcpu);
8953 	} else {
8954 		vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
8955 		vcpu->arch.complete_userspace_io = complete_fast_pio_out;
8956 	}
8957 	return 0;
8958 }
8959 
8960 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
8961 {
8962 	unsigned long val;
8963 
8964 	/* We should only ever be called with arch.pio.count equal to 1 */
8965 	BUG_ON(vcpu->arch.pio.count != 1);
8966 
8967 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
8968 		vcpu->arch.pio.count = 0;
8969 		return 1;
8970 	}
8971 
8972 	/* For size less than 4 we merge, else we zero extend */
8973 	val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
8974 
8975 	complete_emulator_pio_in(vcpu, &val);
8976 	kvm_rax_write(vcpu, val);
8977 
8978 	return kvm_skip_emulated_instruction(vcpu);
8979 }
8980 
8981 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
8982 			   unsigned short port)
8983 {
8984 	unsigned long val;
8985 	int ret;
8986 
8987 	/* For size less than 4 we merge, else we zero extend */
8988 	val = (size < 4) ? kvm_rax_read(vcpu) : 0;
8989 
8990 	ret = emulator_pio_in(vcpu, size, port, &val, 1);
8991 	if (ret) {
8992 		kvm_rax_write(vcpu, val);
8993 		return ret;
8994 	}
8995 
8996 	vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
8997 	vcpu->arch.complete_userspace_io = complete_fast_pio_in;
8998 
8999 	return 0;
9000 }
9001 
9002 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9003 {
9004 	int ret;
9005 
9006 	if (in)
9007 		ret = kvm_fast_pio_in(vcpu, size, port);
9008 	else
9009 		ret = kvm_fast_pio_out(vcpu, size, port);
9010 	return ret && kvm_skip_emulated_instruction(vcpu);
9011 }
9012 EXPORT_SYMBOL_GPL(kvm_fast_pio);
9013 
9014 static int kvmclock_cpu_down_prep(unsigned int cpu)
9015 {
9016 	__this_cpu_write(cpu_tsc_khz, 0);
9017 	return 0;
9018 }
9019 
9020 static void tsc_khz_changed(void *data)
9021 {
9022 	struct cpufreq_freqs *freq = data;
9023 	unsigned long khz = 0;
9024 
9025 	if (data)
9026 		khz = freq->new;
9027 	else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
9028 		khz = cpufreq_quick_get(raw_smp_processor_id());
9029 	if (!khz)
9030 		khz = tsc_khz;
9031 	__this_cpu_write(cpu_tsc_khz, khz);
9032 }
9033 
9034 #ifdef CONFIG_X86_64
9035 static void kvm_hyperv_tsc_notifier(void)
9036 {
9037 	struct kvm *kvm;
9038 	int cpu;
9039 
9040 	mutex_lock(&kvm_lock);
9041 	list_for_each_entry(kvm, &vm_list, vm_list)
9042 		kvm_make_mclock_inprogress_request(kvm);
9043 
9044 	/* no guest entries from this point */
9045 	hyperv_stop_tsc_emulation();
9046 
9047 	/* TSC frequency always matches when on Hyper-V */
9048 	for_each_present_cpu(cpu)
9049 		per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9050 	kvm_caps.max_guest_tsc_khz = tsc_khz;
9051 
9052 	list_for_each_entry(kvm, &vm_list, vm_list) {
9053 		__kvm_start_pvclock_update(kvm);
9054 		pvclock_update_vm_gtod_copy(kvm);
9055 		kvm_end_pvclock_update(kvm);
9056 	}
9057 
9058 	mutex_unlock(&kvm_lock);
9059 }
9060 #endif
9061 
9062 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9063 {
9064 	struct kvm *kvm;
9065 	struct kvm_vcpu *vcpu;
9066 	int send_ipi = 0;
9067 	unsigned long i;
9068 
9069 	/*
9070 	 * We allow guests to temporarily run on slowing clocks,
9071 	 * provided we notify them after, or to run on accelerating
9072 	 * clocks, provided we notify them before.  Thus time never
9073 	 * goes backwards.
9074 	 *
9075 	 * However, we have a problem.  We can't atomically update
9076 	 * the frequency of a given CPU from this function; it is
9077 	 * merely a notifier, which can be called from any CPU.
9078 	 * Changing the TSC frequency at arbitrary points in time
9079 	 * requires a recomputation of local variables related to
9080 	 * the TSC for each VCPU.  We must flag these local variables
9081 	 * to be updated and be sure the update takes place with the
9082 	 * new frequency before any guests proceed.
9083 	 *
9084 	 * Unfortunately, the combination of hotplug CPU and frequency
9085 	 * change creates an intractable locking scenario; the order
9086 	 * of when these callouts happen is undefined with respect to
9087 	 * CPU hotplug, and they can race with each other.  As such,
9088 	 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9089 	 * undefined; you can actually have a CPU frequency change take
9090 	 * place in between the computation of X and the setting of the
9091 	 * variable.  To protect against this problem, all updates of
9092 	 * the per_cpu tsc_khz variable are done in an interrupt
9093 	 * protected IPI, and all callers wishing to update the value
9094 	 * must wait for a synchronous IPI to complete (which is trivial
9095 	 * if the caller is on the CPU already).  This establishes the
9096 	 * necessary total order on variable updates.
9097 	 *
9098 	 * Note that because a guest time update may take place
9099 	 * anytime after the setting of the VCPU's request bit, the
9100 	 * correct TSC value must be set before the request.  However,
9101 	 * to ensure the update actually makes it to any guest which
9102 	 * starts running in hardware virtualization between the set
9103 	 * and the acquisition of the spinlock, we must also ping the
9104 	 * CPU after setting the request bit.
9105 	 *
9106 	 */
9107 
9108 	smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9109 
9110 	mutex_lock(&kvm_lock);
9111 	list_for_each_entry(kvm, &vm_list, vm_list) {
9112 		kvm_for_each_vcpu(i, vcpu, kvm) {
9113 			if (vcpu->cpu != cpu)
9114 				continue;
9115 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9116 			if (vcpu->cpu != raw_smp_processor_id())
9117 				send_ipi = 1;
9118 		}
9119 	}
9120 	mutex_unlock(&kvm_lock);
9121 
9122 	if (freq->old < freq->new && send_ipi) {
9123 		/*
9124 		 * We upscale the frequency.  Must make the guest
9125 		 * doesn't see old kvmclock values while running with
9126 		 * the new frequency, otherwise we risk the guest sees
9127 		 * time go backwards.
9128 		 *
9129 		 * In case we update the frequency for another cpu
9130 		 * (which might be in guest context) send an interrupt
9131 		 * to kick the cpu out of guest context.  Next time
9132 		 * guest context is entered kvmclock will be updated,
9133 		 * so the guest will not see stale values.
9134 		 */
9135 		smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9136 	}
9137 }
9138 
9139 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9140 				     void *data)
9141 {
9142 	struct cpufreq_freqs *freq = data;
9143 	int cpu;
9144 
9145 	if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9146 		return 0;
9147 	if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9148 		return 0;
9149 
9150 	for_each_cpu(cpu, freq->policy->cpus)
9151 		__kvmclock_cpufreq_notifier(freq, cpu);
9152 
9153 	return 0;
9154 }
9155 
9156 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9157 	.notifier_call  = kvmclock_cpufreq_notifier
9158 };
9159 
9160 static int kvmclock_cpu_online(unsigned int cpu)
9161 {
9162 	tsc_khz_changed(NULL);
9163 	return 0;
9164 }
9165 
9166 static void kvm_timer_init(void)
9167 {
9168 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9169 		max_tsc_khz = tsc_khz;
9170 
9171 		if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9172 			struct cpufreq_policy *policy;
9173 			int cpu;
9174 
9175 			cpu = get_cpu();
9176 			policy = cpufreq_cpu_get(cpu);
9177 			if (policy) {
9178 				if (policy->cpuinfo.max_freq)
9179 					max_tsc_khz = policy->cpuinfo.max_freq;
9180 				cpufreq_cpu_put(policy);
9181 			}
9182 			put_cpu();
9183 		}
9184 		cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9185 					  CPUFREQ_TRANSITION_NOTIFIER);
9186 	}
9187 
9188 	cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9189 			  kvmclock_cpu_online, kvmclock_cpu_down_prep);
9190 }
9191 
9192 #ifdef CONFIG_X86_64
9193 static void pvclock_gtod_update_fn(struct work_struct *work)
9194 {
9195 	struct kvm *kvm;
9196 	struct kvm_vcpu *vcpu;
9197 	unsigned long i;
9198 
9199 	mutex_lock(&kvm_lock);
9200 	list_for_each_entry(kvm, &vm_list, vm_list)
9201 		kvm_for_each_vcpu(i, vcpu, kvm)
9202 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9203 	atomic_set(&kvm_guest_has_master_clock, 0);
9204 	mutex_unlock(&kvm_lock);
9205 }
9206 
9207 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9208 
9209 /*
9210  * Indirection to move queue_work() out of the tk_core.seq write held
9211  * region to prevent possible deadlocks against time accessors which
9212  * are invoked with work related locks held.
9213  */
9214 static void pvclock_irq_work_fn(struct irq_work *w)
9215 {
9216 	queue_work(system_long_wq, &pvclock_gtod_work);
9217 }
9218 
9219 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9220 
9221 /*
9222  * Notification about pvclock gtod data update.
9223  */
9224 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9225 			       void *priv)
9226 {
9227 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9228 	struct timekeeper *tk = priv;
9229 
9230 	update_pvclock_gtod(tk);
9231 
9232 	/*
9233 	 * Disable master clock if host does not trust, or does not use,
9234 	 * TSC based clocksource. Delegate queue_work() to irq_work as
9235 	 * this is invoked with tk_core.seq write held.
9236 	 */
9237 	if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9238 	    atomic_read(&kvm_guest_has_master_clock) != 0)
9239 		irq_work_queue(&pvclock_irq_work);
9240 	return 0;
9241 }
9242 
9243 static struct notifier_block pvclock_gtod_notifier = {
9244 	.notifier_call = pvclock_gtod_notify,
9245 };
9246 #endif
9247 
9248 int kvm_arch_init(void *opaque)
9249 {
9250 	struct kvm_x86_init_ops *ops = opaque;
9251 	u64 host_pat;
9252 	int r;
9253 
9254 	if (kvm_x86_ops.hardware_enable) {
9255 		pr_err("kvm: already loaded vendor module '%s'\n", kvm_x86_ops.name);
9256 		return -EEXIST;
9257 	}
9258 
9259 	if (!ops->cpu_has_kvm_support()) {
9260 		pr_err_ratelimited("kvm: no hardware support for '%s'\n",
9261 				   ops->runtime_ops->name);
9262 		return -EOPNOTSUPP;
9263 	}
9264 	if (ops->disabled_by_bios()) {
9265 		pr_err_ratelimited("kvm: support for '%s' disabled by bios\n",
9266 				   ops->runtime_ops->name);
9267 		return -EOPNOTSUPP;
9268 	}
9269 
9270 	/*
9271 	 * KVM explicitly assumes that the guest has an FPU and
9272 	 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9273 	 * vCPU's FPU state as a fxregs_state struct.
9274 	 */
9275 	if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9276 		printk(KERN_ERR "kvm: inadequate fpu\n");
9277 		return -EOPNOTSUPP;
9278 	}
9279 
9280 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9281 		pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
9282 		return -EOPNOTSUPP;
9283 	}
9284 
9285 	/*
9286 	 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
9287 	 * the PAT bits in SPTEs.  Bail if PAT[0] is programmed to something
9288 	 * other than WB.  Note, EPT doesn't utilize the PAT, but don't bother
9289 	 * with an exception.  PAT[0] is set to WB on RESET and also by the
9290 	 * kernel, i.e. failure indicates a kernel bug or broken firmware.
9291 	 */
9292 	if (rdmsrl_safe(MSR_IA32_CR_PAT, &host_pat) ||
9293 	    (host_pat & GENMASK(2, 0)) != 6) {
9294 		pr_err("kvm: host PAT[0] is not WB\n");
9295 		return -EIO;
9296 	}
9297 
9298 	x86_emulator_cache = kvm_alloc_emulator_cache();
9299 	if (!x86_emulator_cache) {
9300 		pr_err("kvm: failed to allocate cache for x86 emulator\n");
9301 		return -ENOMEM;
9302 	}
9303 
9304 	user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
9305 	if (!user_return_msrs) {
9306 		printk(KERN_ERR "kvm: failed to allocate percpu kvm_user_return_msrs\n");
9307 		r = -ENOMEM;
9308 		goto out_free_x86_emulator_cache;
9309 	}
9310 	kvm_nr_uret_msrs = 0;
9311 
9312 	r = kvm_mmu_vendor_module_init();
9313 	if (r)
9314 		goto out_free_percpu;
9315 
9316 	kvm_timer_init();
9317 
9318 	if (boot_cpu_has(X86_FEATURE_XSAVE)) {
9319 		host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
9320 		kvm_caps.supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
9321 	}
9322 
9323 	if (pi_inject_timer == -1)
9324 		pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
9325 #ifdef CONFIG_X86_64
9326 	pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
9327 
9328 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9329 		set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
9330 #endif
9331 
9332 	return 0;
9333 
9334 out_free_percpu:
9335 	free_percpu(user_return_msrs);
9336 out_free_x86_emulator_cache:
9337 	kmem_cache_destroy(x86_emulator_cache);
9338 	return r;
9339 }
9340 
9341 void kvm_arch_exit(void)
9342 {
9343 #ifdef CONFIG_X86_64
9344 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9345 		clear_hv_tscchange_cb();
9346 #endif
9347 	kvm_lapic_exit();
9348 
9349 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
9350 		cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
9351 					    CPUFREQ_TRANSITION_NOTIFIER);
9352 	cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
9353 #ifdef CONFIG_X86_64
9354 	pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
9355 	irq_work_sync(&pvclock_irq_work);
9356 	cancel_work_sync(&pvclock_gtod_work);
9357 #endif
9358 	kvm_x86_ops.hardware_enable = NULL;
9359 	kvm_mmu_vendor_module_exit();
9360 	free_percpu(user_return_msrs);
9361 	kmem_cache_destroy(x86_emulator_cache);
9362 #ifdef CONFIG_KVM_XEN
9363 	static_key_deferred_flush(&kvm_xen_enabled);
9364 	WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
9365 #endif
9366 }
9367 
9368 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
9369 {
9370 	/*
9371 	 * The vCPU has halted, e.g. executed HLT.  Update the run state if the
9372 	 * local APIC is in-kernel, the run loop will detect the non-runnable
9373 	 * state and halt the vCPU.  Exit to userspace if the local APIC is
9374 	 * managed by userspace, in which case userspace is responsible for
9375 	 * handling wake events.
9376 	 */
9377 	++vcpu->stat.halt_exits;
9378 	if (lapic_in_kernel(vcpu)) {
9379 		vcpu->arch.mp_state = state;
9380 		return 1;
9381 	} else {
9382 		vcpu->run->exit_reason = reason;
9383 		return 0;
9384 	}
9385 }
9386 
9387 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
9388 {
9389 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
9390 }
9391 EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
9392 
9393 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
9394 {
9395 	int ret = kvm_skip_emulated_instruction(vcpu);
9396 	/*
9397 	 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
9398 	 * KVM_EXIT_DEBUG here.
9399 	 */
9400 	return kvm_emulate_halt_noskip(vcpu) && ret;
9401 }
9402 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
9403 
9404 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
9405 {
9406 	int ret = kvm_skip_emulated_instruction(vcpu);
9407 
9408 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
9409 					KVM_EXIT_AP_RESET_HOLD) && ret;
9410 }
9411 EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
9412 
9413 #ifdef CONFIG_X86_64
9414 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
9415 			        unsigned long clock_type)
9416 {
9417 	struct kvm_clock_pairing clock_pairing;
9418 	struct timespec64 ts;
9419 	u64 cycle;
9420 	int ret;
9421 
9422 	if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
9423 		return -KVM_EOPNOTSUPP;
9424 
9425 	/*
9426 	 * When tsc is in permanent catchup mode guests won't be able to use
9427 	 * pvclock_read_retry loop to get consistent view of pvclock
9428 	 */
9429 	if (vcpu->arch.tsc_always_catchup)
9430 		return -KVM_EOPNOTSUPP;
9431 
9432 	if (!kvm_get_walltime_and_clockread(&ts, &cycle))
9433 		return -KVM_EOPNOTSUPP;
9434 
9435 	clock_pairing.sec = ts.tv_sec;
9436 	clock_pairing.nsec = ts.tv_nsec;
9437 	clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
9438 	clock_pairing.flags = 0;
9439 	memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
9440 
9441 	ret = 0;
9442 	if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
9443 			    sizeof(struct kvm_clock_pairing)))
9444 		ret = -KVM_EFAULT;
9445 
9446 	return ret;
9447 }
9448 #endif
9449 
9450 /*
9451  * kvm_pv_kick_cpu_op:  Kick a vcpu.
9452  *
9453  * @apicid - apicid of vcpu to be kicked.
9454  */
9455 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
9456 {
9457 	/*
9458 	 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
9459 	 * common code, e.g. for tracing. Defer initialization to the compiler.
9460 	 */
9461 	struct kvm_lapic_irq lapic_irq = {
9462 		.delivery_mode = APIC_DM_REMRD,
9463 		.dest_mode = APIC_DEST_PHYSICAL,
9464 		.shorthand = APIC_DEST_NOSHORT,
9465 		.dest_id = apicid,
9466 	};
9467 
9468 	kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
9469 }
9470 
9471 bool kvm_apicv_activated(struct kvm *kvm)
9472 {
9473 	return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
9474 }
9475 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
9476 
9477 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
9478 {
9479 	ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
9480 	ulong vcpu_reasons = static_call(kvm_x86_vcpu_get_apicv_inhibit_reasons)(vcpu);
9481 
9482 	return (vm_reasons | vcpu_reasons) == 0;
9483 }
9484 EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
9485 
9486 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
9487 				       enum kvm_apicv_inhibit reason, bool set)
9488 {
9489 	if (set)
9490 		__set_bit(reason, inhibits);
9491 	else
9492 		__clear_bit(reason, inhibits);
9493 
9494 	trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
9495 }
9496 
9497 static void kvm_apicv_init(struct kvm *kvm)
9498 {
9499 	unsigned long *inhibits = &kvm->arch.apicv_inhibit_reasons;
9500 
9501 	init_rwsem(&kvm->arch.apicv_update_lock);
9502 
9503 	set_or_clear_apicv_inhibit(inhibits, APICV_INHIBIT_REASON_ABSENT, true);
9504 
9505 	if (!enable_apicv)
9506 		set_or_clear_apicv_inhibit(inhibits,
9507 					   APICV_INHIBIT_REASON_DISABLE, true);
9508 }
9509 
9510 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
9511 {
9512 	struct kvm_vcpu *target = NULL;
9513 	struct kvm_apic_map *map;
9514 
9515 	vcpu->stat.directed_yield_attempted++;
9516 
9517 	if (single_task_running())
9518 		goto no_yield;
9519 
9520 	rcu_read_lock();
9521 	map = rcu_dereference(vcpu->kvm->arch.apic_map);
9522 
9523 	if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
9524 		target = map->phys_map[dest_id]->vcpu;
9525 
9526 	rcu_read_unlock();
9527 
9528 	if (!target || !READ_ONCE(target->ready))
9529 		goto no_yield;
9530 
9531 	/* Ignore requests to yield to self */
9532 	if (vcpu == target)
9533 		goto no_yield;
9534 
9535 	if (kvm_vcpu_yield_to(target) <= 0)
9536 		goto no_yield;
9537 
9538 	vcpu->stat.directed_yield_successful++;
9539 
9540 no_yield:
9541 	return;
9542 }
9543 
9544 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
9545 {
9546 	u64 ret = vcpu->run->hypercall.ret;
9547 
9548 	if (!is_64_bit_mode(vcpu))
9549 		ret = (u32)ret;
9550 	kvm_rax_write(vcpu, ret);
9551 	++vcpu->stat.hypercalls;
9552 	return kvm_skip_emulated_instruction(vcpu);
9553 }
9554 
9555 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
9556 {
9557 	unsigned long nr, a0, a1, a2, a3, ret;
9558 	int op_64_bit;
9559 
9560 	if (kvm_xen_hypercall_enabled(vcpu->kvm))
9561 		return kvm_xen_hypercall(vcpu);
9562 
9563 	if (kvm_hv_hypercall_enabled(vcpu))
9564 		return kvm_hv_hypercall(vcpu);
9565 
9566 	nr = kvm_rax_read(vcpu);
9567 	a0 = kvm_rbx_read(vcpu);
9568 	a1 = kvm_rcx_read(vcpu);
9569 	a2 = kvm_rdx_read(vcpu);
9570 	a3 = kvm_rsi_read(vcpu);
9571 
9572 	trace_kvm_hypercall(nr, a0, a1, a2, a3);
9573 
9574 	op_64_bit = is_64_bit_hypercall(vcpu);
9575 	if (!op_64_bit) {
9576 		nr &= 0xFFFFFFFF;
9577 		a0 &= 0xFFFFFFFF;
9578 		a1 &= 0xFFFFFFFF;
9579 		a2 &= 0xFFFFFFFF;
9580 		a3 &= 0xFFFFFFFF;
9581 	}
9582 
9583 	if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
9584 		ret = -KVM_EPERM;
9585 		goto out;
9586 	}
9587 
9588 	ret = -KVM_ENOSYS;
9589 
9590 	switch (nr) {
9591 	case KVM_HC_VAPIC_POLL_IRQ:
9592 		ret = 0;
9593 		break;
9594 	case KVM_HC_KICK_CPU:
9595 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
9596 			break;
9597 
9598 		kvm_pv_kick_cpu_op(vcpu->kvm, a1);
9599 		kvm_sched_yield(vcpu, a1);
9600 		ret = 0;
9601 		break;
9602 #ifdef CONFIG_X86_64
9603 	case KVM_HC_CLOCK_PAIRING:
9604 		ret = kvm_pv_clock_pairing(vcpu, a0, a1);
9605 		break;
9606 #endif
9607 	case KVM_HC_SEND_IPI:
9608 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
9609 			break;
9610 
9611 		ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
9612 		break;
9613 	case KVM_HC_SCHED_YIELD:
9614 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
9615 			break;
9616 
9617 		kvm_sched_yield(vcpu, a0);
9618 		ret = 0;
9619 		break;
9620 	case KVM_HC_MAP_GPA_RANGE: {
9621 		u64 gpa = a0, npages = a1, attrs = a2;
9622 
9623 		ret = -KVM_ENOSYS;
9624 		if (!(vcpu->kvm->arch.hypercall_exit_enabled & (1 << KVM_HC_MAP_GPA_RANGE)))
9625 			break;
9626 
9627 		if (!PAGE_ALIGNED(gpa) || !npages ||
9628 		    gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
9629 			ret = -KVM_EINVAL;
9630 			break;
9631 		}
9632 
9633 		vcpu->run->exit_reason        = KVM_EXIT_HYPERCALL;
9634 		vcpu->run->hypercall.nr       = KVM_HC_MAP_GPA_RANGE;
9635 		vcpu->run->hypercall.args[0]  = gpa;
9636 		vcpu->run->hypercall.args[1]  = npages;
9637 		vcpu->run->hypercall.args[2]  = attrs;
9638 		vcpu->run->hypercall.longmode = op_64_bit;
9639 		vcpu->arch.complete_userspace_io = complete_hypercall_exit;
9640 		return 0;
9641 	}
9642 	default:
9643 		ret = -KVM_ENOSYS;
9644 		break;
9645 	}
9646 out:
9647 	if (!op_64_bit)
9648 		ret = (u32)ret;
9649 	kvm_rax_write(vcpu, ret);
9650 
9651 	++vcpu->stat.hypercalls;
9652 	return kvm_skip_emulated_instruction(vcpu);
9653 }
9654 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
9655 
9656 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
9657 {
9658 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
9659 	char instruction[3];
9660 	unsigned long rip = kvm_rip_read(vcpu);
9661 
9662 	/*
9663 	 * If the quirk is disabled, synthesize a #UD and let the guest pick up
9664 	 * the pieces.
9665 	 */
9666 	if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
9667 		ctxt->exception.error_code_valid = false;
9668 		ctxt->exception.vector = UD_VECTOR;
9669 		ctxt->have_exception = true;
9670 		return X86EMUL_PROPAGATE_FAULT;
9671 	}
9672 
9673 	static_call(kvm_x86_patch_hypercall)(vcpu, instruction);
9674 
9675 	return emulator_write_emulated(ctxt, rip, instruction, 3,
9676 		&ctxt->exception);
9677 }
9678 
9679 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
9680 {
9681 	return vcpu->run->request_interrupt_window &&
9682 		likely(!pic_in_kernel(vcpu->kvm));
9683 }
9684 
9685 /* Called within kvm->srcu read side.  */
9686 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
9687 {
9688 	struct kvm_run *kvm_run = vcpu->run;
9689 
9690 	kvm_run->if_flag = static_call(kvm_x86_get_if_flag)(vcpu);
9691 	kvm_run->cr8 = kvm_get_cr8(vcpu);
9692 	kvm_run->apic_base = kvm_get_apic_base(vcpu);
9693 
9694 	kvm_run->ready_for_interrupt_injection =
9695 		pic_in_kernel(vcpu->kvm) ||
9696 		kvm_vcpu_ready_for_interrupt_injection(vcpu);
9697 
9698 	if (is_smm(vcpu))
9699 		kvm_run->flags |= KVM_RUN_X86_SMM;
9700 }
9701 
9702 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
9703 {
9704 	int max_irr, tpr;
9705 
9706 	if (!kvm_x86_ops.update_cr8_intercept)
9707 		return;
9708 
9709 	if (!lapic_in_kernel(vcpu))
9710 		return;
9711 
9712 	if (vcpu->arch.apic->apicv_active)
9713 		return;
9714 
9715 	if (!vcpu->arch.apic->vapic_addr)
9716 		max_irr = kvm_lapic_find_highest_irr(vcpu);
9717 	else
9718 		max_irr = -1;
9719 
9720 	if (max_irr != -1)
9721 		max_irr >>= 4;
9722 
9723 	tpr = kvm_lapic_get_cr8(vcpu);
9724 
9725 	static_call(kvm_x86_update_cr8_intercept)(vcpu, tpr, max_irr);
9726 }
9727 
9728 
9729 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
9730 {
9731 	if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
9732 		kvm_x86_ops.nested_ops->triple_fault(vcpu);
9733 		return 1;
9734 	}
9735 
9736 	return kvm_x86_ops.nested_ops->check_events(vcpu);
9737 }
9738 
9739 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
9740 {
9741 	trace_kvm_inj_exception(vcpu->arch.exception.vector,
9742 				vcpu->arch.exception.has_error_code,
9743 				vcpu->arch.exception.error_code,
9744 				vcpu->arch.exception.injected);
9745 
9746 	if (vcpu->arch.exception.error_code && !is_protmode(vcpu))
9747 		vcpu->arch.exception.error_code = false;
9748 	static_call(kvm_x86_inject_exception)(vcpu);
9749 }
9750 
9751 /*
9752  * Check for any event (interrupt or exception) that is ready to be injected,
9753  * and if there is at least one event, inject the event with the highest
9754  * priority.  This handles both "pending" events, i.e. events that have never
9755  * been injected into the guest, and "injected" events, i.e. events that were
9756  * injected as part of a previous VM-Enter, but weren't successfully delivered
9757  * and need to be re-injected.
9758  *
9759  * Note, this is not guaranteed to be invoked on a guest instruction boundary,
9760  * i.e. doesn't guarantee that there's an event window in the guest.  KVM must
9761  * be able to inject exceptions in the "middle" of an instruction, and so must
9762  * also be able to re-inject NMIs and IRQs in the middle of an instruction.
9763  * I.e. for exceptions and re-injected events, NOT invoking this on instruction
9764  * boundaries is necessary and correct.
9765  *
9766  * For simplicity, KVM uses a single path to inject all events (except events
9767  * that are injected directly from L1 to L2) and doesn't explicitly track
9768  * instruction boundaries for asynchronous events.  However, because VM-Exits
9769  * that can occur during instruction execution typically result in KVM skipping
9770  * the instruction or injecting an exception, e.g. instruction and exception
9771  * intercepts, and because pending exceptions have higher priority than pending
9772  * interrupts, KVM still honors instruction boundaries in most scenarios.
9773  *
9774  * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
9775  * the instruction or inject an exception, then KVM can incorrecty inject a new
9776  * asynchrounous event if the event became pending after the CPU fetched the
9777  * instruction (in the guest).  E.g. if a page fault (#PF, #NPF, EPT violation)
9778  * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
9779  * injected on the restarted instruction instead of being deferred until the
9780  * instruction completes.
9781  *
9782  * In practice, this virtualization hole is unlikely to be observed by the
9783  * guest, and even less likely to cause functional problems.  To detect the
9784  * hole, the guest would have to trigger an event on a side effect of an early
9785  * phase of instruction execution, e.g. on the instruction fetch from memory.
9786  * And for it to be a functional problem, the guest would need to depend on the
9787  * ordering between that side effect, the instruction completing, _and_ the
9788  * delivery of the asynchronous event.
9789  */
9790 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
9791 				       bool *req_immediate_exit)
9792 {
9793 	bool can_inject;
9794 	int r;
9795 
9796 	/*
9797 	 * Process nested events first, as nested VM-Exit supercedes event
9798 	 * re-injection.  If there's an event queued for re-injection, it will
9799 	 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
9800 	 */
9801 	if (is_guest_mode(vcpu))
9802 		r = kvm_check_nested_events(vcpu);
9803 	else
9804 		r = 0;
9805 
9806 	/*
9807 	 * Re-inject exceptions and events *especially* if immediate entry+exit
9808 	 * to/from L2 is needed, as any event that has already been injected
9809 	 * into L2 needs to complete its lifecycle before injecting a new event.
9810 	 *
9811 	 * Don't re-inject an NMI or interrupt if there is a pending exception.
9812 	 * This collision arises if an exception occurred while vectoring the
9813 	 * injected event, KVM intercepted said exception, and KVM ultimately
9814 	 * determined the fault belongs to the guest and queues the exception
9815 	 * for injection back into the guest.
9816 	 *
9817 	 * "Injected" interrupts can also collide with pending exceptions if
9818 	 * userspace ignores the "ready for injection" flag and blindly queues
9819 	 * an interrupt.  In that case, prioritizing the exception is correct,
9820 	 * as the exception "occurred" before the exit to userspace.  Trap-like
9821 	 * exceptions, e.g. most #DBs, have higher priority than interrupts.
9822 	 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
9823 	 * priority, they're only generated (pended) during instruction
9824 	 * execution, and interrupts are recognized at instruction boundaries.
9825 	 * Thus a pending fault-like exception means the fault occurred on the
9826 	 * *previous* instruction and must be serviced prior to recognizing any
9827 	 * new events in order to fully complete the previous instruction.
9828 	 */
9829 	if (vcpu->arch.exception.injected)
9830 		kvm_inject_exception(vcpu);
9831 	else if (kvm_is_exception_pending(vcpu))
9832 		; /* see above */
9833 	else if (vcpu->arch.nmi_injected)
9834 		static_call(kvm_x86_inject_nmi)(vcpu);
9835 	else if (vcpu->arch.interrupt.injected)
9836 		static_call(kvm_x86_inject_irq)(vcpu, true);
9837 
9838 	/*
9839 	 * Exceptions that morph to VM-Exits are handled above, and pending
9840 	 * exceptions on top of injected exceptions that do not VM-Exit should
9841 	 * either morph to #DF or, sadly, override the injected exception.
9842 	 */
9843 	WARN_ON_ONCE(vcpu->arch.exception.injected &&
9844 		     vcpu->arch.exception.pending);
9845 
9846 	/*
9847 	 * Bail if immediate entry+exit to/from the guest is needed to complete
9848 	 * nested VM-Enter or event re-injection so that a different pending
9849 	 * event can be serviced (or if KVM needs to exit to userspace).
9850 	 *
9851 	 * Otherwise, continue processing events even if VM-Exit occurred.  The
9852 	 * VM-Exit will have cleared exceptions that were meant for L2, but
9853 	 * there may now be events that can be injected into L1.
9854 	 */
9855 	if (r < 0)
9856 		goto out;
9857 
9858 	/*
9859 	 * A pending exception VM-Exit should either result in nested VM-Exit
9860 	 * or force an immediate re-entry and exit to/from L2, and exception
9861 	 * VM-Exits cannot be injected (flag should _never_ be set).
9862 	 */
9863 	WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
9864 		     vcpu->arch.exception_vmexit.pending);
9865 
9866 	/*
9867 	 * New events, other than exceptions, cannot be injected if KVM needs
9868 	 * to re-inject a previous event.  See above comments on re-injecting
9869 	 * for why pending exceptions get priority.
9870 	 */
9871 	can_inject = !kvm_event_needs_reinjection(vcpu);
9872 
9873 	if (vcpu->arch.exception.pending) {
9874 		/*
9875 		 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
9876 		 * value pushed on the stack.  Trap-like exception and all #DBs
9877 		 * leave RF as-is (KVM follows Intel's behavior in this regard;
9878 		 * AMD states that code breakpoint #DBs excplitly clear RF=0).
9879 		 *
9880 		 * Note, most versions of Intel's SDM and AMD's APM incorrectly
9881 		 * describe the behavior of General Detect #DBs, which are
9882 		 * fault-like.  They do _not_ set RF, a la code breakpoints.
9883 		 */
9884 		if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
9885 			__kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
9886 					     X86_EFLAGS_RF);
9887 
9888 		if (vcpu->arch.exception.vector == DB_VECTOR) {
9889 			kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
9890 			if (vcpu->arch.dr7 & DR7_GD) {
9891 				vcpu->arch.dr7 &= ~DR7_GD;
9892 				kvm_update_dr7(vcpu);
9893 			}
9894 		}
9895 
9896 		kvm_inject_exception(vcpu);
9897 
9898 		vcpu->arch.exception.pending = false;
9899 		vcpu->arch.exception.injected = true;
9900 
9901 		can_inject = false;
9902 	}
9903 
9904 	/* Don't inject interrupts if the user asked to avoid doing so */
9905 	if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
9906 		return 0;
9907 
9908 	/*
9909 	 * Finally, inject interrupt events.  If an event cannot be injected
9910 	 * due to architectural conditions (e.g. IF=0) a window-open exit
9911 	 * will re-request KVM_REQ_EVENT.  Sometimes however an event is pending
9912 	 * and can architecturally be injected, but we cannot do it right now:
9913 	 * an interrupt could have arrived just now and we have to inject it
9914 	 * as a vmexit, or there could already an event in the queue, which is
9915 	 * indicated by can_inject.  In that case we request an immediate exit
9916 	 * in order to make progress and get back here for another iteration.
9917 	 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
9918 	 */
9919 #ifdef CONFIG_KVM_SMM
9920 	if (vcpu->arch.smi_pending) {
9921 		r = can_inject ? static_call(kvm_x86_smi_allowed)(vcpu, true) : -EBUSY;
9922 		if (r < 0)
9923 			goto out;
9924 		if (r) {
9925 			vcpu->arch.smi_pending = false;
9926 			++vcpu->arch.smi_count;
9927 			enter_smm(vcpu);
9928 			can_inject = false;
9929 		} else
9930 			static_call(kvm_x86_enable_smi_window)(vcpu);
9931 	}
9932 #endif
9933 
9934 	if (vcpu->arch.nmi_pending) {
9935 		r = can_inject ? static_call(kvm_x86_nmi_allowed)(vcpu, true) : -EBUSY;
9936 		if (r < 0)
9937 			goto out;
9938 		if (r) {
9939 			--vcpu->arch.nmi_pending;
9940 			vcpu->arch.nmi_injected = true;
9941 			static_call(kvm_x86_inject_nmi)(vcpu);
9942 			can_inject = false;
9943 			WARN_ON(static_call(kvm_x86_nmi_allowed)(vcpu, true) < 0);
9944 		}
9945 		if (vcpu->arch.nmi_pending)
9946 			static_call(kvm_x86_enable_nmi_window)(vcpu);
9947 	}
9948 
9949 	if (kvm_cpu_has_injectable_intr(vcpu)) {
9950 		r = can_inject ? static_call(kvm_x86_interrupt_allowed)(vcpu, true) : -EBUSY;
9951 		if (r < 0)
9952 			goto out;
9953 		if (r) {
9954 			kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
9955 			static_call(kvm_x86_inject_irq)(vcpu, false);
9956 			WARN_ON(static_call(kvm_x86_interrupt_allowed)(vcpu, true) < 0);
9957 		}
9958 		if (kvm_cpu_has_injectable_intr(vcpu))
9959 			static_call(kvm_x86_enable_irq_window)(vcpu);
9960 	}
9961 
9962 	if (is_guest_mode(vcpu) &&
9963 	    kvm_x86_ops.nested_ops->has_events &&
9964 	    kvm_x86_ops.nested_ops->has_events(vcpu))
9965 		*req_immediate_exit = true;
9966 
9967 	/*
9968 	 * KVM must never queue a new exception while injecting an event; KVM
9969 	 * is done emulating and should only propagate the to-be-injected event
9970 	 * to the VMCS/VMCB.  Queueing a new exception can put the vCPU into an
9971 	 * infinite loop as KVM will bail from VM-Enter to inject the pending
9972 	 * exception and start the cycle all over.
9973 	 *
9974 	 * Exempt triple faults as they have special handling and won't put the
9975 	 * vCPU into an infinite loop.  Triple fault can be queued when running
9976 	 * VMX without unrestricted guest, as that requires KVM to emulate Real
9977 	 * Mode events (see kvm_inject_realmode_interrupt()).
9978 	 */
9979 	WARN_ON_ONCE(vcpu->arch.exception.pending ||
9980 		     vcpu->arch.exception_vmexit.pending);
9981 	return 0;
9982 
9983 out:
9984 	if (r == -EBUSY) {
9985 		*req_immediate_exit = true;
9986 		r = 0;
9987 	}
9988 	return r;
9989 }
9990 
9991 static void process_nmi(struct kvm_vcpu *vcpu)
9992 {
9993 	unsigned limit = 2;
9994 
9995 	/*
9996 	 * x86 is limited to one NMI running, and one NMI pending after it.
9997 	 * If an NMI is already in progress, limit further NMIs to just one.
9998 	 * Otherwise, allow two (and we'll inject the first one immediately).
9999 	 */
10000 	if (static_call(kvm_x86_get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10001 		limit = 1;
10002 
10003 	vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10004 	vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10005 	kvm_make_request(KVM_REQ_EVENT, vcpu);
10006 }
10007 
10008 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10009 				       unsigned long *vcpu_bitmap)
10010 {
10011 	kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10012 }
10013 
10014 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10015 {
10016 	kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10017 }
10018 
10019 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10020 {
10021 	struct kvm_lapic *apic = vcpu->arch.apic;
10022 	bool activate;
10023 
10024 	if (!lapic_in_kernel(vcpu))
10025 		return;
10026 
10027 	down_read(&vcpu->kvm->arch.apicv_update_lock);
10028 	preempt_disable();
10029 
10030 	/* Do not activate APICV when APIC is disabled */
10031 	activate = kvm_vcpu_apicv_activated(vcpu) &&
10032 		   (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10033 
10034 	if (apic->apicv_active == activate)
10035 		goto out;
10036 
10037 	apic->apicv_active = activate;
10038 	kvm_apic_update_apicv(vcpu);
10039 	static_call(kvm_x86_refresh_apicv_exec_ctrl)(vcpu);
10040 
10041 	/*
10042 	 * When APICv gets disabled, we may still have injected interrupts
10043 	 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10044 	 * still active when the interrupt got accepted. Make sure
10045 	 * kvm_check_and_inject_events() is called to check for that.
10046 	 */
10047 	if (!apic->apicv_active)
10048 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10049 
10050 out:
10051 	preempt_enable();
10052 	up_read(&vcpu->kvm->arch.apicv_update_lock);
10053 }
10054 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
10055 
10056 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10057 				      enum kvm_apicv_inhibit reason, bool set)
10058 {
10059 	unsigned long old, new;
10060 
10061 	lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10062 
10063 	if (!static_call(kvm_x86_check_apicv_inhibit_reasons)(reason))
10064 		return;
10065 
10066 	old = new = kvm->arch.apicv_inhibit_reasons;
10067 
10068 	set_or_clear_apicv_inhibit(&new, reason, set);
10069 
10070 	if (!!old != !!new) {
10071 		/*
10072 		 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10073 		 * false positives in the sanity check WARN in svm_vcpu_run().
10074 		 * This task will wait for all vCPUs to ack the kick IRQ before
10075 		 * updating apicv_inhibit_reasons, and all other vCPUs will
10076 		 * block on acquiring apicv_update_lock so that vCPUs can't
10077 		 * redo svm_vcpu_run() without seeing the new inhibit state.
10078 		 *
10079 		 * Note, holding apicv_update_lock and taking it in the read
10080 		 * side (handling the request) also prevents other vCPUs from
10081 		 * servicing the request with a stale apicv_inhibit_reasons.
10082 		 */
10083 		kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10084 		kvm->arch.apicv_inhibit_reasons = new;
10085 		if (new) {
10086 			unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10087 			int idx = srcu_read_lock(&kvm->srcu);
10088 
10089 			kvm_zap_gfn_range(kvm, gfn, gfn+1);
10090 			srcu_read_unlock(&kvm->srcu, idx);
10091 		}
10092 	} else {
10093 		kvm->arch.apicv_inhibit_reasons = new;
10094 	}
10095 }
10096 
10097 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10098 				    enum kvm_apicv_inhibit reason, bool set)
10099 {
10100 	if (!enable_apicv)
10101 		return;
10102 
10103 	down_write(&kvm->arch.apicv_update_lock);
10104 	__kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10105 	up_write(&kvm->arch.apicv_update_lock);
10106 }
10107 EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
10108 
10109 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10110 {
10111 	if (!kvm_apic_present(vcpu))
10112 		return;
10113 
10114 	bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10115 
10116 	if (irqchip_split(vcpu->kvm))
10117 		kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
10118 	else {
10119 		static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
10120 		if (ioapic_in_kernel(vcpu->kvm))
10121 			kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
10122 	}
10123 
10124 	if (is_guest_mode(vcpu))
10125 		vcpu->arch.load_eoi_exitmap_pending = true;
10126 	else
10127 		kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10128 }
10129 
10130 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10131 {
10132 	u64 eoi_exit_bitmap[4];
10133 
10134 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10135 		return;
10136 
10137 	if (to_hv_vcpu(vcpu)) {
10138 		bitmap_or((ulong *)eoi_exit_bitmap,
10139 			  vcpu->arch.ioapic_handled_vectors,
10140 			  to_hv_synic(vcpu)->vec_bitmap, 256);
10141 		static_call_cond(kvm_x86_load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
10142 		return;
10143 	}
10144 
10145 	static_call_cond(kvm_x86_load_eoi_exitmap)(
10146 		vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
10147 }
10148 
10149 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
10150 					    unsigned long start, unsigned long end)
10151 {
10152 	unsigned long apic_address;
10153 
10154 	/*
10155 	 * The physical address of apic access page is stored in the VMCS.
10156 	 * Update it when it becomes invalid.
10157 	 */
10158 	apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
10159 	if (start <= apic_address && apic_address < end)
10160 		kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
10161 }
10162 
10163 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
10164 {
10165 	static_call_cond(kvm_x86_guest_memory_reclaimed)(kvm);
10166 }
10167 
10168 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
10169 {
10170 	if (!lapic_in_kernel(vcpu))
10171 		return;
10172 
10173 	static_call_cond(kvm_x86_set_apic_access_page_addr)(vcpu);
10174 }
10175 
10176 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
10177 {
10178 	smp_send_reschedule(vcpu->cpu);
10179 }
10180 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
10181 
10182 /*
10183  * Called within kvm->srcu read side.
10184  * Returns 1 to let vcpu_run() continue the guest execution loop without
10185  * exiting to the userspace.  Otherwise, the value will be returned to the
10186  * userspace.
10187  */
10188 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
10189 {
10190 	int r;
10191 	bool req_int_win =
10192 		dm_request_for_irq_injection(vcpu) &&
10193 		kvm_cpu_accept_dm_intr(vcpu);
10194 	fastpath_t exit_fastpath;
10195 
10196 	bool req_immediate_exit = false;
10197 
10198 	/* Forbid vmenter if vcpu dirty ring is soft-full */
10199 	if (unlikely(vcpu->kvm->dirty_ring_size &&
10200 		     kvm_dirty_ring_soft_full(&vcpu->dirty_ring))) {
10201 		vcpu->run->exit_reason = KVM_EXIT_DIRTY_RING_FULL;
10202 		trace_kvm_dirty_ring_exit(vcpu);
10203 		r = 0;
10204 		goto out;
10205 	}
10206 
10207 	if (kvm_request_pending(vcpu)) {
10208 		if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
10209 			r = -EIO;
10210 			goto out;
10211 		}
10212 		if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
10213 			if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
10214 				r = 0;
10215 				goto out;
10216 			}
10217 		}
10218 		if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
10219 			kvm_mmu_free_obsolete_roots(vcpu);
10220 		if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
10221 			__kvm_migrate_timers(vcpu);
10222 		if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
10223 			kvm_update_masterclock(vcpu->kvm);
10224 		if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
10225 			kvm_gen_kvmclock_update(vcpu);
10226 		if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
10227 			r = kvm_guest_time_update(vcpu);
10228 			if (unlikely(r))
10229 				goto out;
10230 		}
10231 		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
10232 			kvm_mmu_sync_roots(vcpu);
10233 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
10234 			kvm_mmu_load_pgd(vcpu);
10235 		if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
10236 			kvm_vcpu_flush_tlb_all(vcpu);
10237 
10238 			/* Flushing all ASIDs flushes the current ASID... */
10239 			kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
10240 		}
10241 		kvm_service_local_tlb_flush_requests(vcpu);
10242 
10243 		if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
10244 			vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
10245 			r = 0;
10246 			goto out;
10247 		}
10248 		if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10249 			if (is_guest_mode(vcpu)) {
10250 				kvm_x86_ops.nested_ops->triple_fault(vcpu);
10251 			} else {
10252 				vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
10253 				vcpu->mmio_needed = 0;
10254 				r = 0;
10255 				goto out;
10256 			}
10257 		}
10258 		if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
10259 			/* Page is swapped out. Do synthetic halt */
10260 			vcpu->arch.apf.halted = true;
10261 			r = 1;
10262 			goto out;
10263 		}
10264 		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
10265 			record_steal_time(vcpu);
10266 #ifdef CONFIG_KVM_SMM
10267 		if (kvm_check_request(KVM_REQ_SMI, vcpu))
10268 			process_smi(vcpu);
10269 #endif
10270 		if (kvm_check_request(KVM_REQ_NMI, vcpu))
10271 			process_nmi(vcpu);
10272 		if (kvm_check_request(KVM_REQ_PMU, vcpu))
10273 			kvm_pmu_handle_event(vcpu);
10274 		if (kvm_check_request(KVM_REQ_PMI, vcpu))
10275 			kvm_pmu_deliver_pmi(vcpu);
10276 		if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
10277 			BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
10278 			if (test_bit(vcpu->arch.pending_ioapic_eoi,
10279 				     vcpu->arch.ioapic_handled_vectors)) {
10280 				vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
10281 				vcpu->run->eoi.vector =
10282 						vcpu->arch.pending_ioapic_eoi;
10283 				r = 0;
10284 				goto out;
10285 			}
10286 		}
10287 		if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
10288 			vcpu_scan_ioapic(vcpu);
10289 		if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
10290 			vcpu_load_eoi_exitmap(vcpu);
10291 		if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
10292 			kvm_vcpu_reload_apic_access_page(vcpu);
10293 		if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
10294 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10295 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
10296 			vcpu->run->system_event.ndata = 0;
10297 			r = 0;
10298 			goto out;
10299 		}
10300 		if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
10301 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10302 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
10303 			vcpu->run->system_event.ndata = 0;
10304 			r = 0;
10305 			goto out;
10306 		}
10307 		if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
10308 			struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
10309 
10310 			vcpu->run->exit_reason = KVM_EXIT_HYPERV;
10311 			vcpu->run->hyperv = hv_vcpu->exit;
10312 			r = 0;
10313 			goto out;
10314 		}
10315 
10316 		/*
10317 		 * KVM_REQ_HV_STIMER has to be processed after
10318 		 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
10319 		 * depend on the guest clock being up-to-date
10320 		 */
10321 		if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
10322 			kvm_hv_process_stimers(vcpu);
10323 		if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
10324 			kvm_vcpu_update_apicv(vcpu);
10325 		if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
10326 			kvm_check_async_pf_completion(vcpu);
10327 		if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
10328 			static_call(kvm_x86_msr_filter_changed)(vcpu);
10329 
10330 		if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
10331 			static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
10332 	}
10333 
10334 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
10335 	    kvm_xen_has_interrupt(vcpu)) {
10336 		++vcpu->stat.req_event;
10337 		r = kvm_apic_accept_events(vcpu);
10338 		if (r < 0) {
10339 			r = 0;
10340 			goto out;
10341 		}
10342 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
10343 			r = 1;
10344 			goto out;
10345 		}
10346 
10347 		r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
10348 		if (r < 0) {
10349 			r = 0;
10350 			goto out;
10351 		}
10352 		if (req_int_win)
10353 			static_call(kvm_x86_enable_irq_window)(vcpu);
10354 
10355 		if (kvm_lapic_enabled(vcpu)) {
10356 			update_cr8_intercept(vcpu);
10357 			kvm_lapic_sync_to_vapic(vcpu);
10358 		}
10359 	}
10360 
10361 	r = kvm_mmu_reload(vcpu);
10362 	if (unlikely(r)) {
10363 		goto cancel_injection;
10364 	}
10365 
10366 	preempt_disable();
10367 
10368 	static_call(kvm_x86_prepare_switch_to_guest)(vcpu);
10369 
10370 	/*
10371 	 * Disable IRQs before setting IN_GUEST_MODE.  Posted interrupt
10372 	 * IPI are then delayed after guest entry, which ensures that they
10373 	 * result in virtual interrupt delivery.
10374 	 */
10375 	local_irq_disable();
10376 
10377 	/* Store vcpu->apicv_active before vcpu->mode.  */
10378 	smp_store_release(&vcpu->mode, IN_GUEST_MODE);
10379 
10380 	kvm_vcpu_srcu_read_unlock(vcpu);
10381 
10382 	/*
10383 	 * 1) We should set ->mode before checking ->requests.  Please see
10384 	 * the comment in kvm_vcpu_exiting_guest_mode().
10385 	 *
10386 	 * 2) For APICv, we should set ->mode before checking PID.ON. This
10387 	 * pairs with the memory barrier implicit in pi_test_and_set_on
10388 	 * (see vmx_deliver_posted_interrupt).
10389 	 *
10390 	 * 3) This also orders the write to mode from any reads to the page
10391 	 * tables done while the VCPU is running.  Please see the comment
10392 	 * in kvm_flush_remote_tlbs.
10393 	 */
10394 	smp_mb__after_srcu_read_unlock();
10395 
10396 	/*
10397 	 * Process pending posted interrupts to handle the case where the
10398 	 * notification IRQ arrived in the host, or was never sent (because the
10399 	 * target vCPU wasn't running).  Do this regardless of the vCPU's APICv
10400 	 * status, KVM doesn't update assigned devices when APICv is inhibited,
10401 	 * i.e. they can post interrupts even if APICv is temporarily disabled.
10402 	 */
10403 	if (kvm_lapic_enabled(vcpu))
10404 		static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
10405 
10406 	if (kvm_vcpu_exit_request(vcpu)) {
10407 		vcpu->mode = OUTSIDE_GUEST_MODE;
10408 		smp_wmb();
10409 		local_irq_enable();
10410 		preempt_enable();
10411 		kvm_vcpu_srcu_read_lock(vcpu);
10412 		r = 1;
10413 		goto cancel_injection;
10414 	}
10415 
10416 	if (req_immediate_exit) {
10417 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10418 		static_call(kvm_x86_request_immediate_exit)(vcpu);
10419 	}
10420 
10421 	fpregs_assert_state_consistent();
10422 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
10423 		switch_fpu_return();
10424 
10425 	if (vcpu->arch.guest_fpu.xfd_err)
10426 		wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
10427 
10428 	if (unlikely(vcpu->arch.switch_db_regs)) {
10429 		set_debugreg(0, 7);
10430 		set_debugreg(vcpu->arch.eff_db[0], 0);
10431 		set_debugreg(vcpu->arch.eff_db[1], 1);
10432 		set_debugreg(vcpu->arch.eff_db[2], 2);
10433 		set_debugreg(vcpu->arch.eff_db[3], 3);
10434 	} else if (unlikely(hw_breakpoint_active())) {
10435 		set_debugreg(0, 7);
10436 	}
10437 
10438 	guest_timing_enter_irqoff();
10439 
10440 	for (;;) {
10441 		/*
10442 		 * Assert that vCPU vs. VM APICv state is consistent.  An APICv
10443 		 * update must kick and wait for all vCPUs before toggling the
10444 		 * per-VM state, and responsing vCPUs must wait for the update
10445 		 * to complete before servicing KVM_REQ_APICV_UPDATE.
10446 		 */
10447 		WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
10448 			     (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
10449 
10450 		exit_fastpath = static_call(kvm_x86_vcpu_run)(vcpu);
10451 		if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
10452 			break;
10453 
10454 		if (kvm_lapic_enabled(vcpu))
10455 			static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
10456 
10457 		if (unlikely(kvm_vcpu_exit_request(vcpu))) {
10458 			exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
10459 			break;
10460 		}
10461 	}
10462 
10463 	/*
10464 	 * Do this here before restoring debug registers on the host.  And
10465 	 * since we do this before handling the vmexit, a DR access vmexit
10466 	 * can (a) read the correct value of the debug registers, (b) set
10467 	 * KVM_DEBUGREG_WONT_EXIT again.
10468 	 */
10469 	if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
10470 		WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
10471 		static_call(kvm_x86_sync_dirty_debug_regs)(vcpu);
10472 		kvm_update_dr0123(vcpu);
10473 		kvm_update_dr7(vcpu);
10474 	}
10475 
10476 	/*
10477 	 * If the guest has used debug registers, at least dr7
10478 	 * will be disabled while returning to the host.
10479 	 * If we don't have active breakpoints in the host, we don't
10480 	 * care about the messed up debug address registers. But if
10481 	 * we have some of them active, restore the old state.
10482 	 */
10483 	if (hw_breakpoint_active())
10484 		hw_breakpoint_restore();
10485 
10486 	vcpu->arch.last_vmentry_cpu = vcpu->cpu;
10487 	vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
10488 
10489 	vcpu->mode = OUTSIDE_GUEST_MODE;
10490 	smp_wmb();
10491 
10492 	/*
10493 	 * Sync xfd before calling handle_exit_irqoff() which may
10494 	 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
10495 	 * in #NM irqoff handler).
10496 	 */
10497 	if (vcpu->arch.xfd_no_write_intercept)
10498 		fpu_sync_guest_vmexit_xfd_state();
10499 
10500 	static_call(kvm_x86_handle_exit_irqoff)(vcpu);
10501 
10502 	if (vcpu->arch.guest_fpu.xfd_err)
10503 		wrmsrl(MSR_IA32_XFD_ERR, 0);
10504 
10505 	/*
10506 	 * Consume any pending interrupts, including the possible source of
10507 	 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
10508 	 * An instruction is required after local_irq_enable() to fully unblock
10509 	 * interrupts on processors that implement an interrupt shadow, the
10510 	 * stat.exits increment will do nicely.
10511 	 */
10512 	kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
10513 	local_irq_enable();
10514 	++vcpu->stat.exits;
10515 	local_irq_disable();
10516 	kvm_after_interrupt(vcpu);
10517 
10518 	/*
10519 	 * Wait until after servicing IRQs to account guest time so that any
10520 	 * ticks that occurred while running the guest are properly accounted
10521 	 * to the guest.  Waiting until IRQs are enabled degrades the accuracy
10522 	 * of accounting via context tracking, but the loss of accuracy is
10523 	 * acceptable for all known use cases.
10524 	 */
10525 	guest_timing_exit_irqoff();
10526 
10527 	local_irq_enable();
10528 	preempt_enable();
10529 
10530 	kvm_vcpu_srcu_read_lock(vcpu);
10531 
10532 	/*
10533 	 * Profile KVM exit RIPs:
10534 	 */
10535 	if (unlikely(prof_on == KVM_PROFILING)) {
10536 		unsigned long rip = kvm_rip_read(vcpu);
10537 		profile_hit(KVM_PROFILING, (void *)rip);
10538 	}
10539 
10540 	if (unlikely(vcpu->arch.tsc_always_catchup))
10541 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
10542 
10543 	if (vcpu->arch.apic_attention)
10544 		kvm_lapic_sync_from_vapic(vcpu);
10545 
10546 	r = static_call(kvm_x86_handle_exit)(vcpu, exit_fastpath);
10547 	return r;
10548 
10549 cancel_injection:
10550 	if (req_immediate_exit)
10551 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10552 	static_call(kvm_x86_cancel_injection)(vcpu);
10553 	if (unlikely(vcpu->arch.apic_attention))
10554 		kvm_lapic_sync_from_vapic(vcpu);
10555 out:
10556 	return r;
10557 }
10558 
10559 /* Called within kvm->srcu read side.  */
10560 static inline int vcpu_block(struct kvm_vcpu *vcpu)
10561 {
10562 	bool hv_timer;
10563 
10564 	if (!kvm_arch_vcpu_runnable(vcpu)) {
10565 		/*
10566 		 * Switch to the software timer before halt-polling/blocking as
10567 		 * the guest's timer may be a break event for the vCPU, and the
10568 		 * hypervisor timer runs only when the CPU is in guest mode.
10569 		 * Switch before halt-polling so that KVM recognizes an expired
10570 		 * timer before blocking.
10571 		 */
10572 		hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
10573 		if (hv_timer)
10574 			kvm_lapic_switch_to_sw_timer(vcpu);
10575 
10576 		kvm_vcpu_srcu_read_unlock(vcpu);
10577 		if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
10578 			kvm_vcpu_halt(vcpu);
10579 		else
10580 			kvm_vcpu_block(vcpu);
10581 		kvm_vcpu_srcu_read_lock(vcpu);
10582 
10583 		if (hv_timer)
10584 			kvm_lapic_switch_to_hv_timer(vcpu);
10585 
10586 		/*
10587 		 * If the vCPU is not runnable, a signal or another host event
10588 		 * of some kind is pending; service it without changing the
10589 		 * vCPU's activity state.
10590 		 */
10591 		if (!kvm_arch_vcpu_runnable(vcpu))
10592 			return 1;
10593 	}
10594 
10595 	/*
10596 	 * Evaluate nested events before exiting the halted state.  This allows
10597 	 * the halt state to be recorded properly in the VMCS12's activity
10598 	 * state field (AMD does not have a similar field and a VM-Exit always
10599 	 * causes a spurious wakeup from HLT).
10600 	 */
10601 	if (is_guest_mode(vcpu)) {
10602 		if (kvm_check_nested_events(vcpu) < 0)
10603 			return 0;
10604 	}
10605 
10606 	if (kvm_apic_accept_events(vcpu) < 0)
10607 		return 0;
10608 	switch(vcpu->arch.mp_state) {
10609 	case KVM_MP_STATE_HALTED:
10610 	case KVM_MP_STATE_AP_RESET_HOLD:
10611 		vcpu->arch.pv.pv_unhalted = false;
10612 		vcpu->arch.mp_state =
10613 			KVM_MP_STATE_RUNNABLE;
10614 		fallthrough;
10615 	case KVM_MP_STATE_RUNNABLE:
10616 		vcpu->arch.apf.halted = false;
10617 		break;
10618 	case KVM_MP_STATE_INIT_RECEIVED:
10619 		break;
10620 	default:
10621 		WARN_ON_ONCE(1);
10622 		break;
10623 	}
10624 	return 1;
10625 }
10626 
10627 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
10628 {
10629 	return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
10630 		!vcpu->arch.apf.halted);
10631 }
10632 
10633 /* Called within kvm->srcu read side.  */
10634 static int vcpu_run(struct kvm_vcpu *vcpu)
10635 {
10636 	int r;
10637 
10638 	vcpu->arch.l1tf_flush_l1d = true;
10639 
10640 	for (;;) {
10641 		/*
10642 		 * If another guest vCPU requests a PV TLB flush in the middle
10643 		 * of instruction emulation, the rest of the emulation could
10644 		 * use a stale page translation. Assume that any code after
10645 		 * this point can start executing an instruction.
10646 		 */
10647 		vcpu->arch.at_instruction_boundary = false;
10648 		if (kvm_vcpu_running(vcpu)) {
10649 			r = vcpu_enter_guest(vcpu);
10650 		} else {
10651 			r = vcpu_block(vcpu);
10652 		}
10653 
10654 		if (r <= 0)
10655 			break;
10656 
10657 		kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
10658 		if (kvm_xen_has_pending_events(vcpu))
10659 			kvm_xen_inject_pending_events(vcpu);
10660 
10661 		if (kvm_cpu_has_pending_timer(vcpu))
10662 			kvm_inject_pending_timer_irqs(vcpu);
10663 
10664 		if (dm_request_for_irq_injection(vcpu) &&
10665 			kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
10666 			r = 0;
10667 			vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
10668 			++vcpu->stat.request_irq_exits;
10669 			break;
10670 		}
10671 
10672 		if (__xfer_to_guest_mode_work_pending()) {
10673 			kvm_vcpu_srcu_read_unlock(vcpu);
10674 			r = xfer_to_guest_mode_handle_work(vcpu);
10675 			kvm_vcpu_srcu_read_lock(vcpu);
10676 			if (r)
10677 				return r;
10678 		}
10679 	}
10680 
10681 	return r;
10682 }
10683 
10684 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
10685 {
10686 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
10687 }
10688 
10689 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
10690 {
10691 	BUG_ON(!vcpu->arch.pio.count);
10692 
10693 	return complete_emulated_io(vcpu);
10694 }
10695 
10696 /*
10697  * Implements the following, as a state machine:
10698  *
10699  * read:
10700  *   for each fragment
10701  *     for each mmio piece in the fragment
10702  *       write gpa, len
10703  *       exit
10704  *       copy data
10705  *   execute insn
10706  *
10707  * write:
10708  *   for each fragment
10709  *     for each mmio piece in the fragment
10710  *       write gpa, len
10711  *       copy data
10712  *       exit
10713  */
10714 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
10715 {
10716 	struct kvm_run *run = vcpu->run;
10717 	struct kvm_mmio_fragment *frag;
10718 	unsigned len;
10719 
10720 	BUG_ON(!vcpu->mmio_needed);
10721 
10722 	/* Complete previous fragment */
10723 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
10724 	len = min(8u, frag->len);
10725 	if (!vcpu->mmio_is_write)
10726 		memcpy(frag->data, run->mmio.data, len);
10727 
10728 	if (frag->len <= 8) {
10729 		/* Switch to the next fragment. */
10730 		frag++;
10731 		vcpu->mmio_cur_fragment++;
10732 	} else {
10733 		/* Go forward to the next mmio piece. */
10734 		frag->data += len;
10735 		frag->gpa += len;
10736 		frag->len -= len;
10737 	}
10738 
10739 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
10740 		vcpu->mmio_needed = 0;
10741 
10742 		/* FIXME: return into emulator if single-stepping.  */
10743 		if (vcpu->mmio_is_write)
10744 			return 1;
10745 		vcpu->mmio_read_completed = 1;
10746 		return complete_emulated_io(vcpu);
10747 	}
10748 
10749 	run->exit_reason = KVM_EXIT_MMIO;
10750 	run->mmio.phys_addr = frag->gpa;
10751 	if (vcpu->mmio_is_write)
10752 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
10753 	run->mmio.len = min(8u, frag->len);
10754 	run->mmio.is_write = vcpu->mmio_is_write;
10755 	vcpu->arch.complete_userspace_io = complete_emulated_mmio;
10756 	return 0;
10757 }
10758 
10759 /* Swap (qemu) user FPU context for the guest FPU context. */
10760 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
10761 {
10762 	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
10763 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
10764 	trace_kvm_fpu(1);
10765 }
10766 
10767 /* When vcpu_run ends, restore user space FPU context. */
10768 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
10769 {
10770 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
10771 	++vcpu->stat.fpu_reload;
10772 	trace_kvm_fpu(0);
10773 }
10774 
10775 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
10776 {
10777 	struct kvm_queued_exception *ex = &vcpu->arch.exception;
10778 	struct kvm_run *kvm_run = vcpu->run;
10779 	int r;
10780 
10781 	vcpu_load(vcpu);
10782 	kvm_sigset_activate(vcpu);
10783 	kvm_run->flags = 0;
10784 	kvm_load_guest_fpu(vcpu);
10785 
10786 	kvm_vcpu_srcu_read_lock(vcpu);
10787 	if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
10788 		if (kvm_run->immediate_exit) {
10789 			r = -EINTR;
10790 			goto out;
10791 		}
10792 		/*
10793 		 * It should be impossible for the hypervisor timer to be in
10794 		 * use before KVM has ever run the vCPU.
10795 		 */
10796 		WARN_ON_ONCE(kvm_lapic_hv_timer_in_use(vcpu));
10797 
10798 		kvm_vcpu_srcu_read_unlock(vcpu);
10799 		kvm_vcpu_block(vcpu);
10800 		kvm_vcpu_srcu_read_lock(vcpu);
10801 
10802 		if (kvm_apic_accept_events(vcpu) < 0) {
10803 			r = 0;
10804 			goto out;
10805 		}
10806 		r = -EAGAIN;
10807 		if (signal_pending(current)) {
10808 			r = -EINTR;
10809 			kvm_run->exit_reason = KVM_EXIT_INTR;
10810 			++vcpu->stat.signal_exits;
10811 		}
10812 		goto out;
10813 	}
10814 
10815 	if ((kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) ||
10816 	    (kvm_run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)) {
10817 		r = -EINVAL;
10818 		goto out;
10819 	}
10820 
10821 	if (kvm_run->kvm_dirty_regs) {
10822 		r = sync_regs(vcpu);
10823 		if (r != 0)
10824 			goto out;
10825 	}
10826 
10827 	/* re-sync apic's tpr */
10828 	if (!lapic_in_kernel(vcpu)) {
10829 		if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
10830 			r = -EINVAL;
10831 			goto out;
10832 		}
10833 	}
10834 
10835 	/*
10836 	 * If userspace set a pending exception and L2 is active, convert it to
10837 	 * a pending VM-Exit if L1 wants to intercept the exception.
10838 	 */
10839 	if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
10840 	    kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
10841 							ex->error_code)) {
10842 		kvm_queue_exception_vmexit(vcpu, ex->vector,
10843 					   ex->has_error_code, ex->error_code,
10844 					   ex->has_payload, ex->payload);
10845 		ex->injected = false;
10846 		ex->pending = false;
10847 	}
10848 	vcpu->arch.exception_from_userspace = false;
10849 
10850 	if (unlikely(vcpu->arch.complete_userspace_io)) {
10851 		int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
10852 		vcpu->arch.complete_userspace_io = NULL;
10853 		r = cui(vcpu);
10854 		if (r <= 0)
10855 			goto out;
10856 	} else {
10857 		WARN_ON_ONCE(vcpu->arch.pio.count);
10858 		WARN_ON_ONCE(vcpu->mmio_needed);
10859 	}
10860 
10861 	if (kvm_run->immediate_exit) {
10862 		r = -EINTR;
10863 		goto out;
10864 	}
10865 
10866 	r = static_call(kvm_x86_vcpu_pre_run)(vcpu);
10867 	if (r <= 0)
10868 		goto out;
10869 
10870 	r = vcpu_run(vcpu);
10871 
10872 out:
10873 	kvm_put_guest_fpu(vcpu);
10874 	if (kvm_run->kvm_valid_regs)
10875 		store_regs(vcpu);
10876 	post_kvm_run_save(vcpu);
10877 	kvm_vcpu_srcu_read_unlock(vcpu);
10878 
10879 	kvm_sigset_deactivate(vcpu);
10880 	vcpu_put(vcpu);
10881 	return r;
10882 }
10883 
10884 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10885 {
10886 	if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
10887 		/*
10888 		 * We are here if userspace calls get_regs() in the middle of
10889 		 * instruction emulation. Registers state needs to be copied
10890 		 * back from emulation context to vcpu. Userspace shouldn't do
10891 		 * that usually, but some bad designed PV devices (vmware
10892 		 * backdoor interface) need this to work
10893 		 */
10894 		emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
10895 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
10896 	}
10897 	regs->rax = kvm_rax_read(vcpu);
10898 	regs->rbx = kvm_rbx_read(vcpu);
10899 	regs->rcx = kvm_rcx_read(vcpu);
10900 	regs->rdx = kvm_rdx_read(vcpu);
10901 	regs->rsi = kvm_rsi_read(vcpu);
10902 	regs->rdi = kvm_rdi_read(vcpu);
10903 	regs->rsp = kvm_rsp_read(vcpu);
10904 	regs->rbp = kvm_rbp_read(vcpu);
10905 #ifdef CONFIG_X86_64
10906 	regs->r8 = kvm_r8_read(vcpu);
10907 	regs->r9 = kvm_r9_read(vcpu);
10908 	regs->r10 = kvm_r10_read(vcpu);
10909 	regs->r11 = kvm_r11_read(vcpu);
10910 	regs->r12 = kvm_r12_read(vcpu);
10911 	regs->r13 = kvm_r13_read(vcpu);
10912 	regs->r14 = kvm_r14_read(vcpu);
10913 	regs->r15 = kvm_r15_read(vcpu);
10914 #endif
10915 
10916 	regs->rip = kvm_rip_read(vcpu);
10917 	regs->rflags = kvm_get_rflags(vcpu);
10918 }
10919 
10920 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10921 {
10922 	vcpu_load(vcpu);
10923 	__get_regs(vcpu, regs);
10924 	vcpu_put(vcpu);
10925 	return 0;
10926 }
10927 
10928 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10929 {
10930 	vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
10931 	vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
10932 
10933 	kvm_rax_write(vcpu, regs->rax);
10934 	kvm_rbx_write(vcpu, regs->rbx);
10935 	kvm_rcx_write(vcpu, regs->rcx);
10936 	kvm_rdx_write(vcpu, regs->rdx);
10937 	kvm_rsi_write(vcpu, regs->rsi);
10938 	kvm_rdi_write(vcpu, regs->rdi);
10939 	kvm_rsp_write(vcpu, regs->rsp);
10940 	kvm_rbp_write(vcpu, regs->rbp);
10941 #ifdef CONFIG_X86_64
10942 	kvm_r8_write(vcpu, regs->r8);
10943 	kvm_r9_write(vcpu, regs->r9);
10944 	kvm_r10_write(vcpu, regs->r10);
10945 	kvm_r11_write(vcpu, regs->r11);
10946 	kvm_r12_write(vcpu, regs->r12);
10947 	kvm_r13_write(vcpu, regs->r13);
10948 	kvm_r14_write(vcpu, regs->r14);
10949 	kvm_r15_write(vcpu, regs->r15);
10950 #endif
10951 
10952 	kvm_rip_write(vcpu, regs->rip);
10953 	kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
10954 
10955 	vcpu->arch.exception.pending = false;
10956 	vcpu->arch.exception_vmexit.pending = false;
10957 
10958 	kvm_make_request(KVM_REQ_EVENT, vcpu);
10959 }
10960 
10961 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10962 {
10963 	vcpu_load(vcpu);
10964 	__set_regs(vcpu, regs);
10965 	vcpu_put(vcpu);
10966 	return 0;
10967 }
10968 
10969 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
10970 {
10971 	struct desc_ptr dt;
10972 
10973 	if (vcpu->arch.guest_state_protected)
10974 		goto skip_protected_regs;
10975 
10976 	kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
10977 	kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
10978 	kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
10979 	kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
10980 	kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
10981 	kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
10982 
10983 	kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
10984 	kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
10985 
10986 	static_call(kvm_x86_get_idt)(vcpu, &dt);
10987 	sregs->idt.limit = dt.size;
10988 	sregs->idt.base = dt.address;
10989 	static_call(kvm_x86_get_gdt)(vcpu, &dt);
10990 	sregs->gdt.limit = dt.size;
10991 	sregs->gdt.base = dt.address;
10992 
10993 	sregs->cr2 = vcpu->arch.cr2;
10994 	sregs->cr3 = kvm_read_cr3(vcpu);
10995 
10996 skip_protected_regs:
10997 	sregs->cr0 = kvm_read_cr0(vcpu);
10998 	sregs->cr4 = kvm_read_cr4(vcpu);
10999 	sregs->cr8 = kvm_get_cr8(vcpu);
11000 	sregs->efer = vcpu->arch.efer;
11001 	sregs->apic_base = kvm_get_apic_base(vcpu);
11002 }
11003 
11004 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11005 {
11006 	__get_sregs_common(vcpu, sregs);
11007 
11008 	if (vcpu->arch.guest_state_protected)
11009 		return;
11010 
11011 	if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
11012 		set_bit(vcpu->arch.interrupt.nr,
11013 			(unsigned long *)sregs->interrupt_bitmap);
11014 }
11015 
11016 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11017 {
11018 	int i;
11019 
11020 	__get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
11021 
11022 	if (vcpu->arch.guest_state_protected)
11023 		return;
11024 
11025 	if (is_pae_paging(vcpu)) {
11026 		for (i = 0 ; i < 4 ; i++)
11027 			sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
11028 		sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
11029 	}
11030 }
11031 
11032 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
11033 				  struct kvm_sregs *sregs)
11034 {
11035 	vcpu_load(vcpu);
11036 	__get_sregs(vcpu, sregs);
11037 	vcpu_put(vcpu);
11038 	return 0;
11039 }
11040 
11041 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
11042 				    struct kvm_mp_state *mp_state)
11043 {
11044 	int r;
11045 
11046 	vcpu_load(vcpu);
11047 	if (kvm_mpx_supported())
11048 		kvm_load_guest_fpu(vcpu);
11049 
11050 	r = kvm_apic_accept_events(vcpu);
11051 	if (r < 0)
11052 		goto out;
11053 	r = 0;
11054 
11055 	if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
11056 	     vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
11057 	    vcpu->arch.pv.pv_unhalted)
11058 		mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
11059 	else
11060 		mp_state->mp_state = vcpu->arch.mp_state;
11061 
11062 out:
11063 	if (kvm_mpx_supported())
11064 		kvm_put_guest_fpu(vcpu);
11065 	vcpu_put(vcpu);
11066 	return r;
11067 }
11068 
11069 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
11070 				    struct kvm_mp_state *mp_state)
11071 {
11072 	int ret = -EINVAL;
11073 
11074 	vcpu_load(vcpu);
11075 
11076 	switch (mp_state->mp_state) {
11077 	case KVM_MP_STATE_UNINITIALIZED:
11078 	case KVM_MP_STATE_HALTED:
11079 	case KVM_MP_STATE_AP_RESET_HOLD:
11080 	case KVM_MP_STATE_INIT_RECEIVED:
11081 	case KVM_MP_STATE_SIPI_RECEIVED:
11082 		if (!lapic_in_kernel(vcpu))
11083 			goto out;
11084 		break;
11085 
11086 	case KVM_MP_STATE_RUNNABLE:
11087 		break;
11088 
11089 	default:
11090 		goto out;
11091 	}
11092 
11093 	/*
11094 	 * Pending INITs are reported using KVM_SET_VCPU_EVENTS, disallow
11095 	 * forcing the guest into INIT/SIPI if those events are supposed to be
11096 	 * blocked.  KVM prioritizes SMI over INIT, so reject INIT/SIPI state
11097 	 * if an SMI is pending as well.
11098 	 */
11099 	if ((!kvm_apic_init_sipi_allowed(vcpu) || vcpu->arch.smi_pending) &&
11100 	    (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
11101 	     mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
11102 		goto out;
11103 
11104 	if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
11105 		vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
11106 		set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
11107 	} else
11108 		vcpu->arch.mp_state = mp_state->mp_state;
11109 	kvm_make_request(KVM_REQ_EVENT, vcpu);
11110 
11111 	ret = 0;
11112 out:
11113 	vcpu_put(vcpu);
11114 	return ret;
11115 }
11116 
11117 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
11118 		    int reason, bool has_error_code, u32 error_code)
11119 {
11120 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
11121 	int ret;
11122 
11123 	init_emulate_ctxt(vcpu);
11124 
11125 	ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
11126 				   has_error_code, error_code);
11127 	if (ret) {
11128 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11129 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11130 		vcpu->run->internal.ndata = 0;
11131 		return 0;
11132 	}
11133 
11134 	kvm_rip_write(vcpu, ctxt->eip);
11135 	kvm_set_rflags(vcpu, ctxt->eflags);
11136 	return 1;
11137 }
11138 EXPORT_SYMBOL_GPL(kvm_task_switch);
11139 
11140 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11141 {
11142 	if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
11143 		/*
11144 		 * When EFER.LME and CR0.PG are set, the processor is in
11145 		 * 64-bit mode (though maybe in a 32-bit code segment).
11146 		 * CR4.PAE and EFER.LMA must be set.
11147 		 */
11148 		if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
11149 			return false;
11150 		if (kvm_vcpu_is_illegal_gpa(vcpu, sregs->cr3))
11151 			return false;
11152 	} else {
11153 		/*
11154 		 * Not in 64-bit mode: EFER.LMA is clear and the code
11155 		 * segment cannot be 64-bit.
11156 		 */
11157 		if (sregs->efer & EFER_LMA || sregs->cs.l)
11158 			return false;
11159 	}
11160 
11161 	return kvm_is_valid_cr4(vcpu, sregs->cr4);
11162 }
11163 
11164 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
11165 		int *mmu_reset_needed, bool update_pdptrs)
11166 {
11167 	struct msr_data apic_base_msr;
11168 	int idx;
11169 	struct desc_ptr dt;
11170 
11171 	if (!kvm_is_valid_sregs(vcpu, sregs))
11172 		return -EINVAL;
11173 
11174 	apic_base_msr.data = sregs->apic_base;
11175 	apic_base_msr.host_initiated = true;
11176 	if (kvm_set_apic_base(vcpu, &apic_base_msr))
11177 		return -EINVAL;
11178 
11179 	if (vcpu->arch.guest_state_protected)
11180 		return 0;
11181 
11182 	dt.size = sregs->idt.limit;
11183 	dt.address = sregs->idt.base;
11184 	static_call(kvm_x86_set_idt)(vcpu, &dt);
11185 	dt.size = sregs->gdt.limit;
11186 	dt.address = sregs->gdt.base;
11187 	static_call(kvm_x86_set_gdt)(vcpu, &dt);
11188 
11189 	vcpu->arch.cr2 = sregs->cr2;
11190 	*mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
11191 	vcpu->arch.cr3 = sregs->cr3;
11192 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11193 	static_call_cond(kvm_x86_post_set_cr3)(vcpu, sregs->cr3);
11194 
11195 	kvm_set_cr8(vcpu, sregs->cr8);
11196 
11197 	*mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
11198 	static_call(kvm_x86_set_efer)(vcpu, sregs->efer);
11199 
11200 	*mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
11201 	static_call(kvm_x86_set_cr0)(vcpu, sregs->cr0);
11202 	vcpu->arch.cr0 = sregs->cr0;
11203 
11204 	*mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
11205 	static_call(kvm_x86_set_cr4)(vcpu, sregs->cr4);
11206 
11207 	if (update_pdptrs) {
11208 		idx = srcu_read_lock(&vcpu->kvm->srcu);
11209 		if (is_pae_paging(vcpu)) {
11210 			load_pdptrs(vcpu, kvm_read_cr3(vcpu));
11211 			*mmu_reset_needed = 1;
11212 		}
11213 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
11214 	}
11215 
11216 	kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11217 	kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11218 	kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11219 	kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11220 	kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11221 	kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11222 
11223 	kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11224 	kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11225 
11226 	update_cr8_intercept(vcpu);
11227 
11228 	/* Older userspace won't unhalt the vcpu on reset. */
11229 	if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
11230 	    sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
11231 	    !is_protmode(vcpu))
11232 		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11233 
11234 	return 0;
11235 }
11236 
11237 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11238 {
11239 	int pending_vec, max_bits;
11240 	int mmu_reset_needed = 0;
11241 	int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
11242 
11243 	if (ret)
11244 		return ret;
11245 
11246 	if (mmu_reset_needed)
11247 		kvm_mmu_reset_context(vcpu);
11248 
11249 	max_bits = KVM_NR_INTERRUPTS;
11250 	pending_vec = find_first_bit(
11251 		(const unsigned long *)sregs->interrupt_bitmap, max_bits);
11252 
11253 	if (pending_vec < max_bits) {
11254 		kvm_queue_interrupt(vcpu, pending_vec, false);
11255 		pr_debug("Set back pending irq %d\n", pending_vec);
11256 		kvm_make_request(KVM_REQ_EVENT, vcpu);
11257 	}
11258 	return 0;
11259 }
11260 
11261 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11262 {
11263 	int mmu_reset_needed = 0;
11264 	bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
11265 	bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
11266 		!(sregs2->efer & EFER_LMA);
11267 	int i, ret;
11268 
11269 	if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
11270 		return -EINVAL;
11271 
11272 	if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
11273 		return -EINVAL;
11274 
11275 	ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
11276 				 &mmu_reset_needed, !valid_pdptrs);
11277 	if (ret)
11278 		return ret;
11279 
11280 	if (valid_pdptrs) {
11281 		for (i = 0; i < 4 ; i++)
11282 			kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
11283 
11284 		kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
11285 		mmu_reset_needed = 1;
11286 		vcpu->arch.pdptrs_from_userspace = true;
11287 	}
11288 	if (mmu_reset_needed)
11289 		kvm_mmu_reset_context(vcpu);
11290 	return 0;
11291 }
11292 
11293 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
11294 				  struct kvm_sregs *sregs)
11295 {
11296 	int ret;
11297 
11298 	vcpu_load(vcpu);
11299 	ret = __set_sregs(vcpu, sregs);
11300 	vcpu_put(vcpu);
11301 	return ret;
11302 }
11303 
11304 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
11305 {
11306 	bool set = false;
11307 	struct kvm_vcpu *vcpu;
11308 	unsigned long i;
11309 
11310 	if (!enable_apicv)
11311 		return;
11312 
11313 	down_write(&kvm->arch.apicv_update_lock);
11314 
11315 	kvm_for_each_vcpu(i, vcpu, kvm) {
11316 		if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
11317 			set = true;
11318 			break;
11319 		}
11320 	}
11321 	__kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
11322 	up_write(&kvm->arch.apicv_update_lock);
11323 }
11324 
11325 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
11326 					struct kvm_guest_debug *dbg)
11327 {
11328 	unsigned long rflags;
11329 	int i, r;
11330 
11331 	if (vcpu->arch.guest_state_protected)
11332 		return -EINVAL;
11333 
11334 	vcpu_load(vcpu);
11335 
11336 	if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
11337 		r = -EBUSY;
11338 		if (kvm_is_exception_pending(vcpu))
11339 			goto out;
11340 		if (dbg->control & KVM_GUESTDBG_INJECT_DB)
11341 			kvm_queue_exception(vcpu, DB_VECTOR);
11342 		else
11343 			kvm_queue_exception(vcpu, BP_VECTOR);
11344 	}
11345 
11346 	/*
11347 	 * Read rflags as long as potentially injected trace flags are still
11348 	 * filtered out.
11349 	 */
11350 	rflags = kvm_get_rflags(vcpu);
11351 
11352 	vcpu->guest_debug = dbg->control;
11353 	if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
11354 		vcpu->guest_debug = 0;
11355 
11356 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
11357 		for (i = 0; i < KVM_NR_DB_REGS; ++i)
11358 			vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
11359 		vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
11360 	} else {
11361 		for (i = 0; i < KVM_NR_DB_REGS; i++)
11362 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
11363 	}
11364 	kvm_update_dr7(vcpu);
11365 
11366 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
11367 		vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
11368 
11369 	/*
11370 	 * Trigger an rflags update that will inject or remove the trace
11371 	 * flags.
11372 	 */
11373 	kvm_set_rflags(vcpu, rflags);
11374 
11375 	static_call(kvm_x86_update_exception_bitmap)(vcpu);
11376 
11377 	kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
11378 
11379 	r = 0;
11380 
11381 out:
11382 	vcpu_put(vcpu);
11383 	return r;
11384 }
11385 
11386 /*
11387  * Translate a guest virtual address to a guest physical address.
11388  */
11389 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
11390 				    struct kvm_translation *tr)
11391 {
11392 	unsigned long vaddr = tr->linear_address;
11393 	gpa_t gpa;
11394 	int idx;
11395 
11396 	vcpu_load(vcpu);
11397 
11398 	idx = srcu_read_lock(&vcpu->kvm->srcu);
11399 	gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
11400 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
11401 	tr->physical_address = gpa;
11402 	tr->valid = gpa != INVALID_GPA;
11403 	tr->writeable = 1;
11404 	tr->usermode = 0;
11405 
11406 	vcpu_put(vcpu);
11407 	return 0;
11408 }
11409 
11410 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
11411 {
11412 	struct fxregs_state *fxsave;
11413 
11414 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
11415 		return 0;
11416 
11417 	vcpu_load(vcpu);
11418 
11419 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
11420 	memcpy(fpu->fpr, fxsave->st_space, 128);
11421 	fpu->fcw = fxsave->cwd;
11422 	fpu->fsw = fxsave->swd;
11423 	fpu->ftwx = fxsave->twd;
11424 	fpu->last_opcode = fxsave->fop;
11425 	fpu->last_ip = fxsave->rip;
11426 	fpu->last_dp = fxsave->rdp;
11427 	memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
11428 
11429 	vcpu_put(vcpu);
11430 	return 0;
11431 }
11432 
11433 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
11434 {
11435 	struct fxregs_state *fxsave;
11436 
11437 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
11438 		return 0;
11439 
11440 	vcpu_load(vcpu);
11441 
11442 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
11443 
11444 	memcpy(fxsave->st_space, fpu->fpr, 128);
11445 	fxsave->cwd = fpu->fcw;
11446 	fxsave->swd = fpu->fsw;
11447 	fxsave->twd = fpu->ftwx;
11448 	fxsave->fop = fpu->last_opcode;
11449 	fxsave->rip = fpu->last_ip;
11450 	fxsave->rdp = fpu->last_dp;
11451 	memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
11452 
11453 	vcpu_put(vcpu);
11454 	return 0;
11455 }
11456 
11457 static void store_regs(struct kvm_vcpu *vcpu)
11458 {
11459 	BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
11460 
11461 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
11462 		__get_regs(vcpu, &vcpu->run->s.regs.regs);
11463 
11464 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
11465 		__get_sregs(vcpu, &vcpu->run->s.regs.sregs);
11466 
11467 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
11468 		kvm_vcpu_ioctl_x86_get_vcpu_events(
11469 				vcpu, &vcpu->run->s.regs.events);
11470 }
11471 
11472 static int sync_regs(struct kvm_vcpu *vcpu)
11473 {
11474 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
11475 		__set_regs(vcpu, &vcpu->run->s.regs.regs);
11476 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
11477 	}
11478 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
11479 		if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
11480 			return -EINVAL;
11481 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
11482 	}
11483 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
11484 		if (kvm_vcpu_ioctl_x86_set_vcpu_events(
11485 				vcpu, &vcpu->run->s.regs.events))
11486 			return -EINVAL;
11487 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
11488 	}
11489 
11490 	return 0;
11491 }
11492 
11493 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
11494 {
11495 	if (kvm_check_tsc_unstable() && kvm->created_vcpus)
11496 		pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
11497 			     "guest TSC will not be reliable\n");
11498 
11499 	if (!kvm->arch.max_vcpu_ids)
11500 		kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
11501 
11502 	if (id >= kvm->arch.max_vcpu_ids)
11503 		return -EINVAL;
11504 
11505 	return static_call(kvm_x86_vcpu_precreate)(kvm);
11506 }
11507 
11508 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
11509 {
11510 	struct page *page;
11511 	int r;
11512 
11513 	vcpu->arch.last_vmentry_cpu = -1;
11514 	vcpu->arch.regs_avail = ~0;
11515 	vcpu->arch.regs_dirty = ~0;
11516 
11517 	kvm_gpc_init(&vcpu->arch.pv_time);
11518 
11519 	if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
11520 		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11521 	else
11522 		vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
11523 
11524 	r = kvm_mmu_create(vcpu);
11525 	if (r < 0)
11526 		return r;
11527 
11528 	if (irqchip_in_kernel(vcpu->kvm)) {
11529 		r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
11530 		if (r < 0)
11531 			goto fail_mmu_destroy;
11532 
11533 		/*
11534 		 * Defer evaluating inhibits until the vCPU is first run, as
11535 		 * this vCPU will not get notified of any changes until this
11536 		 * vCPU is visible to other vCPUs (marked online and added to
11537 		 * the set of vCPUs).  Opportunistically mark APICv active as
11538 		 * VMX in particularly is highly unlikely to have inhibits.
11539 		 * Ignore the current per-VM APICv state so that vCPU creation
11540 		 * is guaranteed to run with a deterministic value, the request
11541 		 * will ensure the vCPU gets the correct state before VM-Entry.
11542 		 */
11543 		if (enable_apicv) {
11544 			vcpu->arch.apic->apicv_active = true;
11545 			kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
11546 		}
11547 	} else
11548 		static_branch_inc(&kvm_has_noapic_vcpu);
11549 
11550 	r = -ENOMEM;
11551 
11552 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
11553 	if (!page)
11554 		goto fail_free_lapic;
11555 	vcpu->arch.pio_data = page_address(page);
11556 
11557 	vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
11558 				       GFP_KERNEL_ACCOUNT);
11559 	vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
11560 					    GFP_KERNEL_ACCOUNT);
11561 	if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
11562 		goto fail_free_mce_banks;
11563 	vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
11564 
11565 	if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
11566 				GFP_KERNEL_ACCOUNT))
11567 		goto fail_free_mce_banks;
11568 
11569 	if (!alloc_emulate_ctxt(vcpu))
11570 		goto free_wbinvd_dirty_mask;
11571 
11572 	if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
11573 		pr_err("kvm: failed to allocate vcpu's fpu\n");
11574 		goto free_emulate_ctxt;
11575 	}
11576 
11577 	vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
11578 	vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
11579 
11580 	vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
11581 
11582 	kvm_async_pf_hash_reset(vcpu);
11583 
11584 	vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
11585 	kvm_pmu_init(vcpu);
11586 
11587 	vcpu->arch.pending_external_vector = -1;
11588 	vcpu->arch.preempted_in_kernel = false;
11589 
11590 #if IS_ENABLED(CONFIG_HYPERV)
11591 	vcpu->arch.hv_root_tdp = INVALID_PAGE;
11592 #endif
11593 
11594 	r = static_call(kvm_x86_vcpu_create)(vcpu);
11595 	if (r)
11596 		goto free_guest_fpu;
11597 
11598 	vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
11599 	vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
11600 	kvm_xen_init_vcpu(vcpu);
11601 	kvm_vcpu_mtrr_init(vcpu);
11602 	vcpu_load(vcpu);
11603 	kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
11604 	kvm_vcpu_reset(vcpu, false);
11605 	kvm_init_mmu(vcpu);
11606 	vcpu_put(vcpu);
11607 	return 0;
11608 
11609 free_guest_fpu:
11610 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
11611 free_emulate_ctxt:
11612 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
11613 free_wbinvd_dirty_mask:
11614 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
11615 fail_free_mce_banks:
11616 	kfree(vcpu->arch.mce_banks);
11617 	kfree(vcpu->arch.mci_ctl2_banks);
11618 	free_page((unsigned long)vcpu->arch.pio_data);
11619 fail_free_lapic:
11620 	kvm_free_lapic(vcpu);
11621 fail_mmu_destroy:
11622 	kvm_mmu_destroy(vcpu);
11623 	return r;
11624 }
11625 
11626 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
11627 {
11628 	struct kvm *kvm = vcpu->kvm;
11629 
11630 	if (mutex_lock_killable(&vcpu->mutex))
11631 		return;
11632 	vcpu_load(vcpu);
11633 	kvm_synchronize_tsc(vcpu, 0);
11634 	vcpu_put(vcpu);
11635 
11636 	/* poll control enabled by default */
11637 	vcpu->arch.msr_kvm_poll_control = 1;
11638 
11639 	mutex_unlock(&vcpu->mutex);
11640 
11641 	if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
11642 		schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
11643 						KVMCLOCK_SYNC_PERIOD);
11644 }
11645 
11646 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
11647 {
11648 	int idx;
11649 
11650 	kvmclock_reset(vcpu);
11651 
11652 	static_call(kvm_x86_vcpu_free)(vcpu);
11653 
11654 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
11655 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
11656 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
11657 
11658 	kvm_xen_destroy_vcpu(vcpu);
11659 	kvm_hv_vcpu_uninit(vcpu);
11660 	kvm_pmu_destroy(vcpu);
11661 	kfree(vcpu->arch.mce_banks);
11662 	kfree(vcpu->arch.mci_ctl2_banks);
11663 	kvm_free_lapic(vcpu);
11664 	idx = srcu_read_lock(&vcpu->kvm->srcu);
11665 	kvm_mmu_destroy(vcpu);
11666 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
11667 	free_page((unsigned long)vcpu->arch.pio_data);
11668 	kvfree(vcpu->arch.cpuid_entries);
11669 	if (!lapic_in_kernel(vcpu))
11670 		static_branch_dec(&kvm_has_noapic_vcpu);
11671 }
11672 
11673 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
11674 {
11675 	struct kvm_cpuid_entry2 *cpuid_0x1;
11676 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
11677 	unsigned long new_cr0;
11678 
11679 	/*
11680 	 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
11681 	 * to handle side effects.  RESET emulation hits those flows and relies
11682 	 * on emulated/virtualized registers, including those that are loaded
11683 	 * into hardware, to be zeroed at vCPU creation.  Use CRs as a sentinel
11684 	 * to detect improper or missing initialization.
11685 	 */
11686 	WARN_ON_ONCE(!init_event &&
11687 		     (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
11688 
11689 	kvm_lapic_reset(vcpu, init_event);
11690 
11691 	vcpu->arch.hflags = 0;
11692 
11693 	vcpu->arch.smi_pending = 0;
11694 	vcpu->arch.smi_count = 0;
11695 	atomic_set(&vcpu->arch.nmi_queued, 0);
11696 	vcpu->arch.nmi_pending = 0;
11697 	vcpu->arch.nmi_injected = false;
11698 	kvm_clear_interrupt_queue(vcpu);
11699 	kvm_clear_exception_queue(vcpu);
11700 
11701 	memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
11702 	kvm_update_dr0123(vcpu);
11703 	vcpu->arch.dr6 = DR6_ACTIVE_LOW;
11704 	vcpu->arch.dr7 = DR7_FIXED_1;
11705 	kvm_update_dr7(vcpu);
11706 
11707 	vcpu->arch.cr2 = 0;
11708 
11709 	kvm_make_request(KVM_REQ_EVENT, vcpu);
11710 	vcpu->arch.apf.msr_en_val = 0;
11711 	vcpu->arch.apf.msr_int_val = 0;
11712 	vcpu->arch.st.msr_val = 0;
11713 
11714 	kvmclock_reset(vcpu);
11715 
11716 	kvm_clear_async_pf_completion_queue(vcpu);
11717 	kvm_async_pf_hash_reset(vcpu);
11718 	vcpu->arch.apf.halted = false;
11719 
11720 	if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
11721 		struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
11722 
11723 		/*
11724 		 * All paths that lead to INIT are required to load the guest's
11725 		 * FPU state (because most paths are buried in KVM_RUN).
11726 		 */
11727 		if (init_event)
11728 			kvm_put_guest_fpu(vcpu);
11729 
11730 		fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
11731 		fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
11732 
11733 		if (init_event)
11734 			kvm_load_guest_fpu(vcpu);
11735 	}
11736 
11737 	if (!init_event) {
11738 		kvm_pmu_reset(vcpu);
11739 		vcpu->arch.smbase = 0x30000;
11740 
11741 		vcpu->arch.msr_misc_features_enables = 0;
11742 		vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
11743 						  MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
11744 
11745 		__kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
11746 		__kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
11747 	}
11748 
11749 	/* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
11750 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
11751 	kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
11752 
11753 	/*
11754 	 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
11755 	 * if no CPUID match is found.  Note, it's impossible to get a match at
11756 	 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
11757 	 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
11758 	 * on RESET.  But, go through the motions in case that's ever remedied.
11759 	 */
11760 	cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
11761 	kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
11762 
11763 	static_call(kvm_x86_vcpu_reset)(vcpu, init_event);
11764 
11765 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
11766 	kvm_rip_write(vcpu, 0xfff0);
11767 
11768 	vcpu->arch.cr3 = 0;
11769 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11770 
11771 	/*
11772 	 * CR0.CD/NW are set on RESET, preserved on INIT.  Note, some versions
11773 	 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
11774 	 * (or qualify) that with a footnote stating that CD/NW are preserved.
11775 	 */
11776 	new_cr0 = X86_CR0_ET;
11777 	if (init_event)
11778 		new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
11779 	else
11780 		new_cr0 |= X86_CR0_NW | X86_CR0_CD;
11781 
11782 	static_call(kvm_x86_set_cr0)(vcpu, new_cr0);
11783 	static_call(kvm_x86_set_cr4)(vcpu, 0);
11784 	static_call(kvm_x86_set_efer)(vcpu, 0);
11785 	static_call(kvm_x86_update_exception_bitmap)(vcpu);
11786 
11787 	/*
11788 	 * On the standard CR0/CR4/EFER modification paths, there are several
11789 	 * complex conditions determining whether the MMU has to be reset and/or
11790 	 * which PCIDs have to be flushed.  However, CR0.WP and the paging-related
11791 	 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
11792 	 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
11793 	 * CR0 will be '0' prior to RESET).  So we only need to check CR0.PG here.
11794 	 */
11795 	if (old_cr0 & X86_CR0_PG) {
11796 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
11797 		kvm_mmu_reset_context(vcpu);
11798 	}
11799 
11800 	/*
11801 	 * Intel's SDM states that all TLB entries are flushed on INIT.  AMD's
11802 	 * APM states the TLBs are untouched by INIT, but it also states that
11803 	 * the TLBs are flushed on "External initialization of the processor."
11804 	 * Flush the guest TLB regardless of vendor, there is no meaningful
11805 	 * benefit in relying on the guest to flush the TLB immediately after
11806 	 * INIT.  A spurious TLB flush is benign and likely negligible from a
11807 	 * performance perspective.
11808 	 */
11809 	if (init_event)
11810 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
11811 }
11812 EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
11813 
11814 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
11815 {
11816 	struct kvm_segment cs;
11817 
11818 	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
11819 	cs.selector = vector << 8;
11820 	cs.base = vector << 12;
11821 	kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
11822 	kvm_rip_write(vcpu, 0);
11823 }
11824 EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
11825 
11826 int kvm_arch_hardware_enable(void)
11827 {
11828 	struct kvm *kvm;
11829 	struct kvm_vcpu *vcpu;
11830 	unsigned long i;
11831 	int ret;
11832 	u64 local_tsc;
11833 	u64 max_tsc = 0;
11834 	bool stable, backwards_tsc = false;
11835 
11836 	kvm_user_return_msr_cpu_online();
11837 	ret = static_call(kvm_x86_hardware_enable)();
11838 	if (ret != 0)
11839 		return ret;
11840 
11841 	local_tsc = rdtsc();
11842 	stable = !kvm_check_tsc_unstable();
11843 	list_for_each_entry(kvm, &vm_list, vm_list) {
11844 		kvm_for_each_vcpu(i, vcpu, kvm) {
11845 			if (!stable && vcpu->cpu == smp_processor_id())
11846 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11847 			if (stable && vcpu->arch.last_host_tsc > local_tsc) {
11848 				backwards_tsc = true;
11849 				if (vcpu->arch.last_host_tsc > max_tsc)
11850 					max_tsc = vcpu->arch.last_host_tsc;
11851 			}
11852 		}
11853 	}
11854 
11855 	/*
11856 	 * Sometimes, even reliable TSCs go backwards.  This happens on
11857 	 * platforms that reset TSC during suspend or hibernate actions, but
11858 	 * maintain synchronization.  We must compensate.  Fortunately, we can
11859 	 * detect that condition here, which happens early in CPU bringup,
11860 	 * before any KVM threads can be running.  Unfortunately, we can't
11861 	 * bring the TSCs fully up to date with real time, as we aren't yet far
11862 	 * enough into CPU bringup that we know how much real time has actually
11863 	 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
11864 	 * variables that haven't been updated yet.
11865 	 *
11866 	 * So we simply find the maximum observed TSC above, then record the
11867 	 * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
11868 	 * the adjustment will be applied.  Note that we accumulate
11869 	 * adjustments, in case multiple suspend cycles happen before some VCPU
11870 	 * gets a chance to run again.  In the event that no KVM threads get a
11871 	 * chance to run, we will miss the entire elapsed period, as we'll have
11872 	 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
11873 	 * loose cycle time.  This isn't too big a deal, since the loss will be
11874 	 * uniform across all VCPUs (not to mention the scenario is extremely
11875 	 * unlikely). It is possible that a second hibernate recovery happens
11876 	 * much faster than a first, causing the observed TSC here to be
11877 	 * smaller; this would require additional padding adjustment, which is
11878 	 * why we set last_host_tsc to the local tsc observed here.
11879 	 *
11880 	 * N.B. - this code below runs only on platforms with reliable TSC,
11881 	 * as that is the only way backwards_tsc is set above.  Also note
11882 	 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
11883 	 * have the same delta_cyc adjustment applied if backwards_tsc
11884 	 * is detected.  Note further, this adjustment is only done once,
11885 	 * as we reset last_host_tsc on all VCPUs to stop this from being
11886 	 * called multiple times (one for each physical CPU bringup).
11887 	 *
11888 	 * Platforms with unreliable TSCs don't have to deal with this, they
11889 	 * will be compensated by the logic in vcpu_load, which sets the TSC to
11890 	 * catchup mode.  This will catchup all VCPUs to real time, but cannot
11891 	 * guarantee that they stay in perfect synchronization.
11892 	 */
11893 	if (backwards_tsc) {
11894 		u64 delta_cyc = max_tsc - local_tsc;
11895 		list_for_each_entry(kvm, &vm_list, vm_list) {
11896 			kvm->arch.backwards_tsc_observed = true;
11897 			kvm_for_each_vcpu(i, vcpu, kvm) {
11898 				vcpu->arch.tsc_offset_adjustment += delta_cyc;
11899 				vcpu->arch.last_host_tsc = local_tsc;
11900 				kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
11901 			}
11902 
11903 			/*
11904 			 * We have to disable TSC offset matching.. if you were
11905 			 * booting a VM while issuing an S4 host suspend....
11906 			 * you may have some problem.  Solving this issue is
11907 			 * left as an exercise to the reader.
11908 			 */
11909 			kvm->arch.last_tsc_nsec = 0;
11910 			kvm->arch.last_tsc_write = 0;
11911 		}
11912 
11913 	}
11914 	return 0;
11915 }
11916 
11917 void kvm_arch_hardware_disable(void)
11918 {
11919 	static_call(kvm_x86_hardware_disable)();
11920 	drop_user_return_notifiers();
11921 }
11922 
11923 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
11924 {
11925 	memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
11926 
11927 #define __KVM_X86_OP(func) \
11928 	static_call_update(kvm_x86_##func, kvm_x86_ops.func);
11929 #define KVM_X86_OP(func) \
11930 	WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
11931 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
11932 #define KVM_X86_OP_OPTIONAL_RET0(func) \
11933 	static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
11934 					   (void *)__static_call_return0);
11935 #include <asm/kvm-x86-ops.h>
11936 #undef __KVM_X86_OP
11937 
11938 	kvm_pmu_ops_update(ops->pmu_ops);
11939 }
11940 
11941 int kvm_arch_hardware_setup(void *opaque)
11942 {
11943 	struct kvm_x86_init_ops *ops = opaque;
11944 	int r;
11945 
11946 	rdmsrl_safe(MSR_EFER, &host_efer);
11947 
11948 	if (boot_cpu_has(X86_FEATURE_XSAVES))
11949 		rdmsrl(MSR_IA32_XSS, host_xss);
11950 
11951 	kvm_init_pmu_capability();
11952 
11953 	r = ops->hardware_setup();
11954 	if (r != 0)
11955 		return r;
11956 
11957 	kvm_ops_update(ops);
11958 
11959 	kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
11960 
11961 	if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
11962 		kvm_caps.supported_xss = 0;
11963 
11964 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
11965 	cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
11966 #undef __kvm_cpu_cap_has
11967 
11968 	if (kvm_caps.has_tsc_control) {
11969 		/*
11970 		 * Make sure the user can only configure tsc_khz values that
11971 		 * fit into a signed integer.
11972 		 * A min value is not calculated because it will always
11973 		 * be 1 on all machines.
11974 		 */
11975 		u64 max = min(0x7fffffffULL,
11976 			      __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
11977 		kvm_caps.max_guest_tsc_khz = max;
11978 	}
11979 	kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
11980 	kvm_init_msr_list();
11981 	return 0;
11982 }
11983 
11984 void kvm_arch_hardware_unsetup(void)
11985 {
11986 	kvm_unregister_perf_callbacks();
11987 
11988 	static_call(kvm_x86_hardware_unsetup)();
11989 }
11990 
11991 int kvm_arch_check_processor_compat(void *opaque)
11992 {
11993 	struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
11994 	struct kvm_x86_init_ops *ops = opaque;
11995 
11996 	WARN_ON(!irqs_disabled());
11997 
11998 	if (__cr4_reserved_bits(cpu_has, c) !=
11999 	    __cr4_reserved_bits(cpu_has, &boot_cpu_data))
12000 		return -EIO;
12001 
12002 	return ops->check_processor_compatibility();
12003 }
12004 
12005 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
12006 {
12007 	return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
12008 }
12009 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
12010 
12011 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
12012 {
12013 	return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
12014 }
12015 
12016 __read_mostly DEFINE_STATIC_KEY_FALSE(kvm_has_noapic_vcpu);
12017 EXPORT_SYMBOL_GPL(kvm_has_noapic_vcpu);
12018 
12019 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
12020 {
12021 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
12022 
12023 	vcpu->arch.l1tf_flush_l1d = true;
12024 	if (pmu->version && unlikely(pmu->event_count)) {
12025 		pmu->need_cleanup = true;
12026 		kvm_make_request(KVM_REQ_PMU, vcpu);
12027 	}
12028 	static_call(kvm_x86_sched_in)(vcpu, cpu);
12029 }
12030 
12031 void kvm_arch_free_vm(struct kvm *kvm)
12032 {
12033 	kfree(to_kvm_hv(kvm)->hv_pa_pg);
12034 	__kvm_arch_free_vm(kvm);
12035 }
12036 
12037 
12038 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
12039 {
12040 	int ret;
12041 	unsigned long flags;
12042 
12043 	if (type)
12044 		return -EINVAL;
12045 
12046 	ret = kvm_page_track_init(kvm);
12047 	if (ret)
12048 		goto out;
12049 
12050 	ret = kvm_mmu_init_vm(kvm);
12051 	if (ret)
12052 		goto out_page_track;
12053 
12054 	ret = static_call(kvm_x86_vm_init)(kvm);
12055 	if (ret)
12056 		goto out_uninit_mmu;
12057 
12058 	INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
12059 	INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
12060 	atomic_set(&kvm->arch.noncoherent_dma_count, 0);
12061 
12062 	/* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
12063 	set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
12064 	/* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
12065 	set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
12066 		&kvm->arch.irq_sources_bitmap);
12067 
12068 	raw_spin_lock_init(&kvm->arch.tsc_write_lock);
12069 	mutex_init(&kvm->arch.apic_map_lock);
12070 	seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
12071 	kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
12072 
12073 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
12074 	pvclock_update_vm_gtod_copy(kvm);
12075 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
12076 
12077 	kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
12078 	kvm->arch.guest_can_read_msr_platform_info = true;
12079 	kvm->arch.enable_pmu = enable_pmu;
12080 
12081 #if IS_ENABLED(CONFIG_HYPERV)
12082 	spin_lock_init(&kvm->arch.hv_root_tdp_lock);
12083 	kvm->arch.hv_root_tdp = INVALID_PAGE;
12084 #endif
12085 
12086 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
12087 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
12088 
12089 	kvm_apicv_init(kvm);
12090 	kvm_hv_init_vm(kvm);
12091 	kvm_xen_init_vm(kvm);
12092 
12093 	return 0;
12094 
12095 out_uninit_mmu:
12096 	kvm_mmu_uninit_vm(kvm);
12097 out_page_track:
12098 	kvm_page_track_cleanup(kvm);
12099 out:
12100 	return ret;
12101 }
12102 
12103 int kvm_arch_post_init_vm(struct kvm *kvm)
12104 {
12105 	return kvm_mmu_post_init_vm(kvm);
12106 }
12107 
12108 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
12109 {
12110 	vcpu_load(vcpu);
12111 	kvm_mmu_unload(vcpu);
12112 	vcpu_put(vcpu);
12113 }
12114 
12115 static void kvm_unload_vcpu_mmus(struct kvm *kvm)
12116 {
12117 	unsigned long i;
12118 	struct kvm_vcpu *vcpu;
12119 
12120 	kvm_for_each_vcpu(i, vcpu, kvm) {
12121 		kvm_clear_async_pf_completion_queue(vcpu);
12122 		kvm_unload_vcpu_mmu(vcpu);
12123 	}
12124 }
12125 
12126 void kvm_arch_sync_events(struct kvm *kvm)
12127 {
12128 	cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
12129 	cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
12130 	kvm_free_pit(kvm);
12131 }
12132 
12133 /**
12134  * __x86_set_memory_region: Setup KVM internal memory slot
12135  *
12136  * @kvm: the kvm pointer to the VM.
12137  * @id: the slot ID to setup.
12138  * @gpa: the GPA to install the slot (unused when @size == 0).
12139  * @size: the size of the slot. Set to zero to uninstall a slot.
12140  *
12141  * This function helps to setup a KVM internal memory slot.  Specify
12142  * @size > 0 to install a new slot, while @size == 0 to uninstall a
12143  * slot.  The return code can be one of the following:
12144  *
12145  *   HVA:           on success (uninstall will return a bogus HVA)
12146  *   -errno:        on error
12147  *
12148  * The caller should always use IS_ERR() to check the return value
12149  * before use.  Note, the KVM internal memory slots are guaranteed to
12150  * remain valid and unchanged until the VM is destroyed, i.e., the
12151  * GPA->HVA translation will not change.  However, the HVA is a user
12152  * address, i.e. its accessibility is not guaranteed, and must be
12153  * accessed via __copy_{to,from}_user().
12154  */
12155 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
12156 				      u32 size)
12157 {
12158 	int i, r;
12159 	unsigned long hva, old_npages;
12160 	struct kvm_memslots *slots = kvm_memslots(kvm);
12161 	struct kvm_memory_slot *slot;
12162 
12163 	/* Called with kvm->slots_lock held.  */
12164 	if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
12165 		return ERR_PTR_USR(-EINVAL);
12166 
12167 	slot = id_to_memslot(slots, id);
12168 	if (size) {
12169 		if (slot && slot->npages)
12170 			return ERR_PTR_USR(-EEXIST);
12171 
12172 		/*
12173 		 * MAP_SHARED to prevent internal slot pages from being moved
12174 		 * by fork()/COW.
12175 		 */
12176 		hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
12177 			      MAP_SHARED | MAP_ANONYMOUS, 0);
12178 		if (IS_ERR((void *)hva))
12179 			return (void __user *)hva;
12180 	} else {
12181 		if (!slot || !slot->npages)
12182 			return NULL;
12183 
12184 		old_npages = slot->npages;
12185 		hva = slot->userspace_addr;
12186 	}
12187 
12188 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
12189 		struct kvm_userspace_memory_region m;
12190 
12191 		m.slot = id | (i << 16);
12192 		m.flags = 0;
12193 		m.guest_phys_addr = gpa;
12194 		m.userspace_addr = hva;
12195 		m.memory_size = size;
12196 		r = __kvm_set_memory_region(kvm, &m);
12197 		if (r < 0)
12198 			return ERR_PTR_USR(r);
12199 	}
12200 
12201 	if (!size)
12202 		vm_munmap(hva, old_npages * PAGE_SIZE);
12203 
12204 	return (void __user *)hva;
12205 }
12206 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
12207 
12208 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
12209 {
12210 	kvm_mmu_pre_destroy_vm(kvm);
12211 }
12212 
12213 void kvm_arch_destroy_vm(struct kvm *kvm)
12214 {
12215 	if (current->mm == kvm->mm) {
12216 		/*
12217 		 * Free memory regions allocated on behalf of userspace,
12218 		 * unless the memory map has changed due to process exit
12219 		 * or fd copying.
12220 		 */
12221 		mutex_lock(&kvm->slots_lock);
12222 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
12223 					0, 0);
12224 		__x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
12225 					0, 0);
12226 		__x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
12227 		mutex_unlock(&kvm->slots_lock);
12228 	}
12229 	kvm_unload_vcpu_mmus(kvm);
12230 	static_call_cond(kvm_x86_vm_destroy)(kvm);
12231 	kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
12232 	kvm_pic_destroy(kvm);
12233 	kvm_ioapic_destroy(kvm);
12234 	kvm_destroy_vcpus(kvm);
12235 	kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
12236 	kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
12237 	kvm_mmu_uninit_vm(kvm);
12238 	kvm_page_track_cleanup(kvm);
12239 	kvm_xen_destroy_vm(kvm);
12240 	kvm_hv_destroy_vm(kvm);
12241 }
12242 
12243 static void memslot_rmap_free(struct kvm_memory_slot *slot)
12244 {
12245 	int i;
12246 
12247 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12248 		kvfree(slot->arch.rmap[i]);
12249 		slot->arch.rmap[i] = NULL;
12250 	}
12251 }
12252 
12253 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
12254 {
12255 	int i;
12256 
12257 	memslot_rmap_free(slot);
12258 
12259 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12260 		kvfree(slot->arch.lpage_info[i - 1]);
12261 		slot->arch.lpage_info[i - 1] = NULL;
12262 	}
12263 
12264 	kvm_page_track_free_memslot(slot);
12265 }
12266 
12267 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
12268 {
12269 	const int sz = sizeof(*slot->arch.rmap[0]);
12270 	int i;
12271 
12272 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12273 		int level = i + 1;
12274 		int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12275 
12276 		if (slot->arch.rmap[i])
12277 			continue;
12278 
12279 		slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
12280 		if (!slot->arch.rmap[i]) {
12281 			memslot_rmap_free(slot);
12282 			return -ENOMEM;
12283 		}
12284 	}
12285 
12286 	return 0;
12287 }
12288 
12289 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
12290 				      struct kvm_memory_slot *slot)
12291 {
12292 	unsigned long npages = slot->npages;
12293 	int i, r;
12294 
12295 	/*
12296 	 * Clear out the previous array pointers for the KVM_MR_MOVE case.  The
12297 	 * old arrays will be freed by __kvm_set_memory_region() if installing
12298 	 * the new memslot is successful.
12299 	 */
12300 	memset(&slot->arch, 0, sizeof(slot->arch));
12301 
12302 	if (kvm_memslots_have_rmaps(kvm)) {
12303 		r = memslot_rmap_alloc(slot, npages);
12304 		if (r)
12305 			return r;
12306 	}
12307 
12308 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12309 		struct kvm_lpage_info *linfo;
12310 		unsigned long ugfn;
12311 		int lpages;
12312 		int level = i + 1;
12313 
12314 		lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12315 
12316 		linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
12317 		if (!linfo)
12318 			goto out_free;
12319 
12320 		slot->arch.lpage_info[i - 1] = linfo;
12321 
12322 		if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
12323 			linfo[0].disallow_lpage = 1;
12324 		if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
12325 			linfo[lpages - 1].disallow_lpage = 1;
12326 		ugfn = slot->userspace_addr >> PAGE_SHIFT;
12327 		/*
12328 		 * If the gfn and userspace address are not aligned wrt each
12329 		 * other, disable large page support for this slot.
12330 		 */
12331 		if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
12332 			unsigned long j;
12333 
12334 			for (j = 0; j < lpages; ++j)
12335 				linfo[j].disallow_lpage = 1;
12336 		}
12337 	}
12338 
12339 	if (kvm_page_track_create_memslot(kvm, slot, npages))
12340 		goto out_free;
12341 
12342 	return 0;
12343 
12344 out_free:
12345 	memslot_rmap_free(slot);
12346 
12347 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12348 		kvfree(slot->arch.lpage_info[i - 1]);
12349 		slot->arch.lpage_info[i - 1] = NULL;
12350 	}
12351 	return -ENOMEM;
12352 }
12353 
12354 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
12355 {
12356 	struct kvm_vcpu *vcpu;
12357 	unsigned long i;
12358 
12359 	/*
12360 	 * memslots->generation has been incremented.
12361 	 * mmio generation may have reached its maximum value.
12362 	 */
12363 	kvm_mmu_invalidate_mmio_sptes(kvm, gen);
12364 
12365 	/* Force re-initialization of steal_time cache */
12366 	kvm_for_each_vcpu(i, vcpu, kvm)
12367 		kvm_vcpu_kick(vcpu);
12368 }
12369 
12370 int kvm_arch_prepare_memory_region(struct kvm *kvm,
12371 				   const struct kvm_memory_slot *old,
12372 				   struct kvm_memory_slot *new,
12373 				   enum kvm_mr_change change)
12374 {
12375 	if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
12376 		if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
12377 			return -EINVAL;
12378 
12379 		return kvm_alloc_memslot_metadata(kvm, new);
12380 	}
12381 
12382 	if (change == KVM_MR_FLAGS_ONLY)
12383 		memcpy(&new->arch, &old->arch, sizeof(old->arch));
12384 	else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
12385 		return -EIO;
12386 
12387 	return 0;
12388 }
12389 
12390 
12391 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
12392 {
12393 	struct kvm_arch *ka = &kvm->arch;
12394 
12395 	if (!kvm_x86_ops.cpu_dirty_log_size)
12396 		return;
12397 
12398 	if ((enable && ++ka->cpu_dirty_logging_count == 1) ||
12399 	    (!enable && --ka->cpu_dirty_logging_count == 0))
12400 		kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
12401 
12402 	WARN_ON_ONCE(ka->cpu_dirty_logging_count < 0);
12403 }
12404 
12405 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
12406 				     struct kvm_memory_slot *old,
12407 				     const struct kvm_memory_slot *new,
12408 				     enum kvm_mr_change change)
12409 {
12410 	u32 old_flags = old ? old->flags : 0;
12411 	u32 new_flags = new ? new->flags : 0;
12412 	bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
12413 
12414 	/*
12415 	 * Update CPU dirty logging if dirty logging is being toggled.  This
12416 	 * applies to all operations.
12417 	 */
12418 	if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
12419 		kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
12420 
12421 	/*
12422 	 * Nothing more to do for RO slots (which can't be dirtied and can't be
12423 	 * made writable) or CREATE/MOVE/DELETE of a slot.
12424 	 *
12425 	 * For a memslot with dirty logging disabled:
12426 	 * CREATE:      No dirty mappings will already exist.
12427 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
12428 	 *		kvm_arch_flush_shadow_memslot()
12429 	 *
12430 	 * For a memslot with dirty logging enabled:
12431 	 * CREATE:      No shadow pages exist, thus nothing to write-protect
12432 	 *		and no dirty bits to clear.
12433 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
12434 	 *		kvm_arch_flush_shadow_memslot().
12435 	 */
12436 	if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
12437 		return;
12438 
12439 	/*
12440 	 * READONLY and non-flags changes were filtered out above, and the only
12441 	 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
12442 	 * logging isn't being toggled on or off.
12443 	 */
12444 	if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
12445 		return;
12446 
12447 	if (!log_dirty_pages) {
12448 		/*
12449 		 * Dirty logging tracks sptes in 4k granularity, meaning that
12450 		 * large sptes have to be split.  If live migration succeeds,
12451 		 * the guest in the source machine will be destroyed and large
12452 		 * sptes will be created in the destination.  However, if the
12453 		 * guest continues to run in the source machine (for example if
12454 		 * live migration fails), small sptes will remain around and
12455 		 * cause bad performance.
12456 		 *
12457 		 * Scan sptes if dirty logging has been stopped, dropping those
12458 		 * which can be collapsed into a single large-page spte.  Later
12459 		 * page faults will create the large-page sptes.
12460 		 */
12461 		kvm_mmu_zap_collapsible_sptes(kvm, new);
12462 	} else {
12463 		/*
12464 		 * Initially-all-set does not require write protecting any page,
12465 		 * because they're all assumed to be dirty.
12466 		 */
12467 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
12468 			return;
12469 
12470 		if (READ_ONCE(eager_page_split))
12471 			kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
12472 
12473 		if (kvm_x86_ops.cpu_dirty_log_size) {
12474 			kvm_mmu_slot_leaf_clear_dirty(kvm, new);
12475 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
12476 		} else {
12477 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
12478 		}
12479 
12480 		/*
12481 		 * Unconditionally flush the TLBs after enabling dirty logging.
12482 		 * A flush is almost always going to be necessary (see below),
12483 		 * and unconditionally flushing allows the helpers to omit
12484 		 * the subtly complex checks when removing write access.
12485 		 *
12486 		 * Do the flush outside of mmu_lock to reduce the amount of
12487 		 * time mmu_lock is held.  Flushing after dropping mmu_lock is
12488 		 * safe as KVM only needs to guarantee the slot is fully
12489 		 * write-protected before returning to userspace, i.e. before
12490 		 * userspace can consume the dirty status.
12491 		 *
12492 		 * Flushing outside of mmu_lock requires KVM to be careful when
12493 		 * making decisions based on writable status of an SPTE, e.g. a
12494 		 * !writable SPTE doesn't guarantee a CPU can't perform writes.
12495 		 *
12496 		 * Specifically, KVM also write-protects guest page tables to
12497 		 * monitor changes when using shadow paging, and must guarantee
12498 		 * no CPUs can write to those page before mmu_lock is dropped.
12499 		 * Because CPUs may have stale TLB entries at this point, a
12500 		 * !writable SPTE doesn't guarantee CPUs can't perform writes.
12501 		 *
12502 		 * KVM also allows making SPTES writable outside of mmu_lock,
12503 		 * e.g. to allow dirty logging without taking mmu_lock.
12504 		 *
12505 		 * To handle these scenarios, KVM uses a separate software-only
12506 		 * bit (MMU-writable) to track if a SPTE is !writable due to
12507 		 * a guest page table being write-protected (KVM clears the
12508 		 * MMU-writable flag when write-protecting for shadow paging).
12509 		 *
12510 		 * The use of MMU-writable is also the primary motivation for
12511 		 * the unconditional flush.  Because KVM must guarantee that a
12512 		 * CPU doesn't contain stale, writable TLB entries for a
12513 		 * !MMU-writable SPTE, KVM must flush if it encounters any
12514 		 * MMU-writable SPTE regardless of whether the actual hardware
12515 		 * writable bit was set.  I.e. KVM is almost guaranteed to need
12516 		 * to flush, while unconditionally flushing allows the "remove
12517 		 * write access" helpers to ignore MMU-writable entirely.
12518 		 *
12519 		 * See is_writable_pte() for more details (the case involving
12520 		 * access-tracked SPTEs is particularly relevant).
12521 		 */
12522 		kvm_arch_flush_remote_tlbs_memslot(kvm, new);
12523 	}
12524 }
12525 
12526 void kvm_arch_commit_memory_region(struct kvm *kvm,
12527 				struct kvm_memory_slot *old,
12528 				const struct kvm_memory_slot *new,
12529 				enum kvm_mr_change change)
12530 {
12531 	if (!kvm->arch.n_requested_mmu_pages &&
12532 	    (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
12533 		unsigned long nr_mmu_pages;
12534 
12535 		nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
12536 		nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
12537 		kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
12538 	}
12539 
12540 	kvm_mmu_slot_apply_flags(kvm, old, new, change);
12541 
12542 	/* Free the arrays associated with the old memslot. */
12543 	if (change == KVM_MR_MOVE)
12544 		kvm_arch_free_memslot(kvm, old);
12545 }
12546 
12547 void kvm_arch_flush_shadow_all(struct kvm *kvm)
12548 {
12549 	kvm_mmu_zap_all(kvm);
12550 }
12551 
12552 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
12553 				   struct kvm_memory_slot *slot)
12554 {
12555 	kvm_page_track_flush_slot(kvm, slot);
12556 }
12557 
12558 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
12559 {
12560 	return (is_guest_mode(vcpu) &&
12561 		static_call(kvm_x86_guest_apic_has_interrupt)(vcpu));
12562 }
12563 
12564 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
12565 {
12566 	if (!list_empty_careful(&vcpu->async_pf.done))
12567 		return true;
12568 
12569 	if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
12570 	    kvm_apic_init_sipi_allowed(vcpu))
12571 		return true;
12572 
12573 	if (vcpu->arch.pv.pv_unhalted)
12574 		return true;
12575 
12576 	if (kvm_is_exception_pending(vcpu))
12577 		return true;
12578 
12579 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
12580 	    (vcpu->arch.nmi_pending &&
12581 	     static_call(kvm_x86_nmi_allowed)(vcpu, false)))
12582 		return true;
12583 
12584 #ifdef CONFIG_KVM_SMM
12585 	if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
12586 	    (vcpu->arch.smi_pending &&
12587 	     static_call(kvm_x86_smi_allowed)(vcpu, false)))
12588 		return true;
12589 #endif
12590 
12591 	if (kvm_arch_interrupt_allowed(vcpu) &&
12592 	    (kvm_cpu_has_interrupt(vcpu) ||
12593 	    kvm_guest_apic_has_interrupt(vcpu)))
12594 		return true;
12595 
12596 	if (kvm_hv_has_stimer_pending(vcpu))
12597 		return true;
12598 
12599 	if (is_guest_mode(vcpu) &&
12600 	    kvm_x86_ops.nested_ops->has_events &&
12601 	    kvm_x86_ops.nested_ops->has_events(vcpu))
12602 		return true;
12603 
12604 	if (kvm_xen_has_pending_events(vcpu))
12605 		return true;
12606 
12607 	return false;
12608 }
12609 
12610 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
12611 {
12612 	return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
12613 }
12614 
12615 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
12616 {
12617 	if (kvm_vcpu_apicv_active(vcpu) &&
12618 	    static_call(kvm_x86_dy_apicv_has_pending_interrupt)(vcpu))
12619 		return true;
12620 
12621 	return false;
12622 }
12623 
12624 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
12625 {
12626 	if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
12627 		return true;
12628 
12629 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
12630 #ifdef CONFIG_KVM_SMM
12631 		kvm_test_request(KVM_REQ_SMI, vcpu) ||
12632 #endif
12633 		 kvm_test_request(KVM_REQ_EVENT, vcpu))
12634 		return true;
12635 
12636 	return kvm_arch_dy_has_pending_interrupt(vcpu);
12637 }
12638 
12639 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
12640 {
12641 	if (vcpu->arch.guest_state_protected)
12642 		return true;
12643 
12644 	return vcpu->arch.preempted_in_kernel;
12645 }
12646 
12647 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
12648 {
12649 	return kvm_rip_read(vcpu);
12650 }
12651 
12652 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
12653 {
12654 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
12655 }
12656 
12657 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
12658 {
12659 	return static_call(kvm_x86_interrupt_allowed)(vcpu, false);
12660 }
12661 
12662 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
12663 {
12664 	/* Can't read the RIP when guest state is protected, just return 0 */
12665 	if (vcpu->arch.guest_state_protected)
12666 		return 0;
12667 
12668 	if (is_64_bit_mode(vcpu))
12669 		return kvm_rip_read(vcpu);
12670 	return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
12671 		     kvm_rip_read(vcpu));
12672 }
12673 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
12674 
12675 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
12676 {
12677 	return kvm_get_linear_rip(vcpu) == linear_rip;
12678 }
12679 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
12680 
12681 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
12682 {
12683 	unsigned long rflags;
12684 
12685 	rflags = static_call(kvm_x86_get_rflags)(vcpu);
12686 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12687 		rflags &= ~X86_EFLAGS_TF;
12688 	return rflags;
12689 }
12690 EXPORT_SYMBOL_GPL(kvm_get_rflags);
12691 
12692 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
12693 {
12694 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
12695 	    kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
12696 		rflags |= X86_EFLAGS_TF;
12697 	static_call(kvm_x86_set_rflags)(vcpu, rflags);
12698 }
12699 
12700 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
12701 {
12702 	__kvm_set_rflags(vcpu, rflags);
12703 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12704 }
12705 EXPORT_SYMBOL_GPL(kvm_set_rflags);
12706 
12707 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
12708 {
12709 	BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
12710 
12711 	return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
12712 }
12713 
12714 static inline u32 kvm_async_pf_next_probe(u32 key)
12715 {
12716 	return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
12717 }
12718 
12719 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12720 {
12721 	u32 key = kvm_async_pf_hash_fn(gfn);
12722 
12723 	while (vcpu->arch.apf.gfns[key] != ~0)
12724 		key = kvm_async_pf_next_probe(key);
12725 
12726 	vcpu->arch.apf.gfns[key] = gfn;
12727 }
12728 
12729 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
12730 {
12731 	int i;
12732 	u32 key = kvm_async_pf_hash_fn(gfn);
12733 
12734 	for (i = 0; i < ASYNC_PF_PER_VCPU &&
12735 		     (vcpu->arch.apf.gfns[key] != gfn &&
12736 		      vcpu->arch.apf.gfns[key] != ~0); i++)
12737 		key = kvm_async_pf_next_probe(key);
12738 
12739 	return key;
12740 }
12741 
12742 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12743 {
12744 	return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
12745 }
12746 
12747 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12748 {
12749 	u32 i, j, k;
12750 
12751 	i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
12752 
12753 	if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
12754 		return;
12755 
12756 	while (true) {
12757 		vcpu->arch.apf.gfns[i] = ~0;
12758 		do {
12759 			j = kvm_async_pf_next_probe(j);
12760 			if (vcpu->arch.apf.gfns[j] == ~0)
12761 				return;
12762 			k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
12763 			/*
12764 			 * k lies cyclically in ]i,j]
12765 			 * |    i.k.j |
12766 			 * |....j i.k.| or  |.k..j i...|
12767 			 */
12768 		} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
12769 		vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
12770 		i = j;
12771 	}
12772 }
12773 
12774 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
12775 {
12776 	u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
12777 
12778 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
12779 				      sizeof(reason));
12780 }
12781 
12782 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
12783 {
12784 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
12785 
12786 	return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
12787 					     &token, offset, sizeof(token));
12788 }
12789 
12790 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
12791 {
12792 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
12793 	u32 val;
12794 
12795 	if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
12796 					 &val, offset, sizeof(val)))
12797 		return false;
12798 
12799 	return !val;
12800 }
12801 
12802 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
12803 {
12804 
12805 	if (!kvm_pv_async_pf_enabled(vcpu))
12806 		return false;
12807 
12808 	if (vcpu->arch.apf.send_user_only &&
12809 	    static_call(kvm_x86_get_cpl)(vcpu) == 0)
12810 		return false;
12811 
12812 	if (is_guest_mode(vcpu)) {
12813 		/*
12814 		 * L1 needs to opt into the special #PF vmexits that are
12815 		 * used to deliver async page faults.
12816 		 */
12817 		return vcpu->arch.apf.delivery_as_pf_vmexit;
12818 	} else {
12819 		/*
12820 		 * Play it safe in case the guest temporarily disables paging.
12821 		 * The real mode IDT in particular is unlikely to have a #PF
12822 		 * exception setup.
12823 		 */
12824 		return is_paging(vcpu);
12825 	}
12826 }
12827 
12828 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
12829 {
12830 	if (unlikely(!lapic_in_kernel(vcpu) ||
12831 		     kvm_event_needs_reinjection(vcpu) ||
12832 		     kvm_is_exception_pending(vcpu)))
12833 		return false;
12834 
12835 	if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
12836 		return false;
12837 
12838 	/*
12839 	 * If interrupts are off we cannot even use an artificial
12840 	 * halt state.
12841 	 */
12842 	return kvm_arch_interrupt_allowed(vcpu);
12843 }
12844 
12845 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
12846 				     struct kvm_async_pf *work)
12847 {
12848 	struct x86_exception fault;
12849 
12850 	trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
12851 	kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
12852 
12853 	if (kvm_can_deliver_async_pf(vcpu) &&
12854 	    !apf_put_user_notpresent(vcpu)) {
12855 		fault.vector = PF_VECTOR;
12856 		fault.error_code_valid = true;
12857 		fault.error_code = 0;
12858 		fault.nested_page_fault = false;
12859 		fault.address = work->arch.token;
12860 		fault.async_page_fault = true;
12861 		kvm_inject_page_fault(vcpu, &fault);
12862 		return true;
12863 	} else {
12864 		/*
12865 		 * It is not possible to deliver a paravirtualized asynchronous
12866 		 * page fault, but putting the guest in an artificial halt state
12867 		 * can be beneficial nevertheless: if an interrupt arrives, we
12868 		 * can deliver it timely and perhaps the guest will schedule
12869 		 * another process.  When the instruction that triggered a page
12870 		 * fault is retried, hopefully the page will be ready in the host.
12871 		 */
12872 		kvm_make_request(KVM_REQ_APF_HALT, vcpu);
12873 		return false;
12874 	}
12875 }
12876 
12877 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
12878 				 struct kvm_async_pf *work)
12879 {
12880 	struct kvm_lapic_irq irq = {
12881 		.delivery_mode = APIC_DM_FIXED,
12882 		.vector = vcpu->arch.apf.vec
12883 	};
12884 
12885 	if (work->wakeup_all)
12886 		work->arch.token = ~0; /* broadcast wakeup */
12887 	else
12888 		kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
12889 	trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
12890 
12891 	if ((work->wakeup_all || work->notpresent_injected) &&
12892 	    kvm_pv_async_pf_enabled(vcpu) &&
12893 	    !apf_put_user_ready(vcpu, work->arch.token)) {
12894 		vcpu->arch.apf.pageready_pending = true;
12895 		kvm_apic_set_irq(vcpu, &irq, NULL);
12896 	}
12897 
12898 	vcpu->arch.apf.halted = false;
12899 	vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
12900 }
12901 
12902 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
12903 {
12904 	kvm_make_request(KVM_REQ_APF_READY, vcpu);
12905 	if (!vcpu->arch.apf.pageready_pending)
12906 		kvm_vcpu_kick(vcpu);
12907 }
12908 
12909 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
12910 {
12911 	if (!kvm_pv_async_pf_enabled(vcpu))
12912 		return true;
12913 	else
12914 		return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
12915 }
12916 
12917 void kvm_arch_start_assignment(struct kvm *kvm)
12918 {
12919 	if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
12920 		static_call_cond(kvm_x86_pi_start_assignment)(kvm);
12921 }
12922 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
12923 
12924 void kvm_arch_end_assignment(struct kvm *kvm)
12925 {
12926 	atomic_dec(&kvm->arch.assigned_device_count);
12927 }
12928 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
12929 
12930 bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
12931 {
12932 	return arch_atomic_read(&kvm->arch.assigned_device_count);
12933 }
12934 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
12935 
12936 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
12937 {
12938 	atomic_inc(&kvm->arch.noncoherent_dma_count);
12939 }
12940 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
12941 
12942 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
12943 {
12944 	atomic_dec(&kvm->arch.noncoherent_dma_count);
12945 }
12946 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
12947 
12948 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
12949 {
12950 	return atomic_read(&kvm->arch.noncoherent_dma_count);
12951 }
12952 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
12953 
12954 bool kvm_arch_has_irq_bypass(void)
12955 {
12956 	return true;
12957 }
12958 
12959 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
12960 				      struct irq_bypass_producer *prod)
12961 {
12962 	struct kvm_kernel_irqfd *irqfd =
12963 		container_of(cons, struct kvm_kernel_irqfd, consumer);
12964 	int ret;
12965 
12966 	irqfd->producer = prod;
12967 	kvm_arch_start_assignment(irqfd->kvm);
12968 	ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm,
12969 					 prod->irq, irqfd->gsi, 1);
12970 
12971 	if (ret)
12972 		kvm_arch_end_assignment(irqfd->kvm);
12973 
12974 	return ret;
12975 }
12976 
12977 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
12978 				      struct irq_bypass_producer *prod)
12979 {
12980 	int ret;
12981 	struct kvm_kernel_irqfd *irqfd =
12982 		container_of(cons, struct kvm_kernel_irqfd, consumer);
12983 
12984 	WARN_ON(irqfd->producer != prod);
12985 	irqfd->producer = NULL;
12986 
12987 	/*
12988 	 * When producer of consumer is unregistered, we change back to
12989 	 * remapped mode, so we can re-use the current implementation
12990 	 * when the irq is masked/disabled or the consumer side (KVM
12991 	 * int this case doesn't want to receive the interrupts.
12992 	*/
12993 	ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm, prod->irq, irqfd->gsi, 0);
12994 	if (ret)
12995 		printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
12996 		       " fails: %d\n", irqfd->consumer.token, ret);
12997 
12998 	kvm_arch_end_assignment(irqfd->kvm);
12999 }
13000 
13001 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
13002 				   uint32_t guest_irq, bool set)
13003 {
13004 	return static_call(kvm_x86_pi_update_irte)(kvm, host_irq, guest_irq, set);
13005 }
13006 
13007 bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
13008 				  struct kvm_kernel_irq_routing_entry *new)
13009 {
13010 	if (new->type != KVM_IRQ_ROUTING_MSI)
13011 		return true;
13012 
13013 	return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
13014 }
13015 
13016 bool kvm_vector_hashing_enabled(void)
13017 {
13018 	return vector_hashing;
13019 }
13020 
13021 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13022 {
13023 	return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13024 }
13025 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
13026 
13027 
13028 int kvm_spec_ctrl_test_value(u64 value)
13029 {
13030 	/*
13031 	 * test that setting IA32_SPEC_CTRL to given value
13032 	 * is allowed by the host processor
13033 	 */
13034 
13035 	u64 saved_value;
13036 	unsigned long flags;
13037 	int ret = 0;
13038 
13039 	local_irq_save(flags);
13040 
13041 	if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
13042 		ret = 1;
13043 	else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
13044 		ret = 1;
13045 	else
13046 		wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
13047 
13048 	local_irq_restore(flags);
13049 
13050 	return ret;
13051 }
13052 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
13053 
13054 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
13055 {
13056 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
13057 	struct x86_exception fault;
13058 	u64 access = error_code &
13059 		(PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
13060 
13061 	if (!(error_code & PFERR_PRESENT_MASK) ||
13062 	    mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
13063 		/*
13064 		 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
13065 		 * tables probably do not match the TLB.  Just proceed
13066 		 * with the error code that the processor gave.
13067 		 */
13068 		fault.vector = PF_VECTOR;
13069 		fault.error_code_valid = true;
13070 		fault.error_code = error_code;
13071 		fault.nested_page_fault = false;
13072 		fault.address = gva;
13073 		fault.async_page_fault = false;
13074 	}
13075 	vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
13076 }
13077 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
13078 
13079 /*
13080  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
13081  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
13082  * indicates whether exit to userspace is needed.
13083  */
13084 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
13085 			      struct x86_exception *e)
13086 {
13087 	if (r == X86EMUL_PROPAGATE_FAULT) {
13088 		kvm_inject_emulated_page_fault(vcpu, e);
13089 		return 1;
13090 	}
13091 
13092 	/*
13093 	 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
13094 	 * while handling a VMX instruction KVM could've handled the request
13095 	 * correctly by exiting to userspace and performing I/O but there
13096 	 * doesn't seem to be a real use-case behind such requests, just return
13097 	 * KVM_EXIT_INTERNAL_ERROR for now.
13098 	 */
13099 	kvm_prepare_emulation_failure_exit(vcpu);
13100 
13101 	return 0;
13102 }
13103 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
13104 
13105 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
13106 {
13107 	bool pcid_enabled;
13108 	struct x86_exception e;
13109 	struct {
13110 		u64 pcid;
13111 		u64 gla;
13112 	} operand;
13113 	int r;
13114 
13115 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
13116 	if (r != X86EMUL_CONTINUE)
13117 		return kvm_handle_memory_failure(vcpu, r, &e);
13118 
13119 	if (operand.pcid >> 12 != 0) {
13120 		kvm_inject_gp(vcpu, 0);
13121 		return 1;
13122 	}
13123 
13124 	pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
13125 
13126 	switch (type) {
13127 	case INVPCID_TYPE_INDIV_ADDR:
13128 		if ((!pcid_enabled && (operand.pcid != 0)) ||
13129 		    is_noncanonical_address(operand.gla, vcpu)) {
13130 			kvm_inject_gp(vcpu, 0);
13131 			return 1;
13132 		}
13133 		kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
13134 		return kvm_skip_emulated_instruction(vcpu);
13135 
13136 	case INVPCID_TYPE_SINGLE_CTXT:
13137 		if (!pcid_enabled && (operand.pcid != 0)) {
13138 			kvm_inject_gp(vcpu, 0);
13139 			return 1;
13140 		}
13141 
13142 		kvm_invalidate_pcid(vcpu, operand.pcid);
13143 		return kvm_skip_emulated_instruction(vcpu);
13144 
13145 	case INVPCID_TYPE_ALL_NON_GLOBAL:
13146 		/*
13147 		 * Currently, KVM doesn't mark global entries in the shadow
13148 		 * page tables, so a non-global flush just degenerates to a
13149 		 * global flush. If needed, we could optimize this later by
13150 		 * keeping track of global entries in shadow page tables.
13151 		 */
13152 
13153 		fallthrough;
13154 	case INVPCID_TYPE_ALL_INCL_GLOBAL:
13155 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
13156 		return kvm_skip_emulated_instruction(vcpu);
13157 
13158 	default:
13159 		kvm_inject_gp(vcpu, 0);
13160 		return 1;
13161 	}
13162 }
13163 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
13164 
13165 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
13166 {
13167 	struct kvm_run *run = vcpu->run;
13168 	struct kvm_mmio_fragment *frag;
13169 	unsigned int len;
13170 
13171 	BUG_ON(!vcpu->mmio_needed);
13172 
13173 	/* Complete previous fragment */
13174 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
13175 	len = min(8u, frag->len);
13176 	if (!vcpu->mmio_is_write)
13177 		memcpy(frag->data, run->mmio.data, len);
13178 
13179 	if (frag->len <= 8) {
13180 		/* Switch to the next fragment. */
13181 		frag++;
13182 		vcpu->mmio_cur_fragment++;
13183 	} else {
13184 		/* Go forward to the next mmio piece. */
13185 		frag->data += len;
13186 		frag->gpa += len;
13187 		frag->len -= len;
13188 	}
13189 
13190 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
13191 		vcpu->mmio_needed = 0;
13192 
13193 		// VMG change, at this point, we're always done
13194 		// RIP has already been advanced
13195 		return 1;
13196 	}
13197 
13198 	// More MMIO is needed
13199 	run->mmio.phys_addr = frag->gpa;
13200 	run->mmio.len = min(8u, frag->len);
13201 	run->mmio.is_write = vcpu->mmio_is_write;
13202 	if (run->mmio.is_write)
13203 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
13204 	run->exit_reason = KVM_EXIT_MMIO;
13205 
13206 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13207 
13208 	return 0;
13209 }
13210 
13211 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13212 			  void *data)
13213 {
13214 	int handled;
13215 	struct kvm_mmio_fragment *frag;
13216 
13217 	if (!data)
13218 		return -EINVAL;
13219 
13220 	handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13221 	if (handled == bytes)
13222 		return 1;
13223 
13224 	bytes -= handled;
13225 	gpa += handled;
13226 	data += handled;
13227 
13228 	/*TODO: Check if need to increment number of frags */
13229 	frag = vcpu->mmio_fragments;
13230 	vcpu->mmio_nr_fragments = 1;
13231 	frag->len = bytes;
13232 	frag->gpa = gpa;
13233 	frag->data = data;
13234 
13235 	vcpu->mmio_needed = 1;
13236 	vcpu->mmio_cur_fragment = 0;
13237 
13238 	vcpu->run->mmio.phys_addr = gpa;
13239 	vcpu->run->mmio.len = min(8u, frag->len);
13240 	vcpu->run->mmio.is_write = 1;
13241 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
13242 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
13243 
13244 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13245 
13246 	return 0;
13247 }
13248 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
13249 
13250 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13251 			 void *data)
13252 {
13253 	int handled;
13254 	struct kvm_mmio_fragment *frag;
13255 
13256 	if (!data)
13257 		return -EINVAL;
13258 
13259 	handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13260 	if (handled == bytes)
13261 		return 1;
13262 
13263 	bytes -= handled;
13264 	gpa += handled;
13265 	data += handled;
13266 
13267 	/*TODO: Check if need to increment number of frags */
13268 	frag = vcpu->mmio_fragments;
13269 	vcpu->mmio_nr_fragments = 1;
13270 	frag->len = bytes;
13271 	frag->gpa = gpa;
13272 	frag->data = data;
13273 
13274 	vcpu->mmio_needed = 1;
13275 	vcpu->mmio_cur_fragment = 0;
13276 
13277 	vcpu->run->mmio.phys_addr = gpa;
13278 	vcpu->run->mmio.len = min(8u, frag->len);
13279 	vcpu->run->mmio.is_write = 0;
13280 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
13281 
13282 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13283 
13284 	return 0;
13285 }
13286 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
13287 
13288 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
13289 {
13290 	vcpu->arch.sev_pio_count -= count;
13291 	vcpu->arch.sev_pio_data += count * size;
13292 }
13293 
13294 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13295 			   unsigned int port);
13296 
13297 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
13298 {
13299 	int size = vcpu->arch.pio.size;
13300 	int port = vcpu->arch.pio.port;
13301 
13302 	vcpu->arch.pio.count = 0;
13303 	if (vcpu->arch.sev_pio_count)
13304 		return kvm_sev_es_outs(vcpu, size, port);
13305 	return 1;
13306 }
13307 
13308 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13309 			   unsigned int port)
13310 {
13311 	for (;;) {
13312 		unsigned int count =
13313 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13314 		int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
13315 
13316 		/* memcpy done already by emulator_pio_out.  */
13317 		advance_sev_es_emulated_pio(vcpu, count, size);
13318 		if (!ret)
13319 			break;
13320 
13321 		/* Emulation done by the kernel.  */
13322 		if (!vcpu->arch.sev_pio_count)
13323 			return 1;
13324 	}
13325 
13326 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
13327 	return 0;
13328 }
13329 
13330 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13331 			  unsigned int port);
13332 
13333 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
13334 {
13335 	unsigned count = vcpu->arch.pio.count;
13336 	int size = vcpu->arch.pio.size;
13337 	int port = vcpu->arch.pio.port;
13338 
13339 	complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
13340 	advance_sev_es_emulated_pio(vcpu, count, size);
13341 	if (vcpu->arch.sev_pio_count)
13342 		return kvm_sev_es_ins(vcpu, size, port);
13343 	return 1;
13344 }
13345 
13346 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13347 			  unsigned int port)
13348 {
13349 	for (;;) {
13350 		unsigned int count =
13351 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13352 		if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
13353 			break;
13354 
13355 		/* Emulation done by the kernel.  */
13356 		advance_sev_es_emulated_pio(vcpu, count, size);
13357 		if (!vcpu->arch.sev_pio_count)
13358 			return 1;
13359 	}
13360 
13361 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
13362 	return 0;
13363 }
13364 
13365 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
13366 			 unsigned int port, void *data,  unsigned int count,
13367 			 int in)
13368 {
13369 	vcpu->arch.sev_pio_data = data;
13370 	vcpu->arch.sev_pio_count = count;
13371 	return in ? kvm_sev_es_ins(vcpu, size, port)
13372 		  : kvm_sev_es_outs(vcpu, size, port);
13373 }
13374 EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
13375 
13376 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
13377 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
13378 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
13379 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
13380 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
13381 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
13382 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
13383 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
13384 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
13385 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
13386 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
13387 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
13388 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
13389 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
13390 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
13391 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
13392 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
13393 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
13394 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
13395 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
13396 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
13397 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
13398 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
13399 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
13400 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
13401 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
13402 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
13403 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
13404 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
13405 
13406 static int __init kvm_x86_init(void)
13407 {
13408 	kvm_mmu_x86_module_init();
13409 	return 0;
13410 }
13411 module_init(kvm_x86_init);
13412 
13413 static void __exit kvm_x86_exit(void)
13414 {
13415 	/*
13416 	 * If module_init() is implemented, module_exit() must also be
13417 	 * implemented to allow module unload.
13418 	 */
13419 }
13420 module_exit(kvm_x86_exit);
13421