2 * Kernel-based Virtual Machine driver for Linux
4 * This module enables machines with Intel VT-x extensions to run virtual
5 * machines without emulation or binary translation.
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11 * Avi Kivity <avi@qumranet.com>
12 * Yaniv Kamay <yaniv@qumranet.com>
14 * This work is licensed under the terms of the GNU GPL, version 2. See
15 * the COPYING file in the top-level directory.
19 #include <kvm/iodev.h>
21 #include <linux/kvm_host.h>
22 #include <linux/kvm.h>
23 #include <linux/module.h>
24 #include <linux/errno.h>
25 #include <linux/percpu.h>
27 #include <linux/miscdevice.h>
28 #include <linux/vmalloc.h>
29 #include <linux/reboot.h>
30 #include <linux/debugfs.h>
31 #include <linux/highmem.h>
32 #include <linux/file.h>
33 #include <linux/syscore_ops.h>
34 #include <linux/cpu.h>
35 #include <linux/sched/signal.h>
36 #include <linux/sched/mm.h>
37 #include <linux/sched/stat.h>
38 #include <linux/cpumask.h>
39 #include <linux/smp.h>
40 #include <linux/anon_inodes.h>
41 #include <linux/profile.h>
42 #include <linux/kvm_para.h>
43 #include <linux/pagemap.h>
44 #include <linux/mman.h>
45 #include <linux/swap.h>
46 #include <linux/bitops.h>
47 #include <linux/spinlock.h>
48 #include <linux/compat.h>
49 #include <linux/srcu.h>
50 #include <linux/hugetlb.h>
51 #include <linux/slab.h>
52 #include <linux/sort.h>
53 #include <linux/bsearch.h>
54 #include <linux/kthread.h>
56 #include <asm/processor.h>
58 #include <asm/ioctl.h>
59 #include <linux/uaccess.h>
60 #include <asm/pgtable.h>
62 #include "coalesced_mmio.h"
66 #define CREATE_TRACE_POINTS
67 #include <trace/events/kvm.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 /* Default resets per-vcpu halt_poll_ns . */
86 unsigned int halt_poll_ns_shrink;
87 module_param(halt_poll_ns_shrink, uint, 0644);
88 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
93 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
96 DEFINE_MUTEX(kvm_lock);
97 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
100 static cpumask_var_t cpus_hardware_enabled;
101 static int kvm_usage_count;
102 static atomic_t hardware_enable_failed;
104 struct kmem_cache *kvm_vcpu_cache;
105 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
107 static __read_mostly struct preempt_ops kvm_preempt_ops;
109 struct dentry *kvm_debugfs_dir;
110 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
112 static int kvm_debugfs_num_entries;
113 static const struct file_operations *stat_fops_per_vm[];
115 static struct file_operations kvm_chardev_ops;
117 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
119 #ifdef CONFIG_KVM_COMPAT
120 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
123 static int hardware_enable_all(void);
124 static void hardware_disable_all(void);
126 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
128 static void kvm_release_pfn_dirty(kvm_pfn_t pfn);
129 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
131 __visible bool kvm_rebooting;
132 EXPORT_SYMBOL_GPL(kvm_rebooting);
134 static bool largepages_enabled = true;
136 #define KVM_EVENT_CREATE_VM 0
137 #define KVM_EVENT_DESTROY_VM 1
138 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
139 static unsigned long long kvm_createvm_count;
140 static unsigned long long kvm_active_vms;
142 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
143 unsigned long start, unsigned long end)
147 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
150 * The metadata used by is_zone_device_page() to determine whether or
151 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
152 * the device has been pinned, e.g. by get_user_pages(). WARN if the
153 * page_count() is zero to help detect bad usage of this helper.
155 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
158 return is_zone_device_page(pfn_to_page(pfn));
161 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
164 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
165 * perspective they are "normal" pages, albeit with slightly different
169 return PageReserved(pfn_to_page(pfn)) &&
171 !kvm_is_zone_device_pfn(pfn);
177 * Switches to specified vcpu, until a matching vcpu_put()
179 int vcpu_load(struct kvm_vcpu *vcpu)
183 if (mutex_lock_killable(&vcpu->mutex))
186 preempt_notifier_register(&vcpu->preempt_notifier);
187 kvm_arch_vcpu_load(vcpu, cpu);
191 EXPORT_SYMBOL_GPL(vcpu_load);
193 void vcpu_put(struct kvm_vcpu *vcpu)
196 kvm_arch_vcpu_put(vcpu);
197 preempt_notifier_unregister(&vcpu->preempt_notifier);
199 mutex_unlock(&vcpu->mutex);
201 EXPORT_SYMBOL_GPL(vcpu_put);
203 /* TODO: merge with kvm_arch_vcpu_should_kick */
204 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
206 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
209 * We need to wait for the VCPU to reenable interrupts and get out of
210 * READING_SHADOW_PAGE_TABLES mode.
212 if (req & KVM_REQUEST_WAIT)
213 return mode != OUTSIDE_GUEST_MODE;
216 * Need to kick a running VCPU, but otherwise there is nothing to do.
218 return mode == IN_GUEST_MODE;
221 static void ack_flush(void *_completed)
225 static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
228 cpus = cpu_online_mask;
230 if (cpumask_empty(cpus))
233 smp_call_function_many(cpus, ack_flush, NULL, wait);
237 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
242 struct kvm_vcpu *vcpu;
244 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
247 kvm_for_each_vcpu(i, vcpu, kvm) {
248 kvm_make_request(req, vcpu);
251 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
254 if (cpus != NULL && cpu != -1 && cpu != me &&
255 kvm_request_needs_ipi(vcpu, req))
256 __cpumask_set_cpu(cpu, cpus);
258 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
260 free_cpumask_var(cpus);
264 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
265 void kvm_flush_remote_tlbs(struct kvm *kvm)
268 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
269 * kvm_make_all_cpus_request.
271 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
274 * We want to publish modifications to the page tables before reading
275 * mode. Pairs with a memory barrier in arch-specific code.
276 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
277 * and smp_mb in walk_shadow_page_lockless_begin/end.
278 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
280 * There is already an smp_mb__after_atomic() before
281 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
284 if (kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
285 ++kvm->stat.remote_tlb_flush;
286 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
288 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
291 void kvm_reload_remote_mmus(struct kvm *kvm)
293 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
296 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
301 mutex_init(&vcpu->mutex);
306 init_swait_queue_head(&vcpu->wq);
307 kvm_async_pf_vcpu_init(vcpu);
310 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
312 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
317 vcpu->run = page_address(page);
319 kvm_vcpu_set_in_spin_loop(vcpu, false);
320 kvm_vcpu_set_dy_eligible(vcpu, false);
321 vcpu->preempted = false;
323 r = kvm_arch_vcpu_init(vcpu);
329 free_page((unsigned long)vcpu->run);
333 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
335 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
338 * no need for rcu_read_lock as VCPU_RUN is the only place that
339 * will change the vcpu->pid pointer and on uninit all file
340 * descriptors are already gone.
342 put_pid(rcu_dereference_protected(vcpu->pid, 1));
343 kvm_arch_vcpu_uninit(vcpu);
344 free_page((unsigned long)vcpu->run);
346 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
348 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
349 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
351 return container_of(mn, struct kvm, mmu_notifier);
354 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
355 struct mm_struct *mm,
356 unsigned long address,
359 struct kvm *kvm = mmu_notifier_to_kvm(mn);
362 idx = srcu_read_lock(&kvm->srcu);
363 spin_lock(&kvm->mmu_lock);
364 kvm->mmu_notifier_seq++;
365 kvm_set_spte_hva(kvm, address, pte);
366 spin_unlock(&kvm->mmu_lock);
367 srcu_read_unlock(&kvm->srcu, idx);
370 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
371 struct mm_struct *mm,
375 struct kvm *kvm = mmu_notifier_to_kvm(mn);
376 int need_tlb_flush = 0, idx;
378 idx = srcu_read_lock(&kvm->srcu);
379 spin_lock(&kvm->mmu_lock);
381 * The count increase must become visible at unlock time as no
382 * spte can be established without taking the mmu_lock and
383 * count is also read inside the mmu_lock critical section.
385 kvm->mmu_notifier_count++;
386 need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
387 /* we've to flush the tlb before the pages can be freed */
388 if (need_tlb_flush || kvm->tlbs_dirty)
389 kvm_flush_remote_tlbs(kvm);
391 spin_unlock(&kvm->mmu_lock);
393 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
395 srcu_read_unlock(&kvm->srcu, idx);
398 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
399 struct mm_struct *mm,
403 struct kvm *kvm = mmu_notifier_to_kvm(mn);
405 spin_lock(&kvm->mmu_lock);
407 * This sequence increase will notify the kvm page fault that
408 * the page that is going to be mapped in the spte could have
411 kvm->mmu_notifier_seq++;
414 * The above sequence increase must be visible before the
415 * below count decrease, which is ensured by the smp_wmb above
416 * in conjunction with the smp_rmb in mmu_notifier_retry().
418 kvm->mmu_notifier_count--;
419 spin_unlock(&kvm->mmu_lock);
421 BUG_ON(kvm->mmu_notifier_count < 0);
424 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
425 struct mm_struct *mm,
429 struct kvm *kvm = mmu_notifier_to_kvm(mn);
432 idx = srcu_read_lock(&kvm->srcu);
433 spin_lock(&kvm->mmu_lock);
435 young = kvm_age_hva(kvm, start, end);
437 kvm_flush_remote_tlbs(kvm);
439 spin_unlock(&kvm->mmu_lock);
440 srcu_read_unlock(&kvm->srcu, idx);
445 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
446 struct mm_struct *mm,
450 struct kvm *kvm = mmu_notifier_to_kvm(mn);
453 idx = srcu_read_lock(&kvm->srcu);
454 spin_lock(&kvm->mmu_lock);
456 * Even though we do not flush TLB, this will still adversely
457 * affect performance on pre-Haswell Intel EPT, where there is
458 * no EPT Access Bit to clear so that we have to tear down EPT
459 * tables instead. If we find this unacceptable, we can always
460 * add a parameter to kvm_age_hva so that it effectively doesn't
461 * do anything on clear_young.
463 * Also note that currently we never issue secondary TLB flushes
464 * from clear_young, leaving this job up to the regular system
465 * cadence. If we find this inaccurate, we might come up with a
466 * more sophisticated heuristic later.
468 young = kvm_age_hva(kvm, start, end);
469 spin_unlock(&kvm->mmu_lock);
470 srcu_read_unlock(&kvm->srcu, idx);
475 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
476 struct mm_struct *mm,
477 unsigned long address)
479 struct kvm *kvm = mmu_notifier_to_kvm(mn);
482 idx = srcu_read_lock(&kvm->srcu);
483 spin_lock(&kvm->mmu_lock);
484 young = kvm_test_age_hva(kvm, address);
485 spin_unlock(&kvm->mmu_lock);
486 srcu_read_unlock(&kvm->srcu, idx);
491 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
492 struct mm_struct *mm)
494 struct kvm *kvm = mmu_notifier_to_kvm(mn);
497 idx = srcu_read_lock(&kvm->srcu);
498 kvm_arch_flush_shadow_all(kvm);
499 srcu_read_unlock(&kvm->srcu, idx);
502 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
503 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
504 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
505 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
506 .clear_young = kvm_mmu_notifier_clear_young,
507 .test_young = kvm_mmu_notifier_test_young,
508 .change_pte = kvm_mmu_notifier_change_pte,
509 .release = kvm_mmu_notifier_release,
512 static int kvm_init_mmu_notifier(struct kvm *kvm)
514 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
515 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
518 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
520 static int kvm_init_mmu_notifier(struct kvm *kvm)
525 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
527 static struct kvm_memslots *kvm_alloc_memslots(void)
530 struct kvm_memslots *slots;
532 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
536 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
537 slots->id_to_index[i] = slots->memslots[i].id = i;
542 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
544 if (!memslot->dirty_bitmap)
547 kvfree(memslot->dirty_bitmap);
548 memslot->dirty_bitmap = NULL;
552 * Free any memory in @free but not in @dont.
554 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
555 struct kvm_memory_slot *dont)
557 if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
558 kvm_destroy_dirty_bitmap(free);
560 kvm_arch_free_memslot(kvm, free, dont);
565 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
567 struct kvm_memory_slot *memslot;
572 kvm_for_each_memslot(memslot, slots)
573 kvm_free_memslot(kvm, memslot, NULL);
578 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
582 if (!kvm->debugfs_dentry)
585 debugfs_remove_recursive(kvm->debugfs_dentry);
587 if (kvm->debugfs_stat_data) {
588 for (i = 0; i < kvm_debugfs_num_entries; i++)
589 kfree(kvm->debugfs_stat_data[i]);
590 kfree(kvm->debugfs_stat_data);
594 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
596 char dir_name[ITOA_MAX_LEN * 2];
597 struct kvm_stat_data *stat_data;
598 struct kvm_stats_debugfs_item *p;
600 if (!debugfs_initialized())
603 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
604 kvm->debugfs_dentry = debugfs_create_dir(dir_name,
606 if (!kvm->debugfs_dentry)
609 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
610 sizeof(*kvm->debugfs_stat_data),
612 if (!kvm->debugfs_stat_data)
615 for (p = debugfs_entries; p->name; p++) {
616 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL);
620 stat_data->kvm = kvm;
621 stat_data->offset = p->offset;
622 stat_data->mode = p->mode ? p->mode : 0644;
623 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
624 if (!debugfs_create_file(p->name, stat_data->mode,
627 stat_fops_per_vm[p->kind]))
634 * Called after the VM is otherwise initialized, but just before adding it to
637 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
643 * Called just after removing the VM from the vm_list, but before doing any
646 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
650 static struct kvm *kvm_create_vm(unsigned long type)
653 struct kvm *kvm = kvm_arch_alloc_vm();
656 return ERR_PTR(-ENOMEM);
658 spin_lock_init(&kvm->mmu_lock);
660 kvm->mm = current->mm;
661 kvm_eventfd_init(kvm);
662 mutex_init(&kvm->lock);
663 mutex_init(&kvm->irq_lock);
664 mutex_init(&kvm->slots_lock);
665 refcount_set(&kvm->users_count, 1);
666 INIT_LIST_HEAD(&kvm->devices);
668 r = kvm_arch_init_vm(kvm, type);
670 goto out_err_no_disable;
672 r = hardware_enable_all();
674 goto out_err_no_disable;
676 #ifdef CONFIG_HAVE_KVM_IRQFD
677 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
680 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
683 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
684 struct kvm_memslots *slots = kvm_alloc_memslots();
686 goto out_err_no_srcu;
688 * Generations must be different for each address space.
689 * Init kvm generation close to the maximum to easily test the
690 * code of handling generation number wrap-around.
692 slots->generation = i * 2 - 150;
693 rcu_assign_pointer(kvm->memslots[i], slots);
696 if (init_srcu_struct(&kvm->srcu))
697 goto out_err_no_srcu;
698 if (init_srcu_struct(&kvm->irq_srcu))
699 goto out_err_no_irq_srcu;
700 for (i = 0; i < KVM_NR_BUSES; i++) {
701 rcu_assign_pointer(kvm->buses[i],
702 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL));
704 goto out_err_no_mmu_notifier;
707 r = kvm_init_mmu_notifier(kvm);
709 goto out_err_no_mmu_notifier;
711 r = kvm_arch_post_init_vm(kvm);
715 mutex_lock(&kvm_lock);
716 list_add(&kvm->vm_list, &vm_list);
717 mutex_unlock(&kvm_lock);
719 preempt_notifier_inc();
722 * When the fd passed to this ioctl() is opened it pins the module,
723 * but try_module_get() also prevents getting a reference if the module
724 * is in MODULE_STATE_GOING (e.g. if someone ran "rmmod --wait").
726 if (!try_module_get(kvm_chardev_ops.owner)) {
734 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
735 if (kvm->mmu_notifier.ops)
736 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
738 out_err_no_mmu_notifier:
739 cleanup_srcu_struct(&kvm->irq_srcu);
741 cleanup_srcu_struct(&kvm->srcu);
743 hardware_disable_all();
745 refcount_set(&kvm->users_count, 0);
746 for (i = 0; i < KVM_NR_BUSES; i++)
747 kfree(kvm_get_bus(kvm, i));
748 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
749 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
750 kvm_arch_free_vm(kvm);
755 static void kvm_destroy_devices(struct kvm *kvm)
757 struct kvm_device *dev, *tmp;
760 * We do not need to take the kvm->lock here, because nobody else
761 * has a reference to the struct kvm at this point and therefore
762 * cannot access the devices list anyhow.
764 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
765 list_del(&dev->vm_node);
766 dev->ops->destroy(dev);
770 static void kvm_destroy_vm(struct kvm *kvm)
773 struct mm_struct *mm = kvm->mm;
775 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
776 kvm_destroy_vm_debugfs(kvm);
777 kvm_arch_sync_events(kvm);
778 mutex_lock(&kvm_lock);
779 list_del(&kvm->vm_list);
780 mutex_unlock(&kvm_lock);
781 kvm_arch_pre_destroy_vm(kvm);
783 kvm_free_irq_routing(kvm);
784 for (i = 0; i < KVM_NR_BUSES; i++) {
785 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
788 kvm_io_bus_destroy(bus);
789 kvm->buses[i] = NULL;
791 kvm_coalesced_mmio_free(kvm);
792 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
793 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
795 kvm_arch_flush_shadow_all(kvm);
797 kvm_arch_destroy_vm(kvm);
798 kvm_destroy_devices(kvm);
799 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
800 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
801 cleanup_srcu_struct(&kvm->irq_srcu);
802 cleanup_srcu_struct(&kvm->srcu);
803 kvm_arch_free_vm(kvm);
804 preempt_notifier_dec();
805 hardware_disable_all();
807 module_put(kvm_chardev_ops.owner);
810 void kvm_get_kvm(struct kvm *kvm)
812 refcount_inc(&kvm->users_count);
814 EXPORT_SYMBOL_GPL(kvm_get_kvm);
816 void kvm_put_kvm(struct kvm *kvm)
818 if (refcount_dec_and_test(&kvm->users_count))
821 EXPORT_SYMBOL_GPL(kvm_put_kvm);
824 static int kvm_vm_release(struct inode *inode, struct file *filp)
826 struct kvm *kvm = filp->private_data;
828 kvm_irqfd_release(kvm);
835 * Allocation size is twice as large as the actual dirty bitmap size.
836 * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
838 static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
840 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
842 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL);
843 if (!memslot->dirty_bitmap)
850 * Insert memslot and re-sort memslots based on their GFN,
851 * so binary search could be used to lookup GFN.
852 * Sorting algorithm takes advantage of having initially
853 * sorted array and known changed memslot position.
855 static void update_memslots(struct kvm_memslots *slots,
856 struct kvm_memory_slot *new)
859 int i = slots->id_to_index[id];
860 struct kvm_memory_slot *mslots = slots->memslots;
862 WARN_ON(mslots[i].id != id);
864 WARN_ON(!mslots[i].npages);
865 if (mslots[i].npages)
868 if (!mslots[i].npages)
872 while (i < KVM_MEM_SLOTS_NUM - 1 &&
873 new->base_gfn <= mslots[i + 1].base_gfn) {
874 if (!mslots[i + 1].npages)
876 mslots[i] = mslots[i + 1];
877 slots->id_to_index[mslots[i].id] = i;
882 * The ">=" is needed when creating a slot with base_gfn == 0,
883 * so that it moves before all those with base_gfn == npages == 0.
885 * On the other hand, if new->npages is zero, the above loop has
886 * already left i pointing to the beginning of the empty part of
887 * mslots, and the ">=" would move the hole backwards in this
888 * case---which is wrong. So skip the loop when deleting a slot.
892 new->base_gfn >= mslots[i - 1].base_gfn) {
893 mslots[i] = mslots[i - 1];
894 slots->id_to_index[mslots[i].id] = i;
898 WARN_ON_ONCE(i != slots->used_slots);
901 slots->id_to_index[mslots[i].id] = i;
904 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
906 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
908 #ifdef __KVM_HAVE_READONLY_MEM
909 valid_flags |= KVM_MEM_READONLY;
912 if (mem->flags & ~valid_flags)
918 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
919 int as_id, struct kvm_memslots *slots)
921 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
925 * Set the low bit in the generation, which disables SPTE caching
926 * until the end of synchronize_srcu_expedited.
928 WARN_ON(old_memslots->generation & 1);
929 slots->generation = old_memslots->generation + 1;
931 rcu_assign_pointer(kvm->memslots[as_id], slots);
932 synchronize_srcu_expedited(&kvm->srcu);
935 * Increment the new memslot generation a second time. This prevents
936 * vm exits that race with memslot updates from caching a memslot
937 * generation that will (potentially) be valid forever.
939 * Generations must be unique even across address spaces. We do not need
940 * a global counter for that, instead the generation space is evenly split
941 * across address spaces. For example, with two address spaces, address
942 * space 0 will use generations 0, 4, 8, ... while * address space 1 will
943 * use generations 2, 6, 10, 14, ...
945 gen = slots->generation + KVM_ADDRESS_SPACE_NUM * 2 - 1;
947 kvm_arch_memslots_updated(kvm, gen);
949 slots->generation = gen;
955 * Allocate some memory and give it an address in the guest physical address
958 * Discontiguous memory is allowed, mostly for framebuffers.
960 * Must be called holding kvm->slots_lock for write.
962 int __kvm_set_memory_region(struct kvm *kvm,
963 const struct kvm_userspace_memory_region *mem)
967 unsigned long npages;
968 struct kvm_memory_slot *slot;
969 struct kvm_memory_slot old, new;
970 struct kvm_memslots *slots = NULL, *old_memslots;
972 enum kvm_mr_change change;
974 r = check_memory_region_flags(mem);
979 as_id = mem->slot >> 16;
982 /* General sanity checks */
983 if (mem->memory_size & (PAGE_SIZE - 1))
985 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
987 /* We can read the guest memory with __xxx_user() later on. */
988 if ((id < KVM_USER_MEM_SLOTS) &&
989 ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
990 !access_ok(VERIFY_WRITE,
991 (void __user *)(unsigned long)mem->userspace_addr,
994 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
996 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
999 slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1000 base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1001 npages = mem->memory_size >> PAGE_SHIFT;
1003 if (npages > KVM_MEM_MAX_NR_PAGES)
1009 new.base_gfn = base_gfn;
1010 new.npages = npages;
1011 new.flags = mem->flags;
1015 change = KVM_MR_CREATE;
1016 else { /* Modify an existing slot. */
1017 if ((mem->userspace_addr != old.userspace_addr) ||
1018 (npages != old.npages) ||
1019 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1022 if (base_gfn != old.base_gfn)
1023 change = KVM_MR_MOVE;
1024 else if (new.flags != old.flags)
1025 change = KVM_MR_FLAGS_ONLY;
1026 else { /* Nothing to change. */
1035 change = KVM_MR_DELETE;
1040 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1041 /* Check for overlaps */
1043 kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
1046 if (!((base_gfn + npages <= slot->base_gfn) ||
1047 (base_gfn >= slot->base_gfn + slot->npages)))
1052 /* Free page dirty bitmap if unneeded */
1053 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1054 new.dirty_bitmap = NULL;
1057 if (change == KVM_MR_CREATE) {
1058 new.userspace_addr = mem->userspace_addr;
1060 if (kvm_arch_create_memslot(kvm, &new, npages))
1064 /* Allocate page dirty bitmap if needed */
1065 if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
1066 if (kvm_create_dirty_bitmap(&new) < 0)
1070 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
1073 memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
1075 if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
1076 slot = id_to_memslot(slots, id);
1077 slot->flags |= KVM_MEMSLOT_INVALID;
1079 old_memslots = install_new_memslots(kvm, as_id, slots);
1081 /* From this point no new shadow pages pointing to a deleted,
1082 * or moved, memslot will be created.
1084 * validation of sp->gfn happens in:
1085 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1086 * - kvm_is_visible_gfn (mmu_check_roots)
1088 kvm_arch_flush_shadow_memslot(kvm, slot);
1091 * We can re-use the old_memslots from above, the only difference
1092 * from the currently installed memslots is the invalid flag. This
1093 * will get overwritten by update_memslots anyway.
1095 slots = old_memslots;
1098 r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
1102 /* actual memory is freed via old in kvm_free_memslot below */
1103 if (change == KVM_MR_DELETE) {
1104 new.dirty_bitmap = NULL;
1105 memset(&new.arch, 0, sizeof(new.arch));
1108 update_memslots(slots, &new);
1109 old_memslots = install_new_memslots(kvm, as_id, slots);
1111 kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
1113 kvm_free_memslot(kvm, &old, &new);
1114 kvfree(old_memslots);
1120 kvm_free_memslot(kvm, &new, &old);
1124 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1126 int kvm_set_memory_region(struct kvm *kvm,
1127 const struct kvm_userspace_memory_region *mem)
1131 mutex_lock(&kvm->slots_lock);
1132 r = __kvm_set_memory_region(kvm, mem);
1133 mutex_unlock(&kvm->slots_lock);
1136 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1138 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1139 struct kvm_userspace_memory_region *mem)
1141 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1144 return kvm_set_memory_region(kvm, mem);
1147 int kvm_get_dirty_log(struct kvm *kvm,
1148 struct kvm_dirty_log *log, int *is_dirty)
1150 struct kvm_memslots *slots;
1151 struct kvm_memory_slot *memslot;
1154 unsigned long any = 0;
1156 as_id = log->slot >> 16;
1157 id = (u16)log->slot;
1158 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1161 slots = __kvm_memslots(kvm, as_id);
1162 memslot = id_to_memslot(slots, id);
1163 if (!memslot->dirty_bitmap)
1166 n = kvm_dirty_bitmap_bytes(memslot);
1168 for (i = 0; !any && i < n/sizeof(long); ++i)
1169 any = memslot->dirty_bitmap[i];
1171 if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1178 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1180 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1182 * kvm_get_dirty_log_protect - get a snapshot of dirty pages, and if any pages
1183 * are dirty write protect them for next write.
1184 * @kvm: pointer to kvm instance
1185 * @log: slot id and address to which we copy the log
1186 * @is_dirty: flag set if any page is dirty
1188 * We need to keep it in mind that VCPU threads can write to the bitmap
1189 * concurrently. So, to avoid losing track of dirty pages we keep the
1192 * 1. Take a snapshot of the bit and clear it if needed.
1193 * 2. Write protect the corresponding page.
1194 * 3. Copy the snapshot to the userspace.
1195 * 4. Upon return caller flushes TLB's if needed.
1197 * Between 2 and 4, the guest may write to the page using the remaining TLB
1198 * entry. This is not a problem because the page is reported dirty using
1199 * the snapshot taken before and step 4 ensures that writes done after
1200 * exiting to userspace will be logged for the next call.
1203 int kvm_get_dirty_log_protect(struct kvm *kvm,
1204 struct kvm_dirty_log *log, bool *is_dirty)
1206 struct kvm_memslots *slots;
1207 struct kvm_memory_slot *memslot;
1210 unsigned long *dirty_bitmap;
1211 unsigned long *dirty_bitmap_buffer;
1213 as_id = log->slot >> 16;
1214 id = (u16)log->slot;
1215 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1218 slots = __kvm_memslots(kvm, as_id);
1219 memslot = id_to_memslot(slots, id);
1221 dirty_bitmap = memslot->dirty_bitmap;
1225 n = kvm_dirty_bitmap_bytes(memslot);
1227 dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
1228 memset(dirty_bitmap_buffer, 0, n);
1230 spin_lock(&kvm->mmu_lock);
1232 for (i = 0; i < n / sizeof(long); i++) {
1236 if (!dirty_bitmap[i])
1241 mask = xchg(&dirty_bitmap[i], 0);
1242 dirty_bitmap_buffer[i] = mask;
1245 offset = i * BITS_PER_LONG;
1246 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1251 spin_unlock(&kvm->mmu_lock);
1252 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1256 EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
1259 bool kvm_largepages_enabled(void)
1261 return largepages_enabled;
1264 void kvm_disable_largepages(void)
1266 largepages_enabled = false;
1268 EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1270 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1272 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1274 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1276 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1278 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1281 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1283 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1285 if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1286 memslot->flags & KVM_MEMSLOT_INVALID)
1291 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1293 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
1295 struct vm_area_struct *vma;
1296 unsigned long addr, size;
1300 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
1301 if (kvm_is_error_hva(addr))
1304 down_read(¤t->mm->mmap_sem);
1305 vma = find_vma(current->mm, addr);
1309 size = vma_kernel_pagesize(vma);
1312 up_read(¤t->mm->mmap_sem);
1317 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1319 return slot->flags & KVM_MEM_READONLY;
1322 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1323 gfn_t *nr_pages, bool write)
1325 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1326 return KVM_HVA_ERR_BAD;
1328 if (memslot_is_readonly(slot) && write)
1329 return KVM_HVA_ERR_RO_BAD;
1332 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1334 return __gfn_to_hva_memslot(slot, gfn);
1337 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1340 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1343 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1346 return gfn_to_hva_many(slot, gfn, NULL);
1348 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1350 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1352 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1354 EXPORT_SYMBOL_GPL(gfn_to_hva);
1356 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1358 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1360 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1363 * If writable is set to false, the hva returned by this function is only
1364 * allowed to be read.
1366 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1367 gfn_t gfn, bool *writable)
1369 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1371 if (!kvm_is_error_hva(hva) && writable)
1372 *writable = !memslot_is_readonly(slot);
1377 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1379 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1381 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1384 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1386 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1388 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1391 static int get_user_page_nowait(unsigned long start, int write,
1394 int flags = FOLL_NOWAIT | FOLL_HWPOISON;
1397 flags |= FOLL_WRITE;
1399 return get_user_pages(start, 1, flags, page, NULL);
1402 static inline int check_user_page_hwpoison(unsigned long addr)
1404 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1406 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1407 return rc == -EHWPOISON;
1411 * The atomic path to get the writable pfn which will be stored in @pfn,
1412 * true indicates success, otherwise false is returned.
1414 static bool hva_to_pfn_fast(unsigned long addr, bool atomic, bool *async,
1415 bool write_fault, bool *writable, kvm_pfn_t *pfn)
1417 struct page *page[1];
1420 if (!(async || atomic))
1424 * Fast pin a writable pfn only if it is a write fault request
1425 * or the caller allows to map a writable pfn for a read fault
1428 if (!(write_fault || writable))
1431 npages = __get_user_pages_fast(addr, 1, 1, page);
1433 *pfn = page_to_pfn(page[0]);
1444 * The slow path to get the pfn of the specified host virtual address,
1445 * 1 indicates success, -errno is returned if error is detected.
1447 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1448 bool *writable, kvm_pfn_t *pfn)
1450 struct page *page[1];
1456 *writable = write_fault;
1459 down_read(¤t->mm->mmap_sem);
1460 npages = get_user_page_nowait(addr, write_fault, page);
1461 up_read(¤t->mm->mmap_sem);
1463 unsigned int flags = FOLL_HWPOISON;
1466 flags |= FOLL_WRITE;
1468 npages = get_user_pages_unlocked(addr, 1, page, flags);
1473 /* map read fault as writable if possible */
1474 if (unlikely(!write_fault) && writable) {
1475 struct page *wpage[1];
1477 npages = __get_user_pages_fast(addr, 1, 1, wpage);
1486 *pfn = page_to_pfn(page[0]);
1490 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1492 if (unlikely(!(vma->vm_flags & VM_READ)))
1495 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1501 static int kvm_try_get_pfn(kvm_pfn_t pfn)
1503 if (kvm_is_reserved_pfn(pfn))
1505 return get_page_unless_zero(pfn_to_page(pfn));
1508 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1509 unsigned long addr, bool *async,
1510 bool write_fault, bool *writable,
1518 r = follow_pte_pmd(vma->vm_mm, addr, NULL, NULL, &ptep, NULL, &ptl);
1521 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1522 * not call the fault handler, so do it here.
1524 bool unlocked = false;
1525 r = fixup_user_fault(current, current->mm, addr,
1526 (write_fault ? FAULT_FLAG_WRITE : 0),
1533 r = follow_pte_pmd(vma->vm_mm, addr, NULL, NULL, &ptep, NULL, &ptl);
1538 if (write_fault && !pte_write(*ptep)) {
1539 pfn = KVM_PFN_ERR_RO_FAULT;
1544 *writable = pte_write(*ptep);
1545 pfn = pte_pfn(*ptep);
1548 * Get a reference here because callers of *hva_to_pfn* and
1549 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1550 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1551 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1552 * simply do nothing for reserved pfns.
1554 * Whoever called remap_pfn_range is also going to call e.g.
1555 * unmap_mapping_range before the underlying pages are freed,
1556 * causing a call to our MMU notifier.
1558 * Certain IO or PFNMAP mappings can be backed with valid
1559 * struct pages, but be allocated without refcounting e.g.,
1560 * tail pages of non-compound higher order allocations, which
1561 * would then underflow the refcount when the caller does the
1562 * required put_page. Don't allow those pages here.
1564 if (!kvm_try_get_pfn(pfn))
1568 pte_unmap_unlock(ptep, ptl);
1575 * Pin guest page in memory and return its pfn.
1576 * @addr: host virtual address which maps memory to the guest
1577 * @atomic: whether this function can sleep
1578 * @async: whether this function need to wait IO complete if the
1579 * host page is not in the memory
1580 * @write_fault: whether we should get a writable host page
1581 * @writable: whether it allows to map a writable host page for !@write_fault
1583 * The function will map a writable host page for these two cases:
1584 * 1): @write_fault = true
1585 * 2): @write_fault = false && @writable, @writable will tell the caller
1586 * whether the mapping is writable.
1588 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1589 bool write_fault, bool *writable)
1591 struct vm_area_struct *vma;
1595 /* we can do it either atomically or asynchronously, not both */
1596 BUG_ON(atomic && async);
1598 if (hva_to_pfn_fast(addr, atomic, async, write_fault, writable, &pfn))
1602 return KVM_PFN_ERR_FAULT;
1604 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1608 down_read(¤t->mm->mmap_sem);
1609 if (npages == -EHWPOISON ||
1610 (!async && check_user_page_hwpoison(addr))) {
1611 pfn = KVM_PFN_ERR_HWPOISON;
1616 vma = find_vma_intersection(current->mm, addr, addr + 1);
1619 pfn = KVM_PFN_ERR_FAULT;
1620 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1621 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
1625 pfn = KVM_PFN_ERR_FAULT;
1627 if (async && vma_is_valid(vma, write_fault))
1629 pfn = KVM_PFN_ERR_FAULT;
1632 up_read(¤t->mm->mmap_sem);
1636 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1637 bool atomic, bool *async, bool write_fault,
1640 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1642 if (addr == KVM_HVA_ERR_RO_BAD) {
1645 return KVM_PFN_ERR_RO_FAULT;
1648 if (kvm_is_error_hva(addr)) {
1651 return KVM_PFN_NOSLOT;
1654 /* Do not map writable pfn in the readonly memslot. */
1655 if (writable && memslot_is_readonly(slot)) {
1660 return hva_to_pfn(addr, atomic, async, write_fault,
1663 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1665 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1668 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1669 write_fault, writable);
1671 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1673 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1675 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1677 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1679 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1681 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1683 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1685 kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1687 return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1689 EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1691 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1693 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1695 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1697 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1699 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1701 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1703 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1705 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1707 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1709 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1710 struct page **pages, int nr_pages)
1715 addr = gfn_to_hva_many(slot, gfn, &entry);
1716 if (kvm_is_error_hva(addr))
1719 if (entry < nr_pages)
1722 return __get_user_pages_fast(addr, nr_pages, 1, pages);
1724 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1726 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
1728 if (is_error_noslot_pfn(pfn))
1729 return KVM_ERR_PTR_BAD_PAGE;
1731 if (kvm_is_reserved_pfn(pfn)) {
1733 return KVM_ERR_PTR_BAD_PAGE;
1736 return pfn_to_page(pfn);
1739 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1743 pfn = gfn_to_pfn(kvm, gfn);
1745 return kvm_pfn_to_page(pfn);
1747 EXPORT_SYMBOL_GPL(gfn_to_page);
1749 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
1753 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
1755 return kvm_pfn_to_page(pfn);
1757 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
1759 void kvm_release_page_clean(struct page *page)
1761 WARN_ON(is_error_page(page));
1763 kvm_release_pfn_clean(page_to_pfn(page));
1765 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1767 void kvm_release_pfn_clean(kvm_pfn_t pfn)
1769 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
1770 put_page(pfn_to_page(pfn));
1772 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1774 void kvm_release_page_dirty(struct page *page)
1776 WARN_ON(is_error_page(page));
1778 kvm_release_pfn_dirty(page_to_pfn(page));
1780 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1782 static void kvm_release_pfn_dirty(kvm_pfn_t pfn)
1784 kvm_set_pfn_dirty(pfn);
1785 kvm_release_pfn_clean(pfn);
1788 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
1790 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn)) {
1791 struct page *page = pfn_to_page(pfn);
1793 if (!PageReserved(page))
1797 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1799 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
1801 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
1802 mark_page_accessed(pfn_to_page(pfn));
1804 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1806 void kvm_get_pfn(kvm_pfn_t pfn)
1808 if (!kvm_is_reserved_pfn(pfn))
1809 get_page(pfn_to_page(pfn));
1811 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1813 static int next_segment(unsigned long len, int offset)
1815 if (len > PAGE_SIZE - offset)
1816 return PAGE_SIZE - offset;
1821 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
1822 void *data, int offset, int len)
1827 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1828 if (kvm_is_error_hva(addr))
1830 r = __copy_from_user(data, (void __user *)addr + offset, len);
1836 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1839 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1841 return __kvm_read_guest_page(slot, gfn, data, offset, len);
1843 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1845 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
1846 int offset, int len)
1848 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1850 return __kvm_read_guest_page(slot, gfn, data, offset, len);
1852 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
1854 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1856 gfn_t gfn = gpa >> PAGE_SHIFT;
1858 int offset = offset_in_page(gpa);
1861 while ((seg = next_segment(len, offset)) != 0) {
1862 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1872 EXPORT_SYMBOL_GPL(kvm_read_guest);
1874 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
1876 gfn_t gfn = gpa >> PAGE_SHIFT;
1878 int offset = offset_in_page(gpa);
1881 while ((seg = next_segment(len, offset)) != 0) {
1882 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
1892 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
1894 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1895 void *data, int offset, unsigned long len)
1900 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1901 if (kvm_is_error_hva(addr))
1903 pagefault_disable();
1904 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1911 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1914 gfn_t gfn = gpa >> PAGE_SHIFT;
1915 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1916 int offset = offset_in_page(gpa);
1918 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1920 EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
1922 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
1923 void *data, unsigned long len)
1925 gfn_t gfn = gpa >> PAGE_SHIFT;
1926 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1927 int offset = offset_in_page(gpa);
1929 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1931 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
1933 static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
1934 const void *data, int offset, int len)
1939 addr = gfn_to_hva_memslot(memslot, gfn);
1940 if (kvm_is_error_hva(addr))
1942 r = __copy_to_user((void __user *)addr + offset, data, len);
1945 mark_page_dirty_in_slot(memslot, gfn);
1949 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
1950 const void *data, int offset, int len)
1952 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1954 return __kvm_write_guest_page(slot, gfn, data, offset, len);
1956 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1958 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
1959 const void *data, int offset, int len)
1961 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1963 return __kvm_write_guest_page(slot, gfn, data, offset, len);
1965 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
1967 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1970 gfn_t gfn = gpa >> PAGE_SHIFT;
1972 int offset = offset_in_page(gpa);
1975 while ((seg = next_segment(len, offset)) != 0) {
1976 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
1986 EXPORT_SYMBOL_GPL(kvm_write_guest);
1988 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
1991 gfn_t gfn = gpa >> PAGE_SHIFT;
1993 int offset = offset_in_page(gpa);
1996 while ((seg = next_segment(len, offset)) != 0) {
1997 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2007 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2009 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2010 struct gfn_to_hva_cache *ghc,
2011 gpa_t gpa, unsigned long len)
2013 int offset = offset_in_page(gpa);
2014 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2015 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2016 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2017 gfn_t nr_pages_avail;
2020 ghc->generation = slots->generation;
2022 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2023 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, NULL);
2024 if (!kvm_is_error_hva(ghc->hva) && nr_pages_needed <= 1) {
2028 * If the requested region crosses two memslots, we still
2029 * verify that the entire region is valid here.
2031 while (start_gfn <= end_gfn) {
2033 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2034 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2036 if (kvm_is_error_hva(ghc->hva))
2038 start_gfn += nr_pages_avail;
2040 /* Use the slow path for cross page reads and writes. */
2041 ghc->memslot = NULL;
2046 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2047 gpa_t gpa, unsigned long len)
2049 struct kvm_memslots *slots = kvm_memslots(kvm);
2050 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2052 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2054 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2055 void *data, unsigned int offset,
2058 struct kvm_memslots *slots = kvm_memslots(kvm);
2060 gpa_t gpa = ghc->gpa + offset;
2062 BUG_ON(len + offset > ghc->len);
2064 if (slots->generation != ghc->generation)
2065 __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
2067 if (kvm_is_error_hva(ghc->hva))
2070 if (unlikely(!ghc->memslot))
2071 return kvm_write_guest(kvm, gpa, data, len);
2073 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2076 mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
2080 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2082 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2083 void *data, unsigned long len)
2085 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2087 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2089 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2090 void *data, unsigned long len)
2092 struct kvm_memslots *slots = kvm_memslots(kvm);
2095 BUG_ON(len > ghc->len);
2097 if (slots->generation != ghc->generation)
2098 __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
2100 if (kvm_is_error_hva(ghc->hva))
2103 if (unlikely(!ghc->memslot))
2104 return kvm_read_guest(kvm, ghc->gpa, data, len);
2106 r = __copy_from_user(data, (void __user *)ghc->hva, len);
2112 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2114 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2116 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2118 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2120 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2122 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2124 gfn_t gfn = gpa >> PAGE_SHIFT;
2126 int offset = offset_in_page(gpa);
2129 while ((seg = next_segment(len, offset)) != 0) {
2130 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2139 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2141 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2144 if (memslot && memslot->dirty_bitmap) {
2145 unsigned long rel_gfn = gfn - memslot->base_gfn;
2147 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2151 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2153 struct kvm_memory_slot *memslot;
2155 memslot = gfn_to_memslot(kvm, gfn);
2156 mark_page_dirty_in_slot(memslot, gfn);
2158 EXPORT_SYMBOL_GPL(mark_page_dirty);
2160 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2162 struct kvm_memory_slot *memslot;
2164 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2165 mark_page_dirty_in_slot(memslot, gfn);
2167 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2169 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2171 if (!vcpu->sigset_active)
2175 * This does a lockless modification of ->real_blocked, which is fine
2176 * because, only current can change ->real_blocked and all readers of
2177 * ->real_blocked don't care as long ->real_blocked is always a subset
2180 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
2183 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2185 if (!vcpu->sigset_active)
2188 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
2189 sigemptyset(¤t->real_blocked);
2192 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2194 unsigned int old, val, grow;
2196 old = val = vcpu->halt_poll_ns;
2197 grow = READ_ONCE(halt_poll_ns_grow);
2199 if (val == 0 && grow)
2204 if (val > halt_poll_ns)
2207 vcpu->halt_poll_ns = val;
2208 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2211 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2213 unsigned int old, val, shrink;
2215 old = val = vcpu->halt_poll_ns;
2216 shrink = READ_ONCE(halt_poll_ns_shrink);
2222 vcpu->halt_poll_ns = val;
2223 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2226 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2228 if (kvm_arch_vcpu_runnable(vcpu)) {
2229 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2232 if (kvm_cpu_has_pending_timer(vcpu))
2234 if (signal_pending(current))
2241 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2243 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2246 DECLARE_SWAITQUEUE(wait);
2247 bool waited = false;
2250 start = cur = ktime_get();
2251 if (vcpu->halt_poll_ns) {
2252 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2254 ++vcpu->stat.halt_attempted_poll;
2257 * This sets KVM_REQ_UNHALT if an interrupt
2260 if (kvm_vcpu_check_block(vcpu) < 0) {
2261 ++vcpu->stat.halt_successful_poll;
2262 if (!vcpu_valid_wakeup(vcpu))
2263 ++vcpu->stat.halt_poll_invalid;
2267 } while (single_task_running() && ktime_before(cur, stop));
2270 kvm_arch_vcpu_blocking(vcpu);
2273 prepare_to_swait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2275 if (kvm_vcpu_check_block(vcpu) < 0)
2282 finish_swait(&vcpu->wq, &wait);
2285 kvm_arch_vcpu_unblocking(vcpu);
2287 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2289 if (!vcpu_valid_wakeup(vcpu))
2290 shrink_halt_poll_ns(vcpu);
2291 else if (halt_poll_ns) {
2292 if (block_ns <= vcpu->halt_poll_ns)
2294 /* we had a long block, shrink polling */
2295 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2296 shrink_halt_poll_ns(vcpu);
2297 /* we had a short halt and our poll time is too small */
2298 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2299 block_ns < halt_poll_ns)
2300 grow_halt_poll_ns(vcpu);
2302 vcpu->halt_poll_ns = 0;
2304 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2305 kvm_arch_vcpu_block_finish(vcpu);
2307 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2309 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2311 struct swait_queue_head *wqp;
2313 wqp = kvm_arch_vcpu_wq(vcpu);
2314 if (swq_has_sleeper(wqp)) {
2316 ++vcpu->stat.halt_wakeup;
2322 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2326 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2328 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2331 int cpu = vcpu->cpu;
2333 if (kvm_vcpu_wake_up(vcpu))
2337 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2338 if (kvm_arch_vcpu_should_kick(vcpu))
2339 smp_send_reschedule(cpu);
2342 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2343 #endif /* !CONFIG_S390 */
2345 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2348 struct task_struct *task = NULL;
2352 pid = rcu_dereference(target->pid);
2354 task = get_pid_task(pid, PIDTYPE_PID);
2358 ret = yield_to(task, 1);
2359 put_task_struct(task);
2363 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2366 * Helper that checks whether a VCPU is eligible for directed yield.
2367 * Most eligible candidate to yield is decided by following heuristics:
2369 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2370 * (preempted lock holder), indicated by @in_spin_loop.
2371 * Set at the beiginning and cleared at the end of interception/PLE handler.
2373 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2374 * chance last time (mostly it has become eligible now since we have probably
2375 * yielded to lockholder in last iteration. This is done by toggling
2376 * @dy_eligible each time a VCPU checked for eligibility.)
2378 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2379 * to preempted lock-holder could result in wrong VCPU selection and CPU
2380 * burning. Giving priority for a potential lock-holder increases lock
2383 * Since algorithm is based on heuristics, accessing another VCPU data without
2384 * locking does not harm. It may result in trying to yield to same VCPU, fail
2385 * and continue with next VCPU and so on.
2387 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2389 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2392 eligible = !vcpu->spin_loop.in_spin_loop ||
2393 vcpu->spin_loop.dy_eligible;
2395 if (vcpu->spin_loop.in_spin_loop)
2396 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2405 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2406 * a vcpu_load/vcpu_put pair. However, for most architectures
2407 * kvm_arch_vcpu_runnable does not require vcpu_load.
2409 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2411 return kvm_arch_vcpu_runnable(vcpu);
2414 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2416 if (kvm_arch_dy_runnable(vcpu))
2419 #ifdef CONFIG_KVM_ASYNC_PF
2420 if (!list_empty_careful(&vcpu->async_pf.done))
2427 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
2429 struct kvm *kvm = me->kvm;
2430 struct kvm_vcpu *vcpu;
2431 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2437 kvm_vcpu_set_in_spin_loop(me, true);
2439 * We boost the priority of a VCPU that is runnable but not
2440 * currently running, because it got preempted by something
2441 * else and called schedule in __vcpu_run. Hopefully that
2442 * VCPU is holding the lock that we need and will release it.
2443 * We approximate round-robin by starting at the last boosted VCPU.
2445 for (pass = 0; pass < 2 && !yielded && try; pass++) {
2446 kvm_for_each_vcpu(i, vcpu, kvm) {
2447 if (!pass && i <= last_boosted_vcpu) {
2448 i = last_boosted_vcpu;
2450 } else if (pass && i > last_boosted_vcpu)
2452 if (!ACCESS_ONCE(vcpu->preempted))
2456 if (swait_active(&vcpu->wq) && !vcpu_dy_runnable(vcpu))
2458 if (yield_to_kernel_mode && !kvm_arch_vcpu_in_kernel(vcpu))
2460 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2463 yielded = kvm_vcpu_yield_to(vcpu);
2465 kvm->last_boosted_vcpu = i;
2467 } else if (yielded < 0) {
2474 kvm_vcpu_set_in_spin_loop(me, false);
2476 /* Ensure vcpu is not eligible during next spinloop */
2477 kvm_vcpu_set_dy_eligible(me, false);
2479 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2481 static int kvm_vcpu_fault(struct vm_fault *vmf)
2483 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
2486 if (vmf->pgoff == 0)
2487 page = virt_to_page(vcpu->run);
2489 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2490 page = virt_to_page(vcpu->arch.pio_data);
2492 #ifdef CONFIG_KVM_MMIO
2493 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2494 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2497 return kvm_arch_vcpu_fault(vcpu, vmf);
2503 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2504 .fault = kvm_vcpu_fault,
2507 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2509 vma->vm_ops = &kvm_vcpu_vm_ops;
2513 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2515 struct kvm_vcpu *vcpu = filp->private_data;
2517 debugfs_remove_recursive(vcpu->debugfs_dentry);
2518 kvm_put_kvm(vcpu->kvm);
2522 static struct file_operations kvm_vcpu_fops = {
2523 .release = kvm_vcpu_release,
2524 .unlocked_ioctl = kvm_vcpu_ioctl,
2525 #ifdef CONFIG_KVM_COMPAT
2526 .compat_ioctl = kvm_vcpu_compat_ioctl,
2528 .mmap = kvm_vcpu_mmap,
2529 .llseek = noop_llseek,
2533 * Allocates an inode for the vcpu.
2535 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2537 return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2540 static int kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
2542 char dir_name[ITOA_MAX_LEN * 2];
2545 if (!kvm_arch_has_vcpu_debugfs())
2548 if (!debugfs_initialized())
2551 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2552 vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
2553 vcpu->kvm->debugfs_dentry);
2554 if (!vcpu->debugfs_dentry)
2557 ret = kvm_arch_create_vcpu_debugfs(vcpu);
2559 debugfs_remove_recursive(vcpu->debugfs_dentry);
2567 * Creates some virtual cpus. Good luck creating more than one.
2569 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
2572 struct kvm_vcpu *vcpu;
2574 if (id >= KVM_MAX_VCPU_ID)
2577 mutex_lock(&kvm->lock);
2578 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
2579 mutex_unlock(&kvm->lock);
2583 kvm->created_vcpus++;
2584 mutex_unlock(&kvm->lock);
2586 vcpu = kvm_arch_vcpu_create(kvm, id);
2589 goto vcpu_decrement;
2592 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2594 r = kvm_arch_vcpu_setup(vcpu);
2598 r = kvm_create_vcpu_debugfs(vcpu);
2602 mutex_lock(&kvm->lock);
2603 if (kvm_get_vcpu_by_id(kvm, id)) {
2605 goto unlock_vcpu_destroy;
2608 BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
2610 /* Now it's all set up, let userspace reach it */
2612 r = create_vcpu_fd(vcpu);
2615 goto unlock_vcpu_destroy;
2618 kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
2621 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
2622 * before kvm->online_vcpu's incremented value.
2625 atomic_inc(&kvm->online_vcpus);
2627 mutex_unlock(&kvm->lock);
2628 kvm_arch_vcpu_postcreate(vcpu);
2631 unlock_vcpu_destroy:
2632 mutex_unlock(&kvm->lock);
2633 debugfs_remove_recursive(vcpu->debugfs_dentry);
2635 kvm_arch_vcpu_destroy(vcpu);
2637 mutex_lock(&kvm->lock);
2638 kvm->created_vcpus--;
2639 mutex_unlock(&kvm->lock);
2643 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2646 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2647 vcpu->sigset_active = 1;
2648 vcpu->sigset = *sigset;
2650 vcpu->sigset_active = 0;
2654 static long kvm_vcpu_ioctl(struct file *filp,
2655 unsigned int ioctl, unsigned long arg)
2657 struct kvm_vcpu *vcpu = filp->private_data;
2658 void __user *argp = (void __user *)arg;
2660 struct kvm_fpu *fpu = NULL;
2661 struct kvm_sregs *kvm_sregs = NULL;
2663 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_bugged)
2666 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2669 #if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS)
2671 * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
2672 * so vcpu_load() would break it.
2674 if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_S390_IRQ || ioctl == KVM_INTERRUPT)
2675 return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2679 r = vcpu_load(vcpu);
2688 oldpid = rcu_access_pointer(vcpu->pid);
2689 if (unlikely(oldpid != current->pids[PIDTYPE_PID].pid)) {
2690 /* The thread running this VCPU changed. */
2691 struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
2693 rcu_assign_pointer(vcpu->pid, newpid);
2698 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
2699 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
2702 case KVM_GET_REGS: {
2703 struct kvm_regs *kvm_regs;
2706 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
2709 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2713 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2720 case KVM_SET_REGS: {
2721 struct kvm_regs *kvm_regs;
2724 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2725 if (IS_ERR(kvm_regs)) {
2726 r = PTR_ERR(kvm_regs);
2729 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
2733 case KVM_GET_SREGS: {
2734 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
2738 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
2742 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
2747 case KVM_SET_SREGS: {
2748 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
2749 if (IS_ERR(kvm_sregs)) {
2750 r = PTR_ERR(kvm_sregs);
2754 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
2757 case KVM_GET_MP_STATE: {
2758 struct kvm_mp_state mp_state;
2760 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
2764 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
2769 case KVM_SET_MP_STATE: {
2770 struct kvm_mp_state mp_state;
2773 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
2775 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
2778 case KVM_TRANSLATE: {
2779 struct kvm_translation tr;
2782 if (copy_from_user(&tr, argp, sizeof(tr)))
2784 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
2788 if (copy_to_user(argp, &tr, sizeof(tr)))
2793 case KVM_SET_GUEST_DEBUG: {
2794 struct kvm_guest_debug dbg;
2797 if (copy_from_user(&dbg, argp, sizeof(dbg)))
2799 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
2802 case KVM_SET_SIGNAL_MASK: {
2803 struct kvm_signal_mask __user *sigmask_arg = argp;
2804 struct kvm_signal_mask kvm_sigmask;
2805 sigset_t sigset, *p;
2810 if (copy_from_user(&kvm_sigmask, argp,
2811 sizeof(kvm_sigmask)))
2814 if (kvm_sigmask.len != sizeof(sigset))
2817 if (copy_from_user(&sigset, sigmask_arg->sigset,
2822 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
2826 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2830 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
2834 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
2840 fpu = memdup_user(argp, sizeof(*fpu));
2846 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2850 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2859 #ifdef CONFIG_KVM_COMPAT
2860 static long kvm_vcpu_compat_ioctl(struct file *filp,
2861 unsigned int ioctl, unsigned long arg)
2863 struct kvm_vcpu *vcpu = filp->private_data;
2864 void __user *argp = compat_ptr(arg);
2867 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_bugged)
2871 case KVM_SET_SIGNAL_MASK: {
2872 struct kvm_signal_mask __user *sigmask_arg = argp;
2873 struct kvm_signal_mask kvm_sigmask;
2874 compat_sigset_t csigset;
2879 if (copy_from_user(&kvm_sigmask, argp,
2880 sizeof(kvm_sigmask)))
2883 if (kvm_sigmask.len != sizeof(csigset))
2886 if (copy_from_user(&csigset, sigmask_arg->sigset,
2889 sigset_from_compat(&sigset, &csigset);
2890 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2892 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
2896 r = kvm_vcpu_ioctl(filp, ioctl, arg);
2904 static int kvm_device_ioctl_attr(struct kvm_device *dev,
2905 int (*accessor)(struct kvm_device *dev,
2906 struct kvm_device_attr *attr),
2909 struct kvm_device_attr attr;
2914 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2917 return accessor(dev, &attr);
2920 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
2923 struct kvm_device *dev = filp->private_data;
2925 if (dev->kvm->mm != current->mm || dev->kvm->vm_bugged)
2929 case KVM_SET_DEVICE_ATTR:
2930 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
2931 case KVM_GET_DEVICE_ATTR:
2932 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
2933 case KVM_HAS_DEVICE_ATTR:
2934 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
2936 if (dev->ops->ioctl)
2937 return dev->ops->ioctl(dev, ioctl, arg);
2943 static int kvm_device_release(struct inode *inode, struct file *filp)
2945 struct kvm_device *dev = filp->private_data;
2946 struct kvm *kvm = dev->kvm;
2952 static const struct file_operations kvm_device_fops = {
2953 .unlocked_ioctl = kvm_device_ioctl,
2954 #ifdef CONFIG_KVM_COMPAT
2955 .compat_ioctl = kvm_device_ioctl,
2957 .release = kvm_device_release,
2960 struct kvm_device *kvm_device_from_filp(struct file *filp)
2962 if (filp->f_op != &kvm_device_fops)
2965 return filp->private_data;
2968 static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
2969 #ifdef CONFIG_KVM_MPIC
2970 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
2971 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
2975 int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
2977 if (type >= ARRAY_SIZE(kvm_device_ops_table))
2980 if (kvm_device_ops_table[type] != NULL)
2983 kvm_device_ops_table[type] = ops;
2987 void kvm_unregister_device_ops(u32 type)
2989 if (kvm_device_ops_table[type] != NULL)
2990 kvm_device_ops_table[type] = NULL;
2993 static int kvm_ioctl_create_device(struct kvm *kvm,
2994 struct kvm_create_device *cd)
2996 struct kvm_device_ops *ops = NULL;
2997 struct kvm_device *dev;
2998 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
3002 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3005 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3006 ops = kvm_device_ops_table[type];
3013 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3020 mutex_lock(&kvm->lock);
3021 ret = ops->create(dev, type);
3023 mutex_unlock(&kvm->lock);
3027 list_add(&dev->vm_node, &kvm->devices);
3028 mutex_unlock(&kvm->lock);
3034 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3037 mutex_lock(&kvm->lock);
3038 list_del(&dev->vm_node);
3039 mutex_unlock(&kvm->lock);
3048 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3051 case KVM_CAP_USER_MEMORY:
3052 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3053 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3054 case KVM_CAP_INTERNAL_ERROR_DATA:
3055 #ifdef CONFIG_HAVE_KVM_MSI
3056 case KVM_CAP_SIGNAL_MSI:
3058 #ifdef CONFIG_HAVE_KVM_IRQFD
3060 case KVM_CAP_IRQFD_RESAMPLE:
3062 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3063 case KVM_CAP_CHECK_EXTENSION_VM:
3065 #ifdef CONFIG_KVM_MMIO
3066 case KVM_CAP_COALESCED_MMIO:
3067 return KVM_COALESCED_MMIO_PAGE_OFFSET;
3069 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3070 case KVM_CAP_IRQ_ROUTING:
3071 return KVM_MAX_IRQ_ROUTES;
3073 #if KVM_ADDRESS_SPACE_NUM > 1
3074 case KVM_CAP_MULTI_ADDRESS_SPACE:
3075 return KVM_ADDRESS_SPACE_NUM;
3080 return kvm_vm_ioctl_check_extension(kvm, arg);
3083 static long kvm_vm_ioctl(struct file *filp,
3084 unsigned int ioctl, unsigned long arg)
3086 struct kvm *kvm = filp->private_data;
3087 void __user *argp = (void __user *)arg;
3090 if (kvm->mm != current->mm || kvm->vm_bugged)
3093 case KVM_CREATE_VCPU:
3094 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3096 case KVM_SET_USER_MEMORY_REGION: {
3097 struct kvm_userspace_memory_region kvm_userspace_mem;
3100 if (copy_from_user(&kvm_userspace_mem, argp,
3101 sizeof(kvm_userspace_mem)))
3104 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3107 case KVM_GET_DIRTY_LOG: {
3108 struct kvm_dirty_log log;
3111 if (copy_from_user(&log, argp, sizeof(log)))
3113 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3116 #ifdef CONFIG_KVM_MMIO
3117 case KVM_REGISTER_COALESCED_MMIO: {
3118 struct kvm_coalesced_mmio_zone zone;
3121 if (copy_from_user(&zone, argp, sizeof(zone)))
3123 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3126 case KVM_UNREGISTER_COALESCED_MMIO: {
3127 struct kvm_coalesced_mmio_zone zone;
3130 if (copy_from_user(&zone, argp, sizeof(zone)))
3132 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3137 struct kvm_irqfd data;
3140 if (copy_from_user(&data, argp, sizeof(data)))
3142 r = kvm_irqfd(kvm, &data);
3145 case KVM_IOEVENTFD: {
3146 struct kvm_ioeventfd data;
3149 if (copy_from_user(&data, argp, sizeof(data)))
3151 r = kvm_ioeventfd(kvm, &data);
3154 #ifdef CONFIG_HAVE_KVM_MSI
3155 case KVM_SIGNAL_MSI: {
3159 if (copy_from_user(&msi, argp, sizeof(msi)))
3161 r = kvm_send_userspace_msi(kvm, &msi);
3165 #ifdef __KVM_HAVE_IRQ_LINE
3166 case KVM_IRQ_LINE_STATUS:
3167 case KVM_IRQ_LINE: {
3168 struct kvm_irq_level irq_event;
3171 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3174 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3175 ioctl == KVM_IRQ_LINE_STATUS);
3180 if (ioctl == KVM_IRQ_LINE_STATUS) {
3181 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3189 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3190 case KVM_SET_GSI_ROUTING: {
3191 struct kvm_irq_routing routing;
3192 struct kvm_irq_routing __user *urouting;
3193 struct kvm_irq_routing_entry *entries = NULL;
3196 if (copy_from_user(&routing, argp, sizeof(routing)))
3199 if (!kvm_arch_can_set_irq_routing(kvm))
3201 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3207 entries = vmalloc(routing.nr * sizeof(*entries));
3212 if (copy_from_user(entries, urouting->entries,
3213 routing.nr * sizeof(*entries)))
3214 goto out_free_irq_routing;
3216 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3218 out_free_irq_routing:
3222 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3223 case KVM_CREATE_DEVICE: {
3224 struct kvm_create_device cd;
3227 if (copy_from_user(&cd, argp, sizeof(cd)))
3230 r = kvm_ioctl_create_device(kvm, &cd);
3235 if (copy_to_user(argp, &cd, sizeof(cd)))
3241 case KVM_CHECK_EXTENSION:
3242 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3245 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3251 #ifdef CONFIG_KVM_COMPAT
3252 struct compat_kvm_dirty_log {
3256 compat_uptr_t dirty_bitmap; /* one bit per page */
3261 static long kvm_vm_compat_ioctl(struct file *filp,
3262 unsigned int ioctl, unsigned long arg)
3264 struct kvm *kvm = filp->private_data;
3267 if (kvm->mm != current->mm || kvm->vm_bugged)
3270 case KVM_GET_DIRTY_LOG: {
3271 struct compat_kvm_dirty_log compat_log;
3272 struct kvm_dirty_log log;
3274 if (copy_from_user(&compat_log, (void __user *)arg,
3275 sizeof(compat_log)))
3277 log.slot = compat_log.slot;
3278 log.padding1 = compat_log.padding1;
3279 log.padding2 = compat_log.padding2;
3280 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3282 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3286 r = kvm_vm_ioctl(filp, ioctl, arg);
3292 static struct file_operations kvm_vm_fops = {
3293 .release = kvm_vm_release,
3294 .unlocked_ioctl = kvm_vm_ioctl,
3295 #ifdef CONFIG_KVM_COMPAT
3296 .compat_ioctl = kvm_vm_compat_ioctl,
3298 .llseek = noop_llseek,
3301 static int kvm_dev_ioctl_create_vm(unsigned long type)
3307 kvm = kvm_create_vm(type);
3309 return PTR_ERR(kvm);
3310 #ifdef CONFIG_KVM_MMIO
3311 r = kvm_coalesced_mmio_init(kvm);
3317 r = get_unused_fd_flags(O_CLOEXEC);
3322 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3326 return PTR_ERR(file);
3330 * Don't call kvm_put_kvm anymore at this point; file->f_op is
3331 * already set, with ->release() being kvm_vm_release(). In error
3332 * cases it will be called by the final fput(file) and will take
3333 * care of doing kvm_put_kvm(kvm).
3335 if (kvm_create_vm_debugfs(kvm, r) < 0) {
3340 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
3342 fd_install(r, file);
3346 static long kvm_dev_ioctl(struct file *filp,
3347 unsigned int ioctl, unsigned long arg)
3352 case KVM_GET_API_VERSION:
3355 r = KVM_API_VERSION;
3358 r = kvm_dev_ioctl_create_vm(arg);
3360 case KVM_CHECK_EXTENSION:
3361 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3363 case KVM_GET_VCPU_MMAP_SIZE:
3366 r = PAGE_SIZE; /* struct kvm_run */
3368 r += PAGE_SIZE; /* pio data page */
3370 #ifdef CONFIG_KVM_MMIO
3371 r += PAGE_SIZE; /* coalesced mmio ring page */
3374 case KVM_TRACE_ENABLE:
3375 case KVM_TRACE_PAUSE:
3376 case KVM_TRACE_DISABLE:
3380 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3386 static struct file_operations kvm_chardev_ops = {
3387 .unlocked_ioctl = kvm_dev_ioctl,
3388 .compat_ioctl = kvm_dev_ioctl,
3389 .llseek = noop_llseek,
3392 static struct miscdevice kvm_dev = {
3398 static void hardware_enable_nolock(void *junk)
3400 int cpu = raw_smp_processor_id();
3403 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3406 cpumask_set_cpu(cpu, cpus_hardware_enabled);
3408 r = kvm_arch_hardware_enable();
3411 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3412 atomic_inc(&hardware_enable_failed);
3413 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3417 static int kvm_starting_cpu(unsigned int cpu)
3419 raw_spin_lock(&kvm_count_lock);
3420 if (kvm_usage_count)
3421 hardware_enable_nolock(NULL);
3422 raw_spin_unlock(&kvm_count_lock);
3426 static void hardware_disable_nolock(void *junk)
3428 int cpu = raw_smp_processor_id();
3430 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3432 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3433 kvm_arch_hardware_disable();
3436 static int kvm_dying_cpu(unsigned int cpu)
3438 raw_spin_lock(&kvm_count_lock);
3439 if (kvm_usage_count)
3440 hardware_disable_nolock(NULL);
3441 raw_spin_unlock(&kvm_count_lock);
3445 static void hardware_disable_all_nolock(void)
3447 BUG_ON(!kvm_usage_count);
3450 if (!kvm_usage_count)
3451 on_each_cpu(hardware_disable_nolock, NULL, 1);
3454 static void hardware_disable_all(void)
3456 raw_spin_lock(&kvm_count_lock);
3457 hardware_disable_all_nolock();
3458 raw_spin_unlock(&kvm_count_lock);
3461 static int hardware_enable_all(void)
3465 raw_spin_lock(&kvm_count_lock);
3468 if (kvm_usage_count == 1) {
3469 atomic_set(&hardware_enable_failed, 0);
3470 on_each_cpu(hardware_enable_nolock, NULL, 1);
3472 if (atomic_read(&hardware_enable_failed)) {
3473 hardware_disable_all_nolock();
3478 raw_spin_unlock(&kvm_count_lock);
3483 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3487 * Some (well, at least mine) BIOSes hang on reboot if
3490 * And Intel TXT required VMX off for all cpu when system shutdown.
3492 pr_info("kvm: exiting hardware virtualization\n");
3493 kvm_rebooting = true;
3494 on_each_cpu(hardware_disable_nolock, NULL, 1);
3498 static struct notifier_block kvm_reboot_notifier = {
3499 .notifier_call = kvm_reboot,
3503 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3507 for (i = 0; i < bus->dev_count; i++) {
3508 struct kvm_io_device *pos = bus->range[i].dev;
3510 kvm_iodevice_destructor(pos);
3515 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
3516 const struct kvm_io_range *r2)
3518 gpa_t addr1 = r1->addr;
3519 gpa_t addr2 = r2->addr;
3524 /* If r2->len == 0, match the exact address. If r2->len != 0,
3525 * accept any overlapping write. Any order is acceptable for
3526 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3527 * we process all of them.
3540 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3542 return kvm_io_bus_cmp(p1, p2);
3545 static int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
3546 gpa_t addr, int len)
3548 bus->range[bus->dev_count++] = (struct kvm_io_range) {
3554 sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
3555 kvm_io_bus_sort_cmp, NULL);
3560 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
3561 gpa_t addr, int len)
3563 struct kvm_io_range *range, key;
3566 key = (struct kvm_io_range) {
3571 range = bsearch(&key, bus->range, bus->dev_count,
3572 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3576 off = range - bus->range;
3578 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
3584 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3585 struct kvm_io_range *range, const void *val)
3589 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3593 while (idx < bus->dev_count &&
3594 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3595 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
3604 /* kvm_io_bus_write - called under kvm->slots_lock */
3605 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3606 int len, const void *val)
3608 struct kvm_io_bus *bus;
3609 struct kvm_io_range range;
3612 range = (struct kvm_io_range) {
3617 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3620 r = __kvm_io_bus_write(vcpu, bus, &range, val);
3621 return r < 0 ? r : 0;
3624 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
3625 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
3626 gpa_t addr, int len, const void *val, long cookie)
3628 struct kvm_io_bus *bus;
3629 struct kvm_io_range range;
3631 range = (struct kvm_io_range) {
3636 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3640 /* First try the device referenced by cookie. */
3641 if ((cookie >= 0) && (cookie < bus->dev_count) &&
3642 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
3643 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
3648 * cookie contained garbage; fall back to search and return the
3649 * correct cookie value.
3651 return __kvm_io_bus_write(vcpu, bus, &range, val);
3654 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3655 struct kvm_io_range *range, void *val)
3659 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3663 while (idx < bus->dev_count &&
3664 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3665 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
3673 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
3675 /* kvm_io_bus_read - called under kvm->slots_lock */
3676 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3679 struct kvm_io_bus *bus;
3680 struct kvm_io_range range;
3683 range = (struct kvm_io_range) {
3688 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3691 r = __kvm_io_bus_read(vcpu, bus, &range, val);
3692 return r < 0 ? r : 0;
3696 /* Caller must hold slots_lock. */
3697 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3698 int len, struct kvm_io_device *dev)
3700 struct kvm_io_bus *new_bus, *bus;
3702 bus = kvm_get_bus(kvm, bus_idx);
3706 /* exclude ioeventfd which is limited by maximum fd */
3707 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
3710 new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count + 1) *
3711 sizeof(struct kvm_io_range)), GFP_KERNEL);
3714 memcpy(new_bus, bus, sizeof(*bus) + (bus->dev_count *
3715 sizeof(struct kvm_io_range)));
3716 kvm_io_bus_insert_dev(new_bus, dev, addr, len);
3717 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3718 synchronize_srcu_expedited(&kvm->srcu);
3724 /* Caller must hold slots_lock. */
3725 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3726 struct kvm_io_device *dev)
3729 struct kvm_io_bus *new_bus, *bus;
3731 bus = kvm_get_bus(kvm, bus_idx);
3735 for (i = 0; i < bus->dev_count; i++)
3736 if (bus->range[i].dev == dev) {
3740 if (i == bus->dev_count)
3743 new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count - 1) *
3744 sizeof(struct kvm_io_range)), GFP_KERNEL);
3746 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3747 new_bus->dev_count--;
3748 memcpy(new_bus->range + i, bus->range + i + 1,
3749 (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
3751 pr_err("kvm: failed to shrink bus, removing it completely\n");
3752 for (j = 0; j < bus->dev_count; j++) {
3755 kvm_iodevice_destructor(bus->range[j].dev);
3759 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3760 synchronize_srcu_expedited(&kvm->srcu);
3765 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3768 struct kvm_io_bus *bus;
3769 int dev_idx, srcu_idx;
3770 struct kvm_io_device *iodev = NULL;
3772 srcu_idx = srcu_read_lock(&kvm->srcu);
3774 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3778 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
3782 iodev = bus->range[dev_idx].dev;
3785 srcu_read_unlock(&kvm->srcu, srcu_idx);
3789 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
3791 static int kvm_debugfs_open(struct inode *inode, struct file *file,
3792 int (*get)(void *, u64 *), int (*set)(void *, u64),
3795 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3798 /* The debugfs files are a reference to the kvm struct which
3799 * is still valid when kvm_destroy_vm is called.
3800 * To avoid the race between open and the removal of the debugfs
3801 * directory we test against the users count.
3803 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
3806 if (simple_attr_open(inode, file, get,
3807 stat_data->mode & S_IWUGO ? set : NULL,
3809 kvm_put_kvm(stat_data->kvm);
3816 static int kvm_debugfs_release(struct inode *inode, struct file *file)
3818 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3821 simple_attr_release(inode, file);
3822 kvm_put_kvm(stat_data->kvm);
3827 static int vm_stat_get_per_vm(void *data, u64 *val)
3829 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3831 *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
3836 static int vm_stat_clear_per_vm(void *data, u64 val)
3838 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3843 *(ulong *)((void *)stat_data->kvm + stat_data->offset) = 0;
3848 static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
3850 __simple_attr_check_format("%llu\n", 0ull);
3851 return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
3852 vm_stat_clear_per_vm, "%llu\n");
3855 static const struct file_operations vm_stat_get_per_vm_fops = {
3856 .owner = THIS_MODULE,
3857 .open = vm_stat_get_per_vm_open,
3858 .release = kvm_debugfs_release,
3859 .read = simple_attr_read,
3860 .write = simple_attr_write,
3861 .llseek = no_llseek,
3864 static int vcpu_stat_get_per_vm(void *data, u64 *val)
3867 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3868 struct kvm_vcpu *vcpu;
3872 kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3873 *val += *(u64 *)((void *)vcpu + stat_data->offset);
3878 static int vcpu_stat_clear_per_vm(void *data, u64 val)
3881 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3882 struct kvm_vcpu *vcpu;
3887 kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3888 *(u64 *)((void *)vcpu + stat_data->offset) = 0;
3893 static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
3895 __simple_attr_check_format("%llu\n", 0ull);
3896 return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
3897 vcpu_stat_clear_per_vm, "%llu\n");
3900 static const struct file_operations vcpu_stat_get_per_vm_fops = {
3901 .owner = THIS_MODULE,
3902 .open = vcpu_stat_get_per_vm_open,
3903 .release = kvm_debugfs_release,
3904 .read = simple_attr_read,
3905 .write = simple_attr_write,
3906 .llseek = no_llseek,
3909 static const struct file_operations *stat_fops_per_vm[] = {
3910 [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
3911 [KVM_STAT_VM] = &vm_stat_get_per_vm_fops,
3914 static int vm_stat_get(void *_offset, u64 *val)
3916 unsigned offset = (long)_offset;
3918 struct kvm_stat_data stat_tmp = {.offset = offset};
3922 mutex_lock(&kvm_lock);
3923 list_for_each_entry(kvm, &vm_list, vm_list) {
3925 vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3928 mutex_unlock(&kvm_lock);
3932 static int vm_stat_clear(void *_offset, u64 val)
3934 unsigned offset = (long)_offset;
3936 struct kvm_stat_data stat_tmp = {.offset = offset};
3941 mutex_lock(&kvm_lock);
3942 list_for_each_entry(kvm, &vm_list, vm_list) {
3944 vm_stat_clear_per_vm((void *)&stat_tmp, 0);
3946 mutex_unlock(&kvm_lock);
3951 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
3953 static int vcpu_stat_get(void *_offset, u64 *val)
3955 unsigned offset = (long)_offset;
3957 struct kvm_stat_data stat_tmp = {.offset = offset};
3961 mutex_lock(&kvm_lock);
3962 list_for_each_entry(kvm, &vm_list, vm_list) {
3964 vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3967 mutex_unlock(&kvm_lock);
3971 static int vcpu_stat_clear(void *_offset, u64 val)
3973 unsigned offset = (long)_offset;
3975 struct kvm_stat_data stat_tmp = {.offset = offset};
3980 mutex_lock(&kvm_lock);
3981 list_for_each_entry(kvm, &vm_list, vm_list) {
3983 vcpu_stat_clear_per_vm((void *)&stat_tmp, 0);
3985 mutex_unlock(&kvm_lock);
3990 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
3993 static const struct file_operations *stat_fops[] = {
3994 [KVM_STAT_VCPU] = &vcpu_stat_fops,
3995 [KVM_STAT_VM] = &vm_stat_fops,
3998 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4000 struct kobj_uevent_env *env;
4001 unsigned long long created, active;
4003 if (!kvm_dev.this_device || !kvm)
4006 mutex_lock(&kvm_lock);
4007 if (type == KVM_EVENT_CREATE_VM) {
4008 kvm_createvm_count++;
4010 } else if (type == KVM_EVENT_DESTROY_VM) {
4013 created = kvm_createvm_count;
4014 active = kvm_active_vms;
4015 mutex_unlock(&kvm_lock);
4017 env = kzalloc(sizeof(*env), GFP_KERNEL);
4021 add_uevent_var(env, "CREATED=%llu", created);
4022 add_uevent_var(env, "COUNT=%llu", active);
4024 if (type == KVM_EVENT_CREATE_VM) {
4025 add_uevent_var(env, "EVENT=create");
4026 kvm->userspace_pid = task_pid_nr(current);
4027 } else if (type == KVM_EVENT_DESTROY_VM) {
4028 add_uevent_var(env, "EVENT=destroy");
4030 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
4032 if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
4033 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL);
4036 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4038 add_uevent_var(env, "STATS_PATH=%s", tmp);
4042 /* no need for checks, since we are adding at most only 5 keys */
4043 env->envp[env->envp_idx++] = NULL;
4044 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4048 static int kvm_init_debug(void)
4051 struct kvm_stats_debugfs_item *p;
4053 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4054 if (kvm_debugfs_dir == NULL)
4057 kvm_debugfs_num_entries = 0;
4058 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
4059 int mode = p->mode ? p->mode : 0644;
4060 if (!debugfs_create_file(p->name, mode, kvm_debugfs_dir,
4061 (void *)(long)p->offset,
4062 stat_fops[p->kind]))
4069 debugfs_remove_recursive(kvm_debugfs_dir);
4074 static int kvm_suspend(void)
4076 if (kvm_usage_count)
4077 hardware_disable_nolock(NULL);
4081 static void kvm_resume(void)
4083 if (kvm_usage_count) {
4084 WARN_ON(raw_spin_is_locked(&kvm_count_lock));
4085 hardware_enable_nolock(NULL);
4089 static struct syscore_ops kvm_syscore_ops = {
4090 .suspend = kvm_suspend,
4091 .resume = kvm_resume,
4095 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4097 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4100 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4102 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4104 if (vcpu->preempted)
4105 vcpu->preempted = false;
4107 kvm_arch_sched_in(vcpu, cpu);
4109 kvm_arch_vcpu_load(vcpu, cpu);
4112 static void kvm_sched_out(struct preempt_notifier *pn,
4113 struct task_struct *next)
4115 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4117 if (current->state == TASK_RUNNING)
4118 vcpu->preempted = true;
4119 kvm_arch_vcpu_put(vcpu);
4122 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
4123 struct module *module)
4128 r = kvm_arch_init(opaque);
4133 * kvm_arch_init makes sure there's at most one caller
4134 * for architectures that support multiple implementations,
4135 * like intel and amd on x86.
4136 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4137 * conflicts in case kvm is already setup for another implementation.
4139 r = kvm_irqfd_init();
4143 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
4148 r = kvm_arch_hardware_setup();
4152 for_each_online_cpu(cpu) {
4153 smp_call_function_single(cpu,
4154 kvm_arch_check_processor_compat,
4160 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
4161 kvm_starting_cpu, kvm_dying_cpu);
4164 register_reboot_notifier(&kvm_reboot_notifier);
4166 /* A kmem cache lets us meet the alignment requirements of fx_save. */
4168 vcpu_align = __alignof__(struct kvm_vcpu);
4169 kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
4170 SLAB_ACCOUNT, NULL);
4171 if (!kvm_vcpu_cache) {
4176 r = kvm_async_pf_init();
4180 kvm_chardev_ops.owner = module;
4181 kvm_vm_fops.owner = module;
4182 kvm_vcpu_fops.owner = module;
4184 r = misc_register(&kvm_dev);
4186 pr_err("kvm: misc device register failed\n");
4190 register_syscore_ops(&kvm_syscore_ops);
4192 kvm_preempt_ops.sched_in = kvm_sched_in;
4193 kvm_preempt_ops.sched_out = kvm_sched_out;
4195 r = kvm_init_debug();
4197 pr_err("kvm: create debugfs files failed\n");
4201 r = kvm_vfio_ops_init();
4207 unregister_syscore_ops(&kvm_syscore_ops);
4208 misc_deregister(&kvm_dev);
4210 kvm_async_pf_deinit();
4212 kmem_cache_destroy(kvm_vcpu_cache);
4214 unregister_reboot_notifier(&kvm_reboot_notifier);
4215 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4218 kvm_arch_hardware_unsetup();
4220 free_cpumask_var(cpus_hardware_enabled);
4228 EXPORT_SYMBOL_GPL(kvm_init);
4232 debugfs_remove_recursive(kvm_debugfs_dir);
4233 misc_deregister(&kvm_dev);
4234 kmem_cache_destroy(kvm_vcpu_cache);
4235 kvm_async_pf_deinit();
4236 unregister_syscore_ops(&kvm_syscore_ops);
4237 unregister_reboot_notifier(&kvm_reboot_notifier);
4238 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4239 on_each_cpu(hardware_disable_nolock, NULL, 1);
4240 kvm_arch_hardware_unsetup();
4243 free_cpumask_var(cpus_hardware_enabled);
4244 kvm_vfio_ops_exit();
4246 EXPORT_SYMBOL_GPL(kvm_exit);
4248 struct kvm_vm_worker_thread_context {
4250 struct task_struct *parent;
4251 struct completion init_done;
4252 kvm_vm_thread_fn_t thread_fn;
4257 static int kvm_vm_worker_thread(void *context)
4260 * The init_context is allocated on the stack of the parent thread, so
4261 * we have to locally copy anything that is needed beyond initialization
4263 struct kvm_vm_worker_thread_context *init_context = context;
4264 struct kvm *kvm = init_context->kvm;
4265 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4266 uintptr_t data = init_context->data;
4269 err = kthread_park(current);
4270 /* kthread_park(current) is never supposed to return an error */
4275 err = cgroup_attach_task_all(init_context->parent, current);
4277 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4282 set_user_nice(current, task_nice(init_context->parent));
4285 init_context->err = err;
4286 complete(&init_context->init_done);
4287 init_context = NULL;
4292 /* Wait to be woken up by the spawner before proceeding. */
4295 if (!kthread_should_stop())
4296 err = thread_fn(kvm, data);
4301 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4302 uintptr_t data, const char *name,
4303 struct task_struct **thread_ptr)
4305 struct kvm_vm_worker_thread_context init_context = {};
4306 struct task_struct *thread;
4309 init_context.kvm = kvm;
4310 init_context.parent = current;
4311 init_context.thread_fn = thread_fn;
4312 init_context.data = data;
4313 init_completion(&init_context.init_done);
4315 thread = kthread_run(kvm_vm_worker_thread, &init_context,
4316 "%s-%d", name, task_pid_nr(current));
4318 return PTR_ERR(thread);
4320 /* kthread_run is never supposed to return NULL */
4321 WARN_ON(thread == NULL);
4323 wait_for_completion(&init_context.init_done);
4325 if (!init_context.err)
4326 *thread_ptr = thread;
4328 return init_context.err;