]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - arch/x86/kvm/x86.c
KVM: MMU: sync roots on mmu reload
[linux-2.6-omap-h63xx.git] / arch / x86 / kvm / x86.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * derived from drivers/kvm/kvm_main.c
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright (C) 2008 Qumranet, Inc.
8  * Copyright IBM Corporation, 2008
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *   Amit Shah    <amit.shah@qumranet.com>
14  *   Ben-Ami Yassour <benami@il.ibm.com>
15  *
16  * This work is licensed under the terms of the GNU GPL, version 2.  See
17  * the COPYING file in the top-level directory.
18  *
19  */
20
21 #include <linux/kvm_host.h>
22 #include "irq.h"
23 #include "mmu.h"
24 #include "i8254.h"
25 #include "tss.h"
26 #include "kvm_cache_regs.h"
27 #include "x86.h"
28
29 #include <linux/clocksource.h>
30 #include <linux/interrupt.h>
31 #include <linux/kvm.h>
32 #include <linux/fs.h>
33 #include <linux/pci.h>
34 #include <linux/vmalloc.h>
35 #include <linux/module.h>
36 #include <linux/mman.h>
37 #include <linux/highmem.h>
38 #include <linux/intel-iommu.h>
39
40 #include <asm/uaccess.h>
41 #include <asm/msr.h>
42 #include <asm/desc.h>
43
44 #define MAX_IO_MSRS 256
45 #define CR0_RESERVED_BITS                                               \
46         (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
47                           | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
48                           | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
49 #define CR4_RESERVED_BITS                                               \
50         (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
51                           | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE     \
52                           | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR  \
53                           | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
54
55 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
56 /* EFER defaults:
57  * - enable syscall per default because its emulated by KVM
58  * - enable LME and LMA per default on 64 bit KVM
59  */
60 #ifdef CONFIG_X86_64
61 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffafeULL;
62 #else
63 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffffeULL;
64 #endif
65
66 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
67 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
68
69 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
70                                     struct kvm_cpuid_entry2 __user *entries);
71
72 struct kvm_x86_ops *kvm_x86_ops;
73 EXPORT_SYMBOL_GPL(kvm_x86_ops);
74
75 struct kvm_stats_debugfs_item debugfs_entries[] = {
76         { "pf_fixed", VCPU_STAT(pf_fixed) },
77         { "pf_guest", VCPU_STAT(pf_guest) },
78         { "tlb_flush", VCPU_STAT(tlb_flush) },
79         { "invlpg", VCPU_STAT(invlpg) },
80         { "exits", VCPU_STAT(exits) },
81         { "io_exits", VCPU_STAT(io_exits) },
82         { "mmio_exits", VCPU_STAT(mmio_exits) },
83         { "signal_exits", VCPU_STAT(signal_exits) },
84         { "irq_window", VCPU_STAT(irq_window_exits) },
85         { "nmi_window", VCPU_STAT(nmi_window_exits) },
86         { "halt_exits", VCPU_STAT(halt_exits) },
87         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
88         { "hypercalls", VCPU_STAT(hypercalls) },
89         { "request_irq", VCPU_STAT(request_irq_exits) },
90         { "irq_exits", VCPU_STAT(irq_exits) },
91         { "host_state_reload", VCPU_STAT(host_state_reload) },
92         { "efer_reload", VCPU_STAT(efer_reload) },
93         { "fpu_reload", VCPU_STAT(fpu_reload) },
94         { "insn_emulation", VCPU_STAT(insn_emulation) },
95         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
96         { "irq_injections", VCPU_STAT(irq_injections) },
97         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
98         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
99         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
100         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
101         { "mmu_flooded", VM_STAT(mmu_flooded) },
102         { "mmu_recycled", VM_STAT(mmu_recycled) },
103         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
104         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
105         { "largepages", VM_STAT(lpages) },
106         { NULL }
107 };
108
109 static struct kvm_assigned_dev_kernel *kvm_find_assigned_dev(struct list_head *head,
110                                                       int assigned_dev_id)
111 {
112         struct list_head *ptr;
113         struct kvm_assigned_dev_kernel *match;
114
115         list_for_each(ptr, head) {
116                 match = list_entry(ptr, struct kvm_assigned_dev_kernel, list);
117                 if (match->assigned_dev_id == assigned_dev_id)
118                         return match;
119         }
120         return NULL;
121 }
122
123 static void kvm_assigned_dev_interrupt_work_handler(struct work_struct *work)
124 {
125         struct kvm_assigned_dev_kernel *assigned_dev;
126
127         assigned_dev = container_of(work, struct kvm_assigned_dev_kernel,
128                                     interrupt_work);
129
130         /* This is taken to safely inject irq inside the guest. When
131          * the interrupt injection (or the ioapic code) uses a
132          * finer-grained lock, update this
133          */
134         mutex_lock(&assigned_dev->kvm->lock);
135         kvm_set_irq(assigned_dev->kvm,
136                     assigned_dev->guest_irq, 1);
137         mutex_unlock(&assigned_dev->kvm->lock);
138         kvm_put_kvm(assigned_dev->kvm);
139 }
140
141 /* FIXME: Implement the OR logic needed to make shared interrupts on
142  * this line behave properly
143  */
144 static irqreturn_t kvm_assigned_dev_intr(int irq, void *dev_id)
145 {
146         struct kvm_assigned_dev_kernel *assigned_dev =
147                 (struct kvm_assigned_dev_kernel *) dev_id;
148
149         kvm_get_kvm(assigned_dev->kvm);
150         schedule_work(&assigned_dev->interrupt_work);
151         disable_irq_nosync(irq);
152         return IRQ_HANDLED;
153 }
154
155 /* Ack the irq line for an assigned device */
156 static void kvm_assigned_dev_ack_irq(struct kvm_irq_ack_notifier *kian)
157 {
158         struct kvm_assigned_dev_kernel *dev;
159
160         if (kian->gsi == -1)
161                 return;
162
163         dev = container_of(kian, struct kvm_assigned_dev_kernel,
164                            ack_notifier);
165         kvm_set_irq(dev->kvm, dev->guest_irq, 0);
166         enable_irq(dev->host_irq);
167 }
168
169 static void kvm_free_assigned_device(struct kvm *kvm,
170                                      struct kvm_assigned_dev_kernel
171                                      *assigned_dev)
172 {
173         if (irqchip_in_kernel(kvm) && assigned_dev->irq_requested)
174                 free_irq(assigned_dev->host_irq, (void *)assigned_dev);
175
176         kvm_unregister_irq_ack_notifier(kvm, &assigned_dev->ack_notifier);
177
178         if (cancel_work_sync(&assigned_dev->interrupt_work))
179                 /* We had pending work. That means we will have to take
180                  * care of kvm_put_kvm.
181                  */
182                 kvm_put_kvm(kvm);
183
184         pci_release_regions(assigned_dev->dev);
185         pci_disable_device(assigned_dev->dev);
186         pci_dev_put(assigned_dev->dev);
187
188         list_del(&assigned_dev->list);
189         kfree(assigned_dev);
190 }
191
192 static void kvm_free_all_assigned_devices(struct kvm *kvm)
193 {
194         struct list_head *ptr, *ptr2;
195         struct kvm_assigned_dev_kernel *assigned_dev;
196
197         list_for_each_safe(ptr, ptr2, &kvm->arch.assigned_dev_head) {
198                 assigned_dev = list_entry(ptr,
199                                           struct kvm_assigned_dev_kernel,
200                                           list);
201
202                 kvm_free_assigned_device(kvm, assigned_dev);
203         }
204 }
205
206 static int kvm_vm_ioctl_assign_irq(struct kvm *kvm,
207                                    struct kvm_assigned_irq
208                                    *assigned_irq)
209 {
210         int r = 0;
211         struct kvm_assigned_dev_kernel *match;
212
213         mutex_lock(&kvm->lock);
214
215         match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
216                                       assigned_irq->assigned_dev_id);
217         if (!match) {
218                 mutex_unlock(&kvm->lock);
219                 return -EINVAL;
220         }
221
222         if (match->irq_requested) {
223                 match->guest_irq = assigned_irq->guest_irq;
224                 match->ack_notifier.gsi = assigned_irq->guest_irq;
225                 mutex_unlock(&kvm->lock);
226                 return 0;
227         }
228
229         INIT_WORK(&match->interrupt_work,
230                   kvm_assigned_dev_interrupt_work_handler);
231
232         if (irqchip_in_kernel(kvm)) {
233                 if (!capable(CAP_SYS_RAWIO)) {
234                         r = -EPERM;
235                         goto out_release;
236                 }
237
238                 if (assigned_irq->host_irq)
239                         match->host_irq = assigned_irq->host_irq;
240                 else
241                         match->host_irq = match->dev->irq;
242                 match->guest_irq = assigned_irq->guest_irq;
243                 match->ack_notifier.gsi = assigned_irq->guest_irq;
244                 match->ack_notifier.irq_acked = kvm_assigned_dev_ack_irq;
245                 kvm_register_irq_ack_notifier(kvm, &match->ack_notifier);
246
247                 /* Even though this is PCI, we don't want to use shared
248                  * interrupts. Sharing host devices with guest-assigned devices
249                  * on the same interrupt line is not a happy situation: there
250                  * are going to be long delays in accepting, acking, etc.
251                  */
252                 if (request_irq(match->host_irq, kvm_assigned_dev_intr, 0,
253                                 "kvm_assigned_device", (void *)match)) {
254                         r = -EIO;
255                         goto out_release;
256                 }
257         }
258
259         match->irq_requested = true;
260         mutex_unlock(&kvm->lock);
261         return r;
262 out_release:
263         mutex_unlock(&kvm->lock);
264         kvm_free_assigned_device(kvm, match);
265         return r;
266 }
267
268 static int kvm_vm_ioctl_assign_device(struct kvm *kvm,
269                                       struct kvm_assigned_pci_dev *assigned_dev)
270 {
271         int r = 0;
272         struct kvm_assigned_dev_kernel *match;
273         struct pci_dev *dev;
274
275         mutex_lock(&kvm->lock);
276
277         match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
278                                       assigned_dev->assigned_dev_id);
279         if (match) {
280                 /* device already assigned */
281                 r = -EINVAL;
282                 goto out;
283         }
284
285         match = kzalloc(sizeof(struct kvm_assigned_dev_kernel), GFP_KERNEL);
286         if (match == NULL) {
287                 printk(KERN_INFO "%s: Couldn't allocate memory\n",
288                        __func__);
289                 r = -ENOMEM;
290                 goto out;
291         }
292         dev = pci_get_bus_and_slot(assigned_dev->busnr,
293                                    assigned_dev->devfn);
294         if (!dev) {
295                 printk(KERN_INFO "%s: host device not found\n", __func__);
296                 r = -EINVAL;
297                 goto out_free;
298         }
299         if (pci_enable_device(dev)) {
300                 printk(KERN_INFO "%s: Could not enable PCI device\n", __func__);
301                 r = -EBUSY;
302                 goto out_put;
303         }
304         r = pci_request_regions(dev, "kvm_assigned_device");
305         if (r) {
306                 printk(KERN_INFO "%s: Could not get access to device regions\n",
307                        __func__);
308                 goto out_disable;
309         }
310         match->assigned_dev_id = assigned_dev->assigned_dev_id;
311         match->host_busnr = assigned_dev->busnr;
312         match->host_devfn = assigned_dev->devfn;
313         match->dev = dev;
314
315         match->kvm = kvm;
316
317         list_add(&match->list, &kvm->arch.assigned_dev_head);
318
319         if (assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU) {
320                 r = kvm_iommu_map_guest(kvm, match);
321                 if (r)
322                         goto out_list_del;
323         }
324
325 out:
326         mutex_unlock(&kvm->lock);
327         return r;
328 out_list_del:
329         list_del(&match->list);
330         pci_release_regions(dev);
331 out_disable:
332         pci_disable_device(dev);
333 out_put:
334         pci_dev_put(dev);
335 out_free:
336         kfree(match);
337         mutex_unlock(&kvm->lock);
338         return r;
339 }
340
341 unsigned long segment_base(u16 selector)
342 {
343         struct descriptor_table gdt;
344         struct desc_struct *d;
345         unsigned long table_base;
346         unsigned long v;
347
348         if (selector == 0)
349                 return 0;
350
351         asm("sgdt %0" : "=m"(gdt));
352         table_base = gdt.base;
353
354         if (selector & 4) {           /* from ldt */
355                 u16 ldt_selector;
356
357                 asm("sldt %0" : "=g"(ldt_selector));
358                 table_base = segment_base(ldt_selector);
359         }
360         d = (struct desc_struct *)(table_base + (selector & ~7));
361         v = d->base0 | ((unsigned long)d->base1 << 16) |
362                 ((unsigned long)d->base2 << 24);
363 #ifdef CONFIG_X86_64
364         if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
365                 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
366 #endif
367         return v;
368 }
369 EXPORT_SYMBOL_GPL(segment_base);
370
371 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
372 {
373         if (irqchip_in_kernel(vcpu->kvm))
374                 return vcpu->arch.apic_base;
375         else
376                 return vcpu->arch.apic_base;
377 }
378 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
379
380 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
381 {
382         /* TODO: reserve bits check */
383         if (irqchip_in_kernel(vcpu->kvm))
384                 kvm_lapic_set_base(vcpu, data);
385         else
386                 vcpu->arch.apic_base = data;
387 }
388 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
389
390 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
391 {
392         WARN_ON(vcpu->arch.exception.pending);
393         vcpu->arch.exception.pending = true;
394         vcpu->arch.exception.has_error_code = false;
395         vcpu->arch.exception.nr = nr;
396 }
397 EXPORT_SYMBOL_GPL(kvm_queue_exception);
398
399 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, unsigned long addr,
400                            u32 error_code)
401 {
402         ++vcpu->stat.pf_guest;
403         if (vcpu->arch.exception.pending) {
404                 if (vcpu->arch.exception.nr == PF_VECTOR) {
405                         printk(KERN_DEBUG "kvm: inject_page_fault:"
406                                         " double fault 0x%lx\n", addr);
407                         vcpu->arch.exception.nr = DF_VECTOR;
408                         vcpu->arch.exception.error_code = 0;
409                 } else if (vcpu->arch.exception.nr == DF_VECTOR) {
410                         /* triple fault -> shutdown */
411                         set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
412                 }
413                 return;
414         }
415         vcpu->arch.cr2 = addr;
416         kvm_queue_exception_e(vcpu, PF_VECTOR, error_code);
417 }
418
419 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
420 {
421         vcpu->arch.nmi_pending = 1;
422 }
423 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
424
425 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
426 {
427         WARN_ON(vcpu->arch.exception.pending);
428         vcpu->arch.exception.pending = true;
429         vcpu->arch.exception.has_error_code = true;
430         vcpu->arch.exception.nr = nr;
431         vcpu->arch.exception.error_code = error_code;
432 }
433 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
434
435 static void __queue_exception(struct kvm_vcpu *vcpu)
436 {
437         kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
438                                      vcpu->arch.exception.has_error_code,
439                                      vcpu->arch.exception.error_code);
440 }
441
442 /*
443  * Load the pae pdptrs.  Return true is they are all valid.
444  */
445 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
446 {
447         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
448         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
449         int i;
450         int ret;
451         u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
452
453         ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
454                                   offset * sizeof(u64), sizeof(pdpte));
455         if (ret < 0) {
456                 ret = 0;
457                 goto out;
458         }
459         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
460                 if ((pdpte[i] & 1) && (pdpte[i] & 0xfffffff0000001e6ull)) {
461                         ret = 0;
462                         goto out;
463                 }
464         }
465         ret = 1;
466
467         memcpy(vcpu->arch.pdptrs, pdpte, sizeof(vcpu->arch.pdptrs));
468 out:
469
470         return ret;
471 }
472 EXPORT_SYMBOL_GPL(load_pdptrs);
473
474 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
475 {
476         u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
477         bool changed = true;
478         int r;
479
480         if (is_long_mode(vcpu) || !is_pae(vcpu))
481                 return false;
482
483         r = kvm_read_guest(vcpu->kvm, vcpu->arch.cr3 & ~31u, pdpte, sizeof(pdpte));
484         if (r < 0)
485                 goto out;
486         changed = memcmp(pdpte, vcpu->arch.pdptrs, sizeof(pdpte)) != 0;
487 out:
488
489         return changed;
490 }
491
492 void kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
493 {
494         if (cr0 & CR0_RESERVED_BITS) {
495                 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
496                        cr0, vcpu->arch.cr0);
497                 kvm_inject_gp(vcpu, 0);
498                 return;
499         }
500
501         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
502                 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
503                 kvm_inject_gp(vcpu, 0);
504                 return;
505         }
506
507         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
508                 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
509                        "and a clear PE flag\n");
510                 kvm_inject_gp(vcpu, 0);
511                 return;
512         }
513
514         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
515 #ifdef CONFIG_X86_64
516                 if ((vcpu->arch.shadow_efer & EFER_LME)) {
517                         int cs_db, cs_l;
518
519                         if (!is_pae(vcpu)) {
520                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
521                                        "in long mode while PAE is disabled\n");
522                                 kvm_inject_gp(vcpu, 0);
523                                 return;
524                         }
525                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
526                         if (cs_l) {
527                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
528                                        "in long mode while CS.L == 1\n");
529                                 kvm_inject_gp(vcpu, 0);
530                                 return;
531
532                         }
533                 } else
534 #endif
535                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
536                         printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
537                                "reserved bits\n");
538                         kvm_inject_gp(vcpu, 0);
539                         return;
540                 }
541
542         }
543
544         kvm_x86_ops->set_cr0(vcpu, cr0);
545         vcpu->arch.cr0 = cr0;
546
547         kvm_mmu_reset_context(vcpu);
548         return;
549 }
550 EXPORT_SYMBOL_GPL(kvm_set_cr0);
551
552 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
553 {
554         kvm_set_cr0(vcpu, (vcpu->arch.cr0 & ~0x0ful) | (msw & 0x0f));
555         KVMTRACE_1D(LMSW, vcpu,
556                     (u32)((vcpu->arch.cr0 & ~0x0ful) | (msw & 0x0f)),
557                     handler);
558 }
559 EXPORT_SYMBOL_GPL(kvm_lmsw);
560
561 void kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
562 {
563         if (cr4 & CR4_RESERVED_BITS) {
564                 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
565                 kvm_inject_gp(vcpu, 0);
566                 return;
567         }
568
569         if (is_long_mode(vcpu)) {
570                 if (!(cr4 & X86_CR4_PAE)) {
571                         printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
572                                "in long mode\n");
573                         kvm_inject_gp(vcpu, 0);
574                         return;
575                 }
576         } else if (is_paging(vcpu) && !is_pae(vcpu) && (cr4 & X86_CR4_PAE)
577                    && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
578                 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
579                 kvm_inject_gp(vcpu, 0);
580                 return;
581         }
582
583         if (cr4 & X86_CR4_VMXE) {
584                 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
585                 kvm_inject_gp(vcpu, 0);
586                 return;
587         }
588         kvm_x86_ops->set_cr4(vcpu, cr4);
589         vcpu->arch.cr4 = cr4;
590         kvm_mmu_reset_context(vcpu);
591 }
592 EXPORT_SYMBOL_GPL(kvm_set_cr4);
593
594 void kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
595 {
596         if (cr3 == vcpu->arch.cr3 && !pdptrs_changed(vcpu)) {
597                 kvm_mmu_sync_roots(vcpu);
598                 kvm_mmu_flush_tlb(vcpu);
599                 return;
600         }
601
602         if (is_long_mode(vcpu)) {
603                 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
604                         printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
605                         kvm_inject_gp(vcpu, 0);
606                         return;
607                 }
608         } else {
609                 if (is_pae(vcpu)) {
610                         if (cr3 & CR3_PAE_RESERVED_BITS) {
611                                 printk(KERN_DEBUG
612                                        "set_cr3: #GP, reserved bits\n");
613                                 kvm_inject_gp(vcpu, 0);
614                                 return;
615                         }
616                         if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
617                                 printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
618                                        "reserved bits\n");
619                                 kvm_inject_gp(vcpu, 0);
620                                 return;
621                         }
622                 }
623                 /*
624                  * We don't check reserved bits in nonpae mode, because
625                  * this isn't enforced, and VMware depends on this.
626                  */
627         }
628
629         /*
630          * Does the new cr3 value map to physical memory? (Note, we
631          * catch an invalid cr3 even in real-mode, because it would
632          * cause trouble later on when we turn on paging anyway.)
633          *
634          * A real CPU would silently accept an invalid cr3 and would
635          * attempt to use it - with largely undefined (and often hard
636          * to debug) behavior on the guest side.
637          */
638         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
639                 kvm_inject_gp(vcpu, 0);
640         else {
641                 vcpu->arch.cr3 = cr3;
642                 vcpu->arch.mmu.new_cr3(vcpu);
643         }
644 }
645 EXPORT_SYMBOL_GPL(kvm_set_cr3);
646
647 void kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
648 {
649         if (cr8 & CR8_RESERVED_BITS) {
650                 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
651                 kvm_inject_gp(vcpu, 0);
652                 return;
653         }
654         if (irqchip_in_kernel(vcpu->kvm))
655                 kvm_lapic_set_tpr(vcpu, cr8);
656         else
657                 vcpu->arch.cr8 = cr8;
658 }
659 EXPORT_SYMBOL_GPL(kvm_set_cr8);
660
661 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
662 {
663         if (irqchip_in_kernel(vcpu->kvm))
664                 return kvm_lapic_get_cr8(vcpu);
665         else
666                 return vcpu->arch.cr8;
667 }
668 EXPORT_SYMBOL_GPL(kvm_get_cr8);
669
670 /*
671  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
672  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
673  *
674  * This list is modified at module load time to reflect the
675  * capabilities of the host cpu.
676  */
677 static u32 msrs_to_save[] = {
678         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
679         MSR_K6_STAR,
680 #ifdef CONFIG_X86_64
681         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
682 #endif
683         MSR_IA32_TIME_STAMP_COUNTER, MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
684         MSR_IA32_PERF_STATUS,
685 };
686
687 static unsigned num_msrs_to_save;
688
689 static u32 emulated_msrs[] = {
690         MSR_IA32_MISC_ENABLE,
691 };
692
693 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
694 {
695         if (efer & efer_reserved_bits) {
696                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
697                        efer);
698                 kvm_inject_gp(vcpu, 0);
699                 return;
700         }
701
702         if (is_paging(vcpu)
703             && (vcpu->arch.shadow_efer & EFER_LME) != (efer & EFER_LME)) {
704                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
705                 kvm_inject_gp(vcpu, 0);
706                 return;
707         }
708
709         kvm_x86_ops->set_efer(vcpu, efer);
710
711         efer &= ~EFER_LMA;
712         efer |= vcpu->arch.shadow_efer & EFER_LMA;
713
714         vcpu->arch.shadow_efer = efer;
715 }
716
717 void kvm_enable_efer_bits(u64 mask)
718 {
719        efer_reserved_bits &= ~mask;
720 }
721 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
722
723
724 /*
725  * Writes msr value into into the appropriate "register".
726  * Returns 0 on success, non-0 otherwise.
727  * Assumes vcpu_load() was already called.
728  */
729 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
730 {
731         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
732 }
733
734 /*
735  * Adapt set_msr() to msr_io()'s calling convention
736  */
737 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
738 {
739         return kvm_set_msr(vcpu, index, *data);
740 }
741
742 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
743 {
744         static int version;
745         struct pvclock_wall_clock wc;
746         struct timespec now, sys, boot;
747
748         if (!wall_clock)
749                 return;
750
751         version++;
752
753         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
754
755         /*
756          * The guest calculates current wall clock time by adding
757          * system time (updated by kvm_write_guest_time below) to the
758          * wall clock specified here.  guest system time equals host
759          * system time for us, thus we must fill in host boot time here.
760          */
761         now = current_kernel_time();
762         ktime_get_ts(&sys);
763         boot = ns_to_timespec(timespec_to_ns(&now) - timespec_to_ns(&sys));
764
765         wc.sec = boot.tv_sec;
766         wc.nsec = boot.tv_nsec;
767         wc.version = version;
768
769         kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
770
771         version++;
772         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
773 }
774
775 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
776 {
777         uint32_t quotient, remainder;
778
779         /* Don't try to replace with do_div(), this one calculates
780          * "(dividend << 32) / divisor" */
781         __asm__ ( "divl %4"
782                   : "=a" (quotient), "=d" (remainder)
783                   : "0" (0), "1" (dividend), "r" (divisor) );
784         return quotient;
785 }
786
787 static void kvm_set_time_scale(uint32_t tsc_khz, struct pvclock_vcpu_time_info *hv_clock)
788 {
789         uint64_t nsecs = 1000000000LL;
790         int32_t  shift = 0;
791         uint64_t tps64;
792         uint32_t tps32;
793
794         tps64 = tsc_khz * 1000LL;
795         while (tps64 > nsecs*2) {
796                 tps64 >>= 1;
797                 shift--;
798         }
799
800         tps32 = (uint32_t)tps64;
801         while (tps32 <= (uint32_t)nsecs) {
802                 tps32 <<= 1;
803                 shift++;
804         }
805
806         hv_clock->tsc_shift = shift;
807         hv_clock->tsc_to_system_mul = div_frac(nsecs, tps32);
808
809         pr_debug("%s: tsc_khz %u, tsc_shift %d, tsc_mul %u\n",
810                  __FUNCTION__, tsc_khz, hv_clock->tsc_shift,
811                  hv_clock->tsc_to_system_mul);
812 }
813
814 static void kvm_write_guest_time(struct kvm_vcpu *v)
815 {
816         struct timespec ts;
817         unsigned long flags;
818         struct kvm_vcpu_arch *vcpu = &v->arch;
819         void *shared_kaddr;
820
821         if ((!vcpu->time_page))
822                 return;
823
824         if (unlikely(vcpu->hv_clock_tsc_khz != tsc_khz)) {
825                 kvm_set_time_scale(tsc_khz, &vcpu->hv_clock);
826                 vcpu->hv_clock_tsc_khz = tsc_khz;
827         }
828
829         /* Keep irq disabled to prevent changes to the clock */
830         local_irq_save(flags);
831         kvm_get_msr(v, MSR_IA32_TIME_STAMP_COUNTER,
832                           &vcpu->hv_clock.tsc_timestamp);
833         ktime_get_ts(&ts);
834         local_irq_restore(flags);
835
836         /* With all the info we got, fill in the values */
837
838         vcpu->hv_clock.system_time = ts.tv_nsec +
839                                      (NSEC_PER_SEC * (u64)ts.tv_sec);
840         /*
841          * The interface expects us to write an even number signaling that the
842          * update is finished. Since the guest won't see the intermediate
843          * state, we just increase by 2 at the end.
844          */
845         vcpu->hv_clock.version += 2;
846
847         shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
848
849         memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
850                sizeof(vcpu->hv_clock));
851
852         kunmap_atomic(shared_kaddr, KM_USER0);
853
854         mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
855 }
856
857 static bool msr_mtrr_valid(unsigned msr)
858 {
859         switch (msr) {
860         case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
861         case MSR_MTRRfix64K_00000:
862         case MSR_MTRRfix16K_80000:
863         case MSR_MTRRfix16K_A0000:
864         case MSR_MTRRfix4K_C0000:
865         case MSR_MTRRfix4K_C8000:
866         case MSR_MTRRfix4K_D0000:
867         case MSR_MTRRfix4K_D8000:
868         case MSR_MTRRfix4K_E0000:
869         case MSR_MTRRfix4K_E8000:
870         case MSR_MTRRfix4K_F0000:
871         case MSR_MTRRfix4K_F8000:
872         case MSR_MTRRdefType:
873         case MSR_IA32_CR_PAT:
874                 return true;
875         case 0x2f8:
876                 return true;
877         }
878         return false;
879 }
880
881 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
882 {
883         if (!msr_mtrr_valid(msr))
884                 return 1;
885
886         vcpu->arch.mtrr[msr - 0x200] = data;
887         return 0;
888 }
889
890 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
891 {
892         switch (msr) {
893         case MSR_EFER:
894                 set_efer(vcpu, data);
895                 break;
896         case MSR_IA32_MC0_STATUS:
897                 pr_unimpl(vcpu, "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
898                        __func__, data);
899                 break;
900         case MSR_IA32_MCG_STATUS:
901                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
902                         __func__, data);
903                 break;
904         case MSR_IA32_MCG_CTL:
905                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_CTL 0x%llx, nop\n",
906                         __func__, data);
907                 break;
908         case MSR_IA32_DEBUGCTLMSR:
909                 if (!data) {
910                         /* We support the non-activated case already */
911                         break;
912                 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
913                         /* Values other than LBR and BTF are vendor-specific,
914                            thus reserved and should throw a #GP */
915                         return 1;
916                 }
917                 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
918                         __func__, data);
919                 break;
920         case MSR_IA32_UCODE_REV:
921         case MSR_IA32_UCODE_WRITE:
922                 break;
923         case 0x200 ... 0x2ff:
924                 return set_msr_mtrr(vcpu, msr, data);
925         case MSR_IA32_APICBASE:
926                 kvm_set_apic_base(vcpu, data);
927                 break;
928         case MSR_IA32_MISC_ENABLE:
929                 vcpu->arch.ia32_misc_enable_msr = data;
930                 break;
931         case MSR_KVM_WALL_CLOCK:
932                 vcpu->kvm->arch.wall_clock = data;
933                 kvm_write_wall_clock(vcpu->kvm, data);
934                 break;
935         case MSR_KVM_SYSTEM_TIME: {
936                 if (vcpu->arch.time_page) {
937                         kvm_release_page_dirty(vcpu->arch.time_page);
938                         vcpu->arch.time_page = NULL;
939                 }
940
941                 vcpu->arch.time = data;
942
943                 /* we verify if the enable bit is set... */
944                 if (!(data & 1))
945                         break;
946
947                 /* ...but clean it before doing the actual write */
948                 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
949
950                 vcpu->arch.time_page =
951                                 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
952
953                 if (is_error_page(vcpu->arch.time_page)) {
954                         kvm_release_page_clean(vcpu->arch.time_page);
955                         vcpu->arch.time_page = NULL;
956                 }
957
958                 kvm_write_guest_time(vcpu);
959                 break;
960         }
961         default:
962                 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n", msr, data);
963                 return 1;
964         }
965         return 0;
966 }
967 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
968
969
970 /*
971  * Reads an msr value (of 'msr_index') into 'pdata'.
972  * Returns 0 on success, non-0 otherwise.
973  * Assumes vcpu_load() was already called.
974  */
975 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
976 {
977         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
978 }
979
980 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
981 {
982         if (!msr_mtrr_valid(msr))
983                 return 1;
984
985         *pdata = vcpu->arch.mtrr[msr - 0x200];
986         return 0;
987 }
988
989 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
990 {
991         u64 data;
992
993         switch (msr) {
994         case 0xc0010010: /* SYSCFG */
995         case 0xc0010015: /* HWCR */
996         case MSR_IA32_PLATFORM_ID:
997         case MSR_IA32_P5_MC_ADDR:
998         case MSR_IA32_P5_MC_TYPE:
999         case MSR_IA32_MC0_CTL:
1000         case MSR_IA32_MCG_STATUS:
1001         case MSR_IA32_MCG_CAP:
1002         case MSR_IA32_MCG_CTL:
1003         case MSR_IA32_MC0_MISC:
1004         case MSR_IA32_MC0_MISC+4:
1005         case MSR_IA32_MC0_MISC+8:
1006         case MSR_IA32_MC0_MISC+12:
1007         case MSR_IA32_MC0_MISC+16:
1008         case MSR_IA32_MC0_MISC+20:
1009         case MSR_IA32_UCODE_REV:
1010         case MSR_IA32_EBL_CR_POWERON:
1011         case MSR_IA32_DEBUGCTLMSR:
1012         case MSR_IA32_LASTBRANCHFROMIP:
1013         case MSR_IA32_LASTBRANCHTOIP:
1014         case MSR_IA32_LASTINTFROMIP:
1015         case MSR_IA32_LASTINTTOIP:
1016                 data = 0;
1017                 break;
1018         case MSR_MTRRcap:
1019                 data = 0x500 | KVM_NR_VAR_MTRR;
1020                 break;
1021         case 0x200 ... 0x2ff:
1022                 return get_msr_mtrr(vcpu, msr, pdata);
1023         case 0xcd: /* fsb frequency */
1024                 data = 3;
1025                 break;
1026         case MSR_IA32_APICBASE:
1027                 data = kvm_get_apic_base(vcpu);
1028                 break;
1029         case MSR_IA32_MISC_ENABLE:
1030                 data = vcpu->arch.ia32_misc_enable_msr;
1031                 break;
1032         case MSR_IA32_PERF_STATUS:
1033                 /* TSC increment by tick */
1034                 data = 1000ULL;
1035                 /* CPU multiplier */
1036                 data |= (((uint64_t)4ULL) << 40);
1037                 break;
1038         case MSR_EFER:
1039                 data = vcpu->arch.shadow_efer;
1040                 break;
1041         case MSR_KVM_WALL_CLOCK:
1042                 data = vcpu->kvm->arch.wall_clock;
1043                 break;
1044         case MSR_KVM_SYSTEM_TIME:
1045                 data = vcpu->arch.time;
1046                 break;
1047         default:
1048                 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1049                 return 1;
1050         }
1051         *pdata = data;
1052         return 0;
1053 }
1054 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1055
1056 /*
1057  * Read or write a bunch of msrs. All parameters are kernel addresses.
1058  *
1059  * @return number of msrs set successfully.
1060  */
1061 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
1062                     struct kvm_msr_entry *entries,
1063                     int (*do_msr)(struct kvm_vcpu *vcpu,
1064                                   unsigned index, u64 *data))
1065 {
1066         int i;
1067
1068         vcpu_load(vcpu);
1069
1070         down_read(&vcpu->kvm->slots_lock);
1071         for (i = 0; i < msrs->nmsrs; ++i)
1072                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1073                         break;
1074         up_read(&vcpu->kvm->slots_lock);
1075
1076         vcpu_put(vcpu);
1077
1078         return i;
1079 }
1080
1081 /*
1082  * Read or write a bunch of msrs. Parameters are user addresses.
1083  *
1084  * @return number of msrs set successfully.
1085  */
1086 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
1087                   int (*do_msr)(struct kvm_vcpu *vcpu,
1088                                 unsigned index, u64 *data),
1089                   int writeback)
1090 {
1091         struct kvm_msrs msrs;
1092         struct kvm_msr_entry *entries;
1093         int r, n;
1094         unsigned size;
1095
1096         r = -EFAULT;
1097         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
1098                 goto out;
1099
1100         r = -E2BIG;
1101         if (msrs.nmsrs >= MAX_IO_MSRS)
1102                 goto out;
1103
1104         r = -ENOMEM;
1105         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
1106         entries = vmalloc(size);
1107         if (!entries)
1108                 goto out;
1109
1110         r = -EFAULT;
1111         if (copy_from_user(entries, user_msrs->entries, size))
1112                 goto out_free;
1113
1114         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
1115         if (r < 0)
1116                 goto out_free;
1117
1118         r = -EFAULT;
1119         if (writeback && copy_to_user(user_msrs->entries, entries, size))
1120                 goto out_free;
1121
1122         r = n;
1123
1124 out_free:
1125         vfree(entries);
1126 out:
1127         return r;
1128 }
1129
1130 int kvm_dev_ioctl_check_extension(long ext)
1131 {
1132         int r;
1133
1134         switch (ext) {
1135         case KVM_CAP_IRQCHIP:
1136         case KVM_CAP_HLT:
1137         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
1138         case KVM_CAP_USER_MEMORY:
1139         case KVM_CAP_SET_TSS_ADDR:
1140         case KVM_CAP_EXT_CPUID:
1141         case KVM_CAP_CLOCKSOURCE:
1142         case KVM_CAP_PIT:
1143         case KVM_CAP_NOP_IO_DELAY:
1144         case KVM_CAP_MP_STATE:
1145         case KVM_CAP_SYNC_MMU:
1146                 r = 1;
1147                 break;
1148         case KVM_CAP_COALESCED_MMIO:
1149                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
1150                 break;
1151         case KVM_CAP_VAPIC:
1152                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
1153                 break;
1154         case KVM_CAP_NR_VCPUS:
1155                 r = KVM_MAX_VCPUS;
1156                 break;
1157         case KVM_CAP_NR_MEMSLOTS:
1158                 r = KVM_MEMORY_SLOTS;
1159                 break;
1160         case KVM_CAP_PV_MMU:
1161                 r = !tdp_enabled;
1162                 break;
1163         case KVM_CAP_IOMMU:
1164                 r = intel_iommu_found();
1165                 break;
1166         default:
1167                 r = 0;
1168                 break;
1169         }
1170         return r;
1171
1172 }
1173
1174 long kvm_arch_dev_ioctl(struct file *filp,
1175                         unsigned int ioctl, unsigned long arg)
1176 {
1177         void __user *argp = (void __user *)arg;
1178         long r;
1179
1180         switch (ioctl) {
1181         case KVM_GET_MSR_INDEX_LIST: {
1182                 struct kvm_msr_list __user *user_msr_list = argp;
1183                 struct kvm_msr_list msr_list;
1184                 unsigned n;
1185
1186                 r = -EFAULT;
1187                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
1188                         goto out;
1189                 n = msr_list.nmsrs;
1190                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
1191                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
1192                         goto out;
1193                 r = -E2BIG;
1194                 if (n < num_msrs_to_save)
1195                         goto out;
1196                 r = -EFAULT;
1197                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
1198                                  num_msrs_to_save * sizeof(u32)))
1199                         goto out;
1200                 if (copy_to_user(user_msr_list->indices
1201                                  + num_msrs_to_save * sizeof(u32),
1202                                  &emulated_msrs,
1203                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
1204                         goto out;
1205                 r = 0;
1206                 break;
1207         }
1208         case KVM_GET_SUPPORTED_CPUID: {
1209                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1210                 struct kvm_cpuid2 cpuid;
1211
1212                 r = -EFAULT;
1213                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1214                         goto out;
1215                 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
1216                         cpuid_arg->entries);
1217                 if (r)
1218                         goto out;
1219
1220                 r = -EFAULT;
1221                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1222                         goto out;
1223                 r = 0;
1224                 break;
1225         }
1226         default:
1227                 r = -EINVAL;
1228         }
1229 out:
1230         return r;
1231 }
1232
1233 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1234 {
1235         kvm_x86_ops->vcpu_load(vcpu, cpu);
1236         kvm_write_guest_time(vcpu);
1237 }
1238
1239 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
1240 {
1241         kvm_x86_ops->vcpu_put(vcpu);
1242         kvm_put_guest_fpu(vcpu);
1243 }
1244
1245 static int is_efer_nx(void)
1246 {
1247         u64 efer;
1248
1249         rdmsrl(MSR_EFER, efer);
1250         return efer & EFER_NX;
1251 }
1252
1253 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
1254 {
1255         int i;
1256         struct kvm_cpuid_entry2 *e, *entry;
1257
1258         entry = NULL;
1259         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
1260                 e = &vcpu->arch.cpuid_entries[i];
1261                 if (e->function == 0x80000001) {
1262                         entry = e;
1263                         break;
1264                 }
1265         }
1266         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
1267                 entry->edx &= ~(1 << 20);
1268                 printk(KERN_INFO "kvm: guest NX capability removed\n");
1269         }
1270 }
1271
1272 /* when an old userspace process fills a new kernel module */
1273 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
1274                                     struct kvm_cpuid *cpuid,
1275                                     struct kvm_cpuid_entry __user *entries)
1276 {
1277         int r, i;
1278         struct kvm_cpuid_entry *cpuid_entries;
1279
1280         r = -E2BIG;
1281         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1282                 goto out;
1283         r = -ENOMEM;
1284         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
1285         if (!cpuid_entries)
1286                 goto out;
1287         r = -EFAULT;
1288         if (copy_from_user(cpuid_entries, entries,
1289                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
1290                 goto out_free;
1291         for (i = 0; i < cpuid->nent; i++) {
1292                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
1293                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
1294                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
1295                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
1296                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
1297                 vcpu->arch.cpuid_entries[i].index = 0;
1298                 vcpu->arch.cpuid_entries[i].flags = 0;
1299                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
1300                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
1301                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
1302         }
1303         vcpu->arch.cpuid_nent = cpuid->nent;
1304         cpuid_fix_nx_cap(vcpu);
1305         r = 0;
1306
1307 out_free:
1308         vfree(cpuid_entries);
1309 out:
1310         return r;
1311 }
1312
1313 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
1314                                     struct kvm_cpuid2 *cpuid,
1315                                     struct kvm_cpuid_entry2 __user *entries)
1316 {
1317         int r;
1318
1319         r = -E2BIG;
1320         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1321                 goto out;
1322         r = -EFAULT;
1323         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
1324                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
1325                 goto out;
1326         vcpu->arch.cpuid_nent = cpuid->nent;
1327         return 0;
1328
1329 out:
1330         return r;
1331 }
1332
1333 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
1334                                     struct kvm_cpuid2 *cpuid,
1335                                     struct kvm_cpuid_entry2 __user *entries)
1336 {
1337         int r;
1338
1339         r = -E2BIG;
1340         if (cpuid->nent < vcpu->arch.cpuid_nent)
1341                 goto out;
1342         r = -EFAULT;
1343         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
1344                            vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
1345                 goto out;
1346         return 0;
1347
1348 out:
1349         cpuid->nent = vcpu->arch.cpuid_nent;
1350         return r;
1351 }
1352
1353 static inline u32 bit(int bitno)
1354 {
1355         return 1 << (bitno & 31);
1356 }
1357
1358 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1359                           u32 index)
1360 {
1361         entry->function = function;
1362         entry->index = index;
1363         cpuid_count(entry->function, entry->index,
1364                 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1365         entry->flags = 0;
1366 }
1367
1368 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1369                          u32 index, int *nent, int maxnent)
1370 {
1371         const u32 kvm_supported_word0_x86_features = bit(X86_FEATURE_FPU) |
1372                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1373                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1374                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1375                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1376                 bit(X86_FEATURE_SEP) | bit(X86_FEATURE_PGE) |
1377                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1378                 bit(X86_FEATURE_CLFLSH) | bit(X86_FEATURE_MMX) |
1379                 bit(X86_FEATURE_FXSR) | bit(X86_FEATURE_XMM) |
1380                 bit(X86_FEATURE_XMM2) | bit(X86_FEATURE_SELFSNOOP);
1381         const u32 kvm_supported_word1_x86_features = bit(X86_FEATURE_FPU) |
1382                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1383                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1384                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1385                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1386                 bit(X86_FEATURE_PGE) |
1387                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1388                 bit(X86_FEATURE_MMX) | bit(X86_FEATURE_FXSR) |
1389                 bit(X86_FEATURE_SYSCALL) |
1390                 (bit(X86_FEATURE_NX) && is_efer_nx()) |
1391 #ifdef CONFIG_X86_64
1392                 bit(X86_FEATURE_LM) |
1393 #endif
1394                 bit(X86_FEATURE_MMXEXT) |
1395                 bit(X86_FEATURE_3DNOWEXT) |
1396                 bit(X86_FEATURE_3DNOW);
1397         const u32 kvm_supported_word3_x86_features =
1398                 bit(X86_FEATURE_XMM3) | bit(X86_FEATURE_CX16);
1399         const u32 kvm_supported_word6_x86_features =
1400                 bit(X86_FEATURE_LAHF_LM) | bit(X86_FEATURE_CMP_LEGACY);
1401
1402         /* all func 2 cpuid_count() should be called on the same cpu */
1403         get_cpu();
1404         do_cpuid_1_ent(entry, function, index);
1405         ++*nent;
1406
1407         switch (function) {
1408         case 0:
1409                 entry->eax = min(entry->eax, (u32)0xb);
1410                 break;
1411         case 1:
1412                 entry->edx &= kvm_supported_word0_x86_features;
1413                 entry->ecx &= kvm_supported_word3_x86_features;
1414                 break;
1415         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
1416          * may return different values. This forces us to get_cpu() before
1417          * issuing the first command, and also to emulate this annoying behavior
1418          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
1419         case 2: {
1420                 int t, times = entry->eax & 0xff;
1421
1422                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1423                 for (t = 1; t < times && *nent < maxnent; ++t) {
1424                         do_cpuid_1_ent(&entry[t], function, 0);
1425                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1426                         ++*nent;
1427                 }
1428                 break;
1429         }
1430         /* function 4 and 0xb have additional index. */
1431         case 4: {
1432                 int i, cache_type;
1433
1434                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1435                 /* read more entries until cache_type is zero */
1436                 for (i = 1; *nent < maxnent; ++i) {
1437                         cache_type = entry[i - 1].eax & 0x1f;
1438                         if (!cache_type)
1439                                 break;
1440                         do_cpuid_1_ent(&entry[i], function, i);
1441                         entry[i].flags |=
1442                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1443                         ++*nent;
1444                 }
1445                 break;
1446         }
1447         case 0xb: {
1448                 int i, level_type;
1449
1450                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1451                 /* read more entries until level_type is zero */
1452                 for (i = 1; *nent < maxnent; ++i) {
1453                         level_type = entry[i - 1].ecx & 0xff;
1454                         if (!level_type)
1455                                 break;
1456                         do_cpuid_1_ent(&entry[i], function, i);
1457                         entry[i].flags |=
1458                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1459                         ++*nent;
1460                 }
1461                 break;
1462         }
1463         case 0x80000000:
1464                 entry->eax = min(entry->eax, 0x8000001a);
1465                 break;
1466         case 0x80000001:
1467                 entry->edx &= kvm_supported_word1_x86_features;
1468                 entry->ecx &= kvm_supported_word6_x86_features;
1469                 break;
1470         }
1471         put_cpu();
1472 }
1473
1474 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
1475                                     struct kvm_cpuid_entry2 __user *entries)
1476 {
1477         struct kvm_cpuid_entry2 *cpuid_entries;
1478         int limit, nent = 0, r = -E2BIG;
1479         u32 func;
1480
1481         if (cpuid->nent < 1)
1482                 goto out;
1483         r = -ENOMEM;
1484         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
1485         if (!cpuid_entries)
1486                 goto out;
1487
1488         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
1489         limit = cpuid_entries[0].eax;
1490         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
1491                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1492                                 &nent, cpuid->nent);
1493         r = -E2BIG;
1494         if (nent >= cpuid->nent)
1495                 goto out_free;
1496
1497         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1498         limit = cpuid_entries[nent - 1].eax;
1499         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1500                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1501                                &nent, cpuid->nent);
1502         r = -EFAULT;
1503         if (copy_to_user(entries, cpuid_entries,
1504                         nent * sizeof(struct kvm_cpuid_entry2)))
1505                 goto out_free;
1506         cpuid->nent = nent;
1507         r = 0;
1508
1509 out_free:
1510         vfree(cpuid_entries);
1511 out:
1512         return r;
1513 }
1514
1515 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1516                                     struct kvm_lapic_state *s)
1517 {
1518         vcpu_load(vcpu);
1519         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1520         vcpu_put(vcpu);
1521
1522         return 0;
1523 }
1524
1525 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1526                                     struct kvm_lapic_state *s)
1527 {
1528         vcpu_load(vcpu);
1529         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1530         kvm_apic_post_state_restore(vcpu);
1531         vcpu_put(vcpu);
1532
1533         return 0;
1534 }
1535
1536 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1537                                     struct kvm_interrupt *irq)
1538 {
1539         if (irq->irq < 0 || irq->irq >= 256)
1540                 return -EINVAL;
1541         if (irqchip_in_kernel(vcpu->kvm))
1542                 return -ENXIO;
1543         vcpu_load(vcpu);
1544
1545         set_bit(irq->irq, vcpu->arch.irq_pending);
1546         set_bit(irq->irq / BITS_PER_LONG, &vcpu->arch.irq_summary);
1547
1548         vcpu_put(vcpu);
1549
1550         return 0;
1551 }
1552
1553 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
1554                                            struct kvm_tpr_access_ctl *tac)
1555 {
1556         if (tac->flags)
1557                 return -EINVAL;
1558         vcpu->arch.tpr_access_reporting = !!tac->enabled;
1559         return 0;
1560 }
1561
1562 long kvm_arch_vcpu_ioctl(struct file *filp,
1563                          unsigned int ioctl, unsigned long arg)
1564 {
1565         struct kvm_vcpu *vcpu = filp->private_data;
1566         void __user *argp = (void __user *)arg;
1567         int r;
1568         struct kvm_lapic_state *lapic = NULL;
1569
1570         switch (ioctl) {
1571         case KVM_GET_LAPIC: {
1572                 lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
1573
1574                 r = -ENOMEM;
1575                 if (!lapic)
1576                         goto out;
1577                 r = kvm_vcpu_ioctl_get_lapic(vcpu, lapic);
1578                 if (r)
1579                         goto out;
1580                 r = -EFAULT;
1581                 if (copy_to_user(argp, lapic, sizeof(struct kvm_lapic_state)))
1582                         goto out;
1583                 r = 0;
1584                 break;
1585         }
1586         case KVM_SET_LAPIC: {
1587                 lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
1588                 r = -ENOMEM;
1589                 if (!lapic)
1590                         goto out;
1591                 r = -EFAULT;
1592                 if (copy_from_user(lapic, argp, sizeof(struct kvm_lapic_state)))
1593                         goto out;
1594                 r = kvm_vcpu_ioctl_set_lapic(vcpu, lapic);
1595                 if (r)
1596                         goto out;
1597                 r = 0;
1598                 break;
1599         }
1600         case KVM_INTERRUPT: {
1601                 struct kvm_interrupt irq;
1602
1603                 r = -EFAULT;
1604                 if (copy_from_user(&irq, argp, sizeof irq))
1605                         goto out;
1606                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1607                 if (r)
1608                         goto out;
1609                 r = 0;
1610                 break;
1611         }
1612         case KVM_SET_CPUID: {
1613                 struct kvm_cpuid __user *cpuid_arg = argp;
1614                 struct kvm_cpuid cpuid;
1615
1616                 r = -EFAULT;
1617                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1618                         goto out;
1619                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1620                 if (r)
1621                         goto out;
1622                 break;
1623         }
1624         case KVM_SET_CPUID2: {
1625                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1626                 struct kvm_cpuid2 cpuid;
1627
1628                 r = -EFAULT;
1629                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1630                         goto out;
1631                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1632                                 cpuid_arg->entries);
1633                 if (r)
1634                         goto out;
1635                 break;
1636         }
1637         case KVM_GET_CPUID2: {
1638                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1639                 struct kvm_cpuid2 cpuid;
1640
1641                 r = -EFAULT;
1642                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1643                         goto out;
1644                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1645                                 cpuid_arg->entries);
1646                 if (r)
1647                         goto out;
1648                 r = -EFAULT;
1649                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1650                         goto out;
1651                 r = 0;
1652                 break;
1653         }
1654         case KVM_GET_MSRS:
1655                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1656                 break;
1657         case KVM_SET_MSRS:
1658                 r = msr_io(vcpu, argp, do_set_msr, 0);
1659                 break;
1660         case KVM_TPR_ACCESS_REPORTING: {
1661                 struct kvm_tpr_access_ctl tac;
1662
1663                 r = -EFAULT;
1664                 if (copy_from_user(&tac, argp, sizeof tac))
1665                         goto out;
1666                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
1667                 if (r)
1668                         goto out;
1669                 r = -EFAULT;
1670                 if (copy_to_user(argp, &tac, sizeof tac))
1671                         goto out;
1672                 r = 0;
1673                 break;
1674         };
1675         case KVM_SET_VAPIC_ADDR: {
1676                 struct kvm_vapic_addr va;
1677
1678                 r = -EINVAL;
1679                 if (!irqchip_in_kernel(vcpu->kvm))
1680                         goto out;
1681                 r = -EFAULT;
1682                 if (copy_from_user(&va, argp, sizeof va))
1683                         goto out;
1684                 r = 0;
1685                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
1686                 break;
1687         }
1688         default:
1689                 r = -EINVAL;
1690         }
1691 out:
1692         if (lapic)
1693                 kfree(lapic);
1694         return r;
1695 }
1696
1697 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1698 {
1699         int ret;
1700
1701         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1702                 return -1;
1703         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1704         return ret;
1705 }
1706
1707 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1708                                           u32 kvm_nr_mmu_pages)
1709 {
1710         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1711                 return -EINVAL;
1712
1713         down_write(&kvm->slots_lock);
1714
1715         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1716         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1717
1718         up_write(&kvm->slots_lock);
1719         return 0;
1720 }
1721
1722 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1723 {
1724         return kvm->arch.n_alloc_mmu_pages;
1725 }
1726
1727 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1728 {
1729         int i;
1730         struct kvm_mem_alias *alias;
1731
1732         for (i = 0; i < kvm->arch.naliases; ++i) {
1733                 alias = &kvm->arch.aliases[i];
1734                 if (gfn >= alias->base_gfn
1735                     && gfn < alias->base_gfn + alias->npages)
1736                         return alias->target_gfn + gfn - alias->base_gfn;
1737         }
1738         return gfn;
1739 }
1740
1741 /*
1742  * Set a new alias region.  Aliases map a portion of physical memory into
1743  * another portion.  This is useful for memory windows, for example the PC
1744  * VGA region.
1745  */
1746 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1747                                          struct kvm_memory_alias *alias)
1748 {
1749         int r, n;
1750         struct kvm_mem_alias *p;
1751
1752         r = -EINVAL;
1753         /* General sanity checks */
1754         if (alias->memory_size & (PAGE_SIZE - 1))
1755                 goto out;
1756         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1757                 goto out;
1758         if (alias->slot >= KVM_ALIAS_SLOTS)
1759                 goto out;
1760         if (alias->guest_phys_addr + alias->memory_size
1761             < alias->guest_phys_addr)
1762                 goto out;
1763         if (alias->target_phys_addr + alias->memory_size
1764             < alias->target_phys_addr)
1765                 goto out;
1766
1767         down_write(&kvm->slots_lock);
1768         spin_lock(&kvm->mmu_lock);
1769
1770         p = &kvm->arch.aliases[alias->slot];
1771         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1772         p->npages = alias->memory_size >> PAGE_SHIFT;
1773         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1774
1775         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1776                 if (kvm->arch.aliases[n - 1].npages)
1777                         break;
1778         kvm->arch.naliases = n;
1779
1780         spin_unlock(&kvm->mmu_lock);
1781         kvm_mmu_zap_all(kvm);
1782
1783         up_write(&kvm->slots_lock);
1784
1785         return 0;
1786
1787 out:
1788         return r;
1789 }
1790
1791 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1792 {
1793         int r;
1794
1795         r = 0;
1796         switch (chip->chip_id) {
1797         case KVM_IRQCHIP_PIC_MASTER:
1798                 memcpy(&chip->chip.pic,
1799                         &pic_irqchip(kvm)->pics[0],
1800                         sizeof(struct kvm_pic_state));
1801                 break;
1802         case KVM_IRQCHIP_PIC_SLAVE:
1803                 memcpy(&chip->chip.pic,
1804                         &pic_irqchip(kvm)->pics[1],
1805                         sizeof(struct kvm_pic_state));
1806                 break;
1807         case KVM_IRQCHIP_IOAPIC:
1808                 memcpy(&chip->chip.ioapic,
1809                         ioapic_irqchip(kvm),
1810                         sizeof(struct kvm_ioapic_state));
1811                 break;
1812         default:
1813                 r = -EINVAL;
1814                 break;
1815         }
1816         return r;
1817 }
1818
1819 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1820 {
1821         int r;
1822
1823         r = 0;
1824         switch (chip->chip_id) {
1825         case KVM_IRQCHIP_PIC_MASTER:
1826                 memcpy(&pic_irqchip(kvm)->pics[0],
1827                         &chip->chip.pic,
1828                         sizeof(struct kvm_pic_state));
1829                 break;
1830         case KVM_IRQCHIP_PIC_SLAVE:
1831                 memcpy(&pic_irqchip(kvm)->pics[1],
1832                         &chip->chip.pic,
1833                         sizeof(struct kvm_pic_state));
1834                 break;
1835         case KVM_IRQCHIP_IOAPIC:
1836                 memcpy(ioapic_irqchip(kvm),
1837                         &chip->chip.ioapic,
1838                         sizeof(struct kvm_ioapic_state));
1839                 break;
1840         default:
1841                 r = -EINVAL;
1842                 break;
1843         }
1844         kvm_pic_update_irq(pic_irqchip(kvm));
1845         return r;
1846 }
1847
1848 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1849 {
1850         int r = 0;
1851
1852         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
1853         return r;
1854 }
1855
1856 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1857 {
1858         int r = 0;
1859
1860         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
1861         kvm_pit_load_count(kvm, 0, ps->channels[0].count);
1862         return r;
1863 }
1864
1865 /*
1866  * Get (and clear) the dirty memory log for a memory slot.
1867  */
1868 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1869                                       struct kvm_dirty_log *log)
1870 {
1871         int r;
1872         int n;
1873         struct kvm_memory_slot *memslot;
1874         int is_dirty = 0;
1875
1876         down_write(&kvm->slots_lock);
1877
1878         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1879         if (r)
1880                 goto out;
1881
1882         /* If nothing is dirty, don't bother messing with page tables. */
1883         if (is_dirty) {
1884                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1885                 kvm_flush_remote_tlbs(kvm);
1886                 memslot = &kvm->memslots[log->slot];
1887                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1888                 memset(memslot->dirty_bitmap, 0, n);
1889         }
1890         r = 0;
1891 out:
1892         up_write(&kvm->slots_lock);
1893         return r;
1894 }
1895
1896 long kvm_arch_vm_ioctl(struct file *filp,
1897                        unsigned int ioctl, unsigned long arg)
1898 {
1899         struct kvm *kvm = filp->private_data;
1900         void __user *argp = (void __user *)arg;
1901         int r = -EINVAL;
1902         /*
1903          * This union makes it completely explicit to gcc-3.x
1904          * that these two variables' stack usage should be
1905          * combined, not added together.
1906          */
1907         union {
1908                 struct kvm_pit_state ps;
1909                 struct kvm_memory_alias alias;
1910         } u;
1911
1912         switch (ioctl) {
1913         case KVM_SET_TSS_ADDR:
1914                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1915                 if (r < 0)
1916                         goto out;
1917                 break;
1918         case KVM_SET_MEMORY_REGION: {
1919                 struct kvm_memory_region kvm_mem;
1920                 struct kvm_userspace_memory_region kvm_userspace_mem;
1921
1922                 r = -EFAULT;
1923                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1924                         goto out;
1925                 kvm_userspace_mem.slot = kvm_mem.slot;
1926                 kvm_userspace_mem.flags = kvm_mem.flags;
1927                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1928                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1929                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1930                 if (r)
1931                         goto out;
1932                 break;
1933         }
1934         case KVM_SET_NR_MMU_PAGES:
1935                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1936                 if (r)
1937                         goto out;
1938                 break;
1939         case KVM_GET_NR_MMU_PAGES:
1940                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1941                 break;
1942         case KVM_SET_MEMORY_ALIAS:
1943                 r = -EFAULT;
1944                 if (copy_from_user(&u.alias, argp, sizeof(struct kvm_memory_alias)))
1945                         goto out;
1946                 r = kvm_vm_ioctl_set_memory_alias(kvm, &u.alias);
1947                 if (r)
1948                         goto out;
1949                 break;
1950         case KVM_CREATE_IRQCHIP:
1951                 r = -ENOMEM;
1952                 kvm->arch.vpic = kvm_create_pic(kvm);
1953                 if (kvm->arch.vpic) {
1954                         r = kvm_ioapic_init(kvm);
1955                         if (r) {
1956                                 kfree(kvm->arch.vpic);
1957                                 kvm->arch.vpic = NULL;
1958                                 goto out;
1959                         }
1960                 } else
1961                         goto out;
1962                 break;
1963         case KVM_CREATE_PIT:
1964                 r = -ENOMEM;
1965                 kvm->arch.vpit = kvm_create_pit(kvm);
1966                 if (kvm->arch.vpit)
1967                         r = 0;
1968                 break;
1969         case KVM_IRQ_LINE: {
1970                 struct kvm_irq_level irq_event;
1971
1972                 r = -EFAULT;
1973                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1974                         goto out;
1975                 if (irqchip_in_kernel(kvm)) {
1976                         mutex_lock(&kvm->lock);
1977                         kvm_set_irq(kvm, irq_event.irq, irq_event.level);
1978                         mutex_unlock(&kvm->lock);
1979                         r = 0;
1980                 }
1981                 break;
1982         }
1983         case KVM_GET_IRQCHIP: {
1984                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1985                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
1986
1987                 r = -ENOMEM;
1988                 if (!chip)
1989                         goto out;
1990                 r = -EFAULT;
1991                 if (copy_from_user(chip, argp, sizeof *chip))
1992                         goto get_irqchip_out;
1993                 r = -ENXIO;
1994                 if (!irqchip_in_kernel(kvm))
1995                         goto get_irqchip_out;
1996                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
1997                 if (r)
1998                         goto get_irqchip_out;
1999                 r = -EFAULT;
2000                 if (copy_to_user(argp, chip, sizeof *chip))
2001                         goto get_irqchip_out;
2002                 r = 0;
2003         get_irqchip_out:
2004                 kfree(chip);
2005                 if (r)
2006                         goto out;
2007                 break;
2008         }
2009         case KVM_SET_IRQCHIP: {
2010                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
2011                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
2012
2013                 r = -ENOMEM;
2014                 if (!chip)
2015                         goto out;
2016                 r = -EFAULT;
2017                 if (copy_from_user(chip, argp, sizeof *chip))
2018                         goto set_irqchip_out;
2019                 r = -ENXIO;
2020                 if (!irqchip_in_kernel(kvm))
2021                         goto set_irqchip_out;
2022                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
2023                 if (r)
2024                         goto set_irqchip_out;
2025                 r = 0;
2026         set_irqchip_out:
2027                 kfree(chip);
2028                 if (r)
2029                         goto out;
2030                 break;
2031         }
2032         case KVM_ASSIGN_PCI_DEVICE: {
2033                 struct kvm_assigned_pci_dev assigned_dev;
2034
2035                 r = -EFAULT;
2036                 if (copy_from_user(&assigned_dev, argp, sizeof assigned_dev))
2037                         goto out;
2038                 r = kvm_vm_ioctl_assign_device(kvm, &assigned_dev);
2039                 if (r)
2040                         goto out;
2041                 break;
2042         }
2043         case KVM_ASSIGN_IRQ: {
2044                 struct kvm_assigned_irq assigned_irq;
2045
2046                 r = -EFAULT;
2047                 if (copy_from_user(&assigned_irq, argp, sizeof assigned_irq))
2048                         goto out;
2049                 r = kvm_vm_ioctl_assign_irq(kvm, &assigned_irq);
2050                 if (r)
2051                         goto out;
2052                 break;
2053         }
2054         case KVM_GET_PIT: {
2055                 r = -EFAULT;
2056                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
2057                         goto out;
2058                 r = -ENXIO;
2059                 if (!kvm->arch.vpit)
2060                         goto out;
2061                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
2062                 if (r)
2063                         goto out;
2064                 r = -EFAULT;
2065                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
2066                         goto out;
2067                 r = 0;
2068                 break;
2069         }
2070         case KVM_SET_PIT: {
2071                 r = -EFAULT;
2072                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
2073                         goto out;
2074                 r = -ENXIO;
2075                 if (!kvm->arch.vpit)
2076                         goto out;
2077                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
2078                 if (r)
2079                         goto out;
2080                 r = 0;
2081                 break;
2082         }
2083         default:
2084                 ;
2085         }
2086 out:
2087         return r;
2088 }
2089
2090 static void kvm_init_msr_list(void)
2091 {
2092         u32 dummy[2];
2093         unsigned i, j;
2094
2095         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
2096                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
2097                         continue;
2098                 if (j < i)
2099                         msrs_to_save[j] = msrs_to_save[i];
2100                 j++;
2101         }
2102         num_msrs_to_save = j;
2103 }
2104
2105 /*
2106  * Only apic need an MMIO device hook, so shortcut now..
2107  */
2108 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
2109                                                 gpa_t addr, int len,
2110                                                 int is_write)
2111 {
2112         struct kvm_io_device *dev;
2113
2114         if (vcpu->arch.apic) {
2115                 dev = &vcpu->arch.apic->dev;
2116                 if (dev->in_range(dev, addr, len, is_write))
2117                         return dev;
2118         }
2119         return NULL;
2120 }
2121
2122
2123 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
2124                                                 gpa_t addr, int len,
2125                                                 int is_write)
2126 {
2127         struct kvm_io_device *dev;
2128
2129         dev = vcpu_find_pervcpu_dev(vcpu, addr, len, is_write);
2130         if (dev == NULL)
2131                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr, len,
2132                                           is_write);
2133         return dev;
2134 }
2135
2136 int emulator_read_std(unsigned long addr,
2137                              void *val,
2138                              unsigned int bytes,
2139                              struct kvm_vcpu *vcpu)
2140 {
2141         void *data = val;
2142         int r = X86EMUL_CONTINUE;
2143
2144         while (bytes) {
2145                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2146                 unsigned offset = addr & (PAGE_SIZE-1);
2147                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
2148                 int ret;
2149
2150                 if (gpa == UNMAPPED_GVA) {
2151                         r = X86EMUL_PROPAGATE_FAULT;
2152                         goto out;
2153                 }
2154                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
2155                 if (ret < 0) {
2156                         r = X86EMUL_UNHANDLEABLE;
2157                         goto out;
2158                 }
2159
2160                 bytes -= tocopy;
2161                 data += tocopy;
2162                 addr += tocopy;
2163         }
2164 out:
2165         return r;
2166 }
2167 EXPORT_SYMBOL_GPL(emulator_read_std);
2168
2169 static int emulator_read_emulated(unsigned long addr,
2170                                   void *val,
2171                                   unsigned int bytes,
2172                                   struct kvm_vcpu *vcpu)
2173 {
2174         struct kvm_io_device *mmio_dev;
2175         gpa_t                 gpa;
2176
2177         if (vcpu->mmio_read_completed) {
2178                 memcpy(val, vcpu->mmio_data, bytes);
2179                 vcpu->mmio_read_completed = 0;
2180                 return X86EMUL_CONTINUE;
2181         }
2182
2183         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2184
2185         /* For APIC access vmexit */
2186         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2187                 goto mmio;
2188
2189         if (emulator_read_std(addr, val, bytes, vcpu)
2190                         == X86EMUL_CONTINUE)
2191                 return X86EMUL_CONTINUE;
2192         if (gpa == UNMAPPED_GVA)
2193                 return X86EMUL_PROPAGATE_FAULT;
2194
2195 mmio:
2196         /*
2197          * Is this MMIO handled locally?
2198          */
2199         mutex_lock(&vcpu->kvm->lock);
2200         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa, bytes, 0);
2201         if (mmio_dev) {
2202                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
2203                 mutex_unlock(&vcpu->kvm->lock);
2204                 return X86EMUL_CONTINUE;
2205         }
2206         mutex_unlock(&vcpu->kvm->lock);
2207
2208         vcpu->mmio_needed = 1;
2209         vcpu->mmio_phys_addr = gpa;
2210         vcpu->mmio_size = bytes;
2211         vcpu->mmio_is_write = 0;
2212
2213         return X86EMUL_UNHANDLEABLE;
2214 }
2215
2216 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
2217                           const void *val, int bytes)
2218 {
2219         int ret;
2220
2221         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
2222         if (ret < 0)
2223                 return 0;
2224         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
2225         return 1;
2226 }
2227
2228 static int emulator_write_emulated_onepage(unsigned long addr,
2229                                            const void *val,
2230                                            unsigned int bytes,
2231                                            struct kvm_vcpu *vcpu)
2232 {
2233         struct kvm_io_device *mmio_dev;
2234         gpa_t                 gpa;
2235
2236         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2237
2238         if (gpa == UNMAPPED_GVA) {
2239                 kvm_inject_page_fault(vcpu, addr, 2);
2240                 return X86EMUL_PROPAGATE_FAULT;
2241         }
2242
2243         /* For APIC access vmexit */
2244         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2245                 goto mmio;
2246
2247         if (emulator_write_phys(vcpu, gpa, val, bytes))
2248                 return X86EMUL_CONTINUE;
2249
2250 mmio:
2251         /*
2252          * Is this MMIO handled locally?
2253          */
2254         mutex_lock(&vcpu->kvm->lock);
2255         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa, bytes, 1);
2256         if (mmio_dev) {
2257                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
2258                 mutex_unlock(&vcpu->kvm->lock);
2259                 return X86EMUL_CONTINUE;
2260         }
2261         mutex_unlock(&vcpu->kvm->lock);
2262
2263         vcpu->mmio_needed = 1;
2264         vcpu->mmio_phys_addr = gpa;
2265         vcpu->mmio_size = bytes;
2266         vcpu->mmio_is_write = 1;
2267         memcpy(vcpu->mmio_data, val, bytes);
2268
2269         return X86EMUL_CONTINUE;
2270 }
2271
2272 int emulator_write_emulated(unsigned long addr,
2273                                    const void *val,
2274                                    unsigned int bytes,
2275                                    struct kvm_vcpu *vcpu)
2276 {
2277         /* Crossing a page boundary? */
2278         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
2279                 int rc, now;
2280
2281                 now = -addr & ~PAGE_MASK;
2282                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
2283                 if (rc != X86EMUL_CONTINUE)
2284                         return rc;
2285                 addr += now;
2286                 val += now;
2287                 bytes -= now;
2288         }
2289         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
2290 }
2291 EXPORT_SYMBOL_GPL(emulator_write_emulated);
2292
2293 static int emulator_cmpxchg_emulated(unsigned long addr,
2294                                      const void *old,
2295                                      const void *new,
2296                                      unsigned int bytes,
2297                                      struct kvm_vcpu *vcpu)
2298 {
2299         static int reported;
2300
2301         if (!reported) {
2302                 reported = 1;
2303                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
2304         }
2305 #ifndef CONFIG_X86_64
2306         /* guests cmpxchg8b have to be emulated atomically */
2307         if (bytes == 8) {
2308                 gpa_t gpa;
2309                 struct page *page;
2310                 char *kaddr;
2311                 u64 val;
2312
2313                 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2314
2315                 if (gpa == UNMAPPED_GVA ||
2316                    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2317                         goto emul_write;
2318
2319                 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
2320                         goto emul_write;
2321
2322                 val = *(u64 *)new;
2323
2324                 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2325
2326                 kaddr = kmap_atomic(page, KM_USER0);
2327                 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
2328                 kunmap_atomic(kaddr, KM_USER0);
2329                 kvm_release_page_dirty(page);
2330         }
2331 emul_write:
2332 #endif
2333
2334         return emulator_write_emulated(addr, new, bytes, vcpu);
2335 }
2336
2337 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
2338 {
2339         return kvm_x86_ops->get_segment_base(vcpu, seg);
2340 }
2341
2342 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
2343 {
2344         return X86EMUL_CONTINUE;
2345 }
2346
2347 int emulate_clts(struct kvm_vcpu *vcpu)
2348 {
2349         KVMTRACE_0D(CLTS, vcpu, handler);
2350         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
2351         return X86EMUL_CONTINUE;
2352 }
2353
2354 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
2355 {
2356         struct kvm_vcpu *vcpu = ctxt->vcpu;
2357
2358         switch (dr) {
2359         case 0 ... 3:
2360                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
2361                 return X86EMUL_CONTINUE;
2362         default:
2363                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __func__, dr);
2364                 return X86EMUL_UNHANDLEABLE;
2365         }
2366 }
2367
2368 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
2369 {
2370         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
2371         int exception;
2372
2373         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
2374         if (exception) {
2375                 /* FIXME: better handling */
2376                 return X86EMUL_UNHANDLEABLE;
2377         }
2378         return X86EMUL_CONTINUE;
2379 }
2380
2381 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
2382 {
2383         u8 opcodes[4];
2384         unsigned long rip = kvm_rip_read(vcpu);
2385         unsigned long rip_linear;
2386
2387         if (!printk_ratelimit())
2388                 return;
2389
2390         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
2391
2392         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
2393
2394         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
2395                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
2396 }
2397 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
2398
2399 static struct x86_emulate_ops emulate_ops = {
2400         .read_std            = emulator_read_std,
2401         .read_emulated       = emulator_read_emulated,
2402         .write_emulated      = emulator_write_emulated,
2403         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
2404 };
2405
2406 static void cache_all_regs(struct kvm_vcpu *vcpu)
2407 {
2408         kvm_register_read(vcpu, VCPU_REGS_RAX);
2409         kvm_register_read(vcpu, VCPU_REGS_RSP);
2410         kvm_register_read(vcpu, VCPU_REGS_RIP);
2411         vcpu->arch.regs_dirty = ~0;
2412 }
2413
2414 int emulate_instruction(struct kvm_vcpu *vcpu,
2415                         struct kvm_run *run,
2416                         unsigned long cr2,
2417                         u16 error_code,
2418                         int emulation_type)
2419 {
2420         int r;
2421         struct decode_cache *c;
2422
2423         kvm_clear_exception_queue(vcpu);
2424         vcpu->arch.mmio_fault_cr2 = cr2;
2425         /*
2426          * TODO: fix x86_emulate.c to use guest_read/write_register
2427          * instead of direct ->regs accesses, can save hundred cycles
2428          * on Intel for instructions that don't read/change RSP, for
2429          * for example.
2430          */
2431         cache_all_regs(vcpu);
2432
2433         vcpu->mmio_is_write = 0;
2434         vcpu->arch.pio.string = 0;
2435
2436         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
2437                 int cs_db, cs_l;
2438                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
2439
2440                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
2441                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
2442                 vcpu->arch.emulate_ctxt.mode =
2443                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
2444                         ? X86EMUL_MODE_REAL : cs_l
2445                         ? X86EMUL_MODE_PROT64 : cs_db
2446                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
2447
2448                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2449
2450                 /* Reject the instructions other than VMCALL/VMMCALL when
2451                  * try to emulate invalid opcode */
2452                 c = &vcpu->arch.emulate_ctxt.decode;
2453                 if ((emulation_type & EMULTYPE_TRAP_UD) &&
2454                     (!(c->twobyte && c->b == 0x01 &&
2455                       (c->modrm_reg == 0 || c->modrm_reg == 3) &&
2456                        c->modrm_mod == 3 && c->modrm_rm == 1)))
2457                         return EMULATE_FAIL;
2458
2459                 ++vcpu->stat.insn_emulation;
2460                 if (r)  {
2461                         ++vcpu->stat.insn_emulation_fail;
2462                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2463                                 return EMULATE_DONE;
2464                         return EMULATE_FAIL;
2465                 }
2466         }
2467
2468         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2469
2470         if (vcpu->arch.pio.string)
2471                 return EMULATE_DO_MMIO;
2472
2473         if ((r || vcpu->mmio_is_write) && run) {
2474                 run->exit_reason = KVM_EXIT_MMIO;
2475                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
2476                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
2477                 run->mmio.len = vcpu->mmio_size;
2478                 run->mmio.is_write = vcpu->mmio_is_write;
2479         }
2480
2481         if (r) {
2482                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2483                         return EMULATE_DONE;
2484                 if (!vcpu->mmio_needed) {
2485                         kvm_report_emulation_failure(vcpu, "mmio");
2486                         return EMULATE_FAIL;
2487                 }
2488                 return EMULATE_DO_MMIO;
2489         }
2490
2491         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
2492
2493         if (vcpu->mmio_is_write) {
2494                 vcpu->mmio_needed = 0;
2495                 return EMULATE_DO_MMIO;
2496         }
2497
2498         return EMULATE_DONE;
2499 }
2500 EXPORT_SYMBOL_GPL(emulate_instruction);
2501
2502 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
2503 {
2504         int i;
2505
2506         for (i = 0; i < ARRAY_SIZE(vcpu->arch.pio.guest_pages); ++i)
2507                 if (vcpu->arch.pio.guest_pages[i]) {
2508                         kvm_release_page_dirty(vcpu->arch.pio.guest_pages[i]);
2509                         vcpu->arch.pio.guest_pages[i] = NULL;
2510                 }
2511 }
2512
2513 static int pio_copy_data(struct kvm_vcpu *vcpu)
2514 {
2515         void *p = vcpu->arch.pio_data;
2516         void *q;
2517         unsigned bytes;
2518         int nr_pages = vcpu->arch.pio.guest_pages[1] ? 2 : 1;
2519
2520         q = vmap(vcpu->arch.pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
2521                  PAGE_KERNEL);
2522         if (!q) {
2523                 free_pio_guest_pages(vcpu);
2524                 return -ENOMEM;
2525         }
2526         q += vcpu->arch.pio.guest_page_offset;
2527         bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
2528         if (vcpu->arch.pio.in)
2529                 memcpy(q, p, bytes);
2530         else
2531                 memcpy(p, q, bytes);
2532         q -= vcpu->arch.pio.guest_page_offset;
2533         vunmap(q);
2534         free_pio_guest_pages(vcpu);
2535         return 0;
2536 }
2537
2538 int complete_pio(struct kvm_vcpu *vcpu)
2539 {
2540         struct kvm_pio_request *io = &vcpu->arch.pio;
2541         long delta;
2542         int r;
2543         unsigned long val;
2544
2545         if (!io->string) {
2546                 if (io->in) {
2547                         val = kvm_register_read(vcpu, VCPU_REGS_RAX);
2548                         memcpy(&val, vcpu->arch.pio_data, io->size);
2549                         kvm_register_write(vcpu, VCPU_REGS_RAX, val);
2550                 }
2551         } else {
2552                 if (io->in) {
2553                         r = pio_copy_data(vcpu);
2554                         if (r)
2555                                 return r;
2556                 }
2557
2558                 delta = 1;
2559                 if (io->rep) {
2560                         delta *= io->cur_count;
2561                         /*
2562                          * The size of the register should really depend on
2563                          * current address size.
2564                          */
2565                         val = kvm_register_read(vcpu, VCPU_REGS_RCX);
2566                         val -= delta;
2567                         kvm_register_write(vcpu, VCPU_REGS_RCX, val);
2568                 }
2569                 if (io->down)
2570                         delta = -delta;
2571                 delta *= io->size;
2572                 if (io->in) {
2573                         val = kvm_register_read(vcpu, VCPU_REGS_RDI);
2574                         val += delta;
2575                         kvm_register_write(vcpu, VCPU_REGS_RDI, val);
2576                 } else {
2577                         val = kvm_register_read(vcpu, VCPU_REGS_RSI);
2578                         val += delta;
2579                         kvm_register_write(vcpu, VCPU_REGS_RSI, val);
2580                 }
2581         }
2582
2583         io->count -= io->cur_count;
2584         io->cur_count = 0;
2585
2586         return 0;
2587 }
2588
2589 static void kernel_pio(struct kvm_io_device *pio_dev,
2590                        struct kvm_vcpu *vcpu,
2591                        void *pd)
2592 {
2593         /* TODO: String I/O for in kernel device */
2594
2595         mutex_lock(&vcpu->kvm->lock);
2596         if (vcpu->arch.pio.in)
2597                 kvm_iodevice_read(pio_dev, vcpu->arch.pio.port,
2598                                   vcpu->arch.pio.size,
2599                                   pd);
2600         else
2601                 kvm_iodevice_write(pio_dev, vcpu->arch.pio.port,
2602                                    vcpu->arch.pio.size,
2603                                    pd);
2604         mutex_unlock(&vcpu->kvm->lock);
2605 }
2606
2607 static void pio_string_write(struct kvm_io_device *pio_dev,
2608                              struct kvm_vcpu *vcpu)
2609 {
2610         struct kvm_pio_request *io = &vcpu->arch.pio;
2611         void *pd = vcpu->arch.pio_data;
2612         int i;
2613
2614         mutex_lock(&vcpu->kvm->lock);
2615         for (i = 0; i < io->cur_count; i++) {
2616                 kvm_iodevice_write(pio_dev, io->port,
2617                                    io->size,
2618                                    pd);
2619                 pd += io->size;
2620         }
2621         mutex_unlock(&vcpu->kvm->lock);
2622 }
2623
2624 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
2625                                                gpa_t addr, int len,
2626                                                int is_write)
2627 {
2628         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr, len, is_write);
2629 }
2630
2631 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2632                   int size, unsigned port)
2633 {
2634         struct kvm_io_device *pio_dev;
2635         unsigned long val;
2636
2637         vcpu->run->exit_reason = KVM_EXIT_IO;
2638         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2639         vcpu->run->io.size = vcpu->arch.pio.size = size;
2640         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2641         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2642         vcpu->run->io.port = vcpu->arch.pio.port = port;
2643         vcpu->arch.pio.in = in;
2644         vcpu->arch.pio.string = 0;
2645         vcpu->arch.pio.down = 0;
2646         vcpu->arch.pio.guest_page_offset = 0;
2647         vcpu->arch.pio.rep = 0;
2648
2649         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2650                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2651                             handler);
2652         else
2653                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2654                             handler);
2655
2656         val = kvm_register_read(vcpu, VCPU_REGS_RAX);
2657         memcpy(vcpu->arch.pio_data, &val, 4);
2658
2659         kvm_x86_ops->skip_emulated_instruction(vcpu);
2660
2661         pio_dev = vcpu_find_pio_dev(vcpu, port, size, !in);
2662         if (pio_dev) {
2663                 kernel_pio(pio_dev, vcpu, vcpu->arch.pio_data);
2664                 complete_pio(vcpu);
2665                 return 1;
2666         }
2667         return 0;
2668 }
2669 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
2670
2671 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2672                   int size, unsigned long count, int down,
2673                   gva_t address, int rep, unsigned port)
2674 {
2675         unsigned now, in_page;
2676         int i, ret = 0;
2677         int nr_pages = 1;
2678         struct page *page;
2679         struct kvm_io_device *pio_dev;
2680
2681         vcpu->run->exit_reason = KVM_EXIT_IO;
2682         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2683         vcpu->run->io.size = vcpu->arch.pio.size = size;
2684         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2685         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
2686         vcpu->run->io.port = vcpu->arch.pio.port = port;
2687         vcpu->arch.pio.in = in;
2688         vcpu->arch.pio.string = 1;
2689         vcpu->arch.pio.down = down;
2690         vcpu->arch.pio.guest_page_offset = offset_in_page(address);
2691         vcpu->arch.pio.rep = rep;
2692
2693         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2694                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2695                             handler);
2696         else
2697                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2698                             handler);
2699
2700         if (!count) {
2701                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2702                 return 1;
2703         }
2704
2705         if (!down)
2706                 in_page = PAGE_SIZE - offset_in_page(address);
2707         else
2708                 in_page = offset_in_page(address) + size;
2709         now = min(count, (unsigned long)in_page / size);
2710         if (!now) {
2711                 /*
2712                  * String I/O straddles page boundary.  Pin two guest pages
2713                  * so that we satisfy atomicity constraints.  Do just one
2714                  * transaction to avoid complexity.
2715                  */
2716                 nr_pages = 2;
2717                 now = 1;
2718         }
2719         if (down) {
2720                 /*
2721                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
2722                  */
2723                 pr_unimpl(vcpu, "guest string pio down\n");
2724                 kvm_inject_gp(vcpu, 0);
2725                 return 1;
2726         }
2727         vcpu->run->io.count = now;
2728         vcpu->arch.pio.cur_count = now;
2729
2730         if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
2731                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2732
2733         for (i = 0; i < nr_pages; ++i) {
2734                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
2735                 vcpu->arch.pio.guest_pages[i] = page;
2736                 if (!page) {
2737                         kvm_inject_gp(vcpu, 0);
2738                         free_pio_guest_pages(vcpu);
2739                         return 1;
2740                 }
2741         }
2742
2743         pio_dev = vcpu_find_pio_dev(vcpu, port,
2744                                     vcpu->arch.pio.cur_count,
2745                                     !vcpu->arch.pio.in);
2746         if (!vcpu->arch.pio.in) {
2747                 /* string PIO write */
2748                 ret = pio_copy_data(vcpu);
2749                 if (ret >= 0 && pio_dev) {
2750                         pio_string_write(pio_dev, vcpu);
2751                         complete_pio(vcpu);
2752                         if (vcpu->arch.pio.count == 0)
2753                                 ret = 1;
2754                 }
2755         } else if (pio_dev)
2756                 pr_unimpl(vcpu, "no string pio read support yet, "
2757                        "port %x size %d count %ld\n",
2758                         port, size, count);
2759
2760         return ret;
2761 }
2762 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2763
2764 int kvm_arch_init(void *opaque)
2765 {
2766         int r;
2767         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2768
2769         if (kvm_x86_ops) {
2770                 printk(KERN_ERR "kvm: already loaded the other module\n");
2771                 r = -EEXIST;
2772                 goto out;
2773         }
2774
2775         if (!ops->cpu_has_kvm_support()) {
2776                 printk(KERN_ERR "kvm: no hardware support\n");
2777                 r = -EOPNOTSUPP;
2778                 goto out;
2779         }
2780         if (ops->disabled_by_bios()) {
2781                 printk(KERN_ERR "kvm: disabled by bios\n");
2782                 r = -EOPNOTSUPP;
2783                 goto out;
2784         }
2785
2786         r = kvm_mmu_module_init();
2787         if (r)
2788                 goto out;
2789
2790         kvm_init_msr_list();
2791
2792         kvm_x86_ops = ops;
2793         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2794         kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
2795         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
2796                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
2797         return 0;
2798
2799 out:
2800         return r;
2801 }
2802
2803 void kvm_arch_exit(void)
2804 {
2805         kvm_x86_ops = NULL;
2806         kvm_mmu_module_exit();
2807 }
2808
2809 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2810 {
2811         ++vcpu->stat.halt_exits;
2812         KVMTRACE_0D(HLT, vcpu, handler);
2813         if (irqchip_in_kernel(vcpu->kvm)) {
2814                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
2815                 return 1;
2816         } else {
2817                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2818                 return 0;
2819         }
2820 }
2821 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2822
2823 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
2824                            unsigned long a1)
2825 {
2826         if (is_long_mode(vcpu))
2827                 return a0;
2828         else
2829                 return a0 | ((gpa_t)a1 << 32);
2830 }
2831
2832 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2833 {
2834         unsigned long nr, a0, a1, a2, a3, ret;
2835         int r = 1;
2836
2837         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
2838         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
2839         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
2840         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
2841         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
2842
2843         KVMTRACE_1D(VMMCALL, vcpu, (u32)nr, handler);
2844
2845         if (!is_long_mode(vcpu)) {
2846                 nr &= 0xFFFFFFFF;
2847                 a0 &= 0xFFFFFFFF;
2848                 a1 &= 0xFFFFFFFF;
2849                 a2 &= 0xFFFFFFFF;
2850                 a3 &= 0xFFFFFFFF;
2851         }
2852
2853         switch (nr) {
2854         case KVM_HC_VAPIC_POLL_IRQ:
2855                 ret = 0;
2856                 break;
2857         case KVM_HC_MMU_OP:
2858                 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
2859                 break;
2860         default:
2861                 ret = -KVM_ENOSYS;
2862                 break;
2863         }
2864         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
2865         ++vcpu->stat.hypercalls;
2866         return r;
2867 }
2868 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2869
2870 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2871 {
2872         char instruction[3];
2873         int ret = 0;
2874         unsigned long rip = kvm_rip_read(vcpu);
2875
2876
2877         /*
2878          * Blow out the MMU to ensure that no other VCPU has an active mapping
2879          * to ensure that the updated hypercall appears atomically across all
2880          * VCPUs.
2881          */
2882         kvm_mmu_zap_all(vcpu->kvm);
2883
2884         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2885         if (emulator_write_emulated(rip, instruction, 3, vcpu)
2886             != X86EMUL_CONTINUE)
2887                 ret = -EFAULT;
2888
2889         return ret;
2890 }
2891
2892 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2893 {
2894         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2895 }
2896
2897 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2898 {
2899         struct descriptor_table dt = { limit, base };
2900
2901         kvm_x86_ops->set_gdt(vcpu, &dt);
2902 }
2903
2904 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2905 {
2906         struct descriptor_table dt = { limit, base };
2907
2908         kvm_x86_ops->set_idt(vcpu, &dt);
2909 }
2910
2911 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2912                    unsigned long *rflags)
2913 {
2914         kvm_lmsw(vcpu, msw);
2915         *rflags = kvm_x86_ops->get_rflags(vcpu);
2916 }
2917
2918 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2919 {
2920         unsigned long value;
2921
2922         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2923         switch (cr) {
2924         case 0:
2925                 value = vcpu->arch.cr0;
2926                 break;
2927         case 2:
2928                 value = vcpu->arch.cr2;
2929                 break;
2930         case 3:
2931                 value = vcpu->arch.cr3;
2932                 break;
2933         case 4:
2934                 value = vcpu->arch.cr4;
2935                 break;
2936         case 8:
2937                 value = kvm_get_cr8(vcpu);
2938                 break;
2939         default:
2940                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2941                 return 0;
2942         }
2943         KVMTRACE_3D(CR_READ, vcpu, (u32)cr, (u32)value,
2944                     (u32)((u64)value >> 32), handler);
2945
2946         return value;
2947 }
2948
2949 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2950                      unsigned long *rflags)
2951 {
2952         KVMTRACE_3D(CR_WRITE, vcpu, (u32)cr, (u32)val,
2953                     (u32)((u64)val >> 32), handler);
2954
2955         switch (cr) {
2956         case 0:
2957                 kvm_set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2958                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2959                 break;
2960         case 2:
2961                 vcpu->arch.cr2 = val;
2962                 break;
2963         case 3:
2964                 kvm_set_cr3(vcpu, val);
2965                 break;
2966         case 4:
2967                 kvm_set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2968                 break;
2969         case 8:
2970                 kvm_set_cr8(vcpu, val & 0xfUL);
2971                 break;
2972         default:
2973                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2974         }
2975 }
2976
2977 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2978 {
2979         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2980         int j, nent = vcpu->arch.cpuid_nent;
2981
2982         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2983         /* when no next entry is found, the current entry[i] is reselected */
2984         for (j = i + 1; j == i; j = (j + 1) % nent) {
2985                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2986                 if (ej->function == e->function) {
2987                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2988                         return j;
2989                 }
2990         }
2991         return 0; /* silence gcc, even though control never reaches here */
2992 }
2993
2994 /* find an entry with matching function, matching index (if needed), and that
2995  * should be read next (if it's stateful) */
2996 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2997         u32 function, u32 index)
2998 {
2999         if (e->function != function)
3000                 return 0;
3001         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
3002                 return 0;
3003         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
3004                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
3005                 return 0;
3006         return 1;
3007 }
3008
3009 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
3010 {
3011         int i;
3012         u32 function, index;
3013         struct kvm_cpuid_entry2 *e, *best;
3014
3015         function = kvm_register_read(vcpu, VCPU_REGS_RAX);
3016         index = kvm_register_read(vcpu, VCPU_REGS_RCX);
3017         kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
3018         kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
3019         kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
3020         kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
3021         best = NULL;
3022         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
3023                 e = &vcpu->arch.cpuid_entries[i];
3024                 if (is_matching_cpuid_entry(e, function, index)) {
3025                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
3026                                 move_to_next_stateful_cpuid_entry(vcpu, i);
3027                         best = e;
3028                         break;
3029                 }
3030                 /*
3031                  * Both basic or both extended?
3032                  */
3033                 if (((e->function ^ function) & 0x80000000) == 0)
3034                         if (!best || e->function > best->function)
3035                                 best = e;
3036         }
3037         if (best) {
3038                 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
3039                 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
3040                 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
3041                 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
3042         }
3043         kvm_x86_ops->skip_emulated_instruction(vcpu);
3044         KVMTRACE_5D(CPUID, vcpu, function,
3045                     (u32)kvm_register_read(vcpu, VCPU_REGS_RAX),
3046                     (u32)kvm_register_read(vcpu, VCPU_REGS_RBX),
3047                     (u32)kvm_register_read(vcpu, VCPU_REGS_RCX),
3048                     (u32)kvm_register_read(vcpu, VCPU_REGS_RDX), handler);
3049 }
3050 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
3051
3052 /*
3053  * Check if userspace requested an interrupt window, and that the
3054  * interrupt window is open.
3055  *
3056  * No need to exit to userspace if we already have an interrupt queued.
3057  */
3058 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
3059                                           struct kvm_run *kvm_run)
3060 {
3061         return (!vcpu->arch.irq_summary &&
3062                 kvm_run->request_interrupt_window &&
3063                 vcpu->arch.interrupt_window_open &&
3064                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
3065 }
3066
3067 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
3068                               struct kvm_run *kvm_run)
3069 {
3070         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
3071         kvm_run->cr8 = kvm_get_cr8(vcpu);
3072         kvm_run->apic_base = kvm_get_apic_base(vcpu);
3073         if (irqchip_in_kernel(vcpu->kvm))
3074                 kvm_run->ready_for_interrupt_injection = 1;
3075         else
3076                 kvm_run->ready_for_interrupt_injection =
3077                                         (vcpu->arch.interrupt_window_open &&
3078                                          vcpu->arch.irq_summary == 0);
3079 }
3080
3081 static void vapic_enter(struct kvm_vcpu *vcpu)
3082 {
3083         struct kvm_lapic *apic = vcpu->arch.apic;
3084         struct page *page;
3085
3086         if (!apic || !apic->vapic_addr)
3087                 return;
3088
3089         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
3090
3091         vcpu->arch.apic->vapic_page = page;
3092 }
3093
3094 static void vapic_exit(struct kvm_vcpu *vcpu)
3095 {
3096         struct kvm_lapic *apic = vcpu->arch.apic;
3097
3098         if (!apic || !apic->vapic_addr)
3099                 return;
3100
3101         down_read(&vcpu->kvm->slots_lock);
3102         kvm_release_page_dirty(apic->vapic_page);
3103         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
3104         up_read(&vcpu->kvm->slots_lock);
3105 }
3106
3107 static int vcpu_enter_guest(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3108 {
3109         int r;
3110
3111         if (vcpu->requests)
3112                 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
3113                         kvm_mmu_unload(vcpu);
3114
3115         r = kvm_mmu_reload(vcpu);
3116         if (unlikely(r))
3117                 goto out;
3118
3119         if (vcpu->requests) {
3120                 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
3121                         __kvm_migrate_timers(vcpu);
3122                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
3123                         kvm_x86_ops->tlb_flush(vcpu);
3124                 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
3125                                        &vcpu->requests)) {
3126                         kvm_run->exit_reason = KVM_EXIT_TPR_ACCESS;
3127                         r = 0;
3128                         goto out;
3129                 }
3130                 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
3131                         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
3132                         r = 0;
3133                         goto out;
3134                 }
3135         }
3136
3137         clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
3138         kvm_inject_pending_timer_irqs(vcpu);
3139
3140         preempt_disable();
3141
3142         kvm_x86_ops->prepare_guest_switch(vcpu);
3143         kvm_load_guest_fpu(vcpu);
3144
3145         local_irq_disable();
3146
3147         if (vcpu->requests || need_resched() || signal_pending(current)) {
3148                 local_irq_enable();
3149                 preempt_enable();
3150                 r = 1;
3151                 goto out;
3152         }
3153
3154         if (vcpu->guest_debug.enabled)
3155                 kvm_x86_ops->guest_debug_pre(vcpu);
3156
3157         vcpu->guest_mode = 1;
3158         /*
3159          * Make sure that guest_mode assignment won't happen after
3160          * testing the pending IRQ vector bitmap.
3161          */
3162         smp_wmb();
3163
3164         if (vcpu->arch.exception.pending)
3165                 __queue_exception(vcpu);
3166         else if (irqchip_in_kernel(vcpu->kvm))
3167                 kvm_x86_ops->inject_pending_irq(vcpu);
3168         else
3169                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
3170
3171         kvm_lapic_sync_to_vapic(vcpu);
3172
3173         up_read(&vcpu->kvm->slots_lock);
3174
3175         kvm_guest_enter();
3176
3177
3178         KVMTRACE_0D(VMENTRY, vcpu, entryexit);
3179         kvm_x86_ops->run(vcpu, kvm_run);
3180
3181         vcpu->guest_mode = 0;
3182         local_irq_enable();
3183
3184         ++vcpu->stat.exits;
3185
3186         /*
3187          * We must have an instruction between local_irq_enable() and
3188          * kvm_guest_exit(), so the timer interrupt isn't delayed by
3189          * the interrupt shadow.  The stat.exits increment will do nicely.
3190          * But we need to prevent reordering, hence this barrier():
3191          */
3192         barrier();
3193
3194         kvm_guest_exit();
3195
3196         preempt_enable();
3197
3198         down_read(&vcpu->kvm->slots_lock);
3199
3200         /*
3201          * Profile KVM exit RIPs:
3202          */
3203         if (unlikely(prof_on == KVM_PROFILING)) {
3204                 unsigned long rip = kvm_rip_read(vcpu);
3205                 profile_hit(KVM_PROFILING, (void *)rip);
3206         }
3207
3208         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
3209                 vcpu->arch.exception.pending = false;
3210
3211         kvm_lapic_sync_from_vapic(vcpu);
3212
3213         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
3214 out:
3215         return r;
3216 }
3217
3218 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3219 {
3220         int r;
3221
3222         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
3223                 printk("vcpu %d received sipi with vector # %x\n",
3224                        vcpu->vcpu_id, vcpu->arch.sipi_vector);
3225                 kvm_lapic_reset(vcpu);
3226                 r = kvm_x86_ops->vcpu_reset(vcpu);
3227                 if (r)
3228                         return r;
3229                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3230         }
3231
3232         down_read(&vcpu->kvm->slots_lock);
3233         vapic_enter(vcpu);
3234
3235         r = 1;
3236         while (r > 0) {
3237                 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE)
3238                         r = vcpu_enter_guest(vcpu, kvm_run);
3239                 else {
3240                         up_read(&vcpu->kvm->slots_lock);
3241                         kvm_vcpu_block(vcpu);
3242                         down_read(&vcpu->kvm->slots_lock);
3243                         if (test_and_clear_bit(KVM_REQ_UNHALT, &vcpu->requests))
3244                                 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
3245                                         vcpu->arch.mp_state =
3246                                                         KVM_MP_STATE_RUNNABLE;
3247                         if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
3248                                 r = -EINTR;
3249                 }
3250
3251                 if (r > 0) {
3252                         if (dm_request_for_irq_injection(vcpu, kvm_run)) {
3253                                 r = -EINTR;
3254                                 kvm_run->exit_reason = KVM_EXIT_INTR;
3255                                 ++vcpu->stat.request_irq_exits;
3256                         }
3257                         if (signal_pending(current)) {
3258                                 r = -EINTR;
3259                                 kvm_run->exit_reason = KVM_EXIT_INTR;
3260                                 ++vcpu->stat.signal_exits;
3261                         }
3262                         if (need_resched()) {
3263                                 up_read(&vcpu->kvm->slots_lock);
3264                                 kvm_resched(vcpu);
3265                                 down_read(&vcpu->kvm->slots_lock);
3266                         }
3267                 }
3268         }
3269
3270         up_read(&vcpu->kvm->slots_lock);
3271         post_kvm_run_save(vcpu, kvm_run);
3272
3273         vapic_exit(vcpu);
3274
3275         return r;
3276 }
3277
3278 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3279 {
3280         int r;
3281         sigset_t sigsaved;
3282
3283         vcpu_load(vcpu);
3284
3285         if (vcpu->sigset_active)
3286                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
3287
3288         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
3289                 kvm_vcpu_block(vcpu);
3290                 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
3291                 r = -EAGAIN;
3292                 goto out;
3293         }
3294
3295         /* re-sync apic's tpr */
3296         if (!irqchip_in_kernel(vcpu->kvm))
3297                 kvm_set_cr8(vcpu, kvm_run->cr8);
3298
3299         if (vcpu->arch.pio.cur_count) {
3300                 r = complete_pio(vcpu);
3301                 if (r)
3302                         goto out;
3303         }
3304 #if CONFIG_HAS_IOMEM
3305         if (vcpu->mmio_needed) {
3306                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
3307                 vcpu->mmio_read_completed = 1;
3308                 vcpu->mmio_needed = 0;
3309
3310                 down_read(&vcpu->kvm->slots_lock);
3311                 r = emulate_instruction(vcpu, kvm_run,
3312                                         vcpu->arch.mmio_fault_cr2, 0,
3313                                         EMULTYPE_NO_DECODE);
3314                 up_read(&vcpu->kvm->slots_lock);
3315                 if (r == EMULATE_DO_MMIO) {
3316                         /*
3317                          * Read-modify-write.  Back to userspace.
3318                          */
3319                         r = 0;
3320                         goto out;
3321                 }
3322         }
3323 #endif
3324         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
3325                 kvm_register_write(vcpu, VCPU_REGS_RAX,
3326                                      kvm_run->hypercall.ret);
3327
3328         r = __vcpu_run(vcpu, kvm_run);
3329
3330 out:
3331         if (vcpu->sigset_active)
3332                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
3333
3334         vcpu_put(vcpu);
3335         return r;
3336 }
3337
3338 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3339 {
3340         vcpu_load(vcpu);
3341
3342         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3343         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3344         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3345         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3346         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
3347         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
3348         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3349         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3350 #ifdef CONFIG_X86_64
3351         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
3352         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
3353         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
3354         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
3355         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
3356         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
3357         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
3358         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
3359 #endif
3360
3361         regs->rip = kvm_rip_read(vcpu);
3362         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
3363
3364         /*
3365          * Don't leak debug flags in case they were set for guest debugging
3366          */
3367         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
3368                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
3369
3370         vcpu_put(vcpu);
3371
3372         return 0;
3373 }
3374
3375 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3376 {
3377         vcpu_load(vcpu);
3378
3379         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
3380         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
3381         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
3382         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
3383         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
3384         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
3385         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
3386         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
3387 #ifdef CONFIG_X86_64
3388         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
3389         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
3390         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
3391         kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
3392         kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
3393         kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
3394         kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
3395         kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
3396
3397 #endif
3398
3399         kvm_rip_write(vcpu, regs->rip);
3400         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
3401
3402
3403         vcpu->arch.exception.pending = false;
3404
3405         vcpu_put(vcpu);
3406
3407         return 0;
3408 }
3409
3410 void kvm_get_segment(struct kvm_vcpu *vcpu,
3411                      struct kvm_segment *var, int seg)
3412 {
3413         kvm_x86_ops->get_segment(vcpu, var, seg);
3414 }
3415
3416 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3417 {
3418         struct kvm_segment cs;
3419
3420         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
3421         *db = cs.db;
3422         *l = cs.l;
3423 }
3424 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
3425
3426 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
3427                                   struct kvm_sregs *sregs)
3428 {
3429         struct descriptor_table dt;
3430         int pending_vec;
3431
3432         vcpu_load(vcpu);
3433
3434         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3435         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3436         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3437         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3438         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3439         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3440
3441         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3442         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3443
3444         kvm_x86_ops->get_idt(vcpu, &dt);
3445         sregs->idt.limit = dt.limit;
3446         sregs->idt.base = dt.base;
3447         kvm_x86_ops->get_gdt(vcpu, &dt);
3448         sregs->gdt.limit = dt.limit;
3449         sregs->gdt.base = dt.base;
3450
3451         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3452         sregs->cr0 = vcpu->arch.cr0;
3453         sregs->cr2 = vcpu->arch.cr2;
3454         sregs->cr3 = vcpu->arch.cr3;
3455         sregs->cr4 = vcpu->arch.cr4;
3456         sregs->cr8 = kvm_get_cr8(vcpu);
3457         sregs->efer = vcpu->arch.shadow_efer;
3458         sregs->apic_base = kvm_get_apic_base(vcpu);
3459
3460         if (irqchip_in_kernel(vcpu->kvm)) {
3461                 memset(sregs->interrupt_bitmap, 0,
3462                        sizeof sregs->interrupt_bitmap);
3463                 pending_vec = kvm_x86_ops->get_irq(vcpu);
3464                 if (pending_vec >= 0)
3465                         set_bit(pending_vec,
3466                                 (unsigned long *)sregs->interrupt_bitmap);
3467         } else
3468                 memcpy(sregs->interrupt_bitmap, vcpu->arch.irq_pending,
3469                        sizeof sregs->interrupt_bitmap);
3470
3471         vcpu_put(vcpu);
3472
3473         return 0;
3474 }
3475
3476 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
3477                                     struct kvm_mp_state *mp_state)
3478 {
3479         vcpu_load(vcpu);
3480         mp_state->mp_state = vcpu->arch.mp_state;
3481         vcpu_put(vcpu);
3482         return 0;
3483 }
3484
3485 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
3486                                     struct kvm_mp_state *mp_state)
3487 {
3488         vcpu_load(vcpu);
3489         vcpu->arch.mp_state = mp_state->mp_state;
3490         vcpu_put(vcpu);
3491         return 0;
3492 }
3493
3494 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3495                         struct kvm_segment *var, int seg)
3496 {
3497         kvm_x86_ops->set_segment(vcpu, var, seg);
3498 }
3499
3500 static void seg_desct_to_kvm_desct(struct desc_struct *seg_desc, u16 selector,
3501                                    struct kvm_segment *kvm_desct)
3502 {
3503         kvm_desct->base = seg_desc->base0;
3504         kvm_desct->base |= seg_desc->base1 << 16;
3505         kvm_desct->base |= seg_desc->base2 << 24;
3506         kvm_desct->limit = seg_desc->limit0;
3507         kvm_desct->limit |= seg_desc->limit << 16;
3508         if (seg_desc->g) {
3509                 kvm_desct->limit <<= 12;
3510                 kvm_desct->limit |= 0xfff;
3511         }
3512         kvm_desct->selector = selector;
3513         kvm_desct->type = seg_desc->type;
3514         kvm_desct->present = seg_desc->p;
3515         kvm_desct->dpl = seg_desc->dpl;
3516         kvm_desct->db = seg_desc->d;
3517         kvm_desct->s = seg_desc->s;
3518         kvm_desct->l = seg_desc->l;
3519         kvm_desct->g = seg_desc->g;
3520         kvm_desct->avl = seg_desc->avl;
3521         if (!selector)
3522                 kvm_desct->unusable = 1;
3523         else
3524                 kvm_desct->unusable = 0;
3525         kvm_desct->padding = 0;
3526 }
3527
3528 static void get_segment_descritptor_dtable(struct kvm_vcpu *vcpu,
3529                                            u16 selector,
3530                                            struct descriptor_table *dtable)
3531 {
3532         if (selector & 1 << 2) {
3533                 struct kvm_segment kvm_seg;
3534
3535                 kvm_get_segment(vcpu, &kvm_seg, VCPU_SREG_LDTR);
3536
3537                 if (kvm_seg.unusable)
3538                         dtable->limit = 0;
3539                 else
3540                         dtable->limit = kvm_seg.limit;
3541                 dtable->base = kvm_seg.base;
3542         }
3543         else
3544                 kvm_x86_ops->get_gdt(vcpu, dtable);
3545 }
3546
3547 /* allowed just for 8 bytes segments */
3548 static int load_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3549                                          struct desc_struct *seg_desc)
3550 {
3551         gpa_t gpa;
3552         struct descriptor_table dtable;
3553         u16 index = selector >> 3;
3554
3555         get_segment_descritptor_dtable(vcpu, selector, &dtable);
3556
3557         if (dtable.limit < index * 8 + 7) {
3558                 kvm_queue_exception_e(vcpu, GP_VECTOR, selector & 0xfffc);
3559                 return 1;
3560         }
3561         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, dtable.base);
3562         gpa += index * 8;
3563         return kvm_read_guest(vcpu->kvm, gpa, seg_desc, 8);
3564 }
3565
3566 /* allowed just for 8 bytes segments */
3567 static int save_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3568                                          struct desc_struct *seg_desc)
3569 {
3570         gpa_t gpa;
3571         struct descriptor_table dtable;
3572         u16 index = selector >> 3;
3573
3574         get_segment_descritptor_dtable(vcpu, selector, &dtable);
3575
3576         if (dtable.limit < index * 8 + 7)
3577                 return 1;
3578         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, dtable.base);
3579         gpa += index * 8;
3580         return kvm_write_guest(vcpu->kvm, gpa, seg_desc, 8);
3581 }
3582
3583 static u32 get_tss_base_addr(struct kvm_vcpu *vcpu,
3584                              struct desc_struct *seg_desc)
3585 {
3586         u32 base_addr;
3587
3588         base_addr = seg_desc->base0;
3589         base_addr |= (seg_desc->base1 << 16);
3590         base_addr |= (seg_desc->base2 << 24);
3591
3592         return vcpu->arch.mmu.gva_to_gpa(vcpu, base_addr);
3593 }
3594
3595 static u16 get_segment_selector(struct kvm_vcpu *vcpu, int seg)
3596 {
3597         struct kvm_segment kvm_seg;
3598
3599         kvm_get_segment(vcpu, &kvm_seg, seg);
3600         return kvm_seg.selector;
3601 }
3602
3603 static int load_segment_descriptor_to_kvm_desct(struct kvm_vcpu *vcpu,
3604                                                 u16 selector,
3605                                                 struct kvm_segment *kvm_seg)
3606 {
3607         struct desc_struct seg_desc;
3608
3609         if (load_guest_segment_descriptor(vcpu, selector, &seg_desc))
3610                 return 1;
3611         seg_desct_to_kvm_desct(&seg_desc, selector, kvm_seg);
3612         return 0;
3613 }
3614
3615 static int kvm_load_realmode_segment(struct kvm_vcpu *vcpu, u16 selector, int seg)
3616 {
3617         struct kvm_segment segvar = {
3618                 .base = selector << 4,
3619                 .limit = 0xffff,
3620                 .selector = selector,
3621                 .type = 3,
3622                 .present = 1,
3623                 .dpl = 3,
3624                 .db = 0,
3625                 .s = 1,
3626                 .l = 0,
3627                 .g = 0,
3628                 .avl = 0,
3629                 .unusable = 0,
3630         };
3631         kvm_x86_ops->set_segment(vcpu, &segvar, seg);
3632         return 0;
3633 }
3634
3635 int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3636                                 int type_bits, int seg)
3637 {
3638         struct kvm_segment kvm_seg;
3639
3640         if (!(vcpu->arch.cr0 & X86_CR0_PE))
3641                 return kvm_load_realmode_segment(vcpu, selector, seg);
3642         if (load_segment_descriptor_to_kvm_desct(vcpu, selector, &kvm_seg))
3643                 return 1;
3644         kvm_seg.type |= type_bits;
3645
3646         if (seg != VCPU_SREG_SS && seg != VCPU_SREG_CS &&
3647             seg != VCPU_SREG_LDTR)
3648                 if (!kvm_seg.s)
3649                         kvm_seg.unusable = 1;
3650
3651         kvm_set_segment(vcpu, &kvm_seg, seg);
3652         return 0;
3653 }
3654
3655 static void save_state_to_tss32(struct kvm_vcpu *vcpu,
3656                                 struct tss_segment_32 *tss)
3657 {
3658         tss->cr3 = vcpu->arch.cr3;
3659         tss->eip = kvm_rip_read(vcpu);
3660         tss->eflags = kvm_x86_ops->get_rflags(vcpu);
3661         tss->eax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3662         tss->ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3663         tss->edx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3664         tss->ebx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3665         tss->esp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3666         tss->ebp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3667         tss->esi = kvm_register_read(vcpu, VCPU_REGS_RSI);
3668         tss->edi = kvm_register_read(vcpu, VCPU_REGS_RDI);
3669         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3670         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3671         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3672         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3673         tss->fs = get_segment_selector(vcpu, VCPU_SREG_FS);
3674         tss->gs = get_segment_selector(vcpu, VCPU_SREG_GS);
3675         tss->ldt_selector = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3676         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3677 }
3678
3679 static int load_state_from_tss32(struct kvm_vcpu *vcpu,
3680                                   struct tss_segment_32 *tss)
3681 {
3682         kvm_set_cr3(vcpu, tss->cr3);
3683
3684         kvm_rip_write(vcpu, tss->eip);
3685         kvm_x86_ops->set_rflags(vcpu, tss->eflags | 2);
3686
3687         kvm_register_write(vcpu, VCPU_REGS_RAX, tss->eax);
3688         kvm_register_write(vcpu, VCPU_REGS_RCX, tss->ecx);
3689         kvm_register_write(vcpu, VCPU_REGS_RDX, tss->edx);
3690         kvm_register_write(vcpu, VCPU_REGS_RBX, tss->ebx);
3691         kvm_register_write(vcpu, VCPU_REGS_RSP, tss->esp);
3692         kvm_register_write(vcpu, VCPU_REGS_RBP, tss->ebp);
3693         kvm_register_write(vcpu, VCPU_REGS_RSI, tss->esi);
3694         kvm_register_write(vcpu, VCPU_REGS_RDI, tss->edi);
3695
3696         if (kvm_load_segment_descriptor(vcpu, tss->ldt_selector, 0, VCPU_SREG_LDTR))
3697                 return 1;
3698
3699         if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3700                 return 1;
3701
3702         if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3703                 return 1;
3704
3705         if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3706                 return 1;
3707
3708         if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3709                 return 1;
3710
3711         if (kvm_load_segment_descriptor(vcpu, tss->fs, 1, VCPU_SREG_FS))
3712                 return 1;
3713
3714         if (kvm_load_segment_descriptor(vcpu, tss->gs, 1, VCPU_SREG_GS))
3715                 return 1;
3716         return 0;
3717 }
3718
3719 static void save_state_to_tss16(struct kvm_vcpu *vcpu,
3720                                 struct tss_segment_16 *tss)
3721 {
3722         tss->ip = kvm_rip_read(vcpu);
3723         tss->flag = kvm_x86_ops->get_rflags(vcpu);
3724         tss->ax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3725         tss->cx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3726         tss->dx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3727         tss->bx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3728         tss->sp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3729         tss->bp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3730         tss->si = kvm_register_read(vcpu, VCPU_REGS_RSI);
3731         tss->di = kvm_register_read(vcpu, VCPU_REGS_RDI);
3732
3733         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3734         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3735         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3736         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3737         tss->ldt = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3738         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3739 }
3740
3741 static int load_state_from_tss16(struct kvm_vcpu *vcpu,
3742                                  struct tss_segment_16 *tss)
3743 {
3744         kvm_rip_write(vcpu, tss->ip);
3745         kvm_x86_ops->set_rflags(vcpu, tss->flag | 2);
3746         kvm_register_write(vcpu, VCPU_REGS_RAX, tss->ax);
3747         kvm_register_write(vcpu, VCPU_REGS_RCX, tss->cx);
3748         kvm_register_write(vcpu, VCPU_REGS_RDX, tss->dx);
3749         kvm_register_write(vcpu, VCPU_REGS_RBX, tss->bx);
3750         kvm_register_write(vcpu, VCPU_REGS_RSP, tss->sp);
3751         kvm_register_write(vcpu, VCPU_REGS_RBP, tss->bp);
3752         kvm_register_write(vcpu, VCPU_REGS_RSI, tss->si);
3753         kvm_register_write(vcpu, VCPU_REGS_RDI, tss->di);
3754
3755         if (kvm_load_segment_descriptor(vcpu, tss->ldt, 0, VCPU_SREG_LDTR))
3756                 return 1;
3757
3758         if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3759                 return 1;
3760
3761         if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3762                 return 1;
3763
3764         if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3765                 return 1;
3766
3767         if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3768                 return 1;
3769         return 0;
3770 }
3771
3772 static int kvm_task_switch_16(struct kvm_vcpu *vcpu, u16 tss_selector,
3773                        u32 old_tss_base,
3774                        struct desc_struct *nseg_desc)
3775 {
3776         struct tss_segment_16 tss_segment_16;
3777         int ret = 0;
3778
3779         if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
3780                            sizeof tss_segment_16))
3781                 goto out;
3782
3783         save_state_to_tss16(vcpu, &tss_segment_16);
3784
3785         if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
3786                             sizeof tss_segment_16))
3787                 goto out;
3788
3789         if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
3790                            &tss_segment_16, sizeof tss_segment_16))
3791                 goto out;
3792
3793         if (load_state_from_tss16(vcpu, &tss_segment_16))
3794                 goto out;
3795
3796         ret = 1;
3797 out:
3798         return ret;
3799 }
3800
3801 static int kvm_task_switch_32(struct kvm_vcpu *vcpu, u16 tss_selector,
3802                        u32 old_tss_base,
3803                        struct desc_struct *nseg_desc)
3804 {
3805         struct tss_segment_32 tss_segment_32;
3806         int ret = 0;
3807
3808         if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
3809                            sizeof tss_segment_32))
3810                 goto out;
3811
3812         save_state_to_tss32(vcpu, &tss_segment_32);
3813
3814         if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
3815                             sizeof tss_segment_32))
3816                 goto out;
3817
3818         if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
3819                            &tss_segment_32, sizeof tss_segment_32))
3820                 goto out;
3821
3822         if (load_state_from_tss32(vcpu, &tss_segment_32))
3823                 goto out;
3824
3825         ret = 1;
3826 out:
3827         return ret;
3828 }
3829
3830 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason)
3831 {
3832         struct kvm_segment tr_seg;
3833         struct desc_struct cseg_desc;
3834         struct desc_struct nseg_desc;
3835         int ret = 0;
3836         u32 old_tss_base = get_segment_base(vcpu, VCPU_SREG_TR);
3837         u16 old_tss_sel = get_segment_selector(vcpu, VCPU_SREG_TR);
3838
3839         old_tss_base = vcpu->arch.mmu.gva_to_gpa(vcpu, old_tss_base);
3840
3841         /* FIXME: Handle errors. Failure to read either TSS or their
3842          * descriptors should generate a pagefault.
3843          */
3844         if (load_guest_segment_descriptor(vcpu, tss_selector, &nseg_desc))
3845                 goto out;
3846
3847         if (load_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc))
3848                 goto out;
3849
3850         if (reason != TASK_SWITCH_IRET) {
3851                 int cpl;
3852
3853                 cpl = kvm_x86_ops->get_cpl(vcpu);
3854                 if ((tss_selector & 3) > nseg_desc.dpl || cpl > nseg_desc.dpl) {
3855                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
3856                         return 1;
3857                 }
3858         }
3859
3860         if (!nseg_desc.p || (nseg_desc.limit0 | nseg_desc.limit << 16) < 0x67) {
3861                 kvm_queue_exception_e(vcpu, TS_VECTOR, tss_selector & 0xfffc);
3862                 return 1;
3863         }
3864
3865         if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
3866                 cseg_desc.type &= ~(1 << 1); //clear the B flag
3867                 save_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc);
3868         }
3869
3870         if (reason == TASK_SWITCH_IRET) {
3871                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3872                 kvm_x86_ops->set_rflags(vcpu, eflags & ~X86_EFLAGS_NT);
3873         }
3874
3875         kvm_x86_ops->skip_emulated_instruction(vcpu);
3876
3877         if (nseg_desc.type & 8)
3878                 ret = kvm_task_switch_32(vcpu, tss_selector, old_tss_base,
3879                                          &nseg_desc);
3880         else
3881                 ret = kvm_task_switch_16(vcpu, tss_selector, old_tss_base,
3882                                          &nseg_desc);
3883
3884         if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) {
3885                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3886                 kvm_x86_ops->set_rflags(vcpu, eflags | X86_EFLAGS_NT);
3887         }
3888
3889         if (reason != TASK_SWITCH_IRET) {
3890                 nseg_desc.type |= (1 << 1);
3891                 save_guest_segment_descriptor(vcpu, tss_selector,
3892                                               &nseg_desc);
3893         }
3894
3895         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 | X86_CR0_TS);
3896         seg_desct_to_kvm_desct(&nseg_desc, tss_selector, &tr_seg);
3897         tr_seg.type = 11;
3898         kvm_set_segment(vcpu, &tr_seg, VCPU_SREG_TR);
3899 out:
3900         return ret;
3901 }
3902 EXPORT_SYMBOL_GPL(kvm_task_switch);
3903
3904 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
3905                                   struct kvm_sregs *sregs)
3906 {
3907         int mmu_reset_needed = 0;
3908         int i, pending_vec, max_bits;
3909         struct descriptor_table dt;
3910
3911         vcpu_load(vcpu);
3912
3913         dt.limit = sregs->idt.limit;
3914         dt.base = sregs->idt.base;
3915         kvm_x86_ops->set_idt(vcpu, &dt);
3916         dt.limit = sregs->gdt.limit;
3917         dt.base = sregs->gdt.base;
3918         kvm_x86_ops->set_gdt(vcpu, &dt);
3919
3920         vcpu->arch.cr2 = sregs->cr2;
3921         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
3922         vcpu->arch.cr3 = sregs->cr3;
3923
3924         kvm_set_cr8(vcpu, sregs->cr8);
3925
3926         mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
3927         kvm_x86_ops->set_efer(vcpu, sregs->efer);
3928         kvm_set_apic_base(vcpu, sregs->apic_base);
3929
3930         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3931
3932         mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
3933         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
3934         vcpu->arch.cr0 = sregs->cr0;
3935
3936         mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
3937         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
3938         if (!is_long_mode(vcpu) && is_pae(vcpu))
3939                 load_pdptrs(vcpu, vcpu->arch.cr3);
3940
3941         if (mmu_reset_needed)
3942                 kvm_mmu_reset_context(vcpu);
3943
3944         if (!irqchip_in_kernel(vcpu->kvm)) {
3945                 memcpy(vcpu->arch.irq_pending, sregs->interrupt_bitmap,
3946                        sizeof vcpu->arch.irq_pending);
3947                 vcpu->arch.irq_summary = 0;
3948                 for (i = 0; i < ARRAY_SIZE(vcpu->arch.irq_pending); ++i)
3949                         if (vcpu->arch.irq_pending[i])
3950                                 __set_bit(i, &vcpu->arch.irq_summary);
3951         } else {
3952                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
3953                 pending_vec = find_first_bit(
3954                         (const unsigned long *)sregs->interrupt_bitmap,
3955                         max_bits);
3956                 /* Only pending external irq is handled here */
3957                 if (pending_vec < max_bits) {
3958                         kvm_x86_ops->set_irq(vcpu, pending_vec);
3959                         pr_debug("Set back pending irq %d\n",
3960                                  pending_vec);
3961                 }
3962         }
3963
3964         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3965         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3966         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3967         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3968         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3969         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3970
3971         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3972         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3973
3974         /* Older userspace won't unhalt the vcpu on reset. */
3975         if (vcpu->vcpu_id == 0 && kvm_rip_read(vcpu) == 0xfff0 &&
3976             sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
3977             !(vcpu->arch.cr0 & X86_CR0_PE))
3978                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3979
3980         vcpu_put(vcpu);
3981
3982         return 0;
3983 }
3984
3985 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
3986                                     struct kvm_debug_guest *dbg)
3987 {
3988         int r;
3989
3990         vcpu_load(vcpu);
3991
3992         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
3993
3994         vcpu_put(vcpu);
3995
3996         return r;
3997 }
3998
3999 /*
4000  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
4001  * we have asm/x86/processor.h
4002  */
4003 struct fxsave {
4004         u16     cwd;
4005         u16     swd;
4006         u16     twd;
4007         u16     fop;
4008         u64     rip;
4009         u64     rdp;
4010         u32     mxcsr;
4011         u32     mxcsr_mask;
4012         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
4013 #ifdef CONFIG_X86_64
4014         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
4015 #else
4016         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
4017 #endif
4018 };
4019
4020 /*
4021  * Translate a guest virtual address to a guest physical address.
4022  */
4023 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
4024                                     struct kvm_translation *tr)
4025 {
4026         unsigned long vaddr = tr->linear_address;
4027         gpa_t gpa;
4028
4029         vcpu_load(vcpu);
4030         down_read(&vcpu->kvm->slots_lock);
4031         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
4032         up_read(&vcpu->kvm->slots_lock);
4033         tr->physical_address = gpa;
4034         tr->valid = gpa != UNMAPPED_GVA;
4035         tr->writeable = 1;
4036         tr->usermode = 0;
4037         vcpu_put(vcpu);
4038
4039         return 0;
4040 }
4041
4042 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
4043 {
4044         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
4045
4046         vcpu_load(vcpu);
4047
4048         memcpy(fpu->fpr, fxsave->st_space, 128);
4049         fpu->fcw = fxsave->cwd;
4050         fpu->fsw = fxsave->swd;
4051         fpu->ftwx = fxsave->twd;
4052         fpu->last_opcode = fxsave->fop;
4053         fpu->last_ip = fxsave->rip;
4054         fpu->last_dp = fxsave->rdp;
4055         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
4056
4057         vcpu_put(vcpu);
4058
4059         return 0;
4060 }
4061
4062 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
4063 {
4064         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
4065
4066         vcpu_load(vcpu);
4067
4068         memcpy(fxsave->st_space, fpu->fpr, 128);
4069         fxsave->cwd = fpu->fcw;
4070         fxsave->swd = fpu->fsw;
4071         fxsave->twd = fpu->ftwx;
4072         fxsave->fop = fpu->last_opcode;
4073         fxsave->rip = fpu->last_ip;
4074         fxsave->rdp = fpu->last_dp;
4075         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
4076
4077         vcpu_put(vcpu);
4078
4079         return 0;
4080 }
4081
4082 void fx_init(struct kvm_vcpu *vcpu)
4083 {
4084         unsigned after_mxcsr_mask;
4085
4086         /*
4087          * Touch the fpu the first time in non atomic context as if
4088          * this is the first fpu instruction the exception handler
4089          * will fire before the instruction returns and it'll have to
4090          * allocate ram with GFP_KERNEL.
4091          */
4092         if (!used_math())
4093                 kvm_fx_save(&vcpu->arch.host_fx_image);
4094
4095         /* Initialize guest FPU by resetting ours and saving into guest's */
4096         preempt_disable();
4097         kvm_fx_save(&vcpu->arch.host_fx_image);
4098         kvm_fx_finit();
4099         kvm_fx_save(&vcpu->arch.guest_fx_image);
4100         kvm_fx_restore(&vcpu->arch.host_fx_image);
4101         preempt_enable();
4102
4103         vcpu->arch.cr0 |= X86_CR0_ET;
4104         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
4105         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
4106         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
4107                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
4108 }
4109 EXPORT_SYMBOL_GPL(fx_init);
4110
4111 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
4112 {
4113         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
4114                 return;
4115
4116         vcpu->guest_fpu_loaded = 1;
4117         kvm_fx_save(&vcpu->arch.host_fx_image);
4118         kvm_fx_restore(&vcpu->arch.guest_fx_image);
4119 }
4120 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
4121
4122 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
4123 {
4124         if (!vcpu->guest_fpu_loaded)
4125                 return;
4126
4127         vcpu->guest_fpu_loaded = 0;
4128         kvm_fx_save(&vcpu->arch.guest_fx_image);
4129         kvm_fx_restore(&vcpu->arch.host_fx_image);
4130         ++vcpu->stat.fpu_reload;
4131 }
4132 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
4133
4134 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
4135 {
4136         kvm_x86_ops->vcpu_free(vcpu);
4137 }
4138
4139 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
4140                                                 unsigned int id)
4141 {
4142         return kvm_x86_ops->vcpu_create(kvm, id);
4143 }
4144
4145 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
4146 {
4147         int r;
4148
4149         /* We do fxsave: this must be aligned. */
4150         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
4151
4152         vcpu_load(vcpu);
4153         r = kvm_arch_vcpu_reset(vcpu);
4154         if (r == 0)
4155                 r = kvm_mmu_setup(vcpu);
4156         vcpu_put(vcpu);
4157         if (r < 0)
4158                 goto free_vcpu;
4159
4160         return 0;
4161 free_vcpu:
4162         kvm_x86_ops->vcpu_free(vcpu);
4163         return r;
4164 }
4165
4166 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
4167 {
4168         vcpu_load(vcpu);
4169         kvm_mmu_unload(vcpu);
4170         vcpu_put(vcpu);
4171
4172         kvm_x86_ops->vcpu_free(vcpu);
4173 }
4174
4175 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
4176 {
4177         return kvm_x86_ops->vcpu_reset(vcpu);
4178 }
4179
4180 void kvm_arch_hardware_enable(void *garbage)
4181 {
4182         kvm_x86_ops->hardware_enable(garbage);
4183 }
4184
4185 void kvm_arch_hardware_disable(void *garbage)
4186 {
4187         kvm_x86_ops->hardware_disable(garbage);
4188 }
4189
4190 int kvm_arch_hardware_setup(void)
4191 {
4192         return kvm_x86_ops->hardware_setup();
4193 }
4194
4195 void kvm_arch_hardware_unsetup(void)
4196 {
4197         kvm_x86_ops->hardware_unsetup();
4198 }
4199
4200 void kvm_arch_check_processor_compat(void *rtn)
4201 {
4202         kvm_x86_ops->check_processor_compatibility(rtn);
4203 }
4204
4205 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
4206 {
4207         struct page *page;
4208         struct kvm *kvm;
4209         int r;
4210
4211         BUG_ON(vcpu->kvm == NULL);
4212         kvm = vcpu->kvm;
4213
4214         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
4215         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
4216                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4217         else
4218                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
4219
4220         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
4221         if (!page) {
4222                 r = -ENOMEM;
4223                 goto fail;
4224         }
4225         vcpu->arch.pio_data = page_address(page);
4226
4227         r = kvm_mmu_create(vcpu);
4228         if (r < 0)
4229                 goto fail_free_pio_data;
4230
4231         if (irqchip_in_kernel(kvm)) {
4232                 r = kvm_create_lapic(vcpu);
4233                 if (r < 0)
4234                         goto fail_mmu_destroy;
4235         }
4236
4237         return 0;
4238
4239 fail_mmu_destroy:
4240         kvm_mmu_destroy(vcpu);
4241 fail_free_pio_data:
4242         free_page((unsigned long)vcpu->arch.pio_data);
4243 fail:
4244         return r;
4245 }
4246
4247 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
4248 {
4249         kvm_free_lapic(vcpu);
4250         down_read(&vcpu->kvm->slots_lock);
4251         kvm_mmu_destroy(vcpu);
4252         up_read(&vcpu->kvm->slots_lock);
4253         free_page((unsigned long)vcpu->arch.pio_data);
4254 }
4255
4256 struct  kvm *kvm_arch_create_vm(void)
4257 {
4258         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
4259
4260         if (!kvm)
4261                 return ERR_PTR(-ENOMEM);
4262
4263         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
4264         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
4265
4266         return kvm;
4267 }
4268
4269 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
4270 {
4271         vcpu_load(vcpu);
4272         kvm_mmu_unload(vcpu);
4273         vcpu_put(vcpu);
4274 }
4275
4276 static void kvm_free_vcpus(struct kvm *kvm)
4277 {
4278         unsigned int i;
4279
4280         /*
4281          * Unpin any mmu pages first.
4282          */
4283         for (i = 0; i < KVM_MAX_VCPUS; ++i)
4284                 if (kvm->vcpus[i])
4285                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
4286         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
4287                 if (kvm->vcpus[i]) {
4288                         kvm_arch_vcpu_free(kvm->vcpus[i]);
4289                         kvm->vcpus[i] = NULL;
4290                 }
4291         }
4292
4293 }
4294
4295 void kvm_arch_destroy_vm(struct kvm *kvm)
4296 {
4297         kvm_iommu_unmap_guest(kvm);
4298         kvm_free_all_assigned_devices(kvm);
4299         kvm_free_pit(kvm);
4300         kfree(kvm->arch.vpic);
4301         kfree(kvm->arch.vioapic);
4302         kvm_free_vcpus(kvm);
4303         kvm_free_physmem(kvm);
4304         if (kvm->arch.apic_access_page)
4305                 put_page(kvm->arch.apic_access_page);
4306         if (kvm->arch.ept_identity_pagetable)
4307                 put_page(kvm->arch.ept_identity_pagetable);
4308         kfree(kvm);
4309 }
4310
4311 int kvm_arch_set_memory_region(struct kvm *kvm,
4312                                 struct kvm_userspace_memory_region *mem,
4313                                 struct kvm_memory_slot old,
4314                                 int user_alloc)
4315 {
4316         int npages = mem->memory_size >> PAGE_SHIFT;
4317         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
4318
4319         /*To keep backward compatibility with older userspace,
4320          *x86 needs to hanlde !user_alloc case.
4321          */
4322         if (!user_alloc) {
4323                 if (npages && !old.rmap) {
4324                         unsigned long userspace_addr;
4325
4326                         down_write(&current->mm->mmap_sem);
4327                         userspace_addr = do_mmap(NULL, 0,
4328                                                  npages * PAGE_SIZE,
4329                                                  PROT_READ | PROT_WRITE,
4330                                                  MAP_PRIVATE | MAP_ANONYMOUS,
4331                                                  0);
4332                         up_write(&current->mm->mmap_sem);
4333
4334                         if (IS_ERR((void *)userspace_addr))
4335                                 return PTR_ERR((void *)userspace_addr);
4336
4337                         /* set userspace_addr atomically for kvm_hva_to_rmapp */
4338                         spin_lock(&kvm->mmu_lock);
4339                         memslot->userspace_addr = userspace_addr;
4340                         spin_unlock(&kvm->mmu_lock);
4341                 } else {
4342                         if (!old.user_alloc && old.rmap) {
4343                                 int ret;
4344
4345                                 down_write(&current->mm->mmap_sem);
4346                                 ret = do_munmap(current->mm, old.userspace_addr,
4347                                                 old.npages * PAGE_SIZE);
4348                                 up_write(&current->mm->mmap_sem);
4349                                 if (ret < 0)
4350                                         printk(KERN_WARNING
4351                                        "kvm_vm_ioctl_set_memory_region: "
4352                                        "failed to munmap memory\n");
4353                         }
4354                 }
4355         }
4356
4357         if (!kvm->arch.n_requested_mmu_pages) {
4358                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
4359                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
4360         }
4361
4362         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
4363         kvm_flush_remote_tlbs(kvm);
4364
4365         return 0;
4366 }
4367
4368 void kvm_arch_flush_shadow(struct kvm *kvm)
4369 {
4370         kvm_mmu_zap_all(kvm);
4371 }
4372
4373 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
4374 {
4375         return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
4376                || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED;
4377 }
4378
4379 static void vcpu_kick_intr(void *info)
4380 {
4381 #ifdef DEBUG
4382         struct kvm_vcpu *vcpu = (struct kvm_vcpu *)info;
4383         printk(KERN_DEBUG "vcpu_kick_intr %p \n", vcpu);
4384 #endif
4385 }
4386
4387 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
4388 {
4389         int ipi_pcpu = vcpu->cpu;
4390         int cpu = get_cpu();
4391
4392         if (waitqueue_active(&vcpu->wq)) {
4393                 wake_up_interruptible(&vcpu->wq);
4394                 ++vcpu->stat.halt_wakeup;
4395         }
4396         /*
4397          * We may be called synchronously with irqs disabled in guest mode,
4398          * So need not to call smp_call_function_single() in that case.
4399          */
4400         if (vcpu->guest_mode && vcpu->cpu != cpu)
4401                 smp_call_function_single(ipi_pcpu, vcpu_kick_intr, vcpu, 0);
4402         put_cpu();
4403 }