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