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