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