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