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