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