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