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