1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <kvm/iodev.h>
18 #include <linux/kvm_host.h>
19 #include <linux/kvm.h>
20 #include <linux/module.h>
21 #include <linux/errno.h>
22 #include <linux/percpu.h>
24 #include <linux/miscdevice.h>
25 #include <linux/vmalloc.h>
26 #include <linux/reboot.h>
27 #include <linux/debugfs.h>
28 #include <linux/highmem.h>
29 #include <linux/file.h>
30 #include <linux/syscore_ops.h>
31 #include <linux/cpu.h>
32 #include <linux/sched/signal.h>
33 #include <linux/sched/mm.h>
34 #include <linux/sched/stat.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 #include <linux/sort.h>
50 #include <linux/bsearch.h>
52 #include <linux/lockdep.h>
53 #include <linux/kthread.h>
55 #include <asm/processor.h>
56 #include <asm/ioctl.h>
57 #include <linux/uaccess.h>
59 #include "coalesced_mmio.h"
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/kvm.h>
66 #include <linux/kvm_dirty_ring.h>
68 /* Worst case buffer size needed for holding an integer. */
69 #define ITOA_MAX_LEN 12
71 MODULE_AUTHOR("Qumranet");
72 MODULE_LICENSE("GPL");
74 /* Architectures should define their poll value according to the halt latency */
75 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
76 module_param(halt_poll_ns, uint, 0644);
77 EXPORT_SYMBOL_GPL(halt_poll_ns);
79 /* Default doubles per-vcpu halt_poll_ns. */
80 unsigned int halt_poll_ns_grow = 2;
81 module_param(halt_poll_ns_grow, uint, 0644);
82 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
84 /* The start value to grow halt_poll_ns from */
85 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
86 module_param(halt_poll_ns_grow_start, uint, 0644);
87 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
89 /* Default resets per-vcpu halt_poll_ns . */
90 unsigned int halt_poll_ns_shrink;
91 module_param(halt_poll_ns_shrink, uint, 0644);
92 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
97 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
100 DEFINE_MUTEX(kvm_lock);
101 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
104 static cpumask_var_t cpus_hardware_enabled;
105 static int kvm_usage_count;
106 static atomic_t hardware_enable_failed;
108 static struct kmem_cache *kvm_vcpu_cache;
110 static __read_mostly struct preempt_ops kvm_preempt_ops;
111 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
113 struct dentry *kvm_debugfs_dir;
114 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
116 static int kvm_debugfs_num_entries;
117 static const struct file_operations stat_fops_per_vm;
119 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
121 #ifdef CONFIG_KVM_COMPAT
122 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
124 #define KVM_COMPAT(c) .compat_ioctl = (c)
127 * For architectures that don't implement a compat infrastructure,
128 * adopt a double line of defense:
129 * - Prevent a compat task from opening /dev/kvm
130 * - If the open has been done by a 64bit task, and the KVM fd
131 * passed to a compat task, let the ioctls fail.
133 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
134 unsigned long arg) { return -EINVAL; }
136 static int kvm_no_compat_open(struct inode *inode, struct file *file)
138 return is_compat_task() ? -ENODEV : 0;
140 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
141 .open = kvm_no_compat_open
143 static int hardware_enable_all(void);
144 static void hardware_disable_all(void);
146 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
148 __visible bool kvm_rebooting;
149 EXPORT_SYMBOL_GPL(kvm_rebooting);
151 #define KVM_EVENT_CREATE_VM 0
152 #define KVM_EVENT_DESTROY_VM 1
153 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
154 static unsigned long long kvm_createvm_count;
155 static unsigned long long kvm_active_vms;
157 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
158 unsigned long start, unsigned long end)
162 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
165 * The metadata used by is_zone_device_page() to determine whether or
166 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
167 * the device has been pinned, e.g. by get_user_pages(). WARN if the
168 * page_count() is zero to help detect bad usage of this helper.
170 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
173 return is_zone_device_page(pfn_to_page(pfn));
176 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
179 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
180 * perspective they are "normal" pages, albeit with slightly different
184 return PageReserved(pfn_to_page(pfn)) &&
186 !kvm_is_zone_device_pfn(pfn);
191 bool kvm_is_transparent_hugepage(kvm_pfn_t pfn)
193 struct page *page = pfn_to_page(pfn);
195 if (!PageTransCompoundMap(page))
198 return is_transparent_hugepage(compound_head(page));
202 * Switches to specified vcpu, until a matching vcpu_put()
204 void vcpu_load(struct kvm_vcpu *vcpu)
208 __this_cpu_write(kvm_running_vcpu, vcpu);
209 preempt_notifier_register(&vcpu->preempt_notifier);
210 kvm_arch_vcpu_load(vcpu, cpu);
213 EXPORT_SYMBOL_GPL(vcpu_load);
215 void vcpu_put(struct kvm_vcpu *vcpu)
218 kvm_arch_vcpu_put(vcpu);
219 preempt_notifier_unregister(&vcpu->preempt_notifier);
220 __this_cpu_write(kvm_running_vcpu, NULL);
223 EXPORT_SYMBOL_GPL(vcpu_put);
225 /* TODO: merge with kvm_arch_vcpu_should_kick */
226 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
228 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
231 * We need to wait for the VCPU to reenable interrupts and get out of
232 * READING_SHADOW_PAGE_TABLES mode.
234 if (req & KVM_REQUEST_WAIT)
235 return mode != OUTSIDE_GUEST_MODE;
238 * Need to kick a running VCPU, but otherwise there is nothing to do.
240 return mode == IN_GUEST_MODE;
243 static void ack_flush(void *_completed)
247 static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
250 cpus = cpu_online_mask;
252 if (cpumask_empty(cpus))
255 smp_call_function_many(cpus, ack_flush, NULL, wait);
259 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
260 struct kvm_vcpu *except,
261 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
264 struct kvm_vcpu *vcpu;
269 kvm_for_each_vcpu(i, vcpu, kvm) {
270 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
274 kvm_make_request(req, vcpu);
277 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
280 if (tmp != NULL && cpu != -1 && cpu != me &&
281 kvm_request_needs_ipi(vcpu, req))
282 __cpumask_set_cpu(cpu, tmp);
285 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
291 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
292 struct kvm_vcpu *except)
297 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
299 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
301 free_cpumask_var(cpus);
305 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
307 return kvm_make_all_cpus_request_except(kvm, req, NULL);
310 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
311 void kvm_flush_remote_tlbs(struct kvm *kvm)
314 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
315 * kvm_make_all_cpus_request.
317 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
320 * We want to publish modifications to the page tables before reading
321 * mode. Pairs with a memory barrier in arch-specific code.
322 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
323 * and smp_mb in walk_shadow_page_lockless_begin/end.
324 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
326 * There is already an smp_mb__after_atomic() before
327 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
330 if (!kvm_arch_flush_remote_tlb(kvm)
331 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
332 ++kvm->stat.remote_tlb_flush;
333 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
335 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
338 void kvm_reload_remote_mmus(struct kvm *kvm)
340 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
343 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
344 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
347 gfp_flags |= mc->gfp_zero;
350 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
352 return (void *)__get_free_page(gfp_flags);
355 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
359 if (mc->nobjs >= min)
361 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
362 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
364 return mc->nobjs >= min ? 0 : -ENOMEM;
365 mc->objects[mc->nobjs++] = obj;
370 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
375 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
379 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
381 free_page((unsigned long)mc->objects[--mc->nobjs]);
385 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
389 if (WARN_ON(!mc->nobjs))
390 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
392 p = mc->objects[--mc->nobjs];
398 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
400 mutex_init(&vcpu->mutex);
405 rcuwait_init(&vcpu->wait);
406 kvm_async_pf_vcpu_init(vcpu);
409 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
411 kvm_vcpu_set_in_spin_loop(vcpu, false);
412 kvm_vcpu_set_dy_eligible(vcpu, false);
413 vcpu->preempted = false;
415 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
418 void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
420 kvm_dirty_ring_free(&vcpu->dirty_ring);
421 kvm_arch_vcpu_destroy(vcpu);
424 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
425 * the vcpu->pid pointer, and at destruction time all file descriptors
428 put_pid(rcu_dereference_protected(vcpu->pid, 1));
430 free_page((unsigned long)vcpu->run);
431 kmem_cache_free(kvm_vcpu_cache, vcpu);
433 EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
435 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
436 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
438 return container_of(mn, struct kvm, mmu_notifier);
441 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
442 struct mm_struct *mm,
443 unsigned long start, unsigned long end)
445 struct kvm *kvm = mmu_notifier_to_kvm(mn);
448 idx = srcu_read_lock(&kvm->srcu);
449 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
450 srcu_read_unlock(&kvm->srcu, idx);
453 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
454 struct mm_struct *mm,
455 unsigned long address,
458 struct kvm *kvm = mmu_notifier_to_kvm(mn);
461 idx = srcu_read_lock(&kvm->srcu);
462 spin_lock(&kvm->mmu_lock);
463 kvm->mmu_notifier_seq++;
465 if (kvm_set_spte_hva(kvm, address, pte))
466 kvm_flush_remote_tlbs(kvm);
468 spin_unlock(&kvm->mmu_lock);
469 srcu_read_unlock(&kvm->srcu, idx);
472 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
473 const struct mmu_notifier_range *range)
475 struct kvm *kvm = mmu_notifier_to_kvm(mn);
476 int need_tlb_flush = 0, idx;
478 idx = srcu_read_lock(&kvm->srcu);
479 spin_lock(&kvm->mmu_lock);
481 * The count increase must become visible at unlock time as no
482 * spte can be established without taking the mmu_lock and
483 * count is also read inside the mmu_lock critical section.
485 kvm->mmu_notifier_count++;
486 need_tlb_flush = kvm_unmap_hva_range(kvm, range->start, range->end,
488 /* we've to flush the tlb before the pages can be freed */
489 if (need_tlb_flush || kvm->tlbs_dirty)
490 kvm_flush_remote_tlbs(kvm);
492 spin_unlock(&kvm->mmu_lock);
493 srcu_read_unlock(&kvm->srcu, idx);
498 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
499 const struct mmu_notifier_range *range)
501 struct kvm *kvm = mmu_notifier_to_kvm(mn);
503 spin_lock(&kvm->mmu_lock);
505 * This sequence increase will notify the kvm page fault that
506 * the page that is going to be mapped in the spte could have
509 kvm->mmu_notifier_seq++;
512 * The above sequence increase must be visible before the
513 * below count decrease, which is ensured by the smp_wmb above
514 * in conjunction with the smp_rmb in mmu_notifier_retry().
516 kvm->mmu_notifier_count--;
517 spin_unlock(&kvm->mmu_lock);
519 BUG_ON(kvm->mmu_notifier_count < 0);
522 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
523 struct mm_struct *mm,
527 struct kvm *kvm = mmu_notifier_to_kvm(mn);
530 idx = srcu_read_lock(&kvm->srcu);
531 spin_lock(&kvm->mmu_lock);
533 young = kvm_age_hva(kvm, start, end);
535 kvm_flush_remote_tlbs(kvm);
537 spin_unlock(&kvm->mmu_lock);
538 srcu_read_unlock(&kvm->srcu, idx);
543 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
544 struct mm_struct *mm,
548 struct kvm *kvm = mmu_notifier_to_kvm(mn);
551 idx = srcu_read_lock(&kvm->srcu);
552 spin_lock(&kvm->mmu_lock);
554 * Even though we do not flush TLB, this will still adversely
555 * affect performance on pre-Haswell Intel EPT, where there is
556 * no EPT Access Bit to clear so that we have to tear down EPT
557 * tables instead. If we find this unacceptable, we can always
558 * add a parameter to kvm_age_hva so that it effectively doesn't
559 * do anything on clear_young.
561 * Also note that currently we never issue secondary TLB flushes
562 * from clear_young, leaving this job up to the regular system
563 * cadence. If we find this inaccurate, we might come up with a
564 * more sophisticated heuristic later.
566 young = kvm_age_hva(kvm, start, end);
567 spin_unlock(&kvm->mmu_lock);
568 srcu_read_unlock(&kvm->srcu, idx);
573 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
574 struct mm_struct *mm,
575 unsigned long address)
577 struct kvm *kvm = mmu_notifier_to_kvm(mn);
580 idx = srcu_read_lock(&kvm->srcu);
581 spin_lock(&kvm->mmu_lock);
582 young = kvm_test_age_hva(kvm, address);
583 spin_unlock(&kvm->mmu_lock);
584 srcu_read_unlock(&kvm->srcu, idx);
589 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
590 struct mm_struct *mm)
592 struct kvm *kvm = mmu_notifier_to_kvm(mn);
595 idx = srcu_read_lock(&kvm->srcu);
596 kvm_arch_flush_shadow_all(kvm);
597 srcu_read_unlock(&kvm->srcu, idx);
600 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
601 .invalidate_range = kvm_mmu_notifier_invalidate_range,
602 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
603 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
604 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
605 .clear_young = kvm_mmu_notifier_clear_young,
606 .test_young = kvm_mmu_notifier_test_young,
607 .change_pte = kvm_mmu_notifier_change_pte,
608 .release = kvm_mmu_notifier_release,
611 static int kvm_init_mmu_notifier(struct kvm *kvm)
613 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
614 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
617 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
619 static int kvm_init_mmu_notifier(struct kvm *kvm)
624 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
626 static struct kvm_memslots *kvm_alloc_memslots(void)
629 struct kvm_memslots *slots;
631 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
635 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
636 slots->id_to_index[i] = -1;
641 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
643 if (!memslot->dirty_bitmap)
646 kvfree(memslot->dirty_bitmap);
647 memslot->dirty_bitmap = NULL;
650 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
652 kvm_destroy_dirty_bitmap(slot);
654 kvm_arch_free_memslot(kvm, slot);
660 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
662 struct kvm_memory_slot *memslot;
667 kvm_for_each_memslot(memslot, slots)
668 kvm_free_memslot(kvm, memslot);
673 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
677 if (!kvm->debugfs_dentry)
680 debugfs_remove_recursive(kvm->debugfs_dentry);
682 if (kvm->debugfs_stat_data) {
683 for (i = 0; i < kvm_debugfs_num_entries; i++)
684 kfree(kvm->debugfs_stat_data[i]);
685 kfree(kvm->debugfs_stat_data);
689 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
691 char dir_name[ITOA_MAX_LEN * 2];
692 struct kvm_stat_data *stat_data;
693 struct kvm_stats_debugfs_item *p;
695 if (!debugfs_initialized())
698 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
699 kvm->debugfs_dentry = debugfs_create_dir(dir_name, kvm_debugfs_dir);
701 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
702 sizeof(*kvm->debugfs_stat_data),
704 if (!kvm->debugfs_stat_data)
707 for (p = debugfs_entries; p->name; p++) {
708 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
712 stat_data->kvm = kvm;
713 stat_data->dbgfs_item = p;
714 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
715 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
716 kvm->debugfs_dentry, stat_data,
723 * Called after the VM is otherwise initialized, but just before adding it to
726 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
732 * Called just after removing the VM from the vm_list, but before doing any
735 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
739 static struct kvm *kvm_create_vm(unsigned long type)
741 struct kvm *kvm = kvm_arch_alloc_vm();
746 return ERR_PTR(-ENOMEM);
748 spin_lock_init(&kvm->mmu_lock);
750 kvm->mm = current->mm;
751 kvm_eventfd_init(kvm);
752 mutex_init(&kvm->lock);
753 mutex_init(&kvm->irq_lock);
754 mutex_init(&kvm->slots_lock);
755 INIT_LIST_HEAD(&kvm->devices);
757 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
759 if (init_srcu_struct(&kvm->srcu))
760 goto out_err_no_srcu;
761 if (init_srcu_struct(&kvm->irq_srcu))
762 goto out_err_no_irq_srcu;
764 refcount_set(&kvm->users_count, 1);
765 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
766 struct kvm_memslots *slots = kvm_alloc_memslots();
769 goto out_err_no_arch_destroy_vm;
770 /* Generations must be different for each address space. */
771 slots->generation = i;
772 rcu_assign_pointer(kvm->memslots[i], slots);
775 for (i = 0; i < KVM_NR_BUSES; i++) {
776 rcu_assign_pointer(kvm->buses[i],
777 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
779 goto out_err_no_arch_destroy_vm;
782 kvm->max_halt_poll_ns = halt_poll_ns;
784 r = kvm_arch_init_vm(kvm, type);
786 goto out_err_no_arch_destroy_vm;
788 r = hardware_enable_all();
790 goto out_err_no_disable;
792 #ifdef CONFIG_HAVE_KVM_IRQFD
793 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
796 r = kvm_init_mmu_notifier(kvm);
798 goto out_err_no_mmu_notifier;
800 r = kvm_arch_post_init_vm(kvm);
804 mutex_lock(&kvm_lock);
805 list_add(&kvm->vm_list, &vm_list);
806 mutex_unlock(&kvm_lock);
808 preempt_notifier_inc();
813 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
814 if (kvm->mmu_notifier.ops)
815 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
817 out_err_no_mmu_notifier:
818 hardware_disable_all();
820 kvm_arch_destroy_vm(kvm);
821 out_err_no_arch_destroy_vm:
822 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
823 for (i = 0; i < KVM_NR_BUSES; i++)
824 kfree(kvm_get_bus(kvm, i));
825 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
826 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
827 cleanup_srcu_struct(&kvm->irq_srcu);
829 cleanup_srcu_struct(&kvm->srcu);
831 kvm_arch_free_vm(kvm);
836 static void kvm_destroy_devices(struct kvm *kvm)
838 struct kvm_device *dev, *tmp;
841 * We do not need to take the kvm->lock here, because nobody else
842 * has a reference to the struct kvm at this point and therefore
843 * cannot access the devices list anyhow.
845 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
846 list_del(&dev->vm_node);
847 dev->ops->destroy(dev);
851 static void kvm_destroy_vm(struct kvm *kvm)
854 struct mm_struct *mm = kvm->mm;
856 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
857 kvm_destroy_vm_debugfs(kvm);
858 kvm_arch_sync_events(kvm);
859 mutex_lock(&kvm_lock);
860 list_del(&kvm->vm_list);
861 mutex_unlock(&kvm_lock);
862 kvm_arch_pre_destroy_vm(kvm);
864 kvm_free_irq_routing(kvm);
865 for (i = 0; i < KVM_NR_BUSES; i++) {
866 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
869 kvm_io_bus_destroy(bus);
870 kvm->buses[i] = NULL;
872 kvm_coalesced_mmio_free(kvm);
873 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
874 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
876 kvm_arch_flush_shadow_all(kvm);
878 kvm_arch_destroy_vm(kvm);
879 kvm_destroy_devices(kvm);
880 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
881 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
882 cleanup_srcu_struct(&kvm->irq_srcu);
883 cleanup_srcu_struct(&kvm->srcu);
884 kvm_arch_free_vm(kvm);
885 preempt_notifier_dec();
886 hardware_disable_all();
890 void kvm_get_kvm(struct kvm *kvm)
892 refcount_inc(&kvm->users_count);
894 EXPORT_SYMBOL_GPL(kvm_get_kvm);
896 void kvm_put_kvm(struct kvm *kvm)
898 if (refcount_dec_and_test(&kvm->users_count))
901 EXPORT_SYMBOL_GPL(kvm_put_kvm);
904 * Used to put a reference that was taken on behalf of an object associated
905 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
906 * of the new file descriptor fails and the reference cannot be transferred to
907 * its final owner. In such cases, the caller is still actively using @kvm and
908 * will fail miserably if the refcount unexpectedly hits zero.
910 void kvm_put_kvm_no_destroy(struct kvm *kvm)
912 WARN_ON(refcount_dec_and_test(&kvm->users_count));
914 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
916 static int kvm_vm_release(struct inode *inode, struct file *filp)
918 struct kvm *kvm = filp->private_data;
920 kvm_irqfd_release(kvm);
927 * Allocation size is twice as large as the actual dirty bitmap size.
928 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
930 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
932 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
934 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
935 if (!memslot->dirty_bitmap)
942 * Delete a memslot by decrementing the number of used slots and shifting all
943 * other entries in the array forward one spot.
945 static inline void kvm_memslot_delete(struct kvm_memslots *slots,
946 struct kvm_memory_slot *memslot)
948 struct kvm_memory_slot *mslots = slots->memslots;
951 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
956 if (atomic_read(&slots->lru_slot) >= slots->used_slots)
957 atomic_set(&slots->lru_slot, 0);
959 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
960 mslots[i] = mslots[i + 1];
961 slots->id_to_index[mslots[i].id] = i;
963 mslots[i] = *memslot;
964 slots->id_to_index[memslot->id] = -1;
968 * "Insert" a new memslot by incrementing the number of used slots. Returns
969 * the new slot's initial index into the memslots array.
971 static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
973 return slots->used_slots++;
977 * Move a changed memslot backwards in the array by shifting existing slots
978 * with a higher GFN toward the front of the array. Note, the changed memslot
979 * itself is not preserved in the array, i.e. not swapped at this time, only
980 * its new index into the array is tracked. Returns the changed memslot's
981 * current index into the memslots array.
983 static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
984 struct kvm_memory_slot *memslot)
986 struct kvm_memory_slot *mslots = slots->memslots;
989 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
990 WARN_ON_ONCE(!slots->used_slots))
994 * Move the target memslot backward in the array by shifting existing
995 * memslots with a higher GFN (than the target memslot) towards the
996 * front of the array.
998 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
999 if (memslot->base_gfn > mslots[i + 1].base_gfn)
1002 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
1004 /* Shift the next memslot forward one and update its index. */
1005 mslots[i] = mslots[i + 1];
1006 slots->id_to_index[mslots[i].id] = i;
1012 * Move a changed memslot forwards in the array by shifting existing slots with
1013 * a lower GFN toward the back of the array. Note, the changed memslot itself
1014 * is not preserved in the array, i.e. not swapped at this time, only its new
1015 * index into the array is tracked. Returns the changed memslot's final index
1016 * into the memslots array.
1018 static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
1019 struct kvm_memory_slot *memslot,
1022 struct kvm_memory_slot *mslots = slots->memslots;
1025 for (i = start; i > 0; i--) {
1026 if (memslot->base_gfn < mslots[i - 1].base_gfn)
1029 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
1031 /* Shift the next memslot back one and update its index. */
1032 mslots[i] = mslots[i - 1];
1033 slots->id_to_index[mslots[i].id] = i;
1039 * Re-sort memslots based on their GFN to account for an added, deleted, or
1040 * moved memslot. Sorting memslots by GFN allows using a binary search during
1043 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
1044 * at memslots[0] has the highest GFN.
1046 * The sorting algorithm takes advantage of having initially sorted memslots
1047 * and knowing the position of the changed memslot. Sorting is also optimized
1048 * by not swapping the updated memslot and instead only shifting other memslots
1049 * and tracking the new index for the update memslot. Only once its final
1050 * index is known is the updated memslot copied into its position in the array.
1052 * - When deleting a memslot, the deleted memslot simply needs to be moved to
1053 * the end of the array.
1055 * - When creating a memslot, the algorithm "inserts" the new memslot at the
1056 * end of the array and then it forward to its correct location.
1058 * - When moving a memslot, the algorithm first moves the updated memslot
1059 * backward to handle the scenario where the memslot's GFN was changed to a
1060 * lower value. update_memslots() then falls through and runs the same flow
1061 * as creating a memslot to move the memslot forward to handle the scenario
1062 * where its GFN was changed to a higher value.
1064 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1065 * historical reasons. Originally, invalid memslots where denoted by having
1066 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1067 * to the end of the array. The current algorithm uses dedicated logic to
1068 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1070 * The other historical motiviation for highest->lowest was to improve the
1071 * performance of memslot lookup. KVM originally used a linear search starting
1072 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1073 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1074 * single memslot above the 4gb boundary. As the largest memslot is also the
1075 * most likely to be referenced, sorting it to the front of the array was
1076 * advantageous. The current binary search starts from the middle of the array
1077 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1079 static void update_memslots(struct kvm_memslots *slots,
1080 struct kvm_memory_slot *memslot,
1081 enum kvm_mr_change change)
1085 if (change == KVM_MR_DELETE) {
1086 kvm_memslot_delete(slots, memslot);
1088 if (change == KVM_MR_CREATE)
1089 i = kvm_memslot_insert_back(slots);
1091 i = kvm_memslot_move_backward(slots, memslot);
1092 i = kvm_memslot_move_forward(slots, memslot, i);
1095 * Copy the memslot to its new position in memslots and update
1096 * its index accordingly.
1098 slots->memslots[i] = *memslot;
1099 slots->id_to_index[memslot->id] = i;
1103 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1105 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1107 #ifdef __KVM_HAVE_READONLY_MEM
1108 valid_flags |= KVM_MEM_READONLY;
1111 if (mem->flags & ~valid_flags)
1117 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
1118 int as_id, struct kvm_memslots *slots)
1120 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
1121 u64 gen = old_memslots->generation;
1123 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1124 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1126 rcu_assign_pointer(kvm->memslots[as_id], slots);
1127 synchronize_srcu_expedited(&kvm->srcu);
1130 * Increment the new memslot generation a second time, dropping the
1131 * update in-progress flag and incrementing the generation based on
1132 * the number of address spaces. This provides a unique and easily
1133 * identifiable generation number while the memslots are in flux.
1135 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1138 * Generations must be unique even across address spaces. We do not need
1139 * a global counter for that, instead the generation space is evenly split
1140 * across address spaces. For example, with two address spaces, address
1141 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1142 * use generations 1, 3, 5, ...
1144 gen += KVM_ADDRESS_SPACE_NUM;
1146 kvm_arch_memslots_updated(kvm, gen);
1148 slots->generation = gen;
1150 return old_memslots;
1154 * Note, at a minimum, the current number of used slots must be allocated, even
1155 * when deleting a memslot, as we need a complete duplicate of the memslots for
1156 * use when invalidating a memslot prior to deleting/moving the memslot.
1158 static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1159 enum kvm_mr_change change)
1161 struct kvm_memslots *slots;
1162 size_t old_size, new_size;
1164 old_size = sizeof(struct kvm_memslots) +
1165 (sizeof(struct kvm_memory_slot) * old->used_slots);
1167 if (change == KVM_MR_CREATE)
1168 new_size = old_size + sizeof(struct kvm_memory_slot);
1170 new_size = old_size;
1172 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1174 memcpy(slots, old, old_size);
1179 static int kvm_set_memslot(struct kvm *kvm,
1180 const struct kvm_userspace_memory_region *mem,
1181 struct kvm_memory_slot *old,
1182 struct kvm_memory_slot *new, int as_id,
1183 enum kvm_mr_change change)
1185 struct kvm_memory_slot *slot;
1186 struct kvm_memslots *slots;
1189 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
1193 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1195 * Note, the INVALID flag needs to be in the appropriate entry
1196 * in the freshly allocated memslots, not in @old or @new.
1198 slot = id_to_memslot(slots, old->id);
1199 slot->flags |= KVM_MEMSLOT_INVALID;
1202 * We can re-use the old memslots, the only difference from the
1203 * newly installed memslots is the invalid flag, which will get
1204 * dropped by update_memslots anyway. We'll also revert to the
1205 * old memslots if preparing the new memory region fails.
1207 slots = install_new_memslots(kvm, as_id, slots);
1209 /* From this point no new shadow pages pointing to a deleted,
1210 * or moved, memslot will be created.
1212 * validation of sp->gfn happens in:
1213 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1214 * - kvm_is_visible_gfn (mmu_check_root)
1216 kvm_arch_flush_shadow_memslot(kvm, slot);
1219 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1223 update_memslots(slots, new, change);
1224 slots = install_new_memslots(kvm, as_id, slots);
1226 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1232 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1233 slots = install_new_memslots(kvm, as_id, slots);
1238 static int kvm_delete_memslot(struct kvm *kvm,
1239 const struct kvm_userspace_memory_region *mem,
1240 struct kvm_memory_slot *old, int as_id)
1242 struct kvm_memory_slot new;
1248 memset(&new, 0, sizeof(new));
1251 * This is only for debugging purpose; it should never be referenced
1252 * for a removed memslot.
1256 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1260 kvm_free_memslot(kvm, old);
1265 * Allocate some memory and give it an address in the guest physical address
1268 * Discontiguous memory is allowed, mostly for framebuffers.
1270 * Must be called holding kvm->slots_lock for write.
1272 int __kvm_set_memory_region(struct kvm *kvm,
1273 const struct kvm_userspace_memory_region *mem)
1275 struct kvm_memory_slot old, new;
1276 struct kvm_memory_slot *tmp;
1277 enum kvm_mr_change change;
1281 r = check_memory_region_flags(mem);
1285 as_id = mem->slot >> 16;
1286 id = (u16)mem->slot;
1288 /* General sanity checks */
1289 if (mem->memory_size & (PAGE_SIZE - 1))
1291 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1293 /* We can read the guest memory with __xxx_user() later on. */
1294 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1295 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1298 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1300 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1304 * Make a full copy of the old memslot, the pointer will become stale
1305 * when the memslots are re-sorted by update_memslots(), and the old
1306 * memslot needs to be referenced after calling update_memslots(), e.g.
1307 * to free its resources and for arch specific behavior.
1309 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1314 memset(&old, 0, sizeof(old));
1318 if (!mem->memory_size)
1319 return kvm_delete_memslot(kvm, mem, &old, as_id);
1323 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1324 new.npages = mem->memory_size >> PAGE_SHIFT;
1325 new.flags = mem->flags;
1326 new.userspace_addr = mem->userspace_addr;
1328 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1332 change = KVM_MR_CREATE;
1333 new.dirty_bitmap = NULL;
1334 memset(&new.arch, 0, sizeof(new.arch));
1335 } else { /* Modify an existing slot. */
1336 if ((new.userspace_addr != old.userspace_addr) ||
1337 (new.npages != old.npages) ||
1338 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1341 if (new.base_gfn != old.base_gfn)
1342 change = KVM_MR_MOVE;
1343 else if (new.flags != old.flags)
1344 change = KVM_MR_FLAGS_ONLY;
1345 else /* Nothing to change. */
1348 /* Copy dirty_bitmap and arch from the current memslot. */
1349 new.dirty_bitmap = old.dirty_bitmap;
1350 memcpy(&new.arch, &old.arch, sizeof(new.arch));
1353 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1354 /* Check for overlaps */
1355 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1358 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1359 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
1364 /* Allocate/free page dirty bitmap as needed */
1365 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1366 new.dirty_bitmap = NULL;
1367 else if (!new.dirty_bitmap && !kvm->dirty_ring_size) {
1368 r = kvm_alloc_dirty_bitmap(&new);
1372 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1373 bitmap_set(new.dirty_bitmap, 0, new.npages);
1376 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1380 if (old.dirty_bitmap && !new.dirty_bitmap)
1381 kvm_destroy_dirty_bitmap(&old);
1385 if (new.dirty_bitmap && !old.dirty_bitmap)
1386 kvm_destroy_dirty_bitmap(&new);
1389 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1391 int kvm_set_memory_region(struct kvm *kvm,
1392 const struct kvm_userspace_memory_region *mem)
1396 mutex_lock(&kvm->slots_lock);
1397 r = __kvm_set_memory_region(kvm, mem);
1398 mutex_unlock(&kvm->slots_lock);
1401 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1403 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1404 struct kvm_userspace_memory_region *mem)
1406 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1409 return kvm_set_memory_region(kvm, mem);
1412 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1414 * kvm_get_dirty_log - get a snapshot of dirty pages
1415 * @kvm: pointer to kvm instance
1416 * @log: slot id and address to which we copy the log
1417 * @is_dirty: set to '1' if any dirty pages were found
1418 * @memslot: set to the associated memslot, always valid on success
1420 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1421 int *is_dirty, struct kvm_memory_slot **memslot)
1423 struct kvm_memslots *slots;
1426 unsigned long any = 0;
1428 /* Dirty ring tracking is exclusive to dirty log tracking */
1429 if (kvm->dirty_ring_size)
1435 as_id = log->slot >> 16;
1436 id = (u16)log->slot;
1437 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1440 slots = __kvm_memslots(kvm, as_id);
1441 *memslot = id_to_memslot(slots, id);
1442 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1445 kvm_arch_sync_dirty_log(kvm, *memslot);
1447 n = kvm_dirty_bitmap_bytes(*memslot);
1449 for (i = 0; !any && i < n/sizeof(long); ++i)
1450 any = (*memslot)->dirty_bitmap[i];
1452 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1459 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1461 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1463 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1464 * and reenable dirty page tracking for the corresponding pages.
1465 * @kvm: pointer to kvm instance
1466 * @log: slot id and address to which we copy the log
1468 * We need to keep it in mind that VCPU threads can write to the bitmap
1469 * concurrently. So, to avoid losing track of dirty pages we keep the
1472 * 1. Take a snapshot of the bit and clear it if needed.
1473 * 2. Write protect the corresponding page.
1474 * 3. Copy the snapshot to the userspace.
1475 * 4. Upon return caller flushes TLB's if needed.
1477 * Between 2 and 4, the guest may write to the page using the remaining TLB
1478 * entry. This is not a problem because the page is reported dirty using
1479 * the snapshot taken before and step 4 ensures that writes done after
1480 * exiting to userspace will be logged for the next call.
1483 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
1485 struct kvm_memslots *slots;
1486 struct kvm_memory_slot *memslot;
1489 unsigned long *dirty_bitmap;
1490 unsigned long *dirty_bitmap_buffer;
1493 /* Dirty ring tracking is exclusive to dirty log tracking */
1494 if (kvm->dirty_ring_size)
1497 as_id = log->slot >> 16;
1498 id = (u16)log->slot;
1499 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1502 slots = __kvm_memslots(kvm, as_id);
1503 memslot = id_to_memslot(slots, id);
1504 if (!memslot || !memslot->dirty_bitmap)
1507 dirty_bitmap = memslot->dirty_bitmap;
1509 kvm_arch_sync_dirty_log(kvm, memslot);
1511 n = kvm_dirty_bitmap_bytes(memslot);
1513 if (kvm->manual_dirty_log_protect) {
1515 * Unlike kvm_get_dirty_log, we always return false in *flush,
1516 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1517 * is some code duplication between this function and
1518 * kvm_get_dirty_log, but hopefully all architecture
1519 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1520 * can be eliminated.
1522 dirty_bitmap_buffer = dirty_bitmap;
1524 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1525 memset(dirty_bitmap_buffer, 0, n);
1527 spin_lock(&kvm->mmu_lock);
1528 for (i = 0; i < n / sizeof(long); i++) {
1532 if (!dirty_bitmap[i])
1536 mask = xchg(&dirty_bitmap[i], 0);
1537 dirty_bitmap_buffer[i] = mask;
1539 offset = i * BITS_PER_LONG;
1540 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1543 spin_unlock(&kvm->mmu_lock);
1547 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1549 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1556 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1557 * @kvm: kvm instance
1558 * @log: slot id and address to which we copy the log
1560 * Steps 1-4 below provide general overview of dirty page logging. See
1561 * kvm_get_dirty_log_protect() function description for additional details.
1563 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1564 * always flush the TLB (step 4) even if previous step failed and the dirty
1565 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1566 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1567 * writes will be marked dirty for next log read.
1569 * 1. Take a snapshot of the bit and clear it if needed.
1570 * 2. Write protect the corresponding page.
1571 * 3. Copy the snapshot to the userspace.
1572 * 4. Flush TLB's if needed.
1574 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1575 struct kvm_dirty_log *log)
1579 mutex_lock(&kvm->slots_lock);
1581 r = kvm_get_dirty_log_protect(kvm, log);
1583 mutex_unlock(&kvm->slots_lock);
1588 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1589 * and reenable dirty page tracking for the corresponding pages.
1590 * @kvm: pointer to kvm instance
1591 * @log: slot id and address from which to fetch the bitmap of dirty pages
1593 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1594 struct kvm_clear_dirty_log *log)
1596 struct kvm_memslots *slots;
1597 struct kvm_memory_slot *memslot;
1601 unsigned long *dirty_bitmap;
1602 unsigned long *dirty_bitmap_buffer;
1605 /* Dirty ring tracking is exclusive to dirty log tracking */
1606 if (kvm->dirty_ring_size)
1609 as_id = log->slot >> 16;
1610 id = (u16)log->slot;
1611 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1614 if (log->first_page & 63)
1617 slots = __kvm_memslots(kvm, as_id);
1618 memslot = id_to_memslot(slots, id);
1619 if (!memslot || !memslot->dirty_bitmap)
1622 dirty_bitmap = memslot->dirty_bitmap;
1624 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
1626 if (log->first_page > memslot->npages ||
1627 log->num_pages > memslot->npages - log->first_page ||
1628 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1631 kvm_arch_sync_dirty_log(kvm, memslot);
1634 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1635 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1638 spin_lock(&kvm->mmu_lock);
1639 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1640 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
1641 i++, offset += BITS_PER_LONG) {
1642 unsigned long mask = *dirty_bitmap_buffer++;
1643 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1647 mask &= atomic_long_fetch_andnot(mask, p);
1650 * mask contains the bits that really have been cleared. This
1651 * never includes any bits beyond the length of the memslot (if
1652 * the length is not aligned to 64 pages), therefore it is not
1653 * a problem if userspace sets them in log->dirty_bitmap.
1657 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1661 spin_unlock(&kvm->mmu_lock);
1664 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1669 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
1670 struct kvm_clear_dirty_log *log)
1674 mutex_lock(&kvm->slots_lock);
1676 r = kvm_clear_dirty_log_protect(kvm, log);
1678 mutex_unlock(&kvm->slots_lock);
1681 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1683 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1685 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1687 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1689 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1691 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1693 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_memslot);
1695 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1697 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1699 return kvm_is_visible_memslot(memslot);
1701 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1703 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1705 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1707 return kvm_is_visible_memslot(memslot);
1709 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
1711 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
1713 struct vm_area_struct *vma;
1714 unsigned long addr, size;
1718 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
1719 if (kvm_is_error_hva(addr))
1722 mmap_read_lock(current->mm);
1723 vma = find_vma(current->mm, addr);
1727 size = vma_kernel_pagesize(vma);
1730 mmap_read_unlock(current->mm);
1735 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1737 return slot->flags & KVM_MEM_READONLY;
1740 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1741 gfn_t *nr_pages, bool write)
1743 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1744 return KVM_HVA_ERR_BAD;
1746 if (memslot_is_readonly(slot) && write)
1747 return KVM_HVA_ERR_RO_BAD;
1750 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1752 return __gfn_to_hva_memslot(slot, gfn);
1755 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1758 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1761 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1764 return gfn_to_hva_many(slot, gfn, NULL);
1766 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1768 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1770 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1772 EXPORT_SYMBOL_GPL(gfn_to_hva);
1774 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1776 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1778 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1781 * Return the hva of a @gfn and the R/W attribute if possible.
1783 * @slot: the kvm_memory_slot which contains @gfn
1784 * @gfn: the gfn to be translated
1785 * @writable: used to return the read/write attribute of the @slot if the hva
1786 * is valid and @writable is not NULL
1788 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1789 gfn_t gfn, bool *writable)
1791 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1793 if (!kvm_is_error_hva(hva) && writable)
1794 *writable = !memslot_is_readonly(slot);
1799 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1801 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1803 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1806 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1808 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1810 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1813 static inline int check_user_page_hwpoison(unsigned long addr)
1815 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1817 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1818 return rc == -EHWPOISON;
1822 * The fast path to get the writable pfn which will be stored in @pfn,
1823 * true indicates success, otherwise false is returned. It's also the
1824 * only part that runs if we can in atomic context.
1826 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1827 bool *writable, kvm_pfn_t *pfn)
1829 struct page *page[1];
1832 * Fast pin a writable pfn only if it is a write fault request
1833 * or the caller allows to map a writable pfn for a read fault
1836 if (!(write_fault || writable))
1839 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
1840 *pfn = page_to_pfn(page[0]);
1851 * The slow path to get the pfn of the specified host virtual address,
1852 * 1 indicates success, -errno is returned if error is detected.
1854 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1855 bool *writable, kvm_pfn_t *pfn)
1857 unsigned int flags = FOLL_HWPOISON;
1864 *writable = write_fault;
1867 flags |= FOLL_WRITE;
1869 flags |= FOLL_NOWAIT;
1871 npages = get_user_pages_unlocked(addr, 1, &page, flags);
1875 /* map read fault as writable if possible */
1876 if (unlikely(!write_fault) && writable) {
1879 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
1885 *pfn = page_to_pfn(page);
1889 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1891 if (unlikely(!(vma->vm_flags & VM_READ)))
1894 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1900 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1901 unsigned long addr, bool *async,
1902 bool write_fault, bool *writable,
1908 r = follow_pfn(vma, addr, &pfn);
1911 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1912 * not call the fault handler, so do it here.
1914 bool unlocked = false;
1915 r = fixup_user_fault(current->mm, addr,
1916 (write_fault ? FAULT_FLAG_WRITE : 0),
1923 r = follow_pfn(vma, addr, &pfn);
1933 * Get a reference here because callers of *hva_to_pfn* and
1934 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1935 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1936 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1937 * simply do nothing for reserved pfns.
1939 * Whoever called remap_pfn_range is also going to call e.g.
1940 * unmap_mapping_range before the underlying pages are freed,
1941 * causing a call to our MMU notifier.
1950 * Pin guest page in memory and return its pfn.
1951 * @addr: host virtual address which maps memory to the guest
1952 * @atomic: whether this function can sleep
1953 * @async: whether this function need to wait IO complete if the
1954 * host page is not in the memory
1955 * @write_fault: whether we should get a writable host page
1956 * @writable: whether it allows to map a writable host page for !@write_fault
1958 * The function will map a writable host page for these two cases:
1959 * 1): @write_fault = true
1960 * 2): @write_fault = false && @writable, @writable will tell the caller
1961 * whether the mapping is writable.
1963 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1964 bool write_fault, bool *writable)
1966 struct vm_area_struct *vma;
1970 /* we can do it either atomically or asynchronously, not both */
1971 BUG_ON(atomic && async);
1973 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
1977 return KVM_PFN_ERR_FAULT;
1979 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1983 mmap_read_lock(current->mm);
1984 if (npages == -EHWPOISON ||
1985 (!async && check_user_page_hwpoison(addr))) {
1986 pfn = KVM_PFN_ERR_HWPOISON;
1991 vma = find_vma_intersection(current->mm, addr, addr + 1);
1994 pfn = KVM_PFN_ERR_FAULT;
1995 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1996 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
2000 pfn = KVM_PFN_ERR_FAULT;
2002 if (async && vma_is_valid(vma, write_fault))
2004 pfn = KVM_PFN_ERR_FAULT;
2007 mmap_read_unlock(current->mm);
2011 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
2012 bool atomic, bool *async, bool write_fault,
2015 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2017 if (addr == KVM_HVA_ERR_RO_BAD) {
2020 return KVM_PFN_ERR_RO_FAULT;
2023 if (kvm_is_error_hva(addr)) {
2026 return KVM_PFN_NOSLOT;
2029 /* Do not map writable pfn in the readonly memslot. */
2030 if (writable && memslot_is_readonly(slot)) {
2035 return hva_to_pfn(addr, atomic, async, write_fault,
2038 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2040 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2043 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2044 write_fault, writable);
2046 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2048 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
2050 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
2052 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2054 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
2056 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
2058 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2060 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2062 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2064 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2066 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2068 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2070 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2072 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2074 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2076 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2078 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2079 struct page **pages, int nr_pages)
2084 addr = gfn_to_hva_many(slot, gfn, &entry);
2085 if (kvm_is_error_hva(addr))
2088 if (entry < nr_pages)
2091 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2093 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2095 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2097 if (is_error_noslot_pfn(pfn))
2098 return KVM_ERR_PTR_BAD_PAGE;
2100 if (kvm_is_reserved_pfn(pfn)) {
2102 return KVM_ERR_PTR_BAD_PAGE;
2105 return pfn_to_page(pfn);
2108 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2112 pfn = gfn_to_pfn(kvm, gfn);
2114 return kvm_pfn_to_page(pfn);
2116 EXPORT_SYMBOL_GPL(gfn_to_page);
2118 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2124 cache->pfn = cache->gfn = 0;
2127 kvm_release_pfn_dirty(pfn);
2129 kvm_release_pfn_clean(pfn);
2132 static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2133 struct gfn_to_pfn_cache *cache, u64 gen)
2135 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2137 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2139 cache->dirty = false;
2140 cache->generation = gen;
2143 static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
2144 struct kvm_host_map *map,
2145 struct gfn_to_pfn_cache *cache,
2150 struct page *page = KVM_UNMAPPED_PAGE;
2151 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
2152 u64 gen = slots->generation;
2158 if (!cache->pfn || cache->gfn != gfn ||
2159 cache->generation != gen) {
2162 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2168 pfn = gfn_to_pfn_memslot(slot, gfn);
2170 if (is_error_noslot_pfn(pfn))
2173 if (pfn_valid(pfn)) {
2174 page = pfn_to_page(pfn);
2176 hva = kmap_atomic(page);
2179 #ifdef CONFIG_HAS_IOMEM
2180 } else if (!atomic) {
2181 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2198 int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2199 struct gfn_to_pfn_cache *cache, bool atomic)
2201 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2204 EXPORT_SYMBOL_GPL(kvm_map_gfn);
2206 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2208 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2211 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2213 static void __kvm_unmap_gfn(struct kvm *kvm,
2214 struct kvm_memory_slot *memslot,
2215 struct kvm_host_map *map,
2216 struct gfn_to_pfn_cache *cache,
2217 bool dirty, bool atomic)
2225 if (map->page != KVM_UNMAPPED_PAGE) {
2227 kunmap_atomic(map->hva);
2231 #ifdef CONFIG_HAS_IOMEM
2235 WARN_ONCE(1, "Unexpected unmapping in atomic context");
2239 mark_page_dirty_in_slot(kvm, memslot, map->gfn);
2242 cache->dirty |= dirty;
2244 kvm_release_pfn(map->pfn, dirty, NULL);
2250 int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2251 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
2253 __kvm_unmap_gfn(vcpu->kvm, gfn_to_memslot(vcpu->kvm, map->gfn), map,
2254 cache, dirty, atomic);
2257 EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2259 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2261 __kvm_unmap_gfn(vcpu->kvm, kvm_vcpu_gfn_to_memslot(vcpu, map->gfn),
2262 map, NULL, dirty, false);
2264 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2266 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2270 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2272 return kvm_pfn_to_page(pfn);
2274 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2276 void kvm_release_page_clean(struct page *page)
2278 WARN_ON(is_error_page(page));
2280 kvm_release_pfn_clean(page_to_pfn(page));
2282 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2284 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2286 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2287 put_page(pfn_to_page(pfn));
2289 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2291 void kvm_release_page_dirty(struct page *page)
2293 WARN_ON(is_error_page(page));
2295 kvm_release_pfn_dirty(page_to_pfn(page));
2297 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2299 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2301 kvm_set_pfn_dirty(pfn);
2302 kvm_release_pfn_clean(pfn);
2304 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2306 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2308 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2309 SetPageDirty(pfn_to_page(pfn));
2311 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2313 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2315 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2316 mark_page_accessed(pfn_to_page(pfn));
2318 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2320 void kvm_get_pfn(kvm_pfn_t pfn)
2322 if (!kvm_is_reserved_pfn(pfn))
2323 get_page(pfn_to_page(pfn));
2325 EXPORT_SYMBOL_GPL(kvm_get_pfn);
2327 static int next_segment(unsigned long len, int offset)
2329 if (len > PAGE_SIZE - offset)
2330 return PAGE_SIZE - offset;
2335 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2336 void *data, int offset, int len)
2341 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2342 if (kvm_is_error_hva(addr))
2344 r = __copy_from_user(data, (void __user *)addr + offset, len);
2350 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2353 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2355 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2357 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2359 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2360 int offset, int len)
2362 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2364 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2366 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2368 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2370 gfn_t gfn = gpa >> PAGE_SHIFT;
2372 int offset = offset_in_page(gpa);
2375 while ((seg = next_segment(len, offset)) != 0) {
2376 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2386 EXPORT_SYMBOL_GPL(kvm_read_guest);
2388 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2390 gfn_t gfn = gpa >> PAGE_SHIFT;
2392 int offset = offset_in_page(gpa);
2395 while ((seg = next_segment(len, offset)) != 0) {
2396 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2406 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2408 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2409 void *data, int offset, unsigned long len)
2414 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2415 if (kvm_is_error_hva(addr))
2417 pagefault_disable();
2418 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2425 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2426 void *data, unsigned long len)
2428 gfn_t gfn = gpa >> PAGE_SHIFT;
2429 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2430 int offset = offset_in_page(gpa);
2432 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2434 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2436 static int __kvm_write_guest_page(struct kvm *kvm,
2437 struct kvm_memory_slot *memslot, gfn_t gfn,
2438 const void *data, int offset, int len)
2443 addr = gfn_to_hva_memslot(memslot, gfn);
2444 if (kvm_is_error_hva(addr))
2446 r = __copy_to_user((void __user *)addr + offset, data, len);
2449 mark_page_dirty_in_slot(kvm, memslot, gfn);
2453 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2454 const void *data, int offset, int len)
2456 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2458 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2460 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2462 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2463 const void *data, int offset, int len)
2465 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2467 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
2469 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2471 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2474 gfn_t gfn = gpa >> PAGE_SHIFT;
2476 int offset = offset_in_page(gpa);
2479 while ((seg = next_segment(len, offset)) != 0) {
2480 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2490 EXPORT_SYMBOL_GPL(kvm_write_guest);
2492 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2495 gfn_t gfn = gpa >> PAGE_SHIFT;
2497 int offset = offset_in_page(gpa);
2500 while ((seg = next_segment(len, offset)) != 0) {
2501 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2511 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2513 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2514 struct gfn_to_hva_cache *ghc,
2515 gpa_t gpa, unsigned long len)
2517 int offset = offset_in_page(gpa);
2518 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2519 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2520 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2521 gfn_t nr_pages_avail;
2523 /* Update ghc->generation before performing any error checks. */
2524 ghc->generation = slots->generation;
2526 if (start_gfn > end_gfn) {
2527 ghc->hva = KVM_HVA_ERR_BAD;
2532 * If the requested region crosses two memslots, we still
2533 * verify that the entire region is valid here.
2535 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
2536 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2537 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2539 if (kvm_is_error_hva(ghc->hva))
2543 /* Use the slow path for cross page reads and writes. */
2544 if (nr_pages_needed == 1)
2547 ghc->memslot = NULL;
2554 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2555 gpa_t gpa, unsigned long len)
2557 struct kvm_memslots *slots = kvm_memslots(kvm);
2558 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2560 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2562 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2563 void *data, unsigned int offset,
2566 struct kvm_memslots *slots = kvm_memslots(kvm);
2568 gpa_t gpa = ghc->gpa + offset;
2570 BUG_ON(len + offset > ghc->len);
2572 if (slots->generation != ghc->generation) {
2573 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2577 if (kvm_is_error_hva(ghc->hva))
2580 if (unlikely(!ghc->memslot))
2581 return kvm_write_guest(kvm, gpa, data, len);
2583 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2586 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
2590 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2592 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2593 void *data, unsigned long len)
2595 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2597 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2599 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2600 void *data, unsigned int offset,
2603 struct kvm_memslots *slots = kvm_memslots(kvm);
2605 gpa_t gpa = ghc->gpa + offset;
2607 BUG_ON(len + offset > ghc->len);
2609 if (slots->generation != ghc->generation) {
2610 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2614 if (kvm_is_error_hva(ghc->hva))
2617 if (unlikely(!ghc->memslot))
2618 return kvm_read_guest(kvm, gpa, data, len);
2620 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
2626 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
2628 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2629 void *data, unsigned long len)
2631 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
2633 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2635 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2637 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2638 gfn_t gfn = gpa >> PAGE_SHIFT;
2640 int offset = offset_in_page(gpa);
2643 while ((seg = next_segment(len, offset)) != 0) {
2644 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2653 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2655 void mark_page_dirty_in_slot(struct kvm *kvm,
2656 struct kvm_memory_slot *memslot,
2659 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
2660 unsigned long rel_gfn = gfn - memslot->base_gfn;
2661 u32 slot = (memslot->as_id << 16) | memslot->id;
2663 if (kvm->dirty_ring_size)
2664 kvm_dirty_ring_push(kvm_dirty_ring_get(kvm),
2667 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2670 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
2672 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2674 struct kvm_memory_slot *memslot;
2676 memslot = gfn_to_memslot(kvm, gfn);
2677 mark_page_dirty_in_slot(kvm, memslot, gfn);
2679 EXPORT_SYMBOL_GPL(mark_page_dirty);
2681 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2683 struct kvm_memory_slot *memslot;
2685 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2686 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
2688 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2690 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2692 if (!vcpu->sigset_active)
2696 * This does a lockless modification of ->real_blocked, which is fine
2697 * because, only current can change ->real_blocked and all readers of
2698 * ->real_blocked don't care as long ->real_blocked is always a subset
2701 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
2704 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2706 if (!vcpu->sigset_active)
2709 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
2710 sigemptyset(¤t->real_blocked);
2713 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2715 unsigned int old, val, grow, grow_start;
2717 old = val = vcpu->halt_poll_ns;
2718 grow_start = READ_ONCE(halt_poll_ns_grow_start);
2719 grow = READ_ONCE(halt_poll_ns_grow);
2724 if (val < grow_start)
2727 if (val > halt_poll_ns)
2730 vcpu->halt_poll_ns = val;
2732 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2735 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2737 unsigned int old, val, shrink;
2739 old = val = vcpu->halt_poll_ns;
2740 shrink = READ_ONCE(halt_poll_ns_shrink);
2746 vcpu->halt_poll_ns = val;
2747 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2750 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2753 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2755 if (kvm_arch_vcpu_runnable(vcpu)) {
2756 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2759 if (kvm_cpu_has_pending_timer(vcpu))
2761 if (signal_pending(current))
2766 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2771 update_halt_poll_stats(struct kvm_vcpu *vcpu, u64 poll_ns, bool waited)
2774 vcpu->stat.halt_poll_fail_ns += poll_ns;
2776 vcpu->stat.halt_poll_success_ns += poll_ns;
2780 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2782 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2784 ktime_t start, cur, poll_end;
2785 bool waited = false;
2788 kvm_arch_vcpu_blocking(vcpu);
2790 start = cur = poll_end = ktime_get();
2791 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
2792 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2794 ++vcpu->stat.halt_attempted_poll;
2797 * This sets KVM_REQ_UNHALT if an interrupt
2800 if (kvm_vcpu_check_block(vcpu) < 0) {
2801 ++vcpu->stat.halt_successful_poll;
2802 if (!vcpu_valid_wakeup(vcpu))
2803 ++vcpu->stat.halt_poll_invalid;
2806 poll_end = cur = ktime_get();
2807 } while (single_task_running() && ktime_before(cur, stop));
2810 prepare_to_rcuwait(&vcpu->wait);
2812 set_current_state(TASK_INTERRUPTIBLE);
2814 if (kvm_vcpu_check_block(vcpu) < 0)
2820 finish_rcuwait(&vcpu->wait);
2823 kvm_arch_vcpu_unblocking(vcpu);
2824 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2826 update_halt_poll_stats(
2827 vcpu, ktime_to_ns(ktime_sub(poll_end, start)), waited);
2829 if (!kvm_arch_no_poll(vcpu)) {
2830 if (!vcpu_valid_wakeup(vcpu)) {
2831 shrink_halt_poll_ns(vcpu);
2832 } else if (vcpu->kvm->max_halt_poll_ns) {
2833 if (block_ns <= vcpu->halt_poll_ns)
2835 /* we had a long block, shrink polling */
2836 else if (vcpu->halt_poll_ns &&
2837 block_ns > vcpu->kvm->max_halt_poll_ns)
2838 shrink_halt_poll_ns(vcpu);
2839 /* we had a short halt and our poll time is too small */
2840 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
2841 block_ns < vcpu->kvm->max_halt_poll_ns)
2842 grow_halt_poll_ns(vcpu);
2844 vcpu->halt_poll_ns = 0;
2848 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2849 kvm_arch_vcpu_block_finish(vcpu);
2851 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2853 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2855 struct rcuwait *waitp;
2857 waitp = kvm_arch_vcpu_get_wait(vcpu);
2858 if (rcuwait_wake_up(waitp)) {
2859 WRITE_ONCE(vcpu->ready, true);
2860 ++vcpu->stat.halt_wakeup;
2866 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2870 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2872 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2875 int cpu = vcpu->cpu;
2877 if (kvm_vcpu_wake_up(vcpu))
2881 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2882 if (kvm_arch_vcpu_should_kick(vcpu))
2883 smp_send_reschedule(cpu);
2886 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2887 #endif /* !CONFIG_S390 */
2889 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2892 struct task_struct *task = NULL;
2896 pid = rcu_dereference(target->pid);
2898 task = get_pid_task(pid, PIDTYPE_PID);
2902 ret = yield_to(task, 1);
2903 put_task_struct(task);
2907 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2910 * Helper that checks whether a VCPU is eligible for directed yield.
2911 * Most eligible candidate to yield is decided by following heuristics:
2913 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2914 * (preempted lock holder), indicated by @in_spin_loop.
2915 * Set at the beginning and cleared at the end of interception/PLE handler.
2917 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2918 * chance last time (mostly it has become eligible now since we have probably
2919 * yielded to lockholder in last iteration. This is done by toggling
2920 * @dy_eligible each time a VCPU checked for eligibility.)
2922 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2923 * to preempted lock-holder could result in wrong VCPU selection and CPU
2924 * burning. Giving priority for a potential lock-holder increases lock
2927 * Since algorithm is based on heuristics, accessing another VCPU data without
2928 * locking does not harm. It may result in trying to yield to same VCPU, fail
2929 * and continue with next VCPU and so on.
2931 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2933 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2936 eligible = !vcpu->spin_loop.in_spin_loop ||
2937 vcpu->spin_loop.dy_eligible;
2939 if (vcpu->spin_loop.in_spin_loop)
2940 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2949 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2950 * a vcpu_load/vcpu_put pair. However, for most architectures
2951 * kvm_arch_vcpu_runnable does not require vcpu_load.
2953 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2955 return kvm_arch_vcpu_runnable(vcpu);
2958 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2960 if (kvm_arch_dy_runnable(vcpu))
2963 #ifdef CONFIG_KVM_ASYNC_PF
2964 if (!list_empty_careful(&vcpu->async_pf.done))
2971 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
2973 struct kvm *kvm = me->kvm;
2974 struct kvm_vcpu *vcpu;
2975 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2981 kvm_vcpu_set_in_spin_loop(me, true);
2983 * We boost the priority of a VCPU that is runnable but not
2984 * currently running, because it got preempted by something
2985 * else and called schedule in __vcpu_run. Hopefully that
2986 * VCPU is holding the lock that we need and will release it.
2987 * We approximate round-robin by starting at the last boosted VCPU.
2989 for (pass = 0; pass < 2 && !yielded && try; pass++) {
2990 kvm_for_each_vcpu(i, vcpu, kvm) {
2991 if (!pass && i <= last_boosted_vcpu) {
2992 i = last_boosted_vcpu;
2994 } else if (pass && i > last_boosted_vcpu)
2996 if (!READ_ONCE(vcpu->ready))
3000 if (rcuwait_active(&vcpu->wait) &&
3001 !vcpu_dy_runnable(vcpu))
3003 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3004 !kvm_arch_vcpu_in_kernel(vcpu))
3006 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3009 yielded = kvm_vcpu_yield_to(vcpu);
3011 kvm->last_boosted_vcpu = i;
3013 } else if (yielded < 0) {
3020 kvm_vcpu_set_in_spin_loop(me, false);
3022 /* Ensure vcpu is not eligible during next spinloop */
3023 kvm_vcpu_set_dy_eligible(me, false);
3025 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3027 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3029 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3030 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3031 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3032 kvm->dirty_ring_size / PAGE_SIZE);
3038 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3040 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3043 if (vmf->pgoff == 0)
3044 page = virt_to_page(vcpu->run);
3046 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3047 page = virt_to_page(vcpu->arch.pio_data);
3049 #ifdef CONFIG_KVM_MMIO
3050 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3051 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3053 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3054 page = kvm_dirty_ring_get_page(
3056 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3058 return kvm_arch_vcpu_fault(vcpu, vmf);
3064 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3065 .fault = kvm_vcpu_fault,
3068 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3070 struct kvm_vcpu *vcpu = file->private_data;
3071 unsigned long pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
3073 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3074 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3075 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3078 vma->vm_ops = &kvm_vcpu_vm_ops;
3082 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3084 struct kvm_vcpu *vcpu = filp->private_data;
3086 kvm_put_kvm(vcpu->kvm);
3090 static struct file_operations kvm_vcpu_fops = {
3091 .release = kvm_vcpu_release,
3092 .unlocked_ioctl = kvm_vcpu_ioctl,
3093 .mmap = kvm_vcpu_mmap,
3094 .llseek = noop_llseek,
3095 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3099 * Allocates an inode for the vcpu.
3101 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3103 char name[8 + 1 + ITOA_MAX_LEN + 1];
3105 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3106 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3109 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3111 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3112 struct dentry *debugfs_dentry;
3113 char dir_name[ITOA_MAX_LEN * 2];
3115 if (!debugfs_initialized())
3118 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3119 debugfs_dentry = debugfs_create_dir(dir_name,
3120 vcpu->kvm->debugfs_dentry);
3122 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3127 * Creates some virtual cpus. Good luck creating more than one.
3129 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3132 struct kvm_vcpu *vcpu;
3135 if (id >= KVM_MAX_VCPU_ID)
3138 mutex_lock(&kvm->lock);
3139 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3140 mutex_unlock(&kvm->lock);
3144 kvm->created_vcpus++;
3145 mutex_unlock(&kvm->lock);
3147 r = kvm_arch_vcpu_precreate(kvm, id);
3149 goto vcpu_decrement;
3151 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
3154 goto vcpu_decrement;
3157 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3158 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3163 vcpu->run = page_address(page);
3165 kvm_vcpu_init(vcpu, kvm, id);
3167 r = kvm_arch_vcpu_create(vcpu);
3169 goto vcpu_free_run_page;
3171 if (kvm->dirty_ring_size) {
3172 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3173 id, kvm->dirty_ring_size);
3175 goto arch_vcpu_destroy;
3178 mutex_lock(&kvm->lock);
3179 if (kvm_get_vcpu_by_id(kvm, id)) {
3181 goto unlock_vcpu_destroy;
3184 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3185 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
3187 /* Now it's all set up, let userspace reach it */
3189 r = create_vcpu_fd(vcpu);
3191 kvm_put_kvm_no_destroy(kvm);
3192 goto unlock_vcpu_destroy;
3195 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
3198 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3199 * before kvm->online_vcpu's incremented value.
3202 atomic_inc(&kvm->online_vcpus);
3204 mutex_unlock(&kvm->lock);
3205 kvm_arch_vcpu_postcreate(vcpu);
3206 kvm_create_vcpu_debugfs(vcpu);
3209 unlock_vcpu_destroy:
3210 mutex_unlock(&kvm->lock);
3211 kvm_dirty_ring_free(&vcpu->dirty_ring);
3213 kvm_arch_vcpu_destroy(vcpu);
3215 free_page((unsigned long)vcpu->run);
3217 kmem_cache_free(kvm_vcpu_cache, vcpu);
3219 mutex_lock(&kvm->lock);
3220 kvm->created_vcpus--;
3221 mutex_unlock(&kvm->lock);
3225 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3228 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3229 vcpu->sigset_active = 1;
3230 vcpu->sigset = *sigset;
3232 vcpu->sigset_active = 0;
3236 static long kvm_vcpu_ioctl(struct file *filp,
3237 unsigned int ioctl, unsigned long arg)
3239 struct kvm_vcpu *vcpu = filp->private_data;
3240 void __user *argp = (void __user *)arg;
3242 struct kvm_fpu *fpu = NULL;
3243 struct kvm_sregs *kvm_sregs = NULL;
3245 if (vcpu->kvm->mm != current->mm)
3248 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3252 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3253 * execution; mutex_lock() would break them.
3255 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3256 if (r != -ENOIOCTLCMD)
3259 if (mutex_lock_killable(&vcpu->mutex))
3267 oldpid = rcu_access_pointer(vcpu->pid);
3268 if (unlikely(oldpid != task_pid(current))) {
3269 /* The thread running this VCPU changed. */
3272 r = kvm_arch_vcpu_run_pid_change(vcpu);
3276 newpid = get_task_pid(current, PIDTYPE_PID);
3277 rcu_assign_pointer(vcpu->pid, newpid);
3282 r = kvm_arch_vcpu_ioctl_run(vcpu);
3283 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3286 case KVM_GET_REGS: {
3287 struct kvm_regs *kvm_regs;
3290 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3293 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3297 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3304 case KVM_SET_REGS: {
3305 struct kvm_regs *kvm_regs;
3307 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3308 if (IS_ERR(kvm_regs)) {
3309 r = PTR_ERR(kvm_regs);
3312 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3316 case KVM_GET_SREGS: {
3317 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3318 GFP_KERNEL_ACCOUNT);
3322 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3326 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3331 case KVM_SET_SREGS: {
3332 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3333 if (IS_ERR(kvm_sregs)) {
3334 r = PTR_ERR(kvm_sregs);
3338 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3341 case KVM_GET_MP_STATE: {
3342 struct kvm_mp_state mp_state;
3344 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3348 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3353 case KVM_SET_MP_STATE: {
3354 struct kvm_mp_state mp_state;
3357 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3359 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3362 case KVM_TRANSLATE: {
3363 struct kvm_translation tr;
3366 if (copy_from_user(&tr, argp, sizeof(tr)))
3368 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3372 if (copy_to_user(argp, &tr, sizeof(tr)))
3377 case KVM_SET_GUEST_DEBUG: {
3378 struct kvm_guest_debug dbg;
3381 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3383 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3386 case KVM_SET_SIGNAL_MASK: {
3387 struct kvm_signal_mask __user *sigmask_arg = argp;
3388 struct kvm_signal_mask kvm_sigmask;
3389 sigset_t sigset, *p;
3394 if (copy_from_user(&kvm_sigmask, argp,
3395 sizeof(kvm_sigmask)))
3398 if (kvm_sigmask.len != sizeof(sigset))
3401 if (copy_from_user(&sigset, sigmask_arg->sigset,
3406 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3410 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
3414 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3418 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3424 fpu = memdup_user(argp, sizeof(*fpu));
3430 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3434 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3437 mutex_unlock(&vcpu->mutex);
3443 #ifdef CONFIG_KVM_COMPAT
3444 static long kvm_vcpu_compat_ioctl(struct file *filp,
3445 unsigned int ioctl, unsigned long arg)
3447 struct kvm_vcpu *vcpu = filp->private_data;
3448 void __user *argp = compat_ptr(arg);
3451 if (vcpu->kvm->mm != current->mm)
3455 case KVM_SET_SIGNAL_MASK: {
3456 struct kvm_signal_mask __user *sigmask_arg = argp;
3457 struct kvm_signal_mask kvm_sigmask;
3462 if (copy_from_user(&kvm_sigmask, argp,
3463 sizeof(kvm_sigmask)))
3466 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3469 if (get_compat_sigset(&sigset,
3470 (compat_sigset_t __user *)sigmask_arg->sigset))
3472 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3474 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3478 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3486 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3488 struct kvm_device *dev = filp->private_data;
3491 return dev->ops->mmap(dev, vma);
3496 static int kvm_device_ioctl_attr(struct kvm_device *dev,
3497 int (*accessor)(struct kvm_device *dev,
3498 struct kvm_device_attr *attr),
3501 struct kvm_device_attr attr;
3506 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3509 return accessor(dev, &attr);
3512 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3515 struct kvm_device *dev = filp->private_data;
3517 if (dev->kvm->mm != current->mm)
3521 case KVM_SET_DEVICE_ATTR:
3522 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3523 case KVM_GET_DEVICE_ATTR:
3524 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3525 case KVM_HAS_DEVICE_ATTR:
3526 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3528 if (dev->ops->ioctl)
3529 return dev->ops->ioctl(dev, ioctl, arg);
3535 static int kvm_device_release(struct inode *inode, struct file *filp)
3537 struct kvm_device *dev = filp->private_data;
3538 struct kvm *kvm = dev->kvm;
3540 if (dev->ops->release) {
3541 mutex_lock(&kvm->lock);
3542 list_del(&dev->vm_node);
3543 dev->ops->release(dev);
3544 mutex_unlock(&kvm->lock);
3551 static const struct file_operations kvm_device_fops = {
3552 .unlocked_ioctl = kvm_device_ioctl,
3553 .release = kvm_device_release,
3554 KVM_COMPAT(kvm_device_ioctl),
3555 .mmap = kvm_device_mmap,
3558 struct kvm_device *kvm_device_from_filp(struct file *filp)
3560 if (filp->f_op != &kvm_device_fops)
3563 return filp->private_data;
3566 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
3567 #ifdef CONFIG_KVM_MPIC
3568 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3569 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3573 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
3575 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3578 if (kvm_device_ops_table[type] != NULL)
3581 kvm_device_ops_table[type] = ops;
3585 void kvm_unregister_device_ops(u32 type)
3587 if (kvm_device_ops_table[type] != NULL)
3588 kvm_device_ops_table[type] = NULL;
3591 static int kvm_ioctl_create_device(struct kvm *kvm,
3592 struct kvm_create_device *cd)
3594 const struct kvm_device_ops *ops = NULL;
3595 struct kvm_device *dev;
3596 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
3600 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3603 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3604 ops = kvm_device_ops_table[type];
3611 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
3618 mutex_lock(&kvm->lock);
3619 ret = ops->create(dev, type);
3621 mutex_unlock(&kvm->lock);
3625 list_add(&dev->vm_node, &kvm->devices);
3626 mutex_unlock(&kvm->lock);
3632 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3634 kvm_put_kvm_no_destroy(kvm);
3635 mutex_lock(&kvm->lock);
3636 list_del(&dev->vm_node);
3637 mutex_unlock(&kvm->lock);
3646 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3649 case KVM_CAP_USER_MEMORY:
3650 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3651 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3652 case KVM_CAP_INTERNAL_ERROR_DATA:
3653 #ifdef CONFIG_HAVE_KVM_MSI
3654 case KVM_CAP_SIGNAL_MSI:
3656 #ifdef CONFIG_HAVE_KVM_IRQFD
3658 case KVM_CAP_IRQFD_RESAMPLE:
3660 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3661 case KVM_CAP_CHECK_EXTENSION_VM:
3662 case KVM_CAP_ENABLE_CAP_VM:
3663 case KVM_CAP_HALT_POLL:
3665 #ifdef CONFIG_KVM_MMIO
3666 case KVM_CAP_COALESCED_MMIO:
3667 return KVM_COALESCED_MMIO_PAGE_OFFSET;
3668 case KVM_CAP_COALESCED_PIO:
3671 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3672 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
3673 return KVM_DIRTY_LOG_MANUAL_CAPS;
3675 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3676 case KVM_CAP_IRQ_ROUTING:
3677 return KVM_MAX_IRQ_ROUTES;
3679 #if KVM_ADDRESS_SPACE_NUM > 1
3680 case KVM_CAP_MULTI_ADDRESS_SPACE:
3681 return KVM_ADDRESS_SPACE_NUM;
3683 case KVM_CAP_NR_MEMSLOTS:
3684 return KVM_USER_MEM_SLOTS;
3685 case KVM_CAP_DIRTY_LOG_RING:
3686 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3687 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
3694 return kvm_vm_ioctl_check_extension(kvm, arg);
3697 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
3701 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
3704 /* the size should be power of 2 */
3705 if (!size || (size & (size - 1)))
3708 /* Should be bigger to keep the reserved entries, or a page */
3709 if (size < kvm_dirty_ring_get_rsvd_entries() *
3710 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
3713 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
3714 sizeof(struct kvm_dirty_gfn))
3717 /* We only allow it to set once */
3718 if (kvm->dirty_ring_size)
3721 mutex_lock(&kvm->lock);
3723 if (kvm->created_vcpus) {
3724 /* We don't allow to change this value after vcpu created */
3727 kvm->dirty_ring_size = size;
3731 mutex_unlock(&kvm->lock);
3735 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
3738 struct kvm_vcpu *vcpu;
3741 if (!kvm->dirty_ring_size)
3744 mutex_lock(&kvm->slots_lock);
3746 kvm_for_each_vcpu(i, vcpu, kvm)
3747 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
3749 mutex_unlock(&kvm->slots_lock);
3752 kvm_flush_remote_tlbs(kvm);
3757 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3758 struct kvm_enable_cap *cap)
3763 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
3764 struct kvm_enable_cap *cap)
3767 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3768 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
3769 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
3771 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
3772 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
3774 if (cap->flags || (cap->args[0] & ~allowed_options))
3776 kvm->manual_dirty_log_protect = cap->args[0];
3780 case KVM_CAP_HALT_POLL: {
3781 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
3784 kvm->max_halt_poll_ns = cap->args[0];
3787 case KVM_CAP_DIRTY_LOG_RING:
3788 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
3790 return kvm_vm_ioctl_enable_cap(kvm, cap);
3794 static long kvm_vm_ioctl(struct file *filp,
3795 unsigned int ioctl, unsigned long arg)
3797 struct kvm *kvm = filp->private_data;
3798 void __user *argp = (void __user *)arg;
3801 if (kvm->mm != current->mm)
3804 case KVM_CREATE_VCPU:
3805 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3807 case KVM_ENABLE_CAP: {
3808 struct kvm_enable_cap cap;
3811 if (copy_from_user(&cap, argp, sizeof(cap)))
3813 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
3816 case KVM_SET_USER_MEMORY_REGION: {
3817 struct kvm_userspace_memory_region kvm_userspace_mem;
3820 if (copy_from_user(&kvm_userspace_mem, argp,
3821 sizeof(kvm_userspace_mem)))
3824 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3827 case KVM_GET_DIRTY_LOG: {
3828 struct kvm_dirty_log log;
3831 if (copy_from_user(&log, argp, sizeof(log)))
3833 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3836 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3837 case KVM_CLEAR_DIRTY_LOG: {
3838 struct kvm_clear_dirty_log log;
3841 if (copy_from_user(&log, argp, sizeof(log)))
3843 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3847 #ifdef CONFIG_KVM_MMIO
3848 case KVM_REGISTER_COALESCED_MMIO: {
3849 struct kvm_coalesced_mmio_zone zone;
3852 if (copy_from_user(&zone, argp, sizeof(zone)))
3854 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3857 case KVM_UNREGISTER_COALESCED_MMIO: {
3858 struct kvm_coalesced_mmio_zone zone;
3861 if (copy_from_user(&zone, argp, sizeof(zone)))
3863 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3868 struct kvm_irqfd data;
3871 if (copy_from_user(&data, argp, sizeof(data)))
3873 r = kvm_irqfd(kvm, &data);
3876 case KVM_IOEVENTFD: {
3877 struct kvm_ioeventfd data;
3880 if (copy_from_user(&data, argp, sizeof(data)))
3882 r = kvm_ioeventfd(kvm, &data);
3885 #ifdef CONFIG_HAVE_KVM_MSI
3886 case KVM_SIGNAL_MSI: {
3890 if (copy_from_user(&msi, argp, sizeof(msi)))
3892 r = kvm_send_userspace_msi(kvm, &msi);
3896 #ifdef __KVM_HAVE_IRQ_LINE
3897 case KVM_IRQ_LINE_STATUS:
3898 case KVM_IRQ_LINE: {
3899 struct kvm_irq_level irq_event;
3902 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3905 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3906 ioctl == KVM_IRQ_LINE_STATUS);
3911 if (ioctl == KVM_IRQ_LINE_STATUS) {
3912 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3920 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3921 case KVM_SET_GSI_ROUTING: {
3922 struct kvm_irq_routing routing;
3923 struct kvm_irq_routing __user *urouting;
3924 struct kvm_irq_routing_entry *entries = NULL;
3927 if (copy_from_user(&routing, argp, sizeof(routing)))
3930 if (!kvm_arch_can_set_irq_routing(kvm))
3932 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3938 entries = vmemdup_user(urouting->entries,
3939 array_size(sizeof(*entries),
3941 if (IS_ERR(entries)) {
3942 r = PTR_ERR(entries);
3946 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3951 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3952 case KVM_CREATE_DEVICE: {
3953 struct kvm_create_device cd;
3956 if (copy_from_user(&cd, argp, sizeof(cd)))
3959 r = kvm_ioctl_create_device(kvm, &cd);
3964 if (copy_to_user(argp, &cd, sizeof(cd)))
3970 case KVM_CHECK_EXTENSION:
3971 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3973 case KVM_RESET_DIRTY_RINGS:
3974 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
3977 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3983 #ifdef CONFIG_KVM_COMPAT
3984 struct compat_kvm_dirty_log {
3988 compat_uptr_t dirty_bitmap; /* one bit per page */
3993 static long kvm_vm_compat_ioctl(struct file *filp,
3994 unsigned int ioctl, unsigned long arg)
3996 struct kvm *kvm = filp->private_data;
3999 if (kvm->mm != current->mm)
4002 case KVM_GET_DIRTY_LOG: {
4003 struct compat_kvm_dirty_log compat_log;
4004 struct kvm_dirty_log log;
4006 if (copy_from_user(&compat_log, (void __user *)arg,
4007 sizeof(compat_log)))
4009 log.slot = compat_log.slot;
4010 log.padding1 = compat_log.padding1;
4011 log.padding2 = compat_log.padding2;
4012 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4014 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4018 r = kvm_vm_ioctl(filp, ioctl, arg);
4024 static struct file_operations kvm_vm_fops = {
4025 .release = kvm_vm_release,
4026 .unlocked_ioctl = kvm_vm_ioctl,
4027 .llseek = noop_llseek,
4028 KVM_COMPAT(kvm_vm_compat_ioctl),
4031 static int kvm_dev_ioctl_create_vm(unsigned long type)
4037 kvm = kvm_create_vm(type);
4039 return PTR_ERR(kvm);
4040 #ifdef CONFIG_KVM_MMIO
4041 r = kvm_coalesced_mmio_init(kvm);
4045 r = get_unused_fd_flags(O_CLOEXEC);
4049 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4057 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4058 * already set, with ->release() being kvm_vm_release(). In error
4059 * cases it will be called by the final fput(file) and will take
4060 * care of doing kvm_put_kvm(kvm).
4062 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4067 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4069 fd_install(r, file);
4077 static long kvm_dev_ioctl(struct file *filp,
4078 unsigned int ioctl, unsigned long arg)
4083 case KVM_GET_API_VERSION:
4086 r = KVM_API_VERSION;
4089 r = kvm_dev_ioctl_create_vm(arg);
4091 case KVM_CHECK_EXTENSION:
4092 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4094 case KVM_GET_VCPU_MMAP_SIZE:
4097 r = PAGE_SIZE; /* struct kvm_run */
4099 r += PAGE_SIZE; /* pio data page */
4101 #ifdef CONFIG_KVM_MMIO
4102 r += PAGE_SIZE; /* coalesced mmio ring page */
4105 case KVM_TRACE_ENABLE:
4106 case KVM_TRACE_PAUSE:
4107 case KVM_TRACE_DISABLE:
4111 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4117 static struct file_operations kvm_chardev_ops = {
4118 .unlocked_ioctl = kvm_dev_ioctl,
4119 .llseek = noop_llseek,
4120 KVM_COMPAT(kvm_dev_ioctl),
4123 static struct miscdevice kvm_dev = {
4129 static void hardware_enable_nolock(void *junk)
4131 int cpu = raw_smp_processor_id();
4134 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4137 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4139 r = kvm_arch_hardware_enable();
4142 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4143 atomic_inc(&hardware_enable_failed);
4144 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4148 static int kvm_starting_cpu(unsigned int cpu)
4150 raw_spin_lock(&kvm_count_lock);
4151 if (kvm_usage_count)
4152 hardware_enable_nolock(NULL);
4153 raw_spin_unlock(&kvm_count_lock);
4157 static void hardware_disable_nolock(void *junk)
4159 int cpu = raw_smp_processor_id();
4161 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4163 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4164 kvm_arch_hardware_disable();
4167 static int kvm_dying_cpu(unsigned int cpu)
4169 raw_spin_lock(&kvm_count_lock);
4170 if (kvm_usage_count)
4171 hardware_disable_nolock(NULL);
4172 raw_spin_unlock(&kvm_count_lock);
4176 static void hardware_disable_all_nolock(void)
4178 BUG_ON(!kvm_usage_count);
4181 if (!kvm_usage_count)
4182 on_each_cpu(hardware_disable_nolock, NULL, 1);
4185 static void hardware_disable_all(void)
4187 raw_spin_lock(&kvm_count_lock);
4188 hardware_disable_all_nolock();
4189 raw_spin_unlock(&kvm_count_lock);
4192 static int hardware_enable_all(void)
4196 raw_spin_lock(&kvm_count_lock);
4199 if (kvm_usage_count == 1) {
4200 atomic_set(&hardware_enable_failed, 0);
4201 on_each_cpu(hardware_enable_nolock, NULL, 1);
4203 if (atomic_read(&hardware_enable_failed)) {
4204 hardware_disable_all_nolock();
4209 raw_spin_unlock(&kvm_count_lock);
4214 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4218 * Some (well, at least mine) BIOSes hang on reboot if
4221 * And Intel TXT required VMX off for all cpu when system shutdown.
4223 pr_info("kvm: exiting hardware virtualization\n");
4224 kvm_rebooting = true;
4225 on_each_cpu(hardware_disable_nolock, NULL, 1);
4229 static struct notifier_block kvm_reboot_notifier = {
4230 .notifier_call = kvm_reboot,
4234 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4238 for (i = 0; i < bus->dev_count; i++) {
4239 struct kvm_io_device *pos = bus->range[i].dev;
4241 kvm_iodevice_destructor(pos);
4246 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4247 const struct kvm_io_range *r2)
4249 gpa_t addr1 = r1->addr;
4250 gpa_t addr2 = r2->addr;
4255 /* If r2->len == 0, match the exact address. If r2->len != 0,
4256 * accept any overlapping write. Any order is acceptable for
4257 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4258 * we process all of them.
4271 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4273 return kvm_io_bus_cmp(p1, p2);
4276 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4277 gpa_t addr, int len)
4279 struct kvm_io_range *range, key;
4282 key = (struct kvm_io_range) {
4287 range = bsearch(&key, bus->range, bus->dev_count,
4288 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4292 off = range - bus->range;
4294 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
4300 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4301 struct kvm_io_range *range, const void *val)
4305 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4309 while (idx < bus->dev_count &&
4310 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4311 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
4320 /* kvm_io_bus_write - called under kvm->slots_lock */
4321 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4322 int len, const void *val)
4324 struct kvm_io_bus *bus;
4325 struct kvm_io_range range;
4328 range = (struct kvm_io_range) {
4333 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4336 r = __kvm_io_bus_write(vcpu, bus, &range, val);
4337 return r < 0 ? r : 0;
4339 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
4341 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
4342 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4343 gpa_t addr, int len, const void *val, long cookie)
4345 struct kvm_io_bus *bus;
4346 struct kvm_io_range range;
4348 range = (struct kvm_io_range) {
4353 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4357 /* First try the device referenced by cookie. */
4358 if ((cookie >= 0) && (cookie < bus->dev_count) &&
4359 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
4360 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
4365 * cookie contained garbage; fall back to search and return the
4366 * correct cookie value.
4368 return __kvm_io_bus_write(vcpu, bus, &range, val);
4371 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4372 struct kvm_io_range *range, void *val)
4376 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4380 while (idx < bus->dev_count &&
4381 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4382 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4391 /* kvm_io_bus_read - called under kvm->slots_lock */
4392 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4395 struct kvm_io_bus *bus;
4396 struct kvm_io_range range;
4399 range = (struct kvm_io_range) {
4404 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4407 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4408 return r < 0 ? r : 0;
4411 /* Caller must hold slots_lock. */
4412 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4413 int len, struct kvm_io_device *dev)
4416 struct kvm_io_bus *new_bus, *bus;
4417 struct kvm_io_range range;
4419 bus = kvm_get_bus(kvm, bus_idx);
4423 /* exclude ioeventfd which is limited by maximum fd */
4424 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
4427 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
4428 GFP_KERNEL_ACCOUNT);
4432 range = (struct kvm_io_range) {
4438 for (i = 0; i < bus->dev_count; i++)
4439 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4442 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4443 new_bus->dev_count++;
4444 new_bus->range[i] = range;
4445 memcpy(new_bus->range + i + 1, bus->range + i,
4446 (bus->dev_count - i) * sizeof(struct kvm_io_range));
4447 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4448 synchronize_srcu_expedited(&kvm->srcu);
4454 /* Caller must hold slots_lock. */
4455 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4456 struct kvm_io_device *dev)
4459 struct kvm_io_bus *new_bus, *bus;
4461 bus = kvm_get_bus(kvm, bus_idx);
4465 for (i = 0; i < bus->dev_count; i++)
4466 if (bus->range[i].dev == dev) {
4470 if (i == bus->dev_count)
4473 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
4474 GFP_KERNEL_ACCOUNT);
4476 memcpy(new_bus, bus, struct_size(bus, range, i));
4477 new_bus->dev_count--;
4478 memcpy(new_bus->range + i, bus->range + i + 1,
4479 flex_array_size(new_bus, range, new_bus->dev_count - i));
4481 pr_err("kvm: failed to shrink bus, removing it completely\n");
4482 for (j = 0; j < bus->dev_count; j++) {
4485 kvm_iodevice_destructor(bus->range[j].dev);
4489 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4490 synchronize_srcu_expedited(&kvm->srcu);
4495 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4498 struct kvm_io_bus *bus;
4499 int dev_idx, srcu_idx;
4500 struct kvm_io_device *iodev = NULL;
4502 srcu_idx = srcu_read_lock(&kvm->srcu);
4504 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
4508 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
4512 iodev = bus->range[dev_idx].dev;
4515 srcu_read_unlock(&kvm->srcu, srcu_idx);
4519 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4521 static int kvm_debugfs_open(struct inode *inode, struct file *file,
4522 int (*get)(void *, u64 *), int (*set)(void *, u64),
4525 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4528 /* The debugfs files are a reference to the kvm struct which
4529 * is still valid when kvm_destroy_vm is called.
4530 * To avoid the race between open and the removal of the debugfs
4531 * directory we test against the users count.
4533 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
4536 if (simple_attr_open(inode, file, get,
4537 KVM_DBGFS_GET_MODE(stat_data->dbgfs_item) & 0222
4540 kvm_put_kvm(stat_data->kvm);
4547 static int kvm_debugfs_release(struct inode *inode, struct file *file)
4549 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4552 simple_attr_release(inode, file);
4553 kvm_put_kvm(stat_data->kvm);
4558 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
4560 *val = *(ulong *)((void *)kvm + offset);
4565 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
4567 *(ulong *)((void *)kvm + offset) = 0;
4572 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
4575 struct kvm_vcpu *vcpu;
4579 kvm_for_each_vcpu(i, vcpu, kvm)
4580 *val += *(u64 *)((void *)vcpu + offset);
4585 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
4588 struct kvm_vcpu *vcpu;
4590 kvm_for_each_vcpu(i, vcpu, kvm)
4591 *(u64 *)((void *)vcpu + offset) = 0;
4596 static int kvm_stat_data_get(void *data, u64 *val)
4599 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4601 switch (stat_data->dbgfs_item->kind) {
4603 r = kvm_get_stat_per_vm(stat_data->kvm,
4604 stat_data->dbgfs_item->offset, val);
4607 r = kvm_get_stat_per_vcpu(stat_data->kvm,
4608 stat_data->dbgfs_item->offset, val);
4615 static int kvm_stat_data_clear(void *data, u64 val)
4618 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4623 switch (stat_data->dbgfs_item->kind) {
4625 r = kvm_clear_stat_per_vm(stat_data->kvm,
4626 stat_data->dbgfs_item->offset);
4629 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
4630 stat_data->dbgfs_item->offset);
4637 static int kvm_stat_data_open(struct inode *inode, struct file *file)
4639 __simple_attr_check_format("%llu\n", 0ull);
4640 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
4641 kvm_stat_data_clear, "%llu\n");
4644 static const struct file_operations stat_fops_per_vm = {
4645 .owner = THIS_MODULE,
4646 .open = kvm_stat_data_open,
4647 .release = kvm_debugfs_release,
4648 .read = simple_attr_read,
4649 .write = simple_attr_write,
4650 .llseek = no_llseek,
4653 static int vm_stat_get(void *_offset, u64 *val)
4655 unsigned offset = (long)_offset;
4660 mutex_lock(&kvm_lock);
4661 list_for_each_entry(kvm, &vm_list, vm_list) {
4662 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
4665 mutex_unlock(&kvm_lock);
4669 static int vm_stat_clear(void *_offset, u64 val)
4671 unsigned offset = (long)_offset;
4677 mutex_lock(&kvm_lock);
4678 list_for_each_entry(kvm, &vm_list, vm_list) {
4679 kvm_clear_stat_per_vm(kvm, offset);
4681 mutex_unlock(&kvm_lock);
4686 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
4688 static int vcpu_stat_get(void *_offset, u64 *val)
4690 unsigned offset = (long)_offset;
4695 mutex_lock(&kvm_lock);
4696 list_for_each_entry(kvm, &vm_list, vm_list) {
4697 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
4700 mutex_unlock(&kvm_lock);
4704 static int vcpu_stat_clear(void *_offset, u64 val)
4706 unsigned offset = (long)_offset;
4712 mutex_lock(&kvm_lock);
4713 list_for_each_entry(kvm, &vm_list, vm_list) {
4714 kvm_clear_stat_per_vcpu(kvm, offset);
4716 mutex_unlock(&kvm_lock);
4721 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4724 static const struct file_operations *stat_fops[] = {
4725 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4726 [KVM_STAT_VM] = &vm_stat_fops,
4729 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4731 struct kobj_uevent_env *env;
4732 unsigned long long created, active;
4734 if (!kvm_dev.this_device || !kvm)
4737 mutex_lock(&kvm_lock);
4738 if (type == KVM_EVENT_CREATE_VM) {
4739 kvm_createvm_count++;
4741 } else if (type == KVM_EVENT_DESTROY_VM) {
4744 created = kvm_createvm_count;
4745 active = kvm_active_vms;
4746 mutex_unlock(&kvm_lock);
4748 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
4752 add_uevent_var(env, "CREATED=%llu", created);
4753 add_uevent_var(env, "COUNT=%llu", active);
4755 if (type == KVM_EVENT_CREATE_VM) {
4756 add_uevent_var(env, "EVENT=create");
4757 kvm->userspace_pid = task_pid_nr(current);
4758 } else if (type == KVM_EVENT_DESTROY_VM) {
4759 add_uevent_var(env, "EVENT=destroy");
4761 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
4763 if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
4764 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
4767 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4769 add_uevent_var(env, "STATS_PATH=%s", tmp);
4773 /* no need for checks, since we are adding at most only 5 keys */
4774 env->envp[env->envp_idx++] = NULL;
4775 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4779 static void kvm_init_debug(void)
4781 struct kvm_stats_debugfs_item *p;
4783 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4785 kvm_debugfs_num_entries = 0;
4786 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
4787 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
4788 kvm_debugfs_dir, (void *)(long)p->offset,
4789 stat_fops[p->kind]);
4793 static int kvm_suspend(void)
4795 if (kvm_usage_count)
4796 hardware_disable_nolock(NULL);
4800 static void kvm_resume(void)
4802 if (kvm_usage_count) {
4803 #ifdef CONFIG_LOCKDEP
4804 WARN_ON(lockdep_is_held(&kvm_count_lock));
4806 hardware_enable_nolock(NULL);
4810 static struct syscore_ops kvm_syscore_ops = {
4811 .suspend = kvm_suspend,
4812 .resume = kvm_resume,
4816 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4818 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4821 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4823 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4825 WRITE_ONCE(vcpu->preempted, false);
4826 WRITE_ONCE(vcpu->ready, false);
4828 __this_cpu_write(kvm_running_vcpu, vcpu);
4829 kvm_arch_sched_in(vcpu, cpu);
4830 kvm_arch_vcpu_load(vcpu, cpu);
4833 static void kvm_sched_out(struct preempt_notifier *pn,
4834 struct task_struct *next)
4836 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4838 if (current->state == TASK_RUNNING) {
4839 WRITE_ONCE(vcpu->preempted, true);
4840 WRITE_ONCE(vcpu->ready, true);
4842 kvm_arch_vcpu_put(vcpu);
4843 __this_cpu_write(kvm_running_vcpu, NULL);
4847 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
4849 * We can disable preemption locally around accessing the per-CPU variable,
4850 * and use the resolved vcpu pointer after enabling preemption again,
4851 * because even if the current thread is migrated to another CPU, reading
4852 * the per-CPU value later will give us the same value as we update the
4853 * per-CPU variable in the preempt notifier handlers.
4855 struct kvm_vcpu *kvm_get_running_vcpu(void)
4857 struct kvm_vcpu *vcpu;
4860 vcpu = __this_cpu_read(kvm_running_vcpu);
4865 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
4868 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
4870 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
4872 return &kvm_running_vcpu;
4875 struct kvm_cpu_compat_check {
4880 static void check_processor_compat(void *data)
4882 struct kvm_cpu_compat_check *c = data;
4884 *c->ret = kvm_arch_check_processor_compat(c->opaque);
4887 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
4888 struct module *module)
4890 struct kvm_cpu_compat_check c;
4894 r = kvm_arch_init(opaque);
4899 * kvm_arch_init makes sure there's at most one caller
4900 * for architectures that support multiple implementations,
4901 * like intel and amd on x86.
4902 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4903 * conflicts in case kvm is already setup for another implementation.
4905 r = kvm_irqfd_init();
4909 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
4914 r = kvm_arch_hardware_setup(opaque);
4920 for_each_online_cpu(cpu) {
4921 smp_call_function_single(cpu, check_processor_compat, &c, 1);
4926 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
4927 kvm_starting_cpu, kvm_dying_cpu);
4930 register_reboot_notifier(&kvm_reboot_notifier);
4932 /* A kmem cache lets us meet the alignment requirements of fx_save. */
4934 vcpu_align = __alignof__(struct kvm_vcpu);
4936 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4938 offsetof(struct kvm_vcpu, arch),
4939 sizeof_field(struct kvm_vcpu, arch),
4941 if (!kvm_vcpu_cache) {
4946 r = kvm_async_pf_init();
4950 kvm_chardev_ops.owner = module;
4951 kvm_vm_fops.owner = module;
4952 kvm_vcpu_fops.owner = module;
4954 r = misc_register(&kvm_dev);
4956 pr_err("kvm: misc device register failed\n");
4960 register_syscore_ops(&kvm_syscore_ops);
4962 kvm_preempt_ops.sched_in = kvm_sched_in;
4963 kvm_preempt_ops.sched_out = kvm_sched_out;
4967 r = kvm_vfio_ops_init();
4973 kvm_async_pf_deinit();
4975 kmem_cache_destroy(kvm_vcpu_cache);
4977 unregister_reboot_notifier(&kvm_reboot_notifier);
4978 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4980 kvm_arch_hardware_unsetup();
4982 free_cpumask_var(cpus_hardware_enabled);
4990 EXPORT_SYMBOL_GPL(kvm_init);
4994 debugfs_remove_recursive(kvm_debugfs_dir);
4995 misc_deregister(&kvm_dev);
4996 kmem_cache_destroy(kvm_vcpu_cache);
4997 kvm_async_pf_deinit();
4998 unregister_syscore_ops(&kvm_syscore_ops);
4999 unregister_reboot_notifier(&kvm_reboot_notifier);
5000 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5001 on_each_cpu(hardware_disable_nolock, NULL, 1);
5002 kvm_arch_hardware_unsetup();
5005 free_cpumask_var(cpus_hardware_enabled);
5006 kvm_vfio_ops_exit();
5008 EXPORT_SYMBOL_GPL(kvm_exit);
5010 struct kvm_vm_worker_thread_context {
5012 struct task_struct *parent;
5013 struct completion init_done;
5014 kvm_vm_thread_fn_t thread_fn;
5019 static int kvm_vm_worker_thread(void *context)
5022 * The init_context is allocated on the stack of the parent thread, so
5023 * we have to locally copy anything that is needed beyond initialization
5025 struct kvm_vm_worker_thread_context *init_context = context;
5026 struct kvm *kvm = init_context->kvm;
5027 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5028 uintptr_t data = init_context->data;
5031 err = kthread_park(current);
5032 /* kthread_park(current) is never supposed to return an error */
5037 err = cgroup_attach_task_all(init_context->parent, current);
5039 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5044 set_user_nice(current, task_nice(init_context->parent));
5047 init_context->err = err;
5048 complete(&init_context->init_done);
5049 init_context = NULL;
5054 /* Wait to be woken up by the spawner before proceeding. */
5057 if (!kthread_should_stop())
5058 err = thread_fn(kvm, data);
5063 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5064 uintptr_t data, const char *name,
5065 struct task_struct **thread_ptr)
5067 struct kvm_vm_worker_thread_context init_context = {};
5068 struct task_struct *thread;
5071 init_context.kvm = kvm;
5072 init_context.parent = current;
5073 init_context.thread_fn = thread_fn;
5074 init_context.data = data;
5075 init_completion(&init_context.init_done);
5077 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5078 "%s-%d", name, task_pid_nr(current));
5080 return PTR_ERR(thread);
5082 /* kthread_run is never supposed to return NULL */
5083 WARN_ON(thread == NULL);
5085 wait_for_completion(&init_context.init_done);
5087 if (!init_context.err)
5088 *thread_ptr = thread;
5090 return init_context.err;