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