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