]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - arch/x86/kvm/x86.c
KVM: pci device assignment
[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
1546         switch (ioctl) {
1547         case KVM_GET_LAPIC: {
1548                 struct kvm_lapic_state lapic;
1549
1550                 memset(&lapic, 0, sizeof lapic);
1551                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
1552                 if (r)
1553                         goto out;
1554                 r = -EFAULT;
1555                 if (copy_to_user(argp, &lapic, sizeof lapic))
1556                         goto out;
1557                 r = 0;
1558                 break;
1559         }
1560         case KVM_SET_LAPIC: {
1561                 struct kvm_lapic_state lapic;
1562
1563                 r = -EFAULT;
1564                 if (copy_from_user(&lapic, argp, sizeof lapic))
1565                         goto out;
1566                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
1567                 if (r)
1568                         goto out;
1569                 r = 0;
1570                 break;
1571         }
1572         case KVM_INTERRUPT: {
1573                 struct kvm_interrupt irq;
1574
1575                 r = -EFAULT;
1576                 if (copy_from_user(&irq, argp, sizeof irq))
1577                         goto out;
1578                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1579                 if (r)
1580                         goto out;
1581                 r = 0;
1582                 break;
1583         }
1584         case KVM_SET_CPUID: {
1585                 struct kvm_cpuid __user *cpuid_arg = argp;
1586                 struct kvm_cpuid cpuid;
1587
1588                 r = -EFAULT;
1589                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1590                         goto out;
1591                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1592                 if (r)
1593                         goto out;
1594                 break;
1595         }
1596         case KVM_SET_CPUID2: {
1597                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1598                 struct kvm_cpuid2 cpuid;
1599
1600                 r = -EFAULT;
1601                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1602                         goto out;
1603                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1604                                 cpuid_arg->entries);
1605                 if (r)
1606                         goto out;
1607                 break;
1608         }
1609         case KVM_GET_CPUID2: {
1610                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1611                 struct kvm_cpuid2 cpuid;
1612
1613                 r = -EFAULT;
1614                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1615                         goto out;
1616                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1617                                 cpuid_arg->entries);
1618                 if (r)
1619                         goto out;
1620                 r = -EFAULT;
1621                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1622                         goto out;
1623                 r = 0;
1624                 break;
1625         }
1626         case KVM_GET_MSRS:
1627                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1628                 break;
1629         case KVM_SET_MSRS:
1630                 r = msr_io(vcpu, argp, do_set_msr, 0);
1631                 break;
1632         case KVM_TPR_ACCESS_REPORTING: {
1633                 struct kvm_tpr_access_ctl tac;
1634
1635                 r = -EFAULT;
1636                 if (copy_from_user(&tac, argp, sizeof tac))
1637                         goto out;
1638                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
1639                 if (r)
1640                         goto out;
1641                 r = -EFAULT;
1642                 if (copy_to_user(argp, &tac, sizeof tac))
1643                         goto out;
1644                 r = 0;
1645                 break;
1646         };
1647         case KVM_SET_VAPIC_ADDR: {
1648                 struct kvm_vapic_addr va;
1649
1650                 r = -EINVAL;
1651                 if (!irqchip_in_kernel(vcpu->kvm))
1652                         goto out;
1653                 r = -EFAULT;
1654                 if (copy_from_user(&va, argp, sizeof va))
1655                         goto out;
1656                 r = 0;
1657                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
1658                 break;
1659         }
1660         default:
1661                 r = -EINVAL;
1662         }
1663 out:
1664         return r;
1665 }
1666
1667 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1668 {
1669         int ret;
1670
1671         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1672                 return -1;
1673         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1674         return ret;
1675 }
1676
1677 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1678                                           u32 kvm_nr_mmu_pages)
1679 {
1680         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1681                 return -EINVAL;
1682
1683         down_write(&kvm->slots_lock);
1684
1685         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1686         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1687
1688         up_write(&kvm->slots_lock);
1689         return 0;
1690 }
1691
1692 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1693 {
1694         return kvm->arch.n_alloc_mmu_pages;
1695 }
1696
1697 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1698 {
1699         int i;
1700         struct kvm_mem_alias *alias;
1701
1702         for (i = 0; i < kvm->arch.naliases; ++i) {
1703                 alias = &kvm->arch.aliases[i];
1704                 if (gfn >= alias->base_gfn
1705                     && gfn < alias->base_gfn + alias->npages)
1706                         return alias->target_gfn + gfn - alias->base_gfn;
1707         }
1708         return gfn;
1709 }
1710
1711 /*
1712  * Set a new alias region.  Aliases map a portion of physical memory into
1713  * another portion.  This is useful for memory windows, for example the PC
1714  * VGA region.
1715  */
1716 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1717                                          struct kvm_memory_alias *alias)
1718 {
1719         int r, n;
1720         struct kvm_mem_alias *p;
1721
1722         r = -EINVAL;
1723         /* General sanity checks */
1724         if (alias->memory_size & (PAGE_SIZE - 1))
1725                 goto out;
1726         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1727                 goto out;
1728         if (alias->slot >= KVM_ALIAS_SLOTS)
1729                 goto out;
1730         if (alias->guest_phys_addr + alias->memory_size
1731             < alias->guest_phys_addr)
1732                 goto out;
1733         if (alias->target_phys_addr + alias->memory_size
1734             < alias->target_phys_addr)
1735                 goto out;
1736
1737         down_write(&kvm->slots_lock);
1738         spin_lock(&kvm->mmu_lock);
1739
1740         p = &kvm->arch.aliases[alias->slot];
1741         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1742         p->npages = alias->memory_size >> PAGE_SHIFT;
1743         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1744
1745         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1746                 if (kvm->arch.aliases[n - 1].npages)
1747                         break;
1748         kvm->arch.naliases = n;
1749
1750         spin_unlock(&kvm->mmu_lock);
1751         kvm_mmu_zap_all(kvm);
1752
1753         up_write(&kvm->slots_lock);
1754
1755         return 0;
1756
1757 out:
1758         return r;
1759 }
1760
1761 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1762 {
1763         int r;
1764
1765         r = 0;
1766         switch (chip->chip_id) {
1767         case KVM_IRQCHIP_PIC_MASTER:
1768                 memcpy(&chip->chip.pic,
1769                         &pic_irqchip(kvm)->pics[0],
1770                         sizeof(struct kvm_pic_state));
1771                 break;
1772         case KVM_IRQCHIP_PIC_SLAVE:
1773                 memcpy(&chip->chip.pic,
1774                         &pic_irqchip(kvm)->pics[1],
1775                         sizeof(struct kvm_pic_state));
1776                 break;
1777         case KVM_IRQCHIP_IOAPIC:
1778                 memcpy(&chip->chip.ioapic,
1779                         ioapic_irqchip(kvm),
1780                         sizeof(struct kvm_ioapic_state));
1781                 break;
1782         default:
1783                 r = -EINVAL;
1784                 break;
1785         }
1786         return r;
1787 }
1788
1789 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1790 {
1791         int r;
1792
1793         r = 0;
1794         switch (chip->chip_id) {
1795         case KVM_IRQCHIP_PIC_MASTER:
1796                 memcpy(&pic_irqchip(kvm)->pics[0],
1797                         &chip->chip.pic,
1798                         sizeof(struct kvm_pic_state));
1799                 break;
1800         case KVM_IRQCHIP_PIC_SLAVE:
1801                 memcpy(&pic_irqchip(kvm)->pics[1],
1802                         &chip->chip.pic,
1803                         sizeof(struct kvm_pic_state));
1804                 break;
1805         case KVM_IRQCHIP_IOAPIC:
1806                 memcpy(ioapic_irqchip(kvm),
1807                         &chip->chip.ioapic,
1808                         sizeof(struct kvm_ioapic_state));
1809                 break;
1810         default:
1811                 r = -EINVAL;
1812                 break;
1813         }
1814         kvm_pic_update_irq(pic_irqchip(kvm));
1815         return r;
1816 }
1817
1818 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1819 {
1820         int r = 0;
1821
1822         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
1823         return r;
1824 }
1825
1826 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1827 {
1828         int r = 0;
1829
1830         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
1831         kvm_pit_load_count(kvm, 0, ps->channels[0].count);
1832         return r;
1833 }
1834
1835 /*
1836  * Get (and clear) the dirty memory log for a memory slot.
1837  */
1838 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1839                                       struct kvm_dirty_log *log)
1840 {
1841         int r;
1842         int n;
1843         struct kvm_memory_slot *memslot;
1844         int is_dirty = 0;
1845
1846         down_write(&kvm->slots_lock);
1847
1848         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1849         if (r)
1850                 goto out;
1851
1852         /* If nothing is dirty, don't bother messing with page tables. */
1853         if (is_dirty) {
1854                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1855                 kvm_flush_remote_tlbs(kvm);
1856                 memslot = &kvm->memslots[log->slot];
1857                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1858                 memset(memslot->dirty_bitmap, 0, n);
1859         }
1860         r = 0;
1861 out:
1862         up_write(&kvm->slots_lock);
1863         return r;
1864 }
1865
1866 long kvm_arch_vm_ioctl(struct file *filp,
1867                        unsigned int ioctl, unsigned long arg)
1868 {
1869         struct kvm *kvm = filp->private_data;
1870         void __user *argp = (void __user *)arg;
1871         int r = -EINVAL;
1872
1873         switch (ioctl) {
1874         case KVM_SET_TSS_ADDR:
1875                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1876                 if (r < 0)
1877                         goto out;
1878                 break;
1879         case KVM_SET_MEMORY_REGION: {
1880                 struct kvm_memory_region kvm_mem;
1881                 struct kvm_userspace_memory_region kvm_userspace_mem;
1882
1883                 r = -EFAULT;
1884                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1885                         goto out;
1886                 kvm_userspace_mem.slot = kvm_mem.slot;
1887                 kvm_userspace_mem.flags = kvm_mem.flags;
1888                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1889                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1890                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1891                 if (r)
1892                         goto out;
1893                 break;
1894         }
1895         case KVM_SET_NR_MMU_PAGES:
1896                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1897                 if (r)
1898                         goto out;
1899                 break;
1900         case KVM_GET_NR_MMU_PAGES:
1901                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1902                 break;
1903         case KVM_SET_MEMORY_ALIAS: {
1904                 struct kvm_memory_alias alias;
1905
1906                 r = -EFAULT;
1907                 if (copy_from_user(&alias, argp, sizeof alias))
1908                         goto out;
1909                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
1910                 if (r)
1911                         goto out;
1912                 break;
1913         }
1914         case KVM_CREATE_IRQCHIP:
1915                 r = -ENOMEM;
1916                 kvm->arch.vpic = kvm_create_pic(kvm);
1917                 if (kvm->arch.vpic) {
1918                         r = kvm_ioapic_init(kvm);
1919                         if (r) {
1920                                 kfree(kvm->arch.vpic);
1921                                 kvm->arch.vpic = NULL;
1922                                 goto out;
1923                         }
1924                 } else
1925                         goto out;
1926                 break;
1927         case KVM_CREATE_PIT:
1928                 r = -ENOMEM;
1929                 kvm->arch.vpit = kvm_create_pit(kvm);
1930                 if (kvm->arch.vpit)
1931                         r = 0;
1932                 break;
1933         case KVM_IRQ_LINE: {
1934                 struct kvm_irq_level irq_event;
1935
1936                 r = -EFAULT;
1937                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1938                         goto out;
1939                 if (irqchip_in_kernel(kvm)) {
1940                         mutex_lock(&kvm->lock);
1941                         if (irq_event.irq < 16)
1942                                 kvm_pic_set_irq(pic_irqchip(kvm),
1943                                         irq_event.irq,
1944                                         irq_event.level);
1945                         kvm_ioapic_set_irq(kvm->arch.vioapic,
1946                                         irq_event.irq,
1947                                         irq_event.level);
1948                         mutex_unlock(&kvm->lock);
1949                         r = 0;
1950                 }
1951                 break;
1952         }
1953         case KVM_GET_IRQCHIP: {
1954                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1955                 struct kvm_irqchip chip;
1956
1957                 r = -EFAULT;
1958                 if (copy_from_user(&chip, argp, sizeof chip))
1959                         goto out;
1960                 r = -ENXIO;
1961                 if (!irqchip_in_kernel(kvm))
1962                         goto out;
1963                 r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
1964                 if (r)
1965                         goto out;
1966                 r = -EFAULT;
1967                 if (copy_to_user(argp, &chip, sizeof chip))
1968                         goto out;
1969                 r = 0;
1970                 break;
1971         }
1972         case KVM_SET_IRQCHIP: {
1973                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1974                 struct kvm_irqchip chip;
1975
1976                 r = -EFAULT;
1977                 if (copy_from_user(&chip, argp, sizeof chip))
1978                         goto out;
1979                 r = -ENXIO;
1980                 if (!irqchip_in_kernel(kvm))
1981                         goto out;
1982                 r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
1983                 if (r)
1984                         goto out;
1985                 r = 0;
1986                 break;
1987         }
1988         case KVM_ASSIGN_PCI_DEVICE: {
1989                 struct kvm_assigned_pci_dev assigned_dev;
1990
1991                 r = -EFAULT;
1992                 if (copy_from_user(&assigned_dev, argp, sizeof assigned_dev))
1993                         goto out;
1994                 r = kvm_vm_ioctl_assign_device(kvm, &assigned_dev);
1995                 if (r)
1996                         goto out;
1997                 break;
1998         }
1999         case KVM_ASSIGN_IRQ: {
2000                 struct kvm_assigned_irq assigned_irq;
2001
2002                 r = -EFAULT;
2003                 if (copy_from_user(&assigned_irq, argp, sizeof assigned_irq))
2004                         goto out;
2005                 r = kvm_vm_ioctl_assign_irq(kvm, &assigned_irq);
2006                 if (r)
2007                         goto out;
2008                 break;
2009         }
2010         case KVM_GET_PIT: {
2011                 struct kvm_pit_state ps;
2012                 r = -EFAULT;
2013                 if (copy_from_user(&ps, argp, sizeof ps))
2014                         goto out;
2015                 r = -ENXIO;
2016                 if (!kvm->arch.vpit)
2017                         goto out;
2018                 r = kvm_vm_ioctl_get_pit(kvm, &ps);
2019                 if (r)
2020                         goto out;
2021                 r = -EFAULT;
2022                 if (copy_to_user(argp, &ps, sizeof ps))
2023                         goto out;
2024                 r = 0;
2025                 break;
2026         }
2027         case KVM_SET_PIT: {
2028                 struct kvm_pit_state ps;
2029                 r = -EFAULT;
2030                 if (copy_from_user(&ps, argp, sizeof ps))
2031                         goto out;
2032                 r = -ENXIO;
2033                 if (!kvm->arch.vpit)
2034                         goto out;
2035                 r = kvm_vm_ioctl_set_pit(kvm, &ps);
2036                 if (r)
2037                         goto out;
2038                 r = 0;
2039                 break;
2040         }
2041         default:
2042                 ;
2043         }
2044 out:
2045         return r;
2046 }
2047
2048 static void kvm_init_msr_list(void)
2049 {
2050         u32 dummy[2];
2051         unsigned i, j;
2052
2053         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
2054                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
2055                         continue;
2056                 if (j < i)
2057                         msrs_to_save[j] = msrs_to_save[i];
2058                 j++;
2059         }
2060         num_msrs_to_save = j;
2061 }
2062
2063 /*
2064  * Only apic need an MMIO device hook, so shortcut now..
2065  */
2066 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
2067                                                 gpa_t addr, int len,
2068                                                 int is_write)
2069 {
2070         struct kvm_io_device *dev;
2071
2072         if (vcpu->arch.apic) {
2073                 dev = &vcpu->arch.apic->dev;
2074                 if (dev->in_range(dev, addr, len, is_write))
2075                         return dev;
2076         }
2077         return NULL;
2078 }
2079
2080
2081 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
2082                                                 gpa_t addr, int len,
2083                                                 int is_write)
2084 {
2085         struct kvm_io_device *dev;
2086
2087         dev = vcpu_find_pervcpu_dev(vcpu, addr, len, is_write);
2088         if (dev == NULL)
2089                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr, len,
2090                                           is_write);
2091         return dev;
2092 }
2093
2094 int emulator_read_std(unsigned long addr,
2095                              void *val,
2096                              unsigned int bytes,
2097                              struct kvm_vcpu *vcpu)
2098 {
2099         void *data = val;
2100         int r = X86EMUL_CONTINUE;
2101
2102         while (bytes) {
2103                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2104                 unsigned offset = addr & (PAGE_SIZE-1);
2105                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
2106                 int ret;
2107
2108                 if (gpa == UNMAPPED_GVA) {
2109                         r = X86EMUL_PROPAGATE_FAULT;
2110                         goto out;
2111                 }
2112                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
2113                 if (ret < 0) {
2114                         r = X86EMUL_UNHANDLEABLE;
2115                         goto out;
2116                 }
2117
2118                 bytes -= tocopy;
2119                 data += tocopy;
2120                 addr += tocopy;
2121         }
2122 out:
2123         return r;
2124 }
2125 EXPORT_SYMBOL_GPL(emulator_read_std);
2126
2127 static int emulator_read_emulated(unsigned long addr,
2128                                   void *val,
2129                                   unsigned int bytes,
2130                                   struct kvm_vcpu *vcpu)
2131 {
2132         struct kvm_io_device *mmio_dev;
2133         gpa_t                 gpa;
2134
2135         if (vcpu->mmio_read_completed) {
2136                 memcpy(val, vcpu->mmio_data, bytes);
2137                 vcpu->mmio_read_completed = 0;
2138                 return X86EMUL_CONTINUE;
2139         }
2140
2141         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2142
2143         /* For APIC access vmexit */
2144         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2145                 goto mmio;
2146
2147         if (emulator_read_std(addr, val, bytes, vcpu)
2148                         == X86EMUL_CONTINUE)
2149                 return X86EMUL_CONTINUE;
2150         if (gpa == UNMAPPED_GVA)
2151                 return X86EMUL_PROPAGATE_FAULT;
2152
2153 mmio:
2154         /*
2155          * Is this MMIO handled locally?
2156          */
2157         mutex_lock(&vcpu->kvm->lock);
2158         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa, bytes, 0);
2159         if (mmio_dev) {
2160                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
2161                 mutex_unlock(&vcpu->kvm->lock);
2162                 return X86EMUL_CONTINUE;
2163         }
2164         mutex_unlock(&vcpu->kvm->lock);
2165
2166         vcpu->mmio_needed = 1;
2167         vcpu->mmio_phys_addr = gpa;
2168         vcpu->mmio_size = bytes;
2169         vcpu->mmio_is_write = 0;
2170
2171         return X86EMUL_UNHANDLEABLE;
2172 }
2173
2174 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
2175                           const void *val, int bytes)
2176 {
2177         int ret;
2178
2179         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
2180         if (ret < 0)
2181                 return 0;
2182         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
2183         return 1;
2184 }
2185
2186 static int emulator_write_emulated_onepage(unsigned long addr,
2187                                            const void *val,
2188                                            unsigned int bytes,
2189                                            struct kvm_vcpu *vcpu)
2190 {
2191         struct kvm_io_device *mmio_dev;
2192         gpa_t                 gpa;
2193
2194         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2195
2196         if (gpa == UNMAPPED_GVA) {
2197                 kvm_inject_page_fault(vcpu, addr, 2);
2198                 return X86EMUL_PROPAGATE_FAULT;
2199         }
2200
2201         /* For APIC access vmexit */
2202         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2203                 goto mmio;
2204
2205         if (emulator_write_phys(vcpu, gpa, val, bytes))
2206                 return X86EMUL_CONTINUE;
2207
2208 mmio:
2209         /*
2210          * Is this MMIO handled locally?
2211          */
2212         mutex_lock(&vcpu->kvm->lock);
2213         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa, bytes, 1);
2214         if (mmio_dev) {
2215                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
2216                 mutex_unlock(&vcpu->kvm->lock);
2217                 return X86EMUL_CONTINUE;
2218         }
2219         mutex_unlock(&vcpu->kvm->lock);
2220
2221         vcpu->mmio_needed = 1;
2222         vcpu->mmio_phys_addr = gpa;
2223         vcpu->mmio_size = bytes;
2224         vcpu->mmio_is_write = 1;
2225         memcpy(vcpu->mmio_data, val, bytes);
2226
2227         return X86EMUL_CONTINUE;
2228 }
2229
2230 int emulator_write_emulated(unsigned long addr,
2231                                    const void *val,
2232                                    unsigned int bytes,
2233                                    struct kvm_vcpu *vcpu)
2234 {
2235         /* Crossing a page boundary? */
2236         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
2237                 int rc, now;
2238
2239                 now = -addr & ~PAGE_MASK;
2240                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
2241                 if (rc != X86EMUL_CONTINUE)
2242                         return rc;
2243                 addr += now;
2244                 val += now;
2245                 bytes -= now;
2246         }
2247         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
2248 }
2249 EXPORT_SYMBOL_GPL(emulator_write_emulated);
2250
2251 static int emulator_cmpxchg_emulated(unsigned long addr,
2252                                      const void *old,
2253                                      const void *new,
2254                                      unsigned int bytes,
2255                                      struct kvm_vcpu *vcpu)
2256 {
2257         static int reported;
2258
2259         if (!reported) {
2260                 reported = 1;
2261                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
2262         }
2263 #ifndef CONFIG_X86_64
2264         /* guests cmpxchg8b have to be emulated atomically */
2265         if (bytes == 8) {
2266                 gpa_t gpa;
2267                 struct page *page;
2268                 char *kaddr;
2269                 u64 val;
2270
2271                 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2272
2273                 if (gpa == UNMAPPED_GVA ||
2274                    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2275                         goto emul_write;
2276
2277                 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
2278                         goto emul_write;
2279
2280                 val = *(u64 *)new;
2281
2282                 down_read(&current->mm->mmap_sem);
2283                 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2284                 up_read(&current->mm->mmap_sem);
2285
2286                 kaddr = kmap_atomic(page, KM_USER0);
2287                 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
2288                 kunmap_atomic(kaddr, KM_USER0);
2289                 kvm_release_page_dirty(page);
2290         }
2291 emul_write:
2292 #endif
2293
2294         return emulator_write_emulated(addr, new, bytes, vcpu);
2295 }
2296
2297 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
2298 {
2299         return kvm_x86_ops->get_segment_base(vcpu, seg);
2300 }
2301
2302 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
2303 {
2304         return X86EMUL_CONTINUE;
2305 }
2306
2307 int emulate_clts(struct kvm_vcpu *vcpu)
2308 {
2309         KVMTRACE_0D(CLTS, vcpu, handler);
2310         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
2311         return X86EMUL_CONTINUE;
2312 }
2313
2314 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
2315 {
2316         struct kvm_vcpu *vcpu = ctxt->vcpu;
2317
2318         switch (dr) {
2319         case 0 ... 3:
2320                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
2321                 return X86EMUL_CONTINUE;
2322         default:
2323                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __func__, dr);
2324                 return X86EMUL_UNHANDLEABLE;
2325         }
2326 }
2327
2328 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
2329 {
2330         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
2331         int exception;
2332
2333         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
2334         if (exception) {
2335                 /* FIXME: better handling */
2336                 return X86EMUL_UNHANDLEABLE;
2337         }
2338         return X86EMUL_CONTINUE;
2339 }
2340
2341 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
2342 {
2343         u8 opcodes[4];
2344         unsigned long rip = kvm_rip_read(vcpu);
2345         unsigned long rip_linear;
2346
2347         if (!printk_ratelimit())
2348                 return;
2349
2350         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
2351
2352         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
2353
2354         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
2355                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
2356 }
2357 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
2358
2359 static struct x86_emulate_ops emulate_ops = {
2360         .read_std            = emulator_read_std,
2361         .read_emulated       = emulator_read_emulated,
2362         .write_emulated      = emulator_write_emulated,
2363         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
2364 };
2365
2366 static void cache_all_regs(struct kvm_vcpu *vcpu)
2367 {
2368         kvm_register_read(vcpu, VCPU_REGS_RAX);
2369         kvm_register_read(vcpu, VCPU_REGS_RSP);
2370         kvm_register_read(vcpu, VCPU_REGS_RIP);
2371         vcpu->arch.regs_dirty = ~0;
2372 }
2373
2374 int emulate_instruction(struct kvm_vcpu *vcpu,
2375                         struct kvm_run *run,
2376                         unsigned long cr2,
2377                         u16 error_code,
2378                         int emulation_type)
2379 {
2380         int r;
2381         struct decode_cache *c;
2382
2383         kvm_clear_exception_queue(vcpu);
2384         vcpu->arch.mmio_fault_cr2 = cr2;
2385         /*
2386          * TODO: fix x86_emulate.c to use guest_read/write_register
2387          * instead of direct ->regs accesses, can save hundred cycles
2388          * on Intel for instructions that don't read/change RSP, for
2389          * for example.
2390          */
2391         cache_all_regs(vcpu);
2392
2393         vcpu->mmio_is_write = 0;
2394         vcpu->arch.pio.string = 0;
2395
2396         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
2397                 int cs_db, cs_l;
2398                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
2399
2400                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
2401                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
2402                 vcpu->arch.emulate_ctxt.mode =
2403                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
2404                         ? X86EMUL_MODE_REAL : cs_l
2405                         ? X86EMUL_MODE_PROT64 : cs_db
2406                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
2407
2408                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2409
2410                 /* Reject the instructions other than VMCALL/VMMCALL when
2411                  * try to emulate invalid opcode */
2412                 c = &vcpu->arch.emulate_ctxt.decode;
2413                 if ((emulation_type & EMULTYPE_TRAP_UD) &&
2414                     (!(c->twobyte && c->b == 0x01 &&
2415                       (c->modrm_reg == 0 || c->modrm_reg == 3) &&
2416                        c->modrm_mod == 3 && c->modrm_rm == 1)))
2417                         return EMULATE_FAIL;
2418
2419                 ++vcpu->stat.insn_emulation;
2420                 if (r)  {
2421                         ++vcpu->stat.insn_emulation_fail;
2422                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2423                                 return EMULATE_DONE;
2424                         return EMULATE_FAIL;
2425                 }
2426         }
2427
2428         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2429
2430         if (vcpu->arch.pio.string)
2431                 return EMULATE_DO_MMIO;
2432
2433         if ((r || vcpu->mmio_is_write) && run) {
2434                 run->exit_reason = KVM_EXIT_MMIO;
2435                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
2436                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
2437                 run->mmio.len = vcpu->mmio_size;
2438                 run->mmio.is_write = vcpu->mmio_is_write;
2439         }
2440
2441         if (r) {
2442                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2443                         return EMULATE_DONE;
2444                 if (!vcpu->mmio_needed) {
2445                         kvm_report_emulation_failure(vcpu, "mmio");
2446                         return EMULATE_FAIL;
2447                 }
2448                 return EMULATE_DO_MMIO;
2449         }
2450
2451         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
2452
2453         if (vcpu->mmio_is_write) {
2454                 vcpu->mmio_needed = 0;
2455                 return EMULATE_DO_MMIO;
2456         }
2457
2458         return EMULATE_DONE;
2459 }
2460 EXPORT_SYMBOL_GPL(emulate_instruction);
2461
2462 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
2463 {
2464         int i;
2465
2466         for (i = 0; i < ARRAY_SIZE(vcpu->arch.pio.guest_pages); ++i)
2467                 if (vcpu->arch.pio.guest_pages[i]) {
2468                         kvm_release_page_dirty(vcpu->arch.pio.guest_pages[i]);
2469                         vcpu->arch.pio.guest_pages[i] = NULL;
2470                 }
2471 }
2472
2473 static int pio_copy_data(struct kvm_vcpu *vcpu)
2474 {
2475         void *p = vcpu->arch.pio_data;
2476         void *q;
2477         unsigned bytes;
2478         int nr_pages = vcpu->arch.pio.guest_pages[1] ? 2 : 1;
2479
2480         q = vmap(vcpu->arch.pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
2481                  PAGE_KERNEL);
2482         if (!q) {
2483                 free_pio_guest_pages(vcpu);
2484                 return -ENOMEM;
2485         }
2486         q += vcpu->arch.pio.guest_page_offset;
2487         bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
2488         if (vcpu->arch.pio.in)
2489                 memcpy(q, p, bytes);
2490         else
2491                 memcpy(p, q, bytes);
2492         q -= vcpu->arch.pio.guest_page_offset;
2493         vunmap(q);
2494         free_pio_guest_pages(vcpu);
2495         return 0;
2496 }
2497
2498 int complete_pio(struct kvm_vcpu *vcpu)
2499 {
2500         struct kvm_pio_request *io = &vcpu->arch.pio;
2501         long delta;
2502         int r;
2503         unsigned long val;
2504
2505         if (!io->string) {
2506                 if (io->in) {
2507                         val = kvm_register_read(vcpu, VCPU_REGS_RAX);
2508                         memcpy(&val, vcpu->arch.pio_data, io->size);
2509                         kvm_register_write(vcpu, VCPU_REGS_RAX, val);
2510                 }
2511         } else {
2512                 if (io->in) {
2513                         r = pio_copy_data(vcpu);
2514                         if (r)
2515                                 return r;
2516                 }
2517
2518                 delta = 1;
2519                 if (io->rep) {
2520                         delta *= io->cur_count;
2521                         /*
2522                          * The size of the register should really depend on
2523                          * current address size.
2524                          */
2525                         val = kvm_register_read(vcpu, VCPU_REGS_RCX);
2526                         val -= delta;
2527                         kvm_register_write(vcpu, VCPU_REGS_RCX, val);
2528                 }
2529                 if (io->down)
2530                         delta = -delta;
2531                 delta *= io->size;
2532                 if (io->in) {
2533                         val = kvm_register_read(vcpu, VCPU_REGS_RDI);
2534                         val += delta;
2535                         kvm_register_write(vcpu, VCPU_REGS_RDI, val);
2536                 } else {
2537                         val = kvm_register_read(vcpu, VCPU_REGS_RSI);
2538                         val += delta;
2539                         kvm_register_write(vcpu, VCPU_REGS_RSI, val);
2540                 }
2541         }
2542
2543         io->count -= io->cur_count;
2544         io->cur_count = 0;
2545
2546         return 0;
2547 }
2548
2549 static void kernel_pio(struct kvm_io_device *pio_dev,
2550                        struct kvm_vcpu *vcpu,
2551                        void *pd)
2552 {
2553         /* TODO: String I/O for in kernel device */
2554
2555         mutex_lock(&vcpu->kvm->lock);
2556         if (vcpu->arch.pio.in)
2557                 kvm_iodevice_read(pio_dev, vcpu->arch.pio.port,
2558                                   vcpu->arch.pio.size,
2559                                   pd);
2560         else
2561                 kvm_iodevice_write(pio_dev, vcpu->arch.pio.port,
2562                                    vcpu->arch.pio.size,
2563                                    pd);
2564         mutex_unlock(&vcpu->kvm->lock);
2565 }
2566
2567 static void pio_string_write(struct kvm_io_device *pio_dev,
2568                              struct kvm_vcpu *vcpu)
2569 {
2570         struct kvm_pio_request *io = &vcpu->arch.pio;
2571         void *pd = vcpu->arch.pio_data;
2572         int i;
2573
2574         mutex_lock(&vcpu->kvm->lock);
2575         for (i = 0; i < io->cur_count; i++) {
2576                 kvm_iodevice_write(pio_dev, io->port,
2577                                    io->size,
2578                                    pd);
2579                 pd += io->size;
2580         }
2581         mutex_unlock(&vcpu->kvm->lock);
2582 }
2583
2584 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
2585                                                gpa_t addr, int len,
2586                                                int is_write)
2587 {
2588         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr, len, is_write);
2589 }
2590
2591 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2592                   int size, unsigned port)
2593 {
2594         struct kvm_io_device *pio_dev;
2595         unsigned long val;
2596
2597         vcpu->run->exit_reason = KVM_EXIT_IO;
2598         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2599         vcpu->run->io.size = vcpu->arch.pio.size = size;
2600         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2601         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2602         vcpu->run->io.port = vcpu->arch.pio.port = port;
2603         vcpu->arch.pio.in = in;
2604         vcpu->arch.pio.string = 0;
2605         vcpu->arch.pio.down = 0;
2606         vcpu->arch.pio.guest_page_offset = 0;
2607         vcpu->arch.pio.rep = 0;
2608
2609         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2610                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2611                             handler);
2612         else
2613                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2614                             handler);
2615
2616         val = kvm_register_read(vcpu, VCPU_REGS_RAX);
2617         memcpy(vcpu->arch.pio_data, &val, 4);
2618
2619         kvm_x86_ops->skip_emulated_instruction(vcpu);
2620
2621         pio_dev = vcpu_find_pio_dev(vcpu, port, size, !in);
2622         if (pio_dev) {
2623                 kernel_pio(pio_dev, vcpu, vcpu->arch.pio_data);
2624                 complete_pio(vcpu);
2625                 return 1;
2626         }
2627         return 0;
2628 }
2629 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
2630
2631 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2632                   int size, unsigned long count, int down,
2633                   gva_t address, int rep, unsigned port)
2634 {
2635         unsigned now, in_page;
2636         int i, ret = 0;
2637         int nr_pages = 1;
2638         struct page *page;
2639         struct kvm_io_device *pio_dev;
2640
2641         vcpu->run->exit_reason = KVM_EXIT_IO;
2642         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2643         vcpu->run->io.size = vcpu->arch.pio.size = size;
2644         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2645         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
2646         vcpu->run->io.port = vcpu->arch.pio.port = port;
2647         vcpu->arch.pio.in = in;
2648         vcpu->arch.pio.string = 1;
2649         vcpu->arch.pio.down = down;
2650         vcpu->arch.pio.guest_page_offset = offset_in_page(address);
2651         vcpu->arch.pio.rep = rep;
2652
2653         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2654                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2655                             handler);
2656         else
2657                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2658                             handler);
2659
2660         if (!count) {
2661                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2662                 return 1;
2663         }
2664
2665         if (!down)
2666                 in_page = PAGE_SIZE - offset_in_page(address);
2667         else
2668                 in_page = offset_in_page(address) + size;
2669         now = min(count, (unsigned long)in_page / size);
2670         if (!now) {
2671                 /*
2672                  * String I/O straddles page boundary.  Pin two guest pages
2673                  * so that we satisfy atomicity constraints.  Do just one
2674                  * transaction to avoid complexity.
2675                  */
2676                 nr_pages = 2;
2677                 now = 1;
2678         }
2679         if (down) {
2680                 /*
2681                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
2682                  */
2683                 pr_unimpl(vcpu, "guest string pio down\n");
2684                 kvm_inject_gp(vcpu, 0);
2685                 return 1;
2686         }
2687         vcpu->run->io.count = now;
2688         vcpu->arch.pio.cur_count = now;
2689
2690         if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
2691                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2692
2693         for (i = 0; i < nr_pages; ++i) {
2694                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
2695                 vcpu->arch.pio.guest_pages[i] = page;
2696                 if (!page) {
2697                         kvm_inject_gp(vcpu, 0);
2698                         free_pio_guest_pages(vcpu);
2699                         return 1;
2700                 }
2701         }
2702
2703         pio_dev = vcpu_find_pio_dev(vcpu, port,
2704                                     vcpu->arch.pio.cur_count,
2705                                     !vcpu->arch.pio.in);
2706         if (!vcpu->arch.pio.in) {
2707                 /* string PIO write */
2708                 ret = pio_copy_data(vcpu);
2709                 if (ret >= 0 && pio_dev) {
2710                         pio_string_write(pio_dev, vcpu);
2711                         complete_pio(vcpu);
2712                         if (vcpu->arch.pio.count == 0)
2713                                 ret = 1;
2714                 }
2715         } else if (pio_dev)
2716                 pr_unimpl(vcpu, "no string pio read support yet, "
2717                        "port %x size %d count %ld\n",
2718                         port, size, count);
2719
2720         return ret;
2721 }
2722 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2723
2724 int kvm_arch_init(void *opaque)
2725 {
2726         int r;
2727         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2728
2729         if (kvm_x86_ops) {
2730                 printk(KERN_ERR "kvm: already loaded the other module\n");
2731                 r = -EEXIST;
2732                 goto out;
2733         }
2734
2735         if (!ops->cpu_has_kvm_support()) {
2736                 printk(KERN_ERR "kvm: no hardware support\n");
2737                 r = -EOPNOTSUPP;
2738                 goto out;
2739         }
2740         if (ops->disabled_by_bios()) {
2741                 printk(KERN_ERR "kvm: disabled by bios\n");
2742                 r = -EOPNOTSUPP;
2743                 goto out;
2744         }
2745
2746         r = kvm_mmu_module_init();
2747         if (r)
2748                 goto out;
2749
2750         kvm_init_msr_list();
2751
2752         kvm_x86_ops = ops;
2753         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2754         kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
2755         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
2756                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
2757         return 0;
2758
2759 out:
2760         return r;
2761 }
2762
2763 void kvm_arch_exit(void)
2764 {
2765         kvm_x86_ops = NULL;
2766         kvm_mmu_module_exit();
2767 }
2768
2769 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2770 {
2771         ++vcpu->stat.halt_exits;
2772         KVMTRACE_0D(HLT, vcpu, handler);
2773         if (irqchip_in_kernel(vcpu->kvm)) {
2774                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
2775                 up_read(&vcpu->kvm->slots_lock);
2776                 kvm_vcpu_block(vcpu);
2777                 down_read(&vcpu->kvm->slots_lock);
2778                 if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
2779                         return -EINTR;
2780                 return 1;
2781         } else {
2782                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2783                 return 0;
2784         }
2785 }
2786 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2787
2788 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
2789                            unsigned long a1)
2790 {
2791         if (is_long_mode(vcpu))
2792                 return a0;
2793         else
2794                 return a0 | ((gpa_t)a1 << 32);
2795 }
2796
2797 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2798 {
2799         unsigned long nr, a0, a1, a2, a3, ret;
2800         int r = 1;
2801
2802         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
2803         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
2804         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
2805         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
2806         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
2807
2808         KVMTRACE_1D(VMMCALL, vcpu, (u32)nr, handler);
2809
2810         if (!is_long_mode(vcpu)) {
2811                 nr &= 0xFFFFFFFF;
2812                 a0 &= 0xFFFFFFFF;
2813                 a1 &= 0xFFFFFFFF;
2814                 a2 &= 0xFFFFFFFF;
2815                 a3 &= 0xFFFFFFFF;
2816         }
2817
2818         switch (nr) {
2819         case KVM_HC_VAPIC_POLL_IRQ:
2820                 ret = 0;
2821                 break;
2822         case KVM_HC_MMU_OP:
2823                 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
2824                 break;
2825         default:
2826                 ret = -KVM_ENOSYS;
2827                 break;
2828         }
2829         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
2830         ++vcpu->stat.hypercalls;
2831         return r;
2832 }
2833 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2834
2835 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2836 {
2837         char instruction[3];
2838         int ret = 0;
2839         unsigned long rip = kvm_rip_read(vcpu);
2840
2841
2842         /*
2843          * Blow out the MMU to ensure that no other VCPU has an active mapping
2844          * to ensure that the updated hypercall appears atomically across all
2845          * VCPUs.
2846          */
2847         kvm_mmu_zap_all(vcpu->kvm);
2848
2849         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2850         if (emulator_write_emulated(rip, instruction, 3, vcpu)
2851             != X86EMUL_CONTINUE)
2852                 ret = -EFAULT;
2853
2854         return ret;
2855 }
2856
2857 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2858 {
2859         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2860 }
2861
2862 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2863 {
2864         struct descriptor_table dt = { limit, base };
2865
2866         kvm_x86_ops->set_gdt(vcpu, &dt);
2867 }
2868
2869 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2870 {
2871         struct descriptor_table dt = { limit, base };
2872
2873         kvm_x86_ops->set_idt(vcpu, &dt);
2874 }
2875
2876 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2877                    unsigned long *rflags)
2878 {
2879         kvm_lmsw(vcpu, msw);
2880         *rflags = kvm_x86_ops->get_rflags(vcpu);
2881 }
2882
2883 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2884 {
2885         unsigned long value;
2886
2887         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2888         switch (cr) {
2889         case 0:
2890                 value = vcpu->arch.cr0;
2891                 break;
2892         case 2:
2893                 value = vcpu->arch.cr2;
2894                 break;
2895         case 3:
2896                 value = vcpu->arch.cr3;
2897                 break;
2898         case 4:
2899                 value = vcpu->arch.cr4;
2900                 break;
2901         case 8:
2902                 value = kvm_get_cr8(vcpu);
2903                 break;
2904         default:
2905                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2906                 return 0;
2907         }
2908         KVMTRACE_3D(CR_READ, vcpu, (u32)cr, (u32)value,
2909                     (u32)((u64)value >> 32), handler);
2910
2911         return value;
2912 }
2913
2914 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2915                      unsigned long *rflags)
2916 {
2917         KVMTRACE_3D(CR_WRITE, vcpu, (u32)cr, (u32)val,
2918                     (u32)((u64)val >> 32), handler);
2919
2920         switch (cr) {
2921         case 0:
2922                 kvm_set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2923                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2924                 break;
2925         case 2:
2926                 vcpu->arch.cr2 = val;
2927                 break;
2928         case 3:
2929                 kvm_set_cr3(vcpu, val);
2930                 break;
2931         case 4:
2932                 kvm_set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2933                 break;
2934         case 8:
2935                 kvm_set_cr8(vcpu, val & 0xfUL);
2936                 break;
2937         default:
2938                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2939         }
2940 }
2941
2942 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2943 {
2944         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2945         int j, nent = vcpu->arch.cpuid_nent;
2946
2947         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2948         /* when no next entry is found, the current entry[i] is reselected */
2949         for (j = i + 1; j == i; j = (j + 1) % nent) {
2950                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2951                 if (ej->function == e->function) {
2952                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2953                         return j;
2954                 }
2955         }
2956         return 0; /* silence gcc, even though control never reaches here */
2957 }
2958
2959 /* find an entry with matching function, matching index (if needed), and that
2960  * should be read next (if it's stateful) */
2961 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2962         u32 function, u32 index)
2963 {
2964         if (e->function != function)
2965                 return 0;
2966         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
2967                 return 0;
2968         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
2969                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
2970                 return 0;
2971         return 1;
2972 }
2973
2974 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2975 {
2976         int i;
2977         u32 function, index;
2978         struct kvm_cpuid_entry2 *e, *best;
2979
2980         function = kvm_register_read(vcpu, VCPU_REGS_RAX);
2981         index = kvm_register_read(vcpu, VCPU_REGS_RCX);
2982         kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
2983         kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
2984         kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
2985         kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
2986         best = NULL;
2987         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2988                 e = &vcpu->arch.cpuid_entries[i];
2989                 if (is_matching_cpuid_entry(e, function, index)) {
2990                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
2991                                 move_to_next_stateful_cpuid_entry(vcpu, i);
2992                         best = e;
2993                         break;
2994                 }
2995                 /*
2996                  * Both basic or both extended?
2997                  */
2998                 if (((e->function ^ function) & 0x80000000) == 0)
2999                         if (!best || e->function > best->function)
3000                                 best = e;
3001         }
3002         if (best) {
3003                 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
3004                 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
3005                 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
3006                 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
3007         }
3008         kvm_x86_ops->skip_emulated_instruction(vcpu);
3009         KVMTRACE_5D(CPUID, vcpu, function,
3010                     (u32)kvm_register_read(vcpu, VCPU_REGS_RAX),
3011                     (u32)kvm_register_read(vcpu, VCPU_REGS_RBX),
3012                     (u32)kvm_register_read(vcpu, VCPU_REGS_RCX),
3013                     (u32)kvm_register_read(vcpu, VCPU_REGS_RDX), handler);
3014 }
3015 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
3016
3017 /*
3018  * Check if userspace requested an interrupt window, and that the
3019  * interrupt window is open.
3020  *
3021  * No need to exit to userspace if we already have an interrupt queued.
3022  */
3023 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
3024                                           struct kvm_run *kvm_run)
3025 {
3026         return (!vcpu->arch.irq_summary &&
3027                 kvm_run->request_interrupt_window &&
3028                 vcpu->arch.interrupt_window_open &&
3029                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
3030 }
3031
3032 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
3033                               struct kvm_run *kvm_run)
3034 {
3035         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
3036         kvm_run->cr8 = kvm_get_cr8(vcpu);
3037         kvm_run->apic_base = kvm_get_apic_base(vcpu);
3038         if (irqchip_in_kernel(vcpu->kvm))
3039                 kvm_run->ready_for_interrupt_injection = 1;
3040         else
3041                 kvm_run->ready_for_interrupt_injection =
3042                                         (vcpu->arch.interrupt_window_open &&
3043                                          vcpu->arch.irq_summary == 0);
3044 }
3045
3046 static void vapic_enter(struct kvm_vcpu *vcpu)
3047 {
3048         struct kvm_lapic *apic = vcpu->arch.apic;
3049         struct page *page;
3050
3051         if (!apic || !apic->vapic_addr)
3052                 return;
3053
3054         down_read(&current->mm->mmap_sem);
3055         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
3056         up_read(&current->mm->mmap_sem);
3057
3058         vcpu->arch.apic->vapic_page = page;
3059 }
3060
3061 static void vapic_exit(struct kvm_vcpu *vcpu)
3062 {
3063         struct kvm_lapic *apic = vcpu->arch.apic;
3064
3065         if (!apic || !apic->vapic_addr)
3066                 return;
3067
3068         down_read(&vcpu->kvm->slots_lock);
3069         kvm_release_page_dirty(apic->vapic_page);
3070         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
3071         up_read(&vcpu->kvm->slots_lock);
3072 }
3073
3074 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3075 {
3076         int r;
3077
3078         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
3079                 pr_debug("vcpu %d received sipi with vector # %x\n",
3080                        vcpu->vcpu_id, vcpu->arch.sipi_vector);
3081                 kvm_lapic_reset(vcpu);
3082                 r = kvm_x86_ops->vcpu_reset(vcpu);
3083                 if (r)
3084                         return r;
3085                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3086         }
3087
3088         down_read(&vcpu->kvm->slots_lock);
3089         vapic_enter(vcpu);
3090
3091 preempted:
3092         if (vcpu->guest_debug.enabled)
3093                 kvm_x86_ops->guest_debug_pre(vcpu);
3094
3095 again:
3096         if (vcpu->requests)
3097                 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
3098                         kvm_mmu_unload(vcpu);
3099
3100         r = kvm_mmu_reload(vcpu);
3101         if (unlikely(r))
3102                 goto out;
3103
3104         if (vcpu->requests) {
3105                 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
3106                         __kvm_migrate_timers(vcpu);
3107                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
3108                         kvm_x86_ops->tlb_flush(vcpu);
3109                 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
3110                                        &vcpu->requests)) {
3111                         kvm_run->exit_reason = KVM_EXIT_TPR_ACCESS;
3112                         r = 0;
3113                         goto out;
3114                 }
3115                 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
3116                         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
3117                         r = 0;
3118                         goto out;
3119                 }
3120         }
3121
3122         clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
3123         kvm_inject_pending_timer_irqs(vcpu);
3124
3125         preempt_disable();
3126
3127         kvm_x86_ops->prepare_guest_switch(vcpu);
3128         kvm_load_guest_fpu(vcpu);
3129
3130         local_irq_disable();
3131
3132         if (vcpu->requests || need_resched()) {
3133                 local_irq_enable();
3134                 preempt_enable();
3135                 r = 1;
3136                 goto out;
3137         }
3138
3139         if (signal_pending(current)) {
3140                 local_irq_enable();
3141                 preempt_enable();
3142                 r = -EINTR;
3143                 kvm_run->exit_reason = KVM_EXIT_INTR;
3144                 ++vcpu->stat.signal_exits;
3145                 goto out;
3146         }
3147
3148         vcpu->guest_mode = 1;
3149         /*
3150          * Make sure that guest_mode assignment won't happen after
3151          * testing the pending IRQ vector bitmap.
3152          */
3153         smp_wmb();
3154
3155         if (vcpu->arch.exception.pending)
3156                 __queue_exception(vcpu);
3157         else if (irqchip_in_kernel(vcpu->kvm))
3158                 kvm_x86_ops->inject_pending_irq(vcpu);
3159         else
3160                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
3161
3162         kvm_lapic_sync_to_vapic(vcpu);
3163
3164         up_read(&vcpu->kvm->slots_lock);
3165
3166         kvm_guest_enter();
3167
3168
3169         KVMTRACE_0D(VMENTRY, vcpu, entryexit);
3170         kvm_x86_ops->run(vcpu, kvm_run);
3171
3172         vcpu->guest_mode = 0;
3173         local_irq_enable();
3174
3175         ++vcpu->stat.exits;
3176
3177         /*
3178          * We must have an instruction between local_irq_enable() and
3179          * kvm_guest_exit(), so the timer interrupt isn't delayed by
3180          * the interrupt shadow.  The stat.exits increment will do nicely.
3181          * But we need to prevent reordering, hence this barrier():
3182          */
3183         barrier();
3184
3185         kvm_guest_exit();
3186
3187         preempt_enable();
3188
3189         down_read(&vcpu->kvm->slots_lock);
3190
3191         /*
3192          * Profile KVM exit RIPs:
3193          */
3194         if (unlikely(prof_on == KVM_PROFILING)) {
3195                 unsigned long rip = kvm_rip_read(vcpu);
3196                 profile_hit(KVM_PROFILING, (void *)rip);
3197         }
3198
3199         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
3200                 vcpu->arch.exception.pending = false;
3201
3202         kvm_lapic_sync_from_vapic(vcpu);
3203
3204         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
3205
3206         if (r > 0) {
3207                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
3208                         r = -EINTR;
3209                         kvm_run->exit_reason = KVM_EXIT_INTR;
3210                         ++vcpu->stat.request_irq_exits;
3211                         goto out;
3212                 }
3213                 if (!need_resched())
3214                         goto again;
3215         }
3216
3217 out:
3218         up_read(&vcpu->kvm->slots_lock);
3219         if (r > 0) {
3220                 kvm_resched(vcpu);
3221                 down_read(&vcpu->kvm->slots_lock);
3222                 goto preempted;
3223         }
3224
3225         post_kvm_run_save(vcpu, kvm_run);
3226
3227         vapic_exit(vcpu);
3228
3229         return r;
3230 }
3231
3232 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3233 {
3234         int r;
3235         sigset_t sigsaved;
3236
3237         vcpu_load(vcpu);
3238
3239         if (vcpu->sigset_active)
3240                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
3241
3242         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
3243                 kvm_vcpu_block(vcpu);
3244                 r = -EAGAIN;
3245                 goto out;
3246         }
3247
3248         /* re-sync apic's tpr */
3249         if (!irqchip_in_kernel(vcpu->kvm))
3250                 kvm_set_cr8(vcpu, kvm_run->cr8);
3251
3252         if (vcpu->arch.pio.cur_count) {
3253                 r = complete_pio(vcpu);
3254                 if (r)
3255                         goto out;
3256         }
3257 #if CONFIG_HAS_IOMEM
3258         if (vcpu->mmio_needed) {
3259                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
3260                 vcpu->mmio_read_completed = 1;
3261                 vcpu->mmio_needed = 0;
3262
3263                 down_read(&vcpu->kvm->slots_lock);
3264                 r = emulate_instruction(vcpu, kvm_run,
3265                                         vcpu->arch.mmio_fault_cr2, 0,
3266                                         EMULTYPE_NO_DECODE);
3267                 up_read(&vcpu->kvm->slots_lock);
3268                 if (r == EMULATE_DO_MMIO) {
3269                         /*
3270                          * Read-modify-write.  Back to userspace.
3271                          */
3272                         r = 0;
3273                         goto out;
3274                 }
3275         }
3276 #endif
3277         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
3278                 kvm_register_write(vcpu, VCPU_REGS_RAX,
3279                                      kvm_run->hypercall.ret);
3280
3281         r = __vcpu_run(vcpu, kvm_run);
3282
3283 out:
3284         if (vcpu->sigset_active)
3285                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
3286
3287         vcpu_put(vcpu);
3288         return r;
3289 }
3290
3291 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3292 {
3293         vcpu_load(vcpu);
3294
3295         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3296         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3297         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3298         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3299         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
3300         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
3301         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3302         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3303 #ifdef CONFIG_X86_64
3304         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
3305         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
3306         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
3307         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
3308         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
3309         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
3310         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
3311         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
3312 #endif
3313
3314         regs->rip = kvm_rip_read(vcpu);
3315         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
3316
3317         /*
3318          * Don't leak debug flags in case they were set for guest debugging
3319          */
3320         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
3321                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
3322
3323         vcpu_put(vcpu);
3324
3325         return 0;
3326 }
3327
3328 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3329 {
3330         vcpu_load(vcpu);
3331
3332         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
3333         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
3334         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
3335         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
3336         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
3337         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
3338         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
3339         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
3340 #ifdef CONFIG_X86_64
3341         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
3342         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
3343         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
3344         kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
3345         kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
3346         kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
3347         kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
3348         kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
3349
3350 #endif
3351
3352         kvm_rip_write(vcpu, regs->rip);
3353         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
3354
3355
3356         vcpu->arch.exception.pending = false;
3357
3358         vcpu_put(vcpu);
3359
3360         return 0;
3361 }
3362
3363 void kvm_get_segment(struct kvm_vcpu *vcpu,
3364                      struct kvm_segment *var, int seg)
3365 {
3366         kvm_x86_ops->get_segment(vcpu, var, seg);
3367 }
3368
3369 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3370 {
3371         struct kvm_segment cs;
3372
3373         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
3374         *db = cs.db;
3375         *l = cs.l;
3376 }
3377 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
3378
3379 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
3380                                   struct kvm_sregs *sregs)
3381 {
3382         struct descriptor_table dt;
3383         int pending_vec;
3384
3385         vcpu_load(vcpu);
3386
3387         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3388         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3389         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3390         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3391         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3392         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3393
3394         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3395         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3396
3397         kvm_x86_ops->get_idt(vcpu, &dt);
3398         sregs->idt.limit = dt.limit;
3399         sregs->idt.base = dt.base;
3400         kvm_x86_ops->get_gdt(vcpu, &dt);
3401         sregs->gdt.limit = dt.limit;
3402         sregs->gdt.base = dt.base;
3403
3404         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3405         sregs->cr0 = vcpu->arch.cr0;
3406         sregs->cr2 = vcpu->arch.cr2;
3407         sregs->cr3 = vcpu->arch.cr3;
3408         sregs->cr4 = vcpu->arch.cr4;
3409         sregs->cr8 = kvm_get_cr8(vcpu);
3410         sregs->efer = vcpu->arch.shadow_efer;
3411         sregs->apic_base = kvm_get_apic_base(vcpu);
3412
3413         if (irqchip_in_kernel(vcpu->kvm)) {
3414                 memset(sregs->interrupt_bitmap, 0,
3415                        sizeof sregs->interrupt_bitmap);
3416                 pending_vec = kvm_x86_ops->get_irq(vcpu);
3417                 if (pending_vec >= 0)
3418                         set_bit(pending_vec,
3419                                 (unsigned long *)sregs->interrupt_bitmap);
3420         } else
3421                 memcpy(sregs->interrupt_bitmap, vcpu->arch.irq_pending,
3422                        sizeof sregs->interrupt_bitmap);
3423
3424         vcpu_put(vcpu);
3425
3426         return 0;
3427 }
3428
3429 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
3430                                     struct kvm_mp_state *mp_state)
3431 {
3432         vcpu_load(vcpu);
3433         mp_state->mp_state = vcpu->arch.mp_state;
3434         vcpu_put(vcpu);
3435         return 0;
3436 }
3437
3438 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
3439                                     struct kvm_mp_state *mp_state)
3440 {
3441         vcpu_load(vcpu);
3442         vcpu->arch.mp_state = mp_state->mp_state;
3443         vcpu_put(vcpu);
3444         return 0;
3445 }
3446
3447 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3448                         struct kvm_segment *var, int seg)
3449 {
3450         kvm_x86_ops->set_segment(vcpu, var, seg);
3451 }
3452
3453 static void seg_desct_to_kvm_desct(struct desc_struct *seg_desc, u16 selector,
3454                                    struct kvm_segment *kvm_desct)
3455 {
3456         kvm_desct->base = seg_desc->base0;
3457         kvm_desct->base |= seg_desc->base1 << 16;
3458         kvm_desct->base |= seg_desc->base2 << 24;
3459         kvm_desct->limit = seg_desc->limit0;
3460         kvm_desct->limit |= seg_desc->limit << 16;
3461         if (seg_desc->g) {
3462                 kvm_desct->limit <<= 12;
3463                 kvm_desct->limit |= 0xfff;
3464         }
3465         kvm_desct->selector = selector;
3466         kvm_desct->type = seg_desc->type;
3467         kvm_desct->present = seg_desc->p;
3468         kvm_desct->dpl = seg_desc->dpl;
3469         kvm_desct->db = seg_desc->d;
3470         kvm_desct->s = seg_desc->s;
3471         kvm_desct->l = seg_desc->l;
3472         kvm_desct->g = seg_desc->g;
3473         kvm_desct->avl = seg_desc->avl;
3474         if (!selector)
3475                 kvm_desct->unusable = 1;
3476         else
3477                 kvm_desct->unusable = 0;
3478         kvm_desct->padding = 0;
3479 }
3480
3481 static void get_segment_descritptor_dtable(struct kvm_vcpu *vcpu,
3482                                            u16 selector,
3483                                            struct descriptor_table *dtable)
3484 {
3485         if (selector & 1 << 2) {
3486                 struct kvm_segment kvm_seg;
3487
3488                 kvm_get_segment(vcpu, &kvm_seg, VCPU_SREG_LDTR);
3489
3490                 if (kvm_seg.unusable)
3491                         dtable->limit = 0;
3492                 else
3493                         dtable->limit = kvm_seg.limit;
3494                 dtable->base = kvm_seg.base;
3495         }
3496         else
3497                 kvm_x86_ops->get_gdt(vcpu, dtable);
3498 }
3499
3500 /* allowed just for 8 bytes segments */
3501 static int load_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3502                                          struct desc_struct *seg_desc)
3503 {
3504         gpa_t gpa;
3505         struct descriptor_table dtable;
3506         u16 index = selector >> 3;
3507
3508         get_segment_descritptor_dtable(vcpu, selector, &dtable);
3509
3510         if (dtable.limit < index * 8 + 7) {
3511                 kvm_queue_exception_e(vcpu, GP_VECTOR, selector & 0xfffc);
3512                 return 1;
3513         }
3514         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, dtable.base);
3515         gpa += index * 8;
3516         return kvm_read_guest(vcpu->kvm, gpa, seg_desc, 8);
3517 }
3518
3519 /* allowed just for 8 bytes segments */
3520 static int save_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3521                                          struct desc_struct *seg_desc)
3522 {
3523         gpa_t gpa;
3524         struct descriptor_table dtable;
3525         u16 index = selector >> 3;
3526
3527         get_segment_descritptor_dtable(vcpu, selector, &dtable);
3528
3529         if (dtable.limit < index * 8 + 7)
3530                 return 1;
3531         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, dtable.base);
3532         gpa += index * 8;
3533         return kvm_write_guest(vcpu->kvm, gpa, seg_desc, 8);
3534 }
3535
3536 static u32 get_tss_base_addr(struct kvm_vcpu *vcpu,
3537                              struct desc_struct *seg_desc)
3538 {
3539         u32 base_addr;
3540
3541         base_addr = seg_desc->base0;
3542         base_addr |= (seg_desc->base1 << 16);
3543         base_addr |= (seg_desc->base2 << 24);
3544
3545         return vcpu->arch.mmu.gva_to_gpa(vcpu, base_addr);
3546 }
3547
3548 static u16 get_segment_selector(struct kvm_vcpu *vcpu, int seg)
3549 {
3550         struct kvm_segment kvm_seg;
3551
3552         kvm_get_segment(vcpu, &kvm_seg, seg);
3553         return kvm_seg.selector;
3554 }
3555
3556 static int load_segment_descriptor_to_kvm_desct(struct kvm_vcpu *vcpu,
3557                                                 u16 selector,
3558                                                 struct kvm_segment *kvm_seg)
3559 {
3560         struct desc_struct seg_desc;
3561
3562         if (load_guest_segment_descriptor(vcpu, selector, &seg_desc))
3563                 return 1;
3564         seg_desct_to_kvm_desct(&seg_desc, selector, kvm_seg);
3565         return 0;
3566 }
3567
3568 int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3569                                 int type_bits, int seg)
3570 {
3571         struct kvm_segment kvm_seg;
3572
3573         if (load_segment_descriptor_to_kvm_desct(vcpu, selector, &kvm_seg))
3574                 return 1;
3575         kvm_seg.type |= type_bits;
3576
3577         if (seg != VCPU_SREG_SS && seg != VCPU_SREG_CS &&
3578             seg != VCPU_SREG_LDTR)
3579                 if (!kvm_seg.s)
3580                         kvm_seg.unusable = 1;
3581
3582         kvm_set_segment(vcpu, &kvm_seg, seg);
3583         return 0;
3584 }
3585
3586 static void save_state_to_tss32(struct kvm_vcpu *vcpu,
3587                                 struct tss_segment_32 *tss)
3588 {
3589         tss->cr3 = vcpu->arch.cr3;
3590         tss->eip = kvm_rip_read(vcpu);
3591         tss->eflags = kvm_x86_ops->get_rflags(vcpu);
3592         tss->eax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3593         tss->ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3594         tss->edx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3595         tss->ebx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3596         tss->esp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3597         tss->ebp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3598         tss->esi = kvm_register_read(vcpu, VCPU_REGS_RSI);
3599         tss->edi = kvm_register_read(vcpu, VCPU_REGS_RDI);
3600         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3601         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3602         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3603         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3604         tss->fs = get_segment_selector(vcpu, VCPU_SREG_FS);
3605         tss->gs = get_segment_selector(vcpu, VCPU_SREG_GS);
3606         tss->ldt_selector = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3607         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3608 }
3609
3610 static int load_state_from_tss32(struct kvm_vcpu *vcpu,
3611                                   struct tss_segment_32 *tss)
3612 {
3613         kvm_set_cr3(vcpu, tss->cr3);
3614
3615         kvm_rip_write(vcpu, tss->eip);
3616         kvm_x86_ops->set_rflags(vcpu, tss->eflags | 2);
3617
3618         kvm_register_write(vcpu, VCPU_REGS_RAX, tss->eax);
3619         kvm_register_write(vcpu, VCPU_REGS_RCX, tss->ecx);
3620         kvm_register_write(vcpu, VCPU_REGS_RDX, tss->edx);
3621         kvm_register_write(vcpu, VCPU_REGS_RBX, tss->ebx);
3622         kvm_register_write(vcpu, VCPU_REGS_RSP, tss->esp);
3623         kvm_register_write(vcpu, VCPU_REGS_RBP, tss->ebp);
3624         kvm_register_write(vcpu, VCPU_REGS_RSI, tss->esi);
3625         kvm_register_write(vcpu, VCPU_REGS_RDI, tss->edi);
3626
3627         if (kvm_load_segment_descriptor(vcpu, tss->ldt_selector, 0, VCPU_SREG_LDTR))
3628                 return 1;
3629
3630         if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3631                 return 1;
3632
3633         if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3634                 return 1;
3635
3636         if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3637                 return 1;
3638
3639         if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3640                 return 1;
3641
3642         if (kvm_load_segment_descriptor(vcpu, tss->fs, 1, VCPU_SREG_FS))
3643                 return 1;
3644
3645         if (kvm_load_segment_descriptor(vcpu, tss->gs, 1, VCPU_SREG_GS))
3646                 return 1;
3647         return 0;
3648 }
3649
3650 static void save_state_to_tss16(struct kvm_vcpu *vcpu,
3651                                 struct tss_segment_16 *tss)
3652 {
3653         tss->ip = kvm_rip_read(vcpu);
3654         tss->flag = kvm_x86_ops->get_rflags(vcpu);
3655         tss->ax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3656         tss->cx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3657         tss->dx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3658         tss->bx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3659         tss->sp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3660         tss->bp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3661         tss->si = kvm_register_read(vcpu, VCPU_REGS_RSI);
3662         tss->di = kvm_register_read(vcpu, VCPU_REGS_RDI);
3663
3664         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3665         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3666         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3667         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3668         tss->ldt = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3669         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3670 }
3671
3672 static int load_state_from_tss16(struct kvm_vcpu *vcpu,
3673                                  struct tss_segment_16 *tss)
3674 {
3675         kvm_rip_write(vcpu, tss->ip);
3676         kvm_x86_ops->set_rflags(vcpu, tss->flag | 2);
3677         kvm_register_write(vcpu, VCPU_REGS_RAX, tss->ax);
3678         kvm_register_write(vcpu, VCPU_REGS_RCX, tss->cx);
3679         kvm_register_write(vcpu, VCPU_REGS_RDX, tss->dx);
3680         kvm_register_write(vcpu, VCPU_REGS_RBX, tss->bx);
3681         kvm_register_write(vcpu, VCPU_REGS_RSP, tss->sp);
3682         kvm_register_write(vcpu, VCPU_REGS_RBP, tss->bp);
3683         kvm_register_write(vcpu, VCPU_REGS_RSI, tss->si);
3684         kvm_register_write(vcpu, VCPU_REGS_RDI, tss->di);
3685
3686         if (kvm_load_segment_descriptor(vcpu, tss->ldt, 0, VCPU_SREG_LDTR))
3687                 return 1;
3688
3689         if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3690                 return 1;
3691
3692         if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3693                 return 1;
3694
3695         if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3696                 return 1;
3697
3698         if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3699                 return 1;
3700         return 0;
3701 }
3702
3703 static int kvm_task_switch_16(struct kvm_vcpu *vcpu, u16 tss_selector,
3704                        u32 old_tss_base,
3705                        struct desc_struct *nseg_desc)
3706 {
3707         struct tss_segment_16 tss_segment_16;
3708         int ret = 0;
3709
3710         if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
3711                            sizeof tss_segment_16))
3712                 goto out;
3713
3714         save_state_to_tss16(vcpu, &tss_segment_16);
3715
3716         if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
3717                             sizeof tss_segment_16))
3718                 goto out;
3719
3720         if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
3721                            &tss_segment_16, sizeof tss_segment_16))
3722                 goto out;
3723
3724         if (load_state_from_tss16(vcpu, &tss_segment_16))
3725                 goto out;
3726
3727         ret = 1;
3728 out:
3729         return ret;
3730 }
3731
3732 static int kvm_task_switch_32(struct kvm_vcpu *vcpu, u16 tss_selector,
3733                        u32 old_tss_base,
3734                        struct desc_struct *nseg_desc)
3735 {
3736         struct tss_segment_32 tss_segment_32;
3737         int ret = 0;
3738
3739         if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
3740                            sizeof tss_segment_32))
3741                 goto out;
3742
3743         save_state_to_tss32(vcpu, &tss_segment_32);
3744
3745         if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
3746                             sizeof tss_segment_32))
3747                 goto out;
3748
3749         if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
3750                            &tss_segment_32, sizeof tss_segment_32))
3751                 goto out;
3752
3753         if (load_state_from_tss32(vcpu, &tss_segment_32))
3754                 goto out;
3755
3756         ret = 1;
3757 out:
3758         return ret;
3759 }
3760
3761 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason)
3762 {
3763         struct kvm_segment tr_seg;
3764         struct desc_struct cseg_desc;
3765         struct desc_struct nseg_desc;
3766         int ret = 0;
3767         u32 old_tss_base = get_segment_base(vcpu, VCPU_SREG_TR);
3768         u16 old_tss_sel = get_segment_selector(vcpu, VCPU_SREG_TR);
3769
3770         old_tss_base = vcpu->arch.mmu.gva_to_gpa(vcpu, old_tss_base);
3771
3772         /* FIXME: Handle errors. Failure to read either TSS or their
3773          * descriptors should generate a pagefault.
3774          */
3775         if (load_guest_segment_descriptor(vcpu, tss_selector, &nseg_desc))
3776                 goto out;
3777
3778         if (load_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc))
3779                 goto out;
3780
3781         if (reason != TASK_SWITCH_IRET) {
3782                 int cpl;
3783
3784                 cpl = kvm_x86_ops->get_cpl(vcpu);
3785                 if ((tss_selector & 3) > nseg_desc.dpl || cpl > nseg_desc.dpl) {
3786                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
3787                         return 1;
3788                 }
3789         }
3790
3791         if (!nseg_desc.p || (nseg_desc.limit0 | nseg_desc.limit << 16) < 0x67) {
3792                 kvm_queue_exception_e(vcpu, TS_VECTOR, tss_selector & 0xfffc);
3793                 return 1;
3794         }
3795
3796         if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
3797                 cseg_desc.type &= ~(1 << 1); //clear the B flag
3798                 save_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc);
3799         }
3800
3801         if (reason == TASK_SWITCH_IRET) {
3802                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3803                 kvm_x86_ops->set_rflags(vcpu, eflags & ~X86_EFLAGS_NT);
3804         }
3805
3806         kvm_x86_ops->skip_emulated_instruction(vcpu);
3807
3808         if (nseg_desc.type & 8)
3809                 ret = kvm_task_switch_32(vcpu, tss_selector, old_tss_base,
3810                                          &nseg_desc);
3811         else
3812                 ret = kvm_task_switch_16(vcpu, tss_selector, old_tss_base,
3813                                          &nseg_desc);
3814
3815         if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) {
3816                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3817                 kvm_x86_ops->set_rflags(vcpu, eflags | X86_EFLAGS_NT);
3818         }
3819
3820         if (reason != TASK_SWITCH_IRET) {
3821                 nseg_desc.type |= (1 << 1);
3822                 save_guest_segment_descriptor(vcpu, tss_selector,
3823                                               &nseg_desc);
3824         }
3825
3826         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 | X86_CR0_TS);
3827         seg_desct_to_kvm_desct(&nseg_desc, tss_selector, &tr_seg);
3828         tr_seg.type = 11;
3829         kvm_set_segment(vcpu, &tr_seg, VCPU_SREG_TR);
3830 out:
3831         return ret;
3832 }
3833 EXPORT_SYMBOL_GPL(kvm_task_switch);
3834
3835 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
3836                                   struct kvm_sregs *sregs)
3837 {
3838         int mmu_reset_needed = 0;
3839         int i, pending_vec, max_bits;
3840         struct descriptor_table dt;
3841
3842         vcpu_load(vcpu);
3843
3844         dt.limit = sregs->idt.limit;
3845         dt.base = sregs->idt.base;
3846         kvm_x86_ops->set_idt(vcpu, &dt);
3847         dt.limit = sregs->gdt.limit;
3848         dt.base = sregs->gdt.base;
3849         kvm_x86_ops->set_gdt(vcpu, &dt);
3850
3851         vcpu->arch.cr2 = sregs->cr2;
3852         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
3853         vcpu->arch.cr3 = sregs->cr3;
3854
3855         kvm_set_cr8(vcpu, sregs->cr8);
3856
3857         mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
3858         kvm_x86_ops->set_efer(vcpu, sregs->efer);
3859         kvm_set_apic_base(vcpu, sregs->apic_base);
3860
3861         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3862
3863         mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
3864         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
3865         vcpu->arch.cr0 = sregs->cr0;
3866
3867         mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
3868         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
3869         if (!is_long_mode(vcpu) && is_pae(vcpu))
3870                 load_pdptrs(vcpu, vcpu->arch.cr3);
3871
3872         if (mmu_reset_needed)
3873                 kvm_mmu_reset_context(vcpu);
3874
3875         if (!irqchip_in_kernel(vcpu->kvm)) {
3876                 memcpy(vcpu->arch.irq_pending, sregs->interrupt_bitmap,
3877                        sizeof vcpu->arch.irq_pending);
3878                 vcpu->arch.irq_summary = 0;
3879                 for (i = 0; i < ARRAY_SIZE(vcpu->arch.irq_pending); ++i)
3880                         if (vcpu->arch.irq_pending[i])
3881                                 __set_bit(i, &vcpu->arch.irq_summary);
3882         } else {
3883                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
3884                 pending_vec = find_first_bit(
3885                         (const unsigned long *)sregs->interrupt_bitmap,
3886                         max_bits);
3887                 /* Only pending external irq is handled here */
3888                 if (pending_vec < max_bits) {
3889                         kvm_x86_ops->set_irq(vcpu, pending_vec);
3890                         pr_debug("Set back pending irq %d\n",
3891                                  pending_vec);
3892                 }
3893         }
3894
3895         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3896         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3897         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3898         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3899         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3900         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3901
3902         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3903         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3904
3905         vcpu_put(vcpu);
3906
3907         return 0;
3908 }
3909
3910 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
3911                                     struct kvm_debug_guest *dbg)
3912 {
3913         int r;
3914
3915         vcpu_load(vcpu);
3916
3917         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
3918
3919         vcpu_put(vcpu);
3920
3921         return r;
3922 }
3923
3924 /*
3925  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
3926  * we have asm/x86/processor.h
3927  */
3928 struct fxsave {
3929         u16     cwd;
3930         u16     swd;
3931         u16     twd;
3932         u16     fop;
3933         u64     rip;
3934         u64     rdp;
3935         u32     mxcsr;
3936         u32     mxcsr_mask;
3937         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
3938 #ifdef CONFIG_X86_64
3939         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
3940 #else
3941         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
3942 #endif
3943 };
3944
3945 /*
3946  * Translate a guest virtual address to a guest physical address.
3947  */
3948 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
3949                                     struct kvm_translation *tr)
3950 {
3951         unsigned long vaddr = tr->linear_address;
3952         gpa_t gpa;
3953
3954         vcpu_load(vcpu);
3955         down_read(&vcpu->kvm->slots_lock);
3956         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
3957         up_read(&vcpu->kvm->slots_lock);
3958         tr->physical_address = gpa;
3959         tr->valid = gpa != UNMAPPED_GVA;
3960         tr->writeable = 1;
3961         tr->usermode = 0;
3962         vcpu_put(vcpu);
3963
3964         return 0;
3965 }
3966
3967 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
3968 {
3969         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
3970
3971         vcpu_load(vcpu);
3972
3973         memcpy(fpu->fpr, fxsave->st_space, 128);
3974         fpu->fcw = fxsave->cwd;
3975         fpu->fsw = fxsave->swd;
3976         fpu->ftwx = fxsave->twd;
3977         fpu->last_opcode = fxsave->fop;
3978         fpu->last_ip = fxsave->rip;
3979         fpu->last_dp = fxsave->rdp;
3980         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
3981
3982         vcpu_put(vcpu);
3983
3984         return 0;
3985 }
3986
3987 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
3988 {
3989         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
3990
3991         vcpu_load(vcpu);
3992
3993         memcpy(fxsave->st_space, fpu->fpr, 128);
3994         fxsave->cwd = fpu->fcw;
3995         fxsave->swd = fpu->fsw;
3996         fxsave->twd = fpu->ftwx;
3997         fxsave->fop = fpu->last_opcode;
3998         fxsave->rip = fpu->last_ip;
3999         fxsave->rdp = fpu->last_dp;
4000         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
4001
4002         vcpu_put(vcpu);
4003
4004         return 0;
4005 }
4006
4007 void fx_init(struct kvm_vcpu *vcpu)
4008 {
4009         unsigned after_mxcsr_mask;
4010
4011         /*
4012          * Touch the fpu the first time in non atomic context as if
4013          * this is the first fpu instruction the exception handler
4014          * will fire before the instruction returns and it'll have to
4015          * allocate ram with GFP_KERNEL.
4016          */
4017         if (!used_math())
4018                 kvm_fx_save(&vcpu->arch.host_fx_image);
4019
4020         /* Initialize guest FPU by resetting ours and saving into guest's */
4021         preempt_disable();
4022         kvm_fx_save(&vcpu->arch.host_fx_image);
4023         kvm_fx_finit();
4024         kvm_fx_save(&vcpu->arch.guest_fx_image);
4025         kvm_fx_restore(&vcpu->arch.host_fx_image);
4026         preempt_enable();
4027
4028         vcpu->arch.cr0 |= X86_CR0_ET;
4029         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
4030         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
4031         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
4032                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
4033 }
4034 EXPORT_SYMBOL_GPL(fx_init);
4035
4036 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
4037 {
4038         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
4039                 return;
4040
4041         vcpu->guest_fpu_loaded = 1;
4042         kvm_fx_save(&vcpu->arch.host_fx_image);
4043         kvm_fx_restore(&vcpu->arch.guest_fx_image);
4044 }
4045 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
4046
4047 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
4048 {
4049         if (!vcpu->guest_fpu_loaded)
4050                 return;
4051
4052         vcpu->guest_fpu_loaded = 0;
4053         kvm_fx_save(&vcpu->arch.guest_fx_image);
4054         kvm_fx_restore(&vcpu->arch.host_fx_image);
4055         ++vcpu->stat.fpu_reload;
4056 }
4057 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
4058
4059 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
4060 {
4061         kvm_x86_ops->vcpu_free(vcpu);
4062 }
4063
4064 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
4065                                                 unsigned int id)
4066 {
4067         return kvm_x86_ops->vcpu_create(kvm, id);
4068 }
4069
4070 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
4071 {
4072         int r;
4073
4074         /* We do fxsave: this must be aligned. */
4075         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
4076
4077         vcpu_load(vcpu);
4078         r = kvm_arch_vcpu_reset(vcpu);
4079         if (r == 0)
4080                 r = kvm_mmu_setup(vcpu);
4081         vcpu_put(vcpu);
4082         if (r < 0)
4083                 goto free_vcpu;
4084
4085         return 0;
4086 free_vcpu:
4087         kvm_x86_ops->vcpu_free(vcpu);
4088         return r;
4089 }
4090
4091 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
4092 {
4093         vcpu_load(vcpu);
4094         kvm_mmu_unload(vcpu);
4095         vcpu_put(vcpu);
4096
4097         kvm_x86_ops->vcpu_free(vcpu);
4098 }
4099
4100 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
4101 {
4102         return kvm_x86_ops->vcpu_reset(vcpu);
4103 }
4104
4105 void kvm_arch_hardware_enable(void *garbage)
4106 {
4107         kvm_x86_ops->hardware_enable(garbage);
4108 }
4109
4110 void kvm_arch_hardware_disable(void *garbage)
4111 {
4112         kvm_x86_ops->hardware_disable(garbage);
4113 }
4114
4115 int kvm_arch_hardware_setup(void)
4116 {
4117         return kvm_x86_ops->hardware_setup();
4118 }
4119
4120 void kvm_arch_hardware_unsetup(void)
4121 {
4122         kvm_x86_ops->hardware_unsetup();
4123 }
4124
4125 void kvm_arch_check_processor_compat(void *rtn)
4126 {
4127         kvm_x86_ops->check_processor_compatibility(rtn);
4128 }
4129
4130 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
4131 {
4132         struct page *page;
4133         struct kvm *kvm;
4134         int r;
4135
4136         BUG_ON(vcpu->kvm == NULL);
4137         kvm = vcpu->kvm;
4138
4139         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
4140         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
4141                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4142         else
4143                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
4144
4145         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
4146         if (!page) {
4147                 r = -ENOMEM;
4148                 goto fail;
4149         }
4150         vcpu->arch.pio_data = page_address(page);
4151
4152         r = kvm_mmu_create(vcpu);
4153         if (r < 0)
4154                 goto fail_free_pio_data;
4155
4156         if (irqchip_in_kernel(kvm)) {
4157                 r = kvm_create_lapic(vcpu);
4158                 if (r < 0)
4159                         goto fail_mmu_destroy;
4160         }
4161
4162         return 0;
4163
4164 fail_mmu_destroy:
4165         kvm_mmu_destroy(vcpu);
4166 fail_free_pio_data:
4167         free_page((unsigned long)vcpu->arch.pio_data);
4168 fail:
4169         return r;
4170 }
4171
4172 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
4173 {
4174         kvm_free_lapic(vcpu);
4175         down_read(&vcpu->kvm->slots_lock);
4176         kvm_mmu_destroy(vcpu);
4177         up_read(&vcpu->kvm->slots_lock);
4178         free_page((unsigned long)vcpu->arch.pio_data);
4179 }
4180
4181 struct  kvm *kvm_arch_create_vm(void)
4182 {
4183         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
4184
4185         if (!kvm)
4186                 return ERR_PTR(-ENOMEM);
4187
4188         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
4189         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
4190
4191         return kvm;
4192 }
4193
4194 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
4195 {
4196         vcpu_load(vcpu);
4197         kvm_mmu_unload(vcpu);
4198         vcpu_put(vcpu);
4199 }
4200
4201 static void kvm_free_vcpus(struct kvm *kvm)
4202 {
4203         unsigned int i;
4204
4205         /*
4206          * Unpin any mmu pages first.
4207          */
4208         for (i = 0; i < KVM_MAX_VCPUS; ++i)
4209                 if (kvm->vcpus[i])
4210                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
4211         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
4212                 if (kvm->vcpus[i]) {
4213                         kvm_arch_vcpu_free(kvm->vcpus[i]);
4214                         kvm->vcpus[i] = NULL;
4215                 }
4216         }
4217
4218 }
4219
4220 void kvm_arch_destroy_vm(struct kvm *kvm)
4221 {
4222         kvm_free_assigned_devices(kvm);
4223         kvm_free_pit(kvm);
4224         kfree(kvm->arch.vpic);
4225         kfree(kvm->arch.vioapic);
4226         kvm_free_vcpus(kvm);
4227         kvm_free_physmem(kvm);
4228         if (kvm->arch.apic_access_page)
4229                 put_page(kvm->arch.apic_access_page);
4230         if (kvm->arch.ept_identity_pagetable)
4231                 put_page(kvm->arch.ept_identity_pagetable);
4232         kfree(kvm);
4233 }
4234
4235 int kvm_arch_set_memory_region(struct kvm *kvm,
4236                                 struct kvm_userspace_memory_region *mem,
4237                                 struct kvm_memory_slot old,
4238                                 int user_alloc)
4239 {
4240         int npages = mem->memory_size >> PAGE_SHIFT;
4241         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
4242
4243         /*To keep backward compatibility with older userspace,
4244          *x86 needs to hanlde !user_alloc case.
4245          */
4246         if (!user_alloc) {
4247                 if (npages && !old.rmap) {
4248                         unsigned long userspace_addr;
4249
4250                         down_write(&current->mm->mmap_sem);
4251                         userspace_addr = do_mmap(NULL, 0,
4252                                                  npages * PAGE_SIZE,
4253                                                  PROT_READ | PROT_WRITE,
4254                                                  MAP_SHARED | MAP_ANONYMOUS,
4255                                                  0);
4256                         up_write(&current->mm->mmap_sem);
4257
4258                         if (IS_ERR((void *)userspace_addr))
4259                                 return PTR_ERR((void *)userspace_addr);
4260
4261                         /* set userspace_addr atomically for kvm_hva_to_rmapp */
4262                         spin_lock(&kvm->mmu_lock);
4263                         memslot->userspace_addr = userspace_addr;
4264                         spin_unlock(&kvm->mmu_lock);
4265                 } else {
4266                         if (!old.user_alloc && old.rmap) {
4267                                 int ret;
4268
4269                                 down_write(&current->mm->mmap_sem);
4270                                 ret = do_munmap(current->mm, old.userspace_addr,
4271                                                 old.npages * PAGE_SIZE);
4272                                 up_write(&current->mm->mmap_sem);
4273                                 if (ret < 0)
4274                                         printk(KERN_WARNING
4275                                        "kvm_vm_ioctl_set_memory_region: "
4276                                        "failed to munmap memory\n");
4277                         }
4278                 }
4279         }
4280
4281         if (!kvm->arch.n_requested_mmu_pages) {
4282                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
4283                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
4284         }
4285
4286         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
4287         kvm_flush_remote_tlbs(kvm);
4288
4289         return 0;
4290 }
4291
4292 void kvm_arch_flush_shadow(struct kvm *kvm)
4293 {
4294         kvm_mmu_zap_all(kvm);
4295 }
4296
4297 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
4298 {
4299         return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
4300                || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED;
4301 }
4302
4303 static void vcpu_kick_intr(void *info)
4304 {
4305 #ifdef DEBUG
4306         struct kvm_vcpu *vcpu = (struct kvm_vcpu *)info;
4307         printk(KERN_DEBUG "vcpu_kick_intr %p \n", vcpu);
4308 #endif
4309 }
4310
4311 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
4312 {
4313         int ipi_pcpu = vcpu->cpu;
4314         int cpu = get_cpu();
4315
4316         if (waitqueue_active(&vcpu->wq)) {
4317                 wake_up_interruptible(&vcpu->wq);
4318                 ++vcpu->stat.halt_wakeup;
4319         }
4320         /*
4321          * We may be called synchronously with irqs disabled in guest mode,
4322          * So need not to call smp_call_function_single() in that case.
4323          */
4324         if (vcpu->guest_mode && vcpu->cpu != cpu)
4325                 smp_call_function_single(ipi_pcpu, vcpu_kick_intr, vcpu, 0);
4326         put_cpu();
4327 }