KVM: Properly check if "page" is valid in kvm_vcpu_unmap
[linux/fpc-iii.git] / virt / kvm / kvm_main.c
blob33b288469c70c785683e38c4b0ba89f0d0c6dd30
1 /*
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.
10 * Authors:
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>
26 #include <linux/mm.h>
27 #include <linux/miscdevice.h>
28 #include <linux/vmalloc.h>
29 #include <linux/reboot.h>
30 #include <linux/debugfs.h>
31 #include <linux/highmem.h>
32 #include <linux/file.h>
33 #include <linux/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>
55 #include <linux/io.h>
57 #include <asm/processor.h>
58 #include <asm/ioctl.h>
59 #include <linux/uaccess.h>
60 #include <asm/pgtable.h>
62 #include "coalesced_mmio.h"
63 #include "async_pf.h"
64 #include "vfio.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);
91 * Ordering of locks:
93 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
96 DEFINE_MUTEX(kvm_lock);
97 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
98 LIST_HEAD(vm_list);
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 long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
116 unsigned long arg);
117 #ifdef CONFIG_KVM_COMPAT
118 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
119 unsigned long arg);
120 #define KVM_COMPAT(c) .compat_ioctl = (c)
121 #else
122 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
123 unsigned long arg) { return -EINVAL; }
124 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl
125 #endif
126 static int hardware_enable_all(void);
127 static void hardware_disable_all(void);
129 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
131 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
133 __visible bool kvm_rebooting;
134 EXPORT_SYMBOL_GPL(kvm_rebooting);
136 static bool largepages_enabled = true;
138 #define KVM_EVENT_CREATE_VM 0
139 #define KVM_EVENT_DESTROY_VM 1
140 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
141 static unsigned long long kvm_createvm_count;
142 static unsigned long long kvm_active_vms;
144 __weak int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
145 unsigned long start, unsigned long end, bool blockable)
147 return 0;
150 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
153 * The metadata used by is_zone_device_page() to determine whether or
154 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
155 * the device has been pinned, e.g. by get_user_pages(). WARN if the
156 * page_count() is zero to help detect bad usage of this helper.
158 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
159 return false;
161 return is_zone_device_page(pfn_to_page(pfn));
164 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
167 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
168 * perspective they are "normal" pages, albeit with slightly different
169 * usage rules.
171 if (pfn_valid(pfn))
172 return PageReserved(pfn_to_page(pfn)) &&
173 !kvm_is_zone_device_pfn(pfn);
175 return true;
179 * Switches to specified vcpu, until a matching vcpu_put()
181 void vcpu_load(struct kvm_vcpu *vcpu)
183 int cpu = get_cpu();
184 preempt_notifier_register(&vcpu->preempt_notifier);
185 kvm_arch_vcpu_load(vcpu, cpu);
186 put_cpu();
188 EXPORT_SYMBOL_GPL(vcpu_load);
190 void vcpu_put(struct kvm_vcpu *vcpu)
192 preempt_disable();
193 kvm_arch_vcpu_put(vcpu);
194 preempt_notifier_unregister(&vcpu->preempt_notifier);
195 preempt_enable();
197 EXPORT_SYMBOL_GPL(vcpu_put);
199 /* TODO: merge with kvm_arch_vcpu_should_kick */
200 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
202 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
205 * We need to wait for the VCPU to reenable interrupts and get out of
206 * READING_SHADOW_PAGE_TABLES mode.
208 if (req & KVM_REQUEST_WAIT)
209 return mode != OUTSIDE_GUEST_MODE;
212 * Need to kick a running VCPU, but otherwise there is nothing to do.
214 return mode == IN_GUEST_MODE;
217 static void ack_flush(void *_completed)
221 static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
223 if (unlikely(!cpus))
224 cpus = cpu_online_mask;
226 if (cpumask_empty(cpus))
227 return false;
229 smp_call_function_many(cpus, ack_flush, NULL, wait);
230 return true;
233 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
234 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
236 int i, cpu, me;
237 struct kvm_vcpu *vcpu;
238 bool called;
240 me = get_cpu();
242 kvm_for_each_vcpu(i, vcpu, kvm) {
243 if (!test_bit(i, vcpu_bitmap))
244 continue;
246 kvm_make_request(req, vcpu);
247 cpu = vcpu->cpu;
249 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
250 continue;
252 if (tmp != NULL && cpu != -1 && cpu != me &&
253 kvm_request_needs_ipi(vcpu, req))
254 __cpumask_set_cpu(cpu, tmp);
257 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
258 put_cpu();
260 return called;
263 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
265 cpumask_var_t cpus;
266 bool called;
267 static unsigned long vcpu_bitmap[BITS_TO_LONGS(KVM_MAX_VCPUS)]
268 = {[0 ... BITS_TO_LONGS(KVM_MAX_VCPUS)-1] = ULONG_MAX};
270 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
272 called = kvm_make_vcpus_request_mask(kvm, req, vcpu_bitmap, cpus);
274 free_cpumask_var(cpus);
275 return called;
278 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
279 void kvm_flush_remote_tlbs(struct kvm *kvm)
282 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
283 * kvm_make_all_cpus_request.
285 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
288 * We want to publish modifications to the page tables before reading
289 * mode. Pairs with a memory barrier in arch-specific code.
290 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
291 * and smp_mb in walk_shadow_page_lockless_begin/end.
292 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
294 * There is already an smp_mb__after_atomic() before
295 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
296 * barrier here.
298 if (!kvm_arch_flush_remote_tlb(kvm)
299 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
300 ++kvm->stat.remote_tlb_flush;
301 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
303 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
304 #endif
306 void kvm_reload_remote_mmus(struct kvm *kvm)
308 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
311 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
313 struct page *page;
314 int r;
316 mutex_init(&vcpu->mutex);
317 vcpu->cpu = -1;
318 vcpu->kvm = kvm;
319 vcpu->vcpu_id = id;
320 vcpu->pid = NULL;
321 init_swait_queue_head(&vcpu->wq);
322 kvm_async_pf_vcpu_init(vcpu);
324 vcpu->pre_pcpu = -1;
325 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
327 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
328 if (!page) {
329 r = -ENOMEM;
330 goto fail;
332 vcpu->run = page_address(page);
334 kvm_vcpu_set_in_spin_loop(vcpu, false);
335 kvm_vcpu_set_dy_eligible(vcpu, false);
336 vcpu->preempted = false;
338 r = kvm_arch_vcpu_init(vcpu);
339 if (r < 0)
340 goto fail_free_run;
341 return 0;
343 fail_free_run:
344 free_page((unsigned long)vcpu->run);
345 fail:
346 return r;
348 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
350 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
353 * no need for rcu_read_lock as VCPU_RUN is the only place that
354 * will change the vcpu->pid pointer and on uninit all file
355 * descriptors are already gone.
357 put_pid(rcu_dereference_protected(vcpu->pid, 1));
358 kvm_arch_vcpu_uninit(vcpu);
359 free_page((unsigned long)vcpu->run);
361 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
363 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
364 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
366 return container_of(mn, struct kvm, mmu_notifier);
369 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
370 struct mm_struct *mm,
371 unsigned long address,
372 pte_t pte)
374 struct kvm *kvm = mmu_notifier_to_kvm(mn);
375 int idx;
377 idx = srcu_read_lock(&kvm->srcu);
378 spin_lock(&kvm->mmu_lock);
379 kvm->mmu_notifier_seq++;
380 kvm_set_spte_hva(kvm, address, pte);
381 spin_unlock(&kvm->mmu_lock);
382 srcu_read_unlock(&kvm->srcu, idx);
385 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
386 struct mm_struct *mm,
387 unsigned long start,
388 unsigned long end,
389 bool blockable)
391 struct kvm *kvm = mmu_notifier_to_kvm(mn);
392 int need_tlb_flush = 0, idx;
393 int ret;
395 idx = srcu_read_lock(&kvm->srcu);
396 spin_lock(&kvm->mmu_lock);
398 * The count increase must become visible at unlock time as no
399 * spte can be established without taking the mmu_lock and
400 * count is also read inside the mmu_lock critical section.
402 kvm->mmu_notifier_count++;
403 need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
404 need_tlb_flush |= kvm->tlbs_dirty;
405 /* we've to flush the tlb before the pages can be freed */
406 if (need_tlb_flush)
407 kvm_flush_remote_tlbs(kvm);
409 spin_unlock(&kvm->mmu_lock);
411 ret = kvm_arch_mmu_notifier_invalidate_range(kvm, start, end, blockable);
413 srcu_read_unlock(&kvm->srcu, idx);
415 return ret;
418 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
419 struct mm_struct *mm,
420 unsigned long start,
421 unsigned long end)
423 struct kvm *kvm = mmu_notifier_to_kvm(mn);
425 spin_lock(&kvm->mmu_lock);
427 * This sequence increase will notify the kvm page fault that
428 * the page that is going to be mapped in the spte could have
429 * been freed.
431 kvm->mmu_notifier_seq++;
432 smp_wmb();
434 * The above sequence increase must be visible before the
435 * below count decrease, which is ensured by the smp_wmb above
436 * in conjunction with the smp_rmb in mmu_notifier_retry().
438 kvm->mmu_notifier_count--;
439 spin_unlock(&kvm->mmu_lock);
441 BUG_ON(kvm->mmu_notifier_count < 0);
444 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
445 struct mm_struct *mm,
446 unsigned long start,
447 unsigned long end)
449 struct kvm *kvm = mmu_notifier_to_kvm(mn);
450 int young, idx;
452 idx = srcu_read_lock(&kvm->srcu);
453 spin_lock(&kvm->mmu_lock);
455 young = kvm_age_hva(kvm, start, end);
456 if (young)
457 kvm_flush_remote_tlbs(kvm);
459 spin_unlock(&kvm->mmu_lock);
460 srcu_read_unlock(&kvm->srcu, idx);
462 return young;
465 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
466 struct mm_struct *mm,
467 unsigned long start,
468 unsigned long end)
470 struct kvm *kvm = mmu_notifier_to_kvm(mn);
471 int young, idx;
473 idx = srcu_read_lock(&kvm->srcu);
474 spin_lock(&kvm->mmu_lock);
476 * Even though we do not flush TLB, this will still adversely
477 * affect performance on pre-Haswell Intel EPT, where there is
478 * no EPT Access Bit to clear so that we have to tear down EPT
479 * tables instead. If we find this unacceptable, we can always
480 * add a parameter to kvm_age_hva so that it effectively doesn't
481 * do anything on clear_young.
483 * Also note that currently we never issue secondary TLB flushes
484 * from clear_young, leaving this job up to the regular system
485 * cadence. If we find this inaccurate, we might come up with a
486 * more sophisticated heuristic later.
488 young = kvm_age_hva(kvm, start, end);
489 spin_unlock(&kvm->mmu_lock);
490 srcu_read_unlock(&kvm->srcu, idx);
492 return young;
495 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
496 struct mm_struct *mm,
497 unsigned long address)
499 struct kvm *kvm = mmu_notifier_to_kvm(mn);
500 int young, idx;
502 idx = srcu_read_lock(&kvm->srcu);
503 spin_lock(&kvm->mmu_lock);
504 young = kvm_test_age_hva(kvm, address);
505 spin_unlock(&kvm->mmu_lock);
506 srcu_read_unlock(&kvm->srcu, idx);
508 return young;
511 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
512 struct mm_struct *mm)
514 struct kvm *kvm = mmu_notifier_to_kvm(mn);
515 int idx;
517 idx = srcu_read_lock(&kvm->srcu);
518 kvm_arch_flush_shadow_all(kvm);
519 srcu_read_unlock(&kvm->srcu, idx);
522 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
523 .flags = MMU_INVALIDATE_DOES_NOT_BLOCK,
524 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
525 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
526 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
527 .clear_young = kvm_mmu_notifier_clear_young,
528 .test_young = kvm_mmu_notifier_test_young,
529 .change_pte = kvm_mmu_notifier_change_pte,
530 .release = kvm_mmu_notifier_release,
533 static int kvm_init_mmu_notifier(struct kvm *kvm)
535 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
536 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
539 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
541 static int kvm_init_mmu_notifier(struct kvm *kvm)
543 return 0;
546 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
548 static struct kvm_memslots *kvm_alloc_memslots(void)
550 int i;
551 struct kvm_memslots *slots;
553 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
554 if (!slots)
555 return NULL;
557 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
558 slots->id_to_index[i] = slots->memslots[i].id = i;
560 return slots;
563 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
565 if (!memslot->dirty_bitmap)
566 return;
568 kvfree(memslot->dirty_bitmap);
569 memslot->dirty_bitmap = NULL;
573 * Free any memory in @free but not in @dont.
575 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
576 struct kvm_memory_slot *dont)
578 if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
579 kvm_destroy_dirty_bitmap(free);
581 kvm_arch_free_memslot(kvm, free, dont);
583 free->npages = 0;
586 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
588 struct kvm_memory_slot *memslot;
590 if (!slots)
591 return;
593 kvm_for_each_memslot(memslot, slots)
594 kvm_free_memslot(kvm, memslot, NULL);
596 kvfree(slots);
599 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
601 int i;
603 if (!kvm->debugfs_dentry)
604 return;
606 debugfs_remove_recursive(kvm->debugfs_dentry);
608 if (kvm->debugfs_stat_data) {
609 for (i = 0; i < kvm_debugfs_num_entries; i++)
610 kfree(kvm->debugfs_stat_data[i]);
611 kfree(kvm->debugfs_stat_data);
615 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
617 char dir_name[ITOA_MAX_LEN * 2];
618 struct kvm_stat_data *stat_data;
619 struct kvm_stats_debugfs_item *p;
621 if (!debugfs_initialized())
622 return 0;
624 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
625 kvm->debugfs_dentry = debugfs_create_dir(dir_name, kvm_debugfs_dir);
627 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
628 sizeof(*kvm->debugfs_stat_data),
629 GFP_KERNEL);
630 if (!kvm->debugfs_stat_data)
631 return -ENOMEM;
633 for (p = debugfs_entries; p->name; p++) {
634 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL);
635 if (!stat_data)
636 return -ENOMEM;
638 stat_data->kvm = kvm;
639 stat_data->offset = p->offset;
640 stat_data->mode = p->mode ? p->mode : 0644;
641 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
642 debugfs_create_file(p->name, stat_data->mode, kvm->debugfs_dentry,
643 stat_data, stat_fops_per_vm[p->kind]);
645 return 0;
649 * Called after the VM is otherwise initialized, but just before adding it to
650 * the vm_list.
652 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
654 return 0;
658 * Called just after removing the VM from the vm_list, but before doing any
659 * other destruction.
661 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
665 static struct kvm *kvm_create_vm(unsigned long type)
667 int r, i;
668 struct kvm *kvm = kvm_arch_alloc_vm();
670 if (!kvm)
671 return ERR_PTR(-ENOMEM);
673 spin_lock_init(&kvm->mmu_lock);
674 mmgrab(current->mm);
675 kvm->mm = current->mm;
676 kvm_eventfd_init(kvm);
677 mutex_init(&kvm->lock);
678 mutex_init(&kvm->irq_lock);
679 mutex_init(&kvm->slots_lock);
680 refcount_set(&kvm->users_count, 1);
681 INIT_LIST_HEAD(&kvm->devices);
683 r = kvm_arch_init_vm(kvm, type);
684 if (r)
685 goto out_err_no_disable;
687 r = hardware_enable_all();
688 if (r)
689 goto out_err_no_disable;
691 #ifdef CONFIG_HAVE_KVM_IRQFD
692 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
693 #endif
695 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
697 r = -ENOMEM;
698 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
699 struct kvm_memslots *slots = kvm_alloc_memslots();
700 if (!slots)
701 goto out_err_no_srcu;
703 * Generations must be different for each address space.
704 * Init kvm generation close to the maximum to easily test the
705 * code of handling generation number wrap-around.
707 slots->generation = i * 2 - 150;
708 rcu_assign_pointer(kvm->memslots[i], slots);
711 if (init_srcu_struct(&kvm->srcu))
712 goto out_err_no_srcu;
713 if (init_srcu_struct(&kvm->irq_srcu))
714 goto out_err_no_irq_srcu;
715 for (i = 0; i < KVM_NR_BUSES; i++) {
716 rcu_assign_pointer(kvm->buses[i],
717 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL));
718 if (!kvm->buses[i])
719 goto out_err_no_mmu_notifier;
722 r = kvm_init_mmu_notifier(kvm);
723 if (r)
724 goto out_err_no_mmu_notifier;
726 r = kvm_arch_post_init_vm(kvm);
727 if (r)
728 goto out_err;
730 mutex_lock(&kvm_lock);
731 list_add(&kvm->vm_list, &vm_list);
732 mutex_unlock(&kvm_lock);
734 preempt_notifier_inc();
736 return kvm;
738 out_err:
739 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
740 if (kvm->mmu_notifier.ops)
741 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
742 #endif
743 out_err_no_mmu_notifier:
744 cleanup_srcu_struct(&kvm->irq_srcu);
745 out_err_no_irq_srcu:
746 cleanup_srcu_struct(&kvm->srcu);
747 out_err_no_srcu:
748 hardware_disable_all();
749 out_err_no_disable:
750 refcount_set(&kvm->users_count, 0);
751 for (i = 0; i < KVM_NR_BUSES; i++)
752 kfree(kvm_get_bus(kvm, i));
753 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
754 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
755 kvm_arch_free_vm(kvm);
756 mmdrop(current->mm);
757 return ERR_PTR(r);
760 static void kvm_destroy_devices(struct kvm *kvm)
762 struct kvm_device *dev, *tmp;
765 * We do not need to take the kvm->lock here, because nobody else
766 * has a reference to the struct kvm at this point and therefore
767 * cannot access the devices list anyhow.
769 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
770 list_del(&dev->vm_node);
771 dev->ops->destroy(dev);
775 static void kvm_destroy_vm(struct kvm *kvm)
777 int i;
778 struct mm_struct *mm = kvm->mm;
780 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
781 kvm_destroy_vm_debugfs(kvm);
782 kvm_arch_sync_events(kvm);
783 mutex_lock(&kvm_lock);
784 list_del(&kvm->vm_list);
785 mutex_unlock(&kvm_lock);
786 kvm_arch_pre_destroy_vm(kvm);
788 kvm_free_irq_routing(kvm);
789 for (i = 0; i < KVM_NR_BUSES; i++) {
790 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
792 if (bus)
793 kvm_io_bus_destroy(bus);
794 kvm->buses[i] = NULL;
796 kvm_coalesced_mmio_free(kvm);
797 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
798 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
799 #else
800 kvm_arch_flush_shadow_all(kvm);
801 #endif
802 kvm_arch_destroy_vm(kvm);
803 kvm_destroy_devices(kvm);
804 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
805 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
806 cleanup_srcu_struct(&kvm->irq_srcu);
807 cleanup_srcu_struct(&kvm->srcu);
808 kvm_arch_free_vm(kvm);
809 preempt_notifier_dec();
810 hardware_disable_all();
811 mmdrop(mm);
814 void kvm_get_kvm(struct kvm *kvm)
816 refcount_inc(&kvm->users_count);
818 EXPORT_SYMBOL_GPL(kvm_get_kvm);
820 void kvm_put_kvm(struct kvm *kvm)
822 if (refcount_dec_and_test(&kvm->users_count))
823 kvm_destroy_vm(kvm);
825 EXPORT_SYMBOL_GPL(kvm_put_kvm);
828 static int kvm_vm_release(struct inode *inode, struct file *filp)
830 struct kvm *kvm = filp->private_data;
832 kvm_irqfd_release(kvm);
834 kvm_put_kvm(kvm);
835 return 0;
839 * Allocation size is twice as large as the actual dirty bitmap size.
840 * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
842 static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
844 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
846 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL);
847 if (!memslot->dirty_bitmap)
848 return -ENOMEM;
850 return 0;
854 * Insert memslot and re-sort memslots based on their GFN,
855 * so binary search could be used to lookup GFN.
856 * Sorting algorithm takes advantage of having initially
857 * sorted array and known changed memslot position.
859 static void update_memslots(struct kvm_memslots *slots,
860 struct kvm_memory_slot *new)
862 int id = new->id;
863 int i = slots->id_to_index[id];
864 struct kvm_memory_slot *mslots = slots->memslots;
866 WARN_ON(mslots[i].id != id);
867 if (!new->npages) {
868 WARN_ON(!mslots[i].npages);
869 if (mslots[i].npages)
870 slots->used_slots--;
871 } else {
872 if (!mslots[i].npages)
873 slots->used_slots++;
876 while (i < KVM_MEM_SLOTS_NUM - 1 &&
877 new->base_gfn <= mslots[i + 1].base_gfn) {
878 if (!mslots[i + 1].npages)
879 break;
880 mslots[i] = mslots[i + 1];
881 slots->id_to_index[mslots[i].id] = i;
882 i++;
886 * The ">=" is needed when creating a slot with base_gfn == 0,
887 * so that it moves before all those with base_gfn == npages == 0.
889 * On the other hand, if new->npages is zero, the above loop has
890 * already left i pointing to the beginning of the empty part of
891 * mslots, and the ">=" would move the hole backwards in this
892 * case---which is wrong. So skip the loop when deleting a slot.
894 if (new->npages) {
895 while (i > 0 &&
896 new->base_gfn >= mslots[i - 1].base_gfn) {
897 mslots[i] = mslots[i - 1];
898 slots->id_to_index[mslots[i].id] = i;
899 i--;
901 } else
902 WARN_ON_ONCE(i != slots->used_slots);
904 mslots[i] = *new;
905 slots->id_to_index[mslots[i].id] = i;
908 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
910 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
912 #ifdef __KVM_HAVE_READONLY_MEM
913 valid_flags |= KVM_MEM_READONLY;
914 #endif
916 if (mem->flags & ~valid_flags)
917 return -EINVAL;
919 return 0;
922 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
923 int as_id, struct kvm_memslots *slots)
925 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
926 u64 gen;
929 * Set the low bit in the generation, which disables SPTE caching
930 * until the end of synchronize_srcu_expedited.
932 WARN_ON(old_memslots->generation & 1);
933 slots->generation = old_memslots->generation + 1;
935 rcu_assign_pointer(kvm->memslots[as_id], slots);
936 synchronize_srcu_expedited(&kvm->srcu);
939 * Increment the new memslot generation a second time. This prevents
940 * vm exits that race with memslot updates from caching a memslot
941 * generation that will (potentially) be valid forever.
943 * Generations must be unique even across address spaces. We do not need
944 * a global counter for that, instead the generation space is evenly split
945 * across address spaces. For example, with two address spaces, address
946 * space 0 will use generations 0, 4, 8, ... while * address space 1 will
947 * use generations 2, 6, 10, 14, ...
949 gen = slots->generation + KVM_ADDRESS_SPACE_NUM * 2 - 1;
951 kvm_arch_memslots_updated(kvm, gen);
953 slots->generation = gen;
955 return old_memslots;
959 * Allocate some memory and give it an address in the guest physical address
960 * space.
962 * Discontiguous memory is allowed, mostly for framebuffers.
964 * Must be called holding kvm->slots_lock for write.
966 int __kvm_set_memory_region(struct kvm *kvm,
967 const struct kvm_userspace_memory_region *mem)
969 int r;
970 gfn_t base_gfn;
971 unsigned long npages;
972 struct kvm_memory_slot *slot;
973 struct kvm_memory_slot old, new;
974 struct kvm_memslots *slots = NULL, *old_memslots;
975 int as_id, id;
976 enum kvm_mr_change change;
978 r = check_memory_region_flags(mem);
979 if (r)
980 goto out;
982 r = -EINVAL;
983 as_id = mem->slot >> 16;
984 id = (u16)mem->slot;
986 /* General sanity checks */
987 if (mem->memory_size & (PAGE_SIZE - 1))
988 goto out;
989 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
990 goto out;
991 /* We can read the guest memory with __xxx_user() later on. */
992 if ((id < KVM_USER_MEM_SLOTS) &&
993 ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
994 !access_ok(VERIFY_WRITE,
995 (void __user *)(unsigned long)mem->userspace_addr,
996 mem->memory_size)))
997 goto out;
998 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
999 goto out;
1000 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1001 goto out;
1003 slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1004 base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1005 npages = mem->memory_size >> PAGE_SHIFT;
1007 if (npages > KVM_MEM_MAX_NR_PAGES)
1008 goto out;
1010 new = old = *slot;
1012 new.id = id;
1013 new.base_gfn = base_gfn;
1014 new.npages = npages;
1015 new.flags = mem->flags;
1017 if (npages) {
1018 if (!old.npages)
1019 change = KVM_MR_CREATE;
1020 else { /* Modify an existing slot. */
1021 if ((mem->userspace_addr != old.userspace_addr) ||
1022 (npages != old.npages) ||
1023 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1024 goto out;
1026 if (base_gfn != old.base_gfn)
1027 change = KVM_MR_MOVE;
1028 else if (new.flags != old.flags)
1029 change = KVM_MR_FLAGS_ONLY;
1030 else { /* Nothing to change. */
1031 r = 0;
1032 goto out;
1035 } else {
1036 if (!old.npages)
1037 goto out;
1039 change = KVM_MR_DELETE;
1040 new.base_gfn = 0;
1041 new.flags = 0;
1044 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1045 /* Check for overlaps */
1046 r = -EEXIST;
1047 kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
1048 if (slot->id == id)
1049 continue;
1050 if (!((base_gfn + npages <= slot->base_gfn) ||
1051 (base_gfn >= slot->base_gfn + slot->npages)))
1052 goto out;
1056 /* Free page dirty bitmap if unneeded */
1057 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1058 new.dirty_bitmap = NULL;
1060 r = -ENOMEM;
1061 if (change == KVM_MR_CREATE) {
1062 new.userspace_addr = mem->userspace_addr;
1064 if (kvm_arch_create_memslot(kvm, &new, npages))
1065 goto out_free;
1068 /* Allocate page dirty bitmap if needed */
1069 if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
1070 if (kvm_create_dirty_bitmap(&new) < 0)
1071 goto out_free;
1074 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
1075 if (!slots)
1076 goto out_free;
1077 memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
1079 if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
1080 slot = id_to_memslot(slots, id);
1081 slot->flags |= KVM_MEMSLOT_INVALID;
1083 old_memslots = install_new_memslots(kvm, as_id, slots);
1085 /* From this point no new shadow pages pointing to a deleted,
1086 * or moved, memslot will be created.
1088 * validation of sp->gfn happens in:
1089 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1090 * - kvm_is_visible_gfn (mmu_check_roots)
1092 kvm_arch_flush_shadow_memslot(kvm, slot);
1095 * We can re-use the old_memslots from above, the only difference
1096 * from the currently installed memslots is the invalid flag. This
1097 * will get overwritten by update_memslots anyway.
1099 slots = old_memslots;
1102 r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
1103 if (r)
1104 goto out_slots;
1106 /* actual memory is freed via old in kvm_free_memslot below */
1107 if (change == KVM_MR_DELETE) {
1108 new.dirty_bitmap = NULL;
1109 memset(&new.arch, 0, sizeof(new.arch));
1112 update_memslots(slots, &new);
1113 old_memslots = install_new_memslots(kvm, as_id, slots);
1115 kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
1117 kvm_free_memslot(kvm, &old, &new);
1118 kvfree(old_memslots);
1119 return 0;
1121 out_slots:
1122 kvfree(slots);
1123 out_free:
1124 kvm_free_memslot(kvm, &new, &old);
1125 out:
1126 return r;
1128 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1130 int kvm_set_memory_region(struct kvm *kvm,
1131 const struct kvm_userspace_memory_region *mem)
1133 int r;
1135 mutex_lock(&kvm->slots_lock);
1136 r = __kvm_set_memory_region(kvm, mem);
1137 mutex_unlock(&kvm->slots_lock);
1138 return r;
1140 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1142 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1143 struct kvm_userspace_memory_region *mem)
1145 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1146 return -EINVAL;
1148 return kvm_set_memory_region(kvm, mem);
1151 int kvm_get_dirty_log(struct kvm *kvm,
1152 struct kvm_dirty_log *log, int *is_dirty)
1154 struct kvm_memslots *slots;
1155 struct kvm_memory_slot *memslot;
1156 int i, as_id, id;
1157 unsigned long n;
1158 unsigned long any = 0;
1160 as_id = log->slot >> 16;
1161 id = (u16)log->slot;
1162 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1163 return -EINVAL;
1165 slots = __kvm_memslots(kvm, as_id);
1166 memslot = id_to_memslot(slots, id);
1167 if (!memslot->dirty_bitmap)
1168 return -ENOENT;
1170 n = kvm_dirty_bitmap_bytes(memslot);
1172 for (i = 0; !any && i < n/sizeof(long); ++i)
1173 any = memslot->dirty_bitmap[i];
1175 if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1176 return -EFAULT;
1178 if (any)
1179 *is_dirty = 1;
1180 return 0;
1182 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1184 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1186 * kvm_get_dirty_log_protect - get a snapshot of dirty pages, and if any pages
1187 * are dirty write protect them for next write.
1188 * @kvm: pointer to kvm instance
1189 * @log: slot id and address to which we copy the log
1190 * @is_dirty: flag set if any page is dirty
1192 * We need to keep it in mind that VCPU threads can write to the bitmap
1193 * concurrently. So, to avoid losing track of dirty pages we keep the
1194 * following order:
1196 * 1. Take a snapshot of the bit and clear it if needed.
1197 * 2. Write protect the corresponding page.
1198 * 3. Copy the snapshot to the userspace.
1199 * 4. Upon return caller flushes TLB's if needed.
1201 * Between 2 and 4, the guest may write to the page using the remaining TLB
1202 * entry. This is not a problem because the page is reported dirty using
1203 * the snapshot taken before and step 4 ensures that writes done after
1204 * exiting to userspace will be logged for the next call.
1207 int kvm_get_dirty_log_protect(struct kvm *kvm,
1208 struct kvm_dirty_log *log, bool *is_dirty)
1210 struct kvm_memslots *slots;
1211 struct kvm_memory_slot *memslot;
1212 int i, as_id, id;
1213 unsigned long n;
1214 unsigned long *dirty_bitmap;
1215 unsigned long *dirty_bitmap_buffer;
1217 as_id = log->slot >> 16;
1218 id = (u16)log->slot;
1219 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1220 return -EINVAL;
1222 slots = __kvm_memslots(kvm, as_id);
1223 memslot = id_to_memslot(slots, id);
1225 dirty_bitmap = memslot->dirty_bitmap;
1226 if (!dirty_bitmap)
1227 return -ENOENT;
1229 n = kvm_dirty_bitmap_bytes(memslot);
1231 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1232 memset(dirty_bitmap_buffer, 0, n);
1234 spin_lock(&kvm->mmu_lock);
1235 *is_dirty = false;
1236 for (i = 0; i < n / sizeof(long); i++) {
1237 unsigned long mask;
1238 gfn_t offset;
1240 if (!dirty_bitmap[i])
1241 continue;
1243 *is_dirty = true;
1245 mask = xchg(&dirty_bitmap[i], 0);
1246 dirty_bitmap_buffer[i] = mask;
1248 if (mask) {
1249 offset = i * BITS_PER_LONG;
1250 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1251 offset, mask);
1255 spin_unlock(&kvm->mmu_lock);
1256 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1257 return -EFAULT;
1258 return 0;
1260 EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
1261 #endif
1263 bool kvm_largepages_enabled(void)
1265 return largepages_enabled;
1268 void kvm_disable_largepages(void)
1270 largepages_enabled = false;
1272 EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1274 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1276 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1278 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1280 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1282 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1285 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1287 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1289 if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1290 memslot->flags & KVM_MEMSLOT_INVALID)
1291 return false;
1293 return true;
1295 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1297 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
1299 struct vm_area_struct *vma;
1300 unsigned long addr, size;
1302 size = PAGE_SIZE;
1304 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
1305 if (kvm_is_error_hva(addr))
1306 return PAGE_SIZE;
1308 down_read(&current->mm->mmap_sem);
1309 vma = find_vma(current->mm, addr);
1310 if (!vma)
1311 goto out;
1313 size = vma_kernel_pagesize(vma);
1315 out:
1316 up_read(&current->mm->mmap_sem);
1318 return size;
1321 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1323 return slot->flags & KVM_MEM_READONLY;
1326 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1327 gfn_t *nr_pages, bool write)
1329 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1330 return KVM_HVA_ERR_BAD;
1332 if (memslot_is_readonly(slot) && write)
1333 return KVM_HVA_ERR_RO_BAD;
1335 if (nr_pages)
1336 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1338 return __gfn_to_hva_memslot(slot, gfn);
1341 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1342 gfn_t *nr_pages)
1344 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1347 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1348 gfn_t gfn)
1350 return gfn_to_hva_many(slot, gfn, NULL);
1352 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1354 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1356 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1358 EXPORT_SYMBOL_GPL(gfn_to_hva);
1360 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1362 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1364 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1367 * If writable is set to false, the hva returned by this function is only
1368 * allowed to be read.
1370 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1371 gfn_t gfn, bool *writable)
1373 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1375 if (!kvm_is_error_hva(hva) && writable)
1376 *writable = !memslot_is_readonly(slot);
1378 return hva;
1381 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1383 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1385 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1388 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1390 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1392 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1395 static inline int check_user_page_hwpoison(unsigned long addr)
1397 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1399 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1400 return rc == -EHWPOISON;
1404 * The fast path to get the writable pfn which will be stored in @pfn,
1405 * true indicates success, otherwise false is returned. It's also the
1406 * only part that runs if we can are in atomic context.
1408 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1409 bool *writable, kvm_pfn_t *pfn)
1411 struct page *page[1];
1412 int npages;
1415 * Fast pin a writable pfn only if it is a write fault request
1416 * or the caller allows to map a writable pfn for a read fault
1417 * request.
1419 if (!(write_fault || writable))
1420 return false;
1422 npages = __get_user_pages_fast(addr, 1, 1, page);
1423 if (npages == 1) {
1424 *pfn = page_to_pfn(page[0]);
1426 if (writable)
1427 *writable = true;
1428 return true;
1431 return false;
1435 * The slow path to get the pfn of the specified host virtual address,
1436 * 1 indicates success, -errno is returned if error is detected.
1438 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1439 bool *writable, kvm_pfn_t *pfn)
1441 unsigned int flags = FOLL_HWPOISON;
1442 struct page *page;
1443 int npages = 0;
1445 might_sleep();
1447 if (writable)
1448 *writable = write_fault;
1450 if (write_fault)
1451 flags |= FOLL_WRITE;
1452 if (async)
1453 flags |= FOLL_NOWAIT;
1455 npages = get_user_pages_unlocked(addr, 1, &page, flags);
1456 if (npages != 1)
1457 return npages;
1459 /* map read fault as writable if possible */
1460 if (unlikely(!write_fault) && writable) {
1461 struct page *wpage;
1463 if (__get_user_pages_fast(addr, 1, 1, &wpage) == 1) {
1464 *writable = true;
1465 put_page(page);
1466 page = wpage;
1469 *pfn = page_to_pfn(page);
1470 return npages;
1473 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1475 if (unlikely(!(vma->vm_flags & VM_READ)))
1476 return false;
1478 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1479 return false;
1481 return true;
1484 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1485 unsigned long addr, bool *async,
1486 bool write_fault, bool *writable,
1487 kvm_pfn_t *p_pfn)
1489 unsigned long pfn;
1490 int r;
1492 r = follow_pfn(vma, addr, &pfn);
1493 if (r) {
1495 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1496 * not call the fault handler, so do it here.
1498 bool unlocked = false;
1499 r = fixup_user_fault(current, current->mm, addr,
1500 (write_fault ? FAULT_FLAG_WRITE : 0),
1501 &unlocked);
1502 if (unlocked)
1503 return -EAGAIN;
1504 if (r)
1505 return r;
1507 r = follow_pfn(vma, addr, &pfn);
1508 if (r)
1509 return r;
1513 if (writable)
1514 *writable = true;
1517 * Get a reference here because callers of *hva_to_pfn* and
1518 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1519 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1520 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1521 * simply do nothing for reserved pfns.
1523 * Whoever called remap_pfn_range is also going to call e.g.
1524 * unmap_mapping_range before the underlying pages are freed,
1525 * causing a call to our MMU notifier.
1527 kvm_get_pfn(pfn);
1529 *p_pfn = pfn;
1530 return 0;
1534 * Pin guest page in memory and return its pfn.
1535 * @addr: host virtual address which maps memory to the guest
1536 * @atomic: whether this function can sleep
1537 * @async: whether this function need to wait IO complete if the
1538 * host page is not in the memory
1539 * @write_fault: whether we should get a writable host page
1540 * @writable: whether it allows to map a writable host page for !@write_fault
1542 * The function will map a writable host page for these two cases:
1543 * 1): @write_fault = true
1544 * 2): @write_fault = false && @writable, @writable will tell the caller
1545 * whether the mapping is writable.
1547 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1548 bool write_fault, bool *writable)
1550 struct vm_area_struct *vma;
1551 kvm_pfn_t pfn = 0;
1552 int npages, r;
1554 /* we can do it either atomically or asynchronously, not both */
1555 BUG_ON(atomic && async);
1557 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
1558 return pfn;
1560 if (atomic)
1561 return KVM_PFN_ERR_FAULT;
1563 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1564 if (npages == 1)
1565 return pfn;
1567 down_read(&current->mm->mmap_sem);
1568 if (npages == -EHWPOISON ||
1569 (!async && check_user_page_hwpoison(addr))) {
1570 pfn = KVM_PFN_ERR_HWPOISON;
1571 goto exit;
1574 retry:
1575 vma = find_vma_intersection(current->mm, addr, addr + 1);
1577 if (vma == NULL)
1578 pfn = KVM_PFN_ERR_FAULT;
1579 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1580 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
1581 if (r == -EAGAIN)
1582 goto retry;
1583 if (r < 0)
1584 pfn = KVM_PFN_ERR_FAULT;
1585 } else {
1586 if (async && vma_is_valid(vma, write_fault))
1587 *async = true;
1588 pfn = KVM_PFN_ERR_FAULT;
1590 exit:
1591 up_read(&current->mm->mmap_sem);
1592 return pfn;
1595 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1596 bool atomic, bool *async, bool write_fault,
1597 bool *writable)
1599 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1601 if (addr == KVM_HVA_ERR_RO_BAD) {
1602 if (writable)
1603 *writable = false;
1604 return KVM_PFN_ERR_RO_FAULT;
1607 if (kvm_is_error_hva(addr)) {
1608 if (writable)
1609 *writable = false;
1610 return KVM_PFN_NOSLOT;
1613 /* Do not map writable pfn in the readonly memslot. */
1614 if (writable && memslot_is_readonly(slot)) {
1615 *writable = false;
1616 writable = NULL;
1619 return hva_to_pfn(addr, atomic, async, write_fault,
1620 writable);
1622 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1624 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1625 bool *writable)
1627 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1628 write_fault, writable);
1630 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1632 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1634 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1636 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1638 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1640 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1642 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1644 kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1646 return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1648 EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1650 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1652 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1654 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1656 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1658 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1660 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1662 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1664 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1666 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1668 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1669 struct page **pages, int nr_pages)
1671 unsigned long addr;
1672 gfn_t entry = 0;
1674 addr = gfn_to_hva_many(slot, gfn, &entry);
1675 if (kvm_is_error_hva(addr))
1676 return -1;
1678 if (entry < nr_pages)
1679 return 0;
1681 return __get_user_pages_fast(addr, nr_pages, 1, pages);
1683 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1685 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
1687 if (is_error_noslot_pfn(pfn))
1688 return KVM_ERR_PTR_BAD_PAGE;
1690 if (kvm_is_reserved_pfn(pfn)) {
1691 WARN_ON(1);
1692 return KVM_ERR_PTR_BAD_PAGE;
1695 return pfn_to_page(pfn);
1698 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1700 kvm_pfn_t pfn;
1702 pfn = gfn_to_pfn(kvm, gfn);
1704 return kvm_pfn_to_page(pfn);
1706 EXPORT_SYMBOL_GPL(gfn_to_page);
1708 static int __kvm_map_gfn(struct kvm_memory_slot *slot, gfn_t gfn,
1709 struct kvm_host_map *map)
1711 kvm_pfn_t pfn;
1712 void *hva = NULL;
1713 struct page *page = KVM_UNMAPPED_PAGE;
1715 if (!map)
1716 return -EINVAL;
1718 pfn = gfn_to_pfn_memslot(slot, gfn);
1719 if (is_error_noslot_pfn(pfn))
1720 return -EINVAL;
1722 if (pfn_valid(pfn)) {
1723 page = pfn_to_page(pfn);
1724 hva = kmap(page);
1725 #ifdef CONFIG_HAS_IOMEM
1726 } else {
1727 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
1728 #endif
1731 if (!hva)
1732 return -EFAULT;
1734 map->page = page;
1735 map->hva = hva;
1736 map->pfn = pfn;
1737 map->gfn = gfn;
1739 return 0;
1742 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
1744 return __kvm_map_gfn(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, map);
1746 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
1748 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
1749 bool dirty)
1751 if (!map)
1752 return;
1754 if (!map->hva)
1755 return;
1757 if (map->page != KVM_UNMAPPED_PAGE)
1758 kunmap(map->page);
1759 #ifdef CONFIG_HAS_IOMEM
1760 else
1761 memunmap(map->hva);
1762 #endif
1764 if (dirty) {
1765 kvm_vcpu_mark_page_dirty(vcpu, map->gfn);
1766 kvm_release_pfn_dirty(map->pfn);
1767 } else {
1768 kvm_release_pfn_clean(map->pfn);
1771 map->hva = NULL;
1772 map->page = NULL;
1774 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
1776 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
1778 kvm_pfn_t pfn;
1780 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
1782 return kvm_pfn_to_page(pfn);
1784 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
1786 void kvm_release_page_clean(struct page *page)
1788 WARN_ON(is_error_page(page));
1790 kvm_release_pfn_clean(page_to_pfn(page));
1792 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1794 void kvm_release_pfn_clean(kvm_pfn_t pfn)
1796 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
1797 put_page(pfn_to_page(pfn));
1799 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1801 void kvm_release_page_dirty(struct page *page)
1803 WARN_ON(is_error_page(page));
1805 kvm_release_pfn_dirty(page_to_pfn(page));
1807 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1809 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
1811 kvm_set_pfn_dirty(pfn);
1812 kvm_release_pfn_clean(pfn);
1814 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
1816 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
1818 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn)) {
1819 struct page *page = pfn_to_page(pfn);
1821 if (!PageReserved(page))
1822 SetPageDirty(page);
1825 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1827 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
1829 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
1830 mark_page_accessed(pfn_to_page(pfn));
1832 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1834 void kvm_get_pfn(kvm_pfn_t pfn)
1836 if (!kvm_is_reserved_pfn(pfn))
1837 get_page(pfn_to_page(pfn));
1839 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1841 static int next_segment(unsigned long len, int offset)
1843 if (len > PAGE_SIZE - offset)
1844 return PAGE_SIZE - offset;
1845 else
1846 return len;
1849 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
1850 void *data, int offset, int len)
1852 int r;
1853 unsigned long addr;
1855 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1856 if (kvm_is_error_hva(addr))
1857 return -EFAULT;
1858 r = __copy_from_user(data, (void __user *)addr + offset, len);
1859 if (r)
1860 return -EFAULT;
1861 return 0;
1864 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1865 int len)
1867 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1869 return __kvm_read_guest_page(slot, gfn, data, offset, len);
1871 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1873 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
1874 int offset, int len)
1876 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1878 return __kvm_read_guest_page(slot, gfn, data, offset, len);
1880 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
1882 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1884 gfn_t gfn = gpa >> PAGE_SHIFT;
1885 int seg;
1886 int offset = offset_in_page(gpa);
1887 int ret;
1889 while ((seg = next_segment(len, offset)) != 0) {
1890 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1891 if (ret < 0)
1892 return ret;
1893 offset = 0;
1894 len -= seg;
1895 data += seg;
1896 ++gfn;
1898 return 0;
1900 EXPORT_SYMBOL_GPL(kvm_read_guest);
1902 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
1904 gfn_t gfn = gpa >> PAGE_SHIFT;
1905 int seg;
1906 int offset = offset_in_page(gpa);
1907 int ret;
1909 while ((seg = next_segment(len, offset)) != 0) {
1910 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
1911 if (ret < 0)
1912 return ret;
1913 offset = 0;
1914 len -= seg;
1915 data += seg;
1916 ++gfn;
1918 return 0;
1920 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
1922 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1923 void *data, int offset, unsigned long len)
1925 int r;
1926 unsigned long addr;
1928 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1929 if (kvm_is_error_hva(addr))
1930 return -EFAULT;
1931 pagefault_disable();
1932 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1933 pagefault_enable();
1934 if (r)
1935 return -EFAULT;
1936 return 0;
1939 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1940 unsigned long len)
1942 gfn_t gfn = gpa >> PAGE_SHIFT;
1943 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1944 int offset = offset_in_page(gpa);
1946 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1948 EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
1950 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
1951 void *data, unsigned long len)
1953 gfn_t gfn = gpa >> PAGE_SHIFT;
1954 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1955 int offset = offset_in_page(gpa);
1957 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1959 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
1961 static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
1962 const void *data, int offset, int len)
1964 int r;
1965 unsigned long addr;
1967 addr = gfn_to_hva_memslot(memslot, gfn);
1968 if (kvm_is_error_hva(addr))
1969 return -EFAULT;
1970 r = __copy_to_user((void __user *)addr + offset, data, len);
1971 if (r)
1972 return -EFAULT;
1973 mark_page_dirty_in_slot(memslot, gfn);
1974 return 0;
1977 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
1978 const void *data, int offset, int len)
1980 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1982 return __kvm_write_guest_page(slot, gfn, data, offset, len);
1984 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1986 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
1987 const void *data, int offset, int len)
1989 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1991 return __kvm_write_guest_page(slot, gfn, data, offset, len);
1993 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
1995 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1996 unsigned long len)
1998 gfn_t gfn = gpa >> PAGE_SHIFT;
1999 int seg;
2000 int offset = offset_in_page(gpa);
2001 int ret;
2003 while ((seg = next_segment(len, offset)) != 0) {
2004 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2005 if (ret < 0)
2006 return ret;
2007 offset = 0;
2008 len -= seg;
2009 data += seg;
2010 ++gfn;
2012 return 0;
2014 EXPORT_SYMBOL_GPL(kvm_write_guest);
2016 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2017 unsigned long len)
2019 gfn_t gfn = gpa >> PAGE_SHIFT;
2020 int seg;
2021 int offset = offset_in_page(gpa);
2022 int ret;
2024 while ((seg = next_segment(len, offset)) != 0) {
2025 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2026 if (ret < 0)
2027 return ret;
2028 offset = 0;
2029 len -= seg;
2030 data += seg;
2031 ++gfn;
2033 return 0;
2035 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2037 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2038 struct gfn_to_hva_cache *ghc,
2039 gpa_t gpa, unsigned long len)
2041 int offset = offset_in_page(gpa);
2042 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2043 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2044 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2045 gfn_t nr_pages_avail;
2047 ghc->gpa = gpa;
2048 ghc->generation = slots->generation;
2049 ghc->len = len;
2050 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2051 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, NULL);
2052 if (!kvm_is_error_hva(ghc->hva) && nr_pages_needed <= 1) {
2053 ghc->hva += offset;
2054 } else {
2056 * If the requested region crosses two memslots, we still
2057 * verify that the entire region is valid here.
2059 while (start_gfn <= end_gfn) {
2060 nr_pages_avail = 0;
2061 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2062 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2063 &nr_pages_avail);
2064 if (kvm_is_error_hva(ghc->hva))
2065 return -EFAULT;
2066 start_gfn += nr_pages_avail;
2068 /* Use the slow path for cross page reads and writes. */
2069 ghc->memslot = NULL;
2071 return 0;
2074 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2075 gpa_t gpa, unsigned long len)
2077 struct kvm_memslots *slots = kvm_memslots(kvm);
2078 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2080 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2082 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2083 void *data, unsigned int offset,
2084 unsigned long len)
2086 struct kvm_memslots *slots = kvm_memslots(kvm);
2087 int r;
2088 gpa_t gpa = ghc->gpa + offset;
2090 BUG_ON(len + offset > ghc->len);
2092 if (slots->generation != ghc->generation)
2093 __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
2095 if (kvm_is_error_hva(ghc->hva))
2096 return -EFAULT;
2098 if (unlikely(!ghc->memslot))
2099 return kvm_write_guest(kvm, gpa, data, len);
2101 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2102 if (r)
2103 return -EFAULT;
2104 mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
2106 return 0;
2108 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2110 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2111 void *data, unsigned long len)
2113 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2115 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2117 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2118 void *data, unsigned long len)
2120 struct kvm_memslots *slots = kvm_memslots(kvm);
2121 int r;
2123 BUG_ON(len > ghc->len);
2125 if (slots->generation != ghc->generation)
2126 __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
2128 if (kvm_is_error_hva(ghc->hva))
2129 return -EFAULT;
2131 if (unlikely(!ghc->memslot))
2132 return kvm_read_guest(kvm, ghc->gpa, data, len);
2134 r = __copy_from_user(data, (void __user *)ghc->hva, len);
2135 if (r)
2136 return -EFAULT;
2138 return 0;
2140 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2142 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2144 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2146 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2148 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2150 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2152 gfn_t gfn = gpa >> PAGE_SHIFT;
2153 int seg;
2154 int offset = offset_in_page(gpa);
2155 int ret;
2157 while ((seg = next_segment(len, offset)) != 0) {
2158 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2159 if (ret < 0)
2160 return ret;
2161 offset = 0;
2162 len -= seg;
2163 ++gfn;
2165 return 0;
2167 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2169 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2170 gfn_t gfn)
2172 if (memslot && memslot->dirty_bitmap) {
2173 unsigned long rel_gfn = gfn - memslot->base_gfn;
2175 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2179 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2181 struct kvm_memory_slot *memslot;
2183 memslot = gfn_to_memslot(kvm, gfn);
2184 mark_page_dirty_in_slot(memslot, gfn);
2186 EXPORT_SYMBOL_GPL(mark_page_dirty);
2188 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2190 struct kvm_memory_slot *memslot;
2192 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2193 mark_page_dirty_in_slot(memslot, gfn);
2195 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2197 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2199 if (!vcpu->sigset_active)
2200 return;
2203 * This does a lockless modification of ->real_blocked, which is fine
2204 * because, only current can change ->real_blocked and all readers of
2205 * ->real_blocked don't care as long ->real_blocked is always a subset
2206 * of ->blocked.
2208 sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
2211 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2213 if (!vcpu->sigset_active)
2214 return;
2216 sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
2217 sigemptyset(&current->real_blocked);
2220 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2222 unsigned int old, val, grow;
2224 old = val = vcpu->halt_poll_ns;
2225 grow = READ_ONCE(halt_poll_ns_grow);
2226 /* 10us base */
2227 if (val == 0 && grow)
2228 val = 10000;
2229 else
2230 val *= grow;
2232 if (val > halt_poll_ns)
2233 val = halt_poll_ns;
2235 vcpu->halt_poll_ns = val;
2236 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2239 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2241 unsigned int old, val, shrink;
2243 old = val = vcpu->halt_poll_ns;
2244 shrink = READ_ONCE(halt_poll_ns_shrink);
2245 if (shrink == 0)
2246 val = 0;
2247 else
2248 val /= shrink;
2250 vcpu->halt_poll_ns = val;
2251 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2254 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2256 int ret = -EINTR;
2257 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2259 if (kvm_arch_vcpu_runnable(vcpu)) {
2260 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2261 goto out;
2263 if (kvm_cpu_has_pending_timer(vcpu))
2264 goto out;
2265 if (signal_pending(current))
2266 goto out;
2268 ret = 0;
2269 out:
2270 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2271 return ret;
2275 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2277 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2279 ktime_t start, cur;
2280 DECLARE_SWAITQUEUE(wait);
2281 bool waited = false;
2282 u64 block_ns;
2284 start = cur = ktime_get();
2285 if (vcpu->halt_poll_ns) {
2286 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2288 ++vcpu->stat.halt_attempted_poll;
2289 do {
2291 * This sets KVM_REQ_UNHALT if an interrupt
2292 * arrives.
2294 if (kvm_vcpu_check_block(vcpu) < 0) {
2295 ++vcpu->stat.halt_successful_poll;
2296 if (!vcpu_valid_wakeup(vcpu))
2297 ++vcpu->stat.halt_poll_invalid;
2298 goto out;
2300 cur = ktime_get();
2301 } while (single_task_running() && ktime_before(cur, stop));
2304 kvm_arch_vcpu_blocking(vcpu);
2306 for (;;) {
2307 prepare_to_swait_exclusive(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2309 if (kvm_vcpu_check_block(vcpu) < 0)
2310 break;
2312 waited = true;
2313 schedule();
2316 finish_swait(&vcpu->wq, &wait);
2317 cur = ktime_get();
2319 kvm_arch_vcpu_unblocking(vcpu);
2320 out:
2321 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2323 if (!vcpu_valid_wakeup(vcpu))
2324 shrink_halt_poll_ns(vcpu);
2325 else if (halt_poll_ns) {
2326 if (block_ns <= vcpu->halt_poll_ns)
2328 /* we had a long block, shrink polling */
2329 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2330 shrink_halt_poll_ns(vcpu);
2331 /* we had a short halt and our poll time is too small */
2332 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2333 block_ns < halt_poll_ns)
2334 grow_halt_poll_ns(vcpu);
2335 } else
2336 vcpu->halt_poll_ns = 0;
2338 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2339 kvm_arch_vcpu_block_finish(vcpu);
2341 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2343 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2345 struct swait_queue_head *wqp;
2347 wqp = kvm_arch_vcpu_wq(vcpu);
2348 if (swq_has_sleeper(wqp)) {
2349 swake_up_one(wqp);
2350 ++vcpu->stat.halt_wakeup;
2351 return true;
2354 return false;
2356 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2358 #ifndef CONFIG_S390
2360 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2362 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2364 int me;
2365 int cpu = vcpu->cpu;
2367 if (kvm_vcpu_wake_up(vcpu))
2368 return;
2370 me = get_cpu();
2371 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2372 if (kvm_arch_vcpu_should_kick(vcpu))
2373 smp_send_reschedule(cpu);
2374 put_cpu();
2376 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2377 #endif /* !CONFIG_S390 */
2379 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2381 struct pid *pid;
2382 struct task_struct *task = NULL;
2383 int ret = 0;
2385 rcu_read_lock();
2386 pid = rcu_dereference(target->pid);
2387 if (pid)
2388 task = get_pid_task(pid, PIDTYPE_PID);
2389 rcu_read_unlock();
2390 if (!task)
2391 return ret;
2392 ret = yield_to(task, 1);
2393 put_task_struct(task);
2395 return ret;
2397 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2400 * Helper that checks whether a VCPU is eligible for directed yield.
2401 * Most eligible candidate to yield is decided by following heuristics:
2403 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2404 * (preempted lock holder), indicated by @in_spin_loop.
2405 * Set at the beiginning and cleared at the end of interception/PLE handler.
2407 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2408 * chance last time (mostly it has become eligible now since we have probably
2409 * yielded to lockholder in last iteration. This is done by toggling
2410 * @dy_eligible each time a VCPU checked for eligibility.)
2412 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2413 * to preempted lock-holder could result in wrong VCPU selection and CPU
2414 * burning. Giving priority for a potential lock-holder increases lock
2415 * progress.
2417 * Since algorithm is based on heuristics, accessing another VCPU data without
2418 * locking does not harm. It may result in trying to yield to same VCPU, fail
2419 * and continue with next VCPU and so on.
2421 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2423 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2424 bool eligible;
2426 eligible = !vcpu->spin_loop.in_spin_loop ||
2427 vcpu->spin_loop.dy_eligible;
2429 if (vcpu->spin_loop.in_spin_loop)
2430 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2432 return eligible;
2433 #else
2434 return true;
2435 #endif
2439 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2440 * a vcpu_load/vcpu_put pair. However, for most architectures
2441 * kvm_arch_vcpu_runnable does not require vcpu_load.
2443 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2445 return kvm_arch_vcpu_runnable(vcpu);
2448 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2450 if (kvm_arch_dy_runnable(vcpu))
2451 return true;
2453 #ifdef CONFIG_KVM_ASYNC_PF
2454 if (!list_empty_careful(&vcpu->async_pf.done))
2455 return true;
2456 #endif
2458 return false;
2461 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
2463 struct kvm *kvm = me->kvm;
2464 struct kvm_vcpu *vcpu;
2465 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2466 int yielded = 0;
2467 int try = 3;
2468 int pass;
2469 int i;
2471 kvm_vcpu_set_in_spin_loop(me, true);
2473 * We boost the priority of a VCPU that is runnable but not
2474 * currently running, because it got preempted by something
2475 * else and called schedule in __vcpu_run. Hopefully that
2476 * VCPU is holding the lock that we need and will release it.
2477 * We approximate round-robin by starting at the last boosted VCPU.
2479 for (pass = 0; pass < 2 && !yielded && try; pass++) {
2480 kvm_for_each_vcpu(i, vcpu, kvm) {
2481 if (!pass && i <= last_boosted_vcpu) {
2482 i = last_boosted_vcpu;
2483 continue;
2484 } else if (pass && i > last_boosted_vcpu)
2485 break;
2486 if (!READ_ONCE(vcpu->preempted))
2487 continue;
2488 if (vcpu == me)
2489 continue;
2490 if (swait_active(&vcpu->wq) && !vcpu_dy_runnable(vcpu))
2491 continue;
2492 if (yield_to_kernel_mode && !kvm_arch_vcpu_in_kernel(vcpu))
2493 continue;
2494 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2495 continue;
2497 yielded = kvm_vcpu_yield_to(vcpu);
2498 if (yielded > 0) {
2499 kvm->last_boosted_vcpu = i;
2500 break;
2501 } else if (yielded < 0) {
2502 try--;
2503 if (!try)
2504 break;
2508 kvm_vcpu_set_in_spin_loop(me, false);
2510 /* Ensure vcpu is not eligible during next spinloop */
2511 kvm_vcpu_set_dy_eligible(me, false);
2513 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2515 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
2517 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
2518 struct page *page;
2520 if (vmf->pgoff == 0)
2521 page = virt_to_page(vcpu->run);
2522 #ifdef CONFIG_X86
2523 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2524 page = virt_to_page(vcpu->arch.pio_data);
2525 #endif
2526 #ifdef CONFIG_KVM_MMIO
2527 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2528 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2529 #endif
2530 else
2531 return kvm_arch_vcpu_fault(vcpu, vmf);
2532 get_page(page);
2533 vmf->page = page;
2534 return 0;
2537 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2538 .fault = kvm_vcpu_fault,
2541 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2543 vma->vm_ops = &kvm_vcpu_vm_ops;
2544 return 0;
2547 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2549 struct kvm_vcpu *vcpu = filp->private_data;
2551 debugfs_remove_recursive(vcpu->debugfs_dentry);
2552 kvm_put_kvm(vcpu->kvm);
2553 return 0;
2556 static struct file_operations kvm_vcpu_fops = {
2557 .release = kvm_vcpu_release,
2558 .unlocked_ioctl = kvm_vcpu_ioctl,
2559 .mmap = kvm_vcpu_mmap,
2560 .llseek = noop_llseek,
2561 KVM_COMPAT(kvm_vcpu_compat_ioctl),
2565 * Allocates an inode for the vcpu.
2567 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2569 char name[8 + 1 + ITOA_MAX_LEN + 1];
2571 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
2572 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2575 static int kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
2577 char dir_name[ITOA_MAX_LEN * 2];
2578 int ret;
2580 if (!kvm_arch_has_vcpu_debugfs())
2581 return 0;
2583 if (!debugfs_initialized())
2584 return 0;
2586 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2587 vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
2588 vcpu->kvm->debugfs_dentry);
2589 if (!vcpu->debugfs_dentry)
2590 return -ENOMEM;
2592 ret = kvm_arch_create_vcpu_debugfs(vcpu);
2593 if (ret < 0) {
2594 debugfs_remove_recursive(vcpu->debugfs_dentry);
2595 return ret;
2598 return 0;
2602 * Creates some virtual cpus. Good luck creating more than one.
2604 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
2606 int r;
2607 struct kvm_vcpu *vcpu;
2609 if (id >= KVM_MAX_VCPU_ID)
2610 return -EINVAL;
2612 mutex_lock(&kvm->lock);
2613 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
2614 mutex_unlock(&kvm->lock);
2615 return -EINVAL;
2618 kvm->created_vcpus++;
2619 mutex_unlock(&kvm->lock);
2621 vcpu = kvm_arch_vcpu_create(kvm, id);
2622 if (IS_ERR(vcpu)) {
2623 r = PTR_ERR(vcpu);
2624 goto vcpu_decrement;
2627 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2629 r = kvm_arch_vcpu_setup(vcpu);
2630 if (r)
2631 goto vcpu_destroy;
2633 r = kvm_create_vcpu_debugfs(vcpu);
2634 if (r)
2635 goto vcpu_destroy;
2637 mutex_lock(&kvm->lock);
2638 if (kvm_get_vcpu_by_id(kvm, id)) {
2639 r = -EEXIST;
2640 goto unlock_vcpu_destroy;
2643 BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
2645 /* Now it's all set up, let userspace reach it */
2646 kvm_get_kvm(kvm);
2647 r = create_vcpu_fd(vcpu);
2648 if (r < 0) {
2649 kvm_put_kvm(kvm);
2650 goto unlock_vcpu_destroy;
2653 kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
2656 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
2657 * before kvm->online_vcpu's incremented value.
2659 smp_wmb();
2660 atomic_inc(&kvm->online_vcpus);
2662 mutex_unlock(&kvm->lock);
2663 kvm_arch_vcpu_postcreate(vcpu);
2664 return r;
2666 unlock_vcpu_destroy:
2667 mutex_unlock(&kvm->lock);
2668 debugfs_remove_recursive(vcpu->debugfs_dentry);
2669 vcpu_destroy:
2670 kvm_arch_vcpu_destroy(vcpu);
2671 vcpu_decrement:
2672 mutex_lock(&kvm->lock);
2673 kvm->created_vcpus--;
2674 mutex_unlock(&kvm->lock);
2675 return r;
2678 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2680 if (sigset) {
2681 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2682 vcpu->sigset_active = 1;
2683 vcpu->sigset = *sigset;
2684 } else
2685 vcpu->sigset_active = 0;
2686 return 0;
2689 static long kvm_vcpu_ioctl(struct file *filp,
2690 unsigned int ioctl, unsigned long arg)
2692 struct kvm_vcpu *vcpu = filp->private_data;
2693 void __user *argp = (void __user *)arg;
2694 int r;
2695 struct kvm_fpu *fpu = NULL;
2696 struct kvm_sregs *kvm_sregs = NULL;
2698 if (vcpu->kvm->mm != current->mm)
2699 return -EIO;
2701 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2702 return -EINVAL;
2705 * Some architectures have vcpu ioctls that are asynchronous to vcpu
2706 * execution; mutex_lock() would break them.
2708 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
2709 if (r != -ENOIOCTLCMD)
2710 return r;
2712 if (mutex_lock_killable(&vcpu->mutex))
2713 return -EINTR;
2714 switch (ioctl) {
2715 case KVM_RUN: {
2716 struct pid *oldpid;
2717 r = -EINVAL;
2718 if (arg)
2719 goto out;
2720 oldpid = rcu_access_pointer(vcpu->pid);
2721 if (unlikely(oldpid != task_pid(current))) {
2722 /* The thread running this VCPU changed. */
2723 struct pid *newpid;
2725 r = kvm_arch_vcpu_run_pid_change(vcpu);
2726 if (r)
2727 break;
2729 newpid = get_task_pid(current, PIDTYPE_PID);
2730 rcu_assign_pointer(vcpu->pid, newpid);
2731 if (oldpid)
2732 synchronize_rcu();
2733 put_pid(oldpid);
2735 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
2736 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
2737 break;
2739 case KVM_GET_REGS: {
2740 struct kvm_regs *kvm_regs;
2742 r = -ENOMEM;
2743 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
2744 if (!kvm_regs)
2745 goto out;
2746 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2747 if (r)
2748 goto out_free1;
2749 r = -EFAULT;
2750 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2751 goto out_free1;
2752 r = 0;
2753 out_free1:
2754 kfree(kvm_regs);
2755 break;
2757 case KVM_SET_REGS: {
2758 struct kvm_regs *kvm_regs;
2760 r = -ENOMEM;
2761 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2762 if (IS_ERR(kvm_regs)) {
2763 r = PTR_ERR(kvm_regs);
2764 goto out;
2766 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
2767 kfree(kvm_regs);
2768 break;
2770 case KVM_GET_SREGS: {
2771 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
2772 r = -ENOMEM;
2773 if (!kvm_sregs)
2774 goto out;
2775 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
2776 if (r)
2777 goto out;
2778 r = -EFAULT;
2779 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
2780 goto out;
2781 r = 0;
2782 break;
2784 case KVM_SET_SREGS: {
2785 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
2786 if (IS_ERR(kvm_sregs)) {
2787 r = PTR_ERR(kvm_sregs);
2788 kvm_sregs = NULL;
2789 goto out;
2791 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
2792 break;
2794 case KVM_GET_MP_STATE: {
2795 struct kvm_mp_state mp_state;
2797 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
2798 if (r)
2799 goto out;
2800 r = -EFAULT;
2801 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
2802 goto out;
2803 r = 0;
2804 break;
2806 case KVM_SET_MP_STATE: {
2807 struct kvm_mp_state mp_state;
2809 r = -EFAULT;
2810 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
2811 goto out;
2812 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
2813 break;
2815 case KVM_TRANSLATE: {
2816 struct kvm_translation tr;
2818 r = -EFAULT;
2819 if (copy_from_user(&tr, argp, sizeof(tr)))
2820 goto out;
2821 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
2822 if (r)
2823 goto out;
2824 r = -EFAULT;
2825 if (copy_to_user(argp, &tr, sizeof(tr)))
2826 goto out;
2827 r = 0;
2828 break;
2830 case KVM_SET_GUEST_DEBUG: {
2831 struct kvm_guest_debug dbg;
2833 r = -EFAULT;
2834 if (copy_from_user(&dbg, argp, sizeof(dbg)))
2835 goto out;
2836 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
2837 break;
2839 case KVM_SET_SIGNAL_MASK: {
2840 struct kvm_signal_mask __user *sigmask_arg = argp;
2841 struct kvm_signal_mask kvm_sigmask;
2842 sigset_t sigset, *p;
2844 p = NULL;
2845 if (argp) {
2846 r = -EFAULT;
2847 if (copy_from_user(&kvm_sigmask, argp,
2848 sizeof(kvm_sigmask)))
2849 goto out;
2850 r = -EINVAL;
2851 if (kvm_sigmask.len != sizeof(sigset))
2852 goto out;
2853 r = -EFAULT;
2854 if (copy_from_user(&sigset, sigmask_arg->sigset,
2855 sizeof(sigset)))
2856 goto out;
2857 p = &sigset;
2859 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
2860 break;
2862 case KVM_GET_FPU: {
2863 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2864 r = -ENOMEM;
2865 if (!fpu)
2866 goto out;
2867 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
2868 if (r)
2869 goto out;
2870 r = -EFAULT;
2871 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
2872 goto out;
2873 r = 0;
2874 break;
2876 case KVM_SET_FPU: {
2877 fpu = memdup_user(argp, sizeof(*fpu));
2878 if (IS_ERR(fpu)) {
2879 r = PTR_ERR(fpu);
2880 fpu = NULL;
2881 goto out;
2883 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2884 break;
2886 default:
2887 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2889 out:
2890 mutex_unlock(&vcpu->mutex);
2891 kfree(fpu);
2892 kfree(kvm_sregs);
2893 return r;
2896 #ifdef CONFIG_KVM_COMPAT
2897 static long kvm_vcpu_compat_ioctl(struct file *filp,
2898 unsigned int ioctl, unsigned long arg)
2900 struct kvm_vcpu *vcpu = filp->private_data;
2901 void __user *argp = compat_ptr(arg);
2902 int r;
2904 if (vcpu->kvm->mm != current->mm)
2905 return -EIO;
2907 switch (ioctl) {
2908 case KVM_SET_SIGNAL_MASK: {
2909 struct kvm_signal_mask __user *sigmask_arg = argp;
2910 struct kvm_signal_mask kvm_sigmask;
2911 sigset_t sigset;
2913 if (argp) {
2914 r = -EFAULT;
2915 if (copy_from_user(&kvm_sigmask, argp,
2916 sizeof(kvm_sigmask)))
2917 goto out;
2918 r = -EINVAL;
2919 if (kvm_sigmask.len != sizeof(compat_sigset_t))
2920 goto out;
2921 r = -EFAULT;
2922 if (get_compat_sigset(&sigset, (void *)sigmask_arg->sigset))
2923 goto out;
2924 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2925 } else
2926 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
2927 break;
2929 default:
2930 r = kvm_vcpu_ioctl(filp, ioctl, arg);
2933 out:
2934 return r;
2936 #endif
2938 static int kvm_device_ioctl_attr(struct kvm_device *dev,
2939 int (*accessor)(struct kvm_device *dev,
2940 struct kvm_device_attr *attr),
2941 unsigned long arg)
2943 struct kvm_device_attr attr;
2945 if (!accessor)
2946 return -EPERM;
2948 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2949 return -EFAULT;
2951 return accessor(dev, &attr);
2954 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
2955 unsigned long arg)
2957 struct kvm_device *dev = filp->private_data;
2959 if (dev->kvm->mm != current->mm)
2960 return -EIO;
2962 switch (ioctl) {
2963 case KVM_SET_DEVICE_ATTR:
2964 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
2965 case KVM_GET_DEVICE_ATTR:
2966 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
2967 case KVM_HAS_DEVICE_ATTR:
2968 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
2969 default:
2970 if (dev->ops->ioctl)
2971 return dev->ops->ioctl(dev, ioctl, arg);
2973 return -ENOTTY;
2977 static int kvm_device_release(struct inode *inode, struct file *filp)
2979 struct kvm_device *dev = filp->private_data;
2980 struct kvm *kvm = dev->kvm;
2982 kvm_put_kvm(kvm);
2983 return 0;
2986 static const struct file_operations kvm_device_fops = {
2987 .unlocked_ioctl = kvm_device_ioctl,
2988 .release = kvm_device_release,
2989 KVM_COMPAT(kvm_device_ioctl),
2992 struct kvm_device *kvm_device_from_filp(struct file *filp)
2994 if (filp->f_op != &kvm_device_fops)
2995 return NULL;
2997 return filp->private_data;
3000 static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
3001 #ifdef CONFIG_KVM_MPIC
3002 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3003 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3004 #endif
3007 int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
3009 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3010 return -ENOSPC;
3012 if (kvm_device_ops_table[type] != NULL)
3013 return -EEXIST;
3015 kvm_device_ops_table[type] = ops;
3016 return 0;
3019 void kvm_unregister_device_ops(u32 type)
3021 if (kvm_device_ops_table[type] != NULL)
3022 kvm_device_ops_table[type] = NULL;
3025 static int kvm_ioctl_create_device(struct kvm *kvm,
3026 struct kvm_create_device *cd)
3028 struct kvm_device_ops *ops = NULL;
3029 struct kvm_device *dev;
3030 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
3031 int type;
3032 int ret;
3034 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3035 return -ENODEV;
3037 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3038 ops = kvm_device_ops_table[type];
3039 if (ops == NULL)
3040 return -ENODEV;
3042 if (test)
3043 return 0;
3045 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3046 if (!dev)
3047 return -ENOMEM;
3049 dev->ops = ops;
3050 dev->kvm = kvm;
3052 mutex_lock(&kvm->lock);
3053 ret = ops->create(dev, type);
3054 if (ret < 0) {
3055 mutex_unlock(&kvm->lock);
3056 kfree(dev);
3057 return ret;
3059 list_add(&dev->vm_node, &kvm->devices);
3060 mutex_unlock(&kvm->lock);
3062 if (ops->init)
3063 ops->init(dev);
3065 kvm_get_kvm(kvm);
3066 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3067 if (ret < 0) {
3068 kvm_put_kvm(kvm);
3069 mutex_lock(&kvm->lock);
3070 list_del(&dev->vm_node);
3071 mutex_unlock(&kvm->lock);
3072 ops->destroy(dev);
3073 return ret;
3076 cd->fd = ret;
3077 return 0;
3080 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3082 switch (arg) {
3083 case KVM_CAP_USER_MEMORY:
3084 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3085 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3086 case KVM_CAP_INTERNAL_ERROR_DATA:
3087 #ifdef CONFIG_HAVE_KVM_MSI
3088 case KVM_CAP_SIGNAL_MSI:
3089 #endif
3090 #ifdef CONFIG_HAVE_KVM_IRQFD
3091 case KVM_CAP_IRQFD:
3092 case KVM_CAP_IRQFD_RESAMPLE:
3093 #endif
3094 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3095 case KVM_CAP_CHECK_EXTENSION_VM:
3096 return 1;
3097 #ifdef CONFIG_KVM_MMIO
3098 case KVM_CAP_COALESCED_MMIO:
3099 return KVM_COALESCED_MMIO_PAGE_OFFSET;
3100 #endif
3101 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3102 case KVM_CAP_IRQ_ROUTING:
3103 return KVM_MAX_IRQ_ROUTES;
3104 #endif
3105 #if KVM_ADDRESS_SPACE_NUM > 1
3106 case KVM_CAP_MULTI_ADDRESS_SPACE:
3107 return KVM_ADDRESS_SPACE_NUM;
3108 #endif
3109 default:
3110 break;
3112 return kvm_vm_ioctl_check_extension(kvm, arg);
3115 static long kvm_vm_ioctl(struct file *filp,
3116 unsigned int ioctl, unsigned long arg)
3118 struct kvm *kvm = filp->private_data;
3119 void __user *argp = (void __user *)arg;
3120 int r;
3122 if (kvm->mm != current->mm)
3123 return -EIO;
3124 switch (ioctl) {
3125 case KVM_CREATE_VCPU:
3126 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3127 break;
3128 case KVM_SET_USER_MEMORY_REGION: {
3129 struct kvm_userspace_memory_region kvm_userspace_mem;
3131 r = -EFAULT;
3132 if (copy_from_user(&kvm_userspace_mem, argp,
3133 sizeof(kvm_userspace_mem)))
3134 goto out;
3136 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3137 break;
3139 case KVM_GET_DIRTY_LOG: {
3140 struct kvm_dirty_log log;
3142 r = -EFAULT;
3143 if (copy_from_user(&log, argp, sizeof(log)))
3144 goto out;
3145 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3146 break;
3148 #ifdef CONFIG_KVM_MMIO
3149 case KVM_REGISTER_COALESCED_MMIO: {
3150 struct kvm_coalesced_mmio_zone zone;
3152 r = -EFAULT;
3153 if (copy_from_user(&zone, argp, sizeof(zone)))
3154 goto out;
3155 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3156 break;
3158 case KVM_UNREGISTER_COALESCED_MMIO: {
3159 struct kvm_coalesced_mmio_zone zone;
3161 r = -EFAULT;
3162 if (copy_from_user(&zone, argp, sizeof(zone)))
3163 goto out;
3164 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3165 break;
3167 #endif
3168 case KVM_IRQFD: {
3169 struct kvm_irqfd data;
3171 r = -EFAULT;
3172 if (copy_from_user(&data, argp, sizeof(data)))
3173 goto out;
3174 r = kvm_irqfd(kvm, &data);
3175 break;
3177 case KVM_IOEVENTFD: {
3178 struct kvm_ioeventfd data;
3180 r = -EFAULT;
3181 if (copy_from_user(&data, argp, sizeof(data)))
3182 goto out;
3183 r = kvm_ioeventfd(kvm, &data);
3184 break;
3186 #ifdef CONFIG_HAVE_KVM_MSI
3187 case KVM_SIGNAL_MSI: {
3188 struct kvm_msi msi;
3190 r = -EFAULT;
3191 if (copy_from_user(&msi, argp, sizeof(msi)))
3192 goto out;
3193 r = kvm_send_userspace_msi(kvm, &msi);
3194 break;
3196 #endif
3197 #ifdef __KVM_HAVE_IRQ_LINE
3198 case KVM_IRQ_LINE_STATUS:
3199 case KVM_IRQ_LINE: {
3200 struct kvm_irq_level irq_event;
3202 r = -EFAULT;
3203 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3204 goto out;
3206 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3207 ioctl == KVM_IRQ_LINE_STATUS);
3208 if (r)
3209 goto out;
3211 r = -EFAULT;
3212 if (ioctl == KVM_IRQ_LINE_STATUS) {
3213 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3214 goto out;
3217 r = 0;
3218 break;
3220 #endif
3221 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3222 case KVM_SET_GSI_ROUTING: {
3223 struct kvm_irq_routing routing;
3224 struct kvm_irq_routing __user *urouting;
3225 struct kvm_irq_routing_entry *entries = NULL;
3227 r = -EFAULT;
3228 if (copy_from_user(&routing, argp, sizeof(routing)))
3229 goto out;
3230 r = -EINVAL;
3231 if (!kvm_arch_can_set_irq_routing(kvm))
3232 goto out;
3233 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3234 goto out;
3235 if (routing.flags)
3236 goto out;
3237 if (routing.nr) {
3238 r = -ENOMEM;
3239 entries = vmalloc(array_size(sizeof(*entries),
3240 routing.nr));
3241 if (!entries)
3242 goto out;
3243 r = -EFAULT;
3244 urouting = argp;
3245 if (copy_from_user(entries, urouting->entries,
3246 routing.nr * sizeof(*entries)))
3247 goto out_free_irq_routing;
3249 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3250 routing.flags);
3251 out_free_irq_routing:
3252 vfree(entries);
3253 break;
3255 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3256 case KVM_CREATE_DEVICE: {
3257 struct kvm_create_device cd;
3259 r = -EFAULT;
3260 if (copy_from_user(&cd, argp, sizeof(cd)))
3261 goto out;
3263 r = kvm_ioctl_create_device(kvm, &cd);
3264 if (r)
3265 goto out;
3267 r = -EFAULT;
3268 if (copy_to_user(argp, &cd, sizeof(cd)))
3269 goto out;
3271 r = 0;
3272 break;
3274 case KVM_CHECK_EXTENSION:
3275 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3276 break;
3277 default:
3278 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3280 out:
3281 return r;
3284 #ifdef CONFIG_KVM_COMPAT
3285 struct compat_kvm_dirty_log {
3286 __u32 slot;
3287 __u32 padding1;
3288 union {
3289 compat_uptr_t dirty_bitmap; /* one bit per page */
3290 __u64 padding2;
3294 static long kvm_vm_compat_ioctl(struct file *filp,
3295 unsigned int ioctl, unsigned long arg)
3297 struct kvm *kvm = filp->private_data;
3298 int r;
3300 if (kvm->mm != current->mm)
3301 return -EIO;
3302 switch (ioctl) {
3303 case KVM_GET_DIRTY_LOG: {
3304 struct compat_kvm_dirty_log compat_log;
3305 struct kvm_dirty_log log;
3307 if (copy_from_user(&compat_log, (void __user *)arg,
3308 sizeof(compat_log)))
3309 return -EFAULT;
3310 log.slot = compat_log.slot;
3311 log.padding1 = compat_log.padding1;
3312 log.padding2 = compat_log.padding2;
3313 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3315 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3316 break;
3318 default:
3319 r = kvm_vm_ioctl(filp, ioctl, arg);
3321 return r;
3323 #endif
3325 static struct file_operations kvm_vm_fops = {
3326 .release = kvm_vm_release,
3327 .unlocked_ioctl = kvm_vm_ioctl,
3328 .llseek = noop_llseek,
3329 KVM_COMPAT(kvm_vm_compat_ioctl),
3332 static int kvm_dev_ioctl_create_vm(unsigned long type)
3334 int r;
3335 struct kvm *kvm;
3336 struct file *file;
3338 kvm = kvm_create_vm(type);
3339 if (IS_ERR(kvm))
3340 return PTR_ERR(kvm);
3341 #ifdef CONFIG_KVM_MMIO
3342 r = kvm_coalesced_mmio_init(kvm);
3343 if (r < 0)
3344 goto put_kvm;
3345 #endif
3346 r = get_unused_fd_flags(O_CLOEXEC);
3347 if (r < 0)
3348 goto put_kvm;
3350 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3351 if (IS_ERR(file)) {
3352 put_unused_fd(r);
3353 r = PTR_ERR(file);
3354 goto put_kvm;
3358 * Don't call kvm_put_kvm anymore at this point; file->f_op is
3359 * already set, with ->release() being kvm_vm_release(). In error
3360 * cases it will be called by the final fput(file) and will take
3361 * care of doing kvm_put_kvm(kvm).
3363 if (kvm_create_vm_debugfs(kvm, r) < 0) {
3364 put_unused_fd(r);
3365 fput(file);
3366 return -ENOMEM;
3368 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
3370 fd_install(r, file);
3371 return r;
3373 put_kvm:
3374 kvm_put_kvm(kvm);
3375 return r;
3378 static long kvm_dev_ioctl(struct file *filp,
3379 unsigned int ioctl, unsigned long arg)
3381 long r = -EINVAL;
3383 switch (ioctl) {
3384 case KVM_GET_API_VERSION:
3385 if (arg)
3386 goto out;
3387 r = KVM_API_VERSION;
3388 break;
3389 case KVM_CREATE_VM:
3390 r = kvm_dev_ioctl_create_vm(arg);
3391 break;
3392 case KVM_CHECK_EXTENSION:
3393 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3394 break;
3395 case KVM_GET_VCPU_MMAP_SIZE:
3396 if (arg)
3397 goto out;
3398 r = PAGE_SIZE; /* struct kvm_run */
3399 #ifdef CONFIG_X86
3400 r += PAGE_SIZE; /* pio data page */
3401 #endif
3402 #ifdef CONFIG_KVM_MMIO
3403 r += PAGE_SIZE; /* coalesced mmio ring page */
3404 #endif
3405 break;
3406 case KVM_TRACE_ENABLE:
3407 case KVM_TRACE_PAUSE:
3408 case KVM_TRACE_DISABLE:
3409 r = -EOPNOTSUPP;
3410 break;
3411 default:
3412 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3414 out:
3415 return r;
3418 static struct file_operations kvm_chardev_ops = {
3419 .unlocked_ioctl = kvm_dev_ioctl,
3420 .llseek = noop_llseek,
3421 KVM_COMPAT(kvm_dev_ioctl),
3424 static struct miscdevice kvm_dev = {
3425 KVM_MINOR,
3426 "kvm",
3427 &kvm_chardev_ops,
3430 static void hardware_enable_nolock(void *junk)
3432 int cpu = raw_smp_processor_id();
3433 int r;
3435 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3436 return;
3438 cpumask_set_cpu(cpu, cpus_hardware_enabled);
3440 r = kvm_arch_hardware_enable();
3442 if (r) {
3443 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3444 atomic_inc(&hardware_enable_failed);
3445 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3449 static int kvm_starting_cpu(unsigned int cpu)
3451 raw_spin_lock(&kvm_count_lock);
3452 if (kvm_usage_count)
3453 hardware_enable_nolock(NULL);
3454 raw_spin_unlock(&kvm_count_lock);
3455 return 0;
3458 static void hardware_disable_nolock(void *junk)
3460 int cpu = raw_smp_processor_id();
3462 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3463 return;
3464 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3465 kvm_arch_hardware_disable();
3468 static int kvm_dying_cpu(unsigned int cpu)
3470 raw_spin_lock(&kvm_count_lock);
3471 if (kvm_usage_count)
3472 hardware_disable_nolock(NULL);
3473 raw_spin_unlock(&kvm_count_lock);
3474 return 0;
3477 static void hardware_disable_all_nolock(void)
3479 BUG_ON(!kvm_usage_count);
3481 kvm_usage_count--;
3482 if (!kvm_usage_count)
3483 on_each_cpu(hardware_disable_nolock, NULL, 1);
3486 static void hardware_disable_all(void)
3488 raw_spin_lock(&kvm_count_lock);
3489 hardware_disable_all_nolock();
3490 raw_spin_unlock(&kvm_count_lock);
3493 static int hardware_enable_all(void)
3495 int r = 0;
3497 raw_spin_lock(&kvm_count_lock);
3499 kvm_usage_count++;
3500 if (kvm_usage_count == 1) {
3501 atomic_set(&hardware_enable_failed, 0);
3502 on_each_cpu(hardware_enable_nolock, NULL, 1);
3504 if (atomic_read(&hardware_enable_failed)) {
3505 hardware_disable_all_nolock();
3506 r = -EBUSY;
3510 raw_spin_unlock(&kvm_count_lock);
3512 return r;
3515 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3516 void *v)
3519 * Some (well, at least mine) BIOSes hang on reboot if
3520 * in vmx root mode.
3522 * And Intel TXT required VMX off for all cpu when system shutdown.
3524 pr_info("kvm: exiting hardware virtualization\n");
3525 kvm_rebooting = true;
3526 on_each_cpu(hardware_disable_nolock, NULL, 1);
3527 return NOTIFY_OK;
3530 static struct notifier_block kvm_reboot_notifier = {
3531 .notifier_call = kvm_reboot,
3532 .priority = 0,
3535 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3537 int i;
3539 for (i = 0; i < bus->dev_count; i++) {
3540 struct kvm_io_device *pos = bus->range[i].dev;
3542 kvm_iodevice_destructor(pos);
3544 kfree(bus);
3547 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
3548 const struct kvm_io_range *r2)
3550 gpa_t addr1 = r1->addr;
3551 gpa_t addr2 = r2->addr;
3553 if (addr1 < addr2)
3554 return -1;
3556 /* If r2->len == 0, match the exact address. If r2->len != 0,
3557 * accept any overlapping write. Any order is acceptable for
3558 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3559 * we process all of them.
3561 if (r2->len) {
3562 addr1 += r1->len;
3563 addr2 += r2->len;
3566 if (addr1 > addr2)
3567 return 1;
3569 return 0;
3572 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3574 return kvm_io_bus_cmp(p1, p2);
3577 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
3578 gpa_t addr, int len)
3580 struct kvm_io_range *range, key;
3581 int off;
3583 key = (struct kvm_io_range) {
3584 .addr = addr,
3585 .len = len,
3588 range = bsearch(&key, bus->range, bus->dev_count,
3589 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3590 if (range == NULL)
3591 return -ENOENT;
3593 off = range - bus->range;
3595 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
3596 off--;
3598 return off;
3601 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3602 struct kvm_io_range *range, const void *val)
3604 int idx;
3606 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3607 if (idx < 0)
3608 return -EOPNOTSUPP;
3610 while (idx < bus->dev_count &&
3611 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3612 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
3613 range->len, val))
3614 return idx;
3615 idx++;
3618 return -EOPNOTSUPP;
3621 /* kvm_io_bus_write - called under kvm->slots_lock */
3622 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3623 int len, const void *val)
3625 struct kvm_io_bus *bus;
3626 struct kvm_io_range range;
3627 int r;
3629 range = (struct kvm_io_range) {
3630 .addr = addr,
3631 .len = len,
3634 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3635 if (!bus)
3636 return -ENOMEM;
3637 r = __kvm_io_bus_write(vcpu, bus, &range, val);
3638 return r < 0 ? r : 0;
3641 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
3642 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
3643 gpa_t addr, int len, const void *val, long cookie)
3645 struct kvm_io_bus *bus;
3646 struct kvm_io_range range;
3648 range = (struct kvm_io_range) {
3649 .addr = addr,
3650 .len = len,
3653 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3654 if (!bus)
3655 return -ENOMEM;
3657 /* First try the device referenced by cookie. */
3658 if ((cookie >= 0) && (cookie < bus->dev_count) &&
3659 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
3660 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
3661 val))
3662 return cookie;
3665 * cookie contained garbage; fall back to search and return the
3666 * correct cookie value.
3668 return __kvm_io_bus_write(vcpu, bus, &range, val);
3671 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3672 struct kvm_io_range *range, void *val)
3674 int idx;
3676 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3677 if (idx < 0)
3678 return -EOPNOTSUPP;
3680 while (idx < bus->dev_count &&
3681 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3682 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
3683 range->len, val))
3684 return idx;
3685 idx++;
3688 return -EOPNOTSUPP;
3690 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
3692 /* kvm_io_bus_read - called under kvm->slots_lock */
3693 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3694 int len, void *val)
3696 struct kvm_io_bus *bus;
3697 struct kvm_io_range range;
3698 int r;
3700 range = (struct kvm_io_range) {
3701 .addr = addr,
3702 .len = len,
3705 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3706 if (!bus)
3707 return -ENOMEM;
3708 r = __kvm_io_bus_read(vcpu, bus, &range, val);
3709 return r < 0 ? r : 0;
3713 /* Caller must hold slots_lock. */
3714 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3715 int len, struct kvm_io_device *dev)
3717 int i;
3718 struct kvm_io_bus *new_bus, *bus;
3719 struct kvm_io_range range;
3721 bus = kvm_get_bus(kvm, bus_idx);
3722 if (!bus)
3723 return -ENOMEM;
3725 /* exclude ioeventfd which is limited by maximum fd */
3726 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
3727 return -ENOSPC;
3729 new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count + 1) *
3730 sizeof(struct kvm_io_range)), GFP_KERNEL);
3731 if (!new_bus)
3732 return -ENOMEM;
3734 range = (struct kvm_io_range) {
3735 .addr = addr,
3736 .len = len,
3737 .dev = dev,
3740 for (i = 0; i < bus->dev_count; i++)
3741 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
3742 break;
3744 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3745 new_bus->dev_count++;
3746 new_bus->range[i] = range;
3747 memcpy(new_bus->range + i + 1, bus->range + i,
3748 (bus->dev_count - i) * sizeof(struct kvm_io_range));
3749 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3750 synchronize_srcu_expedited(&kvm->srcu);
3751 kfree(bus);
3753 return 0;
3756 /* Caller must hold slots_lock. */
3757 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3758 struct kvm_io_device *dev)
3760 int i;
3761 struct kvm_io_bus *new_bus, *bus;
3763 bus = kvm_get_bus(kvm, bus_idx);
3764 if (!bus)
3765 return;
3767 for (i = 0; i < bus->dev_count; i++)
3768 if (bus->range[i].dev == dev) {
3769 break;
3772 if (i == bus->dev_count)
3773 return;
3775 new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count - 1) *
3776 sizeof(struct kvm_io_range)), GFP_KERNEL);
3777 if (!new_bus) {
3778 pr_err("kvm: failed to shrink bus, removing it completely\n");
3779 goto broken;
3782 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3783 new_bus->dev_count--;
3784 memcpy(new_bus->range + i, bus->range + i + 1,
3785 (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
3787 broken:
3788 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3789 synchronize_srcu_expedited(&kvm->srcu);
3790 kfree(bus);
3791 return;
3794 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3795 gpa_t addr)
3797 struct kvm_io_bus *bus;
3798 int dev_idx, srcu_idx;
3799 struct kvm_io_device *iodev = NULL;
3801 srcu_idx = srcu_read_lock(&kvm->srcu);
3803 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3804 if (!bus)
3805 goto out_unlock;
3807 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
3808 if (dev_idx < 0)
3809 goto out_unlock;
3811 iodev = bus->range[dev_idx].dev;
3813 out_unlock:
3814 srcu_read_unlock(&kvm->srcu, srcu_idx);
3816 return iodev;
3818 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
3820 static int kvm_debugfs_open(struct inode *inode, struct file *file,
3821 int (*get)(void *, u64 *), int (*set)(void *, u64),
3822 const char *fmt)
3824 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3825 inode->i_private;
3827 /* The debugfs files are a reference to the kvm struct which
3828 * is still valid when kvm_destroy_vm is called.
3829 * To avoid the race between open and the removal of the debugfs
3830 * directory we test against the users count.
3832 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
3833 return -ENOENT;
3835 if (simple_attr_open(inode, file, get,
3836 stat_data->mode & S_IWUGO ? set : NULL,
3837 fmt)) {
3838 kvm_put_kvm(stat_data->kvm);
3839 return -ENOMEM;
3842 return 0;
3845 static int kvm_debugfs_release(struct inode *inode, struct file *file)
3847 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3848 inode->i_private;
3850 simple_attr_release(inode, file);
3851 kvm_put_kvm(stat_data->kvm);
3853 return 0;
3856 static int vm_stat_get_per_vm(void *data, u64 *val)
3858 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3860 *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
3862 return 0;
3865 static int vm_stat_clear_per_vm(void *data, u64 val)
3867 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3869 if (val)
3870 return -EINVAL;
3872 *(ulong *)((void *)stat_data->kvm + stat_data->offset) = 0;
3874 return 0;
3877 static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
3879 __simple_attr_check_format("%llu\n", 0ull);
3880 return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
3881 vm_stat_clear_per_vm, "%llu\n");
3884 static const struct file_operations vm_stat_get_per_vm_fops = {
3885 .owner = THIS_MODULE,
3886 .open = vm_stat_get_per_vm_open,
3887 .release = kvm_debugfs_release,
3888 .read = simple_attr_read,
3889 .write = simple_attr_write,
3890 .llseek = no_llseek,
3893 static int vcpu_stat_get_per_vm(void *data, u64 *val)
3895 int i;
3896 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3897 struct kvm_vcpu *vcpu;
3899 *val = 0;
3901 kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3902 *val += *(u64 *)((void *)vcpu + stat_data->offset);
3904 return 0;
3907 static int vcpu_stat_clear_per_vm(void *data, u64 val)
3909 int i;
3910 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3911 struct kvm_vcpu *vcpu;
3913 if (val)
3914 return -EINVAL;
3916 kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3917 *(u64 *)((void *)vcpu + stat_data->offset) = 0;
3919 return 0;
3922 static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
3924 __simple_attr_check_format("%llu\n", 0ull);
3925 return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
3926 vcpu_stat_clear_per_vm, "%llu\n");
3929 static const struct file_operations vcpu_stat_get_per_vm_fops = {
3930 .owner = THIS_MODULE,
3931 .open = vcpu_stat_get_per_vm_open,
3932 .release = kvm_debugfs_release,
3933 .read = simple_attr_read,
3934 .write = simple_attr_write,
3935 .llseek = no_llseek,
3938 static const struct file_operations *stat_fops_per_vm[] = {
3939 [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
3940 [KVM_STAT_VM] = &vm_stat_get_per_vm_fops,
3943 static int vm_stat_get(void *_offset, u64 *val)
3945 unsigned offset = (long)_offset;
3946 struct kvm *kvm;
3947 struct kvm_stat_data stat_tmp = {.offset = offset};
3948 u64 tmp_val;
3950 *val = 0;
3951 mutex_lock(&kvm_lock);
3952 list_for_each_entry(kvm, &vm_list, vm_list) {
3953 stat_tmp.kvm = kvm;
3954 vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3955 *val += tmp_val;
3957 mutex_unlock(&kvm_lock);
3958 return 0;
3961 static int vm_stat_clear(void *_offset, u64 val)
3963 unsigned offset = (long)_offset;
3964 struct kvm *kvm;
3965 struct kvm_stat_data stat_tmp = {.offset = offset};
3967 if (val)
3968 return -EINVAL;
3970 mutex_lock(&kvm_lock);
3971 list_for_each_entry(kvm, &vm_list, vm_list) {
3972 stat_tmp.kvm = kvm;
3973 vm_stat_clear_per_vm((void *)&stat_tmp, 0);
3975 mutex_unlock(&kvm_lock);
3977 return 0;
3980 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
3982 static int vcpu_stat_get(void *_offset, u64 *val)
3984 unsigned offset = (long)_offset;
3985 struct kvm *kvm;
3986 struct kvm_stat_data stat_tmp = {.offset = offset};
3987 u64 tmp_val;
3989 *val = 0;
3990 mutex_lock(&kvm_lock);
3991 list_for_each_entry(kvm, &vm_list, vm_list) {
3992 stat_tmp.kvm = kvm;
3993 vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3994 *val += tmp_val;
3996 mutex_unlock(&kvm_lock);
3997 return 0;
4000 static int vcpu_stat_clear(void *_offset, u64 val)
4002 unsigned offset = (long)_offset;
4003 struct kvm *kvm;
4004 struct kvm_stat_data stat_tmp = {.offset = offset};
4006 if (val)
4007 return -EINVAL;
4009 mutex_lock(&kvm_lock);
4010 list_for_each_entry(kvm, &vm_list, vm_list) {
4011 stat_tmp.kvm = kvm;
4012 vcpu_stat_clear_per_vm((void *)&stat_tmp, 0);
4014 mutex_unlock(&kvm_lock);
4016 return 0;
4019 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4020 "%llu\n");
4022 static const struct file_operations *stat_fops[] = {
4023 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4024 [KVM_STAT_VM] = &vm_stat_fops,
4027 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4029 struct kobj_uevent_env *env;
4030 unsigned long long created, active;
4032 if (!kvm_dev.this_device || !kvm)
4033 return;
4035 mutex_lock(&kvm_lock);
4036 if (type == KVM_EVENT_CREATE_VM) {
4037 kvm_createvm_count++;
4038 kvm_active_vms++;
4039 } else if (type == KVM_EVENT_DESTROY_VM) {
4040 kvm_active_vms--;
4042 created = kvm_createvm_count;
4043 active = kvm_active_vms;
4044 mutex_unlock(&kvm_lock);
4046 env = kzalloc(sizeof(*env), GFP_KERNEL);
4047 if (!env)
4048 return;
4050 add_uevent_var(env, "CREATED=%llu", created);
4051 add_uevent_var(env, "COUNT=%llu", active);
4053 if (type == KVM_EVENT_CREATE_VM) {
4054 add_uevent_var(env, "EVENT=create");
4055 kvm->userspace_pid = task_pid_nr(current);
4056 } else if (type == KVM_EVENT_DESTROY_VM) {
4057 add_uevent_var(env, "EVENT=destroy");
4059 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
4061 if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
4062 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL);
4064 if (p) {
4065 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4066 if (!IS_ERR(tmp))
4067 add_uevent_var(env, "STATS_PATH=%s", tmp);
4068 kfree(p);
4071 /* no need for checks, since we are adding at most only 5 keys */
4072 env->envp[env->envp_idx++] = NULL;
4073 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4074 kfree(env);
4077 static void kvm_init_debug(void)
4079 struct kvm_stats_debugfs_item *p;
4081 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4083 kvm_debugfs_num_entries = 0;
4084 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
4085 int mode = p->mode ? p->mode : 0644;
4086 debugfs_create_file(p->name, mode, kvm_debugfs_dir,
4087 (void *)(long)p->offset,
4088 stat_fops[p->kind]);
4092 static int kvm_suspend(void)
4094 if (kvm_usage_count)
4095 hardware_disable_nolock(NULL);
4096 return 0;
4099 static void kvm_resume(void)
4101 if (kvm_usage_count) {
4102 WARN_ON(raw_spin_is_locked(&kvm_count_lock));
4103 hardware_enable_nolock(NULL);
4107 static struct syscore_ops kvm_syscore_ops = {
4108 .suspend = kvm_suspend,
4109 .resume = kvm_resume,
4112 static inline
4113 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4115 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4118 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4120 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4122 if (vcpu->preempted)
4123 vcpu->preempted = false;
4125 kvm_arch_sched_in(vcpu, cpu);
4127 kvm_arch_vcpu_load(vcpu, cpu);
4130 static void kvm_sched_out(struct preempt_notifier *pn,
4131 struct task_struct *next)
4133 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4135 if (current->state == TASK_RUNNING)
4136 vcpu->preempted = true;
4137 kvm_arch_vcpu_put(vcpu);
4140 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
4141 struct module *module)
4143 int r;
4144 int cpu;
4146 r = kvm_arch_init(opaque);
4147 if (r)
4148 goto out_fail;
4151 * kvm_arch_init makes sure there's at most one caller
4152 * for architectures that support multiple implementations,
4153 * like intel and amd on x86.
4154 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4155 * conflicts in case kvm is already setup for another implementation.
4157 r = kvm_irqfd_init();
4158 if (r)
4159 goto out_irqfd;
4161 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
4162 r = -ENOMEM;
4163 goto out_free_0;
4166 r = kvm_arch_hardware_setup();
4167 if (r < 0)
4168 goto out_free_0a;
4170 for_each_online_cpu(cpu) {
4171 smp_call_function_single(cpu,
4172 kvm_arch_check_processor_compat,
4173 &r, 1);
4174 if (r < 0)
4175 goto out_free_1;
4178 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
4179 kvm_starting_cpu, kvm_dying_cpu);
4180 if (r)
4181 goto out_free_2;
4182 register_reboot_notifier(&kvm_reboot_notifier);
4184 /* A kmem cache lets us meet the alignment requirements of fx_save. */
4185 if (!vcpu_align)
4186 vcpu_align = __alignof__(struct kvm_vcpu);
4187 kvm_vcpu_cache =
4188 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4189 SLAB_ACCOUNT,
4190 offsetof(struct kvm_vcpu, arch),
4191 sizeof_field(struct kvm_vcpu, arch),
4192 NULL);
4193 if (!kvm_vcpu_cache) {
4194 r = -ENOMEM;
4195 goto out_free_3;
4198 r = kvm_async_pf_init();
4199 if (r)
4200 goto out_free;
4202 kvm_chardev_ops.owner = module;
4203 kvm_vm_fops.owner = module;
4204 kvm_vcpu_fops.owner = module;
4206 r = misc_register(&kvm_dev);
4207 if (r) {
4208 pr_err("kvm: misc device register failed\n");
4209 goto out_unreg;
4212 register_syscore_ops(&kvm_syscore_ops);
4214 kvm_preempt_ops.sched_in = kvm_sched_in;
4215 kvm_preempt_ops.sched_out = kvm_sched_out;
4217 kvm_init_debug();
4219 r = kvm_vfio_ops_init();
4220 WARN_ON(r);
4222 return 0;
4224 out_unreg:
4225 kvm_async_pf_deinit();
4226 out_free:
4227 kmem_cache_destroy(kvm_vcpu_cache);
4228 out_free_3:
4229 unregister_reboot_notifier(&kvm_reboot_notifier);
4230 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4231 out_free_2:
4232 out_free_1:
4233 kvm_arch_hardware_unsetup();
4234 out_free_0a:
4235 free_cpumask_var(cpus_hardware_enabled);
4236 out_free_0:
4237 kvm_irqfd_exit();
4238 out_irqfd:
4239 kvm_arch_exit();
4240 out_fail:
4241 return r;
4243 EXPORT_SYMBOL_GPL(kvm_init);
4245 void kvm_exit(void)
4247 debugfs_remove_recursive(kvm_debugfs_dir);
4248 misc_deregister(&kvm_dev);
4249 kmem_cache_destroy(kvm_vcpu_cache);
4250 kvm_async_pf_deinit();
4251 unregister_syscore_ops(&kvm_syscore_ops);
4252 unregister_reboot_notifier(&kvm_reboot_notifier);
4253 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4254 on_each_cpu(hardware_disable_nolock, NULL, 1);
4255 kvm_arch_hardware_unsetup();
4256 kvm_arch_exit();
4257 kvm_irqfd_exit();
4258 free_cpumask_var(cpus_hardware_enabled);
4259 kvm_vfio_ops_exit();
4261 EXPORT_SYMBOL_GPL(kvm_exit);
4263 struct kvm_vm_worker_thread_context {
4264 struct kvm *kvm;
4265 struct task_struct *parent;
4266 struct completion init_done;
4267 kvm_vm_thread_fn_t thread_fn;
4268 uintptr_t data;
4269 int err;
4272 static int kvm_vm_worker_thread(void *context)
4275 * The init_context is allocated on the stack of the parent thread, so
4276 * we have to locally copy anything that is needed beyond initialization
4278 struct kvm_vm_worker_thread_context *init_context = context;
4279 struct kvm *kvm = init_context->kvm;
4280 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4281 uintptr_t data = init_context->data;
4282 int err;
4284 err = kthread_park(current);
4285 /* kthread_park(current) is never supposed to return an error */
4286 WARN_ON(err != 0);
4287 if (err)
4288 goto init_complete;
4290 err = cgroup_attach_task_all(init_context->parent, current);
4291 if (err) {
4292 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4293 __func__, err);
4294 goto init_complete;
4297 set_user_nice(current, task_nice(init_context->parent));
4299 init_complete:
4300 init_context->err = err;
4301 complete(&init_context->init_done);
4302 init_context = NULL;
4304 if (err)
4305 return err;
4307 /* Wait to be woken up by the spawner before proceeding. */
4308 kthread_parkme();
4310 if (!kthread_should_stop())
4311 err = thread_fn(kvm, data);
4313 return err;
4316 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4317 uintptr_t data, const char *name,
4318 struct task_struct **thread_ptr)
4320 struct kvm_vm_worker_thread_context init_context = {};
4321 struct task_struct *thread;
4323 *thread_ptr = NULL;
4324 init_context.kvm = kvm;
4325 init_context.parent = current;
4326 init_context.thread_fn = thread_fn;
4327 init_context.data = data;
4328 init_completion(&init_context.init_done);
4330 thread = kthread_run(kvm_vm_worker_thread, &init_context,
4331 "%s-%d", name, task_pid_nr(current));
4332 if (IS_ERR(thread))
4333 return PTR_ERR(thread);
4335 /* kthread_run is never supposed to return NULL */
4336 WARN_ON(thread == NULL);
4338 wait_for_completion(&init_context.init_done);
4340 if (!init_context.err)
4341 *thread_ptr = thread;
4343 return init_context.err;