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