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