]> git.openfabrics.org - ~shefty/rdma-dev.git/blob - arch/x86/kvm/x86.c
54696b5f8443509eb9ed94ab77c9617b46f4407b
[~shefty/rdma-dev.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 #include "cpuid.h"
30
31 #include <linux/clocksource.h>
32 #include <linux/interrupt.h>
33 #include <linux/kvm.h>
34 #include <linux/fs.h>
35 #include <linux/vmalloc.h>
36 #include <linux/module.h>
37 #include <linux/mman.h>
38 #include <linux/highmem.h>
39 #include <linux/iommu.h>
40 #include <linux/intel-iommu.h>
41 #include <linux/cpufreq.h>
42 #include <linux/user-return-notifier.h>
43 #include <linux/srcu.h>
44 #include <linux/slab.h>
45 #include <linux/perf_event.h>
46 #include <linux/uaccess.h>
47 #include <linux/hash.h>
48 #include <linux/pci.h>
49 #include <trace/events/kvm.h>
50
51 #define CREATE_TRACE_POINTS
52 #include "trace.h"
53
54 #include <asm/debugreg.h>
55 #include <asm/msr.h>
56 #include <asm/desc.h>
57 #include <asm/mtrr.h>
58 #include <asm/mce.h>
59 #include <asm/i387.h>
60 #include <asm/fpu-internal.h> /* Ugh! */
61 #include <asm/xcr.h>
62 #include <asm/pvclock.h>
63 #include <asm/div64.h>
64
65 #define MAX_IO_MSRS 256
66 #define KVM_MAX_MCE_BANKS 32
67 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
68
69 #define emul_to_vcpu(ctxt) \
70         container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
71
72 /* EFER defaults:
73  * - enable syscall per default because its emulated by KVM
74  * - enable LME and LMA per default on 64 bit KVM
75  */
76 #ifdef CONFIG_X86_64
77 static
78 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
79 #else
80 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
81 #endif
82
83 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
84 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
85
86 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
87 static void process_nmi(struct kvm_vcpu *vcpu);
88
89 struct kvm_x86_ops *kvm_x86_ops;
90 EXPORT_SYMBOL_GPL(kvm_x86_ops);
91
92 static bool ignore_msrs = 0;
93 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
94
95 bool kvm_has_tsc_control;
96 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
97 u32  kvm_max_guest_tsc_khz;
98 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
99
100 #define KVM_NR_SHARED_MSRS 16
101
102 struct kvm_shared_msrs_global {
103         int nr;
104         u32 msrs[KVM_NR_SHARED_MSRS];
105 };
106
107 struct kvm_shared_msrs {
108         struct user_return_notifier urn;
109         bool registered;
110         struct kvm_shared_msr_values {
111                 u64 host;
112                 u64 curr;
113         } values[KVM_NR_SHARED_MSRS];
114 };
115
116 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
117 static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
118
119 struct kvm_stats_debugfs_item debugfs_entries[] = {
120         { "pf_fixed", VCPU_STAT(pf_fixed) },
121         { "pf_guest", VCPU_STAT(pf_guest) },
122         { "tlb_flush", VCPU_STAT(tlb_flush) },
123         { "invlpg", VCPU_STAT(invlpg) },
124         { "exits", VCPU_STAT(exits) },
125         { "io_exits", VCPU_STAT(io_exits) },
126         { "mmio_exits", VCPU_STAT(mmio_exits) },
127         { "signal_exits", VCPU_STAT(signal_exits) },
128         { "irq_window", VCPU_STAT(irq_window_exits) },
129         { "nmi_window", VCPU_STAT(nmi_window_exits) },
130         { "halt_exits", VCPU_STAT(halt_exits) },
131         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
132         { "hypercalls", VCPU_STAT(hypercalls) },
133         { "request_irq", VCPU_STAT(request_irq_exits) },
134         { "irq_exits", VCPU_STAT(irq_exits) },
135         { "host_state_reload", VCPU_STAT(host_state_reload) },
136         { "efer_reload", VCPU_STAT(efer_reload) },
137         { "fpu_reload", VCPU_STAT(fpu_reload) },
138         { "insn_emulation", VCPU_STAT(insn_emulation) },
139         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
140         { "irq_injections", VCPU_STAT(irq_injections) },
141         { "nmi_injections", VCPU_STAT(nmi_injections) },
142         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
143         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
144         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
145         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
146         { "mmu_flooded", VM_STAT(mmu_flooded) },
147         { "mmu_recycled", VM_STAT(mmu_recycled) },
148         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
149         { "mmu_unsync", VM_STAT(mmu_unsync) },
150         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
151         { "largepages", VM_STAT(lpages) },
152         { NULL }
153 };
154
155 u64 __read_mostly host_xcr0;
156
157 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
158
159 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
160 {
161         int i;
162         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
163                 vcpu->arch.apf.gfns[i] = ~0;
164 }
165
166 static void kvm_on_user_return(struct user_return_notifier *urn)
167 {
168         unsigned slot;
169         struct kvm_shared_msrs *locals
170                 = container_of(urn, struct kvm_shared_msrs, urn);
171         struct kvm_shared_msr_values *values;
172
173         for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
174                 values = &locals->values[slot];
175                 if (values->host != values->curr) {
176                         wrmsrl(shared_msrs_global.msrs[slot], values->host);
177                         values->curr = values->host;
178                 }
179         }
180         locals->registered = false;
181         user_return_notifier_unregister(urn);
182 }
183
184 static void shared_msr_update(unsigned slot, u32 msr)
185 {
186         struct kvm_shared_msrs *smsr;
187         u64 value;
188
189         smsr = &__get_cpu_var(shared_msrs);
190         /* only read, and nobody should modify it at this time,
191          * so don't need lock */
192         if (slot >= shared_msrs_global.nr) {
193                 printk(KERN_ERR "kvm: invalid MSR slot!");
194                 return;
195         }
196         rdmsrl_safe(msr, &value);
197         smsr->values[slot].host = value;
198         smsr->values[slot].curr = value;
199 }
200
201 void kvm_define_shared_msr(unsigned slot, u32 msr)
202 {
203         if (slot >= shared_msrs_global.nr)
204                 shared_msrs_global.nr = slot + 1;
205         shared_msrs_global.msrs[slot] = msr;
206         /* we need ensured the shared_msr_global have been updated */
207         smp_wmb();
208 }
209 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
210
211 static void kvm_shared_msr_cpu_online(void)
212 {
213         unsigned i;
214
215         for (i = 0; i < shared_msrs_global.nr; ++i)
216                 shared_msr_update(i, shared_msrs_global.msrs[i]);
217 }
218
219 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
220 {
221         struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
222
223         if (((value ^ smsr->values[slot].curr) & mask) == 0)
224                 return;
225         smsr->values[slot].curr = value;
226         wrmsrl(shared_msrs_global.msrs[slot], value);
227         if (!smsr->registered) {
228                 smsr->urn.on_user_return = kvm_on_user_return;
229                 user_return_notifier_register(&smsr->urn);
230                 smsr->registered = true;
231         }
232 }
233 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
234
235 static void drop_user_return_notifiers(void *ignore)
236 {
237         struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
238
239         if (smsr->registered)
240                 kvm_on_user_return(&smsr->urn);
241 }
242
243 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
244 {
245         if (irqchip_in_kernel(vcpu->kvm))
246                 return vcpu->arch.apic_base;
247         else
248                 return vcpu->arch.apic_base;
249 }
250 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
251
252 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
253 {
254         /* TODO: reserve bits check */
255         if (irqchip_in_kernel(vcpu->kvm))
256                 kvm_lapic_set_base(vcpu, data);
257         else
258                 vcpu->arch.apic_base = data;
259 }
260 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
261
262 #define EXCPT_BENIGN            0
263 #define EXCPT_CONTRIBUTORY      1
264 #define EXCPT_PF                2
265
266 static int exception_class(int vector)
267 {
268         switch (vector) {
269         case PF_VECTOR:
270                 return EXCPT_PF;
271         case DE_VECTOR:
272         case TS_VECTOR:
273         case NP_VECTOR:
274         case SS_VECTOR:
275         case GP_VECTOR:
276                 return EXCPT_CONTRIBUTORY;
277         default:
278                 break;
279         }
280         return EXCPT_BENIGN;
281 }
282
283 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
284                 unsigned nr, bool has_error, u32 error_code,
285                 bool reinject)
286 {
287         u32 prev_nr;
288         int class1, class2;
289
290         kvm_make_request(KVM_REQ_EVENT, vcpu);
291
292         if (!vcpu->arch.exception.pending) {
293         queue:
294                 vcpu->arch.exception.pending = true;
295                 vcpu->arch.exception.has_error_code = has_error;
296                 vcpu->arch.exception.nr = nr;
297                 vcpu->arch.exception.error_code = error_code;
298                 vcpu->arch.exception.reinject = reinject;
299                 return;
300         }
301
302         /* to check exception */
303         prev_nr = vcpu->arch.exception.nr;
304         if (prev_nr == DF_VECTOR) {
305                 /* triple fault -> shutdown */
306                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
307                 return;
308         }
309         class1 = exception_class(prev_nr);
310         class2 = exception_class(nr);
311         if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
312                 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
313                 /* generate double fault per SDM Table 5-5 */
314                 vcpu->arch.exception.pending = true;
315                 vcpu->arch.exception.has_error_code = true;
316                 vcpu->arch.exception.nr = DF_VECTOR;
317                 vcpu->arch.exception.error_code = 0;
318         } else
319                 /* replace previous exception with a new one in a hope
320                    that instruction re-execution will regenerate lost
321                    exception */
322                 goto queue;
323 }
324
325 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
326 {
327         kvm_multiple_exception(vcpu, nr, false, 0, false);
328 }
329 EXPORT_SYMBOL_GPL(kvm_queue_exception);
330
331 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
332 {
333         kvm_multiple_exception(vcpu, nr, false, 0, true);
334 }
335 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
336
337 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
338 {
339         if (err)
340                 kvm_inject_gp(vcpu, 0);
341         else
342                 kvm_x86_ops->skip_emulated_instruction(vcpu);
343 }
344 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
345
346 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
347 {
348         ++vcpu->stat.pf_guest;
349         vcpu->arch.cr2 = fault->address;
350         kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
351 }
352 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
353
354 void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
355 {
356         if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
357                 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
358         else
359                 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
360 }
361
362 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
363 {
364         atomic_inc(&vcpu->arch.nmi_queued);
365         kvm_make_request(KVM_REQ_NMI, vcpu);
366 }
367 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
368
369 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
370 {
371         kvm_multiple_exception(vcpu, nr, true, error_code, false);
372 }
373 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
374
375 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
376 {
377         kvm_multiple_exception(vcpu, nr, true, error_code, true);
378 }
379 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
380
381 /*
382  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
383  * a #GP and return false.
384  */
385 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
386 {
387         if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
388                 return true;
389         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
390         return false;
391 }
392 EXPORT_SYMBOL_GPL(kvm_require_cpl);
393
394 /*
395  * This function will be used to read from the physical memory of the currently
396  * running guest. The difference to kvm_read_guest_page is that this function
397  * can read from guest physical or from the guest's guest physical memory.
398  */
399 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
400                             gfn_t ngfn, void *data, int offset, int len,
401                             u32 access)
402 {
403         gfn_t real_gfn;
404         gpa_t ngpa;
405
406         ngpa     = gfn_to_gpa(ngfn);
407         real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
408         if (real_gfn == UNMAPPED_GVA)
409                 return -EFAULT;
410
411         real_gfn = gpa_to_gfn(real_gfn);
412
413         return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
414 }
415 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
416
417 int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
418                                void *data, int offset, int len, u32 access)
419 {
420         return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
421                                        data, offset, len, access);
422 }
423
424 /*
425  * Load the pae pdptrs.  Return true is they are all valid.
426  */
427 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
428 {
429         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
430         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
431         int i;
432         int ret;
433         u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
434
435         ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
436                                       offset * sizeof(u64), sizeof(pdpte),
437                                       PFERR_USER_MASK|PFERR_WRITE_MASK);
438         if (ret < 0) {
439                 ret = 0;
440                 goto out;
441         }
442         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
443                 if (is_present_gpte(pdpte[i]) &&
444                     (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
445                         ret = 0;
446                         goto out;
447                 }
448         }
449         ret = 1;
450
451         memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
452         __set_bit(VCPU_EXREG_PDPTR,
453                   (unsigned long *)&vcpu->arch.regs_avail);
454         __set_bit(VCPU_EXREG_PDPTR,
455                   (unsigned long *)&vcpu->arch.regs_dirty);
456 out:
457
458         return ret;
459 }
460 EXPORT_SYMBOL_GPL(load_pdptrs);
461
462 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
463 {
464         u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
465         bool changed = true;
466         int offset;
467         gfn_t gfn;
468         int r;
469
470         if (is_long_mode(vcpu) || !is_pae(vcpu))
471                 return false;
472
473         if (!test_bit(VCPU_EXREG_PDPTR,
474                       (unsigned long *)&vcpu->arch.regs_avail))
475                 return true;
476
477         gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
478         offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
479         r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
480                                        PFERR_USER_MASK | PFERR_WRITE_MASK);
481         if (r < 0)
482                 goto out;
483         changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
484 out:
485
486         return changed;
487 }
488
489 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
490 {
491         unsigned long old_cr0 = kvm_read_cr0(vcpu);
492         unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
493                                     X86_CR0_CD | X86_CR0_NW;
494
495         cr0 |= X86_CR0_ET;
496
497 #ifdef CONFIG_X86_64
498         if (cr0 & 0xffffffff00000000UL)
499                 return 1;
500 #endif
501
502         cr0 &= ~CR0_RESERVED_BITS;
503
504         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
505                 return 1;
506
507         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
508                 return 1;
509
510         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
511 #ifdef CONFIG_X86_64
512                 if ((vcpu->arch.efer & EFER_LME)) {
513                         int cs_db, cs_l;
514
515                         if (!is_pae(vcpu))
516                                 return 1;
517                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
518                         if (cs_l)
519                                 return 1;
520                 } else
521 #endif
522                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
523                                                  kvm_read_cr3(vcpu)))
524                         return 1;
525         }
526
527         kvm_x86_ops->set_cr0(vcpu, cr0);
528
529         if ((cr0 ^ old_cr0) & X86_CR0_PG) {
530                 kvm_clear_async_pf_completion_queue(vcpu);
531                 kvm_async_pf_hash_reset(vcpu);
532         }
533
534         if ((cr0 ^ old_cr0) & update_bits)
535                 kvm_mmu_reset_context(vcpu);
536         return 0;
537 }
538 EXPORT_SYMBOL_GPL(kvm_set_cr0);
539
540 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
541 {
542         (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
543 }
544 EXPORT_SYMBOL_GPL(kvm_lmsw);
545
546 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
547 {
548         u64 xcr0;
549
550         /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
551         if (index != XCR_XFEATURE_ENABLED_MASK)
552                 return 1;
553         xcr0 = xcr;
554         if (kvm_x86_ops->get_cpl(vcpu) != 0)
555                 return 1;
556         if (!(xcr0 & XSTATE_FP))
557                 return 1;
558         if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
559                 return 1;
560         if (xcr0 & ~host_xcr0)
561                 return 1;
562         vcpu->arch.xcr0 = xcr0;
563         vcpu->guest_xcr0_loaded = 0;
564         return 0;
565 }
566
567 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
568 {
569         if (__kvm_set_xcr(vcpu, index, xcr)) {
570                 kvm_inject_gp(vcpu, 0);
571                 return 1;
572         }
573         return 0;
574 }
575 EXPORT_SYMBOL_GPL(kvm_set_xcr);
576
577 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
578 {
579         unsigned long old_cr4 = kvm_read_cr4(vcpu);
580         unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
581                                    X86_CR4_PAE | X86_CR4_SMEP;
582         if (cr4 & CR4_RESERVED_BITS)
583                 return 1;
584
585         if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
586                 return 1;
587
588         if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
589                 return 1;
590
591         if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
592                 return 1;
593
594         if (is_long_mode(vcpu)) {
595                 if (!(cr4 & X86_CR4_PAE))
596                         return 1;
597         } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
598                    && ((cr4 ^ old_cr4) & pdptr_bits)
599                    && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
600                                    kvm_read_cr3(vcpu)))
601                 return 1;
602
603         if (kvm_x86_ops->set_cr4(vcpu, cr4))
604                 return 1;
605
606         if ((cr4 ^ old_cr4) & pdptr_bits)
607                 kvm_mmu_reset_context(vcpu);
608
609         if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
610                 kvm_update_cpuid(vcpu);
611
612         return 0;
613 }
614 EXPORT_SYMBOL_GPL(kvm_set_cr4);
615
616 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
617 {
618         if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
619                 kvm_mmu_sync_roots(vcpu);
620                 kvm_mmu_flush_tlb(vcpu);
621                 return 0;
622         }
623
624         if (is_long_mode(vcpu)) {
625                 if (cr3 & CR3_L_MODE_RESERVED_BITS)
626                         return 1;
627         } else {
628                 if (is_pae(vcpu)) {
629                         if (cr3 & CR3_PAE_RESERVED_BITS)
630                                 return 1;
631                         if (is_paging(vcpu) &&
632                             !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
633                                 return 1;
634                 }
635                 /*
636                  * We don't check reserved bits in nonpae mode, because
637                  * this isn't enforced, and VMware depends on this.
638                  */
639         }
640
641         /*
642          * Does the new cr3 value map to physical memory? (Note, we
643          * catch an invalid cr3 even in real-mode, because it would
644          * cause trouble later on when we turn on paging anyway.)
645          *
646          * A real CPU would silently accept an invalid cr3 and would
647          * attempt to use it - with largely undefined (and often hard
648          * to debug) behavior on the guest side.
649          */
650         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
651                 return 1;
652         vcpu->arch.cr3 = cr3;
653         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
654         vcpu->arch.mmu.new_cr3(vcpu);
655         return 0;
656 }
657 EXPORT_SYMBOL_GPL(kvm_set_cr3);
658
659 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
660 {
661         if (cr8 & CR8_RESERVED_BITS)
662                 return 1;
663         if (irqchip_in_kernel(vcpu->kvm))
664                 kvm_lapic_set_tpr(vcpu, cr8);
665         else
666                 vcpu->arch.cr8 = cr8;
667         return 0;
668 }
669 EXPORT_SYMBOL_GPL(kvm_set_cr8);
670
671 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
672 {
673         if (irqchip_in_kernel(vcpu->kvm))
674                 return kvm_lapic_get_cr8(vcpu);
675         else
676                 return vcpu->arch.cr8;
677 }
678 EXPORT_SYMBOL_GPL(kvm_get_cr8);
679
680 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
681 {
682         switch (dr) {
683         case 0 ... 3:
684                 vcpu->arch.db[dr] = val;
685                 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
686                         vcpu->arch.eff_db[dr] = val;
687                 break;
688         case 4:
689                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
690                         return 1; /* #UD */
691                 /* fall through */
692         case 6:
693                 if (val & 0xffffffff00000000ULL)
694                         return -1; /* #GP */
695                 vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
696                 break;
697         case 5:
698                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
699                         return 1; /* #UD */
700                 /* fall through */
701         default: /* 7 */
702                 if (val & 0xffffffff00000000ULL)
703                         return -1; /* #GP */
704                 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
705                 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
706                         kvm_x86_ops->set_dr7(vcpu, vcpu->arch.dr7);
707                         vcpu->arch.switch_db_regs = (val & DR7_BP_EN_MASK);
708                 }
709                 break;
710         }
711
712         return 0;
713 }
714
715 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
716 {
717         int res;
718
719         res = __kvm_set_dr(vcpu, dr, val);
720         if (res > 0)
721                 kvm_queue_exception(vcpu, UD_VECTOR);
722         else if (res < 0)
723                 kvm_inject_gp(vcpu, 0);
724
725         return res;
726 }
727 EXPORT_SYMBOL_GPL(kvm_set_dr);
728
729 static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
730 {
731         switch (dr) {
732         case 0 ... 3:
733                 *val = vcpu->arch.db[dr];
734                 break;
735         case 4:
736                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
737                         return 1;
738                 /* fall through */
739         case 6:
740                 *val = vcpu->arch.dr6;
741                 break;
742         case 5:
743                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
744                         return 1;
745                 /* fall through */
746         default: /* 7 */
747                 *val = vcpu->arch.dr7;
748                 break;
749         }
750
751         return 0;
752 }
753
754 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
755 {
756         if (_kvm_get_dr(vcpu, dr, val)) {
757                 kvm_queue_exception(vcpu, UD_VECTOR);
758                 return 1;
759         }
760         return 0;
761 }
762 EXPORT_SYMBOL_GPL(kvm_get_dr);
763
764 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
765 {
766         u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
767         u64 data;
768         int err;
769
770         err = kvm_pmu_read_pmc(vcpu, ecx, &data);
771         if (err)
772                 return err;
773         kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
774         kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
775         return err;
776 }
777 EXPORT_SYMBOL_GPL(kvm_rdpmc);
778
779 /*
780  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
781  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
782  *
783  * This list is modified at module load time to reflect the
784  * capabilities of the host cpu. This capabilities test skips MSRs that are
785  * kvm-specific. Those are put in the beginning of the list.
786  */
787
788 #define KVM_SAVE_MSRS_BEGIN     9
789 static u32 msrs_to_save[] = {
790         MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
791         MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
792         HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
793         HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
794         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
795         MSR_STAR,
796 #ifdef CONFIG_X86_64
797         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
798 #endif
799         MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
800 };
801
802 static unsigned num_msrs_to_save;
803
804 static u32 emulated_msrs[] = {
805         MSR_IA32_TSCDEADLINE,
806         MSR_IA32_MISC_ENABLE,
807         MSR_IA32_MCG_STATUS,
808         MSR_IA32_MCG_CTL,
809 };
810
811 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
812 {
813         u64 old_efer = vcpu->arch.efer;
814
815         if (efer & efer_reserved_bits)
816                 return 1;
817
818         if (is_paging(vcpu)
819             && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
820                 return 1;
821
822         if (efer & EFER_FFXSR) {
823                 struct kvm_cpuid_entry2 *feat;
824
825                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
826                 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
827                         return 1;
828         }
829
830         if (efer & EFER_SVME) {
831                 struct kvm_cpuid_entry2 *feat;
832
833                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
834                 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
835                         return 1;
836         }
837
838         efer &= ~EFER_LMA;
839         efer |= vcpu->arch.efer & EFER_LMA;
840
841         kvm_x86_ops->set_efer(vcpu, efer);
842
843         vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
844
845         /* Update reserved bits */
846         if ((efer ^ old_efer) & EFER_NX)
847                 kvm_mmu_reset_context(vcpu);
848
849         return 0;
850 }
851
852 void kvm_enable_efer_bits(u64 mask)
853 {
854        efer_reserved_bits &= ~mask;
855 }
856 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
857
858
859 /*
860  * Writes msr value into into the appropriate "register".
861  * Returns 0 on success, non-0 otherwise.
862  * Assumes vcpu_load() was already called.
863  */
864 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
865 {
866         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
867 }
868
869 /*
870  * Adapt set_msr() to msr_io()'s calling convention
871  */
872 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
873 {
874         return kvm_set_msr(vcpu, index, *data);
875 }
876
877 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
878 {
879         int version;
880         int r;
881         struct pvclock_wall_clock wc;
882         struct timespec boot;
883
884         if (!wall_clock)
885                 return;
886
887         r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
888         if (r)
889                 return;
890
891         if (version & 1)
892                 ++version;  /* first time write, random junk */
893
894         ++version;
895
896         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
897
898         /*
899          * The guest calculates current wall clock time by adding
900          * system time (updated by kvm_guest_time_update below) to the
901          * wall clock specified here.  guest system time equals host
902          * system time for us, thus we must fill in host boot time here.
903          */
904         getboottime(&boot);
905
906         wc.sec = boot.tv_sec;
907         wc.nsec = boot.tv_nsec;
908         wc.version = version;
909
910         kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
911
912         version++;
913         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
914 }
915
916 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
917 {
918         uint32_t quotient, remainder;
919
920         /* Don't try to replace with do_div(), this one calculates
921          * "(dividend << 32) / divisor" */
922         __asm__ ( "divl %4"
923                   : "=a" (quotient), "=d" (remainder)
924                   : "0" (0), "1" (dividend), "r" (divisor) );
925         return quotient;
926 }
927
928 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
929                                s8 *pshift, u32 *pmultiplier)
930 {
931         uint64_t scaled64;
932         int32_t  shift = 0;
933         uint64_t tps64;
934         uint32_t tps32;
935
936         tps64 = base_khz * 1000LL;
937         scaled64 = scaled_khz * 1000LL;
938         while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
939                 tps64 >>= 1;
940                 shift--;
941         }
942
943         tps32 = (uint32_t)tps64;
944         while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
945                 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
946                         scaled64 >>= 1;
947                 else
948                         tps32 <<= 1;
949                 shift++;
950         }
951
952         *pshift = shift;
953         *pmultiplier = div_frac(scaled64, tps32);
954
955         pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
956                  __func__, base_khz, scaled_khz, shift, *pmultiplier);
957 }
958
959 static inline u64 get_kernel_ns(void)
960 {
961         struct timespec ts;
962
963         WARN_ON(preemptible());
964         ktime_get_ts(&ts);
965         monotonic_to_bootbased(&ts);
966         return timespec_to_ns(&ts);
967 }
968
969 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
970 unsigned long max_tsc_khz;
971
972 static inline int kvm_tsc_changes_freq(void)
973 {
974         int cpu = get_cpu();
975         int ret = !boot_cpu_has(X86_FEATURE_CONSTANT_TSC) &&
976                   cpufreq_quick_get(cpu) != 0;
977         put_cpu();
978         return ret;
979 }
980
981 u64 vcpu_tsc_khz(struct kvm_vcpu *vcpu)
982 {
983         if (vcpu->arch.virtual_tsc_khz)
984                 return vcpu->arch.virtual_tsc_khz;
985         else
986                 return __this_cpu_read(cpu_tsc_khz);
987 }
988
989 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
990 {
991         u64 ret;
992
993         WARN_ON(preemptible());
994         if (kvm_tsc_changes_freq())
995                 printk_once(KERN_WARNING
996                  "kvm: unreliable cycle conversion on adjustable rate TSC\n");
997         ret = nsec * vcpu_tsc_khz(vcpu);
998         do_div(ret, USEC_PER_SEC);
999         return ret;
1000 }
1001
1002 static void kvm_init_tsc_catchup(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1003 {
1004         /* Compute a scale to convert nanoseconds in TSC cycles */
1005         kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1006                            &vcpu->arch.tsc_catchup_shift,
1007                            &vcpu->arch.tsc_catchup_mult);
1008 }
1009
1010 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1011 {
1012         u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.last_tsc_nsec,
1013                                       vcpu->arch.tsc_catchup_mult,
1014                                       vcpu->arch.tsc_catchup_shift);
1015         tsc += vcpu->arch.last_tsc_write;
1016         return tsc;
1017 }
1018
1019 void kvm_write_tsc(struct kvm_vcpu *vcpu, u64 data)
1020 {
1021         struct kvm *kvm = vcpu->kvm;
1022         u64 offset, ns, elapsed;
1023         unsigned long flags;
1024         s64 sdiff;
1025
1026         raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1027         offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1028         ns = get_kernel_ns();
1029         elapsed = ns - kvm->arch.last_tsc_nsec;
1030         sdiff = data - kvm->arch.last_tsc_write;
1031         if (sdiff < 0)
1032                 sdiff = -sdiff;
1033
1034         /*
1035          * Special case: close write to TSC within 5 seconds of
1036          * another CPU is interpreted as an attempt to synchronize
1037          * The 5 seconds is to accommodate host load / swapping as
1038          * well as any reset of TSC during the boot process.
1039          *
1040          * In that case, for a reliable TSC, we can match TSC offsets,
1041          * or make a best guest using elapsed value.
1042          */
1043         if (sdiff < nsec_to_cycles(vcpu, 5ULL * NSEC_PER_SEC) &&
1044             elapsed < 5ULL * NSEC_PER_SEC) {
1045                 if (!check_tsc_unstable()) {
1046                         offset = kvm->arch.last_tsc_offset;
1047                         pr_debug("kvm: matched tsc offset for %llu\n", data);
1048                 } else {
1049                         u64 delta = nsec_to_cycles(vcpu, elapsed);
1050                         offset += delta;
1051                         pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1052                 }
1053                 ns = kvm->arch.last_tsc_nsec;
1054         }
1055         kvm->arch.last_tsc_nsec = ns;
1056         kvm->arch.last_tsc_write = data;
1057         kvm->arch.last_tsc_offset = offset;
1058         kvm_x86_ops->write_tsc_offset(vcpu, offset);
1059         raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1060
1061         /* Reset of TSC must disable overshoot protection below */
1062         vcpu->arch.hv_clock.tsc_timestamp = 0;
1063         vcpu->arch.last_tsc_write = data;
1064         vcpu->arch.last_tsc_nsec = ns;
1065 }
1066 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1067
1068 static int kvm_guest_time_update(struct kvm_vcpu *v)
1069 {
1070         unsigned long flags;
1071         struct kvm_vcpu_arch *vcpu = &v->arch;
1072         void *shared_kaddr;
1073         unsigned long this_tsc_khz;
1074         s64 kernel_ns, max_kernel_ns;
1075         u64 tsc_timestamp;
1076
1077         /* Keep irq disabled to prevent changes to the clock */
1078         local_irq_save(flags);
1079         tsc_timestamp = kvm_x86_ops->read_l1_tsc(v);
1080         kernel_ns = get_kernel_ns();
1081         this_tsc_khz = vcpu_tsc_khz(v);
1082         if (unlikely(this_tsc_khz == 0)) {
1083                 local_irq_restore(flags);
1084                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1085                 return 1;
1086         }
1087
1088         /*
1089          * We may have to catch up the TSC to match elapsed wall clock
1090          * time for two reasons, even if kvmclock is used.
1091          *   1) CPU could have been running below the maximum TSC rate
1092          *   2) Broken TSC compensation resets the base at each VCPU
1093          *      entry to avoid unknown leaps of TSC even when running
1094          *      again on the same CPU.  This may cause apparent elapsed
1095          *      time to disappear, and the guest to stand still or run
1096          *      very slowly.
1097          */
1098         if (vcpu->tsc_catchup) {
1099                 u64 tsc = compute_guest_tsc(v, kernel_ns);
1100                 if (tsc > tsc_timestamp) {
1101                         kvm_x86_ops->adjust_tsc_offset(v, tsc - tsc_timestamp);
1102                         tsc_timestamp = tsc;
1103                 }
1104         }
1105
1106         local_irq_restore(flags);
1107
1108         if (!vcpu->time_page)
1109                 return 0;
1110
1111         /*
1112          * Time as measured by the TSC may go backwards when resetting the base
1113          * tsc_timestamp.  The reason for this is that the TSC resolution is
1114          * higher than the resolution of the other clock scales.  Thus, many
1115          * possible measurments of the TSC correspond to one measurement of any
1116          * other clock, and so a spread of values is possible.  This is not a
1117          * problem for the computation of the nanosecond clock; with TSC rates
1118          * around 1GHZ, there can only be a few cycles which correspond to one
1119          * nanosecond value, and any path through this code will inevitably
1120          * take longer than that.  However, with the kernel_ns value itself,
1121          * the precision may be much lower, down to HZ granularity.  If the
1122          * first sampling of TSC against kernel_ns ends in the low part of the
1123          * range, and the second in the high end of the range, we can get:
1124          *
1125          * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
1126          *
1127          * As the sampling errors potentially range in the thousands of cycles,
1128          * it is possible such a time value has already been observed by the
1129          * guest.  To protect against this, we must compute the system time as
1130          * observed by the guest and ensure the new system time is greater.
1131          */
1132         max_kernel_ns = 0;
1133         if (vcpu->hv_clock.tsc_timestamp && vcpu->last_guest_tsc) {
1134                 max_kernel_ns = vcpu->last_guest_tsc -
1135                                 vcpu->hv_clock.tsc_timestamp;
1136                 max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
1137                                     vcpu->hv_clock.tsc_to_system_mul,
1138                                     vcpu->hv_clock.tsc_shift);
1139                 max_kernel_ns += vcpu->last_kernel_ns;
1140         }
1141
1142         if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1143                 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1144                                    &vcpu->hv_clock.tsc_shift,
1145                                    &vcpu->hv_clock.tsc_to_system_mul);
1146                 vcpu->hw_tsc_khz = this_tsc_khz;
1147         }
1148
1149         if (max_kernel_ns > kernel_ns)
1150                 kernel_ns = max_kernel_ns;
1151
1152         /* With all the info we got, fill in the values */
1153         vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1154         vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1155         vcpu->last_kernel_ns = kernel_ns;
1156         vcpu->last_guest_tsc = tsc_timestamp;
1157         vcpu->hv_clock.flags = 0;
1158
1159         /*
1160          * The interface expects us to write an even number signaling that the
1161          * update is finished. Since the guest won't see the intermediate
1162          * state, we just increase by 2 at the end.
1163          */
1164         vcpu->hv_clock.version += 2;
1165
1166         shared_kaddr = kmap_atomic(vcpu->time_page);
1167
1168         memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
1169                sizeof(vcpu->hv_clock));
1170
1171         kunmap_atomic(shared_kaddr);
1172
1173         mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
1174         return 0;
1175 }
1176
1177 static bool msr_mtrr_valid(unsigned msr)
1178 {
1179         switch (msr) {
1180         case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1181         case MSR_MTRRfix64K_00000:
1182         case MSR_MTRRfix16K_80000:
1183         case MSR_MTRRfix16K_A0000:
1184         case MSR_MTRRfix4K_C0000:
1185         case MSR_MTRRfix4K_C8000:
1186         case MSR_MTRRfix4K_D0000:
1187         case MSR_MTRRfix4K_D8000:
1188         case MSR_MTRRfix4K_E0000:
1189         case MSR_MTRRfix4K_E8000:
1190         case MSR_MTRRfix4K_F0000:
1191         case MSR_MTRRfix4K_F8000:
1192         case MSR_MTRRdefType:
1193         case MSR_IA32_CR_PAT:
1194                 return true;
1195         case 0x2f8:
1196                 return true;
1197         }
1198         return false;
1199 }
1200
1201 static bool valid_pat_type(unsigned t)
1202 {
1203         return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1204 }
1205
1206 static bool valid_mtrr_type(unsigned t)
1207 {
1208         return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1209 }
1210
1211 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1212 {
1213         int i;
1214
1215         if (!msr_mtrr_valid(msr))
1216                 return false;
1217
1218         if (msr == MSR_IA32_CR_PAT) {
1219                 for (i = 0; i < 8; i++)
1220                         if (!valid_pat_type((data >> (i * 8)) & 0xff))
1221                                 return false;
1222                 return true;
1223         } else if (msr == MSR_MTRRdefType) {
1224                 if (data & ~0xcff)
1225                         return false;
1226                 return valid_mtrr_type(data & 0xff);
1227         } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1228                 for (i = 0; i < 8 ; i++)
1229                         if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1230                                 return false;
1231                 return true;
1232         }
1233
1234         /* variable MTRRs */
1235         return valid_mtrr_type(data & 0xff);
1236 }
1237
1238 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1239 {
1240         u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1241
1242         if (!mtrr_valid(vcpu, msr, data))
1243                 return 1;
1244
1245         if (msr == MSR_MTRRdefType) {
1246                 vcpu->arch.mtrr_state.def_type = data;
1247                 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1248         } else if (msr == MSR_MTRRfix64K_00000)
1249                 p[0] = data;
1250         else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1251                 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1252         else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1253                 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1254         else if (msr == MSR_IA32_CR_PAT)
1255                 vcpu->arch.pat = data;
1256         else {  /* Variable MTRRs */
1257                 int idx, is_mtrr_mask;
1258                 u64 *pt;
1259
1260                 idx = (msr - 0x200) / 2;
1261                 is_mtrr_mask = msr - 0x200 - 2 * idx;
1262                 if (!is_mtrr_mask)
1263                         pt =
1264                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1265                 else
1266                         pt =
1267                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1268                 *pt = data;
1269         }
1270
1271         kvm_mmu_reset_context(vcpu);
1272         return 0;
1273 }
1274
1275 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1276 {
1277         u64 mcg_cap = vcpu->arch.mcg_cap;
1278         unsigned bank_num = mcg_cap & 0xff;
1279
1280         switch (msr) {
1281         case MSR_IA32_MCG_STATUS:
1282                 vcpu->arch.mcg_status = data;
1283                 break;
1284         case MSR_IA32_MCG_CTL:
1285                 if (!(mcg_cap & MCG_CTL_P))
1286                         return 1;
1287                 if (data != 0 && data != ~(u64)0)
1288                         return -1;
1289                 vcpu->arch.mcg_ctl = data;
1290                 break;
1291         default:
1292                 if (msr >= MSR_IA32_MC0_CTL &&
1293                     msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1294                         u32 offset = msr - MSR_IA32_MC0_CTL;
1295                         /* only 0 or all 1s can be written to IA32_MCi_CTL
1296                          * some Linux kernels though clear bit 10 in bank 4 to
1297                          * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1298                          * this to avoid an uncatched #GP in the guest
1299                          */
1300                         if ((offset & 0x3) == 0 &&
1301                             data != 0 && (data | (1 << 10)) != ~(u64)0)
1302                                 return -1;
1303                         vcpu->arch.mce_banks[offset] = data;
1304                         break;
1305                 }
1306                 return 1;
1307         }
1308         return 0;
1309 }
1310
1311 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1312 {
1313         struct kvm *kvm = vcpu->kvm;
1314         int lm = is_long_mode(vcpu);
1315         u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1316                 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1317         u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1318                 : kvm->arch.xen_hvm_config.blob_size_32;
1319         u32 page_num = data & ~PAGE_MASK;
1320         u64 page_addr = data & PAGE_MASK;
1321         u8 *page;
1322         int r;
1323
1324         r = -E2BIG;
1325         if (page_num >= blob_size)
1326                 goto out;
1327         r = -ENOMEM;
1328         page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1329         if (IS_ERR(page)) {
1330                 r = PTR_ERR(page);
1331                 goto out;
1332         }
1333         if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1334                 goto out_free;
1335         r = 0;
1336 out_free:
1337         kfree(page);
1338 out:
1339         return r;
1340 }
1341
1342 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1343 {
1344         return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1345 }
1346
1347 static bool kvm_hv_msr_partition_wide(u32 msr)
1348 {
1349         bool r = false;
1350         switch (msr) {
1351         case HV_X64_MSR_GUEST_OS_ID:
1352         case HV_X64_MSR_HYPERCALL:
1353                 r = true;
1354                 break;
1355         }
1356
1357         return r;
1358 }
1359
1360 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1361 {
1362         struct kvm *kvm = vcpu->kvm;
1363
1364         switch (msr) {
1365         case HV_X64_MSR_GUEST_OS_ID:
1366                 kvm->arch.hv_guest_os_id = data;
1367                 /* setting guest os id to zero disables hypercall page */
1368                 if (!kvm->arch.hv_guest_os_id)
1369                         kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1370                 break;
1371         case HV_X64_MSR_HYPERCALL: {
1372                 u64 gfn;
1373                 unsigned long addr;
1374                 u8 instructions[4];
1375
1376                 /* if guest os id is not set hypercall should remain disabled */
1377                 if (!kvm->arch.hv_guest_os_id)
1378                         break;
1379                 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1380                         kvm->arch.hv_hypercall = data;
1381                         break;
1382                 }
1383                 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1384                 addr = gfn_to_hva(kvm, gfn);
1385                 if (kvm_is_error_hva(addr))
1386                         return 1;
1387                 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1388                 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1389                 if (__copy_to_user((void __user *)addr, instructions, 4))
1390                         return 1;
1391                 kvm->arch.hv_hypercall = data;
1392                 break;
1393         }
1394         default:
1395                 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1396                           "data 0x%llx\n", msr, data);
1397                 return 1;
1398         }
1399         return 0;
1400 }
1401
1402 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1403 {
1404         switch (msr) {
1405         case HV_X64_MSR_APIC_ASSIST_PAGE: {
1406                 unsigned long addr;
1407
1408                 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1409                         vcpu->arch.hv_vapic = data;
1410                         break;
1411                 }
1412                 addr = gfn_to_hva(vcpu->kvm, data >>
1413                                   HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1414                 if (kvm_is_error_hva(addr))
1415                         return 1;
1416                 if (__clear_user((void __user *)addr, PAGE_SIZE))
1417                         return 1;
1418                 vcpu->arch.hv_vapic = data;
1419                 break;
1420         }
1421         case HV_X64_MSR_EOI:
1422                 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1423         case HV_X64_MSR_ICR:
1424                 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1425         case HV_X64_MSR_TPR:
1426                 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1427         default:
1428                 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1429                           "data 0x%llx\n", msr, data);
1430                 return 1;
1431         }
1432
1433         return 0;
1434 }
1435
1436 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1437 {
1438         gpa_t gpa = data & ~0x3f;
1439
1440         /* Bits 2:5 are resrved, Should be zero */
1441         if (data & 0x3c)
1442                 return 1;
1443
1444         vcpu->arch.apf.msr_val = data;
1445
1446         if (!(data & KVM_ASYNC_PF_ENABLED)) {
1447                 kvm_clear_async_pf_completion_queue(vcpu);
1448                 kvm_async_pf_hash_reset(vcpu);
1449                 return 0;
1450         }
1451
1452         if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
1453                 return 1;
1454
1455         vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1456         kvm_async_pf_wakeup_all(vcpu);
1457         return 0;
1458 }
1459
1460 static void kvmclock_reset(struct kvm_vcpu *vcpu)
1461 {
1462         if (vcpu->arch.time_page) {
1463                 kvm_release_page_dirty(vcpu->arch.time_page);
1464                 vcpu->arch.time_page = NULL;
1465         }
1466 }
1467
1468 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
1469 {
1470         u64 delta;
1471
1472         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1473                 return;
1474
1475         delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
1476         vcpu->arch.st.last_steal = current->sched_info.run_delay;
1477         vcpu->arch.st.accum_steal = delta;
1478 }
1479
1480 static void record_steal_time(struct kvm_vcpu *vcpu)
1481 {
1482         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1483                 return;
1484
1485         if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1486                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
1487                 return;
1488
1489         vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
1490         vcpu->arch.st.steal.version += 2;
1491         vcpu->arch.st.accum_steal = 0;
1492
1493         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1494                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
1495 }
1496
1497 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1498 {
1499         bool pr = false;
1500
1501         switch (msr) {
1502         case MSR_EFER:
1503                 return set_efer(vcpu, data);
1504         case MSR_K7_HWCR:
1505                 data &= ~(u64)0x40;     /* ignore flush filter disable */
1506                 data &= ~(u64)0x100;    /* ignore ignne emulation enable */
1507                 if (data != 0) {
1508                         pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1509                                 data);
1510                         return 1;
1511                 }
1512                 break;
1513         case MSR_FAM10H_MMIO_CONF_BASE:
1514                 if (data != 0) {
1515                         pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1516                                 "0x%llx\n", data);
1517                         return 1;
1518                 }
1519                 break;
1520         case MSR_AMD64_NB_CFG:
1521                 break;
1522         case MSR_IA32_DEBUGCTLMSR:
1523                 if (!data) {
1524                         /* We support the non-activated case already */
1525                         break;
1526                 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1527                         /* Values other than LBR and BTF are vendor-specific,
1528                            thus reserved and should throw a #GP */
1529                         return 1;
1530                 }
1531                 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1532                         __func__, data);
1533                 break;
1534         case MSR_IA32_UCODE_REV:
1535         case MSR_IA32_UCODE_WRITE:
1536         case MSR_VM_HSAVE_PA:
1537         case MSR_AMD64_PATCH_LOADER:
1538                 break;
1539         case 0x200 ... 0x2ff:
1540                 return set_msr_mtrr(vcpu, msr, data);
1541         case MSR_IA32_APICBASE:
1542                 kvm_set_apic_base(vcpu, data);
1543                 break;
1544         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1545                 return kvm_x2apic_msr_write(vcpu, msr, data);
1546         case MSR_IA32_TSCDEADLINE:
1547                 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1548                 break;
1549         case MSR_IA32_MISC_ENABLE:
1550                 vcpu->arch.ia32_misc_enable_msr = data;
1551                 break;
1552         case MSR_KVM_WALL_CLOCK_NEW:
1553         case MSR_KVM_WALL_CLOCK:
1554                 vcpu->kvm->arch.wall_clock = data;
1555                 kvm_write_wall_clock(vcpu->kvm, data);
1556                 break;
1557         case MSR_KVM_SYSTEM_TIME_NEW:
1558         case MSR_KVM_SYSTEM_TIME: {
1559                 kvmclock_reset(vcpu);
1560
1561                 vcpu->arch.time = data;
1562                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1563
1564                 /* we verify if the enable bit is set... */
1565                 if (!(data & 1))
1566                         break;
1567
1568                 /* ...but clean it before doing the actual write */
1569                 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
1570
1571                 vcpu->arch.time_page =
1572                                 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
1573
1574                 if (is_error_page(vcpu->arch.time_page)) {
1575                         kvm_release_page_clean(vcpu->arch.time_page);
1576                         vcpu->arch.time_page = NULL;
1577                 }
1578                 break;
1579         }
1580         case MSR_KVM_ASYNC_PF_EN:
1581                 if (kvm_pv_enable_async_pf(vcpu, data))
1582                         return 1;
1583                 break;
1584         case MSR_KVM_STEAL_TIME:
1585
1586                 if (unlikely(!sched_info_on()))
1587                         return 1;
1588
1589                 if (data & KVM_STEAL_RESERVED_MASK)
1590                         return 1;
1591
1592                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
1593                                                         data & KVM_STEAL_VALID_BITS))
1594                         return 1;
1595
1596                 vcpu->arch.st.msr_val = data;
1597
1598                 if (!(data & KVM_MSR_ENABLED))
1599                         break;
1600
1601                 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1602
1603                 preempt_disable();
1604                 accumulate_steal_time(vcpu);
1605                 preempt_enable();
1606
1607                 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
1608
1609                 break;
1610
1611         case MSR_IA32_MCG_CTL:
1612         case MSR_IA32_MCG_STATUS:
1613         case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1614                 return set_msr_mce(vcpu, msr, data);
1615
1616         /* Performance counters are not protected by a CPUID bit,
1617          * so we should check all of them in the generic path for the sake of
1618          * cross vendor migration.
1619          * Writing a zero into the event select MSRs disables them,
1620          * which we perfectly emulate ;-). Any other value should be at least
1621          * reported, some guests depend on them.
1622          */
1623         case MSR_K7_EVNTSEL0:
1624         case MSR_K7_EVNTSEL1:
1625         case MSR_K7_EVNTSEL2:
1626         case MSR_K7_EVNTSEL3:
1627                 if (data != 0)
1628                         pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1629                                 "0x%x data 0x%llx\n", msr, data);
1630                 break;
1631         /* at least RHEL 4 unconditionally writes to the perfctr registers,
1632          * so we ignore writes to make it happy.
1633          */
1634         case MSR_K7_PERFCTR0:
1635         case MSR_K7_PERFCTR1:
1636         case MSR_K7_PERFCTR2:
1637         case MSR_K7_PERFCTR3:
1638                 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1639                         "0x%x data 0x%llx\n", msr, data);
1640                 break;
1641         case MSR_P6_PERFCTR0:
1642         case MSR_P6_PERFCTR1:
1643                 pr = true;
1644         case MSR_P6_EVNTSEL0:
1645         case MSR_P6_EVNTSEL1:
1646                 if (kvm_pmu_msr(vcpu, msr))
1647                         return kvm_pmu_set_msr(vcpu, msr, data);
1648
1649                 if (pr || data != 0)
1650                         pr_unimpl(vcpu, "disabled perfctr wrmsr: "
1651                                 "0x%x data 0x%llx\n", msr, data);
1652                 break;
1653         case MSR_K7_CLK_CTL:
1654                 /*
1655                  * Ignore all writes to this no longer documented MSR.
1656                  * Writes are only relevant for old K7 processors,
1657                  * all pre-dating SVM, but a recommended workaround from
1658                  * AMD for these chips. It is possible to speicify the
1659                  * affected processor models on the command line, hence
1660                  * the need to ignore the workaround.
1661                  */
1662                 break;
1663         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1664                 if (kvm_hv_msr_partition_wide(msr)) {
1665                         int r;
1666                         mutex_lock(&vcpu->kvm->lock);
1667                         r = set_msr_hyperv_pw(vcpu, msr, data);
1668                         mutex_unlock(&vcpu->kvm->lock);
1669                         return r;
1670                 } else
1671                         return set_msr_hyperv(vcpu, msr, data);
1672                 break;
1673         case MSR_IA32_BBL_CR_CTL3:
1674                 /* Drop writes to this legacy MSR -- see rdmsr
1675                  * counterpart for further detail.
1676                  */
1677                 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
1678                 break;
1679         default:
1680                 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
1681                         return xen_hvm_config(vcpu, data);
1682                 if (kvm_pmu_msr(vcpu, msr))
1683                         return kvm_pmu_set_msr(vcpu, msr, data);
1684                 if (!ignore_msrs) {
1685                         pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
1686                                 msr, data);
1687                         return 1;
1688                 } else {
1689                         pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
1690                                 msr, data);
1691                         break;
1692                 }
1693         }
1694         return 0;
1695 }
1696 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1697
1698
1699 /*
1700  * Reads an msr value (of 'msr_index') into 'pdata'.
1701  * Returns 0 on success, non-0 otherwise.
1702  * Assumes vcpu_load() was already called.
1703  */
1704 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1705 {
1706         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1707 }
1708
1709 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1710 {
1711         u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1712
1713         if (!msr_mtrr_valid(msr))
1714                 return 1;
1715
1716         if (msr == MSR_MTRRdefType)
1717                 *pdata = vcpu->arch.mtrr_state.def_type +
1718                          (vcpu->arch.mtrr_state.enabled << 10);
1719         else if (msr == MSR_MTRRfix64K_00000)
1720                 *pdata = p[0];
1721         else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1722                 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1723         else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1724                 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1725         else if (msr == MSR_IA32_CR_PAT)
1726                 *pdata = vcpu->arch.pat;
1727         else {  /* Variable MTRRs */
1728                 int idx, is_mtrr_mask;
1729                 u64 *pt;
1730
1731                 idx = (msr - 0x200) / 2;
1732                 is_mtrr_mask = msr - 0x200 - 2 * idx;
1733                 if (!is_mtrr_mask)
1734                         pt =
1735                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1736                 else
1737                         pt =
1738                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1739                 *pdata = *pt;
1740         }
1741
1742         return 0;
1743 }
1744
1745 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1746 {
1747         u64 data;
1748         u64 mcg_cap = vcpu->arch.mcg_cap;
1749         unsigned bank_num = mcg_cap & 0xff;
1750
1751         switch (msr) {
1752         case MSR_IA32_P5_MC_ADDR:
1753         case MSR_IA32_P5_MC_TYPE:
1754                 data = 0;
1755                 break;
1756         case MSR_IA32_MCG_CAP:
1757                 data = vcpu->arch.mcg_cap;
1758                 break;
1759         case MSR_IA32_MCG_CTL:
1760                 if (!(mcg_cap & MCG_CTL_P))
1761                         return 1;
1762                 data = vcpu->arch.mcg_ctl;
1763                 break;
1764         case MSR_IA32_MCG_STATUS:
1765                 data = vcpu->arch.mcg_status;
1766                 break;
1767         default:
1768                 if (msr >= MSR_IA32_MC0_CTL &&
1769                     msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1770                         u32 offset = msr - MSR_IA32_MC0_CTL;
1771                         data = vcpu->arch.mce_banks[offset];
1772                         break;
1773                 }
1774                 return 1;
1775         }
1776         *pdata = data;
1777         return 0;
1778 }
1779
1780 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1781 {
1782         u64 data = 0;
1783         struct kvm *kvm = vcpu->kvm;
1784
1785         switch (msr) {
1786         case HV_X64_MSR_GUEST_OS_ID:
1787                 data = kvm->arch.hv_guest_os_id;
1788                 break;
1789         case HV_X64_MSR_HYPERCALL:
1790                 data = kvm->arch.hv_hypercall;
1791                 break;
1792         default:
1793                 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1794                 return 1;
1795         }
1796
1797         *pdata = data;
1798         return 0;
1799 }
1800
1801 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1802 {
1803         u64 data = 0;
1804
1805         switch (msr) {
1806         case HV_X64_MSR_VP_INDEX: {
1807                 int r;
1808                 struct kvm_vcpu *v;
1809                 kvm_for_each_vcpu(r, v, vcpu->kvm)
1810                         if (v == vcpu)
1811                                 data = r;
1812                 break;
1813         }
1814         case HV_X64_MSR_EOI:
1815                 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1816         case HV_X64_MSR_ICR:
1817                 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1818         case HV_X64_MSR_TPR:
1819                 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1820         case HV_X64_MSR_APIC_ASSIST_PAGE:
1821                 data = vcpu->arch.hv_vapic;
1822                 break;
1823         default:
1824                 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1825                 return 1;
1826         }
1827         *pdata = data;
1828         return 0;
1829 }
1830
1831 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1832 {
1833         u64 data;
1834
1835         switch (msr) {
1836         case MSR_IA32_PLATFORM_ID:
1837         case MSR_IA32_EBL_CR_POWERON:
1838         case MSR_IA32_DEBUGCTLMSR:
1839         case MSR_IA32_LASTBRANCHFROMIP:
1840         case MSR_IA32_LASTBRANCHTOIP:
1841         case MSR_IA32_LASTINTFROMIP:
1842         case MSR_IA32_LASTINTTOIP:
1843         case MSR_K8_SYSCFG:
1844         case MSR_K7_HWCR:
1845         case MSR_VM_HSAVE_PA:
1846         case MSR_K7_EVNTSEL0:
1847         case MSR_K7_PERFCTR0:
1848         case MSR_K8_INT_PENDING_MSG:
1849         case MSR_AMD64_NB_CFG:
1850         case MSR_FAM10H_MMIO_CONF_BASE:
1851                 data = 0;
1852                 break;
1853         case MSR_P6_PERFCTR0:
1854         case MSR_P6_PERFCTR1:
1855         case MSR_P6_EVNTSEL0:
1856         case MSR_P6_EVNTSEL1:
1857                 if (kvm_pmu_msr(vcpu, msr))
1858                         return kvm_pmu_get_msr(vcpu, msr, pdata);
1859                 data = 0;
1860                 break;
1861         case MSR_IA32_UCODE_REV:
1862                 data = 0x100000000ULL;
1863                 break;
1864         case MSR_MTRRcap:
1865                 data = 0x500 | KVM_NR_VAR_MTRR;
1866                 break;
1867         case 0x200 ... 0x2ff:
1868                 return get_msr_mtrr(vcpu, msr, pdata);
1869         case 0xcd: /* fsb frequency */
1870                 data = 3;
1871                 break;
1872                 /*
1873                  * MSR_EBC_FREQUENCY_ID
1874                  * Conservative value valid for even the basic CPU models.
1875                  * Models 0,1: 000 in bits 23:21 indicating a bus speed of
1876                  * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
1877                  * and 266MHz for model 3, or 4. Set Core Clock
1878                  * Frequency to System Bus Frequency Ratio to 1 (bits
1879                  * 31:24) even though these are only valid for CPU
1880                  * models > 2, however guests may end up dividing or
1881                  * multiplying by zero otherwise.
1882                  */
1883         case MSR_EBC_FREQUENCY_ID:
1884                 data = 1 << 24;
1885                 break;
1886         case MSR_IA32_APICBASE:
1887                 data = kvm_get_apic_base(vcpu);
1888                 break;
1889         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1890                 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1891                 break;
1892         case MSR_IA32_TSCDEADLINE:
1893                 data = kvm_get_lapic_tscdeadline_msr(vcpu);
1894                 break;
1895         case MSR_IA32_MISC_ENABLE:
1896                 data = vcpu->arch.ia32_misc_enable_msr;
1897                 break;
1898         case MSR_IA32_PERF_STATUS:
1899                 /* TSC increment by tick */
1900                 data = 1000ULL;
1901                 /* CPU multiplier */
1902                 data |= (((uint64_t)4ULL) << 40);
1903                 break;
1904         case MSR_EFER:
1905                 data = vcpu->arch.efer;
1906                 break;
1907         case MSR_KVM_WALL_CLOCK:
1908         case MSR_KVM_WALL_CLOCK_NEW:
1909                 data = vcpu->kvm->arch.wall_clock;
1910                 break;
1911         case MSR_KVM_SYSTEM_TIME:
1912         case MSR_KVM_SYSTEM_TIME_NEW:
1913                 data = vcpu->arch.time;
1914                 break;
1915         case MSR_KVM_ASYNC_PF_EN:
1916                 data = vcpu->arch.apf.msr_val;
1917                 break;
1918         case MSR_KVM_STEAL_TIME:
1919                 data = vcpu->arch.st.msr_val;
1920                 break;
1921         case MSR_IA32_P5_MC_ADDR:
1922         case MSR_IA32_P5_MC_TYPE:
1923         case MSR_IA32_MCG_CAP:
1924         case MSR_IA32_MCG_CTL:
1925         case MSR_IA32_MCG_STATUS:
1926         case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1927                 return get_msr_mce(vcpu, msr, pdata);
1928         case MSR_K7_CLK_CTL:
1929                 /*
1930                  * Provide expected ramp-up count for K7. All other
1931                  * are set to zero, indicating minimum divisors for
1932                  * every field.
1933                  *
1934                  * This prevents guest kernels on AMD host with CPU
1935                  * type 6, model 8 and higher from exploding due to
1936                  * the rdmsr failing.
1937                  */
1938                 data = 0x20000000;
1939                 break;
1940         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1941                 if (kvm_hv_msr_partition_wide(msr)) {
1942                         int r;
1943                         mutex_lock(&vcpu->kvm->lock);
1944                         r = get_msr_hyperv_pw(vcpu, msr, pdata);
1945                         mutex_unlock(&vcpu->kvm->lock);
1946                         return r;
1947                 } else
1948                         return get_msr_hyperv(vcpu, msr, pdata);
1949                 break;
1950         case MSR_IA32_BBL_CR_CTL3:
1951                 /* This legacy MSR exists but isn't fully documented in current
1952                  * silicon.  It is however accessed by winxp in very narrow
1953                  * scenarios where it sets bit #19, itself documented as
1954                  * a "reserved" bit.  Best effort attempt to source coherent
1955                  * read data here should the balance of the register be
1956                  * interpreted by the guest:
1957                  *
1958                  * L2 cache control register 3: 64GB range, 256KB size,
1959                  * enabled, latency 0x1, configured
1960                  */
1961                 data = 0xbe702111;
1962                 break;
1963         default:
1964                 if (kvm_pmu_msr(vcpu, msr))
1965                         return kvm_pmu_get_msr(vcpu, msr, pdata);
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         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2025         entries = memdup_user(user_msrs->entries, size);
2026         if (IS_ERR(entries)) {
2027                 r = PTR_ERR(entries);
2028                 goto out;
2029         }
2030
2031         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2032         if (r < 0)
2033                 goto out_free;
2034
2035         r = -EFAULT;
2036         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2037                 goto out_free;
2038
2039         r = n;
2040
2041 out_free:
2042         kfree(entries);
2043 out:
2044         return r;
2045 }
2046
2047 int kvm_dev_ioctl_check_extension(long ext)
2048 {
2049         int r;
2050
2051         switch (ext) {
2052         case KVM_CAP_IRQCHIP:
2053         case KVM_CAP_HLT:
2054         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2055         case KVM_CAP_SET_TSS_ADDR:
2056         case KVM_CAP_EXT_CPUID:
2057         case KVM_CAP_CLOCKSOURCE:
2058         case KVM_CAP_PIT:
2059         case KVM_CAP_NOP_IO_DELAY:
2060         case KVM_CAP_MP_STATE:
2061         case KVM_CAP_SYNC_MMU:
2062         case KVM_CAP_USER_NMI:
2063         case KVM_CAP_REINJECT_CONTROL:
2064         case KVM_CAP_IRQ_INJECT_STATUS:
2065         case KVM_CAP_ASSIGN_DEV_IRQ:
2066         case KVM_CAP_IRQFD:
2067         case KVM_CAP_IOEVENTFD:
2068         case KVM_CAP_PIT2:
2069         case KVM_CAP_PIT_STATE2:
2070         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2071         case KVM_CAP_XEN_HVM:
2072         case KVM_CAP_ADJUST_CLOCK:
2073         case KVM_CAP_VCPU_EVENTS:
2074         case KVM_CAP_HYPERV:
2075         case KVM_CAP_HYPERV_VAPIC:
2076         case KVM_CAP_HYPERV_SPIN:
2077         case KVM_CAP_PCI_SEGMENT:
2078         case KVM_CAP_DEBUGREGS:
2079         case KVM_CAP_X86_ROBUST_SINGLESTEP:
2080         case KVM_CAP_XSAVE:
2081         case KVM_CAP_ASYNC_PF:
2082         case KVM_CAP_GET_TSC_KHZ:
2083                 r = 1;
2084                 break;
2085         case KVM_CAP_COALESCED_MMIO:
2086                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2087                 break;
2088         case KVM_CAP_VAPIC:
2089                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2090                 break;
2091         case KVM_CAP_NR_VCPUS:
2092                 r = KVM_SOFT_MAX_VCPUS;
2093                 break;
2094         case KVM_CAP_MAX_VCPUS:
2095                 r = KVM_MAX_VCPUS;
2096                 break;
2097         case KVM_CAP_NR_MEMSLOTS:
2098                 r = KVM_MEMORY_SLOTS;
2099                 break;
2100         case KVM_CAP_PV_MMU:    /* obsolete */
2101                 r = 0;
2102                 break;
2103         case KVM_CAP_IOMMU:
2104                 r = iommu_present(&pci_bus_type);
2105                 break;
2106         case KVM_CAP_MCE:
2107                 r = KVM_MAX_MCE_BANKS;
2108                 break;
2109         case KVM_CAP_XCRS:
2110                 r = cpu_has_xsave;
2111                 break;
2112         case KVM_CAP_TSC_CONTROL:
2113                 r = kvm_has_tsc_control;
2114                 break;
2115         case KVM_CAP_TSC_DEADLINE_TIMER:
2116                 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
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 kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2250                                     struct kvm_lapic_state *s)
2251 {
2252         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2253
2254         return 0;
2255 }
2256
2257 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2258                                     struct kvm_lapic_state *s)
2259 {
2260         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2261         kvm_apic_post_state_restore(vcpu);
2262         update_cr8_intercept(vcpu);
2263
2264         return 0;
2265 }
2266
2267 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2268                                     struct kvm_interrupt *irq)
2269 {
2270         if (irq->irq < 0 || irq->irq >= 256)
2271                 return -EINVAL;
2272         if (irqchip_in_kernel(vcpu->kvm))
2273                 return -ENXIO;
2274
2275         kvm_queue_interrupt(vcpu, irq->irq, false);
2276         kvm_make_request(KVM_REQ_EVENT, vcpu);
2277
2278         return 0;
2279 }
2280
2281 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2282 {
2283         kvm_inject_nmi(vcpu);
2284
2285         return 0;
2286 }
2287
2288 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2289                                            struct kvm_tpr_access_ctl *tac)
2290 {
2291         if (tac->flags)
2292                 return -EINVAL;
2293         vcpu->arch.tpr_access_reporting = !!tac->enabled;
2294         return 0;
2295 }
2296
2297 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2298                                         u64 mcg_cap)
2299 {
2300         int r;
2301         unsigned bank_num = mcg_cap & 0xff, bank;
2302
2303         r = -EINVAL;
2304         if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2305                 goto out;
2306         if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2307                 goto out;
2308         r = 0;
2309         vcpu->arch.mcg_cap = mcg_cap;
2310         /* Init IA32_MCG_CTL to all 1s */
2311         if (mcg_cap & MCG_CTL_P)
2312                 vcpu->arch.mcg_ctl = ~(u64)0;
2313         /* Init IA32_MCi_CTL to all 1s */
2314         for (bank = 0; bank < bank_num; bank++)
2315                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2316 out:
2317         return r;
2318 }
2319
2320 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2321                                       struct kvm_x86_mce *mce)
2322 {
2323         u64 mcg_cap = vcpu->arch.mcg_cap;
2324         unsigned bank_num = mcg_cap & 0xff;
2325         u64 *banks = vcpu->arch.mce_banks;
2326
2327         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2328                 return -EINVAL;
2329         /*
2330          * if IA32_MCG_CTL is not all 1s, the uncorrected error
2331          * reporting is disabled
2332          */
2333         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2334             vcpu->arch.mcg_ctl != ~(u64)0)
2335                 return 0;
2336         banks += 4 * mce->bank;
2337         /*
2338          * if IA32_MCi_CTL is not all 1s, the uncorrected error
2339          * reporting is disabled for the bank
2340          */
2341         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2342                 return 0;
2343         if (mce->status & MCI_STATUS_UC) {
2344                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2345                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2346                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2347                         return 0;
2348                 }
2349                 if (banks[1] & MCI_STATUS_VAL)
2350                         mce->status |= MCI_STATUS_OVER;
2351                 banks[2] = mce->addr;
2352                 banks[3] = mce->misc;
2353                 vcpu->arch.mcg_status = mce->mcg_status;
2354                 banks[1] = mce->status;
2355                 kvm_queue_exception(vcpu, MC_VECTOR);
2356         } else if (!(banks[1] & MCI_STATUS_VAL)
2357                    || !(banks[1] & MCI_STATUS_UC)) {
2358                 if (banks[1] & MCI_STATUS_VAL)
2359                         mce->status |= MCI_STATUS_OVER;
2360                 banks[2] = mce->addr;
2361                 banks[3] = mce->misc;
2362                 banks[1] = mce->status;
2363         } else
2364                 banks[1] |= MCI_STATUS_OVER;
2365         return 0;
2366 }
2367
2368 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2369                                                struct kvm_vcpu_events *events)
2370 {
2371         process_nmi(vcpu);
2372         events->exception.injected =
2373                 vcpu->arch.exception.pending &&
2374                 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2375         events->exception.nr = vcpu->arch.exception.nr;
2376         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2377         events->exception.pad = 0;
2378         events->exception.error_code = vcpu->arch.exception.error_code;
2379
2380         events->interrupt.injected =
2381                 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2382         events->interrupt.nr = vcpu->arch.interrupt.nr;
2383         events->interrupt.soft = 0;
2384         events->interrupt.shadow =
2385                 kvm_x86_ops->get_interrupt_shadow(vcpu,
2386                         KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2387
2388         events->nmi.injected = vcpu->arch.nmi_injected;
2389         events->nmi.pending = vcpu->arch.nmi_pending != 0;
2390         events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2391         events->nmi.pad = 0;
2392
2393         events->sipi_vector = vcpu->arch.sipi_vector;
2394
2395         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2396                          | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2397                          | KVM_VCPUEVENT_VALID_SHADOW);
2398         memset(&events->reserved, 0, sizeof(events->reserved));
2399 }
2400
2401 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2402                                               struct kvm_vcpu_events *events)
2403 {
2404         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2405                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2406                               | KVM_VCPUEVENT_VALID_SHADOW))
2407                 return -EINVAL;
2408
2409         process_nmi(vcpu);
2410         vcpu->arch.exception.pending = events->exception.injected;
2411         vcpu->arch.exception.nr = events->exception.nr;
2412         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2413         vcpu->arch.exception.error_code = events->exception.error_code;
2414
2415         vcpu->arch.interrupt.pending = events->interrupt.injected;
2416         vcpu->arch.interrupt.nr = events->interrupt.nr;
2417         vcpu->arch.interrupt.soft = events->interrupt.soft;
2418         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2419                 kvm_x86_ops->set_interrupt_shadow(vcpu,
2420                                                   events->interrupt.shadow);
2421
2422         vcpu->arch.nmi_injected = events->nmi.injected;
2423         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2424                 vcpu->arch.nmi_pending = events->nmi.pending;
2425         kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2426
2427         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2428                 vcpu->arch.sipi_vector = events->sipi_vector;
2429
2430         kvm_make_request(KVM_REQ_EVENT, vcpu);
2431
2432         return 0;
2433 }
2434
2435 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2436                                              struct kvm_debugregs *dbgregs)
2437 {
2438         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2439         dbgregs->dr6 = vcpu->arch.dr6;
2440         dbgregs->dr7 = vcpu->arch.dr7;
2441         dbgregs->flags = 0;
2442         memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
2443 }
2444
2445 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2446                                             struct kvm_debugregs *dbgregs)
2447 {
2448         if (dbgregs->flags)
2449                 return -EINVAL;
2450
2451         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2452         vcpu->arch.dr6 = dbgregs->dr6;
2453         vcpu->arch.dr7 = dbgregs->dr7;
2454
2455         return 0;
2456 }
2457
2458 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
2459                                          struct kvm_xsave *guest_xsave)
2460 {
2461         if (cpu_has_xsave)
2462                 memcpy(guest_xsave->region,
2463                         &vcpu->arch.guest_fpu.state->xsave,
2464                         xstate_size);
2465         else {
2466                 memcpy(guest_xsave->region,
2467                         &vcpu->arch.guest_fpu.state->fxsave,
2468                         sizeof(struct i387_fxsave_struct));
2469                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
2470                         XSTATE_FPSSE;
2471         }
2472 }
2473
2474 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
2475                                         struct kvm_xsave *guest_xsave)
2476 {
2477         u64 xstate_bv =
2478                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
2479
2480         if (cpu_has_xsave)
2481                 memcpy(&vcpu->arch.guest_fpu.state->xsave,
2482                         guest_xsave->region, xstate_size);
2483         else {
2484                 if (xstate_bv & ~XSTATE_FPSSE)
2485                         return -EINVAL;
2486                 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
2487                         guest_xsave->region, sizeof(struct i387_fxsave_struct));
2488         }
2489         return 0;
2490 }
2491
2492 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
2493                                         struct kvm_xcrs *guest_xcrs)
2494 {
2495         if (!cpu_has_xsave) {
2496                 guest_xcrs->nr_xcrs = 0;
2497                 return;
2498         }
2499
2500         guest_xcrs->nr_xcrs = 1;
2501         guest_xcrs->flags = 0;
2502         guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
2503         guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
2504 }
2505
2506 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
2507                                        struct kvm_xcrs *guest_xcrs)
2508 {
2509         int i, r = 0;
2510
2511         if (!cpu_has_xsave)
2512                 return -EINVAL;
2513
2514         if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
2515                 return -EINVAL;
2516
2517         for (i = 0; i < guest_xcrs->nr_xcrs; i++)
2518                 /* Only support XCR0 currently */
2519                 if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
2520                         r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
2521                                 guest_xcrs->xcrs[0].value);
2522                         break;
2523                 }
2524         if (r)
2525                 r = -EINVAL;
2526         return r;
2527 }
2528
2529 long kvm_arch_vcpu_ioctl(struct file *filp,
2530                          unsigned int ioctl, unsigned long arg)
2531 {
2532         struct kvm_vcpu *vcpu = filp->private_data;
2533         void __user *argp = (void __user *)arg;
2534         int r;
2535         union {
2536                 struct kvm_lapic_state *lapic;
2537                 struct kvm_xsave *xsave;
2538                 struct kvm_xcrs *xcrs;
2539                 void *buffer;
2540         } u;
2541
2542         u.buffer = NULL;
2543         switch (ioctl) {
2544         case KVM_GET_LAPIC: {
2545                 r = -EINVAL;
2546                 if (!vcpu->arch.apic)
2547                         goto out;
2548                 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2549
2550                 r = -ENOMEM;
2551                 if (!u.lapic)
2552                         goto out;
2553                 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
2554                 if (r)
2555                         goto out;
2556                 r = -EFAULT;
2557                 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
2558                         goto out;
2559                 r = 0;
2560                 break;
2561         }
2562         case KVM_SET_LAPIC: {
2563                 r = -EINVAL;
2564                 if (!vcpu->arch.apic)
2565                         goto out;
2566                 u.lapic = memdup_user(argp, sizeof(*u.lapic));
2567                 if (IS_ERR(u.lapic)) {
2568                         r = PTR_ERR(u.lapic);
2569                         goto out;
2570                 }
2571
2572                 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
2573                 if (r)
2574                         goto out;
2575                 r = 0;
2576                 break;
2577         }
2578         case KVM_INTERRUPT: {
2579                 struct kvm_interrupt irq;
2580
2581                 r = -EFAULT;
2582                 if (copy_from_user(&irq, argp, sizeof irq))
2583                         goto out;
2584                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2585                 if (r)
2586                         goto out;
2587                 r = 0;
2588                 break;
2589         }
2590         case KVM_NMI: {
2591                 r = kvm_vcpu_ioctl_nmi(vcpu);
2592                 if (r)
2593                         goto out;
2594                 r = 0;
2595                 break;
2596         }
2597         case KVM_SET_CPUID: {
2598                 struct kvm_cpuid __user *cpuid_arg = argp;
2599                 struct kvm_cpuid cpuid;
2600
2601                 r = -EFAULT;
2602                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2603                         goto out;
2604                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2605                 if (r)
2606                         goto out;
2607                 break;
2608         }
2609         case KVM_SET_CPUID2: {
2610                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2611                 struct kvm_cpuid2 cpuid;
2612
2613                 r = -EFAULT;
2614                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2615                         goto out;
2616                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
2617                                               cpuid_arg->entries);
2618                 if (r)
2619                         goto out;
2620                 break;
2621         }
2622         case KVM_GET_CPUID2: {
2623                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2624                 struct kvm_cpuid2 cpuid;
2625
2626                 r = -EFAULT;
2627                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2628                         goto out;
2629                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
2630                                               cpuid_arg->entries);
2631                 if (r)
2632                         goto out;
2633                 r = -EFAULT;
2634                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2635                         goto out;
2636                 r = 0;
2637                 break;
2638         }
2639         case KVM_GET_MSRS:
2640                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
2641                 break;
2642         case KVM_SET_MSRS:
2643                 r = msr_io(vcpu, argp, do_set_msr, 0);
2644                 break;
2645         case KVM_TPR_ACCESS_REPORTING: {
2646                 struct kvm_tpr_access_ctl tac;
2647
2648                 r = -EFAULT;
2649                 if (copy_from_user(&tac, argp, sizeof tac))
2650                         goto out;
2651                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
2652                 if (r)
2653                         goto out;
2654                 r = -EFAULT;
2655                 if (copy_to_user(argp, &tac, sizeof tac))
2656                         goto out;
2657                 r = 0;
2658                 break;
2659         };
2660         case KVM_SET_VAPIC_ADDR: {
2661                 struct kvm_vapic_addr va;
2662
2663                 r = -EINVAL;
2664                 if (!irqchip_in_kernel(vcpu->kvm))
2665                         goto out;
2666                 r = -EFAULT;
2667                 if (copy_from_user(&va, argp, sizeof va))
2668                         goto out;
2669                 r = 0;
2670                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
2671                 break;
2672         }
2673         case KVM_X86_SETUP_MCE: {
2674                 u64 mcg_cap;
2675
2676                 r = -EFAULT;
2677                 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
2678                         goto out;
2679                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
2680                 break;
2681         }
2682         case KVM_X86_SET_MCE: {
2683                 struct kvm_x86_mce mce;
2684
2685                 r = -EFAULT;
2686                 if (copy_from_user(&mce, argp, sizeof mce))
2687                         goto out;
2688                 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
2689                 break;
2690         }
2691         case KVM_GET_VCPU_EVENTS: {
2692                 struct kvm_vcpu_events events;
2693
2694                 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
2695
2696                 r = -EFAULT;
2697                 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
2698                         break;
2699                 r = 0;
2700                 break;
2701         }
2702         case KVM_SET_VCPU_EVENTS: {
2703                 struct kvm_vcpu_events events;
2704
2705                 r = -EFAULT;
2706                 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
2707                         break;
2708
2709                 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
2710                 break;
2711         }
2712         case KVM_GET_DEBUGREGS: {
2713                 struct kvm_debugregs dbgregs;
2714
2715                 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
2716
2717                 r = -EFAULT;
2718                 if (copy_to_user(argp, &dbgregs,
2719                                  sizeof(struct kvm_debugregs)))
2720                         break;
2721                 r = 0;
2722                 break;
2723         }
2724         case KVM_SET_DEBUGREGS: {
2725                 struct kvm_debugregs dbgregs;
2726
2727                 r = -EFAULT;
2728                 if (copy_from_user(&dbgregs, argp,
2729                                    sizeof(struct kvm_debugregs)))
2730                         break;
2731
2732                 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
2733                 break;
2734         }
2735         case KVM_GET_XSAVE: {
2736                 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
2737                 r = -ENOMEM;
2738                 if (!u.xsave)
2739                         break;
2740
2741                 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
2742
2743                 r = -EFAULT;
2744                 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
2745                         break;
2746                 r = 0;
2747                 break;
2748         }
2749         case KVM_SET_XSAVE: {
2750                 u.xsave = memdup_user(argp, sizeof(*u.xsave));
2751                 if (IS_ERR(u.xsave)) {
2752                         r = PTR_ERR(u.xsave);
2753                         goto out;
2754                 }
2755
2756                 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
2757                 break;
2758         }
2759         case KVM_GET_XCRS: {
2760                 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
2761                 r = -ENOMEM;
2762                 if (!u.xcrs)
2763                         break;
2764
2765                 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
2766
2767                 r = -EFAULT;
2768                 if (copy_to_user(argp, u.xcrs,
2769                                  sizeof(struct kvm_xcrs)))
2770                         break;
2771                 r = 0;
2772                 break;
2773         }
2774         case KVM_SET_XCRS: {
2775                 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
2776                 if (IS_ERR(u.xcrs)) {
2777                         r = PTR_ERR(u.xcrs);
2778                         goto out;
2779                 }
2780
2781                 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
2782                 break;
2783         }
2784         case KVM_SET_TSC_KHZ: {
2785                 u32 user_tsc_khz;
2786
2787                 r = -EINVAL;
2788                 if (!kvm_has_tsc_control)
2789                         break;
2790
2791                 user_tsc_khz = (u32)arg;
2792
2793                 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
2794                         goto out;
2795
2796                 kvm_x86_ops->set_tsc_khz(vcpu, user_tsc_khz);
2797
2798                 r = 0;
2799                 goto out;
2800         }
2801         case KVM_GET_TSC_KHZ: {
2802                 r = -EIO;
2803                 if (check_tsc_unstable())
2804                         goto out;
2805
2806                 r = vcpu_tsc_khz(vcpu);
2807
2808                 goto out;
2809         }
2810         default:
2811                 r = -EINVAL;
2812         }
2813 out:
2814         kfree(u.buffer);
2815         return r;
2816 }
2817
2818 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
2819 {
2820         int ret;
2821
2822         if (addr > (unsigned int)(-3 * PAGE_SIZE))
2823                 return -1;
2824         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
2825         return ret;
2826 }
2827
2828 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
2829                                               u64 ident_addr)
2830 {
2831         kvm->arch.ept_identity_map_addr = ident_addr;
2832         return 0;
2833 }
2834
2835 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
2836                                           u32 kvm_nr_mmu_pages)
2837 {
2838         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
2839                 return -EINVAL;
2840
2841         mutex_lock(&kvm->slots_lock);
2842         spin_lock(&kvm->mmu_lock);
2843
2844         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
2845         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
2846
2847         spin_unlock(&kvm->mmu_lock);
2848         mutex_unlock(&kvm->slots_lock);
2849         return 0;
2850 }
2851
2852 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
2853 {
2854         return kvm->arch.n_max_mmu_pages;
2855 }
2856
2857 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2858 {
2859         int r;
2860
2861         r = 0;
2862         switch (chip->chip_id) {
2863         case KVM_IRQCHIP_PIC_MASTER:
2864                 memcpy(&chip->chip.pic,
2865                         &pic_irqchip(kvm)->pics[0],
2866                         sizeof(struct kvm_pic_state));
2867                 break;
2868         case KVM_IRQCHIP_PIC_SLAVE:
2869                 memcpy(&chip->chip.pic,
2870                         &pic_irqchip(kvm)->pics[1],
2871                         sizeof(struct kvm_pic_state));
2872                 break;
2873         case KVM_IRQCHIP_IOAPIC:
2874                 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
2875                 break;
2876         default:
2877                 r = -EINVAL;
2878                 break;
2879         }
2880         return r;
2881 }
2882
2883 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2884 {
2885         int r;
2886
2887         r = 0;
2888         switch (chip->chip_id) {
2889         case KVM_IRQCHIP_PIC_MASTER:
2890                 spin_lock(&pic_irqchip(kvm)->lock);
2891                 memcpy(&pic_irqchip(kvm)->pics[0],
2892                         &chip->chip.pic,
2893                         sizeof(struct kvm_pic_state));
2894                 spin_unlock(&pic_irqchip(kvm)->lock);
2895                 break;
2896         case KVM_IRQCHIP_PIC_SLAVE:
2897                 spin_lock(&pic_irqchip(kvm)->lock);
2898                 memcpy(&pic_irqchip(kvm)->pics[1],
2899                         &chip->chip.pic,
2900                         sizeof(struct kvm_pic_state));
2901                 spin_unlock(&pic_irqchip(kvm)->lock);
2902                 break;
2903         case KVM_IRQCHIP_IOAPIC:
2904                 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
2905                 break;
2906         default:
2907                 r = -EINVAL;
2908                 break;
2909         }
2910         kvm_pic_update_irq(pic_irqchip(kvm));
2911         return r;
2912 }
2913
2914 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2915 {
2916         int r = 0;
2917
2918         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2919         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
2920         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2921         return r;
2922 }
2923
2924 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2925 {
2926         int r = 0;
2927
2928         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2929         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
2930         kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
2931         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2932         return r;
2933 }
2934
2935 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2936 {
2937         int r = 0;
2938
2939         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2940         memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
2941                 sizeof(ps->channels));
2942         ps->flags = kvm->arch.vpit->pit_state.flags;
2943         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2944         memset(&ps->reserved, 0, sizeof(ps->reserved));
2945         return r;
2946 }
2947
2948 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2949 {
2950         int r = 0, start = 0;
2951         u32 prev_legacy, cur_legacy;
2952         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2953         prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
2954         cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
2955         if (!prev_legacy && cur_legacy)
2956                 start = 1;
2957         memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
2958                sizeof(kvm->arch.vpit->pit_state.channels));
2959         kvm->arch.vpit->pit_state.flags = ps->flags;
2960         kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
2961         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2962         return r;
2963 }
2964
2965 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
2966                                  struct kvm_reinject_control *control)
2967 {
2968         if (!kvm->arch.vpit)
2969                 return -ENXIO;
2970         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2971         kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
2972         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2973         return 0;
2974 }
2975
2976 /**
2977  * write_protect_slot - write protect a slot for dirty logging
2978  * @kvm: the kvm instance
2979  * @memslot: the slot we protect
2980  * @dirty_bitmap: the bitmap indicating which pages are dirty
2981  * @nr_dirty_pages: the number of dirty pages
2982  *
2983  * We have two ways to find all sptes to protect:
2984  * 1. Use kvm_mmu_slot_remove_write_access() which walks all shadow pages and
2985  *    checks ones that have a spte mapping a page in the slot.
2986  * 2. Use kvm_mmu_rmap_write_protect() for each gfn found in the bitmap.
2987  *
2988  * Generally speaking, if there are not so many dirty pages compared to the
2989  * number of shadow pages, we should use the latter.
2990  *
2991  * Note that letting others write into a page marked dirty in the old bitmap
2992  * by using the remaining tlb entry is not a problem.  That page will become
2993  * write protected again when we flush the tlb and then be reported dirty to
2994  * the user space by copying the old bitmap.
2995  */
2996 static void write_protect_slot(struct kvm *kvm,
2997                                struct kvm_memory_slot *memslot,
2998                                unsigned long *dirty_bitmap,
2999                                unsigned long nr_dirty_pages)
3000 {
3001         /* Not many dirty pages compared to # of shadow pages. */
3002         if (nr_dirty_pages < kvm->arch.n_used_mmu_pages) {
3003                 unsigned long gfn_offset;
3004
3005                 for_each_set_bit(gfn_offset, dirty_bitmap, memslot->npages) {
3006                         unsigned long gfn = memslot->base_gfn + gfn_offset;
3007
3008                         spin_lock(&kvm->mmu_lock);
3009                         kvm_mmu_rmap_write_protect(kvm, gfn, memslot);
3010                         spin_unlock(&kvm->mmu_lock);
3011                 }
3012                 kvm_flush_remote_tlbs(kvm);
3013         } else {
3014                 spin_lock(&kvm->mmu_lock);
3015                 kvm_mmu_slot_remove_write_access(kvm, memslot->id);
3016                 spin_unlock(&kvm->mmu_lock);
3017         }
3018 }
3019
3020 /*
3021  * Get (and clear) the dirty memory log for a memory slot.
3022  */
3023 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
3024                                       struct kvm_dirty_log *log)
3025 {
3026         int r;
3027         struct kvm_memory_slot *memslot;
3028         unsigned long n, nr_dirty_pages;
3029
3030         mutex_lock(&kvm->slots_lock);
3031
3032         r = -EINVAL;
3033         if (log->slot >= KVM_MEMORY_SLOTS)
3034                 goto out;
3035
3036         memslot = id_to_memslot(kvm->memslots, log->slot);
3037         r = -ENOENT;
3038         if (!memslot->dirty_bitmap)
3039                 goto out;
3040
3041         n = kvm_dirty_bitmap_bytes(memslot);
3042         nr_dirty_pages = memslot->nr_dirty_pages;
3043
3044         /* If nothing is dirty, don't bother messing with page tables. */
3045         if (nr_dirty_pages) {
3046                 struct kvm_memslots *slots, *old_slots;
3047                 unsigned long *dirty_bitmap, *dirty_bitmap_head;
3048
3049                 dirty_bitmap = memslot->dirty_bitmap;
3050                 dirty_bitmap_head = memslot->dirty_bitmap_head;
3051                 if (dirty_bitmap == dirty_bitmap_head)
3052                         dirty_bitmap_head += n / sizeof(long);
3053                 memset(dirty_bitmap_head, 0, n);
3054
3055                 r = -ENOMEM;
3056                 slots = kmemdup(kvm->memslots, sizeof(*kvm->memslots), GFP_KERNEL);
3057                 if (!slots)
3058                         goto out;
3059
3060                 memslot = id_to_memslot(slots, log->slot);
3061                 memslot->nr_dirty_pages = 0;
3062                 memslot->dirty_bitmap = dirty_bitmap_head;
3063                 update_memslots(slots, NULL);
3064
3065                 old_slots = kvm->memslots;
3066                 rcu_assign_pointer(kvm->memslots, slots);
3067                 synchronize_srcu_expedited(&kvm->srcu);
3068                 kfree(old_slots);
3069
3070                 write_protect_slot(kvm, memslot, dirty_bitmap, nr_dirty_pages);
3071
3072                 r = -EFAULT;
3073                 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n))
3074                         goto out;
3075         } else {
3076                 r = -EFAULT;
3077                 if (clear_user(log->dirty_bitmap, n))
3078                         goto out;
3079         }
3080
3081         r = 0;
3082 out:
3083         mutex_unlock(&kvm->slots_lock);
3084         return r;
3085 }
3086
3087 long kvm_arch_vm_ioctl(struct file *filp,
3088                        unsigned int ioctl, unsigned long arg)
3089 {
3090         struct kvm *kvm = filp->private_data;
3091         void __user *argp = (void __user *)arg;
3092         int r = -ENOTTY;
3093         /*
3094          * This union makes it completely explicit to gcc-3.x
3095          * that these two variables' stack usage should be
3096          * combined, not added together.
3097          */
3098         union {
3099                 struct kvm_pit_state ps;
3100                 struct kvm_pit_state2 ps2;
3101                 struct kvm_pit_config pit_config;
3102         } u;
3103
3104         switch (ioctl) {
3105         case KVM_SET_TSS_ADDR:
3106                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3107                 if (r < 0)
3108                         goto out;
3109                 break;
3110         case KVM_SET_IDENTITY_MAP_ADDR: {
3111                 u64 ident_addr;
3112
3113                 r = -EFAULT;
3114                 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3115                         goto out;
3116                 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3117                 if (r < 0)
3118                         goto out;
3119                 break;
3120         }
3121         case KVM_SET_NR_MMU_PAGES:
3122                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3123                 if (r)
3124                         goto out;
3125                 break;
3126         case KVM_GET_NR_MMU_PAGES:
3127                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3128                 break;
3129         case KVM_CREATE_IRQCHIP: {
3130                 struct kvm_pic *vpic;
3131
3132                 mutex_lock(&kvm->lock);
3133                 r = -EEXIST;
3134                 if (kvm->arch.vpic)
3135                         goto create_irqchip_unlock;
3136                 r = -ENOMEM;
3137                 vpic = kvm_create_pic(kvm);
3138                 if (vpic) {
3139                         r = kvm_ioapic_init(kvm);
3140                         if (r) {
3141                                 mutex_lock(&kvm->slots_lock);
3142                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3143                                                           &vpic->dev_master);
3144                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3145                                                           &vpic->dev_slave);
3146                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3147                                                           &vpic->dev_eclr);
3148                                 mutex_unlock(&kvm->slots_lock);
3149                                 kfree(vpic);
3150                                 goto create_irqchip_unlock;
3151                         }
3152                 } else
3153                         goto create_irqchip_unlock;
3154                 smp_wmb();
3155                 kvm->arch.vpic = vpic;
3156                 smp_wmb();
3157                 r = kvm_setup_default_irq_routing(kvm);
3158                 if (r) {
3159                         mutex_lock(&kvm->slots_lock);
3160                         mutex_lock(&kvm->irq_lock);
3161                         kvm_ioapic_destroy(kvm);
3162                         kvm_destroy_pic(kvm);
3163                         mutex_unlock(&kvm->irq_lock);
3164                         mutex_unlock(&kvm->slots_lock);
3165                 }
3166         create_irqchip_unlock:
3167                 mutex_unlock(&kvm->lock);
3168                 break;
3169         }
3170         case KVM_CREATE_PIT:
3171                 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3172                 goto create_pit;
3173         case KVM_CREATE_PIT2:
3174                 r = -EFAULT;
3175                 if (copy_from_user(&u.pit_config, argp,
3176                                    sizeof(struct kvm_pit_config)))
3177                         goto out;
3178         create_pit:
3179                 mutex_lock(&kvm->slots_lock);
3180                 r = -EEXIST;
3181                 if (kvm->arch.vpit)
3182                         goto create_pit_unlock;
3183                 r = -ENOMEM;
3184                 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3185                 if (kvm->arch.vpit)
3186                         r = 0;
3187         create_pit_unlock:
3188                 mutex_unlock(&kvm->slots_lock);
3189                 break;
3190         case KVM_IRQ_LINE_STATUS:
3191         case KVM_IRQ_LINE: {
3192                 struct kvm_irq_level irq_event;
3193
3194                 r = -EFAULT;
3195                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
3196                         goto out;
3197                 r = -ENXIO;
3198                 if (irqchip_in_kernel(kvm)) {
3199                         __s32 status;
3200                         status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3201                                         irq_event.irq, irq_event.level);
3202                         if (ioctl == KVM_IRQ_LINE_STATUS) {
3203                                 r = -EFAULT;
3204                                 irq_event.status = status;
3205                                 if (copy_to_user(argp, &irq_event,
3206                                                         sizeof irq_event))
3207                                         goto out;
3208                         }
3209                         r = 0;
3210                 }
3211                 break;
3212         }
3213         case KVM_GET_IRQCHIP: {
3214                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3215                 struct kvm_irqchip *chip;
3216
3217                 chip = memdup_user(argp, sizeof(*chip));
3218                 if (IS_ERR(chip)) {
3219                         r = PTR_ERR(chip);
3220                         goto out;
3221                 }
3222
3223                 r = -ENXIO;
3224                 if (!irqchip_in_kernel(kvm))
3225                         goto get_irqchip_out;
3226                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3227                 if (r)
3228                         goto get_irqchip_out;
3229                 r = -EFAULT;
3230                 if (copy_to_user(argp, chip, sizeof *chip))
3231                         goto get_irqchip_out;
3232                 r = 0;
3233         get_irqchip_out:
3234                 kfree(chip);
3235                 if (r)
3236                         goto out;
3237                 break;
3238         }
3239         case KVM_SET_IRQCHIP: {
3240                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3241                 struct kvm_irqchip *chip;
3242
3243                 chip = memdup_user(argp, sizeof(*chip));
3244                 if (IS_ERR(chip)) {
3245                         r = PTR_ERR(chip);
3246                         goto out;
3247                 }
3248
3249                 r = -ENXIO;
3250                 if (!irqchip_in_kernel(kvm))
3251                         goto set_irqchip_out;
3252                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3253                 if (r)
3254                         goto set_irqchip_out;
3255                 r = 0;
3256         set_irqchip_out:
3257                 kfree(chip);
3258                 if (r)
3259                         goto out;
3260                 break;
3261         }
3262         case KVM_GET_PIT: {
3263                 r = -EFAULT;
3264                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3265                         goto out;
3266                 r = -ENXIO;
3267                 if (!kvm->arch.vpit)
3268                         goto out;
3269                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3270                 if (r)
3271                         goto out;
3272                 r = -EFAULT;
3273                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3274                         goto out;
3275                 r = 0;
3276                 break;
3277         }
3278         case KVM_SET_PIT: {
3279                 r = -EFAULT;
3280                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3281                         goto out;
3282                 r = -ENXIO;
3283                 if (!kvm->arch.vpit)
3284                         goto out;
3285                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3286                 if (r)
3287                         goto out;
3288                 r = 0;
3289                 break;
3290         }
3291         case KVM_GET_PIT2: {
3292                 r = -ENXIO;
3293                 if (!kvm->arch.vpit)
3294                         goto out;
3295                 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3296                 if (r)
3297                         goto out;
3298                 r = -EFAULT;
3299                 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3300                         goto out;
3301                 r = 0;
3302                 break;
3303         }
3304         case KVM_SET_PIT2: {
3305                 r = -EFAULT;
3306                 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3307                         goto out;
3308                 r = -ENXIO;
3309                 if (!kvm->arch.vpit)
3310                         goto out;
3311                 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3312                 if (r)
3313                         goto out;
3314                 r = 0;
3315                 break;
3316         }
3317         case KVM_REINJECT_CONTROL: {
3318                 struct kvm_reinject_control control;
3319                 r =  -EFAULT;
3320                 if (copy_from_user(&control, argp, sizeof(control)))
3321                         goto out;
3322                 r = kvm_vm_ioctl_reinject(kvm, &control);
3323                 if (r)
3324                         goto out;
3325                 r = 0;
3326                 break;
3327         }
3328         case KVM_XEN_HVM_CONFIG: {
3329                 r = -EFAULT;
3330                 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3331                                    sizeof(struct kvm_xen_hvm_config)))
3332                         goto out;
3333                 r = -EINVAL;
3334                 if (kvm->arch.xen_hvm_config.flags)
3335                         goto out;
3336                 r = 0;
3337                 break;
3338         }
3339         case KVM_SET_CLOCK: {
3340                 struct kvm_clock_data user_ns;
3341                 u64 now_ns;
3342                 s64 delta;
3343
3344                 r = -EFAULT;
3345                 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3346                         goto out;
3347
3348                 r = -EINVAL;
3349                 if (user_ns.flags)
3350                         goto out;
3351
3352                 r = 0;
3353                 local_irq_disable();
3354                 now_ns = get_kernel_ns();
3355                 delta = user_ns.clock - now_ns;
3356                 local_irq_enable();
3357                 kvm->arch.kvmclock_offset = delta;
3358                 break;
3359         }
3360         case KVM_GET_CLOCK: {
3361                 struct kvm_clock_data user_ns;
3362                 u64 now_ns;
3363
3364                 local_irq_disable();
3365                 now_ns = get_kernel_ns();
3366                 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3367                 local_irq_enable();
3368                 user_ns.flags = 0;
3369                 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
3370
3371                 r = -EFAULT;
3372                 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3373                         goto out;
3374                 r = 0;
3375                 break;
3376         }
3377
3378         default:
3379                 ;
3380         }
3381 out:
3382         return r;
3383 }
3384