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