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