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