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