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