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"
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/kvm.h>
67 #include <linux/kvm_dirty_ring.h>
69 /* Worst case buffer size needed for holding an integer. */
70 #define ITOA_MAX_LEN 12
72 MODULE_AUTHOR("Qumranet");
73 MODULE_LICENSE("GPL");
75 /* Architectures should define their poll value according to the halt latency */
76 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
77 module_param(halt_poll_ns, uint, 0644);
78 EXPORT_SYMBOL_GPL(halt_poll_ns);
80 /* Default doubles per-vcpu halt_poll_ns. */
81 unsigned int halt_poll_ns_grow = 2;
82 module_param(halt_poll_ns_grow, uint, 0644);
83 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
85 /* The start value to grow halt_poll_ns from */
86 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
87 module_param(halt_poll_ns_grow_start, uint, 0644);
88 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
90 /* Default resets per-vcpu halt_poll_ns . */
91 unsigned int halt_poll_ns_shrink;
92 module_param(halt_poll_ns_shrink, uint, 0644);
93 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
98 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
101 DEFINE_MUTEX(kvm_lock);
102 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
105 static cpumask_var_t cpus_hardware_enabled;
106 static int kvm_usage_count;
107 static atomic_t hardware_enable_failed;
109 static struct kmem_cache *kvm_vcpu_cache;
111 static __read_mostly struct preempt_ops kvm_preempt_ops;
112 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
114 struct dentry *kvm_debugfs_dir;
115 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
117 static int kvm_debugfs_num_entries;
118 static const struct file_operations stat_fops_per_vm;
120 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
122 #ifdef CONFIG_KVM_COMPAT
123 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
125 #define KVM_COMPAT(c) .compat_ioctl = (c)
128 * For architectures that don't implement a compat infrastructure,
129 * adopt a double line of defense:
130 * - Prevent a compat task from opening /dev/kvm
131 * - If the open has been done by a 64bit task, and the KVM fd
132 * passed to a compat task, let the ioctls fail.
134 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
135 unsigned long arg) { return -EINVAL; }
137 static int kvm_no_compat_open(struct inode *inode, struct file *file)
139 return is_compat_task() ? -ENODEV : 0;
141 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
142 .open = kvm_no_compat_open
144 static int hardware_enable_all(void);
145 static void hardware_disable_all(void);
147 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
149 __visible bool kvm_rebooting;
150 EXPORT_SYMBOL_GPL(kvm_rebooting);
152 #define KVM_EVENT_CREATE_VM 0
153 #define KVM_EVENT_DESTROY_VM 1
154 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
155 static unsigned long long kvm_createvm_count;
156 static unsigned long long kvm_active_vms;
158 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
159 unsigned long start, unsigned long end)
163 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
166 * The metadata used by is_zone_device_page() to determine whether or
167 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
168 * the device has been pinned, e.g. by get_user_pages(). WARN if the
169 * page_count() is zero to help detect bad usage of this helper.
171 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
174 return is_zone_device_page(pfn_to_page(pfn));
177 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
180 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
181 * perspective they are "normal" pages, albeit with slightly different
185 return PageReserved(pfn_to_page(pfn)) &&
187 !kvm_is_zone_device_pfn(pfn);
192 bool kvm_is_transparent_hugepage(kvm_pfn_t pfn)
194 struct page *page = pfn_to_page(pfn);
196 if (!PageTransCompoundMap(page))
199 return is_transparent_hugepage(compound_head(page));
203 * Switches to specified vcpu, until a matching vcpu_put()
205 void vcpu_load(struct kvm_vcpu *vcpu)
209 __this_cpu_write(kvm_running_vcpu, vcpu);
210 preempt_notifier_register(&vcpu->preempt_notifier);
211 kvm_arch_vcpu_load(vcpu, cpu);
214 EXPORT_SYMBOL_GPL(vcpu_load);
216 void vcpu_put(struct kvm_vcpu *vcpu)
219 kvm_arch_vcpu_put(vcpu);
220 preempt_notifier_unregister(&vcpu->preempt_notifier);
221 __this_cpu_write(kvm_running_vcpu, NULL);
224 EXPORT_SYMBOL_GPL(vcpu_put);
226 /* TODO: merge with kvm_arch_vcpu_should_kick */
227 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
229 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
232 * We need to wait for the VCPU to reenable interrupts and get out of
233 * READING_SHADOW_PAGE_TABLES mode.
235 if (req & KVM_REQUEST_WAIT)
236 return mode != OUTSIDE_GUEST_MODE;
239 * Need to kick a running VCPU, but otherwise there is nothing to do.
241 return mode == IN_GUEST_MODE;
244 static void ack_flush(void *_completed)
248 static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
251 cpus = cpu_online_mask;
253 if (cpumask_empty(cpus))
256 smp_call_function_many(cpus, ack_flush, NULL, wait);
260 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
261 struct kvm_vcpu *except,
262 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
265 struct kvm_vcpu *vcpu;
270 kvm_for_each_vcpu(i, vcpu, kvm) {
271 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
275 kvm_make_request(req, vcpu);
278 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
281 if (tmp != NULL && cpu != -1 && cpu != me &&
282 kvm_request_needs_ipi(vcpu, req))
283 __cpumask_set_cpu(cpu, tmp);
286 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
292 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
293 struct kvm_vcpu *except)
298 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
300 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
302 free_cpumask_var(cpus);
306 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
308 return kvm_make_all_cpus_request_except(kvm, req, NULL);
311 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
312 void kvm_flush_remote_tlbs(struct kvm *kvm)
315 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
316 * kvm_make_all_cpus_request.
318 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
321 * We want to publish modifications to the page tables before reading
322 * mode. Pairs with a memory barrier in arch-specific code.
323 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
324 * and smp_mb in walk_shadow_page_lockless_begin/end.
325 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
327 * There is already an smp_mb__after_atomic() before
328 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
331 if (!kvm_arch_flush_remote_tlb(kvm)
332 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
333 ++kvm->stat.remote_tlb_flush;
334 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
336 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
339 void kvm_reload_remote_mmus(struct kvm *kvm)
341 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
344 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
345 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
348 gfp_flags |= mc->gfp_zero;
351 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
353 return (void *)__get_free_page(gfp_flags);
356 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
360 if (mc->nobjs >= min)
362 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
363 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
365 return mc->nobjs >= min ? 0 : -ENOMEM;
366 mc->objects[mc->nobjs++] = obj;
371 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
376 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
380 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
382 free_page((unsigned long)mc->objects[--mc->nobjs]);
386 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
390 if (WARN_ON(!mc->nobjs))
391 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
393 p = mc->objects[--mc->nobjs];
399 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
401 mutex_init(&vcpu->mutex);
406 rcuwait_init(&vcpu->wait);
407 kvm_async_pf_vcpu_init(vcpu);
410 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
412 kvm_vcpu_set_in_spin_loop(vcpu, false);
413 kvm_vcpu_set_dy_eligible(vcpu, false);
414 vcpu->preempted = false;
416 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
419 void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
421 kvm_dirty_ring_free(&vcpu->dirty_ring);
422 kvm_arch_vcpu_destroy(vcpu);
425 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
426 * the vcpu->pid pointer, and at destruction time all file descriptors
429 put_pid(rcu_dereference_protected(vcpu->pid, 1));
431 free_page((unsigned long)vcpu->run);
432 kmem_cache_free(kvm_vcpu_cache, vcpu);
434 EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
436 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
437 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
439 return container_of(mn, struct kvm, mmu_notifier);
442 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
443 struct mm_struct *mm,
444 unsigned long start, unsigned long end)
446 struct kvm *kvm = mmu_notifier_to_kvm(mn);
449 idx = srcu_read_lock(&kvm->srcu);
450 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
451 srcu_read_unlock(&kvm->srcu, idx);
454 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
455 struct mm_struct *mm,
456 unsigned long address,
459 struct kvm *kvm = mmu_notifier_to_kvm(mn);
462 trace_kvm_set_spte_hva(address);
464 idx = srcu_read_lock(&kvm->srcu);
468 kvm->mmu_notifier_seq++;
470 if (kvm_set_spte_hva(kvm, address, pte))
471 kvm_flush_remote_tlbs(kvm);
474 srcu_read_unlock(&kvm->srcu, idx);
477 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
478 const struct mmu_notifier_range *range)
480 struct kvm *kvm = mmu_notifier_to_kvm(mn);
481 int need_tlb_flush = 0, idx;
483 trace_kvm_unmap_hva_range(range->start, range->end);
485 idx = srcu_read_lock(&kvm->srcu);
488 * The count increase must become visible at unlock time as no
489 * spte can be established without taking the mmu_lock and
490 * count is also read inside the mmu_lock critical section.
492 kvm->mmu_notifier_count++;
493 if (likely(kvm->mmu_notifier_count == 1)) {
494 kvm->mmu_notifier_range_start = range->start;
495 kvm->mmu_notifier_range_end = range->end;
498 * Fully tracking multiple concurrent ranges has dimishing
499 * returns. Keep things simple and just find the minimal range
500 * which includes the current and new ranges. As there won't be
501 * enough information to subtract a range after its invalidate
502 * completes, any ranges invalidated concurrently will
503 * accumulate and persist until all outstanding invalidates
506 kvm->mmu_notifier_range_start =
507 min(kvm->mmu_notifier_range_start, range->start);
508 kvm->mmu_notifier_range_end =
509 max(kvm->mmu_notifier_range_end, range->end);
511 need_tlb_flush = kvm_unmap_hva_range(kvm, range->start, range->end,
513 /* we've to flush the tlb before the pages can be freed */
514 if (need_tlb_flush || kvm->tlbs_dirty)
515 kvm_flush_remote_tlbs(kvm);
518 srcu_read_unlock(&kvm->srcu, idx);
523 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
524 const struct mmu_notifier_range *range)
526 struct kvm *kvm = mmu_notifier_to_kvm(mn);
530 * This sequence increase will notify the kvm page fault that
531 * the page that is going to be mapped in the spte could have
534 kvm->mmu_notifier_seq++;
537 * The above sequence increase must be visible before the
538 * below count decrease, which is ensured by the smp_wmb above
539 * in conjunction with the smp_rmb in mmu_notifier_retry().
541 kvm->mmu_notifier_count--;
544 BUG_ON(kvm->mmu_notifier_count < 0);
547 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
548 struct mm_struct *mm,
552 struct kvm *kvm = mmu_notifier_to_kvm(mn);
555 trace_kvm_age_hva(start, end);
557 idx = srcu_read_lock(&kvm->srcu);
560 young = kvm_age_hva(kvm, start, end);
562 kvm_flush_remote_tlbs(kvm);
565 srcu_read_unlock(&kvm->srcu, idx);
570 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
571 struct mm_struct *mm,
575 struct kvm *kvm = mmu_notifier_to_kvm(mn);
578 trace_kvm_age_hva(start, end);
580 idx = srcu_read_lock(&kvm->srcu);
583 * Even though we do not flush TLB, this will still adversely
584 * affect performance on pre-Haswell Intel EPT, where there is
585 * no EPT Access Bit to clear so that we have to tear down EPT
586 * tables instead. If we find this unacceptable, we can always
587 * add a parameter to kvm_age_hva so that it effectively doesn't
588 * do anything on clear_young.
590 * Also note that currently we never issue secondary TLB flushes
591 * from clear_young, leaving this job up to the regular system
592 * cadence. If we find this inaccurate, we might come up with a
593 * more sophisticated heuristic later.
595 young = kvm_age_hva(kvm, start, end);
597 srcu_read_unlock(&kvm->srcu, idx);
602 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
603 struct mm_struct *mm,
604 unsigned long address)
606 struct kvm *kvm = mmu_notifier_to_kvm(mn);
609 trace_kvm_test_age_hva(address);
611 idx = srcu_read_lock(&kvm->srcu);
613 young = kvm_test_age_hva(kvm, address);
615 srcu_read_unlock(&kvm->srcu, idx);
620 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
621 struct mm_struct *mm)
623 struct kvm *kvm = mmu_notifier_to_kvm(mn);
626 idx = srcu_read_lock(&kvm->srcu);
627 kvm_arch_flush_shadow_all(kvm);
628 srcu_read_unlock(&kvm->srcu, idx);
631 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
632 .invalidate_range = kvm_mmu_notifier_invalidate_range,
633 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
634 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
635 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
636 .clear_young = kvm_mmu_notifier_clear_young,
637 .test_young = kvm_mmu_notifier_test_young,
638 .change_pte = kvm_mmu_notifier_change_pte,
639 .release = kvm_mmu_notifier_release,
642 static int kvm_init_mmu_notifier(struct kvm *kvm)
644 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
645 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
648 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
650 static int kvm_init_mmu_notifier(struct kvm *kvm)
655 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
657 static struct kvm_memslots *kvm_alloc_memslots(void)
660 struct kvm_memslots *slots;
662 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
666 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
667 slots->id_to_index[i] = -1;
672 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
674 if (!memslot->dirty_bitmap)
677 kvfree(memslot->dirty_bitmap);
678 memslot->dirty_bitmap = NULL;
681 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
683 kvm_destroy_dirty_bitmap(slot);
685 kvm_arch_free_memslot(kvm, slot);
691 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
693 struct kvm_memory_slot *memslot;
698 kvm_for_each_memslot(memslot, slots)
699 kvm_free_memslot(kvm, memslot);
704 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
708 if (!kvm->debugfs_dentry)
711 debugfs_remove_recursive(kvm->debugfs_dentry);
713 if (kvm->debugfs_stat_data) {
714 for (i = 0; i < kvm_debugfs_num_entries; i++)
715 kfree(kvm->debugfs_stat_data[i]);
716 kfree(kvm->debugfs_stat_data);
720 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
722 char dir_name[ITOA_MAX_LEN * 2];
723 struct kvm_stat_data *stat_data;
724 struct kvm_stats_debugfs_item *p;
726 if (!debugfs_initialized())
729 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
730 kvm->debugfs_dentry = debugfs_create_dir(dir_name, kvm_debugfs_dir);
732 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
733 sizeof(*kvm->debugfs_stat_data),
735 if (!kvm->debugfs_stat_data)
738 for (p = debugfs_entries; p->name; p++) {
739 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
743 stat_data->kvm = kvm;
744 stat_data->dbgfs_item = p;
745 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
746 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
747 kvm->debugfs_dentry, stat_data,
754 * Called after the VM is otherwise initialized, but just before adding it to
757 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
763 * Called just after removing the VM from the vm_list, but before doing any
766 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
770 static struct kvm *kvm_create_vm(unsigned long type)
772 struct kvm *kvm = kvm_arch_alloc_vm();
777 return ERR_PTR(-ENOMEM);
779 KVM_MMU_LOCK_INIT(kvm);
781 kvm->mm = current->mm;
782 kvm_eventfd_init(kvm);
783 mutex_init(&kvm->lock);
784 mutex_init(&kvm->irq_lock);
785 mutex_init(&kvm->slots_lock);
786 INIT_LIST_HEAD(&kvm->devices);
788 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
790 if (init_srcu_struct(&kvm->srcu))
791 goto out_err_no_srcu;
792 if (init_srcu_struct(&kvm->irq_srcu))
793 goto out_err_no_irq_srcu;
795 refcount_set(&kvm->users_count, 1);
796 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
797 struct kvm_memslots *slots = kvm_alloc_memslots();
800 goto out_err_no_arch_destroy_vm;
801 /* Generations must be different for each address space. */
802 slots->generation = i;
803 rcu_assign_pointer(kvm->memslots[i], slots);
806 for (i = 0; i < KVM_NR_BUSES; i++) {
807 rcu_assign_pointer(kvm->buses[i],
808 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
810 goto out_err_no_arch_destroy_vm;
813 kvm->max_halt_poll_ns = halt_poll_ns;
815 r = kvm_arch_init_vm(kvm, type);
817 goto out_err_no_arch_destroy_vm;
819 r = hardware_enable_all();
821 goto out_err_no_disable;
823 #ifdef CONFIG_HAVE_KVM_IRQFD
824 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
827 r = kvm_init_mmu_notifier(kvm);
829 goto out_err_no_mmu_notifier;
831 r = kvm_arch_post_init_vm(kvm);
835 mutex_lock(&kvm_lock);
836 list_add(&kvm->vm_list, &vm_list);
837 mutex_unlock(&kvm_lock);
839 preempt_notifier_inc();
844 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
845 if (kvm->mmu_notifier.ops)
846 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
848 out_err_no_mmu_notifier:
849 hardware_disable_all();
851 kvm_arch_destroy_vm(kvm);
852 out_err_no_arch_destroy_vm:
853 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
854 for (i = 0; i < KVM_NR_BUSES; i++)
855 kfree(kvm_get_bus(kvm, i));
856 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
857 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
858 cleanup_srcu_struct(&kvm->irq_srcu);
860 cleanup_srcu_struct(&kvm->srcu);
862 kvm_arch_free_vm(kvm);
867 static void kvm_destroy_devices(struct kvm *kvm)
869 struct kvm_device *dev, *tmp;
872 * We do not need to take the kvm->lock here, because nobody else
873 * has a reference to the struct kvm at this point and therefore
874 * cannot access the devices list anyhow.
876 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
877 list_del(&dev->vm_node);
878 dev->ops->destroy(dev);
882 static void kvm_destroy_vm(struct kvm *kvm)
885 struct mm_struct *mm = kvm->mm;
887 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
888 kvm_destroy_vm_debugfs(kvm);
889 kvm_arch_sync_events(kvm);
890 mutex_lock(&kvm_lock);
891 list_del(&kvm->vm_list);
892 mutex_unlock(&kvm_lock);
893 kvm_arch_pre_destroy_vm(kvm);
895 kvm_free_irq_routing(kvm);
896 for (i = 0; i < KVM_NR_BUSES; i++) {
897 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
900 kvm_io_bus_destroy(bus);
901 kvm->buses[i] = NULL;
903 kvm_coalesced_mmio_free(kvm);
904 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
905 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
907 kvm_arch_flush_shadow_all(kvm);
909 kvm_arch_destroy_vm(kvm);
910 kvm_destroy_devices(kvm);
911 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
912 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
913 cleanup_srcu_struct(&kvm->irq_srcu);
914 cleanup_srcu_struct(&kvm->srcu);
915 kvm_arch_free_vm(kvm);
916 preempt_notifier_dec();
917 hardware_disable_all();
921 void kvm_get_kvm(struct kvm *kvm)
923 refcount_inc(&kvm->users_count);
925 EXPORT_SYMBOL_GPL(kvm_get_kvm);
927 void kvm_put_kvm(struct kvm *kvm)
929 if (refcount_dec_and_test(&kvm->users_count))
932 EXPORT_SYMBOL_GPL(kvm_put_kvm);
935 * Used to put a reference that was taken on behalf of an object associated
936 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
937 * of the new file descriptor fails and the reference cannot be transferred to
938 * its final owner. In such cases, the caller is still actively using @kvm and
939 * will fail miserably if the refcount unexpectedly hits zero.
941 void kvm_put_kvm_no_destroy(struct kvm *kvm)
943 WARN_ON(refcount_dec_and_test(&kvm->users_count));
945 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
947 static int kvm_vm_release(struct inode *inode, struct file *filp)
949 struct kvm *kvm = filp->private_data;
951 kvm_irqfd_release(kvm);
958 * Allocation size is twice as large as the actual dirty bitmap size.
959 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
961 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
963 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
965 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
966 if (!memslot->dirty_bitmap)
973 * Delete a memslot by decrementing the number of used slots and shifting all
974 * other entries in the array forward one spot.
976 static inline void kvm_memslot_delete(struct kvm_memslots *slots,
977 struct kvm_memory_slot *memslot)
979 struct kvm_memory_slot *mslots = slots->memslots;
982 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
987 if (atomic_read(&slots->lru_slot) >= slots->used_slots)
988 atomic_set(&slots->lru_slot, 0);
990 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
991 mslots[i] = mslots[i + 1];
992 slots->id_to_index[mslots[i].id] = i;
994 mslots[i] = *memslot;
995 slots->id_to_index[memslot->id] = -1;
999 * "Insert" a new memslot by incrementing the number of used slots. Returns
1000 * the new slot's initial index into the memslots array.
1002 static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
1004 return slots->used_slots++;
1008 * Move a changed memslot backwards in the array by shifting existing slots
1009 * with a higher GFN toward the front of the array. Note, the changed memslot
1010 * itself is not preserved in the array, i.e. not swapped at this time, only
1011 * its new index into the array is tracked. Returns the changed memslot's
1012 * current index into the memslots array.
1014 static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
1015 struct kvm_memory_slot *memslot)
1017 struct kvm_memory_slot *mslots = slots->memslots;
1020 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
1021 WARN_ON_ONCE(!slots->used_slots))
1025 * Move the target memslot backward in the array by shifting existing
1026 * memslots with a higher GFN (than the target memslot) towards the
1027 * front of the array.
1029 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
1030 if (memslot->base_gfn > mslots[i + 1].base_gfn)
1033 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
1035 /* Shift the next memslot forward one and update its index. */
1036 mslots[i] = mslots[i + 1];
1037 slots->id_to_index[mslots[i].id] = i;
1043 * Move a changed memslot forwards in the array by shifting existing slots with
1044 * a lower GFN toward the back of the array. Note, the changed memslot itself
1045 * is not preserved in the array, i.e. not swapped at this time, only its new
1046 * index into the array is tracked. Returns the changed memslot's final index
1047 * into the memslots array.
1049 static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
1050 struct kvm_memory_slot *memslot,
1053 struct kvm_memory_slot *mslots = slots->memslots;
1056 for (i = start; i > 0; i--) {
1057 if (memslot->base_gfn < mslots[i - 1].base_gfn)
1060 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
1062 /* Shift the next memslot back one and update its index. */
1063 mslots[i] = mslots[i - 1];
1064 slots->id_to_index[mslots[i].id] = i;
1070 * Re-sort memslots based on their GFN to account for an added, deleted, or
1071 * moved memslot. Sorting memslots by GFN allows using a binary search during
1074 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
1075 * at memslots[0] has the highest GFN.
1077 * The sorting algorithm takes advantage of having initially sorted memslots
1078 * and knowing the position of the changed memslot. Sorting is also optimized
1079 * by not swapping the updated memslot and instead only shifting other memslots
1080 * and tracking the new index for the update memslot. Only once its final
1081 * index is known is the updated memslot copied into its position in the array.
1083 * - When deleting a memslot, the deleted memslot simply needs to be moved to
1084 * the end of the array.
1086 * - When creating a memslot, the algorithm "inserts" the new memslot at the
1087 * end of the array and then it forward to its correct location.
1089 * - When moving a memslot, the algorithm first moves the updated memslot
1090 * backward to handle the scenario where the memslot's GFN was changed to a
1091 * lower value. update_memslots() then falls through and runs the same flow
1092 * as creating a memslot to move the memslot forward to handle the scenario
1093 * where its GFN was changed to a higher value.
1095 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1096 * historical reasons. Originally, invalid memslots where denoted by having
1097 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1098 * to the end of the array. The current algorithm uses dedicated logic to
1099 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1101 * The other historical motiviation for highest->lowest was to improve the
1102 * performance of memslot lookup. KVM originally used a linear search starting
1103 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1104 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1105 * single memslot above the 4gb boundary. As the largest memslot is also the
1106 * most likely to be referenced, sorting it to the front of the array was
1107 * advantageous. The current binary search starts from the middle of the array
1108 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1110 static void update_memslots(struct kvm_memslots *slots,
1111 struct kvm_memory_slot *memslot,
1112 enum kvm_mr_change change)
1116 if (change == KVM_MR_DELETE) {
1117 kvm_memslot_delete(slots, memslot);
1119 if (change == KVM_MR_CREATE)
1120 i = kvm_memslot_insert_back(slots);
1122 i = kvm_memslot_move_backward(slots, memslot);
1123 i = kvm_memslot_move_forward(slots, memslot, i);
1126 * Copy the memslot to its new position in memslots and update
1127 * its index accordingly.
1129 slots->memslots[i] = *memslot;
1130 slots->id_to_index[memslot->id] = i;
1134 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1136 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1138 #ifdef __KVM_HAVE_READONLY_MEM
1139 valid_flags |= KVM_MEM_READONLY;
1142 if (mem->flags & ~valid_flags)
1148 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
1149 int as_id, struct kvm_memslots *slots)
1151 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
1152 u64 gen = old_memslots->generation;
1154 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1155 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1157 rcu_assign_pointer(kvm->memslots[as_id], slots);
1158 synchronize_srcu_expedited(&kvm->srcu);
1161 * Increment the new memslot generation a second time, dropping the
1162 * update in-progress flag and incrementing the generation based on
1163 * the number of address spaces. This provides a unique and easily
1164 * identifiable generation number while the memslots are in flux.
1166 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1169 * Generations must be unique even across address spaces. We do not need
1170 * a global counter for that, instead the generation space is evenly split
1171 * across address spaces. For example, with two address spaces, address
1172 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1173 * use generations 1, 3, 5, ...
1175 gen += KVM_ADDRESS_SPACE_NUM;
1177 kvm_arch_memslots_updated(kvm, gen);
1179 slots->generation = gen;
1181 return old_memslots;
1185 * Note, at a minimum, the current number of used slots must be allocated, even
1186 * when deleting a memslot, as we need a complete duplicate of the memslots for
1187 * use when invalidating a memslot prior to deleting/moving the memslot.
1189 static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1190 enum kvm_mr_change change)
1192 struct kvm_memslots *slots;
1193 size_t old_size, new_size;
1195 old_size = sizeof(struct kvm_memslots) +
1196 (sizeof(struct kvm_memory_slot) * old->used_slots);
1198 if (change == KVM_MR_CREATE)
1199 new_size = old_size + sizeof(struct kvm_memory_slot);
1201 new_size = old_size;
1203 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1205 memcpy(slots, old, old_size);
1210 static int kvm_set_memslot(struct kvm *kvm,
1211 const struct kvm_userspace_memory_region *mem,
1212 struct kvm_memory_slot *old,
1213 struct kvm_memory_slot *new, int as_id,
1214 enum kvm_mr_change change)
1216 struct kvm_memory_slot *slot;
1217 struct kvm_memslots *slots;
1220 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
1224 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1226 * Note, the INVALID flag needs to be in the appropriate entry
1227 * in the freshly allocated memslots, not in @old or @new.
1229 slot = id_to_memslot(slots, old->id);
1230 slot->flags |= KVM_MEMSLOT_INVALID;
1233 * We can re-use the old memslots, the only difference from the
1234 * newly installed memslots is the invalid flag, which will get
1235 * dropped by update_memslots anyway. We'll also revert to the
1236 * old memslots if preparing the new memory region fails.
1238 slots = install_new_memslots(kvm, as_id, slots);
1240 /* From this point no new shadow pages pointing to a deleted,
1241 * or moved, memslot will be created.
1243 * validation of sp->gfn happens in:
1244 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1245 * - kvm_is_visible_gfn (mmu_check_root)
1247 kvm_arch_flush_shadow_memslot(kvm, slot);
1250 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1254 update_memslots(slots, new, change);
1255 slots = install_new_memslots(kvm, as_id, slots);
1257 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1263 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1264 slots = install_new_memslots(kvm, as_id, slots);
1269 static int kvm_delete_memslot(struct kvm *kvm,
1270 const struct kvm_userspace_memory_region *mem,
1271 struct kvm_memory_slot *old, int as_id)
1273 struct kvm_memory_slot new;
1279 memset(&new, 0, sizeof(new));
1282 * This is only for debugging purpose; it should never be referenced
1283 * for a removed memslot.
1287 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1291 kvm_free_memslot(kvm, old);
1296 * Allocate some memory and give it an address in the guest physical address
1299 * Discontiguous memory is allowed, mostly for framebuffers.
1301 * Must be called holding kvm->slots_lock for write.
1303 int __kvm_set_memory_region(struct kvm *kvm,
1304 const struct kvm_userspace_memory_region *mem)
1306 struct kvm_memory_slot old, new;
1307 struct kvm_memory_slot *tmp;
1308 enum kvm_mr_change change;
1312 r = check_memory_region_flags(mem);
1316 as_id = mem->slot >> 16;
1317 id = (u16)mem->slot;
1319 /* General sanity checks */
1320 if (mem->memory_size & (PAGE_SIZE - 1))
1322 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1324 /* We can read the guest memory with __xxx_user() later on. */
1325 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1326 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1327 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1330 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1332 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1336 * Make a full copy of the old memslot, the pointer will become stale
1337 * when the memslots are re-sorted by update_memslots(), and the old
1338 * memslot needs to be referenced after calling update_memslots(), e.g.
1339 * to free its resources and for arch specific behavior.
1341 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1346 memset(&old, 0, sizeof(old));
1350 if (!mem->memory_size)
1351 return kvm_delete_memslot(kvm, mem, &old, as_id);
1355 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1356 new.npages = mem->memory_size >> PAGE_SHIFT;
1357 new.flags = mem->flags;
1358 new.userspace_addr = mem->userspace_addr;
1360 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1364 change = KVM_MR_CREATE;
1365 new.dirty_bitmap = NULL;
1366 memset(&new.arch, 0, sizeof(new.arch));
1367 } else { /* Modify an existing slot. */
1368 if ((new.userspace_addr != old.userspace_addr) ||
1369 (new.npages != old.npages) ||
1370 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1373 if (new.base_gfn != old.base_gfn)
1374 change = KVM_MR_MOVE;
1375 else if (new.flags != old.flags)
1376 change = KVM_MR_FLAGS_ONLY;
1377 else /* Nothing to change. */
1380 /* Copy dirty_bitmap and arch from the current memslot. */
1381 new.dirty_bitmap = old.dirty_bitmap;
1382 memcpy(&new.arch, &old.arch, sizeof(new.arch));
1385 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1386 /* Check for overlaps */
1387 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1390 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1391 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
1396 /* Allocate/free page dirty bitmap as needed */
1397 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1398 new.dirty_bitmap = NULL;
1399 else if (!new.dirty_bitmap && !kvm->dirty_ring_size) {
1400 r = kvm_alloc_dirty_bitmap(&new);
1404 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1405 bitmap_set(new.dirty_bitmap, 0, new.npages);
1408 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1412 if (old.dirty_bitmap && !new.dirty_bitmap)
1413 kvm_destroy_dirty_bitmap(&old);
1417 if (new.dirty_bitmap && !old.dirty_bitmap)
1418 kvm_destroy_dirty_bitmap(&new);
1421 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1423 int kvm_set_memory_region(struct kvm *kvm,
1424 const struct kvm_userspace_memory_region *mem)
1428 mutex_lock(&kvm->slots_lock);
1429 r = __kvm_set_memory_region(kvm, mem);
1430 mutex_unlock(&kvm->slots_lock);
1433 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1435 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1436 struct kvm_userspace_memory_region *mem)
1438 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1441 return kvm_set_memory_region(kvm, mem);
1444 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1446 * kvm_get_dirty_log - get a snapshot of dirty pages
1447 * @kvm: pointer to kvm instance
1448 * @log: slot id and address to which we copy the log
1449 * @is_dirty: set to '1' if any dirty pages were found
1450 * @memslot: set to the associated memslot, always valid on success
1452 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1453 int *is_dirty, struct kvm_memory_slot **memslot)
1455 struct kvm_memslots *slots;
1458 unsigned long any = 0;
1460 /* Dirty ring tracking is exclusive to dirty log tracking */
1461 if (kvm->dirty_ring_size)
1467 as_id = log->slot >> 16;
1468 id = (u16)log->slot;
1469 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1472 slots = __kvm_memslots(kvm, as_id);
1473 *memslot = id_to_memslot(slots, id);
1474 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1477 kvm_arch_sync_dirty_log(kvm, *memslot);
1479 n = kvm_dirty_bitmap_bytes(*memslot);
1481 for (i = 0; !any && i < n/sizeof(long); ++i)
1482 any = (*memslot)->dirty_bitmap[i];
1484 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1491 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1493 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1495 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1496 * and reenable dirty page tracking for the corresponding pages.
1497 * @kvm: pointer to kvm instance
1498 * @log: slot id and address to which we copy the log
1500 * We need to keep it in mind that VCPU threads can write to the bitmap
1501 * concurrently. So, to avoid losing track of dirty pages we keep the
1504 * 1. Take a snapshot of the bit and clear it if needed.
1505 * 2. Write protect the corresponding page.
1506 * 3. Copy the snapshot to the userspace.
1507 * 4. Upon return caller flushes TLB's if needed.
1509 * Between 2 and 4, the guest may write to the page using the remaining TLB
1510 * entry. This is not a problem because the page is reported dirty using
1511 * the snapshot taken before and step 4 ensures that writes done after
1512 * exiting to userspace will be logged for the next call.
1515 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
1517 struct kvm_memslots *slots;
1518 struct kvm_memory_slot *memslot;
1521 unsigned long *dirty_bitmap;
1522 unsigned long *dirty_bitmap_buffer;
1525 /* Dirty ring tracking is exclusive to dirty log tracking */
1526 if (kvm->dirty_ring_size)
1529 as_id = log->slot >> 16;
1530 id = (u16)log->slot;
1531 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1534 slots = __kvm_memslots(kvm, as_id);
1535 memslot = id_to_memslot(slots, id);
1536 if (!memslot || !memslot->dirty_bitmap)
1539 dirty_bitmap = memslot->dirty_bitmap;
1541 kvm_arch_sync_dirty_log(kvm, memslot);
1543 n = kvm_dirty_bitmap_bytes(memslot);
1545 if (kvm->manual_dirty_log_protect) {
1547 * Unlike kvm_get_dirty_log, we always return false in *flush,
1548 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1549 * is some code duplication between this function and
1550 * kvm_get_dirty_log, but hopefully all architecture
1551 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1552 * can be eliminated.
1554 dirty_bitmap_buffer = dirty_bitmap;
1556 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1557 memset(dirty_bitmap_buffer, 0, n);
1560 for (i = 0; i < n / sizeof(long); i++) {
1564 if (!dirty_bitmap[i])
1568 mask = xchg(&dirty_bitmap[i], 0);
1569 dirty_bitmap_buffer[i] = mask;
1571 offset = i * BITS_PER_LONG;
1572 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1575 KVM_MMU_UNLOCK(kvm);
1579 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1581 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1588 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1589 * @kvm: kvm instance
1590 * @log: slot id and address to which we copy the log
1592 * Steps 1-4 below provide general overview of dirty page logging. See
1593 * kvm_get_dirty_log_protect() function description for additional details.
1595 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1596 * always flush the TLB (step 4) even if previous step failed and the dirty
1597 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1598 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1599 * writes will be marked dirty for next log read.
1601 * 1. Take a snapshot of the bit and clear it if needed.
1602 * 2. Write protect the corresponding page.
1603 * 3. Copy the snapshot to the userspace.
1604 * 4. Flush TLB's if needed.
1606 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1607 struct kvm_dirty_log *log)
1611 mutex_lock(&kvm->slots_lock);
1613 r = kvm_get_dirty_log_protect(kvm, log);
1615 mutex_unlock(&kvm->slots_lock);
1620 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1621 * and reenable dirty page tracking for the corresponding pages.
1622 * @kvm: pointer to kvm instance
1623 * @log: slot id and address from which to fetch the bitmap of dirty pages
1625 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1626 struct kvm_clear_dirty_log *log)
1628 struct kvm_memslots *slots;
1629 struct kvm_memory_slot *memslot;
1633 unsigned long *dirty_bitmap;
1634 unsigned long *dirty_bitmap_buffer;
1637 /* Dirty ring tracking is exclusive to dirty log tracking */
1638 if (kvm->dirty_ring_size)
1641 as_id = log->slot >> 16;
1642 id = (u16)log->slot;
1643 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1646 if (log->first_page & 63)
1649 slots = __kvm_memslots(kvm, as_id);
1650 memslot = id_to_memslot(slots, id);
1651 if (!memslot || !memslot->dirty_bitmap)
1654 dirty_bitmap = memslot->dirty_bitmap;
1656 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
1658 if (log->first_page > memslot->npages ||
1659 log->num_pages > memslot->npages - log->first_page ||
1660 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1663 kvm_arch_sync_dirty_log(kvm, memslot);
1666 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1667 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1671 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1672 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
1673 i++, offset += BITS_PER_LONG) {
1674 unsigned long mask = *dirty_bitmap_buffer++;
1675 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1679 mask &= atomic_long_fetch_andnot(mask, p);
1682 * mask contains the bits that really have been cleared. This
1683 * never includes any bits beyond the length of the memslot (if
1684 * the length is not aligned to 64 pages), therefore it is not
1685 * a problem if userspace sets them in log->dirty_bitmap.
1689 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1693 KVM_MMU_UNLOCK(kvm);
1696 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1701 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
1702 struct kvm_clear_dirty_log *log)
1706 mutex_lock(&kvm->slots_lock);
1708 r = kvm_clear_dirty_log_protect(kvm, log);
1710 mutex_unlock(&kvm->slots_lock);
1713 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1715 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1717 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1719 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1721 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1723 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1725 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_memslot);
1727 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1729 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1731 return kvm_is_visible_memslot(memslot);
1733 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1735 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1737 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1739 return kvm_is_visible_memslot(memslot);
1741 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
1743 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
1745 struct vm_area_struct *vma;
1746 unsigned long addr, size;
1750 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
1751 if (kvm_is_error_hva(addr))
1754 mmap_read_lock(current->mm);
1755 vma = find_vma(current->mm, addr);
1759 size = vma_kernel_pagesize(vma);
1762 mmap_read_unlock(current->mm);
1767 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1769 return slot->flags & KVM_MEM_READONLY;
1772 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1773 gfn_t *nr_pages, bool write)
1775 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1776 return KVM_HVA_ERR_BAD;
1778 if (memslot_is_readonly(slot) && write)
1779 return KVM_HVA_ERR_RO_BAD;
1782 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1784 return __gfn_to_hva_memslot(slot, gfn);
1787 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1790 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1793 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1796 return gfn_to_hva_many(slot, gfn, NULL);
1798 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1800 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1802 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1804 EXPORT_SYMBOL_GPL(gfn_to_hva);
1806 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1808 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1810 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1813 * Return the hva of a @gfn and the R/W attribute if possible.
1815 * @slot: the kvm_memory_slot which contains @gfn
1816 * @gfn: the gfn to be translated
1817 * @writable: used to return the read/write attribute of the @slot if the hva
1818 * is valid and @writable is not NULL
1820 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1821 gfn_t gfn, bool *writable)
1823 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1825 if (!kvm_is_error_hva(hva) && writable)
1826 *writable = !memslot_is_readonly(slot);
1831 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1833 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1835 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1838 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1840 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1842 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1845 static inline int check_user_page_hwpoison(unsigned long addr)
1847 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1849 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1850 return rc == -EHWPOISON;
1854 * The fast path to get the writable pfn which will be stored in @pfn,
1855 * true indicates success, otherwise false is returned. It's also the
1856 * only part that runs if we can in atomic context.
1858 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1859 bool *writable, kvm_pfn_t *pfn)
1861 struct page *page[1];
1864 * Fast pin a writable pfn only if it is a write fault request
1865 * or the caller allows to map a writable pfn for a read fault
1868 if (!(write_fault || writable))
1871 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
1872 *pfn = page_to_pfn(page[0]);
1883 * The slow path to get the pfn of the specified host virtual address,
1884 * 1 indicates success, -errno is returned if error is detected.
1886 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1887 bool *writable, kvm_pfn_t *pfn)
1889 unsigned int flags = FOLL_HWPOISON;
1896 *writable = write_fault;
1899 flags |= FOLL_WRITE;
1901 flags |= FOLL_NOWAIT;
1903 npages = get_user_pages_unlocked(addr, 1, &page, flags);
1907 /* map read fault as writable if possible */
1908 if (unlikely(!write_fault) && writable) {
1911 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
1917 *pfn = page_to_pfn(page);
1921 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1923 if (unlikely(!(vma->vm_flags & VM_READ)))
1926 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1932 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1933 unsigned long addr, bool *async,
1934 bool write_fault, bool *writable,
1942 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
1945 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1946 * not call the fault handler, so do it here.
1948 bool unlocked = false;
1949 r = fixup_user_fault(current->mm, addr,
1950 (write_fault ? FAULT_FLAG_WRITE : 0),
1957 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
1962 if (write_fault && !pte_write(*ptep)) {
1963 pfn = KVM_PFN_ERR_RO_FAULT;
1968 *writable = pte_write(*ptep);
1969 pfn = pte_pfn(*ptep);
1972 * Get a reference here because callers of *hva_to_pfn* and
1973 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1974 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1975 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1976 * simply do nothing for reserved pfns.
1978 * Whoever called remap_pfn_range is also going to call e.g.
1979 * unmap_mapping_range before the underlying pages are freed,
1980 * causing a call to our MMU notifier.
1985 pte_unmap_unlock(ptep, ptl);
1991 * Pin guest page in memory and return its pfn.
1992 * @addr: host virtual address which maps memory to the guest
1993 * @atomic: whether this function can sleep
1994 * @async: whether this function need to wait IO complete if the
1995 * host page is not in the memory
1996 * @write_fault: whether we should get a writable host page
1997 * @writable: whether it allows to map a writable host page for !@write_fault
1999 * The function will map a writable host page for these two cases:
2000 * 1): @write_fault = true
2001 * 2): @write_fault = false && @writable, @writable will tell the caller
2002 * whether the mapping is writable.
2004 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2005 bool write_fault, bool *writable)
2007 struct vm_area_struct *vma;
2011 /* we can do it either atomically or asynchronously, not both */
2012 BUG_ON(atomic && async);
2014 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2018 return KVM_PFN_ERR_FAULT;
2020 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2024 mmap_read_lock(current->mm);
2025 if (npages == -EHWPOISON ||
2026 (!async && check_user_page_hwpoison(addr))) {
2027 pfn = KVM_PFN_ERR_HWPOISON;
2032 vma = find_vma_intersection(current->mm, addr, addr + 1);
2035 pfn = KVM_PFN_ERR_FAULT;
2036 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2037 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
2041 pfn = KVM_PFN_ERR_FAULT;
2043 if (async && vma_is_valid(vma, write_fault))
2045 pfn = KVM_PFN_ERR_FAULT;
2048 mmap_read_unlock(current->mm);
2052 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
2053 bool atomic, bool *async, bool write_fault,
2054 bool *writable, hva_t *hva)
2056 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2061 if (addr == KVM_HVA_ERR_RO_BAD) {
2064 return KVM_PFN_ERR_RO_FAULT;
2067 if (kvm_is_error_hva(addr)) {
2070 return KVM_PFN_NOSLOT;
2073 /* Do not map writable pfn in the readonly memslot. */
2074 if (writable && memslot_is_readonly(slot)) {
2079 return hva_to_pfn(addr, atomic, async, write_fault,
2082 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2084 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2087 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2088 write_fault, writable, NULL);
2090 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2092 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
2094 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2096 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2098 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
2100 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2102 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2104 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2106 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2108 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2110 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2112 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2114 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2116 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2118 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2120 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2122 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2123 struct page **pages, int nr_pages)
2128 addr = gfn_to_hva_many(slot, gfn, &entry);
2129 if (kvm_is_error_hva(addr))
2132 if (entry < nr_pages)
2135 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2137 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2139 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2141 if (is_error_noslot_pfn(pfn))
2142 return KVM_ERR_PTR_BAD_PAGE;
2144 if (kvm_is_reserved_pfn(pfn)) {
2146 return KVM_ERR_PTR_BAD_PAGE;
2149 return pfn_to_page(pfn);
2152 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2156 pfn = gfn_to_pfn(kvm, gfn);
2158 return kvm_pfn_to_page(pfn);
2160 EXPORT_SYMBOL_GPL(gfn_to_page);
2162 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2168 cache->pfn = cache->gfn = 0;
2171 kvm_release_pfn_dirty(pfn);
2173 kvm_release_pfn_clean(pfn);
2176 static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2177 struct gfn_to_pfn_cache *cache, u64 gen)
2179 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2181 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2183 cache->dirty = false;
2184 cache->generation = gen;
2187 static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
2188 struct kvm_host_map *map,
2189 struct gfn_to_pfn_cache *cache,
2194 struct page *page = KVM_UNMAPPED_PAGE;
2195 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
2196 u64 gen = slots->generation;
2202 if (!cache->pfn || cache->gfn != gfn ||
2203 cache->generation != gen) {
2206 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2212 pfn = gfn_to_pfn_memslot(slot, gfn);
2214 if (is_error_noslot_pfn(pfn))
2217 if (pfn_valid(pfn)) {
2218 page = pfn_to_page(pfn);
2220 hva = kmap_atomic(page);
2223 #ifdef CONFIG_HAS_IOMEM
2224 } else if (!atomic) {
2225 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2242 int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2243 struct gfn_to_pfn_cache *cache, bool atomic)
2245 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2248 EXPORT_SYMBOL_GPL(kvm_map_gfn);
2250 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2252 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2255 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2257 static void __kvm_unmap_gfn(struct kvm *kvm,
2258 struct kvm_memory_slot *memslot,
2259 struct kvm_host_map *map,
2260 struct gfn_to_pfn_cache *cache,
2261 bool dirty, bool atomic)
2269 if (map->page != KVM_UNMAPPED_PAGE) {
2271 kunmap_atomic(map->hva);
2275 #ifdef CONFIG_HAS_IOMEM
2279 WARN_ONCE(1, "Unexpected unmapping in atomic context");
2283 mark_page_dirty_in_slot(kvm, memslot, map->gfn);
2286 cache->dirty |= dirty;
2288 kvm_release_pfn(map->pfn, dirty, NULL);
2294 int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2295 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
2297 __kvm_unmap_gfn(vcpu->kvm, gfn_to_memslot(vcpu->kvm, map->gfn), map,
2298 cache, dirty, atomic);
2301 EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2303 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2305 __kvm_unmap_gfn(vcpu->kvm, kvm_vcpu_gfn_to_memslot(vcpu, map->gfn),
2306 map, NULL, dirty, false);
2308 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2310 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2314 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2316 return kvm_pfn_to_page(pfn);
2318 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2320 void kvm_release_page_clean(struct page *page)
2322 WARN_ON(is_error_page(page));
2324 kvm_release_pfn_clean(page_to_pfn(page));
2326 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2328 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2330 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2331 put_page(pfn_to_page(pfn));
2333 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2335 void kvm_release_page_dirty(struct page *page)
2337 WARN_ON(is_error_page(page));
2339 kvm_release_pfn_dirty(page_to_pfn(page));
2341 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2343 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2345 kvm_set_pfn_dirty(pfn);
2346 kvm_release_pfn_clean(pfn);
2348 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2350 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2352 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2353 SetPageDirty(pfn_to_page(pfn));
2355 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2357 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2359 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2360 mark_page_accessed(pfn_to_page(pfn));
2362 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2364 void kvm_get_pfn(kvm_pfn_t pfn)
2366 if (!kvm_is_reserved_pfn(pfn))
2367 get_page(pfn_to_page(pfn));
2369 EXPORT_SYMBOL_GPL(kvm_get_pfn);
2371 static int next_segment(unsigned long len, int offset)
2373 if (len > PAGE_SIZE - offset)
2374 return PAGE_SIZE - offset;
2379 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2380 void *data, int offset, int len)
2385 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2386 if (kvm_is_error_hva(addr))
2388 r = __copy_from_user(data, (void __user *)addr + offset, len);
2394 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2397 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2399 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2401 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2403 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2404 int offset, int len)
2406 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2408 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2410 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2412 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2414 gfn_t gfn = gpa >> PAGE_SHIFT;
2416 int offset = offset_in_page(gpa);
2419 while ((seg = next_segment(len, offset)) != 0) {
2420 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2430 EXPORT_SYMBOL_GPL(kvm_read_guest);
2432 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2434 gfn_t gfn = gpa >> PAGE_SHIFT;
2436 int offset = offset_in_page(gpa);
2439 while ((seg = next_segment(len, offset)) != 0) {
2440 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2450 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2452 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2453 void *data, int offset, unsigned long len)
2458 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2459 if (kvm_is_error_hva(addr))
2461 pagefault_disable();
2462 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2469 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2470 void *data, unsigned long len)
2472 gfn_t gfn = gpa >> PAGE_SHIFT;
2473 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2474 int offset = offset_in_page(gpa);
2476 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2478 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2480 static int __kvm_write_guest_page(struct kvm *kvm,
2481 struct kvm_memory_slot *memslot, gfn_t gfn,
2482 const void *data, int offset, int len)
2487 addr = gfn_to_hva_memslot(memslot, gfn);
2488 if (kvm_is_error_hva(addr))
2490 r = __copy_to_user((void __user *)addr + offset, data, len);
2493 mark_page_dirty_in_slot(kvm, memslot, gfn);
2497 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2498 const void *data, int offset, int len)
2500 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2502 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2504 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2506 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2507 const void *data, int offset, int len)
2509 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2511 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
2513 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2515 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2518 gfn_t gfn = gpa >> PAGE_SHIFT;
2520 int offset = offset_in_page(gpa);
2523 while ((seg = next_segment(len, offset)) != 0) {
2524 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2534 EXPORT_SYMBOL_GPL(kvm_write_guest);
2536 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2539 gfn_t gfn = gpa >> PAGE_SHIFT;
2541 int offset = offset_in_page(gpa);
2544 while ((seg = next_segment(len, offset)) != 0) {
2545 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2555 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2557 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2558 struct gfn_to_hva_cache *ghc,
2559 gpa_t gpa, unsigned long len)
2561 int offset = offset_in_page(gpa);
2562 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2563 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2564 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2565 gfn_t nr_pages_avail;
2567 /* Update ghc->generation before performing any error checks. */
2568 ghc->generation = slots->generation;
2570 if (start_gfn > end_gfn) {
2571 ghc->hva = KVM_HVA_ERR_BAD;
2576 * If the requested region crosses two memslots, we still
2577 * verify that the entire region is valid here.
2579 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
2580 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2581 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2583 if (kvm_is_error_hva(ghc->hva))
2587 /* Use the slow path for cross page reads and writes. */
2588 if (nr_pages_needed == 1)
2591 ghc->memslot = NULL;
2598 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2599 gpa_t gpa, unsigned long len)
2601 struct kvm_memslots *slots = kvm_memslots(kvm);
2602 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2604 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2606 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2607 void *data, unsigned int offset,
2610 struct kvm_memslots *slots = kvm_memslots(kvm);
2612 gpa_t gpa = ghc->gpa + offset;
2614 BUG_ON(len + offset > ghc->len);
2616 if (slots->generation != ghc->generation) {
2617 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2621 if (kvm_is_error_hva(ghc->hva))
2624 if (unlikely(!ghc->memslot))
2625 return kvm_write_guest(kvm, gpa, data, len);
2627 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2630 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
2634 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2636 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2637 void *data, unsigned long len)
2639 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2641 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2643 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2644 void *data, unsigned int offset,
2647 struct kvm_memslots *slots = kvm_memslots(kvm);
2649 gpa_t gpa = ghc->gpa + offset;
2651 BUG_ON(len + offset > ghc->len);
2653 if (slots->generation != ghc->generation) {
2654 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2658 if (kvm_is_error_hva(ghc->hva))
2661 if (unlikely(!ghc->memslot))
2662 return kvm_read_guest(kvm, gpa, data, len);
2664 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
2670 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
2672 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2673 void *data, unsigned long len)
2675 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
2677 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2679 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2681 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2682 gfn_t gfn = gpa >> PAGE_SHIFT;
2684 int offset = offset_in_page(gpa);
2687 while ((seg = next_segment(len, offset)) != 0) {
2688 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2697 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2699 void mark_page_dirty_in_slot(struct kvm *kvm,
2700 struct kvm_memory_slot *memslot,
2703 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
2704 unsigned long rel_gfn = gfn - memslot->base_gfn;
2705 u32 slot = (memslot->as_id << 16) | memslot->id;
2707 if (kvm->dirty_ring_size)
2708 kvm_dirty_ring_push(kvm_dirty_ring_get(kvm),
2711 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2714 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
2716 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2718 struct kvm_memory_slot *memslot;
2720 memslot = gfn_to_memslot(kvm, gfn);
2721 mark_page_dirty_in_slot(kvm, memslot, gfn);
2723 EXPORT_SYMBOL_GPL(mark_page_dirty);
2725 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2727 struct kvm_memory_slot *memslot;
2729 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2730 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
2732 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2734 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2736 if (!vcpu->sigset_active)
2740 * This does a lockless modification of ->real_blocked, which is fine
2741 * because, only current can change ->real_blocked and all readers of
2742 * ->real_blocked don't care as long ->real_blocked is always a subset
2745 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
2748 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2750 if (!vcpu->sigset_active)
2753 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
2754 sigemptyset(¤t->real_blocked);
2757 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2759 unsigned int old, val, grow, grow_start;
2761 old = val = vcpu->halt_poll_ns;
2762 grow_start = READ_ONCE(halt_poll_ns_grow_start);
2763 grow = READ_ONCE(halt_poll_ns_grow);
2768 if (val < grow_start)
2771 if (val > halt_poll_ns)
2774 vcpu->halt_poll_ns = val;
2776 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2779 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2781 unsigned int old, val, shrink;
2783 old = val = vcpu->halt_poll_ns;
2784 shrink = READ_ONCE(halt_poll_ns_shrink);
2790 vcpu->halt_poll_ns = val;
2791 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2794 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2797 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2799 if (kvm_arch_vcpu_runnable(vcpu)) {
2800 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2803 if (kvm_cpu_has_pending_timer(vcpu))
2805 if (signal_pending(current))
2810 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2815 update_halt_poll_stats(struct kvm_vcpu *vcpu, u64 poll_ns, bool waited)
2818 vcpu->stat.halt_poll_fail_ns += poll_ns;
2820 vcpu->stat.halt_poll_success_ns += poll_ns;
2824 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2826 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2828 ktime_t start, cur, poll_end;
2829 bool waited = false;
2832 kvm_arch_vcpu_blocking(vcpu);
2834 start = cur = poll_end = ktime_get();
2835 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
2836 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2838 ++vcpu->stat.halt_attempted_poll;
2841 * This sets KVM_REQ_UNHALT if an interrupt
2844 if (kvm_vcpu_check_block(vcpu) < 0) {
2845 ++vcpu->stat.halt_successful_poll;
2846 if (!vcpu_valid_wakeup(vcpu))
2847 ++vcpu->stat.halt_poll_invalid;
2850 poll_end = cur = ktime_get();
2851 } while (single_task_running() && ktime_before(cur, stop));
2854 prepare_to_rcuwait(&vcpu->wait);
2856 set_current_state(TASK_INTERRUPTIBLE);
2858 if (kvm_vcpu_check_block(vcpu) < 0)
2864 finish_rcuwait(&vcpu->wait);
2867 kvm_arch_vcpu_unblocking(vcpu);
2868 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2870 update_halt_poll_stats(
2871 vcpu, ktime_to_ns(ktime_sub(poll_end, start)), waited);
2873 if (!kvm_arch_no_poll(vcpu)) {
2874 if (!vcpu_valid_wakeup(vcpu)) {
2875 shrink_halt_poll_ns(vcpu);
2876 } else if (vcpu->kvm->max_halt_poll_ns) {
2877 if (block_ns <= vcpu->halt_poll_ns)
2879 /* we had a long block, shrink polling */
2880 else if (vcpu->halt_poll_ns &&
2881 block_ns > vcpu->kvm->max_halt_poll_ns)
2882 shrink_halt_poll_ns(vcpu);
2883 /* we had a short halt and our poll time is too small */
2884 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
2885 block_ns < vcpu->kvm->max_halt_poll_ns)
2886 grow_halt_poll_ns(vcpu);
2888 vcpu->halt_poll_ns = 0;
2892 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2893 kvm_arch_vcpu_block_finish(vcpu);
2895 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2897 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2899 struct rcuwait *waitp;
2901 waitp = kvm_arch_vcpu_get_wait(vcpu);
2902 if (rcuwait_wake_up(waitp)) {
2903 WRITE_ONCE(vcpu->ready, true);
2904 ++vcpu->stat.halt_wakeup;
2910 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2914 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2916 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2919 int cpu = vcpu->cpu;
2921 if (kvm_vcpu_wake_up(vcpu))
2925 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2926 if (kvm_arch_vcpu_should_kick(vcpu))
2927 smp_send_reschedule(cpu);
2930 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2931 #endif /* !CONFIG_S390 */
2933 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2936 struct task_struct *task = NULL;
2940 pid = rcu_dereference(target->pid);
2942 task = get_pid_task(pid, PIDTYPE_PID);
2946 ret = yield_to(task, 1);
2947 put_task_struct(task);
2951 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2954 * Helper that checks whether a VCPU is eligible for directed yield.
2955 * Most eligible candidate to yield is decided by following heuristics:
2957 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2958 * (preempted lock holder), indicated by @in_spin_loop.
2959 * Set at the beginning and cleared at the end of interception/PLE handler.
2961 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2962 * chance last time (mostly it has become eligible now since we have probably
2963 * yielded to lockholder in last iteration. This is done by toggling
2964 * @dy_eligible each time a VCPU checked for eligibility.)
2966 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2967 * to preempted lock-holder could result in wrong VCPU selection and CPU
2968 * burning. Giving priority for a potential lock-holder increases lock
2971 * Since algorithm is based on heuristics, accessing another VCPU data without
2972 * locking does not harm. It may result in trying to yield to same VCPU, fail
2973 * and continue with next VCPU and so on.
2975 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2977 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2980 eligible = !vcpu->spin_loop.in_spin_loop ||
2981 vcpu->spin_loop.dy_eligible;
2983 if (vcpu->spin_loop.in_spin_loop)
2984 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2993 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2994 * a vcpu_load/vcpu_put pair. However, for most architectures
2995 * kvm_arch_vcpu_runnable does not require vcpu_load.
2997 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2999 return kvm_arch_vcpu_runnable(vcpu);
3002 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3004 if (kvm_arch_dy_runnable(vcpu))
3007 #ifdef CONFIG_KVM_ASYNC_PF
3008 if (!list_empty_careful(&vcpu->async_pf.done))
3015 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3017 struct kvm *kvm = me->kvm;
3018 struct kvm_vcpu *vcpu;
3019 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3025 kvm_vcpu_set_in_spin_loop(me, true);
3027 * We boost the priority of a VCPU that is runnable but not
3028 * currently running, because it got preempted by something
3029 * else and called schedule in __vcpu_run. Hopefully that
3030 * VCPU is holding the lock that we need and will release it.
3031 * We approximate round-robin by starting at the last boosted VCPU.
3033 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3034 kvm_for_each_vcpu(i, vcpu, kvm) {
3035 if (!pass && i <= last_boosted_vcpu) {
3036 i = last_boosted_vcpu;
3038 } else if (pass && i > last_boosted_vcpu)
3040 if (!READ_ONCE(vcpu->ready))
3044 if (rcuwait_active(&vcpu->wait) &&
3045 !vcpu_dy_runnable(vcpu))
3047 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3048 !kvm_arch_vcpu_in_kernel(vcpu))
3050 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3053 yielded = kvm_vcpu_yield_to(vcpu);
3055 kvm->last_boosted_vcpu = i;
3057 } else if (yielded < 0) {
3064 kvm_vcpu_set_in_spin_loop(me, false);
3066 /* Ensure vcpu is not eligible during next spinloop */
3067 kvm_vcpu_set_dy_eligible(me, false);
3069 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3071 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3073 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3074 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3075 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3076 kvm->dirty_ring_size / PAGE_SIZE);
3082 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3084 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3087 if (vmf->pgoff == 0)
3088 page = virt_to_page(vcpu->run);
3090 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3091 page = virt_to_page(vcpu->arch.pio_data);
3093 #ifdef CONFIG_KVM_MMIO
3094 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3095 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3097 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3098 page = kvm_dirty_ring_get_page(
3100 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3102 return kvm_arch_vcpu_fault(vcpu, vmf);
3108 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3109 .fault = kvm_vcpu_fault,
3112 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3114 struct kvm_vcpu *vcpu = file->private_data;
3115 unsigned long pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
3117 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3118 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3119 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3122 vma->vm_ops = &kvm_vcpu_vm_ops;
3126 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3128 struct kvm_vcpu *vcpu = filp->private_data;
3130 kvm_put_kvm(vcpu->kvm);
3134 static struct file_operations kvm_vcpu_fops = {
3135 .release = kvm_vcpu_release,
3136 .unlocked_ioctl = kvm_vcpu_ioctl,
3137 .mmap = kvm_vcpu_mmap,
3138 .llseek = noop_llseek,
3139 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3143 * Allocates an inode for the vcpu.
3145 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3147 char name[8 + 1 + ITOA_MAX_LEN + 1];
3149 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3150 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3153 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3155 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3156 struct dentry *debugfs_dentry;
3157 char dir_name[ITOA_MAX_LEN * 2];
3159 if (!debugfs_initialized())
3162 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3163 debugfs_dentry = debugfs_create_dir(dir_name,
3164 vcpu->kvm->debugfs_dentry);
3166 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3171 * Creates some virtual cpus. Good luck creating more than one.
3173 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3176 struct kvm_vcpu *vcpu;
3179 if (id >= KVM_MAX_VCPU_ID)
3182 mutex_lock(&kvm->lock);
3183 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3184 mutex_unlock(&kvm->lock);
3188 kvm->created_vcpus++;
3189 mutex_unlock(&kvm->lock);
3191 r = kvm_arch_vcpu_precreate(kvm, id);
3193 goto vcpu_decrement;
3195 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3198 goto vcpu_decrement;
3201 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3202 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3207 vcpu->run = page_address(page);
3209 kvm_vcpu_init(vcpu, kvm, id);
3211 r = kvm_arch_vcpu_create(vcpu);
3213 goto vcpu_free_run_page;
3215 if (kvm->dirty_ring_size) {
3216 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3217 id, kvm->dirty_ring_size);
3219 goto arch_vcpu_destroy;
3222 mutex_lock(&kvm->lock);
3223 if (kvm_get_vcpu_by_id(kvm, id)) {
3225 goto unlock_vcpu_destroy;
3228 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3229 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
3231 /* Now it's all set up, let userspace reach it */
3233 r = create_vcpu_fd(vcpu);
3235 kvm_put_kvm_no_destroy(kvm);
3236 goto unlock_vcpu_destroy;
3239 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
3242 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3243 * before kvm->online_vcpu's incremented value.
3246 atomic_inc(&kvm->online_vcpus);
3248 mutex_unlock(&kvm->lock);
3249 kvm_arch_vcpu_postcreate(vcpu);
3250 kvm_create_vcpu_debugfs(vcpu);
3253 unlock_vcpu_destroy:
3254 mutex_unlock(&kvm->lock);
3255 kvm_dirty_ring_free(&vcpu->dirty_ring);
3257 kvm_arch_vcpu_destroy(vcpu);
3259 free_page((unsigned long)vcpu->run);
3261 kmem_cache_free(kvm_vcpu_cache, vcpu);
3263 mutex_lock(&kvm->lock);
3264 kvm->created_vcpus--;
3265 mutex_unlock(&kvm->lock);
3269 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3272 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3273 vcpu->sigset_active = 1;
3274 vcpu->sigset = *sigset;
3276 vcpu->sigset_active = 0;
3280 static long kvm_vcpu_ioctl(struct file *filp,
3281 unsigned int ioctl, unsigned long arg)
3283 struct kvm_vcpu *vcpu = filp->private_data;
3284 void __user *argp = (void __user *)arg;
3286 struct kvm_fpu *fpu = NULL;
3287 struct kvm_sregs *kvm_sregs = NULL;
3289 if (vcpu->kvm->mm != current->mm)
3292 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3296 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3297 * execution; mutex_lock() would break them.
3299 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3300 if (r != -ENOIOCTLCMD)
3303 if (mutex_lock_killable(&vcpu->mutex))
3311 oldpid = rcu_access_pointer(vcpu->pid);
3312 if (unlikely(oldpid != task_pid(current))) {
3313 /* The thread running this VCPU changed. */
3316 r = kvm_arch_vcpu_run_pid_change(vcpu);
3320 newpid = get_task_pid(current, PIDTYPE_PID);
3321 rcu_assign_pointer(vcpu->pid, newpid);
3326 r = kvm_arch_vcpu_ioctl_run(vcpu);
3327 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3330 case KVM_GET_REGS: {
3331 struct kvm_regs *kvm_regs;
3334 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3337 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3341 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3348 case KVM_SET_REGS: {
3349 struct kvm_regs *kvm_regs;
3351 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3352 if (IS_ERR(kvm_regs)) {
3353 r = PTR_ERR(kvm_regs);
3356 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3360 case KVM_GET_SREGS: {
3361 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3362 GFP_KERNEL_ACCOUNT);
3366 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3370 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3375 case KVM_SET_SREGS: {
3376 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3377 if (IS_ERR(kvm_sregs)) {
3378 r = PTR_ERR(kvm_sregs);
3382 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3385 case KVM_GET_MP_STATE: {
3386 struct kvm_mp_state mp_state;
3388 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3392 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3397 case KVM_SET_MP_STATE: {
3398 struct kvm_mp_state mp_state;
3401 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3403 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3406 case KVM_TRANSLATE: {
3407 struct kvm_translation tr;
3410 if (copy_from_user(&tr, argp, sizeof(tr)))
3412 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3416 if (copy_to_user(argp, &tr, sizeof(tr)))
3421 case KVM_SET_GUEST_DEBUG: {
3422 struct kvm_guest_debug dbg;
3425 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3427 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3430 case KVM_SET_SIGNAL_MASK: {
3431 struct kvm_signal_mask __user *sigmask_arg = argp;
3432 struct kvm_signal_mask kvm_sigmask;
3433 sigset_t sigset, *p;
3438 if (copy_from_user(&kvm_sigmask, argp,
3439 sizeof(kvm_sigmask)))
3442 if (kvm_sigmask.len != sizeof(sigset))
3445 if (copy_from_user(&sigset, sigmask_arg->sigset,
3450 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3454 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
3458 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3462 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3468 fpu = memdup_user(argp, sizeof(*fpu));
3474 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3478 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3481 mutex_unlock(&vcpu->mutex);
3487 #ifdef CONFIG_KVM_COMPAT
3488 static long kvm_vcpu_compat_ioctl(struct file *filp,
3489 unsigned int ioctl, unsigned long arg)
3491 struct kvm_vcpu *vcpu = filp->private_data;
3492 void __user *argp = compat_ptr(arg);
3495 if (vcpu->kvm->mm != current->mm)
3499 case KVM_SET_SIGNAL_MASK: {
3500 struct kvm_signal_mask __user *sigmask_arg = argp;
3501 struct kvm_signal_mask kvm_sigmask;
3506 if (copy_from_user(&kvm_sigmask, argp,
3507 sizeof(kvm_sigmask)))
3510 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3513 if (get_compat_sigset(&sigset,
3514 (compat_sigset_t __user *)sigmask_arg->sigset))
3516 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3518 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3522 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3530 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3532 struct kvm_device *dev = filp->private_data;
3535 return dev->ops->mmap(dev, vma);
3540 static int kvm_device_ioctl_attr(struct kvm_device *dev,
3541 int (*accessor)(struct kvm_device *dev,
3542 struct kvm_device_attr *attr),
3545 struct kvm_device_attr attr;
3550 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3553 return accessor(dev, &attr);
3556 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3559 struct kvm_device *dev = filp->private_data;
3561 if (dev->kvm->mm != current->mm)
3565 case KVM_SET_DEVICE_ATTR:
3566 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3567 case KVM_GET_DEVICE_ATTR:
3568 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3569 case KVM_HAS_DEVICE_ATTR:
3570 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3572 if (dev->ops->ioctl)
3573 return dev->ops->ioctl(dev, ioctl, arg);
3579 static int kvm_device_release(struct inode *inode, struct file *filp)
3581 struct kvm_device *dev = filp->private_data;
3582 struct kvm *kvm = dev->kvm;
3584 if (dev->ops->release) {
3585 mutex_lock(&kvm->lock);
3586 list_del(&dev->vm_node);
3587 dev->ops->release(dev);
3588 mutex_unlock(&kvm->lock);
3595 static const struct file_operations kvm_device_fops = {
3596 .unlocked_ioctl = kvm_device_ioctl,
3597 .release = kvm_device_release,
3598 KVM_COMPAT(kvm_device_ioctl),
3599 .mmap = kvm_device_mmap,
3602 struct kvm_device *kvm_device_from_filp(struct file *filp)
3604 if (filp->f_op != &kvm_device_fops)
3607 return filp->private_data;
3610 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
3611 #ifdef CONFIG_KVM_MPIC
3612 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3613 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3617 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
3619 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3622 if (kvm_device_ops_table[type] != NULL)
3625 kvm_device_ops_table[type] = ops;
3629 void kvm_unregister_device_ops(u32 type)
3631 if (kvm_device_ops_table[type] != NULL)
3632 kvm_device_ops_table[type] = NULL;
3635 static int kvm_ioctl_create_device(struct kvm *kvm,
3636 struct kvm_create_device *cd)
3638 const struct kvm_device_ops *ops = NULL;
3639 struct kvm_device *dev;
3640 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
3644 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3647 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3648 ops = kvm_device_ops_table[type];
3655 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
3662 mutex_lock(&kvm->lock);
3663 ret = ops->create(dev, type);
3665 mutex_unlock(&kvm->lock);
3669 list_add(&dev->vm_node, &kvm->devices);
3670 mutex_unlock(&kvm->lock);
3676 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3678 kvm_put_kvm_no_destroy(kvm);
3679 mutex_lock(&kvm->lock);
3680 list_del(&dev->vm_node);
3681 mutex_unlock(&kvm->lock);
3690 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3693 case KVM_CAP_USER_MEMORY:
3694 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3695 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3696 case KVM_CAP_INTERNAL_ERROR_DATA:
3697 #ifdef CONFIG_HAVE_KVM_MSI
3698 case KVM_CAP_SIGNAL_MSI:
3700 #ifdef CONFIG_HAVE_KVM_IRQFD
3702 case KVM_CAP_IRQFD_RESAMPLE:
3704 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3705 case KVM_CAP_CHECK_EXTENSION_VM:
3706 case KVM_CAP_ENABLE_CAP_VM:
3707 case KVM_CAP_HALT_POLL:
3709 #ifdef CONFIG_KVM_MMIO
3710 case KVM_CAP_COALESCED_MMIO:
3711 return KVM_COALESCED_MMIO_PAGE_OFFSET;
3712 case KVM_CAP_COALESCED_PIO:
3715 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3716 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
3717 return KVM_DIRTY_LOG_MANUAL_CAPS;
3719 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3720 case KVM_CAP_IRQ_ROUTING:
3721 return KVM_MAX_IRQ_ROUTES;
3723 #if KVM_ADDRESS_SPACE_NUM > 1
3724 case KVM_CAP_MULTI_ADDRESS_SPACE:
3725 return KVM_ADDRESS_SPACE_NUM;
3727 case KVM_CAP_NR_MEMSLOTS:
3728 return KVM_USER_MEM_SLOTS;
3729 case KVM_CAP_DIRTY_LOG_RING:
3730 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3731 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
3738 return kvm_vm_ioctl_check_extension(kvm, arg);
3741 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
3745 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
3748 /* the size should be power of 2 */
3749 if (!size || (size & (size - 1)))
3752 /* Should be bigger to keep the reserved entries, or a page */
3753 if (size < kvm_dirty_ring_get_rsvd_entries() *
3754 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
3757 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
3758 sizeof(struct kvm_dirty_gfn))
3761 /* We only allow it to set once */
3762 if (kvm->dirty_ring_size)
3765 mutex_lock(&kvm->lock);
3767 if (kvm->created_vcpus) {
3768 /* We don't allow to change this value after vcpu created */
3771 kvm->dirty_ring_size = size;
3775 mutex_unlock(&kvm->lock);
3779 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
3782 struct kvm_vcpu *vcpu;
3785 if (!kvm->dirty_ring_size)
3788 mutex_lock(&kvm->slots_lock);
3790 kvm_for_each_vcpu(i, vcpu, kvm)
3791 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
3793 mutex_unlock(&kvm->slots_lock);
3796 kvm_flush_remote_tlbs(kvm);
3801 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3802 struct kvm_enable_cap *cap)
3807 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
3808 struct kvm_enable_cap *cap)
3811 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3812 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
3813 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
3815 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
3816 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
3818 if (cap->flags || (cap->args[0] & ~allowed_options))
3820 kvm->manual_dirty_log_protect = cap->args[0];
3824 case KVM_CAP_HALT_POLL: {
3825 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
3828 kvm->max_halt_poll_ns = cap->args[0];
3831 case KVM_CAP_DIRTY_LOG_RING:
3832 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
3834 return kvm_vm_ioctl_enable_cap(kvm, cap);
3838 static long kvm_vm_ioctl(struct file *filp,
3839 unsigned int ioctl, unsigned long arg)
3841 struct kvm *kvm = filp->private_data;
3842 void __user *argp = (void __user *)arg;
3845 if (kvm->mm != current->mm)
3848 case KVM_CREATE_VCPU:
3849 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3851 case KVM_ENABLE_CAP: {
3852 struct kvm_enable_cap cap;
3855 if (copy_from_user(&cap, argp, sizeof(cap)))
3857 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
3860 case KVM_SET_USER_MEMORY_REGION: {
3861 struct kvm_userspace_memory_region kvm_userspace_mem;
3864 if (copy_from_user(&kvm_userspace_mem, argp,
3865 sizeof(kvm_userspace_mem)))
3868 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3871 case KVM_GET_DIRTY_LOG: {
3872 struct kvm_dirty_log log;
3875 if (copy_from_user(&log, argp, sizeof(log)))
3877 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3880 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3881 case KVM_CLEAR_DIRTY_LOG: {
3882 struct kvm_clear_dirty_log log;
3885 if (copy_from_user(&log, argp, sizeof(log)))
3887 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3891 #ifdef CONFIG_KVM_MMIO
3892 case KVM_REGISTER_COALESCED_MMIO: {
3893 struct kvm_coalesced_mmio_zone zone;
3896 if (copy_from_user(&zone, argp, sizeof(zone)))
3898 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3901 case KVM_UNREGISTER_COALESCED_MMIO: {
3902 struct kvm_coalesced_mmio_zone zone;
3905 if (copy_from_user(&zone, argp, sizeof(zone)))
3907 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3912 struct kvm_irqfd data;
3915 if (copy_from_user(&data, argp, sizeof(data)))
3917 r = kvm_irqfd(kvm, &data);
3920 case KVM_IOEVENTFD: {
3921 struct kvm_ioeventfd data;
3924 if (copy_from_user(&data, argp, sizeof(data)))
3926 r = kvm_ioeventfd(kvm, &data);
3929 #ifdef CONFIG_HAVE_KVM_MSI
3930 case KVM_SIGNAL_MSI: {
3934 if (copy_from_user(&msi, argp, sizeof(msi)))
3936 r = kvm_send_userspace_msi(kvm, &msi);
3940 #ifdef __KVM_HAVE_IRQ_LINE
3941 case KVM_IRQ_LINE_STATUS:
3942 case KVM_IRQ_LINE: {
3943 struct kvm_irq_level irq_event;
3946 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3949 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3950 ioctl == KVM_IRQ_LINE_STATUS);
3955 if (ioctl == KVM_IRQ_LINE_STATUS) {
3956 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3964 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3965 case KVM_SET_GSI_ROUTING: {
3966 struct kvm_irq_routing routing;
3967 struct kvm_irq_routing __user *urouting;
3968 struct kvm_irq_routing_entry *entries = NULL;
3971 if (copy_from_user(&routing, argp, sizeof(routing)))
3974 if (!kvm_arch_can_set_irq_routing(kvm))
3976 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3982 entries = vmemdup_user(urouting->entries,
3983 array_size(sizeof(*entries),
3985 if (IS_ERR(entries)) {
3986 r = PTR_ERR(entries);
3990 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3995 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3996 case KVM_CREATE_DEVICE: {
3997 struct kvm_create_device cd;
4000 if (copy_from_user(&cd, argp, sizeof(cd)))
4003 r = kvm_ioctl_create_device(kvm, &cd);
4008 if (copy_to_user(argp, &cd, sizeof(cd)))
4014 case KVM_CHECK_EXTENSION:
4015 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4017 case KVM_RESET_DIRTY_RINGS:
4018 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4021 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4027 #ifdef CONFIG_KVM_COMPAT
4028 struct compat_kvm_dirty_log {
4032 compat_uptr_t dirty_bitmap; /* one bit per page */
4037 static long kvm_vm_compat_ioctl(struct file *filp,
4038 unsigned int ioctl, unsigned long arg)
4040 struct kvm *kvm = filp->private_data;
4043 if (kvm->mm != current->mm)
4046 case KVM_GET_DIRTY_LOG: {
4047 struct compat_kvm_dirty_log compat_log;
4048 struct kvm_dirty_log log;
4050 if (copy_from_user(&compat_log, (void __user *)arg,
4051 sizeof(compat_log)))
4053 log.slot = compat_log.slot;
4054 log.padding1 = compat_log.padding1;
4055 log.padding2 = compat_log.padding2;
4056 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4058 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4062 r = kvm_vm_ioctl(filp, ioctl, arg);
4068 static struct file_operations kvm_vm_fops = {
4069 .release = kvm_vm_release,
4070 .unlocked_ioctl = kvm_vm_ioctl,
4071 .llseek = noop_llseek,
4072 KVM_COMPAT(kvm_vm_compat_ioctl),
4075 static int kvm_dev_ioctl_create_vm(unsigned long type)
4081 kvm = kvm_create_vm(type);
4083 return PTR_ERR(kvm);
4084 #ifdef CONFIG_KVM_MMIO
4085 r = kvm_coalesced_mmio_init(kvm);
4089 r = get_unused_fd_flags(O_CLOEXEC);
4093 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4101 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4102 * already set, with ->release() being kvm_vm_release(). In error
4103 * cases it will be called by the final fput(file) and will take
4104 * care of doing kvm_put_kvm(kvm).
4106 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4111 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4113 fd_install(r, file);
4121 static long kvm_dev_ioctl(struct file *filp,
4122 unsigned int ioctl, unsigned long arg)
4127 case KVM_GET_API_VERSION:
4130 r = KVM_API_VERSION;
4133 r = kvm_dev_ioctl_create_vm(arg);
4135 case KVM_CHECK_EXTENSION:
4136 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4138 case KVM_GET_VCPU_MMAP_SIZE:
4141 r = PAGE_SIZE; /* struct kvm_run */
4143 r += PAGE_SIZE; /* pio data page */
4145 #ifdef CONFIG_KVM_MMIO
4146 r += PAGE_SIZE; /* coalesced mmio ring page */
4149 case KVM_TRACE_ENABLE:
4150 case KVM_TRACE_PAUSE:
4151 case KVM_TRACE_DISABLE:
4155 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4161 static struct file_operations kvm_chardev_ops = {
4162 .unlocked_ioctl = kvm_dev_ioctl,
4163 .llseek = noop_llseek,
4164 KVM_COMPAT(kvm_dev_ioctl),
4167 static struct miscdevice kvm_dev = {
4173 static void hardware_enable_nolock(void *junk)
4175 int cpu = raw_smp_processor_id();
4178 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4181 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4183 r = kvm_arch_hardware_enable();
4186 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4187 atomic_inc(&hardware_enable_failed);
4188 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4192 static int kvm_starting_cpu(unsigned int cpu)
4194 raw_spin_lock(&kvm_count_lock);
4195 if (kvm_usage_count)
4196 hardware_enable_nolock(NULL);
4197 raw_spin_unlock(&kvm_count_lock);
4201 static void hardware_disable_nolock(void *junk)
4203 int cpu = raw_smp_processor_id();
4205 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4207 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4208 kvm_arch_hardware_disable();
4211 static int kvm_dying_cpu(unsigned int cpu)
4213 raw_spin_lock(&kvm_count_lock);
4214 if (kvm_usage_count)
4215 hardware_disable_nolock(NULL);
4216 raw_spin_unlock(&kvm_count_lock);
4220 static void hardware_disable_all_nolock(void)
4222 BUG_ON(!kvm_usage_count);
4225 if (!kvm_usage_count)
4226 on_each_cpu(hardware_disable_nolock, NULL, 1);
4229 static void hardware_disable_all(void)
4231 raw_spin_lock(&kvm_count_lock);
4232 hardware_disable_all_nolock();
4233 raw_spin_unlock(&kvm_count_lock);
4236 static int hardware_enable_all(void)
4240 raw_spin_lock(&kvm_count_lock);
4243 if (kvm_usage_count == 1) {
4244 atomic_set(&hardware_enable_failed, 0);
4245 on_each_cpu(hardware_enable_nolock, NULL, 1);
4247 if (atomic_read(&hardware_enable_failed)) {
4248 hardware_disable_all_nolock();
4253 raw_spin_unlock(&kvm_count_lock);
4258 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4262 * Some (well, at least mine) BIOSes hang on reboot if
4265 * And Intel TXT required VMX off for all cpu when system shutdown.
4267 pr_info("kvm: exiting hardware virtualization\n");
4268 kvm_rebooting = true;
4269 on_each_cpu(hardware_disable_nolock, NULL, 1);
4273 static struct notifier_block kvm_reboot_notifier = {
4274 .notifier_call = kvm_reboot,
4278 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4282 for (i = 0; i < bus->dev_count; i++) {
4283 struct kvm_io_device *pos = bus->range[i].dev;
4285 kvm_iodevice_destructor(pos);
4290 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4291 const struct kvm_io_range *r2)
4293 gpa_t addr1 = r1->addr;
4294 gpa_t addr2 = r2->addr;
4299 /* If r2->len == 0, match the exact address. If r2->len != 0,
4300 * accept any overlapping write. Any order is acceptable for
4301 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4302 * we process all of them.
4315 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4317 return kvm_io_bus_cmp(p1, p2);
4320 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4321 gpa_t addr, int len)
4323 struct kvm_io_range *range, key;
4326 key = (struct kvm_io_range) {
4331 range = bsearch(&key, bus->range, bus->dev_count,
4332 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4336 off = range - bus->range;
4338 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
4344 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4345 struct kvm_io_range *range, const void *val)
4349 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4353 while (idx < bus->dev_count &&
4354 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4355 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
4364 /* kvm_io_bus_write - called under kvm->slots_lock */
4365 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4366 int len, const void *val)
4368 struct kvm_io_bus *bus;
4369 struct kvm_io_range range;
4372 range = (struct kvm_io_range) {
4377 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4380 r = __kvm_io_bus_write(vcpu, bus, &range, val);
4381 return r < 0 ? r : 0;
4383 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
4385 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
4386 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4387 gpa_t addr, int len, const void *val, long cookie)
4389 struct kvm_io_bus *bus;
4390 struct kvm_io_range range;
4392 range = (struct kvm_io_range) {
4397 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4401 /* First try the device referenced by cookie. */
4402 if ((cookie >= 0) && (cookie < bus->dev_count) &&
4403 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
4404 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
4409 * cookie contained garbage; fall back to search and return the
4410 * correct cookie value.
4412 return __kvm_io_bus_write(vcpu, bus, &range, val);
4415 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4416 struct kvm_io_range *range, void *val)
4420 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4424 while (idx < bus->dev_count &&
4425 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4426 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4435 /* kvm_io_bus_read - called under kvm->slots_lock */
4436 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4439 struct kvm_io_bus *bus;
4440 struct kvm_io_range range;
4443 range = (struct kvm_io_range) {
4448 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4451 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4452 return r < 0 ? r : 0;
4455 /* Caller must hold slots_lock. */
4456 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4457 int len, struct kvm_io_device *dev)
4460 struct kvm_io_bus *new_bus, *bus;
4461 struct kvm_io_range range;
4463 bus = kvm_get_bus(kvm, bus_idx);
4467 /* exclude ioeventfd which is limited by maximum fd */
4468 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
4471 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
4472 GFP_KERNEL_ACCOUNT);
4476 range = (struct kvm_io_range) {
4482 for (i = 0; i < bus->dev_count; i++)
4483 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4486 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4487 new_bus->dev_count++;
4488 new_bus->range[i] = range;
4489 memcpy(new_bus->range + i + 1, bus->range + i,
4490 (bus->dev_count - i) * sizeof(struct kvm_io_range));
4491 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4492 synchronize_srcu_expedited(&kvm->srcu);
4498 /* Caller must hold slots_lock. */
4499 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4500 struct kvm_io_device *dev)
4503 struct kvm_io_bus *new_bus, *bus;
4505 bus = kvm_get_bus(kvm, bus_idx);
4509 for (i = 0; i < bus->dev_count; i++)
4510 if (bus->range[i].dev == dev) {
4514 if (i == bus->dev_count)
4517 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
4518 GFP_KERNEL_ACCOUNT);
4520 memcpy(new_bus, bus, struct_size(bus, range, i));
4521 new_bus->dev_count--;
4522 memcpy(new_bus->range + i, bus->range + i + 1,
4523 flex_array_size(new_bus, range, new_bus->dev_count - i));
4525 pr_err("kvm: failed to shrink bus, removing it completely\n");
4526 for (j = 0; j < bus->dev_count; j++) {
4529 kvm_iodevice_destructor(bus->range[j].dev);
4533 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4534 synchronize_srcu_expedited(&kvm->srcu);
4539 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4542 struct kvm_io_bus *bus;
4543 int dev_idx, srcu_idx;
4544 struct kvm_io_device *iodev = NULL;
4546 srcu_idx = srcu_read_lock(&kvm->srcu);
4548 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
4552 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
4556 iodev = bus->range[dev_idx].dev;
4559 srcu_read_unlock(&kvm->srcu, srcu_idx);
4563 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4565 static int kvm_debugfs_open(struct inode *inode, struct file *file,
4566 int (*get)(void *, u64 *), int (*set)(void *, u64),
4569 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4572 /* The debugfs files are a reference to the kvm struct which
4573 * is still valid when kvm_destroy_vm is called.
4574 * To avoid the race between open and the removal of the debugfs
4575 * directory we test against the users count.
4577 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
4580 if (simple_attr_open(inode, file, get,
4581 KVM_DBGFS_GET_MODE(stat_data->dbgfs_item) & 0222
4584 kvm_put_kvm(stat_data->kvm);
4591 static int kvm_debugfs_release(struct inode *inode, struct file *file)
4593 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4596 simple_attr_release(inode, file);
4597 kvm_put_kvm(stat_data->kvm);
4602 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
4604 *val = *(ulong *)((void *)kvm + offset);
4609 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
4611 *(ulong *)((void *)kvm + offset) = 0;
4616 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
4619 struct kvm_vcpu *vcpu;
4623 kvm_for_each_vcpu(i, vcpu, kvm)
4624 *val += *(u64 *)((void *)vcpu + offset);
4629 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
4632 struct kvm_vcpu *vcpu;
4634 kvm_for_each_vcpu(i, vcpu, kvm)
4635 *(u64 *)((void *)vcpu + offset) = 0;
4640 static int kvm_stat_data_get(void *data, u64 *val)
4643 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4645 switch (stat_data->dbgfs_item->kind) {
4647 r = kvm_get_stat_per_vm(stat_data->kvm,
4648 stat_data->dbgfs_item->offset, val);
4651 r = kvm_get_stat_per_vcpu(stat_data->kvm,
4652 stat_data->dbgfs_item->offset, val);
4659 static int kvm_stat_data_clear(void *data, u64 val)
4662 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4667 switch (stat_data->dbgfs_item->kind) {
4669 r = kvm_clear_stat_per_vm(stat_data->kvm,
4670 stat_data->dbgfs_item->offset);
4673 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
4674 stat_data->dbgfs_item->offset);
4681 static int kvm_stat_data_open(struct inode *inode, struct file *file)
4683 __simple_attr_check_format("%llu\n", 0ull);
4684 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
4685 kvm_stat_data_clear, "%llu\n");
4688 static const struct file_operations stat_fops_per_vm = {
4689 .owner = THIS_MODULE,
4690 .open = kvm_stat_data_open,
4691 .release = kvm_debugfs_release,
4692 .read = simple_attr_read,
4693 .write = simple_attr_write,
4694 .llseek = no_llseek,
4697 static int vm_stat_get(void *_offset, u64 *val)
4699 unsigned offset = (long)_offset;
4704 mutex_lock(&kvm_lock);
4705 list_for_each_entry(kvm, &vm_list, vm_list) {
4706 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
4709 mutex_unlock(&kvm_lock);
4713 static int vm_stat_clear(void *_offset, u64 val)
4715 unsigned offset = (long)_offset;
4721 mutex_lock(&kvm_lock);
4722 list_for_each_entry(kvm, &vm_list, vm_list) {
4723 kvm_clear_stat_per_vm(kvm, offset);
4725 mutex_unlock(&kvm_lock);
4730 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
4732 static int vcpu_stat_get(void *_offset, u64 *val)
4734 unsigned offset = (long)_offset;
4739 mutex_lock(&kvm_lock);
4740 list_for_each_entry(kvm, &vm_list, vm_list) {
4741 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
4744 mutex_unlock(&kvm_lock);
4748 static int vcpu_stat_clear(void *_offset, u64 val)
4750 unsigned offset = (long)_offset;
4756 mutex_lock(&kvm_lock);
4757 list_for_each_entry(kvm, &vm_list, vm_list) {
4758 kvm_clear_stat_per_vcpu(kvm, offset);
4760 mutex_unlock(&kvm_lock);
4765 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4768 static const struct file_operations *stat_fops[] = {
4769 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4770 [KVM_STAT_VM] = &vm_stat_fops,
4773 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4775 struct kobj_uevent_env *env;
4776 unsigned long long created, active;
4778 if (!kvm_dev.this_device || !kvm)
4781 mutex_lock(&kvm_lock);
4782 if (type == KVM_EVENT_CREATE_VM) {
4783 kvm_createvm_count++;
4785 } else if (type == KVM_EVENT_DESTROY_VM) {
4788 created = kvm_createvm_count;
4789 active = kvm_active_vms;
4790 mutex_unlock(&kvm_lock);
4792 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
4796 add_uevent_var(env, "CREATED=%llu", created);
4797 add_uevent_var(env, "COUNT=%llu", active);
4799 if (type == KVM_EVENT_CREATE_VM) {
4800 add_uevent_var(env, "EVENT=create");
4801 kvm->userspace_pid = task_pid_nr(current);
4802 } else if (type == KVM_EVENT_DESTROY_VM) {
4803 add_uevent_var(env, "EVENT=destroy");
4805 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
4807 if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
4808 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
4811 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4813 add_uevent_var(env, "STATS_PATH=%s", tmp);
4817 /* no need for checks, since we are adding at most only 5 keys */
4818 env->envp[env->envp_idx++] = NULL;
4819 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4823 static void kvm_init_debug(void)
4825 struct kvm_stats_debugfs_item *p;
4827 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4829 kvm_debugfs_num_entries = 0;
4830 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
4831 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
4832 kvm_debugfs_dir, (void *)(long)p->offset,
4833 stat_fops[p->kind]);
4837 static int kvm_suspend(void)
4839 if (kvm_usage_count)
4840 hardware_disable_nolock(NULL);
4844 static void kvm_resume(void)
4846 if (kvm_usage_count) {
4847 #ifdef CONFIG_LOCKDEP
4848 WARN_ON(lockdep_is_held(&kvm_count_lock));
4850 hardware_enable_nolock(NULL);
4854 static struct syscore_ops kvm_syscore_ops = {
4855 .suspend = kvm_suspend,
4856 .resume = kvm_resume,
4860 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4862 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4865 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4867 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4869 WRITE_ONCE(vcpu->preempted, false);
4870 WRITE_ONCE(vcpu->ready, false);
4872 __this_cpu_write(kvm_running_vcpu, vcpu);
4873 kvm_arch_sched_in(vcpu, cpu);
4874 kvm_arch_vcpu_load(vcpu, cpu);
4877 static void kvm_sched_out(struct preempt_notifier *pn,
4878 struct task_struct *next)
4880 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4882 if (current->state == TASK_RUNNING) {
4883 WRITE_ONCE(vcpu->preempted, true);
4884 WRITE_ONCE(vcpu->ready, true);
4886 kvm_arch_vcpu_put(vcpu);
4887 __this_cpu_write(kvm_running_vcpu, NULL);
4891 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
4893 * We can disable preemption locally around accessing the per-CPU variable,
4894 * and use the resolved vcpu pointer after enabling preemption again,
4895 * because even if the current thread is migrated to another CPU, reading
4896 * the per-CPU value later will give us the same value as we update the
4897 * per-CPU variable in the preempt notifier handlers.
4899 struct kvm_vcpu *kvm_get_running_vcpu(void)
4901 struct kvm_vcpu *vcpu;
4904 vcpu = __this_cpu_read(kvm_running_vcpu);
4909 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
4912 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
4914 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
4916 return &kvm_running_vcpu;
4919 struct kvm_cpu_compat_check {
4924 static void check_processor_compat(void *data)
4926 struct kvm_cpu_compat_check *c = data;
4928 *c->ret = kvm_arch_check_processor_compat(c->opaque);
4931 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
4932 struct module *module)
4934 struct kvm_cpu_compat_check c;
4938 r = kvm_arch_init(opaque);
4943 * kvm_arch_init makes sure there's at most one caller
4944 * for architectures that support multiple implementations,
4945 * like intel and amd on x86.
4946 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4947 * conflicts in case kvm is already setup for another implementation.
4949 r = kvm_irqfd_init();
4953 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
4958 r = kvm_arch_hardware_setup(opaque);
4964 for_each_online_cpu(cpu) {
4965 smp_call_function_single(cpu, check_processor_compat, &c, 1);
4970 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
4971 kvm_starting_cpu, kvm_dying_cpu);
4974 register_reboot_notifier(&kvm_reboot_notifier);
4976 /* A kmem cache lets us meet the alignment requirements of fx_save. */
4978 vcpu_align = __alignof__(struct kvm_vcpu);
4980 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4982 offsetof(struct kvm_vcpu, arch),
4983 sizeof_field(struct kvm_vcpu, arch),
4985 if (!kvm_vcpu_cache) {
4990 r = kvm_async_pf_init();
4994 kvm_chardev_ops.owner = module;
4995 kvm_vm_fops.owner = module;
4996 kvm_vcpu_fops.owner = module;
4998 r = misc_register(&kvm_dev);
5000 pr_err("kvm: misc device register failed\n");
5004 register_syscore_ops(&kvm_syscore_ops);
5006 kvm_preempt_ops.sched_in = kvm_sched_in;
5007 kvm_preempt_ops.sched_out = kvm_sched_out;
5011 r = kvm_vfio_ops_init();
5017 kvm_async_pf_deinit();
5019 kmem_cache_destroy(kvm_vcpu_cache);
5021 unregister_reboot_notifier(&kvm_reboot_notifier);
5022 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5024 kvm_arch_hardware_unsetup();
5026 free_cpumask_var(cpus_hardware_enabled);
5034 EXPORT_SYMBOL_GPL(kvm_init);
5038 debugfs_remove_recursive(kvm_debugfs_dir);
5039 misc_deregister(&kvm_dev);
5040 kmem_cache_destroy(kvm_vcpu_cache);
5041 kvm_async_pf_deinit();
5042 unregister_syscore_ops(&kvm_syscore_ops);
5043 unregister_reboot_notifier(&kvm_reboot_notifier);
5044 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5045 on_each_cpu(hardware_disable_nolock, NULL, 1);
5046 kvm_arch_hardware_unsetup();
5049 free_cpumask_var(cpus_hardware_enabled);
5050 kvm_vfio_ops_exit();
5052 EXPORT_SYMBOL_GPL(kvm_exit);
5054 struct kvm_vm_worker_thread_context {
5056 struct task_struct *parent;
5057 struct completion init_done;
5058 kvm_vm_thread_fn_t thread_fn;
5063 static int kvm_vm_worker_thread(void *context)
5066 * The init_context is allocated on the stack of the parent thread, so
5067 * we have to locally copy anything that is needed beyond initialization
5069 struct kvm_vm_worker_thread_context *init_context = context;
5070 struct kvm *kvm = init_context->kvm;
5071 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5072 uintptr_t data = init_context->data;
5075 err = kthread_park(current);
5076 /* kthread_park(current) is never supposed to return an error */
5081 err = cgroup_attach_task_all(init_context->parent, current);
5083 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5088 set_user_nice(current, task_nice(init_context->parent));
5091 init_context->err = err;
5092 complete(&init_context->init_done);
5093 init_context = NULL;
5098 /* Wait to be woken up by the spawner before proceeding. */
5101 if (!kthread_should_stop())
5102 err = thread_fn(kvm, data);
5107 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5108 uintptr_t data, const char *name,
5109 struct task_struct **thread_ptr)
5111 struct kvm_vm_worker_thread_context init_context = {};
5112 struct task_struct *thread;
5115 init_context.kvm = kvm;
5116 init_context.parent = current;
5117 init_context.thread_fn = thread_fn;
5118 init_context.data = data;
5119 init_completion(&init_context.init_done);
5121 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5122 "%s-%d", name, task_pid_nr(current));
5124 return PTR_ERR(thread);
5126 /* kthread_run is never supposed to return NULL */
5127 WARN_ON(thread == NULL);
5129 wait_for_completion(&init_context.init_done);
5131 if (!init_context.err)
5132 *thread_ptr = thread;
5134 return init_context.err;