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