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