c41eb57ce29b8c7ba6ffd2b78175b90ad8254bae
[linux-2.6.git] / virt / kvm / kvm_main.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  *
9  * Authors:
10  *   Avi Kivity   <avi@qumranet.com>
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17
18 #include "iodev.h"
19
20 #include <linux/kvm_host.h>
21 #include <linux/kvm.h>
22 #include <linux/module.h>
23 #include <linux/errno.h>
24 #include <linux/percpu.h>
25 #include <linux/gfp.h>
26 #include <linux/mm.h>
27 #include <linux/miscdevice.h>
28 #include <linux/vmalloc.h>
29 #include <linux/reboot.h>
30 #include <linux/debugfs.h>
31 #include <linux/highmem.h>
32 #include <linux/file.h>
33 #include <linux/sysdev.h>
34 #include <linux/cpu.h>
35 #include <linux/sched.h>
36 #include <linux/cpumask.h>
37 #include <linux/smp.h>
38 #include <linux/anon_inodes.h>
39 #include <linux/profile.h>
40 #include <linux/kvm_para.h>
41 #include <linux/pagemap.h>
42 #include <linux/mman.h>
43
44 #include <asm/processor.h>
45 #include <asm/io.h>
46 #include <asm/uaccess.h>
47 #include <asm/pgtable.h>
48
49 MODULE_AUTHOR("Qumranet");
50 MODULE_LICENSE("GPL");
51
52 DEFINE_SPINLOCK(kvm_lock);
53 LIST_HEAD(vm_list);
54
55 static cpumask_t cpus_hardware_enabled;
56
57 struct kmem_cache *kvm_vcpu_cache;
58 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
59
60 static __read_mostly struct preempt_ops kvm_preempt_ops;
61
62 static struct dentry *debugfs_dir;
63
64 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
65                            unsigned long arg);
66
67 static inline int valid_vcpu(int n)
68 {
69         return likely(n >= 0 && n < KVM_MAX_VCPUS);
70 }
71
72 /*
73  * Switches to specified vcpu, until a matching vcpu_put()
74  */
75 void vcpu_load(struct kvm_vcpu *vcpu)
76 {
77         int cpu;
78
79         mutex_lock(&vcpu->mutex);
80         cpu = get_cpu();
81         preempt_notifier_register(&vcpu->preempt_notifier);
82         kvm_arch_vcpu_load(vcpu, cpu);
83         put_cpu();
84 }
85
86 void vcpu_put(struct kvm_vcpu *vcpu)
87 {
88         preempt_disable();
89         kvm_arch_vcpu_put(vcpu);
90         preempt_notifier_unregister(&vcpu->preempt_notifier);
91         preempt_enable();
92         mutex_unlock(&vcpu->mutex);
93 }
94
95 static void ack_flush(void *_completed)
96 {
97 }
98
99 void kvm_flush_remote_tlbs(struct kvm *kvm)
100 {
101         int i, cpu;
102         cpumask_t cpus;
103         struct kvm_vcpu *vcpu;
104
105         cpus_clear(cpus);
106         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
107                 vcpu = kvm->vcpus[i];
108                 if (!vcpu)
109                         continue;
110                 if (test_and_set_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
111                         continue;
112                 cpu = vcpu->cpu;
113                 if (cpu != -1 && cpu != raw_smp_processor_id())
114                         cpu_set(cpu, cpus);
115         }
116         if (cpus_empty(cpus))
117                 return;
118         ++kvm->stat.remote_tlb_flush;
119         smp_call_function_mask(cpus, ack_flush, NULL, 1);
120 }
121
122 void kvm_reload_remote_mmus(struct kvm *kvm)
123 {
124         int i, cpu;
125         cpumask_t cpus;
126         struct kvm_vcpu *vcpu;
127
128         cpus_clear(cpus);
129         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
130                 vcpu = kvm->vcpus[i];
131                 if (!vcpu)
132                         continue;
133                 if (test_and_set_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
134                         continue;
135                 cpu = vcpu->cpu;
136                 if (cpu != -1 && cpu != raw_smp_processor_id())
137                         cpu_set(cpu, cpus);
138         }
139         if (cpus_empty(cpus))
140                 return;
141         smp_call_function_mask(cpus, ack_flush, NULL, 1);
142 }
143
144
145 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
146 {
147         struct page *page;
148         int r;
149
150         mutex_init(&vcpu->mutex);
151         vcpu->cpu = -1;
152         vcpu->kvm = kvm;
153         vcpu->vcpu_id = id;
154         init_waitqueue_head(&vcpu->wq);
155
156         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
157         if (!page) {
158                 r = -ENOMEM;
159                 goto fail;
160         }
161         vcpu->run = page_address(page);
162
163         r = kvm_arch_vcpu_init(vcpu);
164         if (r < 0)
165                 goto fail_free_run;
166         return 0;
167
168 fail_free_run:
169         free_page((unsigned long)vcpu->run);
170 fail:
171         return r;
172 }
173 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
174
175 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
176 {
177         kvm_arch_vcpu_uninit(vcpu);
178         free_page((unsigned long)vcpu->run);
179 }
180 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
181
182 static struct kvm *kvm_create_vm(void)
183 {
184         struct kvm *kvm = kvm_arch_create_vm();
185
186         if (IS_ERR(kvm))
187                 goto out;
188
189         kvm->mm = current->mm;
190         atomic_inc(&kvm->mm->mm_count);
191         spin_lock_init(&kvm->mmu_lock);
192         kvm_io_bus_init(&kvm->pio_bus);
193         mutex_init(&kvm->lock);
194         kvm_io_bus_init(&kvm->mmio_bus);
195         init_rwsem(&kvm->slots_lock);
196         spin_lock(&kvm_lock);
197         list_add(&kvm->vm_list, &vm_list);
198         spin_unlock(&kvm_lock);
199 out:
200         return kvm;
201 }
202
203 /*
204  * Free any memory in @free but not in @dont.
205  */
206 static void kvm_free_physmem_slot(struct kvm_memory_slot *free,
207                                   struct kvm_memory_slot *dont)
208 {
209         if (!dont || free->rmap != dont->rmap)
210                 vfree(free->rmap);
211
212         if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
213                 vfree(free->dirty_bitmap);
214
215         free->npages = 0;
216         free->dirty_bitmap = NULL;
217         free->rmap = NULL;
218 }
219
220 void kvm_free_physmem(struct kvm *kvm)
221 {
222         int i;
223
224         for (i = 0; i < kvm->nmemslots; ++i)
225                 kvm_free_physmem_slot(&kvm->memslots[i], NULL);
226 }
227
228 static void kvm_destroy_vm(struct kvm *kvm)
229 {
230         struct mm_struct *mm = kvm->mm;
231
232         spin_lock(&kvm_lock);
233         list_del(&kvm->vm_list);
234         spin_unlock(&kvm_lock);
235         kvm_io_bus_destroy(&kvm->pio_bus);
236         kvm_io_bus_destroy(&kvm->mmio_bus);
237         kvm_arch_destroy_vm(kvm);
238         mmdrop(mm);
239 }
240
241 static int kvm_vm_release(struct inode *inode, struct file *filp)
242 {
243         struct kvm *kvm = filp->private_data;
244
245         kvm_destroy_vm(kvm);
246         return 0;
247 }
248
249 /*
250  * Allocate some memory and give it an address in the guest physical address
251  * space.
252  *
253  * Discontiguous memory is allowed, mostly for framebuffers.
254  *
255  * Must be called holding mmap_sem for write.
256  */
257 int __kvm_set_memory_region(struct kvm *kvm,
258                             struct kvm_userspace_memory_region *mem,
259                             int user_alloc)
260 {
261         int r;
262         gfn_t base_gfn;
263         unsigned long npages;
264         unsigned long i;
265         struct kvm_memory_slot *memslot;
266         struct kvm_memory_slot old, new;
267
268         r = -EINVAL;
269         /* General sanity checks */
270         if (mem->memory_size & (PAGE_SIZE - 1))
271                 goto out;
272         if (mem->guest_phys_addr & (PAGE_SIZE - 1))
273                 goto out;
274         if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
275                 goto out;
276         if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
277                 goto out;
278
279         memslot = &kvm->memslots[mem->slot];
280         base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
281         npages = mem->memory_size >> PAGE_SHIFT;
282
283         if (!npages)
284                 mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
285
286         new = old = *memslot;
287
288         new.base_gfn = base_gfn;
289         new.npages = npages;
290         new.flags = mem->flags;
291
292         /* Disallow changing a memory slot's size. */
293         r = -EINVAL;
294         if (npages && old.npages && npages != old.npages)
295                 goto out_free;
296
297         /* Check for overlaps */
298         r = -EEXIST;
299         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
300                 struct kvm_memory_slot *s = &kvm->memslots[i];
301
302                 if (s == memslot)
303                         continue;
304                 if (!((base_gfn + npages <= s->base_gfn) ||
305                       (base_gfn >= s->base_gfn + s->npages)))
306                         goto out_free;
307         }
308
309         /* Free page dirty bitmap if unneeded */
310         if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
311                 new.dirty_bitmap = NULL;
312
313         r = -ENOMEM;
314
315         /* Allocate if a slot is being created */
316         if (npages && !new.rmap) {
317                 new.rmap = vmalloc(npages * sizeof(struct page *));
318
319                 if (!new.rmap)
320                         goto out_free;
321
322                 memset(new.rmap, 0, npages * sizeof(*new.rmap));
323
324                 new.user_alloc = user_alloc;
325                 new.userspace_addr = mem->userspace_addr;
326         }
327
328         /* Allocate page dirty bitmap if needed */
329         if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
330                 unsigned dirty_bytes = ALIGN(npages, BITS_PER_LONG) / 8;
331
332                 new.dirty_bitmap = vmalloc(dirty_bytes);
333                 if (!new.dirty_bitmap)
334                         goto out_free;
335                 memset(new.dirty_bitmap, 0, dirty_bytes);
336         }
337
338         if (mem->slot >= kvm->nmemslots)
339                 kvm->nmemslots = mem->slot + 1;
340
341         *memslot = new;
342
343         r = kvm_arch_set_memory_region(kvm, mem, old, user_alloc);
344         if (r) {
345                 *memslot = old;
346                 goto out_free;
347         }
348
349         kvm_free_physmem_slot(&old, &new);
350         return 0;
351
352 out_free:
353         kvm_free_physmem_slot(&new, &old);
354 out:
355         return r;
356
357 }
358 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
359
360 int kvm_set_memory_region(struct kvm *kvm,
361                           struct kvm_userspace_memory_region *mem,
362                           int user_alloc)
363 {
364         int r;
365
366         down_write(&kvm->slots_lock);
367         r = __kvm_set_memory_region(kvm, mem, user_alloc);
368         up_write(&kvm->slots_lock);
369         return r;
370 }
371 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
372
373 int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
374                                    struct
375                                    kvm_userspace_memory_region *mem,
376                                    int user_alloc)
377 {
378         if (mem->slot >= KVM_MEMORY_SLOTS)
379                 return -EINVAL;
380         return kvm_set_memory_region(kvm, mem, user_alloc);
381 }
382
383 int kvm_get_dirty_log(struct kvm *kvm,
384                         struct kvm_dirty_log *log, int *is_dirty)
385 {
386         struct kvm_memory_slot *memslot;
387         int r, i;
388         int n;
389         unsigned long any = 0;
390
391         r = -EINVAL;
392         if (log->slot >= KVM_MEMORY_SLOTS)
393                 goto out;
394
395         memslot = &kvm->memslots[log->slot];
396         r = -ENOENT;
397         if (!memslot->dirty_bitmap)
398                 goto out;
399
400         n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
401
402         for (i = 0; !any && i < n/sizeof(long); ++i)
403                 any = memslot->dirty_bitmap[i];
404
405         r = -EFAULT;
406         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
407                 goto out;
408
409         if (any)
410                 *is_dirty = 1;
411
412         r = 0;
413 out:
414         return r;
415 }
416
417 int is_error_page(struct page *page)
418 {
419         return page == bad_page;
420 }
421 EXPORT_SYMBOL_GPL(is_error_page);
422
423 static inline unsigned long bad_hva(void)
424 {
425         return PAGE_OFFSET;
426 }
427
428 int kvm_is_error_hva(unsigned long addr)
429 {
430         return addr == bad_hva();
431 }
432 EXPORT_SYMBOL_GPL(kvm_is_error_hva);
433
434 static struct kvm_memory_slot *__gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
435 {
436         int i;
437
438         for (i = 0; i < kvm->nmemslots; ++i) {
439                 struct kvm_memory_slot *memslot = &kvm->memslots[i];
440
441                 if (gfn >= memslot->base_gfn
442                     && gfn < memslot->base_gfn + memslot->npages)
443                         return memslot;
444         }
445         return NULL;
446 }
447
448 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
449 {
450         gfn = unalias_gfn(kvm, gfn);
451         return __gfn_to_memslot(kvm, gfn);
452 }
453
454 int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
455 {
456         int i;
457
458         gfn = unalias_gfn(kvm, gfn);
459         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
460                 struct kvm_memory_slot *memslot = &kvm->memslots[i];
461
462                 if (gfn >= memslot->base_gfn
463                     && gfn < memslot->base_gfn + memslot->npages)
464                         return 1;
465         }
466         return 0;
467 }
468 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
469
470 static unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
471 {
472         struct kvm_memory_slot *slot;
473
474         gfn = unalias_gfn(kvm, gfn);
475         slot = __gfn_to_memslot(kvm, gfn);
476         if (!slot)
477                 return bad_hva();
478         return (slot->userspace_addr + (gfn - slot->base_gfn) * PAGE_SIZE);
479 }
480
481 /*
482  * Requires current->mm->mmap_sem to be held
483  */
484 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
485 {
486         struct page *page[1];
487         unsigned long addr;
488         int npages;
489
490         might_sleep();
491
492         addr = gfn_to_hva(kvm, gfn);
493         if (kvm_is_error_hva(addr)) {
494                 get_page(bad_page);
495                 return bad_page;
496         }
497
498         npages = get_user_pages(current, current->mm, addr, 1, 1, 1, page,
499                                 NULL);
500
501         if (npages != 1) {
502                 get_page(bad_page);
503                 return bad_page;
504         }
505
506         return page[0];
507 }
508
509 EXPORT_SYMBOL_GPL(gfn_to_page);
510
511 void kvm_release_page_clean(struct page *page)
512 {
513         put_page(page);
514 }
515 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
516
517 void kvm_release_page_dirty(struct page *page)
518 {
519         if (!PageReserved(page))
520                 SetPageDirty(page);
521         put_page(page);
522 }
523 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
524
525 static int next_segment(unsigned long len, int offset)
526 {
527         if (len > PAGE_SIZE - offset)
528                 return PAGE_SIZE - offset;
529         else
530                 return len;
531 }
532
533 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
534                         int len)
535 {
536         int r;
537         unsigned long addr;
538
539         addr = gfn_to_hva(kvm, gfn);
540         if (kvm_is_error_hva(addr))
541                 return -EFAULT;
542         r = copy_from_user(data, (void __user *)addr + offset, len);
543         if (r)
544                 return -EFAULT;
545         return 0;
546 }
547 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
548
549 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
550 {
551         gfn_t gfn = gpa >> PAGE_SHIFT;
552         int seg;
553         int offset = offset_in_page(gpa);
554         int ret;
555
556         while ((seg = next_segment(len, offset)) != 0) {
557                 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
558                 if (ret < 0)
559                         return ret;
560                 offset = 0;
561                 len -= seg;
562                 data += seg;
563                 ++gfn;
564         }
565         return 0;
566 }
567 EXPORT_SYMBOL_GPL(kvm_read_guest);
568
569 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
570                           unsigned long len)
571 {
572         int r;
573         unsigned long addr;
574         gfn_t gfn = gpa >> PAGE_SHIFT;
575         int offset = offset_in_page(gpa);
576
577         addr = gfn_to_hva(kvm, gfn);
578         if (kvm_is_error_hva(addr))
579                 return -EFAULT;
580         pagefault_disable();
581         r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
582         pagefault_enable();
583         if (r)
584                 return -EFAULT;
585         return 0;
586 }
587 EXPORT_SYMBOL(kvm_read_guest_atomic);
588
589 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
590                          int offset, int len)
591 {
592         int r;
593         unsigned long addr;
594
595         addr = gfn_to_hva(kvm, gfn);
596         if (kvm_is_error_hva(addr))
597                 return -EFAULT;
598         r = copy_to_user((void __user *)addr + offset, data, len);
599         if (r)
600                 return -EFAULT;
601         mark_page_dirty(kvm, gfn);
602         return 0;
603 }
604 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
605
606 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
607                     unsigned long len)
608 {
609         gfn_t gfn = gpa >> PAGE_SHIFT;
610         int seg;
611         int offset = offset_in_page(gpa);
612         int ret;
613
614         while ((seg = next_segment(len, offset)) != 0) {
615                 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
616                 if (ret < 0)
617                         return ret;
618                 offset = 0;
619                 len -= seg;
620                 data += seg;
621                 ++gfn;
622         }
623         return 0;
624 }
625
626 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
627 {
628         return kvm_write_guest_page(kvm, gfn, empty_zero_page, offset, len);
629 }
630 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
631
632 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
633 {
634         gfn_t gfn = gpa >> PAGE_SHIFT;
635         int seg;
636         int offset = offset_in_page(gpa);
637         int ret;
638
639         while ((seg = next_segment(len, offset)) != 0) {
640                 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
641                 if (ret < 0)
642                         return ret;
643                 offset = 0;
644                 len -= seg;
645                 ++gfn;
646         }
647         return 0;
648 }
649 EXPORT_SYMBOL_GPL(kvm_clear_guest);
650
651 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
652 {
653         struct kvm_memory_slot *memslot;
654
655         gfn = unalias_gfn(kvm, gfn);
656         memslot = __gfn_to_memslot(kvm, gfn);
657         if (memslot && memslot->dirty_bitmap) {
658                 unsigned long rel_gfn = gfn - memslot->base_gfn;
659
660                 /* avoid RMW */
661                 if (!test_bit(rel_gfn, memslot->dirty_bitmap))
662                         set_bit(rel_gfn, memslot->dirty_bitmap);
663         }
664 }
665
666 /*
667  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
668  */
669 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
670 {
671         DECLARE_WAITQUEUE(wait, current);
672
673         add_wait_queue(&vcpu->wq, &wait);
674
675         /*
676          * We will block until either an interrupt or a signal wakes us up
677          */
678         while (!kvm_cpu_has_interrupt(vcpu)
679                && !signal_pending(current)
680                && !kvm_arch_vcpu_runnable(vcpu)) {
681                 set_current_state(TASK_INTERRUPTIBLE);
682                 vcpu_put(vcpu);
683                 schedule();
684                 vcpu_load(vcpu);
685         }
686
687         __set_current_state(TASK_RUNNING);
688         remove_wait_queue(&vcpu->wq, &wait);
689 }
690
691 void kvm_resched(struct kvm_vcpu *vcpu)
692 {
693         if (!need_resched())
694                 return;
695         cond_resched();
696 }
697 EXPORT_SYMBOL_GPL(kvm_resched);
698
699 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
700 {
701         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
702         struct page *page;
703
704         if (vmf->pgoff == 0)
705                 page = virt_to_page(vcpu->run);
706 #ifdef CONFIG_X86
707         else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
708                 page = virt_to_page(vcpu->arch.pio_data);
709 #endif
710         else
711                 return VM_FAULT_SIGBUS;
712         get_page(page);
713         vmf->page = page;
714         return 0;
715 }
716
717 static struct vm_operations_struct kvm_vcpu_vm_ops = {
718         .fault = kvm_vcpu_fault,
719 };
720
721 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
722 {
723         vma->vm_ops = &kvm_vcpu_vm_ops;
724         return 0;
725 }
726
727 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
728 {
729         struct kvm_vcpu *vcpu = filp->private_data;
730
731         fput(vcpu->kvm->filp);
732         return 0;
733 }
734
735 static const struct file_operations kvm_vcpu_fops = {
736         .release        = kvm_vcpu_release,
737         .unlocked_ioctl = kvm_vcpu_ioctl,
738         .compat_ioctl   = kvm_vcpu_ioctl,
739         .mmap           = kvm_vcpu_mmap,
740 };
741
742 /*
743  * Allocates an inode for the vcpu.
744  */
745 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
746 {
747         int fd, r;
748         struct inode *inode;
749         struct file *file;
750
751         r = anon_inode_getfd(&fd, &inode, &file,
752                              "kvm-vcpu", &kvm_vcpu_fops, vcpu);
753         if (r)
754                 return r;
755         atomic_inc(&vcpu->kvm->filp->f_count);
756         return fd;
757 }
758
759 /*
760  * Creates some virtual cpus.  Good luck creating more than one.
761  */
762 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, int n)
763 {
764         int r;
765         struct kvm_vcpu *vcpu;
766
767         if (!valid_vcpu(n))
768                 return -EINVAL;
769
770         vcpu = kvm_arch_vcpu_create(kvm, n);
771         if (IS_ERR(vcpu))
772                 return PTR_ERR(vcpu);
773
774         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
775
776         r = kvm_arch_vcpu_setup(vcpu);
777         if (r)
778                 goto vcpu_destroy;
779
780         mutex_lock(&kvm->lock);
781         if (kvm->vcpus[n]) {
782                 r = -EEXIST;
783                 mutex_unlock(&kvm->lock);
784                 goto vcpu_destroy;
785         }
786         kvm->vcpus[n] = vcpu;
787         mutex_unlock(&kvm->lock);
788
789         /* Now it's all set up, let userspace reach it */
790         r = create_vcpu_fd(vcpu);
791         if (r < 0)
792                 goto unlink;
793         return r;
794
795 unlink:
796         mutex_lock(&kvm->lock);
797         kvm->vcpus[n] = NULL;
798         mutex_unlock(&kvm->lock);
799 vcpu_destroy:
800         kvm_arch_vcpu_destroy(vcpu);
801         return r;
802 }
803
804 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
805 {
806         if (sigset) {
807                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
808                 vcpu->sigset_active = 1;
809                 vcpu->sigset = *sigset;
810         } else
811                 vcpu->sigset_active = 0;
812         return 0;
813 }
814
815 static long kvm_vcpu_ioctl(struct file *filp,
816                            unsigned int ioctl, unsigned long arg)
817 {
818         struct kvm_vcpu *vcpu = filp->private_data;
819         void __user *argp = (void __user *)arg;
820         int r;
821
822         if (vcpu->kvm->mm != current->mm)
823                 return -EIO;
824         switch (ioctl) {
825         case KVM_RUN:
826                 r = -EINVAL;
827                 if (arg)
828                         goto out;
829                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
830                 break;
831         case KVM_GET_REGS: {
832                 struct kvm_regs kvm_regs;
833
834                 memset(&kvm_regs, 0, sizeof kvm_regs);
835                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, &kvm_regs);
836                 if (r)
837                         goto out;
838                 r = -EFAULT;
839                 if (copy_to_user(argp, &kvm_regs, sizeof kvm_regs))
840                         goto out;
841                 r = 0;
842                 break;
843         }
844         case KVM_SET_REGS: {
845                 struct kvm_regs kvm_regs;
846
847                 r = -EFAULT;
848                 if (copy_from_user(&kvm_regs, argp, sizeof kvm_regs))
849                         goto out;
850                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, &kvm_regs);
851                 if (r)
852                         goto out;
853                 r = 0;
854                 break;
855         }
856         case KVM_GET_SREGS: {
857                 struct kvm_sregs kvm_sregs;
858
859                 memset(&kvm_sregs, 0, sizeof kvm_sregs);
860                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, &kvm_sregs);
861                 if (r)
862                         goto out;
863                 r = -EFAULT;
864                 if (copy_to_user(argp, &kvm_sregs, sizeof kvm_sregs))
865                         goto out;
866                 r = 0;
867                 break;
868         }
869         case KVM_SET_SREGS: {
870                 struct kvm_sregs kvm_sregs;
871
872                 r = -EFAULT;
873                 if (copy_from_user(&kvm_sregs, argp, sizeof kvm_sregs))
874                         goto out;
875                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, &kvm_sregs);
876                 if (r)
877                         goto out;
878                 r = 0;
879                 break;
880         }
881         case KVM_TRANSLATE: {
882                 struct kvm_translation tr;
883
884                 r = -EFAULT;
885                 if (copy_from_user(&tr, argp, sizeof tr))
886                         goto out;
887                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
888                 if (r)
889                         goto out;
890                 r = -EFAULT;
891                 if (copy_to_user(argp, &tr, sizeof tr))
892                         goto out;
893                 r = 0;
894                 break;
895         }
896         case KVM_DEBUG_GUEST: {
897                 struct kvm_debug_guest dbg;
898
899                 r = -EFAULT;
900                 if (copy_from_user(&dbg, argp, sizeof dbg))
901                         goto out;
902                 r = kvm_arch_vcpu_ioctl_debug_guest(vcpu, &dbg);
903                 if (r)
904                         goto out;
905                 r = 0;
906                 break;
907         }
908         case KVM_SET_SIGNAL_MASK: {
909                 struct kvm_signal_mask __user *sigmask_arg = argp;
910                 struct kvm_signal_mask kvm_sigmask;
911                 sigset_t sigset, *p;
912
913                 p = NULL;
914                 if (argp) {
915                         r = -EFAULT;
916                         if (copy_from_user(&kvm_sigmask, argp,
917                                            sizeof kvm_sigmask))
918                                 goto out;
919                         r = -EINVAL;
920                         if (kvm_sigmask.len != sizeof sigset)
921                                 goto out;
922                         r = -EFAULT;
923                         if (copy_from_user(&sigset, sigmask_arg->sigset,
924                                            sizeof sigset))
925                                 goto out;
926                         p = &sigset;
927                 }
928                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
929                 break;
930         }
931         case KVM_GET_FPU: {
932                 struct kvm_fpu fpu;
933
934                 memset(&fpu, 0, sizeof fpu);
935                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, &fpu);
936                 if (r)
937                         goto out;
938                 r = -EFAULT;
939                 if (copy_to_user(argp, &fpu, sizeof fpu))
940                         goto out;
941                 r = 0;
942                 break;
943         }
944         case KVM_SET_FPU: {
945                 struct kvm_fpu fpu;
946
947                 r = -EFAULT;
948                 if (copy_from_user(&fpu, argp, sizeof fpu))
949                         goto out;
950                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, &fpu);
951                 if (r)
952                         goto out;
953                 r = 0;
954                 break;
955         }
956         default:
957                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
958         }
959 out:
960         return r;
961 }
962
963 static long kvm_vm_ioctl(struct file *filp,
964                            unsigned int ioctl, unsigned long arg)
965 {
966         struct kvm *kvm = filp->private_data;
967         void __user *argp = (void __user *)arg;
968         int r;
969
970         if (kvm->mm != current->mm)
971                 return -EIO;
972         switch (ioctl) {
973         case KVM_CREATE_VCPU:
974                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
975                 if (r < 0)
976                         goto out;
977                 break;
978         case KVM_SET_USER_MEMORY_REGION: {
979                 struct kvm_userspace_memory_region kvm_userspace_mem;
980
981                 r = -EFAULT;
982                 if (copy_from_user(&kvm_userspace_mem, argp,
983                                                 sizeof kvm_userspace_mem))
984                         goto out;
985
986                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
987                 if (r)
988                         goto out;
989                 break;
990         }
991         case KVM_GET_DIRTY_LOG: {
992                 struct kvm_dirty_log log;
993
994                 r = -EFAULT;
995                 if (copy_from_user(&log, argp, sizeof log))
996                         goto out;
997                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
998                 if (r)
999                         goto out;
1000                 break;
1001         }
1002         default:
1003                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
1004         }
1005 out:
1006         return r;
1007 }
1008
1009 static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1010 {
1011         struct kvm *kvm = vma->vm_file->private_data;
1012         struct page *page;
1013
1014         if (!kvm_is_visible_gfn(kvm, vmf->pgoff))
1015                 return VM_FAULT_SIGBUS;
1016         page = gfn_to_page(kvm, vmf->pgoff);
1017         if (is_error_page(page)) {
1018                 kvm_release_page_clean(page);
1019                 return VM_FAULT_SIGBUS;
1020         }
1021         vmf->page = page;
1022         return 0;
1023 }
1024
1025 static struct vm_operations_struct kvm_vm_vm_ops = {
1026         .fault = kvm_vm_fault,
1027 };
1028
1029 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
1030 {
1031         vma->vm_ops = &kvm_vm_vm_ops;
1032         return 0;
1033 }
1034
1035 static const struct file_operations kvm_vm_fops = {
1036         .release        = kvm_vm_release,
1037         .unlocked_ioctl = kvm_vm_ioctl,
1038         .compat_ioctl   = kvm_vm_ioctl,
1039         .mmap           = kvm_vm_mmap,
1040 };
1041
1042 static int kvm_dev_ioctl_create_vm(void)
1043 {
1044         int fd, r;
1045         struct inode *inode;
1046         struct file *file;
1047         struct kvm *kvm;
1048
1049         kvm = kvm_create_vm();
1050         if (IS_ERR(kvm))
1051                 return PTR_ERR(kvm);
1052         r = anon_inode_getfd(&fd, &inode, &file, "kvm-vm", &kvm_vm_fops, kvm);
1053         if (r) {
1054                 kvm_destroy_vm(kvm);
1055                 return r;
1056         }
1057
1058         kvm->filp = file;
1059
1060         return fd;
1061 }
1062
1063 static long kvm_dev_ioctl(struct file *filp,
1064                           unsigned int ioctl, unsigned long arg)
1065 {
1066         void __user *argp = (void __user *)arg;
1067         long r = -EINVAL;
1068
1069         switch (ioctl) {
1070         case KVM_GET_API_VERSION:
1071                 r = -EINVAL;
1072                 if (arg)
1073                         goto out;
1074                 r = KVM_API_VERSION;
1075                 break;
1076         case KVM_CREATE_VM:
1077                 r = -EINVAL;
1078                 if (arg)
1079                         goto out;
1080                 r = kvm_dev_ioctl_create_vm();
1081                 break;
1082         case KVM_CHECK_EXTENSION:
1083                 r = kvm_dev_ioctl_check_extension((long)argp);
1084                 break;
1085         case KVM_GET_VCPU_MMAP_SIZE:
1086                 r = -EINVAL;
1087                 if (arg)
1088                         goto out;
1089                 r = PAGE_SIZE;     /* struct kvm_run */
1090 #ifdef CONFIG_X86
1091                 r += PAGE_SIZE;    /* pio data page */
1092 #endif
1093                 break;
1094         default:
1095                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
1096         }
1097 out:
1098         return r;
1099 }
1100
1101 static struct file_operations kvm_chardev_ops = {
1102         .unlocked_ioctl = kvm_dev_ioctl,
1103         .compat_ioctl   = kvm_dev_ioctl,
1104 };
1105
1106 static struct miscdevice kvm_dev = {
1107         KVM_MINOR,
1108         "kvm",
1109         &kvm_chardev_ops,
1110 };
1111
1112 static void hardware_enable(void *junk)
1113 {
1114         int cpu = raw_smp_processor_id();
1115
1116         if (cpu_isset(cpu, cpus_hardware_enabled))
1117                 return;
1118         cpu_set(cpu, cpus_hardware_enabled);
1119         kvm_arch_hardware_enable(NULL);
1120 }
1121
1122 static void hardware_disable(void *junk)
1123 {
1124         int cpu = raw_smp_processor_id();
1125
1126         if (!cpu_isset(cpu, cpus_hardware_enabled))
1127                 return;
1128         cpu_clear(cpu, cpus_hardware_enabled);
1129         decache_vcpus_on_cpu(cpu);
1130         kvm_arch_hardware_disable(NULL);
1131 }
1132
1133 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
1134                            void *v)
1135 {
1136         int cpu = (long)v;
1137
1138         val &= ~CPU_TASKS_FROZEN;
1139         switch (val) {
1140         case CPU_DYING:
1141                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
1142                        cpu);
1143                 hardware_disable(NULL);
1144                 break;
1145         case CPU_UP_CANCELED:
1146                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
1147                        cpu);
1148                 smp_call_function_single(cpu, hardware_disable, NULL, 0, 1);
1149                 break;
1150         case CPU_ONLINE:
1151                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
1152                        cpu);
1153                 smp_call_function_single(cpu, hardware_enable, NULL, 0, 1);
1154                 break;
1155         }
1156         return NOTIFY_OK;
1157 }
1158
1159 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
1160                       void *v)
1161 {
1162         if (val == SYS_RESTART) {
1163                 /*
1164                  * Some (well, at least mine) BIOSes hang on reboot if
1165                  * in vmx root mode.
1166                  */
1167                 printk(KERN_INFO "kvm: exiting hardware virtualization\n");
1168                 on_each_cpu(hardware_disable, NULL, 0, 1);
1169         }
1170         return NOTIFY_OK;
1171 }
1172
1173 static struct notifier_block kvm_reboot_notifier = {
1174         .notifier_call = kvm_reboot,
1175         .priority = 0,
1176 };
1177
1178 void kvm_io_bus_init(struct kvm_io_bus *bus)
1179 {
1180         memset(bus, 0, sizeof(*bus));
1181 }
1182
1183 void kvm_io_bus_destroy(struct kvm_io_bus *bus)
1184 {
1185         int i;
1186
1187         for (i = 0; i < bus->dev_count; i++) {
1188                 struct kvm_io_device *pos = bus->devs[i];
1189
1190                 kvm_iodevice_destructor(pos);
1191         }
1192 }
1193
1194 struct kvm_io_device *kvm_io_bus_find_dev(struct kvm_io_bus *bus, gpa_t addr)
1195 {
1196         int i;
1197
1198         for (i = 0; i < bus->dev_count; i++) {
1199                 struct kvm_io_device *pos = bus->devs[i];
1200
1201                 if (pos->in_range(pos, addr))
1202                         return pos;
1203         }
1204
1205         return NULL;
1206 }
1207
1208 void kvm_io_bus_register_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev)
1209 {
1210         BUG_ON(bus->dev_count > (NR_IOBUS_DEVS-1));
1211
1212         bus->devs[bus->dev_count++] = dev;
1213 }
1214
1215 static struct notifier_block kvm_cpu_notifier = {
1216         .notifier_call = kvm_cpu_hotplug,
1217         .priority = 20, /* must be > scheduler priority */
1218 };
1219
1220 static int vm_stat_get(void *_offset, u64 *val)
1221 {
1222         unsigned offset = (long)_offset;
1223         struct kvm *kvm;
1224
1225         *val = 0;
1226         spin_lock(&kvm_lock);
1227         list_for_each_entry(kvm, &vm_list, vm_list)
1228                 *val += *(u32 *)((void *)kvm + offset);
1229         spin_unlock(&kvm_lock);
1230         return 0;
1231 }
1232
1233 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
1234
1235 static int vcpu_stat_get(void *_offset, u64 *val)
1236 {
1237         unsigned offset = (long)_offset;
1238         struct kvm *kvm;
1239         struct kvm_vcpu *vcpu;
1240         int i;
1241
1242         *val = 0;
1243         spin_lock(&kvm_lock);
1244         list_for_each_entry(kvm, &vm_list, vm_list)
1245                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
1246                         vcpu = kvm->vcpus[i];
1247                         if (vcpu)
1248                                 *val += *(u32 *)((void *)vcpu + offset);
1249                 }
1250         spin_unlock(&kvm_lock);
1251         return 0;
1252 }
1253
1254 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
1255
1256 static struct file_operations *stat_fops[] = {
1257         [KVM_STAT_VCPU] = &vcpu_stat_fops,
1258         [KVM_STAT_VM]   = &vm_stat_fops,
1259 };
1260
1261 static void kvm_init_debug(void)
1262 {
1263         struct kvm_stats_debugfs_item *p;
1264
1265         debugfs_dir = debugfs_create_dir("kvm", NULL);
1266         for (p = debugfs_entries; p->name; ++p)
1267                 p->dentry = debugfs_create_file(p->name, 0444, debugfs_dir,
1268                                                 (void *)(long)p->offset,
1269                                                 stat_fops[p->kind]);
1270 }
1271
1272 static void kvm_exit_debug(void)
1273 {
1274         struct kvm_stats_debugfs_item *p;
1275
1276         for (p = debugfs_entries; p->name; ++p)
1277                 debugfs_remove(p->dentry);
1278         debugfs_remove(debugfs_dir);
1279 }
1280
1281 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
1282 {
1283         hardware_disable(NULL);
1284         return 0;
1285 }
1286
1287 static int kvm_resume(struct sys_device *dev)
1288 {
1289         hardware_enable(NULL);
1290         return 0;
1291 }
1292
1293 static struct sysdev_class kvm_sysdev_class = {
1294         .name = "kvm",
1295         .suspend = kvm_suspend,
1296         .resume = kvm_resume,
1297 };
1298
1299 static struct sys_device kvm_sysdev = {
1300         .id = 0,
1301         .cls = &kvm_sysdev_class,
1302 };
1303
1304 struct page *bad_page;
1305
1306 static inline
1307 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
1308 {
1309         return container_of(pn, struct kvm_vcpu, preempt_notifier);
1310 }
1311
1312 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
1313 {
1314         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
1315
1316         kvm_arch_vcpu_load(vcpu, cpu);
1317 }
1318
1319 static void kvm_sched_out(struct preempt_notifier *pn,
1320                           struct task_struct *next)
1321 {
1322         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
1323
1324         kvm_arch_vcpu_put(vcpu);
1325 }
1326
1327 int kvm_init(void *opaque, unsigned int vcpu_size,
1328                   struct module *module)
1329 {
1330         int r;
1331         int cpu;
1332
1333         kvm_init_debug();
1334
1335         r = kvm_arch_init(opaque);
1336         if (r)
1337                 goto out_fail;
1338
1339         bad_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
1340
1341         if (bad_page == NULL) {
1342                 r = -ENOMEM;
1343                 goto out;
1344         }
1345
1346         r = kvm_arch_hardware_setup();
1347         if (r < 0)
1348                 goto out_free_0;
1349
1350         for_each_online_cpu(cpu) {
1351                 smp_call_function_single(cpu,
1352                                 kvm_arch_check_processor_compat,
1353                                 &r, 0, 1);
1354                 if (r < 0)
1355                         goto out_free_1;
1356         }
1357
1358         on_each_cpu(hardware_enable, NULL, 0, 1);
1359         r = register_cpu_notifier(&kvm_cpu_notifier);
1360         if (r)
1361                 goto out_free_2;
1362         register_reboot_notifier(&kvm_reboot_notifier);
1363
1364         r = sysdev_class_register(&kvm_sysdev_class);
1365         if (r)
1366                 goto out_free_3;
1367
1368         r = sysdev_register(&kvm_sysdev);
1369         if (r)
1370                 goto out_free_4;
1371
1372         /* A kmem cache lets us meet the alignment requirements of fx_save. */
1373         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size,
1374                                            __alignof__(struct kvm_vcpu),
1375                                            0, NULL);
1376         if (!kvm_vcpu_cache) {
1377                 r = -ENOMEM;
1378                 goto out_free_5;
1379         }
1380
1381         kvm_chardev_ops.owner = module;
1382
1383         r = misc_register(&kvm_dev);
1384         if (r) {
1385                 printk(KERN_ERR "kvm: misc device register failed\n");
1386                 goto out_free;
1387         }
1388
1389         kvm_preempt_ops.sched_in = kvm_sched_in;
1390         kvm_preempt_ops.sched_out = kvm_sched_out;
1391
1392         return 0;
1393
1394 out_free:
1395         kmem_cache_destroy(kvm_vcpu_cache);
1396 out_free_5:
1397         sysdev_unregister(&kvm_sysdev);
1398 out_free_4:
1399         sysdev_class_unregister(&kvm_sysdev_class);
1400 out_free_3:
1401         unregister_reboot_notifier(&kvm_reboot_notifier);
1402         unregister_cpu_notifier(&kvm_cpu_notifier);
1403 out_free_2:
1404         on_each_cpu(hardware_disable, NULL, 0, 1);
1405 out_free_1:
1406         kvm_arch_hardware_unsetup();
1407 out_free_0:
1408         __free_page(bad_page);
1409 out:
1410         kvm_arch_exit();
1411         kvm_exit_debug();
1412 out_fail:
1413         return r;
1414 }
1415 EXPORT_SYMBOL_GPL(kvm_init);
1416
1417 void kvm_exit(void)
1418 {
1419         misc_deregister(&kvm_dev);
1420         kmem_cache_destroy(kvm_vcpu_cache);
1421         sysdev_unregister(&kvm_sysdev);
1422         sysdev_class_unregister(&kvm_sysdev_class);
1423         unregister_reboot_notifier(&kvm_reboot_notifier);
1424         unregister_cpu_notifier(&kvm_cpu_notifier);
1425         on_each_cpu(hardware_disable, NULL, 0, 1);
1426         kvm_arch_hardware_unsetup();
1427         kvm_arch_exit();
1428         kvm_exit_debug();
1429         __free_page(bad_page);
1430 }
1431 EXPORT_SYMBOL_GPL(kvm_exit);