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