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