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