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