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