KVM: Add MSI-X interrupt injection logic
[linux-2.6.git] / virt / kvm / kvm_main.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  *
9  * Authors:
10  *   Avi Kivity   <avi@qumranet.com>
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17
18 #include "iodev.h"
19
20 #include <linux/kvm_host.h>
21 #include <linux/kvm.h>
22 #include <linux/module.h>
23 #include <linux/errno.h>
24 #include <linux/percpu.h>
25 #include <linux/gfp.h>
26 #include <linux/mm.h>
27 #include <linux/miscdevice.h>
28 #include <linux/vmalloc.h>
29 #include <linux/reboot.h>
30 #include <linux/debugfs.h>
31 #include <linux/highmem.h>
32 #include <linux/file.h>
33 #include <linux/sysdev.h>
34 #include <linux/cpu.h>
35 #include <linux/sched.h>
36 #include <linux/cpumask.h>
37 #include <linux/smp.h>
38 #include <linux/anon_inodes.h>
39 #include <linux/profile.h>
40 #include <linux/kvm_para.h>
41 #include <linux/pagemap.h>
42 #include <linux/mman.h>
43 #include <linux/swap.h>
44
45 #include <asm/processor.h>
46 #include <asm/io.h>
47 #include <asm/uaccess.h>
48 #include <asm/pgtable.h>
49
50 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
51 #include "coalesced_mmio.h"
52 #endif
53
54 #ifdef KVM_CAP_DEVICE_ASSIGNMENT
55 #include <linux/pci.h>
56 #include <linux/interrupt.h>
57 #include "irq.h"
58 #endif
59
60 MODULE_AUTHOR("Qumranet");
61 MODULE_LICENSE("GPL");
62
63 static int msi2intx = 1;
64 module_param(msi2intx, bool, 0);
65
66 DEFINE_SPINLOCK(kvm_lock);
67 LIST_HEAD(vm_list);
68
69 static cpumask_var_t cpus_hardware_enabled;
70
71 struct kmem_cache *kvm_vcpu_cache;
72 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
73
74 static __read_mostly struct preempt_ops kvm_preempt_ops;
75
76 struct dentry *kvm_debugfs_dir;
77
78 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
79                            unsigned long arg);
80
81 static bool kvm_rebooting;
82
83 #ifdef KVM_CAP_DEVICE_ASSIGNMENT
84 static struct kvm_assigned_dev_kernel *kvm_find_assigned_dev(struct list_head *head,
85                                                       int assigned_dev_id)
86 {
87         struct list_head *ptr;
88         struct kvm_assigned_dev_kernel *match;
89
90         list_for_each(ptr, head) {
91                 match = list_entry(ptr, struct kvm_assigned_dev_kernel, list);
92                 if (match->assigned_dev_id == assigned_dev_id)
93                         return match;
94         }
95         return NULL;
96 }
97
98 static int find_index_from_host_irq(struct kvm_assigned_dev_kernel
99                                     *assigned_dev, int irq)
100 {
101         int i, index;
102         struct msix_entry *host_msix_entries;
103
104         host_msix_entries = assigned_dev->host_msix_entries;
105
106         index = -1;
107         for (i = 0; i < assigned_dev->entries_nr; i++)
108                 if (irq == host_msix_entries[i].vector) {
109                         index = i;
110                         break;
111                 }
112         if (index < 0) {
113                 printk(KERN_WARNING "Fail to find correlated MSI-X entry!\n");
114                 return 0;
115         }
116
117         return index;
118 }
119
120 static void kvm_assigned_dev_interrupt_work_handler(struct work_struct *work)
121 {
122         struct kvm_assigned_dev_kernel *assigned_dev;
123         struct kvm *kvm;
124         int irq, i;
125
126         assigned_dev = container_of(work, struct kvm_assigned_dev_kernel,
127                                     interrupt_work);
128         kvm = assigned_dev->kvm;
129
130         /* This is taken to safely inject irq inside the guest. When
131          * the interrupt injection (or the ioapic code) uses a
132          * finer-grained lock, update this
133          */
134         mutex_lock(&kvm->lock);
135         if (assigned_dev->irq_requested_type & KVM_ASSIGNED_DEV_MSIX) {
136                 struct kvm_guest_msix_entry *guest_entries =
137                         assigned_dev->guest_msix_entries;
138                 for (i = 0; i < assigned_dev->entries_nr; i++) {
139                         if (!(guest_entries[i].flags &
140                                         KVM_ASSIGNED_MSIX_PENDING))
141                                 continue;
142                         guest_entries[i].flags &= ~KVM_ASSIGNED_MSIX_PENDING;
143                         kvm_set_irq(assigned_dev->kvm,
144                                     assigned_dev->irq_source_id,
145                                     guest_entries[i].vector, 1);
146                         irq = assigned_dev->host_msix_entries[i].vector;
147                         if (irq != 0)
148                                 enable_irq(irq);
149                         assigned_dev->host_irq_disabled = false;
150                 }
151         } else {
152                 kvm_set_irq(assigned_dev->kvm, assigned_dev->irq_source_id,
153                             assigned_dev->guest_irq, 1);
154                 if (assigned_dev->irq_requested_type &
155                                 KVM_ASSIGNED_DEV_GUEST_MSI) {
156                         enable_irq(assigned_dev->host_irq);
157                         assigned_dev->host_irq_disabled = false;
158                 }
159         }
160
161         mutex_unlock(&assigned_dev->kvm->lock);
162 }
163
164 static irqreturn_t kvm_assigned_dev_intr(int irq, void *dev_id)
165 {
166         struct kvm_assigned_dev_kernel *assigned_dev =
167                 (struct kvm_assigned_dev_kernel *) dev_id;
168
169         if (assigned_dev->irq_requested_type == KVM_ASSIGNED_DEV_MSIX) {
170                 int index = find_index_from_host_irq(assigned_dev, irq);
171                 if (index < 0)
172                         return IRQ_HANDLED;
173                 assigned_dev->guest_msix_entries[index].flags |=
174                         KVM_ASSIGNED_MSIX_PENDING;
175         }
176
177         schedule_work(&assigned_dev->interrupt_work);
178
179         disable_irq_nosync(irq);
180         assigned_dev->host_irq_disabled = true;
181
182         return IRQ_HANDLED;
183 }
184
185 /* Ack the irq line for an assigned device */
186 static void kvm_assigned_dev_ack_irq(struct kvm_irq_ack_notifier *kian)
187 {
188         struct kvm_assigned_dev_kernel *dev;
189
190         if (kian->gsi == -1)
191                 return;
192
193         dev = container_of(kian, struct kvm_assigned_dev_kernel,
194                            ack_notifier);
195
196         kvm_set_irq(dev->kvm, dev->irq_source_id, dev->guest_irq, 0);
197
198         /* The guest irq may be shared so this ack may be
199          * from another device.
200          */
201         if (dev->host_irq_disabled) {
202                 enable_irq(dev->host_irq);
203                 dev->host_irq_disabled = false;
204         }
205 }
206
207 /* The function implicit hold kvm->lock mutex due to cancel_work_sync() */
208 static void kvm_free_assigned_irq(struct kvm *kvm,
209                                   struct kvm_assigned_dev_kernel *assigned_dev)
210 {
211         if (!irqchip_in_kernel(kvm))
212                 return;
213
214         kvm_unregister_irq_ack_notifier(&assigned_dev->ack_notifier);
215
216         if (assigned_dev->irq_source_id != -1)
217                 kvm_free_irq_source_id(kvm, assigned_dev->irq_source_id);
218         assigned_dev->irq_source_id = -1;
219
220         if (!assigned_dev->irq_requested_type)
221                 return;
222
223         /*
224          * In kvm_free_device_irq, cancel_work_sync return true if:
225          * 1. work is scheduled, and then cancelled.
226          * 2. work callback is executed.
227          *
228          * The first one ensured that the irq is disabled and no more events
229          * would happen. But for the second one, the irq may be enabled (e.g.
230          * for MSI). So we disable irq here to prevent further events.
231          *
232          * Notice this maybe result in nested disable if the interrupt type is
233          * INTx, but it's OK for we are going to free it.
234          *
235          * If this function is a part of VM destroy, please ensure that till
236          * now, the kvm state is still legal for probably we also have to wait
237          * interrupt_work done.
238          */
239         disable_irq_nosync(assigned_dev->host_irq);
240         cancel_work_sync(&assigned_dev->interrupt_work);
241
242         free_irq(assigned_dev->host_irq, (void *)assigned_dev);
243
244         if (assigned_dev->irq_requested_type & KVM_ASSIGNED_DEV_HOST_MSI)
245                 pci_disable_msi(assigned_dev->dev);
246
247         assigned_dev->irq_requested_type = 0;
248 }
249
250
251 static void kvm_free_assigned_device(struct kvm *kvm,
252                                      struct kvm_assigned_dev_kernel
253                                      *assigned_dev)
254 {
255         kvm_free_assigned_irq(kvm, assigned_dev);
256
257         pci_reset_function(assigned_dev->dev);
258
259         pci_release_regions(assigned_dev->dev);
260         pci_disable_device(assigned_dev->dev);
261         pci_dev_put(assigned_dev->dev);
262
263         list_del(&assigned_dev->list);
264         kfree(assigned_dev);
265 }
266
267 void kvm_free_all_assigned_devices(struct kvm *kvm)
268 {
269         struct list_head *ptr, *ptr2;
270         struct kvm_assigned_dev_kernel *assigned_dev;
271
272         list_for_each_safe(ptr, ptr2, &kvm->arch.assigned_dev_head) {
273                 assigned_dev = list_entry(ptr,
274                                           struct kvm_assigned_dev_kernel,
275                                           list);
276
277                 kvm_free_assigned_device(kvm, assigned_dev);
278         }
279 }
280
281 static int assigned_device_update_intx(struct kvm *kvm,
282                         struct kvm_assigned_dev_kernel *adev,
283                         struct kvm_assigned_irq *airq)
284 {
285         adev->guest_irq = airq->guest_irq;
286         adev->ack_notifier.gsi = airq->guest_irq;
287
288         if (adev->irq_requested_type & KVM_ASSIGNED_DEV_HOST_INTX)
289                 return 0;
290
291         if (irqchip_in_kernel(kvm)) {
292                 if (!msi2intx &&
293                     (adev->irq_requested_type & KVM_ASSIGNED_DEV_HOST_MSI)) {
294                         free_irq(adev->host_irq, (void *)adev);
295                         pci_disable_msi(adev->dev);
296                 }
297
298                 if (!capable(CAP_SYS_RAWIO))
299                         return -EPERM;
300
301                 if (airq->host_irq)
302                         adev->host_irq = airq->host_irq;
303                 else
304                         adev->host_irq = adev->dev->irq;
305
306                 /* Even though this is PCI, we don't want to use shared
307                  * interrupts. Sharing host devices with guest-assigned devices
308                  * on the same interrupt line is not a happy situation: there
309                  * are going to be long delays in accepting, acking, etc.
310                  */
311                 if (request_irq(adev->host_irq, kvm_assigned_dev_intr,
312                                 0, "kvm_assigned_intx_device", (void *)adev))
313                         return -EIO;
314         }
315
316         adev->irq_requested_type = KVM_ASSIGNED_DEV_GUEST_INTX |
317                                    KVM_ASSIGNED_DEV_HOST_INTX;
318         return 0;
319 }
320
321 #ifdef CONFIG_X86
322 static int assigned_device_update_msi(struct kvm *kvm,
323                         struct kvm_assigned_dev_kernel *adev,
324                         struct kvm_assigned_irq *airq)
325 {
326         int r;
327
328         adev->guest_irq = airq->guest_irq;
329         if (airq->flags & KVM_DEV_IRQ_ASSIGN_ENABLE_MSI) {
330                 /* x86 don't care upper address of guest msi message addr */
331                 adev->irq_requested_type |= KVM_ASSIGNED_DEV_GUEST_MSI;
332                 adev->irq_requested_type &= ~KVM_ASSIGNED_DEV_GUEST_INTX;
333                 adev->ack_notifier.gsi = -1;
334         } else if (msi2intx) {
335                 adev->irq_requested_type |= KVM_ASSIGNED_DEV_GUEST_INTX;
336                 adev->irq_requested_type &= ~KVM_ASSIGNED_DEV_GUEST_MSI;
337                 adev->ack_notifier.gsi = airq->guest_irq;
338         } else {
339                 /*
340                  * Guest require to disable device MSI, we disable MSI and
341                  * re-enable INTx by default again. Notice it's only for
342                  * non-msi2intx.
343                  */
344                 assigned_device_update_intx(kvm, adev, airq);
345                 return 0;
346         }
347
348         if (adev->irq_requested_type & KVM_ASSIGNED_DEV_HOST_MSI)
349                 return 0;
350
351         if (irqchip_in_kernel(kvm)) {
352                 if (!msi2intx) {
353                         if (adev->irq_requested_type &
354                                         KVM_ASSIGNED_DEV_HOST_INTX)
355                                 free_irq(adev->host_irq, (void *)adev);
356
357                         r = pci_enable_msi(adev->dev);
358                         if (r)
359                                 return r;
360                 }
361
362                 adev->host_irq = adev->dev->irq;
363                 if (request_irq(adev->host_irq, kvm_assigned_dev_intr, 0,
364                                 "kvm_assigned_msi_device", (void *)adev))
365                         return -EIO;
366         }
367
368         if (!msi2intx)
369                 adev->irq_requested_type = KVM_ASSIGNED_DEV_GUEST_MSI;
370
371         adev->irq_requested_type |= KVM_ASSIGNED_DEV_HOST_MSI;
372         return 0;
373 }
374 #endif
375
376 static int kvm_vm_ioctl_assign_irq(struct kvm *kvm,
377                                    struct kvm_assigned_irq
378                                    *assigned_irq)
379 {
380         int r = 0;
381         struct kvm_assigned_dev_kernel *match;
382         u32 current_flags = 0, changed_flags;
383
384         mutex_lock(&kvm->lock);
385
386         match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
387                                       assigned_irq->assigned_dev_id);
388         if (!match) {
389                 mutex_unlock(&kvm->lock);
390                 return -EINVAL;
391         }
392
393         if (!match->irq_requested_type) {
394                 INIT_WORK(&match->interrupt_work,
395                                 kvm_assigned_dev_interrupt_work_handler);
396                 if (irqchip_in_kernel(kvm)) {
397                         /* Register ack nofitier */
398                         match->ack_notifier.gsi = -1;
399                         match->ack_notifier.irq_acked =
400                                         kvm_assigned_dev_ack_irq;
401                         kvm_register_irq_ack_notifier(kvm,
402                                         &match->ack_notifier);
403
404                         /* Request IRQ source ID */
405                         r = kvm_request_irq_source_id(kvm);
406                         if (r < 0)
407                                 goto out_release;
408                         else
409                                 match->irq_source_id = r;
410
411 #ifdef CONFIG_X86
412                         /* Determine host device irq type, we can know the
413                          * result from dev->msi_enabled */
414                         if (msi2intx)
415                                 pci_enable_msi(match->dev);
416 #endif
417                 }
418         }
419
420         if ((match->irq_requested_type & KVM_ASSIGNED_DEV_HOST_MSI) &&
421                  (match->irq_requested_type & KVM_ASSIGNED_DEV_GUEST_MSI))
422                 current_flags |= KVM_DEV_IRQ_ASSIGN_ENABLE_MSI;
423
424         changed_flags = assigned_irq->flags ^ current_flags;
425
426         if ((changed_flags & KVM_DEV_IRQ_ASSIGN_MSI_ACTION) ||
427             (msi2intx && match->dev->msi_enabled)) {
428 #ifdef CONFIG_X86
429                 r = assigned_device_update_msi(kvm, match, assigned_irq);
430                 if (r) {
431                         printk(KERN_WARNING "kvm: failed to enable "
432                                         "MSI device!\n");
433                         goto out_release;
434                 }
435 #else
436                 r = -ENOTTY;
437 #endif
438         } else if (assigned_irq->host_irq == 0 && match->dev->irq == 0) {
439                 /* Host device IRQ 0 means don't support INTx */
440                 if (!msi2intx) {
441                         printk(KERN_WARNING
442                                "kvm: wait device to enable MSI!\n");
443                         r = 0;
444                 } else {
445                         printk(KERN_WARNING
446                                "kvm: failed to enable MSI device!\n");
447                         r = -ENOTTY;
448                         goto out_release;
449                 }
450         } else {
451                 /* Non-sharing INTx mode */
452                 r = assigned_device_update_intx(kvm, match, assigned_irq);
453                 if (r) {
454                         printk(KERN_WARNING "kvm: failed to enable "
455                                         "INTx device!\n");
456                         goto out_release;
457                 }
458         }
459
460         mutex_unlock(&kvm->lock);
461         return r;
462 out_release:
463         mutex_unlock(&kvm->lock);
464         kvm_free_assigned_device(kvm, match);
465         return r;
466 }
467
468 static int kvm_vm_ioctl_assign_device(struct kvm *kvm,
469                                       struct kvm_assigned_pci_dev *assigned_dev)
470 {
471         int r = 0;
472         struct kvm_assigned_dev_kernel *match;
473         struct pci_dev *dev;
474
475         down_read(&kvm->slots_lock);
476         mutex_lock(&kvm->lock);
477
478         match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
479                                       assigned_dev->assigned_dev_id);
480         if (match) {
481                 /* device already assigned */
482                 r = -EINVAL;
483                 goto out;
484         }
485
486         match = kzalloc(sizeof(struct kvm_assigned_dev_kernel), GFP_KERNEL);
487         if (match == NULL) {
488                 printk(KERN_INFO "%s: Couldn't allocate memory\n",
489                        __func__);
490                 r = -ENOMEM;
491                 goto out;
492         }
493         dev = pci_get_bus_and_slot(assigned_dev->busnr,
494                                    assigned_dev->devfn);
495         if (!dev) {
496                 printk(KERN_INFO "%s: host device not found\n", __func__);
497                 r = -EINVAL;
498                 goto out_free;
499         }
500         if (pci_enable_device(dev)) {
501                 printk(KERN_INFO "%s: Could not enable PCI device\n", __func__);
502                 r = -EBUSY;
503                 goto out_put;
504         }
505         r = pci_request_regions(dev, "kvm_assigned_device");
506         if (r) {
507                 printk(KERN_INFO "%s: Could not get access to device regions\n",
508                        __func__);
509                 goto out_disable;
510         }
511
512         pci_reset_function(dev);
513
514         match->assigned_dev_id = assigned_dev->assigned_dev_id;
515         match->host_busnr = assigned_dev->busnr;
516         match->host_devfn = assigned_dev->devfn;
517         match->flags = assigned_dev->flags;
518         match->dev = dev;
519         match->irq_source_id = -1;
520         match->kvm = kvm;
521
522         list_add(&match->list, &kvm->arch.assigned_dev_head);
523
524         if (assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU) {
525                 if (!kvm->arch.iommu_domain) {
526                         r = kvm_iommu_map_guest(kvm);
527                         if (r)
528                                 goto out_list_del;
529                 }
530                 r = kvm_assign_device(kvm, match);
531                 if (r)
532                         goto out_list_del;
533         }
534
535 out:
536         mutex_unlock(&kvm->lock);
537         up_read(&kvm->slots_lock);
538         return r;
539 out_list_del:
540         list_del(&match->list);
541         pci_release_regions(dev);
542 out_disable:
543         pci_disable_device(dev);
544 out_put:
545         pci_dev_put(dev);
546 out_free:
547         kfree(match);
548         mutex_unlock(&kvm->lock);
549         up_read(&kvm->slots_lock);
550         return r;
551 }
552 #endif
553
554 #ifdef KVM_CAP_DEVICE_DEASSIGNMENT
555 static int kvm_vm_ioctl_deassign_device(struct kvm *kvm,
556                 struct kvm_assigned_pci_dev *assigned_dev)
557 {
558         int r = 0;
559         struct kvm_assigned_dev_kernel *match;
560
561         mutex_lock(&kvm->lock);
562
563         match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
564                                       assigned_dev->assigned_dev_id);
565         if (!match) {
566                 printk(KERN_INFO "%s: device hasn't been assigned before, "
567                   "so cannot be deassigned\n", __func__);
568                 r = -EINVAL;
569                 goto out;
570         }
571
572         if (match->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU)
573                 kvm_deassign_device(kvm, match);
574
575         kvm_free_assigned_device(kvm, match);
576
577 out:
578         mutex_unlock(&kvm->lock);
579         return r;
580 }
581 #endif
582
583 static inline int valid_vcpu(int n)
584 {
585         return likely(n >= 0 && n < KVM_MAX_VCPUS);
586 }
587
588 inline int kvm_is_mmio_pfn(pfn_t pfn)
589 {
590         if (pfn_valid(pfn)) {
591                 struct page *page = compound_head(pfn_to_page(pfn));
592                 return PageReserved(page);
593         }
594
595         return true;
596 }
597
598 /*
599  * Switches to specified vcpu, until a matching vcpu_put()
600  */
601 void vcpu_load(struct kvm_vcpu *vcpu)
602 {
603         int cpu;
604
605         mutex_lock(&vcpu->mutex);
606         cpu = get_cpu();
607         preempt_notifier_register(&vcpu->preempt_notifier);
608         kvm_arch_vcpu_load(vcpu, cpu);
609         put_cpu();
610 }
611
612 void vcpu_put(struct kvm_vcpu *vcpu)
613 {
614         preempt_disable();
615         kvm_arch_vcpu_put(vcpu);
616         preempt_notifier_unregister(&vcpu->preempt_notifier);
617         preempt_enable();
618         mutex_unlock(&vcpu->mutex);
619 }
620
621 static void ack_flush(void *_completed)
622 {
623 }
624
625 static bool make_all_cpus_request(struct kvm *kvm, unsigned int req)
626 {
627         int i, cpu, me;
628         cpumask_var_t cpus;
629         bool called = true;
630         struct kvm_vcpu *vcpu;
631
632         if (alloc_cpumask_var(&cpus, GFP_ATOMIC))
633                 cpumask_clear(cpus);
634
635         me = get_cpu();
636         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
637                 vcpu = kvm->vcpus[i];
638                 if (!vcpu)
639                         continue;
640                 if (test_and_set_bit(req, &vcpu->requests))
641                         continue;
642                 cpu = vcpu->cpu;
643                 if (cpus != NULL && cpu != -1 && cpu != me)
644                         cpumask_set_cpu(cpu, cpus);
645         }
646         if (unlikely(cpus == NULL))
647                 smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
648         else if (!cpumask_empty(cpus))
649                 smp_call_function_many(cpus, ack_flush, NULL, 1);
650         else
651                 called = false;
652         put_cpu();
653         free_cpumask_var(cpus);
654         return called;
655 }
656
657 void kvm_flush_remote_tlbs(struct kvm *kvm)
658 {
659         if (make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
660                 ++kvm->stat.remote_tlb_flush;
661 }
662
663 void kvm_reload_remote_mmus(struct kvm *kvm)
664 {
665         make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
666 }
667
668 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
669 {
670         struct page *page;
671         int r;
672
673         mutex_init(&vcpu->mutex);
674         vcpu->cpu = -1;
675         vcpu->kvm = kvm;
676         vcpu->vcpu_id = id;
677         init_waitqueue_head(&vcpu->wq);
678
679         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
680         if (!page) {
681                 r = -ENOMEM;
682                 goto fail;
683         }
684         vcpu->run = page_address(page);
685
686         r = kvm_arch_vcpu_init(vcpu);
687         if (r < 0)
688                 goto fail_free_run;
689         return 0;
690
691 fail_free_run:
692         free_page((unsigned long)vcpu->run);
693 fail:
694         return r;
695 }
696 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
697
698 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
699 {
700         kvm_arch_vcpu_uninit(vcpu);
701         free_page((unsigned long)vcpu->run);
702 }
703 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
704
705 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
706 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
707 {
708         return container_of(mn, struct kvm, mmu_notifier);
709 }
710
711 static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
712                                              struct mm_struct *mm,
713                                              unsigned long address)
714 {
715         struct kvm *kvm = mmu_notifier_to_kvm(mn);
716         int need_tlb_flush;
717
718         /*
719          * When ->invalidate_page runs, the linux pte has been zapped
720          * already but the page is still allocated until
721          * ->invalidate_page returns. So if we increase the sequence
722          * here the kvm page fault will notice if the spte can't be
723          * established because the page is going to be freed. If
724          * instead the kvm page fault establishes the spte before
725          * ->invalidate_page runs, kvm_unmap_hva will release it
726          * before returning.
727          *
728          * The sequence increase only need to be seen at spin_unlock
729          * time, and not at spin_lock time.
730          *
731          * Increasing the sequence after the spin_unlock would be
732          * unsafe because the kvm page fault could then establish the
733          * pte after kvm_unmap_hva returned, without noticing the page
734          * is going to be freed.
735          */
736         spin_lock(&kvm->mmu_lock);
737         kvm->mmu_notifier_seq++;
738         need_tlb_flush = kvm_unmap_hva(kvm, address);
739         spin_unlock(&kvm->mmu_lock);
740
741         /* we've to flush the tlb before the pages can be freed */
742         if (need_tlb_flush)
743                 kvm_flush_remote_tlbs(kvm);
744
745 }
746
747 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
748                                                     struct mm_struct *mm,
749                                                     unsigned long start,
750                                                     unsigned long end)
751 {
752         struct kvm *kvm = mmu_notifier_to_kvm(mn);
753         int need_tlb_flush = 0;
754
755         spin_lock(&kvm->mmu_lock);
756         /*
757          * The count increase must become visible at unlock time as no
758          * spte can be established without taking the mmu_lock and
759          * count is also read inside the mmu_lock critical section.
760          */
761         kvm->mmu_notifier_count++;
762         for (; start < end; start += PAGE_SIZE)
763                 need_tlb_flush |= kvm_unmap_hva(kvm, start);
764         spin_unlock(&kvm->mmu_lock);
765
766         /* we've to flush the tlb before the pages can be freed */
767         if (need_tlb_flush)
768                 kvm_flush_remote_tlbs(kvm);
769 }
770
771 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
772                                                   struct mm_struct *mm,
773                                                   unsigned long start,
774                                                   unsigned long end)
775 {
776         struct kvm *kvm = mmu_notifier_to_kvm(mn);
777
778         spin_lock(&kvm->mmu_lock);
779         /*
780          * This sequence increase will notify the kvm page fault that
781          * the page that is going to be mapped in the spte could have
782          * been freed.
783          */
784         kvm->mmu_notifier_seq++;
785         /*
786          * The above sequence increase must be visible before the
787          * below count decrease but both values are read by the kvm
788          * page fault under mmu_lock spinlock so we don't need to add
789          * a smb_wmb() here in between the two.
790          */
791         kvm->mmu_notifier_count--;
792         spin_unlock(&kvm->mmu_lock);
793
794         BUG_ON(kvm->mmu_notifier_count < 0);
795 }
796
797 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
798                                               struct mm_struct *mm,
799                                               unsigned long address)
800 {
801         struct kvm *kvm = mmu_notifier_to_kvm(mn);
802         int young;
803
804         spin_lock(&kvm->mmu_lock);
805         young = kvm_age_hva(kvm, address);
806         spin_unlock(&kvm->mmu_lock);
807
808         if (young)
809                 kvm_flush_remote_tlbs(kvm);
810
811         return young;
812 }
813
814 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
815                                      struct mm_struct *mm)
816 {
817         struct kvm *kvm = mmu_notifier_to_kvm(mn);
818         kvm_arch_flush_shadow(kvm);
819 }
820
821 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
822         .invalidate_page        = kvm_mmu_notifier_invalidate_page,
823         .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
824         .invalidate_range_end   = kvm_mmu_notifier_invalidate_range_end,
825         .clear_flush_young      = kvm_mmu_notifier_clear_flush_young,
826         .release                = kvm_mmu_notifier_release,
827 };
828 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
829
830 static struct kvm *kvm_create_vm(void)
831 {
832         struct kvm *kvm = kvm_arch_create_vm();
833 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
834         struct page *page;
835 #endif
836
837         if (IS_ERR(kvm))
838                 goto out;
839 #ifdef CONFIG_HAVE_KVM_IRQCHIP
840         INIT_LIST_HEAD(&kvm->irq_routing);
841         INIT_HLIST_HEAD(&kvm->mask_notifier_list);
842 #endif
843
844 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
845         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
846         if (!page) {
847                 kfree(kvm);
848                 return ERR_PTR(-ENOMEM);
849         }
850         kvm->coalesced_mmio_ring =
851                         (struct kvm_coalesced_mmio_ring *)page_address(page);
852 #endif
853
854 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
855         {
856                 int err;
857                 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
858                 err = mmu_notifier_register(&kvm->mmu_notifier, current->mm);
859                 if (err) {
860 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
861                         put_page(page);
862 #endif
863                         kfree(kvm);
864                         return ERR_PTR(err);
865                 }
866         }
867 #endif
868
869         kvm->mm = current->mm;
870         atomic_inc(&kvm->mm->mm_count);
871         spin_lock_init(&kvm->mmu_lock);
872         kvm_io_bus_init(&kvm->pio_bus);
873         mutex_init(&kvm->lock);
874         kvm_io_bus_init(&kvm->mmio_bus);
875         init_rwsem(&kvm->slots_lock);
876         atomic_set(&kvm->users_count, 1);
877         spin_lock(&kvm_lock);
878         list_add(&kvm->vm_list, &vm_list);
879         spin_unlock(&kvm_lock);
880 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
881         kvm_coalesced_mmio_init(kvm);
882 #endif
883 out:
884         return kvm;
885 }
886
887 /*
888  * Free any memory in @free but not in @dont.
889  */
890 static void kvm_free_physmem_slot(struct kvm_memory_slot *free,
891                                   struct kvm_memory_slot *dont)
892 {
893         if (!dont || free->rmap != dont->rmap)
894                 vfree(free->rmap);
895
896         if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
897                 vfree(free->dirty_bitmap);
898
899         if (!dont || free->lpage_info != dont->lpage_info)
900                 vfree(free->lpage_info);
901
902         free->npages = 0;
903         free->dirty_bitmap = NULL;
904         free->rmap = NULL;
905         free->lpage_info = NULL;
906 }
907
908 void kvm_free_physmem(struct kvm *kvm)
909 {
910         int i;
911
912         for (i = 0; i < kvm->nmemslots; ++i)
913                 kvm_free_physmem_slot(&kvm->memslots[i], NULL);
914 }
915
916 static void kvm_destroy_vm(struct kvm *kvm)
917 {
918         struct mm_struct *mm = kvm->mm;
919
920         kvm_arch_sync_events(kvm);
921         spin_lock(&kvm_lock);
922         list_del(&kvm->vm_list);
923         spin_unlock(&kvm_lock);
924         kvm_free_irq_routing(kvm);
925         kvm_io_bus_destroy(&kvm->pio_bus);
926         kvm_io_bus_destroy(&kvm->mmio_bus);
927 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
928         if (kvm->coalesced_mmio_ring != NULL)
929                 free_page((unsigned long)kvm->coalesced_mmio_ring);
930 #endif
931 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
932         mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
933 #endif
934         kvm_arch_destroy_vm(kvm);
935         mmdrop(mm);
936 }
937
938 void kvm_get_kvm(struct kvm *kvm)
939 {
940         atomic_inc(&kvm->users_count);
941 }
942 EXPORT_SYMBOL_GPL(kvm_get_kvm);
943
944 void kvm_put_kvm(struct kvm *kvm)
945 {
946         if (atomic_dec_and_test(&kvm->users_count))
947                 kvm_destroy_vm(kvm);
948 }
949 EXPORT_SYMBOL_GPL(kvm_put_kvm);
950
951
952 static int kvm_vm_release(struct inode *inode, struct file *filp)
953 {
954         struct kvm *kvm = filp->private_data;
955
956         kvm_put_kvm(kvm);
957         return 0;
958 }
959
960 /*
961  * Allocate some memory and give it an address in the guest physical address
962  * space.
963  *
964  * Discontiguous memory is allowed, mostly for framebuffers.
965  *
966  * Must be called holding mmap_sem for write.
967  */
968 int __kvm_set_memory_region(struct kvm *kvm,
969                             struct kvm_userspace_memory_region *mem,
970                             int user_alloc)
971 {
972         int r;
973         gfn_t base_gfn;
974         unsigned long npages;
975         int largepages;
976         unsigned long i;
977         struct kvm_memory_slot *memslot;
978         struct kvm_memory_slot old, new;
979
980         r = -EINVAL;
981         /* General sanity checks */
982         if (mem->memory_size & (PAGE_SIZE - 1))
983                 goto out;
984         if (mem->guest_phys_addr & (PAGE_SIZE - 1))
985                 goto out;
986         if (user_alloc && (mem->userspace_addr & (PAGE_SIZE - 1)))
987                 goto out;
988         if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
989                 goto out;
990         if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
991                 goto out;
992
993         memslot = &kvm->memslots[mem->slot];
994         base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
995         npages = mem->memory_size >> PAGE_SHIFT;
996
997         if (!npages)
998                 mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
999
1000         new = old = *memslot;
1001
1002         new.base_gfn = base_gfn;
1003         new.npages = npages;
1004         new.flags = mem->flags;
1005
1006         /* Disallow changing a memory slot's size. */
1007         r = -EINVAL;
1008         if (npages && old.npages && npages != old.npages)
1009                 goto out_free;
1010
1011         /* Check for overlaps */
1012         r = -EEXIST;
1013         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
1014                 struct kvm_memory_slot *s = &kvm->memslots[i];
1015
1016                 if (s == memslot || !s->npages)
1017                         continue;
1018                 if (!((base_gfn + npages <= s->base_gfn) ||
1019                       (base_gfn >= s->base_gfn + s->npages)))
1020                         goto out_free;
1021         }
1022
1023         /* Free page dirty bitmap if unneeded */
1024         if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1025                 new.dirty_bitmap = NULL;
1026
1027         r = -ENOMEM;
1028
1029         /* Allocate if a slot is being created */
1030 #ifndef CONFIG_S390
1031         if (npages && !new.rmap) {
1032                 new.rmap = vmalloc(npages * sizeof(struct page *));
1033
1034                 if (!new.rmap)
1035                         goto out_free;
1036
1037                 memset(new.rmap, 0, npages * sizeof(*new.rmap));
1038
1039                 new.user_alloc = user_alloc;
1040                 /*
1041                  * hva_to_rmmap() serialzies with the mmu_lock and to be
1042                  * safe it has to ignore memslots with !user_alloc &&
1043                  * !userspace_addr.
1044                  */
1045                 if (user_alloc)
1046                         new.userspace_addr = mem->userspace_addr;
1047                 else
1048                         new.userspace_addr = 0;
1049         }
1050         if (npages && !new.lpage_info) {
1051                 largepages = 1 + (base_gfn + npages - 1) / KVM_PAGES_PER_HPAGE;
1052                 largepages -= base_gfn / KVM_PAGES_PER_HPAGE;
1053
1054                 new.lpage_info = vmalloc(largepages * sizeof(*new.lpage_info));
1055
1056                 if (!new.lpage_info)
1057                         goto out_free;
1058
1059                 memset(new.lpage_info, 0, largepages * sizeof(*new.lpage_info));
1060
1061                 if (base_gfn % KVM_PAGES_PER_HPAGE)
1062                         new.lpage_info[0].write_count = 1;
1063                 if ((base_gfn+npages) % KVM_PAGES_PER_HPAGE)
1064                         new.lpage_info[largepages-1].write_count = 1;
1065         }
1066
1067         /* Allocate page dirty bitmap if needed */
1068         if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
1069                 unsigned dirty_bytes = ALIGN(npages, BITS_PER_LONG) / 8;
1070
1071                 new.dirty_bitmap = vmalloc(dirty_bytes);
1072                 if (!new.dirty_bitmap)
1073                         goto out_free;
1074                 memset(new.dirty_bitmap, 0, dirty_bytes);
1075         }
1076 #endif /* not defined CONFIG_S390 */
1077
1078         if (!npages)
1079                 kvm_arch_flush_shadow(kvm);
1080
1081         spin_lock(&kvm->mmu_lock);
1082         if (mem->slot >= kvm->nmemslots)
1083                 kvm->nmemslots = mem->slot + 1;
1084
1085         *memslot = new;
1086         spin_unlock(&kvm->mmu_lock);
1087
1088         r = kvm_arch_set_memory_region(kvm, mem, old, user_alloc);
1089         if (r) {
1090                 spin_lock(&kvm->mmu_lock);
1091                 *memslot = old;
1092                 spin_unlock(&kvm->mmu_lock);
1093                 goto out_free;
1094         }
1095
1096         kvm_free_physmem_slot(&old, npages ? &new : NULL);
1097         /* Slot deletion case: we have to update the current slot */
1098         if (!npages)
1099                 *memslot = old;
1100 #ifdef CONFIG_DMAR
1101         /* map the pages in iommu page table */
1102         r = kvm_iommu_map_pages(kvm, base_gfn, npages);
1103         if (r)
1104                 goto out;
1105 #endif
1106         return 0;
1107
1108 out_free:
1109         kvm_free_physmem_slot(&new, &old);
1110 out:
1111         return r;
1112
1113 }
1114 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1115
1116 int kvm_set_memory_region(struct kvm *kvm,
1117                           struct kvm_userspace_memory_region *mem,
1118                           int user_alloc)
1119 {
1120         int r;
1121
1122         down_write(&kvm->slots_lock);
1123         r = __kvm_set_memory_region(kvm, mem, user_alloc);
1124         up_write(&kvm->slots_lock);
1125         return r;
1126 }
1127 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1128
1129 int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1130                                    struct
1131                                    kvm_userspace_memory_region *mem,
1132                                    int user_alloc)
1133 {
1134         if (mem->slot >= KVM_MEMORY_SLOTS)
1135                 return -EINVAL;
1136         return kvm_set_memory_region(kvm, mem, user_alloc);
1137 }
1138
1139 int kvm_get_dirty_log(struct kvm *kvm,
1140                         struct kvm_dirty_log *log, int *is_dirty)
1141 {
1142         struct kvm_memory_slot *memslot;
1143         int r, i;
1144         int n;
1145         unsigned long any = 0;
1146
1147         r = -EINVAL;
1148         if (log->slot >= KVM_MEMORY_SLOTS)
1149                 goto out;
1150
1151         memslot = &kvm->memslots[log->slot];
1152         r = -ENOENT;
1153         if (!memslot->dirty_bitmap)
1154                 goto out;
1155
1156         n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1157
1158         for (i = 0; !any && i < n/sizeof(long); ++i)
1159                 any = memslot->dirty_bitmap[i];
1160
1161         r = -EFAULT;
1162         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1163                 goto out;
1164
1165         if (any)
1166                 *is_dirty = 1;
1167
1168         r = 0;
1169 out:
1170         return r;
1171 }
1172
1173 int is_error_page(struct page *page)
1174 {
1175         return page == bad_page;
1176 }
1177 EXPORT_SYMBOL_GPL(is_error_page);
1178
1179 int is_error_pfn(pfn_t pfn)
1180 {
1181         return pfn == bad_pfn;
1182 }
1183 EXPORT_SYMBOL_GPL(is_error_pfn);
1184
1185 static inline unsigned long bad_hva(void)
1186 {
1187         return PAGE_OFFSET;
1188 }
1189
1190 int kvm_is_error_hva(unsigned long addr)
1191 {
1192         return addr == bad_hva();
1193 }
1194 EXPORT_SYMBOL_GPL(kvm_is_error_hva);
1195
1196 struct kvm_memory_slot *gfn_to_memslot_unaliased(struct kvm *kvm, gfn_t gfn)
1197 {
1198         int i;
1199
1200         for (i = 0; i < kvm->nmemslots; ++i) {
1201                 struct kvm_memory_slot *memslot = &kvm->memslots[i];
1202
1203                 if (gfn >= memslot->base_gfn
1204                     && gfn < memslot->base_gfn + memslot->npages)
1205                         return memslot;
1206         }
1207         return NULL;
1208 }
1209 EXPORT_SYMBOL_GPL(gfn_to_memslot_unaliased);
1210
1211 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1212 {
1213         gfn = unalias_gfn(kvm, gfn);
1214         return gfn_to_memslot_unaliased(kvm, gfn);
1215 }
1216
1217 int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1218 {
1219         int i;
1220
1221         gfn = unalias_gfn(kvm, gfn);
1222         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
1223                 struct kvm_memory_slot *memslot = &kvm->memslots[i];
1224
1225                 if (gfn >= memslot->base_gfn
1226                     && gfn < memslot->base_gfn + memslot->npages)
1227                         return 1;
1228         }
1229         return 0;
1230 }
1231 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1232
1233 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1234 {
1235         struct kvm_memory_slot *slot;
1236
1237         gfn = unalias_gfn(kvm, gfn);
1238         slot = gfn_to_memslot_unaliased(kvm, gfn);
1239         if (!slot)
1240                 return bad_hva();
1241         return (slot->userspace_addr + (gfn - slot->base_gfn) * PAGE_SIZE);
1242 }
1243 EXPORT_SYMBOL_GPL(gfn_to_hva);
1244
1245 pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1246 {
1247         struct page *page[1];
1248         unsigned long addr;
1249         int npages;
1250         pfn_t pfn;
1251
1252         might_sleep();
1253
1254         addr = gfn_to_hva(kvm, gfn);
1255         if (kvm_is_error_hva(addr)) {
1256                 get_page(bad_page);
1257                 return page_to_pfn(bad_page);
1258         }
1259
1260         npages = get_user_pages_fast(addr, 1, 1, page);
1261
1262         if (unlikely(npages != 1)) {
1263                 struct vm_area_struct *vma;
1264
1265                 down_read(&current->mm->mmap_sem);
1266                 vma = find_vma(current->mm, addr);
1267
1268                 if (vma == NULL || addr < vma->vm_start ||
1269                     !(vma->vm_flags & VM_PFNMAP)) {
1270                         up_read(&current->mm->mmap_sem);
1271                         get_page(bad_page);
1272                         return page_to_pfn(bad_page);
1273                 }
1274
1275                 pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
1276                 up_read(&current->mm->mmap_sem);
1277                 BUG_ON(!kvm_is_mmio_pfn(pfn));
1278         } else
1279                 pfn = page_to_pfn(page[0]);
1280
1281         return pfn;
1282 }
1283
1284 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1285
1286 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1287 {
1288         pfn_t pfn;
1289
1290         pfn = gfn_to_pfn(kvm, gfn);
1291         if (!kvm_is_mmio_pfn(pfn))
1292                 return pfn_to_page(pfn);
1293
1294         WARN_ON(kvm_is_mmio_pfn(pfn));
1295
1296         get_page(bad_page);
1297         return bad_page;
1298 }
1299
1300 EXPORT_SYMBOL_GPL(gfn_to_page);
1301
1302 void kvm_release_page_clean(struct page *page)
1303 {
1304         kvm_release_pfn_clean(page_to_pfn(page));
1305 }
1306 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1307
1308 void kvm_release_pfn_clean(pfn_t pfn)
1309 {
1310         if (!kvm_is_mmio_pfn(pfn))
1311                 put_page(pfn_to_page(pfn));
1312 }
1313 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1314
1315 void kvm_release_page_dirty(struct page *page)
1316 {
1317         kvm_release_pfn_dirty(page_to_pfn(page));
1318 }
1319 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1320
1321 void kvm_release_pfn_dirty(pfn_t pfn)
1322 {
1323         kvm_set_pfn_dirty(pfn);
1324         kvm_release_pfn_clean(pfn);
1325 }
1326 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
1327
1328 void kvm_set_page_dirty(struct page *page)
1329 {
1330         kvm_set_pfn_dirty(page_to_pfn(page));
1331 }
1332 EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
1333
1334 void kvm_set_pfn_dirty(pfn_t pfn)
1335 {
1336         if (!kvm_is_mmio_pfn(pfn)) {
1337                 struct page *page = pfn_to_page(pfn);
1338                 if (!PageReserved(page))
1339                         SetPageDirty(page);
1340         }
1341 }
1342 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1343
1344 void kvm_set_pfn_accessed(pfn_t pfn)
1345 {
1346         if (!kvm_is_mmio_pfn(pfn))
1347                 mark_page_accessed(pfn_to_page(pfn));
1348 }
1349 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1350
1351 void kvm_get_pfn(pfn_t pfn)
1352 {
1353         if (!kvm_is_mmio_pfn(pfn))
1354                 get_page(pfn_to_page(pfn));
1355 }
1356 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1357
1358 static int next_segment(unsigned long len, int offset)
1359 {
1360         if (len > PAGE_SIZE - offset)
1361                 return PAGE_SIZE - offset;
1362         else
1363                 return len;
1364 }
1365
1366 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1367                         int len)
1368 {
1369         int r;
1370         unsigned long addr;
1371
1372         addr = gfn_to_hva(kvm, gfn);
1373         if (kvm_is_error_hva(addr))
1374                 return -EFAULT;
1375         r = copy_from_user(data, (void __user *)addr + offset, len);
1376         if (r)
1377                 return -EFAULT;
1378         return 0;
1379 }
1380 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1381
1382 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1383 {
1384         gfn_t gfn = gpa >> PAGE_SHIFT;
1385         int seg;
1386         int offset = offset_in_page(gpa);
1387         int ret;
1388
1389         while ((seg = next_segment(len, offset)) != 0) {
1390                 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1391                 if (ret < 0)
1392                         return ret;
1393                 offset = 0;
1394                 len -= seg;
1395                 data += seg;
1396                 ++gfn;
1397         }
1398         return 0;
1399 }
1400 EXPORT_SYMBOL_GPL(kvm_read_guest);
1401
1402 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1403                           unsigned long len)
1404 {
1405         int r;
1406         unsigned long addr;
1407         gfn_t gfn = gpa >> PAGE_SHIFT;
1408         int offset = offset_in_page(gpa);
1409
1410         addr = gfn_to_hva(kvm, gfn);
1411         if (kvm_is_error_hva(addr))
1412                 return -EFAULT;
1413         pagefault_disable();
1414         r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1415         pagefault_enable();
1416         if (r)
1417                 return -EFAULT;
1418         return 0;
1419 }
1420 EXPORT_SYMBOL(kvm_read_guest_atomic);
1421
1422 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
1423                          int offset, int len)
1424 {
1425         int r;
1426         unsigned long addr;
1427
1428         addr = gfn_to_hva(kvm, gfn);
1429         if (kvm_is_error_hva(addr))
1430                 return -EFAULT;
1431         r = copy_to_user((void __user *)addr + offset, data, len);
1432         if (r)
1433                 return -EFAULT;
1434         mark_page_dirty(kvm, gfn);
1435         return 0;
1436 }
1437 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1438
1439 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1440                     unsigned long len)
1441 {
1442         gfn_t gfn = gpa >> PAGE_SHIFT;
1443         int seg;
1444         int offset = offset_in_page(gpa);
1445         int ret;
1446
1447         while ((seg = next_segment(len, offset)) != 0) {
1448                 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
1449                 if (ret < 0)
1450                         return ret;
1451                 offset = 0;
1452                 len -= seg;
1453                 data += seg;
1454                 ++gfn;
1455         }
1456         return 0;
1457 }
1458
1459 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
1460 {
1461         return kvm_write_guest_page(kvm, gfn, empty_zero_page, offset, len);
1462 }
1463 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
1464
1465 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
1466 {
1467         gfn_t gfn = gpa >> PAGE_SHIFT;
1468         int seg;
1469         int offset = offset_in_page(gpa);
1470         int ret;
1471
1472         while ((seg = next_segment(len, offset)) != 0) {
1473                 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
1474                 if (ret < 0)
1475                         return ret;
1476                 offset = 0;
1477                 len -= seg;
1478                 ++gfn;
1479         }
1480         return 0;
1481 }
1482 EXPORT_SYMBOL_GPL(kvm_clear_guest);
1483
1484 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
1485 {
1486         struct kvm_memory_slot *memslot;
1487
1488         gfn = unalias_gfn(kvm, gfn);
1489         memslot = gfn_to_memslot_unaliased(kvm, gfn);
1490         if (memslot && memslot->dirty_bitmap) {
1491                 unsigned long rel_gfn = gfn - memslot->base_gfn;
1492
1493                 /* avoid RMW */
1494                 if (!test_bit(rel_gfn, memslot->dirty_bitmap))
1495                         set_bit(rel_gfn, memslot->dirty_bitmap);
1496         }
1497 }
1498
1499 /*
1500  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
1501  */
1502 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
1503 {
1504         DEFINE_WAIT(wait);
1505
1506         for (;;) {
1507                 prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
1508
1509                 if (kvm_cpu_has_interrupt(vcpu) ||
1510                     kvm_cpu_has_pending_timer(vcpu) ||
1511                     kvm_arch_vcpu_runnable(vcpu)) {
1512                         set_bit(KVM_REQ_UNHALT, &vcpu->requests);
1513                         break;
1514                 }
1515                 if (signal_pending(current))
1516                         break;
1517
1518                 vcpu_put(vcpu);
1519                 schedule();
1520                 vcpu_load(vcpu);
1521         }
1522
1523         finish_wait(&vcpu->wq, &wait);
1524 }
1525
1526 void kvm_resched(struct kvm_vcpu *vcpu)
1527 {
1528         if (!need_resched())
1529                 return;
1530         cond_resched();
1531 }
1532 EXPORT_SYMBOL_GPL(kvm_resched);
1533
1534 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1535 {
1536         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
1537         struct page *page;
1538
1539         if (vmf->pgoff == 0)
1540                 page = virt_to_page(vcpu->run);
1541 #ifdef CONFIG_X86
1542         else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
1543                 page = virt_to_page(vcpu->arch.pio_data);
1544 #endif
1545 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1546         else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
1547                 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
1548 #endif
1549         else
1550                 return VM_FAULT_SIGBUS;
1551         get_page(page);
1552         vmf->page = page;
1553         return 0;
1554 }
1555
1556 static struct vm_operations_struct kvm_vcpu_vm_ops = {
1557         .fault = kvm_vcpu_fault,
1558 };
1559
1560 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
1561 {
1562         vma->vm_ops = &kvm_vcpu_vm_ops;
1563         return 0;
1564 }
1565
1566 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
1567 {
1568         struct kvm_vcpu *vcpu = filp->private_data;
1569
1570         kvm_put_kvm(vcpu->kvm);
1571         return 0;
1572 }
1573
1574 static struct file_operations kvm_vcpu_fops = {
1575         .release        = kvm_vcpu_release,
1576         .unlocked_ioctl = kvm_vcpu_ioctl,
1577         .compat_ioctl   = kvm_vcpu_ioctl,
1578         .mmap           = kvm_vcpu_mmap,
1579 };
1580
1581 /*
1582  * Allocates an inode for the vcpu.
1583  */
1584 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
1585 {
1586         int fd = anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, 0);
1587         if (fd < 0)
1588                 kvm_put_kvm(vcpu->kvm);
1589         return fd;
1590 }
1591
1592 /*
1593  * Creates some virtual cpus.  Good luck creating more than one.
1594  */
1595 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, int n)
1596 {
1597         int r;
1598         struct kvm_vcpu *vcpu;
1599
1600         if (!valid_vcpu(n))
1601                 return -EINVAL;
1602
1603         vcpu = kvm_arch_vcpu_create(kvm, n);
1604         if (IS_ERR(vcpu))
1605                 return PTR_ERR(vcpu);
1606
1607         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
1608
1609         r = kvm_arch_vcpu_setup(vcpu);
1610         if (r)
1611                 return r;
1612
1613         mutex_lock(&kvm->lock);
1614         if (kvm->vcpus[n]) {
1615                 r = -EEXIST;
1616                 goto vcpu_destroy;
1617         }
1618         kvm->vcpus[n] = vcpu;
1619         mutex_unlock(&kvm->lock);
1620
1621         /* Now it's all set up, let userspace reach it */
1622         kvm_get_kvm(kvm);
1623         r = create_vcpu_fd(vcpu);
1624         if (r < 0)
1625                 goto unlink;
1626         return r;
1627
1628 unlink:
1629         mutex_lock(&kvm->lock);
1630         kvm->vcpus[n] = NULL;
1631 vcpu_destroy:
1632         mutex_unlock(&kvm->lock);
1633         kvm_arch_vcpu_destroy(vcpu);
1634         return r;
1635 }
1636
1637 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
1638 {
1639         if (sigset) {
1640                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
1641                 vcpu->sigset_active = 1;
1642                 vcpu->sigset = *sigset;
1643         } else
1644                 vcpu->sigset_active = 0;
1645         return 0;
1646 }
1647
1648 #ifdef __KVM_HAVE_MSIX
1649 static int kvm_vm_ioctl_set_msix_nr(struct kvm *kvm,
1650                                     struct kvm_assigned_msix_nr *entry_nr)
1651 {
1652         int r = 0;
1653         struct kvm_assigned_dev_kernel *adev;
1654
1655         mutex_lock(&kvm->lock);
1656
1657         adev = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
1658                                       entry_nr->assigned_dev_id);
1659         if (!adev) {
1660                 r = -EINVAL;
1661                 goto msix_nr_out;
1662         }
1663
1664         if (adev->entries_nr == 0) {
1665                 adev->entries_nr = entry_nr->entry_nr;
1666                 if (adev->entries_nr == 0 ||
1667                     adev->entries_nr >= KVM_MAX_MSIX_PER_DEV) {
1668                         r = -EINVAL;
1669                         goto msix_nr_out;
1670                 }
1671
1672                 adev->host_msix_entries = kzalloc(sizeof(struct msix_entry) *
1673                                                 entry_nr->entry_nr,
1674                                                 GFP_KERNEL);
1675                 if (!adev->host_msix_entries) {
1676                         r = -ENOMEM;
1677                         goto msix_nr_out;
1678                 }
1679                 adev->guest_msix_entries = kzalloc(
1680                                 sizeof(struct kvm_guest_msix_entry) *
1681                                 entry_nr->entry_nr, GFP_KERNEL);
1682                 if (!adev->guest_msix_entries) {
1683                         kfree(adev->host_msix_entries);
1684                         r = -ENOMEM;
1685                         goto msix_nr_out;
1686                 }
1687         } else /* Not allowed set MSI-X number twice */
1688                 r = -EINVAL;
1689 msix_nr_out:
1690         mutex_unlock(&kvm->lock);
1691         return r;
1692 }
1693
1694 static int kvm_vm_ioctl_set_msix_entry(struct kvm *kvm,
1695                                        struct kvm_assigned_msix_entry *entry)
1696 {
1697         int r = 0, i;
1698         struct kvm_assigned_dev_kernel *adev;
1699
1700         mutex_lock(&kvm->lock);
1701
1702         adev = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
1703                                       entry->assigned_dev_id);
1704
1705         if (!adev) {
1706                 r = -EINVAL;
1707                 goto msix_entry_out;
1708         }
1709
1710         for (i = 0; i < adev->entries_nr; i++)
1711                 if (adev->guest_msix_entries[i].vector == 0 ||
1712                     adev->guest_msix_entries[i].entry == entry->entry) {
1713                         adev->guest_msix_entries[i].entry = entry->entry;
1714                         adev->guest_msix_entries[i].vector = entry->gsi;
1715                         adev->host_msix_entries[i].entry = entry->entry;
1716                         break;
1717                 }
1718         if (i == adev->entries_nr) {
1719                 r = -ENOSPC;
1720                 goto msix_entry_out;
1721         }
1722
1723 msix_entry_out:
1724         mutex_unlock(&kvm->lock);
1725
1726         return r;
1727 }
1728 #endif
1729
1730 static long kvm_vcpu_ioctl(struct file *filp,
1731                            unsigned int ioctl, unsigned long arg)
1732 {
1733         struct kvm_vcpu *vcpu = filp->private_data;
1734         void __user *argp = (void __user *)arg;
1735         int r;
1736         struct kvm_fpu *fpu = NULL;
1737         struct kvm_sregs *kvm_sregs = NULL;
1738
1739         if (vcpu->kvm->mm != current->mm)
1740                 return -EIO;
1741         switch (ioctl) {
1742         case KVM_RUN:
1743                 r = -EINVAL;
1744                 if (arg)
1745                         goto out;
1746                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
1747                 break;
1748         case KVM_GET_REGS: {
1749                 struct kvm_regs *kvm_regs;
1750
1751                 r = -ENOMEM;
1752                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1753                 if (!kvm_regs)
1754                         goto out;
1755                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
1756                 if (r)
1757                         goto out_free1;
1758                 r = -EFAULT;
1759                 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
1760                         goto out_free1;
1761                 r = 0;
1762 out_free1:
1763                 kfree(kvm_regs);
1764                 break;
1765         }
1766         case KVM_SET_REGS: {
1767                 struct kvm_regs *kvm_regs;
1768
1769                 r = -ENOMEM;
1770                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1771                 if (!kvm_regs)
1772                         goto out;
1773                 r = -EFAULT;
1774                 if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs)))
1775                         goto out_free2;
1776                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
1777                 if (r)
1778                         goto out_free2;
1779                 r = 0;
1780 out_free2:
1781                 kfree(kvm_regs);
1782                 break;
1783         }
1784         case KVM_GET_SREGS: {
1785                 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1786                 r = -ENOMEM;
1787                 if (!kvm_sregs)
1788                         goto out;
1789                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
1790                 if (r)
1791                         goto out;
1792                 r = -EFAULT;
1793                 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
1794                         goto out;
1795                 r = 0;
1796                 break;
1797         }
1798         case KVM_SET_SREGS: {
1799                 kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1800                 r = -ENOMEM;
1801                 if (!kvm_sregs)
1802                         goto out;
1803                 r = -EFAULT;
1804                 if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs)))
1805                         goto out;
1806                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
1807                 if (r)
1808                         goto out;
1809                 r = 0;
1810                 break;
1811         }
1812         case KVM_GET_MP_STATE: {
1813                 struct kvm_mp_state mp_state;
1814
1815                 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
1816                 if (r)
1817                         goto out;
1818                 r = -EFAULT;
1819                 if (copy_to_user(argp, &mp_state, sizeof mp_state))
1820                         goto out;
1821                 r = 0;
1822                 break;
1823         }
1824         case KVM_SET_MP_STATE: {
1825                 struct kvm_mp_state mp_state;
1826
1827                 r = -EFAULT;
1828                 if (copy_from_user(&mp_state, argp, sizeof mp_state))
1829                         goto out;
1830                 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
1831                 if (r)
1832                         goto out;
1833                 r = 0;
1834                 break;
1835         }
1836         case KVM_TRANSLATE: {
1837                 struct kvm_translation tr;
1838
1839                 r = -EFAULT;
1840                 if (copy_from_user(&tr, argp, sizeof tr))
1841                         goto out;
1842                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
1843                 if (r)
1844                         goto out;
1845                 r = -EFAULT;
1846                 if (copy_to_user(argp, &tr, sizeof tr))
1847                         goto out;
1848                 r = 0;
1849                 break;
1850         }
1851         case KVM_SET_GUEST_DEBUG: {
1852                 struct kvm_guest_debug dbg;
1853
1854                 r = -EFAULT;
1855                 if (copy_from_user(&dbg, argp, sizeof dbg))
1856                         goto out;
1857                 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
1858                 if (r)
1859                         goto out;
1860                 r = 0;
1861                 break;
1862         }
1863         case KVM_SET_SIGNAL_MASK: {
1864                 struct kvm_signal_mask __user *sigmask_arg = argp;
1865                 struct kvm_signal_mask kvm_sigmask;
1866                 sigset_t sigset, *p;
1867
1868                 p = NULL;
1869                 if (argp) {
1870                         r = -EFAULT;
1871                         if (copy_from_user(&kvm_sigmask, argp,
1872                                            sizeof kvm_sigmask))
1873                                 goto out;
1874                         r = -EINVAL;
1875                         if (kvm_sigmask.len != sizeof sigset)
1876                                 goto out;
1877                         r = -EFAULT;
1878                         if (copy_from_user(&sigset, sigmask_arg->sigset,
1879                                            sizeof sigset))
1880                                 goto out;
1881                         p = &sigset;
1882                 }
1883                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
1884                 break;
1885         }
1886         case KVM_GET_FPU: {
1887                 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1888                 r = -ENOMEM;
1889                 if (!fpu)
1890                         goto out;
1891                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
1892                 if (r)
1893                         goto out;
1894                 r = -EFAULT;
1895                 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
1896                         goto out;
1897                 r = 0;
1898                 break;
1899         }
1900         case KVM_SET_FPU: {
1901                 fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1902                 r = -ENOMEM;
1903                 if (!fpu)
1904                         goto out;
1905                 r = -EFAULT;
1906                 if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu)))
1907                         goto out;
1908                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
1909                 if (r)
1910                         goto out;
1911                 r = 0;
1912                 break;
1913         }
1914         default:
1915                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1916         }
1917 out:
1918         kfree(fpu);
1919         kfree(kvm_sregs);
1920         return r;
1921 }
1922
1923 static long kvm_vm_ioctl(struct file *filp,
1924                            unsigned int ioctl, unsigned long arg)
1925 {
1926         struct kvm *kvm = filp->private_data;
1927         void __user *argp = (void __user *)arg;
1928         int r;
1929
1930         if (kvm->mm != current->mm)
1931                 return -EIO;
1932         switch (ioctl) {
1933         case KVM_CREATE_VCPU:
1934                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
1935                 if (r < 0)
1936                         goto out;
1937                 break;
1938         case KVM_SET_USER_MEMORY_REGION: {
1939                 struct kvm_userspace_memory_region kvm_userspace_mem;
1940
1941                 r = -EFAULT;
1942                 if (copy_from_user(&kvm_userspace_mem, argp,
1943                                                 sizeof kvm_userspace_mem))
1944                         goto out;
1945
1946                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
1947                 if (r)
1948                         goto out;
1949                 break;
1950         }
1951         case KVM_GET_DIRTY_LOG: {
1952                 struct kvm_dirty_log log;
1953
1954                 r = -EFAULT;
1955                 if (copy_from_user(&log, argp, sizeof log))
1956                         goto out;
1957                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
1958                 if (r)
1959                         goto out;
1960                 break;
1961         }
1962 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1963         case KVM_REGISTER_COALESCED_MMIO: {
1964                 struct kvm_coalesced_mmio_zone zone;
1965                 r = -EFAULT;
1966                 if (copy_from_user(&zone, argp, sizeof zone))
1967                         goto out;
1968                 r = -ENXIO;
1969                 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
1970                 if (r)
1971                         goto out;
1972                 r = 0;
1973                 break;
1974         }
1975         case KVM_UNREGISTER_COALESCED_MMIO: {
1976                 struct kvm_coalesced_mmio_zone zone;
1977                 r = -EFAULT;
1978                 if (copy_from_user(&zone, argp, sizeof zone))
1979                         goto out;
1980                 r = -ENXIO;
1981                 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
1982                 if (r)
1983                         goto out;
1984                 r = 0;
1985                 break;
1986         }
1987 #endif
1988 #ifdef KVM_CAP_DEVICE_ASSIGNMENT
1989         case KVM_ASSIGN_PCI_DEVICE: {
1990                 struct kvm_assigned_pci_dev assigned_dev;
1991
1992                 r = -EFAULT;
1993                 if (copy_from_user(&assigned_dev, argp, sizeof assigned_dev))
1994                         goto out;
1995                 r = kvm_vm_ioctl_assign_device(kvm, &assigned_dev);
1996                 if (r)
1997                         goto out;
1998                 break;
1999         }
2000         case KVM_ASSIGN_IRQ: {
2001                 struct kvm_assigned_irq assigned_irq;
2002
2003                 r = -EFAULT;
2004                 if (copy_from_user(&assigned_irq, argp, sizeof assigned_irq))
2005                         goto out;
2006                 r = kvm_vm_ioctl_assign_irq(kvm, &assigned_irq);
2007                 if (r)
2008                         goto out;
2009                 break;
2010         }
2011 #endif
2012 #ifdef KVM_CAP_DEVICE_DEASSIGNMENT
2013         case KVM_DEASSIGN_PCI_DEVICE: {
2014                 struct kvm_assigned_pci_dev assigned_dev;
2015
2016                 r = -EFAULT;
2017                 if (copy_from_user(&assigned_dev, argp, sizeof assigned_dev))
2018                         goto out;
2019                 r = kvm_vm_ioctl_deassign_device(kvm, &assigned_dev);
2020                 if (r)
2021                         goto out;
2022                 break;
2023         }
2024 #endif
2025 #ifdef KVM_CAP_IRQ_ROUTING
2026         case KVM_SET_GSI_ROUTING: {
2027                 struct kvm_irq_routing routing;
2028                 struct kvm_irq_routing __user *urouting;
2029                 struct kvm_irq_routing_entry *entries;
2030
2031                 r = -EFAULT;
2032                 if (copy_from_user(&routing, argp, sizeof(routing)))
2033                         goto out;
2034                 r = -EINVAL;
2035                 if (routing.nr >= KVM_MAX_IRQ_ROUTES)
2036                         goto out;
2037                 if (routing.flags)
2038                         goto out;
2039                 r = -ENOMEM;
2040                 entries = vmalloc(routing.nr * sizeof(*entries));
2041                 if (!entries)
2042                         goto out;
2043                 r = -EFAULT;
2044                 urouting = argp;
2045                 if (copy_from_user(entries, urouting->entries,
2046                                    routing.nr * sizeof(*entries)))
2047                         goto out_free_irq_routing;
2048                 r = kvm_set_irq_routing(kvm, entries, routing.nr,
2049                                         routing.flags);
2050         out_free_irq_routing:
2051                 vfree(entries);
2052                 break;
2053         }
2054 #ifdef __KVM_HAVE_MSIX
2055         case KVM_ASSIGN_SET_MSIX_NR: {
2056                 struct kvm_assigned_msix_nr entry_nr;
2057                 r = -EFAULT;
2058                 if (copy_from_user(&entry_nr, argp, sizeof entry_nr))
2059                         goto out;
2060                 r = kvm_vm_ioctl_set_msix_nr(kvm, &entry_nr);
2061                 if (r)
2062                         goto out;
2063                 break;
2064         }
2065         case KVM_ASSIGN_SET_MSIX_ENTRY: {
2066                 struct kvm_assigned_msix_entry entry;
2067                 r = -EFAULT;
2068                 if (copy_from_user(&entry, argp, sizeof entry))
2069                         goto out;
2070                 r = kvm_vm_ioctl_set_msix_entry(kvm, &entry);
2071                 if (r)
2072                         goto out;
2073                 break;
2074         }
2075 #endif
2076 #endif /* KVM_CAP_IRQ_ROUTING */
2077         default:
2078                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
2079         }
2080 out:
2081         return r;
2082 }
2083
2084 static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2085 {
2086         struct page *page[1];
2087         unsigned long addr;
2088         int npages;
2089         gfn_t gfn = vmf->pgoff;
2090         struct kvm *kvm = vma->vm_file->private_data;
2091
2092         addr = gfn_to_hva(kvm, gfn);
2093         if (kvm_is_error_hva(addr))
2094                 return VM_FAULT_SIGBUS;
2095
2096         npages = get_user_pages(current, current->mm, addr, 1, 1, 0, page,
2097                                 NULL);
2098         if (unlikely(npages != 1))
2099                 return VM_FAULT_SIGBUS;
2100
2101         vmf->page = page[0];
2102         return 0;
2103 }
2104
2105 static struct vm_operations_struct kvm_vm_vm_ops = {
2106         .fault = kvm_vm_fault,
2107 };
2108
2109 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
2110 {
2111         vma->vm_ops = &kvm_vm_vm_ops;
2112         return 0;
2113 }
2114
2115 static struct file_operations kvm_vm_fops = {
2116         .release        = kvm_vm_release,
2117         .unlocked_ioctl = kvm_vm_ioctl,
2118         .compat_ioctl   = kvm_vm_ioctl,
2119         .mmap           = kvm_vm_mmap,
2120 };
2121
2122 static int kvm_dev_ioctl_create_vm(void)
2123 {
2124         int fd;
2125         struct kvm *kvm;
2126
2127         kvm = kvm_create_vm();
2128         if (IS_ERR(kvm))
2129                 return PTR_ERR(kvm);
2130         fd = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, 0);
2131         if (fd < 0)
2132                 kvm_put_kvm(kvm);
2133
2134         return fd;
2135 }
2136
2137 static long kvm_dev_ioctl_check_extension_generic(long arg)
2138 {
2139         switch (arg) {
2140         case KVM_CAP_USER_MEMORY:
2141         case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
2142         case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
2143                 return 1;
2144 #ifdef CONFIG_HAVE_KVM_IRQCHIP
2145         case KVM_CAP_IRQ_ROUTING:
2146                 return KVM_MAX_IRQ_ROUTES;
2147 #endif
2148         default:
2149                 break;
2150         }
2151         return kvm_dev_ioctl_check_extension(arg);
2152 }
2153
2154 static long kvm_dev_ioctl(struct file *filp,
2155                           unsigned int ioctl, unsigned long arg)
2156 {
2157         long r = -EINVAL;
2158
2159         switch (ioctl) {
2160         case KVM_GET_API_VERSION:
2161                 r = -EINVAL;
2162                 if (arg)
2163                         goto out;
2164                 r = KVM_API_VERSION;
2165                 break;
2166         case KVM_CREATE_VM:
2167                 r = -EINVAL;
2168                 if (arg)
2169                         goto out;
2170                 r = kvm_dev_ioctl_create_vm();
2171                 break;
2172         case KVM_CHECK_EXTENSION:
2173                 r = kvm_dev_ioctl_check_extension_generic(arg);
2174                 break;
2175         case KVM_GET_VCPU_MMAP_SIZE:
2176                 r = -EINVAL;
2177                 if (arg)
2178                         goto out;
2179                 r = PAGE_SIZE;     /* struct kvm_run */
2180 #ifdef CONFIG_X86
2181                 r += PAGE_SIZE;    /* pio data page */
2182 #endif
2183 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2184                 r += PAGE_SIZE;    /* coalesced mmio ring page */
2185 #endif
2186                 break;
2187         case KVM_TRACE_ENABLE:
2188         case KVM_TRACE_PAUSE:
2189         case KVM_TRACE_DISABLE:
2190                 r = kvm_trace_ioctl(ioctl, arg);
2191                 break;
2192         default:
2193                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
2194         }
2195 out:
2196         return r;
2197 }
2198
2199 static struct file_operations kvm_chardev_ops = {
2200         .unlocked_ioctl = kvm_dev_ioctl,
2201         .compat_ioctl   = kvm_dev_ioctl,
2202 };
2203
2204 static struct miscdevice kvm_dev = {
2205         KVM_MINOR,
2206         "kvm",
2207         &kvm_chardev_ops,
2208 };
2209
2210 static void hardware_enable(void *junk)
2211 {
2212         int cpu = raw_smp_processor_id();
2213
2214         if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
2215                 return;
2216         cpumask_set_cpu(cpu, cpus_hardware_enabled);
2217         kvm_arch_hardware_enable(NULL);
2218 }
2219
2220 static void hardware_disable(void *junk)
2221 {
2222         int cpu = raw_smp_processor_id();
2223
2224         if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
2225                 return;
2226         cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2227         kvm_arch_hardware_disable(NULL);
2228 }
2229
2230 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2231                            void *v)
2232 {
2233         int cpu = (long)v;
2234
2235         val &= ~CPU_TASKS_FROZEN;
2236         switch (val) {
2237         case CPU_DYING:
2238                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2239                        cpu);
2240                 hardware_disable(NULL);
2241                 break;
2242         case CPU_UP_CANCELED:
2243                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2244                        cpu);
2245                 smp_call_function_single(cpu, hardware_disable, NULL, 1);
2246                 break;
2247         case CPU_ONLINE:
2248                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2249                        cpu);
2250                 smp_call_function_single(cpu, hardware_enable, NULL, 1);
2251                 break;
2252         }
2253         return NOTIFY_OK;
2254 }
2255
2256
2257 asmlinkage void kvm_handle_fault_on_reboot(void)
2258 {
2259         if (kvm_rebooting)
2260                 /* spin while reset goes on */
2261                 while (true)
2262                         ;
2263         /* Fault while not rebooting.  We want the trace. */
2264         BUG();
2265 }
2266 EXPORT_SYMBOL_GPL(kvm_handle_fault_on_reboot);
2267
2268 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2269                       void *v)
2270 {
2271         if (val == SYS_RESTART) {
2272                 /*
2273                  * Some (well, at least mine) BIOSes hang on reboot if
2274                  * in vmx root mode.
2275                  */
2276                 printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2277                 kvm_rebooting = true;
2278                 on_each_cpu(hardware_disable, NULL, 1);
2279         }
2280         return NOTIFY_OK;
2281 }
2282
2283 static struct notifier_block kvm_reboot_notifier = {
2284         .notifier_call = kvm_reboot,
2285         .priority = 0,
2286 };
2287
2288 void kvm_io_bus_init(struct kvm_io_bus *bus)
2289 {
2290         memset(bus, 0, sizeof(*bus));
2291 }
2292
2293 void kvm_io_bus_destroy(struct kvm_io_bus *bus)
2294 {
2295         int i;
2296
2297         for (i = 0; i < bus->dev_count; i++) {
2298                 struct kvm_io_device *pos = bus->devs[i];
2299
2300                 kvm_iodevice_destructor(pos);
2301         }
2302 }
2303
2304 struct kvm_io_device *kvm_io_bus_find_dev(struct kvm_io_bus *bus,
2305                                           gpa_t addr, int len, int is_write)
2306 {
2307         int i;
2308
2309         for (i = 0; i < bus->dev_count; i++) {
2310                 struct kvm_io_device *pos = bus->devs[i];
2311
2312                 if (pos->in_range(pos, addr, len, is_write))
2313                         return pos;
2314         }
2315
2316         return NULL;
2317 }
2318
2319 void kvm_io_bus_register_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev)
2320 {
2321         BUG_ON(bus->dev_count > (NR_IOBUS_DEVS-1));
2322
2323         bus->devs[bus->dev_count++] = dev;
2324 }
2325
2326 static struct notifier_block kvm_cpu_notifier = {
2327         .notifier_call = kvm_cpu_hotplug,
2328         .priority = 20, /* must be > scheduler priority */
2329 };
2330
2331 static int vm_stat_get(void *_offset, u64 *val)
2332 {
2333         unsigned offset = (long)_offset;
2334         struct kvm *kvm;
2335
2336         *val = 0;
2337         spin_lock(&kvm_lock);
2338         list_for_each_entry(kvm, &vm_list, vm_list)
2339                 *val += *(u32 *)((void *)kvm + offset);
2340         spin_unlock(&kvm_lock);
2341         return 0;
2342 }
2343
2344 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
2345
2346 static int vcpu_stat_get(void *_offset, u64 *val)
2347 {
2348         unsigned offset = (long)_offset;
2349         struct kvm *kvm;
2350         struct kvm_vcpu *vcpu;
2351         int i;
2352
2353         *val = 0;
2354         spin_lock(&kvm_lock);
2355         list_for_each_entry(kvm, &vm_list, vm_list)
2356                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
2357                         vcpu = kvm->vcpus[i];
2358                         if (vcpu)
2359                                 *val += *(u32 *)((void *)vcpu + offset);
2360                 }
2361         spin_unlock(&kvm_lock);
2362         return 0;
2363 }
2364
2365 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
2366
2367 static struct file_operations *stat_fops[] = {
2368         [KVM_STAT_VCPU] = &vcpu_stat_fops,
2369         [KVM_STAT_VM]   = &vm_stat_fops,
2370 };
2371
2372 static void kvm_init_debug(void)
2373 {
2374         struct kvm_stats_debugfs_item *p;
2375
2376         kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
2377         for (p = debugfs_entries; p->name; ++p)
2378                 p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
2379                                                 (void *)(long)p->offset,
2380                                                 stat_fops[p->kind]);
2381 }
2382
2383 static void kvm_exit_debug(void)
2384 {
2385         struct kvm_stats_debugfs_item *p;
2386
2387         for (p = debugfs_entries; p->name; ++p)
2388                 debugfs_remove(p->dentry);
2389         debugfs_remove(kvm_debugfs_dir);
2390 }
2391
2392 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
2393 {
2394         hardware_disable(NULL);
2395         return 0;
2396 }
2397
2398 static int kvm_resume(struct sys_device *dev)
2399 {
2400         hardware_enable(NULL);
2401         return 0;
2402 }
2403
2404 static struct sysdev_class kvm_sysdev_class = {
2405         .name = "kvm",
2406         .suspend = kvm_suspend,
2407         .resume = kvm_resume,
2408 };
2409
2410 static struct sys_device kvm_sysdev = {
2411         .id = 0,
2412         .cls = &kvm_sysdev_class,
2413 };
2414
2415 struct page *bad_page;
2416 pfn_t bad_pfn;
2417
2418 static inline
2419 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
2420 {
2421         return container_of(pn, struct kvm_vcpu, preempt_notifier);
2422 }
2423
2424 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
2425 {
2426         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2427
2428         kvm_arch_vcpu_load(vcpu, cpu);
2429 }
2430
2431 static void kvm_sched_out(struct preempt_notifier *pn,
2432                           struct task_struct *next)
2433 {
2434         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2435
2436         kvm_arch_vcpu_put(vcpu);
2437 }
2438
2439 int kvm_init(void *opaque, unsigned int vcpu_size,
2440                   struct module *module)
2441 {
2442         int r;
2443         int cpu;
2444
2445         kvm_init_debug();
2446
2447         r = kvm_arch_init(opaque);
2448         if (r)
2449                 goto out_fail;
2450
2451         bad_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2452
2453         if (bad_page == NULL) {
2454                 r = -ENOMEM;
2455                 goto out;
2456         }
2457
2458         bad_pfn = page_to_pfn(bad_page);
2459
2460         if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
2461                 r = -ENOMEM;
2462                 goto out_free_0;
2463         }
2464         cpumask_clear(cpus_hardware_enabled);
2465
2466         r = kvm_arch_hardware_setup();
2467         if (r < 0)
2468                 goto out_free_0a;
2469
2470         for_each_online_cpu(cpu) {
2471                 smp_call_function_single(cpu,
2472                                 kvm_arch_check_processor_compat,
2473                                 &r, 1);
2474                 if (r < 0)
2475                         goto out_free_1;
2476         }
2477
2478         on_each_cpu(hardware_enable, NULL, 1);
2479         r = register_cpu_notifier(&kvm_cpu_notifier);
2480         if (r)
2481                 goto out_free_2;
2482         register_reboot_notifier(&kvm_reboot_notifier);
2483
2484         r = sysdev_class_register(&kvm_sysdev_class);
2485         if (r)
2486                 goto out_free_3;
2487
2488         r = sysdev_register(&kvm_sysdev);
2489         if (r)
2490                 goto out_free_4;
2491
2492         /* A kmem cache lets us meet the alignment requirements of fx_save. */
2493         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size,
2494                                            __alignof__(struct kvm_vcpu),
2495                                            0, NULL);
2496         if (!kvm_vcpu_cache) {
2497                 r = -ENOMEM;
2498                 goto out_free_5;
2499         }
2500
2501         kvm_chardev_ops.owner = module;
2502         kvm_vm_fops.owner = module;
2503         kvm_vcpu_fops.owner = module;
2504
2505         r = misc_register(&kvm_dev);
2506         if (r) {
2507                 printk(KERN_ERR "kvm: misc device register failed\n");
2508                 goto out_free;
2509         }
2510
2511         kvm_preempt_ops.sched_in = kvm_sched_in;
2512         kvm_preempt_ops.sched_out = kvm_sched_out;
2513 #ifndef CONFIG_X86
2514         msi2intx = 0;
2515 #endif
2516
2517         return 0;
2518
2519 out_free:
2520         kmem_cache_destroy(kvm_vcpu_cache);
2521 out_free_5:
2522         sysdev_unregister(&kvm_sysdev);
2523 out_free_4:
2524         sysdev_class_unregister(&kvm_sysdev_class);
2525 out_free_3:
2526         unregister_reboot_notifier(&kvm_reboot_notifier);
2527         unregister_cpu_notifier(&kvm_cpu_notifier);
2528 out_free_2:
2529         on_each_cpu(hardware_disable, NULL, 1);
2530 out_free_1:
2531         kvm_arch_hardware_unsetup();
2532 out_free_0a:
2533         free_cpumask_var(cpus_hardware_enabled);
2534 out_free_0:
2535         __free_page(bad_page);
2536 out:
2537         kvm_arch_exit();
2538         kvm_exit_debug();
2539 out_fail:
2540         return r;
2541 }
2542 EXPORT_SYMBOL_GPL(kvm_init);
2543
2544 void kvm_exit(void)
2545 {
2546         kvm_trace_cleanup();
2547         misc_deregister(&kvm_dev);
2548         kmem_cache_destroy(kvm_vcpu_cache);
2549         sysdev_unregister(&kvm_sysdev);
2550         sysdev_class_unregister(&kvm_sysdev_class);
2551         unregister_reboot_notifier(&kvm_reboot_notifier);
2552         unregister_cpu_notifier(&kvm_cpu_notifier);
2553         on_each_cpu(hardware_disable, NULL, 1);
2554         kvm_arch_hardware_unsetup();
2555         kvm_arch_exit();
2556         kvm_exit_debug();
2557         free_cpumask_var(cpus_hardware_enabled);
2558         __free_page(bad_page);
2559 }
2560 EXPORT_SYMBOL_GPL(kvm_exit);