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