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