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