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