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