KVM: x86: do not execute halted vcpus
[safe/jmp/linux-2.6] / 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                 return 1;
2802         } else {
2803                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2804                 return 0;
2805         }
2806 }
2807 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2808
2809 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
2810                            unsigned long a1)
2811 {
2812         if (is_long_mode(vcpu))
2813                 return a0;
2814         else
2815                 return a0 | ((gpa_t)a1 << 32);
2816 }
2817
2818 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2819 {
2820         unsigned long nr, a0, a1, a2, a3, ret;
2821         int r = 1;
2822
2823         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
2824         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
2825         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
2826         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
2827         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
2828
2829         KVMTRACE_1D(VMMCALL, vcpu, (u32)nr, handler);
2830
2831         if (!is_long_mode(vcpu)) {
2832                 nr &= 0xFFFFFFFF;
2833                 a0 &= 0xFFFFFFFF;
2834                 a1 &= 0xFFFFFFFF;
2835                 a2 &= 0xFFFFFFFF;
2836                 a3 &= 0xFFFFFFFF;
2837         }
2838
2839         switch (nr) {
2840         case KVM_HC_VAPIC_POLL_IRQ:
2841                 ret = 0;
2842                 break;
2843         case KVM_HC_MMU_OP:
2844                 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
2845                 break;
2846         default:
2847                 ret = -KVM_ENOSYS;
2848                 break;
2849         }
2850         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
2851         ++vcpu->stat.hypercalls;
2852         return r;
2853 }
2854 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2855
2856 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2857 {
2858         char instruction[3];
2859         int ret = 0;
2860         unsigned long rip = kvm_rip_read(vcpu);
2861
2862
2863         /*
2864          * Blow out the MMU to ensure that no other VCPU has an active mapping
2865          * to ensure that the updated hypercall appears atomically across all
2866          * VCPUs.
2867          */
2868         kvm_mmu_zap_all(vcpu->kvm);
2869
2870         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2871         if (emulator_write_emulated(rip, instruction, 3, vcpu)
2872             != X86EMUL_CONTINUE)
2873                 ret = -EFAULT;
2874
2875         return ret;
2876 }
2877
2878 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2879 {
2880         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2881 }
2882
2883 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2884 {
2885         struct descriptor_table dt = { limit, base };
2886
2887         kvm_x86_ops->set_gdt(vcpu, &dt);
2888 }
2889
2890 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2891 {
2892         struct descriptor_table dt = { limit, base };
2893
2894         kvm_x86_ops->set_idt(vcpu, &dt);
2895 }
2896
2897 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2898                    unsigned long *rflags)
2899 {
2900         kvm_lmsw(vcpu, msw);
2901         *rflags = kvm_x86_ops->get_rflags(vcpu);
2902 }
2903
2904 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2905 {
2906         unsigned long value;
2907
2908         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2909         switch (cr) {
2910         case 0:
2911                 value = vcpu->arch.cr0;
2912                 break;
2913         case 2:
2914                 value = vcpu->arch.cr2;
2915                 break;
2916         case 3:
2917                 value = vcpu->arch.cr3;
2918                 break;
2919         case 4:
2920                 value = vcpu->arch.cr4;
2921                 break;
2922         case 8:
2923                 value = kvm_get_cr8(vcpu);
2924                 break;
2925         default:
2926                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2927                 return 0;
2928         }
2929         KVMTRACE_3D(CR_READ, vcpu, (u32)cr, (u32)value,
2930                     (u32)((u64)value >> 32), handler);
2931
2932         return value;
2933 }
2934
2935 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2936                      unsigned long *rflags)
2937 {
2938         KVMTRACE_3D(CR_WRITE, vcpu, (u32)cr, (u32)val,
2939                     (u32)((u64)val >> 32), handler);
2940
2941         switch (cr) {
2942         case 0:
2943                 kvm_set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2944                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2945                 break;
2946         case 2:
2947                 vcpu->arch.cr2 = val;
2948                 break;
2949         case 3:
2950                 kvm_set_cr3(vcpu, val);
2951                 break;
2952         case 4:
2953                 kvm_set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2954                 break;
2955         case 8:
2956                 kvm_set_cr8(vcpu, val & 0xfUL);
2957                 break;
2958         default:
2959                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2960         }
2961 }
2962
2963 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2964 {
2965         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2966         int j, nent = vcpu->arch.cpuid_nent;
2967
2968         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2969         /* when no next entry is found, the current entry[i] is reselected */
2970         for (j = i + 1; j == i; j = (j + 1) % nent) {
2971                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2972                 if (ej->function == e->function) {
2973                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2974                         return j;
2975                 }
2976         }
2977         return 0; /* silence gcc, even though control never reaches here */
2978 }
2979
2980 /* find an entry with matching function, matching index (if needed), and that
2981  * should be read next (if it's stateful) */
2982 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2983         u32 function, u32 index)
2984 {
2985         if (e->function != function)
2986                 return 0;
2987         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
2988                 return 0;
2989         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
2990                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
2991                 return 0;
2992         return 1;
2993 }
2994
2995 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2996 {
2997         int i;
2998         u32 function, index;
2999         struct kvm_cpuid_entry2 *e, *best;
3000
3001         function = kvm_register_read(vcpu, VCPU_REGS_RAX);
3002         index = kvm_register_read(vcpu, VCPU_REGS_RCX);
3003         kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
3004         kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
3005         kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
3006         kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
3007         best = NULL;
3008         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
3009                 e = &vcpu->arch.cpuid_entries[i];
3010                 if (is_matching_cpuid_entry(e, function, index)) {
3011                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
3012                                 move_to_next_stateful_cpuid_entry(vcpu, i);
3013                         best = e;
3014                         break;
3015                 }
3016                 /*
3017                  * Both basic or both extended?
3018                  */
3019                 if (((e->function ^ function) & 0x80000000) == 0)
3020                         if (!best || e->function > best->function)
3021                                 best = e;
3022         }
3023         if (best) {
3024                 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
3025                 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
3026                 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
3027                 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
3028         }
3029         kvm_x86_ops->skip_emulated_instruction(vcpu);
3030         KVMTRACE_5D(CPUID, vcpu, function,
3031                     (u32)kvm_register_read(vcpu, VCPU_REGS_RAX),
3032                     (u32)kvm_register_read(vcpu, VCPU_REGS_RBX),
3033                     (u32)kvm_register_read(vcpu, VCPU_REGS_RCX),
3034                     (u32)kvm_register_read(vcpu, VCPU_REGS_RDX), handler);
3035 }
3036 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
3037
3038 /*
3039  * Check if userspace requested an interrupt window, and that the
3040  * interrupt window is open.
3041  *
3042  * No need to exit to userspace if we already have an interrupt queued.
3043  */
3044 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
3045                                           struct kvm_run *kvm_run)
3046 {
3047         return (!vcpu->arch.irq_summary &&
3048                 kvm_run->request_interrupt_window &&
3049                 vcpu->arch.interrupt_window_open &&
3050                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
3051 }
3052
3053 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
3054                               struct kvm_run *kvm_run)
3055 {
3056         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
3057         kvm_run->cr8 = kvm_get_cr8(vcpu);
3058         kvm_run->apic_base = kvm_get_apic_base(vcpu);
3059         if (irqchip_in_kernel(vcpu->kvm))
3060                 kvm_run->ready_for_interrupt_injection = 1;
3061         else
3062                 kvm_run->ready_for_interrupt_injection =
3063                                         (vcpu->arch.interrupt_window_open &&
3064                                          vcpu->arch.irq_summary == 0);
3065 }
3066
3067 static void vapic_enter(struct kvm_vcpu *vcpu)
3068 {
3069         struct kvm_lapic *apic = vcpu->arch.apic;
3070         struct page *page;
3071
3072         if (!apic || !apic->vapic_addr)
3073                 return;
3074
3075         down_read(&current->mm->mmap_sem);
3076         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
3077         up_read(&current->mm->mmap_sem);
3078
3079         vcpu->arch.apic->vapic_page = page;
3080 }
3081
3082 static void vapic_exit(struct kvm_vcpu *vcpu)
3083 {
3084         struct kvm_lapic *apic = vcpu->arch.apic;
3085
3086         if (!apic || !apic->vapic_addr)
3087                 return;
3088
3089         down_read(&vcpu->kvm->slots_lock);
3090         kvm_release_page_dirty(apic->vapic_page);
3091         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
3092         up_read(&vcpu->kvm->slots_lock);
3093 }
3094
3095 static int vcpu_enter_guest(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3096 {
3097         int r;
3098
3099         if (vcpu->requests)
3100                 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
3101                         kvm_mmu_unload(vcpu);
3102
3103         r = kvm_mmu_reload(vcpu);
3104         if (unlikely(r))
3105                 goto out;
3106
3107         if (vcpu->requests) {
3108                 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
3109                         __kvm_migrate_timers(vcpu);
3110                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
3111                         kvm_x86_ops->tlb_flush(vcpu);
3112                 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
3113                                        &vcpu->requests)) {
3114                         kvm_run->exit_reason = KVM_EXIT_TPR_ACCESS;
3115                         r = 0;
3116                         goto out;
3117                 }
3118                 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
3119                         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
3120                         r = 0;
3121                         goto out;
3122                 }
3123         }
3124
3125         clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
3126         kvm_inject_pending_timer_irqs(vcpu);
3127
3128         preempt_disable();
3129
3130         kvm_x86_ops->prepare_guest_switch(vcpu);
3131         kvm_load_guest_fpu(vcpu);
3132
3133         local_irq_disable();
3134
3135         if (vcpu->requests || need_resched() || signal_pending(current)) {
3136                 local_irq_enable();
3137                 preempt_enable();
3138                 r = 1;
3139                 goto out;
3140         }
3141
3142         if (vcpu->guest_debug.enabled)
3143                 kvm_x86_ops->guest_debug_pre(vcpu);
3144
3145         vcpu->guest_mode = 1;
3146         /*
3147          * Make sure that guest_mode assignment won't happen after
3148          * testing the pending IRQ vector bitmap.
3149          */
3150         smp_wmb();
3151
3152         if (vcpu->arch.exception.pending)
3153                 __queue_exception(vcpu);
3154         else if (irqchip_in_kernel(vcpu->kvm))
3155                 kvm_x86_ops->inject_pending_irq(vcpu);
3156         else
3157                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
3158
3159         kvm_lapic_sync_to_vapic(vcpu);
3160
3161         up_read(&vcpu->kvm->slots_lock);
3162
3163         kvm_guest_enter();
3164
3165
3166         KVMTRACE_0D(VMENTRY, vcpu, entryexit);
3167         kvm_x86_ops->run(vcpu, kvm_run);
3168
3169         vcpu->guest_mode = 0;
3170         local_irq_enable();
3171
3172         ++vcpu->stat.exits;
3173
3174         /*
3175          * We must have an instruction between local_irq_enable() and
3176          * kvm_guest_exit(), so the timer interrupt isn't delayed by
3177          * the interrupt shadow.  The stat.exits increment will do nicely.
3178          * But we need to prevent reordering, hence this barrier():
3179          */
3180         barrier();
3181
3182         kvm_guest_exit();
3183
3184         preempt_enable();
3185
3186         down_read(&vcpu->kvm->slots_lock);
3187
3188         /*
3189          * Profile KVM exit RIPs:
3190          */
3191         if (unlikely(prof_on == KVM_PROFILING)) {
3192                 unsigned long rip = kvm_rip_read(vcpu);
3193                 profile_hit(KVM_PROFILING, (void *)rip);
3194         }
3195
3196         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
3197                 vcpu->arch.exception.pending = false;
3198
3199         kvm_lapic_sync_from_vapic(vcpu);
3200
3201         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
3202 out:
3203         return r;
3204 }
3205
3206 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3207 {
3208         int r;
3209
3210         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
3211                 printk("vcpu %d received sipi with vector # %x\n",
3212                        vcpu->vcpu_id, vcpu->arch.sipi_vector);
3213                 kvm_lapic_reset(vcpu);
3214                 r = kvm_x86_ops->vcpu_reset(vcpu);
3215                 if (r)
3216                         return r;
3217                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3218         }
3219
3220         down_read(&vcpu->kvm->slots_lock);
3221         vapic_enter(vcpu);
3222
3223         r = 1;
3224         while (r > 0) {
3225                 if (kvm_arch_vcpu_runnable(vcpu))
3226                         r = vcpu_enter_guest(vcpu, kvm_run);
3227                 else {
3228                         up_read(&vcpu->kvm->slots_lock);
3229                         kvm_vcpu_block(vcpu);
3230                         down_read(&vcpu->kvm->slots_lock);
3231                         if (test_and_clear_bit(KVM_REQ_UNHALT, &vcpu->requests))
3232                                 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
3233                                         vcpu->arch.mp_state =
3234                                                         KVM_MP_STATE_RUNNABLE;
3235                         if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
3236                                 r = -EINTR;
3237                 }
3238
3239                 if (r > 0) {
3240                         if (dm_request_for_irq_injection(vcpu, kvm_run)) {
3241                                 r = -EINTR;
3242                                 kvm_run->exit_reason = KVM_EXIT_INTR;
3243                                 ++vcpu->stat.request_irq_exits;
3244                         }
3245                         if (signal_pending(current)) {
3246                                 r = -EINTR;
3247                                 kvm_run->exit_reason = KVM_EXIT_INTR;
3248                                 ++vcpu->stat.signal_exits;
3249                         }
3250                         if (need_resched()) {
3251                                 up_read(&vcpu->kvm->slots_lock);
3252                                 kvm_resched(vcpu);
3253                                 down_read(&vcpu->kvm->slots_lock);
3254                         }
3255                 }
3256         }
3257
3258         up_read(&vcpu->kvm->slots_lock);
3259         post_kvm_run_save(vcpu, kvm_run);
3260
3261         vapic_exit(vcpu);
3262
3263         return r;
3264 }
3265
3266 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3267 {
3268         int r;
3269         sigset_t sigsaved;
3270
3271         vcpu_load(vcpu);
3272
3273         if (vcpu->sigset_active)
3274                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
3275
3276         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
3277                 kvm_vcpu_block(vcpu);
3278                 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
3279                 r = -EAGAIN;
3280                 goto out;
3281         }
3282
3283         /* re-sync apic's tpr */
3284         if (!irqchip_in_kernel(vcpu->kvm))
3285                 kvm_set_cr8(vcpu, kvm_run->cr8);
3286
3287         if (vcpu->arch.pio.cur_count) {
3288                 r = complete_pio(vcpu);
3289                 if (r)
3290                         goto out;
3291         }
3292 #if CONFIG_HAS_IOMEM
3293         if (vcpu->mmio_needed) {
3294                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
3295                 vcpu->mmio_read_completed = 1;
3296                 vcpu->mmio_needed = 0;
3297
3298                 down_read(&vcpu->kvm->slots_lock);
3299                 r = emulate_instruction(vcpu, kvm_run,
3300                                         vcpu->arch.mmio_fault_cr2, 0,
3301                                         EMULTYPE_NO_DECODE);
3302                 up_read(&vcpu->kvm->slots_lock);
3303                 if (r == EMULATE_DO_MMIO) {
3304                         /*
3305                          * Read-modify-write.  Back to userspace.
3306                          */
3307                         r = 0;
3308                         goto out;
3309                 }
3310         }
3311 #endif
3312         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
3313                 kvm_register_write(vcpu, VCPU_REGS_RAX,
3314                                      kvm_run->hypercall.ret);
3315
3316         r = __vcpu_run(vcpu, kvm_run);
3317
3318 out:
3319         if (vcpu->sigset_active)
3320                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
3321
3322         vcpu_put(vcpu);
3323         return r;
3324 }
3325
3326 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3327 {
3328         vcpu_load(vcpu);
3329
3330         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3331         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3332         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3333         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3334         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
3335         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
3336         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3337         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3338 #ifdef CONFIG_X86_64
3339         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
3340         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
3341         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
3342         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
3343         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
3344         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
3345         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
3346         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
3347 #endif
3348
3349         regs->rip = kvm_rip_read(vcpu);
3350         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
3351
3352         /*
3353          * Don't leak debug flags in case they were set for guest debugging
3354          */
3355         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
3356                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
3357
3358         vcpu_put(vcpu);
3359
3360         return 0;
3361 }
3362
3363 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3364 {
3365         vcpu_load(vcpu);
3366
3367         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
3368         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
3369         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
3370         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
3371         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
3372         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
3373         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
3374         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
3375 #ifdef CONFIG_X86_64
3376         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
3377         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
3378         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
3379         kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
3380         kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
3381         kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
3382         kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
3383         kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
3384
3385 #endif
3386
3387         kvm_rip_write(vcpu, regs->rip);
3388         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
3389
3390
3391         vcpu->arch.exception.pending = false;
3392
3393         vcpu_put(vcpu);
3394
3395         return 0;
3396 }
3397
3398 void kvm_get_segment(struct kvm_vcpu *vcpu,
3399                      struct kvm_segment *var, int seg)
3400 {
3401         kvm_x86_ops->get_segment(vcpu, var, seg);
3402 }
3403
3404 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3405 {
3406         struct kvm_segment cs;
3407
3408         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
3409         *db = cs.db;
3410         *l = cs.l;
3411 }
3412 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
3413
3414 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
3415                                   struct kvm_sregs *sregs)
3416 {
3417         struct descriptor_table dt;
3418         int pending_vec;
3419
3420         vcpu_load(vcpu);
3421
3422         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3423         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3424         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3425         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3426         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3427         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3428
3429         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3430         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3431
3432         kvm_x86_ops->get_idt(vcpu, &dt);
3433         sregs->idt.limit = dt.limit;
3434         sregs->idt.base = dt.base;
3435         kvm_x86_ops->get_gdt(vcpu, &dt);
3436         sregs->gdt.limit = dt.limit;
3437         sregs->gdt.base = dt.base;
3438
3439         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3440         sregs->cr0 = vcpu->arch.cr0;
3441         sregs->cr2 = vcpu->arch.cr2;
3442         sregs->cr3 = vcpu->arch.cr3;
3443         sregs->cr4 = vcpu->arch.cr4;
3444         sregs->cr8 = kvm_get_cr8(vcpu);
3445         sregs->efer = vcpu->arch.shadow_efer;
3446         sregs->apic_base = kvm_get_apic_base(vcpu);
3447
3448         if (irqchip_in_kernel(vcpu->kvm)) {
3449                 memset(sregs->interrupt_bitmap, 0,
3450                        sizeof sregs->interrupt_bitmap);
3451                 pending_vec = kvm_x86_ops->get_irq(vcpu);
3452                 if (pending_vec >= 0)
3453                         set_bit(pending_vec,
3454                                 (unsigned long *)sregs->interrupt_bitmap);
3455         } else
3456                 memcpy(sregs->interrupt_bitmap, vcpu->arch.irq_pending,
3457                        sizeof sregs->interrupt_bitmap);
3458
3459         vcpu_put(vcpu);
3460
3461         return 0;
3462 }
3463
3464 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
3465                                     struct kvm_mp_state *mp_state)
3466 {
3467         vcpu_load(vcpu);
3468         mp_state->mp_state = vcpu->arch.mp_state;
3469         vcpu_put(vcpu);
3470         return 0;
3471 }
3472
3473 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
3474                                     struct kvm_mp_state *mp_state)
3475 {
3476         vcpu_load(vcpu);
3477         vcpu->arch.mp_state = mp_state->mp_state;
3478         vcpu_put(vcpu);
3479         return 0;
3480 }
3481
3482 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3483                         struct kvm_segment *var, int seg)
3484 {
3485         kvm_x86_ops->set_segment(vcpu, var, seg);
3486 }
3487
3488 static void seg_desct_to_kvm_desct(struct desc_struct *seg_desc, u16 selector,
3489                                    struct kvm_segment *kvm_desct)
3490 {
3491         kvm_desct->base = seg_desc->base0;
3492         kvm_desct->base |= seg_desc->base1 << 16;
3493         kvm_desct->base |= seg_desc->base2 << 24;
3494         kvm_desct->limit = seg_desc->limit0;
3495         kvm_desct->limit |= seg_desc->limit << 16;
3496         if (seg_desc->g) {
3497                 kvm_desct->limit <<= 12;
3498                 kvm_desct->limit |= 0xfff;
3499         }
3500         kvm_desct->selector = selector;
3501         kvm_desct->type = seg_desc->type;
3502         kvm_desct->present = seg_desc->p;
3503         kvm_desct->dpl = seg_desc->dpl;
3504         kvm_desct->db = seg_desc->d;
3505         kvm_desct->s = seg_desc->s;
3506         kvm_desct->l = seg_desc->l;
3507         kvm_desct->g = seg_desc->g;
3508         kvm_desct->avl = seg_desc->avl;
3509         if (!selector)
3510                 kvm_desct->unusable = 1;
3511         else
3512                 kvm_desct->unusable = 0;
3513         kvm_desct->padding = 0;
3514 }
3515
3516 static void get_segment_descritptor_dtable(struct kvm_vcpu *vcpu,
3517                                            u16 selector,
3518                                            struct descriptor_table *dtable)
3519 {
3520         if (selector & 1 << 2) {
3521                 struct kvm_segment kvm_seg;
3522
3523                 kvm_get_segment(vcpu, &kvm_seg, VCPU_SREG_LDTR);
3524
3525                 if (kvm_seg.unusable)
3526                         dtable->limit = 0;
3527                 else
3528                         dtable->limit = kvm_seg.limit;
3529                 dtable->base = kvm_seg.base;
3530         }
3531         else
3532                 kvm_x86_ops->get_gdt(vcpu, dtable);
3533 }
3534
3535 /* allowed just for 8 bytes segments */
3536 static int load_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3537                                          struct desc_struct *seg_desc)
3538 {
3539         gpa_t gpa;
3540         struct descriptor_table dtable;
3541         u16 index = selector >> 3;
3542
3543         get_segment_descritptor_dtable(vcpu, selector, &dtable);
3544
3545         if (dtable.limit < index * 8 + 7) {
3546                 kvm_queue_exception_e(vcpu, GP_VECTOR, selector & 0xfffc);
3547                 return 1;
3548         }
3549         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, dtable.base);
3550         gpa += index * 8;
3551         return kvm_read_guest(vcpu->kvm, gpa, seg_desc, 8);
3552 }
3553
3554 /* allowed just for 8 bytes segments */
3555 static int save_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3556                                          struct desc_struct *seg_desc)
3557 {
3558         gpa_t gpa;
3559         struct descriptor_table dtable;
3560         u16 index = selector >> 3;
3561
3562         get_segment_descritptor_dtable(vcpu, selector, &dtable);
3563
3564         if (dtable.limit < index * 8 + 7)
3565                 return 1;
3566         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, dtable.base);
3567         gpa += index * 8;
3568         return kvm_write_guest(vcpu->kvm, gpa, seg_desc, 8);
3569 }
3570
3571 static u32 get_tss_base_addr(struct kvm_vcpu *vcpu,
3572                              struct desc_struct *seg_desc)
3573 {
3574         u32 base_addr;
3575
3576         base_addr = seg_desc->base0;
3577         base_addr |= (seg_desc->base1 << 16);
3578         base_addr |= (seg_desc->base2 << 24);
3579
3580         return vcpu->arch.mmu.gva_to_gpa(vcpu, base_addr);
3581 }
3582
3583 static u16 get_segment_selector(struct kvm_vcpu *vcpu, int seg)
3584 {
3585         struct kvm_segment kvm_seg;
3586
3587         kvm_get_segment(vcpu, &kvm_seg, seg);
3588         return kvm_seg.selector;
3589 }
3590
3591 static int load_segment_descriptor_to_kvm_desct(struct kvm_vcpu *vcpu,
3592                                                 u16 selector,
3593                                                 struct kvm_segment *kvm_seg)
3594 {
3595         struct desc_struct seg_desc;
3596
3597         if (load_guest_segment_descriptor(vcpu, selector, &seg_desc))
3598                 return 1;
3599         seg_desct_to_kvm_desct(&seg_desc, selector, kvm_seg);
3600         return 0;
3601 }
3602
3603 int kvm_load_realmode_segment(struct kvm_vcpu *vcpu, u16 selector, int seg)
3604 {
3605         struct kvm_segment segvar = {
3606                 .base = selector << 4,
3607                 .limit = 0xffff,
3608                 .selector = selector,
3609                 .type = 3,
3610                 .present = 1,
3611                 .dpl = 3,
3612                 .db = 0,
3613                 .s = 1,
3614                 .l = 0,
3615                 .g = 0,
3616                 .avl = 0,
3617                 .unusable = 0,
3618         };
3619         kvm_x86_ops->set_segment(vcpu, &segvar, seg);
3620         return 0;
3621 }
3622
3623 int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3624                                 int type_bits, int seg)
3625 {
3626         struct kvm_segment kvm_seg;
3627
3628         if (!(vcpu->arch.cr0 & X86_CR0_PE))
3629                 return kvm_load_realmode_segment(vcpu, selector, seg);
3630         if (load_segment_descriptor_to_kvm_desct(vcpu, selector, &kvm_seg))
3631                 return 1;
3632         kvm_seg.type |= type_bits;
3633
3634         if (seg != VCPU_SREG_SS && seg != VCPU_SREG_CS &&
3635             seg != VCPU_SREG_LDTR)
3636                 if (!kvm_seg.s)
3637                         kvm_seg.unusable = 1;
3638
3639         kvm_set_segment(vcpu, &kvm_seg, seg);
3640         return 0;
3641 }
3642
3643 static void save_state_to_tss32(struct kvm_vcpu *vcpu,
3644                                 struct tss_segment_32 *tss)
3645 {
3646         tss->cr3 = vcpu->arch.cr3;
3647         tss->eip = kvm_rip_read(vcpu);
3648         tss->eflags = kvm_x86_ops->get_rflags(vcpu);
3649         tss->eax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3650         tss->ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3651         tss->edx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3652         tss->ebx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3653         tss->esp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3654         tss->ebp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3655         tss->esi = kvm_register_read(vcpu, VCPU_REGS_RSI);
3656         tss->edi = kvm_register_read(vcpu, VCPU_REGS_RDI);
3657         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3658         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3659         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3660         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3661         tss->fs = get_segment_selector(vcpu, VCPU_SREG_FS);
3662         tss->gs = get_segment_selector(vcpu, VCPU_SREG_GS);
3663         tss->ldt_selector = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3664         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3665 }
3666
3667 static int load_state_from_tss32(struct kvm_vcpu *vcpu,
3668                                   struct tss_segment_32 *tss)
3669 {
3670         kvm_set_cr3(vcpu, tss->cr3);
3671
3672         kvm_rip_write(vcpu, tss->eip);
3673         kvm_x86_ops->set_rflags(vcpu, tss->eflags | 2);
3674
3675         kvm_register_write(vcpu, VCPU_REGS_RAX, tss->eax);
3676         kvm_register_write(vcpu, VCPU_REGS_RCX, tss->ecx);
3677         kvm_register_write(vcpu, VCPU_REGS_RDX, tss->edx);
3678         kvm_register_write(vcpu, VCPU_REGS_RBX, tss->ebx);
3679         kvm_register_write(vcpu, VCPU_REGS_RSP, tss->esp);
3680         kvm_register_write(vcpu, VCPU_REGS_RBP, tss->ebp);
3681         kvm_register_write(vcpu, VCPU_REGS_RSI, tss->esi);
3682         kvm_register_write(vcpu, VCPU_REGS_RDI, tss->edi);
3683
3684         if (kvm_load_segment_descriptor(vcpu, tss->ldt_selector, 0, VCPU_SREG_LDTR))
3685                 return 1;
3686
3687         if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3688                 return 1;
3689
3690         if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3691                 return 1;
3692
3693         if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3694                 return 1;
3695
3696         if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3697                 return 1;
3698
3699         if (kvm_load_segment_descriptor(vcpu, tss->fs, 1, VCPU_SREG_FS))
3700                 return 1;
3701
3702         if (kvm_load_segment_descriptor(vcpu, tss->gs, 1, VCPU_SREG_GS))
3703                 return 1;
3704         return 0;
3705 }
3706
3707 static void save_state_to_tss16(struct kvm_vcpu *vcpu,
3708                                 struct tss_segment_16 *tss)
3709 {
3710         tss->ip = kvm_rip_read(vcpu);
3711         tss->flag = kvm_x86_ops->get_rflags(vcpu);
3712         tss->ax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3713         tss->cx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3714         tss->dx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3715         tss->bx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3716         tss->sp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3717         tss->bp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3718         tss->si = kvm_register_read(vcpu, VCPU_REGS_RSI);
3719         tss->di = kvm_register_read(vcpu, VCPU_REGS_RDI);
3720
3721         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3722         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3723         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3724         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3725         tss->ldt = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3726         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3727 }
3728
3729 static int load_state_from_tss16(struct kvm_vcpu *vcpu,
3730                                  struct tss_segment_16 *tss)
3731 {
3732         kvm_rip_write(vcpu, tss->ip);
3733         kvm_x86_ops->set_rflags(vcpu, tss->flag | 2);
3734         kvm_register_write(vcpu, VCPU_REGS_RAX, tss->ax);
3735         kvm_register_write(vcpu, VCPU_REGS_RCX, tss->cx);
3736         kvm_register_write(vcpu, VCPU_REGS_RDX, tss->dx);
3737         kvm_register_write(vcpu, VCPU_REGS_RBX, tss->bx);
3738         kvm_register_write(vcpu, VCPU_REGS_RSP, tss->sp);
3739         kvm_register_write(vcpu, VCPU_REGS_RBP, tss->bp);
3740         kvm_register_write(vcpu, VCPU_REGS_RSI, tss->si);
3741         kvm_register_write(vcpu, VCPU_REGS_RDI, tss->di);
3742
3743         if (kvm_load_segment_descriptor(vcpu, tss->ldt, 0, VCPU_SREG_LDTR))
3744                 return 1;
3745
3746         if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3747                 return 1;
3748
3749         if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3750                 return 1;
3751
3752         if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3753                 return 1;
3754
3755         if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3756                 return 1;
3757         return 0;
3758 }
3759
3760 static int kvm_task_switch_16(struct kvm_vcpu *vcpu, u16 tss_selector,
3761                        u32 old_tss_base,
3762                        struct desc_struct *nseg_desc)
3763 {
3764         struct tss_segment_16 tss_segment_16;
3765         int ret = 0;
3766
3767         if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
3768                            sizeof tss_segment_16))
3769                 goto out;
3770
3771         save_state_to_tss16(vcpu, &tss_segment_16);
3772
3773         if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
3774                             sizeof tss_segment_16))
3775                 goto out;
3776
3777         if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
3778                            &tss_segment_16, sizeof tss_segment_16))
3779                 goto out;
3780
3781         if (load_state_from_tss16(vcpu, &tss_segment_16))
3782                 goto out;
3783
3784         ret = 1;
3785 out:
3786         return ret;
3787 }
3788
3789 static int kvm_task_switch_32(struct kvm_vcpu *vcpu, u16 tss_selector,
3790                        u32 old_tss_base,
3791                        struct desc_struct *nseg_desc)
3792 {
3793         struct tss_segment_32 tss_segment_32;
3794         int ret = 0;
3795
3796         if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
3797                            sizeof tss_segment_32))
3798                 goto out;
3799
3800         save_state_to_tss32(vcpu, &tss_segment_32);
3801
3802         if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
3803                             sizeof tss_segment_32))
3804                 goto out;
3805
3806         if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
3807                            &tss_segment_32, sizeof tss_segment_32))
3808                 goto out;
3809
3810         if (load_state_from_tss32(vcpu, &tss_segment_32))
3811                 goto out;
3812
3813         ret = 1;
3814 out:
3815         return ret;
3816 }
3817
3818 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason)
3819 {
3820         struct kvm_segment tr_seg;
3821         struct desc_struct cseg_desc;
3822         struct desc_struct nseg_desc;
3823         int ret = 0;
3824         u32 old_tss_base = get_segment_base(vcpu, VCPU_SREG_TR);
3825         u16 old_tss_sel = get_segment_selector(vcpu, VCPU_SREG_TR);
3826
3827         old_tss_base = vcpu->arch.mmu.gva_to_gpa(vcpu, old_tss_base);
3828
3829         /* FIXME: Handle errors. Failure to read either TSS or their
3830          * descriptors should generate a pagefault.
3831          */
3832         if (load_guest_segment_descriptor(vcpu, tss_selector, &nseg_desc))
3833                 goto out;
3834
3835         if (load_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc))
3836                 goto out;
3837
3838         if (reason != TASK_SWITCH_IRET) {
3839                 int cpl;
3840
3841                 cpl = kvm_x86_ops->get_cpl(vcpu);
3842                 if ((tss_selector & 3) > nseg_desc.dpl || cpl > nseg_desc.dpl) {
3843                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
3844                         return 1;
3845                 }
3846         }
3847
3848         if (!nseg_desc.p || (nseg_desc.limit0 | nseg_desc.limit << 16) < 0x67) {
3849                 kvm_queue_exception_e(vcpu, TS_VECTOR, tss_selector & 0xfffc);
3850                 return 1;
3851         }
3852
3853         if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
3854                 cseg_desc.type &= ~(1 << 1); //clear the B flag
3855                 save_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc);
3856         }
3857
3858         if (reason == TASK_SWITCH_IRET) {
3859                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3860                 kvm_x86_ops->set_rflags(vcpu, eflags & ~X86_EFLAGS_NT);
3861         }
3862
3863         kvm_x86_ops->skip_emulated_instruction(vcpu);
3864
3865         if (nseg_desc.type & 8)
3866                 ret = kvm_task_switch_32(vcpu, tss_selector, old_tss_base,
3867                                          &nseg_desc);
3868         else
3869                 ret = kvm_task_switch_16(vcpu, tss_selector, old_tss_base,
3870                                          &nseg_desc);
3871
3872         if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) {
3873                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3874                 kvm_x86_ops->set_rflags(vcpu, eflags | X86_EFLAGS_NT);
3875         }
3876
3877         if (reason != TASK_SWITCH_IRET) {
3878                 nseg_desc.type |= (1 << 1);
3879                 save_guest_segment_descriptor(vcpu, tss_selector,
3880                                               &nseg_desc);
3881         }
3882
3883         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 | X86_CR0_TS);
3884         seg_desct_to_kvm_desct(&nseg_desc, tss_selector, &tr_seg);
3885         tr_seg.type = 11;
3886         kvm_set_segment(vcpu, &tr_seg, VCPU_SREG_TR);
3887 out:
3888         return ret;
3889 }
3890 EXPORT_SYMBOL_GPL(kvm_task_switch);
3891
3892 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
3893                                   struct kvm_sregs *sregs)
3894 {
3895         int mmu_reset_needed = 0;
3896         int i, pending_vec, max_bits;
3897         struct descriptor_table dt;
3898
3899         vcpu_load(vcpu);
3900
3901         dt.limit = sregs->idt.limit;
3902         dt.base = sregs->idt.base;
3903         kvm_x86_ops->set_idt(vcpu, &dt);
3904         dt.limit = sregs->gdt.limit;
3905         dt.base = sregs->gdt.base;
3906         kvm_x86_ops->set_gdt(vcpu, &dt);
3907
3908         vcpu->arch.cr2 = sregs->cr2;
3909         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
3910         vcpu->arch.cr3 = sregs->cr3;
3911
3912         kvm_set_cr8(vcpu, sregs->cr8);
3913
3914         mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
3915         kvm_x86_ops->set_efer(vcpu, sregs->efer);
3916         kvm_set_apic_base(vcpu, sregs->apic_base);
3917
3918         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3919
3920         mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
3921         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
3922         vcpu->arch.cr0 = sregs->cr0;
3923
3924         mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
3925         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
3926         if (!is_long_mode(vcpu) && is_pae(vcpu))
3927                 load_pdptrs(vcpu, vcpu->arch.cr3);
3928
3929         if (mmu_reset_needed)
3930                 kvm_mmu_reset_context(vcpu);
3931
3932         if (!irqchip_in_kernel(vcpu->kvm)) {
3933                 memcpy(vcpu->arch.irq_pending, sregs->interrupt_bitmap,
3934                        sizeof vcpu->arch.irq_pending);
3935                 vcpu->arch.irq_summary = 0;
3936                 for (i = 0; i < ARRAY_SIZE(vcpu->arch.irq_pending); ++i)
3937                         if (vcpu->arch.irq_pending[i])
3938                                 __set_bit(i, &vcpu->arch.irq_summary);
3939         } else {
3940                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
3941                 pending_vec = find_first_bit(
3942                         (const unsigned long *)sregs->interrupt_bitmap,
3943                         max_bits);
3944                 /* Only pending external irq is handled here */
3945                 if (pending_vec < max_bits) {
3946                         kvm_x86_ops->set_irq(vcpu, pending_vec);
3947                         pr_debug("Set back pending irq %d\n",
3948                                  pending_vec);
3949                 }
3950         }
3951
3952         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3953         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3954         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3955         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3956         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3957         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3958
3959         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3960         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3961
3962         vcpu_put(vcpu);
3963
3964         return 0;
3965 }
3966
3967 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
3968                                     struct kvm_debug_guest *dbg)
3969 {
3970         int r;
3971
3972         vcpu_load(vcpu);
3973
3974         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
3975
3976         vcpu_put(vcpu);
3977
3978         return r;
3979 }
3980
3981 /*
3982  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
3983  * we have asm/x86/processor.h
3984  */
3985 struct fxsave {
3986         u16     cwd;
3987         u16     swd;
3988         u16     twd;
3989         u16     fop;
3990         u64     rip;
3991         u64     rdp;
3992         u32     mxcsr;
3993         u32     mxcsr_mask;
3994         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
3995 #ifdef CONFIG_X86_64
3996         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
3997 #else
3998         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
3999 #endif
4000 };
4001
4002 /*
4003  * Translate a guest virtual address to a guest physical address.
4004  */
4005 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
4006                                     struct kvm_translation *tr)
4007 {
4008         unsigned long vaddr = tr->linear_address;
4009         gpa_t gpa;
4010
4011         vcpu_load(vcpu);
4012         down_read(&vcpu->kvm->slots_lock);
4013         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
4014         up_read(&vcpu->kvm->slots_lock);
4015         tr->physical_address = gpa;
4016         tr->valid = gpa != UNMAPPED_GVA;
4017         tr->writeable = 1;
4018         tr->usermode = 0;
4019         vcpu_put(vcpu);
4020
4021         return 0;
4022 }
4023
4024 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
4025 {
4026         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
4027
4028         vcpu_load(vcpu);
4029
4030         memcpy(fpu->fpr, fxsave->st_space, 128);
4031         fpu->fcw = fxsave->cwd;
4032         fpu->fsw = fxsave->swd;
4033         fpu->ftwx = fxsave->twd;
4034         fpu->last_opcode = fxsave->fop;
4035         fpu->last_ip = fxsave->rip;
4036         fpu->last_dp = fxsave->rdp;
4037         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
4038
4039         vcpu_put(vcpu);
4040
4041         return 0;
4042 }
4043
4044 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
4045 {
4046         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
4047
4048         vcpu_load(vcpu);
4049
4050         memcpy(fxsave->st_space, fpu->fpr, 128);
4051         fxsave->cwd = fpu->fcw;
4052         fxsave->swd = fpu->fsw;
4053         fxsave->twd = fpu->ftwx;
4054         fxsave->fop = fpu->last_opcode;
4055         fxsave->rip = fpu->last_ip;
4056         fxsave->rdp = fpu->last_dp;
4057         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
4058
4059         vcpu_put(vcpu);
4060
4061         return 0;
4062 }
4063
4064 void fx_init(struct kvm_vcpu *vcpu)
4065 {
4066         unsigned after_mxcsr_mask;
4067
4068         /*
4069          * Touch the fpu the first time in non atomic context as if
4070          * this is the first fpu instruction the exception handler
4071          * will fire before the instruction returns and it'll have to
4072          * allocate ram with GFP_KERNEL.
4073          */
4074         if (!used_math())
4075                 kvm_fx_save(&vcpu->arch.host_fx_image);
4076
4077         /* Initialize guest FPU by resetting ours and saving into guest's */
4078         preempt_disable();
4079         kvm_fx_save(&vcpu->arch.host_fx_image);
4080         kvm_fx_finit();
4081         kvm_fx_save(&vcpu->arch.guest_fx_image);
4082         kvm_fx_restore(&vcpu->arch.host_fx_image);
4083         preempt_enable();
4084
4085         vcpu->arch.cr0 |= X86_CR0_ET;
4086         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
4087         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
4088         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
4089                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
4090 }
4091 EXPORT_SYMBOL_GPL(fx_init);
4092
4093 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
4094 {
4095         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
4096                 return;
4097
4098         vcpu->guest_fpu_loaded = 1;
4099         kvm_fx_save(&vcpu->arch.host_fx_image);
4100         kvm_fx_restore(&vcpu->arch.guest_fx_image);
4101 }
4102 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
4103
4104 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
4105 {
4106         if (!vcpu->guest_fpu_loaded)
4107                 return;
4108
4109         vcpu->guest_fpu_loaded = 0;
4110         kvm_fx_save(&vcpu->arch.guest_fx_image);
4111         kvm_fx_restore(&vcpu->arch.host_fx_image);
4112         ++vcpu->stat.fpu_reload;
4113 }
4114 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
4115
4116 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
4117 {
4118         kvm_x86_ops->vcpu_free(vcpu);
4119 }
4120
4121 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
4122                                                 unsigned int id)
4123 {
4124         return kvm_x86_ops->vcpu_create(kvm, id);
4125 }
4126
4127 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
4128 {
4129         int r;
4130
4131         /* We do fxsave: this must be aligned. */
4132         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
4133
4134         vcpu_load(vcpu);
4135         r = kvm_arch_vcpu_reset(vcpu);
4136         if (r == 0)
4137                 r = kvm_mmu_setup(vcpu);
4138         vcpu_put(vcpu);
4139         if (r < 0)
4140                 goto free_vcpu;
4141
4142         return 0;
4143 free_vcpu:
4144         kvm_x86_ops->vcpu_free(vcpu);
4145         return r;
4146 }
4147
4148 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
4149 {
4150         vcpu_load(vcpu);
4151         kvm_mmu_unload(vcpu);
4152         vcpu_put(vcpu);
4153
4154         kvm_x86_ops->vcpu_free(vcpu);
4155 }
4156
4157 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
4158 {
4159         return kvm_x86_ops->vcpu_reset(vcpu);
4160 }
4161
4162 void kvm_arch_hardware_enable(void *garbage)
4163 {
4164         kvm_x86_ops->hardware_enable(garbage);
4165 }
4166
4167 void kvm_arch_hardware_disable(void *garbage)
4168 {
4169         kvm_x86_ops->hardware_disable(garbage);
4170 }
4171
4172 int kvm_arch_hardware_setup(void)
4173 {
4174         return kvm_x86_ops->hardware_setup();
4175 }
4176
4177 void kvm_arch_hardware_unsetup(void)
4178 {
4179         kvm_x86_ops->hardware_unsetup();
4180 }
4181
4182 void kvm_arch_check_processor_compat(void *rtn)
4183 {
4184         kvm_x86_ops->check_processor_compatibility(rtn);
4185 }
4186
4187 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
4188 {
4189         struct page *page;
4190         struct kvm *kvm;
4191         int r;
4192
4193         BUG_ON(vcpu->kvm == NULL);
4194         kvm = vcpu->kvm;
4195
4196         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
4197         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
4198                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4199         else
4200                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
4201
4202         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
4203         if (!page) {
4204                 r = -ENOMEM;
4205                 goto fail;
4206         }
4207         vcpu->arch.pio_data = page_address(page);
4208
4209         r = kvm_mmu_create(vcpu);
4210         if (r < 0)
4211                 goto fail_free_pio_data;
4212
4213         if (irqchip_in_kernel(kvm)) {
4214                 r = kvm_create_lapic(vcpu);
4215                 if (r < 0)
4216                         goto fail_mmu_destroy;
4217         }
4218
4219         return 0;
4220
4221 fail_mmu_destroy:
4222         kvm_mmu_destroy(vcpu);
4223 fail_free_pio_data:
4224         free_page((unsigned long)vcpu->arch.pio_data);
4225 fail:
4226         return r;
4227 }
4228
4229 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
4230 {
4231         kvm_free_lapic(vcpu);
4232         down_read(&vcpu->kvm->slots_lock);
4233         kvm_mmu_destroy(vcpu);
4234         up_read(&vcpu->kvm->slots_lock);
4235         free_page((unsigned long)vcpu->arch.pio_data);
4236 }
4237
4238 struct  kvm *kvm_arch_create_vm(void)
4239 {
4240         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
4241
4242         if (!kvm)
4243                 return ERR_PTR(-ENOMEM);
4244
4245         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
4246         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
4247
4248         return kvm;
4249 }
4250
4251 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
4252 {
4253         vcpu_load(vcpu);
4254         kvm_mmu_unload(vcpu);
4255         vcpu_put(vcpu);
4256 }
4257
4258 static void kvm_free_vcpus(struct kvm *kvm)
4259 {
4260         unsigned int i;
4261
4262         /*
4263          * Unpin any mmu pages first.
4264          */
4265         for (i = 0; i < KVM_MAX_VCPUS; ++i)
4266                 if (kvm->vcpus[i])
4267                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
4268         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
4269                 if (kvm->vcpus[i]) {
4270                         kvm_arch_vcpu_free(kvm->vcpus[i]);
4271                         kvm->vcpus[i] = NULL;
4272                 }
4273         }
4274
4275 }
4276
4277 void kvm_arch_destroy_vm(struct kvm *kvm)
4278 {
4279         kvm_free_assigned_devices(kvm);
4280         kvm_free_pit(kvm);
4281         kfree(kvm->arch.vpic);
4282         kfree(kvm->arch.vioapic);
4283         kvm_free_vcpus(kvm);
4284         kvm_free_physmem(kvm);
4285         if (kvm->arch.apic_access_page)
4286                 put_page(kvm->arch.apic_access_page);
4287         if (kvm->arch.ept_identity_pagetable)
4288                 put_page(kvm->arch.ept_identity_pagetable);
4289         kfree(kvm);
4290 }
4291
4292 int kvm_arch_set_memory_region(struct kvm *kvm,
4293                                 struct kvm_userspace_memory_region *mem,
4294                                 struct kvm_memory_slot old,
4295                                 int user_alloc)
4296 {
4297         int npages = mem->memory_size >> PAGE_SHIFT;
4298         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
4299
4300         /*To keep backward compatibility with older userspace,
4301          *x86 needs to hanlde !user_alloc case.
4302          */
4303         if (!user_alloc) {
4304                 if (npages && !old.rmap) {
4305                         unsigned long userspace_addr;
4306
4307                         down_write(&current->mm->mmap_sem);
4308                         userspace_addr = do_mmap(NULL, 0,
4309                                                  npages * PAGE_SIZE,
4310                                                  PROT_READ | PROT_WRITE,
4311                                                  MAP_PRIVATE | MAP_ANONYMOUS,
4312                                                  0);
4313                         up_write(&current->mm->mmap_sem);
4314
4315                         if (IS_ERR((void *)userspace_addr))
4316                                 return PTR_ERR((void *)userspace_addr);
4317
4318                         /* set userspace_addr atomically for kvm_hva_to_rmapp */
4319                         spin_lock(&kvm->mmu_lock);
4320                         memslot->userspace_addr = userspace_addr;
4321                         spin_unlock(&kvm->mmu_lock);
4322                 } else {
4323                         if (!old.user_alloc && old.rmap) {
4324                                 int ret;
4325
4326                                 down_write(&current->mm->mmap_sem);
4327                                 ret = do_munmap(current->mm, old.userspace_addr,
4328                                                 old.npages * PAGE_SIZE);
4329                                 up_write(&current->mm->mmap_sem);
4330                                 if (ret < 0)
4331                                         printk(KERN_WARNING
4332                                        "kvm_vm_ioctl_set_memory_region: "
4333                                        "failed to munmap memory\n");
4334                         }
4335                 }
4336         }
4337
4338         if (!kvm->arch.n_requested_mmu_pages) {
4339                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
4340                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
4341         }
4342
4343         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
4344         kvm_flush_remote_tlbs(kvm);
4345
4346         return 0;
4347 }
4348
4349 void kvm_arch_flush_shadow(struct kvm *kvm)
4350 {
4351         kvm_mmu_zap_all(kvm);
4352 }
4353
4354 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
4355 {
4356         return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
4357                || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED;
4358 }
4359
4360 static void vcpu_kick_intr(void *info)
4361 {
4362 #ifdef DEBUG
4363         struct kvm_vcpu *vcpu = (struct kvm_vcpu *)info;
4364         printk(KERN_DEBUG "vcpu_kick_intr %p \n", vcpu);
4365 #endif
4366 }
4367
4368 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
4369 {
4370         int ipi_pcpu = vcpu->cpu;
4371         int cpu = get_cpu();
4372
4373         if (waitqueue_active(&vcpu->wq)) {
4374                 wake_up_interruptible(&vcpu->wq);
4375                 ++vcpu->stat.halt_wakeup;
4376         }
4377         /*
4378          * We may be called synchronously with irqs disabled in guest mode,
4379          * So need not to call smp_call_function_single() in that case.
4380          */
4381         if (vcpu->guest_mode && vcpu->cpu != cpu)
4382                 smp_call_function_single(ipi_pcpu, vcpu_kick_intr, vcpu, 0);
4383         put_cpu();
4384 }