KVM: x86: trap invlpg
[linux-2.6.git] / arch / x86 / kvm / x86.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * derived from drivers/kvm/kvm_main.c
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright (C) 2008 Qumranet, Inc.
8  * Copyright IBM Corporation, 2008
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *   Amit Shah    <amit.shah@qumranet.com>
14  *   Ben-Ami Yassour <benami@il.ibm.com>
15  *
16  * This work is licensed under the terms of the GNU GPL, version 2.  See
17  * the COPYING file in the top-level directory.
18  *
19  */
20
21 #include <linux/kvm_host.h>
22 #include "irq.h"
23 #include "mmu.h"
24 #include "i8254.h"
25 #include "tss.h"
26 #include "kvm_cache_regs.h"
27 #include "x86.h"
28
29 #include <linux/clocksource.h>
30 #include <linux/interrupt.h>
31 #include <linux/kvm.h>
32 #include <linux/fs.h>
33 #include <linux/pci.h>
34 #include <linux/vmalloc.h>
35 #include <linux/module.h>
36 #include <linux/mman.h>
37 #include <linux/highmem.h>
38 #include <linux/intel-iommu.h>
39
40 #include <asm/uaccess.h>
41 #include <asm/msr.h>
42 #include <asm/desc.h>
43
44 #define MAX_IO_MSRS 256
45 #define CR0_RESERVED_BITS                                               \
46         (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
47                           | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
48                           | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
49 #define CR4_RESERVED_BITS                                               \
50         (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
51                           | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE     \
52                           | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR  \
53                           | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
54
55 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
56 /* EFER defaults:
57  * - enable syscall per default because its emulated by KVM
58  * - enable LME and LMA per default on 64 bit KVM
59  */
60 #ifdef CONFIG_X86_64
61 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffafeULL;
62 #else
63 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffffeULL;
64 #endif
65
66 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
67 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
68
69 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
70                                     struct kvm_cpuid_entry2 __user *entries);
71
72 struct kvm_x86_ops *kvm_x86_ops;
73 EXPORT_SYMBOL_GPL(kvm_x86_ops);
74
75 struct kvm_stats_debugfs_item debugfs_entries[] = {
76         { "pf_fixed", VCPU_STAT(pf_fixed) },
77         { "pf_guest", VCPU_STAT(pf_guest) },
78         { "tlb_flush", VCPU_STAT(tlb_flush) },
79         { "invlpg", VCPU_STAT(invlpg) },
80         { "exits", VCPU_STAT(exits) },
81         { "io_exits", VCPU_STAT(io_exits) },
82         { "mmio_exits", VCPU_STAT(mmio_exits) },
83         { "signal_exits", VCPU_STAT(signal_exits) },
84         { "irq_window", VCPU_STAT(irq_window_exits) },
85         { "nmi_window", VCPU_STAT(nmi_window_exits) },
86         { "halt_exits", VCPU_STAT(halt_exits) },
87         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
88         { "hypercalls", VCPU_STAT(hypercalls) },
89         { "request_irq", VCPU_STAT(request_irq_exits) },
90         { "irq_exits", VCPU_STAT(irq_exits) },
91         { "host_state_reload", VCPU_STAT(host_state_reload) },
92         { "efer_reload", VCPU_STAT(efer_reload) },
93         { "fpu_reload", VCPU_STAT(fpu_reload) },
94         { "insn_emulation", VCPU_STAT(insn_emulation) },
95         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
96         { "irq_injections", VCPU_STAT(irq_injections) },
97         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
98         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
99         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
100         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
101         { "mmu_flooded", VM_STAT(mmu_flooded) },
102         { "mmu_recycled", VM_STAT(mmu_recycled) },
103         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
104         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
105         { "largepages", VM_STAT(lpages) },
106         { NULL }
107 };
108
109 static struct kvm_assigned_dev_kernel *kvm_find_assigned_dev(struct list_head *head,
110                                                       int assigned_dev_id)
111 {
112         struct list_head *ptr;
113         struct kvm_assigned_dev_kernel *match;
114
115         list_for_each(ptr, head) {
116                 match = list_entry(ptr, struct kvm_assigned_dev_kernel, list);
117                 if (match->assigned_dev_id == assigned_dev_id)
118                         return match;
119         }
120         return NULL;
121 }
122
123 static void kvm_assigned_dev_interrupt_work_handler(struct work_struct *work)
124 {
125         struct kvm_assigned_dev_kernel *assigned_dev;
126
127         assigned_dev = container_of(work, struct kvm_assigned_dev_kernel,
128                                     interrupt_work);
129
130         /* This is taken to safely inject irq inside the guest. When
131          * the interrupt injection (or the ioapic code) uses a
132          * finer-grained lock, update this
133          */
134         mutex_lock(&assigned_dev->kvm->lock);
135         kvm_set_irq(assigned_dev->kvm,
136                     assigned_dev->guest_irq, 1);
137         mutex_unlock(&assigned_dev->kvm->lock);
138         kvm_put_kvm(assigned_dev->kvm);
139 }
140
141 /* FIXME: Implement the OR logic needed to make shared interrupts on
142  * this line behave properly
143  */
144 static irqreturn_t kvm_assigned_dev_intr(int irq, void *dev_id)
145 {
146         struct kvm_assigned_dev_kernel *assigned_dev =
147                 (struct kvm_assigned_dev_kernel *) dev_id;
148
149         kvm_get_kvm(assigned_dev->kvm);
150         schedule_work(&assigned_dev->interrupt_work);
151         disable_irq_nosync(irq);
152         return IRQ_HANDLED;
153 }
154
155 /* Ack the irq line for an assigned device */
156 static void kvm_assigned_dev_ack_irq(struct kvm_irq_ack_notifier *kian)
157 {
158         struct kvm_assigned_dev_kernel *dev;
159
160         if (kian->gsi == -1)
161                 return;
162
163         dev = container_of(kian, struct kvm_assigned_dev_kernel,
164                            ack_notifier);
165         kvm_set_irq(dev->kvm, dev->guest_irq, 0);
166         enable_irq(dev->host_irq);
167 }
168
169 static void kvm_free_assigned_device(struct kvm *kvm,
170                                      struct kvm_assigned_dev_kernel
171                                      *assigned_dev)
172 {
173         if (irqchip_in_kernel(kvm) && assigned_dev->irq_requested)
174                 free_irq(assigned_dev->host_irq, (void *)assigned_dev);
175
176         kvm_unregister_irq_ack_notifier(kvm, &assigned_dev->ack_notifier);
177
178         if (cancel_work_sync(&assigned_dev->interrupt_work))
179                 /* We had pending work. That means we will have to take
180                  * care of kvm_put_kvm.
181                  */
182                 kvm_put_kvm(kvm);
183
184         pci_release_regions(assigned_dev->dev);
185         pci_disable_device(assigned_dev->dev);
186         pci_dev_put(assigned_dev->dev);
187
188         list_del(&assigned_dev->list);
189         kfree(assigned_dev);
190 }
191
192 static void kvm_free_all_assigned_devices(struct kvm *kvm)
193 {
194         struct list_head *ptr, *ptr2;
195         struct kvm_assigned_dev_kernel *assigned_dev;
196
197         list_for_each_safe(ptr, ptr2, &kvm->arch.assigned_dev_head) {
198                 assigned_dev = list_entry(ptr,
199                                           struct kvm_assigned_dev_kernel,
200                                           list);
201
202                 kvm_free_assigned_device(kvm, assigned_dev);
203         }
204 }
205
206 static int kvm_vm_ioctl_assign_irq(struct kvm *kvm,
207                                    struct kvm_assigned_irq
208                                    *assigned_irq)
209 {
210         int r = 0;
211         struct kvm_assigned_dev_kernel *match;
212
213         mutex_lock(&kvm->lock);
214
215         match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
216                                       assigned_irq->assigned_dev_id);
217         if (!match) {
218                 mutex_unlock(&kvm->lock);
219                 return -EINVAL;
220         }
221
222         if (match->irq_requested) {
223                 match->guest_irq = assigned_irq->guest_irq;
224                 match->ack_notifier.gsi = assigned_irq->guest_irq;
225                 mutex_unlock(&kvm->lock);
226                 return 0;
227         }
228
229         INIT_WORK(&match->interrupt_work,
230                   kvm_assigned_dev_interrupt_work_handler);
231
232         if (irqchip_in_kernel(kvm)) {
233                 if (!capable(CAP_SYS_RAWIO)) {
234                         r = -EPERM;
235                         goto out_release;
236                 }
237
238                 if (assigned_irq->host_irq)
239                         match->host_irq = assigned_irq->host_irq;
240                 else
241                         match->host_irq = match->dev->irq;
242                 match->guest_irq = assigned_irq->guest_irq;
243                 match->ack_notifier.gsi = assigned_irq->guest_irq;
244                 match->ack_notifier.irq_acked = kvm_assigned_dev_ack_irq;
245                 kvm_register_irq_ack_notifier(kvm, &match->ack_notifier);
246
247                 /* Even though this is PCI, we don't want to use shared
248                  * interrupts. Sharing host devices with guest-assigned devices
249                  * on the same interrupt line is not a happy situation: there
250                  * are going to be long delays in accepting, acking, etc.
251                  */
252                 if (request_irq(match->host_irq, kvm_assigned_dev_intr, 0,
253                                 "kvm_assigned_device", (void *)match)) {
254                         r = -EIO;
255                         goto out_release;
256                 }
257         }
258
259         match->irq_requested = true;
260         mutex_unlock(&kvm->lock);
261         return r;
262 out_release:
263         mutex_unlock(&kvm->lock);
264         kvm_free_assigned_device(kvm, match);
265         return r;
266 }
267
268 static int kvm_vm_ioctl_assign_device(struct kvm *kvm,
269                                       struct kvm_assigned_pci_dev *assigned_dev)
270 {
271         int r = 0;
272         struct kvm_assigned_dev_kernel *match;
273         struct pci_dev *dev;
274
275         mutex_lock(&kvm->lock);
276
277         match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
278                                       assigned_dev->assigned_dev_id);
279         if (match) {
280                 /* device already assigned */
281                 r = -EINVAL;
282                 goto out;
283         }
284
285         match = kzalloc(sizeof(struct kvm_assigned_dev_kernel), GFP_KERNEL);
286         if (match == NULL) {
287                 printk(KERN_INFO "%s: Couldn't allocate memory\n",
288                        __func__);
289                 r = -ENOMEM;
290                 goto out;
291         }
292         dev = pci_get_bus_and_slot(assigned_dev->busnr,
293                                    assigned_dev->devfn);
294         if (!dev) {
295                 printk(KERN_INFO "%s: host device not found\n", __func__);
296                 r = -EINVAL;
297                 goto out_free;
298         }
299         if (pci_enable_device(dev)) {
300                 printk(KERN_INFO "%s: Could not enable PCI device\n", __func__);
301                 r = -EBUSY;
302                 goto out_put;
303         }
304         r = pci_request_regions(dev, "kvm_assigned_device");
305         if (r) {
306                 printk(KERN_INFO "%s: Could not get access to device regions\n",
307                        __func__);
308                 goto out_disable;
309         }
310         match->assigned_dev_id = assigned_dev->assigned_dev_id;
311         match->host_busnr = assigned_dev->busnr;
312         match->host_devfn = assigned_dev->devfn;
313         match->dev = dev;
314
315         match->kvm = kvm;
316
317         list_add(&match->list, &kvm->arch.assigned_dev_head);
318
319         if (assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU) {
320                 r = kvm_iommu_map_guest(kvm, match);
321                 if (r)
322                         goto out_list_del;
323         }
324
325 out:
326         mutex_unlock(&kvm->lock);
327         return r;
328 out_list_del:
329         list_del(&match->list);
330         pci_release_regions(dev);
331 out_disable:
332         pci_disable_device(dev);
333 out_put:
334         pci_dev_put(dev);
335 out_free:
336         kfree(match);
337         mutex_unlock(&kvm->lock);
338         return r;
339 }
340
341 unsigned long segment_base(u16 selector)
342 {
343         struct descriptor_table gdt;
344         struct desc_struct *d;
345         unsigned long table_base;
346         unsigned long v;
347
348         if (selector == 0)
349                 return 0;
350
351         asm("sgdt %0" : "=m"(gdt));
352         table_base = gdt.base;
353
354         if (selector & 4) {           /* from ldt */
355                 u16 ldt_selector;
356
357                 asm("sldt %0" : "=g"(ldt_selector));
358                 table_base = segment_base(ldt_selector);
359         }
360         d = (struct desc_struct *)(table_base + (selector & ~7));
361         v = d->base0 | ((unsigned long)d->base1 << 16) |
362                 ((unsigned long)d->base2 << 24);
363 #ifdef CONFIG_X86_64
364         if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
365                 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
366 #endif
367         return v;
368 }
369 EXPORT_SYMBOL_GPL(segment_base);
370
371 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
372 {
373         if (irqchip_in_kernel(vcpu->kvm))
374                 return vcpu->arch.apic_base;
375         else
376                 return vcpu->arch.apic_base;
377 }
378 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
379
380 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
381 {
382         /* TODO: reserve bits check */
383         if (irqchip_in_kernel(vcpu->kvm))
384                 kvm_lapic_set_base(vcpu, data);
385         else
386                 vcpu->arch.apic_base = data;
387 }
388 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
389
390 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
391 {
392         WARN_ON(vcpu->arch.exception.pending);
393         vcpu->arch.exception.pending = true;
394         vcpu->arch.exception.has_error_code = false;
395         vcpu->arch.exception.nr = nr;
396 }
397 EXPORT_SYMBOL_GPL(kvm_queue_exception);
398
399 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, unsigned long addr,
400                            u32 error_code)
401 {
402         ++vcpu->stat.pf_guest;
403         if (vcpu->arch.exception.pending) {
404                 if (vcpu->arch.exception.nr == PF_VECTOR) {
405                         printk(KERN_DEBUG "kvm: inject_page_fault:"
406                                         " double fault 0x%lx\n", addr);
407                         vcpu->arch.exception.nr = DF_VECTOR;
408                         vcpu->arch.exception.error_code = 0;
409                 } else if (vcpu->arch.exception.nr == DF_VECTOR) {
410                         /* triple fault -> shutdown */
411                         set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
412                 }
413                 return;
414         }
415         vcpu->arch.cr2 = addr;
416         kvm_queue_exception_e(vcpu, PF_VECTOR, error_code);
417 }
418
419 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
420 {
421         vcpu->arch.nmi_pending = 1;
422 }
423 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
424
425 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
426 {
427         WARN_ON(vcpu->arch.exception.pending);
428         vcpu->arch.exception.pending = true;
429         vcpu->arch.exception.has_error_code = true;
430         vcpu->arch.exception.nr = nr;
431         vcpu->arch.exception.error_code = error_code;
432 }
433 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
434
435 static void __queue_exception(struct kvm_vcpu *vcpu)
436 {
437         kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
438                                      vcpu->arch.exception.has_error_code,
439                                      vcpu->arch.exception.error_code);
440 }
441
442 /*
443  * Load the pae pdptrs.  Return true is they are all valid.
444  */
445 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
446 {
447         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
448         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
449         int i;
450         int ret;
451         u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
452
453         ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
454                                   offset * sizeof(u64), sizeof(pdpte));
455         if (ret < 0) {
456                 ret = 0;
457                 goto out;
458         }
459         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
460                 if ((pdpte[i] & 1) && (pdpte[i] & 0xfffffff0000001e6ull)) {
461                         ret = 0;
462                         goto out;
463                 }
464         }
465         ret = 1;
466
467         memcpy(vcpu->arch.pdptrs, pdpte, sizeof(vcpu->arch.pdptrs));
468 out:
469
470         return ret;
471 }
472 EXPORT_SYMBOL_GPL(load_pdptrs);
473
474 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
475 {
476         u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
477         bool changed = true;
478         int r;
479
480         if (is_long_mode(vcpu) || !is_pae(vcpu))
481                 return false;
482
483         r = kvm_read_guest(vcpu->kvm, vcpu->arch.cr3 & ~31u, pdpte, sizeof(pdpte));
484         if (r < 0)
485                 goto out;
486         changed = memcmp(pdpte, vcpu->arch.pdptrs, sizeof(pdpte)) != 0;
487 out:
488
489         return changed;
490 }
491
492 void kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
493 {
494         if (cr0 & CR0_RESERVED_BITS) {
495                 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
496                        cr0, vcpu->arch.cr0);
497                 kvm_inject_gp(vcpu, 0);
498                 return;
499         }
500
501         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
502                 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
503                 kvm_inject_gp(vcpu, 0);
504                 return;
505         }
506
507         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
508                 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
509                        "and a clear PE flag\n");
510                 kvm_inject_gp(vcpu, 0);
511                 return;
512         }
513
514         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
515 #ifdef CONFIG_X86_64
516                 if ((vcpu->arch.shadow_efer & EFER_LME)) {
517                         int cs_db, cs_l;
518
519                         if (!is_pae(vcpu)) {
520                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
521                                        "in long mode while PAE is disabled\n");
522                                 kvm_inject_gp(vcpu, 0);
523                                 return;
524                         }
525                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
526                         if (cs_l) {
527                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
528                                        "in long mode while CS.L == 1\n");
529                                 kvm_inject_gp(vcpu, 0);
530                                 return;
531
532                         }
533                 } else
534 #endif
535                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
536                         printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
537                                "reserved bits\n");
538                         kvm_inject_gp(vcpu, 0);
539                         return;
540                 }
541
542         }
543
544         kvm_x86_ops->set_cr0(vcpu, cr0);
545         vcpu->arch.cr0 = cr0;
546
547         kvm_mmu_reset_context(vcpu);
548         return;
549 }
550 EXPORT_SYMBOL_GPL(kvm_set_cr0);
551
552 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
553 {
554         kvm_set_cr0(vcpu, (vcpu->arch.cr0 & ~0x0ful) | (msw & 0x0f));
555         KVMTRACE_1D(LMSW, vcpu,
556                     (u32)((vcpu->arch.cr0 & ~0x0ful) | (msw & 0x0f)),
557                     handler);
558 }
559 EXPORT_SYMBOL_GPL(kvm_lmsw);
560
561 void kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
562 {
563         if (cr4 & CR4_RESERVED_BITS) {
564                 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
565                 kvm_inject_gp(vcpu, 0);
566                 return;
567         }
568
569         if (is_long_mode(vcpu)) {
570                 if (!(cr4 & X86_CR4_PAE)) {
571                         printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
572                                "in long mode\n");
573                         kvm_inject_gp(vcpu, 0);
574                         return;
575                 }
576         } else if (is_paging(vcpu) && !is_pae(vcpu) && (cr4 & X86_CR4_PAE)
577                    && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
578                 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
579                 kvm_inject_gp(vcpu, 0);
580                 return;
581         }
582
583         if (cr4 & X86_CR4_VMXE) {
584                 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
585                 kvm_inject_gp(vcpu, 0);
586                 return;
587         }
588         kvm_x86_ops->set_cr4(vcpu, cr4);
589         vcpu->arch.cr4 = cr4;
590         kvm_mmu_reset_context(vcpu);
591 }
592 EXPORT_SYMBOL_GPL(kvm_set_cr4);
593
594 void kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
595 {
596         if (cr3 == vcpu->arch.cr3 && !pdptrs_changed(vcpu)) {
597                 kvm_mmu_sync_roots(vcpu);
598                 kvm_mmu_flush_tlb(vcpu);
599                 return;
600         }
601
602         if (is_long_mode(vcpu)) {
603                 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
604                         printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
605                         kvm_inject_gp(vcpu, 0);
606                         return;
607                 }
608         } else {
609                 if (is_pae(vcpu)) {
610                         if (cr3 & CR3_PAE_RESERVED_BITS) {
611                                 printk(KERN_DEBUG
612                                        "set_cr3: #GP, reserved bits\n");
613                                 kvm_inject_gp(vcpu, 0);
614                                 return;
615                         }
616                         if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
617                                 printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
618                                        "reserved bits\n");
619                                 kvm_inject_gp(vcpu, 0);
620                                 return;
621                         }
622                 }
623                 /*
624                  * We don't check reserved bits in nonpae mode, because
625                  * this isn't enforced, and VMware depends on this.
626                  */
627         }
628
629         /*
630          * Does the new cr3 value map to physical memory? (Note, we
631          * catch an invalid cr3 even in real-mode, because it would
632          * cause trouble later on when we turn on paging anyway.)
633          *
634          * A real CPU would silently accept an invalid cr3 and would
635          * attempt to use it - with largely undefined (and often hard
636          * to debug) behavior on the guest side.
637          */
638         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
639                 kvm_inject_gp(vcpu, 0);
640         else {
641                 vcpu->arch.cr3 = cr3;
642                 vcpu->arch.mmu.new_cr3(vcpu);
643         }
644 }
645 EXPORT_SYMBOL_GPL(kvm_set_cr3);
646
647 void kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
648 {
649         if (cr8 & CR8_RESERVED_BITS) {
650                 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
651                 kvm_inject_gp(vcpu, 0);
652                 return;
653         }
654         if (irqchip_in_kernel(vcpu->kvm))
655                 kvm_lapic_set_tpr(vcpu, cr8);
656         else
657                 vcpu->arch.cr8 = cr8;
658 }
659 EXPORT_SYMBOL_GPL(kvm_set_cr8);
660
661 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
662 {
663         if (irqchip_in_kernel(vcpu->kvm))
664                 return kvm_lapic_get_cr8(vcpu);
665         else
666                 return vcpu->arch.cr8;
667 }
668 EXPORT_SYMBOL_GPL(kvm_get_cr8);
669
670 /*
671  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
672  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
673  *
674  * This list is modified at module load time to reflect the
675  * capabilities of the host cpu.
676  */
677 static u32 msrs_to_save[] = {
678         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
679         MSR_K6_STAR,
680 #ifdef CONFIG_X86_64
681         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
682 #endif
683         MSR_IA32_TIME_STAMP_COUNTER, MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
684         MSR_IA32_PERF_STATUS,
685 };
686
687 static unsigned num_msrs_to_save;
688
689 static u32 emulated_msrs[] = {
690         MSR_IA32_MISC_ENABLE,
691 };
692
693 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
694 {
695         if (efer & efer_reserved_bits) {
696                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
697                        efer);
698                 kvm_inject_gp(vcpu, 0);
699                 return;
700         }
701
702         if (is_paging(vcpu)
703             && (vcpu->arch.shadow_efer & EFER_LME) != (efer & EFER_LME)) {
704                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
705                 kvm_inject_gp(vcpu, 0);
706                 return;
707         }
708
709         kvm_x86_ops->set_efer(vcpu, efer);
710
711         efer &= ~EFER_LMA;
712         efer |= vcpu->arch.shadow_efer & EFER_LMA;
713
714         vcpu->arch.shadow_efer = efer;
715 }
716
717 void kvm_enable_efer_bits(u64 mask)
718 {
719        efer_reserved_bits &= ~mask;
720 }
721 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
722
723
724 /*
725  * Writes msr value into into the appropriate "register".
726  * Returns 0 on success, non-0 otherwise.
727  * Assumes vcpu_load() was already called.
728  */
729 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
730 {
731         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
732 }
733
734 /*
735  * Adapt set_msr() to msr_io()'s calling convention
736  */
737 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
738 {
739         return kvm_set_msr(vcpu, index, *data);
740 }
741
742 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
743 {
744         static int version;
745         struct pvclock_wall_clock wc;
746         struct timespec now, sys, boot;
747
748         if (!wall_clock)
749                 return;
750
751         version++;
752
753         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
754
755         /*
756          * The guest calculates current wall clock time by adding
757          * system time (updated by kvm_write_guest_time below) to the
758          * wall clock specified here.  guest system time equals host
759          * system time for us, thus we must fill in host boot time here.
760          */
761         now = current_kernel_time();
762         ktime_get_ts(&sys);
763         boot = ns_to_timespec(timespec_to_ns(&now) - timespec_to_ns(&sys));
764
765         wc.sec = boot.tv_sec;
766         wc.nsec = boot.tv_nsec;
767         wc.version = version;
768
769         kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
770
771         version++;
772         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
773 }
774
775 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
776 {
777         uint32_t quotient, remainder;
778
779         /* Don't try to replace with do_div(), this one calculates
780          * "(dividend << 32) / divisor" */
781         __asm__ ( "divl %4"
782                   : "=a" (quotient), "=d" (remainder)
783                   : "0" (0), "1" (dividend), "r" (divisor) );
784         return quotient;
785 }
786
787 static void kvm_set_time_scale(uint32_t tsc_khz, struct pvclock_vcpu_time_info *hv_clock)
788 {
789         uint64_t nsecs = 1000000000LL;
790         int32_t  shift = 0;
791         uint64_t tps64;
792         uint32_t tps32;
793
794         tps64 = tsc_khz * 1000LL;
795         while (tps64 > nsecs*2) {
796                 tps64 >>= 1;
797                 shift--;
798         }
799
800         tps32 = (uint32_t)tps64;
801         while (tps32 <= (uint32_t)nsecs) {
802                 tps32 <<= 1;
803                 shift++;
804         }
805
806         hv_clock->tsc_shift = shift;
807         hv_clock->tsc_to_system_mul = div_frac(nsecs, tps32);
808
809         pr_debug("%s: tsc_khz %u, tsc_shift %d, tsc_mul %u\n",
810                  __FUNCTION__, tsc_khz, hv_clock->tsc_shift,
811                  hv_clock->tsc_to_system_mul);
812 }
813
814 static void kvm_write_guest_time(struct kvm_vcpu *v)
815 {
816         struct timespec ts;
817         unsigned long flags;
818         struct kvm_vcpu_arch *vcpu = &v->arch;
819         void *shared_kaddr;
820
821         if ((!vcpu->time_page))
822                 return;
823
824         if (unlikely(vcpu->hv_clock_tsc_khz != tsc_khz)) {
825                 kvm_set_time_scale(tsc_khz, &vcpu->hv_clock);
826                 vcpu->hv_clock_tsc_khz = tsc_khz;
827         }
828
829         /* Keep irq disabled to prevent changes to the clock */
830         local_irq_save(flags);
831         kvm_get_msr(v, MSR_IA32_TIME_STAMP_COUNTER,
832                           &vcpu->hv_clock.tsc_timestamp);
833         ktime_get_ts(&ts);
834         local_irq_restore(flags);
835
836         /* With all the info we got, fill in the values */
837
838         vcpu->hv_clock.system_time = ts.tv_nsec +
839                                      (NSEC_PER_SEC * (u64)ts.tv_sec);
840         /*
841          * The interface expects us to write an even number signaling that the
842          * update is finished. Since the guest won't see the intermediate
843          * state, we just increase by 2 at the end.
844          */
845         vcpu->hv_clock.version += 2;
846
847         shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
848
849         memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
850                sizeof(vcpu->hv_clock));
851
852         kunmap_atomic(shared_kaddr, KM_USER0);
853
854         mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
855 }
856
857 static bool msr_mtrr_valid(unsigned msr)
858 {
859         switch (msr) {
860         case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
861         case MSR_MTRRfix64K_00000:
862         case MSR_MTRRfix16K_80000:
863         case MSR_MTRRfix16K_A0000:
864         case MSR_MTRRfix4K_C0000:
865         case MSR_MTRRfix4K_C8000:
866         case MSR_MTRRfix4K_D0000:
867         case MSR_MTRRfix4K_D8000:
868         case MSR_MTRRfix4K_E0000:
869         case MSR_MTRRfix4K_E8000:
870         case MSR_MTRRfix4K_F0000:
871         case MSR_MTRRfix4K_F8000:
872         case MSR_MTRRdefType:
873         case MSR_IA32_CR_PAT:
874                 return true;
875         case 0x2f8:
876                 return true;
877         }
878         return false;
879 }
880
881 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
882 {
883         if (!msr_mtrr_valid(msr))
884                 return 1;
885
886         vcpu->arch.mtrr[msr - 0x200] = data;
887         return 0;
888 }
889
890 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
891 {
892         switch (msr) {
893         case MSR_EFER:
894                 set_efer(vcpu, data);
895                 break;
896         case MSR_IA32_MC0_STATUS:
897                 pr_unimpl(vcpu, "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
898                        __func__, data);
899                 break;
900         case MSR_IA32_MCG_STATUS:
901                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
902                         __func__, data);
903                 break;
904         case MSR_IA32_MCG_CTL:
905                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_CTL 0x%llx, nop\n",
906                         __func__, data);
907                 break;
908         case MSR_IA32_DEBUGCTLMSR:
909                 if (!data) {
910                         /* We support the non-activated case already */
911                         break;
912                 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
913                         /* Values other than LBR and BTF are vendor-specific,
914                            thus reserved and should throw a #GP */
915                         return 1;
916                 }
917                 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
918                         __func__, data);
919                 break;
920         case MSR_IA32_UCODE_REV:
921         case MSR_IA32_UCODE_WRITE:
922                 break;
923         case 0x200 ... 0x2ff:
924                 return set_msr_mtrr(vcpu, msr, data);
925         case MSR_IA32_APICBASE:
926                 kvm_set_apic_base(vcpu, data);
927                 break;
928         case MSR_IA32_MISC_ENABLE:
929                 vcpu->arch.ia32_misc_enable_msr = data;
930                 break;
931         case MSR_KVM_WALL_CLOCK:
932                 vcpu->kvm->arch.wall_clock = data;
933                 kvm_write_wall_clock(vcpu->kvm, data);
934                 break;
935         case MSR_KVM_SYSTEM_TIME: {
936                 if (vcpu->arch.time_page) {
937                         kvm_release_page_dirty(vcpu->arch.time_page);
938                         vcpu->arch.time_page = NULL;
939                 }
940
941                 vcpu->arch.time = data;
942
943                 /* we verify if the enable bit is set... */
944                 if (!(data & 1))
945                         break;
946
947                 /* ...but clean it before doing the actual write */
948                 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
949
950                 vcpu->arch.time_page =
951                                 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
952
953                 if (is_error_page(vcpu->arch.time_page)) {
954                         kvm_release_page_clean(vcpu->arch.time_page);
955                         vcpu->arch.time_page = NULL;
956                 }
957
958                 kvm_write_guest_time(vcpu);
959                 break;
960         }
961         default:
962                 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n", msr, data);
963                 return 1;
964         }
965         return 0;
966 }
967 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
968
969
970 /*
971  * Reads an msr value (of 'msr_index') into 'pdata'.
972  * Returns 0 on success, non-0 otherwise.
973  * Assumes vcpu_load() was already called.
974  */
975 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
976 {
977         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
978 }
979
980 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
981 {
982         if (!msr_mtrr_valid(msr))
983                 return 1;
984
985         *pdata = vcpu->arch.mtrr[msr - 0x200];
986         return 0;
987 }
988
989 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
990 {
991         u64 data;
992
993         switch (msr) {
994         case 0xc0010010: /* SYSCFG */
995         case 0xc0010015: /* HWCR */
996         case MSR_IA32_PLATFORM_ID:
997         case MSR_IA32_P5_MC_ADDR:
998         case MSR_IA32_P5_MC_TYPE:
999         case MSR_IA32_MC0_CTL:
1000         case MSR_IA32_MCG_STATUS:
1001         case MSR_IA32_MCG_CAP:
1002         case MSR_IA32_MCG_CTL:
1003         case MSR_IA32_MC0_MISC:
1004         case MSR_IA32_MC0_MISC+4:
1005         case MSR_IA32_MC0_MISC+8:
1006         case MSR_IA32_MC0_MISC+12:
1007         case MSR_IA32_MC0_MISC+16:
1008         case MSR_IA32_MC0_MISC+20:
1009         case MSR_IA32_UCODE_REV:
1010         case MSR_IA32_EBL_CR_POWERON:
1011         case MSR_IA32_DEBUGCTLMSR:
1012         case MSR_IA32_LASTBRANCHFROMIP:
1013         case MSR_IA32_LASTBRANCHTOIP:
1014         case MSR_IA32_LASTINTFROMIP:
1015         case MSR_IA32_LASTINTTOIP:
1016                 data = 0;
1017                 break;
1018         case MSR_MTRRcap:
1019                 data = 0x500 | KVM_NR_VAR_MTRR;
1020                 break;
1021         case 0x200 ... 0x2ff:
1022                 return get_msr_mtrr(vcpu, msr, pdata);
1023         case 0xcd: /* fsb frequency */
1024                 data = 3;
1025                 break;
1026         case MSR_IA32_APICBASE:
1027                 data = kvm_get_apic_base(vcpu);
1028                 break;
1029         case MSR_IA32_MISC_ENABLE:
1030                 data = vcpu->arch.ia32_misc_enable_msr;
1031                 break;
1032         case MSR_IA32_PERF_STATUS:
1033                 /* TSC increment by tick */
1034                 data = 1000ULL;
1035                 /* CPU multiplier */
1036                 data |= (((uint64_t)4ULL) << 40);
1037                 break;
1038         case MSR_EFER:
1039                 data = vcpu->arch.shadow_efer;
1040                 break;
1041         case MSR_KVM_WALL_CLOCK:
1042                 data = vcpu->kvm->arch.wall_clock;
1043                 break;
1044         case MSR_KVM_SYSTEM_TIME:
1045                 data = vcpu->arch.time;
1046                 break;
1047         default:
1048                 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1049                 return 1;
1050         }
1051         *pdata = data;
1052         return 0;
1053 }
1054 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1055
1056 /*
1057  * Read or write a bunch of msrs. All parameters are kernel addresses.
1058  *
1059  * @return number of msrs set successfully.
1060  */
1061 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
1062                     struct kvm_msr_entry *entries,
1063                     int (*do_msr)(struct kvm_vcpu *vcpu,
1064                                   unsigned index, u64 *data))
1065 {
1066         int i;
1067
1068         vcpu_load(vcpu);
1069
1070         down_read(&vcpu->kvm->slots_lock);
1071         for (i = 0; i < msrs->nmsrs; ++i)
1072                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1073                         break;
1074         up_read(&vcpu->kvm->slots_lock);
1075
1076         vcpu_put(vcpu);
1077
1078         return i;
1079 }
1080
1081 /*
1082  * Read or write a bunch of msrs. Parameters are user addresses.
1083  *
1084  * @return number of msrs set successfully.
1085  */
1086 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
1087                   int (*do_msr)(struct kvm_vcpu *vcpu,
1088                                 unsigned index, u64 *data),
1089                   int writeback)
1090 {
1091         struct kvm_msrs msrs;
1092         struct kvm_msr_entry *entries;
1093         int r, n;
1094         unsigned size;
1095
1096         r = -EFAULT;
1097         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
1098                 goto out;
1099
1100         r = -E2BIG;
1101         if (msrs.nmsrs >= MAX_IO_MSRS)
1102                 goto out;
1103
1104         r = -ENOMEM;
1105         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
1106         entries = vmalloc(size);
1107         if (!entries)
1108                 goto out;
1109
1110         r = -EFAULT;
1111         if (copy_from_user(entries, user_msrs->entries, size))
1112                 goto out_free;
1113
1114         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
1115         if (r < 0)
1116                 goto out_free;
1117
1118         r = -EFAULT;
1119         if (writeback && copy_to_user(user_msrs->entries, entries, size))
1120                 goto out_free;
1121
1122         r = n;
1123
1124 out_free:
1125         vfree(entries);
1126 out:
1127         return r;
1128 }
1129
1130 int kvm_dev_ioctl_check_extension(long ext)
1131 {
1132         int r;
1133
1134         switch (ext) {
1135         case KVM_CAP_IRQCHIP:
1136         case KVM_CAP_HLT:
1137         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
1138         case KVM_CAP_USER_MEMORY:
1139         case KVM_CAP_SET_TSS_ADDR:
1140         case KVM_CAP_EXT_CPUID:
1141         case KVM_CAP_CLOCKSOURCE:
1142         case KVM_CAP_PIT:
1143         case KVM_CAP_NOP_IO_DELAY:
1144         case KVM_CAP_MP_STATE:
1145         case KVM_CAP_SYNC_MMU:
1146                 r = 1;
1147                 break;
1148         case KVM_CAP_COALESCED_MMIO:
1149                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
1150                 break;
1151         case KVM_CAP_VAPIC:
1152                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
1153                 break;
1154         case KVM_CAP_NR_VCPUS:
1155                 r = KVM_MAX_VCPUS;
1156                 break;
1157         case KVM_CAP_NR_MEMSLOTS:
1158                 r = KVM_MEMORY_SLOTS;
1159                 break;
1160         case KVM_CAP_PV_MMU:
1161                 r = !tdp_enabled;
1162                 break;
1163         case KVM_CAP_IOMMU:
1164                 r = intel_iommu_found();
1165                 break;
1166         default:
1167                 r = 0;
1168                 break;
1169         }
1170         return r;
1171
1172 }
1173
1174 long kvm_arch_dev_ioctl(struct file *filp,
1175                         unsigned int ioctl, unsigned long arg)
1176 {
1177         void __user *argp = (void __user *)arg;
1178         long r;
1179
1180         switch (ioctl) {
1181         case KVM_GET_MSR_INDEX_LIST: {
1182                 struct kvm_msr_list __user *user_msr_list = argp;
1183                 struct kvm_msr_list msr_list;
1184                 unsigned n;
1185
1186                 r = -EFAULT;
1187                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
1188                         goto out;
1189                 n = msr_list.nmsrs;
1190                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
1191                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
1192                         goto out;
1193                 r = -E2BIG;
1194                 if (n < num_msrs_to_save)
1195                         goto out;
1196                 r = -EFAULT;
1197                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
1198                                  num_msrs_to_save * sizeof(u32)))
1199                         goto out;
1200                 if (copy_to_user(user_msr_list->indices
1201                                  + num_msrs_to_save * sizeof(u32),
1202                                  &emulated_msrs,
1203                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
1204                         goto out;
1205                 r = 0;
1206                 break;
1207         }
1208         case KVM_GET_SUPPORTED_CPUID: {
1209                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1210                 struct kvm_cpuid2 cpuid;
1211
1212                 r = -EFAULT;
1213                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1214                         goto out;
1215                 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
1216                         cpuid_arg->entries);
1217                 if (r)
1218                         goto out;
1219
1220                 r = -EFAULT;
1221                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1222                         goto out;
1223                 r = 0;
1224                 break;
1225         }
1226         default:
1227                 r = -EINVAL;
1228         }
1229 out:
1230         return r;
1231 }
1232
1233 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1234 {
1235         kvm_x86_ops->vcpu_load(vcpu, cpu);
1236         kvm_write_guest_time(vcpu);
1237 }
1238
1239 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
1240 {
1241         kvm_x86_ops->vcpu_put(vcpu);
1242         kvm_put_guest_fpu(vcpu);
1243 }
1244
1245 static int is_efer_nx(void)
1246 {
1247         u64 efer;
1248
1249         rdmsrl(MSR_EFER, efer);
1250         return efer & EFER_NX;
1251 }
1252
1253 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
1254 {
1255         int i;
1256         struct kvm_cpuid_entry2 *e, *entry;
1257
1258         entry = NULL;
1259         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
1260                 e = &vcpu->arch.cpuid_entries[i];
1261                 if (e->function == 0x80000001) {
1262                         entry = e;
1263                         break;
1264                 }
1265         }
1266         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
1267                 entry->edx &= ~(1 << 20);
1268                 printk(KERN_INFO "kvm: guest NX capability removed\n");
1269         }
1270 }
1271
1272 /* when an old userspace process fills a new kernel module */
1273 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
1274                                     struct kvm_cpuid *cpuid,
1275                                     struct kvm_cpuid_entry __user *entries)
1276 {
1277         int r, i;
1278         struct kvm_cpuid_entry *cpuid_entries;
1279
1280         r = -E2BIG;
1281         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1282                 goto out;
1283         r = -ENOMEM;
1284         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
1285         if (!cpuid_entries)
1286                 goto out;
1287         r = -EFAULT;
1288         if (copy_from_user(cpuid_entries, entries,
1289                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
1290                 goto out_free;
1291         for (i = 0; i < cpuid->nent; i++) {
1292                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
1293                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
1294                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
1295                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
1296                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
1297                 vcpu->arch.cpuid_entries[i].index = 0;
1298                 vcpu->arch.cpuid_entries[i].flags = 0;
1299                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
1300                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
1301                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
1302         }
1303         vcpu->arch.cpuid_nent = cpuid->nent;
1304         cpuid_fix_nx_cap(vcpu);
1305         r = 0;
1306
1307 out_free:
1308         vfree(cpuid_entries);
1309 out:
1310         return r;
1311 }
1312
1313 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
1314                                     struct kvm_cpuid2 *cpuid,
1315                                     struct kvm_cpuid_entry2 __user *entries)
1316 {
1317         int r;
1318
1319         r = -E2BIG;
1320         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1321                 goto out;
1322         r = -EFAULT;
1323         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
1324                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
1325                 goto out;
1326         vcpu->arch.cpuid_nent = cpuid->nent;
1327         return 0;
1328
1329 out:
1330         return r;
1331 }
1332
1333 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
1334                                     struct kvm_cpuid2 *cpuid,
1335                                     struct kvm_cpuid_entry2 __user *entries)
1336 {
1337         int r;
1338
1339         r = -E2BIG;
1340         if (cpuid->nent < vcpu->arch.cpuid_nent)
1341                 goto out;
1342         r = -EFAULT;
1343         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
1344                            vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
1345                 goto out;
1346         return 0;
1347
1348 out:
1349         cpuid->nent = vcpu->arch.cpuid_nent;
1350         return r;
1351 }
1352
1353 static inline u32 bit(int bitno)
1354 {
1355         return 1 << (bitno & 31);
1356 }
1357
1358 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1359                           u32 index)
1360 {
1361         entry->function = function;
1362         entry->index = index;
1363         cpuid_count(entry->function, entry->index,
1364                 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1365         entry->flags = 0;
1366 }
1367
1368 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1369                          u32 index, int *nent, int maxnent)
1370 {
1371         const u32 kvm_supported_word0_x86_features = bit(X86_FEATURE_FPU) |
1372                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1373                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1374                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1375                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1376                 bit(X86_FEATURE_SEP) | bit(X86_FEATURE_PGE) |
1377                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1378                 bit(X86_FEATURE_CLFLSH) | bit(X86_FEATURE_MMX) |
1379                 bit(X86_FEATURE_FXSR) | bit(X86_FEATURE_XMM) |
1380                 bit(X86_FEATURE_XMM2) | bit(X86_FEATURE_SELFSNOOP);
1381         const u32 kvm_supported_word1_x86_features = bit(X86_FEATURE_FPU) |
1382                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1383                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1384                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1385                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1386                 bit(X86_FEATURE_PGE) |
1387                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1388                 bit(X86_FEATURE_MMX) | bit(X86_FEATURE_FXSR) |
1389                 bit(X86_FEATURE_SYSCALL) |
1390                 (bit(X86_FEATURE_NX) && is_efer_nx()) |
1391 #ifdef CONFIG_X86_64
1392                 bit(X86_FEATURE_LM) |
1393 #endif
1394                 bit(X86_FEATURE_MMXEXT) |
1395                 bit(X86_FEATURE_3DNOWEXT) |
1396                 bit(X86_FEATURE_3DNOW);
1397         const u32 kvm_supported_word3_x86_features =
1398                 bit(X86_FEATURE_XMM3) | bit(X86_FEATURE_CX16);
1399         const u32 kvm_supported_word6_x86_features =
1400                 bit(X86_FEATURE_LAHF_LM) | bit(X86_FEATURE_CMP_LEGACY);
1401
1402         /* all func 2 cpuid_count() should be called on the same cpu */
1403         get_cpu();
1404         do_cpuid_1_ent(entry, function, index);
1405         ++*nent;
1406
1407         switch (function) {
1408         case 0:
1409                 entry->eax = min(entry->eax, (u32)0xb);
1410                 break;
1411         case 1:
1412                 entry->edx &= kvm_supported_word0_x86_features;
1413                 entry->ecx &= kvm_supported_word3_x86_features;
1414                 break;
1415         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
1416          * may return different values. This forces us to get_cpu() before
1417          * issuing the first command, and also to emulate this annoying behavior
1418          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
1419         case 2: {
1420                 int t, times = entry->eax & 0xff;
1421
1422                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1423                 for (t = 1; t < times && *nent < maxnent; ++t) {
1424                         do_cpuid_1_ent(&entry[t], function, 0);
1425                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1426                         ++*nent;
1427                 }
1428                 break;
1429         }
1430         /* function 4 and 0xb have additional index. */
1431         case 4: {
1432                 int i, cache_type;
1433
1434                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1435                 /* read more entries until cache_type is zero */
1436                 for (i = 1; *nent < maxnent; ++i) {
1437                         cache_type = entry[i - 1].eax & 0x1f;
1438                         if (!cache_type)
1439                                 break;
1440                         do_cpuid_1_ent(&entry[i], function, i);
1441                         entry[i].flags |=
1442                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1443                         ++*nent;
1444                 }
1445                 break;
1446         }
1447         case 0xb: {
1448                 int i, level_type;
1449
1450                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1451                 /* read more entries until level_type is zero */
1452                 for (i = 1; *nent < maxnent; ++i) {
1453                         level_type = entry[i - 1].ecx & 0xff;
1454                         if (!level_type)
1455                                 break;
1456                         do_cpuid_1_ent(&entry[i], function, i);
1457                         entry[i].flags |=
1458                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1459                         ++*nent;
1460                 }
1461                 break;
1462         }
1463         case 0x80000000:
1464                 entry->eax = min(entry->eax, 0x8000001a);
1465                 break;
1466         case 0x80000001:
1467                 entry->edx &= kvm_supported_word1_x86_features;
1468                 entry->ecx &= kvm_supported_word6_x86_features;
1469                 break;
1470         }
1471         put_cpu();
1472 }
1473
1474 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
1475                                     struct kvm_cpuid_entry2 __user *entries)
1476 {
1477         struct kvm_cpuid_entry2 *cpuid_entries;
1478         int limit, nent = 0, r = -E2BIG;
1479         u32 func;
1480
1481         if (cpuid->nent < 1)
1482                 goto out;
1483         r = -ENOMEM;
1484         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
1485         if (!cpuid_entries)
1486                 goto out;
1487
1488         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
1489         limit = cpuid_entries[0].eax;
1490         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
1491                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1492                                 &nent, cpuid->nent);
1493         r = -E2BIG;
1494         if (nent >= cpuid->nent)
1495                 goto out_free;
1496
1497         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1498         limit = cpuid_entries[nent - 1].eax;
1499         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1500                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1501                                &nent, cpuid->nent);
1502         r = -EFAULT;
1503         if (copy_to_user(entries, cpuid_entries,
1504                         nent * sizeof(struct kvm_cpuid_entry2)))
1505                 goto out_free;
1506         cpuid->nent = nent;
1507         r = 0;
1508
1509 out_free:
1510         vfree(cpuid_entries);
1511 out:
1512         return r;
1513 }
1514
1515 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1516                                     struct kvm_lapic_state *s)
1517 {
1518         vcpu_load(vcpu);
1519         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1520         vcpu_put(vcpu);
1521
1522         return 0;
1523 }
1524
1525 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1526                                     struct kvm_lapic_state *s)
1527 {
1528         vcpu_load(vcpu);
1529         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1530         kvm_apic_post_state_restore(vcpu);
1531         vcpu_put(vcpu);
1532
1533         return 0;
1534 }
1535
1536 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1537                                     struct kvm_interrupt *irq)
1538 {
1539         if (irq->irq < 0 || irq->irq >= 256)
1540                 return -EINVAL;
1541         if (irqchip_in_kernel(vcpu->kvm))
1542                 return -ENXIO;
1543         vcpu_load(vcpu);
1544
1545         set_bit(irq->irq, vcpu->arch.irq_pending);
1546         set_bit(irq->irq / BITS_PER_LONG, &vcpu->arch.irq_summary);
1547
1548         vcpu_put(vcpu);
1549
1550         return 0;
1551 }
1552
1553 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
1554                                            struct kvm_tpr_access_ctl *tac)
1555 {
1556         if (tac->flags)
1557                 return -EINVAL;
1558         vcpu->arch.tpr_access_reporting = !!tac->enabled;
1559         return 0;
1560 }
1561
1562 long kvm_arch_vcpu_ioctl(struct file *filp,
1563                          unsigned int ioctl, unsigned long arg)
1564 {
1565         struct kvm_vcpu *vcpu = filp->private_data;
1566         void __user *argp = (void __user *)arg;
1567         int r;
1568         struct kvm_lapic_state *lapic = NULL;
1569
1570         switch (ioctl) {
1571         case KVM_GET_LAPIC: {
1572                 lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
1573
1574                 r = -ENOMEM;
1575                 if (!lapic)
1576                         goto out;
1577                 r = kvm_vcpu_ioctl_get_lapic(vcpu, lapic);
1578                 if (r)
1579                         goto out;
1580                 r = -EFAULT;
1581                 if (copy_to_user(argp, lapic, sizeof(struct kvm_lapic_state)))
1582                         goto out;
1583                 r = 0;
1584                 break;
1585         }
1586         case KVM_SET_LAPIC: {
1587                 lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
1588                 r = -ENOMEM;
1589                 if (!lapic)
1590                         goto out;
1591                 r = -EFAULT;
1592                 if (copy_from_user(lapic, argp, sizeof(struct kvm_lapic_state)))
1593                         goto out;
1594                 r = kvm_vcpu_ioctl_set_lapic(vcpu, lapic);
1595                 if (r)
1596                         goto out;
1597                 r = 0;
1598                 break;
1599         }
1600         case KVM_INTERRUPT: {
1601                 struct kvm_interrupt irq;
1602
1603                 r = -EFAULT;
1604                 if (copy_from_user(&irq, argp, sizeof irq))
1605                         goto out;
1606                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1607                 if (r)
1608                         goto out;
1609                 r = 0;
1610                 break;
1611         }
1612         case KVM_SET_CPUID: {
1613                 struct kvm_cpuid __user *cpuid_arg = argp;
1614                 struct kvm_cpuid cpuid;
1615
1616                 r = -EFAULT;
1617                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1618                         goto out;
1619                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1620                 if (r)
1621                         goto out;
1622                 break;
1623         }
1624         case KVM_SET_CPUID2: {
1625                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1626                 struct kvm_cpuid2 cpuid;
1627
1628                 r = -EFAULT;
1629                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1630                         goto out;
1631                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1632                                 cpuid_arg->entries);
1633                 if (r)
1634                         goto out;
1635                 break;
1636         }
1637         case KVM_GET_CPUID2: {
1638                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1639                 struct kvm_cpuid2 cpuid;
1640
1641                 r = -EFAULT;
1642                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1643                         goto out;
1644                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1645                                 cpuid_arg->entries);
1646                 if (r)
1647                         goto out;
1648                 r = -EFAULT;
1649                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1650                         goto out;
1651                 r = 0;
1652                 break;
1653         }
1654         case KVM_GET_MSRS:
1655                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1656                 break;
1657         case KVM_SET_MSRS:
1658                 r = msr_io(vcpu, argp, do_set_msr, 0);
1659                 break;
1660         case KVM_TPR_ACCESS_REPORTING: {
1661                 struct kvm_tpr_access_ctl tac;
1662
1663                 r = -EFAULT;
1664                 if (copy_from_user(&tac, argp, sizeof tac))
1665                         goto out;
1666                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
1667                 if (r)
1668                         goto out;
1669                 r = -EFAULT;
1670                 if (copy_to_user(argp, &tac, sizeof tac))
1671                         goto out;
1672                 r = 0;
1673                 break;
1674         };
1675         case KVM_SET_VAPIC_ADDR: {
1676                 struct kvm_vapic_addr va;
1677
1678                 r = -EINVAL;
1679                 if (!irqchip_in_kernel(vcpu->kvm))
1680                         goto out;
1681                 r = -EFAULT;
1682                 if (copy_from_user(&va, argp, sizeof va))
1683                         goto out;
1684                 r = 0;
1685                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
1686                 break;
1687         }
1688         default:
1689                 r = -EINVAL;
1690         }
1691 out:
1692         if (lapic)
1693                 kfree(lapic);
1694         return r;
1695 }
1696
1697 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1698 {
1699         int ret;
1700
1701         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1702                 return -1;
1703         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1704         return ret;
1705 }
1706
1707 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1708                                           u32 kvm_nr_mmu_pages)
1709 {
1710         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1711                 return -EINVAL;
1712
1713         down_write(&kvm->slots_lock);
1714
1715         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1716         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1717
1718         up_write(&kvm->slots_lock);
1719         return 0;
1720 }
1721
1722 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1723 {
1724         return kvm->arch.n_alloc_mmu_pages;
1725 }
1726
1727 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1728 {
1729         int i;
1730         struct kvm_mem_alias *alias;
1731
1732         for (i = 0; i < kvm->arch.naliases; ++i) {
1733                 alias = &kvm->arch.aliases[i];
1734                 if (gfn >= alias->base_gfn
1735                     && gfn < alias->base_gfn + alias->npages)
1736                         return alias->target_gfn + gfn - alias->base_gfn;
1737         }
1738         return gfn;
1739 }
1740
1741 /*
1742  * Set a new alias region.  Aliases map a portion of physical memory into
1743  * another portion.  This is useful for memory windows, for example the PC
1744  * VGA region.
1745  */
1746 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1747                                          struct kvm_memory_alias *alias)
1748 {
1749         int r, n;
1750         struct kvm_mem_alias *p;
1751
1752         r = -EINVAL;
1753         /* General sanity checks */
1754         if (alias->memory_size & (PAGE_SIZE - 1))
1755                 goto out;
1756         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1757                 goto out;
1758         if (alias->slot >= KVM_ALIAS_SLOTS)
1759                 goto out;
1760         if (alias->guest_phys_addr + alias->memory_size
1761             < alias->guest_phys_addr)
1762                 goto out;
1763         if (alias->target_phys_addr + alias->memory_size
1764             < alias->target_phys_addr)
1765                 goto out;
1766
1767         down_write(&kvm->slots_lock);
1768         spin_lock(&kvm->mmu_lock);
1769
1770         p = &kvm->arch.aliases[alias->slot];
1771         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1772         p->npages = alias->memory_size >> PAGE_SHIFT;
1773         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1774
1775         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1776                 if (kvm->arch.aliases[n - 1].npages)
1777                         break;
1778         kvm->arch.naliases = n;
1779
1780         spin_unlock(&kvm->mmu_lock);
1781         kvm_mmu_zap_all(kvm);
1782
1783         up_write(&kvm->slots_lock);
1784
1785         return 0;
1786
1787 out:
1788         return r;
1789 }
1790
1791 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1792 {
1793         int r;
1794
1795         r = 0;
1796         switch (chip->chip_id) {
1797         case KVM_IRQCHIP_PIC_MASTER:
1798                 memcpy(&chip->chip.pic,
1799                         &pic_irqchip(kvm)->pics[0],
1800                         sizeof(struct kvm_pic_state));
1801                 break;
1802         case KVM_IRQCHIP_PIC_SLAVE:
1803                 memcpy(&chip->chip.pic,
1804                         &pic_irqchip(kvm)->pics[1],
1805                         sizeof(struct kvm_pic_state));
1806                 break;
1807         case KVM_IRQCHIP_IOAPIC:
1808                 memcpy(&chip->chip.ioapic,
1809                         ioapic_irqchip(kvm),
1810                         sizeof(struct kvm_ioapic_state));
1811                 break;
1812         default:
1813                 r = -EINVAL;
1814                 break;
1815         }
1816         return r;
1817 }
1818
1819 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1820 {
1821         int r;
1822
1823         r = 0;
1824         switch (chip->chip_id) {
1825         case KVM_IRQCHIP_PIC_MASTER:
1826                 memcpy(&pic_irqchip(kvm)->pics[0],
1827                         &chip->chip.pic,
1828                         sizeof(struct kvm_pic_state));
1829                 break;
1830         case KVM_IRQCHIP_PIC_SLAVE:
1831                 memcpy(&pic_irqchip(kvm)->pics[1],
1832                         &chip->chip.pic,
1833                         sizeof(struct kvm_pic_state));
1834                 break;
1835         case KVM_IRQCHIP_IOAPIC:
1836                 memcpy(ioapic_irqchip(kvm),
1837                         &chip->chip.ioapic,
1838                         sizeof(struct kvm_ioapic_state));
1839                 break;
1840         default:
1841                 r = -EINVAL;
1842                 break;
1843         }
1844         kvm_pic_update_irq(pic_irqchip(kvm));
1845         return r;
1846 }
1847
1848 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1849 {
1850         int r = 0;
1851
1852         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
1853         return r;
1854 }
1855
1856 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1857 {
1858         int r = 0;
1859
1860         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
1861         kvm_pit_load_count(kvm, 0, ps->channels[0].count);
1862         return r;
1863 }
1864
1865 /*
1866  * Get (and clear) the dirty memory log for a memory slot.
1867  */
1868 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1869                                       struct kvm_dirty_log *log)
1870 {
1871         int r;
1872         int n;
1873         struct kvm_memory_slot *memslot;
1874         int is_dirty = 0;
1875
1876         down_write(&kvm->slots_lock);
1877
1878         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1879         if (r)
1880                 goto out;
1881
1882         /* If nothing is dirty, don't bother messing with page tables. */
1883         if (is_dirty) {
1884                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1885                 kvm_flush_remote_tlbs(kvm);
1886                 memslot = &kvm->memslots[log->slot];
1887                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1888                 memset(memslot->dirty_bitmap, 0, n);
1889         }
1890         r = 0;
1891 out:
1892         up_write(&kvm->slots_lock);
1893         return r;
1894 }
1895
1896 long kvm_arch_vm_ioctl(struct file *filp,
1897                        unsigned int ioctl, unsigned long arg)
1898 {
1899         struct kvm *kvm = filp->private_data;
1900         void __user *argp = (void __user *)arg;
1901         int r = -EINVAL;
1902         /*
1903          * This union makes it completely explicit to gcc-3.x
1904          * that these two variables' stack usage should be
1905          * combined, not added together.
1906          */
1907         union {
1908                 struct kvm_pit_state ps;
1909                 struct kvm_memory_alias alias;
1910         } u;
1911
1912         switch (ioctl) {
1913         case KVM_SET_TSS_ADDR:
1914                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1915                 if (r < 0)
1916                         goto out;
1917                 break;
1918         case KVM_SET_MEMORY_REGION: {
1919                 struct kvm_memory_region kvm_mem;
1920                 struct kvm_userspace_memory_region kvm_userspace_mem;
1921
1922                 r = -EFAULT;
1923                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1924                         goto out;
1925                 kvm_userspace_mem.slot = kvm_mem.slot;
1926                 kvm_userspace_mem.flags = kvm_mem.flags;
1927                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1928                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1929                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1930                 if (r)
1931                         goto out;
1932                 break;
1933         }
1934         case KVM_SET_NR_MMU_PAGES:
1935                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1936                 if (r)
1937                         goto out;
1938                 break;
1939         case KVM_GET_NR_MMU_PAGES:
1940                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1941                 break;
1942         case KVM_SET_MEMORY_ALIAS:
1943                 r = -EFAULT;
1944                 if (copy_from_user(&u.alias, argp, sizeof(struct kvm_memory_alias)))
1945                         goto out;
1946                 r = kvm_vm_ioctl_set_memory_alias(kvm, &u.alias);
1947                 if (r)
1948                         goto out;
1949                 break;
1950         case KVM_CREATE_IRQCHIP:
1951                 r = -ENOMEM;
1952                 kvm->arch.vpic = kvm_create_pic(kvm);
1953                 if (kvm->arch.vpic) {
1954                         r = kvm_ioapic_init(kvm);
1955                         if (r) {
1956                                 kfree(kvm->arch.vpic);
1957                                 kvm->arch.vpic = NULL;
1958                                 goto out;
1959                         }
1960                 } else
1961                         goto out;
1962                 break;
1963         case KVM_CREATE_PIT:
1964                 r = -ENOMEM;
1965                 kvm->arch.vpit = kvm_create_pit(kvm);
1966                 if (kvm->arch.vpit)
1967                         r = 0;
1968                 break;
1969         case KVM_IRQ_LINE: {
1970                 struct kvm_irq_level irq_event;
1971
1972                 r = -EFAULT;
1973                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1974                         goto out;
1975                 if (irqchip_in_kernel(kvm)) {
1976                         mutex_lock(&kvm->lock);
1977                         kvm_set_irq(kvm, irq_event.irq, irq_event.level);
1978                         mutex_unlock(&kvm->lock);
1979                         r = 0;
1980                 }
1981                 break;
1982         }
1983         case KVM_GET_IRQCHIP: {
1984                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1985                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
1986
1987                 r = -ENOMEM;
1988                 if (!chip)
1989                         goto out;
1990                 r = -EFAULT;
1991                 if (copy_from_user(chip, argp, sizeof *chip))
1992                         goto get_irqchip_out;
1993                 r = -ENXIO;
1994                 if (!irqchip_in_kernel(kvm))
1995                         goto get_irqchip_out;
1996                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
1997                 if (r)
1998                         goto get_irqchip_out;
1999                 r = -EFAULT;
2000                 if (copy_to_user(argp, chip, sizeof *chip))
2001                         goto get_irqchip_out;
2002                 r = 0;
2003         get_irqchip_out:
2004                 kfree(chip);
2005                 if (r)
2006                         goto out;
2007                 break;
2008         }
2009         case KVM_SET_IRQCHIP: {
2010                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
2011                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
2012
2013                 r = -ENOMEM;
2014                 if (!chip)
2015                         goto out;
2016                 r = -EFAULT;
2017                 if (copy_from_user(chip, argp, sizeof *chip))
2018                         goto set_irqchip_out;
2019                 r = -ENXIO;
2020                 if (!irqchip_in_kernel(kvm))
2021                         goto set_irqchip_out;
2022                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
2023                 if (r)
2024                         goto set_irqchip_out;
2025                 r = 0;
2026         set_irqchip_out:
2027                 kfree(chip);
2028                 if (r)
2029                         goto out;
2030                 break;
2031         }
2032         case KVM_ASSIGN_PCI_DEVICE: {
2033                 struct kvm_assigned_pci_dev assigned_dev;
2034
2035                 r = -EFAULT;
2036                 if (copy_from_user(&assigned_dev, argp, sizeof assigned_dev))
2037                         goto out;
2038                 r = kvm_vm_ioctl_assign_device(kvm, &assigned_dev);
2039                 if (r)
2040                         goto out;
2041                 break;
2042         }
2043         case KVM_ASSIGN_IRQ: {
2044                 struct kvm_assigned_irq assigned_irq;
2045
2046                 r = -EFAULT;
2047                 if (copy_from_user(&assigned_irq, argp, sizeof assigned_irq))
2048                         goto out;
2049                 r = kvm_vm_ioctl_assign_irq(kvm, &assigned_irq);
2050                 if (r)
2051                         goto out;
2052                 break;
2053         }
2054         case KVM_GET_PIT: {
2055                 r = -EFAULT;
2056                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
2057                         goto out;
2058                 r = -ENXIO;
2059                 if (!kvm->arch.vpit)
2060                         goto out;
2061                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
2062                 if (r)
2063                         goto out;
2064                 r = -EFAULT;
2065                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
2066                         goto out;
2067                 r = 0;
2068                 break;
2069         }
2070         case KVM_SET_PIT: {
2071                 r = -EFAULT;
2072                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
2073                         goto out;
2074                 r = -ENXIO;
2075                 if (!kvm->arch.vpit)
2076                         goto out;
2077                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
2078                 if (r)
2079                         goto out;
2080                 r = 0;
2081                 break;
2082         }
2083         default:
2084                 ;
2085         }
2086 out:
2087         return r;
2088 }
2089
2090 static void kvm_init_msr_list(void)
2091 {
2092         u32 dummy[2];
2093         unsigned i, j;
2094
2095         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
2096                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
2097                         continue;
2098                 if (j < i)
2099                         msrs_to_save[j] = msrs_to_save[i];
2100                 j++;
2101         }
2102         num_msrs_to_save = j;
2103 }
2104
2105 /*
2106  * Only apic need an MMIO device hook, so shortcut now..
2107  */
2108 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
2109                                                 gpa_t addr, int len,
2110                                                 int is_write)
2111 {
2112         struct kvm_io_device *dev;
2113
2114         if (vcpu->arch.apic) {
2115                 dev = &vcpu->arch.apic->dev;
2116                 if (dev->in_range(dev, addr, len, is_write))
2117                         return dev;
2118         }
2119         return NULL;
2120 }
2121
2122
2123 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
2124                                                 gpa_t addr, int len,
2125                                                 int is_write)
2126 {
2127         struct kvm_io_device *dev;
2128
2129         dev = vcpu_find_pervcpu_dev(vcpu, addr, len, is_write);
2130         if (dev == NULL)
2131                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr, len,
2132                                           is_write);
2133         return dev;
2134 }
2135
2136 int emulator_read_std(unsigned long addr,
2137                              void *val,
2138                              unsigned int bytes,
2139                              struct kvm_vcpu *vcpu)
2140 {
2141         void *data = val;
2142         int r = X86EMUL_CONTINUE;
2143
2144         while (bytes) {
2145                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2146                 unsigned offset = addr & (PAGE_SIZE-1);
2147                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
2148                 int ret;
2149
2150                 if (gpa == UNMAPPED_GVA) {
2151                         r = X86EMUL_PROPAGATE_FAULT;
2152                         goto out;
2153                 }
2154                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
2155                 if (ret < 0) {
2156                         r = X86EMUL_UNHANDLEABLE;
2157                         goto out;
2158                 }
2159
2160                 bytes -= tocopy;
2161                 data += tocopy;
2162                 addr += tocopy;
2163         }
2164 out:
2165         return r;
2166 }
2167 EXPORT_SYMBOL_GPL(emulator_read_std);
2168
2169 static int emulator_read_emulated(unsigned long addr,
2170                                   void *val,
2171                                   unsigned int bytes,
2172                                   struct kvm_vcpu *vcpu)
2173 {
2174         struct kvm_io_device *mmio_dev;
2175         gpa_t                 gpa;
2176
2177         if (vcpu->mmio_read_completed) {
2178                 memcpy(val, vcpu->mmio_data, bytes);
2179                 vcpu->mmio_read_completed = 0;
2180                 return X86EMUL_CONTINUE;
2181         }
2182
2183         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2184
2185         /* For APIC access vmexit */
2186         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2187                 goto mmio;
2188
2189         if (emulator_read_std(addr, val, bytes, vcpu)
2190                         == X86EMUL_CONTINUE)
2191                 return X86EMUL_CONTINUE;
2192         if (gpa == UNMAPPED_GVA)
2193                 return X86EMUL_PROPAGATE_FAULT;
2194
2195 mmio:
2196         /*
2197          * Is this MMIO handled locally?
2198          */
2199         mutex_lock(&vcpu->kvm->lock);
2200         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa, bytes, 0);
2201         if (mmio_dev) {
2202                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
2203                 mutex_unlock(&vcpu->kvm->lock);
2204                 return X86EMUL_CONTINUE;
2205         }
2206         mutex_unlock(&vcpu->kvm->lock);
2207
2208         vcpu->mmio_needed = 1;
2209         vcpu->mmio_phys_addr = gpa;
2210         vcpu->mmio_size = bytes;
2211         vcpu->mmio_is_write = 0;
2212
2213         return X86EMUL_UNHANDLEABLE;
2214 }
2215
2216 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
2217                           const void *val, int bytes)
2218 {
2219         int ret;
2220
2221         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
2222         if (ret < 0)
2223                 return 0;
2224         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
2225         return 1;
2226 }
2227
2228 static int emulator_write_emulated_onepage(unsigned long addr,
2229                                            const void *val,
2230                                            unsigned int bytes,
2231                                            struct kvm_vcpu *vcpu)
2232 {
2233         struct kvm_io_device *mmio_dev;
2234         gpa_t                 gpa;
2235
2236         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2237
2238         if (gpa == UNMAPPED_GVA) {
2239                 kvm_inject_page_fault(vcpu, addr, 2);
2240                 return X86EMUL_PROPAGATE_FAULT;
2241         }
2242
2243         /* For APIC access vmexit */
2244         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2245                 goto mmio;
2246
2247         if (emulator_write_phys(vcpu, gpa, val, bytes))
2248                 return X86EMUL_CONTINUE;
2249
2250 mmio:
2251         /*
2252          * Is this MMIO handled locally?
2253          */
2254         mutex_lock(&vcpu->kvm->lock);
2255         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa, bytes, 1);
2256         if (mmio_dev) {
2257                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
2258                 mutex_unlock(&vcpu->kvm->lock);
2259                 return X86EMUL_CONTINUE;
2260         }
2261         mutex_unlock(&vcpu->kvm->lock);
2262
2263         vcpu->mmio_needed = 1;
2264         vcpu->mmio_phys_addr = gpa;
2265         vcpu->mmio_size = bytes;
2266         vcpu->mmio_is_write = 1;
2267         memcpy(vcpu->mmio_data, val, bytes);
2268
2269         return X86EMUL_CONTINUE;
2270 }
2271
2272 int emulator_write_emulated(unsigned long addr,
2273                                    const void *val,
2274                                    unsigned int bytes,
2275                                    struct kvm_vcpu *vcpu)
2276 {
2277         /* Crossing a page boundary? */
2278         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
2279                 int rc, now;
2280
2281                 now = -addr & ~PAGE_MASK;
2282                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
2283                 if (rc != X86EMUL_CONTINUE)
2284                         return rc;
2285                 addr += now;
2286                 val += now;
2287                 bytes -= now;
2288         }
2289         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
2290 }
2291 EXPORT_SYMBOL_GPL(emulator_write_emulated);
2292
2293 static int emulator_cmpxchg_emulated(unsigned long addr,
2294                                      const void *old,
2295                                      const void *new,
2296                                      unsigned int bytes,
2297                                      struct kvm_vcpu *vcpu)
2298 {
2299         static int reported;
2300
2301         if (!reported) {
2302                 reported = 1;
2303                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
2304         }
2305 #ifndef CONFIG_X86_64
2306         /* guests cmpxchg8b have to be emulated atomically */
2307         if (bytes == 8) {
2308                 gpa_t gpa;
2309                 struct page *page;
2310                 char *kaddr;
2311                 u64 val;
2312
2313                 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2314
2315                 if (gpa == UNMAPPED_GVA ||
2316                    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2317                         goto emul_write;
2318
2319                 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
2320                         goto emul_write;
2321
2322                 val = *(u64 *)new;
2323
2324                 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2325
2326                 kaddr = kmap_atomic(page, KM_USER0);
2327                 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
2328                 kunmap_atomic(kaddr, KM_USER0);
2329                 kvm_release_page_dirty(page);
2330         }
2331 emul_write:
2332 #endif
2333
2334         return emulator_write_emulated(addr, new, bytes, vcpu);
2335 }
2336
2337 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
2338 {
2339         return kvm_x86_ops->get_segment_base(vcpu, seg);
2340 }
2341
2342 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
2343 {
2344         kvm_mmu_invlpg(vcpu, address);
2345         return X86EMUL_CONTINUE;
2346 }
2347
2348 int emulate_clts(struct kvm_vcpu *vcpu)
2349 {
2350         KVMTRACE_0D(CLTS, vcpu, handler);
2351         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
2352         return X86EMUL_CONTINUE;
2353 }
2354
2355 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
2356 {
2357         struct kvm_vcpu *vcpu = ctxt->vcpu;
2358
2359         switch (dr) {
2360         case 0 ... 3:
2361                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
2362                 return X86EMUL_CONTINUE;
2363         default:
2364                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __func__, dr);
2365                 return X86EMUL_UNHANDLEABLE;
2366         }
2367 }
2368
2369 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
2370 {
2371         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
2372         int exception;
2373
2374         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
2375         if (exception) {
2376                 /* FIXME: better handling */
2377                 return X86EMUL_UNHANDLEABLE;
2378         }
2379         return X86EMUL_CONTINUE;
2380 }
2381
2382 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
2383 {
2384         u8 opcodes[4];
2385         unsigned long rip = kvm_rip_read(vcpu);
2386         unsigned long rip_linear;
2387
2388         if (!printk_ratelimit())
2389                 return;
2390
2391         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
2392
2393         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
2394
2395         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
2396                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
2397 }
2398 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
2399
2400 static struct x86_emulate_ops emulate_ops = {
2401         .read_std            = emulator_read_std,
2402         .read_emulated       = emulator_read_emulated,
2403         .write_emulated      = emulator_write_emulated,
2404         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
2405 };
2406
2407 static void cache_all_regs(struct kvm_vcpu *vcpu)
2408 {
2409         kvm_register_read(vcpu, VCPU_REGS_RAX);
2410         kvm_register_read(vcpu, VCPU_REGS_RSP);
2411         kvm_register_read(vcpu, VCPU_REGS_RIP);
2412         vcpu->arch.regs_dirty = ~0;
2413 }
2414
2415 int emulate_instruction(struct kvm_vcpu *vcpu,
2416                         struct kvm_run *run,
2417                         unsigned long cr2,
2418                         u16 error_code,
2419                         int emulation_type)
2420 {
2421         int r;
2422         struct decode_cache *c;
2423
2424         kvm_clear_exception_queue(vcpu);
2425         vcpu->arch.mmio_fault_cr2 = cr2;
2426         /*
2427          * TODO: fix x86_emulate.c to use guest_read/write_register
2428          * instead of direct ->regs accesses, can save hundred cycles
2429          * on Intel for instructions that don't read/change RSP, for
2430          * for example.
2431          */
2432         cache_all_regs(vcpu);
2433
2434         vcpu->mmio_is_write = 0;
2435         vcpu->arch.pio.string = 0;
2436
2437         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
2438                 int cs_db, cs_l;
2439                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
2440
2441                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
2442                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
2443                 vcpu->arch.emulate_ctxt.mode =
2444                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
2445                         ? X86EMUL_MODE_REAL : cs_l
2446                         ? X86EMUL_MODE_PROT64 : cs_db
2447                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
2448
2449                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2450
2451                 /* Reject the instructions other than VMCALL/VMMCALL when
2452                  * try to emulate invalid opcode */
2453                 c = &vcpu->arch.emulate_ctxt.decode;
2454                 if ((emulation_type & EMULTYPE_TRAP_UD) &&
2455                     (!(c->twobyte && c->b == 0x01 &&
2456                       (c->modrm_reg == 0 || c->modrm_reg == 3) &&
2457                        c->modrm_mod == 3 && c->modrm_rm == 1)))
2458                         return EMULATE_FAIL;
2459
2460                 ++vcpu->stat.insn_emulation;
2461                 if (r)  {
2462                         ++vcpu->stat.insn_emulation_fail;
2463                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2464                                 return EMULATE_DONE;
2465                         return EMULATE_FAIL;
2466                 }
2467         }
2468
2469         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2470
2471         if (vcpu->arch.pio.string)
2472                 return EMULATE_DO_MMIO;
2473
2474         if ((r || vcpu->mmio_is_write) && run) {
2475                 run->exit_reason = KVM_EXIT_MMIO;
2476                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
2477                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
2478                 run->mmio.len = vcpu->mmio_size;
2479                 run->mmio.is_write = vcpu->mmio_is_write;
2480         }
2481
2482         if (r) {
2483                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2484                         return EMULATE_DONE;
2485                 if (!vcpu->mmio_needed) {
2486                         kvm_report_emulation_failure(vcpu, "mmio");
2487                         return EMULATE_FAIL;
2488                 }
2489                 return EMULATE_DO_MMIO;
2490         }
2491
2492         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
2493
2494         if (vcpu->mmio_is_write) {
2495                 vcpu->mmio_needed = 0;
2496                 return EMULATE_DO_MMIO;
2497         }
2498
2499         return EMULATE_DONE;
2500 }
2501 EXPORT_SYMBOL_GPL(emulate_instruction);
2502
2503 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
2504 {
2505         int i;
2506
2507         for (i = 0; i < ARRAY_SIZE(vcpu->arch.pio.guest_pages); ++i)
2508                 if (vcpu->arch.pio.guest_pages[i]) {
2509                         kvm_release_page_dirty(vcpu->arch.pio.guest_pages[i]);
2510                         vcpu->arch.pio.guest_pages[i] = NULL;
2511                 }
2512 }
2513
2514 static int pio_copy_data(struct kvm_vcpu *vcpu)
2515 {
2516         void *p = vcpu->arch.pio_data;
2517         void *q;
2518         unsigned bytes;
2519         int nr_pages = vcpu->arch.pio.guest_pages[1] ? 2 : 1;
2520
2521         q = vmap(vcpu->arch.pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
2522                  PAGE_KERNEL);
2523         if (!q) {
2524                 free_pio_guest_pages(vcpu);
2525                 return -ENOMEM;
2526         }
2527         q += vcpu->arch.pio.guest_page_offset;
2528         bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
2529         if (vcpu->arch.pio.in)
2530                 memcpy(q, p, bytes);
2531         else
2532                 memcpy(p, q, bytes);
2533         q -= vcpu->arch.pio.guest_page_offset;
2534         vunmap(q);
2535         free_pio_guest_pages(vcpu);
2536         return 0;
2537 }
2538
2539 int complete_pio(struct kvm_vcpu *vcpu)
2540 {
2541         struct kvm_pio_request *io = &vcpu->arch.pio;
2542         long delta;
2543         int r;
2544         unsigned long val;
2545
2546         if (!io->string) {
2547                 if (io->in) {
2548                         val = kvm_register_read(vcpu, VCPU_REGS_RAX);
2549                         memcpy(&val, vcpu->arch.pio_data, io->size);
2550                         kvm_register_write(vcpu, VCPU_REGS_RAX, val);
2551                 }
2552         } else {
2553                 if (io->in) {
2554                         r = pio_copy_data(vcpu);
2555                         if (r)
2556                                 return r;
2557                 }
2558
2559                 delta = 1;
2560                 if (io->rep) {
2561                         delta *= io->cur_count;
2562                         /*
2563                          * The size of the register should really depend on
2564                          * current address size.
2565                          */
2566                         val = kvm_register_read(vcpu, VCPU_REGS_RCX);
2567                         val -= delta;
2568                         kvm_register_write(vcpu, VCPU_REGS_RCX, val);
2569                 }
2570                 if (io->down)
2571                         delta = -delta;
2572                 delta *= io->size;
2573                 if (io->in) {
2574                         val = kvm_register_read(vcpu, VCPU_REGS_RDI);
2575                         val += delta;
2576                         kvm_register_write(vcpu, VCPU_REGS_RDI, val);
2577                 } else {
2578                         val = kvm_register_read(vcpu, VCPU_REGS_RSI);
2579                         val += delta;
2580                         kvm_register_write(vcpu, VCPU_REGS_RSI, val);
2581                 }
2582         }
2583
2584         io->count -= io->cur_count;
2585         io->cur_count = 0;
2586
2587         return 0;
2588 }
2589
2590 static void kernel_pio(struct kvm_io_device *pio_dev,
2591                        struct kvm_vcpu *vcpu,
2592                        void *pd)
2593 {
2594         /* TODO: String I/O for in kernel device */
2595
2596         mutex_lock(&vcpu->kvm->lock);
2597         if (vcpu->arch.pio.in)
2598                 kvm_iodevice_read(pio_dev, vcpu->arch.pio.port,
2599                                   vcpu->arch.pio.size,
2600                                   pd);
2601         else
2602                 kvm_iodevice_write(pio_dev, vcpu->arch.pio.port,
2603                                    vcpu->arch.pio.size,
2604                                    pd);
2605         mutex_unlock(&vcpu->kvm->lock);
2606 }
2607
2608 static void pio_string_write(struct kvm_io_device *pio_dev,
2609                              struct kvm_vcpu *vcpu)
2610 {
2611         struct kvm_pio_request *io = &vcpu->arch.pio;
2612         void *pd = vcpu->arch.pio_data;
2613         int i;
2614
2615         mutex_lock(&vcpu->kvm->lock);
2616         for (i = 0; i < io->cur_count; i++) {
2617                 kvm_iodevice_write(pio_dev, io->port,
2618                                    io->size,
2619                                    pd);
2620                 pd += io->size;
2621         }
2622         mutex_unlock(&vcpu->kvm->lock);
2623 }
2624
2625 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
2626                                                gpa_t addr, int len,
2627                                                int is_write)
2628 {
2629         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr, len, is_write);
2630 }
2631
2632 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2633                   int size, unsigned port)
2634 {
2635         struct kvm_io_device *pio_dev;
2636         unsigned long val;
2637
2638         vcpu->run->exit_reason = KVM_EXIT_IO;
2639         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2640         vcpu->run->io.size = vcpu->arch.pio.size = size;
2641         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2642         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2643         vcpu->run->io.port = vcpu->arch.pio.port = port;
2644         vcpu->arch.pio.in = in;
2645         vcpu->arch.pio.string = 0;
2646         vcpu->arch.pio.down = 0;
2647         vcpu->arch.pio.guest_page_offset = 0;
2648         vcpu->arch.pio.rep = 0;
2649
2650         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2651                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2652                             handler);
2653         else
2654                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2655                             handler);
2656
2657         val = kvm_register_read(vcpu, VCPU_REGS_RAX);
2658         memcpy(vcpu->arch.pio_data, &val, 4);
2659
2660         kvm_x86_ops->skip_emulated_instruction(vcpu);
2661
2662         pio_dev = vcpu_find_pio_dev(vcpu, port, size, !in);
2663         if (pio_dev) {
2664                 kernel_pio(pio_dev, vcpu, vcpu->arch.pio_data);
2665                 complete_pio(vcpu);
2666                 return 1;
2667         }
2668         return 0;
2669 }
2670 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
2671
2672 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2673                   int size, unsigned long count, int down,
2674                   gva_t address, int rep, unsigned port)
2675 {
2676         unsigned now, in_page;
2677         int i, ret = 0;
2678         int nr_pages = 1;
2679         struct page *page;
2680         struct kvm_io_device *pio_dev;
2681
2682         vcpu->run->exit_reason = KVM_EXIT_IO;
2683         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2684         vcpu->run->io.size = vcpu->arch.pio.size = size;
2685         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2686         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
2687         vcpu->run->io.port = vcpu->arch.pio.port = port;
2688         vcpu->arch.pio.in = in;
2689         vcpu->arch.pio.string = 1;
2690         vcpu->arch.pio.down = down;
2691         vcpu->arch.pio.guest_page_offset = offset_in_page(address);
2692         vcpu->arch.pio.rep = rep;
2693
2694         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2695                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2696                             handler);
2697         else
2698                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2699                             handler);
2700
2701         if (!count) {
2702                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2703                 return 1;
2704         }
2705
2706         if (!down)
2707                 in_page = PAGE_SIZE - offset_in_page(address);
2708         else
2709                 in_page = offset_in_page(address) + size;
2710         now = min(count, (unsigned long)in_page / size);
2711         if (!now) {
2712                 /*
2713                  * String I/O straddles page boundary.  Pin two guest pages
2714                  * so that we satisfy atomicity constraints.  Do just one
2715                  * transaction to avoid complexity.
2716                  */
2717                 nr_pages = 2;
2718                 now = 1;
2719         }
2720         if (down) {
2721                 /*
2722                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
2723                  */
2724                 pr_unimpl(vcpu, "guest string pio down\n");
2725                 kvm_inject_gp(vcpu, 0);
2726                 return 1;
2727         }
2728         vcpu->run->io.count = now;
2729         vcpu->arch.pio.cur_count = now;
2730
2731         if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
2732                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2733
2734         for (i = 0; i < nr_pages; ++i) {
2735                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
2736                 vcpu->arch.pio.guest_pages[i] = page;
2737                 if (!page) {
2738                         kvm_inject_gp(vcpu, 0);
2739                         free_pio_guest_pages(vcpu);
2740                         return 1;
2741                 }
2742         }
2743
2744         pio_dev = vcpu_find_pio_dev(vcpu, port,
2745                                     vcpu->arch.pio.cur_count,
2746                                     !vcpu->arch.pio.in);
2747         if (!vcpu->arch.pio.in) {
2748                 /* string PIO write */
2749                 ret = pio_copy_data(vcpu);
2750                 if (ret >= 0 && pio_dev) {
2751                         pio_string_write(pio_dev, vcpu);
2752                         complete_pio(vcpu);
2753                         if (vcpu->arch.pio.count == 0)
2754                                 ret = 1;
2755                 }
2756         } else if (pio_dev)
2757                 pr_unimpl(vcpu, "no string pio read support yet, "
2758                        "port %x size %d count %ld\n",
2759                         port, size, count);
2760
2761         return ret;
2762 }
2763 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2764
2765 int kvm_arch_init(void *opaque)
2766 {
2767         int r;
2768         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2769
2770         if (kvm_x86_ops) {
2771                 printk(KERN_ERR "kvm: already loaded the other module\n");
2772                 r = -EEXIST;
2773                 goto out;
2774         }
2775
2776         if (!ops->cpu_has_kvm_support()) {
2777                 printk(KERN_ERR "kvm: no hardware support\n");
2778                 r = -EOPNOTSUPP;
2779                 goto out;
2780         }
2781         if (ops->disabled_by_bios()) {
2782                 printk(KERN_ERR "kvm: disabled by bios\n");
2783                 r = -EOPNOTSUPP;
2784                 goto out;
2785         }
2786
2787         r = kvm_mmu_module_init();
2788         if (r)
2789                 goto out;
2790
2791         kvm_init_msr_list();
2792
2793         kvm_x86_ops = ops;
2794         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2795         kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
2796         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
2797                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
2798         return 0;
2799
2800 out:
2801         return r;
2802 }
2803
2804 void kvm_arch_exit(void)
2805 {
2806         kvm_x86_ops = NULL;
2807         kvm_mmu_module_exit();
2808 }
2809
2810 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2811 {
2812         ++vcpu->stat.halt_exits;
2813         KVMTRACE_0D(HLT, vcpu, handler);
2814         if (irqchip_in_kernel(vcpu->kvm)) {
2815                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
2816                 return 1;
2817         } else {
2818                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2819                 return 0;
2820         }
2821 }
2822 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2823
2824 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
2825                            unsigned long a1)
2826 {
2827         if (is_long_mode(vcpu))
2828                 return a0;
2829         else
2830                 return a0 | ((gpa_t)a1 << 32);
2831 }
2832
2833 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2834 {
2835         unsigned long nr, a0, a1, a2, a3, ret;
2836         int r = 1;
2837
2838         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
2839         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
2840         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
2841         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
2842         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
2843
2844         KVMTRACE_1D(VMMCALL, vcpu, (u32)nr, handler);
2845
2846         if (!is_long_mode(vcpu)) {
2847                 nr &= 0xFFFFFFFF;
2848                 a0 &= 0xFFFFFFFF;
2849                 a1 &= 0xFFFFFFFF;
2850                 a2 &= 0xFFFFFFFF;
2851                 a3 &= 0xFFFFFFFF;
2852         }
2853
2854         switch (nr) {
2855         case KVM_HC_VAPIC_POLL_IRQ:
2856                 ret = 0;
2857                 break;
2858         case KVM_HC_MMU_OP:
2859                 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
2860                 break;
2861         default:
2862                 ret = -KVM_ENOSYS;
2863                 break;
2864         }
2865         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
2866         ++vcpu->stat.hypercalls;
2867         return r;
2868 }
2869 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2870
2871 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2872 {
2873         char instruction[3];
2874         int ret = 0;
2875         unsigned long rip = kvm_rip_read(vcpu);
2876
2877
2878         /*
2879          * Blow out the MMU to ensure that no other VCPU has an active mapping
2880          * to ensure that the updated hypercall appears atomically across all
2881          * VCPUs.
2882          */
2883         kvm_mmu_zap_all(vcpu->kvm);
2884
2885         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2886         if (emulator_write_emulated(rip, instruction, 3, vcpu)
2887             != X86EMUL_CONTINUE)
2888                 ret = -EFAULT;
2889
2890         return ret;
2891 }
2892
2893 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2894 {
2895         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2896 }
2897
2898 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2899 {
2900         struct descriptor_table dt = { limit, base };
2901
2902         kvm_x86_ops->set_gdt(vcpu, &dt);
2903 }
2904
2905 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2906 {
2907         struct descriptor_table dt = { limit, base };
2908
2909         kvm_x86_ops->set_idt(vcpu, &dt);
2910 }
2911
2912 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2913                    unsigned long *rflags)
2914 {
2915         kvm_lmsw(vcpu, msw);
2916         *rflags = kvm_x86_ops->get_rflags(vcpu);
2917 }
2918
2919 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2920 {
2921         unsigned long value;
2922
2923         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2924         switch (cr) {
2925         case 0:
2926                 value = vcpu->arch.cr0;
2927                 break;
2928         case 2:
2929                 value = vcpu->arch.cr2;
2930                 break;
2931         case 3:
2932                 value = vcpu->arch.cr3;
2933                 break;
2934         case 4:
2935                 value = vcpu->arch.cr4;
2936                 break;
2937         case 8:
2938                 value = kvm_get_cr8(vcpu);
2939                 break;
2940         default:
2941                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2942                 return 0;
2943         }
2944         KVMTRACE_3D(CR_READ, vcpu, (u32)cr, (u32)value,
2945                     (u32)((u64)value >> 32), handler);
2946
2947         return value;
2948 }
2949
2950 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2951                      unsigned long *rflags)
2952 {
2953         KVMTRACE_3D(CR_WRITE, vcpu, (u32)cr, (u32)val,
2954                     (u32)((u64)val >> 32), handler);
2955
2956         switch (cr) {
2957         case 0:
2958                 kvm_set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2959                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2960                 break;
2961         case 2:
2962                 vcpu->arch.cr2 = val;
2963                 break;
2964         case 3:
2965                 kvm_set_cr3(vcpu, val);
2966                 break;
2967         case 4:
2968                 kvm_set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2969                 break;
2970         case 8:
2971                 kvm_set_cr8(vcpu, val & 0xfUL);
2972                 break;
2973         default:
2974                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2975         }
2976 }
2977
2978 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2979 {
2980         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2981         int j, nent = vcpu->arch.cpuid_nent;
2982
2983         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2984         /* when no next entry is found, the current entry[i] is reselected */
2985         for (j = i + 1; j == i; j = (j + 1) % nent) {
2986                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2987                 if (ej->function == e->function) {
2988                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2989                         return j;
2990                 }
2991         }
2992         return 0; /* silence gcc, even though control never reaches here */
2993 }
2994
2995 /* find an entry with matching function, matching index (if needed), and that
2996  * should be read next (if it's stateful) */
2997 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2998         u32 function, u32 index)
2999 {
3000         if (e->function != function)
3001                 return 0;
3002         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
3003                 return 0;
3004         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
3005                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
3006                 return 0;
3007         return 1;
3008 }
3009
3010 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
3011 {
3012         int i;
3013         u32 function, index;
3014         struct kvm_cpuid_entry2 *e, *best;
3015
3016         function = kvm_register_read(vcpu, VCPU_REGS_RAX);
3017         index = kvm_register_read(vcpu, VCPU_REGS_RCX);
3018         kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
3019         kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
3020         kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
3021         kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
3022         best = NULL;
3023         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
3024                 e = &vcpu->arch.cpuid_entries[i];
3025                 if (is_matching_cpuid_entry(e, function, index)) {
3026                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
3027                                 move_to_next_stateful_cpuid_entry(vcpu, i);
3028                         best = e;
3029                         break;
3030                 }
3031                 /*
3032                  * Both basic or both extended?
3033                  */
3034                 if (((e->function ^ function) & 0x80000000) == 0)
3035                         if (!best || e->function > best->function)
3036                                 best = e;
3037         }
3038         if (best) {
3039                 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
3040                 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
3041                 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
3042                 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
3043         }
3044         kvm_x86_ops->skip_emulated_instruction(vcpu);
3045         KVMTRACE_5D(CPUID, vcpu, function,
3046                     (u32)kvm_register_read(vcpu, VCPU_REGS_RAX),
3047                     (u32)kvm_register_read(vcpu, VCPU_REGS_RBX),
3048                     (u32)kvm_register_read(vcpu, VCPU_REGS_RCX),
3049                     (u32)kvm_register_read(vcpu, VCPU_REGS_RDX), handler);
3050 }
3051 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
3052
3053 /*
3054  * Check if userspace requested an interrupt window, and that the
3055  * interrupt window is open.
3056  *
3057  * No need to exit to userspace if we already have an interrupt queued.
3058  */
3059 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
3060                                           struct kvm_run *kvm_run)
3061 {
3062         return (!vcpu->arch.irq_summary &&
3063                 kvm_run->request_interrupt_window &&
3064                 vcpu->arch.interrupt_window_open &&
3065                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
3066 }
3067
3068 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
3069                               struct kvm_run *kvm_run)
3070 {
3071         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
3072         kvm_run->cr8 = kvm_get_cr8(vcpu);
3073         kvm_run->apic_base = kvm_get_apic_base(vcpu);
3074         if (irqchip_in_kernel(vcpu->kvm))
3075                 kvm_run->ready_for_interrupt_injection = 1;
3076         else
3077                 kvm_run->ready_for_interrupt_injection =
3078                                         (vcpu->arch.interrupt_window_open &&
3079                                          vcpu->arch.irq_summary == 0);
3080 }
3081
3082 static void vapic_enter(struct kvm_vcpu *vcpu)
3083 {
3084         struct kvm_lapic *apic = vcpu->arch.apic;
3085         struct page *page;
3086
3087         if (!apic || !apic->vapic_addr)
3088                 return;
3089
3090         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
3091
3092         vcpu->arch.apic->vapic_page = page;
3093 }
3094
3095 static void vapic_exit(struct kvm_vcpu *vcpu)
3096 {
3097         struct kvm_lapic *apic = vcpu->arch.apic;
3098
3099         if (!apic || !apic->vapic_addr)
3100                 return;
3101
3102         down_read(&vcpu->kvm->slots_lock);
3103         kvm_release_page_dirty(apic->vapic_page);
3104         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
3105         up_read(&vcpu->kvm->slots_lock);
3106 }
3107
3108 static int vcpu_enter_guest(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3109 {
3110         int r;
3111
3112         if (vcpu->requests)
3113                 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
3114                         kvm_mmu_unload(vcpu);
3115
3116         r = kvm_mmu_reload(vcpu);
3117         if (unlikely(r))
3118                 goto out;
3119
3120         if (vcpu->requests) {
3121                 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
3122                         __kvm_migrate_timers(vcpu);
3123                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
3124                         kvm_x86_ops->tlb_flush(vcpu);
3125                 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
3126                                        &vcpu->requests)) {
3127                         kvm_run->exit_reason = KVM_EXIT_TPR_ACCESS;
3128                         r = 0;
3129                         goto out;
3130                 }
3131                 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
3132                         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
3133                         r = 0;
3134                         goto out;
3135                 }
3136         }
3137
3138         clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
3139         kvm_inject_pending_timer_irqs(vcpu);
3140
3141         preempt_disable();
3142
3143         kvm_x86_ops->prepare_guest_switch(vcpu);
3144         kvm_load_guest_fpu(vcpu);
3145
3146         local_irq_disable();
3147
3148         if (vcpu->requests || need_resched() || signal_pending(current)) {
3149                 local_irq_enable();
3150                 preempt_enable();
3151                 r = 1;
3152                 goto out;
3153         }
3154
3155         if (vcpu->guest_debug.enabled)
3156                 kvm_x86_ops->guest_debug_pre(vcpu);
3157
3158         vcpu->guest_mode = 1;
3159         /*
3160          * Make sure that guest_mode assignment won't happen after
3161          * testing the pending IRQ vector bitmap.
3162          */
3163         smp_wmb();
3164
3165         if (vcpu->arch.exception.pending)
3166                 __queue_exception(vcpu);
3167         else if (irqchip_in_kernel(vcpu->kvm))
3168                 kvm_x86_ops->inject_pending_irq(vcpu);
3169         else
3170                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
3171
3172         kvm_lapic_sync_to_vapic(vcpu);
3173
3174         up_read(&vcpu->kvm->slots_lock);
3175
3176         kvm_guest_enter();
3177
3178
3179         KVMTRACE_0D(VMENTRY, vcpu, entryexit);
3180         kvm_x86_ops->run(vcpu, kvm_run);
3181
3182         vcpu->guest_mode = 0;
3183         local_irq_enable();
3184
3185         ++vcpu->stat.exits;
3186
3187         /*
3188          * We must have an instruction between local_irq_enable() and
3189          * kvm_guest_exit(), so the timer interrupt isn't delayed by
3190          * the interrupt shadow.  The stat.exits increment will do nicely.
3191          * But we need to prevent reordering, hence this barrier():
3192          */
3193         barrier();
3194
3195         kvm_guest_exit();
3196
3197         preempt_enable();
3198
3199         down_read(&vcpu->kvm->slots_lock);
3200
3201         /*
3202          * Profile KVM exit RIPs:
3203          */
3204         if (unlikely(prof_on == KVM_PROFILING)) {
3205                 unsigned long rip = kvm_rip_read(vcpu);
3206                 profile_hit(KVM_PROFILING, (void *)rip);
3207         }
3208
3209         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
3210                 vcpu->arch.exception.pending = false;
3211
3212         kvm_lapic_sync_from_vapic(vcpu);
3213
3214         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
3215 out:
3216         return r;
3217 }
3218
3219 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3220 {
3221         int r;
3222
3223         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
3224                 printk("vcpu %d received sipi with vector # %x\n",
3225                        vcpu->vcpu_id, vcpu->arch.sipi_vector);
3226                 kvm_lapic_reset(vcpu);
3227                 r = kvm_x86_ops->vcpu_reset(vcpu);
3228                 if (r)
3229                         return r;
3230                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3231         }
3232
3233         down_read(&vcpu->kvm->slots_lock);
3234         vapic_enter(vcpu);
3235
3236         r = 1;
3237         while (r > 0) {
3238                 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE)
3239                         r = vcpu_enter_guest(vcpu, kvm_run);
3240                 else {
3241                         up_read(&vcpu->kvm->slots_lock);
3242                         kvm_vcpu_block(vcpu);
3243                         down_read(&vcpu->kvm->slots_lock);
3244                         if (test_and_clear_bit(KVM_REQ_UNHALT, &vcpu->requests))
3245                                 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
3246                                         vcpu->arch.mp_state =
3247                                                         KVM_MP_STATE_RUNNABLE;
3248                         if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
3249                                 r = -EINTR;
3250                 }
3251
3252                 if (r > 0) {
3253                         if (dm_request_for_irq_injection(vcpu, kvm_run)) {
3254                                 r = -EINTR;
3255                                 kvm_run->exit_reason = KVM_EXIT_INTR;
3256                                 ++vcpu->stat.request_irq_exits;
3257                         }
3258                         if (signal_pending(current)) {
3259                                 r = -EINTR;
3260                                 kvm_run->exit_reason = KVM_EXIT_INTR;
3261                                 ++vcpu->stat.signal_exits;
3262                         }
3263                         if (need_resched()) {
3264                                 up_read(&vcpu->kvm->slots_lock);
3265                                 kvm_resched(vcpu);
3266                                 down_read(&vcpu->kvm->slots_lock);
3267                         }
3268                 }
3269         }
3270
3271         up_read(&vcpu->kvm->slots_lock);
3272         post_kvm_run_save(vcpu, kvm_run);
3273
3274         vapic_exit(vcpu);
3275
3276         return r;
3277 }
3278
3279 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3280 {
3281         int r;
3282         sigset_t sigsaved;
3283
3284         vcpu_load(vcpu);
3285
3286         if (vcpu->sigset_active)
3287                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
3288
3289         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
3290                 kvm_vcpu_block(vcpu);
3291                 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
3292                 r = -EAGAIN;
3293                 goto out;
3294         }
3295
3296         /* re-sync apic's tpr */
3297         if (!irqchip_in_kernel(vcpu->kvm))
3298                 kvm_set_cr8(vcpu, kvm_run->cr8);
3299
3300         if (vcpu->arch.pio.cur_count) {
3301                 r = complete_pio(vcpu);
3302                 if (r)
3303                         goto out;
3304         }
3305 #if CONFIG_HAS_IOMEM
3306         if (vcpu->mmio_needed) {
3307                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
3308                 vcpu->mmio_read_completed = 1;
3309                 vcpu->mmio_needed = 0;
3310
3311                 down_read(&vcpu->kvm->slots_lock);
3312                 r = emulate_instruction(vcpu, kvm_run,
3313                                         vcpu->arch.mmio_fault_cr2, 0,
3314                                         EMULTYPE_NO_DECODE);
3315                 up_read(&vcpu->kvm->slots_lock);
3316                 if (r == EMULATE_DO_MMIO) {
3317                         /*
3318                          * Read-modify-write.  Back to userspace.
3319                          */
3320                         r = 0;
3321                         goto out;
3322                 }
3323         }
3324 #endif
3325         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
3326                 kvm_register_write(vcpu, VCPU_REGS_RAX,
3327                                      kvm_run->hypercall.ret);
3328
3329         r = __vcpu_run(vcpu, kvm_run);
3330
3331 out:
3332         if (vcpu->sigset_active)
3333                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
3334
3335         vcpu_put(vcpu);
3336         return r;
3337 }
3338
3339 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3340 {
3341         vcpu_load(vcpu);
3342
3343         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3344         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3345         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3346         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3347         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
3348         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
3349         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3350         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3351 #ifdef CONFIG_X86_64
3352         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
3353         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
3354         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
3355         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
3356         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
3357         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
3358         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
3359         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
3360 #endif
3361
3362         regs->rip = kvm_rip_read(vcpu);
3363         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
3364
3365         /*
3366          * Don't leak debug flags in case they were set for guest debugging
3367          */
3368         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
3369                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
3370
3371         vcpu_put(vcpu);
3372
3373         return 0;
3374 }
3375
3376 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3377 {
3378         vcpu_load(vcpu);
3379
3380         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
3381         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
3382         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
3383         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
3384         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
3385         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
3386         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
3387         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
3388 #ifdef CONFIG_X86_64
3389         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
3390         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
3391         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);