KVM: Device assignment framework rework
[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 #endif
1036         kvm_arch_destroy_vm(kvm);
1037         mmdrop(mm);
1038 }
1039
1040 void kvm_get_kvm(struct kvm *kvm)
1041 {
1042         atomic_inc(&kvm->users_count);
1043 }
1044 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1045
1046 void kvm_put_kvm(struct kvm *kvm)
1047 {
1048         if (atomic_dec_and_test(&kvm->users_count))
1049                 kvm_destroy_vm(kvm);
1050 }
1051 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1052
1053
1054 static int kvm_vm_release(struct inode *inode, struct file *filp)
1055 {
1056         struct kvm *kvm = filp->private_data;
1057
1058         kvm_put_kvm(kvm);
1059         return 0;
1060 }
1061
1062 /*
1063  * Allocate some memory and give it an address in the guest physical address
1064  * space.
1065  *
1066  * Discontiguous memory is allowed, mostly for framebuffers.
1067  *
1068  * Must be called holding mmap_sem for write.
1069  */
1070 int __kvm_set_memory_region(struct kvm *kvm,
1071                             struct kvm_userspace_memory_region *mem,
1072                             int user_alloc)
1073 {
1074         int r;
1075         gfn_t base_gfn;
1076         unsigned long npages;
1077         int largepages;
1078         unsigned long i;
1079         struct kvm_memory_slot *memslot;
1080         struct kvm_memory_slot old, new;
1081
1082         r = -EINVAL;
1083         /* General sanity checks */
1084         if (mem->memory_size & (PAGE_SIZE - 1))
1085                 goto out;
1086         if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1087                 goto out;
1088         if (user_alloc && (mem->userspace_addr & (PAGE_SIZE - 1)))
1089                 goto out;
1090         if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
1091                 goto out;
1092         if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1093                 goto out;
1094
1095         memslot = &kvm->memslots[mem->slot];
1096         base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1097         npages = mem->memory_size >> PAGE_SHIFT;
1098
1099         if (!npages)
1100                 mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
1101
1102         new = old = *memslot;
1103
1104         new.base_gfn = base_gfn;
1105         new.npages = npages;
1106         new.flags = mem->flags;
1107
1108         /* Disallow changing a memory slot's size. */
1109         r = -EINVAL;
1110         if (npages && old.npages && npages != old.npages)
1111                 goto out_free;
1112
1113         /* Check for overlaps */
1114         r = -EEXIST;
1115         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
1116                 struct kvm_memory_slot *s = &kvm->memslots[i];
1117
1118                 if (s == memslot || !s->npages)
1119                         continue;
1120                 if (!((base_gfn + npages <= s->base_gfn) ||
1121                       (base_gfn >= s->base_gfn + s->npages)))
1122                         goto out_free;
1123         }
1124
1125         /* Free page dirty bitmap if unneeded */
1126         if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1127                 new.dirty_bitmap = NULL;
1128
1129         r = -ENOMEM;
1130
1131         /* Allocate if a slot is being created */
1132 #ifndef CONFIG_S390
1133         if (npages && !new.rmap) {
1134                 new.rmap = vmalloc(npages * sizeof(struct page *));
1135
1136                 if (!new.rmap)
1137                         goto out_free;
1138
1139                 memset(new.rmap, 0, npages * sizeof(*new.rmap));
1140
1141                 new.user_alloc = user_alloc;
1142                 /*
1143                  * hva_to_rmmap() serialzies with the mmu_lock and to be
1144                  * safe it has to ignore memslots with !user_alloc &&
1145                  * !userspace_addr.
1146                  */
1147                 if (user_alloc)
1148                         new.userspace_addr = mem->userspace_addr;
1149                 else
1150                         new.userspace_addr = 0;
1151         }
1152         if (npages && !new.lpage_info) {
1153                 largepages = 1 + (base_gfn + npages - 1) / KVM_PAGES_PER_HPAGE;
1154                 largepages -= base_gfn / KVM_PAGES_PER_HPAGE;
1155
1156                 new.lpage_info = vmalloc(largepages * sizeof(*new.lpage_info));
1157
1158                 if (!new.lpage_info)
1159                         goto out_free;
1160
1161                 memset(new.lpage_info, 0, largepages * sizeof(*new.lpage_info));
1162
1163                 if (base_gfn % KVM_PAGES_PER_HPAGE)
1164                         new.lpage_info[0].write_count = 1;
1165                 if ((base_gfn+npages) % KVM_PAGES_PER_HPAGE)
1166                         new.lpage_info[largepages-1].write_count = 1;
1167         }
1168
1169         /* Allocate page dirty bitmap if needed */
1170         if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
1171                 unsigned dirty_bytes = ALIGN(npages, BITS_PER_LONG) / 8;
1172
1173                 new.dirty_bitmap = vmalloc(dirty_bytes);
1174                 if (!new.dirty_bitmap)
1175                         goto out_free;
1176                 memset(new.dirty_bitmap, 0, dirty_bytes);
1177         }
1178 #endif /* not defined CONFIG_S390 */
1179
1180         if (!npages)
1181                 kvm_arch_flush_shadow(kvm);
1182
1183         spin_lock(&kvm->mmu_lock);
1184         if (mem->slot >= kvm->nmemslots)
1185                 kvm->nmemslots = mem->slot + 1;
1186
1187         *memslot = new;
1188         spin_unlock(&kvm->mmu_lock);
1189
1190         r = kvm_arch_set_memory_region(kvm, mem, old, user_alloc);
1191         if (r) {
1192                 spin_lock(&kvm->mmu_lock);
1193                 *memslot = old;
1194                 spin_unlock(&kvm->mmu_lock);
1195                 goto out_free;
1196         }
1197
1198         kvm_free_physmem_slot(&old, npages ? &new : NULL);
1199         /* Slot deletion case: we have to update the current slot */
1200         if (!npages)
1201                 *memslot = old;
1202 #ifdef CONFIG_DMAR
1203         /* map the pages in iommu page table */
1204         r = kvm_iommu_map_pages(kvm, base_gfn, npages);
1205         if (r)
1206                 goto out;
1207 #endif
1208         return 0;
1209
1210 out_free:
1211         kvm_free_physmem_slot(&new, &old);
1212 out:
1213         return r;
1214
1215 }
1216 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1217
1218 int kvm_set_memory_region(struct kvm *kvm,
1219                           struct kvm_userspace_memory_region *mem,
1220                           int user_alloc)
1221 {
1222         int r;
1223
1224         down_write(&kvm->slots_lock);
1225         r = __kvm_set_memory_region(kvm, mem, user_alloc);
1226         up_write(&kvm->slots_lock);
1227         return r;
1228 }
1229 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1230
1231 int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1232                                    struct
1233                                    kvm_userspace_memory_region *mem,
1234                                    int user_alloc)
1235 {
1236         if (mem->slot >= KVM_MEMORY_SLOTS)
1237                 return -EINVAL;
1238         return kvm_set_memory_region(kvm, mem, user_alloc);
1239 }
1240
1241 int kvm_get_dirty_log(struct kvm *kvm,
1242                         struct kvm_dirty_log *log, int *is_dirty)
1243 {
1244         struct kvm_memory_slot *memslot;
1245         int r, i;
1246         int n;
1247         unsigned long any = 0;
1248
1249         r = -EINVAL;
1250         if (log->slot >= KVM_MEMORY_SLOTS)
1251                 goto out;
1252
1253         memslot = &kvm->memslots[log->slot];
1254         r = -ENOENT;
1255         if (!memslot->dirty_bitmap)
1256                 goto out;
1257
1258         n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1259
1260         for (i = 0; !any && i < n/sizeof(long); ++i)
1261                 any = memslot->dirty_bitmap[i];
1262
1263         r = -EFAULT;
1264         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1265                 goto out;
1266
1267         if (any)
1268                 *is_dirty = 1;
1269
1270         r = 0;
1271 out:
1272         return r;
1273 }
1274
1275 int is_error_page(struct page *page)
1276 {
1277         return page == bad_page;
1278 }
1279 EXPORT_SYMBOL_GPL(is_error_page);
1280
1281 int is_error_pfn(pfn_t pfn)
1282 {
1283         return pfn == bad_pfn;
1284 }
1285 EXPORT_SYMBOL_GPL(is_error_pfn);
1286
1287 static inline unsigned long bad_hva(void)
1288 {
1289         return PAGE_OFFSET;
1290 }
1291
1292 int kvm_is_error_hva(unsigned long addr)
1293 {
1294         return addr == bad_hva();
1295 }
1296 EXPORT_SYMBOL_GPL(kvm_is_error_hva);
1297
1298 struct kvm_memory_slot *gfn_to_memslot_unaliased(struct kvm *kvm, gfn_t gfn)
1299 {
1300         int i;
1301
1302         for (i = 0; i < kvm->nmemslots; ++i) {
1303                 struct kvm_memory_slot *memslot = &kvm->memslots[i];
1304
1305                 if (gfn >= memslot->base_gfn
1306                     && gfn < memslot->base_gfn + memslot->npages)
1307                         return memslot;
1308         }
1309         return NULL;
1310 }
1311 EXPORT_SYMBOL_GPL(gfn_to_memslot_unaliased);
1312
1313 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1314 {
1315         gfn = unalias_gfn(kvm, gfn);
1316         return gfn_to_memslot_unaliased(kvm, gfn);
1317 }
1318
1319 int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1320 {
1321         int i;
1322
1323         gfn = unalias_gfn(kvm, gfn);
1324         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
1325                 struct kvm_memory_slot *memslot = &kvm->memslots[i];
1326
1327                 if (gfn >= memslot->base_gfn
1328                     && gfn < memslot->base_gfn + memslot->npages)
1329                         return 1;
1330         }
1331         return 0;
1332 }
1333 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1334
1335 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1336 {
1337         struct kvm_memory_slot *slot;
1338
1339         gfn = unalias_gfn(kvm, gfn);
1340         slot = gfn_to_memslot_unaliased(kvm, gfn);
1341         if (!slot)
1342                 return bad_hva();
1343         return (slot->userspace_addr + (gfn - slot->base_gfn) * PAGE_SIZE);
1344 }
1345 EXPORT_SYMBOL_GPL(gfn_to_hva);
1346
1347 pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1348 {
1349         struct page *page[1];
1350         unsigned long addr;
1351         int npages;
1352         pfn_t pfn;
1353
1354         might_sleep();
1355
1356         addr = gfn_to_hva(kvm, gfn);
1357         if (kvm_is_error_hva(addr)) {
1358                 get_page(bad_page);
1359                 return page_to_pfn(bad_page);
1360         }
1361
1362         npages = get_user_pages_fast(addr, 1, 1, page);
1363
1364         if (unlikely(npages != 1)) {
1365                 struct vm_area_struct *vma;
1366
1367                 down_read(&current->mm->mmap_sem);
1368                 vma = find_vma(current->mm, addr);
1369
1370                 if (vma == NULL || addr < vma->vm_start ||
1371                     !(vma->vm_flags & VM_PFNMAP)) {
1372                         up_read(&current->mm->mmap_sem);
1373                         get_page(bad_page);
1374                         return page_to_pfn(bad_page);
1375                 }
1376
1377                 pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
1378                 up_read(&current->mm->mmap_sem);
1379                 BUG_ON(!kvm_is_mmio_pfn(pfn));
1380         } else
1381                 pfn = page_to_pfn(page[0]);
1382
1383         return pfn;
1384 }
1385
1386 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1387
1388 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1389 {
1390         pfn_t pfn;
1391
1392         pfn = gfn_to_pfn(kvm, gfn);
1393         if (!kvm_is_mmio_pfn(pfn))
1394                 return pfn_to_page(pfn);
1395
1396         WARN_ON(kvm_is_mmio_pfn(pfn));
1397
1398         get_page(bad_page);
1399         return bad_page;
1400 }
1401
1402 EXPORT_SYMBOL_GPL(gfn_to_page);
1403
1404 void kvm_release_page_clean(struct page *page)
1405 {
1406         kvm_release_pfn_clean(page_to_pfn(page));
1407 }
1408 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1409
1410 void kvm_release_pfn_clean(pfn_t pfn)
1411 {
1412         if (!kvm_is_mmio_pfn(pfn))
1413                 put_page(pfn_to_page(pfn));
1414 }
1415 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1416
1417 void kvm_release_page_dirty(struct page *page)
1418 {
1419         kvm_release_pfn_dirty(page_to_pfn(page));
1420 }
1421 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1422
1423 void kvm_release_pfn_dirty(pfn_t pfn)
1424 {
1425         kvm_set_pfn_dirty(pfn);
1426         kvm_release_pfn_clean(pfn);
1427 }
1428 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
1429
1430 void kvm_set_page_dirty(struct page *page)
1431 {
1432         kvm_set_pfn_dirty(page_to_pfn(page));
1433 }
1434 EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
1435
1436 void kvm_set_pfn_dirty(pfn_t pfn)
1437 {
1438         if (!kvm_is_mmio_pfn(pfn)) {
1439                 struct page *page = pfn_to_page(pfn);
1440                 if (!PageReserved(page))
1441                         SetPageDirty(page);
1442         }
1443 }
1444 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1445
1446 void kvm_set_pfn_accessed(pfn_t pfn)
1447 {
1448         if (!kvm_is_mmio_pfn(pfn))
1449                 mark_page_accessed(pfn_to_page(pfn));
1450 }
1451 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1452
1453 void kvm_get_pfn(pfn_t pfn)
1454 {
1455         if (!kvm_is_mmio_pfn(pfn))
1456                 get_page(pfn_to_page(pfn));
1457 }
1458 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1459
1460 static int next_segment(unsigned long len, int offset)
1461 {
1462         if (len > PAGE_SIZE - offset)
1463                 return PAGE_SIZE - offset;
1464         else
1465                 return len;
1466 }
1467
1468 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1469                         int len)
1470 {
1471         int r;
1472         unsigned long addr;
1473
1474         addr = gfn_to_hva(kvm, gfn);
1475         if (kvm_is_error_hva(addr))
1476                 return -EFAULT;
1477         r = copy_from_user(data, (void __user *)addr + offset, len);
1478         if (r)
1479                 return -EFAULT;
1480         return 0;
1481 }
1482 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1483
1484 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1485 {
1486         gfn_t gfn = gpa >> PAGE_SHIFT;
1487         int seg;
1488         int offset = offset_in_page(gpa);
1489         int ret;
1490
1491         while ((seg = next_segment(len, offset)) != 0) {
1492                 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1493                 if (ret < 0)
1494                         return ret;
1495                 offset = 0;
1496                 len -= seg;
1497                 data += seg;
1498                 ++gfn;
1499         }
1500         return 0;
1501 }
1502 EXPORT_SYMBOL_GPL(kvm_read_guest);
1503
1504 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1505                           unsigned long len)
1506 {
1507         int r;
1508         unsigned long addr;
1509         gfn_t gfn = gpa >> PAGE_SHIFT;
1510         int offset = offset_in_page(gpa);
1511
1512         addr = gfn_to_hva(kvm, gfn);
1513         if (kvm_is_error_hva(addr))
1514                 return -EFAULT;
1515         pagefault_disable();
1516         r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1517         pagefault_enable();
1518         if (r)
1519                 return -EFAULT;
1520         return 0;
1521 }
1522 EXPORT_SYMBOL(kvm_read_guest_atomic);
1523
1524 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
1525                          int offset, int len)
1526 {
1527         int r;
1528         unsigned long addr;
1529
1530         addr = gfn_to_hva(kvm, gfn);
1531         if (kvm_is_error_hva(addr))
1532                 return -EFAULT;
1533         r = copy_to_user((void __user *)addr + offset, data, len);
1534         if (r)
1535                 return -EFAULT;
1536         mark_page_dirty(kvm, gfn);
1537         return 0;
1538 }
1539 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1540
1541 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1542                     unsigned long len)
1543 {
1544         gfn_t gfn = gpa >> PAGE_SHIFT;
1545         int seg;
1546         int offset = offset_in_page(gpa);
1547         int ret;
1548
1549         while ((seg = next_segment(len, offset)) != 0) {
1550                 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
1551                 if (ret < 0)
1552                         return ret;
1553                 offset = 0;
1554                 len -= seg;
1555                 data += seg;
1556                 ++gfn;
1557         }
1558         return 0;
1559 }
1560
1561 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
1562 {
1563         return kvm_write_guest_page(kvm, gfn, empty_zero_page, offset, len);
1564 }
1565 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
1566
1567 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
1568 {
1569         gfn_t gfn = gpa >> PAGE_SHIFT;
1570         int seg;
1571         int offset = offset_in_page(gpa);
1572         int ret;
1573
1574         while ((seg = next_segment(len, offset)) != 0) {
1575                 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
1576                 if (ret < 0)
1577                         return ret;
1578                 offset = 0;
1579                 len -= seg;
1580                 ++gfn;
1581         }
1582         return 0;
1583 }
1584 EXPORT_SYMBOL_GPL(kvm_clear_guest);
1585
1586 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
1587 {
1588         struct kvm_memory_slot *memslot;
1589
1590         gfn = unalias_gfn(kvm, gfn);
1591         memslot = gfn_to_memslot_unaliased(kvm, gfn);
1592         if (memslot && memslot->dirty_bitmap) {
1593                 unsigned long rel_gfn = gfn - memslot->base_gfn;
1594
1595                 /* avoid RMW */
1596                 if (!test_bit(rel_gfn, memslot->dirty_bitmap))
1597                         set_bit(rel_gfn, memslot->dirty_bitmap);
1598         }
1599 }
1600
1601 /*
1602  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
1603  */
1604 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
1605 {
1606         DEFINE_WAIT(wait);
1607
1608         for (;;) {
1609                 prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
1610
1611                 if (kvm_cpu_has_interrupt(vcpu) ||
1612                     kvm_cpu_has_pending_timer(vcpu) ||
1613                     kvm_arch_vcpu_runnable(vcpu)) {
1614                         set_bit(KVM_REQ_UNHALT, &vcpu->requests);
1615                         break;
1616                 }
1617                 if (signal_pending(current))
1618                         break;
1619
1620                 vcpu_put(vcpu);
1621                 schedule();
1622                 vcpu_load(vcpu);
1623         }
1624
1625         finish_wait(&vcpu->wq, &wait);
1626 }
1627
1628 void kvm_resched(struct kvm_vcpu *vcpu)
1629 {
1630         if (!need_resched())
1631                 return;
1632         cond_resched();
1633 }
1634 EXPORT_SYMBOL_GPL(kvm_resched);
1635
1636 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1637 {
1638         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
1639         struct page *page;
1640
1641         if (vmf->pgoff == 0)
1642                 page = virt_to_page(vcpu->run);
1643 #ifdef CONFIG_X86
1644         else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
1645                 page = virt_to_page(vcpu->arch.pio_data);
1646 #endif
1647 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1648         else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
1649                 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
1650 #endif
1651         else
1652                 return VM_FAULT_SIGBUS;
1653         get_page(page);
1654         vmf->page = page;
1655         return 0;
1656 }
1657
1658 static struct vm_operations_struct kvm_vcpu_vm_ops = {
1659         .fault = kvm_vcpu_fault,
1660 };
1661
1662 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
1663 {
1664         vma->vm_ops = &kvm_vcpu_vm_ops;
1665         return 0;
1666 }
1667
1668 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
1669 {
1670         struct kvm_vcpu *vcpu = filp->private_data;
1671
1672         kvm_put_kvm(vcpu->kvm);
1673         return 0;
1674 }
1675
1676 static struct file_operations kvm_vcpu_fops = {
1677         .release        = kvm_vcpu_release,
1678         .unlocked_ioctl = kvm_vcpu_ioctl,
1679         .compat_ioctl   = kvm_vcpu_ioctl,
1680         .mmap           = kvm_vcpu_mmap,
1681 };
1682
1683 /*
1684  * Allocates an inode for the vcpu.
1685  */
1686 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
1687 {
1688         int fd = anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, 0);
1689         if (fd < 0)
1690                 kvm_put_kvm(vcpu->kvm);
1691         return fd;
1692 }
1693
1694 /*
1695  * Creates some virtual cpus.  Good luck creating more than one.
1696  */
1697 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, int n)
1698 {
1699         int r;
1700         struct kvm_vcpu *vcpu;
1701
1702         if (!valid_vcpu(n))
1703                 return -EINVAL;
1704
1705         vcpu = kvm_arch_vcpu_create(kvm, n);
1706         if (IS_ERR(vcpu))
1707                 return PTR_ERR(vcpu);
1708
1709         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
1710
1711         r = kvm_arch_vcpu_setup(vcpu);
1712         if (r)
1713                 return r;
1714
1715         mutex_lock(&kvm->lock);
1716         if (kvm->vcpus[n]) {
1717                 r = -EEXIST;
1718                 goto vcpu_destroy;
1719         }
1720         kvm->vcpus[n] = vcpu;
1721         mutex_unlock(&kvm->lock);
1722
1723         /* Now it's all set up, let userspace reach it */
1724         kvm_get_kvm(kvm);
1725         r = create_vcpu_fd(vcpu);
1726         if (r < 0)
1727                 goto unlink;
1728         return r;
1729
1730 unlink:
1731         mutex_lock(&kvm->lock);
1732         kvm->vcpus[n] = NULL;
1733 vcpu_destroy:
1734         mutex_unlock(&kvm->lock);
1735         kvm_arch_vcpu_destroy(vcpu);
1736         return r;
1737 }
1738
1739 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
1740 {
1741         if (sigset) {
1742                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
1743                 vcpu->sigset_active = 1;
1744                 vcpu->sigset = *sigset;
1745         } else
1746                 vcpu->sigset_active = 0;
1747         return 0;
1748 }
1749
1750 #ifdef __KVM_HAVE_MSIX
1751 static int kvm_vm_ioctl_set_msix_nr(struct kvm *kvm,
1752                                     struct kvm_assigned_msix_nr *entry_nr)
1753 {
1754         int r = 0;
1755         struct kvm_assigned_dev_kernel *adev;
1756
1757         mutex_lock(&kvm->lock);
1758
1759         adev = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
1760                                       entry_nr->assigned_dev_id);
1761         if (!adev) {
1762                 r = -EINVAL;
1763                 goto msix_nr_out;
1764         }
1765
1766         if (adev->entries_nr == 0) {
1767                 adev->entries_nr = entry_nr->entry_nr;
1768                 if (adev->entries_nr == 0 ||
1769                     adev->entries_nr >= KVM_MAX_MSIX_PER_DEV) {
1770                         r = -EINVAL;
1771                         goto msix_nr_out;
1772                 }
1773
1774                 adev->host_msix_entries = kzalloc(sizeof(struct msix_entry) *
1775                                                 entry_nr->entry_nr,
1776                                                 GFP_KERNEL);
1777                 if (!adev->host_msix_entries) {
1778                         r = -ENOMEM;
1779                         goto msix_nr_out;
1780                 }
1781                 adev->guest_msix_entries = kzalloc(
1782                                 sizeof(struct kvm_guest_msix_entry) *
1783                                 entry_nr->entry_nr, GFP_KERNEL);
1784                 if (!adev->guest_msix_entries) {
1785                         kfree(adev->host_msix_entries);
1786                         r = -ENOMEM;
1787                         goto msix_nr_out;
1788                 }
1789         } else /* Not allowed set MSI-X number twice */
1790                 r = -EINVAL;
1791 msix_nr_out:
1792         mutex_unlock(&kvm->lock);
1793         return r;
1794 }
1795
1796 static int kvm_vm_ioctl_set_msix_entry(struct kvm *kvm,
1797                                        struct kvm_assigned_msix_entry *entry)
1798 {
1799         int r = 0, i;
1800         struct kvm_assigned_dev_kernel *adev;
1801
1802         mutex_lock(&kvm->lock);
1803
1804         adev = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
1805                                       entry->assigned_dev_id);
1806
1807         if (!adev) {
1808                 r = -EINVAL;
1809                 goto msix_entry_out;
1810         }
1811
1812         for (i = 0; i < adev->entries_nr; i++)
1813                 if (adev->guest_msix_entries[i].vector == 0 ||
1814                     adev->guest_msix_entries[i].entry == entry->entry) {
1815                         adev->guest_msix_entries[i].entry = entry->entry;
1816                         adev->guest_msix_entries[i].vector = entry->gsi;
1817                         adev->host_msix_entries[i].entry = entry->entry;
1818                         break;
1819                 }
1820         if (i == adev->entries_nr) {
1821                 r = -ENOSPC;
1822                 goto msix_entry_out;
1823         }
1824
1825 msix_entry_out:
1826         mutex_unlock(&kvm->lock);
1827
1828         return r;
1829 }
1830 #endif
1831
1832 static long kvm_vcpu_ioctl(struct file *filp,
1833                            unsigned int ioctl, unsigned long arg)
1834 {
1835         struct kvm_vcpu *vcpu = filp->private_data;
1836         void __user *argp = (void __user *)arg;
1837         int r;
1838         struct kvm_fpu *fpu = NULL;
1839         struct kvm_sregs *kvm_sregs = NULL;
1840
1841         if (vcpu->kvm->mm != current->mm)
1842                 return -EIO;
1843         switch (ioctl) {
1844         case KVM_RUN:
1845                 r = -EINVAL;
1846                 if (arg)
1847                         goto out;
1848                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
1849                 break;
1850         case KVM_GET_REGS: {
1851                 struct kvm_regs *kvm_regs;
1852
1853                 r = -ENOMEM;
1854                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1855                 if (!kvm_regs)
1856                         goto out;
1857                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
1858                 if (r)
1859                         goto out_free1;
1860                 r = -EFAULT;
1861                 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
1862                         goto out_free1;
1863                 r = 0;
1864 out_free1:
1865                 kfree(kvm_regs);
1866                 break;
1867         }
1868         case KVM_SET_REGS: {
1869                 struct kvm_regs *kvm_regs;
1870
1871                 r = -ENOMEM;
1872                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1873                 if (!kvm_regs)
1874                         goto out;
1875                 r = -EFAULT;
1876                 if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs)))
1877                         goto out_free2;
1878                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
1879                 if (r)
1880                         goto out_free2;
1881                 r = 0;
1882 out_free2:
1883                 kfree(kvm_regs);
1884                 break;
1885         }
1886         case KVM_GET_SREGS: {
1887                 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1888                 r = -ENOMEM;
1889                 if (!kvm_sregs)
1890                         goto out;
1891                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
1892                 if (r)
1893                         goto out;
1894                 r = -EFAULT;
1895                 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
1896                         goto out;
1897                 r = 0;
1898                 break;
1899         }
1900         case KVM_SET_SREGS: {
1901                 kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1902                 r = -ENOMEM;
1903                 if (!kvm_sregs)
1904                         goto out;
1905                 r = -EFAULT;
1906                 if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs)))
1907                         goto out;
1908                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
1909                 if (r)
1910                         goto out;
1911                 r = 0;
1912                 break;
1913         }
1914         case KVM_GET_MP_STATE: {
1915                 struct kvm_mp_state mp_state;
1916
1917                 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
1918                 if (r)
1919                         goto out;
1920                 r = -EFAULT;
1921                 if (copy_to_user(argp, &mp_state, sizeof mp_state))
1922                         goto out;
1923                 r = 0;
1924                 break;
1925         }
1926         case KVM_SET_MP_STATE: {
1927                 struct kvm_mp_state mp_state;
1928
1929                 r = -EFAULT;
1930                 if (copy_from_user(&mp_state, argp, sizeof mp_state))
1931                         goto out;
1932                 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
1933                 if (r)
1934                         goto out;
1935                 r = 0;
1936                 break;
1937         }
1938         case KVM_TRANSLATE: {
1939                 struct kvm_translation tr;
1940
1941                 r = -EFAULT;
1942                 if (copy_from_user(&tr, argp, sizeof tr))
1943                         goto out;
1944                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
1945                 if (r)
1946                         goto out;
1947                 r = -EFAULT;
1948                 if (copy_to_user(argp, &tr, sizeof tr))
1949                         goto out;
1950                 r = 0;
1951                 break;
1952         }
1953         case KVM_SET_GUEST_DEBUG: {
1954                 struct kvm_guest_debug dbg;
1955
1956                 r = -EFAULT;
1957                 if (copy_from_user(&dbg, argp, sizeof dbg))
1958                         goto out;
1959                 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
1960                 if (r)
1961                         goto out;
1962                 r = 0;
1963                 break;
1964         }
1965         case KVM_SET_SIGNAL_MASK: {
1966                 struct kvm_signal_mask __user *sigmask_arg = argp;
1967                 struct kvm_signal_mask kvm_sigmask;
1968                 sigset_t sigset, *p;
1969
1970                 p = NULL;
1971                 if (argp) {
1972                         r = -EFAULT;
1973                         if (copy_from_user(&kvm_sigmask, argp,
1974                                            sizeof kvm_sigmask))
1975                                 goto out;
1976                         r = -EINVAL;
1977                         if (kvm_sigmask.len != sizeof sigset)
1978                                 goto out;
1979                         r = -EFAULT;
1980                         if (copy_from_user(&sigset, sigmask_arg->sigset,
1981                                            sizeof sigset))
1982                                 goto out;
1983                         p = &sigset;
1984                 }
1985                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
1986                 break;
1987         }
1988         case KVM_GET_FPU: {
1989                 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1990                 r = -ENOMEM;
1991                 if (!fpu)
1992                         goto out;
1993                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
1994                 if (r)
1995                         goto out;
1996                 r = -EFAULT;
1997                 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
1998                         goto out;
1999                 r = 0;
2000                 break;
2001         }
2002         case KVM_SET_FPU: {
2003                 fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2004                 r = -ENOMEM;
2005                 if (!fpu)
2006                         goto out;
2007                 r = -EFAULT;
2008                 if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu)))
2009                         goto out;
2010                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2011                 if (r)
2012                         goto out;
2013                 r = 0;
2014                 break;
2015         }
2016         default:
2017                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2018         }
2019 out:
2020         kfree(fpu);
2021         kfree(kvm_sregs);
2022         return r;
2023 }
2024
2025 static long kvm_vm_ioctl(struct file *filp,
2026                            unsigned int ioctl, unsigned long arg)
2027 {
2028         struct kvm *kvm = filp->private_data;
2029         void __user *argp = (void __user *)arg;
2030         int r;
2031
2032         if (kvm->mm != current->mm)
2033                 return -EIO;
2034         switch (ioctl) {
2035         case KVM_CREATE_VCPU:
2036                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
2037                 if (r < 0)
2038                         goto out;
2039                 break;
2040         case KVM_SET_USER_MEMORY_REGION: {
2041                 struct kvm_userspace_memory_region kvm_userspace_mem;
2042
2043                 r = -EFAULT;
2044                 if (copy_from_user(&kvm_userspace_mem, argp,
2045                                                 sizeof kvm_userspace_mem))
2046                         goto out;
2047
2048                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
2049                 if (r)
2050                         goto out;
2051                 break;
2052         }
2053         case KVM_GET_DIRTY_LOG: {
2054                 struct kvm_dirty_log log;
2055
2056                 r = -EFAULT;
2057                 if (copy_from_user(&log, argp, sizeof log))
2058                         goto out;
2059                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2060                 if (r)
2061                         goto out;
2062                 break;
2063         }
2064 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2065         case KVM_REGISTER_COALESCED_MMIO: {
2066                 struct kvm_coalesced_mmio_zone zone;
2067                 r = -EFAULT;
2068                 if (copy_from_user(&zone, argp, sizeof zone))
2069                         goto out;
2070                 r = -ENXIO;
2071                 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
2072                 if (r)
2073                         goto out;
2074                 r = 0;
2075                 break;
2076         }
2077         case KVM_UNREGISTER_COALESCED_MMIO: {
2078                 struct kvm_coalesced_mmio_zone zone;
2079                 r = -EFAULT;
2080                 if (copy_from_user(&zone, argp, sizeof zone))
2081                         goto out;
2082                 r = -ENXIO;
2083                 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
2084                 if (r)
2085                         goto out;
2086                 r = 0;
2087                 break;
2088         }
2089 #endif
2090 #ifdef KVM_CAP_DEVICE_ASSIGNMENT
2091         case KVM_ASSIGN_PCI_DEVICE: {
2092                 struct kvm_assigned_pci_dev assigned_dev;
2093
2094                 r = -EFAULT;
2095                 if (copy_from_user(&assigned_dev, argp, sizeof assigned_dev))
2096                         goto out;
2097                 r = kvm_vm_ioctl_assign_device(kvm, &assigned_dev);
2098                 if (r)
2099                         goto out;
2100                 break;
2101         }
2102         case KVM_ASSIGN_IRQ: {
2103                 r = -EOPNOTSUPP;
2104                 break;
2105         }
2106 #ifdef KVM_CAP_ASSIGN_DEV_IRQ
2107         case KVM_ASSIGN_DEV_IRQ: {
2108                 struct kvm_assigned_irq assigned_irq;
2109
2110                 r = -EFAULT;
2111                 if (copy_from_user(&assigned_irq, argp, sizeof assigned_irq))
2112                         goto out;
2113                 r = kvm_vm_ioctl_assign_irq(kvm, &assigned_irq);
2114                 if (r)
2115                         goto out;
2116                 break;
2117         }
2118         case KVM_DEASSIGN_DEV_IRQ: {
2119                 struct kvm_assigned_irq assigned_irq;
2120
2121                 r = -EFAULT;
2122                 if (copy_from_user(&assigned_irq, argp, sizeof assigned_irq))
2123                         goto out;
2124                 r = kvm_vm_ioctl_deassign_dev_irq(kvm, &assigned_irq);
2125                 if (r)
2126                         goto out;
2127                 break;
2128         }
2129 #endif
2130 #endif
2131 #ifdef KVM_CAP_DEVICE_DEASSIGNMENT
2132         case KVM_DEASSIGN_PCI_DEVICE: {
2133                 struct kvm_assigned_pci_dev assigned_dev;
2134
2135                 r = -EFAULT;
2136                 if (copy_from_user(&assigned_dev, argp, sizeof assigned_dev))
2137                         goto out;
2138                 r = kvm_vm_ioctl_deassign_device(kvm, &assigned_dev);
2139                 if (r)
2140                         goto out;
2141                 break;
2142         }
2143 #endif
2144 #ifdef KVM_CAP_IRQ_ROUTING
2145         case KVM_SET_GSI_ROUTING: {
2146                 struct kvm_irq_routing routing;
2147                 struct kvm_irq_routing __user *urouting;
2148                 struct kvm_irq_routing_entry *entries;
2149
2150                 r = -EFAULT;
2151                 if (copy_from_user(&routing, argp, sizeof(routing)))
2152                         goto out;
2153                 r = -EINVAL;
2154                 if (routing.nr >= KVM_MAX_IRQ_ROUTES)
2155                         goto out;
2156                 if (routing.flags)
2157                         goto out;
2158                 r = -ENOMEM;
2159                 entries = vmalloc(routing.nr * sizeof(*entries));
2160                 if (!entries)
2161                         goto out;
2162                 r = -EFAULT;
2163                 urouting = argp;
2164                 if (copy_from_user(entries, urouting->entries,
2165                                    routing.nr * sizeof(*entries)))
2166                         goto out_free_irq_routing;
2167                 r = kvm_set_irq_routing(kvm, entries, routing.nr,
2168                                         routing.flags);
2169         out_free_irq_routing:
2170                 vfree(entries);
2171                 break;
2172         }
2173 #ifdef __KVM_HAVE_MSIX
2174         case KVM_ASSIGN_SET_MSIX_NR: {
2175                 struct kvm_assigned_msix_nr entry_nr;
2176                 r = -EFAULT;
2177                 if (copy_from_user(&entry_nr, argp, sizeof entry_nr))
2178                         goto out;
2179                 r = kvm_vm_ioctl_set_msix_nr(kvm, &entry_nr);
2180                 if (r)
2181                         goto out;
2182                 break;
2183         }
2184         case KVM_ASSIGN_SET_MSIX_ENTRY: {
2185                 struct kvm_assigned_msix_entry entry;
2186                 r = -EFAULT;
2187                 if (copy_from_user(&entry, argp, sizeof entry))
2188                         goto out;
2189                 r = kvm_vm_ioctl_set_msix_entry(kvm, &entry);
2190                 if (r)
2191                         goto out;
2192                 break;
2193         }
2194 #endif
2195 #endif /* KVM_CAP_IRQ_ROUTING */
2196         default:
2197                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
2198         }
2199 out:
2200         return r;
2201 }
2202
2203 static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2204 {
2205         struct page *page[1];
2206         unsigned long addr;
2207         int npages;
2208         gfn_t gfn = vmf->pgoff;
2209         struct kvm *kvm = vma->vm_file->private_data;
2210
2211         addr = gfn_to_hva(kvm, gfn);
2212         if (kvm_is_error_hva(addr))
2213                 return VM_FAULT_SIGBUS;
2214
2215         npages = get_user_pages(current, current->mm, addr, 1, 1, 0, page,
2216                                 NULL);
2217         if (unlikely(npages != 1))
2218                 return VM_FAULT_SIGBUS;
2219
2220         vmf->page = page[0];
2221         return 0;
2222 }
2223
2224 static struct vm_operations_struct kvm_vm_vm_ops = {
2225         .fault = kvm_vm_fault,
2226 };
2227
2228 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
2229 {
2230         vma->vm_ops = &kvm_vm_vm_ops;
2231         return 0;
2232 }
2233
2234 static struct file_operations kvm_vm_fops = {
2235         .release        = kvm_vm_release,
2236         .unlocked_ioctl = kvm_vm_ioctl,
2237         .compat_ioctl   = kvm_vm_ioctl,
2238         .mmap           = kvm_vm_mmap,
2239 };
2240
2241 static int kvm_dev_ioctl_create_vm(void)
2242 {
2243         int fd;
2244         struct kvm *kvm;
2245
2246         kvm = kvm_create_vm();
2247         if (IS_ERR(kvm))
2248                 return PTR_ERR(kvm);
2249         fd = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, 0);
2250         if (fd < 0)
2251                 kvm_put_kvm(kvm);
2252
2253         return fd;
2254 }
2255
2256 static long kvm_dev_ioctl_check_extension_generic(long arg)
2257 {
2258         switch (arg) {
2259         case KVM_CAP_USER_MEMORY:
2260         case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
2261         case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
2262                 return 1;
2263 #ifdef CONFIG_HAVE_KVM_IRQCHIP
2264         case KVM_CAP_IRQ_ROUTING:
2265                 return KVM_MAX_IRQ_ROUTES;
2266 #endif
2267         default:
2268                 break;
2269         }
2270         return kvm_dev_ioctl_check_extension(arg);
2271 }
2272
2273 static long kvm_dev_ioctl(struct file *filp,
2274                           unsigned int ioctl, unsigned long arg)
2275 {
2276         long r = -EINVAL;
2277
2278         switch (ioctl) {
2279         case KVM_GET_API_VERSION:
2280                 r = -EINVAL;
2281                 if (arg)
2282                         goto out;
2283                 r = KVM_API_VERSION;
2284                 break;
2285         case KVM_CREATE_VM:
2286                 r = -EINVAL;
2287                 if (arg)
2288                         goto out;
2289                 r = kvm_dev_ioctl_create_vm();
2290                 break;
2291         case KVM_CHECK_EXTENSION:
2292                 r = kvm_dev_ioctl_check_extension_generic(arg);
2293                 break;
2294         case KVM_GET_VCPU_MMAP_SIZE:
2295                 r = -EINVAL;
2296                 if (arg)
2297                         goto out;
2298                 r = PAGE_SIZE;     /* struct kvm_run */
2299 #ifdef CONFIG_X86
2300                 r += PAGE_SIZE;    /* pio data page */
2301 #endif
2302 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2303                 r += PAGE_SIZE;    /* coalesced mmio ring page */
2304 #endif
2305                 break;
2306         case KVM_TRACE_ENABLE:
2307         case KVM_TRACE_PAUSE:
2308         case KVM_TRACE_DISABLE:
2309                 r = kvm_trace_ioctl(ioctl, arg);
2310                 break;
2311         default:
2312                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
2313         }
2314 out:
2315         return r;
2316 }
2317
2318 static struct file_operations kvm_chardev_ops = {
2319         .unlocked_ioctl = kvm_dev_ioctl,
2320         .compat_ioctl   = kvm_dev_ioctl,
2321 };
2322
2323 static struct miscdevice kvm_dev = {
2324         KVM_MINOR,
2325         "kvm",
2326         &kvm_chardev_ops,
2327 };
2328
2329 static void hardware_enable(void *junk)
2330 {
2331         int cpu = raw_smp_processor_id();
2332
2333         if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
2334                 return;
2335         cpumask_set_cpu(cpu, cpus_hardware_enabled);
2336         kvm_arch_hardware_enable(NULL);
2337 }
2338
2339 static void hardware_disable(void *junk)
2340 {
2341         int cpu = raw_smp_processor_id();
2342
2343         if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
2344                 return;
2345         cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2346         kvm_arch_hardware_disable(NULL);
2347 }
2348
2349 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2350                            void *v)
2351 {
2352         int cpu = (long)v;
2353
2354         val &= ~CPU_TASKS_FROZEN;
2355         switch (val) {
2356         case CPU_DYING:
2357                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2358                        cpu);
2359                 hardware_disable(NULL);
2360                 break;
2361         case CPU_UP_CANCELED:
2362                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2363                        cpu);
2364                 smp_call_function_single(cpu, hardware_disable, NULL, 1);
2365                 break;
2366         case CPU_ONLINE:
2367                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2368                        cpu);
2369                 smp_call_function_single(cpu, hardware_enable, NULL, 1);
2370                 break;
2371         }
2372         return NOTIFY_OK;
2373 }
2374
2375
2376 asmlinkage void kvm_handle_fault_on_reboot(void)
2377 {
2378         if (kvm_rebooting)
2379                 /* spin while reset goes on */
2380                 while (true)
2381                         ;
2382         /* Fault while not rebooting.  We want the trace. */
2383         BUG();
2384 }
2385 EXPORT_SYMBOL_GPL(kvm_handle_fault_on_reboot);
2386
2387 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2388                       void *v)
2389 {
2390         if (val == SYS_RESTART) {
2391                 /*
2392                  * Some (well, at least mine) BIOSes hang on reboot if
2393                  * in vmx root mode.
2394                  */
2395                 printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2396                 kvm_rebooting = true;
2397                 on_each_cpu(hardware_disable, NULL, 1);
2398         }
2399         return NOTIFY_OK;
2400 }
2401
2402 static struct notifier_block kvm_reboot_notifier = {
2403         .notifier_call = kvm_reboot,
2404         .priority = 0,
2405 };
2406
2407 void kvm_io_bus_init(struct kvm_io_bus *bus)
2408 {
2409         memset(bus, 0, sizeof(*bus));
2410 }
2411
2412 void kvm_io_bus_destroy(struct kvm_io_bus *bus)
2413 {
2414         int i;
2415
2416         for (i = 0; i < bus->dev_count; i++) {
2417                 struct kvm_io_device *pos = bus->devs[i];
2418
2419                 kvm_iodevice_destructor(pos);
2420         }
2421 }
2422
2423 struct kvm_io_device *kvm_io_bus_find_dev(struct kvm_io_bus *bus,
2424                                           gpa_t addr, int len, int is_write)
2425 {
2426         int i;
2427
2428         for (i = 0; i < bus->dev_count; i++) {
2429                 struct kvm_io_device *pos = bus->devs[i];
2430
2431                 if (pos->in_range(pos, addr, len, is_write))
2432                         return pos;
2433         }
2434
2435         return NULL;
2436 }
2437
2438 void kvm_io_bus_register_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev)
2439 {
2440         BUG_ON(bus->dev_count > (NR_IOBUS_DEVS-1));
2441
2442         bus->devs[bus->dev_count++] = dev;
2443 }
2444
2445 static struct notifier_block kvm_cpu_notifier = {
2446         .notifier_call = kvm_cpu_hotplug,
2447         .priority = 20, /* must be > scheduler priority */
2448 };
2449
2450 static int vm_stat_get(void *_offset, u64 *val)
2451 {
2452         unsigned offset = (long)_offset;
2453         struct kvm *kvm;
2454
2455         *val = 0;
2456         spin_lock(&kvm_lock);
2457         list_for_each_entry(kvm, &vm_list, vm_list)
2458                 *val += *(u32 *)((void *)kvm + offset);
2459         spin_unlock(&kvm_lock);
2460         return 0;
2461 }
2462
2463 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
2464
2465 static int vcpu_stat_get(void *_offset, u64 *val)
2466 {
2467         unsigned offset = (long)_offset;
2468         struct kvm *kvm;
2469         struct kvm_vcpu *vcpu;
2470         int i;
2471
2472         *val = 0;
2473         spin_lock(&kvm_lock);
2474         list_for_each_entry(kvm, &vm_list, vm_list)
2475                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
2476                         vcpu = kvm->vcpus[i];
2477                         if (vcpu)
2478                                 *val += *(u32 *)((void *)vcpu + offset);
2479                 }
2480         spin_unlock(&kvm_lock);
2481         return 0;
2482 }
2483
2484 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
2485
2486 static struct file_operations *stat_fops[] = {
2487         [KVM_STAT_VCPU] = &vcpu_stat_fops,
2488         [KVM_STAT_VM]   = &vm_stat_fops,
2489 };
2490
2491 static void kvm_init_debug(void)
2492 {
2493         struct kvm_stats_debugfs_item *p;
2494
2495         kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
2496         for (p = debugfs_entries; p->name; ++p)
2497                 p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
2498                                                 (void *)(long)p->offset,
2499                                                 stat_fops[p->kind]);
2500 }
2501
2502 static void kvm_exit_debug(void)
2503 {
2504         struct kvm_stats_debugfs_item *p;
2505
2506         for (p = debugfs_entries; p->name; ++p)
2507                 debugfs_remove(p->dentry);
2508         debugfs_remove(kvm_debugfs_dir);
2509 }
2510
2511 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
2512 {
2513         hardware_disable(NULL);
2514         return 0;
2515 }
2516
2517 static int kvm_resume(struct sys_device *dev)
2518 {
2519         hardware_enable(NULL);
2520         return 0;
2521 }
2522
2523 static struct sysdev_class kvm_sysdev_class = {
2524         .name = "kvm",
2525         .suspend = kvm_suspend,
2526         .resume = kvm_resume,
2527 };
2528
2529 static struct sys_device kvm_sysdev = {
2530         .id = 0,
2531         .cls = &kvm_sysdev_class,
2532 };
2533
2534 struct page *bad_page;
2535 pfn_t bad_pfn;
2536
2537 static inline
2538 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
2539 {
2540         return container_of(pn, struct kvm_vcpu, preempt_notifier);
2541 }
2542
2543 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
2544 {
2545         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2546
2547         kvm_arch_vcpu_load(vcpu, cpu);
2548 }
2549
2550 static void kvm_sched_out(struct preempt_notifier *pn,
2551                           struct task_struct *next)
2552 {
2553         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2554
2555         kvm_arch_vcpu_put(vcpu);
2556 }
2557
2558 int kvm_init(void *opaque, unsigned int vcpu_size,
2559                   struct module *module)
2560 {
2561         int r;
2562         int cpu;
2563
2564         kvm_init_debug();
2565
2566         r = kvm_arch_init(opaque);
2567         if (r)
2568                 goto out_fail;
2569
2570         bad_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2571
2572         if (bad_page == NULL) {
2573                 r = -ENOMEM;
2574                 goto out;
2575         }
2576
2577         bad_pfn = page_to_pfn(bad_page);
2578
2579         if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
2580                 r = -ENOMEM;
2581                 goto out_free_0;
2582         }
2583         cpumask_clear(cpus_hardware_enabled);
2584
2585         r = kvm_arch_hardware_setup();
2586         if (r < 0)
2587                 goto out_free_0a;
2588
2589         for_each_online_cpu(cpu) {
2590                 smp_call_function_single(cpu,
2591                                 kvm_arch_check_processor_compat,
2592                                 &r, 1);
2593                 if (r < 0)
2594                         goto out_free_1;
2595         }
2596
2597         on_each_cpu(hardware_enable, NULL, 1);
2598         r = register_cpu_notifier(&kvm_cpu_notifier);
2599         if (r)
2600                 goto out_free_2;
2601         register_reboot_notifier(&kvm_reboot_notifier);
2602
2603         r = sysdev_class_register(&kvm_sysdev_class);
2604         if (r)
2605                 goto out_free_3;
2606
2607         r = sysdev_register(&kvm_sysdev);
2608         if (r)
2609                 goto out_free_4;
2610
2611         /* A kmem cache lets us meet the alignment requirements of fx_save. */
2612         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size,
2613                                            __alignof__(struct kvm_vcpu),
2614                                            0, NULL);
2615         if (!kvm_vcpu_cache) {
2616                 r = -ENOMEM;
2617                 goto out_free_5;
2618         }
2619
2620         kvm_chardev_ops.owner = module;
2621         kvm_vm_fops.owner = module;
2622         kvm_vcpu_fops.owner = module;
2623
2624         r = misc_register(&kvm_dev);
2625         if (r) {
2626                 printk(KERN_ERR "kvm: misc device register failed\n");
2627                 goto out_free;
2628         }
2629
2630         kvm_preempt_ops.sched_in = kvm_sched_in;
2631         kvm_preempt_ops.sched_out = kvm_sched_out;
2632
2633         return 0;
2634
2635 out_free:
2636         kmem_cache_destroy(kvm_vcpu_cache);
2637 out_free_5:
2638         sysdev_unregister(&kvm_sysdev);
2639 out_free_4:
2640         sysdev_class_unregister(&kvm_sysdev_class);
2641 out_free_3:
2642         unregister_reboot_notifier(&kvm_reboot_notifier);
2643         unregister_cpu_notifier(&kvm_cpu_notifier);
2644 out_free_2:
2645         on_each_cpu(hardware_disable, NULL, 1);
2646 out_free_1:
2647         kvm_arch_hardware_unsetup();
2648 out_free_0a:
2649         free_cpumask_var(cpus_hardware_enabled);
2650 out_free_0:
2651         __free_page(bad_page);
2652 out:
2653         kvm_arch_exit();
2654         kvm_exit_debug();
2655 out_fail:
2656         return r;
2657 }
2658 EXPORT_SYMBOL_GPL(kvm_init);
2659
2660 void kvm_exit(void)
2661 {
2662         kvm_trace_cleanup();
2663         misc_deregister(&kvm_dev);
2664         kmem_cache_destroy(kvm_vcpu_cache);
2665         sysdev_unregister(&kvm_sysdev);
2666         sysdev_class_unregister(&kvm_sysdev_class);
2667         unregister_reboot_notifier(&kvm_reboot_notifier);
2668         unregister_cpu_notifier(&kvm_cpu_notifier);
2669         on_each_cpu(hardware_disable, NULL, 1);
2670         kvm_arch_hardware_unsetup();
2671         kvm_arch_exit();
2672         kvm_exit_debug();
2673         free_cpumask_var(cpus_hardware_enabled);
2674         __free_page(bad_page);
2675 }
2676 EXPORT_SYMBOL_GPL(kvm_exit);