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