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