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