Revert "tty: hvc: Fix data abort due to race in hvc_open"
[linux/fpc-iii.git] / virt / kvm / kvm_main.c
blob77aa91fb08d2b90cb1ce33d15c167c85b0ef4d97
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11 * Authors:
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <kvm/iodev.h>
18 #include <linux/kvm_host.h>
19 #include <linux/kvm.h>
20 #include <linux/module.h>
21 #include <linux/errno.h>
22 #include <linux/percpu.h>
23 #include <linux/mm.h>
24 #include <linux/miscdevice.h>
25 #include <linux/vmalloc.h>
26 #include <linux/reboot.h>
27 #include <linux/debugfs.h>
28 #include <linux/highmem.h>
29 #include <linux/file.h>
30 #include <linux/syscore_ops.h>
31 #include <linux/cpu.h>
32 #include <linux/sched/signal.h>
33 #include <linux/sched/mm.h>
34 #include <linux/sched/stat.h>
35 #include <linux/cpumask.h>
36 #include <linux/smp.h>
37 #include <linux/anon_inodes.h>
38 #include <linux/profile.h>
39 #include <linux/kvm_para.h>
40 #include <linux/pagemap.h>
41 #include <linux/mman.h>
42 #include <linux/swap.h>
43 #include <linux/bitops.h>
44 #include <linux/spinlock.h>
45 #include <linux/compat.h>
46 #include <linux/srcu.h>
47 #include <linux/hugetlb.h>
48 #include <linux/slab.h>
49 #include <linux/sort.h>
50 #include <linux/bsearch.h>
51 #include <linux/io.h>
52 #include <linux/lockdep.h>
53 #include <linux/kthread.h>
55 #include <asm/processor.h>
56 #include <asm/ioctl.h>
57 #include <linux/uaccess.h>
58 #include <asm/pgtable.h>
60 #include "coalesced_mmio.h"
61 #include "async_pf.h"
62 #include "vfio.h"
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/kvm.h>
67 /* Worst case buffer size needed for holding an integer. */
68 #define ITOA_MAX_LEN 12
70 MODULE_AUTHOR("Qumranet");
71 MODULE_LICENSE("GPL");
73 /* Architectures should define their poll value according to the halt latency */
74 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
75 module_param(halt_poll_ns, uint, 0644);
76 EXPORT_SYMBOL_GPL(halt_poll_ns);
78 /* Default doubles per-vcpu halt_poll_ns. */
79 unsigned int halt_poll_ns_grow = 2;
80 module_param(halt_poll_ns_grow, uint, 0644);
81 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
83 /* The start value to grow halt_poll_ns from */
84 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
85 module_param(halt_poll_ns_grow_start, uint, 0644);
86 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
88 /* Default resets per-vcpu halt_poll_ns . */
89 unsigned int halt_poll_ns_shrink;
90 module_param(halt_poll_ns_shrink, uint, 0644);
91 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
94 * Ordering of locks:
96 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
99 DEFINE_MUTEX(kvm_lock);
100 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
101 LIST_HEAD(vm_list);
103 static cpumask_var_t cpus_hardware_enabled;
104 static int kvm_usage_count;
105 static atomic_t hardware_enable_failed;
107 static struct kmem_cache *kvm_vcpu_cache;
109 static __read_mostly struct preempt_ops kvm_preempt_ops;
110 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
112 struct dentry *kvm_debugfs_dir;
113 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
115 static int kvm_debugfs_num_entries;
116 static const struct file_operations stat_fops_per_vm;
118 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
119 unsigned long arg);
120 #ifdef CONFIG_KVM_COMPAT
121 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
122 unsigned long arg);
123 #define KVM_COMPAT(c) .compat_ioctl = (c)
124 #else
126 * For architectures that don't implement a compat infrastructure,
127 * adopt a double line of defense:
128 * - Prevent a compat task from opening /dev/kvm
129 * - If the open has been done by a 64bit task, and the KVM fd
130 * passed to a compat task, let the ioctls fail.
132 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
133 unsigned long arg) { return -EINVAL; }
135 static int kvm_no_compat_open(struct inode *inode, struct file *file)
137 return is_compat_task() ? -ENODEV : 0;
139 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
140 .open = kvm_no_compat_open
141 #endif
142 static int hardware_enable_all(void);
143 static void hardware_disable_all(void);
145 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
147 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
149 __visible bool kvm_rebooting;
150 EXPORT_SYMBOL_GPL(kvm_rebooting);
152 #define KVM_EVENT_CREATE_VM 0
153 #define KVM_EVENT_DESTROY_VM 1
154 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
155 static unsigned long long kvm_createvm_count;
156 static unsigned long long kvm_active_vms;
158 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
159 unsigned long start, unsigned long end)
163 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
166 * The metadata used by is_zone_device_page() to determine whether or
167 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
168 * the device has been pinned, e.g. by get_user_pages(). WARN if the
169 * page_count() is zero to help detect bad usage of this helper.
171 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
172 return false;
174 return is_zone_device_page(pfn_to_page(pfn));
177 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
180 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
181 * perspective they are "normal" pages, albeit with slightly different
182 * usage rules.
184 if (pfn_valid(pfn))
185 return PageReserved(pfn_to_page(pfn)) &&
186 !is_zero_pfn(pfn) &&
187 !kvm_is_zone_device_pfn(pfn);
189 return true;
192 bool kvm_is_transparent_hugepage(kvm_pfn_t pfn)
194 struct page *page = pfn_to_page(pfn);
196 if (!PageTransCompoundMap(page))
197 return false;
199 return is_transparent_hugepage(compound_head(page));
203 * Switches to specified vcpu, until a matching vcpu_put()
205 void vcpu_load(struct kvm_vcpu *vcpu)
207 int cpu = get_cpu();
209 __this_cpu_write(kvm_running_vcpu, vcpu);
210 preempt_notifier_register(&vcpu->preempt_notifier);
211 kvm_arch_vcpu_load(vcpu, cpu);
212 put_cpu();
214 EXPORT_SYMBOL_GPL(vcpu_load);
216 void vcpu_put(struct kvm_vcpu *vcpu)
218 preempt_disable();
219 kvm_arch_vcpu_put(vcpu);
220 preempt_notifier_unregister(&vcpu->preempt_notifier);
221 __this_cpu_write(kvm_running_vcpu, NULL);
222 preempt_enable();
224 EXPORT_SYMBOL_GPL(vcpu_put);
226 /* TODO: merge with kvm_arch_vcpu_should_kick */
227 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
229 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
232 * We need to wait for the VCPU to reenable interrupts and get out of
233 * READING_SHADOW_PAGE_TABLES mode.
235 if (req & KVM_REQUEST_WAIT)
236 return mode != OUTSIDE_GUEST_MODE;
239 * Need to kick a running VCPU, but otherwise there is nothing to do.
241 return mode == IN_GUEST_MODE;
244 static void ack_flush(void *_completed)
248 static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
250 if (unlikely(!cpus))
251 cpus = cpu_online_mask;
253 if (cpumask_empty(cpus))
254 return false;
256 smp_call_function_many(cpus, ack_flush, NULL, wait);
257 return true;
260 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
261 struct kvm_vcpu *except,
262 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
264 int i, cpu, me;
265 struct kvm_vcpu *vcpu;
266 bool called;
268 me = get_cpu();
270 kvm_for_each_vcpu(i, vcpu, kvm) {
271 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
272 vcpu == except)
273 continue;
275 kvm_make_request(req, vcpu);
276 cpu = vcpu->cpu;
278 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
279 continue;
281 if (tmp != NULL && cpu != -1 && cpu != me &&
282 kvm_request_needs_ipi(vcpu, req))
283 __cpumask_set_cpu(cpu, tmp);
286 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
287 put_cpu();
289 return called;
292 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
293 struct kvm_vcpu *except)
295 cpumask_var_t cpus;
296 bool called;
298 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
300 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
302 free_cpumask_var(cpus);
303 return called;
306 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
308 return kvm_make_all_cpus_request_except(kvm, req, NULL);
311 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
312 void kvm_flush_remote_tlbs(struct kvm *kvm)
315 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
316 * kvm_make_all_cpus_request.
318 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
321 * We want to publish modifications to the page tables before reading
322 * mode. Pairs with a memory barrier in arch-specific code.
323 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
324 * and smp_mb in walk_shadow_page_lockless_begin/end.
325 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
327 * There is already an smp_mb__after_atomic() before
328 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
329 * barrier here.
331 if (!kvm_arch_flush_remote_tlb(kvm)
332 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
333 ++kvm->stat.remote_tlb_flush;
334 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
336 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
337 #endif
339 void kvm_reload_remote_mmus(struct kvm *kvm)
341 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
344 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
346 mutex_init(&vcpu->mutex);
347 vcpu->cpu = -1;
348 vcpu->kvm = kvm;
349 vcpu->vcpu_id = id;
350 vcpu->pid = NULL;
351 init_swait_queue_head(&vcpu->wq);
352 kvm_async_pf_vcpu_init(vcpu);
354 vcpu->pre_pcpu = -1;
355 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
357 kvm_vcpu_set_in_spin_loop(vcpu, false);
358 kvm_vcpu_set_dy_eligible(vcpu, false);
359 vcpu->preempted = false;
360 vcpu->ready = false;
361 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
364 void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
366 kvm_arch_vcpu_destroy(vcpu);
369 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
370 * the vcpu->pid pointer, and at destruction time all file descriptors
371 * are already gone.
373 put_pid(rcu_dereference_protected(vcpu->pid, 1));
375 free_page((unsigned long)vcpu->run);
376 kmem_cache_free(kvm_vcpu_cache, vcpu);
378 EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
380 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
381 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
383 return container_of(mn, struct kvm, mmu_notifier);
386 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
387 struct mm_struct *mm,
388 unsigned long start, unsigned long end)
390 struct kvm *kvm = mmu_notifier_to_kvm(mn);
391 int idx;
393 idx = srcu_read_lock(&kvm->srcu);
394 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
395 srcu_read_unlock(&kvm->srcu, idx);
398 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
399 struct mm_struct *mm,
400 unsigned long address,
401 pte_t pte)
403 struct kvm *kvm = mmu_notifier_to_kvm(mn);
404 int idx;
406 idx = srcu_read_lock(&kvm->srcu);
407 spin_lock(&kvm->mmu_lock);
408 kvm->mmu_notifier_seq++;
410 if (kvm_set_spte_hva(kvm, address, pte))
411 kvm_flush_remote_tlbs(kvm);
413 spin_unlock(&kvm->mmu_lock);
414 srcu_read_unlock(&kvm->srcu, idx);
417 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
418 const struct mmu_notifier_range *range)
420 struct kvm *kvm = mmu_notifier_to_kvm(mn);
421 int need_tlb_flush = 0, idx;
423 idx = srcu_read_lock(&kvm->srcu);
424 spin_lock(&kvm->mmu_lock);
426 * The count increase must become visible at unlock time as no
427 * spte can be established without taking the mmu_lock and
428 * count is also read inside the mmu_lock critical section.
430 kvm->mmu_notifier_count++;
431 need_tlb_flush = kvm_unmap_hva_range(kvm, range->start, range->end);
432 need_tlb_flush |= kvm->tlbs_dirty;
433 /* we've to flush the tlb before the pages can be freed */
434 if (need_tlb_flush)
435 kvm_flush_remote_tlbs(kvm);
437 spin_unlock(&kvm->mmu_lock);
438 srcu_read_unlock(&kvm->srcu, idx);
440 return 0;
443 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
444 const struct mmu_notifier_range *range)
446 struct kvm *kvm = mmu_notifier_to_kvm(mn);
448 spin_lock(&kvm->mmu_lock);
450 * This sequence increase will notify the kvm page fault that
451 * the page that is going to be mapped in the spte could have
452 * been freed.
454 kvm->mmu_notifier_seq++;
455 smp_wmb();
457 * The above sequence increase must be visible before the
458 * below count decrease, which is ensured by the smp_wmb above
459 * in conjunction with the smp_rmb in mmu_notifier_retry().
461 kvm->mmu_notifier_count--;
462 spin_unlock(&kvm->mmu_lock);
464 BUG_ON(kvm->mmu_notifier_count < 0);
467 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
468 struct mm_struct *mm,
469 unsigned long start,
470 unsigned long end)
472 struct kvm *kvm = mmu_notifier_to_kvm(mn);
473 int young, idx;
475 idx = srcu_read_lock(&kvm->srcu);
476 spin_lock(&kvm->mmu_lock);
478 young = kvm_age_hva(kvm, start, end);
479 if (young)
480 kvm_flush_remote_tlbs(kvm);
482 spin_unlock(&kvm->mmu_lock);
483 srcu_read_unlock(&kvm->srcu, idx);
485 return young;
488 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
489 struct mm_struct *mm,
490 unsigned long start,
491 unsigned long end)
493 struct kvm *kvm = mmu_notifier_to_kvm(mn);
494 int young, idx;
496 idx = srcu_read_lock(&kvm->srcu);
497 spin_lock(&kvm->mmu_lock);
499 * Even though we do not flush TLB, this will still adversely
500 * affect performance on pre-Haswell Intel EPT, where there is
501 * no EPT Access Bit to clear so that we have to tear down EPT
502 * tables instead. If we find this unacceptable, we can always
503 * add a parameter to kvm_age_hva so that it effectively doesn't
504 * do anything on clear_young.
506 * Also note that currently we never issue secondary TLB flushes
507 * from clear_young, leaving this job up to the regular system
508 * cadence. If we find this inaccurate, we might come up with a
509 * more sophisticated heuristic later.
511 young = kvm_age_hva(kvm, start, end);
512 spin_unlock(&kvm->mmu_lock);
513 srcu_read_unlock(&kvm->srcu, idx);
515 return young;
518 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
519 struct mm_struct *mm,
520 unsigned long address)
522 struct kvm *kvm = mmu_notifier_to_kvm(mn);
523 int young, idx;
525 idx = srcu_read_lock(&kvm->srcu);
526 spin_lock(&kvm->mmu_lock);
527 young = kvm_test_age_hva(kvm, address);
528 spin_unlock(&kvm->mmu_lock);
529 srcu_read_unlock(&kvm->srcu, idx);
531 return young;
534 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
535 struct mm_struct *mm)
537 struct kvm *kvm = mmu_notifier_to_kvm(mn);
538 int idx;
540 idx = srcu_read_lock(&kvm->srcu);
541 kvm_arch_flush_shadow_all(kvm);
542 srcu_read_unlock(&kvm->srcu, idx);
545 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
546 .invalidate_range = kvm_mmu_notifier_invalidate_range,
547 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
548 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
549 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
550 .clear_young = kvm_mmu_notifier_clear_young,
551 .test_young = kvm_mmu_notifier_test_young,
552 .change_pte = kvm_mmu_notifier_change_pte,
553 .release = kvm_mmu_notifier_release,
556 static int kvm_init_mmu_notifier(struct kvm *kvm)
558 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
559 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
562 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
564 static int kvm_init_mmu_notifier(struct kvm *kvm)
566 return 0;
569 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
571 static struct kvm_memslots *kvm_alloc_memslots(void)
573 int i;
574 struct kvm_memslots *slots;
576 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
577 if (!slots)
578 return NULL;
580 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
581 slots->id_to_index[i] = -1;
583 return slots;
586 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
588 if (!memslot->dirty_bitmap)
589 return;
591 kvfree(memslot->dirty_bitmap);
592 memslot->dirty_bitmap = NULL;
595 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
597 kvm_destroy_dirty_bitmap(slot);
599 kvm_arch_free_memslot(kvm, slot);
601 slot->flags = 0;
602 slot->npages = 0;
605 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
607 struct kvm_memory_slot *memslot;
609 if (!slots)
610 return;
612 kvm_for_each_memslot(memslot, slots)
613 kvm_free_memslot(kvm, memslot);
615 kvfree(slots);
618 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
620 int i;
622 if (!kvm->debugfs_dentry)
623 return;
625 debugfs_remove_recursive(kvm->debugfs_dentry);
627 if (kvm->debugfs_stat_data) {
628 for (i = 0; i < kvm_debugfs_num_entries; i++)
629 kfree(kvm->debugfs_stat_data[i]);
630 kfree(kvm->debugfs_stat_data);
634 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
636 char dir_name[ITOA_MAX_LEN * 2];
637 struct kvm_stat_data *stat_data;
638 struct kvm_stats_debugfs_item *p;
640 if (!debugfs_initialized())
641 return 0;
643 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
644 kvm->debugfs_dentry = debugfs_create_dir(dir_name, kvm_debugfs_dir);
646 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
647 sizeof(*kvm->debugfs_stat_data),
648 GFP_KERNEL_ACCOUNT);
649 if (!kvm->debugfs_stat_data)
650 return -ENOMEM;
652 for (p = debugfs_entries; p->name; p++) {
653 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
654 if (!stat_data)
655 return -ENOMEM;
657 stat_data->kvm = kvm;
658 stat_data->dbgfs_item = p;
659 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
660 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
661 kvm->debugfs_dentry, stat_data,
662 &stat_fops_per_vm);
664 return 0;
668 * Called after the VM is otherwise initialized, but just before adding it to
669 * the vm_list.
671 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
673 return 0;
677 * Called just after removing the VM from the vm_list, but before doing any
678 * other destruction.
680 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
684 static struct kvm *kvm_create_vm(unsigned long type)
686 struct kvm *kvm = kvm_arch_alloc_vm();
687 int r = -ENOMEM;
688 int i;
690 if (!kvm)
691 return ERR_PTR(-ENOMEM);
693 spin_lock_init(&kvm->mmu_lock);
694 mmgrab(current->mm);
695 kvm->mm = current->mm;
696 kvm_eventfd_init(kvm);
697 mutex_init(&kvm->lock);
698 mutex_init(&kvm->irq_lock);
699 mutex_init(&kvm->slots_lock);
700 INIT_LIST_HEAD(&kvm->devices);
702 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
704 if (init_srcu_struct(&kvm->srcu))
705 goto out_err_no_srcu;
706 if (init_srcu_struct(&kvm->irq_srcu))
707 goto out_err_no_irq_srcu;
709 refcount_set(&kvm->users_count, 1);
710 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
711 struct kvm_memslots *slots = kvm_alloc_memslots();
713 if (!slots)
714 goto out_err_no_arch_destroy_vm;
715 /* Generations must be different for each address space. */
716 slots->generation = i;
717 rcu_assign_pointer(kvm->memslots[i], slots);
720 for (i = 0; i < KVM_NR_BUSES; i++) {
721 rcu_assign_pointer(kvm->buses[i],
722 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
723 if (!kvm->buses[i])
724 goto out_err_no_arch_destroy_vm;
727 r = kvm_arch_init_vm(kvm, type);
728 if (r)
729 goto out_err_no_arch_destroy_vm;
731 r = hardware_enable_all();
732 if (r)
733 goto out_err_no_disable;
735 #ifdef CONFIG_HAVE_KVM_IRQFD
736 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
737 #endif
739 r = kvm_init_mmu_notifier(kvm);
740 if (r)
741 goto out_err_no_mmu_notifier;
743 r = kvm_arch_post_init_vm(kvm);
744 if (r)
745 goto out_err;
747 mutex_lock(&kvm_lock);
748 list_add(&kvm->vm_list, &vm_list);
749 mutex_unlock(&kvm_lock);
751 preempt_notifier_inc();
753 return kvm;
755 out_err:
756 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
757 if (kvm->mmu_notifier.ops)
758 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
759 #endif
760 out_err_no_mmu_notifier:
761 hardware_disable_all();
762 out_err_no_disable:
763 kvm_arch_destroy_vm(kvm);
764 out_err_no_arch_destroy_vm:
765 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
766 for (i = 0; i < KVM_NR_BUSES; i++)
767 kfree(kvm_get_bus(kvm, i));
768 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
769 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
770 cleanup_srcu_struct(&kvm->irq_srcu);
771 out_err_no_irq_srcu:
772 cleanup_srcu_struct(&kvm->srcu);
773 out_err_no_srcu:
774 kvm_arch_free_vm(kvm);
775 mmdrop(current->mm);
776 return ERR_PTR(r);
779 static void kvm_destroy_devices(struct kvm *kvm)
781 struct kvm_device *dev, *tmp;
784 * We do not need to take the kvm->lock here, because nobody else
785 * has a reference to the struct kvm at this point and therefore
786 * cannot access the devices list anyhow.
788 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
789 list_del(&dev->vm_node);
790 dev->ops->destroy(dev);
794 static void kvm_destroy_vm(struct kvm *kvm)
796 int i;
797 struct mm_struct *mm = kvm->mm;
799 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
800 kvm_destroy_vm_debugfs(kvm);
801 kvm_arch_sync_events(kvm);
802 mutex_lock(&kvm_lock);
803 list_del(&kvm->vm_list);
804 mutex_unlock(&kvm_lock);
805 kvm_arch_pre_destroy_vm(kvm);
807 kvm_free_irq_routing(kvm);
808 for (i = 0; i < KVM_NR_BUSES; i++) {
809 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
811 if (bus)
812 kvm_io_bus_destroy(bus);
813 kvm->buses[i] = NULL;
815 kvm_coalesced_mmio_free(kvm);
816 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
817 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
818 #else
819 kvm_arch_flush_shadow_all(kvm);
820 #endif
821 kvm_arch_destroy_vm(kvm);
822 kvm_destroy_devices(kvm);
823 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
824 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
825 cleanup_srcu_struct(&kvm->irq_srcu);
826 cleanup_srcu_struct(&kvm->srcu);
827 kvm_arch_free_vm(kvm);
828 preempt_notifier_dec();
829 hardware_disable_all();
830 mmdrop(mm);
833 void kvm_get_kvm(struct kvm *kvm)
835 refcount_inc(&kvm->users_count);
837 EXPORT_SYMBOL_GPL(kvm_get_kvm);
839 void kvm_put_kvm(struct kvm *kvm)
841 if (refcount_dec_and_test(&kvm->users_count))
842 kvm_destroy_vm(kvm);
844 EXPORT_SYMBOL_GPL(kvm_put_kvm);
847 * Used to put a reference that was taken on behalf of an object associated
848 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
849 * of the new file descriptor fails and the reference cannot be transferred to
850 * its final owner. In such cases, the caller is still actively using @kvm and
851 * will fail miserably if the refcount unexpectedly hits zero.
853 void kvm_put_kvm_no_destroy(struct kvm *kvm)
855 WARN_ON(refcount_dec_and_test(&kvm->users_count));
857 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
859 static int kvm_vm_release(struct inode *inode, struct file *filp)
861 struct kvm *kvm = filp->private_data;
863 kvm_irqfd_release(kvm);
865 kvm_put_kvm(kvm);
866 return 0;
870 * Allocation size is twice as large as the actual dirty bitmap size.
871 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
873 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
875 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
877 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
878 if (!memslot->dirty_bitmap)
879 return -ENOMEM;
881 return 0;
885 * Delete a memslot by decrementing the number of used slots and shifting all
886 * other entries in the array forward one spot.
888 static inline void kvm_memslot_delete(struct kvm_memslots *slots,
889 struct kvm_memory_slot *memslot)
891 struct kvm_memory_slot *mslots = slots->memslots;
892 int i;
894 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
895 return;
897 slots->used_slots--;
899 if (atomic_read(&slots->lru_slot) >= slots->used_slots)
900 atomic_set(&slots->lru_slot, 0);
902 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
903 mslots[i] = mslots[i + 1];
904 slots->id_to_index[mslots[i].id] = i;
906 mslots[i] = *memslot;
907 slots->id_to_index[memslot->id] = -1;
911 * "Insert" a new memslot by incrementing the number of used slots. Returns
912 * the new slot's initial index into the memslots array.
914 static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
916 return slots->used_slots++;
920 * Move a changed memslot backwards in the array by shifting existing slots
921 * with a higher GFN toward the front of the array. Note, the changed memslot
922 * itself is not preserved in the array, i.e. not swapped at this time, only
923 * its new index into the array is tracked. Returns the changed memslot's
924 * current index into the memslots array.
926 static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
927 struct kvm_memory_slot *memslot)
929 struct kvm_memory_slot *mslots = slots->memslots;
930 int i;
932 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
933 WARN_ON_ONCE(!slots->used_slots))
934 return -1;
937 * Move the target memslot backward in the array by shifting existing
938 * memslots with a higher GFN (than the target memslot) towards the
939 * front of the array.
941 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
942 if (memslot->base_gfn > mslots[i + 1].base_gfn)
943 break;
945 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
947 /* Shift the next memslot forward one and update its index. */
948 mslots[i] = mslots[i + 1];
949 slots->id_to_index[mslots[i].id] = i;
951 return i;
955 * Move a changed memslot forwards in the array by shifting existing slots with
956 * a lower GFN toward the back of the array. Note, the changed memslot itself
957 * is not preserved in the array, i.e. not swapped at this time, only its new
958 * index into the array is tracked. Returns the changed memslot's final index
959 * into the memslots array.
961 static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
962 struct kvm_memory_slot *memslot,
963 int start)
965 struct kvm_memory_slot *mslots = slots->memslots;
966 int i;
968 for (i = start; i > 0; i--) {
969 if (memslot->base_gfn < mslots[i - 1].base_gfn)
970 break;
972 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
974 /* Shift the next memslot back one and update its index. */
975 mslots[i] = mslots[i - 1];
976 slots->id_to_index[mslots[i].id] = i;
978 return i;
982 * Re-sort memslots based on their GFN to account for an added, deleted, or
983 * moved memslot. Sorting memslots by GFN allows using a binary search during
984 * memslot lookup.
986 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
987 * at memslots[0] has the highest GFN.
989 * The sorting algorithm takes advantage of having initially sorted memslots
990 * and knowing the position of the changed memslot. Sorting is also optimized
991 * by not swapping the updated memslot and instead only shifting other memslots
992 * and tracking the new index for the update memslot. Only once its final
993 * index is known is the updated memslot copied into its position in the array.
995 * - When deleting a memslot, the deleted memslot simply needs to be moved to
996 * the end of the array.
998 * - When creating a memslot, the algorithm "inserts" the new memslot at the
999 * end of the array and then it forward to its correct location.
1001 * - When moving a memslot, the algorithm first moves the updated memslot
1002 * backward to handle the scenario where the memslot's GFN was changed to a
1003 * lower value. update_memslots() then falls through and runs the same flow
1004 * as creating a memslot to move the memslot forward to handle the scenario
1005 * where its GFN was changed to a higher value.
1007 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1008 * historical reasons. Originally, invalid memslots where denoted by having
1009 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1010 * to the end of the array. The current algorithm uses dedicated logic to
1011 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1013 * The other historical motiviation for highest->lowest was to improve the
1014 * performance of memslot lookup. KVM originally used a linear search starting
1015 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1016 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1017 * single memslot above the 4gb boundary. As the largest memslot is also the
1018 * most likely to be referenced, sorting it to the front of the array was
1019 * advantageous. The current binary search starts from the middle of the array
1020 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1022 static void update_memslots(struct kvm_memslots *slots,
1023 struct kvm_memory_slot *memslot,
1024 enum kvm_mr_change change)
1026 int i;
1028 if (change == KVM_MR_DELETE) {
1029 kvm_memslot_delete(slots, memslot);
1030 } else {
1031 if (change == KVM_MR_CREATE)
1032 i = kvm_memslot_insert_back(slots);
1033 else
1034 i = kvm_memslot_move_backward(slots, memslot);
1035 i = kvm_memslot_move_forward(slots, memslot, i);
1038 * Copy the memslot to its new position in memslots and update
1039 * its index accordingly.
1041 slots->memslots[i] = *memslot;
1042 slots->id_to_index[memslot->id] = i;
1046 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1048 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1050 #ifdef __KVM_HAVE_READONLY_MEM
1051 valid_flags |= KVM_MEM_READONLY;
1052 #endif
1054 if (mem->flags & ~valid_flags)
1055 return -EINVAL;
1057 return 0;
1060 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
1061 int as_id, struct kvm_memslots *slots)
1063 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
1064 u64 gen = old_memslots->generation;
1066 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1067 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1069 rcu_assign_pointer(kvm->memslots[as_id], slots);
1070 synchronize_srcu_expedited(&kvm->srcu);
1073 * Increment the new memslot generation a second time, dropping the
1074 * update in-progress flag and incrementing the generation based on
1075 * the number of address spaces. This provides a unique and easily
1076 * identifiable generation number while the memslots are in flux.
1078 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1081 * Generations must be unique even across address spaces. We do not need
1082 * a global counter for that, instead the generation space is evenly split
1083 * across address spaces. For example, with two address spaces, address
1084 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1085 * use generations 1, 3, 5, ...
1087 gen += KVM_ADDRESS_SPACE_NUM;
1089 kvm_arch_memslots_updated(kvm, gen);
1091 slots->generation = gen;
1093 return old_memslots;
1097 * Note, at a minimum, the current number of used slots must be allocated, even
1098 * when deleting a memslot, as we need a complete duplicate of the memslots for
1099 * use when invalidating a memslot prior to deleting/moving the memslot.
1101 static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1102 enum kvm_mr_change change)
1104 struct kvm_memslots *slots;
1105 size_t old_size, new_size;
1107 old_size = sizeof(struct kvm_memslots) +
1108 (sizeof(struct kvm_memory_slot) * old->used_slots);
1110 if (change == KVM_MR_CREATE)
1111 new_size = old_size + sizeof(struct kvm_memory_slot);
1112 else
1113 new_size = old_size;
1115 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1116 if (likely(slots))
1117 memcpy(slots, old, old_size);
1119 return slots;
1122 static int kvm_set_memslot(struct kvm *kvm,
1123 const struct kvm_userspace_memory_region *mem,
1124 struct kvm_memory_slot *old,
1125 struct kvm_memory_slot *new, int as_id,
1126 enum kvm_mr_change change)
1128 struct kvm_memory_slot *slot;
1129 struct kvm_memslots *slots;
1130 int r;
1132 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
1133 if (!slots)
1134 return -ENOMEM;
1136 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1138 * Note, the INVALID flag needs to be in the appropriate entry
1139 * in the freshly allocated memslots, not in @old or @new.
1141 slot = id_to_memslot(slots, old->id);
1142 slot->flags |= KVM_MEMSLOT_INVALID;
1145 * We can re-use the old memslots, the only difference from the
1146 * newly installed memslots is the invalid flag, which will get
1147 * dropped by update_memslots anyway. We'll also revert to the
1148 * old memslots if preparing the new memory region fails.
1150 slots = install_new_memslots(kvm, as_id, slots);
1152 /* From this point no new shadow pages pointing to a deleted,
1153 * or moved, memslot will be created.
1155 * validation of sp->gfn happens in:
1156 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1157 * - kvm_is_visible_gfn (mmu_check_root)
1159 kvm_arch_flush_shadow_memslot(kvm, slot);
1162 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1163 if (r)
1164 goto out_slots;
1166 update_memslots(slots, new, change);
1167 slots = install_new_memslots(kvm, as_id, slots);
1169 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1171 kvfree(slots);
1172 return 0;
1174 out_slots:
1175 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1176 slots = install_new_memslots(kvm, as_id, slots);
1177 kvfree(slots);
1178 return r;
1181 static int kvm_delete_memslot(struct kvm *kvm,
1182 const struct kvm_userspace_memory_region *mem,
1183 struct kvm_memory_slot *old, int as_id)
1185 struct kvm_memory_slot new;
1186 int r;
1188 if (!old->npages)
1189 return -EINVAL;
1191 memset(&new, 0, sizeof(new));
1192 new.id = old->id;
1194 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1195 if (r)
1196 return r;
1198 kvm_free_memslot(kvm, old);
1199 return 0;
1203 * Allocate some memory and give it an address in the guest physical address
1204 * space.
1206 * Discontiguous memory is allowed, mostly for framebuffers.
1208 * Must be called holding kvm->slots_lock for write.
1210 int __kvm_set_memory_region(struct kvm *kvm,
1211 const struct kvm_userspace_memory_region *mem)
1213 struct kvm_memory_slot old, new;
1214 struct kvm_memory_slot *tmp;
1215 enum kvm_mr_change change;
1216 int as_id, id;
1217 int r;
1219 r = check_memory_region_flags(mem);
1220 if (r)
1221 return r;
1223 as_id = mem->slot >> 16;
1224 id = (u16)mem->slot;
1226 /* General sanity checks */
1227 if (mem->memory_size & (PAGE_SIZE - 1))
1228 return -EINVAL;
1229 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1230 return -EINVAL;
1231 /* We can read the guest memory with __xxx_user() later on. */
1232 if ((id < KVM_USER_MEM_SLOTS) &&
1233 ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1234 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1235 mem->memory_size)))
1236 return -EINVAL;
1237 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1238 return -EINVAL;
1239 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1240 return -EINVAL;
1243 * Make a full copy of the old memslot, the pointer will become stale
1244 * when the memslots are re-sorted by update_memslots(), and the old
1245 * memslot needs to be referenced after calling update_memslots(), e.g.
1246 * to free its resources and for arch specific behavior.
1248 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1249 if (tmp) {
1250 old = *tmp;
1251 tmp = NULL;
1252 } else {
1253 memset(&old, 0, sizeof(old));
1254 old.id = id;
1257 if (!mem->memory_size)
1258 return kvm_delete_memslot(kvm, mem, &old, as_id);
1260 new.id = id;
1261 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1262 new.npages = mem->memory_size >> PAGE_SHIFT;
1263 new.flags = mem->flags;
1264 new.userspace_addr = mem->userspace_addr;
1266 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1267 return -EINVAL;
1269 if (!old.npages) {
1270 change = KVM_MR_CREATE;
1271 new.dirty_bitmap = NULL;
1272 memset(&new.arch, 0, sizeof(new.arch));
1273 } else { /* Modify an existing slot. */
1274 if ((new.userspace_addr != old.userspace_addr) ||
1275 (new.npages != old.npages) ||
1276 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1277 return -EINVAL;
1279 if (new.base_gfn != old.base_gfn)
1280 change = KVM_MR_MOVE;
1281 else if (new.flags != old.flags)
1282 change = KVM_MR_FLAGS_ONLY;
1283 else /* Nothing to change. */
1284 return 0;
1286 /* Copy dirty_bitmap and arch from the current memslot. */
1287 new.dirty_bitmap = old.dirty_bitmap;
1288 memcpy(&new.arch, &old.arch, sizeof(new.arch));
1291 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1292 /* Check for overlaps */
1293 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1294 if (tmp->id == id)
1295 continue;
1296 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1297 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
1298 return -EEXIST;
1302 /* Allocate/free page dirty bitmap as needed */
1303 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1304 new.dirty_bitmap = NULL;
1305 else if (!new.dirty_bitmap) {
1306 r = kvm_alloc_dirty_bitmap(&new);
1307 if (r)
1308 return r;
1310 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1311 bitmap_set(new.dirty_bitmap, 0, new.npages);
1314 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1315 if (r)
1316 goto out_bitmap;
1318 if (old.dirty_bitmap && !new.dirty_bitmap)
1319 kvm_destroy_dirty_bitmap(&old);
1320 return 0;
1322 out_bitmap:
1323 if (new.dirty_bitmap && !old.dirty_bitmap)
1324 kvm_destroy_dirty_bitmap(&new);
1325 return r;
1327 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1329 int kvm_set_memory_region(struct kvm *kvm,
1330 const struct kvm_userspace_memory_region *mem)
1332 int r;
1334 mutex_lock(&kvm->slots_lock);
1335 r = __kvm_set_memory_region(kvm, mem);
1336 mutex_unlock(&kvm->slots_lock);
1337 return r;
1339 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1341 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1342 struct kvm_userspace_memory_region *mem)
1344 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1345 return -EINVAL;
1347 return kvm_set_memory_region(kvm, mem);
1350 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1352 * kvm_get_dirty_log - get a snapshot of dirty pages
1353 * @kvm: pointer to kvm instance
1354 * @log: slot id and address to which we copy the log
1355 * @is_dirty: set to '1' if any dirty pages were found
1356 * @memslot: set to the associated memslot, always valid on success
1358 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1359 int *is_dirty, struct kvm_memory_slot **memslot)
1361 struct kvm_memslots *slots;
1362 int i, as_id, id;
1363 unsigned long n;
1364 unsigned long any = 0;
1366 *memslot = NULL;
1367 *is_dirty = 0;
1369 as_id = log->slot >> 16;
1370 id = (u16)log->slot;
1371 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1372 return -EINVAL;
1374 slots = __kvm_memslots(kvm, as_id);
1375 *memslot = id_to_memslot(slots, id);
1376 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1377 return -ENOENT;
1379 kvm_arch_sync_dirty_log(kvm, *memslot);
1381 n = kvm_dirty_bitmap_bytes(*memslot);
1383 for (i = 0; !any && i < n/sizeof(long); ++i)
1384 any = (*memslot)->dirty_bitmap[i];
1386 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1387 return -EFAULT;
1389 if (any)
1390 *is_dirty = 1;
1391 return 0;
1393 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1395 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1397 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1398 * and reenable dirty page tracking for the corresponding pages.
1399 * @kvm: pointer to kvm instance
1400 * @log: slot id and address to which we copy the log
1402 * We need to keep it in mind that VCPU threads can write to the bitmap
1403 * concurrently. So, to avoid losing track of dirty pages we keep the
1404 * following order:
1406 * 1. Take a snapshot of the bit and clear it if needed.
1407 * 2. Write protect the corresponding page.
1408 * 3. Copy the snapshot to the userspace.
1409 * 4. Upon return caller flushes TLB's if needed.
1411 * Between 2 and 4, the guest may write to the page using the remaining TLB
1412 * entry. This is not a problem because the page is reported dirty using
1413 * the snapshot taken before and step 4 ensures that writes done after
1414 * exiting to userspace will be logged for the next call.
1417 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
1419 struct kvm_memslots *slots;
1420 struct kvm_memory_slot *memslot;
1421 int i, as_id, id;
1422 unsigned long n;
1423 unsigned long *dirty_bitmap;
1424 unsigned long *dirty_bitmap_buffer;
1425 bool flush;
1427 as_id = log->slot >> 16;
1428 id = (u16)log->slot;
1429 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1430 return -EINVAL;
1432 slots = __kvm_memslots(kvm, as_id);
1433 memslot = id_to_memslot(slots, id);
1434 if (!memslot || !memslot->dirty_bitmap)
1435 return -ENOENT;
1437 dirty_bitmap = memslot->dirty_bitmap;
1439 kvm_arch_sync_dirty_log(kvm, memslot);
1441 n = kvm_dirty_bitmap_bytes(memslot);
1442 flush = false;
1443 if (kvm->manual_dirty_log_protect) {
1445 * Unlike kvm_get_dirty_log, we always return false in *flush,
1446 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1447 * is some code duplication between this function and
1448 * kvm_get_dirty_log, but hopefully all architecture
1449 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1450 * can be eliminated.
1452 dirty_bitmap_buffer = dirty_bitmap;
1453 } else {
1454 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1455 memset(dirty_bitmap_buffer, 0, n);
1457 spin_lock(&kvm->mmu_lock);
1458 for (i = 0; i < n / sizeof(long); i++) {
1459 unsigned long mask;
1460 gfn_t offset;
1462 if (!dirty_bitmap[i])
1463 continue;
1465 flush = true;
1466 mask = xchg(&dirty_bitmap[i], 0);
1467 dirty_bitmap_buffer[i] = mask;
1469 offset = i * BITS_PER_LONG;
1470 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1471 offset, mask);
1473 spin_unlock(&kvm->mmu_lock);
1476 if (flush)
1477 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1479 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1480 return -EFAULT;
1481 return 0;
1486 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1487 * @kvm: kvm instance
1488 * @log: slot id and address to which we copy the log
1490 * Steps 1-4 below provide general overview of dirty page logging. See
1491 * kvm_get_dirty_log_protect() function description for additional details.
1493 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1494 * always flush the TLB (step 4) even if previous step failed and the dirty
1495 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1496 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1497 * writes will be marked dirty for next log read.
1499 * 1. Take a snapshot of the bit and clear it if needed.
1500 * 2. Write protect the corresponding page.
1501 * 3. Copy the snapshot to the userspace.
1502 * 4. Flush TLB's if needed.
1504 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1505 struct kvm_dirty_log *log)
1507 int r;
1509 mutex_lock(&kvm->slots_lock);
1511 r = kvm_get_dirty_log_protect(kvm, log);
1513 mutex_unlock(&kvm->slots_lock);
1514 return r;
1518 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1519 * and reenable dirty page tracking for the corresponding pages.
1520 * @kvm: pointer to kvm instance
1521 * @log: slot id and address from which to fetch the bitmap of dirty pages
1523 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1524 struct kvm_clear_dirty_log *log)
1526 struct kvm_memslots *slots;
1527 struct kvm_memory_slot *memslot;
1528 int as_id, id;
1529 gfn_t offset;
1530 unsigned long i, n;
1531 unsigned long *dirty_bitmap;
1532 unsigned long *dirty_bitmap_buffer;
1533 bool flush;
1535 as_id = log->slot >> 16;
1536 id = (u16)log->slot;
1537 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1538 return -EINVAL;
1540 if (log->first_page & 63)
1541 return -EINVAL;
1543 slots = __kvm_memslots(kvm, as_id);
1544 memslot = id_to_memslot(slots, id);
1545 if (!memslot || !memslot->dirty_bitmap)
1546 return -ENOENT;
1548 dirty_bitmap = memslot->dirty_bitmap;
1550 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
1552 if (log->first_page > memslot->npages ||
1553 log->num_pages > memslot->npages - log->first_page ||
1554 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1555 return -EINVAL;
1557 kvm_arch_sync_dirty_log(kvm, memslot);
1559 flush = false;
1560 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1561 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1562 return -EFAULT;
1564 spin_lock(&kvm->mmu_lock);
1565 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1566 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
1567 i++, offset += BITS_PER_LONG) {
1568 unsigned long mask = *dirty_bitmap_buffer++;
1569 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1570 if (!mask)
1571 continue;
1573 mask &= atomic_long_fetch_andnot(mask, p);
1576 * mask contains the bits that really have been cleared. This
1577 * never includes any bits beyond the length of the memslot (if
1578 * the length is not aligned to 64 pages), therefore it is not
1579 * a problem if userspace sets them in log->dirty_bitmap.
1581 if (mask) {
1582 flush = true;
1583 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1584 offset, mask);
1587 spin_unlock(&kvm->mmu_lock);
1589 if (flush)
1590 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1592 return 0;
1595 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
1596 struct kvm_clear_dirty_log *log)
1598 int r;
1600 mutex_lock(&kvm->slots_lock);
1602 r = kvm_clear_dirty_log_protect(kvm, log);
1604 mutex_unlock(&kvm->slots_lock);
1605 return r;
1607 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1609 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1611 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1613 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1615 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1617 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1620 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1622 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1624 if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1625 memslot->flags & KVM_MEMSLOT_INVALID)
1626 return false;
1628 return true;
1630 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1632 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
1634 struct vm_area_struct *vma;
1635 unsigned long addr, size;
1637 size = PAGE_SIZE;
1639 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
1640 if (kvm_is_error_hva(addr))
1641 return PAGE_SIZE;
1643 down_read(&current->mm->mmap_sem);
1644 vma = find_vma(current->mm, addr);
1645 if (!vma)
1646 goto out;
1648 size = vma_kernel_pagesize(vma);
1650 out:
1651 up_read(&current->mm->mmap_sem);
1653 return size;
1656 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1658 return slot->flags & KVM_MEM_READONLY;
1661 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1662 gfn_t *nr_pages, bool write)
1664 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1665 return KVM_HVA_ERR_BAD;
1667 if (memslot_is_readonly(slot) && write)
1668 return KVM_HVA_ERR_RO_BAD;
1670 if (nr_pages)
1671 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1673 return __gfn_to_hva_memslot(slot, gfn);
1676 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1677 gfn_t *nr_pages)
1679 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1682 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1683 gfn_t gfn)
1685 return gfn_to_hva_many(slot, gfn, NULL);
1687 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1689 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1691 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1693 EXPORT_SYMBOL_GPL(gfn_to_hva);
1695 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1697 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1699 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1702 * Return the hva of a @gfn and the R/W attribute if possible.
1704 * @slot: the kvm_memory_slot which contains @gfn
1705 * @gfn: the gfn to be translated
1706 * @writable: used to return the read/write attribute of the @slot if the hva
1707 * is valid and @writable is not NULL
1709 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1710 gfn_t gfn, bool *writable)
1712 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1714 if (!kvm_is_error_hva(hva) && writable)
1715 *writable = !memslot_is_readonly(slot);
1717 return hva;
1720 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1722 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1724 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1727 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1729 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1731 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1734 static inline int check_user_page_hwpoison(unsigned long addr)
1736 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1738 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1739 return rc == -EHWPOISON;
1743 * The fast path to get the writable pfn which will be stored in @pfn,
1744 * true indicates success, otherwise false is returned. It's also the
1745 * only part that runs if we can in atomic context.
1747 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1748 bool *writable, kvm_pfn_t *pfn)
1750 struct page *page[1];
1751 int npages;
1754 * Fast pin a writable pfn only if it is a write fault request
1755 * or the caller allows to map a writable pfn for a read fault
1756 * request.
1758 if (!(write_fault || writable))
1759 return false;
1761 npages = __get_user_pages_fast(addr, 1, 1, page);
1762 if (npages == 1) {
1763 *pfn = page_to_pfn(page[0]);
1765 if (writable)
1766 *writable = true;
1767 return true;
1770 return false;
1774 * The slow path to get the pfn of the specified host virtual address,
1775 * 1 indicates success, -errno is returned if error is detected.
1777 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1778 bool *writable, kvm_pfn_t *pfn)
1780 unsigned int flags = FOLL_HWPOISON;
1781 struct page *page;
1782 int npages = 0;
1784 might_sleep();
1786 if (writable)
1787 *writable = write_fault;
1789 if (write_fault)
1790 flags |= FOLL_WRITE;
1791 if (async)
1792 flags |= FOLL_NOWAIT;
1794 npages = get_user_pages_unlocked(addr, 1, &page, flags);
1795 if (npages != 1)
1796 return npages;
1798 /* map read fault as writable if possible */
1799 if (unlikely(!write_fault) && writable) {
1800 struct page *wpage;
1802 if (__get_user_pages_fast(addr, 1, 1, &wpage) == 1) {
1803 *writable = true;
1804 put_page(page);
1805 page = wpage;
1808 *pfn = page_to_pfn(page);
1809 return npages;
1812 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1814 if (unlikely(!(vma->vm_flags & VM_READ)))
1815 return false;
1817 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1818 return false;
1820 return true;
1823 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1824 unsigned long addr, bool *async,
1825 bool write_fault, bool *writable,
1826 kvm_pfn_t *p_pfn)
1828 unsigned long pfn;
1829 int r;
1831 r = follow_pfn(vma, addr, &pfn);
1832 if (r) {
1834 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1835 * not call the fault handler, so do it here.
1837 bool unlocked = false;
1838 r = fixup_user_fault(current, current->mm, addr,
1839 (write_fault ? FAULT_FLAG_WRITE : 0),
1840 &unlocked);
1841 if (unlocked)
1842 return -EAGAIN;
1843 if (r)
1844 return r;
1846 r = follow_pfn(vma, addr, &pfn);
1847 if (r)
1848 return r;
1852 if (writable)
1853 *writable = true;
1856 * Get a reference here because callers of *hva_to_pfn* and
1857 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1858 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1859 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1860 * simply do nothing for reserved pfns.
1862 * Whoever called remap_pfn_range is also going to call e.g.
1863 * unmap_mapping_range before the underlying pages are freed,
1864 * causing a call to our MMU notifier.
1866 kvm_get_pfn(pfn);
1868 *p_pfn = pfn;
1869 return 0;
1873 * Pin guest page in memory and return its pfn.
1874 * @addr: host virtual address which maps memory to the guest
1875 * @atomic: whether this function can sleep
1876 * @async: whether this function need to wait IO complete if the
1877 * host page is not in the memory
1878 * @write_fault: whether we should get a writable host page
1879 * @writable: whether it allows to map a writable host page for !@write_fault
1881 * The function will map a writable host page for these two cases:
1882 * 1): @write_fault = true
1883 * 2): @write_fault = false && @writable, @writable will tell the caller
1884 * whether the mapping is writable.
1886 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1887 bool write_fault, bool *writable)
1889 struct vm_area_struct *vma;
1890 kvm_pfn_t pfn = 0;
1891 int npages, r;
1893 /* we can do it either atomically or asynchronously, not both */
1894 BUG_ON(atomic && async);
1896 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
1897 return pfn;
1899 if (atomic)
1900 return KVM_PFN_ERR_FAULT;
1902 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1903 if (npages == 1)
1904 return pfn;
1906 down_read(&current->mm->mmap_sem);
1907 if (npages == -EHWPOISON ||
1908 (!async && check_user_page_hwpoison(addr))) {
1909 pfn = KVM_PFN_ERR_HWPOISON;
1910 goto exit;
1913 retry:
1914 vma = find_vma_intersection(current->mm, addr, addr + 1);
1916 if (vma == NULL)
1917 pfn = KVM_PFN_ERR_FAULT;
1918 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1919 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
1920 if (r == -EAGAIN)
1921 goto retry;
1922 if (r < 0)
1923 pfn = KVM_PFN_ERR_FAULT;
1924 } else {
1925 if (async && vma_is_valid(vma, write_fault))
1926 *async = true;
1927 pfn = KVM_PFN_ERR_FAULT;
1929 exit:
1930 up_read(&current->mm->mmap_sem);
1931 return pfn;
1934 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1935 bool atomic, bool *async, bool write_fault,
1936 bool *writable)
1938 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1940 if (addr == KVM_HVA_ERR_RO_BAD) {
1941 if (writable)
1942 *writable = false;
1943 return KVM_PFN_ERR_RO_FAULT;
1946 if (kvm_is_error_hva(addr)) {
1947 if (writable)
1948 *writable = false;
1949 return KVM_PFN_NOSLOT;
1952 /* Do not map writable pfn in the readonly memslot. */
1953 if (writable && memslot_is_readonly(slot)) {
1954 *writable = false;
1955 writable = NULL;
1958 return hva_to_pfn(addr, atomic, async, write_fault,
1959 writable);
1961 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1963 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1964 bool *writable)
1966 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1967 write_fault, writable);
1969 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1971 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1973 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1975 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1977 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1979 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1981 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1983 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1985 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1987 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1989 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1991 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1993 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1995 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1997 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1999 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2001 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2002 struct page **pages, int nr_pages)
2004 unsigned long addr;
2005 gfn_t entry = 0;
2007 addr = gfn_to_hva_many(slot, gfn, &entry);
2008 if (kvm_is_error_hva(addr))
2009 return -1;
2011 if (entry < nr_pages)
2012 return 0;
2014 return __get_user_pages_fast(addr, nr_pages, 1, pages);
2016 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2018 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2020 if (is_error_noslot_pfn(pfn))
2021 return KVM_ERR_PTR_BAD_PAGE;
2023 if (kvm_is_reserved_pfn(pfn)) {
2024 WARN_ON(1);
2025 return KVM_ERR_PTR_BAD_PAGE;
2028 return pfn_to_page(pfn);
2031 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2033 kvm_pfn_t pfn;
2035 pfn = gfn_to_pfn(kvm, gfn);
2037 return kvm_pfn_to_page(pfn);
2039 EXPORT_SYMBOL_GPL(gfn_to_page);
2041 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2043 if (pfn == 0)
2044 return;
2046 if (cache)
2047 cache->pfn = cache->gfn = 0;
2049 if (dirty)
2050 kvm_release_pfn_dirty(pfn);
2051 else
2052 kvm_release_pfn_clean(pfn);
2055 static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2056 struct gfn_to_pfn_cache *cache, u64 gen)
2058 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2060 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2061 cache->gfn = gfn;
2062 cache->dirty = false;
2063 cache->generation = gen;
2066 static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
2067 struct kvm_host_map *map,
2068 struct gfn_to_pfn_cache *cache,
2069 bool atomic)
2071 kvm_pfn_t pfn;
2072 void *hva = NULL;
2073 struct page *page = KVM_UNMAPPED_PAGE;
2074 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
2075 u64 gen = slots->generation;
2077 if (!map)
2078 return -EINVAL;
2080 if (cache) {
2081 if (!cache->pfn || cache->gfn != gfn ||
2082 cache->generation != gen) {
2083 if (atomic)
2084 return -EAGAIN;
2085 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2087 pfn = cache->pfn;
2088 } else {
2089 if (atomic)
2090 return -EAGAIN;
2091 pfn = gfn_to_pfn_memslot(slot, gfn);
2093 if (is_error_noslot_pfn(pfn))
2094 return -EINVAL;
2096 if (pfn_valid(pfn)) {
2097 page = pfn_to_page(pfn);
2098 if (atomic)
2099 hva = kmap_atomic(page);
2100 else
2101 hva = kmap(page);
2102 #ifdef CONFIG_HAS_IOMEM
2103 } else if (!atomic) {
2104 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2105 } else {
2106 return -EINVAL;
2107 #endif
2110 if (!hva)
2111 return -EFAULT;
2113 map->page = page;
2114 map->hva = hva;
2115 map->pfn = pfn;
2116 map->gfn = gfn;
2118 return 0;
2121 int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2122 struct gfn_to_pfn_cache *cache, bool atomic)
2124 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2125 cache, atomic);
2127 EXPORT_SYMBOL_GPL(kvm_map_gfn);
2129 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2131 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2132 NULL, false);
2134 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2136 static void __kvm_unmap_gfn(struct kvm_memory_slot *memslot,
2137 struct kvm_host_map *map,
2138 struct gfn_to_pfn_cache *cache,
2139 bool dirty, bool atomic)
2141 if (!map)
2142 return;
2144 if (!map->hva)
2145 return;
2147 if (map->page != KVM_UNMAPPED_PAGE) {
2148 if (atomic)
2149 kunmap_atomic(map->hva);
2150 else
2151 kunmap(map->page);
2153 #ifdef CONFIG_HAS_IOMEM
2154 else if (!atomic)
2155 memunmap(map->hva);
2156 else
2157 WARN_ONCE(1, "Unexpected unmapping in atomic context");
2158 #endif
2160 if (dirty)
2161 mark_page_dirty_in_slot(memslot, map->gfn);
2163 if (cache)
2164 cache->dirty |= dirty;
2165 else
2166 kvm_release_pfn(map->pfn, dirty, NULL);
2168 map->hva = NULL;
2169 map->page = NULL;
2172 int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2173 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
2175 __kvm_unmap_gfn(gfn_to_memslot(vcpu->kvm, map->gfn), map,
2176 cache, dirty, atomic);
2177 return 0;
2179 EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2181 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2183 __kvm_unmap_gfn(kvm_vcpu_gfn_to_memslot(vcpu, map->gfn), map, NULL,
2184 dirty, false);
2186 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2188 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2190 kvm_pfn_t pfn;
2192 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2194 return kvm_pfn_to_page(pfn);
2196 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2198 void kvm_release_page_clean(struct page *page)
2200 WARN_ON(is_error_page(page));
2202 kvm_release_pfn_clean(page_to_pfn(page));
2204 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2206 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2208 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2209 put_page(pfn_to_page(pfn));
2211 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2213 void kvm_release_page_dirty(struct page *page)
2215 WARN_ON(is_error_page(page));
2217 kvm_release_pfn_dirty(page_to_pfn(page));
2219 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2221 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2223 kvm_set_pfn_dirty(pfn);
2224 kvm_release_pfn_clean(pfn);
2226 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2228 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2230 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2231 SetPageDirty(pfn_to_page(pfn));
2233 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2235 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2237 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2238 mark_page_accessed(pfn_to_page(pfn));
2240 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2242 void kvm_get_pfn(kvm_pfn_t pfn)
2244 if (!kvm_is_reserved_pfn(pfn))
2245 get_page(pfn_to_page(pfn));
2247 EXPORT_SYMBOL_GPL(kvm_get_pfn);
2249 static int next_segment(unsigned long len, int offset)
2251 if (len > PAGE_SIZE - offset)
2252 return PAGE_SIZE - offset;
2253 else
2254 return len;
2257 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2258 void *data, int offset, int len)
2260 int r;
2261 unsigned long addr;
2263 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2264 if (kvm_is_error_hva(addr))
2265 return -EFAULT;
2266 r = __copy_from_user(data, (void __user *)addr + offset, len);
2267 if (r)
2268 return -EFAULT;
2269 return 0;
2272 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2273 int len)
2275 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2277 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2279 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2281 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2282 int offset, int len)
2284 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2286 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2288 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2290 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2292 gfn_t gfn = gpa >> PAGE_SHIFT;
2293 int seg;
2294 int offset = offset_in_page(gpa);
2295 int ret;
2297 while ((seg = next_segment(len, offset)) != 0) {
2298 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2299 if (ret < 0)
2300 return ret;
2301 offset = 0;
2302 len -= seg;
2303 data += seg;
2304 ++gfn;
2306 return 0;
2308 EXPORT_SYMBOL_GPL(kvm_read_guest);
2310 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2312 gfn_t gfn = gpa >> PAGE_SHIFT;
2313 int seg;
2314 int offset = offset_in_page(gpa);
2315 int ret;
2317 while ((seg = next_segment(len, offset)) != 0) {
2318 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2319 if (ret < 0)
2320 return ret;
2321 offset = 0;
2322 len -= seg;
2323 data += seg;
2324 ++gfn;
2326 return 0;
2328 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2330 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2331 void *data, int offset, unsigned long len)
2333 int r;
2334 unsigned long addr;
2336 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2337 if (kvm_is_error_hva(addr))
2338 return -EFAULT;
2339 pagefault_disable();
2340 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2341 pagefault_enable();
2342 if (r)
2343 return -EFAULT;
2344 return 0;
2347 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2348 void *data, unsigned long len)
2350 gfn_t gfn = gpa >> PAGE_SHIFT;
2351 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2352 int offset = offset_in_page(gpa);
2354 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2356 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2358 static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
2359 const void *data, int offset, int len)
2361 int r;
2362 unsigned long addr;
2364 addr = gfn_to_hva_memslot(memslot, gfn);
2365 if (kvm_is_error_hva(addr))
2366 return -EFAULT;
2367 r = __copy_to_user((void __user *)addr + offset, data, len);
2368 if (r)
2369 return -EFAULT;
2370 mark_page_dirty_in_slot(memslot, gfn);
2371 return 0;
2374 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2375 const void *data, int offset, int len)
2377 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2379 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2381 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2383 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2384 const void *data, int offset, int len)
2386 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2388 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2390 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2392 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2393 unsigned long len)
2395 gfn_t gfn = gpa >> PAGE_SHIFT;
2396 int seg;
2397 int offset = offset_in_page(gpa);
2398 int ret;
2400 while ((seg = next_segment(len, offset)) != 0) {
2401 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2402 if (ret < 0)
2403 return ret;
2404 offset = 0;
2405 len -= seg;
2406 data += seg;
2407 ++gfn;
2409 return 0;
2411 EXPORT_SYMBOL_GPL(kvm_write_guest);
2413 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2414 unsigned long len)
2416 gfn_t gfn = gpa >> PAGE_SHIFT;
2417 int seg;
2418 int offset = offset_in_page(gpa);
2419 int ret;
2421 while ((seg = next_segment(len, offset)) != 0) {
2422 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2423 if (ret < 0)
2424 return ret;
2425 offset = 0;
2426 len -= seg;
2427 data += seg;
2428 ++gfn;
2430 return 0;
2432 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2434 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2435 struct gfn_to_hva_cache *ghc,
2436 gpa_t gpa, unsigned long len)
2438 int offset = offset_in_page(gpa);
2439 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2440 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2441 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2442 gfn_t nr_pages_avail;
2444 /* Update ghc->generation before performing any error checks. */
2445 ghc->generation = slots->generation;
2447 if (start_gfn > end_gfn) {
2448 ghc->hva = KVM_HVA_ERR_BAD;
2449 return -EINVAL;
2453 * If the requested region crosses two memslots, we still
2454 * verify that the entire region is valid here.
2456 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
2457 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2458 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2459 &nr_pages_avail);
2460 if (kvm_is_error_hva(ghc->hva))
2461 return -EFAULT;
2464 /* Use the slow path for cross page reads and writes. */
2465 if (nr_pages_needed == 1)
2466 ghc->hva += offset;
2467 else
2468 ghc->memslot = NULL;
2470 ghc->gpa = gpa;
2471 ghc->len = len;
2472 return 0;
2475 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2476 gpa_t gpa, unsigned long len)
2478 struct kvm_memslots *slots = kvm_memslots(kvm);
2479 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2481 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2483 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2484 void *data, unsigned int offset,
2485 unsigned long len)
2487 struct kvm_memslots *slots = kvm_memslots(kvm);
2488 int r;
2489 gpa_t gpa = ghc->gpa + offset;
2491 BUG_ON(len + offset > ghc->len);
2493 if (slots->generation != ghc->generation) {
2494 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2495 return -EFAULT;
2498 if (kvm_is_error_hva(ghc->hva))
2499 return -EFAULT;
2501 if (unlikely(!ghc->memslot))
2502 return kvm_write_guest(kvm, gpa, data, len);
2504 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2505 if (r)
2506 return -EFAULT;
2507 mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
2509 return 0;
2511 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2513 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2514 void *data, unsigned long len)
2516 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2518 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2520 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2521 void *data, unsigned long len)
2523 struct kvm_memslots *slots = kvm_memslots(kvm);
2524 int r;
2526 BUG_ON(len > ghc->len);
2528 if (slots->generation != ghc->generation) {
2529 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2530 return -EFAULT;
2533 if (kvm_is_error_hva(ghc->hva))
2534 return -EFAULT;
2536 if (unlikely(!ghc->memslot))
2537 return kvm_read_guest(kvm, ghc->gpa, data, len);
2539 r = __copy_from_user(data, (void __user *)ghc->hva, len);
2540 if (r)
2541 return -EFAULT;
2543 return 0;
2545 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2547 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2549 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2551 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2553 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2555 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2557 gfn_t gfn = gpa >> PAGE_SHIFT;
2558 int seg;
2559 int offset = offset_in_page(gpa);
2560 int ret;
2562 while ((seg = next_segment(len, offset)) != 0) {
2563 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2564 if (ret < 0)
2565 return ret;
2566 offset = 0;
2567 len -= seg;
2568 ++gfn;
2570 return 0;
2572 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2574 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2575 gfn_t gfn)
2577 if (memslot && memslot->dirty_bitmap) {
2578 unsigned long rel_gfn = gfn - memslot->base_gfn;
2580 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2584 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2586 struct kvm_memory_slot *memslot;
2588 memslot = gfn_to_memslot(kvm, gfn);
2589 mark_page_dirty_in_slot(memslot, gfn);
2591 EXPORT_SYMBOL_GPL(mark_page_dirty);
2593 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2595 struct kvm_memory_slot *memslot;
2597 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2598 mark_page_dirty_in_slot(memslot, gfn);
2600 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2602 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2604 if (!vcpu->sigset_active)
2605 return;
2608 * This does a lockless modification of ->real_blocked, which is fine
2609 * because, only current can change ->real_blocked and all readers of
2610 * ->real_blocked don't care as long ->real_blocked is always a subset
2611 * of ->blocked.
2613 sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
2616 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2618 if (!vcpu->sigset_active)
2619 return;
2621 sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
2622 sigemptyset(&current->real_blocked);
2625 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2627 unsigned int old, val, grow, grow_start;
2629 old = val = vcpu->halt_poll_ns;
2630 grow_start = READ_ONCE(halt_poll_ns_grow_start);
2631 grow = READ_ONCE(halt_poll_ns_grow);
2632 if (!grow)
2633 goto out;
2635 val *= grow;
2636 if (val < grow_start)
2637 val = grow_start;
2639 if (val > halt_poll_ns)
2640 val = halt_poll_ns;
2642 vcpu->halt_poll_ns = val;
2643 out:
2644 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2647 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2649 unsigned int old, val, shrink;
2651 old = val = vcpu->halt_poll_ns;
2652 shrink = READ_ONCE(halt_poll_ns_shrink);
2653 if (shrink == 0)
2654 val = 0;
2655 else
2656 val /= shrink;
2658 vcpu->halt_poll_ns = val;
2659 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2662 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2664 int ret = -EINTR;
2665 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2667 if (kvm_arch_vcpu_runnable(vcpu)) {
2668 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2669 goto out;
2671 if (kvm_cpu_has_pending_timer(vcpu))
2672 goto out;
2673 if (signal_pending(current))
2674 goto out;
2676 ret = 0;
2677 out:
2678 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2679 return ret;
2683 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2685 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2687 ktime_t start, cur;
2688 DECLARE_SWAITQUEUE(wait);
2689 bool waited = false;
2690 u64 block_ns;
2692 kvm_arch_vcpu_blocking(vcpu);
2694 start = cur = ktime_get();
2695 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
2696 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2698 ++vcpu->stat.halt_attempted_poll;
2699 do {
2701 * This sets KVM_REQ_UNHALT if an interrupt
2702 * arrives.
2704 if (kvm_vcpu_check_block(vcpu) < 0) {
2705 ++vcpu->stat.halt_successful_poll;
2706 if (!vcpu_valid_wakeup(vcpu))
2707 ++vcpu->stat.halt_poll_invalid;
2708 goto out;
2710 cur = ktime_get();
2711 } while (single_task_running() && ktime_before(cur, stop));
2714 for (;;) {
2715 prepare_to_swait_exclusive(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2717 if (kvm_vcpu_check_block(vcpu) < 0)
2718 break;
2720 waited = true;
2721 schedule();
2724 finish_swait(&vcpu->wq, &wait);
2725 cur = ktime_get();
2726 out:
2727 kvm_arch_vcpu_unblocking(vcpu);
2728 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2730 if (!kvm_arch_no_poll(vcpu)) {
2731 if (!vcpu_valid_wakeup(vcpu)) {
2732 shrink_halt_poll_ns(vcpu);
2733 } else if (halt_poll_ns) {
2734 if (block_ns <= vcpu->halt_poll_ns)
2736 /* we had a long block, shrink polling */
2737 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2738 shrink_halt_poll_ns(vcpu);
2739 /* we had a short halt and our poll time is too small */
2740 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2741 block_ns < halt_poll_ns)
2742 grow_halt_poll_ns(vcpu);
2743 } else {
2744 vcpu->halt_poll_ns = 0;
2748 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2749 kvm_arch_vcpu_block_finish(vcpu);
2751 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2753 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2755 struct swait_queue_head *wqp;
2757 wqp = kvm_arch_vcpu_wq(vcpu);
2758 if (swq_has_sleeper(wqp)) {
2759 swake_up_one(wqp);
2760 WRITE_ONCE(vcpu->ready, true);
2761 ++vcpu->stat.halt_wakeup;
2762 return true;
2765 return false;
2767 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2769 #ifndef CONFIG_S390
2771 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2773 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2775 int me;
2776 int cpu = vcpu->cpu;
2778 if (kvm_vcpu_wake_up(vcpu))
2779 return;
2781 me = get_cpu();
2782 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2783 if (kvm_arch_vcpu_should_kick(vcpu))
2784 smp_send_reschedule(cpu);
2785 put_cpu();
2787 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2788 #endif /* !CONFIG_S390 */
2790 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2792 struct pid *pid;
2793 struct task_struct *task = NULL;
2794 int ret = 0;
2796 rcu_read_lock();
2797 pid = rcu_dereference(target->pid);
2798 if (pid)
2799 task = get_pid_task(pid, PIDTYPE_PID);
2800 rcu_read_unlock();
2801 if (!task)
2802 return ret;
2803 ret = yield_to(task, 1);
2804 put_task_struct(task);
2806 return ret;
2808 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2811 * Helper that checks whether a VCPU is eligible for directed yield.
2812 * Most eligible candidate to yield is decided by following heuristics:
2814 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2815 * (preempted lock holder), indicated by @in_spin_loop.
2816 * Set at the beiginning and cleared at the end of interception/PLE handler.
2818 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2819 * chance last time (mostly it has become eligible now since we have probably
2820 * yielded to lockholder in last iteration. This is done by toggling
2821 * @dy_eligible each time a VCPU checked for eligibility.)
2823 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2824 * to preempted lock-holder could result in wrong VCPU selection and CPU
2825 * burning. Giving priority for a potential lock-holder increases lock
2826 * progress.
2828 * Since algorithm is based on heuristics, accessing another VCPU data without
2829 * locking does not harm. It may result in trying to yield to same VCPU, fail
2830 * and continue with next VCPU and so on.
2832 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2834 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2835 bool eligible;
2837 eligible = !vcpu->spin_loop.in_spin_loop ||
2838 vcpu->spin_loop.dy_eligible;
2840 if (vcpu->spin_loop.in_spin_loop)
2841 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2843 return eligible;
2844 #else
2845 return true;
2846 #endif
2850 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2851 * a vcpu_load/vcpu_put pair. However, for most architectures
2852 * kvm_arch_vcpu_runnable does not require vcpu_load.
2854 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2856 return kvm_arch_vcpu_runnable(vcpu);
2859 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2861 if (kvm_arch_dy_runnable(vcpu))
2862 return true;
2864 #ifdef CONFIG_KVM_ASYNC_PF
2865 if (!list_empty_careful(&vcpu->async_pf.done))
2866 return true;
2867 #endif
2869 return false;
2872 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
2874 struct kvm *kvm = me->kvm;
2875 struct kvm_vcpu *vcpu;
2876 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2877 int yielded = 0;
2878 int try = 3;
2879 int pass;
2880 int i;
2882 kvm_vcpu_set_in_spin_loop(me, true);
2884 * We boost the priority of a VCPU that is runnable but not
2885 * currently running, because it got preempted by something
2886 * else and called schedule in __vcpu_run. Hopefully that
2887 * VCPU is holding the lock that we need and will release it.
2888 * We approximate round-robin by starting at the last boosted VCPU.
2890 for (pass = 0; pass < 2 && !yielded && try; pass++) {
2891 kvm_for_each_vcpu(i, vcpu, kvm) {
2892 if (!pass && i <= last_boosted_vcpu) {
2893 i = last_boosted_vcpu;
2894 continue;
2895 } else if (pass && i > last_boosted_vcpu)
2896 break;
2897 if (!READ_ONCE(vcpu->ready))
2898 continue;
2899 if (vcpu == me)
2900 continue;
2901 if (swait_active(&vcpu->wq) && !vcpu_dy_runnable(vcpu))
2902 continue;
2903 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
2904 !kvm_arch_vcpu_in_kernel(vcpu))
2905 continue;
2906 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2907 continue;
2909 yielded = kvm_vcpu_yield_to(vcpu);
2910 if (yielded > 0) {
2911 kvm->last_boosted_vcpu = i;
2912 break;
2913 } else if (yielded < 0) {
2914 try--;
2915 if (!try)
2916 break;
2920 kvm_vcpu_set_in_spin_loop(me, false);
2922 /* Ensure vcpu is not eligible during next spinloop */
2923 kvm_vcpu_set_dy_eligible(me, false);
2925 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2927 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
2929 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
2930 struct page *page;
2932 if (vmf->pgoff == 0)
2933 page = virt_to_page(vcpu->run);
2934 #ifdef CONFIG_X86
2935 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2936 page = virt_to_page(vcpu->arch.pio_data);
2937 #endif
2938 #ifdef CONFIG_KVM_MMIO
2939 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2940 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2941 #endif
2942 else
2943 return kvm_arch_vcpu_fault(vcpu, vmf);
2944 get_page(page);
2945 vmf->page = page;
2946 return 0;
2949 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2950 .fault = kvm_vcpu_fault,
2953 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2955 vma->vm_ops = &kvm_vcpu_vm_ops;
2956 return 0;
2959 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2961 struct kvm_vcpu *vcpu = filp->private_data;
2963 debugfs_remove_recursive(vcpu->debugfs_dentry);
2964 kvm_put_kvm(vcpu->kvm);
2965 return 0;
2968 static struct file_operations kvm_vcpu_fops = {
2969 .release = kvm_vcpu_release,
2970 .unlocked_ioctl = kvm_vcpu_ioctl,
2971 .mmap = kvm_vcpu_mmap,
2972 .llseek = noop_llseek,
2973 KVM_COMPAT(kvm_vcpu_compat_ioctl),
2977 * Allocates an inode for the vcpu.
2979 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2981 char name[8 + 1 + ITOA_MAX_LEN + 1];
2983 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
2984 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2987 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
2989 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
2990 char dir_name[ITOA_MAX_LEN * 2];
2992 if (!debugfs_initialized())
2993 return;
2995 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2996 vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
2997 vcpu->kvm->debugfs_dentry);
2999 kvm_arch_create_vcpu_debugfs(vcpu);
3000 #endif
3004 * Creates some virtual cpus. Good luck creating more than one.
3006 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3008 int r;
3009 struct kvm_vcpu *vcpu;
3010 struct page *page;
3012 if (id >= KVM_MAX_VCPU_ID)
3013 return -EINVAL;
3015 mutex_lock(&kvm->lock);
3016 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3017 mutex_unlock(&kvm->lock);
3018 return -EINVAL;
3021 kvm->created_vcpus++;
3022 mutex_unlock(&kvm->lock);
3024 r = kvm_arch_vcpu_precreate(kvm, id);
3025 if (r)
3026 goto vcpu_decrement;
3028 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
3029 if (!vcpu) {
3030 r = -ENOMEM;
3031 goto vcpu_decrement;
3034 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3035 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3036 if (!page) {
3037 r = -ENOMEM;
3038 goto vcpu_free;
3040 vcpu->run = page_address(page);
3042 kvm_vcpu_init(vcpu, kvm, id);
3044 r = kvm_arch_vcpu_create(vcpu);
3045 if (r)
3046 goto vcpu_free_run_page;
3048 kvm_create_vcpu_debugfs(vcpu);
3050 mutex_lock(&kvm->lock);
3051 if (kvm_get_vcpu_by_id(kvm, id)) {
3052 r = -EEXIST;
3053 goto unlock_vcpu_destroy;
3056 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3057 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
3059 /* Now it's all set up, let userspace reach it */
3060 kvm_get_kvm(kvm);
3061 r = create_vcpu_fd(vcpu);
3062 if (r < 0) {
3063 kvm_put_kvm_no_destroy(kvm);
3064 goto unlock_vcpu_destroy;
3067 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
3070 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3071 * before kvm->online_vcpu's incremented value.
3073 smp_wmb();
3074 atomic_inc(&kvm->online_vcpus);
3076 mutex_unlock(&kvm->lock);
3077 kvm_arch_vcpu_postcreate(vcpu);
3078 return r;
3080 unlock_vcpu_destroy:
3081 mutex_unlock(&kvm->lock);
3082 debugfs_remove_recursive(vcpu->debugfs_dentry);
3083 kvm_arch_vcpu_destroy(vcpu);
3084 vcpu_free_run_page:
3085 free_page((unsigned long)vcpu->run);
3086 vcpu_free:
3087 kmem_cache_free(kvm_vcpu_cache, vcpu);
3088 vcpu_decrement:
3089 mutex_lock(&kvm->lock);
3090 kvm->created_vcpus--;
3091 mutex_unlock(&kvm->lock);
3092 return r;
3095 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3097 if (sigset) {
3098 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3099 vcpu->sigset_active = 1;
3100 vcpu->sigset = *sigset;
3101 } else
3102 vcpu->sigset_active = 0;
3103 return 0;
3106 static long kvm_vcpu_ioctl(struct file *filp,
3107 unsigned int ioctl, unsigned long arg)
3109 struct kvm_vcpu *vcpu = filp->private_data;
3110 void __user *argp = (void __user *)arg;
3111 int r;
3112 struct kvm_fpu *fpu = NULL;
3113 struct kvm_sregs *kvm_sregs = NULL;
3115 if (vcpu->kvm->mm != current->mm)
3116 return -EIO;
3118 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3119 return -EINVAL;
3122 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3123 * execution; mutex_lock() would break them.
3125 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3126 if (r != -ENOIOCTLCMD)
3127 return r;
3129 if (mutex_lock_killable(&vcpu->mutex))
3130 return -EINTR;
3131 switch (ioctl) {
3132 case KVM_RUN: {
3133 struct pid *oldpid;
3134 r = -EINVAL;
3135 if (arg)
3136 goto out;
3137 oldpid = rcu_access_pointer(vcpu->pid);
3138 if (unlikely(oldpid != task_pid(current))) {
3139 /* The thread running this VCPU changed. */
3140 struct pid *newpid;
3142 r = kvm_arch_vcpu_run_pid_change(vcpu);
3143 if (r)
3144 break;
3146 newpid = get_task_pid(current, PIDTYPE_PID);
3147 rcu_assign_pointer(vcpu->pid, newpid);
3148 if (oldpid)
3149 synchronize_rcu();
3150 put_pid(oldpid);
3152 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
3153 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3154 break;
3156 case KVM_GET_REGS: {
3157 struct kvm_regs *kvm_regs;
3159 r = -ENOMEM;
3160 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3161 if (!kvm_regs)
3162 goto out;
3163 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3164 if (r)
3165 goto out_free1;
3166 r = -EFAULT;
3167 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3168 goto out_free1;
3169 r = 0;
3170 out_free1:
3171 kfree(kvm_regs);
3172 break;
3174 case KVM_SET_REGS: {
3175 struct kvm_regs *kvm_regs;
3177 r = -ENOMEM;
3178 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3179 if (IS_ERR(kvm_regs)) {
3180 r = PTR_ERR(kvm_regs);
3181 goto out;
3183 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3184 kfree(kvm_regs);
3185 break;
3187 case KVM_GET_SREGS: {
3188 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3189 GFP_KERNEL_ACCOUNT);
3190 r = -ENOMEM;
3191 if (!kvm_sregs)
3192 goto out;
3193 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3194 if (r)
3195 goto out;
3196 r = -EFAULT;
3197 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3198 goto out;
3199 r = 0;
3200 break;
3202 case KVM_SET_SREGS: {
3203 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3204 if (IS_ERR(kvm_sregs)) {
3205 r = PTR_ERR(kvm_sregs);
3206 kvm_sregs = NULL;
3207 goto out;
3209 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3210 break;
3212 case KVM_GET_MP_STATE: {
3213 struct kvm_mp_state mp_state;
3215 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3216 if (r)
3217 goto out;
3218 r = -EFAULT;
3219 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3220 goto out;
3221 r = 0;
3222 break;
3224 case KVM_SET_MP_STATE: {
3225 struct kvm_mp_state mp_state;
3227 r = -EFAULT;
3228 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3229 goto out;
3230 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3231 break;
3233 case KVM_TRANSLATE: {
3234 struct kvm_translation tr;
3236 r = -EFAULT;
3237 if (copy_from_user(&tr, argp, sizeof(tr)))
3238 goto out;
3239 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3240 if (r)
3241 goto out;
3242 r = -EFAULT;
3243 if (copy_to_user(argp, &tr, sizeof(tr)))
3244 goto out;
3245 r = 0;
3246 break;
3248 case KVM_SET_GUEST_DEBUG: {
3249 struct kvm_guest_debug dbg;
3251 r = -EFAULT;
3252 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3253 goto out;
3254 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3255 break;
3257 case KVM_SET_SIGNAL_MASK: {
3258 struct kvm_signal_mask __user *sigmask_arg = argp;
3259 struct kvm_signal_mask kvm_sigmask;
3260 sigset_t sigset, *p;
3262 p = NULL;
3263 if (argp) {
3264 r = -EFAULT;
3265 if (copy_from_user(&kvm_sigmask, argp,
3266 sizeof(kvm_sigmask)))
3267 goto out;
3268 r = -EINVAL;
3269 if (kvm_sigmask.len != sizeof(sigset))
3270 goto out;
3271 r = -EFAULT;
3272 if (copy_from_user(&sigset, sigmask_arg->sigset,
3273 sizeof(sigset)))
3274 goto out;
3275 p = &sigset;
3277 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3278 break;
3280 case KVM_GET_FPU: {
3281 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
3282 r = -ENOMEM;
3283 if (!fpu)
3284 goto out;
3285 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3286 if (r)
3287 goto out;
3288 r = -EFAULT;
3289 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3290 goto out;
3291 r = 0;
3292 break;
3294 case KVM_SET_FPU: {
3295 fpu = memdup_user(argp, sizeof(*fpu));
3296 if (IS_ERR(fpu)) {
3297 r = PTR_ERR(fpu);
3298 fpu = NULL;
3299 goto out;
3301 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3302 break;
3304 default:
3305 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3307 out:
3308 mutex_unlock(&vcpu->mutex);
3309 kfree(fpu);
3310 kfree(kvm_sregs);
3311 return r;
3314 #ifdef CONFIG_KVM_COMPAT
3315 static long kvm_vcpu_compat_ioctl(struct file *filp,
3316 unsigned int ioctl, unsigned long arg)
3318 struct kvm_vcpu *vcpu = filp->private_data;
3319 void __user *argp = compat_ptr(arg);
3320 int r;
3322 if (vcpu->kvm->mm != current->mm)
3323 return -EIO;
3325 switch (ioctl) {
3326 case KVM_SET_SIGNAL_MASK: {
3327 struct kvm_signal_mask __user *sigmask_arg = argp;
3328 struct kvm_signal_mask kvm_sigmask;
3329 sigset_t sigset;
3331 if (argp) {
3332 r = -EFAULT;
3333 if (copy_from_user(&kvm_sigmask, argp,
3334 sizeof(kvm_sigmask)))
3335 goto out;
3336 r = -EINVAL;
3337 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3338 goto out;
3339 r = -EFAULT;
3340 if (get_compat_sigset(&sigset, (void *)sigmask_arg->sigset))
3341 goto out;
3342 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3343 } else
3344 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3345 break;
3347 default:
3348 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3351 out:
3352 return r;
3354 #endif
3356 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3358 struct kvm_device *dev = filp->private_data;
3360 if (dev->ops->mmap)
3361 return dev->ops->mmap(dev, vma);
3363 return -ENODEV;
3366 static int kvm_device_ioctl_attr(struct kvm_device *dev,
3367 int (*accessor)(struct kvm_device *dev,
3368 struct kvm_device_attr *attr),
3369 unsigned long arg)
3371 struct kvm_device_attr attr;
3373 if (!accessor)
3374 return -EPERM;
3376 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3377 return -EFAULT;
3379 return accessor(dev, &attr);
3382 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3383 unsigned long arg)
3385 struct kvm_device *dev = filp->private_data;
3387 if (dev->kvm->mm != current->mm)
3388 return -EIO;
3390 switch (ioctl) {
3391 case KVM_SET_DEVICE_ATTR:
3392 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3393 case KVM_GET_DEVICE_ATTR:
3394 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3395 case KVM_HAS_DEVICE_ATTR:
3396 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3397 default:
3398 if (dev->ops->ioctl)
3399 return dev->ops->ioctl(dev, ioctl, arg);
3401 return -ENOTTY;
3405 static int kvm_device_release(struct inode *inode, struct file *filp)
3407 struct kvm_device *dev = filp->private_data;
3408 struct kvm *kvm = dev->kvm;
3410 if (dev->ops->release) {
3411 mutex_lock(&kvm->lock);
3412 list_del(&dev->vm_node);
3413 dev->ops->release(dev);
3414 mutex_unlock(&kvm->lock);
3417 kvm_put_kvm(kvm);
3418 return 0;
3421 static const struct file_operations kvm_device_fops = {
3422 .unlocked_ioctl = kvm_device_ioctl,
3423 .release = kvm_device_release,
3424 KVM_COMPAT(kvm_device_ioctl),
3425 .mmap = kvm_device_mmap,
3428 struct kvm_device *kvm_device_from_filp(struct file *filp)
3430 if (filp->f_op != &kvm_device_fops)
3431 return NULL;
3433 return filp->private_data;
3436 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
3437 #ifdef CONFIG_KVM_MPIC
3438 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3439 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3440 #endif
3443 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
3445 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3446 return -ENOSPC;
3448 if (kvm_device_ops_table[type] != NULL)
3449 return -EEXIST;
3451 kvm_device_ops_table[type] = ops;
3452 return 0;
3455 void kvm_unregister_device_ops(u32 type)
3457 if (kvm_device_ops_table[type] != NULL)
3458 kvm_device_ops_table[type] = NULL;
3461 static int kvm_ioctl_create_device(struct kvm *kvm,
3462 struct kvm_create_device *cd)
3464 const struct kvm_device_ops *ops = NULL;
3465 struct kvm_device *dev;
3466 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
3467 int type;
3468 int ret;
3470 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3471 return -ENODEV;
3473 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3474 ops = kvm_device_ops_table[type];
3475 if (ops == NULL)
3476 return -ENODEV;
3478 if (test)
3479 return 0;
3481 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
3482 if (!dev)
3483 return -ENOMEM;
3485 dev->ops = ops;
3486 dev->kvm = kvm;
3488 mutex_lock(&kvm->lock);
3489 ret = ops->create(dev, type);
3490 if (ret < 0) {
3491 mutex_unlock(&kvm->lock);
3492 kfree(dev);
3493 return ret;
3495 list_add(&dev->vm_node, &kvm->devices);
3496 mutex_unlock(&kvm->lock);
3498 if (ops->init)
3499 ops->init(dev);
3501 kvm_get_kvm(kvm);
3502 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3503 if (ret < 0) {
3504 kvm_put_kvm_no_destroy(kvm);
3505 mutex_lock(&kvm->lock);
3506 list_del(&dev->vm_node);
3507 mutex_unlock(&kvm->lock);
3508 ops->destroy(dev);
3509 return ret;
3512 cd->fd = ret;
3513 return 0;
3516 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3518 switch (arg) {
3519 case KVM_CAP_USER_MEMORY:
3520 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3521 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3522 case KVM_CAP_INTERNAL_ERROR_DATA:
3523 #ifdef CONFIG_HAVE_KVM_MSI
3524 case KVM_CAP_SIGNAL_MSI:
3525 #endif
3526 #ifdef CONFIG_HAVE_KVM_IRQFD
3527 case KVM_CAP_IRQFD:
3528 case KVM_CAP_IRQFD_RESAMPLE:
3529 #endif
3530 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3531 case KVM_CAP_CHECK_EXTENSION_VM:
3532 case KVM_CAP_ENABLE_CAP_VM:
3533 return 1;
3534 #ifdef CONFIG_KVM_MMIO
3535 case KVM_CAP_COALESCED_MMIO:
3536 return KVM_COALESCED_MMIO_PAGE_OFFSET;
3537 case KVM_CAP_COALESCED_PIO:
3538 return 1;
3539 #endif
3540 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3541 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
3542 return KVM_DIRTY_LOG_MANUAL_CAPS;
3543 #endif
3544 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3545 case KVM_CAP_IRQ_ROUTING:
3546 return KVM_MAX_IRQ_ROUTES;
3547 #endif
3548 #if KVM_ADDRESS_SPACE_NUM > 1
3549 case KVM_CAP_MULTI_ADDRESS_SPACE:
3550 return KVM_ADDRESS_SPACE_NUM;
3551 #endif
3552 case KVM_CAP_NR_MEMSLOTS:
3553 return KVM_USER_MEM_SLOTS;
3554 default:
3555 break;
3557 return kvm_vm_ioctl_check_extension(kvm, arg);
3560 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3561 struct kvm_enable_cap *cap)
3563 return -EINVAL;
3566 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
3567 struct kvm_enable_cap *cap)
3569 switch (cap->cap) {
3570 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3571 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
3572 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
3574 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
3575 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
3577 if (cap->flags || (cap->args[0] & ~allowed_options))
3578 return -EINVAL;
3579 kvm->manual_dirty_log_protect = cap->args[0];
3580 return 0;
3582 #endif
3583 default:
3584 return kvm_vm_ioctl_enable_cap(kvm, cap);
3588 static long kvm_vm_ioctl(struct file *filp,
3589 unsigned int ioctl, unsigned long arg)
3591 struct kvm *kvm = filp->private_data;
3592 void __user *argp = (void __user *)arg;
3593 int r;
3595 if (kvm->mm != current->mm)
3596 return -EIO;
3597 switch (ioctl) {
3598 case KVM_CREATE_VCPU:
3599 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3600 break;
3601 case KVM_ENABLE_CAP: {
3602 struct kvm_enable_cap cap;
3604 r = -EFAULT;
3605 if (copy_from_user(&cap, argp, sizeof(cap)))
3606 goto out;
3607 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
3608 break;
3610 case KVM_SET_USER_MEMORY_REGION: {
3611 struct kvm_userspace_memory_region kvm_userspace_mem;
3613 r = -EFAULT;
3614 if (copy_from_user(&kvm_userspace_mem, argp,
3615 sizeof(kvm_userspace_mem)))
3616 goto out;
3618 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3619 break;
3621 case KVM_GET_DIRTY_LOG: {
3622 struct kvm_dirty_log log;
3624 r = -EFAULT;
3625 if (copy_from_user(&log, argp, sizeof(log)))
3626 goto out;
3627 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3628 break;
3630 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3631 case KVM_CLEAR_DIRTY_LOG: {
3632 struct kvm_clear_dirty_log log;
3634 r = -EFAULT;
3635 if (copy_from_user(&log, argp, sizeof(log)))
3636 goto out;
3637 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3638 break;
3640 #endif
3641 #ifdef CONFIG_KVM_MMIO
3642 case KVM_REGISTER_COALESCED_MMIO: {
3643 struct kvm_coalesced_mmio_zone zone;
3645 r = -EFAULT;
3646 if (copy_from_user(&zone, argp, sizeof(zone)))
3647 goto out;
3648 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3649 break;
3651 case KVM_UNREGISTER_COALESCED_MMIO: {
3652 struct kvm_coalesced_mmio_zone zone;
3654 r = -EFAULT;
3655 if (copy_from_user(&zone, argp, sizeof(zone)))
3656 goto out;
3657 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3658 break;
3660 #endif
3661 case KVM_IRQFD: {
3662 struct kvm_irqfd data;
3664 r = -EFAULT;
3665 if (copy_from_user(&data, argp, sizeof(data)))
3666 goto out;
3667 r = kvm_irqfd(kvm, &data);
3668 break;
3670 case KVM_IOEVENTFD: {
3671 struct kvm_ioeventfd data;
3673 r = -EFAULT;
3674 if (copy_from_user(&data, argp, sizeof(data)))
3675 goto out;
3676 r = kvm_ioeventfd(kvm, &data);
3677 break;
3679 #ifdef CONFIG_HAVE_KVM_MSI
3680 case KVM_SIGNAL_MSI: {
3681 struct kvm_msi msi;
3683 r = -EFAULT;
3684 if (copy_from_user(&msi, argp, sizeof(msi)))
3685 goto out;
3686 r = kvm_send_userspace_msi(kvm, &msi);
3687 break;
3689 #endif
3690 #ifdef __KVM_HAVE_IRQ_LINE
3691 case KVM_IRQ_LINE_STATUS:
3692 case KVM_IRQ_LINE: {
3693 struct kvm_irq_level irq_event;
3695 r = -EFAULT;
3696 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3697 goto out;
3699 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3700 ioctl == KVM_IRQ_LINE_STATUS);
3701 if (r)
3702 goto out;
3704 r = -EFAULT;
3705 if (ioctl == KVM_IRQ_LINE_STATUS) {
3706 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3707 goto out;
3710 r = 0;
3711 break;
3713 #endif
3714 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3715 case KVM_SET_GSI_ROUTING: {
3716 struct kvm_irq_routing routing;
3717 struct kvm_irq_routing __user *urouting;
3718 struct kvm_irq_routing_entry *entries = NULL;
3720 r = -EFAULT;
3721 if (copy_from_user(&routing, argp, sizeof(routing)))
3722 goto out;
3723 r = -EINVAL;
3724 if (!kvm_arch_can_set_irq_routing(kvm))
3725 goto out;
3726 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3727 goto out;
3728 if (routing.flags)
3729 goto out;
3730 if (routing.nr) {
3731 r = -ENOMEM;
3732 entries = vmalloc(array_size(sizeof(*entries),
3733 routing.nr));
3734 if (!entries)
3735 goto out;
3736 r = -EFAULT;
3737 urouting = argp;
3738 if (copy_from_user(entries, urouting->entries,
3739 routing.nr * sizeof(*entries)))
3740 goto out_free_irq_routing;
3742 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3743 routing.flags);
3744 out_free_irq_routing:
3745 vfree(entries);
3746 break;
3748 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3749 case KVM_CREATE_DEVICE: {
3750 struct kvm_create_device cd;
3752 r = -EFAULT;
3753 if (copy_from_user(&cd, argp, sizeof(cd)))
3754 goto out;
3756 r = kvm_ioctl_create_device(kvm, &cd);
3757 if (r)
3758 goto out;
3760 r = -EFAULT;
3761 if (copy_to_user(argp, &cd, sizeof(cd)))
3762 goto out;
3764 r = 0;
3765 break;
3767 case KVM_CHECK_EXTENSION:
3768 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3769 break;
3770 default:
3771 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3773 out:
3774 return r;
3777 #ifdef CONFIG_KVM_COMPAT
3778 struct compat_kvm_dirty_log {
3779 __u32 slot;
3780 __u32 padding1;
3781 union {
3782 compat_uptr_t dirty_bitmap; /* one bit per page */
3783 __u64 padding2;
3787 static long kvm_vm_compat_ioctl(struct file *filp,
3788 unsigned int ioctl, unsigned long arg)
3790 struct kvm *kvm = filp->private_data;
3791 int r;
3793 if (kvm->mm != current->mm)
3794 return -EIO;
3795 switch (ioctl) {
3796 case KVM_GET_DIRTY_LOG: {
3797 struct compat_kvm_dirty_log compat_log;
3798 struct kvm_dirty_log log;
3800 if (copy_from_user(&compat_log, (void __user *)arg,
3801 sizeof(compat_log)))
3802 return -EFAULT;
3803 log.slot = compat_log.slot;
3804 log.padding1 = compat_log.padding1;
3805 log.padding2 = compat_log.padding2;
3806 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3808 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3809 break;
3811 default:
3812 r = kvm_vm_ioctl(filp, ioctl, arg);
3814 return r;
3816 #endif
3818 static struct file_operations kvm_vm_fops = {
3819 .release = kvm_vm_release,
3820 .unlocked_ioctl = kvm_vm_ioctl,
3821 .llseek = noop_llseek,
3822 KVM_COMPAT(kvm_vm_compat_ioctl),
3825 static int kvm_dev_ioctl_create_vm(unsigned long type)
3827 int r;
3828 struct kvm *kvm;
3829 struct file *file;
3831 kvm = kvm_create_vm(type);
3832 if (IS_ERR(kvm))
3833 return PTR_ERR(kvm);
3834 #ifdef CONFIG_KVM_MMIO
3835 r = kvm_coalesced_mmio_init(kvm);
3836 if (r < 0)
3837 goto put_kvm;
3838 #endif
3839 r = get_unused_fd_flags(O_CLOEXEC);
3840 if (r < 0)
3841 goto put_kvm;
3843 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3844 if (IS_ERR(file)) {
3845 put_unused_fd(r);
3846 r = PTR_ERR(file);
3847 goto put_kvm;
3851 * Don't call kvm_put_kvm anymore at this point; file->f_op is
3852 * already set, with ->release() being kvm_vm_release(). In error
3853 * cases it will be called by the final fput(file) and will take
3854 * care of doing kvm_put_kvm(kvm).
3856 if (kvm_create_vm_debugfs(kvm, r) < 0) {
3857 put_unused_fd(r);
3858 fput(file);
3859 return -ENOMEM;
3861 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
3863 fd_install(r, file);
3864 return r;
3866 put_kvm:
3867 kvm_put_kvm(kvm);
3868 return r;
3871 static long kvm_dev_ioctl(struct file *filp,
3872 unsigned int ioctl, unsigned long arg)
3874 long r = -EINVAL;
3876 switch (ioctl) {
3877 case KVM_GET_API_VERSION:
3878 if (arg)
3879 goto out;
3880 r = KVM_API_VERSION;
3881 break;
3882 case KVM_CREATE_VM:
3883 r = kvm_dev_ioctl_create_vm(arg);
3884 break;
3885 case KVM_CHECK_EXTENSION:
3886 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3887 break;
3888 case KVM_GET_VCPU_MMAP_SIZE:
3889 if (arg)
3890 goto out;
3891 r = PAGE_SIZE; /* struct kvm_run */
3892 #ifdef CONFIG_X86
3893 r += PAGE_SIZE; /* pio data page */
3894 #endif
3895 #ifdef CONFIG_KVM_MMIO
3896 r += PAGE_SIZE; /* coalesced mmio ring page */
3897 #endif
3898 break;
3899 case KVM_TRACE_ENABLE:
3900 case KVM_TRACE_PAUSE:
3901 case KVM_TRACE_DISABLE:
3902 r = -EOPNOTSUPP;
3903 break;
3904 default:
3905 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3907 out:
3908 return r;
3911 static struct file_operations kvm_chardev_ops = {
3912 .unlocked_ioctl = kvm_dev_ioctl,
3913 .llseek = noop_llseek,
3914 KVM_COMPAT(kvm_dev_ioctl),
3917 static struct miscdevice kvm_dev = {
3918 KVM_MINOR,
3919 "kvm",
3920 &kvm_chardev_ops,
3923 static void hardware_enable_nolock(void *junk)
3925 int cpu = raw_smp_processor_id();
3926 int r;
3928 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3929 return;
3931 cpumask_set_cpu(cpu, cpus_hardware_enabled);
3933 r = kvm_arch_hardware_enable();
3935 if (r) {
3936 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3937 atomic_inc(&hardware_enable_failed);
3938 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3942 static int kvm_starting_cpu(unsigned int cpu)
3944 raw_spin_lock(&kvm_count_lock);
3945 if (kvm_usage_count)
3946 hardware_enable_nolock(NULL);
3947 raw_spin_unlock(&kvm_count_lock);
3948 return 0;
3951 static void hardware_disable_nolock(void *junk)
3953 int cpu = raw_smp_processor_id();
3955 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3956 return;
3957 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3958 kvm_arch_hardware_disable();
3961 static int kvm_dying_cpu(unsigned int cpu)
3963 raw_spin_lock(&kvm_count_lock);
3964 if (kvm_usage_count)
3965 hardware_disable_nolock(NULL);
3966 raw_spin_unlock(&kvm_count_lock);
3967 return 0;
3970 static void hardware_disable_all_nolock(void)
3972 BUG_ON(!kvm_usage_count);
3974 kvm_usage_count--;
3975 if (!kvm_usage_count)
3976 on_each_cpu(hardware_disable_nolock, NULL, 1);
3979 static void hardware_disable_all(void)
3981 raw_spin_lock(&kvm_count_lock);
3982 hardware_disable_all_nolock();
3983 raw_spin_unlock(&kvm_count_lock);
3986 static int hardware_enable_all(void)
3988 int r = 0;
3990 raw_spin_lock(&kvm_count_lock);
3992 kvm_usage_count++;
3993 if (kvm_usage_count == 1) {
3994 atomic_set(&hardware_enable_failed, 0);
3995 on_each_cpu(hardware_enable_nolock, NULL, 1);
3997 if (atomic_read(&hardware_enable_failed)) {
3998 hardware_disable_all_nolock();
3999 r = -EBUSY;
4003 raw_spin_unlock(&kvm_count_lock);
4005 return r;
4008 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4009 void *v)
4012 * Some (well, at least mine) BIOSes hang on reboot if
4013 * in vmx root mode.
4015 * And Intel TXT required VMX off for all cpu when system shutdown.
4017 pr_info("kvm: exiting hardware virtualization\n");
4018 kvm_rebooting = true;
4019 on_each_cpu(hardware_disable_nolock, NULL, 1);
4020 return NOTIFY_OK;
4023 static struct notifier_block kvm_reboot_notifier = {
4024 .notifier_call = kvm_reboot,
4025 .priority = 0,
4028 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4030 int i;
4032 for (i = 0; i < bus->dev_count; i++) {
4033 struct kvm_io_device *pos = bus->range[i].dev;
4035 kvm_iodevice_destructor(pos);
4037 kfree(bus);
4040 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4041 const struct kvm_io_range *r2)
4043 gpa_t addr1 = r1->addr;
4044 gpa_t addr2 = r2->addr;
4046 if (addr1 < addr2)
4047 return -1;
4049 /* If r2->len == 0, match the exact address. If r2->len != 0,
4050 * accept any overlapping write. Any order is acceptable for
4051 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4052 * we process all of them.
4054 if (r2->len) {
4055 addr1 += r1->len;
4056 addr2 += r2->len;
4059 if (addr1 > addr2)
4060 return 1;
4062 return 0;
4065 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4067 return kvm_io_bus_cmp(p1, p2);
4070 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4071 gpa_t addr, int len)
4073 struct kvm_io_range *range, key;
4074 int off;
4076 key = (struct kvm_io_range) {
4077 .addr = addr,
4078 .len = len,
4081 range = bsearch(&key, bus->range, bus->dev_count,
4082 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4083 if (range == NULL)
4084 return -ENOENT;
4086 off = range - bus->range;
4088 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
4089 off--;
4091 return off;
4094 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4095 struct kvm_io_range *range, const void *val)
4097 int idx;
4099 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4100 if (idx < 0)
4101 return -EOPNOTSUPP;
4103 while (idx < bus->dev_count &&
4104 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4105 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
4106 range->len, val))
4107 return idx;
4108 idx++;
4111 return -EOPNOTSUPP;
4114 /* kvm_io_bus_write - called under kvm->slots_lock */
4115 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4116 int len, const void *val)
4118 struct kvm_io_bus *bus;
4119 struct kvm_io_range range;
4120 int r;
4122 range = (struct kvm_io_range) {
4123 .addr = addr,
4124 .len = len,
4127 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4128 if (!bus)
4129 return -ENOMEM;
4130 r = __kvm_io_bus_write(vcpu, bus, &range, val);
4131 return r < 0 ? r : 0;
4133 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
4135 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
4136 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4137 gpa_t addr, int len, const void *val, long cookie)
4139 struct kvm_io_bus *bus;
4140 struct kvm_io_range range;
4142 range = (struct kvm_io_range) {
4143 .addr = addr,
4144 .len = len,
4147 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4148 if (!bus)
4149 return -ENOMEM;
4151 /* First try the device referenced by cookie. */
4152 if ((cookie >= 0) && (cookie < bus->dev_count) &&
4153 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
4154 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
4155 val))
4156 return cookie;
4159 * cookie contained garbage; fall back to search and return the
4160 * correct cookie value.
4162 return __kvm_io_bus_write(vcpu, bus, &range, val);
4165 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4166 struct kvm_io_range *range, void *val)
4168 int idx;
4170 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4171 if (idx < 0)
4172 return -EOPNOTSUPP;
4174 while (idx < bus->dev_count &&
4175 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4176 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4177 range->len, val))
4178 return idx;
4179 idx++;
4182 return -EOPNOTSUPP;
4185 /* kvm_io_bus_read - called under kvm->slots_lock */
4186 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4187 int len, void *val)
4189 struct kvm_io_bus *bus;
4190 struct kvm_io_range range;
4191 int r;
4193 range = (struct kvm_io_range) {
4194 .addr = addr,
4195 .len = len,
4198 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4199 if (!bus)
4200 return -ENOMEM;
4201 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4202 return r < 0 ? r : 0;
4205 /* Caller must hold slots_lock. */
4206 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4207 int len, struct kvm_io_device *dev)
4209 int i;
4210 struct kvm_io_bus *new_bus, *bus;
4211 struct kvm_io_range range;
4213 bus = kvm_get_bus(kvm, bus_idx);
4214 if (!bus)
4215 return -ENOMEM;
4217 /* exclude ioeventfd which is limited by maximum fd */
4218 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
4219 return -ENOSPC;
4221 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
4222 GFP_KERNEL_ACCOUNT);
4223 if (!new_bus)
4224 return -ENOMEM;
4226 range = (struct kvm_io_range) {
4227 .addr = addr,
4228 .len = len,
4229 .dev = dev,
4232 for (i = 0; i < bus->dev_count; i++)
4233 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4234 break;
4236 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4237 new_bus->dev_count++;
4238 new_bus->range[i] = range;
4239 memcpy(new_bus->range + i + 1, bus->range + i,
4240 (bus->dev_count - i) * sizeof(struct kvm_io_range));
4241 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4242 synchronize_srcu_expedited(&kvm->srcu);
4243 kfree(bus);
4245 return 0;
4248 /* Caller must hold slots_lock. */
4249 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4250 struct kvm_io_device *dev)
4252 int i;
4253 struct kvm_io_bus *new_bus, *bus;
4255 bus = kvm_get_bus(kvm, bus_idx);
4256 if (!bus)
4257 return;
4259 for (i = 0; i < bus->dev_count; i++)
4260 if (bus->range[i].dev == dev) {
4261 break;
4264 if (i == bus->dev_count)
4265 return;
4267 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
4268 GFP_KERNEL_ACCOUNT);
4269 if (!new_bus) {
4270 pr_err("kvm: failed to shrink bus, removing it completely\n");
4271 goto broken;
4274 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4275 new_bus->dev_count--;
4276 memcpy(new_bus->range + i, bus->range + i + 1,
4277 (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
4279 broken:
4280 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4281 synchronize_srcu_expedited(&kvm->srcu);
4282 kfree(bus);
4283 return;
4286 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4287 gpa_t addr)
4289 struct kvm_io_bus *bus;
4290 int dev_idx, srcu_idx;
4291 struct kvm_io_device *iodev = NULL;
4293 srcu_idx = srcu_read_lock(&kvm->srcu);
4295 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
4296 if (!bus)
4297 goto out_unlock;
4299 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
4300 if (dev_idx < 0)
4301 goto out_unlock;
4303 iodev = bus->range[dev_idx].dev;
4305 out_unlock:
4306 srcu_read_unlock(&kvm->srcu, srcu_idx);
4308 return iodev;
4310 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4312 static int kvm_debugfs_open(struct inode *inode, struct file *file,
4313 int (*get)(void *, u64 *), int (*set)(void *, u64),
4314 const char *fmt)
4316 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4317 inode->i_private;
4319 /* The debugfs files are a reference to the kvm struct which
4320 * is still valid when kvm_destroy_vm is called.
4321 * To avoid the race between open and the removal of the debugfs
4322 * directory we test against the users count.
4324 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
4325 return -ENOENT;
4327 if (simple_attr_open(inode, file, get,
4328 KVM_DBGFS_GET_MODE(stat_data->dbgfs_item) & 0222
4329 ? set : NULL,
4330 fmt)) {
4331 kvm_put_kvm(stat_data->kvm);
4332 return -ENOMEM;
4335 return 0;
4338 static int kvm_debugfs_release(struct inode *inode, struct file *file)
4340 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4341 inode->i_private;
4343 simple_attr_release(inode, file);
4344 kvm_put_kvm(stat_data->kvm);
4346 return 0;
4349 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
4351 *val = *(ulong *)((void *)kvm + offset);
4353 return 0;
4356 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
4358 *(ulong *)((void *)kvm + offset) = 0;
4360 return 0;
4363 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
4365 int i;
4366 struct kvm_vcpu *vcpu;
4368 *val = 0;
4370 kvm_for_each_vcpu(i, vcpu, kvm)
4371 *val += *(u64 *)((void *)vcpu + offset);
4373 return 0;
4376 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
4378 int i;
4379 struct kvm_vcpu *vcpu;
4381 kvm_for_each_vcpu(i, vcpu, kvm)
4382 *(u64 *)((void *)vcpu + offset) = 0;
4384 return 0;
4387 static int kvm_stat_data_get(void *data, u64 *val)
4389 int r = -EFAULT;
4390 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4392 switch (stat_data->dbgfs_item->kind) {
4393 case KVM_STAT_VM:
4394 r = kvm_get_stat_per_vm(stat_data->kvm,
4395 stat_data->dbgfs_item->offset, val);
4396 break;
4397 case KVM_STAT_VCPU:
4398 r = kvm_get_stat_per_vcpu(stat_data->kvm,
4399 stat_data->dbgfs_item->offset, val);
4400 break;
4403 return r;
4406 static int kvm_stat_data_clear(void *data, u64 val)
4408 int r = -EFAULT;
4409 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4411 if (val)
4412 return -EINVAL;
4414 switch (stat_data->dbgfs_item->kind) {
4415 case KVM_STAT_VM:
4416 r = kvm_clear_stat_per_vm(stat_data->kvm,
4417 stat_data->dbgfs_item->offset);
4418 break;
4419 case KVM_STAT_VCPU:
4420 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
4421 stat_data->dbgfs_item->offset);
4422 break;
4425 return r;
4428 static int kvm_stat_data_open(struct inode *inode, struct file *file)
4430 __simple_attr_check_format("%llu\n", 0ull);
4431 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
4432 kvm_stat_data_clear, "%llu\n");
4435 static const struct file_operations stat_fops_per_vm = {
4436 .owner = THIS_MODULE,
4437 .open = kvm_stat_data_open,
4438 .release = kvm_debugfs_release,
4439 .read = simple_attr_read,
4440 .write = simple_attr_write,
4441 .llseek = no_llseek,
4444 static int vm_stat_get(void *_offset, u64 *val)
4446 unsigned offset = (long)_offset;
4447 struct kvm *kvm;
4448 u64 tmp_val;
4450 *val = 0;
4451 mutex_lock(&kvm_lock);
4452 list_for_each_entry(kvm, &vm_list, vm_list) {
4453 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
4454 *val += tmp_val;
4456 mutex_unlock(&kvm_lock);
4457 return 0;
4460 static int vm_stat_clear(void *_offset, u64 val)
4462 unsigned offset = (long)_offset;
4463 struct kvm *kvm;
4465 if (val)
4466 return -EINVAL;
4468 mutex_lock(&kvm_lock);
4469 list_for_each_entry(kvm, &vm_list, vm_list) {
4470 kvm_clear_stat_per_vm(kvm, offset);
4472 mutex_unlock(&kvm_lock);
4474 return 0;
4477 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
4479 static int vcpu_stat_get(void *_offset, u64 *val)
4481 unsigned offset = (long)_offset;
4482 struct kvm *kvm;
4483 u64 tmp_val;
4485 *val = 0;
4486 mutex_lock(&kvm_lock);
4487 list_for_each_entry(kvm, &vm_list, vm_list) {
4488 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
4489 *val += tmp_val;
4491 mutex_unlock(&kvm_lock);
4492 return 0;
4495 static int vcpu_stat_clear(void *_offset, u64 val)
4497 unsigned offset = (long)_offset;
4498 struct kvm *kvm;
4500 if (val)
4501 return -EINVAL;
4503 mutex_lock(&kvm_lock);
4504 list_for_each_entry(kvm, &vm_list, vm_list) {
4505 kvm_clear_stat_per_vcpu(kvm, offset);
4507 mutex_unlock(&kvm_lock);
4509 return 0;
4512 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4513 "%llu\n");
4515 static const struct file_operations *stat_fops[] = {
4516 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4517 [KVM_STAT_VM] = &vm_stat_fops,
4520 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4522 struct kobj_uevent_env *env;
4523 unsigned long long created, active;
4525 if (!kvm_dev.this_device || !kvm)
4526 return;
4528 mutex_lock(&kvm_lock);
4529 if (type == KVM_EVENT_CREATE_VM) {
4530 kvm_createvm_count++;
4531 kvm_active_vms++;
4532 } else if (type == KVM_EVENT_DESTROY_VM) {
4533 kvm_active_vms--;
4535 created = kvm_createvm_count;
4536 active = kvm_active_vms;
4537 mutex_unlock(&kvm_lock);
4539 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
4540 if (!env)
4541 return;
4543 add_uevent_var(env, "CREATED=%llu", created);
4544 add_uevent_var(env, "COUNT=%llu", active);
4546 if (type == KVM_EVENT_CREATE_VM) {
4547 add_uevent_var(env, "EVENT=create");
4548 kvm->userspace_pid = task_pid_nr(current);
4549 } else if (type == KVM_EVENT_DESTROY_VM) {
4550 add_uevent_var(env, "EVENT=destroy");
4552 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
4554 if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
4555 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
4557 if (p) {
4558 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4559 if (!IS_ERR(tmp))
4560 add_uevent_var(env, "STATS_PATH=%s", tmp);
4561 kfree(p);
4564 /* no need for checks, since we are adding at most only 5 keys */
4565 env->envp[env->envp_idx++] = NULL;
4566 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4567 kfree(env);
4570 static void kvm_init_debug(void)
4572 struct kvm_stats_debugfs_item *p;
4574 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4576 kvm_debugfs_num_entries = 0;
4577 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
4578 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
4579 kvm_debugfs_dir, (void *)(long)p->offset,
4580 stat_fops[p->kind]);
4584 static int kvm_suspend(void)
4586 if (kvm_usage_count)
4587 hardware_disable_nolock(NULL);
4588 return 0;
4591 static void kvm_resume(void)
4593 if (kvm_usage_count) {
4594 #ifdef CONFIG_LOCKDEP
4595 WARN_ON(lockdep_is_held(&kvm_count_lock));
4596 #endif
4597 hardware_enable_nolock(NULL);
4601 static struct syscore_ops kvm_syscore_ops = {
4602 .suspend = kvm_suspend,
4603 .resume = kvm_resume,
4606 static inline
4607 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4609 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4612 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4614 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4616 WRITE_ONCE(vcpu->preempted, false);
4617 WRITE_ONCE(vcpu->ready, false);
4619 __this_cpu_write(kvm_running_vcpu, vcpu);
4620 kvm_arch_sched_in(vcpu, cpu);
4621 kvm_arch_vcpu_load(vcpu, cpu);
4624 static void kvm_sched_out(struct preempt_notifier *pn,
4625 struct task_struct *next)
4627 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4629 if (current->state == TASK_RUNNING) {
4630 WRITE_ONCE(vcpu->preempted, true);
4631 WRITE_ONCE(vcpu->ready, true);
4633 kvm_arch_vcpu_put(vcpu);
4634 __this_cpu_write(kvm_running_vcpu, NULL);
4638 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
4640 * We can disable preemption locally around accessing the per-CPU variable,
4641 * and use the resolved vcpu pointer after enabling preemption again,
4642 * because even if the current thread is migrated to another CPU, reading
4643 * the per-CPU value later will give us the same value as we update the
4644 * per-CPU variable in the preempt notifier handlers.
4646 struct kvm_vcpu *kvm_get_running_vcpu(void)
4648 struct kvm_vcpu *vcpu;
4650 preempt_disable();
4651 vcpu = __this_cpu_read(kvm_running_vcpu);
4652 preempt_enable();
4654 return vcpu;
4658 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
4660 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
4662 return &kvm_running_vcpu;
4665 struct kvm_cpu_compat_check {
4666 void *opaque;
4667 int *ret;
4670 static void check_processor_compat(void *data)
4672 struct kvm_cpu_compat_check *c = data;
4674 *c->ret = kvm_arch_check_processor_compat(c->opaque);
4677 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
4678 struct module *module)
4680 struct kvm_cpu_compat_check c;
4681 int r;
4682 int cpu;
4684 r = kvm_arch_init(opaque);
4685 if (r)
4686 goto out_fail;
4689 * kvm_arch_init makes sure there's at most one caller
4690 * for architectures that support multiple implementations,
4691 * like intel and amd on x86.
4692 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4693 * conflicts in case kvm is already setup for another implementation.
4695 r = kvm_irqfd_init();
4696 if (r)
4697 goto out_irqfd;
4699 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
4700 r = -ENOMEM;
4701 goto out_free_0;
4704 r = kvm_arch_hardware_setup(opaque);
4705 if (r < 0)
4706 goto out_free_1;
4708 c.ret = &r;
4709 c.opaque = opaque;
4710 for_each_online_cpu(cpu) {
4711 smp_call_function_single(cpu, check_processor_compat, &c, 1);
4712 if (r < 0)
4713 goto out_free_2;
4716 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
4717 kvm_starting_cpu, kvm_dying_cpu);
4718 if (r)
4719 goto out_free_2;
4720 register_reboot_notifier(&kvm_reboot_notifier);
4722 /* A kmem cache lets us meet the alignment requirements of fx_save. */
4723 if (!vcpu_align)
4724 vcpu_align = __alignof__(struct kvm_vcpu);
4725 kvm_vcpu_cache =
4726 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4727 SLAB_ACCOUNT,
4728 offsetof(struct kvm_vcpu, arch),
4729 sizeof_field(struct kvm_vcpu, arch),
4730 NULL);
4731 if (!kvm_vcpu_cache) {
4732 r = -ENOMEM;
4733 goto out_free_3;
4736 r = kvm_async_pf_init();
4737 if (r)
4738 goto out_free;
4740 kvm_chardev_ops.owner = module;
4741 kvm_vm_fops.owner = module;
4742 kvm_vcpu_fops.owner = module;
4744 r = misc_register(&kvm_dev);
4745 if (r) {
4746 pr_err("kvm: misc device register failed\n");
4747 goto out_unreg;
4750 register_syscore_ops(&kvm_syscore_ops);
4752 kvm_preempt_ops.sched_in = kvm_sched_in;
4753 kvm_preempt_ops.sched_out = kvm_sched_out;
4755 kvm_init_debug();
4757 r = kvm_vfio_ops_init();
4758 WARN_ON(r);
4760 return 0;
4762 out_unreg:
4763 kvm_async_pf_deinit();
4764 out_free:
4765 kmem_cache_destroy(kvm_vcpu_cache);
4766 out_free_3:
4767 unregister_reboot_notifier(&kvm_reboot_notifier);
4768 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4769 out_free_2:
4770 kvm_arch_hardware_unsetup();
4771 out_free_1:
4772 free_cpumask_var(cpus_hardware_enabled);
4773 out_free_0:
4774 kvm_irqfd_exit();
4775 out_irqfd:
4776 kvm_arch_exit();
4777 out_fail:
4778 return r;
4780 EXPORT_SYMBOL_GPL(kvm_init);
4782 void kvm_exit(void)
4784 debugfs_remove_recursive(kvm_debugfs_dir);
4785 misc_deregister(&kvm_dev);
4786 kmem_cache_destroy(kvm_vcpu_cache);
4787 kvm_async_pf_deinit();
4788 unregister_syscore_ops(&kvm_syscore_ops);
4789 unregister_reboot_notifier(&kvm_reboot_notifier);
4790 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4791 on_each_cpu(hardware_disable_nolock, NULL, 1);
4792 kvm_arch_hardware_unsetup();
4793 kvm_arch_exit();
4794 kvm_irqfd_exit();
4795 free_cpumask_var(cpus_hardware_enabled);
4796 kvm_vfio_ops_exit();
4798 EXPORT_SYMBOL_GPL(kvm_exit);
4800 struct kvm_vm_worker_thread_context {
4801 struct kvm *kvm;
4802 struct task_struct *parent;
4803 struct completion init_done;
4804 kvm_vm_thread_fn_t thread_fn;
4805 uintptr_t data;
4806 int err;
4809 static int kvm_vm_worker_thread(void *context)
4812 * The init_context is allocated on the stack of the parent thread, so
4813 * we have to locally copy anything that is needed beyond initialization
4815 struct kvm_vm_worker_thread_context *init_context = context;
4816 struct kvm *kvm = init_context->kvm;
4817 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4818 uintptr_t data = init_context->data;
4819 int err;
4821 err = kthread_park(current);
4822 /* kthread_park(current) is never supposed to return an error */
4823 WARN_ON(err != 0);
4824 if (err)
4825 goto init_complete;
4827 err = cgroup_attach_task_all(init_context->parent, current);
4828 if (err) {
4829 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4830 __func__, err);
4831 goto init_complete;
4834 set_user_nice(current, task_nice(init_context->parent));
4836 init_complete:
4837 init_context->err = err;
4838 complete(&init_context->init_done);
4839 init_context = NULL;
4841 if (err)
4842 return err;
4844 /* Wait to be woken up by the spawner before proceeding. */
4845 kthread_parkme();
4847 if (!kthread_should_stop())
4848 err = thread_fn(kvm, data);
4850 return err;
4853 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4854 uintptr_t data, const char *name,
4855 struct task_struct **thread_ptr)
4857 struct kvm_vm_worker_thread_context init_context = {};
4858 struct task_struct *thread;
4860 *thread_ptr = NULL;
4861 init_context.kvm = kvm;
4862 init_context.parent = current;
4863 init_context.thread_fn = thread_fn;
4864 init_context.data = data;
4865 init_completion(&init_context.init_done);
4867 thread = kthread_run(kvm_vm_worker_thread, &init_context,
4868 "%s-%d", name, task_pid_nr(current));
4869 if (IS_ERR(thread))
4870 return PTR_ERR(thread);
4872 /* kthread_run is never supposed to return NULL */
4873 WARN_ON(thread == NULL);
4875 wait_for_completion(&init_context.init_done);
4877 if (!init_context.err)
4878 *thread_ptr = thread;
4880 return init_context.err;