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