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