xref: /linux/arch/x86/kvm/x86.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * derived from drivers/kvm/kvm_main.c
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright (C) 2008 Qumranet, Inc.
9  * Copyright IBM Corporation, 2008
10  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11  *
12  * Authors:
13  *   Avi Kivity   <avi@qumranet.com>
14  *   Yaniv Kamay  <yaniv@qumranet.com>
15  *   Amit Shah    <amit.shah@qumranet.com>
16  *   Ben-Ami Yassour <benami@il.ibm.com>
17  */
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19 
20 #include <linux/kvm_host.h>
21 #include "irq.h"
22 #include "ioapic.h"
23 #include "mmu.h"
24 #include "i8254.h"
25 #include "tss.h"
26 #include "regs.h"
27 #include "kvm_emulate.h"
28 #include "mmu/page_track.h"
29 #include "x86.h"
30 #include "cpuid.h"
31 #include "pmu.h"
32 #include "hyperv.h"
33 #include "lapic.h"
34 #include "xen.h"
35 #include "smm.h"
36 
37 #include <linux/clocksource.h>
38 #include <linux/interrupt.h>
39 #include <linux/kvm.h>
40 #include <linux/fs.h>
41 #include <linux/vmalloc.h>
42 #include <linux/export.h>
43 #include <linux/moduleparam.h>
44 #include <linux/mman.h>
45 #include <linux/highmem.h>
46 #include <linux/iommu.h>
47 #include <linux/cpufreq.h>
48 #include <linux/user-return-notifier.h>
49 #include <linux/srcu.h>
50 #include <linux/slab.h>
51 #include <linux/perf_event.h>
52 #include <linux/uaccess.h>
53 #include <linux/hash.h>
54 #include <linux/pci.h>
55 #include <linux/timekeeper_internal.h>
56 #include <linux/pvclock_gtod.h>
57 #include <linux/kvm_irqfd.h>
58 #include <linux/irqbypass.h>
59 #include <linux/sched/stat.h>
60 #include <linux/sched/isolation.h>
61 #include <linux/mem_encrypt.h>
62 #include <linux/suspend.h>
63 #include <linux/smp.h>
64 
65 #include <trace/events/ipi.h>
66 #include <trace/events/kvm.h>
67 
68 #include <asm/debugreg.h>
69 #include <asm/msr.h>
70 #include <asm/desc.h>
71 #include <asm/mce.h>
72 #include <asm/pkru.h>
73 #include <linux/kernel_stat.h>
74 #include <asm/fpu/api.h>
75 #include <asm/fpu/xcr.h>
76 #include <asm/fpu/xstate.h>
77 #include <asm/pvclock.h>
78 #include <asm/div64.h>
79 #include <asm/irq_remapping.h>
80 #include <asm/mshyperv.h>
81 #include <asm/hypervisor.h>
82 #include <asm/tlbflush.h>
83 #include <asm/emulate_prefix.h>
84 #include <asm/sgx.h>
85 #include <asm/virt.h>
86 
87 #include <clocksource/hyperv_timer.h>
88 
89 #define CREATE_TRACE_POINTS
90 #include "trace.h"
91 
92 /*
93  * Note, kvm_caps fields should *never* have default values, all fields must be
94  * recomputed from scratch during vendor module load, e.g. to account for a
95  * vendor module being reloaded with different module parameters.
96  */
97 struct kvm_caps kvm_caps __read_mostly;
98 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_caps);
99 
100 struct kvm_host_values kvm_host __read_mostly;
101 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_host);
102 
103 #define  ERR_PTR_USR(e)  ((void __user *)ERR_PTR(e))
104 
105 #define emul_to_vcpu(ctxt) \
106 	((struct kvm_vcpu *)(ctxt)->vcpu)
107 
108 /*
109  * KVM previously used a u32 field in kvm_run to indicate the hypercall was
110  * initiated from long mode. KVM now sets bit 0 to indicate long mode, but the
111  * remaining 31 lower bits must be 0 to preserve ABI.
112  */
113 #define KVM_EXIT_HYPERCALL_MBZ		GENMASK_ULL(31, 1)
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_GUESTDBG_VALID_MASK \
119 	(KVM_GUESTDBG_ENABLE | \
120 	KVM_GUESTDBG_SINGLESTEP | \
121 	KVM_GUESTDBG_USE_HW_BP | \
122 	KVM_GUESTDBG_USE_SW_BP | \
123 	KVM_GUESTDBG_INJECT_BP | \
124 	KVM_GUESTDBG_INJECT_DB | \
125 	KVM_GUESTDBG_BLOCKIRQ)
126 
127 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS		| \
128 				    KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK	| \
129 				    KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST	| \
130 				    KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST)
131 
132 #define KVM_CLOCK_VALID_FLAGS						\
133 	(KVM_CLOCK_TSC_STABLE | KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC)
134 
135 #define KVM_X86_VALID_QUIRKS			\
136 	(KVM_X86_QUIRK_LINT0_REENABLED |	\
137 	 KVM_X86_QUIRK_CD_NW_CLEARED |		\
138 	 KVM_X86_QUIRK_LAPIC_MMIO_HOLE |	\
139 	 KVM_X86_QUIRK_OUT_7E_INC_RIP |		\
140 	 KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT |	\
141 	 KVM_X86_QUIRK_FIX_HYPERCALL_INSN |	\
142 	 KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS |	\
143 	 KVM_X86_QUIRK_SLOT_ZAP_ALL |		\
144 	 KVM_X86_QUIRK_STUFF_FEATURE_MSRS |	\
145 	 KVM_X86_QUIRK_IGNORE_GUEST_PAT |	\
146 	 KVM_X86_QUIRK_VMCS12_ALLOW_FREEZE_IN_SMM |	\
147 	 KVM_X86_QUIRK_NESTED_SVM_SHARED_PAT)
148 
149 #define KVM_X86_CONDITIONAL_QUIRKS		\
150 	(KVM_X86_QUIRK_CD_NW_CLEARED |		\
151 	 KVM_X86_QUIRK_IGNORE_GUEST_PAT)
152 
153 #define KVM_BUS_LOCK_DETECTION_VALID_MODE	(KVM_BUS_LOCK_DETECTION_OFF | \
154 						 KVM_BUS_LOCK_DETECTION_EXIT)
155 
156 #define KVM_X86_NOTIFY_VMEXIT_VALID_BITS	(KVM_X86_NOTIFY_VMEXIT_ENABLED | \
157 						 KVM_X86_NOTIFY_VMEXIT_USER)
158 
159 static void process_nmi(struct kvm_vcpu *vcpu);
160 static void store_regs(struct kvm_vcpu *vcpu);
161 static int sync_regs(struct kvm_vcpu *vcpu);
162 
163 static DEFINE_MUTEX(vendor_module_lock);
164 
165 struct kvm_x86_ops kvm_x86_ops __read_mostly;
166 struct kvm_x86_nested_ops kvm_nested_ops __read_mostly;
167 
168 #define KVM_X86_OP(func)					     \
169 	DEFINE_STATIC_CALL_NULL(kvm_x86_##func,			     \
170 				*(((struct kvm_x86_ops *)0)->func));
171 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
172 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
173 #include <asm/kvm-x86-ops.h>
174 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
175 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
176 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cpl);
177 
178 #define KVM_X86_NESTED_OP(func)							\
179 	DEFINE_STATIC_CALL_NULL(kvm_x86_nested_##func,				\
180 				*(((struct kvm_x86_nested_ops *)0)->func));
181 #define KVM_X86_NESTED_OP_OPTIONAL KVM_X86_NESTED_OP
182 #define KVM_X86_NESTED_OP_OPTIONAL_RET0 KVM_X86_NESTED_OP
183 #include <asm/kvm-x86-nested-ops.h>
184 
185 unsigned int min_timer_period_us = 200;
186 module_param(min_timer_period_us, uint, 0644);
187 
188 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
189 static u32 __read_mostly tsc_tolerance_ppm = 250;
190 module_param(tsc_tolerance_ppm, uint, 0644);
191 
192 bool __read_mostly enable_vmware_backdoor = false;
193 module_param(enable_vmware_backdoor, bool, 0444);
194 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_vmware_backdoor);
195 
196 /*
197  * Flags to manipulate forced emulation behavior (any non-zero value will
198  * enable forced emulation).
199  */
200 #define KVM_FEP_CLEAR_RFLAGS_RF	BIT(1)
201 static int __read_mostly force_emulation_prefix;
202 module_param(force_emulation_prefix, int, 0644);
203 
204 int __read_mostly pi_inject_timer = -1;
205 module_param(pi_inject_timer, bint, 0644);
206 
207 /* Enable/disable SMT_RSB bug mitigation */
208 static bool __read_mostly mitigate_smt_rsb;
209 module_param(mitigate_smt_rsb, bool, 0444);
210 
211 #define KVM_SUPPORTED_XCR0     (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
212 				| XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
213 				| XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
214 				| XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
215 
216 #define XFEATURE_MASK_CET_ALL	(XFEATURE_MASK_CET_USER | XFEATURE_MASK_CET_KERNEL)
217 /*
218  * Note, KVM supports exposing PT to the guest, but does not support context
219  * switching PT via XSTATE (KVM's PT virtualization relies on perf; swapping
220  * PT via guest XSTATE would clobber perf state), i.e. KVM doesn't support
221  * IA32_XSS[bit 8] (guests can/must use RDMSR/WRMSR to save/restore PT MSRs).
222  */
223 #define KVM_SUPPORTED_XSS	(XFEATURE_MASK_CET_ALL)
224 
225 bool __read_mostly allow_smaller_maxphyaddr = 0;
226 EXPORT_SYMBOL_FOR_KVM_INTERNAL(allow_smaller_maxphyaddr);
227 
228 bool __read_mostly enable_apicv = true;
229 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_apicv);
230 
231 bool __read_mostly enable_ipiv = true;
232 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_ipiv);
233 
234 bool __read_mostly enable_device_posted_irqs = true;
235 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_device_posted_irqs);
236 
237 const struct kvm_stats_desc kvm_vm_stats_desc[] = {
238 	KVM_GENERIC_VM_STATS(),
239 	STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
240 	STATS_DESC_COUNTER(VM, mmu_pte_write),
241 	STATS_DESC_COUNTER(VM, mmu_pde_zapped),
242 	STATS_DESC_COUNTER(VM, mmu_flooded),
243 	STATS_DESC_COUNTER(VM, mmu_recycled),
244 	STATS_DESC_COUNTER(VM, mmu_cache_miss),
245 	STATS_DESC_ICOUNTER(VM, mmu_unsync),
246 	STATS_DESC_ICOUNTER(VM, mmu_shadow_pages),
247 	STATS_DESC_ICOUNTER(VM, pages_4k),
248 	STATS_DESC_ICOUNTER(VM, pages_2m),
249 	STATS_DESC_ICOUNTER(VM, pages_1g),
250 	STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
251 	STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
252 	STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
253 };
254 
255 const struct kvm_stats_header kvm_vm_stats_header = {
256 	.name_size = KVM_STATS_NAME_SIZE,
257 	.num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
258 	.id_offset = sizeof(struct kvm_stats_header),
259 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
260 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
261 		       sizeof(kvm_vm_stats_desc),
262 };
263 
264 const struct kvm_stats_desc kvm_vcpu_stats_desc[] = {
265 	KVM_GENERIC_VCPU_STATS(),
266 	STATS_DESC_COUNTER(VCPU, pf_taken),
267 	STATS_DESC_COUNTER(VCPU, pf_fixed),
268 	STATS_DESC_COUNTER(VCPU, pf_emulate),
269 	STATS_DESC_COUNTER(VCPU, pf_spurious),
270 	STATS_DESC_COUNTER(VCPU, pf_fast),
271 	STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
272 	STATS_DESC_COUNTER(VCPU, pf_guest),
273 	STATS_DESC_COUNTER(VCPU, tlb_flush),
274 	STATS_DESC_COUNTER(VCPU, invlpg),
275 	STATS_DESC_COUNTER(VCPU, exits),
276 	STATS_DESC_COUNTER(VCPU, io_exits),
277 	STATS_DESC_COUNTER(VCPU, mmio_exits),
278 	STATS_DESC_COUNTER(VCPU, signal_exits),
279 	STATS_DESC_COUNTER(VCPU, irq_window_exits),
280 	STATS_DESC_COUNTER(VCPU, nmi_window_exits),
281 	STATS_DESC_COUNTER(VCPU, l1d_flush),
282 	STATS_DESC_COUNTER(VCPU, halt_exits),
283 	STATS_DESC_COUNTER(VCPU, request_irq_exits),
284 	STATS_DESC_COUNTER(VCPU, irq_exits),
285 	STATS_DESC_COUNTER(VCPU, host_state_reload),
286 	STATS_DESC_COUNTER(VCPU, fpu_reload),
287 	STATS_DESC_COUNTER(VCPU, insn_emulation),
288 	STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
289 	STATS_DESC_COUNTER(VCPU, hypercalls),
290 	STATS_DESC_COUNTER(VCPU, irq_injections),
291 	STATS_DESC_COUNTER(VCPU, nmi_injections),
292 	STATS_DESC_COUNTER(VCPU, req_event),
293 	STATS_DESC_COUNTER(VCPU, nested_run),
294 	STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
295 	STATS_DESC_COUNTER(VCPU, directed_yield_successful),
296 	STATS_DESC_COUNTER(VCPU, preemption_reported),
297 	STATS_DESC_COUNTER(VCPU, preemption_other),
298 	STATS_DESC_IBOOLEAN(VCPU, guest_mode),
299 	STATS_DESC_COUNTER(VCPU, notify_window_exits),
300 };
301 
302 const struct kvm_stats_header kvm_vcpu_stats_header = {
303 	.name_size = KVM_STATS_NAME_SIZE,
304 	.num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
305 	.id_offset = sizeof(struct kvm_stats_header),
306 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
307 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
308 		       sizeof(kvm_vcpu_stats_desc),
309 };
310 
311 static struct kmem_cache *x86_emulator_cache;
312 
313 static struct kmem_cache *kvm_alloc_emulator_cache(void)
314 {
315 	unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
316 	unsigned int size = sizeof(struct x86_emulate_ctxt);
317 
318 	return kmem_cache_create_usercopy("x86_emulator", size,
319 					  __alignof__(struct x86_emulate_ctxt),
320 					  SLAB_ACCOUNT, useroffset,
321 					  size - useroffset, NULL);
322 }
323 
324 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
325 
326 /*
327  * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
328  *
329  * Hardware virtualization extension instructions may fault if a reboot turns
330  * off virtualization while processes are running.  Usually after catching the
331  * fault we just panic; during reboot instead the instruction is ignored.
332  */
333 noinstr void kvm_spurious_fault(void)
334 {
335 	/* Fault while not rebooting.  We want the trace. */
336 	BUG_ON(!virt_rebooting);
337 }
338 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_spurious_fault);
339 
340 #define EXCPT_BENIGN		0
341 #define EXCPT_CONTRIBUTORY	1
342 #define EXCPT_PF		2
343 
344 static int exception_class(int vector)
345 {
346 	switch (vector) {
347 	case PF_VECTOR:
348 		return EXCPT_PF;
349 	case DE_VECTOR:
350 	case TS_VECTOR:
351 	case NP_VECTOR:
352 	case SS_VECTOR:
353 	case GP_VECTOR:
354 		return EXCPT_CONTRIBUTORY;
355 	default:
356 		break;
357 	}
358 	return EXCPT_BENIGN;
359 }
360 
361 #define EXCPT_FAULT		0
362 #define EXCPT_TRAP		1
363 #define EXCPT_ABORT		2
364 #define EXCPT_INTERRUPT		3
365 #define EXCPT_DB		4
366 
367 static int exception_type(int vector)
368 {
369 	unsigned int mask;
370 
371 	if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
372 		return EXCPT_INTERRUPT;
373 
374 	mask = 1 << vector;
375 
376 	/*
377 	 * #DBs can be trap-like or fault-like, the caller must check other CPU
378 	 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
379 	 */
380 	if (mask & (1 << DB_VECTOR))
381 		return EXCPT_DB;
382 
383 	if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
384 		return EXCPT_TRAP;
385 
386 	if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
387 		return EXCPT_ABORT;
388 
389 	/* Reserved exceptions will result in fault */
390 	return EXCPT_FAULT;
391 }
392 
393 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
394 				   struct kvm_queued_exception *ex)
395 {
396 	if (!ex->has_payload)
397 		return;
398 
399 	switch (ex->vector) {
400 	case DB_VECTOR:
401 		/*
402 		 * "Certain debug exceptions may clear bit 0-3.  The
403 		 * remaining contents of the DR6 register are never
404 		 * cleared by the processor".
405 		 */
406 		vcpu->arch.dr6 &= ~DR_TRAP_BITS;
407 		/*
408 		 * In order to reflect the #DB exception payload in guest
409 		 * dr6, three components need to be considered: active low
410 		 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
411 		 * DR6_BS and DR6_BT)
412 		 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
413 		 * In the target guest dr6:
414 		 * FIXED_1 bits should always be set.
415 		 * Active low bits should be cleared if 1-setting in payload.
416 		 * Active high bits should be set if 1-setting in payload.
417 		 *
418 		 * Note, the payload is compatible with the pending debug
419 		 * exceptions/exit qualification under VMX, that active_low bits
420 		 * are active high in payload.
421 		 * So they need to be flipped for DR6.
422 		 */
423 		vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
424 		vcpu->arch.dr6 |= ex->payload;
425 		vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
426 
427 		/*
428 		 * The #DB payload is defined as compatible with the 'pending
429 		 * debug exceptions' field under VMX, not DR6. While bit 12 is
430 		 * defined in the 'pending debug exceptions' field (enabled
431 		 * breakpoint), it is reserved and must be zero in DR6.
432 		 */
433 		vcpu->arch.dr6 &= ~BIT(12);
434 		break;
435 	case PF_VECTOR:
436 		vcpu->arch.cr2 = ex->payload;
437 		break;
438 	}
439 
440 	ex->has_payload = false;
441 	ex->payload = 0;
442 }
443 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_deliver_exception_payload);
444 
445 static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
446 				       bool has_error_code, u32 error_code,
447 				       bool has_payload, unsigned long payload)
448 {
449 	struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
450 
451 	ex->vector = vector;
452 	ex->injected = false;
453 	ex->pending = true;
454 	ex->has_error_code = has_error_code;
455 	ex->error_code = error_code;
456 	ex->has_payload = has_payload;
457 	ex->payload = payload;
458 }
459 
460 static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
461 				   bool has_error, u32 error_code,
462 				   bool has_payload, unsigned long payload)
463 {
464 	u32 prev_nr;
465 	int class1, class2;
466 
467 	kvm_make_request(KVM_REQ_EVENT, vcpu);
468 
469 	/*
470 	 * If the exception is destined for L2, morph it to a VM-Exit if L1
471 	 * wants to intercept the exception.
472 	 */
473 	if (is_guest_mode(vcpu) &&
474 	    kvm_nested_call(is_exception_vmexit)(vcpu, nr, error_code)) {
475 		kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
476 					   has_payload, payload);
477 		return;
478 	}
479 
480 	if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
481 	queue:
482 		vcpu->arch.exception.pending = true;
483 		vcpu->arch.exception.injected = false;
484 
485 		vcpu->arch.exception.has_error_code = has_error;
486 		vcpu->arch.exception.vector = nr;
487 		vcpu->arch.exception.error_code = error_code;
488 		vcpu->arch.exception.has_payload = has_payload;
489 		vcpu->arch.exception.payload = payload;
490 		return;
491 	}
492 
493 	/* to check exception */
494 	prev_nr = vcpu->arch.exception.vector;
495 	if (prev_nr == DF_VECTOR) {
496 		/* triple fault -> shutdown */
497 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
498 		return;
499 	}
500 	class1 = exception_class(prev_nr);
501 	class2 = exception_class(nr);
502 	if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
503 	    (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
504 		/*
505 		 * Synthesize #DF.  Clear the previously injected or pending
506 		 * exception so as not to incorrectly trigger shutdown.
507 		 */
508 		vcpu->arch.exception.injected = false;
509 		vcpu->arch.exception.pending = false;
510 
511 		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
512 	} else {
513 		/* replace previous exception with a new one in a hope
514 		   that instruction re-execution will regenerate lost
515 		   exception */
516 		goto queue;
517 	}
518 }
519 
520 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
521 {
522 	kvm_multiple_exception(vcpu, nr, false, 0, false, 0);
523 }
524 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception);
525 
526 
527 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
528 			   unsigned long payload)
529 {
530 	kvm_multiple_exception(vcpu, nr, false, 0, true, payload);
531 }
532 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_p);
533 
534 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
535 				    u32 error_code, unsigned long payload)
536 {
537 	kvm_multiple_exception(vcpu, nr, true, error_code, true, payload);
538 }
539 
540 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
541 			   bool has_error_code, u32 error_code)
542 {
543 
544 	/*
545 	 * On VM-Entry, an exception can be pending if and only if event
546 	 * injection was blocked by nested_run_pending.  In that case, however,
547 	 * vcpu_enter_guest() requests an immediate exit, and the guest
548 	 * shouldn't proceed far enough to need reinjection.
549 	 */
550 	WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
551 
552 	/*
553 	 * Do not check for interception when injecting an event for L2, as the
554 	 * exception was checked for intercept when it was original queued, and
555 	 * re-checking is incorrect if _L1_ injected the exception, in which
556 	 * case it's exempt from interception.
557 	 */
558 	kvm_make_request(KVM_REQ_EVENT, vcpu);
559 
560 	vcpu->arch.exception.injected = true;
561 	vcpu->arch.exception.has_error_code = has_error_code;
562 	vcpu->arch.exception.vector = nr;
563 	vcpu->arch.exception.error_code = error_code;
564 	vcpu->arch.exception.has_payload = false;
565 	vcpu->arch.exception.payload = 0;
566 }
567 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_requeue_exception);
568 
569 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
570 {
571 	if (err)
572 		kvm_inject_gp(vcpu, 0);
573 	else
574 		return kvm_skip_emulated_instruction(vcpu);
575 
576 	return 1;
577 }
578 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_complete_insn_gp);
579 
580 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault,
581 			   bool from_hardware)
582 {
583 	++vcpu->stat.pf_guest;
584 
585 	/*
586 	 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
587 	 * whether or not L1 wants to intercept "regular" #PF.
588 	 */
589 	if (is_guest_mode(vcpu) && fault->async_page_fault)
590 		kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
591 					   true, fault->error_code,
592 					   true, fault->address);
593 	else
594 		kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
595 					fault->address);
596 }
597 
598 void __kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
599 				      struct x86_exception *fault,
600 				      bool from_hardware)
601 {
602 	struct kvm_pagewalk *fault_walk;
603 
604 	WARN_ON_ONCE(fault->vector != PF_VECTOR);
605 
606 	fault_walk = fault->nested_page_fault ? &vcpu->arch.ngpa_walk :
607 						&vcpu->arch.gva_walk;
608 
609 	/*
610 	 * Invalidate the TLB entry for the faulting address, if it exists,
611 	 * else the access will fault indefinitely (and to emulate hardware).
612 	 */
613 	if ((fault->error_code & PFERR_PRESENT_MASK) &&
614 	    !(fault->error_code & PFERR_RSVD_MASK))
615 		kvm_mmu_invalidate_addr(vcpu, fault_walk, fault->address,
616 					KVM_MMU_ROOT_CURRENT);
617 
618 	fault_walk->inject_page_fault(vcpu, fault, from_hardware);
619 }
620 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_inject_emulated_page_fault);
621 
622 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
623 {
624 	atomic_inc(&vcpu->arch.nmi_queued);
625 	kvm_make_request(KVM_REQ_NMI, vcpu);
626 }
627 
628 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
629 {
630 	kvm_multiple_exception(vcpu, nr, true, error_code, false, 0);
631 }
632 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_e);
633 
634 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
635 {
636 	if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
637 		return true;
638 
639 	kvm_queue_exception(vcpu, UD_VECTOR);
640 	return false;
641 }
642 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_require_dr);
643 
644 static void kvm_load_xfeatures(struct kvm_vcpu *vcpu, bool load_guest)
645 {
646 	if (vcpu->arch.guest_state_protected)
647 		return;
648 
649 	if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE))
650 		return;
651 
652 	if (vcpu->arch.xcr0 != kvm_host.xcr0)
653 		xsetbv(XCR_XFEATURE_ENABLED_MASK,
654 		       load_guest ? vcpu->arch.xcr0 : kvm_host.xcr0);
655 
656 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
657 	    vcpu->arch.ia32_xss != kvm_host.xss)
658 		wrmsrq(MSR_IA32_XSS, load_guest ? vcpu->arch.ia32_xss : kvm_host.xss);
659 }
660 
661 static void kvm_load_guest_pkru(struct kvm_vcpu *vcpu)
662 {
663 	if (vcpu->arch.guest_state_protected)
664 		return;
665 
666 	if (cpu_feature_enabled(X86_FEATURE_PKU) &&
667 	    vcpu->arch.pkru != vcpu->arch.host_pkru &&
668 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
669 	     kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
670 		wrpkru(vcpu->arch.pkru);
671 }
672 
673 static void kvm_load_host_pkru(struct kvm_vcpu *vcpu)
674 {
675 	if (vcpu->arch.guest_state_protected)
676 		return;
677 
678 	if (cpu_feature_enabled(X86_FEATURE_PKU) &&
679 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
680 	     kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
681 		vcpu->arch.pkru = rdpkru();
682 		if (vcpu->arch.pkru != vcpu->arch.host_pkru)
683 			wrpkru(vcpu->arch.host_pkru);
684 	}
685 }
686 
687 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
688 {
689 	u64 xcr0 = xcr;
690 	u64 old_xcr0 = vcpu->arch.xcr0;
691 	u64 valid_bits;
692 
693 	/* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
694 	if (index != XCR_XFEATURE_ENABLED_MASK)
695 		return 1;
696 	if (!(xcr0 & XFEATURE_MASK_FP))
697 		return 1;
698 	if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
699 		return 1;
700 
701 	/*
702 	 * Do not allow the guest to set bits that we do not support
703 	 * saving.  However, xcr0 bit 0 is always set, even if the
704 	 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
705 	 */
706 	valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
707 	if (xcr0 & ~valid_bits)
708 		return 1;
709 
710 	if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
711 	    (!(xcr0 & XFEATURE_MASK_BNDCSR)))
712 		return 1;
713 
714 	if (xcr0 & XFEATURE_MASK_AVX512) {
715 		if (!(xcr0 & XFEATURE_MASK_YMM))
716 			return 1;
717 		if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
718 			return 1;
719 	}
720 
721 	if ((xcr0 & XFEATURE_MASK_XTILE) &&
722 	    ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
723 		return 1;
724 
725 	vcpu->arch.xcr0 = xcr0;
726 
727 	if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
728 		vcpu->arch.cpuid_dynamic_bits_dirty = true;
729 	return 0;
730 }
731 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_set_xcr);
732 
733 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
734 {
735 	/* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
736 	if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
737 	    __kvm_set_xcr(vcpu, kvm_ecx_read(vcpu), kvm_read_edx_eax(vcpu))) {
738 		kvm_inject_gp(vcpu, 0);
739 		return 1;
740 	}
741 
742 	return kvm_skip_emulated_instruction(vcpu);
743 }
744 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_xsetbv);
745 
746 void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
747 {
748 	struct kvm_mmu *mmu = vcpu->arch.mmu;
749 	unsigned long roots_to_free = 0;
750 	int i;
751 
752 	/*
753 	 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
754 	 * this is reachable when running EPT=1 and unrestricted_guest=0,  and
755 	 * also via the emulator.  KVM's TDP page tables are not in the scope of
756 	 * the invalidation, but the guest's TLB entries need to be flushed as
757 	 * the CPU may have cached entries in its TLB for the target PCID.
758 	 */
759 	if (unlikely(tdp_enabled)) {
760 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
761 		return;
762 	}
763 
764 	/*
765 	 * If neither the current CR3 nor any of the prev_roots use the given
766 	 * PCID, then nothing needs to be done here because a resync will
767 	 * happen anyway before switching to any other CR3.
768 	 */
769 	if (kvm_get_active_pcid(vcpu) == pcid) {
770 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
771 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
772 	}
773 
774 	/*
775 	 * If PCID is disabled, there is no need to free prev_roots even if the
776 	 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
777 	 * with PCIDE=0.
778 	 */
779 	if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
780 		return;
781 
782 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
783 		if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
784 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
785 
786 	kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
787 }
788 
789 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
790 {
791 	u32 pmc = kvm_ecx_read(vcpu);
792 	u64 data;
793 
794 	if (kvm_pmu_rdpmc(vcpu, pmc, &data)) {
795 		kvm_inject_gp(vcpu, 0);
796 		return 1;
797 	}
798 
799 	kvm_eax_write(vcpu, data);
800 	kvm_edx_write(vcpu, data >> 32);
801 	return kvm_skip_emulated_instruction(vcpu);
802 }
803 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdpmc);
804 
805 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
806 {
807 	return kvm_skip_emulated_instruction(vcpu);
808 }
809 
810 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
811 {
812 	/* Treat an INVD instruction as a NOP and just skip it. */
813 	return kvm_emulate_as_nop(vcpu);
814 }
815 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_invd);
816 
817 fastpath_t handle_fastpath_invd(struct kvm_vcpu *vcpu)
818 {
819 	if (!kvm_pmu_is_fastpath_emulation_allowed(vcpu))
820 		return EXIT_FASTPATH_NONE;
821 
822 	if (!kvm_emulate_invd(vcpu))
823 		return EXIT_FASTPATH_EXIT_USERSPACE;
824 
825 	return EXIT_FASTPATH_REENTER_GUEST;
826 }
827 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_invd);
828 
829 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
830 {
831 	kvm_queue_exception(vcpu, UD_VECTOR);
832 	return 1;
833 }
834 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invalid_op);
835 
836 
837 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
838 {
839 	bool enabled;
840 
841 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS))
842 		goto emulate_as_nop;
843 
844 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
845 		enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_MWAIT);
846 	else
847 		enabled = vcpu->arch.ia32_misc_enable_msr & MSR_IA32_MISC_ENABLE_MWAIT;
848 
849 	if (!enabled)
850 		return kvm_handle_invalid_op(vcpu);
851 
852 emulate_as_nop:
853 	pr_warn_once("%s instruction emulated as NOP!\n", insn);
854 	return kvm_emulate_as_nop(vcpu);
855 }
856 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
857 {
858 	return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
859 }
860 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_mwait);
861 
862 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
863 {
864 	return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
865 }
866 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_monitor);
867 
868 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
869 {
870 	xfer_to_guest_mode_prepare();
871 
872 	return READ_ONCE(vcpu->mode) == EXITING_GUEST_MODE ||
873 	       kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending();
874 }
875 
876 #ifdef CONFIG_X86_64
877 struct pvclock_clock {
878 	int vclock_mode;
879 	u64 cycle_last;
880 	u64 mask;
881 	u32 mult;
882 	u32 shift;
883 	u64 base_cycles;
884 	u64 offset;
885 };
886 
887 struct pvclock_gtod_data {
888 	seqcount_t	seq;
889 
890 	struct pvclock_clock clock; /* extract of a clocksource struct */
891 	struct pvclock_clock raw_clock; /* extract of a clocksource struct */
892 
893 	ktime_t		offs_boot;
894 	u64		wall_time_sec;
895 };
896 
897 static struct pvclock_gtod_data pvclock_gtod_data;
898 
899 static void update_pvclock_gtod(struct timekeeper *tk)
900 {
901 	struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
902 
903 	write_seqcount_begin(&vdata->seq);
904 
905 	/* copy pvclock gtod data */
906 	vdata->clock.vclock_mode	= tk->tkr_mono.clock->vdso_clock_mode;
907 	vdata->clock.cycle_last		= tk->tkr_mono.cycle_last;
908 	vdata->clock.mask		= tk->tkr_mono.mask;
909 	vdata->clock.mult		= tk->tkr_mono.mult;
910 	vdata->clock.shift		= tk->tkr_mono.shift;
911 	vdata->clock.base_cycles	= tk->tkr_mono.xtime_nsec;
912 	vdata->clock.offset		= tk->tkr_mono.base;
913 
914 	vdata->raw_clock.vclock_mode	= tk->tkr_raw.clock->vdso_clock_mode;
915 	vdata->raw_clock.cycle_last	= tk->tkr_raw.cycle_last;
916 	vdata->raw_clock.mask		= tk->tkr_raw.mask;
917 	vdata->raw_clock.mult		= tk->tkr_raw.mult;
918 	vdata->raw_clock.shift		= tk->tkr_raw.shift;
919 	vdata->raw_clock.base_cycles	= tk->tkr_raw.xtime_nsec;
920 	vdata->raw_clock.offset		= tk->tkr_raw.base;
921 
922 	vdata->wall_time_sec            = tk->xtime_sec;
923 
924 	vdata->offs_boot		= tk->offs_boot;
925 
926 	write_seqcount_end(&vdata->seq);
927 }
928 
929 static s64 get_kvmclock_base_ns(void)
930 {
931 	/* Count up from boot time, but with the frequency of the raw clock.  */
932 	return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
933 }
934 #else
935 static s64 get_kvmclock_base_ns(void)
936 {
937 	/* Master clock not used, so we can just use CLOCK_BOOTTIME.  */
938 	return ktime_get_boottime_ns();
939 }
940 #endif
941 
942 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
943 {
944 	do_shl32_div32(dividend, divisor);
945 	return dividend;
946 }
947 
948 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
949 			       s8 *pshift, u32 *pmultiplier)
950 {
951 	uint64_t scaled64;
952 	int32_t  shift = 0;
953 	uint64_t tps64;
954 	uint32_t tps32;
955 
956 	tps64 = base_hz;
957 	scaled64 = scaled_hz;
958 	while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
959 		tps64 >>= 1;
960 		shift--;
961 	}
962 
963 	tps32 = (uint32_t)tps64;
964 	while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
965 		if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
966 			scaled64 >>= 1;
967 		else
968 			tps32 <<= 1;
969 		shift++;
970 	}
971 
972 	*pshift = shift;
973 	*pmultiplier = div_frac(scaled64, tps32);
974 }
975 
976 #ifdef CONFIG_X86_64
977 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
978 #endif
979 
980 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
981 static unsigned long max_tsc_khz;
982 
983 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
984 {
985 	u64 v = (u64)khz * (1000000 + ppm);
986 	do_div(v, 1000000);
987 	return v;
988 }
989 
990 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
991 
992 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
993 {
994 	u64 ratio;
995 
996 	/* Guest TSC same frequency as host TSC? */
997 	if (!scale) {
998 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
999 		return 0;
1000 	}
1001 
1002 	/* TSC scaling supported? */
1003 	if (!kvm_caps.has_tsc_control) {
1004 		if (user_tsc_khz > tsc_khz) {
1005 			vcpu->arch.tsc_catchup = 1;
1006 			vcpu->arch.tsc_always_catchup = 1;
1007 			return 0;
1008 		} else {
1009 			pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1010 			return -1;
1011 		}
1012 	}
1013 
1014 	/* TSC scaling required  - calculate ratio */
1015 	ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
1016 				user_tsc_khz, tsc_khz);
1017 
1018 	if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
1019 		pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1020 			            user_tsc_khz);
1021 		return -1;
1022 	}
1023 
1024 	kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
1025 	return 0;
1026 }
1027 
1028 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1029 {
1030 	u32 thresh_lo, thresh_hi;
1031 	int use_scaling = 0;
1032 
1033 	/* tsc_khz can be zero if TSC calibration fails */
1034 	if (user_tsc_khz == 0) {
1035 		/* set tsc_scaling_ratio to a safe value */
1036 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
1037 		return -1;
1038 	}
1039 
1040 	/* Compute a scale to convert nanoseconds in TSC cycles */
1041 	kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1042 			   &vcpu->arch.virtual_tsc_shift,
1043 			   &vcpu->arch.virtual_tsc_mult);
1044 	vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1045 
1046 	/*
1047 	 * Compute the variation in TSC rate which is acceptable
1048 	 * within the range of tolerance and decide if the
1049 	 * rate being applied is within that bounds of the hardware
1050 	 * rate.  If so, no scaling or compensation need be done.
1051 	 */
1052 	thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1053 	thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1054 	if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1055 		pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
1056 			 user_tsc_khz, thresh_lo, thresh_hi);
1057 		use_scaling = 1;
1058 	}
1059 	return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1060 }
1061 
1062 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1063 {
1064 	u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1065 				      vcpu->arch.virtual_tsc_mult,
1066 				      vcpu->arch.virtual_tsc_shift);
1067 	tsc += vcpu->arch.this_tsc_write;
1068 	return tsc;
1069 }
1070 
1071 #ifdef CONFIG_X86_64
1072 static inline bool gtod_is_based_on_tsc(int mode)
1073 {
1074 	return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
1075 }
1076 #endif
1077 
1078 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
1079 {
1080 #ifdef CONFIG_X86_64
1081 	struct kvm_arch *ka = &vcpu->kvm->arch;
1082 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1083 
1084 	/*
1085 	 * To use the masterclock, the host clocksource must be based on TSC
1086 	 * and all vCPUs must have matching TSCs.  Note, the count for matching
1087 	 * vCPUs doesn't include the reference vCPU, hence "+1".
1088 	 */
1089 	bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
1090 				 atomic_read(&vcpu->kvm->online_vcpus)) &&
1091 				gtod_is_based_on_tsc(gtod->clock.vclock_mode);
1092 
1093 	/*
1094 	 * Request a masterclock update if the masterclock needs to be toggled
1095 	 * on/off, or when starting a new generation and the masterclock is
1096 	 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
1097 	 * taken _after_ the new generation is created).
1098 	 */
1099 	if ((ka->use_master_clock && new_generation) ||
1100 	    (ka->use_master_clock != use_master_clock))
1101 		kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1102 
1103 	trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1104 			    atomic_read(&vcpu->kvm->online_vcpus),
1105 		            ka->use_master_clock, gtod->clock.vclock_mode);
1106 #endif
1107 }
1108 
1109 /*
1110  * Multiply tsc by a fixed point number represented by ratio.
1111  *
1112  * The most significant 64-N bits (mult) of ratio represent the
1113  * integral part of the fixed point number; the remaining N bits
1114  * (frac) represent the fractional part, ie. ratio represents a fixed
1115  * point number (mult + frac * 2^(-N)).
1116  *
1117  * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
1118  */
1119 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1120 {
1121 	return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
1122 }
1123 
1124 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
1125 {
1126 	u64 _tsc = tsc;
1127 
1128 	if (ratio != kvm_caps.default_tsc_scaling_ratio)
1129 		_tsc = __scale_tsc(ratio, tsc);
1130 
1131 	return _tsc;
1132 }
1133 
1134 u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1135 {
1136 	u64 tsc;
1137 
1138 	tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
1139 
1140 	return target_tsc - tsc;
1141 }
1142 
1143 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1144 {
1145 	return vcpu->arch.l1_tsc_offset +
1146 		kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
1147 }
1148 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_l1_tsc);
1149 
1150 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
1151 {
1152 	u64 nested_offset;
1153 
1154 	if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
1155 		nested_offset = l1_offset;
1156 	else
1157 		nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
1158 						kvm_caps.tsc_scaling_ratio_frac_bits);
1159 
1160 	nested_offset += l2_offset;
1161 	return nested_offset;
1162 }
1163 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_offset);
1164 
1165 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
1166 {
1167 	if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
1168 		return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
1169 				       kvm_caps.tsc_scaling_ratio_frac_bits);
1170 
1171 	return l1_multiplier;
1172 }
1173 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_multiplier);
1174 
1175 void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
1176 {
1177 	if (vcpu->arch.guest_tsc_protected)
1178 		return;
1179 
1180 	trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1181 				   vcpu->arch.l1_tsc_offset,
1182 				   l1_offset);
1183 
1184 	vcpu->arch.l1_tsc_offset = l1_offset;
1185 
1186 	/*
1187 	 * If we are here because L1 chose not to trap WRMSR to TSC then
1188 	 * according to the spec this should set L1's TSC (as opposed to
1189 	 * setting L1's offset for L2).
1190 	 */
1191 	if (is_guest_mode(vcpu))
1192 		vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
1193 			l1_offset,
1194 			kvm_x86_call(get_l2_tsc_offset)(vcpu),
1195 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
1196 	else
1197 		vcpu->arch.tsc_offset = l1_offset;
1198 
1199 	kvm_x86_call(write_tsc_offset)(vcpu);
1200 }
1201 
1202 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
1203 {
1204 	vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
1205 
1206 	/* Userspace is changing the multiplier while L2 is active */
1207 	if (is_guest_mode(vcpu))
1208 		vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
1209 			l1_multiplier,
1210 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
1211 	else
1212 		vcpu->arch.tsc_scaling_ratio = l1_multiplier;
1213 
1214 	if (kvm_caps.has_tsc_control)
1215 		kvm_x86_call(write_tsc_multiplier)(vcpu);
1216 }
1217 
1218 static inline bool kvm_check_tsc_unstable(void)
1219 {
1220 #ifdef CONFIG_X86_64
1221 	/*
1222 	 * TSC is marked unstable when we're running on Hyper-V,
1223 	 * 'TSC page' clocksource is good.
1224 	 */
1225 	if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
1226 		return false;
1227 #endif
1228 	return check_tsc_unstable();
1229 }
1230 
1231 /*
1232  * Infers attempts to synchronize the guest's tsc from host writes. Sets the
1233  * offset for the vcpu and tracks the TSC matching generation that the vcpu
1234  * participates in.
1235  */
1236 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
1237 				  u64 ns, bool matched, bool user_set_tsc)
1238 {
1239 	struct kvm *kvm = vcpu->kvm;
1240 
1241 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
1242 
1243 	if (vcpu->arch.guest_tsc_protected)
1244 		return;
1245 
1246 	if (user_set_tsc)
1247 		vcpu->kvm->arch.user_set_tsc = true;
1248 
1249 	/*
1250 	 * We also track th most recent recorded KHZ, write and time to
1251 	 * allow the matching interval to be extended at each write.
1252 	 */
1253 	kvm->arch.last_tsc_nsec = ns;
1254 	kvm->arch.last_tsc_write = tsc;
1255 	kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1256 	kvm->arch.last_tsc_offset = offset;
1257 
1258 	vcpu->arch.last_guest_tsc = tsc;
1259 
1260 	kvm_vcpu_write_tsc_offset(vcpu, offset);
1261 
1262 	if (!matched) {
1263 		/*
1264 		 * We split periods of matched TSC writes into generations.
1265 		 * For each generation, we track the original measured
1266 		 * nanosecond time, offset, and write, so if TSCs are in
1267 		 * sync, we can match exact offset, and if not, we can match
1268 		 * exact software computation in compute_guest_tsc()
1269 		 *
1270 		 * These values are tracked in kvm->arch.cur_xxx variables.
1271 		 */
1272 		kvm->arch.cur_tsc_generation++;
1273 		kvm->arch.cur_tsc_nsec = ns;
1274 		kvm->arch.cur_tsc_write = tsc;
1275 		kvm->arch.cur_tsc_offset = offset;
1276 		kvm->arch.nr_vcpus_matched_tsc = 0;
1277 	} else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
1278 		kvm->arch.nr_vcpus_matched_tsc++;
1279 	}
1280 
1281 	/* Keep track of which generation this VCPU has synchronized to */
1282 	vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1283 	vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1284 	vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1285 
1286 	kvm_track_tsc_matching(vcpu, !matched);
1287 }
1288 
1289 void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
1290 {
1291 	u64 data = user_value ? *user_value : 0;
1292 	struct kvm *kvm = vcpu->kvm;
1293 	u64 offset, ns, elapsed;
1294 	unsigned long flags;
1295 	bool matched = false;
1296 	bool synchronizing = false;
1297 
1298 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1299 	offset = kvm_compute_l1_tsc_offset(vcpu, data);
1300 	ns = get_kvmclock_base_ns();
1301 	elapsed = ns - kvm->arch.last_tsc_nsec;
1302 
1303 	if (vcpu->arch.virtual_tsc_khz) {
1304 		if (data == 0) {
1305 			/*
1306 			 * Force synchronization when creating a vCPU, or when
1307 			 * userspace explicitly writes a zero value.
1308 			 */
1309 			synchronizing = true;
1310 		} else if (kvm->arch.user_set_tsc) {
1311 			u64 tsc_exp = kvm->arch.last_tsc_write +
1312 						nsec_to_cycles(vcpu, elapsed);
1313 			u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
1314 			/*
1315 			 * Here lies UAPI baggage: when a user-initiated TSC write has
1316 			 * a small delta (1 second) of virtual cycle time against the
1317 			 * previously set vCPU, we assume that they were intended to be
1318 			 * in sync and the delta was only due to the racy nature of the
1319 			 * legacy API.
1320 			 *
1321 			 * This trick falls down when restoring a guest which genuinely
1322 			 * has been running for less time than the 1 second of imprecision
1323 			 * which we allow for in the legacy API. In this case, the first
1324 			 * value written by userspace (on any vCPU) should not be subject
1325 			 * to this 'correction' to make it sync up with values that only
1326 			 * come from the kernel's default vCPU creation. Make the 1-second
1327 			 * slop hack only trigger if the user_set_tsc flag is already set.
1328 			 */
1329 			synchronizing = data < tsc_exp + tsc_hz &&
1330 					data + tsc_hz > tsc_exp;
1331 		}
1332 	}
1333 
1334 
1335 	/*
1336 	 * For a reliable TSC, we can match TSC offsets, and for an unstable
1337 	 * TSC, we add elapsed time in this computation.  We could let the
1338 	 * compensation code attempt to catch up if we fall behind, but
1339 	 * it's better to try to match offsets from the beginning.
1340          */
1341 	if (synchronizing &&
1342 	    vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1343 		if (!kvm_check_tsc_unstable()) {
1344 			offset = kvm->arch.cur_tsc_offset;
1345 		} else {
1346 			u64 delta = nsec_to_cycles(vcpu, elapsed);
1347 			data += delta;
1348 			offset = kvm_compute_l1_tsc_offset(vcpu, data);
1349 		}
1350 		matched = true;
1351 	}
1352 
1353 	__kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value);
1354 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1355 }
1356 
1357 #ifdef CONFIG_X86_64
1358 
1359 static u64 read_tsc(void)
1360 {
1361 	u64 ret = (u64)rdtsc_ordered();
1362 	u64 last = pvclock_gtod_data.clock.cycle_last;
1363 
1364 	if (likely(ret >= last))
1365 		return ret;
1366 
1367 	/*
1368 	 * GCC likes to generate cmov here, but this branch is extremely
1369 	 * predictable (it's just a function of time and the likely is
1370 	 * very likely) and there's a data dependence, so force GCC
1371 	 * to generate a branch instead.  I don't barrier() because
1372 	 * we don't actually need a barrier, and if this function
1373 	 * ever gets inlined it will generate worse code.
1374 	 */
1375 	asm volatile ("");
1376 	return last;
1377 }
1378 
1379 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
1380 			  int *mode)
1381 {
1382 	u64 tsc_pg_val;
1383 	long v;
1384 
1385 	switch (clock->vclock_mode) {
1386 	case VDSO_CLOCKMODE_HVCLOCK:
1387 		if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
1388 					 tsc_timestamp, &tsc_pg_val)) {
1389 			/* TSC page valid */
1390 			*mode = VDSO_CLOCKMODE_HVCLOCK;
1391 			v = (tsc_pg_val - clock->cycle_last) &
1392 				clock->mask;
1393 		} else {
1394 			/* TSC page invalid */
1395 			*mode = VDSO_CLOCKMODE_NONE;
1396 		}
1397 		break;
1398 	case VDSO_CLOCKMODE_TSC:
1399 		*mode = VDSO_CLOCKMODE_TSC;
1400 		*tsc_timestamp = read_tsc();
1401 		v = (*tsc_timestamp - clock->cycle_last) &
1402 			clock->mask;
1403 		break;
1404 	default:
1405 		*mode = VDSO_CLOCKMODE_NONE;
1406 	}
1407 
1408 	if (*mode == VDSO_CLOCKMODE_NONE)
1409 		*tsc_timestamp = v = 0;
1410 
1411 	return v * clock->mult;
1412 }
1413 
1414 /*
1415  * As with get_kvmclock_base_ns(), this counts from boot time, at the
1416  * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
1417  */
1418 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
1419 {
1420 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1421 	unsigned long seq;
1422 	int mode;
1423 	u64 ns;
1424 
1425 	do {
1426 		seq = read_seqcount_begin(&gtod->seq);
1427 		ns = gtod->raw_clock.base_cycles;
1428 		ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
1429 		ns >>= gtod->raw_clock.shift;
1430 		ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
1431 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1432 	*t = ns;
1433 
1434 	return mode;
1435 }
1436 
1437 /*
1438  * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
1439  * no boot time offset.
1440  */
1441 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
1442 {
1443 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1444 	unsigned long seq;
1445 	int mode;
1446 	u64 ns;
1447 
1448 	do {
1449 		seq = read_seqcount_begin(&gtod->seq);
1450 		ns = gtod->clock.base_cycles;
1451 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
1452 		ns >>= gtod->clock.shift;
1453 		ns += ktime_to_ns(gtod->clock.offset);
1454 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1455 	*t = ns;
1456 
1457 	return mode;
1458 }
1459 
1460 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
1461 {
1462 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1463 	unsigned long seq;
1464 	int mode;
1465 	u64 ns;
1466 
1467 	do {
1468 		seq = read_seqcount_begin(&gtod->seq);
1469 		ts->tv_sec = gtod->wall_time_sec;
1470 		ns = gtod->clock.base_cycles;
1471 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
1472 		ns >>= gtod->clock.shift;
1473 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1474 
1475 	ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
1476 	ts->tv_nsec = ns;
1477 
1478 	return mode;
1479 }
1480 
1481 /*
1482  * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
1483  * reports the TSC value from which it do so. Returns true if host is
1484  * using TSC based clocksource.
1485  */
1486 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
1487 {
1488 	/* checked again under seqlock below */
1489 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1490 		return false;
1491 
1492 	return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
1493 						     tsc_timestamp));
1494 }
1495 
1496 /*
1497  * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
1498  * so. Returns true if host is using TSC based clocksource.
1499  */
1500 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
1501 {
1502 	/* checked again under seqlock below */
1503 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1504 		return false;
1505 
1506 	return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
1507 						 tsc_timestamp));
1508 }
1509 
1510 /*
1511  * Calculates CLOCK_REALTIME and reports the TSC value from which it did
1512  * so. Returns true if host is using TSC based clocksource.
1513  *
1514  * DO NOT USE this for anything related to migration. You want CLOCK_TAI
1515  * for that.
1516  */
1517 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
1518 					   u64 *tsc_timestamp)
1519 {
1520 	/* checked again under seqlock below */
1521 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
1522 		return false;
1523 
1524 	return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
1525 }
1526 #endif
1527 
1528 /*
1529  *
1530  * Assuming a stable TSC across physical CPUS, and a stable TSC
1531  * across virtual CPUs, the following condition is possible.
1532  * Each numbered line represents an event visible to both
1533  * CPUs at the next numbered event.
1534  *
1535  * "timespecX" represents host monotonic time. "tscX" represents
1536  * RDTSC value.
1537  *
1538  * 		VCPU0 on CPU0		|	VCPU1 on CPU1
1539  *
1540  * 1.  read timespec0,tsc0
1541  * 2.					| timespec1 = timespec0 + N
1542  * 					| tsc1 = tsc0 + M
1543  * 3. transition to guest		| transition to guest
1544  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1545  * 5.				        | ret1 = timespec1 + (rdtsc - tsc1)
1546  * 				        | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1547  *
1548  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1549  *
1550  * 	- ret0 < ret1
1551  *	- timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1552  *		...
1553  *	- 0 < N - M => M < N
1554  *
1555  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1556  * always the case (the difference between two distinct xtime instances
1557  * might be smaller then the difference between corresponding TSC reads,
1558  * when updating guest vcpus pvclock areas).
1559  *
1560  * To avoid that problem, do not allow visibility of distinct
1561  * system_timestamp/tsc_timestamp values simultaneously: use a master
1562  * copy of host monotonic time values. Update that master copy
1563  * in lockstep.
1564  *
1565  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1566  *
1567  */
1568 
1569 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1570 {
1571 #ifdef CONFIG_X86_64
1572 	struct kvm_arch *ka = &kvm->arch;
1573 	int vclock_mode;
1574 	bool host_tsc_clocksource, vcpus_matched;
1575 
1576 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
1577 	vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1578 			atomic_read(&kvm->online_vcpus));
1579 
1580 	/*
1581 	 * If the host uses TSC clock, then passthrough TSC as stable
1582 	 * to the guest.
1583 	 */
1584 	host_tsc_clocksource = kvm_get_time_and_clockread(
1585 					&ka->master_kernel_ns,
1586 					&ka->master_cycle_now);
1587 
1588 	ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1589 				&& !ka->backwards_tsc_observed
1590 				&& !ka->boot_vcpu_runs_old_kvmclock;
1591 
1592 	if (ka->use_master_clock)
1593 		atomic_set(&kvm_guest_has_master_clock, 1);
1594 
1595 	vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1596 	trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1597 					vcpus_matched);
1598 #endif
1599 }
1600 
1601 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
1602 {
1603 	kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
1604 }
1605 
1606 static void __kvm_start_pvclock_update(struct kvm *kvm)
1607 {
1608 	raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
1609 	write_seqcount_begin(&kvm->arch.pvclock_sc);
1610 }
1611 
1612 static void kvm_start_pvclock_update(struct kvm *kvm)
1613 {
1614 	kvm_make_mclock_inprogress_request(kvm);
1615 
1616 	/* no guest entries from this point */
1617 	__kvm_start_pvclock_update(kvm);
1618 }
1619 
1620 static void kvm_end_pvclock_update(struct kvm *kvm)
1621 {
1622 	struct kvm_arch *ka = &kvm->arch;
1623 	struct kvm_vcpu *vcpu;
1624 	unsigned long i;
1625 
1626 	write_seqcount_end(&ka->pvclock_sc);
1627 	raw_spin_unlock_irq(&ka->tsc_write_lock);
1628 	kvm_for_each_vcpu(i, vcpu, kvm)
1629 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1630 
1631 	/* guest entries allowed */
1632 	kvm_for_each_vcpu(i, vcpu, kvm)
1633 		kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
1634 }
1635 
1636 static void kvm_update_masterclock(struct kvm *kvm)
1637 {
1638 	kvm_hv_request_tsc_page_update(kvm);
1639 	kvm_start_pvclock_update(kvm);
1640 	pvclock_update_vm_gtod_copy(kvm);
1641 	kvm_end_pvclock_update(kvm);
1642 }
1643 
1644 /*
1645  * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
1646  * per-CPU value (which may be zero if a CPU is going offline).  Note, tsc_khz
1647  * can change during boot even if the TSC is constant, as it's possible for KVM
1648  * to be loaded before TSC calibration completes.  Ideally, KVM would get a
1649  * notification when calibration completes, but practically speaking calibration
1650  * will complete before userspace is alive enough to create VMs.
1651  */
1652 static unsigned long get_cpu_tsc_khz(void)
1653 {
1654 	if (cpu_feature_enabled(X86_FEATURE_CONSTANT_TSC))
1655 		return tsc_khz;
1656 	else
1657 		return __this_cpu_read(cpu_tsc_khz);
1658 }
1659 
1660 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc.  */
1661 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
1662 {
1663 	struct kvm_arch *ka = &kvm->arch;
1664 	struct pvclock_vcpu_time_info hv_clock;
1665 
1666 	/* both __this_cpu_read() and rdtsc() should be on the same cpu */
1667 	get_cpu();
1668 
1669 	data->flags = 0;
1670 	if (ka->use_master_clock &&
1671 	    (cpu_feature_enabled(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
1672 #ifdef CONFIG_X86_64
1673 		struct timespec64 ts;
1674 
1675 		if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
1676 			data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
1677 			data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
1678 		} else
1679 #endif
1680 		data->host_tsc = rdtsc();
1681 
1682 		data->flags |= KVM_CLOCK_TSC_STABLE;
1683 		hv_clock.tsc_timestamp = ka->master_cycle_now;
1684 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
1685 		kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
1686 				   &hv_clock.tsc_shift,
1687 				   &hv_clock.tsc_to_system_mul);
1688 		data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
1689 	} else {
1690 		data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
1691 	}
1692 
1693 	put_cpu();
1694 }
1695 
1696 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
1697 {
1698 	struct kvm_arch *ka = &kvm->arch;
1699 	unsigned seq;
1700 
1701 	do {
1702 		seq = read_seqcount_begin(&ka->pvclock_sc);
1703 		__get_kvmclock(kvm, data);
1704 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
1705 }
1706 
1707 u64 get_kvmclock_ns(struct kvm *kvm)
1708 {
1709 	struct kvm_clock_data data;
1710 
1711 	get_kvmclock(kvm, &data);
1712 	return data.clock;
1713 }
1714 
1715 static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
1716 				    struct kvm_vcpu *vcpu,
1717 				    struct gfn_to_pfn_cache *gpc,
1718 				    unsigned int offset)
1719 {
1720 	struct pvclock_vcpu_time_info *guest_hv_clock;
1721 	struct pvclock_vcpu_time_info hv_clock;
1722 	unsigned long flags;
1723 
1724 	memcpy(&hv_clock, ref_hv_clock, sizeof(hv_clock));
1725 
1726 	read_lock_irqsave(&gpc->lock, flags);
1727 	while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
1728 		read_unlock_irqrestore(&gpc->lock, flags);
1729 
1730 		if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
1731 			return;
1732 
1733 		read_lock_irqsave(&gpc->lock, flags);
1734 	}
1735 
1736 	guest_hv_clock = (void *)(gpc->khva + offset);
1737 
1738 	/*
1739 	 * This VCPU is paused, but it's legal for a guest to read another
1740 	 * VCPU's kvmclock, so we really have to follow the specification where
1741 	 * it says that version is odd if data is being modified, and even after
1742 	 * it is consistent.
1743 	 */
1744 
1745 	guest_hv_clock->version = hv_clock.version = (guest_hv_clock->version + 1) | 1;
1746 	smp_wmb();
1747 
1748 	/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1749 	hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
1750 
1751 	memcpy(guest_hv_clock, &hv_clock, sizeof(*guest_hv_clock));
1752 
1753 	smp_wmb();
1754 
1755 	guest_hv_clock->version = ++hv_clock.version;
1756 
1757 	kvm_gpc_mark_dirty_in_slot(gpc);
1758 	read_unlock_irqrestore(&gpc->lock, flags);
1759 
1760 	trace_kvm_pvclock_update(vcpu->vcpu_id, &hv_clock);
1761 }
1762 
1763 int kvm_guest_time_update(struct kvm_vcpu *v)
1764 {
1765 	struct pvclock_vcpu_time_info hv_clock = {};
1766 	unsigned long flags, tgt_tsc_khz;
1767 	unsigned seq;
1768 	struct kvm_vcpu_arch *vcpu = &v->arch;
1769 	struct kvm_arch *ka = &v->kvm->arch;
1770 	s64 kernel_ns;
1771 	u64 tsc_timestamp, host_tsc;
1772 	bool use_master_clock;
1773 
1774 	kernel_ns = 0;
1775 	host_tsc = 0;
1776 
1777 	/*
1778 	 * If the host uses TSC clock, then passthrough TSC as stable
1779 	 * to the guest.
1780 	 */
1781 	do {
1782 		seq = read_seqcount_begin(&ka->pvclock_sc);
1783 		use_master_clock = ka->use_master_clock;
1784 		if (use_master_clock) {
1785 			host_tsc = ka->master_cycle_now;
1786 			kernel_ns = ka->master_kernel_ns;
1787 		}
1788 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
1789 
1790 	/* Keep irq disabled to prevent changes to the clock */
1791 	local_irq_save(flags);
1792 	tgt_tsc_khz = get_cpu_tsc_khz();
1793 	if (unlikely(tgt_tsc_khz == 0)) {
1794 		local_irq_restore(flags);
1795 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1796 		return 1;
1797 	}
1798 	if (!use_master_clock) {
1799 		host_tsc = rdtsc();
1800 		kernel_ns = get_kvmclock_base_ns();
1801 	}
1802 
1803 	tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
1804 
1805 	/*
1806 	 * We may have to catch up the TSC to match elapsed wall clock
1807 	 * time for two reasons, even if kvmclock is used.
1808 	 *   1) CPU could have been running below the maximum TSC rate
1809 	 *   2) Broken TSC compensation resets the base at each VCPU
1810 	 *      entry to avoid unknown leaps of TSC even when running
1811 	 *      again on the same CPU.  This may cause apparent elapsed
1812 	 *      time to disappear, and the guest to stand still or run
1813 	 *	very slowly.
1814 	 */
1815 	if (vcpu->tsc_catchup) {
1816 		u64 tsc = compute_guest_tsc(v, kernel_ns);
1817 		if (tsc > tsc_timestamp) {
1818 			adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1819 			tsc_timestamp = tsc;
1820 		}
1821 	}
1822 
1823 	local_irq_restore(flags);
1824 
1825 	/* With all the info we got, fill in the values */
1826 
1827 	if (kvm_caps.has_tsc_control) {
1828 		tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
1829 					    v->arch.l1_tsc_scaling_ratio);
1830 		tgt_tsc_khz = tgt_tsc_khz ? : 1;
1831 	}
1832 
1833 	if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
1834 		kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
1835 				   &vcpu->pvclock_tsc_shift,
1836 				   &vcpu->pvclock_tsc_mul);
1837 		vcpu->hw_tsc_khz = tgt_tsc_khz;
1838 	}
1839 
1840 	hv_clock.tsc_shift = vcpu->pvclock_tsc_shift;
1841 	hv_clock.tsc_to_system_mul = vcpu->pvclock_tsc_mul;
1842 	hv_clock.tsc_timestamp = tsc_timestamp;
1843 	hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1844 	vcpu->last_guest_tsc = tsc_timestamp;
1845 
1846 	/* If the host uses TSC clocksource, then it is stable */
1847 	hv_clock.flags = 0;
1848 	if (use_master_clock)
1849 		hv_clock.flags |= PVCLOCK_TSC_STABLE_BIT;
1850 
1851 	if (vcpu->pv_time.active) {
1852 		/*
1853 		 * GUEST_STOPPED is only supported by kvmclock, and KVM's
1854 		 * historic behavior is to only process the request if kvmclock
1855 		 * is active/enabled.
1856 		 */
1857 		if (vcpu->pvclock_set_guest_stopped_request) {
1858 			hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
1859 			vcpu->pvclock_set_guest_stopped_request = false;
1860 		}
1861 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->pv_time, 0);
1862 
1863 		hv_clock.flags &= ~PVCLOCK_GUEST_STOPPED;
1864 	}
1865 
1866 	kvm_hv_setup_tsc_page(v->kvm, &hv_clock);
1867 
1868 #ifdef CONFIG_KVM_XEN
1869 	/*
1870 	 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
1871 	 * explicitly told to use TSC as its clocksource Xen will not set this bit.
1872 	 * This default behaviour led to bugs in some guest kernels which cause
1873 	 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
1874 	 *
1875 	 * Note!  Clear TSC_STABLE only for Xen clocks, i.e. the order matters!
1876 	 */
1877 	if (ka->xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
1878 		hv_clock.flags &= ~PVCLOCK_TSC_STABLE_BIT;
1879 
1880 	if (vcpu->xen.vcpu_info_cache.active)
1881 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_info_cache,
1882 					offsetof(struct compat_vcpu_info, time));
1883 	if (vcpu->xen.vcpu_time_info_cache.active)
1884 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_time_info_cache, 0);
1885 #endif
1886 	return 0;
1887 }
1888 
1889 /*
1890  * The pvclock_wall_clock ABI tells the guest the wall clock time at
1891  * which it started (i.e. its epoch, when its kvmclock was zero).
1892  *
1893  * In fact those clocks are subtly different; wall clock frequency is
1894  * adjusted by NTP and has leap seconds, while the kvmclock is a
1895  * simple function of the TSC without any such adjustment.
1896  *
1897  * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
1898  * that and kvmclock, but even that would be subject to change over
1899  * time.
1900  *
1901  * Attempt to calculate the epoch at a given moment using the *same*
1902  * TSC reading via kvm_get_walltime_and_clockread() to obtain both
1903  * wallclock and kvmclock times, and subtracting one from the other.
1904  *
1905  * Fall back to using their values at slightly different moments by
1906  * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
1907  */
1908 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
1909 {
1910 #ifdef CONFIG_X86_64
1911 	struct pvclock_vcpu_time_info hv_clock;
1912 	struct kvm_arch *ka = &kvm->arch;
1913 	unsigned long seq, local_tsc_khz;
1914 	struct timespec64 ts;
1915 	uint64_t host_tsc;
1916 
1917 	do {
1918 		seq = read_seqcount_begin(&ka->pvclock_sc);
1919 
1920 		local_tsc_khz = 0;
1921 		if (!ka->use_master_clock)
1922 			break;
1923 
1924 		/*
1925 		 * The TSC read and the call to get_cpu_tsc_khz() must happen
1926 		 * on the same CPU.
1927 		 */
1928 		get_cpu();
1929 
1930 		local_tsc_khz = get_cpu_tsc_khz();
1931 
1932 		if (local_tsc_khz &&
1933 		    !kvm_get_walltime_and_clockread(&ts, &host_tsc))
1934 			local_tsc_khz = 0; /* Fall back to old method */
1935 
1936 		put_cpu();
1937 
1938 		/*
1939 		 * These values must be snapshotted within the seqcount loop.
1940 		 * After that, it's just mathematics which can happen on any
1941 		 * CPU at any time.
1942 		 */
1943 		hv_clock.tsc_timestamp = ka->master_cycle_now;
1944 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
1945 
1946 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
1947 
1948 	/*
1949 	 * If the conditions were right, and obtaining the wallclock+TSC was
1950 	 * successful, calculate the KVM clock at the corresponding time and
1951 	 * subtract one from the other to get the guest's epoch in nanoseconds
1952 	 * since 1970-01-01.
1953 	 */
1954 	if (local_tsc_khz) {
1955 		kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
1956 				   &hv_clock.tsc_shift,
1957 				   &hv_clock.tsc_to_system_mul);
1958 		return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
1959 			__pvclock_read_cycles(&hv_clock, host_tsc);
1960 	}
1961 #endif
1962 	return ktime_get_real_ns() - get_kvmclock_ns(kvm);
1963 }
1964 
1965 /*
1966  * kvmclock updates which are isolated to a given vcpu, such as
1967  * vcpu->cpu migration, should not allow system_timestamp from
1968  * the rest of the vcpus to remain static.
1969  *
1970  * So in those cases, request a kvmclock update for all vcpus.
1971  * The worst case for a remote vcpu to update its kvmclock
1972  * is then bounded by maximum nohz sleep latency.
1973  */
1974 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1975 {
1976 	unsigned long i;
1977 	struct kvm_vcpu *vcpu;
1978 	struct kvm *kvm = v->kvm;
1979 
1980 	kvm_for_each_vcpu(i, vcpu, kvm) {
1981 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1982 		kvm_vcpu_kick(vcpu);
1983 	}
1984 }
1985 
1986 static void kvmclock_reset(struct kvm_vcpu *vcpu)
1987 {
1988 	kvm_gpc_deactivate(&vcpu->arch.pv_time);
1989 	vcpu->arch.time = 0;
1990 }
1991 
1992 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
1993 {
1994 	++vcpu->stat.tlb_flush;
1995 	kvm_x86_call(flush_tlb_all)(vcpu);
1996 
1997 	/* Flushing all ASIDs flushes the current ASID... */
1998 	kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1999 }
2000 
2001 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
2002 {
2003 	++vcpu->stat.tlb_flush;
2004 
2005 	if (!tdp_enabled) {
2006 		/*
2007 		 * A TLB flush on behalf of the guest is equivalent to
2008 		 * INVPCID(all), toggling CR4.PGE, etc., which requires
2009 		 * a forced sync of the shadow page tables.  Ensure all the
2010 		 * roots are synced and the guest TLB in hardware is clean.
2011 		 */
2012 		kvm_mmu_sync_roots(vcpu);
2013 		kvm_mmu_sync_prev_roots(vcpu);
2014 	}
2015 
2016 	kvm_x86_call(flush_tlb_guest)(vcpu);
2017 
2018 	/*
2019 	 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
2020 	 * grained flushing.
2021 	 */
2022 	kvm_hv_vcpu_purge_flush_tlb(vcpu);
2023 }
2024 
2025 
2026 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
2027 {
2028 	++vcpu->stat.tlb_flush;
2029 	kvm_x86_call(flush_tlb_current)(vcpu);
2030 }
2031 
2032 /*
2033  * Service "local" TLB flush requests, which are specific to the current MMU
2034  * context.  In addition to the generic event handling in vcpu_enter_guest(),
2035  * TLB flushes that are targeted at an MMU context also need to be serviced
2036  * prior before nested VM-Enter/VM-Exit.
2037  */
2038 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
2039 {
2040 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
2041 		kvm_vcpu_flush_tlb_current(vcpu);
2042 
2043 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
2044 		kvm_vcpu_flush_tlb_guest(vcpu);
2045 }
2046 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_service_local_tlb_flush_requests);
2047 
2048 static void record_steal_time(struct kvm_vcpu *vcpu)
2049 {
2050 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
2051 	struct kvm_steal_time __user *st;
2052 	struct kvm_memslots *slots;
2053 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
2054 	u64 steal;
2055 	u32 version;
2056 
2057 	if (kvm_xen_msr_enabled(vcpu->kvm)) {
2058 		kvm_xen_runstate_set_running(vcpu);
2059 		return;
2060 	}
2061 
2062 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2063 		return;
2064 
2065 	if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
2066 		return;
2067 
2068 	slots = kvm_memslots(vcpu->kvm);
2069 
2070 	if (unlikely(slots->generation != ghc->generation ||
2071 		     gpa != ghc->gpa ||
2072 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
2073 		/* We rely on the fact that it fits in a single page. */
2074 		BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
2075 
2076 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
2077 		    kvm_is_error_hva(ghc->hva) || !ghc->memslot)
2078 			return;
2079 	}
2080 
2081 	st = (struct kvm_steal_time __user *)ghc->hva;
2082 	/*
2083 	 * Doing a TLB flush here, on the guest's behalf, can avoid
2084 	 * expensive IPIs.
2085 	 */
2086 	if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
2087 		u8 st_preempted = 0;
2088 		int err = -EFAULT;
2089 
2090 		if (!user_access_begin(st, sizeof(*st)))
2091 			return;
2092 
2093 		asm volatile("1: xchgb %0, %2\n"
2094 			     "xor %1, %1\n"
2095 			     "2:\n"
2096 			     _ASM_EXTABLE_UA(1b, 2b)
2097 			     : "+q" (st_preempted),
2098 			       "+&r" (err),
2099 			       "+m" (st->preempted));
2100 		if (err)
2101 			goto out;
2102 
2103 		user_access_end();
2104 
2105 		vcpu->arch.st.preempted = 0;
2106 
2107 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
2108 				       st_preempted & KVM_VCPU_FLUSH_TLB);
2109 		if (st_preempted & KVM_VCPU_FLUSH_TLB)
2110 			kvm_vcpu_flush_tlb_guest(vcpu);
2111 
2112 		if (!user_access_begin(st, sizeof(*st)))
2113 			goto dirty;
2114 	} else {
2115 		if (!user_access_begin(st, sizeof(*st)))
2116 			return;
2117 
2118 		unsafe_put_user(0, &st->preempted, out);
2119 		vcpu->arch.st.preempted = 0;
2120 	}
2121 
2122 	unsafe_get_user(version, &st->version, out);
2123 	if (version & 1)
2124 		version += 1;  /* first time write, random junk */
2125 
2126 	version += 1;
2127 	unsafe_put_user(version, &st->version, out);
2128 
2129 	smp_wmb();
2130 
2131 	unsafe_get_user(steal, &st->steal, out);
2132 	steal += current->sched_info.run_delay -
2133 		vcpu->arch.st.last_steal;
2134 	vcpu->arch.st.last_steal = current->sched_info.run_delay;
2135 	unsafe_put_user(steal, &st->steal, out);
2136 
2137 	version += 1;
2138 	unsafe_put_user(version, &st->version, out);
2139 
2140  out:
2141 	user_access_end();
2142  dirty:
2143 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
2144 }
2145 
2146 static inline bool kvm_can_mwait_in_guest(void)
2147 {
2148 	return boot_cpu_has(X86_FEATURE_MWAIT) &&
2149 		!boot_cpu_has_bug(X86_BUG_MONITOR) &&
2150 		boot_cpu_has(X86_FEATURE_ARAT);
2151 }
2152 
2153 static u64 kvm_get_allowed_disable_exits(void)
2154 {
2155 	u64 r = KVM_X86_DISABLE_EXITS_PAUSE;
2156 
2157 	if (boot_cpu_has(X86_FEATURE_APERFMPERF))
2158 		r |= KVM_X86_DISABLE_EXITS_APERFMPERF;
2159 
2160 	if (!mitigate_smt_rsb) {
2161 		r |= KVM_X86_DISABLE_EXITS_HLT |
2162 			KVM_X86_DISABLE_EXITS_CSTATE;
2163 
2164 		if (kvm_can_mwait_in_guest())
2165 			r |= KVM_X86_DISABLE_EXITS_MWAIT;
2166 	}
2167 	return r;
2168 }
2169 
2170 #ifdef CONFIG_KVM_HYPERV
2171 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
2172 					    struct kvm_cpuid2 __user *cpuid_arg)
2173 {
2174 	struct kvm_cpuid2 cpuid;
2175 	int r;
2176 
2177 	r = -EFAULT;
2178 	if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
2179 		return r;
2180 
2181 	r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2182 	if (r)
2183 		return r;
2184 
2185 	r = -EFAULT;
2186 	if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
2187 		return r;
2188 
2189 	return 0;
2190 }
2191 #endif
2192 
2193 static bool kvm_is_vm_type_supported(unsigned long type)
2194 {
2195 	return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
2196 }
2197 
2198 static inline u64 kvm_sync_valid_fields(struct kvm *kvm)
2199 {
2200 	return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
2201 }
2202 
2203 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2204 {
2205 	int r = 0;
2206 
2207 	switch (ext) {
2208 	case KVM_CAP_IRQCHIP:
2209 	case KVM_CAP_HLT:
2210 	case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2211 	case KVM_CAP_SET_TSS_ADDR:
2212 	case KVM_CAP_EXT_CPUID:
2213 	case KVM_CAP_EXT_EMUL_CPUID:
2214 	case KVM_CAP_CLOCKSOURCE:
2215 #ifdef CONFIG_KVM_IOAPIC
2216 	case KVM_CAP_PIT:
2217 	case KVM_CAP_PIT2:
2218 	case KVM_CAP_PIT_STATE2:
2219 	case KVM_CAP_REINJECT_CONTROL:
2220 #endif
2221 	case KVM_CAP_NOP_IO_DELAY:
2222 	case KVM_CAP_MP_STATE:
2223 	case KVM_CAP_USER_NMI:
2224 	case KVM_CAP_IRQ_INJECT_STATUS:
2225 	case KVM_CAP_IOEVENTFD:
2226 	case KVM_CAP_IOEVENTFD_NO_LENGTH:
2227 
2228 	case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2229 	case KVM_CAP_VCPU_EVENTS:
2230 #ifdef CONFIG_KVM_HYPERV
2231 	case KVM_CAP_HYPERV:
2232 	case KVM_CAP_HYPERV_VAPIC:
2233 	case KVM_CAP_HYPERV_SPIN:
2234 	case KVM_CAP_HYPERV_TIME:
2235 	case KVM_CAP_HYPERV_SYNIC:
2236 	case KVM_CAP_HYPERV_SYNIC2:
2237 	case KVM_CAP_HYPERV_VP_INDEX:
2238 	case KVM_CAP_HYPERV_EVENTFD:
2239 	case KVM_CAP_HYPERV_TLBFLUSH:
2240 	case KVM_CAP_HYPERV_SEND_IPI:
2241 	case KVM_CAP_HYPERV_CPUID:
2242 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
2243 	case KVM_CAP_SYS_HYPERV_CPUID:
2244 #endif
2245 	case KVM_CAP_PCI_SEGMENT:
2246 	case KVM_CAP_DEBUGREGS:
2247 	case KVM_CAP_X86_ROBUST_SINGLESTEP:
2248 	case KVM_CAP_XSAVE:
2249 	case KVM_CAP_ASYNC_PF:
2250 	case KVM_CAP_ASYNC_PF_INT:
2251 	case KVM_CAP_GET_TSC_KHZ:
2252 	case KVM_CAP_KVMCLOCK_CTRL:
2253 	case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2254 	case KVM_CAP_TSC_DEADLINE_TIMER:
2255 	case KVM_CAP_DISABLE_QUIRKS:
2256 	case KVM_CAP_SET_BOOT_CPU_ID:
2257  	case KVM_CAP_SPLIT_IRQCHIP:
2258 	case KVM_CAP_IMMEDIATE_EXIT:
2259 	case KVM_CAP_PMU_EVENT_FILTER:
2260 	case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
2261 	case KVM_CAP_GET_MSR_FEATURES:
2262 	case KVM_CAP_MSR_PLATFORM_INFO:
2263 	case KVM_CAP_EXCEPTION_PAYLOAD:
2264 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
2265 	case KVM_CAP_SET_GUEST_DEBUG:
2266 	case KVM_CAP_LAST_CPU:
2267 	case KVM_CAP_X86_USER_SPACE_MSR:
2268 	case KVM_CAP_X86_MSR_FILTER:
2269 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
2270 #ifdef CONFIG_X86_SGX_KVM
2271 	case KVM_CAP_SGX_ATTRIBUTE:
2272 #endif
2273 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
2274 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
2275 	case KVM_CAP_SREGS2:
2276 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
2277 	case KVM_CAP_VCPU_ATTRIBUTES:
2278 	case KVM_CAP_SYS_ATTRIBUTES:
2279 	case KVM_CAP_VAPIC:
2280 	case KVM_CAP_ENABLE_CAP:
2281 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
2282 	case KVM_CAP_IRQFD_RESAMPLE:
2283 	case KVM_CAP_MEMORY_FAULT_INFO:
2284 	case KVM_CAP_X86_GUEST_MODE:
2285 	case KVM_CAP_ONE_REG:
2286 		r = 1;
2287 		break;
2288 	case KVM_CAP_PRE_FAULT_MEMORY:
2289 		r = tdp_enabled;
2290 		break;
2291 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
2292 		r = kvm ? kvm->arch.apic_bus_cycle_ns : APIC_BUS_CYCLE_NS_DEFAULT;
2293 		break;
2294 	case KVM_CAP_EXIT_HYPERCALL:
2295 		r = KVM_EXIT_HYPERCALL_VALID_MASK;
2296 		break;
2297 	case KVM_CAP_SET_GUEST_DEBUG2:
2298 		return KVM_GUESTDBG_VALID_MASK;
2299 #ifdef CONFIG_KVM_XEN
2300 	case KVM_CAP_XEN_HVM:
2301 		r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
2302 		    KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
2303 		    KVM_XEN_HVM_CONFIG_SHARED_INFO |
2304 		    KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
2305 		    KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
2306 		    KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
2307 		    KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
2308 		if (sched_info_on())
2309 			r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
2310 			     KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
2311 		break;
2312 #endif
2313 	case KVM_CAP_SYNC_REGS:
2314 		r = kvm_sync_valid_fields(kvm);
2315 		break;
2316 	case KVM_CAP_ADJUST_CLOCK:
2317 		r = KVM_CLOCK_VALID_FLAGS;
2318 		break;
2319 	case KVM_CAP_X86_DISABLE_EXITS:
2320 		r = kvm_get_allowed_disable_exits();
2321 		break;
2322 	case KVM_CAP_X86_SMM:
2323 		if (!IS_ENABLED(CONFIG_KVM_SMM))
2324 			break;
2325 
2326 		/* SMBASE is usually relocated above 1M on modern chipsets,
2327 		 * and SMM handlers might indeed rely on 4G segment limits,
2328 		 * so do not report SMM to be available if real mode is
2329 		 * emulated via vm86 mode.  Still, do not go to great lengths
2330 		 * to avoid userspace's usage of the feature, because it is a
2331 		 * fringe case that is not enabled except via specific settings
2332 		 * of the module parameters.
2333 		 */
2334 		r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
2335 		break;
2336 	case KVM_CAP_NR_VCPUS:
2337 		r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
2338 		break;
2339 	case KVM_CAP_MAX_VCPUS:
2340 		r = KVM_MAX_VCPUS;
2341 		if (kvm)
2342 			r = kvm->max_vcpus;
2343 		break;
2344 	case KVM_CAP_MAX_VCPU_ID:
2345 		r = KVM_MAX_VCPU_IDS;
2346 		break;
2347 	case KVM_CAP_PV_MMU:	/* obsolete */
2348 		r = 0;
2349 		break;
2350 	case KVM_CAP_MCE:
2351 		r = KVM_MAX_MCE_BANKS;
2352 		break;
2353 	case KVM_CAP_XCRS:
2354 		r = boot_cpu_has(X86_FEATURE_XSAVE);
2355 		break;
2356 	case KVM_CAP_TSC_CONTROL:
2357 	case KVM_CAP_VM_TSC_CONTROL:
2358 		r = kvm_caps.has_tsc_control;
2359 		break;
2360 	case KVM_CAP_X2APIC_API:
2361 		r = KVM_X2APIC_API_VALID_FLAGS;
2362 		if (kvm && !irqchip_split(kvm))
2363 			r &= ~KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST;
2364 		break;
2365 	case KVM_CAP_NESTED_STATE:
2366 		r = kvm_nested_ops.enabled ? kvm_nested_call(get_state)(NULL, NULL, 0) : 0;
2367 		break;
2368 #ifdef CONFIG_KVM_HYPERV
2369 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
2370 		r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
2371 		break;
2372 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
2373 		r = kvm_nested_ops.enabled && kvm_nested_ops.enable_evmcs != NULL;
2374 		break;
2375 #endif
2376 	case KVM_CAP_SMALLER_MAXPHYADDR:
2377 		r = (int) allow_smaller_maxphyaddr;
2378 		break;
2379 	case KVM_CAP_STEAL_TIME:
2380 		r = sched_info_on();
2381 		break;
2382 	case KVM_CAP_X86_BUS_LOCK_EXIT:
2383 		if (kvm_caps.has_bus_lock_exit)
2384 			r = KVM_BUS_LOCK_DETECTION_OFF |
2385 			    KVM_BUS_LOCK_DETECTION_EXIT;
2386 		else
2387 			r = 0;
2388 		break;
2389 	case KVM_CAP_XSAVE2: {
2390 		r = xstate_required_size(kvm_get_filtered_xcr0(), false);
2391 		if (r < sizeof(struct kvm_xsave))
2392 			r = sizeof(struct kvm_xsave);
2393 		break;
2394 	}
2395 	case KVM_CAP_PMU_CAPABILITY:
2396 		r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
2397 		break;
2398 	case KVM_CAP_DISABLE_QUIRKS2:
2399 		r = kvm_caps.supported_quirks;
2400 		break;
2401 	case KVM_CAP_X86_NOTIFY_VMEXIT:
2402 		r = kvm_caps.has_notify_vmexit;
2403 		break;
2404 	case KVM_CAP_VM_TYPES:
2405 		r = kvm_caps.supported_vm_types;
2406 		break;
2407 	case KVM_CAP_READONLY_MEM:
2408 		r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
2409 		break;
2410 	default:
2411 		break;
2412 	}
2413 	return r;
2414 }
2415 
2416 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
2417 {
2418 	if (attr->group) {
2419 		if (kvm_x86_ops.dev_get_attr)
2420 			return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
2421 		return -ENXIO;
2422 	}
2423 
2424 	switch (attr->attr) {
2425 	case KVM_X86_XCOMP_GUEST_SUPP:
2426 		*val = kvm_caps.supported_xcr0;
2427 		return 0;
2428 	default:
2429 		return -ENXIO;
2430 	}
2431 }
2432 
2433 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
2434 {
2435 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
2436 	int r;
2437 	u64 val;
2438 
2439 	r = __kvm_x86_dev_get_attr(attr, &val);
2440 	if (r < 0)
2441 		return r;
2442 
2443 	if (put_user(val, uaddr))
2444 		return -EFAULT;
2445 
2446 	return 0;
2447 }
2448 
2449 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
2450 {
2451 	u64 val;
2452 
2453 	return __kvm_x86_dev_get_attr(attr, &val);
2454 }
2455 
2456 long kvm_arch_dev_ioctl(struct file *filp,
2457 			unsigned int ioctl, unsigned long arg)
2458 {
2459 	void __user *argp = (void __user *)arg;
2460 	long r;
2461 
2462 	switch (ioctl) {
2463 	case KVM_GET_MSR_INDEX_LIST:
2464 		r = kvm_get_msr_index_list(argp);
2465 		break;
2466 	case KVM_GET_SUPPORTED_CPUID:
2467 	case KVM_GET_EMULATED_CPUID: {
2468 		struct kvm_cpuid2 __user *cpuid_arg = argp;
2469 		struct kvm_cpuid2 cpuid;
2470 
2471 		r = -EFAULT;
2472 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
2473 			goto out;
2474 
2475 		r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2476 					    ioctl);
2477 		if (r)
2478 			goto out;
2479 
2480 		r = -EFAULT;
2481 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
2482 			goto out;
2483 		r = 0;
2484 		break;
2485 	}
2486 	case KVM_X86_GET_MCE_CAP_SUPPORTED:
2487 		r = -EFAULT;
2488 		if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
2489 				 sizeof(kvm_caps.supported_mce_cap)))
2490 			goto out;
2491 		r = 0;
2492 		break;
2493 	case KVM_GET_MSR_FEATURE_INDEX_LIST:
2494 		r = kvm_get_feature_msr_index_list(argp);
2495 		break;
2496 	case KVM_GET_MSRS:
2497 		r = kvm_get_feature_msrs(argp);
2498 		break;
2499 #ifdef CONFIG_KVM_HYPERV
2500 	case KVM_GET_SUPPORTED_HV_CPUID:
2501 		r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
2502 		break;
2503 #endif
2504 	case KVM_GET_DEVICE_ATTR: {
2505 		struct kvm_device_attr attr;
2506 		r = -EFAULT;
2507 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2508 			break;
2509 		r = kvm_x86_dev_get_attr(&attr);
2510 		break;
2511 	}
2512 	case KVM_HAS_DEVICE_ATTR: {
2513 		struct kvm_device_attr attr;
2514 		r = -EFAULT;
2515 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2516 			break;
2517 		r = kvm_x86_dev_has_attr(&attr);
2518 		break;
2519 	}
2520 	default:
2521 		r = -EINVAL;
2522 		break;
2523 	}
2524 out:
2525 	return r;
2526 }
2527 
2528 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2529 {
2530 	return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2531 }
2532 
2533 static DEFINE_PER_CPU(struct kvm_vcpu *, last_vcpu);
2534 
2535 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2536 {
2537 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
2538 
2539 	kvm_request_l1tf_flush_l1d();
2540 
2541 	if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
2542 		pmu->need_cleanup = true;
2543 		kvm_make_request(KVM_REQ_PMU, vcpu);
2544 	}
2545 
2546 	/* Address WBINVD may be executed by guest */
2547 	if (need_emulate_wbinvd(vcpu)) {
2548 		if (kvm_x86_call(has_wbinvd_exit)())
2549 			cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2550 		else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2551 			wbinvd_on_cpu(vcpu->cpu);
2552 	}
2553 
2554 	kvm_x86_call(vcpu_load)(vcpu, cpu);
2555 
2556 	if (vcpu != per_cpu(last_vcpu, cpu)) {
2557 		/*
2558 		 * Flush the branch predictor when switching vCPUs on the same
2559 		 * physical CPU, as each vCPU needs its own branch prediction
2560 		 * domain.  No IBPB is needed when switching between L1 and L2
2561 		 * on the same vCPU unless IBRS is advertised to the vCPU; that
2562 		 * is handled on the nested VM-Exit path.
2563 		 */
2564 		if (static_branch_likely(&switch_vcpu_ibpb))
2565 			indirect_branch_prediction_barrier();
2566 		per_cpu(last_vcpu, cpu) = vcpu;
2567 	}
2568 
2569 	/* Save host pkru register if supported */
2570 	vcpu->arch.host_pkru = read_pkru();
2571 
2572 	/* Apply any externally detected TSC adjustments (due to suspend) */
2573 	if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2574 		adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2575 		vcpu->arch.tsc_offset_adjustment = 0;
2576 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2577 	}
2578 
2579 	if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
2580 		s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2581 				rdtsc() - vcpu->arch.last_host_tsc;
2582 		if (tsc_delta < 0)
2583 			mark_tsc_unstable("KVM discovered backwards TSC");
2584 
2585 		if (kvm_check_tsc_unstable()) {
2586 			u64 offset = kvm_compute_l1_tsc_offset(vcpu,
2587 						vcpu->arch.last_guest_tsc);
2588 			kvm_vcpu_write_tsc_offset(vcpu, offset);
2589 			if (!vcpu->arch.guest_tsc_protected)
2590 				vcpu->arch.tsc_catchup = 1;
2591 		}
2592 
2593 		if (kvm_lapic_hv_timer_in_use(vcpu))
2594 			kvm_lapic_restart_hv_timer(vcpu);
2595 
2596 		/*
2597 		 * On a host with synchronized TSC, there is no need to update
2598 		 * kvmclock on vcpu->cpu migration
2599 		 */
2600 		if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1) {
2601 			if (__ratelimit(&vcpu->kvm->arch.kvmclock_update_rs))
2602 				kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2603 			else
2604 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2605 		}
2606 
2607 		if (vcpu->cpu != cpu)
2608 			kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
2609 		vcpu->cpu = cpu;
2610 	}
2611 
2612 	kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2613 }
2614 
2615 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
2616 {
2617 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
2618 	struct kvm_steal_time __user *st;
2619 	struct kvm_memslots *slots;
2620 	static const u8 preempted = KVM_VCPU_PREEMPTED;
2621 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
2622 
2623 	/*
2624 	 * The vCPU can be marked preempted if and only if the VM-Exit was on
2625 	 * an instruction boundary and will not trigger guest emulation of any
2626 	 * kind (see vcpu_run).  Vendor specific code controls (conservatively)
2627 	 * when this is true, for example allowing the vCPU to be marked
2628 	 * preempted if and only if the VM-Exit was due to a host interrupt.
2629 	 */
2630 	if (!vcpu->arch.at_instruction_boundary) {
2631 		vcpu->stat.preemption_other++;
2632 		return;
2633 	}
2634 
2635 	vcpu->stat.preemption_reported++;
2636 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2637 		return;
2638 
2639 	if (vcpu->arch.st.preempted)
2640 		return;
2641 
2642 	/* This happens on process exit */
2643 	if (unlikely(current->mm != vcpu->kvm->mm))
2644 		return;
2645 
2646 	slots = kvm_memslots(vcpu->kvm);
2647 
2648 	if (unlikely(slots->generation != ghc->generation ||
2649 		     gpa != ghc->gpa ||
2650 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot))
2651 		return;
2652 
2653 	st = (struct kvm_steal_time __user *)ghc->hva;
2654 	BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
2655 
2656 	if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
2657 		vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
2658 
2659 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
2660 }
2661 
2662 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2663 {
2664 	int idx;
2665 
2666 	if (vcpu->preempted) {
2667 		/*
2668 		 * Assume protected guests are in-kernel.  Inefficient yielding
2669 		 * due to false positives is preferable to never yielding due
2670 		 * to false negatives.
2671 		 */
2672 		vcpu->arch.preempted_in_kernel = vcpu->arch.guest_state_protected ||
2673 						 !kvm_x86_call(get_cpl_no_cache)(vcpu);
2674 
2675 		/*
2676 		 * Take the srcu lock as memslots will be accessed to check the gfn
2677 		 * cache generation against the memslots generation.
2678 		 */
2679 		idx = srcu_read_lock(&vcpu->kvm->srcu);
2680 		if (kvm_xen_msr_enabled(vcpu->kvm))
2681 			kvm_xen_runstate_set_preempted(vcpu);
2682 		else
2683 			kvm_steal_time_set_preempted(vcpu);
2684 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
2685 	}
2686 
2687 	kvm_x86_call(vcpu_put)(vcpu);
2688 	vcpu->arch.last_host_tsc = rdtsc();
2689 }
2690 
2691 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2692 				    struct kvm_lapic_state *s)
2693 {
2694 	if (vcpu->arch.apic->guest_apic_protected)
2695 		return -EINVAL;
2696 
2697 	kvm_x86_call(sync_pir_to_irr)(vcpu);
2698 
2699 	return kvm_apic_get_state(vcpu, s);
2700 }
2701 
2702 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2703 				    struct kvm_lapic_state *s)
2704 {
2705 	int r;
2706 
2707 	if (vcpu->arch.apic->guest_apic_protected)
2708 		return -EINVAL;
2709 
2710 	r = kvm_apic_set_state(vcpu, s);
2711 	if (r)
2712 		return r;
2713 
2714 	return 0;
2715 }
2716 
2717 static bool kvm_is_interrupt_allowed(struct kvm_vcpu *vcpu)
2718 {
2719 	/*
2720 	 * Note, .interrupt_allowed() returns -EBUSY if interrupts are allowed
2721 	 * based on CPU state, but can't be immediately delivered due to a
2722 	 * pending nested VM-Enter.  Treat that case as "allowed", because
2723 	 * the goal here is just to check if interrupts are architecturally
2724 	 * allowed, not to check if they can be injected.
2725 	 */
2726 	return kvm_x86_call(interrupt_allowed)(vcpu, false);
2727 }
2728 
2729 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
2730 {
2731 	/*
2732 	 * We can accept userspace's request for interrupt injection
2733 	 * as long as we have a place to store the interrupt number.
2734 	 * The actual injection will happen when the CPU is able to
2735 	 * deliver the interrupt.
2736 	 */
2737 	if (kvm_cpu_has_extint(vcpu))
2738 		return false;
2739 
2740 	/* Acknowledging ExtINT does not happen if LINT0 is masked.  */
2741 	return (!lapic_in_kernel(vcpu) ||
2742 		kvm_apic_accept_pic_intr(vcpu));
2743 }
2744 
2745 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
2746 {
2747 	/*
2748 	 * Do not cause an interrupt window exit if an exception
2749 	 * is pending or an event needs reinjection; userspace
2750 	 * might want to inject the interrupt manually using KVM_SET_REGS
2751 	 * or KVM_SET_SREGS.  For that to work, we must be at an
2752 	 * instruction boundary and with no events half-injected.
2753 	 */
2754 	return (kvm_is_interrupt_allowed(vcpu) &&
2755 		kvm_cpu_accept_dm_intr(vcpu) &&
2756 		!kvm_event_needs_reinjection(vcpu) &&
2757 		!kvm_is_exception_pending(vcpu));
2758 }
2759 
2760 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2761 				    struct kvm_interrupt *irq)
2762 {
2763 	if (irq->irq >= KVM_NR_INTERRUPTS)
2764 		return -EINVAL;
2765 
2766 	if (!irqchip_in_kernel(vcpu->kvm)) {
2767 		kvm_queue_interrupt(vcpu, irq->irq, false);
2768 		kvm_make_request(KVM_REQ_EVENT, vcpu);
2769 		return 0;
2770 	}
2771 
2772 	/*
2773 	 * With in-kernel LAPIC, we only use this to inject EXTINT, so
2774 	 * fail for in-kernel 8259.
2775 	 */
2776 	if (pic_in_kernel(vcpu->kvm))
2777 		return -ENXIO;
2778 
2779 	if (vcpu->arch.pending_external_vector != -1)
2780 		return -EEXIST;
2781 
2782 	vcpu->arch.pending_external_vector = irq->irq;
2783 	kvm_make_request(KVM_REQ_EVENT, vcpu);
2784 	return 0;
2785 }
2786 
2787 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2788 {
2789 	kvm_inject_nmi(vcpu);
2790 
2791 	return 0;
2792 }
2793 
2794 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2795 					   struct kvm_tpr_access_ctl *tac)
2796 {
2797 	if (tac->flags)
2798 		return -EINVAL;
2799 	vcpu->arch.tpr_access_reporting = !!tac->enabled;
2800 	return 0;
2801 }
2802 
2803 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2804 					u64 mcg_cap)
2805 {
2806 	int r;
2807 	unsigned bank_num = mcg_cap & 0xff, bank;
2808 
2809 	r = -EINVAL;
2810 	if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
2811 		goto out;
2812 	if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
2813 		goto out;
2814 	r = 0;
2815 	vcpu->arch.mcg_cap = mcg_cap;
2816 	/* Init IA32_MCG_CTL to all 1s */
2817 	if (mcg_cap & MCG_CTL_P)
2818 		vcpu->arch.mcg_ctl = ~(u64)0;
2819 	/* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
2820 	for (bank = 0; bank < bank_num; bank++) {
2821 		vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2822 		if (mcg_cap & MCG_CMCI_P)
2823 			vcpu->arch.mci_ctl2_banks[bank] = 0;
2824 	}
2825 
2826 	kvm_apic_after_set_mcg_cap(vcpu);
2827 
2828 	kvm_x86_call(setup_mce)(vcpu);
2829 out:
2830 	return r;
2831 }
2832 
2833 /*
2834  * Validate this is an UCNA (uncorrectable no action) error by checking the
2835  * MCG_STATUS and MCi_STATUS registers:
2836  * - none of the bits for Machine Check Exceptions are set
2837  * - both the VAL (valid) and UC (uncorrectable) bits are set
2838  * MCI_STATUS_PCC - Processor Context Corrupted
2839  * MCI_STATUS_S - Signaled as a Machine Check Exception
2840  * MCI_STATUS_AR - Software recoverable Action Required
2841  */
2842 static bool is_ucna(struct kvm_x86_mce *mce)
2843 {
2844 	return	!mce->mcg_status &&
2845 		!(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
2846 		(mce->status & MCI_STATUS_VAL) &&
2847 		(mce->status & MCI_STATUS_UC);
2848 }
2849 
2850 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
2851 {
2852 	u64 mcg_cap = vcpu->arch.mcg_cap;
2853 
2854 	banks[1] = mce->status;
2855 	banks[2] = mce->addr;
2856 	banks[3] = mce->misc;
2857 	vcpu->arch.mcg_status = mce->mcg_status;
2858 
2859 	if (!(mcg_cap & MCG_CMCI_P) ||
2860 	    !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
2861 		return 0;
2862 
2863 	if (lapic_in_kernel(vcpu))
2864 		kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
2865 
2866 	return 0;
2867 }
2868 
2869 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2870 				      struct kvm_x86_mce *mce)
2871 {
2872 	u64 mcg_cap = vcpu->arch.mcg_cap;
2873 	unsigned bank_num = mcg_cap & 0xff;
2874 	u64 *banks = vcpu->arch.mce_banks;
2875 
2876 	if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2877 		return -EINVAL;
2878 
2879 	mce->bank = array_index_nospec(mce->bank, bank_num);
2880 	banks += 4 * mce->bank;
2881 
2882 	if (is_ucna(mce))
2883 		return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
2884 
2885 	/*
2886 	 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2887 	 * reporting is disabled
2888 	 */
2889 	if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2890 	    vcpu->arch.mcg_ctl != ~(u64)0)
2891 		return 0;
2892 	/*
2893 	 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2894 	 * reporting is disabled for the bank
2895 	 */
2896 	if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2897 		return 0;
2898 	if (mce->status & MCI_STATUS_UC) {
2899 		if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2900 		    !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
2901 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2902 			return 0;
2903 		}
2904 		if (banks[1] & MCI_STATUS_VAL)
2905 			mce->status |= MCI_STATUS_OVER;
2906 		banks[2] = mce->addr;
2907 		banks[3] = mce->misc;
2908 		vcpu->arch.mcg_status = mce->mcg_status;
2909 		banks[1] = mce->status;
2910 		kvm_queue_exception(vcpu, MC_VECTOR);
2911 	} else if (!(banks[1] & MCI_STATUS_VAL)
2912 		   || !(banks[1] & MCI_STATUS_UC)) {
2913 		if (banks[1] & MCI_STATUS_VAL)
2914 			mce->status |= MCI_STATUS_OVER;
2915 		banks[2] = mce->addr;
2916 		banks[3] = mce->misc;
2917 		banks[1] = mce->status;
2918 	} else
2919 		banks[1] |= MCI_STATUS_OVER;
2920 	return 0;
2921 }
2922 
2923 static struct kvm_queued_exception *kvm_get_exception_to_save(struct kvm_vcpu *vcpu)
2924 {
2925 	/*
2926 	 * KVM's ABI only allows for one exception to be migrated.  Luckily,
2927 	 * the only time there can be two queued exceptions is if there's a
2928 	 * non-exiting _injected_ exception, and a pending exiting exception.
2929 	 * In that case, ignore the VM-Exiting exception as it's an extension
2930 	 * of the injected exception.
2931 	 */
2932 	if (vcpu->arch.exception_vmexit.pending &&
2933 	    !vcpu->arch.exception.pending &&
2934 	    !vcpu->arch.exception.injected)
2935 		return &vcpu->arch.exception_vmexit;
2936 
2937 	return &vcpu->arch.exception;
2938 }
2939 
2940 void kvm_handle_exception_payload_quirk(struct kvm_vcpu *vcpu)
2941 {
2942 	struct kvm_queued_exception *ex = kvm_get_exception_to_save(vcpu);
2943 
2944 	/*
2945 	 * If KVM_CAP_EXCEPTION_PAYLOAD is disabled, then (prematurely) deliver
2946 	 * the pending exception payload when userspace saves *any* vCPU state
2947 	 * that interacts with exception payloads to avoid breaking userspace.
2948 	 *
2949 	 * Architecturally, KVM must not deliver an exception payload until the
2950 	 * exception is actually injected, e.g. to avoid losing pending #DB
2951 	 * information (which VMX tracks in the VMCS), and to avoid clobbering
2952 	 * state if the exception is never injected for whatever reason.  But
2953 	 * if KVM_CAP_EXCEPTION_PAYLOAD isn't enabled, then userspace may or
2954 	 * may not propagate the payload across save+restore, and so KVM can't
2955 	 * safely defer delivery of the payload.
2956 	 */
2957 	if (!vcpu->kvm->arch.exception_payload_enabled &&
2958 	    ex->pending && ex->has_payload)
2959 		kvm_deliver_exception_payload(vcpu, ex);
2960 }
2961 
2962 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2963 					       struct kvm_vcpu_events *events)
2964 {
2965 	struct kvm_queued_exception *ex = kvm_get_exception_to_save(vcpu);
2966 
2967 	process_nmi(vcpu);
2968 
2969 #ifdef CONFIG_KVM_SMM
2970 	if (kvm_check_request(KVM_REQ_SMI, vcpu))
2971 		process_smi(vcpu);
2972 #endif
2973 
2974 	kvm_handle_exception_payload_quirk(vcpu);
2975 
2976 	memset(events, 0, sizeof(*events));
2977 
2978 	/*
2979 	 * The API doesn't provide the instruction length for software
2980 	 * exceptions, so don't report them. As long as the guest RIP
2981 	 * isn't advanced, we should expect to encounter the exception
2982 	 * again.
2983 	 */
2984 	if (!kvm_exception_is_soft(ex->vector)) {
2985 		events->exception.injected = ex->injected;
2986 		events->exception.pending = ex->pending;
2987 		/*
2988 		 * For ABI compatibility, deliberately conflate
2989 		 * pending and injected exceptions when
2990 		 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
2991 		 */
2992 		if (!vcpu->kvm->arch.exception_payload_enabled)
2993 			events->exception.injected |= ex->pending;
2994 	}
2995 	events->exception.nr = ex->vector;
2996 	events->exception.has_error_code = ex->has_error_code;
2997 	events->exception.error_code = ex->error_code;
2998 	events->exception_has_payload = ex->has_payload;
2999 	events->exception_payload = ex->payload;
3000 
3001 	events->interrupt.injected =
3002 		vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3003 	events->interrupt.nr = vcpu->arch.interrupt.nr;
3004 	events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
3005 
3006 	events->nmi.injected = vcpu->arch.nmi_injected;
3007 	events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
3008 	events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
3009 
3010 	/* events->sipi_vector is never valid when reporting to user space */
3011 
3012 #ifdef CONFIG_KVM_SMM
3013 	events->smi.smm = is_smm(vcpu);
3014 	events->smi.pending = vcpu->arch.smi_pending;
3015 	events->smi.smm_inside_nmi =
3016 		!!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3017 #endif
3018 	events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3019 
3020 	events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3021 			 | KVM_VCPUEVENT_VALID_SHADOW
3022 			 | KVM_VCPUEVENT_VALID_SMM);
3023 	if (vcpu->kvm->arch.exception_payload_enabled)
3024 		events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3025 	if (vcpu->kvm->arch.triple_fault_event) {
3026 		events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3027 		events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
3028 	}
3029 }
3030 
3031 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3032 					      struct kvm_vcpu_events *events)
3033 {
3034 	if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3035 			      | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3036 			      | KVM_VCPUEVENT_VALID_SHADOW
3037 			      | KVM_VCPUEVENT_VALID_SMM
3038 			      | KVM_VCPUEVENT_VALID_PAYLOAD
3039 			      | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
3040 		return -EINVAL;
3041 
3042 	if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3043 		if (!vcpu->kvm->arch.exception_payload_enabled)
3044 			return -EINVAL;
3045 		if (events->exception.pending)
3046 			events->exception.injected = 0;
3047 		else
3048 			events->exception_has_payload = 0;
3049 	} else {
3050 		events->exception.pending = 0;
3051 		events->exception_has_payload = 0;
3052 	}
3053 
3054 	if ((events->exception.injected || events->exception.pending) &&
3055 	    (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3056 		return -EINVAL;
3057 
3058 	process_nmi(vcpu);
3059 
3060 	/*
3061 	 * Flag that userspace is stuffing an exception, the next KVM_RUN will
3062 	 * morph the exception to a VM-Exit if appropriate.  Do this only for
3063 	 * pending exceptions, already-injected exceptions are not subject to
3064 	 * intercpetion.  Note, userspace that conflates pending and injected
3065 	 * is hosed, and will incorrectly convert an injected exception into a
3066 	 * pending exception, which in turn may cause a spurious VM-Exit.
3067 	 */
3068 	vcpu->arch.exception_from_userspace = events->exception.pending;
3069 
3070 	vcpu->arch.exception_vmexit.pending = false;
3071 
3072 	vcpu->arch.exception.injected = events->exception.injected;
3073 	vcpu->arch.exception.pending = events->exception.pending;
3074 	vcpu->arch.exception.vector = events->exception.nr;
3075 	vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3076 	vcpu->arch.exception.error_code = events->exception.error_code;
3077 	vcpu->arch.exception.has_payload = events->exception_has_payload;
3078 	vcpu->arch.exception.payload = events->exception_payload;
3079 
3080 	vcpu->arch.interrupt.injected = events->interrupt.injected;
3081 	vcpu->arch.interrupt.nr = events->interrupt.nr;
3082 	vcpu->arch.interrupt.soft = events->interrupt.soft;
3083 	if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3084 		kvm_x86_call(set_interrupt_shadow)(vcpu,
3085 						   events->interrupt.shadow);
3086 
3087 	vcpu->arch.nmi_injected = events->nmi.injected;
3088 	if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
3089 		vcpu->arch.nmi_pending = 0;
3090 		atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
3091 		if (events->nmi.pending)
3092 			kvm_make_request(KVM_REQ_NMI, vcpu);
3093 	}
3094 	kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
3095 
3096 	if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3097 	    lapic_in_kernel(vcpu))
3098 		vcpu->arch.apic->sipi_vector = events->sipi_vector;
3099 
3100 	if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3101 #ifdef CONFIG_KVM_SMM
3102 		if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
3103 			kvm_leave_nested(vcpu);
3104 			kvm_smm_changed(vcpu, events->smi.smm);
3105 		}
3106 
3107 		vcpu->arch.smi_pending = events->smi.pending;
3108 
3109 		if (events->smi.smm) {
3110 			if (events->smi.smm_inside_nmi)
3111 				vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3112 			else
3113 				vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3114 		}
3115 
3116 #else
3117 		if (events->smi.smm || events->smi.pending ||
3118 		    events->smi.smm_inside_nmi)
3119 			return -EINVAL;
3120 #endif
3121 
3122 		if (lapic_in_kernel(vcpu)) {
3123 			if (events->smi.latched_init)
3124 				set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3125 			else
3126 				clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3127 		}
3128 	}
3129 
3130 	if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
3131 		if (!vcpu->kvm->arch.triple_fault_event)
3132 			return -EINVAL;
3133 		if (events->triple_fault.pending)
3134 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3135 		else
3136 			kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3137 	}
3138 
3139 	kvm_make_request(KVM_REQ_EVENT, vcpu);
3140 
3141 	return 0;
3142 }
3143 
3144 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
3145 					 u8 *state, unsigned int size)
3146 {
3147 	/*
3148 	 * Only copy state for features that are enabled for the guest.  The
3149 	 * state itself isn't problematic, but setting bits in the header for
3150 	 * features that are supported in *this* host but not exposed to the
3151 	 * guest can result in KVM_SET_XSAVE failing when live migrating to a
3152 	 * compatible host without the features that are NOT exposed to the
3153 	 * guest.
3154 	 *
3155 	 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
3156 	 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
3157 	 * supported by the host.
3158 	 */
3159 	u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
3160 			     XFEATURE_MASK_FPSSE;
3161 
3162 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
3163 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
3164 
3165 	fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
3166 				       supported_xcr0, vcpu->arch.pkru);
3167 	return 0;
3168 }
3169 
3170 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3171 					struct kvm_xsave *guest_xsave)
3172 {
3173 	return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
3174 					     sizeof(guest_xsave->region));
3175 }
3176 
3177 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3178 					struct kvm_xsave *guest_xsave)
3179 {
3180 	union fpregs_state *xstate = (union fpregs_state *)guest_xsave->region;
3181 
3182 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
3183 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
3184 
3185 	/*
3186 	 * For backwards compatibility, do not expect disabled features to be in
3187 	 * their initial state.  XSTATE_BV[i] must still be cleared whenever
3188 	 * XFD[i]=1, or XRSTOR would cause a #NM.
3189 	 */
3190 	xstate->xsave.header.xfeatures &= ~vcpu->arch.guest_fpu.fpstate->xfd;
3191 
3192 	return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
3193 					      guest_xsave->region,
3194 					      kvm_caps.supported_xcr0,
3195 					      &vcpu->arch.pkru);
3196 }
3197 
3198 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3199 				       struct kvm_xcrs *guest_xcrs)
3200 {
3201 	if (vcpu->kvm->arch.has_protected_state &&
3202 	    vcpu->arch.guest_state_protected)
3203 		return -EINVAL;
3204 
3205 	if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
3206 		guest_xcrs->nr_xcrs = 0;
3207 		return 0;
3208 	}
3209 
3210 	guest_xcrs->nr_xcrs = 1;
3211 	guest_xcrs->flags = 0;
3212 	guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3213 	guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3214 	return 0;
3215 }
3216 
3217 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3218 				       struct kvm_xcrs *guest_xcrs)
3219 {
3220 	int i, r = 0;
3221 
3222 	if (vcpu->kvm->arch.has_protected_state &&
3223 	    vcpu->arch.guest_state_protected)
3224 		return -EINVAL;
3225 
3226 	if (!boot_cpu_has(X86_FEATURE_XSAVE))
3227 		return -EINVAL;
3228 
3229 	if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3230 		return -EINVAL;
3231 
3232 	for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3233 		/* Only support XCR0 currently */
3234 		if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3235 			r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3236 				guest_xcrs->xcrs[i].value);
3237 			break;
3238 		}
3239 	if (r)
3240 		r = -EINVAL;
3241 	return r;
3242 }
3243 
3244 /*
3245  * kvm_set_guest_paused() indicates to the guest kernel that it has been
3246  * stopped by the hypervisor.  This function will be called from the host only.
3247  * EINVAL is returned when the host attempts to set the flag for a guest that
3248  * does not support pv clocks.
3249  */
3250 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3251 {
3252 	if (!vcpu->arch.pv_time.active)
3253 		return -EINVAL;
3254 	vcpu->arch.pvclock_set_guest_stopped_request = true;
3255 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3256 	return 0;
3257 }
3258 
3259 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
3260 				 struct kvm_device_attr *attr)
3261 {
3262 	int r;
3263 
3264 	switch (attr->attr) {
3265 	case KVM_VCPU_TSC_OFFSET:
3266 		r = 0;
3267 		break;
3268 	default:
3269 		r = -ENXIO;
3270 	}
3271 
3272 	return r;
3273 }
3274 
3275 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
3276 				 struct kvm_device_attr *attr)
3277 {
3278 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
3279 	int r;
3280 
3281 	switch (attr->attr) {
3282 	case KVM_VCPU_TSC_OFFSET:
3283 		r = -EFAULT;
3284 		if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
3285 			break;
3286 		r = 0;
3287 		break;
3288 	default:
3289 		r = -ENXIO;
3290 	}
3291 
3292 	return r;
3293 }
3294 
3295 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
3296 				 struct kvm_device_attr *attr)
3297 {
3298 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
3299 	struct kvm *kvm = vcpu->kvm;
3300 	int r;
3301 
3302 	switch (attr->attr) {
3303 	case KVM_VCPU_TSC_OFFSET: {
3304 		u64 offset, tsc, ns;
3305 		unsigned long flags;
3306 		bool matched;
3307 
3308 		r = -EFAULT;
3309 		if (get_user(offset, uaddr))
3310 			break;
3311 
3312 		raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
3313 
3314 		matched = (vcpu->arch.virtual_tsc_khz &&
3315 			   kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
3316 			   kvm->arch.last_tsc_offset == offset);
3317 
3318 		tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
3319 		ns = get_kvmclock_base_ns();
3320 
3321 		__kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched, true);
3322 		raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
3323 
3324 		r = 0;
3325 		break;
3326 	}
3327 	default:
3328 		r = -ENXIO;
3329 	}
3330 
3331 	return r;
3332 }
3333 
3334 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
3335 				      unsigned int ioctl,
3336 				      void __user *argp)
3337 {
3338 	struct kvm_device_attr attr;
3339 	int r;
3340 
3341 	if (copy_from_user(&attr, argp, sizeof(attr)))
3342 		return -EFAULT;
3343 
3344 	if (attr.group != KVM_VCPU_TSC_CTRL)
3345 		return -ENXIO;
3346 
3347 	switch (ioctl) {
3348 	case KVM_HAS_DEVICE_ATTR:
3349 		r = kvm_arch_tsc_has_attr(vcpu, &attr);
3350 		break;
3351 	case KVM_GET_DEVICE_ATTR:
3352 		r = kvm_arch_tsc_get_attr(vcpu, &attr);
3353 		break;
3354 	case KVM_SET_DEVICE_ATTR:
3355 		r = kvm_arch_tsc_set_attr(vcpu, &attr);
3356 		break;
3357 	}
3358 
3359 	return r;
3360 }
3361 
3362 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3363 				     struct kvm_enable_cap *cap)
3364 {
3365 	if (cap->flags)
3366 		return -EINVAL;
3367 
3368 	switch (cap->cap) {
3369 #ifdef CONFIG_KVM_HYPERV
3370 	case KVM_CAP_HYPERV_SYNIC2:
3371 		if (cap->args[0])
3372 			return -EINVAL;
3373 		fallthrough;
3374 
3375 	case KVM_CAP_HYPERV_SYNIC:
3376 		if (!irqchip_in_kernel(vcpu->kvm))
3377 			return -EINVAL;
3378 		return kvm_hv_activate_synic(vcpu, cap->cap ==
3379 					     KVM_CAP_HYPERV_SYNIC2);
3380 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3381 		{
3382 			int r;
3383 			uint16_t vmcs_version;
3384 			void __user *user_ptr;
3385 
3386 			if (!kvm_nested_ops.enabled ||
3387 			    !kvm_nested_ops.enable_evmcs)
3388 				return -ENOTTY;
3389 			r = kvm_nested_call(enable_evmcs)(vcpu, &vmcs_version);
3390 			if (!r) {
3391 				user_ptr = (void __user *)(uintptr_t)cap->args[0];
3392 				if (copy_to_user(user_ptr, &vmcs_version,
3393 						 sizeof(vmcs_version)))
3394 					r = -EFAULT;
3395 			}
3396 			return r;
3397 		}
3398 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3399 		if (!kvm_x86_ops.enable_l2_tlb_flush)
3400 			return -ENOTTY;
3401 
3402 		return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
3403 
3404 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
3405 		return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
3406 #endif
3407 
3408 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
3409 		vcpu->arch.pv_cpuid.enforce = cap->args[0];
3410 		return 0;
3411 	default:
3412 		return -EINVAL;
3413 	}
3414 }
3415 
3416 long kvm_arch_vcpu_ioctl(struct file *filp,
3417 			 unsigned int ioctl, unsigned long arg)
3418 {
3419 	struct kvm_vcpu *vcpu = filp->private_data;
3420 	void __user *argp = (void __user *)arg;
3421 	int r;
3422 	union {
3423 		struct kvm_sregs2 *sregs2;
3424 		struct kvm_lapic_state *lapic;
3425 		struct kvm_xsave *xsave;
3426 		struct kvm_xcrs *xcrs;
3427 		void *buffer;
3428 	} u;
3429 
3430 	vcpu_load(vcpu);
3431 
3432 	u.buffer = NULL;
3433 	switch (ioctl) {
3434 	case KVM_GET_LAPIC: {
3435 		r = -EINVAL;
3436 		if (!lapic_in_kernel(vcpu))
3437 			goto out;
3438 		u.lapic = kzalloc_obj(struct kvm_lapic_state);
3439 
3440 		r = -ENOMEM;
3441 		if (!u.lapic)
3442 			goto out;
3443 		r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3444 		if (r)
3445 			goto out;
3446 		r = -EFAULT;
3447 		if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3448 			goto out;
3449 		r = 0;
3450 		break;
3451 	}
3452 	case KVM_SET_LAPIC: {
3453 		r = -EINVAL;
3454 		if (!lapic_in_kernel(vcpu))
3455 			goto out;
3456 		u.lapic = memdup_user(argp, sizeof(*u.lapic));
3457 		if (IS_ERR(u.lapic)) {
3458 			r = PTR_ERR(u.lapic);
3459 			goto out_nofree;
3460 		}
3461 
3462 		r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3463 		break;
3464 	}
3465 	case KVM_INTERRUPT: {
3466 		struct kvm_interrupt irq;
3467 
3468 		r = -EFAULT;
3469 		if (copy_from_user(&irq, argp, sizeof(irq)))
3470 			goto out;
3471 		r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3472 		break;
3473 	}
3474 	case KVM_NMI: {
3475 		r = kvm_vcpu_ioctl_nmi(vcpu);
3476 		break;
3477 	}
3478 	case KVM_SMI: {
3479 		r = kvm_inject_smi(vcpu);
3480 		break;
3481 	}
3482 	case KVM_SET_CPUID: {
3483 		struct kvm_cpuid __user *cpuid_arg = argp;
3484 		struct kvm_cpuid cpuid;
3485 
3486 		r = -EFAULT;
3487 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3488 			goto out;
3489 		r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3490 		break;
3491 	}
3492 	case KVM_SET_CPUID2: {
3493 		struct kvm_cpuid2 __user *cpuid_arg = argp;
3494 		struct kvm_cpuid2 cpuid;
3495 
3496 		r = -EFAULT;
3497 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3498 			goto out;
3499 		r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3500 					      cpuid_arg->entries);
3501 		break;
3502 	}
3503 	case KVM_GET_CPUID2: {
3504 		struct kvm_cpuid2 __user *cpuid_arg = argp;
3505 		struct kvm_cpuid2 cpuid;
3506 
3507 		r = -EFAULT;
3508 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3509 			goto out;
3510 		r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3511 					      cpuid_arg->entries);
3512 		if (r)
3513 			goto out;
3514 		r = -EFAULT;
3515 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3516 			goto out;
3517 		r = 0;
3518 		break;
3519 	}
3520 	case KVM_GET_MSRS:
3521 		r = kvm_get_msrs(vcpu, argp);
3522 		break;
3523 	case KVM_SET_MSRS:
3524 		r = kvm_set_msrs(vcpu, argp);
3525 		break;
3526 	case KVM_GET_ONE_REG:
3527 	case KVM_SET_ONE_REG:
3528 		r = kvm_get_set_one_reg(vcpu, ioctl, argp);
3529 		break;
3530 	case KVM_GET_REG_LIST:
3531 		r = kvm_get_reg_list(vcpu, argp);
3532 		break;
3533 	case KVM_TPR_ACCESS_REPORTING: {
3534 		struct kvm_tpr_access_ctl tac;
3535 
3536 		r = -EFAULT;
3537 		if (copy_from_user(&tac, argp, sizeof(tac)))
3538 			goto out;
3539 		r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3540 		if (r)
3541 			goto out;
3542 		r = -EFAULT;
3543 		if (copy_to_user(argp, &tac, sizeof(tac)))
3544 			goto out;
3545 		r = 0;
3546 		break;
3547 	};
3548 	case KVM_SET_VAPIC_ADDR: {
3549 		struct kvm_vapic_addr va;
3550 		int idx;
3551 
3552 		r = -EINVAL;
3553 		if (!lapic_in_kernel(vcpu))
3554 			goto out;
3555 		r = -EFAULT;
3556 		if (copy_from_user(&va, argp, sizeof(va)))
3557 			goto out;
3558 		idx = srcu_read_lock(&vcpu->kvm->srcu);
3559 		r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3560 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
3561 		break;
3562 	}
3563 	case KVM_X86_SETUP_MCE: {
3564 		u64 mcg_cap;
3565 
3566 		r = -EFAULT;
3567 		if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
3568 			goto out;
3569 		r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3570 		break;
3571 	}
3572 	case KVM_X86_SET_MCE: {
3573 		struct kvm_x86_mce mce;
3574 
3575 		r = -EFAULT;
3576 		if (copy_from_user(&mce, argp, sizeof(mce)))
3577 			goto out;
3578 		r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3579 		break;
3580 	}
3581 	case KVM_GET_VCPU_EVENTS: {
3582 		struct kvm_vcpu_events events;
3583 
3584 		kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3585 
3586 		r = -EFAULT;
3587 		if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3588 			break;
3589 		r = 0;
3590 		break;
3591 	}
3592 	case KVM_SET_VCPU_EVENTS: {
3593 		struct kvm_vcpu_events events;
3594 
3595 		r = -EFAULT;
3596 		if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3597 			break;
3598 
3599 		kvm_vcpu_srcu_read_lock(vcpu);
3600 		r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3601 		kvm_vcpu_srcu_read_unlock(vcpu);
3602 		break;
3603 	}
3604 	case KVM_GET_DEBUGREGS: {
3605 		struct kvm_debugregs dbgregs;
3606 
3607 		r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3608 		if (r < 0)
3609 			break;
3610 
3611 		r = -EFAULT;
3612 		if (copy_to_user(argp, &dbgregs,
3613 				 sizeof(struct kvm_debugregs)))
3614 			break;
3615 		r = 0;
3616 		break;
3617 	}
3618 	case KVM_SET_DEBUGREGS: {
3619 		struct kvm_debugregs dbgregs;
3620 
3621 		r = -EFAULT;
3622 		if (copy_from_user(&dbgregs, argp,
3623 				   sizeof(struct kvm_debugregs)))
3624 			break;
3625 
3626 		r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3627 		break;
3628 	}
3629 	case KVM_GET_XSAVE: {
3630 		r = -EINVAL;
3631 		if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
3632 			break;
3633 
3634 		u.xsave = kzalloc_obj(struct kvm_xsave);
3635 		r = -ENOMEM;
3636 		if (!u.xsave)
3637 			break;
3638 
3639 		r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3640 		if (r < 0)
3641 			break;
3642 
3643 		r = -EFAULT;
3644 		if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3645 			break;
3646 		r = 0;
3647 		break;
3648 	}
3649 	case KVM_SET_XSAVE: {
3650 		int size = vcpu->arch.guest_fpu.uabi_size;
3651 
3652 		u.xsave = memdup_user(argp, size);
3653 		if (IS_ERR(u.xsave)) {
3654 			r = PTR_ERR(u.xsave);
3655 			goto out_nofree;
3656 		}
3657 
3658 		r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3659 		break;
3660 	}
3661 
3662 	case KVM_GET_XSAVE2: {
3663 		int size = vcpu->arch.guest_fpu.uabi_size;
3664 
3665 		u.xsave = kzalloc(size, GFP_KERNEL);
3666 		r = -ENOMEM;
3667 		if (!u.xsave)
3668 			break;
3669 
3670 		r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
3671 		if (r < 0)
3672 			break;
3673 
3674 		r = -EFAULT;
3675 		if (copy_to_user(argp, u.xsave, size))
3676 			break;
3677 
3678 		r = 0;
3679 		break;
3680 	}
3681 
3682 	case KVM_GET_XCRS: {
3683 		u.xcrs = kzalloc_obj(struct kvm_xcrs);
3684 		r = -ENOMEM;
3685 		if (!u.xcrs)
3686 			break;
3687 
3688 		r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3689 		if (r < 0)
3690 			break;
3691 
3692 		r = -EFAULT;
3693 		if (copy_to_user(argp, u.xcrs,
3694 				 sizeof(struct kvm_xcrs)))
3695 			break;
3696 		r = 0;
3697 		break;
3698 	}
3699 	case KVM_SET_XCRS: {
3700 		u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3701 		if (IS_ERR(u.xcrs)) {
3702 			r = PTR_ERR(u.xcrs);
3703 			goto out_nofree;
3704 		}
3705 
3706 		r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3707 		break;
3708 	}
3709 	case KVM_SET_TSC_KHZ: {
3710 		u32 user_tsc_khz;
3711 
3712 		r = -EINVAL;
3713 
3714 		if (vcpu->arch.guest_tsc_protected)
3715 			goto out;
3716 
3717 		user_tsc_khz = (u32)arg;
3718 
3719 		if (kvm_caps.has_tsc_control &&
3720 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
3721 			goto out;
3722 
3723 		if (user_tsc_khz == 0)
3724 			user_tsc_khz = tsc_khz;
3725 
3726 		if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3727 			r = 0;
3728 
3729 		goto out;
3730 	}
3731 	case KVM_GET_TSC_KHZ: {
3732 		r = vcpu->arch.virtual_tsc_khz;
3733 		goto out;
3734 	}
3735 	case KVM_KVMCLOCK_CTRL: {
3736 		r = kvm_set_guest_paused(vcpu);
3737 		goto out;
3738 	}
3739 	case KVM_ENABLE_CAP: {
3740 		struct kvm_enable_cap cap;
3741 
3742 		r = -EFAULT;
3743 		if (copy_from_user(&cap, argp, sizeof(cap)))
3744 			goto out;
3745 		r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
3746 		break;
3747 	}
3748 	case KVM_GET_NESTED_STATE: {
3749 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
3750 		u32 user_data_size;
3751 
3752 		r = -EINVAL;
3753 		if (!kvm_nested_ops.enabled)
3754 			break;
3755 
3756 		BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
3757 		r = -EFAULT;
3758 		if (get_user(user_data_size, &user_kvm_nested_state->size))
3759 			break;
3760 
3761 		r = kvm_nested_call(get_state)(vcpu, user_kvm_nested_state, user_data_size);
3762 		if (r < 0)
3763 			break;
3764 
3765 		if (r > user_data_size) {
3766 			if (put_user(r, &user_kvm_nested_state->size))
3767 				r = -EFAULT;
3768 			else
3769 				r = -E2BIG;
3770 			break;
3771 		}
3772 
3773 		r = 0;
3774 		break;
3775 	}
3776 	case KVM_SET_NESTED_STATE: {
3777 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
3778 		struct kvm_nested_state kvm_state;
3779 		int idx;
3780 
3781 		r = -EINVAL;
3782 		if (!kvm_nested_ops.enabled)
3783 			break;
3784 
3785 		r = -EFAULT;
3786 		if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
3787 			break;
3788 
3789 		r = -EINVAL;
3790 		if (kvm_state.size < sizeof(kvm_state))
3791 			break;
3792 
3793 		if (kvm_state.flags &
3794 		    ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
3795 		      | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
3796 		      | KVM_STATE_NESTED_GIF_SET))
3797 			break;
3798 
3799 		/* nested_run_pending implies guest_mode.  */
3800 		if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
3801 		    && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
3802 			break;
3803 
3804 		idx = srcu_read_lock(&vcpu->kvm->srcu);
3805 		r = kvm_nested_call(set_state)(vcpu, user_kvm_nested_state, &kvm_state);
3806 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
3807 		break;
3808 	}
3809 #ifdef CONFIG_KVM_HYPERV
3810 	case KVM_GET_SUPPORTED_HV_CPUID:
3811 		r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
3812 		break;
3813 #endif
3814 #ifdef CONFIG_KVM_XEN
3815 	case KVM_XEN_VCPU_GET_ATTR: {
3816 		struct kvm_xen_vcpu_attr xva;
3817 
3818 		r = -EFAULT;
3819 		if (copy_from_user(&xva, argp, sizeof(xva)))
3820 			goto out;
3821 		r = kvm_xen_vcpu_get_attr(vcpu, &xva);
3822 		if (!r && copy_to_user(argp, &xva, sizeof(xva)))
3823 			r = -EFAULT;
3824 		break;
3825 	}
3826 	case KVM_XEN_VCPU_SET_ATTR: {
3827 		struct kvm_xen_vcpu_attr xva;
3828 
3829 		r = -EFAULT;
3830 		if (copy_from_user(&xva, argp, sizeof(xva)))
3831 			goto out;
3832 		r = kvm_xen_vcpu_set_attr(vcpu, &xva);
3833 		break;
3834 	}
3835 #endif
3836 	case KVM_GET_SREGS2: {
3837 		r = -EINVAL;
3838 		if (vcpu->kvm->arch.has_protected_state &&
3839 		    vcpu->arch.guest_state_protected)
3840 			goto out;
3841 
3842 		u.sregs2 = kzalloc_obj(struct kvm_sregs2);
3843 		r = -ENOMEM;
3844 		if (!u.sregs2)
3845 			goto out;
3846 		kvm_vcpu_ioctl_x86_get_sregs2(vcpu, u.sregs2);
3847 		r = -EFAULT;
3848 		if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
3849 			goto out;
3850 		r = 0;
3851 		break;
3852 	}
3853 	case KVM_SET_SREGS2: {
3854 		r = -EINVAL;
3855 		if (vcpu->kvm->arch.has_protected_state &&
3856 		    vcpu->arch.guest_state_protected)
3857 			goto out;
3858 
3859 		u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
3860 		if (IS_ERR(u.sregs2)) {
3861 			r = PTR_ERR(u.sregs2);
3862 			u.sregs2 = NULL;
3863 			goto out;
3864 		}
3865 		r = kvm_vcpu_ioctl_x86_set_sregs2(vcpu, u.sregs2);
3866 		break;
3867 	}
3868 	case KVM_HAS_DEVICE_ATTR:
3869 	case KVM_GET_DEVICE_ATTR:
3870 	case KVM_SET_DEVICE_ATTR:
3871 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
3872 		break;
3873 	case KVM_MEMORY_ENCRYPT_OP:
3874 		r = -ENOTTY;
3875 		if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
3876 			goto out;
3877 		r = kvm_x86_ops.vcpu_mem_enc_ioctl(vcpu, argp);
3878 		break;
3879 	default:
3880 		r = -EINVAL;
3881 	}
3882 out:
3883 	kfree(u.buffer);
3884 out_nofree:
3885 	vcpu_put(vcpu);
3886 	return r;
3887 }
3888 
3889 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3890 {
3891 	return VM_FAULT_SIGBUS;
3892 }
3893 
3894 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3895 {
3896 	int ret;
3897 
3898 	if (addr > (unsigned int)(-3 * PAGE_SIZE))
3899 		return -EINVAL;
3900 	ret = kvm_x86_call(set_tss_addr)(kvm, addr);
3901 	return ret;
3902 }
3903 
3904 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3905 					      u64 ident_addr)
3906 {
3907 	return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
3908 }
3909 
3910 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3911 					 unsigned long kvm_nr_mmu_pages)
3912 {
3913 	if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3914 		return -EINVAL;
3915 
3916 	mutex_lock(&kvm->slots_lock);
3917 
3918 	kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3919 	kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3920 
3921 	mutex_unlock(&kvm->slots_lock);
3922 	return 0;
3923 }
3924 
3925 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
3926 {
3927 
3928 	/*
3929 	 * Flush all CPUs' dirty log buffers to the  dirty_bitmap.  Called
3930 	 * before reporting dirty_bitmap to userspace.  KVM flushes the buffers
3931 	 * on all VM-Exits, thus we only need to kick running vCPUs to force a
3932 	 * VM-Exit.
3933 	 */
3934 	struct kvm_vcpu *vcpu;
3935 	unsigned long i;
3936 
3937 	if (!kvm->arch.cpu_dirty_log_size)
3938 		return;
3939 
3940 	kvm_for_each_vcpu(i, vcpu, kvm)
3941 		kvm_vcpu_kick(vcpu);
3942 }
3943 
3944 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3945 			    struct kvm_enable_cap *cap)
3946 {
3947 	int r;
3948 
3949 	if (cap->flags)
3950 		return -EINVAL;
3951 
3952 	switch (cap->cap) {
3953 	case KVM_CAP_DISABLE_QUIRKS2:
3954 		r = -EINVAL;
3955 		if (cap->args[0] & ~kvm_caps.supported_quirks)
3956 			break;
3957 		fallthrough;
3958 	case KVM_CAP_DISABLE_QUIRKS:
3959 		mutex_lock(&kvm->lock);
3960 		WRITE_ONCE(kvm->arch.disabled_quirks,
3961 			   kvm->arch.disabled_quirks | (cap->args[0] & kvm_caps.supported_quirks));
3962 		mutex_unlock(&kvm->lock);
3963 		r = 0;
3964 		break;
3965 	case KVM_CAP_SPLIT_IRQCHIP: {
3966 		mutex_lock(&kvm->lock);
3967 		r = -EINVAL;
3968 		if (cap->args[0] > KVM_MAX_IRQ_ROUTES)
3969 			goto split_irqchip_unlock;
3970 		r = -EEXIST;
3971 		if (irqchip_in_kernel(kvm))
3972 			goto split_irqchip_unlock;
3973 		if (kvm->created_vcpus)
3974 			goto split_irqchip_unlock;
3975 		/* Pairs with irqchip_in_kernel. */
3976 		smp_wmb();
3977 		kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
3978 		kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
3979 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
3980 		r = 0;
3981 split_irqchip_unlock:
3982 		mutex_unlock(&kvm->lock);
3983 		break;
3984 	}
3985 	case KVM_CAP_X2APIC_API:
3986 		r = -EINVAL;
3987 		if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
3988 			break;
3989 
3990 		if ((cap->args[0] & KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST) &&
3991 		    (cap->args[0] & KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST))
3992 			break;
3993 
3994 		if ((cap->args[0] & KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST) &&
3995 		    !irqchip_split(kvm))
3996 			break;
3997 
3998 		if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
3999 			kvm->arch.x2apic_format = true;
4000 		if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4001 			kvm->arch.x2apic_broadcast_quirk_disabled = true;
4002 
4003 		if (cap->args[0] & KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST)
4004 			kvm->arch.suppress_eoi_broadcast_mode = KVM_SUPPRESS_EOI_BROADCAST_ENABLED;
4005 		if (cap->args[0] & KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST)
4006 			kvm->arch.suppress_eoi_broadcast_mode = KVM_SUPPRESS_EOI_BROADCAST_DISABLED;
4007 
4008 		r = 0;
4009 		break;
4010 	case KVM_CAP_X86_DISABLE_EXITS:
4011 		r = -EINVAL;
4012 		if (cap->args[0] & ~kvm_get_allowed_disable_exits())
4013 			break;
4014 
4015 		mutex_lock(&kvm->lock);
4016 		if (kvm->created_vcpus)
4017 			goto disable_exits_unlock;
4018 
4019 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
4020 		    "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
4021 
4022 		if (!mitigate_smt_rsb && boot_cpu_has_bug(X86_BUG_SMT_RSB) &&
4023 		    cpu_smt_possible() &&
4024 		    (cap->args[0] & ~(KVM_X86_DISABLE_EXITS_PAUSE |
4025 				      KVM_X86_DISABLE_EXITS_APERFMPERF)))
4026 			pr_warn_once(SMT_RSB_MSG);
4027 
4028 		kvm_disable_exits(kvm, cap->args[0]);
4029 		r = 0;
4030 disable_exits_unlock:
4031 		mutex_unlock(&kvm->lock);
4032 		break;
4033 	case KVM_CAP_MSR_PLATFORM_INFO:
4034 		kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4035 		r = 0;
4036 		break;
4037 	case KVM_CAP_EXCEPTION_PAYLOAD:
4038 		kvm->arch.exception_payload_enabled = cap->args[0];
4039 		r = 0;
4040 		break;
4041 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4042 		kvm->arch.triple_fault_event = cap->args[0];
4043 		r = 0;
4044 		break;
4045 	case KVM_CAP_X86_USER_SPACE_MSR:
4046 		r = -EINVAL;
4047 		if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
4048 			break;
4049 		kvm->arch.user_space_msr_mask = cap->args[0];
4050 		r = 0;
4051 		break;
4052 	case KVM_CAP_X86_BUS_LOCK_EXIT:
4053 		r = -EINVAL;
4054 		if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
4055 			break;
4056 
4057 		if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
4058 		    (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
4059 			break;
4060 
4061 		if (kvm_caps.has_bus_lock_exit &&
4062 		    cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
4063 			kvm->arch.bus_lock_detection_enabled = true;
4064 		r = 0;
4065 		break;
4066 #ifdef CONFIG_X86_SGX_KVM
4067 	case KVM_CAP_SGX_ATTRIBUTE: {
4068 		unsigned long allowed_attributes = 0;
4069 
4070 		r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
4071 		if (r)
4072 			break;
4073 
4074 		/* KVM only supports the PROVISIONKEY privileged attribute. */
4075 		if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
4076 		    !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
4077 			kvm->arch.sgx_provisioning_allowed = true;
4078 		else
4079 			r = -EINVAL;
4080 		break;
4081 	}
4082 #endif
4083 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4084 		r = -EINVAL;
4085 		if (!kvm_x86_ops.vm_copy_enc_context_from)
4086 			break;
4087 
4088 		r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
4089 		break;
4090 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4091 		r = -EINVAL;
4092 		if (!kvm_x86_ops.vm_move_enc_context_from)
4093 			break;
4094 
4095 		r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
4096 		break;
4097 	case KVM_CAP_EXIT_HYPERCALL:
4098 		if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
4099 			r = -EINVAL;
4100 			break;
4101 		}
4102 		kvm->arch.hypercall_exit_enabled = cap->args[0];
4103 		r = 0;
4104 		break;
4105 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4106 		r = -EINVAL;
4107 		if (cap->args[0] & ~1)
4108 			break;
4109 		kvm->arch.exit_on_emulation_error = cap->args[0];
4110 		r = 0;
4111 		break;
4112 	case KVM_CAP_PMU_CAPABILITY:
4113 		r = -EINVAL;
4114 		if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
4115 			break;
4116 
4117 		if (kvm->arch.has_protected_pmu &&
4118 		    cap->args[0] != KVM_PMU_CAP_DISABLE)
4119 			break;
4120 
4121 		mutex_lock(&kvm->lock);
4122 		if (!kvm->created_vcpus && !kvm->arch.created_mediated_pmu) {
4123 			kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
4124 			r = 0;
4125 		}
4126 		mutex_unlock(&kvm->lock);
4127 		break;
4128 	case KVM_CAP_MAX_VCPU_ID:
4129 		r = -EINVAL;
4130 		if (cap->args[0] > KVM_MAX_VCPU_IDS)
4131 			break;
4132 
4133 		mutex_lock(&kvm->lock);
4134 		if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
4135 			;
4136 		} else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
4137 			r = 0;
4138 		} else if (!kvm->arch.max_vcpu_ids) {
4139 			kvm->arch.max_vcpu_ids = cap->args[0];
4140 			r = 0;
4141 		}
4142 		mutex_unlock(&kvm->lock);
4143 		break;
4144 	case KVM_CAP_X86_NOTIFY_VMEXIT:
4145 		r = -EINVAL;
4146 		if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
4147 			break;
4148 		if (!kvm_caps.has_notify_vmexit)
4149 			break;
4150 		if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
4151 			break;
4152 		mutex_lock(&kvm->lock);
4153 		if (!kvm->created_vcpus) {
4154 			kvm->arch.notify_window = cap->args[0] >> 32;
4155 			kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
4156 			r = 0;
4157 		}
4158 		mutex_unlock(&kvm->lock);
4159 		break;
4160 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4161 		r = -EINVAL;
4162 
4163 		/*
4164 		 * Since the risk of disabling NX hugepages is a guest crashing
4165 		 * the system, ensure the userspace process has permission to
4166 		 * reboot the system.
4167 		 *
4168 		 * Note that unlike the reboot() syscall, the process must have
4169 		 * this capability in the root namespace because exposing
4170 		 * /dev/kvm into a container does not limit the scope of the
4171 		 * iTLB multihit bug to that container. In other words,
4172 		 * this must use capable(), not ns_capable().
4173 		 */
4174 		if (!capable(CAP_SYS_BOOT)) {
4175 			r = -EPERM;
4176 			break;
4177 		}
4178 
4179 		if (cap->args[0])
4180 			break;
4181 
4182 		mutex_lock(&kvm->lock);
4183 		if (!kvm->created_vcpus) {
4184 			kvm->arch.disable_nx_huge_pages = true;
4185 			r = 0;
4186 		}
4187 		mutex_unlock(&kvm->lock);
4188 		break;
4189 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
4190 		u64 bus_cycle_ns = cap->args[0];
4191 		u64 unused;
4192 
4193 		/*
4194 		 * Guard against overflow in tmict_to_ns(). 128 is the highest
4195 		 * divide value that can be programmed in APIC_TDCR.
4196 		 */
4197 		r = -EINVAL;
4198 		if (!bus_cycle_ns ||
4199 		    check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
4200 			break;
4201 
4202 		r = 0;
4203 		mutex_lock(&kvm->lock);
4204 		if (!irqchip_in_kernel(kvm))
4205 			r = -ENXIO;
4206 		else if (kvm->created_vcpus)
4207 			r = -EINVAL;
4208 		else
4209 			kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
4210 		mutex_unlock(&kvm->lock);
4211 		break;
4212 	}
4213 	default:
4214 		r = -EINVAL;
4215 		break;
4216 	}
4217 	return r;
4218 }
4219 
4220 #ifdef CONFIG_KVM_COMPAT
4221 /* for KVM_X86_SET_MSR_FILTER */
4222 struct kvm_msr_filter_range_compat {
4223 	__u32 flags;
4224 	__u32 nmsrs;
4225 	__u32 base;
4226 	__u32 bitmap;
4227 };
4228 
4229 struct kvm_msr_filter_compat {
4230 	__u32 flags;
4231 	struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
4232 };
4233 
4234 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
4235 
4236 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
4237 			      unsigned long arg)
4238 {
4239 	void __user *argp = (void __user *)arg;
4240 	struct kvm *kvm = filp->private_data;
4241 	long r = -ENOTTY;
4242 
4243 	switch (ioctl) {
4244 	case KVM_X86_SET_MSR_FILTER_COMPAT: {
4245 		struct kvm_msr_filter __user *user_msr_filter = argp;
4246 		struct kvm_msr_filter_compat filter_compat;
4247 		struct kvm_msr_filter filter;
4248 		int i;
4249 
4250 		if (copy_from_user(&filter_compat, user_msr_filter,
4251 				   sizeof(filter_compat)))
4252 			return -EFAULT;
4253 
4254 		filter.flags = filter_compat.flags;
4255 		for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
4256 			struct kvm_msr_filter_range_compat *cr;
4257 
4258 			cr = &filter_compat.ranges[i];
4259 			filter.ranges[i] = (struct kvm_msr_filter_range) {
4260 				.flags = cr->flags,
4261 				.nmsrs = cr->nmsrs,
4262 				.base = cr->base,
4263 				.bitmap = (__u8 *)(ulong)cr->bitmap,
4264 			};
4265 		}
4266 
4267 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
4268 		break;
4269 	}
4270 	}
4271 
4272 	return r;
4273 }
4274 #endif
4275 
4276 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
4277 static int kvm_arch_suspend_notifier(struct kvm *kvm)
4278 {
4279 	struct kvm_vcpu *vcpu;
4280 	unsigned long i;
4281 
4282 	/*
4283 	 * Ignore the return, marking the guest paused only "fails" if the vCPU
4284 	 * isn't using kvmclock; continuing on is correct and desirable.
4285 	 */
4286 	kvm_for_each_vcpu(i, vcpu, kvm)
4287 		(void)kvm_set_guest_paused(vcpu);
4288 
4289 	return NOTIFY_DONE;
4290 }
4291 
4292 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
4293 {
4294 	switch (state) {
4295 	case PM_HIBERNATION_PREPARE:
4296 	case PM_SUSPEND_PREPARE:
4297 		return kvm_arch_suspend_notifier(kvm);
4298 	}
4299 
4300 	return NOTIFY_DONE;
4301 }
4302 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
4303 
4304 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
4305 {
4306 	struct kvm_clock_data data = { 0 };
4307 
4308 	get_kvmclock(kvm, &data);
4309 	if (copy_to_user(argp, &data, sizeof(data)))
4310 		return -EFAULT;
4311 
4312 	return 0;
4313 }
4314 
4315 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
4316 {
4317 	struct kvm_arch *ka = &kvm->arch;
4318 	struct kvm_clock_data data;
4319 	u64 now_raw_ns;
4320 
4321 	if (copy_from_user(&data, argp, sizeof(data)))
4322 		return -EFAULT;
4323 
4324 	/*
4325 	 * Only KVM_CLOCK_REALTIME is used, but allow passing the
4326 	 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
4327 	 */
4328 	if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
4329 		return -EINVAL;
4330 
4331 	kvm_hv_request_tsc_page_update(kvm);
4332 	kvm_start_pvclock_update(kvm);
4333 	pvclock_update_vm_gtod_copy(kvm);
4334 
4335 	/*
4336 	 * This pairs with kvm_guest_time_update(): when masterclock is
4337 	 * in use, we use master_kernel_ns + kvmclock_offset to set
4338 	 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
4339 	 * is slightly ahead) here we risk going negative on unsigned
4340 	 * 'system_time' when 'data.clock' is very small.
4341 	 */
4342 	if (data.flags & KVM_CLOCK_REALTIME) {
4343 		u64 now_real_ns = ktime_get_real_ns();
4344 
4345 		/*
4346 		 * Avoid stepping the kvmclock backwards.
4347 		 */
4348 		if (now_real_ns > data.realtime)
4349 			data.clock += now_real_ns - data.realtime;
4350 	}
4351 
4352 	if (ka->use_master_clock)
4353 		now_raw_ns = ka->master_kernel_ns;
4354 	else
4355 		now_raw_ns = get_kvmclock_base_ns();
4356 	ka->kvmclock_offset = data.clock - now_raw_ns;
4357 	kvm_end_pvclock_update(kvm);
4358 	return 0;
4359 }
4360 
4361 long kvm_arch_vcpu_unlocked_ioctl(struct file *filp, unsigned int ioctl,
4362 				  unsigned long arg)
4363 {
4364 	struct kvm_vcpu *vcpu = filp->private_data;
4365 	void __user *argp = (void __user *)arg;
4366 
4367 	if (ioctl == KVM_MEMORY_ENCRYPT_OP &&
4368 	    kvm_x86_ops.vcpu_mem_enc_unlocked_ioctl)
4369 		return kvm_x86_call(vcpu_mem_enc_unlocked_ioctl)(vcpu, argp);
4370 
4371 	return -ENOIOCTLCMD;
4372 }
4373 
4374 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
4375 {
4376 	struct kvm *kvm = filp->private_data;
4377 	void __user *argp = (void __user *)arg;
4378 	int r = -ENOTTY;
4379 
4380 #ifdef CONFIG_KVM_IOAPIC
4381 	/*
4382 	 * This union makes it completely explicit to gcc-3.x
4383 	 * that these three variables' stack usage should be
4384 	 * combined, not added together.
4385 	 */
4386 	union {
4387 		struct kvm_pit_state ps;
4388 		struct kvm_pit_state2 ps2;
4389 		struct kvm_pit_config pit_config;
4390 	} u;
4391 #endif
4392 
4393 	switch (ioctl) {
4394 	case KVM_SET_TSS_ADDR:
4395 		r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4396 		break;
4397 	case KVM_SET_IDENTITY_MAP_ADDR: {
4398 		u64 ident_addr;
4399 
4400 		mutex_lock(&kvm->lock);
4401 		r = -EINVAL;
4402 		if (kvm->created_vcpus)
4403 			goto set_identity_unlock;
4404 		r = -EFAULT;
4405 		if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
4406 			goto set_identity_unlock;
4407 		r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4408 set_identity_unlock:
4409 		mutex_unlock(&kvm->lock);
4410 		break;
4411 	}
4412 	case KVM_SET_NR_MMU_PAGES:
4413 		r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4414 		break;
4415 #ifdef CONFIG_KVM_IOAPIC
4416 	case KVM_CREATE_IRQCHIP: {
4417 		mutex_lock(&kvm->lock);
4418 
4419 		r = -EEXIST;
4420 		if (irqchip_in_kernel(kvm))
4421 			goto create_irqchip_unlock;
4422 
4423 		/*
4424 		 * Disallow an in-kernel I/O APIC if the VM has protected EOIs,
4425 		 * i.e. if KVM can't intercept EOIs and thus can't properly
4426 		 * emulate level-triggered interrupts.
4427 		 */
4428 		r = -ENOTTY;
4429 		if (kvm->arch.has_protected_eoi)
4430 			goto create_irqchip_unlock;
4431 
4432 		r = -EINVAL;
4433 		if (kvm->created_vcpus)
4434 			goto create_irqchip_unlock;
4435 
4436 		r = kvm_pic_init(kvm);
4437 		if (r)
4438 			goto create_irqchip_unlock;
4439 
4440 		r = kvm_ioapic_init(kvm);
4441 		if (r) {
4442 			kvm_pic_destroy(kvm);
4443 			goto create_irqchip_unlock;
4444 		}
4445 
4446 		r = kvm_setup_default_ioapic_and_pic_routing(kvm);
4447 		if (r) {
4448 			kvm_ioapic_destroy(kvm);
4449 			kvm_pic_destroy(kvm);
4450 			goto create_irqchip_unlock;
4451 		}
4452 		/* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4453 		smp_wmb();
4454 		kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
4455 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
4456 	create_irqchip_unlock:
4457 		mutex_unlock(&kvm->lock);
4458 		break;
4459 	}
4460 	case KVM_CREATE_PIT:
4461 		u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4462 		goto create_pit;
4463 	case KVM_CREATE_PIT2:
4464 		r = -EFAULT;
4465 		if (copy_from_user(&u.pit_config, argp,
4466 				   sizeof(struct kvm_pit_config)))
4467 			goto out;
4468 	create_pit:
4469 		mutex_lock(&kvm->lock);
4470 		r = -EEXIST;
4471 		if (kvm->arch.vpit)
4472 			goto create_pit_unlock;
4473 		r = -ENOENT;
4474 		if (!pic_in_kernel(kvm))
4475 			goto create_pit_unlock;
4476 		r = -ENOMEM;
4477 		kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4478 		if (kvm->arch.vpit)
4479 			r = 0;
4480 	create_pit_unlock:
4481 		mutex_unlock(&kvm->lock);
4482 		break;
4483 	case KVM_GET_IRQCHIP: {
4484 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4485 		struct kvm_irqchip *chip;
4486 
4487 		chip = memdup_user(argp, sizeof(*chip));
4488 		if (IS_ERR(chip)) {
4489 			r = PTR_ERR(chip);
4490 			goto out;
4491 		}
4492 
4493 		r = -ENXIO;
4494 		if (!irqchip_full(kvm))
4495 			goto get_irqchip_out;
4496 		r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4497 		if (r)
4498 			goto get_irqchip_out;
4499 		r = -EFAULT;
4500 		if (copy_to_user(argp, chip, sizeof(*chip)))
4501 			goto get_irqchip_out;
4502 		r = 0;
4503 	get_irqchip_out:
4504 		kfree(chip);
4505 		break;
4506 	}
4507 	case KVM_SET_IRQCHIP: {
4508 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4509 		struct kvm_irqchip *chip;
4510 
4511 		chip = memdup_user(argp, sizeof(*chip));
4512 		if (IS_ERR(chip)) {
4513 			r = PTR_ERR(chip);
4514 			goto out;
4515 		}
4516 
4517 		r = -ENXIO;
4518 		if (!irqchip_full(kvm))
4519 			goto set_irqchip_out;
4520 		r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4521 	set_irqchip_out:
4522 		kfree(chip);
4523 		break;
4524 	}
4525 	case KVM_GET_PIT: {
4526 		r = -EFAULT;
4527 		if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4528 			goto out;
4529 		r = -ENXIO;
4530 		if (!kvm->arch.vpit)
4531 			goto out;
4532 		r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4533 		if (r)
4534 			goto out;
4535 		r = -EFAULT;
4536 		if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4537 			goto out;
4538 		r = 0;
4539 		break;
4540 	}
4541 	case KVM_SET_PIT: {
4542 		r = -EFAULT;
4543 		if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
4544 			goto out;
4545 		mutex_lock(&kvm->lock);
4546 		r = -ENXIO;
4547 		if (!kvm->arch.vpit)
4548 			goto set_pit_out;
4549 		r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4550 set_pit_out:
4551 		mutex_unlock(&kvm->lock);
4552 		break;
4553 	}
4554 	case KVM_GET_PIT2: {
4555 		r = -ENXIO;
4556 		if (!kvm->arch.vpit)
4557 			goto out;
4558 		r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4559 		if (r)
4560 			goto out;
4561 		r = -EFAULT;
4562 		if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4563 			goto out;
4564 		r = 0;
4565 		break;
4566 	}
4567 	case KVM_SET_PIT2: {
4568 		r = -EFAULT;
4569 		if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4570 			goto out;
4571 		mutex_lock(&kvm->lock);
4572 		r = -ENXIO;
4573 		if (!kvm->arch.vpit)
4574 			goto set_pit2_out;
4575 		r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4576 set_pit2_out:
4577 		mutex_unlock(&kvm->lock);
4578 		break;
4579 	}
4580 	case KVM_REINJECT_CONTROL: {
4581 		struct kvm_reinject_control control;
4582 		r =  -EFAULT;
4583 		if (copy_from_user(&control, argp, sizeof(control)))
4584 			goto out;
4585 		r = -ENXIO;
4586 		if (!kvm->arch.vpit)
4587 			goto out;
4588 		r = kvm_vm_ioctl_reinject(kvm, &control);
4589 		break;
4590 	}
4591 #endif
4592 	case KVM_SET_BOOT_CPU_ID:
4593 		r = 0;
4594 		mutex_lock(&kvm->lock);
4595 		if (kvm->created_vcpus)
4596 			r = -EBUSY;
4597 		else if (arg > KVM_MAX_VCPU_IDS ||
4598 			 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
4599 			r = -EINVAL;
4600 		else
4601 			kvm->arch.bsp_vcpu_id = arg;
4602 		mutex_unlock(&kvm->lock);
4603 		break;
4604 #ifdef CONFIG_KVM_XEN
4605 	case KVM_XEN_HVM_CONFIG: {
4606 		struct kvm_xen_hvm_config xhc;
4607 		r = -EFAULT;
4608 		if (copy_from_user(&xhc, argp, sizeof(xhc)))
4609 			goto out;
4610 		r = kvm_xen_hvm_config(kvm, &xhc);
4611 		break;
4612 	}
4613 	case KVM_XEN_HVM_GET_ATTR: {
4614 		struct kvm_xen_hvm_attr xha;
4615 
4616 		r = -EFAULT;
4617 		if (copy_from_user(&xha, argp, sizeof(xha)))
4618 			goto out;
4619 		r = kvm_xen_hvm_get_attr(kvm, &xha);
4620 		if (!r && copy_to_user(argp, &xha, sizeof(xha)))
4621 			r = -EFAULT;
4622 		break;
4623 	}
4624 	case KVM_XEN_HVM_SET_ATTR: {
4625 		struct kvm_xen_hvm_attr xha;
4626 
4627 		r = -EFAULT;
4628 		if (copy_from_user(&xha, argp, sizeof(xha)))
4629 			goto out;
4630 		r = kvm_xen_hvm_set_attr(kvm, &xha);
4631 		break;
4632 	}
4633 	case KVM_XEN_HVM_EVTCHN_SEND: {
4634 		struct kvm_irq_routing_xen_evtchn uxe;
4635 
4636 		r = -EFAULT;
4637 		if (copy_from_user(&uxe, argp, sizeof(uxe)))
4638 			goto out;
4639 		r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
4640 		break;
4641 	}
4642 #endif
4643 	case KVM_SET_CLOCK:
4644 		r = kvm_vm_ioctl_set_clock(kvm, argp);
4645 		break;
4646 	case KVM_GET_CLOCK:
4647 		r = kvm_vm_ioctl_get_clock(kvm, argp);
4648 		break;
4649 	case KVM_SET_TSC_KHZ: {
4650 		u32 user_tsc_khz;
4651 
4652 		r = -EINVAL;
4653 		user_tsc_khz = (u32)arg;
4654 
4655 		if (kvm_caps.has_tsc_control &&
4656 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
4657 			goto out;
4658 
4659 		if (user_tsc_khz == 0)
4660 			user_tsc_khz = tsc_khz;
4661 
4662 		mutex_lock(&kvm->lock);
4663 		if (!kvm->created_vcpus) {
4664 			WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
4665 			r = 0;
4666 		}
4667 		mutex_unlock(&kvm->lock);
4668 		goto out;
4669 	}
4670 	case KVM_GET_TSC_KHZ: {
4671 		r = READ_ONCE(kvm->arch.default_tsc_khz);
4672 		goto out;
4673 	}
4674 	case KVM_MEMORY_ENCRYPT_OP:
4675 		r = -ENOTTY;
4676 		if (!kvm_x86_ops.mem_enc_ioctl)
4677 			goto out;
4678 
4679 		r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
4680 		break;
4681 	case KVM_MEMORY_ENCRYPT_REG_REGION: {
4682 		struct kvm_enc_region region;
4683 
4684 		r = -EFAULT;
4685 		if (copy_from_user(&region, argp, sizeof(region)))
4686 			goto out;
4687 
4688 		r = -ENOTTY;
4689 		if (!kvm_x86_ops.mem_enc_register_region)
4690 			goto out;
4691 
4692 		r = kvm_x86_call(mem_enc_register_region)(kvm, &region);
4693 		break;
4694 	}
4695 	case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
4696 		struct kvm_enc_region region;
4697 
4698 		r = -EFAULT;
4699 		if (copy_from_user(&region, argp, sizeof(region)))
4700 			goto out;
4701 
4702 		r = -ENOTTY;
4703 		if (!kvm_x86_ops.mem_enc_unregister_region)
4704 			goto out;
4705 
4706 		r = kvm_x86_call(mem_enc_unregister_region)(kvm, &region);
4707 		break;
4708 	}
4709 #ifdef CONFIG_KVM_HYPERV
4710 	case KVM_HYPERV_EVENTFD: {
4711 		struct kvm_hyperv_eventfd hvevfd;
4712 
4713 		r = -EFAULT;
4714 		if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
4715 			goto out;
4716 		r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
4717 		break;
4718 	}
4719 #endif
4720 	case KVM_SET_PMU_EVENT_FILTER:
4721 		r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
4722 		break;
4723 	case KVM_X86_SET_MSR_FILTER: {
4724 		struct kvm_msr_filter __user *user_msr_filter = argp;
4725 		struct kvm_msr_filter filter;
4726 
4727 		if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
4728 			return -EFAULT;
4729 
4730 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
4731 		break;
4732 	}
4733 	default:
4734 		r = -ENOTTY;
4735 	}
4736 out:
4737 	return r;
4738 }
4739 
4740 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4741 			   void *__v)
4742 {
4743 	const void *v = __v;
4744 	int handled = 0;
4745 	int n;
4746 
4747 	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, len, addr, __v);
4748 
4749 	do {
4750 		n = min(len, 8);
4751 		if (!(lapic_in_kernel(vcpu) &&
4752 		      !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4753 		    && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4754 			break;
4755 		handled += n;
4756 		addr += n;
4757 		len -= n;
4758 		v += n;
4759 	} while (len);
4760 
4761 	return handled;
4762 }
4763 
4764 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4765 {
4766 	int handled = 0;
4767 	int n;
4768 
4769 	do {
4770 		n = min(len, 8);
4771 		if (!(lapic_in_kernel(vcpu) &&
4772 		      !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4773 					 addr, n, v))
4774 		    && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4775 			break;
4776 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4777 		handled += n;
4778 		addr += n;
4779 		len -= n;
4780 		v += n;
4781 	} while (len);
4782 
4783 	if (len)
4784 		trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, len, addr, NULL);
4785 
4786 	return handled;
4787 }
4788 
4789 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4790 			      struct x86_exception *exception)
4791 {
4792 	struct kvm_pagewalk *gva_walk = &vcpu->arch.gva_walk;
4793 
4794 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
4795 	return gva_walk->gva_to_gpa(vcpu, gva_walk, gva, access, exception);
4796 }
4797 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_read);
4798 
4799 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4800 			       struct x86_exception *exception)
4801 {
4802 	struct kvm_pagewalk *gva_walk = &vcpu->arch.gva_walk;
4803 
4804 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
4805 	access |= PFERR_WRITE_MASK;
4806 	return gva_walk->gva_to_gpa(vcpu, gva_walk, gva, access, exception);
4807 }
4808 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_write);
4809 
4810 /* uses this to access any guest's mapped memory without checking CPL */
4811 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4812 				struct x86_exception *exception)
4813 {
4814 	struct kvm_pagewalk *gva_walk = &vcpu->arch.gva_walk;
4815 
4816 	return gva_walk->gva_to_gpa(vcpu, gva_walk, gva, 0, exception);
4817 }
4818 
4819 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4820 				      struct kvm_vcpu *vcpu, u64 access,
4821 				      struct x86_exception *exception)
4822 {
4823 	struct kvm_pagewalk *gva_walk = &vcpu->arch.gva_walk;
4824 	void *data = val;
4825 	int r = X86EMUL_CONTINUE;
4826 
4827 	while (bytes) {
4828 		gpa_t gpa = gva_walk->gva_to_gpa(vcpu, gva_walk, addr, access, exception);
4829 		unsigned offset = addr & (PAGE_SIZE-1);
4830 		unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4831 		int ret;
4832 
4833 		if (gpa == INVALID_GPA)
4834 			return X86EMUL_PROPAGATE_FAULT;
4835 		ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4836 					       offset, toread);
4837 		if (ret < 0) {
4838 			r = X86EMUL_IO_NEEDED;
4839 			goto out;
4840 		}
4841 
4842 		bytes -= toread;
4843 		data += toread;
4844 		addr += toread;
4845 	}
4846 out:
4847 	return r;
4848 }
4849 
4850 /* used for instruction fetching */
4851 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4852 				gva_t addr, void *val, unsigned int bytes,
4853 				struct x86_exception *exception)
4854 {
4855 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4856 	struct kvm_pagewalk *gva_walk = &vcpu->arch.gva_walk;
4857 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
4858 	unsigned offset;
4859 	int ret;
4860 
4861 	/* Inline kvm_read_guest_virt_helper for speed.  */
4862 	gpa_t gpa = gva_walk->gva_to_gpa(vcpu, gva_walk, addr, access|PFERR_FETCH_MASK,
4863 					  exception);
4864 	if (unlikely(gpa == INVALID_GPA))
4865 		return X86EMUL_PROPAGATE_FAULT;
4866 
4867 	offset = addr & (PAGE_SIZE-1);
4868 	if (WARN_ON(offset + bytes > PAGE_SIZE))
4869 		bytes = (unsigned)PAGE_SIZE - offset;
4870 	ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4871 				       offset, bytes);
4872 	if (unlikely(ret < 0))
4873 		return X86EMUL_IO_NEEDED;
4874 
4875 	return X86EMUL_CONTINUE;
4876 }
4877 
4878 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
4879 			       gva_t addr, void *val, unsigned int bytes,
4880 			       struct x86_exception *exception)
4881 {
4882 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
4883 
4884 	/*
4885 	 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4886 	 * is returned, but our callers are not ready for that and they blindly
4887 	 * call kvm_inject_page_fault.  Ensure that they at least do not leak
4888 	 * uninitialized kernel stack memory into cr2 and error code.
4889 	 */
4890 	memset(exception, 0, sizeof(*exception));
4891 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4892 					  exception);
4893 }
4894 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_virt);
4895 
4896 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
4897 			     gva_t addr, void *val, unsigned int bytes,
4898 			     struct x86_exception *exception, bool system)
4899 {
4900 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4901 	u64 access = 0;
4902 
4903 	if (system)
4904 		access |= PFERR_IMPLICIT_ACCESS;
4905 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
4906 		access |= PFERR_USER_MASK;
4907 
4908 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
4909 }
4910 
4911 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4912 				      struct kvm_vcpu *vcpu, u64 access,
4913 				      struct x86_exception *exception)
4914 {
4915 	struct kvm_pagewalk *gva_walk = &vcpu->arch.gva_walk;
4916 	void *data = val;
4917 	int r = X86EMUL_CONTINUE;
4918 
4919 	while (bytes) {
4920 		gpa_t gpa = gva_walk->gva_to_gpa(vcpu, gva_walk, addr, access, exception);
4921 		unsigned offset = addr & (PAGE_SIZE-1);
4922 		unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4923 		int ret;
4924 
4925 		if (gpa == INVALID_GPA)
4926 			return X86EMUL_PROPAGATE_FAULT;
4927 		ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4928 		if (ret < 0) {
4929 			r = X86EMUL_IO_NEEDED;
4930 			goto out;
4931 		}
4932 
4933 		bytes -= towrite;
4934 		data += towrite;
4935 		addr += towrite;
4936 	}
4937 out:
4938 	return r;
4939 }
4940 
4941 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
4942 			      unsigned int bytes, struct x86_exception *exception,
4943 			      bool system)
4944 {
4945 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4946 	u64 access = PFERR_WRITE_MASK;
4947 
4948 	if (system)
4949 		access |= PFERR_IMPLICIT_ACCESS;
4950 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
4951 		access |= PFERR_USER_MASK;
4952 
4953 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4954 					   access, exception);
4955 }
4956 
4957 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
4958 				unsigned int bytes, struct x86_exception *exception)
4959 {
4960 	/* kvm_write_guest_virt_system can pull in tons of pages. */
4961 	kvm_request_l1tf_flush_l1d();
4962 
4963 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4964 					   PFERR_WRITE_MASK, exception);
4965 }
4966 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_write_guest_virt_system);
4967 
4968 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
4969 				  void *insn, int insn_len)
4970 {
4971 	return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
4972 						       insn, insn_len);
4973 }
4974 
4975 int handle_ud(struct kvm_vcpu *vcpu)
4976 {
4977 	static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
4978 	int fep_flags = READ_ONCE(force_emulation_prefix);
4979 	int emul_type = EMULTYPE_TRAP_UD;
4980 	char sig[5]; /* ud2; .ascii "kvm" */
4981 	struct x86_exception e;
4982 	int r;
4983 
4984 	r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
4985 	if (r != X86EMUL_CONTINUE)
4986 		return 1;
4987 
4988 	if (fep_flags &&
4989 	    kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
4990 				sig, sizeof(sig), &e) == 0 &&
4991 	    memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
4992 		if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
4993 			kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
4994 		kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
4995 		emul_type = EMULTYPE_TRAP_UD_FORCED;
4996 	}
4997 
4998 	return kvm_emulate_instruction(vcpu, emul_type);
4999 }
5000 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_ud);
5001 
5002 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5003 			    gpa_t gpa, bool write)
5004 {
5005 	/* For APIC access vmexit */
5006 	if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5007 		return 1;
5008 
5009 	if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5010 		trace_vcpu_match_mmio(gva, gpa, write, true);
5011 		return 1;
5012 	}
5013 
5014 	return 0;
5015 }
5016 
5017 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5018 				gpa_t *gpa, struct x86_exception *exception,
5019 				bool write)
5020 {
5021 	struct kvm_pagewalk *gva_walk = &vcpu->arch.gva_walk;
5022 	u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
5023 		     | (write ? PFERR_WRITE_MASK : 0);
5024 
5025 	/*
5026 	 * currently PKRU is only applied to ept enabled guest so
5027 	 * there is no pkey in EPT page table for L1 guest or EPT
5028 	 * shadow page table for L2 guest.
5029 	 */
5030 	if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
5031 	    !permission_fault(vcpu, gva_walk,
5032 			      vcpu->arch.mmio_access, 0, access))) {
5033 		*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5034 					(gva & (PAGE_SIZE - 1));
5035 		trace_vcpu_match_mmio(gva, *gpa, write, false);
5036 		return 1;
5037 	}
5038 
5039 	*gpa = gva_walk->gva_to_gpa(vcpu, gva_walk, gva, access, exception);
5040 
5041 	if (*gpa == INVALID_GPA)
5042 		return -1;
5043 
5044 	return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5045 }
5046 
5047 struct read_write_emulator_ops {
5048 	int (*read_write_guest)(struct kvm_vcpu *vcpu, gpa_t gpa,
5049 				void *val, int bytes);
5050 	int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5051 			       int bytes, void *val);
5052 	bool write;
5053 };
5054 
5055 static int emulator_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa,
5056 			       void *val, int bytes)
5057 {
5058 	return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5059 }
5060 
5061 static int emulator_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa,
5062 				void *val, int bytes)
5063 {
5064 	int ret;
5065 
5066 	ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5067 	if (ret < 0)
5068 		return 0;
5069 	kvm_page_track_write(vcpu, gpa, val, bytes);
5070 	return 1;
5071 }
5072 
5073 static int emulator_read_write_onepage(unsigned long addr, void *val,
5074 				       unsigned int bytes,
5075 				       struct x86_exception *exception,
5076 				       struct kvm_vcpu *vcpu,
5077 				       const struct read_write_emulator_ops *ops)
5078 {
5079 	gpa_t gpa;
5080 	int handled, ret;
5081 	bool write = ops->write;
5082 	struct kvm_mmio_fragment *frag;
5083 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
5084 
5085 	/*
5086 	 * If the exit was due to a NPF we may already have a GPA.
5087 	 * If the GPA is present, use it to avoid the GVA to GPA table walk.
5088 	 * Note, this cannot be used on string operations since string
5089 	 * operation using rep will only have the initial GPA from the NPF
5090 	 * occurred.
5091 	 */
5092 	if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
5093 	    (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
5094 		gpa = ctxt->gpa_val;
5095 		ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5096 	} else {
5097 		ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5098 		if (ret < 0)
5099 			return X86EMUL_PROPAGATE_FAULT;
5100 	}
5101 
5102 	/*
5103 	 * If the memory is not _known_ to be emulated MMIO, attempt to access
5104 	 * guest memory.  If accessing guest memory fails, e.g. because there's
5105 	 * no memslot, then handle the access as MMIO.  Note, treating the
5106 	 * access as emulated MMIO is technically wrong if there is a memslot,
5107 	 * i.e. if accessing host user memory failed, but this has been KVM's
5108 	 * historical ABI for decades.
5109 	 */
5110 	if (!ret && ops->read_write_guest(vcpu, gpa, val, bytes))
5111 		return X86EMUL_CONTINUE;
5112 
5113 	/*
5114 	 * Attempt to handle emulated MMIO within the kernel, e.g. for accesses
5115 	 * to an in-kernel local or I/O APIC, or to an ioeventfd range attached
5116 	 * to MMIO bus.  If the access isn't fully resolved, insert an MMIO
5117 	 * fragment with the relevant details.
5118 	 */
5119 	handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5120 	if (handled == bytes)
5121 		return X86EMUL_CONTINUE;
5122 
5123 	gpa += handled;
5124 	bytes -= handled;
5125 	val += handled;
5126 
5127 	WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5128 	frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5129 	frag->gpa = gpa;
5130 	if (write && bytes <= 8u) {
5131 		frag->val = 0;
5132 		frag->data = &frag->val;
5133 		memcpy(&frag->val, val, bytes);
5134 	} else {
5135 		frag->data = val;
5136 	}
5137 	frag->len = bytes;
5138 
5139 	/*
5140 	 * Continue emulating, even though KVM needs to (eventually) do an MMIO
5141 	 * exit to userspace.  If the access splits multiple pages, then KVM
5142 	 * needs to exit to userspace only after emulating both parts of the
5143 	 * access.
5144 	 */
5145 	return X86EMUL_CONTINUE;
5146 }
5147 
5148 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5149 			unsigned long addr,
5150 			void *val, unsigned int bytes,
5151 			struct x86_exception *exception,
5152 			const struct read_write_emulator_ops *ops)
5153 {
5154 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5155 	int rc;
5156 
5157 	if (WARN_ON_ONCE((bytes > 8u || !ops->write) && object_is_on_stack(val)))
5158 		return X86EMUL_UNHANDLEABLE;
5159 
5160 	/*
5161 	 * If the read was already completed via a userspace MMIO exit, there's
5162 	 * nothing left to do except trace the MMIO read.  When completing MMIO
5163 	 * reads, KVM re-emulates the instruction to propagate the value into
5164 	 * the correct destination, e.g. into the correct register, but the
5165 	 * value itself has already been copied to the read cache.
5166 	 *
5167 	 * Note!  This is *tightly* coupled to read_emulated() satisfying reads
5168 	 * from the emulator's mem_read cache, so that the MMIO fragment data
5169 	 * is copied to the correct chunk of the correct operand.
5170 	 */
5171 	if (!ops->write && vcpu->mmio_read_completed) {
5172 		/*
5173 		 * For simplicity, trace the entire MMIO read in one shot, even
5174 		 * though the GPA might be incorrect if there are two fragments
5175 		 * that aren't contiguous in the GPA space.
5176 		 */
5177 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5178 			       vcpu->mmio_fragments[0].gpa, val);
5179 		vcpu->mmio_read_completed = 0;
5180 		return X86EMUL_CONTINUE;
5181 	}
5182 
5183 	vcpu->mmio_nr_fragments = 0;
5184 
5185 	/* Crossing a page boundary? */
5186 	if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5187 		int now;
5188 
5189 		now = -addr & ~PAGE_MASK;
5190 		rc = emulator_read_write_onepage(addr, val, now, exception,
5191 						 vcpu, ops);
5192 
5193 		if (rc != X86EMUL_CONTINUE)
5194 			return rc;
5195 		addr += now;
5196 		if (ctxt->mode != X86EMUL_MODE_PROT64)
5197 			addr = (u32)addr;
5198 		val += now;
5199 		bytes -= now;
5200 	}
5201 
5202 	rc = emulator_read_write_onepage(addr, val, bytes, exception,
5203 					 vcpu, ops);
5204 	if (rc != X86EMUL_CONTINUE)
5205 		return rc;
5206 
5207 	if (!vcpu->mmio_nr_fragments)
5208 		return X86EMUL_CONTINUE;
5209 
5210 	vcpu->mmio_needed = 1;
5211 	vcpu->mmio_cur_fragment = 0;
5212 	vcpu->mmio_is_write = ops->write;
5213 
5214 	kvm_prepare_emulated_mmio_exit(vcpu, &vcpu->mmio_fragments[0]);
5215 
5216 	/*
5217 	 * For MMIO reads, stop emulating and immediately exit to userspace, as
5218 	 * KVM needs the value to correctly emulate the instruction.  For MMIO
5219 	 * writes, continue emulating as the write to MMIO is a side effect for
5220 	 * all intents and purposes.  KVM will still exit to userspace, but
5221 	 * after completing emulation (see the check on vcpu->mmio_needed in
5222 	 * x86_emulate_instruction()).
5223 	 */
5224 	return ops->write ? X86EMUL_CONTINUE : X86EMUL_IO_NEEDED;
5225 }
5226 
5227 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5228 				  unsigned long addr,
5229 				  void *val,
5230 				  unsigned int bytes,
5231 				  struct x86_exception *exception)
5232 {
5233 	static const struct read_write_emulator_ops ops = {
5234 		.read_write_guest = emulator_read_guest,
5235 		.read_write_mmio = vcpu_mmio_read,
5236 		.write = false,
5237 	};
5238 
5239 	return emulator_read_write(ctxt, addr, val, bytes, exception, &ops);
5240 }
5241 
5242 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5243 			    unsigned long addr,
5244 			    const void *val,
5245 			    unsigned int bytes,
5246 			    struct x86_exception *exception)
5247 {
5248 	static const struct read_write_emulator_ops ops = {
5249 		.read_write_guest = emulator_write_guest,
5250 		.read_write_mmio = vcpu_mmio_write,
5251 		.write = true,
5252 	};
5253 
5254 	return emulator_read_write(ctxt, addr, (void *)val, bytes, exception, &ops);
5255 }
5256 
5257 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
5258 	(__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
5259 
5260 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5261 				     unsigned long addr,
5262 				     const void *old,
5263 				     const void *new,
5264 				     unsigned int bytes,
5265 				     struct x86_exception *exception)
5266 {
5267 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5268 	u64 page_line_mask;
5269 	unsigned long hva;
5270 	gpa_t gpa;
5271 	int r;
5272 
5273 	/* guests cmpxchg8b have to be emulated atomically */
5274 	if (bytes > 8 || (bytes & (bytes - 1)))
5275 		goto emul_write;
5276 
5277 	gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5278 
5279 	if (gpa == INVALID_GPA ||
5280 	    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5281 		goto emul_write;
5282 
5283 	/*
5284 	 * Emulate the atomic as a straight write to avoid #AC if SLD is
5285 	 * enabled in the host and the access splits a cache line.
5286 	 */
5287 	if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5288 		page_line_mask = ~(cache_line_size() - 1);
5289 	else
5290 		page_line_mask = PAGE_MASK;
5291 
5292 	if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
5293 		goto emul_write;
5294 
5295 	hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
5296 	if (kvm_is_error_hva(hva))
5297 		goto emul_write;
5298 
5299 	hva += offset_in_page(gpa);
5300 
5301 	switch (bytes) {
5302 	case 1:
5303 		r = emulator_try_cmpxchg_user(u8, hva, old, new);
5304 		break;
5305 	case 2:
5306 		r = emulator_try_cmpxchg_user(u16, hva, old, new);
5307 		break;
5308 	case 4:
5309 		r = emulator_try_cmpxchg_user(u32, hva, old, new);
5310 		break;
5311 	case 8:
5312 		r = emulator_try_cmpxchg_user(u64, hva, old, new);
5313 		break;
5314 	default:
5315 		BUG();
5316 	}
5317 
5318 	if (r < 0)
5319 		return X86EMUL_UNHANDLEABLE;
5320 
5321 	/*
5322 	 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
5323 	 * successful, as the old value is written back on failure.  Note, for
5324 	 * live migration, this is unnecessarily conservative as CMPXCHG writes
5325 	 * back the original value and the access is atomic, but KVM's ABI is
5326 	 * that all writes are dirty logged, regardless of the value written.
5327 	 */
5328 	kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
5329 
5330 	if (r)
5331 		return X86EMUL_CMPXCHG_FAILED;
5332 
5333 	kvm_page_track_write(vcpu, gpa, new, bytes);
5334 
5335 	return X86EMUL_CONTINUE;
5336 
5337 emul_write:
5338 	pr_warn_once("emulating exchange as write\n");
5339 
5340 	return emulator_write_emulated(ctxt, addr, new, bytes, exception);
5341 }
5342 
5343 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
5344 			       unsigned short port, void *data,
5345 			       unsigned int count, bool in)
5346 {
5347 	unsigned i;
5348 	int r;
5349 
5350 	WARN_ON_ONCE(vcpu->arch.pio.count);
5351 	for (i = 0; i < count; i++) {
5352 		if (in)
5353 			r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
5354 		else
5355 			r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
5356 
5357 		if (r) {
5358 			if (i == 0)
5359 				goto userspace_io;
5360 
5361 			/*
5362 			 * Userspace must have unregistered the device while PIO
5363 			 * was running.  Drop writes / read as 0.
5364 			 */
5365 			if (in)
5366 				memset(data, 0, size * (count - i));
5367 			break;
5368 		}
5369 
5370 		data += size;
5371 	}
5372 	return 1;
5373 
5374 userspace_io:
5375 	vcpu->arch.pio.port = port;
5376 	vcpu->arch.pio.in = in;
5377 	vcpu->arch.pio.count = count;
5378 	vcpu->arch.pio.size = size;
5379 
5380 	if (in)
5381 		memset(vcpu->arch.pio_data, 0, size * count);
5382 	else
5383 		memcpy(vcpu->arch.pio_data, data, size * count);
5384 
5385 	vcpu->run->exit_reason = KVM_EXIT_IO;
5386 	vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
5387 	vcpu->run->io.size = size;
5388 	vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
5389 	vcpu->run->io.count = count;
5390 	vcpu->run->io.port = port;
5391 	return 0;
5392 }
5393 
5394 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
5395       			   unsigned short port, void *val, unsigned int count)
5396 {
5397 	int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
5398 	if (r)
5399 		trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
5400 
5401 	return r;
5402 }
5403 
5404 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
5405 {
5406 	int size = vcpu->arch.pio.size;
5407 	unsigned int count = vcpu->arch.pio.count;
5408 	memcpy(val, vcpu->arch.pio_data, size * count);
5409 	trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
5410 	vcpu->arch.pio.count = 0;
5411 }
5412 
5413 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
5414 				    int size, unsigned short port, void *val,
5415 				    unsigned int count)
5416 {
5417 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5418 	if (vcpu->arch.pio.count) {
5419 		/*
5420 		 * Complete a previous iteration that required userspace I/O.
5421 		 * Note, @count isn't guaranteed to match pio.count as userspace
5422 		 * can modify ECX before rerunning the vCPU.  Ignore any such
5423 		 * shenanigans as KVM doesn't support modifying the rep count,
5424 		 * and the emulator ensures @count doesn't overflow the buffer.
5425 		 */
5426 		complete_emulator_pio_in(vcpu, val);
5427 		return 1;
5428 	}
5429 
5430 	return emulator_pio_in(vcpu, size, port, val, count);
5431 }
5432 
5433 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
5434 			    unsigned short port, const void *val,
5435 			    unsigned int count)
5436 {
5437 	trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
5438 	return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
5439 }
5440 
5441 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
5442 				     int size, unsigned short port,
5443 				     const void *val, unsigned int count)
5444 {
5445 	return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
5446 }
5447 
5448 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
5449 {
5450 	kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
5451 }
5452 
5453 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
5454 {
5455 	if (!need_emulate_wbinvd(vcpu))
5456 		return X86EMUL_CONTINUE;
5457 
5458 	if (kvm_x86_call(has_wbinvd_exit)()) {
5459 		int cpu = get_cpu();
5460 
5461 		cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5462 		wbinvd_on_cpus_mask(vcpu->arch.wbinvd_dirty_mask);
5463 		put_cpu();
5464 		cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5465 	} else
5466 		wbinvd();
5467 	return X86EMUL_CONTINUE;
5468 }
5469 
5470 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5471 {
5472 	kvm_emulate_wbinvd_noskip(vcpu);
5473 	return kvm_skip_emulated_instruction(vcpu);
5474 }
5475 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wbinvd);
5476 
5477 
5478 
5479 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5480 {
5481 	kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5482 }
5483 
5484 static unsigned long emulator_get_effective_dr7(struct x86_emulate_ctxt *ctxt)
5485 {
5486 	return kvm_get_effective_dr7(emul_to_vcpu(ctxt));
5487 }
5488 
5489 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
5490 {
5491 	return kvm_get_dr(emul_to_vcpu(ctxt), dr);
5492 }
5493 
5494 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5495 			   unsigned long value)
5496 {
5497 
5498 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
5499 }
5500 
5501 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5502 {
5503 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5504 }
5505 
5506 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
5507 {
5508 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5509 	unsigned long value;
5510 
5511 	switch (cr) {
5512 	case 0:
5513 		value = kvm_read_cr0(vcpu);
5514 		break;
5515 	case 2:
5516 		value = vcpu->arch.cr2;
5517 		break;
5518 	case 3:
5519 		value = kvm_read_cr3(vcpu);
5520 		break;
5521 	case 4:
5522 		value = kvm_read_cr4(vcpu);
5523 		break;
5524 	case 8:
5525 		value = kvm_get_cr8(vcpu);
5526 		break;
5527 	default:
5528 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
5529 		return 0;
5530 	}
5531 
5532 	return value;
5533 }
5534 
5535 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
5536 {
5537 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5538 	int res = 0;
5539 
5540 	switch (cr) {
5541 	case 0:
5542 		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
5543 		break;
5544 	case 2:
5545 		vcpu->arch.cr2 = val;
5546 		break;
5547 	case 3:
5548 		res = kvm_set_cr3(vcpu, val);
5549 		break;
5550 	case 4:
5551 		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
5552 		break;
5553 	case 8:
5554 		res = kvm_set_cr8(vcpu, val);
5555 		break;
5556 	default:
5557 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
5558 		res = -1;
5559 	}
5560 
5561 	return res;
5562 }
5563 
5564 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
5565 {
5566 	return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
5567 }
5568 
5569 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5570 {
5571 	kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
5572 }
5573 
5574 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5575 {
5576 	kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
5577 }
5578 
5579 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5580 {
5581 	kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
5582 }
5583 
5584 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5585 {
5586 	kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
5587 }
5588 
5589 static unsigned long emulator_get_cached_segment_base(
5590 	struct x86_emulate_ctxt *ctxt, int seg)
5591 {
5592 	return kvm_get_segment_base(emul_to_vcpu(ctxt), seg);
5593 }
5594 
5595 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
5596 				 struct desc_struct *desc, u32 *base3,
5597 				 int seg)
5598 {
5599 	struct kvm_segment var;
5600 
5601 	kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
5602 	*selector = var.selector;
5603 
5604 	if (var.unusable) {
5605 		memset(desc, 0, sizeof(*desc));
5606 		if (base3)
5607 			*base3 = 0;
5608 		return false;
5609 	}
5610 
5611 	if (var.g)
5612 		var.limit >>= 12;
5613 	set_desc_limit(desc, var.limit);
5614 	set_desc_base(desc, (unsigned long)var.base);
5615 #ifdef CONFIG_X86_64
5616 	if (base3)
5617 		*base3 = var.base >> 32;
5618 #endif
5619 	desc->type = var.type;
5620 	desc->s = var.s;
5621 	desc->dpl = var.dpl;
5622 	desc->p = var.present;
5623 	desc->avl = var.avl;
5624 	desc->l = var.l;
5625 	desc->d = var.db;
5626 	desc->g = var.g;
5627 
5628 	return true;
5629 }
5630 
5631 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5632 				 struct desc_struct *desc, u32 base3,
5633 				 int seg)
5634 {
5635 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5636 	struct kvm_segment var;
5637 
5638 	var.selector = selector;
5639 	var.base = get_desc_base(desc);
5640 #ifdef CONFIG_X86_64
5641 	var.base |= ((u64)base3) << 32;
5642 #endif
5643 	var.limit = get_desc_limit(desc);
5644 	if (desc->g)
5645 		var.limit = (var.limit << 12) | 0xfff;
5646 	var.type = desc->type;
5647 	var.dpl = desc->dpl;
5648 	var.db = desc->d;
5649 	var.s = desc->s;
5650 	var.l = desc->l;
5651 	var.g = desc->g;
5652 	var.avl = desc->avl;
5653 	var.present = desc->p;
5654 	var.unusable = !var.present;
5655 	var.padding = 0;
5656 
5657 	kvm_set_segment(vcpu, &var, seg);
5658 	return;
5659 }
5660 
5661 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
5662 					u32 msr_index, u64 *pdata)
5663 {
5664 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5665 
5666 	return kvm_emulator_get_msr_with_filter(vcpu, msr_index, pdata);
5667 }
5668 
5669 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
5670 					u32 msr_index, u64 data)
5671 {
5672 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5673 
5674 	return kvm_emulator_set_msr_with_filter(vcpu, msr_index, data);
5675 }
5676 
5677 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5678 			    u32 msr_index, u64 *pdata)
5679 {
5680 	return kvm_emulator_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
5681 }
5682 
5683 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
5684 {
5685 	return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
5686 }
5687 
5688 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5689 			     u32 pmc, u64 *pdata)
5690 {
5691 	return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5692 }
5693 
5694 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5695 {
5696 	emul_to_vcpu(ctxt)->arch.halt_request = 1;
5697 }
5698 
5699 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5700 			      struct x86_instruction_info *info,
5701 			      enum x86_intercept_stage stage)
5702 {
5703 	return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
5704 					     &ctxt->exception);
5705 }
5706 
5707 static bool emulator_is_cpuid_allowed(struct x86_emulate_ctxt *ctxt)
5708 {
5709 	return kvm_is_cpuid_allowed(emul_to_vcpu(ctxt));
5710 }
5711 
5712 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5713 			      u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
5714 			      bool exact_only)
5715 {
5716 	return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
5717 }
5718 
5719 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
5720 {
5721 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
5722 }
5723 
5724 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
5725 {
5726 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
5727 }
5728 
5729 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
5730 {
5731 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
5732 }
5733 
5734 static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
5735 {
5736 	return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
5737 }
5738 
5739 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5740 {
5741 	return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
5742 }
5743 
5744 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5745 {
5746 	kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
5747 }
5748 
5749 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5750 {
5751 	kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
5752 }
5753 
5754 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
5755 {
5756 	return is_smm(emul_to_vcpu(ctxt));
5757 }
5758 
5759 #ifndef CONFIG_KVM_SMM
5760 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
5761 {
5762 	WARN_ON_ONCE(1);
5763 	return X86EMUL_UNHANDLEABLE;
5764 }
5765 #endif
5766 
5767 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
5768 {
5769 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
5770 }
5771 
5772 static int emulator_get_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 *xcr)
5773 {
5774 	if (index != XCR_XFEATURE_ENABLED_MASK)
5775 		return 1;
5776 	*xcr = emul_to_vcpu(ctxt)->arch.xcr0;
5777 	return 0;
5778 }
5779 
5780 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
5781 {
5782 	return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
5783 }
5784 
5785 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
5786 {
5787 	struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
5788 
5789 	if (!kvm->vm_bugged)
5790 		kvm_vm_bugged(kvm);
5791 }
5792 
5793 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
5794 					gva_t addr, unsigned int flags)
5795 {
5796 	if (!kvm_x86_ops.get_untagged_addr)
5797 		return addr;
5798 
5799 	return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
5800 					       addr, flags);
5801 }
5802 
5803 static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
5804 				       gva_t addr, unsigned int flags)
5805 {
5806 	return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
5807 }
5808 
5809 static bool emulator_page_address_valid(struct x86_emulate_ctxt *ctxt, gpa_t gpa)
5810 {
5811 	return page_address_valid(emul_to_vcpu(ctxt), gpa);
5812 }
5813 
5814 static const struct x86_emulate_ops emulate_ops = {
5815 	.vm_bugged           = emulator_vm_bugged,
5816 	.read_gpr            = emulator_read_gpr,
5817 	.write_gpr           = emulator_write_gpr,
5818 	.read_std            = emulator_read_std,
5819 	.write_std           = emulator_write_std,
5820 	.fetch               = kvm_fetch_guest_virt,
5821 	.read_emulated       = emulator_read_emulated,
5822 	.write_emulated      = emulator_write_emulated,
5823 	.cmpxchg_emulated    = emulator_cmpxchg_emulated,
5824 	.invlpg              = emulator_invlpg,
5825 	.pio_in_emulated     = emulator_pio_in_emulated,
5826 	.pio_out_emulated    = emulator_pio_out_emulated,
5827 	.get_segment         = emulator_get_segment,
5828 	.set_segment         = emulator_set_segment,
5829 	.get_cached_segment_base = emulator_get_cached_segment_base,
5830 	.get_gdt             = emulator_get_gdt,
5831 	.get_idt	     = emulator_get_idt,
5832 	.set_gdt             = emulator_set_gdt,
5833 	.set_idt	     = emulator_set_idt,
5834 	.get_cr              = emulator_get_cr,
5835 	.set_cr              = emulator_set_cr,
5836 	.cpl                 = emulator_get_cpl,
5837 	.get_effective_dr7   = emulator_get_effective_dr7,
5838 	.get_dr              = emulator_get_dr,
5839 	.set_dr              = emulator_set_dr,
5840 	.set_msr_with_filter = emulator_set_msr_with_filter,
5841 	.get_msr_with_filter = emulator_get_msr_with_filter,
5842 	.get_msr             = emulator_get_msr,
5843 	.check_rdpmc_early   = emulator_check_rdpmc_early,
5844 	.read_pmc            = emulator_read_pmc,
5845 	.halt                = emulator_halt,
5846 	.wbinvd              = emulator_wbinvd,
5847 	.fix_hypercall       = emulator_fix_hypercall,
5848 	.intercept           = emulator_intercept,
5849 	.is_cpuid_allowed    = emulator_is_cpuid_allowed,
5850 	.get_cpuid           = emulator_get_cpuid,
5851 	.guest_has_movbe     = emulator_guest_has_movbe,
5852 	.guest_has_fxsr      = emulator_guest_has_fxsr,
5853 	.guest_has_rdpid     = emulator_guest_has_rdpid,
5854 	.guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
5855 	.set_nmi_mask        = emulator_set_nmi_mask,
5856 	.is_smm              = emulator_is_smm,
5857 	.leave_smm           = emulator_leave_smm,
5858 	.triple_fault        = emulator_triple_fault,
5859 	.get_xcr             = emulator_get_xcr,
5860 	.set_xcr             = emulator_set_xcr,
5861 	.get_untagged_addr   = emulator_get_untagged_addr,
5862 	.is_canonical_addr   = emulator_is_canonical_addr,
5863 	.page_address_valid  = emulator_page_address_valid,
5864 };
5865 
5866 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5867 {
5868 	u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
5869 	/*
5870 	 * an sti; sti; sequence only disable interrupts for the first
5871 	 * instruction. So, if the last instruction, be it emulated or
5872 	 * not, left the system with the INT_STI flag enabled, it
5873 	 * means that the last instruction is an sti. We should not
5874 	 * leave the flag on in this case. The same goes for mov ss
5875 	 */
5876 	if (int_shadow & mask)
5877 		mask = 0;
5878 	if (unlikely(int_shadow || mask)) {
5879 		kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
5880 		if (!mask)
5881 			kvm_make_request(KVM_REQ_EVENT, vcpu);
5882 	}
5883 }
5884 
5885 static int kvm_inject_emulated_db(struct kvm_vcpu *vcpu, unsigned long dr6)
5886 {
5887 	struct kvm_run *kvm_run = vcpu->run;
5888 
5889 	if (vcpu->guest_debug & (KVM_GUESTDBG_USE_HW_BP | KVM_GUESTDBG_SINGLESTEP)) {
5890 		kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
5891 		kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5892 		kvm_run->debug.arch.exception = DB_VECTOR;
5893 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
5894 		return 0;
5895 	}
5896 
5897 	kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
5898 	return 1;
5899 }
5900 
5901 static int inject_emulated_exception(struct kvm_vcpu *vcpu)
5902 {
5903 	struct x86_exception *ex = &vcpu->arch.emulate_ctxt->exception;
5904 
5905 	if (ex->vector == DB_VECTOR)
5906 		return kvm_inject_emulated_db(vcpu, ex->dr6);
5907 
5908 	if (ex->vector == PF_VECTOR)
5909 		kvm_inject_emulated_page_fault(vcpu, ex);
5910 	else if (ex->error_code_valid)
5911 		kvm_queue_exception_e(vcpu, ex->vector, ex->error_code);
5912 	else
5913 		kvm_queue_exception(vcpu, ex->vector);
5914 	return 1;
5915 }
5916 
5917 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
5918 {
5919 	struct x86_emulate_ctxt *ctxt;
5920 
5921 	ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
5922 	if (!ctxt) {
5923 		pr_err("failed to allocate vcpu's emulator\n");
5924 		return NULL;
5925 	}
5926 
5927 	ctxt->vcpu = vcpu;
5928 	ctxt->ops = &emulate_ops;
5929 	vcpu->arch.emulate_ctxt = ctxt;
5930 
5931 	return ctxt;
5932 }
5933 
5934 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5935 {
5936 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
5937 	int cs_db, cs_l;
5938 
5939 	kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
5940 
5941 	ctxt->gpa_available = false;
5942 	ctxt->eflags = kvm_get_rflags(vcpu);
5943 	ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5944 
5945 	ctxt->eip = kvm_rip_read(vcpu);
5946 	ctxt->mode = (!is_protmode(vcpu))		? X86EMUL_MODE_REAL :
5947 		     (ctxt->eflags & X86_EFLAGS_VM)	? X86EMUL_MODE_VM86 :
5948 		     (cs_l && is_long_mode(vcpu))	? X86EMUL_MODE_PROT64 :
5949 		     cs_db				? X86EMUL_MODE_PROT32 :
5950 							  X86EMUL_MODE_PROT16;
5951 	ctxt->interruptibility = 0;
5952 	ctxt->have_exception = false;
5953 	ctxt->exception.vector = -1;
5954 	ctxt->exception.payload = 0;
5955 	ctxt->perm_ok = false;
5956 
5957 	init_decode_cache(ctxt);
5958 	vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5959 }
5960 
5961 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5962 {
5963 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
5964 	int ret;
5965 
5966 	init_emulate_ctxt(vcpu);
5967 
5968 	ctxt->op_bytes = 2;
5969 	ctxt->ad_bytes = 2;
5970 	ctxt->_eip = ctxt->eip + inc_eip;
5971 	ret = emulate_int_real(ctxt, irq);
5972 
5973 	if (ret != X86EMUL_CONTINUE) {
5974 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5975 	} else {
5976 		ctxt->eip = ctxt->_eip;
5977 		kvm_rip_write(vcpu, ctxt->eip);
5978 		kvm_set_rflags(vcpu, ctxt->eflags);
5979 	}
5980 }
5981 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_realmode_interrupt);
5982 
5983 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
5984 					   u8 ndata, u8 *insn_bytes, u8 insn_size)
5985 {
5986 	struct kvm_run *run = vcpu->run;
5987 	u64 info[5];
5988 	u8 info_start;
5989 
5990 	/*
5991 	 * Zero the whole array used to retrieve the exit info, as casting to
5992 	 * u32 for select entries will leave some chunks uninitialized.
5993 	 */
5994 	memset(&info, 0, sizeof(info));
5995 
5996 	kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
5997 				    (u32 *)&info[3], (u32 *)&info[4]);
5998 
5999 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6000 	run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
6001 
6002 	/*
6003 	 * There's currently space for 13 entries, but 5 are used for the exit
6004 	 * reason and info.  Restrict to 4 to reduce the maintenance burden
6005 	 * when expanding kvm_run.emulation_failure in the future.
6006 	 */
6007 	if (WARN_ON_ONCE(ndata > 4))
6008 		ndata = 4;
6009 
6010 	/* Always include the flags as a 'data' entry. */
6011 	info_start = 1;
6012 	run->emulation_failure.flags = 0;
6013 
6014 	if (insn_size) {
6015 		BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
6016 			      sizeof(run->emulation_failure.insn_bytes) != 16));
6017 		info_start += 2;
6018 		run->emulation_failure.flags |=
6019 			KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
6020 		run->emulation_failure.insn_size = insn_size;
6021 		memset(run->emulation_failure.insn_bytes, 0x90,
6022 		       sizeof(run->emulation_failure.insn_bytes));
6023 		memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
6024 	}
6025 
6026 	memcpy(&run->internal.data[info_start], info, sizeof(info));
6027 	memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
6028 	       ndata * sizeof(data[0]));
6029 
6030 	run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
6031 }
6032 
6033 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
6034 {
6035 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6036 
6037 	prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
6038 				       ctxt->fetch.end - ctxt->fetch.data);
6039 }
6040 
6041 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
6042 					  u8 ndata)
6043 {
6044 	prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
6045 }
6046 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_prepare_emulation_failure_exit);
6047 
6048 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
6049 {
6050 	__kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
6051 }
6052 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_emulation_failure_exit);
6053 
6054 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa)
6055 {
6056 	u32 reason, intr_info, error_code;
6057 	struct kvm_run *run = vcpu->run;
6058 	u64 info1, info2;
6059 	int ndata = 0;
6060 
6061 	kvm_x86_call(get_exit_info)(vcpu, &reason, &info1, &info2,
6062 				    &intr_info, &error_code);
6063 
6064 	run->internal.data[ndata++] = info2;
6065 	run->internal.data[ndata++] = reason;
6066 	run->internal.data[ndata++] = info1;
6067 	run->internal.data[ndata++] = gpa;
6068 	run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6069 
6070 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6071 	run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6072 	run->internal.ndata = ndata;
6073 }
6074 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_event_vectoring_exit);
6075 
6076 void kvm_prepare_unexpected_reason_exit(struct kvm_vcpu *vcpu, u64 exit_reason)
6077 {
6078 	vcpu_unimpl(vcpu, "unexpected exit reason 0x%llx\n", exit_reason);
6079 
6080 	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6081 	vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6082 	vcpu->run->internal.ndata = 2;
6083 	vcpu->run->internal.data[0] = exit_reason;
6084 	vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6085 }
6086 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_unexpected_reason_exit);
6087 
6088 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6089 {
6090 	struct kvm *kvm = vcpu->kvm;
6091 
6092 	++vcpu->stat.insn_emulation_fail;
6093 	trace_kvm_emulate_insn_failed(vcpu);
6094 
6095 	if (emulation_type & EMULTYPE_VMWARE_GP) {
6096 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6097 		return 1;
6098 	}
6099 
6100 	if (kvm->arch.exit_on_emulation_error ||
6101 	    (emulation_type & EMULTYPE_SKIP)) {
6102 		prepare_emulation_ctxt_failure_exit(vcpu);
6103 		return 0;
6104 	}
6105 
6106 	kvm_queue_exception(vcpu, UD_VECTOR);
6107 
6108 	if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
6109 		prepare_emulation_ctxt_failure_exit(vcpu);
6110 		return 0;
6111 	}
6112 
6113 	return 1;
6114 }
6115 
6116 static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
6117 					       gpa_t cr2_or_gpa,
6118 					       int emulation_type)
6119 {
6120 	if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6121 		return false;
6122 
6123 	/*
6124 	 * If the failed instruction faulted on an access to page tables that
6125 	 * are used to translate any part of the instruction, KVM can't resolve
6126 	 * the issue by unprotecting the gfn, as zapping the shadow page will
6127 	 * result in the instruction taking a !PRESENT page fault and thus put
6128 	 * the vCPU into an infinite loop of page faults.  E.g. KVM will create
6129 	 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
6130 	 * then zap the SPTE to unprotect the gfn, and then do it all over
6131 	 * again.  Report the error to userspace.
6132 	 */
6133 	if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
6134 		return false;
6135 
6136 	/*
6137 	 * If emulation may have been triggered by a write to a shadowed page
6138 	 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
6139 	 * guest to let the CPU re-execute the instruction in the hope that the
6140 	 * CPU can cleanly execute the instruction that KVM failed to emulate.
6141 	 */
6142 	__kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
6143 
6144 	/*
6145 	 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
6146 	 * all SPTEs were already zapped by a different task.  The alternative
6147 	 * is to report the error to userspace and likely terminate the guest,
6148 	 * and the last_retry_{eip,addr} checks will prevent retrying the page
6149 	 * fault indefinitely, i.e. there's nothing to lose by retrying.
6150 	 */
6151 	return true;
6152 }
6153 
6154 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6155 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6156 
6157 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6158 				unsigned long *db)
6159 {
6160 	u32 dr6 = 0;
6161 	int i;
6162 	u32 enable, rwlen;
6163 
6164 	enable = dr7;
6165 	rwlen = dr7 >> 16;
6166 	for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6167 		if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6168 			dr6 |= (1 << i);
6169 	return dr6;
6170 }
6171 
6172 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6173 {
6174 	unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
6175 	int r;
6176 
6177 	r = kvm_x86_call(skip_emulated_instruction)(vcpu);
6178 	if (unlikely(!r))
6179 		return 0;
6180 
6181 	kvm_pmu_instruction_retired(vcpu);
6182 
6183 	/*
6184 	 * rflags is the old, "raw" value of the flags.  The new value has
6185 	 * not been saved yet.
6186 	 *
6187 	 * This is correct even for TF set by the guest, because "the
6188 	 * processor will not generate this exception after the instruction
6189 	 * that sets the TF flag".
6190 	 */
6191 	if (unlikely(rflags & X86_EFLAGS_TF))
6192 		r = kvm_inject_emulated_db(vcpu, DR6_BS);
6193 	return r;
6194 }
6195 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_skip_emulated_instruction);
6196 
6197 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
6198 {
6199 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
6200 		return false;
6201 
6202 	if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
6203 		return true;
6204 
6205 	/*
6206 	 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
6207 	 * active, but AMD compatible CPUs do not.
6208 	 */
6209 	if (!guest_cpuid_is_intel_compatible(vcpu))
6210 		return false;
6211 
6212 	return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
6213 }
6214 
6215 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
6216 					   int emulation_type, int *r)
6217 {
6218 	unsigned long dr7 = kvm_get_effective_dr7(vcpu);
6219 
6220 	WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
6221 
6222 	/*
6223 	 * Do not check for code breakpoints if hardware has already done the
6224 	 * checks, as inferred from the emulation type.  On NO_DECODE and SKIP,
6225 	 * the instruction has passed all exception checks, and all intercepted
6226 	 * exceptions that trigger emulation have lower priority than code
6227 	 * breakpoints, i.e. the fact that the intercepted exception occurred
6228 	 * means any code breakpoints have already been serviced.
6229 	 *
6230 	 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
6231 	 * hardware has checked the RIP of the magic prefix, but not the RIP of
6232 	 * the instruction being emulated.  The intent of forced emulation is
6233 	 * to behave as if KVM intercepted the instruction without an exception
6234 	 * and without a prefix.
6235 	 */
6236 	if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
6237 			      EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
6238 		return false;
6239 
6240 	if (unlikely(dr7 & DR7_BP_EN_MASK) &&
6241 	    !kvm_is_code_breakpoint_inhibited(vcpu)) {
6242 		unsigned long eip = kvm_get_linear_rip(vcpu);
6243 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0, dr7,
6244 					       vcpu->arch.eff_db);
6245 
6246 		if (dr6) {
6247 			*r = kvm_inject_emulated_db(vcpu, dr6);
6248 			return true;
6249 		}
6250 	}
6251 
6252 	return false;
6253 }
6254 
6255 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6256 {
6257 	switch (ctxt->opcode_len) {
6258 	case 1:
6259 		switch (ctxt->b) {
6260 		case 0xe4:	/* IN */
6261 		case 0xe5:
6262 		case 0xec:
6263 		case 0xed:
6264 		case 0xe6:	/* OUT */
6265 		case 0xe7:
6266 		case 0xee:
6267 		case 0xef:
6268 		case 0x6c:	/* INS */
6269 		case 0x6d:
6270 		case 0x6e:	/* OUTS */
6271 		case 0x6f:
6272 			return true;
6273 		}
6274 		break;
6275 	case 2:
6276 		switch (ctxt->b) {
6277 		case 0x33:	/* RDPMC */
6278 			return true;
6279 		}
6280 		break;
6281 	}
6282 
6283 	return false;
6284 }
6285 
6286 static bool is_soft_int_instruction(struct x86_emulate_ctxt *ctxt,
6287 				    int emulation_type)
6288 {
6289 	u8 vector = EMULTYPE_GET_SOFT_INT_VECTOR(emulation_type);
6290 
6291 	switch (ctxt->b) {
6292 	case 0xcc:
6293 		return vector == BP_VECTOR;
6294 	case 0xcd:
6295 		return vector == ctxt->src.val;
6296 	case 0xce:
6297 		return vector == OF_VECTOR;
6298 	default:
6299 		return false;
6300 	}
6301 }
6302 
6303 /*
6304  * Decode an instruction for emulation.  The caller is responsible for handling
6305  * code breakpoints.  Note, manually detecting code breakpoints is unnecessary
6306  * (and wrong) when emulating on an intercepted fault-like exception[*], as
6307  * code breakpoints have higher priority and thus have already been done by
6308  * hardware.
6309  *
6310  * [*] Except #MC, which is higher priority, but KVM should never emulate in
6311  *     response to a machine check.
6312  */
6313 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
6314 				    void *insn, int insn_len)
6315 {
6316 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6317 	int r;
6318 
6319 	init_emulate_ctxt(vcpu);
6320 
6321 	r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
6322 
6323 	trace_kvm_emulate_insn_start(vcpu);
6324 	++vcpu->stat.insn_emulation;
6325 
6326 	return r;
6327 }
6328 EXPORT_SYMBOL_FOR_KVM_INTERNAL(x86_decode_emulated_instruction);
6329 
6330 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6331 			    int emulation_type, void *insn, int insn_len)
6332 {
6333 	int r;
6334 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6335 	bool writeback = true;
6336 
6337 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
6338 	    (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6339 	     WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
6340 		emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
6341 
6342 	r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
6343 	if (r != X86EMUL_CONTINUE) {
6344 		if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
6345 			return 1;
6346 
6347 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
6348 						       emulation_type))
6349 			return 1;
6350 
6351 		if (r == X86EMUL_UNHANDLEABLE_VECTORING) {
6352 			kvm_prepare_event_vectoring_exit(vcpu, cr2_or_gpa);
6353 			return 0;
6354 		}
6355 
6356 		WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
6357 		return handle_emulation_failure(vcpu, emulation_type);
6358 	}
6359 
6360 	kvm_request_l1tf_flush_l1d();
6361 
6362 	if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6363 		kvm_clear_exception_queue(vcpu);
6364 
6365 		/*
6366 		 * Return immediately if RIP hits a code breakpoint, such #DBs
6367 		 * are fault-like and are higher priority than any faults on
6368 		 * the code fetch itself.
6369 		 */
6370 		if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
6371 			return r;
6372 
6373 		r = x86_decode_emulated_instruction(vcpu, emulation_type,
6374 						    insn, insn_len);
6375 		if (r != EMULATION_OK)  {
6376 			if ((emulation_type & EMULTYPE_TRAP_UD) ||
6377 			    (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6378 				kvm_queue_exception(vcpu, UD_VECTOR);
6379 				return 1;
6380 			}
6381 			if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
6382 							       emulation_type))
6383 				return 1;
6384 
6385 			if (ctxt->have_exception &&
6386 			    !(emulation_type & EMULTYPE_SKIP)) {
6387 				/*
6388 				 * #UD should result in just EMULATION_FAILED, and trap-like
6389 				 * exception should not be encountered during decode.
6390 				 */
6391 				WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6392 					     exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6393 				return inject_emulated_exception(vcpu);
6394 			}
6395 			return handle_emulation_failure(vcpu, emulation_type);
6396 		}
6397 	}
6398 
6399 	if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6400 	    !is_vmware_backdoor_opcode(ctxt)) {
6401 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6402 		return 1;
6403 	}
6404 
6405 	/*
6406 	 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
6407 	 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
6408 	 * The caller is responsible for updating interruptibility state and
6409 	 * injecting single-step #DBs.
6410 	 */
6411 	if (emulation_type & EMULTYPE_SKIP) {
6412 		if (emulation_type & EMULTYPE_SKIP_SOFT_INT &&
6413 		    !is_soft_int_instruction(ctxt, emulation_type))
6414 			return 0;
6415 
6416 		if (ctxt->mode != X86EMUL_MODE_PROT64)
6417 			ctxt->eip = (u32)ctxt->_eip;
6418 		else
6419 			ctxt->eip = ctxt->_eip;
6420 
6421 		if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
6422 			r = 1;
6423 			goto writeback;
6424 		}
6425 
6426 		kvm_rip_write(vcpu, ctxt->eip);
6427 		if (ctxt->eflags & X86_EFLAGS_RF)
6428 			kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6429 		return 1;
6430 	}
6431 
6432 	/*
6433 	 * If emulation was caused by a write-protection #PF on a non-page_table
6434 	 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
6435 	 * and retry the instruction, as the vCPU is likely no longer using the
6436 	 * gfn as a page table.
6437 	 */
6438 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
6439 	    !x86_page_table_writing_insn(ctxt) &&
6440 	    kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
6441 		return 1;
6442 
6443 	/* this is needed for vmware backdoor interface to work since it
6444 	   changes registers values  during IO operation */
6445 	if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6446 		vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6447 		emulator_invalidate_register_cache(ctxt);
6448 	}
6449 
6450 restart:
6451 	if (emulation_type & EMULTYPE_PF) {
6452 		/* Save the faulting GPA (cr2) in the address field */
6453 		ctxt->exception.address = cr2_or_gpa;
6454 
6455 		/* With shadow page tables, cr2 contains a GVA or nGPA. */
6456 		if (vcpu->arch.mmu->root_role.direct) {
6457 			ctxt->gpa_available = true;
6458 			ctxt->gpa_val = cr2_or_gpa;
6459 		}
6460 	} else {
6461 		/* Sanitize the address out of an abundance of paranoia. */
6462 		ctxt->exception.address = 0;
6463 	}
6464 
6465 	/*
6466 	 * Check L1's instruction intercepts when emulating instructions for
6467 	 * L2, unless KVM is re-emulating a previously decoded instruction,
6468 	 * e.g. to complete userspace I/O, in which case KVM has already
6469 	 * checked the intercepts.
6470 	 */
6471 	r = x86_emulate_insn(ctxt, is_guest_mode(vcpu) &&
6472 				   !(emulation_type & EMULTYPE_NO_DECODE));
6473 
6474 	if (r == EMULATION_INTERCEPTED)
6475 		return 1;
6476 
6477 	if (r == EMULATION_FAILED) {
6478 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
6479 						       emulation_type))
6480 			return 1;
6481 
6482 		return handle_emulation_failure(vcpu, emulation_type);
6483 	}
6484 
6485 	if (ctxt->have_exception) {
6486 		WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
6487 		vcpu->mmio_needed = false;
6488 		r = inject_emulated_exception(vcpu);
6489 	} else if (vcpu->arch.pio.count) {
6490 		if (!vcpu->arch.pio.in) {
6491 			/* FIXME: return into emulator if single-stepping.  */
6492 			vcpu->arch.pio.count = 0;
6493 		} else {
6494 			writeback = false;
6495 			vcpu->arch.complete_userspace_io = complete_emulated_pio;
6496 		}
6497 		r = 0;
6498 	} else if (vcpu->mmio_needed) {
6499 		++vcpu->stat.mmio_exits;
6500 
6501 		if (!vcpu->mmio_is_write)
6502 			writeback = false;
6503 		r = 0;
6504 		vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6505 	} else if (vcpu->arch.complete_userspace_io) {
6506 		writeback = false;
6507 		r = 0;
6508 	} else if (r == EMULATION_RESTART)
6509 		goto restart;
6510 	else
6511 		r = 1;
6512 
6513 writeback:
6514 	if (writeback) {
6515 		unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
6516 		toggle_interruptibility(vcpu, ctxt->interruptibility);
6517 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6518 
6519 		/*
6520 		 * Note, EXCPT_DB is assumed to be fault-like as the emulator
6521 		 * only supports code breakpoints and general detect #DB, both
6522 		 * of which are fault-like.
6523 		 */
6524 		if (!ctxt->have_exception ||
6525 		    exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
6526 			kvm_pmu_instruction_retired(vcpu);
6527 			if (ctxt->is_branch)
6528 				kvm_pmu_branch_retired(vcpu);
6529 			kvm_rip_write(vcpu, ctxt->eip);
6530 			if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
6531 				r = kvm_inject_emulated_db(vcpu, DR6_BS);
6532 			kvm_x86_call(update_emulated_instruction)(vcpu);
6533 			__kvm_set_rflags(vcpu, ctxt->eflags);
6534 		}
6535 
6536 		/*
6537 		 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
6538 		 * do nothing, and it will be requested again as soon as
6539 		 * the shadow expires.  But we still need to check here,
6540 		 * because POPF has no interrupt shadow.
6541 		 */
6542 		if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
6543 			kvm_make_request(KVM_REQ_EVENT, vcpu);
6544 	} else
6545 		vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
6546 
6547 	return r;
6548 }
6549 
6550 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
6551 {
6552 	return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
6553 }
6554 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction);
6555 
6556 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
6557 					void *insn, int insn_len)
6558 {
6559 	return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
6560 }
6561 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction_from_buffer);
6562 
6563 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
6564 {
6565 	vcpu->arch.pio.count = 0;
6566 	return 1;
6567 }
6568 
6569 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
6570 {
6571 	vcpu->arch.pio.count = 0;
6572 
6573 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip)))
6574 		return 1;
6575 
6576 	return kvm_skip_emulated_instruction(vcpu);
6577 }
6578 
6579 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
6580 			    unsigned short port)
6581 {
6582 	unsigned long val = kvm_rax_read_raw(vcpu);
6583 	int ret = emulator_pio_out(vcpu, size, port, &val, 1);
6584 
6585 	if (ret)
6586 		return ret;
6587 
6588 	/*
6589 	 * Workaround userspace that relies on old KVM behavior of %rip being
6590 	 * incremented prior to exiting to userspace to handle "OUT 0x7e".
6591 	 */
6592 	if (port == 0x7e &&
6593 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
6594 		vcpu->arch.complete_userspace_io =
6595 			complete_fast_pio_out_port_0x7e;
6596 		kvm_skip_emulated_instruction(vcpu);
6597 	} else {
6598 		vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
6599 		vcpu->arch.complete_userspace_io = complete_fast_pio_out;
6600 	}
6601 	return 0;
6602 }
6603 
6604 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
6605 {
6606 	unsigned long val;
6607 
6608 	/* We should only ever be called with arch.pio.count equal to 1 */
6609 	if (KVM_BUG_ON(vcpu->arch.pio.count != 1, vcpu->kvm))
6610 		return -EIO;
6611 
6612 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip))) {
6613 		vcpu->arch.pio.count = 0;
6614 		return 1;
6615 	}
6616 
6617 	/* For size less than 4 we merge, else we zero extend */
6618 	val = (vcpu->arch.pio.size < 4) ? kvm_rax_read_raw(vcpu) : 0;
6619 
6620 	complete_emulator_pio_in(vcpu, &val);
6621 	kvm_rax_write_raw(vcpu, val);
6622 
6623 	return kvm_skip_emulated_instruction(vcpu);
6624 }
6625 
6626 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
6627 			   unsigned short port)
6628 {
6629 	unsigned long val;
6630 	int ret;
6631 
6632 	/* For size less than 4 we merge, else we zero extend */
6633 	val = (size < 4) ? kvm_rax_read_raw(vcpu) : 0;
6634 
6635 	ret = emulator_pio_in(vcpu, size, port, &val, 1);
6636 	if (ret) {
6637 		kvm_rax_write_raw(vcpu, val);
6638 		return ret;
6639 	}
6640 
6641 	vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
6642 	vcpu->arch.complete_userspace_io = complete_fast_pio_in;
6643 
6644 	return 0;
6645 }
6646 
6647 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
6648 {
6649 	int ret;
6650 
6651 	if (in)
6652 		ret = kvm_fast_pio_in(vcpu, size, port);
6653 	else
6654 		ret = kvm_fast_pio_out(vcpu, size, port);
6655 	return ret && kvm_skip_emulated_instruction(vcpu);
6656 }
6657 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fast_pio);
6658 
6659 static int kvmclock_cpu_down_prep(unsigned int cpu)
6660 {
6661 	__this_cpu_write(cpu_tsc_khz, 0);
6662 	return 0;
6663 }
6664 
6665 static void tsc_khz_changed(void *data)
6666 {
6667 	struct cpufreq_freqs *freq = data;
6668 	unsigned long khz;
6669 
6670 	WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
6671 
6672 	if (data)
6673 		khz = freq->new;
6674 	else
6675 		khz = cpufreq_quick_get(raw_smp_processor_id());
6676 	if (!khz)
6677 		khz = tsc_khz;
6678 	__this_cpu_write(cpu_tsc_khz, khz);
6679 }
6680 
6681 #ifdef CONFIG_X86_64
6682 static void kvm_hyperv_tsc_notifier(void)
6683 {
6684 	struct kvm *kvm;
6685 	int cpu;
6686 
6687 	mutex_lock(&kvm_lock);
6688 	list_for_each_entry(kvm, &vm_list, vm_list)
6689 		kvm_make_mclock_inprogress_request(kvm);
6690 
6691 	/* no guest entries from this point */
6692 	hyperv_stop_tsc_emulation();
6693 
6694 	/* TSC frequency always matches when on Hyper-V */
6695 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
6696 		for_each_present_cpu(cpu)
6697 			per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
6698 	}
6699 	kvm_caps.max_guest_tsc_khz = tsc_khz;
6700 
6701 	list_for_each_entry(kvm, &vm_list, vm_list) {
6702 		__kvm_start_pvclock_update(kvm);
6703 		pvclock_update_vm_gtod_copy(kvm);
6704 		kvm_end_pvclock_update(kvm);
6705 	}
6706 
6707 	mutex_unlock(&kvm_lock);
6708 }
6709 #endif
6710 
6711 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
6712 {
6713 	struct kvm *kvm;
6714 	struct kvm_vcpu *vcpu;
6715 	int send_ipi = 0;
6716 	unsigned long i;
6717 
6718 	/*
6719 	 * We allow guests to temporarily run on slowing clocks,
6720 	 * provided we notify them after, or to run on accelerating
6721 	 * clocks, provided we notify them before.  Thus time never
6722 	 * goes backwards.
6723 	 *
6724 	 * However, we have a problem.  We can't atomically update
6725 	 * the frequency of a given CPU from this function; it is
6726 	 * merely a notifier, which can be called from any CPU.
6727 	 * Changing the TSC frequency at arbitrary points in time
6728 	 * requires a recomputation of local variables related to
6729 	 * the TSC for each VCPU.  We must flag these local variables
6730 	 * to be updated and be sure the update takes place with the
6731 	 * new frequency before any guests proceed.
6732 	 *
6733 	 * Unfortunately, the combination of hotplug CPU and frequency
6734 	 * change creates an intractable locking scenario; the order
6735 	 * of when these callouts happen is undefined with respect to
6736 	 * CPU hotplug, and they can race with each other.  As such,
6737 	 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
6738 	 * undefined; you can actually have a CPU frequency change take
6739 	 * place in between the computation of X and the setting of the
6740 	 * variable.  To protect against this problem, all updates of
6741 	 * the per_cpu tsc_khz variable are done in an interrupt
6742 	 * protected IPI, and all callers wishing to update the value
6743 	 * must wait for a synchronous IPI to complete (which is trivial
6744 	 * if the caller is on the CPU already).  This establishes the
6745 	 * necessary total order on variable updates.
6746 	 *
6747 	 * Note that because a guest time update may take place
6748 	 * anytime after the setting of the VCPU's request bit, the
6749 	 * correct TSC value must be set before the request.  However,
6750 	 * to ensure the update actually makes it to any guest which
6751 	 * starts running in hardware virtualization between the set
6752 	 * and the acquisition of the spinlock, we must also ping the
6753 	 * CPU after setting the request bit.
6754 	 *
6755 	 */
6756 
6757 	smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
6758 
6759 	mutex_lock(&kvm_lock);
6760 	list_for_each_entry(kvm, &vm_list, vm_list) {
6761 		kvm_for_each_vcpu(i, vcpu, kvm) {
6762 			if (vcpu->cpu != cpu)
6763 				continue;
6764 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6765 			if (vcpu->cpu != raw_smp_processor_id())
6766 				send_ipi = 1;
6767 		}
6768 	}
6769 	mutex_unlock(&kvm_lock);
6770 
6771 	if (freq->old < freq->new && send_ipi) {
6772 		/*
6773 		 * We upscale the frequency.  Must make the guest
6774 		 * doesn't see old kvmclock values while running with
6775 		 * the new frequency, otherwise we risk the guest sees
6776 		 * time go backwards.
6777 		 *
6778 		 * In case we update the frequency for another cpu
6779 		 * (which might be in guest context) send an interrupt
6780 		 * to kick the cpu out of guest context.  Next time
6781 		 * guest context is entered kvmclock will be updated,
6782 		 * so the guest will not see stale values.
6783 		 */
6784 		smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
6785 	}
6786 }
6787 
6788 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
6789 				     void *data)
6790 {
6791 	struct cpufreq_freqs *freq = data;
6792 	int cpu;
6793 
6794 	if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
6795 		return 0;
6796 	if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
6797 		return 0;
6798 
6799 	for_each_cpu(cpu, freq->policy->cpus)
6800 		__kvmclock_cpufreq_notifier(freq, cpu);
6801 
6802 	return 0;
6803 }
6804 
6805 static struct notifier_block kvmclock_cpufreq_notifier_block = {
6806 	.notifier_call  = kvmclock_cpufreq_notifier
6807 };
6808 
6809 static int kvmclock_cpu_online(unsigned int cpu)
6810 {
6811 	tsc_khz_changed(NULL);
6812 	return 0;
6813 }
6814 
6815 static void kvm_timer_init(void)
6816 {
6817 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
6818 		max_tsc_khz = tsc_khz;
6819 
6820 		if (IS_ENABLED(CONFIG_CPU_FREQ)) {
6821 			struct cpufreq_policy *policy;
6822 			int cpu;
6823 
6824 			cpu = get_cpu();
6825 			policy = cpufreq_cpu_get(cpu);
6826 			if (policy) {
6827 				if (policy->cpuinfo.max_freq)
6828 					max_tsc_khz = policy->cpuinfo.max_freq;
6829 				cpufreq_cpu_put(policy);
6830 			}
6831 			put_cpu();
6832 		}
6833 		cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
6834 					  CPUFREQ_TRANSITION_NOTIFIER);
6835 
6836 		cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
6837 				  kvmclock_cpu_online, kvmclock_cpu_down_prep);
6838 	}
6839 }
6840 
6841 #ifdef CONFIG_X86_64
6842 static void pvclock_gtod_update_fn(struct work_struct *work)
6843 {
6844 	struct kvm *kvm;
6845 	struct kvm_vcpu *vcpu;
6846 	unsigned long i;
6847 
6848 	mutex_lock(&kvm_lock);
6849 	list_for_each_entry(kvm, &vm_list, vm_list)
6850 		kvm_for_each_vcpu(i, vcpu, kvm)
6851 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
6852 	atomic_set(&kvm_guest_has_master_clock, 0);
6853 	mutex_unlock(&kvm_lock);
6854 }
6855 
6856 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
6857 
6858 /*
6859  * Indirection to move queue_work() out of the tk_core.seq write held
6860  * region to prevent possible deadlocks against time accessors which
6861  * are invoked with work related locks held.
6862  */
6863 static void pvclock_irq_work_fn(struct irq_work *w)
6864 {
6865 	queue_work(system_long_wq, &pvclock_gtod_work);
6866 }
6867 
6868 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
6869 
6870 /*
6871  * Notification about pvclock gtod data update.
6872  */
6873 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
6874 			       void *priv)
6875 {
6876 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
6877 	struct timekeeper *tk = priv;
6878 
6879 	update_pvclock_gtod(tk);
6880 
6881 	/*
6882 	 * Disable master clock if host does not trust, or does not use,
6883 	 * TSC based clocksource. Delegate queue_work() to irq_work as
6884 	 * this is invoked with tk_core.seq write held.
6885 	 */
6886 	if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
6887 	    atomic_read(&kvm_guest_has_master_clock) != 0)
6888 		irq_work_queue(&pvclock_irq_work);
6889 	return 0;
6890 }
6891 
6892 static struct notifier_block pvclock_gtod_notifier = {
6893 	.notifier_call = pvclock_gtod_notify,
6894 };
6895 #endif
6896 
6897 void kvm_setup_xss_caps(void)
6898 {
6899 	if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
6900 		kvm_caps.supported_xss = 0;
6901 
6902 	if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
6903 	    !kvm_cpu_cap_has(X86_FEATURE_IBT))
6904 		kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
6905 
6906 	if ((kvm_caps.supported_xss & XFEATURE_MASK_CET_ALL) != XFEATURE_MASK_CET_ALL) {
6907 		kvm_cpu_cap_clear(X86_FEATURE_SHSTK);
6908 		kvm_cpu_cap_clear(X86_FEATURE_IBT);
6909 		kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
6910 	}
6911 }
6912 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_setup_xss_caps);
6913 
6914 static void kvm_setup_efer_caps(void)
6915 {
6916 	/* Enable syscall by default because its emulated by KVM */
6917 	kvm_caps.supported_efer_bits = (u64)EFER_SCE;
6918 
6919 	if (kvm_cpu_cap_has(X86_FEATURE_LM))
6920 		kvm_caps.supported_efer_bits |= (EFER_LME | EFER_LMA);
6921 
6922 	if (kvm_cpu_cap_has(X86_FEATURE_NX))
6923 		kvm_caps.supported_efer_bits |= EFER_NX;
6924 
6925 	if (kvm_cpu_cap_has(X86_FEATURE_FXSR_OPT))
6926 		kvm_caps.supported_efer_bits |= EFER_FFXSR;
6927 
6928 	if (kvm_cpu_cap_has(X86_FEATURE_AUTOIBRS))
6929 		kvm_caps.supported_efer_bits |= EFER_AUTOIBRS;
6930 
6931 	if (kvm_cpu_cap_has(X86_FEATURE_SVM)) {
6932 		kvm_caps.supported_efer_bits |= EFER_SVME;
6933 		if (!boot_cpu_has(X86_FEATURE_EFER_LMSLE_MBZ))
6934 			kvm_caps.supported_efer_bits |= EFER_LMSLE;
6935 	}
6936 }
6937 
6938 static void kvm_nested_ops_update(const struct kvm_x86_nested_ops *nested_ops)
6939 {
6940 	memcpy(&kvm_nested_ops, nested_ops, sizeof(kvm_nested_ops));
6941 
6942 #define __KVM_X86_NESTED_OP(func) \
6943 	static_call_update(kvm_x86_nested_##func, kvm_nested_ops.func);
6944 #define KVM_X86_NESTED_OP(func) \
6945 	WARN_ON(!kvm_nested_ops.func); __KVM_X86_NESTED_OP(func)
6946 #define KVM_X86_NESTED_OP_OPTIONAL __KVM_X86_NESTED_OP
6947 #define KVM_X86_NESTED_OP_OPTIONAL_RET0(func) \
6948 	static_call_update(kvm_x86_nested_##func, (void *)kvm_nested_ops.func ? : \
6949 						  (void *)__static_call_return0);
6950 #include <asm/kvm-x86-nested-ops.h>
6951 #undef __KVM_X86_NESTED_OP
6952 }
6953 
6954 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
6955 {
6956 	memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
6957 
6958 #define __KVM_X86_OP(func) \
6959 	static_call_update(kvm_x86_##func, kvm_x86_ops.func);
6960 #define KVM_X86_OP(func) \
6961 	WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
6962 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
6963 #define KVM_X86_OP_OPTIONAL_RET0(func) \
6964 	static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
6965 					   (void *)__static_call_return0);
6966 #include <asm/kvm-x86-ops.h>
6967 #undef __KVM_X86_OP
6968 
6969 	kvm_nested_ops_update(ops->nested_ops);
6970 
6971 	kvm_pmu_ops_update(ops->pmu_ops);
6972 }
6973 
6974 static int kvm_x86_check_processor_compatibility(void)
6975 {
6976 	int cpu = smp_processor_id();
6977 	struct cpuinfo_x86 *c = &cpu_data(cpu);
6978 
6979 	/*
6980 	 * Compatibility checks are done when loading KVM and when enabling
6981 	 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
6982 	 * compatible, i.e. KVM should never perform a compatibility check on
6983 	 * an offline CPU.
6984 	 */
6985 	WARN_ON(!cpu_online(cpu));
6986 
6987 	if (__cr4_reserved_bits(cpu_has, c) !=
6988 	    __cr4_reserved_bits(cpu_has, &boot_cpu_data))
6989 		return -EIO;
6990 
6991 	return kvm_x86_call(check_processor_compatibility)();
6992 }
6993 
6994 static void kvm_x86_check_cpu_compat(void *ret)
6995 {
6996 	*(int *)ret = kvm_x86_check_processor_compatibility();
6997 }
6998 
6999 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
7000 {
7001 	u64 host_pat;
7002 	int r, cpu;
7003 
7004 	guard(mutex)(&vendor_module_lock);
7005 
7006 	if (kvm_x86_ops.enable_virtualization_cpu) {
7007 		pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
7008 		return -EEXIST;
7009 	}
7010 
7011 	/*
7012 	 * KVM explicitly assumes that the guest has an FPU and
7013 	 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7014 	 * vCPU's FPU state as a fxregs_state struct.
7015 	 */
7016 	if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7017 		pr_err("inadequate fpu\n");
7018 		return -EOPNOTSUPP;
7019 	}
7020 
7021 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7022 		pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
7023 		return -EOPNOTSUPP;
7024 	}
7025 
7026 	/*
7027 	 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
7028 	 * the PAT bits in SPTEs.  Bail if PAT[0] is programmed to something
7029 	 * other than WB.  Note, EPT doesn't utilize the PAT, but don't bother
7030 	 * with an exception.  PAT[0] is set to WB on RESET and also by the
7031 	 * kernel, i.e. failure indicates a kernel bug or broken firmware.
7032 	 */
7033 	if (rdmsrq_safe(MSR_IA32_CR_PAT, &host_pat) ||
7034 	    (host_pat & GENMASK(2, 0)) != 6) {
7035 		pr_err("host PAT[0] is not WB\n");
7036 		return -EIO;
7037 	}
7038 
7039 	if (boot_cpu_has(X86_FEATURE_SHSTK) || boot_cpu_has(X86_FEATURE_IBT)) {
7040 		rdmsrq(MSR_IA32_S_CET, kvm_host.s_cet);
7041 		/*
7042 		 * Linux doesn't yet support supervisor shadow stacks (SSS), so
7043 		 * KVM doesn't save/restore the associated MSRs, i.e. KVM may
7044 		 * clobber the host values.  Yell and refuse to load if SSS is
7045 		 * unexpectedly enabled, e.g. to avoid crashing the host.
7046 		 */
7047 		if (WARN_ON_ONCE(kvm_host.s_cet & CET_SHSTK_EN))
7048 			return -EIO;
7049 	}
7050 
7051 	memset(&kvm_caps, 0, sizeof(kvm_caps));
7052 
7053 	x86_emulator_cache = kvm_alloc_emulator_cache();
7054 	if (!x86_emulator_cache) {
7055 		pr_err("failed to allocate cache for x86 emulator\n");
7056 		return -ENOMEM;
7057 	}
7058 
7059 	r = kvm_mmu_vendor_module_init();
7060 	if (r)
7061 		goto out_free_x86_emulator_cache;
7062 
7063 	kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
7064 	kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
7065 
7066 	if (boot_cpu_has(X86_FEATURE_XSAVE)) {
7067 		kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7068 		kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
7069 	}
7070 
7071 	if (boot_cpu_has(X86_FEATURE_XSAVES)) {
7072 		rdmsrq(MSR_IA32_XSS, kvm_host.xss);
7073 		kvm_caps.supported_xss = kvm_host.xss & KVM_SUPPORTED_XSS;
7074 	}
7075 
7076 	kvm_caps.supported_quirks = KVM_X86_VALID_QUIRKS;
7077 	kvm_caps.inapplicable_quirks = KVM_X86_CONDITIONAL_QUIRKS;
7078 
7079 	rdmsrq_safe(MSR_EFER, &kvm_host.efer);
7080 
7081 	kvm_init_pmu_capability(ops->pmu_ops);
7082 
7083 	if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
7084 		rdmsrq(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
7085 
7086 	WARN_ON_ONCE(kvm_nr_uret_msrs);
7087 
7088 	r = ops->hardware_setup();
7089 	if (r != 0)
7090 		goto out_mmu_exit;
7091 
7092 	kvm_setup_efer_caps();
7093 
7094 	enable_device_posted_irqs &= enable_apicv &&
7095 				     irq_remapping_cap(IRQ_POSTING_CAP);
7096 
7097 	kvm_ops_update(ops);
7098 
7099 	for_each_online_cpu(cpu) {
7100 		smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
7101 		if (r < 0)
7102 			goto out_unwind_ops;
7103 	}
7104 
7105 	/*
7106 	 * Point of no return!  DO NOT add error paths below this point unless
7107 	 * absolutely necessary, as most operations from this point forward
7108 	 * require unwinding.
7109 	 */
7110 	kvm_timer_init();
7111 
7112 	if (pi_inject_timer == -1)
7113 		pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
7114 #ifdef CONFIG_X86_64
7115 	pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7116 
7117 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7118 		set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7119 #endif
7120 
7121 	__kvm_register_perf_callbacks(ops->handle_intel_pt_intr,
7122 				      enable_mediated_pmu ? kvm_handle_guest_mediated_pmi : NULL);
7123 
7124 	if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
7125 		kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
7126 
7127 	/* KVM always ignores guest PAT for shadow paging.  */
7128 	if (!tdp_enabled)
7129 		kvm_caps.supported_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT;
7130 
7131 	if (kvm_caps.has_tsc_control) {
7132 		/*
7133 		 * Make sure the user can only configure tsc_khz values that
7134 		 * fit into a signed integer.
7135 		 * A min value is not calculated because it will always
7136 		 * be 1 on all machines.
7137 		 */
7138 		u64 max = min(0x7fffffffULL,
7139 			      __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
7140 		kvm_caps.max_guest_tsc_khz = max;
7141 	}
7142 	kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
7143 	kvm_init_msr_lists();
7144 	return 0;
7145 
7146 out_unwind_ops:
7147 	kvm_x86_ops.enable_virtualization_cpu = NULL;
7148 	kvm_x86_call(hardware_unsetup)();
7149 out_mmu_exit:
7150 	kvm_destroy_user_return_msrs();
7151 	kvm_mmu_vendor_module_exit();
7152 out_free_x86_emulator_cache:
7153 	kmem_cache_destroy(x86_emulator_cache);
7154 	return r;
7155 }
7156 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_init);
7157 
7158 void kvm_x86_vendor_exit(void)
7159 {
7160 	kvm_unregister_perf_callbacks();
7161 
7162 #ifdef CONFIG_X86_64
7163 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7164 		clear_hv_tscchange_cb();
7165 #endif
7166 	kvm_lapic_exit();
7167 
7168 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7169 		cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7170 					    CPUFREQ_TRANSITION_NOTIFIER);
7171 		cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7172 	}
7173 #ifdef CONFIG_X86_64
7174 	pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7175 	irq_work_sync(&pvclock_irq_work);
7176 	cancel_work_sync(&pvclock_gtod_work);
7177 #endif
7178 	kvm_x86_call(hardware_unsetup)();
7179 	kvm_destroy_user_return_msrs();
7180 	kvm_mmu_vendor_module_exit();
7181 	kmem_cache_destroy(x86_emulator_cache);
7182 #ifdef CONFIG_KVM_XEN
7183 	static_key_deferred_flush(&kvm_xen_enabled);
7184 	WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
7185 #endif
7186 	mutex_lock(&vendor_module_lock);
7187 	kvm_x86_ops.enable_virtualization_cpu = NULL;
7188 	mutex_unlock(&vendor_module_lock);
7189 }
7190 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_exit);
7191 
7192 #ifdef CONFIG_X86_64
7193 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7194 			        unsigned long clock_type)
7195 {
7196 	struct kvm_clock_pairing clock_pairing;
7197 	struct timespec64 ts;
7198 	u64 cycle;
7199 	int ret;
7200 
7201 	if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7202 		return -KVM_EOPNOTSUPP;
7203 
7204 	/*
7205 	 * When tsc is in permanent catchup mode guests won't be able to use
7206 	 * pvclock_read_retry loop to get consistent view of pvclock
7207 	 */
7208 	if (vcpu->arch.tsc_always_catchup)
7209 		return -KVM_EOPNOTSUPP;
7210 
7211 	if (!kvm_get_walltime_and_clockread(&ts, &cycle))
7212 		return -KVM_EOPNOTSUPP;
7213 
7214 	clock_pairing.sec = ts.tv_sec;
7215 	clock_pairing.nsec = ts.tv_nsec;
7216 	clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7217 	clock_pairing.flags = 0;
7218 	memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7219 
7220 	ret = 0;
7221 	if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7222 			    sizeof(struct kvm_clock_pairing)))
7223 		ret = -KVM_EFAULT;
7224 
7225 	return ret;
7226 }
7227 #endif
7228 
7229 /*
7230  * kvm_pv_kick_cpu_op:  Kick a vcpu.
7231  *
7232  * @apicid - apicid of vcpu to be kicked.
7233  */
7234 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
7235 {
7236 	/*
7237 	 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
7238 	 * common code, e.g. for tracing. Defer initialization to the compiler.
7239 	 */
7240 	struct kvm_lapic_irq lapic_irq = {
7241 		.delivery_mode = APIC_DM_REMRD,
7242 		.dest_mode = APIC_DEST_PHYSICAL,
7243 		.shorthand = APIC_DEST_NOSHORT,
7244 		.dest_id = apicid,
7245 	};
7246 
7247 	kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq);
7248 }
7249 
7250 bool kvm_apicv_activated(struct kvm *kvm)
7251 {
7252 	return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
7253 }
7254 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_apicv_activated);
7255 
7256 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
7257 {
7258 	ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
7259 	ulong vcpu_reasons =
7260 			kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
7261 
7262 	return (vm_reasons | vcpu_reasons) == 0;
7263 }
7264 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_apicv_activated);
7265 
7266 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
7267 				       enum kvm_apicv_inhibit reason, bool set)
7268 {
7269 	const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
7270 
7271 	BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
7272 
7273 	if (set)
7274 		__set_bit(reason, inhibits);
7275 	else
7276 		__clear_bit(reason, inhibits);
7277 
7278 	trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
7279 }
7280 
7281 static void kvm_apicv_init(struct kvm *kvm)
7282 {
7283 	enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
7284 						       APICV_INHIBIT_REASON_DISABLED;
7285 
7286 	set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
7287 
7288 	init_rwsem(&kvm->arch.apicv_update_lock);
7289 }
7290 
7291 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
7292 {
7293 	struct kvm_vcpu *target = NULL;
7294 	struct kvm_apic_map *map;
7295 
7296 	vcpu->stat.directed_yield_attempted++;
7297 
7298 	if (single_task_running())
7299 		goto no_yield;
7300 
7301 	rcu_read_lock();
7302 	map = rcu_dereference(vcpu->kvm->arch.apic_map);
7303 
7304 	if (likely(map) && dest_id <= map->max_apic_id) {
7305 		dest_id = array_index_nospec(dest_id, map->max_apic_id + 1);
7306 		if (map->phys_map[dest_id])
7307 			target = map->phys_map[dest_id]->vcpu;
7308 	}
7309 
7310 	rcu_read_unlock();
7311 
7312 	if (!target || !READ_ONCE(target->ready))
7313 		goto no_yield;
7314 
7315 	/* Ignore requests to yield to self */
7316 	if (vcpu == target)
7317 		goto no_yield;
7318 
7319 	if (kvm_vcpu_yield_to(target) <= 0)
7320 		goto no_yield;
7321 
7322 	vcpu->stat.directed_yield_successful++;
7323 
7324 no_yield:
7325 	return;
7326 }
7327 
7328 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
7329 {
7330 	u64 ret = vcpu->run->hypercall.ret;
7331 
7332 	if (!is_64_bit_hypercall(vcpu))
7333 		ret = (u32)ret;
7334 	kvm_rax_write_raw(vcpu, ret);
7335 	return kvm_skip_emulated_instruction(vcpu);
7336 }
7337 
7338 int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
7339 			      int (*complete_hypercall)(struct kvm_vcpu *))
7340 {
7341 	int op_64_bit = is_64_bit_hypercall(vcpu);
7342 	unsigned long ret, nr, a0, a1, a2, a3;
7343 
7344 	++vcpu->stat.hypercalls;
7345 
7346 	if (op_64_bit) {
7347 		nr = kvm_rax_read_raw(vcpu);
7348 		a0 = kvm_rbx_read_raw(vcpu);
7349 		a1 = kvm_rcx_read_raw(vcpu);
7350 		a2 = kvm_rdx_read_raw(vcpu);
7351 		a3 = kvm_rsi_read_raw(vcpu);
7352 	} else {
7353 		nr = kvm_eax_read(vcpu);
7354 		a0 = kvm_ebx_read(vcpu);
7355 		a1 = kvm_ecx_read(vcpu);
7356 		a2 = kvm_edx_read(vcpu);
7357 		a3 = kvm_esi_read(vcpu);
7358 	}
7359 
7360 	trace_kvm_hypercall(nr, a0, a1, a2, a3);
7361 
7362 	if (cpl) {
7363 		ret = -KVM_EPERM;
7364 		goto out;
7365 	}
7366 
7367 	ret = -KVM_ENOSYS;
7368 
7369 	switch (nr) {
7370 	case KVM_HC_VAPIC_POLL_IRQ:
7371 		ret = 0;
7372 		break;
7373 	case KVM_HC_KICK_CPU:
7374 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
7375 			break;
7376 
7377 		kvm_pv_kick_cpu_op(vcpu->kvm, a1);
7378 		kvm_sched_yield(vcpu, a1);
7379 		ret = 0;
7380 		break;
7381 #ifdef CONFIG_X86_64
7382 	case KVM_HC_CLOCK_PAIRING:
7383 		ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7384 		break;
7385 #endif
7386 	case KVM_HC_SEND_IPI:
7387 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
7388 			break;
7389 
7390 		ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7391 		break;
7392 	case KVM_HC_SCHED_YIELD:
7393 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
7394 			break;
7395 
7396 		kvm_sched_yield(vcpu, a0);
7397 		ret = 0;
7398 		break;
7399 	case KVM_HC_MAP_GPA_RANGE: {
7400 		u64 gpa = a0, npages = a1, attrs = a2;
7401 
7402 		ret = -KVM_ENOSYS;
7403 		if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE))
7404 			break;
7405 
7406 		if (!PAGE_ALIGNED(gpa) || !npages ||
7407 		    gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
7408 			ret = -KVM_EINVAL;
7409 			break;
7410 		}
7411 
7412 		vcpu->run->exit_reason        = KVM_EXIT_HYPERCALL;
7413 		vcpu->run->hypercall.nr       = KVM_HC_MAP_GPA_RANGE;
7414 		/*
7415 		 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
7416 		 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
7417 		 * it was always zero on KVM_EXIT_HYPERCALL.  Since KVM is now overwriting
7418 		 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
7419 		 */
7420 		vcpu->run->hypercall.ret = 0;
7421 		vcpu->run->hypercall.args[0]  = gpa;
7422 		vcpu->run->hypercall.args[1]  = npages;
7423 		vcpu->run->hypercall.args[2]  = attrs;
7424 		vcpu->run->hypercall.flags    = 0;
7425 		if (op_64_bit)
7426 			vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
7427 
7428 		WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
7429 		vcpu->arch.complete_userspace_io = complete_hypercall;
7430 		return 0;
7431 	}
7432 	default:
7433 		ret = -KVM_ENOSYS;
7434 		break;
7435 	}
7436 
7437 out:
7438 	vcpu->run->hypercall.ret = ret;
7439 	return 1;
7440 }
7441 EXPORT_SYMBOL_FOR_KVM_INTERNAL(____kvm_emulate_hypercall);
7442 
7443 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7444 {
7445 	if (kvm_xen_hypercall_enabled(vcpu->kvm))
7446 		return kvm_xen_hypercall(vcpu);
7447 
7448 	if (kvm_hv_hypercall_enabled(vcpu))
7449 		return kvm_hv_hypercall(vcpu);
7450 
7451 	return __kvm_emulate_hypercall(vcpu, kvm_x86_call(get_cpl)(vcpu),
7452 				       complete_hypercall_exit);
7453 }
7454 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_hypercall);
7455 
7456 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7457 {
7458 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7459 	char instruction[3];
7460 	unsigned long rip = kvm_rip_read(vcpu);
7461 
7462 	/*
7463 	 * If the quirk is disabled, synthesize a #UD and let the guest pick up
7464 	 * the pieces.
7465 	 */
7466 	if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
7467 		ctxt->exception.error_code_valid = false;
7468 		ctxt->exception.vector = UD_VECTOR;
7469 		ctxt->have_exception = true;
7470 		return X86EMUL_PROPAGATE_FAULT;
7471 	}
7472 
7473 	kvm_x86_call(patch_hypercall)(vcpu, instruction);
7474 
7475 	return emulator_write_emulated(ctxt, rip, instruction, 3,
7476 		&ctxt->exception);
7477 }
7478 
7479 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7480 {
7481 	return vcpu->run->request_interrupt_window &&
7482 		likely(!pic_in_kernel(vcpu->kvm));
7483 }
7484 
7485 /* Called within kvm->srcu read side.  */
7486 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7487 {
7488 	struct kvm_run *kvm_run = vcpu->run;
7489 
7490 	kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
7491 	kvm_run->cr8 = kvm_get_cr8(vcpu);
7492 	kvm_run->apic_base = vcpu->arch.apic_base;
7493 
7494 	kvm_run->ready_for_interrupt_injection =
7495 		pic_in_kernel(vcpu->kvm) ||
7496 		kvm_vcpu_ready_for_interrupt_injection(vcpu);
7497 
7498 	if (is_smm(vcpu))
7499 		kvm_run->flags |= KVM_RUN_X86_SMM;
7500 	if (is_guest_mode(vcpu))
7501 		kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
7502 }
7503 
7504 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
7505 {
7506 	if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
7507 		kvm_nested_call(triple_fault)(vcpu);
7508 		return 1;
7509 	}
7510 
7511 	return kvm_nested_call(check_events)(vcpu);
7512 }
7513 
7514 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
7515 {
7516 	/*
7517 	 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
7518 	 * exceptions don't report error codes.  The presence of an error code
7519 	 * is carried with the exception and only stripped when the exception
7520 	 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
7521 	 * report an error code despite the CPU being in Real Mode.
7522 	 */
7523 	vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
7524 
7525 	trace_kvm_inj_exception(vcpu->arch.exception.vector,
7526 				vcpu->arch.exception.has_error_code,
7527 				vcpu->arch.exception.error_code,
7528 				vcpu->arch.exception.injected);
7529 
7530 	kvm_x86_call(inject_exception)(vcpu);
7531 }
7532 
7533 /*
7534  * Check for any event (interrupt or exception) that is ready to be injected,
7535  * and if there is at least one event, inject the event with the highest
7536  * priority.  This handles both "pending" events, i.e. events that have never
7537  * been injected into the guest, and "injected" events, i.e. events that were
7538  * injected as part of a previous VM-Enter, but weren't successfully delivered
7539  * and need to be re-injected.
7540  *
7541  * Note, this is not guaranteed to be invoked on a guest instruction boundary,
7542  * i.e. doesn't guarantee that there's an event window in the guest.  KVM must
7543  * be able to inject exceptions in the "middle" of an instruction, and so must
7544  * also be able to re-inject NMIs and IRQs in the middle of an instruction.
7545  * I.e. for exceptions and re-injected events, NOT invoking this on instruction
7546  * boundaries is necessary and correct.
7547  *
7548  * For simplicity, KVM uses a single path to inject all events (except events
7549  * that are injected directly from L1 to L2) and doesn't explicitly track
7550  * instruction boundaries for asynchronous events.  However, because VM-Exits
7551  * that can occur during instruction execution typically result in KVM skipping
7552  * the instruction or injecting an exception, e.g. instruction and exception
7553  * intercepts, and because pending exceptions have higher priority than pending
7554  * interrupts, KVM still honors instruction boundaries in most scenarios.
7555  *
7556  * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
7557  * the instruction or inject an exception, then KVM can incorrecty inject a new
7558  * asynchronous event if the event became pending after the CPU fetched the
7559  * instruction (in the guest).  E.g. if a page fault (#PF, #NPF, EPT violation)
7560  * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
7561  * injected on the restarted instruction instead of being deferred until the
7562  * instruction completes.
7563  *
7564  * In practice, this virtualization hole is unlikely to be observed by the
7565  * guest, and even less likely to cause functional problems.  To detect the
7566  * hole, the guest would have to trigger an event on a side effect of an early
7567  * phase of instruction execution, e.g. on the instruction fetch from memory.
7568  * And for it to be a functional problem, the guest would need to depend on the
7569  * ordering between that side effect, the instruction completing, _and_ the
7570  * delivery of the asynchronous event.
7571  */
7572 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
7573 				       bool *req_immediate_exit)
7574 {
7575 	bool can_inject;
7576 	int r;
7577 
7578 	/*
7579 	 * Process nested events first, as nested VM-Exit supersedes event
7580 	 * re-injection.  If there's an event queued for re-injection, it will
7581 	 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
7582 	 */
7583 	if (is_guest_mode(vcpu))
7584 		r = kvm_check_nested_events(vcpu);
7585 	else
7586 		r = 0;
7587 
7588 	/*
7589 	 * Re-inject exceptions and events *especially* if immediate entry+exit
7590 	 * to/from L2 is needed, as any event that has already been injected
7591 	 * into L2 needs to complete its lifecycle before injecting a new event.
7592 	 *
7593 	 * Don't re-inject an NMI or interrupt if there is a pending exception.
7594 	 * This collision arises if an exception occurred while vectoring the
7595 	 * injected event, KVM intercepted said exception, and KVM ultimately
7596 	 * determined the fault belongs to the guest and queues the exception
7597 	 * for injection back into the guest.
7598 	 *
7599 	 * "Injected" interrupts can also collide with pending exceptions if
7600 	 * userspace ignores the "ready for injection" flag and blindly queues
7601 	 * an interrupt.  In that case, prioritizing the exception is correct,
7602 	 * as the exception "occurred" before the exit to userspace.  Trap-like
7603 	 * exceptions, e.g. most #DBs, have higher priority than interrupts.
7604 	 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
7605 	 * priority, they're only generated (pended) during instruction
7606 	 * execution, and interrupts are recognized at instruction boundaries.
7607 	 * Thus a pending fault-like exception means the fault occurred on the
7608 	 * *previous* instruction and must be serviced prior to recognizing any
7609 	 * new events in order to fully complete the previous instruction.
7610 	 */
7611 	if (vcpu->arch.exception.injected)
7612 		kvm_inject_exception(vcpu);
7613 	else if (kvm_is_exception_pending(vcpu))
7614 		; /* see above */
7615 	else if (vcpu->arch.nmi_injected)
7616 		kvm_x86_call(inject_nmi)(vcpu);
7617 	else if (vcpu->arch.interrupt.injected)
7618 		kvm_x86_call(inject_irq)(vcpu, true);
7619 
7620 	/*
7621 	 * Exceptions that morph to VM-Exits are handled above, and pending
7622 	 * exceptions on top of injected exceptions that do not VM-Exit should
7623 	 * either morph to #DF or, sadly, override the injected exception.
7624 	 */
7625 	WARN_ON_ONCE(vcpu->arch.exception.injected &&
7626 		     vcpu->arch.exception.pending);
7627 
7628 	/*
7629 	 * Bail if immediate entry+exit to/from the guest is needed to complete
7630 	 * nested VM-Enter or event re-injection so that a different pending
7631 	 * event can be serviced (or if KVM needs to exit to userspace).
7632 	 *
7633 	 * Otherwise, continue processing events even if VM-Exit occurred.  The
7634 	 * VM-Exit will have cleared exceptions that were meant for L2, but
7635 	 * there may now be events that can be injected into L1.
7636 	 */
7637 	if (r < 0)
7638 		goto out;
7639 
7640 	/*
7641 	 * A pending exception VM-Exit should either result in nested VM-Exit
7642 	 * or force an immediate re-entry and exit to/from L2, and exception
7643 	 * VM-Exits cannot be injected (flag should _never_ be set).
7644 	 */
7645 	WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
7646 		     vcpu->arch.exception_vmexit.pending);
7647 
7648 	/*
7649 	 * New events, other than exceptions, cannot be injected if KVM needs
7650 	 * to re-inject a previous event.  See above comments on re-injecting
7651 	 * for why pending exceptions get priority.
7652 	 */
7653 	can_inject = !kvm_event_needs_reinjection(vcpu);
7654 
7655 	if (vcpu->arch.exception.pending) {
7656 		/*
7657 		 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
7658 		 * value pushed on the stack.  Trap-like exception and all #DBs
7659 		 * leave RF as-is (KVM follows Intel's behavior in this regard;
7660 		 * AMD states that code breakpoint #DBs excplitly clear RF=0).
7661 		 *
7662 		 * Note, most versions of Intel's SDM and AMD's APM incorrectly
7663 		 * describe the behavior of General Detect #DBs, which are
7664 		 * fault-like.  They do _not_ set RF, a la code breakpoints.
7665 		 */
7666 		if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
7667 			__kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7668 					     X86_EFLAGS_RF);
7669 
7670 		if (vcpu->arch.exception.vector == DB_VECTOR &&
7671 		    vcpu->arch.dr7 & DR7_GD) {
7672 			vcpu->arch.dr7 &= ~DR7_GD;
7673 			kvm_update_dr7(vcpu);
7674 		}
7675 
7676 		kvm_inject_exception(vcpu);
7677 
7678 		vcpu->arch.exception.pending = false;
7679 		vcpu->arch.exception.injected = true;
7680 
7681 		can_inject = false;
7682 	}
7683 
7684 	/* Don't inject interrupts if the user asked to avoid doing so */
7685 	if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
7686 		return 0;
7687 
7688 	/*
7689 	 * Finally, inject interrupt events.  If an event cannot be injected
7690 	 * due to architectural conditions (e.g. IF=0) a window-open exit
7691 	 * will re-request KVM_REQ_EVENT.  Sometimes however an event is pending
7692 	 * and can architecturally be injected, but we cannot do it right now:
7693 	 * an interrupt could have arrived just now and we have to inject it
7694 	 * as a vmexit, or there could already an event in the queue, which is
7695 	 * indicated by can_inject.  In that case we request an immediate exit
7696 	 * in order to make progress and get back here for another iteration.
7697 	 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
7698 	 */
7699 #ifdef CONFIG_KVM_SMM
7700 	if (vcpu->arch.smi_pending) {
7701 		r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
7702 				 -EBUSY;
7703 		if (r < 0)
7704 			goto out;
7705 		if (r) {
7706 			vcpu->arch.smi_pending = false;
7707 			++vcpu->arch.smi_count;
7708 			enter_smm(vcpu);
7709 			can_inject = false;
7710 		} else
7711 			kvm_x86_call(enable_smi_window)(vcpu);
7712 	}
7713 #endif
7714 
7715 	if (vcpu->arch.nmi_pending) {
7716 		r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
7717 				 -EBUSY;
7718 		if (r < 0)
7719 			goto out;
7720 		if (r) {
7721 			--vcpu->arch.nmi_pending;
7722 			vcpu->arch.nmi_injected = true;
7723 			kvm_x86_call(inject_nmi)(vcpu);
7724 			can_inject = false;
7725 			WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
7726 		}
7727 		if (vcpu->arch.nmi_pending)
7728 			kvm_x86_call(enable_nmi_window)(vcpu);
7729 	}
7730 
7731 	if (kvm_cpu_has_injectable_intr(vcpu)) {
7732 		r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
7733 				 -EBUSY;
7734 		if (r < 0)
7735 			goto out;
7736 		if (r) {
7737 			int irq = kvm_cpu_get_interrupt(vcpu);
7738 
7739 			if (likely(irq != -1)) {
7740 				kvm_queue_interrupt(vcpu, irq, false);
7741 				kvm_x86_call(inject_irq)(vcpu, false);
7742 				WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
7743 			} else {
7744 				kvm_warn_on_lost_irq(vcpu);
7745 			}
7746 		}
7747 		if (kvm_cpu_has_injectable_intr(vcpu))
7748 			kvm_x86_call(enable_irq_window)(vcpu);
7749 	}
7750 
7751 	if (is_guest_mode(vcpu) && kvm_nested_call(has_events)(vcpu, true))
7752 		*req_immediate_exit = true;
7753 
7754 	/*
7755 	 * KVM must never queue a new exception while injecting an event; KVM
7756 	 * is done emulating and should only propagate the to-be-injected event
7757 	 * to the VMCS/VMCB.  Queueing a new exception can put the vCPU into an
7758 	 * infinite loop as KVM will bail from VM-Enter to inject the pending
7759 	 * exception and start the cycle all over.
7760 	 *
7761 	 * Exempt triple faults as they have special handling and won't put the
7762 	 * vCPU into an infinite loop.  Triple fault can be queued when running
7763 	 * VMX without unrestricted guest, as that requires KVM to emulate Real
7764 	 * Mode events (see kvm_inject_realmode_interrupt()).
7765 	 */
7766 	WARN_ON_ONCE(vcpu->arch.exception.pending ||
7767 		     vcpu->arch.exception_vmexit.pending);
7768 	return 0;
7769 
7770 out:
7771 	if (r == -EBUSY) {
7772 		*req_immediate_exit = true;
7773 		r = 0;
7774 	}
7775 	return r;
7776 }
7777 
7778 static void process_nmi(struct kvm_vcpu *vcpu)
7779 {
7780 	unsigned int limit;
7781 
7782 	/*
7783 	 * x86 is limited to one NMI pending, but because KVM can't react to
7784 	 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
7785 	 * scheduled out, KVM needs to play nice with two queued NMIs showing
7786 	 * up at the same time.  To handle this scenario, allow two NMIs to be
7787 	 * (temporarily) pending so long as NMIs are not blocked and KVM is not
7788 	 * waiting for a previous NMI injection to complete (which effectively
7789 	 * blocks NMIs).  KVM will immediately inject one of the two NMIs, and
7790 	 * will request an NMI window to handle the second NMI.
7791 	 */
7792 	if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
7793 		limit = 1;
7794 	else
7795 		limit = 2;
7796 
7797 	/*
7798 	 * Adjust the limit to account for pending virtual NMIs, which aren't
7799 	 * tracked in vcpu->arch.nmi_pending.
7800 	 */
7801 	if (kvm_x86_call(is_vnmi_pending)(vcpu))
7802 		limit--;
7803 
7804 	vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7805 	vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7806 
7807 	if (vcpu->arch.nmi_pending &&
7808 	    (kvm_x86_call(set_vnmi_pending)(vcpu)))
7809 		vcpu->arch.nmi_pending--;
7810 
7811 	if (vcpu->arch.nmi_pending)
7812 		kvm_make_request(KVM_REQ_EVENT, vcpu);
7813 }
7814 
7815 /* Return total number of NMIs pending injection to the VM */
7816 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
7817 {
7818 	return vcpu->arch.nmi_pending +
7819 	       kvm_x86_call(is_vnmi_pending)(vcpu);
7820 }
7821 
7822 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
7823 				       unsigned long *vcpu_bitmap)
7824 {
7825 	kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
7826 }
7827 
7828 void kvm_make_scan_ioapic_request(struct kvm *kvm)
7829 {
7830 	kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
7831 }
7832 
7833 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
7834 {
7835 	struct kvm_lapic *apic = vcpu->arch.apic;
7836 	bool activate;
7837 
7838 	if (!lapic_in_kernel(vcpu))
7839 		return;
7840 
7841 	down_read(&vcpu->kvm->arch.apicv_update_lock);
7842 	preempt_disable();
7843 
7844 	/* Do not activate APICV when APIC is disabled */
7845 	activate = kvm_vcpu_apicv_activated(vcpu) &&
7846 		   (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
7847 
7848 	if (apic->apicv_active == activate)
7849 		goto out;
7850 
7851 	apic->apicv_active = activate;
7852 	kvm_apic_update_apicv(vcpu);
7853 	kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
7854 
7855 	/*
7856 	 * When APICv gets disabled, we may still have injected interrupts
7857 	 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
7858 	 * still active when the interrupt got accepted. Make sure
7859 	 * kvm_check_and_inject_events() is called to check for that.
7860 	 */
7861 	if (!apic->apicv_active)
7862 		kvm_make_request(KVM_REQ_EVENT, vcpu);
7863 
7864 out:
7865 	preempt_enable();
7866 	up_read(&vcpu->kvm->arch.apicv_update_lock);
7867 }
7868 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_vcpu_update_apicv);
7869 
7870 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
7871 {
7872 	if (!lapic_in_kernel(vcpu))
7873 		return;
7874 
7875 	/*
7876 	 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
7877 	 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
7878 	 * and hardware doesn't support x2APIC virtualization.  E.g. some AMD
7879 	 * CPUs support AVIC but not x2APIC.  KVM still allows enabling AVIC in
7880 	 * this case so that KVM can use the AVIC doorbell to inject interrupts
7881 	 * to running vCPUs, but KVM must not create SPTEs for the APIC base as
7882 	 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
7883 	 * despite being in x2APIC mode.  For simplicity, inhibiting the APIC
7884 	 * access page is sticky.
7885 	 */
7886 	if (apic_x2apic_mode(vcpu->arch.apic) &&
7887 	    kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
7888 		kvm_inhibit_apic_access_page(vcpu);
7889 
7890 	__kvm_vcpu_update_apicv(vcpu);
7891 }
7892 
7893 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
7894 				      enum kvm_apicv_inhibit reason, bool set)
7895 {
7896 	unsigned long old, new;
7897 
7898 	lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
7899 
7900 	if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
7901 		return;
7902 
7903 	old = new = kvm->arch.apicv_inhibit_reasons;
7904 
7905 	if (reason != APICV_INHIBIT_REASON_IRQWIN)
7906 		set_or_clear_apicv_inhibit(&new, reason, set);
7907 
7908 	set_or_clear_apicv_inhibit(&new, APICV_INHIBIT_REASON_IRQWIN,
7909 				   atomic_read(&kvm->arch.apicv_nr_irq_window_req));
7910 
7911 	if (!!old != !!new) {
7912 		/*
7913 		 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
7914 		 * false positives in the sanity check WARN in vcpu_enter_guest().
7915 		 * This task will wait for all vCPUs to ack the kick IRQ before
7916 		 * updating apicv_inhibit_reasons, and all other vCPUs will
7917 		 * block on acquiring apicv_update_lock so that vCPUs can't
7918 		 * redo vcpu_enter_guest() without seeing the new inhibit state.
7919 		 *
7920 		 * Note, holding apicv_update_lock and taking it in the read
7921 		 * side (handling the request) also prevents other vCPUs from
7922 		 * servicing the request with a stale apicv_inhibit_reasons.
7923 		 */
7924 		kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
7925 		kvm->arch.apicv_inhibit_reasons = new;
7926 		if (new) {
7927 			unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
7928 			int idx = srcu_read_lock(&kvm->srcu);
7929 
7930 			kvm_zap_gfn_range(kvm, gfn, gfn+1);
7931 			srcu_read_unlock(&kvm->srcu, idx);
7932 		}
7933 	} else {
7934 		kvm->arch.apicv_inhibit_reasons = new;
7935 	}
7936 }
7937 
7938 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
7939 				    enum kvm_apicv_inhibit reason, bool set)
7940 {
7941 	if (!enable_apicv)
7942 		return;
7943 
7944 	down_write(&kvm->arch.apicv_update_lock);
7945 	__kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
7946 	up_write(&kvm->arch.apicv_update_lock);
7947 }
7948 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_or_clear_apicv_inhibit);
7949 
7950 void kvm_inc_or_dec_irq_window_inhibit(struct kvm *kvm, bool inc)
7951 {
7952 	int add = inc ? 1 : -1;
7953 
7954 	if (!enable_apicv)
7955 		return;
7956 
7957 	/*
7958 	 * IRQ windows are requested either because of ExtINT injections, or
7959 	 * because APICv is already disabled/inhibited for another reason.
7960 	 * While ExtINT injections are rare and should not happen while the
7961 	 * vCPU is running its actual workload, it's worth avoiding thrashing
7962 	 * if the IRQ window is being requested because APICv is already
7963 	 * inhibited.  So, toggle the actual inhibit (which requires taking
7964 	 * the lock for write) if and only if there's no other inhibit.
7965 	 * kvm_set_or_clear_apicv_inhibit() always evaluates the IRQ window
7966 	 * count; thus the IRQ window inhibit call _will_ be lazily updated on
7967 	 * the next call, if it ever happens.
7968 	 */
7969 	if (READ_ONCE(kvm->arch.apicv_inhibit_reasons) & ~BIT(APICV_INHIBIT_REASON_IRQWIN)) {
7970 		guard(rwsem_read)(&kvm->arch.apicv_update_lock);
7971 		if (READ_ONCE(kvm->arch.apicv_inhibit_reasons) & ~BIT(APICV_INHIBIT_REASON_IRQWIN)) {
7972 			atomic_add(add, &kvm->arch.apicv_nr_irq_window_req);
7973 			return;
7974 		}
7975 	}
7976 
7977 	/*
7978 	 * Strictly speaking, the lock is only needed if going 0->1 or 1->0,
7979 	 * a la atomic_dec_and_mutex_lock.  However, ExtINTs are rare and
7980 	 * only target a single CPU, so that is the common case; do not
7981 	 * bother eliding the down_write()/up_write() pair.
7982 	 */
7983 	guard(rwsem_write)(&kvm->arch.apicv_update_lock);
7984 	if (atomic_add_return(add, &kvm->arch.apicv_nr_irq_window_req) == inc)
7985 		__kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_IRQWIN, inc);
7986 }
7987 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inc_or_dec_irq_window_inhibit);
7988 
7989 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
7990 {
7991 	if (!kvm_apic_present(vcpu))
7992 		return;
7993 
7994 	bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
7995 	vcpu->arch.highest_stale_pending_ioapic_eoi = -1;
7996 
7997 	kvm_x86_call(sync_pir_to_irr)(vcpu);
7998 
7999 	if (irqchip_split(vcpu->kvm))
8000 		kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8001 #ifdef CONFIG_KVM_IOAPIC
8002 	else if (ioapic_in_kernel(vcpu->kvm))
8003 		kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8004 #endif
8005 
8006 	if (is_guest_mode(vcpu))
8007 		vcpu->arch.load_eoi_exitmap_pending = true;
8008 	else
8009 		kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8010 }
8011 
8012 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8013 {
8014 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8015 		return;
8016 
8017 #ifdef CONFIG_KVM_HYPERV
8018 	if (to_hv_vcpu(vcpu)) {
8019 		u64 eoi_exit_bitmap[4];
8020 
8021 		bitmap_or((ulong *)eoi_exit_bitmap,
8022 			  vcpu->arch.ioapic_handled_vectors,
8023 			  to_hv_synic(vcpu)->vec_bitmap, 256);
8024 		kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
8025 		return;
8026 	}
8027 #endif
8028 	kvm_x86_call(load_eoi_exitmap)(
8029 		vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
8030 }
8031 
8032 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
8033 {
8034 	kvm_x86_call(guest_memory_reclaimed)(kvm);
8035 }
8036 
8037 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8038 {
8039 	if (!lapic_in_kernel(vcpu))
8040 		return;
8041 
8042 	kvm_x86_call(set_apic_access_page_addr)(vcpu);
8043 }
8044 
8045 /*
8046  * Called within kvm->srcu read side.
8047  * Returns 1 to let vcpu_run() continue the guest execution loop without
8048  * exiting to the userspace.  Otherwise, the value will be returned to the
8049  * userspace.
8050  */
8051 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8052 {
8053 	int r;
8054 	bool req_int_win =
8055 		dm_request_for_irq_injection(vcpu) &&
8056 		kvm_cpu_accept_dm_intr(vcpu);
8057 	fastpath_t exit_fastpath;
8058 	u64 run_flags, debug_ctl;
8059 
8060 	bool req_immediate_exit = false;
8061 
8062 	if (kvm_request_pending(vcpu)) {
8063 		if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
8064 			r = -EIO;
8065 			goto out;
8066 		}
8067 
8068 		if (kvm_dirty_ring_check_request(vcpu)) {
8069 			r = 0;
8070 			goto out;
8071 		}
8072 
8073 		if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
8074 			if (unlikely(!kvm_nested_call(get_nested_state_pages)(vcpu))) {
8075 				r = 0;
8076 				goto out;
8077 			}
8078 		}
8079 		if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
8080 			kvm_mmu_free_obsolete_roots(vcpu);
8081 		if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8082 			__kvm_migrate_timers(vcpu);
8083 		if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8084 			kvm_update_masterclock(vcpu->kvm);
8085 		if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8086 			kvm_gen_kvmclock_update(vcpu);
8087 		if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8088 			r = kvm_guest_time_update(vcpu);
8089 			if (unlikely(r))
8090 				goto out;
8091 		}
8092 		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8093 			kvm_mmu_sync_roots(vcpu);
8094 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8095 			kvm_mmu_load_pgd(vcpu);
8096 
8097 		/*
8098 		 * Note, the order matters here, as flushing "all" TLB entries
8099 		 * also flushes the "current" TLB entries, i.e. servicing the
8100 		 * flush "all" will clear any request to flush "current".
8101 		 */
8102 		if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
8103 			kvm_vcpu_flush_tlb_all(vcpu);
8104 
8105 		kvm_service_local_tlb_flush_requests(vcpu);
8106 
8107 		/*
8108 		 * Fall back to a "full" guest flush if Hyper-V's precise
8109 		 * flushing fails.  Note, Hyper-V's flushing is per-vCPU, but
8110 		 * the flushes are considered "remote" and not "local" because
8111 		 * the requests can be initiated from other vCPUs.
8112 		 */
8113 #ifdef CONFIG_KVM_HYPERV
8114 		if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
8115 		    kvm_hv_vcpu_flush_tlb(vcpu))
8116 			kvm_vcpu_flush_tlb_guest(vcpu);
8117 #endif
8118 
8119 		if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8120 			vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8121 			r = 0;
8122 			goto out;
8123 		}
8124 		if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8125 			if (is_guest_mode(vcpu))
8126 				kvm_nested_call(triple_fault)(vcpu);
8127 
8128 			if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8129 				vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8130 				vcpu->mmio_needed = 0;
8131 				r = 0;
8132 				goto out;
8133 			}
8134 		}
8135 		if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8136 			/* Page is swapped out. Do synthetic halt */
8137 			vcpu->arch.apf.halted = true;
8138 			r = 1;
8139 			goto out;
8140 		}
8141 		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8142 			record_steal_time(vcpu);
8143 		if (kvm_check_request(KVM_REQ_PMU, vcpu))
8144 			kvm_pmu_handle_event(vcpu);
8145 		if (kvm_check_request(KVM_REQ_PMI, vcpu))
8146 			kvm_pmu_deliver_pmi(vcpu);
8147 #ifdef CONFIG_KVM_SMM
8148 		if (kvm_check_request(KVM_REQ_SMI, vcpu))
8149 			process_smi(vcpu);
8150 #endif
8151 		if (kvm_check_request(KVM_REQ_NMI, vcpu))
8152 			process_nmi(vcpu);
8153 		if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8154 			BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8155 			if (test_bit(vcpu->arch.pending_ioapic_eoi,
8156 				     vcpu->arch.ioapic_handled_vectors)) {
8157 				vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8158 				vcpu->run->eoi.vector =
8159 						vcpu->arch.pending_ioapic_eoi;
8160 				r = 0;
8161 				goto out;
8162 			}
8163 		}
8164 		if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8165 			vcpu_scan_ioapic(vcpu);
8166 		if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8167 			vcpu_load_eoi_exitmap(vcpu);
8168 		if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8169 			kvm_vcpu_reload_apic_access_page(vcpu);
8170 #ifdef CONFIG_KVM_HYPERV
8171 		if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8172 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8173 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8174 			vcpu->run->system_event.ndata = 0;
8175 			r = 0;
8176 			goto out;
8177 		}
8178 		if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8179 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8180 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8181 			vcpu->run->system_event.ndata = 0;
8182 			r = 0;
8183 			goto out;
8184 		}
8185 		if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8186 			struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
8187 
8188 			vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8189 			vcpu->run->hyperv = hv_vcpu->exit;
8190 			r = 0;
8191 			goto out;
8192 		}
8193 
8194 		/*
8195 		 * KVM_REQ_HV_STIMER has to be processed after
8196 		 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8197 		 * depend on the guest clock being up-to-date
8198 		 */
8199 		if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8200 			kvm_hv_process_stimers(vcpu);
8201 #endif
8202 		if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
8203 			kvm_vcpu_update_apicv(vcpu);
8204 		if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
8205 			kvm_check_async_pf_completion(vcpu);
8206 
8207 		if (kvm_check_request(KVM_REQ_RECALC_INTERCEPTS, vcpu))
8208 			kvm_x86_call(recalc_intercepts)(vcpu);
8209 
8210 		if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
8211 			kvm_x86_call(update_cpu_dirty_logging)(vcpu);
8212 
8213 		if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
8214 			kvm_vcpu_reset(vcpu, true);
8215 			if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
8216 				r = 1;
8217 				goto out;
8218 			}
8219 		}
8220 		if (kvm_check_request(KVM_REQ_VMSA_PAGE_RELOAD, vcpu))
8221 			kvm_x86_call(reload_vmsa)(vcpu);
8222 	}
8223 
8224 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
8225 	    kvm_xen_has_interrupt(vcpu)) {
8226 		++vcpu->stat.req_event;
8227 		r = kvm_apic_accept_events(vcpu);
8228 		if (r < 0) {
8229 			r = 0;
8230 			goto out;
8231 		}
8232 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8233 			r = 1;
8234 			goto out;
8235 		}
8236 
8237 		r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
8238 		if (r < 0) {
8239 			r = 0;
8240 			goto out;
8241 		}
8242 		if (req_int_win)
8243 			kvm_x86_call(enable_irq_window)(vcpu);
8244 
8245 		if (kvm_lapic_enabled(vcpu)) {
8246 			kvm_lapic_update_cr8_intercept(vcpu);
8247 			kvm_lapic_sync_to_vapic(vcpu);
8248 		}
8249 	}
8250 
8251 	r = kvm_mmu_reload(vcpu);
8252 	if (unlikely(r)) {
8253 		goto cancel_injection;
8254 	}
8255 
8256 	preempt_disable();
8257 
8258 	kvm_x86_call(prepare_switch_to_guest)(vcpu);
8259 
8260 	/*
8261 	 * Disable IRQs before setting IN_GUEST_MODE.  Posted interrupt
8262 	 * IPI are then delayed after guest entry, which ensures that they
8263 	 * result in virtual interrupt delivery.
8264 	 */
8265 	local_irq_disable();
8266 
8267 	/* Store vcpu->apicv_active before vcpu->mode.  */
8268 	smp_store_release(&vcpu->mode, IN_GUEST_MODE);
8269 
8270 	kvm_vcpu_srcu_read_unlock(vcpu);
8271 
8272 	/*
8273 	 * 1) We should set ->mode before checking ->requests.  Please see
8274 	 * the comment in kvm_vcpu_exiting_guest_mode().
8275 	 *
8276 	 * 2) For APICv, we should set ->mode before checking PID.ON. This
8277 	 * pairs with the memory barrier implicit in pi_test_and_set_on
8278 	 * (see vmx_deliver_posted_interrupt).
8279 	 *
8280 	 * 3) This also orders the write to mode from any reads to the page
8281 	 * tables done while the VCPU is running.  Please see the comment
8282 	 * in kvm_flush_remote_tlbs.
8283 	 */
8284 	smp_mb__after_srcu_read_unlock();
8285 
8286 	/*
8287 	 * Process pending posted interrupts to handle the case where the
8288 	 * notification IRQ arrived in the host, or was never sent (because the
8289 	 * target vCPU wasn't running).  Do this regardless of the vCPU's APICv
8290 	 * status, KVM doesn't update assigned devices when APICv is inhibited,
8291 	 * i.e. they can post interrupts even if APICv is temporarily disabled.
8292 	 */
8293 	if (kvm_lapic_enabled(vcpu))
8294 		kvm_x86_call(sync_pir_to_irr)(vcpu);
8295 
8296 	if (kvm_vcpu_exit_request(vcpu)) {
8297 		vcpu->mode = OUTSIDE_GUEST_MODE;
8298 		smp_wmb();
8299 		local_irq_enable();
8300 		preempt_enable();
8301 		kvm_vcpu_srcu_read_lock(vcpu);
8302 		r = 1;
8303 		goto cancel_injection;
8304 	}
8305 
8306 	run_flags = 0;
8307 	if (req_immediate_exit) {
8308 		run_flags |= KVM_RUN_FORCE_IMMEDIATE_EXIT;
8309 		kvm_make_request(KVM_REQ_EVENT, vcpu);
8310 	}
8311 
8312 	fpregs_assert_state_consistent();
8313 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
8314 		switch_fpu_return();
8315 
8316 	if (vcpu->arch.guest_fpu.xfd_err)
8317 		wrmsrq(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
8318 
8319 	kvm_load_xfeatures(vcpu, true);
8320 
8321 	if (unlikely(vcpu->arch.switch_db_regs &&
8322 		     !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
8323 		set_debugreg(DR7_FIXED_1, 7);
8324 		set_debugreg(vcpu->arch.eff_db[0], 0);
8325 		set_debugreg(vcpu->arch.eff_db[1], 1);
8326 		set_debugreg(vcpu->arch.eff_db[2], 2);
8327 		set_debugreg(vcpu->arch.eff_db[3], 3);
8328 		/* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
8329 		if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
8330 			run_flags |= KVM_RUN_LOAD_GUEST_DR6;
8331 	} else if (unlikely(hw_breakpoint_active())) {
8332 		set_debugreg(DR7_FIXED_1, 7);
8333 	}
8334 
8335 	/*
8336 	 * Refresh the host DEBUGCTL snapshot after disabling IRQs, as DEBUGCTL
8337 	 * can be modified in IRQ context, e.g. via SMP function calls.  Inform
8338 	 * vendor code if any host-owned bits were changed, e.g. so that the
8339 	 * value loaded into hardware while running the guest can be updated.
8340 	 */
8341 	debug_ctl = get_debugctlmsr();
8342 	if ((debug_ctl ^ vcpu->arch.host_debugctl) & kvm_x86_ops.HOST_OWNED_DEBUGCTL &&
8343 	    !vcpu->arch.guest_state_protected)
8344 		run_flags |= KVM_RUN_LOAD_DEBUGCTL;
8345 	vcpu->arch.host_debugctl = debug_ctl;
8346 
8347 	kvm_mediated_pmu_load(vcpu);
8348 
8349 	guest_timing_enter_irqoff();
8350 
8351 	/*
8352 	 * Swap PKRU with hardware breakpoints disabled to minimize the number
8353 	 * of flows where non-KVM code can run with guest state loaded.
8354 	 */
8355 	kvm_load_guest_pkru(vcpu);
8356 
8357 	for (;;) {
8358 		/*
8359 		 * Assert that vCPU vs. VM APICv state is consistent.  An APICv
8360 		 * update must kick and wait for all vCPUs before toggling the
8361 		 * per-VM state, and responding vCPUs must wait for the update
8362 		 * to complete before servicing KVM_REQ_APICV_UPDATE.
8363 		 */
8364 		WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
8365 			     (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
8366 
8367 		exit_fastpath = kvm_x86_call(vcpu_run)(vcpu, run_flags);
8368 		if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
8369 			break;
8370 
8371 		if (kvm_lapic_enabled(vcpu))
8372 			kvm_x86_call(sync_pir_to_irr)(vcpu);
8373 
8374 		if (unlikely(kvm_vcpu_exit_request(vcpu))) {
8375 			exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
8376 			break;
8377 		}
8378 
8379 		run_flags = 0;
8380 
8381 		/* Note, VM-Exits that go down the "slow" path are accounted below. */
8382 		++vcpu->stat.exits;
8383 	}
8384 
8385 	kvm_load_host_pkru(vcpu);
8386 
8387 	kvm_mediated_pmu_put(vcpu);
8388 
8389 	/*
8390 	 * Do this here before restoring debug registers on the host.  And
8391 	 * since we do this before handling the vmexit, a DR access vmexit
8392 	 * can (a) read the correct value of the debug registers, (b) set
8393 	 * KVM_DEBUGREG_WONT_EXIT again.
8394 	 */
8395 	if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8396 		WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8397 		WARN_ON(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH);
8398 		kvm_x86_call(sync_dirty_debug_regs)(vcpu);
8399 		kvm_update_dr0123(vcpu);
8400 		kvm_update_dr7(vcpu);
8401 	}
8402 
8403 	/*
8404 	 * If the guest has used debug registers, at least dr7
8405 	 * will be disabled while returning to the host.
8406 	 * If we don't have active breakpoints in the host, we don't
8407 	 * care about the messed up debug address registers. But if
8408 	 * we have some of them active, restore the old state.
8409 	 */
8410 	if (hw_breakpoint_active())
8411 		hw_breakpoint_restore();
8412 
8413 	vcpu->arch.last_vmentry_cpu = vcpu->cpu;
8414 	vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8415 
8416 	vcpu->mode = OUTSIDE_GUEST_MODE;
8417 	smp_wmb();
8418 
8419 	kvm_load_xfeatures(vcpu, false);
8420 
8421 	/*
8422 	 * Sync xfd before calling handle_exit_irqoff() which may
8423 	 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
8424 	 * in #NM irqoff handler).
8425 	 */
8426 	if (vcpu->arch.xfd_no_write_intercept)
8427 		fpu_sync_guest_vmexit_xfd_state();
8428 
8429 	kvm_x86_call(handle_exit_irqoff)(vcpu);
8430 
8431 	if (vcpu->arch.guest_fpu.xfd_err)
8432 		wrmsrq(MSR_IA32_XFD_ERR, 0);
8433 
8434 	/*
8435 	 * Mark this CPU as needing a branch predictor flush before running
8436 	 * userspace. Must be done before enabling preemption to ensure it gets
8437 	 * set for the CPU that actually ran the guest, and not the CPU that it
8438 	 * may migrate to.
8439 	 */
8440 	if (cpu_feature_enabled(X86_FEATURE_IBPB_EXIT_TO_USER))
8441 		this_cpu_write(x86_ibpb_exit_to_user, true);
8442 
8443 	/*
8444 	 * Consume any pending interrupts, including the possible source of
8445 	 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8446 	 * An instruction is required after local_irq_enable() to fully unblock
8447 	 * interrupts on processors that implement an interrupt shadow, the
8448 	 * stat.exits increment will do nicely.
8449 	 */
8450 	kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
8451 	local_irq_enable();
8452 	++vcpu->stat.exits;
8453 	local_irq_disable();
8454 	kvm_after_interrupt(vcpu);
8455 
8456 	/*
8457 	 * Wait until after servicing IRQs to account guest time so that any
8458 	 * ticks that occurred while running the guest are properly accounted
8459 	 * to the guest.  Waiting until IRQs are enabled degrades the accuracy
8460 	 * of accounting via context tracking, but the loss of accuracy is
8461 	 * acceptable for all known use cases.
8462 	 */
8463 	guest_timing_exit_irqoff();
8464 
8465 	local_irq_enable();
8466 	preempt_enable();
8467 
8468 	kvm_vcpu_srcu_read_lock(vcpu);
8469 
8470 	/*
8471 	 * Call this to ensure WC buffers in guest are evicted after each VM
8472 	 * Exit, so that the evicted WC writes can be snooped across all cpus
8473 	 */
8474 	smp_mb__after_srcu_read_lock();
8475 
8476 	/*
8477 	 * Profile KVM exit RIPs:
8478 	 */
8479 	if (unlikely(prof_on == KVM_PROFILING &&
8480 		     !vcpu->arch.guest_state_protected)) {
8481 		unsigned long rip = kvm_rip_read(vcpu);
8482 		profile_hit(KVM_PROFILING, (void *)rip);
8483 	}
8484 
8485 	if (unlikely(vcpu->arch.tsc_always_catchup))
8486 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8487 
8488 	if (vcpu->arch.apic_attention)
8489 		kvm_lapic_sync_from_vapic(vcpu);
8490 
8491 	r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
8492 	return r;
8493 
8494 cancel_injection:
8495 	if (req_immediate_exit)
8496 		kvm_make_request(KVM_REQ_EVENT, vcpu);
8497 	kvm_x86_call(cancel_injection)(vcpu);
8498 	if (unlikely(vcpu->arch.apic_attention))
8499 		kvm_lapic_sync_from_vapic(vcpu);
8500 out:
8501 	return r;
8502 }
8503 
8504 static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8505 {
8506 	return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8507 		!vcpu->arch.apf.halted);
8508 }
8509 
8510 bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8511 {
8512 	if (!list_empty_careful(&vcpu->async_pf.done))
8513 		return true;
8514 
8515 	if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
8516 	    kvm_apic_init_sipi_allowed(vcpu))
8517 		return true;
8518 
8519 	if (kvm_is_exception_pending(vcpu))
8520 		return true;
8521 
8522 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
8523 	    (vcpu->arch.nmi_pending &&
8524 	     kvm_x86_call(nmi_allowed)(vcpu, false)))
8525 		return true;
8526 
8527 #ifdef CONFIG_KVM_SMM
8528 	if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
8529 	    (vcpu->arch.smi_pending &&
8530 	     kvm_x86_call(smi_allowed)(vcpu, false)))
8531 		return true;
8532 #endif
8533 
8534 	if (kvm_test_request(KVM_REQ_PMI, vcpu))
8535 		return true;
8536 
8537 	if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
8538 		return true;
8539 
8540 	if (kvm_is_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
8541 		return true;
8542 
8543 	if (kvm_hv_has_stimer_pending(vcpu))
8544 		return true;
8545 
8546 	if (is_guest_mode(vcpu) && kvm_nested_call(has_events)(vcpu, false))
8547 		return true;
8548 
8549 	if (kvm_xen_has_pending_events(vcpu))
8550 		return true;
8551 
8552 	return false;
8553 }
8554 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_has_events);
8555 
8556 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8557 {
8558 	return kvm_vcpu_running(vcpu) || vcpu->arch.pv.pv_unhalted ||
8559 	       kvm_vcpu_has_events(vcpu);
8560 }
8561 
8562 /* Called within kvm->srcu read side.  */
8563 static inline int vcpu_block(struct kvm_vcpu *vcpu)
8564 {
8565 	bool hv_timer;
8566 
8567 	if (!kvm_arch_vcpu_runnable(vcpu)) {
8568 		/*
8569 		 * Switch to the software timer before halt-polling/blocking as
8570 		 * the guest's timer may be a break event for the vCPU, and the
8571 		 * hypervisor timer runs only when the CPU is in guest mode.
8572 		 * Switch before halt-polling so that KVM recognizes an expired
8573 		 * timer before blocking.
8574 		 */
8575 		hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
8576 		if (hv_timer)
8577 			kvm_lapic_switch_to_sw_timer(vcpu);
8578 
8579 		kvm_vcpu_srcu_read_unlock(vcpu);
8580 		if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
8581 			kvm_vcpu_halt(vcpu);
8582 		else
8583 			kvm_vcpu_block(vcpu);
8584 		kvm_vcpu_srcu_read_lock(vcpu);
8585 
8586 		if (hv_timer)
8587 			kvm_lapic_switch_to_hv_timer(vcpu);
8588 
8589 		/*
8590 		 * If the vCPU is not runnable, a signal or another host event
8591 		 * of some kind is pending; service it without changing the
8592 		 * vCPU's activity state.
8593 		 */
8594 		if (!kvm_arch_vcpu_runnable(vcpu))
8595 			return 1;
8596 	}
8597 
8598 	/*
8599 	 * Evaluate nested events before exiting the halted state.  This allows
8600 	 * the halt state to be recorded properly in the VMCS12's activity
8601 	 * state field (AMD does not have a similar field and a VM-Exit always
8602 	 * causes a spurious wakeup from HLT).
8603 	 */
8604 	if (is_guest_mode(vcpu)) {
8605 		int r = kvm_check_nested_events(vcpu);
8606 
8607 		if (r < 0 && r != -EBUSY)
8608 			return 0;
8609 	}
8610 
8611 	if (kvm_apic_accept_events(vcpu) < 0)
8612 		return 0;
8613 	switch(vcpu->arch.mp_state) {
8614 	case KVM_MP_STATE_HALTED:
8615 	case KVM_MP_STATE_AP_RESET_HOLD:
8616 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
8617 		fallthrough;
8618 	case KVM_MP_STATE_RUNNABLE:
8619 		vcpu->arch.apf.halted = false;
8620 		break;
8621 	case KVM_MP_STATE_INIT_RECEIVED:
8622 		break;
8623 	default:
8624 		WARN_ON_ONCE(1);
8625 		break;
8626 	}
8627 	return 1;
8628 }
8629 
8630 /* Called within kvm->srcu read side.  */
8631 static int vcpu_run(struct kvm_vcpu *vcpu)
8632 {
8633 	int r;
8634 
8635 	vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
8636 
8637 	for (;;) {
8638 		/*
8639 		 * If another guest vCPU requests a PV TLB flush in the middle
8640 		 * of instruction emulation, the rest of the emulation could
8641 		 * use a stale page translation. Assume that any code after
8642 		 * this point can start executing an instruction.
8643 		 */
8644 		vcpu->arch.at_instruction_boundary = false;
8645 		if (kvm_vcpu_running(vcpu)) {
8646 			r = vcpu_enter_guest(vcpu);
8647 		} else {
8648 			r = vcpu_block(vcpu);
8649 		}
8650 
8651 		if (r <= 0)
8652 			break;
8653 
8654 		kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
8655 		if (kvm_xen_has_pending_events(vcpu))
8656 			kvm_xen_inject_pending_events(vcpu);
8657 
8658 		if (kvm_cpu_has_pending_timer(vcpu))
8659 			kvm_inject_pending_timer_irqs(vcpu);
8660 
8661 		if (dm_request_for_irq_injection(vcpu) &&
8662 			kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8663 			r = 0;
8664 			vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8665 			++vcpu->stat.request_irq_exits;
8666 			break;
8667 		}
8668 
8669 		if (__xfer_to_guest_mode_work_pending()) {
8670 			kvm_vcpu_srcu_read_unlock(vcpu);
8671 			r = kvm_xfer_to_guest_mode_handle_work(vcpu);
8672 			kvm_vcpu_srcu_read_lock(vcpu);
8673 			if (r)
8674 				return r;
8675 		}
8676 	}
8677 
8678 	return r;
8679 }
8680 
8681 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
8682 {
8683 	/*
8684 	 * The vCPU has halted, e.g. executed HLT.  Update the run state if the
8685 	 * local APIC is in-kernel, the run loop will detect the non-runnable
8686 	 * state and halt the vCPU.  Exit to userspace if the local APIC is
8687 	 * managed by userspace, in which case userspace is responsible for
8688 	 * handling wake events.
8689 	 */
8690 	++vcpu->stat.halt_exits;
8691 	if (lapic_in_kernel(vcpu)) {
8692 		if (kvm_vcpu_has_events(vcpu) || vcpu->arch.pv.pv_unhalted)
8693 			state = KVM_MP_STATE_RUNNABLE;
8694 		kvm_set_mp_state(vcpu, state);
8695 		return 1;
8696 	} else {
8697 		vcpu->run->exit_reason = reason;
8698 		return 0;
8699 	}
8700 }
8701 
8702 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
8703 {
8704 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
8705 }
8706 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt_noskip);
8707 
8708 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
8709 {
8710 	int ret = kvm_skip_emulated_instruction(vcpu);
8711 	/*
8712 	 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
8713 	 * KVM_EXIT_DEBUG here.
8714 	 */
8715 	return kvm_emulate_halt_noskip(vcpu) && ret;
8716 }
8717 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt);
8718 
8719 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
8720 {
8721 	if (!kvm_pmu_is_fastpath_emulation_allowed(vcpu))
8722 		return EXIT_FASTPATH_NONE;
8723 
8724 	if (!kvm_emulate_halt(vcpu))
8725 		return EXIT_FASTPATH_EXIT_USERSPACE;
8726 
8727 	if (kvm_vcpu_running(vcpu))
8728 		return EXIT_FASTPATH_REENTER_GUEST;
8729 
8730 	return EXIT_FASTPATH_EXIT_HANDLED;
8731 }
8732 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_hlt);
8733 
8734 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
8735 {
8736 	int ret = kvm_skip_emulated_instruction(vcpu);
8737 
8738 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
8739 					KVM_EXIT_AP_RESET_HOLD) && ret;
8740 }
8741 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_ap_reset_hold);
8742 
8743 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
8744 {
8745 	return kvm_vcpu_apicv_active(vcpu) &&
8746 	       kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
8747 }
8748 
8749 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
8750 {
8751 	return vcpu->arch.preempted_in_kernel;
8752 }
8753 
8754 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
8755 {
8756 	if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
8757 		return true;
8758 
8759 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
8760 #ifdef CONFIG_KVM_SMM
8761 		kvm_test_request(KVM_REQ_SMI, vcpu) ||
8762 #endif
8763 		 kvm_test_request(KVM_REQ_EVENT, vcpu))
8764 		return true;
8765 
8766 	return kvm_arch_dy_has_pending_interrupt(vcpu);
8767 }
8768 
8769 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8770 {
8771 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8772 }
8773 
8774 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8775 {
8776 	if (KVM_BUG_ON(!vcpu->arch.pio.count, vcpu->kvm))
8777 		return -EIO;
8778 
8779 	return complete_emulated_io(vcpu);
8780 }
8781 
8782 /*
8783  * Implements the following, as a state machine:
8784  *
8785  * read:
8786  *   for each fragment
8787  *     for each mmio piece in the fragment
8788  *       write gpa, len
8789  *       exit
8790  *       copy data
8791  *   execute insn
8792  *
8793  * write:
8794  *   for each fragment
8795  *     for each mmio piece in the fragment
8796  *       write gpa, len
8797  *       copy data
8798  *       exit
8799  */
8800 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8801 {
8802 	struct kvm_run *run = vcpu->run;
8803 	struct kvm_mmio_fragment *frag;
8804 	unsigned len;
8805 
8806 	if (KVM_BUG_ON(!vcpu->mmio_needed, vcpu->kvm))
8807 		return -EIO;
8808 
8809 	/* Complete previous fragment */
8810 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8811 	len = min(8u, frag->len);
8812 	if (!vcpu->mmio_is_write)
8813 		memcpy(frag->data, run->mmio.data, len);
8814 
8815 	if (frag->len <= 8) {
8816 		/* Switch to the next fragment. */
8817 		frag++;
8818 		vcpu->mmio_cur_fragment++;
8819 	} else {
8820 		if (WARN_ON_ONCE(frag->data == &frag->val))
8821 			return -EIO;
8822 
8823 		/* Go forward to the next mmio piece. */
8824 		frag->data += len;
8825 		frag->gpa += len;
8826 		frag->len -= len;
8827 	}
8828 
8829 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8830 		vcpu->mmio_needed = 0;
8831 
8832 		/* FIXME: return into emulator if single-stepping.  */
8833 		if (vcpu->mmio_is_write)
8834 			return 1;
8835 		vcpu->mmio_read_completed = 1;
8836 		return complete_emulated_io(vcpu);
8837 	}
8838 
8839 	kvm_prepare_emulated_mmio_exit(vcpu, frag);
8840 	vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8841 	return 0;
8842 }
8843 
8844 static int kvm_x86_vcpu_pre_run(struct kvm_vcpu *vcpu)
8845 {
8846 	/*
8847 	 * Userspace may have modified vCPU state, mark nested_run_pending as
8848 	 * "untrusted" to avoid triggering false-positive WARNs.
8849 	 */
8850 	if (vcpu->arch.nested_run_pending == KVM_NESTED_RUN_PENDING)
8851 		vcpu->arch.nested_run_pending = KVM_NESTED_RUN_PENDING_UNTRUSTED;
8852 
8853 	/*
8854 	 * SIPI_RECEIVED is obsolete; KVM leaves the vCPU in Wait-For-SIPI and
8855 	 * tracks the pending SIPI separately.  SIPI_RECEIVED is still accepted
8856 	 * by KVM_SET_VCPU_EVENTS for backwards compatibility, but should be
8857 	 * converted to INIT_RECEIVED.
8858 	 */
8859 	if (WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED))
8860 		return -EINVAL;
8861 
8862 	/*
8863 	 * Disallow running the vCPU if userspace forced it into an impossible
8864 	 * MP_STATE, e.g. if the vCPU is in WFS but SIPI is blocked.
8865 	 */
8866 	if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED &&
8867 	    !kvm_apic_init_sipi_allowed(vcpu))
8868 		return -EINVAL;
8869 
8870 	if (kvm_x86_call(vcpu_needs_initialization)(vcpu))
8871 		return -EINVAL;
8872 
8873 	if (kvm_x86_call(unhandleable_emulation_required)(vcpu)) {
8874 		kvm_prepare_emulation_failure_exit(vcpu);
8875 		return 0;
8876 	}
8877 
8878 	return 1;
8879 }
8880 
8881 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
8882 {
8883 	struct kvm_queued_exception *ex = &vcpu->arch.exception;
8884 	struct kvm_run *kvm_run = vcpu->run;
8885 	u64 sync_valid_fields;
8886 	int r;
8887 
8888 	r = kvm_mmu_post_init_vm(vcpu->kvm);
8889 	if (r)
8890 		return r;
8891 
8892 	vcpu_load(vcpu);
8893 	kvm_sigset_activate(vcpu);
8894 	kvm_run->flags = 0;
8895 	kvm_load_guest_fpu(vcpu);
8896 
8897 	kvm_vcpu_srcu_read_lock(vcpu);
8898 	if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8899 		if (!vcpu->wants_to_run) {
8900 			r = -EINTR;
8901 			goto out;
8902 		}
8903 
8904 		/*
8905 		 * Don't bother switching APIC timer emulation from the
8906 		 * hypervisor timer to the software timer, the only way for the
8907 		 * APIC timer to be active is if userspace stuffed vCPU state,
8908 		 * i.e. put the vCPU into a nonsensical state.  Only an INIT
8909 		 * will transition the vCPU out of UNINITIALIZED (without more
8910 		 * state stuffing from userspace), which will reset the local
8911 		 * APIC and thus cancel the timer or drop the IRQ (if the timer
8912 		 * already expired).
8913 		 */
8914 		kvm_vcpu_srcu_read_unlock(vcpu);
8915 		kvm_vcpu_block(vcpu);
8916 		kvm_vcpu_srcu_read_lock(vcpu);
8917 
8918 		if (kvm_apic_accept_events(vcpu) < 0) {
8919 			r = 0;
8920 			goto out;
8921 		}
8922 		r = -EAGAIN;
8923 		if (signal_pending(current)) {
8924 			r = -EINTR;
8925 			kvm_run->exit_reason = KVM_EXIT_INTR;
8926 			++vcpu->stat.signal_exits;
8927 		}
8928 		goto out;
8929 	}
8930 
8931 	sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
8932 	if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
8933 	    (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
8934 		r = -EINVAL;
8935 		goto out;
8936 	}
8937 
8938 	if (kvm_run->kvm_dirty_regs) {
8939 		r = sync_regs(vcpu);
8940 		if (r != 0)
8941 			goto out;
8942 	}
8943 
8944 	/* re-sync apic's tpr */
8945 	if (!lapic_in_kernel(vcpu)) {
8946 		if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8947 			r = -EINVAL;
8948 			goto out;
8949 		}
8950 	}
8951 
8952 	/*
8953 	 * If userspace set a pending exception and L2 is active, convert it to
8954 	 * a pending VM-Exit if L1 wants to intercept the exception.
8955 	 */
8956 	if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
8957 	    kvm_nested_call(is_exception_vmexit)(vcpu, ex->vector, ex->error_code)) {
8958 		kvm_queue_exception_vmexit(vcpu, ex->vector,
8959 					   ex->has_error_code, ex->error_code,
8960 					   ex->has_payload, ex->payload);
8961 		ex->injected = false;
8962 		ex->pending = false;
8963 	}
8964 	vcpu->arch.exception_from_userspace = false;
8965 
8966 	if (unlikely(vcpu->arch.complete_userspace_io)) {
8967 		int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8968 		vcpu->arch.complete_userspace_io = NULL;
8969 		r = cui(vcpu);
8970 		if (r <= 0)
8971 			goto out;
8972 	} else {
8973 		WARN_ON_ONCE(vcpu->arch.pio.count);
8974 		WARN_ON_ONCE(vcpu->mmio_needed);
8975 	}
8976 
8977 	if (!vcpu->wants_to_run) {
8978 		r = -EINTR;
8979 		goto out;
8980 	}
8981 
8982 	r = kvm_x86_vcpu_pre_run(vcpu);
8983 	if (r <= 0)
8984 		goto out;
8985 
8986 	r = vcpu_run(vcpu);
8987 
8988 out:
8989 	kvm_put_guest_fpu(vcpu);
8990 	if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
8991 		store_regs(vcpu);
8992 	post_kvm_run_save(vcpu);
8993 	kvm_vcpu_srcu_read_unlock(vcpu);
8994 
8995 	kvm_sigset_deactivate(vcpu);
8996 	vcpu_put(vcpu);
8997 	return r;
8998 }
8999 
9000 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
9001 				    struct kvm_mp_state *mp_state)
9002 {
9003 	int r;
9004 
9005 	vcpu_load(vcpu);
9006 	kvm_vcpu_srcu_read_lock(vcpu);
9007 
9008 	r = kvm_apic_accept_events(vcpu);
9009 	if (r < 0)
9010 		goto out;
9011 	r = 0;
9012 
9013 	if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
9014 	     vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
9015 	    vcpu->arch.pv.pv_unhalted)
9016 		mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
9017 	else
9018 		mp_state->mp_state = vcpu->arch.mp_state;
9019 
9020 out:
9021 	kvm_vcpu_srcu_read_unlock(vcpu);
9022 	vcpu_put(vcpu);
9023 	return r;
9024 }
9025 
9026 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
9027 				    struct kvm_mp_state *mp_state)
9028 {
9029 	int ret = -EINVAL;
9030 
9031 	vcpu_load(vcpu);
9032 
9033 	switch (mp_state->mp_state) {
9034 	case KVM_MP_STATE_UNINITIALIZED:
9035 	case KVM_MP_STATE_HALTED:
9036 	case KVM_MP_STATE_AP_RESET_HOLD:
9037 	case KVM_MP_STATE_INIT_RECEIVED:
9038 	case KVM_MP_STATE_SIPI_RECEIVED:
9039 		if (!lapic_in_kernel(vcpu))
9040 			goto out;
9041 		break;
9042 
9043 	case KVM_MP_STATE_RUNNABLE:
9044 		break;
9045 
9046 	default:
9047 		goto out;
9048 	}
9049 
9050 	/*
9051 	 * SIPI_RECEIVED is obsolete and no longer used internally; KVM instead
9052 	 * leaves the vCPU in INIT_RECIEVED (Wait-For-SIPI) and pends the SIPI.
9053 	 * Translate SIPI_RECEIVED as appropriate for backwards compatibility.
9054 	 */
9055 	if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9056 		mp_state->mp_state = KVM_MP_STATE_INIT_RECEIVED;
9057 		set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9058 	}
9059 
9060 	kvm_set_mp_state(vcpu, mp_state->mp_state);
9061 	kvm_make_request(KVM_REQ_EVENT, vcpu);
9062 
9063 	ret = 0;
9064 out:
9065 	vcpu_put(vcpu);
9066 	return ret;
9067 }
9068 
9069 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9070 		    int reason, bool has_error_code, u32 error_code)
9071 {
9072 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9073 	int ret;
9074 
9075 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_CET)) {
9076 		u64 u_cet, s_cet;
9077 
9078 		/*
9079 		 * Check both User and Supervisor on task switches as inter-
9080 		 * privilege level task switches are impacted by CET at both
9081 		 * the current privilege level and the new privilege level, and
9082 		 * that information is not known at this time.  The expectation
9083 		 * is that the guest won't require emulation of task switches
9084 		 * while using IBT or Shadow Stacks.
9085 		 */
9086 		if (__kvm_emulate_msr_read(vcpu, MSR_IA32_U_CET, &u_cet) ||
9087 		    __kvm_emulate_msr_read(vcpu, MSR_IA32_S_CET, &s_cet))
9088 			goto unhandled_task_switch;
9089 
9090 		if ((u_cet | s_cet) & (CET_ENDBR_EN | CET_SHSTK_EN))
9091 			goto unhandled_task_switch;
9092 	}
9093 
9094 	init_emulate_ctxt(vcpu);
9095 
9096 	ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9097 				   has_error_code, error_code);
9098 
9099 	/*
9100 	 * Report an error userspace if MMIO is needed, as KVM doesn't support
9101 	 * MMIO during a task switch (or any other complex operation).
9102 	 */
9103 	if (ret || vcpu->mmio_needed)
9104 		goto unhandled_task_switch;
9105 
9106 	kvm_rip_write(vcpu, ctxt->eip);
9107 	kvm_set_rflags(vcpu, ctxt->eflags);
9108 	return 1;
9109 
9110 unhandled_task_switch:
9111 	vcpu->mmio_needed = false;
9112 	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9113 	vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9114 	vcpu->run->internal.ndata = 0;
9115 	return 0;
9116 }
9117 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_task_switch);
9118 
9119 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
9120 {
9121 	bool set = false;
9122 	struct kvm_vcpu *vcpu;
9123 	unsigned long i;
9124 
9125 	if (!enable_apicv)
9126 		return;
9127 
9128 	down_write(&kvm->arch.apicv_update_lock);
9129 
9130 	kvm_for_each_vcpu(i, vcpu, kvm) {
9131 		if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
9132 			set = true;
9133 			break;
9134 		}
9135 	}
9136 	__kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
9137 	up_write(&kvm->arch.apicv_update_lock);
9138 }
9139 
9140 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9141 					struct kvm_guest_debug *dbg)
9142 {
9143 	unsigned long rflags;
9144 	int i, r;
9145 
9146 	if (vcpu->arch.guest_state_protected)
9147 		return -EINVAL;
9148 
9149 	vcpu_load(vcpu);
9150 
9151 	if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9152 		r = -EBUSY;
9153 		if (kvm_is_exception_pending(vcpu) || vcpu->arch.exception.injected)
9154 			goto out;
9155 		if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9156 			kvm_queue_exception(vcpu, DB_VECTOR);
9157 		else
9158 			kvm_queue_exception(vcpu, BP_VECTOR);
9159 	}
9160 
9161 	/*
9162 	 * Read rflags as long as potentially injected trace flags are still
9163 	 * filtered out.
9164 	 */
9165 	rflags = kvm_get_rflags(vcpu);
9166 
9167 	vcpu->guest_debug = dbg->control;
9168 	if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9169 		vcpu->guest_debug = 0;
9170 
9171 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9172 		for (i = 0; i < KVM_NR_DB_REGS; ++i)
9173 			vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9174 		vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9175 	} else {
9176 		for (i = 0; i < KVM_NR_DB_REGS; i++)
9177 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9178 	}
9179 	kvm_update_dr7(vcpu);
9180 
9181 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9182 		vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
9183 
9184 	/*
9185 	 * Trigger an rflags update that will inject or remove the trace
9186 	 * flags.
9187 	 */
9188 	kvm_set_rflags(vcpu, rflags);
9189 
9190 	kvm_x86_call(update_exception_bitmap)(vcpu);
9191 
9192 	kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
9193 
9194 	r = 0;
9195 
9196 out:
9197 	vcpu_put(vcpu);
9198 	return r;
9199 }
9200 
9201 /*
9202  * Translate a guest virtual address to a guest physical address.
9203  */
9204 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9205 				    struct kvm_translation *tr)
9206 {
9207 	unsigned long vaddr = tr->linear_address;
9208 	gpa_t gpa;
9209 	int idx;
9210 
9211 	vcpu_load(vcpu);
9212 
9213 	idx = srcu_read_lock(&vcpu->kvm->srcu);
9214 	gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9215 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
9216 	tr->physical_address = gpa;
9217 	tr->valid = gpa != INVALID_GPA;
9218 	tr->writeable = 1;
9219 	tr->usermode = 0;
9220 
9221 	vcpu_put(vcpu);
9222 	return 0;
9223 }
9224 
9225 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9226 {
9227 	struct fxregs_state *fxsave;
9228 
9229 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
9230 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
9231 
9232 	vcpu_load(vcpu);
9233 
9234 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
9235 	memcpy(fpu->fpr, fxsave->st_space, 128);
9236 	fpu->fcw = fxsave->cwd;
9237 	fpu->fsw = fxsave->swd;
9238 	fpu->ftwx = fxsave->twd;
9239 	fpu->last_opcode = fxsave->fop;
9240 	fpu->last_ip = fxsave->rip;
9241 	fpu->last_dp = fxsave->rdp;
9242 	memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9243 
9244 	vcpu_put(vcpu);
9245 	return 0;
9246 }
9247 
9248 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9249 {
9250 	struct fxregs_state *fxsave;
9251 
9252 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
9253 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
9254 
9255 	vcpu_load(vcpu);
9256 
9257 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
9258 
9259 	memcpy(fxsave->st_space, fpu->fpr, 128);
9260 	fxsave->cwd = fpu->fcw;
9261 	fxsave->swd = fpu->fsw;
9262 	fxsave->twd = fpu->ftwx;
9263 	fxsave->fop = fpu->last_opcode;
9264 	fxsave->rip = fpu->last_ip;
9265 	fxsave->rdp = fpu->last_dp;
9266 	memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9267 
9268 	vcpu_put(vcpu);
9269 	return 0;
9270 }
9271 
9272 static void store_regs(struct kvm_vcpu *vcpu)
9273 {
9274 	kvm_run_sync_regs_to_user(vcpu);
9275 
9276 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9277 		kvm_vcpu_ioctl_x86_get_vcpu_events(
9278 				vcpu, &vcpu->run->s.regs.events);
9279 }
9280 
9281 static int sync_regs(struct kvm_vcpu *vcpu)
9282 {
9283 	if (kvm_run_sync_regs_from_user(vcpu))
9284 		return -EINVAL;
9285 
9286 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9287 		struct kvm_vcpu_events events = vcpu->run->s.regs.events;
9288 
9289 		if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
9290 			return -EINVAL;
9291 
9292 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9293 	}
9294 
9295 	return 0;
9296 }
9297 
9298 #define PERF_MEDIATED_PMU_MSG \
9299 	"Failed to enable mediated vPMU, try disabling system wide perf events and nmi_watchdog.\n"
9300 
9301 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
9302 {
9303 	int r;
9304 
9305 	if (kvm_check_tsc_unstable() && kvm->created_vcpus)
9306 		pr_warn_once("SMP vm created on host with unstable TSC; "
9307 			     "guest TSC will not be reliable\n");
9308 
9309 	if (!kvm->arch.max_vcpu_ids)
9310 		kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
9311 
9312 	if (id >= kvm->arch.max_vcpu_ids)
9313 		return -EINVAL;
9314 
9315 	/*
9316 	 * Note, any actions done by .vcpu_create() must be idempotent with
9317 	 * respect to creating multiple vCPUs, and therefore are not undone if
9318 	 * creating a vCPU fails (including failure during pre-create).
9319 	 */
9320 	r = kvm_x86_call(vcpu_precreate)(kvm);
9321 	if (r)
9322 		return r;
9323 
9324 	if (enable_mediated_pmu && kvm->arch.enable_pmu &&
9325 	    !kvm->arch.created_mediated_pmu) {
9326 		if (irqchip_in_kernel(kvm)) {
9327 			r = perf_create_mediated_pmu();
9328 			if (r) {
9329 				pr_warn_ratelimited(PERF_MEDIATED_PMU_MSG);
9330 				return r;
9331 			}
9332 			kvm->arch.created_mediated_pmu = true;
9333 		} else {
9334 			kvm->arch.enable_pmu = false;
9335 		}
9336 	}
9337 	return 0;
9338 }
9339 
9340 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
9341 {
9342 	struct page *page;
9343 	int r;
9344 
9345 	vcpu->arch.last_vmentry_cpu = -1;
9346 	bitmap_fill(vcpu->arch.regs_avail, NR_VCPU_TOTAL_REGS);
9347 	bitmap_fill(vcpu->arch.regs_dirty, NR_VCPU_TOTAL_REGS);
9348 
9349 	kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
9350 
9351 	if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9352 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
9353 	else
9354 		kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);
9355 
9356 	r = kvm_mmu_create(vcpu);
9357 	if (r < 0)
9358 		return r;
9359 
9360 	r = kvm_create_lapic(vcpu);
9361 	if (r < 0)
9362 		goto fail_mmu_destroy;
9363 
9364 	r = -ENOMEM;
9365 
9366 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
9367 	if (!page)
9368 		goto fail_free_lapic;
9369 	vcpu->arch.pio_data = page_address(page);
9370 
9371 	vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
9372 				       GFP_KERNEL_ACCOUNT);
9373 	vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
9374 					    GFP_KERNEL_ACCOUNT);
9375 	if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
9376 		goto fail_free_mce_banks;
9377 	vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9378 
9379 	if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9380 				GFP_KERNEL_ACCOUNT))
9381 		goto fail_free_mce_banks;
9382 
9383 	if (!alloc_emulate_ctxt(vcpu))
9384 		goto free_wbinvd_dirty_mask;
9385 
9386 	if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
9387 		pr_err("failed to allocate vcpu's fpu\n");
9388 		goto free_emulate_ctxt;
9389 	}
9390 
9391 	kvm_async_pf_hash_reset(vcpu);
9392 
9393 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) {
9394 		vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9395 		vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9396 		vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
9397 	}
9398 	kvm_pmu_init(vcpu);
9399 
9400 	vcpu->arch.pending_external_vector = -1;
9401 	vcpu->arch.preempted_in_kernel = false;
9402 
9403 #if IS_ENABLED(CONFIG_HYPERV)
9404 	vcpu->arch.hv_root_tdp = INVALID_PAGE;
9405 #endif
9406 
9407 	r = kvm_x86_call(vcpu_create)(vcpu);
9408 	if (r)
9409 		goto free_guest_fpu;
9410 
9411 	kvm_xen_init_vcpu(vcpu);
9412 	vcpu_load(vcpu);
9413 	kvm_vcpu_after_set_cpuid(vcpu);
9414 	kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
9415 	kvm_vcpu_reset(vcpu, false);
9416 	kvm_init_mmu(vcpu);
9417 	vcpu_put(vcpu);
9418 	return 0;
9419 
9420 free_guest_fpu:
9421 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
9422 free_emulate_ctxt:
9423 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9424 free_wbinvd_dirty_mask:
9425 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9426 fail_free_mce_banks:
9427 	kfree(vcpu->arch.mce_banks);
9428 	kfree(vcpu->arch.mci_ctl2_banks);
9429 	free_page((unsigned long)vcpu->arch.pio_data);
9430 fail_free_lapic:
9431 	kvm_free_lapic(vcpu);
9432 fail_mmu_destroy:
9433 	kvm_mmu_destroy(vcpu);
9434 	return r;
9435 }
9436 
9437 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9438 {
9439 	if (mutex_lock_killable(&vcpu->mutex))
9440 		return;
9441 	vcpu_load(vcpu);
9442 	kvm_synchronize_tsc(vcpu, NULL);
9443 	vcpu_put(vcpu);
9444 
9445 	/* poll control enabled by default */
9446 	vcpu->arch.msr_kvm_poll_control = 1;
9447 
9448 	mutex_unlock(&vcpu->mutex);
9449 }
9450 
9451 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9452 {
9453 	int idx, cpu;
9454 
9455 	kvm_clear_async_pf_completion_queue(vcpu);
9456 	kvm_mmu_unload(vcpu);
9457 
9458 	kvmclock_reset(vcpu);
9459 
9460 	for_each_possible_cpu(cpu)
9461 		cmpxchg(per_cpu_ptr(&last_vcpu, cpu), vcpu, NULL);
9462 
9463 	kvm_x86_call(vcpu_free)(vcpu);
9464 
9465 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9466 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9467 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
9468 
9469 	kvm_xen_destroy_vcpu(vcpu);
9470 	kvm_hv_vcpu_uninit(vcpu);
9471 	kvm_pmu_destroy(vcpu);
9472 	kfree(vcpu->arch.mce_banks);
9473 	kfree(vcpu->arch.mci_ctl2_banks);
9474 	kvm_free_lapic(vcpu);
9475 	idx = srcu_read_lock(&vcpu->kvm->srcu);
9476 	kvm_mmu_destroy(vcpu);
9477 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
9478 	free_page((unsigned long)vcpu->arch.pio_data);
9479 	kvfree(vcpu->arch.cpuid_entries);
9480 }
9481 
9482 static void kvm_xstate_reset(struct kvm_vcpu *vcpu, bool init_event)
9483 {
9484 	struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
9485 	u64 xfeatures_mask;
9486 	bool fpu_in_use;
9487 	int i;
9488 
9489 	/*
9490 	 * Guest FPU state is zero allocated and so doesn't need to be manually
9491 	 * cleared on RESET, i.e. during vCPU creation.
9492 	 */
9493 	if (!init_event || !fpstate)
9494 		return;
9495 
9496 	/*
9497 	 * On INIT, only select XSTATE components are zeroed, most components
9498 	 * are unchanged.  Currently, the only components that are zeroed and
9499 	 * supported by KVM are MPX and CET related.
9500 	 */
9501 	xfeatures_mask = (kvm_caps.supported_xcr0 | kvm_caps.supported_xss) &
9502 			 (XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR |
9503 			  XFEATURE_MASK_CET_ALL);
9504 	if (!xfeatures_mask)
9505 		return;
9506 
9507 	BUILD_BUG_ON(sizeof(xfeatures_mask) * BITS_PER_BYTE <= XFEATURE_MAX);
9508 
9509 	/*
9510 	 * Unload guest FPU state (if necessary) before zeroing XSTATE fields
9511 	 * as the kernel can only modify the state when its resident in memory,
9512 	 * i.e. when it's not loaded into hardware.
9513 	 *
9514 	 * WARN if the vCPU's desire to run, i.e. whether or not its in KVM_RUN,
9515 	 * doesn't match the loaded/in-use state of the FPU, as KVM_RUN is the
9516 	 * only path that can trigger INIT emulation _and_ loads FPU state, and
9517 	 * KVM_RUN should _always_ load FPU state.
9518 	 */
9519 	WARN_ON_ONCE(vcpu->wants_to_run != fpstate->in_use);
9520 	fpu_in_use = fpstate->in_use;
9521 	if (fpu_in_use)
9522 		kvm_put_guest_fpu(vcpu);
9523 	for_each_set_bit(i, (unsigned long *)&xfeatures_mask, XFEATURE_MAX)
9524 		fpstate_clear_xstate_component(fpstate, i);
9525 	if (fpu_in_use)
9526 		kvm_load_guest_fpu(vcpu);
9527 }
9528 
9529 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9530 {
9531 	struct kvm_cpuid_entry2 *cpuid_0x1;
9532 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
9533 	unsigned long new_cr0;
9534 
9535 	/*
9536 	 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
9537 	 * to handle side effects.  RESET emulation hits those flows and relies
9538 	 * on emulated/virtualized registers, including those that are loaded
9539 	 * into hardware, to be zeroed at vCPU creation.  Use CRs as a sentinel
9540 	 * to detect improper or missing initialization.
9541 	 */
9542 	WARN_ON_ONCE(!init_event &&
9543 		     (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
9544 
9545 	/*
9546 	 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
9547 	 * possible to INIT the vCPU while L2 is active.  Force the vCPU back
9548 	 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
9549 	 * bits), i.e. virtualization is disabled.
9550 	 */
9551 	if (is_guest_mode(vcpu))
9552 		kvm_leave_nested(vcpu);
9553 
9554 	kvm_lapic_reset(vcpu, init_event);
9555 
9556 	WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
9557 	vcpu->arch.hflags = 0;
9558 
9559 	vcpu->arch.smi_pending = 0;
9560 	vcpu->arch.smi_count = 0;
9561 	atomic_set(&vcpu->arch.nmi_queued, 0);
9562 	vcpu->arch.nmi_pending = 0;
9563 	vcpu->arch.nmi_injected = false;
9564 	kvm_clear_interrupt_queue(vcpu);
9565 	kvm_clear_exception_queue(vcpu);
9566 
9567 	memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9568 	kvm_update_dr0123(vcpu);
9569 	vcpu->arch.dr6 = DR6_ACTIVE_LOW;
9570 	vcpu->arch.dr7 = DR7_FIXED_1;
9571 	kvm_update_dr7(vcpu);
9572 
9573 	vcpu->arch.cr2 = 0;
9574 
9575 	kvm_make_request(KVM_REQ_EVENT, vcpu);
9576 	vcpu->arch.apf.msr_en_val = 0;
9577 	vcpu->arch.apf.msr_int_val = 0;
9578 	vcpu->arch.st.msr_val = 0;
9579 
9580 	kvmclock_reset(vcpu);
9581 
9582 	kvm_clear_async_pf_completion_queue(vcpu);
9583 	kvm_async_pf_hash_reset(vcpu);
9584 	vcpu->arch.apf.halted = false;
9585 
9586 	kvm_xstate_reset(vcpu, init_event);
9587 
9588 	if (!init_event) {
9589 		vcpu->arch.smbase = 0x30000;
9590 
9591 		vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9592 
9593 		vcpu->arch.msr_misc_features_enables = 0;
9594 		vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
9595 						  MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
9596 
9597 		__kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
9598 		kvm_msr_write(vcpu, MSR_IA32_XSS, 0);
9599 	}
9600 
9601 	/* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
9602 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9603 	kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
9604 
9605 	/*
9606 	 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
9607 	 * if no CPUID match is found.  Note, it's impossible to get a match at
9608 	 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
9609 	 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
9610 	 * on RESET.  But, go through the motions in case that's ever remedied.
9611 	 */
9612 	cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
9613 	kvm_edx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
9614 
9615 	kvm_x86_call(vcpu_reset)(vcpu, init_event);
9616 
9617 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
9618 	kvm_rip_write(vcpu, 0xfff0);
9619 
9620 	vcpu->arch.cr3 = 0;
9621 	kvm_register_mark_dirty(vcpu, VCPU_REG_CR3);
9622 
9623 	/*
9624 	 * CR0.CD/NW are set on RESET, preserved on INIT.  Note, some versions
9625 	 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
9626 	 * (or qualify) that with a footnote stating that CD/NW are preserved.
9627 	 */
9628 	new_cr0 = X86_CR0_ET;
9629 	if (init_event)
9630 		new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
9631 	else
9632 		new_cr0 |= X86_CR0_NW | X86_CR0_CD;
9633 
9634 	kvm_x86_call(set_cr0)(vcpu, new_cr0);
9635 	kvm_x86_call(set_cr4)(vcpu, 0);
9636 	kvm_x86_call(set_efer)(vcpu, 0);
9637 	kvm_x86_call(update_exception_bitmap)(vcpu);
9638 
9639 	/*
9640 	 * On the standard CR0/CR4/EFER modification paths, there are several
9641 	 * complex conditions determining whether the MMU has to be reset and/or
9642 	 * which PCIDs have to be flushed.  However, CR0.WP and the paging-related
9643 	 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
9644 	 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
9645 	 * CR0 will be '0' prior to RESET).  So we only need to check CR0.PG here.
9646 	 */
9647 	if (old_cr0 & X86_CR0_PG) {
9648 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
9649 		kvm_mmu_reset_context(vcpu);
9650 	}
9651 
9652 	/*
9653 	 * Intel's SDM states that all TLB entries are flushed on INIT.  AMD's
9654 	 * APM states the TLBs are untouched by INIT, but it also states that
9655 	 * the TLBs are flushed on "External initialization of the processor."
9656 	 * Flush the guest TLB regardless of vendor, there is no meaningful
9657 	 * benefit in relying on the guest to flush the TLB immediately after
9658 	 * INIT.  A spurious TLB flush is benign and likely negligible from a
9659 	 * performance perspective.
9660 	 */
9661 	if (init_event)
9662 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
9663 }
9664 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_reset);
9665 
9666 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9667 {
9668 	struct kvm_segment cs;
9669 
9670 	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9671 	cs.selector = vector << 8;
9672 	cs.base = vector << 12;
9673 	kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9674 	kvm_rip_write(vcpu, 0);
9675 }
9676 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_deliver_sipi_vector);
9677 
9678 void kvm_arch_enable_virtualization(void)
9679 {
9680 	x86_virt_register_emergency_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
9681 }
9682 
9683 void kvm_arch_disable_virtualization(void)
9684 {
9685 	x86_virt_unregister_emergency_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
9686 }
9687 
9688 int kvm_arch_enable_virtualization_cpu(void)
9689 {
9690 	struct kvm *kvm;
9691 	struct kvm_vcpu *vcpu;
9692 	unsigned long i;
9693 	int ret;
9694 	u64 local_tsc;
9695 	u64 max_tsc = 0;
9696 	bool stable, backwards_tsc = false;
9697 
9698 	kvm_user_return_msr_cpu_online();
9699 
9700 	ret = kvm_x86_check_processor_compatibility();
9701 	if (ret)
9702 		return ret;
9703 
9704 	ret = kvm_x86_call(enable_virtualization_cpu)();
9705 	if (ret != 0)
9706 		return ret;
9707 
9708 	local_tsc = rdtsc();
9709 	stable = !kvm_check_tsc_unstable();
9710 	list_for_each_entry(kvm, &vm_list, vm_list) {
9711 		kvm_for_each_vcpu(i, vcpu, kvm) {
9712 			if (!stable && vcpu->cpu == smp_processor_id())
9713 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9714 			if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9715 				backwards_tsc = true;
9716 				if (vcpu->arch.last_host_tsc > max_tsc)
9717 					max_tsc = vcpu->arch.last_host_tsc;
9718 			}
9719 		}
9720 	}
9721 
9722 	/*
9723 	 * Sometimes, even reliable TSCs go backwards.  This happens on
9724 	 * platforms that reset TSC during suspend or hibernate actions, but
9725 	 * maintain synchronization.  We must compensate.  Fortunately, we can
9726 	 * detect that condition here, which happens early in CPU bringup,
9727 	 * before any KVM threads can be running.  Unfortunately, we can't
9728 	 * bring the TSCs fully up to date with real time, as we aren't yet far
9729 	 * enough into CPU bringup that we know how much real time has actually
9730 	 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9731 	 * variables that haven't been updated yet.
9732 	 *
9733 	 * So we simply find the maximum observed TSC above, then record the
9734 	 * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
9735 	 * the adjustment will be applied.  Note that we accumulate
9736 	 * adjustments, in case multiple suspend cycles happen before some VCPU
9737 	 * gets a chance to run again.  In the event that no KVM threads get a
9738 	 * chance to run, we will miss the entire elapsed period, as we'll have
9739 	 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9740 	 * loose cycle time.  This isn't too big a deal, since the loss will be
9741 	 * uniform across all VCPUs (not to mention the scenario is extremely
9742 	 * unlikely). It is possible that a second hibernate recovery happens
9743 	 * much faster than a first, causing the observed TSC here to be
9744 	 * smaller; this would require additional padding adjustment, which is
9745 	 * why we set last_host_tsc to the local tsc observed here.
9746 	 *
9747 	 * N.B. - this code below runs only on platforms with reliable TSC,
9748 	 * as that is the only way backwards_tsc is set above.  Also note
9749 	 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9750 	 * have the same delta_cyc adjustment applied if backwards_tsc
9751 	 * is detected.  Note further, this adjustment is only done once,
9752 	 * as we reset last_host_tsc on all VCPUs to stop this from being
9753 	 * called multiple times (one for each physical CPU bringup).
9754 	 *
9755 	 * Platforms with unreliable TSCs don't have to deal with this, they
9756 	 * will be compensated by the logic in vcpu_load, which sets the TSC to
9757 	 * catchup mode.  This will catchup all VCPUs to real time, but cannot
9758 	 * guarantee that they stay in perfect synchronization.
9759 	 */
9760 	if (backwards_tsc) {
9761 		u64 delta_cyc = max_tsc - local_tsc;
9762 		list_for_each_entry(kvm, &vm_list, vm_list) {
9763 			kvm->arch.backwards_tsc_observed = true;
9764 			kvm_for_each_vcpu(i, vcpu, kvm) {
9765 				vcpu->arch.tsc_offset_adjustment += delta_cyc;
9766 				vcpu->arch.last_host_tsc = local_tsc;
9767 				kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9768 			}
9769 
9770 			/*
9771 			 * We have to disable TSC offset matching.. if you were
9772 			 * booting a VM while issuing an S4 host suspend....
9773 			 * you may have some problem.  Solving this issue is
9774 			 * left as an exercise to the reader.
9775 			 */
9776 			kvm->arch.last_tsc_nsec = 0;
9777 			kvm->arch.last_tsc_write = 0;
9778 		}
9779 
9780 	}
9781 	return 0;
9782 }
9783 
9784 void kvm_arch_shutdown(void)
9785 {
9786 	/*
9787 	 * Set virt_rebooting to indicate that KVM has asynchronously disabled
9788 	 * hardware virtualization, i.e. that errors and/or exceptions on SVM
9789 	 * and VMX instructions are expected and should be ignored.
9790 	 */
9791 	virt_rebooting = true;
9792 
9793 	/*
9794 	 * Ensure virt_rebooting is visible before IPIs are sent to other CPUs
9795 	 * to disable virtualization.  Effectively pairs with the reception of
9796 	 * the IPI (virt_rebooting is read in task/exception context, but only
9797 	 * _needs_ to be read as %true after the IPI function callback disables
9798 	 * virtualization).
9799 	 */
9800 	smp_wmb();
9801 }
9802 
9803 void kvm_arch_disable_virtualization_cpu(void)
9804 {
9805 	kvm_x86_call(disable_virtualization_cpu)();
9806 
9807 	/*
9808 	 * Leave the user-return notifiers as-is when disabling virtualization
9809 	 * for reboot, i.e. when disabling via IPI function call, and instead
9810 	 * pin kvm.ko (if it's a module) to defend against use-after-free (in
9811 	 * the *very* unlikely scenario module unload is racing with reboot).
9812 	 * On a forced reboot, tasks aren't frozen before shutdown, and so KVM
9813 	 * could be actively modifying user-return MSR state when the IPI to
9814 	 * disable virtualization arrives.  Handle the extreme edge case here
9815 	 * instead of trying to account for it in the normal flows.
9816 	 */
9817 	if (in_task() || WARN_ON_ONCE(!virt_rebooting))
9818 		drop_user_return_notifiers();
9819 	else
9820 		__module_get(THIS_MODULE);
9821 }
9822 
9823 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9824 {
9825 	return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9826 }
9827 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_is_reset_bsp);
9828 
9829 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9830 {
9831 	return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9832 }
9833 
9834 void kvm_arch_free_vm(struct kvm *kvm)
9835 {
9836 #if IS_ENABLED(CONFIG_HYPERV)
9837 	kfree(kvm->arch.hv_pa_pg);
9838 #endif
9839 	__kvm_arch_free_vm(kvm);
9840 }
9841 
9842 
9843 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9844 {
9845 	int ret;
9846 	unsigned long flags;
9847 
9848 	if (!kvm_is_vm_type_supported(type))
9849 		return -EINVAL;
9850 
9851 	kvm->arch.vm_type = type;
9852 	kvm->arch.has_private_mem =
9853 		(type == KVM_X86_SW_PROTECTED_VM);
9854 	/* Decided by the vendor code for other VM types.  */
9855 	kvm->arch.pre_fault_allowed =
9856 		type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
9857 	kvm->arch.disabled_quirks = kvm_caps.inapplicable_quirks & kvm_caps.supported_quirks;
9858 
9859 	ret = kvm_page_track_init(kvm);
9860 	if (ret)
9861 		goto out;
9862 
9863 	ret = kvm_mmu_init_vm(kvm);
9864 	if (ret)
9865 		goto out_cleanup_page_track;
9866 
9867 	ret = kvm_x86_call(vm_init)(kvm);
9868 	if (ret)
9869 		goto out_uninit_mmu;
9870 
9871 	atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9872 
9873 	raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9874 	mutex_init(&kvm->arch.apic_map_lock);
9875 	seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
9876 	ratelimit_state_init(&kvm->arch.kvmclock_update_rs, HZ, 10);
9877 	ratelimit_set_flags(&kvm->arch.kvmclock_update_rs, RATELIMIT_MSG_ON_RELEASE);
9878 	kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
9879 
9880 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
9881 	pvclock_update_vm_gtod_copy(kvm);
9882 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
9883 
9884 	kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
9885 	kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
9886 	kvm->arch.guest_can_read_msr_platform_info = true;
9887 	kvm->arch.enable_pmu = enable_pmu && !kvm->arch.has_protected_pmu;
9888 
9889 #if IS_ENABLED(CONFIG_HYPERV)
9890 	spin_lock_init(&kvm->arch.hv_root_tdp_lock);
9891 	kvm->arch.hv_root_tdp = INVALID_PAGE;
9892 #endif
9893 
9894 	kvm_apicv_init(kvm);
9895 	kvm_hv_init_vm(kvm);
9896 	kvm_xen_init_vm(kvm);
9897 
9898 	if (ignore_msrs && !report_ignored_msrs) {
9899 		pr_warn_once("Running KVM with ignore_msrs=1 and report_ignored_msrs=0 is not a\n"
9900 			     "a supported configuration.  Lying to the guest about the existence of MSRs\n"
9901 			     "may cause the guest operating system to hang or produce errors.  If a guest\n"
9902 			     "does not run without ignore_msrs=1, please report it to kvm@vger.kernel.org.\n");
9903 	}
9904 
9905 	once_init(&kvm->arch.nx_once);
9906 	return 0;
9907 
9908 out_uninit_mmu:
9909 	kvm_mmu_uninit_vm(kvm);
9910 out_cleanup_page_track:
9911 	kvm_page_track_cleanup(kvm);
9912 out:
9913 	return ret;
9914 }
9915 
9916 /**
9917  * __x86_set_memory_region: Setup KVM internal memory slot
9918  *
9919  * @kvm: the kvm pointer to the VM.
9920  * @id: the slot ID to setup.
9921  * @gpa: the GPA to install the slot (unused when @size == 0).
9922  * @size: the size of the slot. Set to zero to uninstall a slot.
9923  *
9924  * This function helps to setup a KVM internal memory slot.  Specify
9925  * @size > 0 to install a new slot, while @size == 0 to uninstall a
9926  * slot.  The return code can be one of the following:
9927  *
9928  *   HVA:           on success (uninstall will return a bogus HVA)
9929  *   -errno:        on error
9930  *
9931  * The caller should always use IS_ERR() to check the return value
9932  * before use.  Note, the KVM internal memory slots are guaranteed to
9933  * remain valid and unchanged until the VM is destroyed, i.e., the
9934  * GPA->HVA translation will not change.  However, the HVA is a user
9935  * address, i.e. its accessibility is not guaranteed, and must be
9936  * accessed via __copy_{to,from}_user().
9937  */
9938 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
9939 				      u32 size)
9940 {
9941 	int i, r;
9942 	unsigned long hva, old_npages;
9943 	struct kvm_memslots *slots = kvm_memslots(kvm);
9944 	struct kvm_memory_slot *slot;
9945 
9946 	lockdep_assert_held(&kvm->slots_lock);
9947 
9948 	if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9949 		return ERR_PTR_USR(-EINVAL);
9950 
9951 	slot = id_to_memslot(slots, id);
9952 	if (size) {
9953 		if (slot && slot->npages)
9954 			return ERR_PTR_USR(-EEXIST);
9955 
9956 		/*
9957 		 * MAP_SHARED to prevent internal slot pages from being moved
9958 		 * by fork()/COW.
9959 		 */
9960 		hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9961 			      MAP_SHARED | MAP_ANONYMOUS, 0);
9962 		if (IS_ERR_VALUE(hva))
9963 			return (void __user *)hva;
9964 	} else {
9965 		if (!slot || !slot->npages)
9966 			return NULL;
9967 
9968 		old_npages = slot->npages;
9969 		hva = slot->userspace_addr;
9970 	}
9971 
9972 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
9973 		struct kvm_userspace_memory_region2 m;
9974 
9975 		m.slot = id | (i << 16);
9976 		m.flags = 0;
9977 		m.guest_phys_addr = gpa;
9978 		m.userspace_addr = hva;
9979 		m.memory_size = size;
9980 		r = kvm_set_internal_memslot(kvm, &m);
9981 		if (r < 0)
9982 			return ERR_PTR_USR(r);
9983 	}
9984 
9985 	if (!size)
9986 		vm_munmap(hva, old_npages * PAGE_SIZE);
9987 
9988 	return (void __user *)hva;
9989 }
9990 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__x86_set_memory_region);
9991 
9992 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
9993 {
9994 	/*
9995 	 * Stop all background workers and kthreads before destroying vCPUs, as
9996 	 * iterating over vCPUs in a different task while vCPUs are being freed
9997 	 * is unsafe, i.e. will lead to use-after-free.  The PIT also needs to
9998 	 * be stopped before IRQ routing is freed.
9999 	 *
10000 	 * Do NOT free the in-kernel PIC or I/O APIC here (but as above, make
10001 	 * sure to flush any background work), as KVM expects interrupt routing
10002 	 * structures to be valid until vCPUs are destroyed.
10003 	 */
10004 #ifdef CONFIG_KVM_IOAPIC
10005 	kvm_free_pit(kvm);
10006 	if (kvm->arch.vioapic)
10007 		cancel_delayed_work_sync(&kvm->arch.vioapic->eoi_inject);
10008 #endif
10009 
10010 	kvm_mmu_pre_destroy_vm(kvm);
10011 	kvm_x86_call(vm_pre_destroy)(kvm);
10012 }
10013 
10014 void kvm_arch_destroy_vm(struct kvm *kvm)
10015 {
10016 	if (current->mm == kvm->mm) {
10017 		/*
10018 		 * Free memory regions allocated on behalf of userspace,
10019 		 * unless the memory map has changed due to process exit
10020 		 * or fd copying.
10021 		 */
10022 		mutex_lock(&kvm->slots_lock);
10023 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
10024 					0, 0);
10025 		__x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
10026 					0, 0);
10027 		__x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
10028 		mutex_unlock(&kvm->slots_lock);
10029 	}
10030 	if (kvm->arch.created_mediated_pmu)
10031 		perf_release_mediated_pmu();
10032 	kvm_destroy_vcpus(kvm);
10033 	kvm_free_msr_filter((void * __force)kvm->arch.msr_filter);
10034 #ifdef CONFIG_KVM_IOAPIC
10035 	kvm_pic_destroy(kvm);
10036 	kvm_ioapic_destroy(kvm);
10037 #endif
10038 	kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
10039 	kfree((void * __force)kvm->arch.pmu_event_filter);
10040 	kvm_mmu_uninit_vm(kvm);
10041 	kvm_page_track_cleanup(kvm);
10042 	kvm_xen_destroy_vm(kvm);
10043 	kvm_hv_destroy_vm(kvm);
10044 	kvm_x86_call(vm_destroy)(kvm);
10045 }
10046 
10047 static void memslot_rmap_free(struct kvm_memory_slot *slot)
10048 {
10049 	int i;
10050 
10051 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10052 		vfree(slot->arch.rmap[i]);
10053 		slot->arch.rmap[i] = NULL;
10054 	}
10055 }
10056 
10057 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
10058 {
10059 	int i;
10060 
10061 	memslot_rmap_free(slot);
10062 
10063 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
10064 		vfree(slot->arch.lpage_info[i - 1]);
10065 		slot->arch.lpage_info[i - 1] = NULL;
10066 	}
10067 
10068 	kvm_page_track_free_memslot(slot);
10069 }
10070 
10071 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
10072 {
10073 	const int sz = sizeof(*slot->arch.rmap[0]);
10074 	int i;
10075 
10076 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10077 		int level = i + 1;
10078 		int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
10079 
10080 		if (slot->arch.rmap[i])
10081 			continue;
10082 
10083 		slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
10084 		if (!slot->arch.rmap[i]) {
10085 			memslot_rmap_free(slot);
10086 			return -ENOMEM;
10087 		}
10088 	}
10089 
10090 	return 0;
10091 }
10092 
10093 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
10094 				      struct kvm_memory_slot *slot)
10095 {
10096 	unsigned long npages = slot->npages;
10097 	int i, r;
10098 
10099 	/*
10100 	 * Clear out the previous array pointers for the KVM_MR_MOVE case.  The
10101 	 * old arrays will be freed by kvm_set_memory_region() if installing
10102 	 * the new memslot is successful.
10103 	 */
10104 	memset(&slot->arch, 0, sizeof(slot->arch));
10105 
10106 	if (kvm_memslots_have_rmaps(kvm)) {
10107 		r = memslot_rmap_alloc(slot, npages);
10108 		if (r)
10109 			return r;
10110 	}
10111 
10112 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
10113 		struct kvm_lpage_info *linfo;
10114 		unsigned long ugfn;
10115 		int lpages;
10116 		int level = i + 1;
10117 
10118 		lpages = __kvm_mmu_slot_lpages(slot, npages, level);
10119 
10120 		linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
10121 		if (!linfo)
10122 			goto out_free;
10123 
10124 		slot->arch.lpage_info[i - 1] = linfo;
10125 
10126 		if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10127 			linfo[0].disallow_lpage = 1;
10128 		if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10129 			linfo[lpages - 1].disallow_lpage = 1;
10130 		ugfn = slot->userspace_addr >> PAGE_SHIFT;
10131 		/*
10132 		 * If the gfn and userspace address are not aligned wrt each
10133 		 * other, disable large page support for this slot.
10134 		 */
10135 		if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10136 			unsigned long j;
10137 
10138 			for (j = 0; j < lpages; ++j)
10139 				linfo[j].disallow_lpage = 1;
10140 		}
10141 	}
10142 
10143 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
10144 	kvm_mmu_init_memslot_memory_attributes(kvm, slot);
10145 #endif
10146 
10147 	if (kvm_page_track_create_memslot(kvm, slot, npages))
10148 		goto out_free;
10149 
10150 	return 0;
10151 
10152 out_free:
10153 	memslot_rmap_free(slot);
10154 
10155 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
10156 		vfree(slot->arch.lpage_info[i - 1]);
10157 		slot->arch.lpage_info[i - 1] = NULL;
10158 	}
10159 	return -ENOMEM;
10160 }
10161 
10162 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10163 {
10164 	struct kvm_vcpu *vcpu;
10165 	unsigned long i;
10166 
10167 	/*
10168 	 * memslots->generation has been incremented.
10169 	 * mmio generation may have reached its maximum value.
10170 	 */
10171 	kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10172 
10173 	/* Force re-initialization of steal_time cache */
10174 	kvm_for_each_vcpu(i, vcpu, kvm)
10175 		kvm_vcpu_kick(vcpu);
10176 }
10177 
10178 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10179 				   const struct kvm_memory_slot *old,
10180 				   struct kvm_memory_slot *new,
10181 				   enum kvm_mr_change change)
10182 {
10183 	/*
10184 	 * KVM doesn't support moving memslots when there are external page
10185 	 * trackers attached to the VM, i.e. if KVMGT is in use.
10186 	 */
10187 	if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
10188 		return -EINVAL;
10189 
10190 	if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
10191 		if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
10192 			return -EINVAL;
10193 
10194 		if (kvm_is_gfn_alias(kvm, new->base_gfn + new->npages - 1))
10195 			return -EINVAL;
10196 
10197 		return kvm_alloc_memslot_metadata(kvm, new);
10198 	}
10199 
10200 	if (change == KVM_MR_FLAGS_ONLY)
10201 		memcpy(&new->arch, &old->arch, sizeof(old->arch));
10202 	else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
10203 		return -EIO;
10204 
10205 	return 0;
10206 }
10207 
10208 
10209 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
10210 {
10211 	int nr_slots;
10212 
10213 	if (!kvm->arch.cpu_dirty_log_size)
10214 		return;
10215 
10216 	nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
10217 	if ((enable && nr_slots == 1) || !nr_slots)
10218 		kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
10219 }
10220 
10221 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10222 				     struct kvm_memory_slot *old,
10223 				     const struct kvm_memory_slot *new,
10224 				     enum kvm_mr_change change)
10225 {
10226 	u32 old_flags = old ? old->flags : 0;
10227 	u32 new_flags = new ? new->flags : 0;
10228 	bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
10229 
10230 	/*
10231 	 * Update CPU dirty logging if dirty logging is being toggled.  This
10232 	 * applies to all operations.
10233 	 */
10234 	if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
10235 		kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
10236 
10237 	/*
10238 	 * Nothing more to do for RO slots (which can't be dirtied and can't be
10239 	 * made writable) or CREATE/MOVE/DELETE of a slot.
10240 	 *
10241 	 * For a memslot with dirty logging disabled:
10242 	 * CREATE:      No dirty mappings will already exist.
10243 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
10244 	 *		kvm_arch_flush_shadow_memslot()
10245 	 *
10246 	 * For a memslot with dirty logging enabled:
10247 	 * CREATE:      No shadow pages exist, thus nothing to write-protect
10248 	 *		and no dirty bits to clear.
10249 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
10250 	 *		kvm_arch_flush_shadow_memslot().
10251 	 */
10252 	if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
10253 		return;
10254 
10255 	/*
10256 	 * READONLY and non-flags changes were filtered out above, and the only
10257 	 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
10258 	 * logging isn't being toggled on or off.
10259 	 */
10260 	if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
10261 		return;
10262 
10263 	if (!log_dirty_pages) {
10264 		/*
10265 		 * Recover huge page mappings in the slot now that dirty logging
10266 		 * is disabled, i.e. now that KVM does not have to track guest
10267 		 * writes at 4KiB granularity.
10268 		 *
10269 		 * Dirty logging might be disabled by userspace if an ongoing VM
10270 		 * live migration is cancelled and the VM must continue running
10271 		 * on the source.
10272 		 */
10273 		kvm_mmu_recover_huge_pages(kvm, new);
10274 	} else {
10275 		/*
10276 		 * Initially-all-set does not require write protecting any page,
10277 		 * because they're all assumed to be dirty.
10278 		 */
10279 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
10280 			return;
10281 
10282 		if (READ_ONCE(eager_page_split))
10283 			kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
10284 
10285 		if (kvm->arch.cpu_dirty_log_size) {
10286 			kvm_mmu_slot_leaf_clear_dirty(kvm, new);
10287 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
10288 		} else {
10289 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
10290 		}
10291 
10292 		/*
10293 		 * Unconditionally flush the TLBs after enabling dirty logging.
10294 		 * A flush is almost always going to be necessary (see below),
10295 		 * and unconditionally flushing allows the helpers to omit
10296 		 * the subtly complex checks when removing write access.
10297 		 *
10298 		 * Do the flush outside of mmu_lock to reduce the amount of
10299 		 * time mmu_lock is held.  Flushing after dropping mmu_lock is
10300 		 * safe as KVM only needs to guarantee the slot is fully
10301 		 * write-protected before returning to userspace, i.e. before
10302 		 * userspace can consume the dirty status.
10303 		 *
10304 		 * Flushing outside of mmu_lock requires KVM to be careful when
10305 		 * making decisions based on writable status of an SPTE, e.g. a
10306 		 * !writable SPTE doesn't guarantee a CPU can't perform writes.
10307 		 *
10308 		 * Specifically, KVM also write-protects guest page tables to
10309 		 * monitor changes when using shadow paging, and must guarantee
10310 		 * no CPUs can write to those page before mmu_lock is dropped.
10311 		 * Because CPUs may have stale TLB entries at this point, a
10312 		 * !writable SPTE doesn't guarantee CPUs can't perform writes.
10313 		 *
10314 		 * KVM also allows making SPTES writable outside of mmu_lock,
10315 		 * e.g. to allow dirty logging without taking mmu_lock.
10316 		 *
10317 		 * To handle these scenarios, KVM uses a separate software-only
10318 		 * bit (MMU-writable) to track if a SPTE is !writable due to
10319 		 * a guest page table being write-protected (KVM clears the
10320 		 * MMU-writable flag when write-protecting for shadow paging).
10321 		 *
10322 		 * The use of MMU-writable is also the primary motivation for
10323 		 * the unconditional flush.  Because KVM must guarantee that a
10324 		 * CPU doesn't contain stale, writable TLB entries for a
10325 		 * !MMU-writable SPTE, KVM must flush if it encounters any
10326 		 * MMU-writable SPTE regardless of whether the actual hardware
10327 		 * writable bit was set.  I.e. KVM is almost guaranteed to need
10328 		 * to flush, while unconditionally flushing allows the "remove
10329 		 * write access" helpers to ignore MMU-writable entirely.
10330 		 *
10331 		 * See is_writable_pte() for more details (the case involving
10332 		 * access-tracked SPTEs is particularly relevant).
10333 		 */
10334 		kvm_flush_remote_tlbs_memslot(kvm, new);
10335 	}
10336 }
10337 
10338 void kvm_arch_commit_memory_region(struct kvm *kvm,
10339 				struct kvm_memory_slot *old,
10340 				const struct kvm_memory_slot *new,
10341 				enum kvm_mr_change change)
10342 {
10343 	if (change == KVM_MR_DELETE)
10344 		kvm_page_track_delete_slot(kvm, old);
10345 
10346 	if (!kvm->arch.n_requested_mmu_pages &&
10347 	    (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
10348 		unsigned long nr_mmu_pages;
10349 
10350 		nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
10351 		nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
10352 		kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
10353 	}
10354 
10355 	kvm_mmu_slot_apply_flags(kvm, old, new, change);
10356 
10357 	/* Free the arrays associated with the old memslot. */
10358 	if (change == KVM_MR_MOVE)
10359 		kvm_arch_free_memslot(kvm, old);
10360 }
10361 
10362 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
10363 {
10364 	WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
10365 
10366 	if (vcpu->arch.guest_state_protected)
10367 		return true;
10368 
10369 	return kvm_x86_call(get_cpl)(vcpu) == 0;
10370 }
10371 
10372 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
10373 {
10374 	WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
10375 
10376 	if (vcpu->arch.guest_state_protected)
10377 		return 0;
10378 
10379 	return kvm_rip_read(vcpu);
10380 }
10381 
10382 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
10383 {
10384 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
10385 }
10386 
10387 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10388 {
10389 	BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
10390 
10391 	return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10392 }
10393 
10394 static inline u32 kvm_async_pf_next_probe(u32 key)
10395 {
10396 	return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
10397 }
10398 
10399 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10400 {
10401 	u32 key = kvm_async_pf_hash_fn(gfn);
10402 
10403 	while (vcpu->arch.apf.gfns[key] != ~0)
10404 		key = kvm_async_pf_next_probe(key);
10405 
10406 	vcpu->arch.apf.gfns[key] = gfn;
10407 }
10408 
10409 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10410 {
10411 	int i;
10412 	u32 key = kvm_async_pf_hash_fn(gfn);
10413 
10414 	for (i = 0; i < ASYNC_PF_PER_VCPU &&
10415 		     (vcpu->arch.apf.gfns[key] != gfn &&
10416 		      vcpu->arch.apf.gfns[key] != ~0); i++)
10417 		key = kvm_async_pf_next_probe(key);
10418 
10419 	return key;
10420 }
10421 
10422 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10423 {
10424 	return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10425 }
10426 
10427 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10428 {
10429 	u32 i, j, k;
10430 
10431 	i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10432 
10433 	if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
10434 		return;
10435 
10436 	while (true) {
10437 		vcpu->arch.apf.gfns[i] = ~0;
10438 		do {
10439 			j = kvm_async_pf_next_probe(j);
10440 			if (vcpu->arch.apf.gfns[j] == ~0)
10441 				return;
10442 			k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10443 			/*
10444 			 * k lies cyclically in ]i,j]
10445 			 * |    i.k.j |
10446 			 * |....j i.k.| or  |.k..j i...|
10447 			 */
10448 		} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10449 		vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10450 		i = j;
10451 	}
10452 }
10453 
10454 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
10455 {
10456 	u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
10457 
10458 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
10459 				      sizeof(reason));
10460 }
10461 
10462 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
10463 {
10464 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10465 
10466 	return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10467 					     &token, offset, sizeof(token));
10468 }
10469 
10470 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
10471 {
10472 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10473 	u32 val;
10474 
10475 	if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10476 					 &val, offset, sizeof(val)))
10477 		return false;
10478 
10479 	return !val;
10480 }
10481 
10482 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10483 {
10484 
10485 	if (!kvm_pv_async_pf_enabled(vcpu))
10486 		return false;
10487 
10488 	if (!(vcpu->arch.apf.msr_en_val & KVM_ASYNC_PF_SEND_ALWAYS) &&
10489 	    (vcpu->arch.guest_state_protected || !kvm_x86_call(get_cpl)(vcpu)))
10490 		return false;
10491 
10492 	if (is_guest_mode(vcpu)) {
10493 		/*
10494 		 * L1 needs to opt into the special #PF vmexits that are
10495 		 * used to deliver async page faults.
10496 		 */
10497 		return vcpu->arch.apf.msr_en_val & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
10498 	} else {
10499 		/*
10500 		 * Play it safe in case the guest temporarily disables paging.
10501 		 * The real mode IDT in particular is unlikely to have a #PF
10502 		 * exception setup.
10503 		 */
10504 		return is_paging(vcpu);
10505 	}
10506 }
10507 
10508 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10509 {
10510 	if (unlikely(!lapic_in_kernel(vcpu) ||
10511 		     kvm_event_needs_reinjection(vcpu) ||
10512 		     kvm_is_exception_pending(vcpu)))
10513 		return false;
10514 
10515 	if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10516 		return false;
10517 
10518 	/*
10519 	 * If interrupts are off we cannot even use an artificial
10520 	 * halt state.
10521 	 */
10522 	return kvm_is_interrupt_allowed(vcpu);
10523 }
10524 
10525 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10526 				     struct kvm_async_pf *work)
10527 {
10528 	struct x86_exception fault;
10529 
10530 	trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
10531 	kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10532 
10533 	if (kvm_can_deliver_async_pf(vcpu) &&
10534 	    !apf_put_user_notpresent(vcpu)) {
10535 		fault.vector = PF_VECTOR;
10536 		fault.error_code_valid = true;
10537 		fault.error_code = 0;
10538 		fault.nested_page_fault = false;
10539 		fault.address = work->arch.token;
10540 		fault.async_page_fault = true;
10541 		kvm_inject_page_fault(vcpu, &fault, false);
10542 		return true;
10543 	} else {
10544 		/*
10545 		 * It is not possible to deliver a paravirtualized asynchronous
10546 		 * page fault, but putting the guest in an artificial halt state
10547 		 * can be beneficial nevertheless: if an interrupt arrives, we
10548 		 * can deliver it timely and perhaps the guest will schedule
10549 		 * another process.  When the instruction that triggered a page
10550 		 * fault is retried, hopefully the page will be ready in the host.
10551 		 */
10552 		kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10553 		return false;
10554 	}
10555 }
10556 
10557 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10558 				 struct kvm_async_pf *work)
10559 {
10560 	struct kvm_lapic_irq irq = {
10561 		.delivery_mode = APIC_DM_FIXED,
10562 		.vector = vcpu->arch.apf.vec
10563 	};
10564 
10565 	if (work->wakeup_all)
10566 		work->arch.token = ~0; /* broadcast wakeup */
10567 	else
10568 		kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10569 	trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
10570 
10571 	if ((work->wakeup_all || work->notpresent_injected) &&
10572 	    kvm_pv_async_pf_enabled(vcpu) &&
10573 	    !apf_put_user_ready(vcpu, work->arch.token)) {
10574 		WRITE_ONCE(vcpu->arch.apf.pageready_pending, true);
10575 		kvm_apic_set_irq(vcpu, &irq, NULL);
10576 	}
10577 
10578 	vcpu->arch.apf.halted = false;
10579 	kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
10580 }
10581 
10582 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
10583 {
10584 	kvm_make_request(KVM_REQ_APF_READY, vcpu);
10585 
10586 	/* Pairs with smp_store_mb() in kvm_set_msr_common(). */
10587 	smp_mb__after_atomic();
10588 
10589 	if (!READ_ONCE(vcpu->arch.apf.pageready_pending))
10590 		kvm_vcpu_kick(vcpu);
10591 }
10592 
10593 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
10594 {
10595 	if (!kvm_pv_async_pf_enabled(vcpu))
10596 		return true;
10597 	else
10598 		return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
10599 }
10600 
10601 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
10602 {
10603 	/*
10604 	 * Non-coherent DMA assignment and de-assignment may affect whether or
10605 	 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
10606 	 * due to toggling the "ignore PAT" bit.  Zap all SPTEs when the first
10607 	 * (or last) non-coherent device is (un)registered to so that new SPTEs
10608 	 * with the correct "ignore guest PAT" setting are created.
10609 	 *
10610 	 * If KVM always honors guest PAT, however, there is nothing to do.
10611 	 */
10612 	if (kvm_check_has_quirk(kvm, KVM_X86_QUIRK_IGNORE_GUEST_PAT))
10613 		kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
10614 }
10615 
10616 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10617 {
10618 	if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
10619 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
10620 }
10621 
10622 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10623 {
10624 	if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
10625 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
10626 }
10627 
10628 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10629 {
10630 	return atomic_read(&kvm->arch.noncoherent_dma_count);
10631 }
10632 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_arch_has_noncoherent_dma);
10633 
10634 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10635 {
10636 	return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10637 }
10638 
10639 #ifdef CONFIG_KVM_GUEST_MEMFD
10640 /*
10641  * KVM doesn't yet support initializing guest_memfd memory as shared for VMs
10642  * with private memory (the private vs. shared tracking needs to be moved into
10643  * guest_memfd).
10644  */
10645 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm)
10646 {
10647 	return !kvm_arch_has_private_mem(kvm);
10648 }
10649 
10650 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_CONVERT
10651 int kvm_arch_gmem_make_private(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
10652 			       kvm_pfn_t nr_pages)
10653 {
10654 	return kvm_x86_call(gmem_make_private)(kvm, gfn, pfn, nr_pages);
10655 }
10656 #endif
10657 
10658 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_RECLAIM
10659 void kvm_arch_gmem_reclaim(kvm_pfn_t pfn, kvm_pfn_t nr_pages)
10660 {
10661 	kvm_x86_call(gmem_make_shared)(pfn, nr_pages);
10662 }
10663 #endif
10664 
10665 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
10666 void kvm_arch_gmem_invalidate_range(struct kvm *kvm, struct kvm_gfn_range *range)
10667 {
10668 	kvm_x86_call(gmem_invalidate_range)(kvm, range);
10669 }
10670 #endif
10671 #endif
10672 
10673 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
10674 {
10675 	struct kvm_pagewalk *gva_walk = &vcpu->arch.gva_walk;
10676 	struct x86_exception fault;
10677 	u64 access = error_code &
10678 		(PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
10679 
10680 	if (!(error_code & PFERR_PRESENT_MASK) ||
10681 	    gva_walk->gva_to_gpa(vcpu, gva_walk, gva, access, &fault) != INVALID_GPA) {
10682 		/*
10683 		 * If gva_walk->gva_to_gpa succeeded, the page
10684 		 * tables probably do not match the TLB.  Just proceed
10685 		 * with the error code that the processor gave.
10686 		 */
10687 		fault.vector = PF_VECTOR;
10688 		fault.error_code_valid = true;
10689 		fault.error_code = error_code;
10690 		fault.nested_page_fault = false;
10691 		fault.address = gva;
10692 		fault.async_page_fault = false;
10693 	}
10694 	gva_walk->inject_page_fault(vcpu, &fault, true);
10695 }
10696 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fixup_and_inject_pf_error);
10697 
10698 /*
10699  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
10700  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
10701  * indicates whether exit to userspace is needed.
10702  */
10703 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
10704 			      struct x86_exception *e)
10705 {
10706 	if (r == X86EMUL_PROPAGATE_FAULT) {
10707 		if (KVM_BUG_ON(!e, vcpu->kvm))
10708 			return -EIO;
10709 
10710 		kvm_inject_emulated_page_fault(vcpu, e);
10711 		return 1;
10712 	}
10713 
10714 	/*
10715 	 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
10716 	 * while handling a VMX instruction KVM could've handled the request
10717 	 * correctly by exiting to userspace and performing I/O but there
10718 	 * doesn't seem to be a real use-case behind such requests, just return
10719 	 * KVM_EXIT_INTERNAL_ERROR for now.
10720 	 */
10721 	kvm_prepare_emulation_failure_exit(vcpu);
10722 
10723 	return 0;
10724 }
10725 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_memory_failure);
10726 
10727 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
10728 {
10729 	bool pcid_enabled;
10730 	struct x86_exception e;
10731 	struct {
10732 		u64 pcid;
10733 		u64 gla;
10734 	} operand;
10735 	int r;
10736 
10737 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
10738 	if (r != X86EMUL_CONTINUE)
10739 		return kvm_handle_memory_failure(vcpu, r, &e);
10740 
10741 	if (operand.pcid >> 12 != 0) {
10742 		kvm_inject_gp(vcpu, 0);
10743 		return 1;
10744 	}
10745 
10746 	if (WARN_ON_ONCE(tdp_enabled))
10747 		return 0;
10748 
10749 	pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
10750 
10751 	switch (type) {
10752 	case INVPCID_TYPE_INDIV_ADDR:
10753 		/*
10754 		 * LAM doesn't apply to addresses that are inputs to TLB
10755 		 * invalidation.
10756 		 */
10757 		if ((!pcid_enabled && (operand.pcid != 0)) ||
10758 		    is_noncanonical_invlpg_address(operand.gla, vcpu)) {
10759 			kvm_inject_gp(vcpu, 0);
10760 			return 1;
10761 		}
10762 		kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
10763 		return kvm_skip_emulated_instruction(vcpu);
10764 
10765 	case INVPCID_TYPE_SINGLE_CTXT:
10766 		if (!pcid_enabled && (operand.pcid != 0)) {
10767 			kvm_inject_gp(vcpu, 0);
10768 			return 1;
10769 		}
10770 
10771 		/*
10772 		 * When ERAPS is supported, invalidating a specific PCID clears
10773 		 * the RAP (Return Address Predicator).
10774 		 */
10775 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_ERAPS))
10776 			kvm_register_mark_dirty(vcpu, VCPU_REG_ERAPS);
10777 
10778 		kvm_invalidate_pcid(vcpu, operand.pcid);
10779 		return kvm_skip_emulated_instruction(vcpu);
10780 
10781 	case INVPCID_TYPE_ALL_NON_GLOBAL:
10782 		/*
10783 		 * Currently, KVM doesn't mark global entries in the shadow
10784 		 * page tables, so a non-global flush just degenerates to a
10785 		 * global flush. If needed, we could optimize this later by
10786 		 * keeping track of global entries in shadow page tables.
10787 		 */
10788 
10789 		fallthrough;
10790 	case INVPCID_TYPE_ALL_INCL_GLOBAL:
10791 		/*
10792 		 * Don't bother marking VCPU_REG_ERAPS dirty, SVM will take
10793 		 * care of doing so when emulating the full guest TLB flush
10794 		 * (the RAP is cleared on all implicit TLB flushes).
10795 		 */
10796 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
10797 		return kvm_skip_emulated_instruction(vcpu);
10798 
10799 	default:
10800 		kvm_inject_gp(vcpu, 0);
10801 		return 1;
10802 	}
10803 }
10804 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invpcid);
10805 
10806 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
10807 {
10808 	struct kvm_run *run = vcpu->run;
10809 	struct kvm_mmio_fragment *frag;
10810 	unsigned int len;
10811 
10812 	if (KVM_BUG_ON(!vcpu->mmio_needed, vcpu->kvm))
10813 		return -EIO;
10814 
10815 	/* Complete previous fragment */
10816 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
10817 	len = min(8u, frag->len);
10818 	if (!vcpu->mmio_is_write)
10819 		memcpy(frag->data, run->mmio.data, len);
10820 
10821 	if (frag->len <= 8) {
10822 		/* Switch to the next fragment. */
10823 		frag++;
10824 		vcpu->mmio_cur_fragment++;
10825 	} else {
10826 		/* Go forward to the next mmio piece. */
10827 		frag->data += len;
10828 		frag->gpa += len;
10829 		frag->len -= len;
10830 	}
10831 
10832 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
10833 		vcpu->mmio_needed = 0;
10834 
10835 		/*
10836 		 * All done, as frag->data always points at the GHCB scratch
10837 		 * area and VMGEXIT is trap-like (RIP is advanced by hardware).
10838 		 */
10839 		return 1;
10840 	}
10841 
10842 	// More MMIO is needed
10843 	kvm_prepare_emulated_mmio_exit(vcpu, frag);
10844 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
10845 	return 0;
10846 }
10847 
10848 int kvm_sev_es_mmio(struct kvm_vcpu *vcpu, bool is_write, gpa_t gpa,
10849 		    unsigned int bytes, void *data)
10850 {
10851 	struct kvm_mmio_fragment *frag;
10852 	int handled;
10853 
10854 	if (!data || WARN_ON_ONCE(object_is_on_stack(data)))
10855 		return -EINVAL;
10856 
10857 	if (is_write)
10858 		handled = vcpu_mmio_write(vcpu, gpa, bytes, data);
10859 	else
10860 		handled = vcpu_mmio_read(vcpu, gpa, bytes, data);
10861 	if (handled == bytes)
10862 		return 1;
10863 
10864 	bytes -= handled;
10865 	gpa += handled;
10866 	data += handled;
10867 
10868 	/*
10869 	 * TODO: Determine whether or not userspace plays nice with MMIO
10870 	 *       requests that split a page boundary.
10871 	 */
10872 	frag = vcpu->mmio_fragments;
10873 	frag->len = bytes;
10874 	frag->gpa = gpa;
10875 	frag->data = data;
10876 
10877 	vcpu->mmio_needed = 1;
10878 	vcpu->mmio_cur_fragment = 0;
10879 	vcpu->mmio_nr_fragments = 1;
10880 	vcpu->mmio_is_write = is_write;
10881 
10882 	kvm_prepare_emulated_mmio_exit(vcpu, frag);
10883 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
10884 	return 0;
10885 }
10886 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_mmio);
10887 
10888 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
10889 {
10890 	vcpu->arch.sev_pio_count -= count;
10891 	vcpu->arch.sev_pio_data += count * size;
10892 }
10893 
10894 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
10895 			   unsigned int port);
10896 
10897 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
10898 {
10899 	int size = vcpu->arch.pio.size;
10900 	int port = vcpu->arch.pio.port;
10901 
10902 	vcpu->arch.pio.count = 0;
10903 	if (vcpu->arch.sev_pio_count)
10904 		return kvm_sev_es_outs(vcpu, size, port);
10905 	return 1;
10906 }
10907 
10908 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
10909 			   unsigned int port)
10910 {
10911 	for (;;) {
10912 		unsigned int count =
10913 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
10914 		int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
10915 
10916 		/* memcpy done already by emulator_pio_out.  */
10917 		advance_sev_es_emulated_pio(vcpu, count, size);
10918 		if (!ret)
10919 			break;
10920 
10921 		/* Emulation done by the kernel.  */
10922 		if (!vcpu->arch.sev_pio_count)
10923 			return 1;
10924 	}
10925 
10926 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
10927 	return 0;
10928 }
10929 
10930 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
10931 			  unsigned int port);
10932 
10933 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
10934 {
10935 	unsigned count = vcpu->arch.pio.count;
10936 	int size = vcpu->arch.pio.size;
10937 	int port = vcpu->arch.pio.port;
10938 
10939 	complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
10940 	advance_sev_es_emulated_pio(vcpu, count, size);
10941 	if (vcpu->arch.sev_pio_count)
10942 		return kvm_sev_es_ins(vcpu, size, port);
10943 	return 1;
10944 }
10945 
10946 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
10947 			  unsigned int port)
10948 {
10949 	for (;;) {
10950 		unsigned int count =
10951 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
10952 		if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
10953 			break;
10954 
10955 		/* Emulation done by the kernel.  */
10956 		advance_sev_es_emulated_pio(vcpu, count, size);
10957 		if (!vcpu->arch.sev_pio_count)
10958 			return 1;
10959 	}
10960 
10961 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
10962 	return 0;
10963 }
10964 
10965 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
10966 			 unsigned int port, void *data,  unsigned int count,
10967 			 int in)
10968 {
10969 	vcpu->arch.sev_pio_data = data;
10970 	vcpu->arch.sev_pio_count = count;
10971 	return in ? kvm_sev_es_ins(vcpu, size, port)
10972 		  : kvm_sev_es_outs(vcpu, size, port);
10973 }
10974 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_string_io);
10975 
10976 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
10977 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10978 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_mmio);
10979 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10980 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10981 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10982 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10983 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10984 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
10985 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10986 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10987 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10988 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10989 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10990 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10991 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10992 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10993 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10994 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10995 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10996 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
10997 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
10998 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
10999 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
11000 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
11001 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
11002 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
11003 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
11004 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
11005 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
11006 
11007 static int __init kvm_x86_init(void)
11008 {
11009 	kvm_init_xstate_sizes();
11010 
11011 	kvm_mmu_x86_module_init();
11012 	mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
11013 	return 0;
11014 }
11015 module_init(kvm_x86_init);
11016 
11017 static void __exit kvm_x86_exit(void)
11018 {
11019 	WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
11020 }
11021 module_exit(kvm_x86_exit);
11022