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