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