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