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