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