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