blob: d22de439250768a5b1c7cd6780424ae69a22316a [file] [log] [blame]
David Brazdil0f672f62019-12-10 10:32:29 +00001// SPDX-License-Identifier: GPL-2.0-only
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002/*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
7 *
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10 *
11 * Authors:
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000014 */
15
16#include <kvm/iodev.h>
17
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>
David Brazdil0f672f62019-12-10 10:32:29 +000051#include <linux/io.h>
52#include <linux/lockdep.h>
53#include <linux/kthread.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000054
55#include <asm/processor.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000056#include <asm/ioctl.h>
57#include <linux/uaccess.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000058
59#include "coalesced_mmio.h"
60#include "async_pf.h"
61#include "vfio.h"
62
63#define CREATE_TRACE_POINTS
64#include <trace/events/kvm.h>
65
66/* Worst case buffer size needed for holding an integer. */
67#define ITOA_MAX_LEN 12
68
69MODULE_AUTHOR("Qumranet");
70MODULE_LICENSE("GPL");
71
72/* Architectures should define their poll value according to the halt latency */
73unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
74module_param(halt_poll_ns, uint, 0644);
75EXPORT_SYMBOL_GPL(halt_poll_ns);
76
77/* Default doubles per-vcpu halt_poll_ns. */
78unsigned int halt_poll_ns_grow = 2;
79module_param(halt_poll_ns_grow, uint, 0644);
80EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
81
David Brazdil0f672f62019-12-10 10:32:29 +000082/* The start value to grow halt_poll_ns from */
83unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
84module_param(halt_poll_ns_grow_start, uint, 0644);
85EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
86
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000087/* Default resets per-vcpu halt_poll_ns . */
88unsigned int halt_poll_ns_shrink;
89module_param(halt_poll_ns_shrink, uint, 0644);
90EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
91
92/*
93 * Ordering of locks:
94 *
95 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
96 */
97
David Brazdil0f672f62019-12-10 10:32:29 +000098DEFINE_MUTEX(kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000099static DEFINE_RAW_SPINLOCK(kvm_count_lock);
100LIST_HEAD(vm_list);
101
102static cpumask_var_t cpus_hardware_enabled;
103static int kvm_usage_count;
104static atomic_t hardware_enable_failed;
105
Olivier Deprez157378f2022-04-04 15:47:50 +0200106static struct kmem_cache *kvm_vcpu_cache;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000107
108static __read_mostly struct preempt_ops kvm_preempt_ops;
Olivier Deprez157378f2022-04-04 15:47:50 +0200109static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000110
111struct dentry *kvm_debugfs_dir;
112EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
113
114static int kvm_debugfs_num_entries;
Olivier Deprez157378f2022-04-04 15:47:50 +0200115static const struct file_operations stat_fops_per_vm;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000116
117static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
118 unsigned long arg);
119#ifdef CONFIG_KVM_COMPAT
120static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
121 unsigned long arg);
122#define KVM_COMPAT(c) .compat_ioctl = (c)
123#else
David Brazdil0f672f62019-12-10 10:32:29 +0000124/*
125 * For architectures that don't implement a compat infrastructure,
126 * adopt a double line of defense:
127 * - Prevent a compat task from opening /dev/kvm
128 * - If the open has been done by a 64bit task, and the KVM fd
129 * passed to a compat task, let the ioctls fail.
130 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000131static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
132 unsigned long arg) { return -EINVAL; }
David Brazdil0f672f62019-12-10 10:32:29 +0000133
134static int kvm_no_compat_open(struct inode *inode, struct file *file)
135{
136 return is_compat_task() ? -ENODEV : 0;
137}
138#define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
139 .open = kvm_no_compat_open
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000140#endif
141static int hardware_enable_all(void);
142static void hardware_disable_all(void);
143
144static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
145
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000146__visible bool kvm_rebooting;
147EXPORT_SYMBOL_GPL(kvm_rebooting);
148
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000149#define KVM_EVENT_CREATE_VM 0
150#define KVM_EVENT_DESTROY_VM 1
151static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
152static unsigned long long kvm_createvm_count;
153static unsigned long long kvm_active_vms;
154
Olivier Deprez0e641232021-09-23 10:07:05 +0200155__weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
156 unsigned long start, unsigned long end)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000157{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000158}
159
David Brazdil0f672f62019-12-10 10:32:29 +0000160bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
161{
162 /*
163 * The metadata used by is_zone_device_page() to determine whether or
164 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
165 * the device has been pinned, e.g. by get_user_pages(). WARN if the
166 * page_count() is zero to help detect bad usage of this helper.
167 */
168 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
169 return false;
170
171 return is_zone_device_page(pfn_to_page(pfn));
172}
173
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000174bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
175{
David Brazdil0f672f62019-12-10 10:32:29 +0000176 /*
177 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
178 * perspective they are "normal" pages, albeit with slightly different
179 * usage rules.
180 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000181 if (pfn_valid(pfn))
David Brazdil0f672f62019-12-10 10:32:29 +0000182 return PageReserved(pfn_to_page(pfn)) &&
Olivier Deprez0e641232021-09-23 10:07:05 +0200183 !is_zero_pfn(pfn) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000184 !kvm_is_zone_device_pfn(pfn);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000185
186 return true;
187}
188
Olivier Deprez157378f2022-04-04 15:47:50 +0200189bool kvm_is_transparent_hugepage(kvm_pfn_t pfn)
190{
191 struct page *page = pfn_to_page(pfn);
192
193 if (!PageTransCompoundMap(page))
194 return false;
195
196 return is_transparent_hugepage(compound_head(page));
197}
198
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000199/*
200 * Switches to specified vcpu, until a matching vcpu_put()
201 */
202void vcpu_load(struct kvm_vcpu *vcpu)
203{
204 int cpu = get_cpu();
Olivier Deprez157378f2022-04-04 15:47:50 +0200205
206 __this_cpu_write(kvm_running_vcpu, vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000207 preempt_notifier_register(&vcpu->preempt_notifier);
208 kvm_arch_vcpu_load(vcpu, cpu);
209 put_cpu();
210}
211EXPORT_SYMBOL_GPL(vcpu_load);
212
213void vcpu_put(struct kvm_vcpu *vcpu)
214{
215 preempt_disable();
216 kvm_arch_vcpu_put(vcpu);
217 preempt_notifier_unregister(&vcpu->preempt_notifier);
Olivier Deprez157378f2022-04-04 15:47:50 +0200218 __this_cpu_write(kvm_running_vcpu, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000219 preempt_enable();
220}
221EXPORT_SYMBOL_GPL(vcpu_put);
222
223/* TODO: merge with kvm_arch_vcpu_should_kick */
224static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
225{
226 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
227
228 /*
229 * We need to wait for the VCPU to reenable interrupts and get out of
230 * READING_SHADOW_PAGE_TABLES mode.
231 */
232 if (req & KVM_REQUEST_WAIT)
233 return mode != OUTSIDE_GUEST_MODE;
234
235 /*
236 * Need to kick a running VCPU, but otherwise there is nothing to do.
237 */
238 return mode == IN_GUEST_MODE;
239}
240
241static void ack_flush(void *_completed)
242{
243}
244
245static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
246{
247 if (unlikely(!cpus))
248 cpus = cpu_online_mask;
249
250 if (cpumask_empty(cpus))
251 return false;
252
253 smp_call_function_many(cpus, ack_flush, NULL, wait);
254 return true;
255}
256
257bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
Olivier Deprez157378f2022-04-04 15:47:50 +0200258 struct kvm_vcpu *except,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000259 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
260{
261 int i, cpu, me;
262 struct kvm_vcpu *vcpu;
263 bool called;
264
265 me = get_cpu();
266
267 kvm_for_each_vcpu(i, vcpu, kvm) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200268 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
269 vcpu == except)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000270 continue;
271
272 kvm_make_request(req, vcpu);
273 cpu = vcpu->cpu;
274
275 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
276 continue;
277
278 if (tmp != NULL && cpu != -1 && cpu != me &&
279 kvm_request_needs_ipi(vcpu, req))
280 __cpumask_set_cpu(cpu, tmp);
281 }
282
283 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
284 put_cpu();
285
286 return called;
287}
288
Olivier Deprez157378f2022-04-04 15:47:50 +0200289bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
290 struct kvm_vcpu *except)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000291{
292 cpumask_var_t cpus;
293 bool called;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000294
295 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
296
Olivier Deprez157378f2022-04-04 15:47:50 +0200297 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000298
299 free_cpumask_var(cpus);
300 return called;
301}
302
Olivier Deprez157378f2022-04-04 15:47:50 +0200303bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
304{
305 return kvm_make_all_cpus_request_except(kvm, req, NULL);
306}
307
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000308#ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
309void kvm_flush_remote_tlbs(struct kvm *kvm)
310{
311 /*
312 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
313 * kvm_make_all_cpus_request.
314 */
315 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
316
317 /*
318 * We want to publish modifications to the page tables before reading
319 * mode. Pairs with a memory barrier in arch-specific code.
320 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
321 * and smp_mb in walk_shadow_page_lockless_begin/end.
322 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
323 *
324 * There is already an smp_mb__after_atomic() before
325 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
326 * barrier here.
327 */
328 if (!kvm_arch_flush_remote_tlb(kvm)
329 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
330 ++kvm->stat.remote_tlb_flush;
331 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
332}
333EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
334#endif
335
336void kvm_reload_remote_mmus(struct kvm *kvm)
337{
338 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
339}
340
Olivier Deprez157378f2022-04-04 15:47:50 +0200341#ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
342static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
343 gfp_t gfp_flags)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000344{
Olivier Deprez157378f2022-04-04 15:47:50 +0200345 gfp_flags |= mc->gfp_zero;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000346
Olivier Deprez157378f2022-04-04 15:47:50 +0200347 if (mc->kmem_cache)
348 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
349 else
350 return (void *)__get_free_page(gfp_flags);
351}
352
353int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
354{
355 void *obj;
356
357 if (mc->nobjs >= min)
358 return 0;
359 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
360 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
361 if (!obj)
362 return mc->nobjs >= min ? 0 : -ENOMEM;
363 mc->objects[mc->nobjs++] = obj;
364 }
365 return 0;
366}
367
368int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
369{
370 return mc->nobjs;
371}
372
373void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
374{
375 while (mc->nobjs) {
376 if (mc->kmem_cache)
377 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
378 else
379 free_page((unsigned long)mc->objects[--mc->nobjs]);
380 }
381}
382
383void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
384{
385 void *p;
386
387 if (WARN_ON(!mc->nobjs))
388 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
389 else
390 p = mc->objects[--mc->nobjs];
391 BUG_ON(!p);
392 return p;
393}
394#endif
395
396static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
397{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000398 mutex_init(&vcpu->mutex);
399 vcpu->cpu = -1;
400 vcpu->kvm = kvm;
401 vcpu->vcpu_id = id;
402 vcpu->pid = NULL;
Olivier Deprez157378f2022-04-04 15:47:50 +0200403 rcuwait_init(&vcpu->wait);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000404 kvm_async_pf_vcpu_init(vcpu);
405
406 vcpu->pre_pcpu = -1;
407 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
408
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000409 kvm_vcpu_set_in_spin_loop(vcpu, false);
410 kvm_vcpu_set_dy_eligible(vcpu, false);
411 vcpu->preempted = false;
David Brazdil0f672f62019-12-10 10:32:29 +0000412 vcpu->ready = false;
Olivier Deprez157378f2022-04-04 15:47:50 +0200413 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000414}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000415
Olivier Deprez157378f2022-04-04 15:47:50 +0200416void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000417{
Olivier Deprez157378f2022-04-04 15:47:50 +0200418 kvm_arch_vcpu_destroy(vcpu);
419
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000420 /*
Olivier Deprez157378f2022-04-04 15:47:50 +0200421 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
422 * the vcpu->pid pointer, and at destruction time all file descriptors
423 * are already gone.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000424 */
425 put_pid(rcu_dereference_protected(vcpu->pid, 1));
Olivier Deprez157378f2022-04-04 15:47:50 +0200426
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000427 free_page((unsigned long)vcpu->run);
Olivier Deprez157378f2022-04-04 15:47:50 +0200428 kmem_cache_free(kvm_vcpu_cache, vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000429}
Olivier Deprez157378f2022-04-04 15:47:50 +0200430EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000431
432#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
433static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
434{
435 return container_of(mn, struct kvm, mmu_notifier);
436}
437
Olivier Deprez0e641232021-09-23 10:07:05 +0200438static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
439 struct mm_struct *mm,
440 unsigned long start, unsigned long end)
441{
442 struct kvm *kvm = mmu_notifier_to_kvm(mn);
443 int idx;
444
445 idx = srcu_read_lock(&kvm->srcu);
446 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
447 srcu_read_unlock(&kvm->srcu, idx);
448}
449
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000450static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
451 struct mm_struct *mm,
452 unsigned long address,
453 pte_t pte)
454{
455 struct kvm *kvm = mmu_notifier_to_kvm(mn);
456 int idx;
457
458 idx = srcu_read_lock(&kvm->srcu);
459 spin_lock(&kvm->mmu_lock);
460 kvm->mmu_notifier_seq++;
David Brazdil0f672f62019-12-10 10:32:29 +0000461
462 if (kvm_set_spte_hva(kvm, address, pte))
463 kvm_flush_remote_tlbs(kvm);
464
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000465 spin_unlock(&kvm->mmu_lock);
466 srcu_read_unlock(&kvm->srcu, idx);
467}
468
469static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
David Brazdil0f672f62019-12-10 10:32:29 +0000470 const struct mmu_notifier_range *range)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000471{
472 struct kvm *kvm = mmu_notifier_to_kvm(mn);
473 int need_tlb_flush = 0, idx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000474
475 idx = srcu_read_lock(&kvm->srcu);
476 spin_lock(&kvm->mmu_lock);
477 /*
478 * The count increase must become visible at unlock time as no
479 * spte can be established without taking the mmu_lock and
480 * count is also read inside the mmu_lock critical section.
481 */
482 kvm->mmu_notifier_count++;
Olivier Deprez0e641232021-09-23 10:07:05 +0200483 need_tlb_flush = kvm_unmap_hva_range(kvm, range->start, range->end,
484 range->flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000485 /* we've to flush the tlb before the pages can be freed */
Olivier Deprez0e641232021-09-23 10:07:05 +0200486 if (need_tlb_flush || kvm->tlbs_dirty)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000487 kvm_flush_remote_tlbs(kvm);
488
489 spin_unlock(&kvm->mmu_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000490 srcu_read_unlock(&kvm->srcu, idx);
491
Olivier Deprez0e641232021-09-23 10:07:05 +0200492 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000493}
494
495static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
David Brazdil0f672f62019-12-10 10:32:29 +0000496 const struct mmu_notifier_range *range)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000497{
498 struct kvm *kvm = mmu_notifier_to_kvm(mn);
499
500 spin_lock(&kvm->mmu_lock);
501 /*
502 * This sequence increase will notify the kvm page fault that
503 * the page that is going to be mapped in the spte could have
504 * been freed.
505 */
506 kvm->mmu_notifier_seq++;
507 smp_wmb();
508 /*
509 * The above sequence increase must be visible before the
510 * below count decrease, which is ensured by the smp_wmb above
511 * in conjunction with the smp_rmb in mmu_notifier_retry().
512 */
513 kvm->mmu_notifier_count--;
514 spin_unlock(&kvm->mmu_lock);
515
516 BUG_ON(kvm->mmu_notifier_count < 0);
517}
518
519static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
520 struct mm_struct *mm,
521 unsigned long start,
522 unsigned long end)
523{
524 struct kvm *kvm = mmu_notifier_to_kvm(mn);
525 int young, idx;
526
527 idx = srcu_read_lock(&kvm->srcu);
528 spin_lock(&kvm->mmu_lock);
529
530 young = kvm_age_hva(kvm, start, end);
531 if (young)
532 kvm_flush_remote_tlbs(kvm);
533
534 spin_unlock(&kvm->mmu_lock);
535 srcu_read_unlock(&kvm->srcu, idx);
536
537 return young;
538}
539
540static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
541 struct mm_struct *mm,
542 unsigned long start,
543 unsigned long end)
544{
545 struct kvm *kvm = mmu_notifier_to_kvm(mn);
546 int young, idx;
547
548 idx = srcu_read_lock(&kvm->srcu);
549 spin_lock(&kvm->mmu_lock);
550 /*
551 * Even though we do not flush TLB, this will still adversely
552 * affect performance on pre-Haswell Intel EPT, where there is
553 * no EPT Access Bit to clear so that we have to tear down EPT
554 * tables instead. If we find this unacceptable, we can always
555 * add a parameter to kvm_age_hva so that it effectively doesn't
556 * do anything on clear_young.
557 *
558 * Also note that currently we never issue secondary TLB flushes
559 * from clear_young, leaving this job up to the regular system
560 * cadence. If we find this inaccurate, we might come up with a
561 * more sophisticated heuristic later.
562 */
563 young = kvm_age_hva(kvm, start, end);
564 spin_unlock(&kvm->mmu_lock);
565 srcu_read_unlock(&kvm->srcu, idx);
566
567 return young;
568}
569
570static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
571 struct mm_struct *mm,
572 unsigned long address)
573{
574 struct kvm *kvm = mmu_notifier_to_kvm(mn);
575 int young, idx;
576
577 idx = srcu_read_lock(&kvm->srcu);
578 spin_lock(&kvm->mmu_lock);
579 young = kvm_test_age_hva(kvm, address);
580 spin_unlock(&kvm->mmu_lock);
581 srcu_read_unlock(&kvm->srcu, idx);
582
583 return young;
584}
585
586static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
587 struct mm_struct *mm)
588{
589 struct kvm *kvm = mmu_notifier_to_kvm(mn);
590 int idx;
591
592 idx = srcu_read_lock(&kvm->srcu);
593 kvm_arch_flush_shadow_all(kvm);
594 srcu_read_unlock(&kvm->srcu, idx);
595}
596
597static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
Olivier Deprez0e641232021-09-23 10:07:05 +0200598 .invalidate_range = kvm_mmu_notifier_invalidate_range,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000599 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
600 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
601 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
602 .clear_young = kvm_mmu_notifier_clear_young,
603 .test_young = kvm_mmu_notifier_test_young,
604 .change_pte = kvm_mmu_notifier_change_pte,
605 .release = kvm_mmu_notifier_release,
606};
607
608static int kvm_init_mmu_notifier(struct kvm *kvm)
609{
610 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
611 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
612}
613
614#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
615
616static int kvm_init_mmu_notifier(struct kvm *kvm)
617{
618 return 0;
619}
620
621#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
622
623static struct kvm_memslots *kvm_alloc_memslots(void)
624{
625 int i;
626 struct kvm_memslots *slots;
627
David Brazdil0f672f62019-12-10 10:32:29 +0000628 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000629 if (!slots)
630 return NULL;
631
632 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
Olivier Deprez157378f2022-04-04 15:47:50 +0200633 slots->id_to_index[i] = -1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000634
635 return slots;
636}
637
638static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
639{
640 if (!memslot->dirty_bitmap)
641 return;
642
643 kvfree(memslot->dirty_bitmap);
644 memslot->dirty_bitmap = NULL;
645}
646
Olivier Deprez157378f2022-04-04 15:47:50 +0200647static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000648{
Olivier Deprez157378f2022-04-04 15:47:50 +0200649 kvm_destroy_dirty_bitmap(slot);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000650
Olivier Deprez157378f2022-04-04 15:47:50 +0200651 kvm_arch_free_memslot(kvm, slot);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000652
Olivier Deprez157378f2022-04-04 15:47:50 +0200653 slot->flags = 0;
654 slot->npages = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000655}
656
657static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
658{
659 struct kvm_memory_slot *memslot;
660
661 if (!slots)
662 return;
663
664 kvm_for_each_memslot(memslot, slots)
Olivier Deprez157378f2022-04-04 15:47:50 +0200665 kvm_free_memslot(kvm, memslot);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000666
667 kvfree(slots);
668}
669
670static void kvm_destroy_vm_debugfs(struct kvm *kvm)
671{
672 int i;
673
674 if (!kvm->debugfs_dentry)
675 return;
676
677 debugfs_remove_recursive(kvm->debugfs_dentry);
678
679 if (kvm->debugfs_stat_data) {
680 for (i = 0; i < kvm_debugfs_num_entries; i++)
681 kfree(kvm->debugfs_stat_data[i]);
682 kfree(kvm->debugfs_stat_data);
683 }
684}
685
686static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
687{
Olivier Deprez0e641232021-09-23 10:07:05 +0200688 static DEFINE_MUTEX(kvm_debugfs_lock);
689 struct dentry *dent;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000690 char dir_name[ITOA_MAX_LEN * 2];
691 struct kvm_stat_data *stat_data;
692 struct kvm_stats_debugfs_item *p;
693
694 if (!debugfs_initialized())
695 return 0;
696
697 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
Olivier Deprez0e641232021-09-23 10:07:05 +0200698 mutex_lock(&kvm_debugfs_lock);
699 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
700 if (dent) {
701 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
702 dput(dent);
703 mutex_unlock(&kvm_debugfs_lock);
704 return 0;
705 }
706 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
707 mutex_unlock(&kvm_debugfs_lock);
708 if (IS_ERR(dent))
709 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000710
Olivier Deprez0e641232021-09-23 10:07:05 +0200711 kvm->debugfs_dentry = dent;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000712 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
713 sizeof(*kvm->debugfs_stat_data),
David Brazdil0f672f62019-12-10 10:32:29 +0000714 GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000715 if (!kvm->debugfs_stat_data)
716 return -ENOMEM;
717
718 for (p = debugfs_entries; p->name; p++) {
David Brazdil0f672f62019-12-10 10:32:29 +0000719 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000720 if (!stat_data)
721 return -ENOMEM;
722
723 stat_data->kvm = kvm;
Olivier Deprez157378f2022-04-04 15:47:50 +0200724 stat_data->dbgfs_item = p;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000725 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
Olivier Deprez157378f2022-04-04 15:47:50 +0200726 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
727 kvm->debugfs_dentry, stat_data,
728 &stat_fops_per_vm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000729 }
730 return 0;
731}
732
David Brazdil0f672f62019-12-10 10:32:29 +0000733/*
734 * Called after the VM is otherwise initialized, but just before adding it to
735 * the vm_list.
736 */
737int __weak kvm_arch_post_init_vm(struct kvm *kvm)
738{
739 return 0;
740}
741
742/*
743 * Called just after removing the VM from the vm_list, but before doing any
744 * other destruction.
745 */
746void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
747{
748}
749
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000750static struct kvm *kvm_create_vm(unsigned long type)
751{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000752 struct kvm *kvm = kvm_arch_alloc_vm();
David Brazdil0f672f62019-12-10 10:32:29 +0000753 int r = -ENOMEM;
754 int i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000755
756 if (!kvm)
757 return ERR_PTR(-ENOMEM);
758
759 spin_lock_init(&kvm->mmu_lock);
760 mmgrab(current->mm);
761 kvm->mm = current->mm;
762 kvm_eventfd_init(kvm);
763 mutex_init(&kvm->lock);
764 mutex_init(&kvm->irq_lock);
765 mutex_init(&kvm->slots_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000766 INIT_LIST_HEAD(&kvm->devices);
767
David Brazdil0f672f62019-12-10 10:32:29 +0000768 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
769
770 if (init_srcu_struct(&kvm->srcu))
771 goto out_err_no_srcu;
772 if (init_srcu_struct(&kvm->irq_srcu))
773 goto out_err_no_irq_srcu;
774
775 refcount_set(&kvm->users_count, 1);
776 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
777 struct kvm_memslots *slots = kvm_alloc_memslots();
778
779 if (!slots)
780 goto out_err_no_arch_destroy_vm;
781 /* Generations must be different for each address space. */
782 slots->generation = i;
783 rcu_assign_pointer(kvm->memslots[i], slots);
784 }
785
786 for (i = 0; i < KVM_NR_BUSES; i++) {
787 rcu_assign_pointer(kvm->buses[i],
788 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
789 if (!kvm->buses[i])
790 goto out_err_no_arch_destroy_vm;
791 }
792
Olivier Deprez157378f2022-04-04 15:47:50 +0200793 kvm->max_halt_poll_ns = halt_poll_ns;
794
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000795 r = kvm_arch_init_vm(kvm, type);
796 if (r)
David Brazdil0f672f62019-12-10 10:32:29 +0000797 goto out_err_no_arch_destroy_vm;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000798
799 r = hardware_enable_all();
800 if (r)
801 goto out_err_no_disable;
802
803#ifdef CONFIG_HAVE_KVM_IRQFD
804 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
805#endif
806
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000807 r = kvm_init_mmu_notifier(kvm);
808 if (r)
David Brazdil0f672f62019-12-10 10:32:29 +0000809 goto out_err_no_mmu_notifier;
810
811 r = kvm_arch_post_init_vm(kvm);
812 if (r)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000813 goto out_err;
814
David Brazdil0f672f62019-12-10 10:32:29 +0000815 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000816 list_add(&kvm->vm_list, &vm_list);
David Brazdil0f672f62019-12-10 10:32:29 +0000817 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000818
819 preempt_notifier_inc();
820
821 return kvm;
822
823out_err:
David Brazdil0f672f62019-12-10 10:32:29 +0000824#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
825 if (kvm->mmu_notifier.ops)
826 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
827#endif
828out_err_no_mmu_notifier:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000829 hardware_disable_all();
830out_err_no_disable:
David Brazdil0f672f62019-12-10 10:32:29 +0000831 kvm_arch_destroy_vm(kvm);
832out_err_no_arch_destroy_vm:
833 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000834 for (i = 0; i < KVM_NR_BUSES; i++)
835 kfree(kvm_get_bus(kvm, i));
836 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
837 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
David Brazdil0f672f62019-12-10 10:32:29 +0000838 cleanup_srcu_struct(&kvm->irq_srcu);
839out_err_no_irq_srcu:
840 cleanup_srcu_struct(&kvm->srcu);
841out_err_no_srcu:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000842 kvm_arch_free_vm(kvm);
843 mmdrop(current->mm);
844 return ERR_PTR(r);
845}
846
847static void kvm_destroy_devices(struct kvm *kvm)
848{
849 struct kvm_device *dev, *tmp;
850
851 /*
852 * We do not need to take the kvm->lock here, because nobody else
853 * has a reference to the struct kvm at this point and therefore
854 * cannot access the devices list anyhow.
855 */
856 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
857 list_del(&dev->vm_node);
858 dev->ops->destroy(dev);
859 }
860}
861
862static void kvm_destroy_vm(struct kvm *kvm)
863{
864 int i;
865 struct mm_struct *mm = kvm->mm;
866
867 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
868 kvm_destroy_vm_debugfs(kvm);
869 kvm_arch_sync_events(kvm);
David Brazdil0f672f62019-12-10 10:32:29 +0000870 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000871 list_del(&kvm->vm_list);
David Brazdil0f672f62019-12-10 10:32:29 +0000872 mutex_unlock(&kvm_lock);
873 kvm_arch_pre_destroy_vm(kvm);
874
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000875 kvm_free_irq_routing(kvm);
876 for (i = 0; i < KVM_NR_BUSES; i++) {
877 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
878
879 if (bus)
880 kvm_io_bus_destroy(bus);
881 kvm->buses[i] = NULL;
882 }
883 kvm_coalesced_mmio_free(kvm);
884#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
885 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
886#else
887 kvm_arch_flush_shadow_all(kvm);
888#endif
889 kvm_arch_destroy_vm(kvm);
890 kvm_destroy_devices(kvm);
891 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
892 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
893 cleanup_srcu_struct(&kvm->irq_srcu);
894 cleanup_srcu_struct(&kvm->srcu);
895 kvm_arch_free_vm(kvm);
896 preempt_notifier_dec();
897 hardware_disable_all();
898 mmdrop(mm);
899}
900
901void kvm_get_kvm(struct kvm *kvm)
902{
903 refcount_inc(&kvm->users_count);
904}
905EXPORT_SYMBOL_GPL(kvm_get_kvm);
906
907void kvm_put_kvm(struct kvm *kvm)
908{
909 if (refcount_dec_and_test(&kvm->users_count))
910 kvm_destroy_vm(kvm);
911}
912EXPORT_SYMBOL_GPL(kvm_put_kvm);
913
Olivier Deprez157378f2022-04-04 15:47:50 +0200914/*
915 * Used to put a reference that was taken on behalf of an object associated
916 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
917 * of the new file descriptor fails and the reference cannot be transferred to
918 * its final owner. In such cases, the caller is still actively using @kvm and
919 * will fail miserably if the refcount unexpectedly hits zero.
920 */
921void kvm_put_kvm_no_destroy(struct kvm *kvm)
922{
923 WARN_ON(refcount_dec_and_test(&kvm->users_count));
924}
925EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000926
927static int kvm_vm_release(struct inode *inode, struct file *filp)
928{
929 struct kvm *kvm = filp->private_data;
930
931 kvm_irqfd_release(kvm);
932
933 kvm_put_kvm(kvm);
934 return 0;
935}
936
937/*
938 * Allocation size is twice as large as the actual dirty bitmap size.
Olivier Deprez157378f2022-04-04 15:47:50 +0200939 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000940 */
Olivier Deprez157378f2022-04-04 15:47:50 +0200941static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000942{
943 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
944
David Brazdil0f672f62019-12-10 10:32:29 +0000945 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000946 if (!memslot->dirty_bitmap)
947 return -ENOMEM;
948
949 return 0;
950}
951
952/*
Olivier Deprez157378f2022-04-04 15:47:50 +0200953 * Delete a memslot by decrementing the number of used slots and shifting all
954 * other entries in the array forward one spot.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000955 */
Olivier Deprez157378f2022-04-04 15:47:50 +0200956static inline void kvm_memslot_delete(struct kvm_memslots *slots,
957 struct kvm_memory_slot *memslot)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000958{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000959 struct kvm_memory_slot *mslots = slots->memslots;
Olivier Deprez157378f2022-04-04 15:47:50 +0200960 int i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000961
Olivier Deprez157378f2022-04-04 15:47:50 +0200962 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
963 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000964
Olivier Deprez157378f2022-04-04 15:47:50 +0200965 slots->used_slots--;
966
967 if (atomic_read(&slots->lru_slot) >= slots->used_slots)
968 atomic_set(&slots->lru_slot, 0);
969
970 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000971 mslots[i] = mslots[i + 1];
972 slots->id_to_index[mslots[i].id] = i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000973 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200974 mslots[i] = *memslot;
975 slots->id_to_index[memslot->id] = -1;
976}
977
978/*
979 * "Insert" a new memslot by incrementing the number of used slots. Returns
980 * the new slot's initial index into the memslots array.
981 */
982static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
983{
984 return slots->used_slots++;
985}
986
987/*
988 * Move a changed memslot backwards in the array by shifting existing slots
989 * with a higher GFN toward the front of the array. Note, the changed memslot
990 * itself is not preserved in the array, i.e. not swapped at this time, only
991 * its new index into the array is tracked. Returns the changed memslot's
992 * current index into the memslots array.
993 */
994static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
995 struct kvm_memory_slot *memslot)
996{
997 struct kvm_memory_slot *mslots = slots->memslots;
998 int i;
999
1000 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
1001 WARN_ON_ONCE(!slots->used_slots))
1002 return -1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001003
1004 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02001005 * Move the target memslot backward in the array by shifting existing
1006 * memslots with a higher GFN (than the target memslot) towards the
1007 * front of the array.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001008 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001009 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
1010 if (memslot->base_gfn > mslots[i + 1].base_gfn)
1011 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001012
Olivier Deprez157378f2022-04-04 15:47:50 +02001013 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
1014
1015 /* Shift the next memslot forward one and update its index. */
1016 mslots[i] = mslots[i + 1];
1017 slots->id_to_index[mslots[i].id] = i;
1018 }
1019 return i;
1020}
1021
1022/*
1023 * Move a changed memslot forwards in the array by shifting existing slots with
1024 * a lower GFN toward the back of the array. Note, the changed memslot itself
1025 * is not preserved in the array, i.e. not swapped at this time, only its new
1026 * index into the array is tracked. Returns the changed memslot's final index
1027 * into the memslots array.
1028 */
1029static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
1030 struct kvm_memory_slot *memslot,
1031 int start)
1032{
1033 struct kvm_memory_slot *mslots = slots->memslots;
1034 int i;
1035
1036 for (i = start; i > 0; i--) {
1037 if (memslot->base_gfn < mslots[i - 1].base_gfn)
1038 break;
1039
1040 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
1041
1042 /* Shift the next memslot back one and update its index. */
1043 mslots[i] = mslots[i - 1];
1044 slots->id_to_index[mslots[i].id] = i;
1045 }
1046 return i;
1047}
1048
1049/*
1050 * Re-sort memslots based on their GFN to account for an added, deleted, or
1051 * moved memslot. Sorting memslots by GFN allows using a binary search during
1052 * memslot lookup.
1053 *
1054 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
1055 * at memslots[0] has the highest GFN.
1056 *
1057 * The sorting algorithm takes advantage of having initially sorted memslots
1058 * and knowing the position of the changed memslot. Sorting is also optimized
1059 * by not swapping the updated memslot and instead only shifting other memslots
1060 * and tracking the new index for the update memslot. Only once its final
1061 * index is known is the updated memslot copied into its position in the array.
1062 *
1063 * - When deleting a memslot, the deleted memslot simply needs to be moved to
1064 * the end of the array.
1065 *
1066 * - When creating a memslot, the algorithm "inserts" the new memslot at the
1067 * end of the array and then it forward to its correct location.
1068 *
1069 * - When moving a memslot, the algorithm first moves the updated memslot
1070 * backward to handle the scenario where the memslot's GFN was changed to a
1071 * lower value. update_memslots() then falls through and runs the same flow
1072 * as creating a memslot to move the memslot forward to handle the scenario
1073 * where its GFN was changed to a higher value.
1074 *
1075 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1076 * historical reasons. Originally, invalid memslots where denoted by having
1077 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1078 * to the end of the array. The current algorithm uses dedicated logic to
1079 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1080 *
1081 * The other historical motiviation for highest->lowest was to improve the
1082 * performance of memslot lookup. KVM originally used a linear search starting
1083 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1084 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1085 * single memslot above the 4gb boundary. As the largest memslot is also the
1086 * most likely to be referenced, sorting it to the front of the array was
1087 * advantageous. The current binary search starts from the middle of the array
1088 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1089 */
1090static void update_memslots(struct kvm_memslots *slots,
1091 struct kvm_memory_slot *memslot,
1092 enum kvm_mr_change change)
1093{
1094 int i;
1095
1096 if (change == KVM_MR_DELETE) {
1097 kvm_memslot_delete(slots, memslot);
1098 } else {
1099 if (change == KVM_MR_CREATE)
1100 i = kvm_memslot_insert_back(slots);
1101 else
1102 i = kvm_memslot_move_backward(slots, memslot);
1103 i = kvm_memslot_move_forward(slots, memslot, i);
1104
1105 /*
1106 * Copy the memslot to its new position in memslots and update
1107 * its index accordingly.
1108 */
1109 slots->memslots[i] = *memslot;
1110 slots->id_to_index[memslot->id] = i;
1111 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001112}
1113
1114static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1115{
1116 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1117
1118#ifdef __KVM_HAVE_READONLY_MEM
1119 valid_flags |= KVM_MEM_READONLY;
1120#endif
1121
1122 if (mem->flags & ~valid_flags)
1123 return -EINVAL;
1124
1125 return 0;
1126}
1127
1128static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
1129 int as_id, struct kvm_memslots *slots)
1130{
1131 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
David Brazdil0f672f62019-12-10 10:32:29 +00001132 u64 gen = old_memslots->generation;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001133
David Brazdil0f672f62019-12-10 10:32:29 +00001134 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1135 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001136
1137 rcu_assign_pointer(kvm->memslots[as_id], slots);
1138 synchronize_srcu_expedited(&kvm->srcu);
1139
1140 /*
David Brazdil0f672f62019-12-10 10:32:29 +00001141 * Increment the new memslot generation a second time, dropping the
Olivier Deprez157378f2022-04-04 15:47:50 +02001142 * update in-progress flag and incrementing the generation based on
David Brazdil0f672f62019-12-10 10:32:29 +00001143 * the number of address spaces. This provides a unique and easily
1144 * identifiable generation number while the memslots are in flux.
1145 */
1146 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1147
1148 /*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001149 * Generations must be unique even across address spaces. We do not need
1150 * a global counter for that, instead the generation space is evenly split
1151 * across address spaces. For example, with two address spaces, address
David Brazdil0f672f62019-12-10 10:32:29 +00001152 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1153 * use generations 1, 3, 5, ...
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001154 */
David Brazdil0f672f62019-12-10 10:32:29 +00001155 gen += KVM_ADDRESS_SPACE_NUM;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001156
David Brazdil0f672f62019-12-10 10:32:29 +00001157 kvm_arch_memslots_updated(kvm, gen);
1158
1159 slots->generation = gen;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001160
1161 return old_memslots;
1162}
1163
1164/*
Olivier Deprez157378f2022-04-04 15:47:50 +02001165 * Note, at a minimum, the current number of used slots must be allocated, even
1166 * when deleting a memslot, as we need a complete duplicate of the memslots for
1167 * use when invalidating a memslot prior to deleting/moving the memslot.
1168 */
1169static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1170 enum kvm_mr_change change)
1171{
1172 struct kvm_memslots *slots;
1173 size_t old_size, new_size;
1174
1175 old_size = sizeof(struct kvm_memslots) +
1176 (sizeof(struct kvm_memory_slot) * old->used_slots);
1177
1178 if (change == KVM_MR_CREATE)
1179 new_size = old_size + sizeof(struct kvm_memory_slot);
1180 else
1181 new_size = old_size;
1182
1183 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1184 if (likely(slots))
1185 memcpy(slots, old, old_size);
1186
1187 return slots;
1188}
1189
1190static int kvm_set_memslot(struct kvm *kvm,
1191 const struct kvm_userspace_memory_region *mem,
1192 struct kvm_memory_slot *old,
1193 struct kvm_memory_slot *new, int as_id,
1194 enum kvm_mr_change change)
1195{
1196 struct kvm_memory_slot *slot;
1197 struct kvm_memslots *slots;
1198 int r;
1199
1200 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
1201 if (!slots)
1202 return -ENOMEM;
1203
1204 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1205 /*
1206 * Note, the INVALID flag needs to be in the appropriate entry
1207 * in the freshly allocated memslots, not in @old or @new.
1208 */
1209 slot = id_to_memslot(slots, old->id);
1210 slot->flags |= KVM_MEMSLOT_INVALID;
1211
1212 /*
1213 * We can re-use the old memslots, the only difference from the
1214 * newly installed memslots is the invalid flag, which will get
1215 * dropped by update_memslots anyway. We'll also revert to the
1216 * old memslots if preparing the new memory region fails.
1217 */
1218 slots = install_new_memslots(kvm, as_id, slots);
1219
1220 /* From this point no new shadow pages pointing to a deleted,
1221 * or moved, memslot will be created.
1222 *
1223 * validation of sp->gfn happens in:
1224 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1225 * - kvm_is_visible_gfn (mmu_check_root)
1226 */
1227 kvm_arch_flush_shadow_memslot(kvm, slot);
1228 }
1229
1230 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1231 if (r)
1232 goto out_slots;
1233
1234 update_memslots(slots, new, change);
1235 slots = install_new_memslots(kvm, as_id, slots);
1236
1237 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1238
1239 kvfree(slots);
1240 return 0;
1241
1242out_slots:
1243 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1244 slots = install_new_memslots(kvm, as_id, slots);
1245 kvfree(slots);
1246 return r;
1247}
1248
1249static int kvm_delete_memslot(struct kvm *kvm,
1250 const struct kvm_userspace_memory_region *mem,
1251 struct kvm_memory_slot *old, int as_id)
1252{
1253 struct kvm_memory_slot new;
1254 int r;
1255
1256 if (!old->npages)
1257 return -EINVAL;
1258
1259 memset(&new, 0, sizeof(new));
1260 new.id = old->id;
1261 /*
1262 * This is only for debugging purpose; it should never be referenced
1263 * for a removed memslot.
1264 */
1265 new.as_id = as_id;
1266
1267 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1268 if (r)
1269 return r;
1270
1271 kvm_free_memslot(kvm, old);
1272 return 0;
1273}
1274
1275/*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001276 * Allocate some memory and give it an address in the guest physical address
1277 * space.
1278 *
1279 * Discontiguous memory is allowed, mostly for framebuffers.
1280 *
1281 * Must be called holding kvm->slots_lock for write.
1282 */
1283int __kvm_set_memory_region(struct kvm *kvm,
1284 const struct kvm_userspace_memory_region *mem)
1285{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001286 struct kvm_memory_slot old, new;
Olivier Deprez157378f2022-04-04 15:47:50 +02001287 struct kvm_memory_slot *tmp;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001288 enum kvm_mr_change change;
Olivier Deprez157378f2022-04-04 15:47:50 +02001289 int as_id, id;
1290 int r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001291
1292 r = check_memory_region_flags(mem);
1293 if (r)
Olivier Deprez157378f2022-04-04 15:47:50 +02001294 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001295
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001296 as_id = mem->slot >> 16;
1297 id = (u16)mem->slot;
1298
1299 /* General sanity checks */
Olivier Deprez157378f2022-04-04 15:47:50 +02001300 if ((mem->memory_size & (PAGE_SIZE - 1)) ||
1301 (mem->memory_size != (unsigned long)mem->memory_size))
1302 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001303 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
Olivier Deprez157378f2022-04-04 15:47:50 +02001304 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001305 /* We can read the guest memory with __xxx_user() later on. */
Olivier Deprez157378f2022-04-04 15:47:50 +02001306 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1307 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
David Brazdil0f672f62019-12-10 10:32:29 +00001308 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
Olivier Deprez157378f2022-04-04 15:47:50 +02001309 mem->memory_size))
1310 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001311 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
Olivier Deprez157378f2022-04-04 15:47:50 +02001312 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001313 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
Olivier Deprez157378f2022-04-04 15:47:50 +02001314 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001315
Olivier Deprez157378f2022-04-04 15:47:50 +02001316 /*
1317 * Make a full copy of the old memslot, the pointer will become stale
1318 * when the memslots are re-sorted by update_memslots(), and the old
1319 * memslot needs to be referenced after calling update_memslots(), e.g.
1320 * to free its resources and for arch specific behavior.
1321 */
1322 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1323 if (tmp) {
1324 old = *tmp;
1325 tmp = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001326 } else {
Olivier Deprez157378f2022-04-04 15:47:50 +02001327 memset(&old, 0, sizeof(old));
1328 old.id = id;
1329 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001330
Olivier Deprez157378f2022-04-04 15:47:50 +02001331 if (!mem->memory_size)
1332 return kvm_delete_memslot(kvm, mem, &old, as_id);
1333
1334 new.as_id = as_id;
1335 new.id = id;
1336 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1337 new.npages = mem->memory_size >> PAGE_SHIFT;
1338 new.flags = mem->flags;
1339 new.userspace_addr = mem->userspace_addr;
1340
1341 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1342 return -EINVAL;
1343
1344 if (!old.npages) {
1345 change = KVM_MR_CREATE;
1346 new.dirty_bitmap = NULL;
1347 memset(&new.arch, 0, sizeof(new.arch));
1348 } else { /* Modify an existing slot. */
1349 if ((new.userspace_addr != old.userspace_addr) ||
1350 (new.npages != old.npages) ||
1351 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1352 return -EINVAL;
1353
1354 if (new.base_gfn != old.base_gfn)
1355 change = KVM_MR_MOVE;
1356 else if (new.flags != old.flags)
1357 change = KVM_MR_FLAGS_ONLY;
1358 else /* Nothing to change. */
1359 return 0;
1360
1361 /* Copy dirty_bitmap and arch from the current memslot. */
1362 new.dirty_bitmap = old.dirty_bitmap;
1363 memcpy(&new.arch, &old.arch, sizeof(new.arch));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001364 }
1365
1366 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1367 /* Check for overlaps */
Olivier Deprez157378f2022-04-04 15:47:50 +02001368 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1369 if (tmp->id == id)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001370 continue;
Olivier Deprez157378f2022-04-04 15:47:50 +02001371 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1372 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
1373 return -EEXIST;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001374 }
1375 }
1376
Olivier Deprez157378f2022-04-04 15:47:50 +02001377 /* Allocate/free page dirty bitmap as needed */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001378 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1379 new.dirty_bitmap = NULL;
Olivier Deprez157378f2022-04-04 15:47:50 +02001380 else if (!new.dirty_bitmap) {
1381 r = kvm_alloc_dirty_bitmap(&new);
1382 if (r)
1383 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001384
Olivier Deprez157378f2022-04-04 15:47:50 +02001385 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1386 bitmap_set(new.dirty_bitmap, 0, new.npages);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001387 }
1388
Olivier Deprez157378f2022-04-04 15:47:50 +02001389 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001390 if (r)
Olivier Deprez157378f2022-04-04 15:47:50 +02001391 goto out_bitmap;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001392
Olivier Deprez157378f2022-04-04 15:47:50 +02001393 if (old.dirty_bitmap && !new.dirty_bitmap)
1394 kvm_destroy_dirty_bitmap(&old);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001395 return 0;
1396
Olivier Deprez157378f2022-04-04 15:47:50 +02001397out_bitmap:
1398 if (new.dirty_bitmap && !old.dirty_bitmap)
1399 kvm_destroy_dirty_bitmap(&new);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001400 return r;
1401}
1402EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1403
1404int kvm_set_memory_region(struct kvm *kvm,
1405 const struct kvm_userspace_memory_region *mem)
1406{
1407 int r;
1408
1409 mutex_lock(&kvm->slots_lock);
1410 r = __kvm_set_memory_region(kvm, mem);
1411 mutex_unlock(&kvm->slots_lock);
1412 return r;
1413}
1414EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1415
1416static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1417 struct kvm_userspace_memory_region *mem)
1418{
1419 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1420 return -EINVAL;
1421
1422 return kvm_set_memory_region(kvm, mem);
1423}
1424
Olivier Deprez157378f2022-04-04 15:47:50 +02001425#ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1426/**
1427 * kvm_get_dirty_log - get a snapshot of dirty pages
1428 * @kvm: pointer to kvm instance
1429 * @log: slot id and address to which we copy the log
1430 * @is_dirty: set to '1' if any dirty pages were found
1431 * @memslot: set to the associated memslot, always valid on success
1432 */
1433int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1434 int *is_dirty, struct kvm_memory_slot **memslot)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001435{
1436 struct kvm_memslots *slots;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001437 int i, as_id, id;
1438 unsigned long n;
1439 unsigned long any = 0;
1440
Olivier Deprez157378f2022-04-04 15:47:50 +02001441 *memslot = NULL;
1442 *is_dirty = 0;
1443
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001444 as_id = log->slot >> 16;
1445 id = (u16)log->slot;
1446 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1447 return -EINVAL;
1448
1449 slots = __kvm_memslots(kvm, as_id);
Olivier Deprez157378f2022-04-04 15:47:50 +02001450 *memslot = id_to_memslot(slots, id);
1451 if (!(*memslot) || !(*memslot)->dirty_bitmap)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001452 return -ENOENT;
1453
Olivier Deprez157378f2022-04-04 15:47:50 +02001454 kvm_arch_sync_dirty_log(kvm, *memslot);
1455
1456 n = kvm_dirty_bitmap_bytes(*memslot);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001457
1458 for (i = 0; !any && i < n/sizeof(long); ++i)
Olivier Deprez157378f2022-04-04 15:47:50 +02001459 any = (*memslot)->dirty_bitmap[i];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001460
Olivier Deprez157378f2022-04-04 15:47:50 +02001461 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001462 return -EFAULT;
1463
1464 if (any)
1465 *is_dirty = 1;
1466 return 0;
1467}
1468EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1469
Olivier Deprez157378f2022-04-04 15:47:50 +02001470#else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001471/**
David Brazdil0f672f62019-12-10 10:32:29 +00001472 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1473 * and reenable dirty page tracking for the corresponding pages.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001474 * @kvm: pointer to kvm instance
1475 * @log: slot id and address to which we copy the log
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001476 *
1477 * We need to keep it in mind that VCPU threads can write to the bitmap
1478 * concurrently. So, to avoid losing track of dirty pages we keep the
1479 * following order:
1480 *
1481 * 1. Take a snapshot of the bit and clear it if needed.
1482 * 2. Write protect the corresponding page.
1483 * 3. Copy the snapshot to the userspace.
1484 * 4. Upon return caller flushes TLB's if needed.
1485 *
1486 * Between 2 and 4, the guest may write to the page using the remaining TLB
1487 * entry. This is not a problem because the page is reported dirty using
1488 * the snapshot taken before and step 4 ensures that writes done after
1489 * exiting to userspace will be logged for the next call.
1490 *
1491 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001492static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001493{
1494 struct kvm_memslots *slots;
1495 struct kvm_memory_slot *memslot;
1496 int i, as_id, id;
1497 unsigned long n;
1498 unsigned long *dirty_bitmap;
1499 unsigned long *dirty_bitmap_buffer;
Olivier Deprez157378f2022-04-04 15:47:50 +02001500 bool flush;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001501
1502 as_id = log->slot >> 16;
1503 id = (u16)log->slot;
1504 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1505 return -EINVAL;
1506
1507 slots = __kvm_memslots(kvm, as_id);
1508 memslot = id_to_memslot(slots, id);
Olivier Deprez157378f2022-04-04 15:47:50 +02001509 if (!memslot || !memslot->dirty_bitmap)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001510 return -ENOENT;
1511
Olivier Deprez157378f2022-04-04 15:47:50 +02001512 dirty_bitmap = memslot->dirty_bitmap;
1513
1514 kvm_arch_sync_dirty_log(kvm, memslot);
1515
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001516 n = kvm_dirty_bitmap_bytes(memslot);
Olivier Deprez157378f2022-04-04 15:47:50 +02001517 flush = false;
David Brazdil0f672f62019-12-10 10:32:29 +00001518 if (kvm->manual_dirty_log_protect) {
1519 /*
1520 * Unlike kvm_get_dirty_log, we always return false in *flush,
1521 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1522 * is some code duplication between this function and
1523 * kvm_get_dirty_log, but hopefully all architecture
1524 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1525 * can be eliminated.
1526 */
1527 dirty_bitmap_buffer = dirty_bitmap;
1528 } else {
1529 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1530 memset(dirty_bitmap_buffer, 0, n);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001531
David Brazdil0f672f62019-12-10 10:32:29 +00001532 spin_lock(&kvm->mmu_lock);
1533 for (i = 0; i < n / sizeof(long); i++) {
1534 unsigned long mask;
1535 gfn_t offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001536
David Brazdil0f672f62019-12-10 10:32:29 +00001537 if (!dirty_bitmap[i])
1538 continue;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001539
Olivier Deprez157378f2022-04-04 15:47:50 +02001540 flush = true;
David Brazdil0f672f62019-12-10 10:32:29 +00001541 mask = xchg(&dirty_bitmap[i], 0);
1542 dirty_bitmap_buffer[i] = mask;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001543
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001544 offset = i * BITS_PER_LONG;
1545 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1546 offset, mask);
1547 }
David Brazdil0f672f62019-12-10 10:32:29 +00001548 spin_unlock(&kvm->mmu_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001549 }
1550
Olivier Deprez157378f2022-04-04 15:47:50 +02001551 if (flush)
1552 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1553
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001554 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1555 return -EFAULT;
1556 return 0;
1557}
Olivier Deprez157378f2022-04-04 15:47:50 +02001558
1559
1560/**
1561 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1562 * @kvm: kvm instance
1563 * @log: slot id and address to which we copy the log
1564 *
1565 * Steps 1-4 below provide general overview of dirty page logging. See
1566 * kvm_get_dirty_log_protect() function description for additional details.
1567 *
1568 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1569 * always flush the TLB (step 4) even if previous step failed and the dirty
1570 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1571 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1572 * writes will be marked dirty for next log read.
1573 *
1574 * 1. Take a snapshot of the bit and clear it if needed.
1575 * 2. Write protect the corresponding page.
1576 * 3. Copy the snapshot to the userspace.
1577 * 4. Flush TLB's if needed.
1578 */
1579static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1580 struct kvm_dirty_log *log)
1581{
1582 int r;
1583
1584 mutex_lock(&kvm->slots_lock);
1585
1586 r = kvm_get_dirty_log_protect(kvm, log);
1587
1588 mutex_unlock(&kvm->slots_lock);
1589 return r;
1590}
David Brazdil0f672f62019-12-10 10:32:29 +00001591
1592/**
1593 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1594 * and reenable dirty page tracking for the corresponding pages.
1595 * @kvm: pointer to kvm instance
1596 * @log: slot id and address from which to fetch the bitmap of dirty pages
David Brazdil0f672f62019-12-10 10:32:29 +00001597 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001598static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1599 struct kvm_clear_dirty_log *log)
David Brazdil0f672f62019-12-10 10:32:29 +00001600{
1601 struct kvm_memslots *slots;
1602 struct kvm_memory_slot *memslot;
1603 int as_id, id;
1604 gfn_t offset;
1605 unsigned long i, n;
1606 unsigned long *dirty_bitmap;
1607 unsigned long *dirty_bitmap_buffer;
Olivier Deprez157378f2022-04-04 15:47:50 +02001608 bool flush;
David Brazdil0f672f62019-12-10 10:32:29 +00001609
1610 as_id = log->slot >> 16;
1611 id = (u16)log->slot;
1612 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1613 return -EINVAL;
1614
1615 if (log->first_page & 63)
1616 return -EINVAL;
1617
1618 slots = __kvm_memslots(kvm, as_id);
1619 memslot = id_to_memslot(slots, id);
Olivier Deprez157378f2022-04-04 15:47:50 +02001620 if (!memslot || !memslot->dirty_bitmap)
1621 return -ENOENT;
David Brazdil0f672f62019-12-10 10:32:29 +00001622
1623 dirty_bitmap = memslot->dirty_bitmap;
David Brazdil0f672f62019-12-10 10:32:29 +00001624
1625 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
1626
1627 if (log->first_page > memslot->npages ||
1628 log->num_pages > memslot->npages - log->first_page ||
1629 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1630 return -EINVAL;
1631
Olivier Deprez157378f2022-04-04 15:47:50 +02001632 kvm_arch_sync_dirty_log(kvm, memslot);
1633
1634 flush = false;
David Brazdil0f672f62019-12-10 10:32:29 +00001635 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1636 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1637 return -EFAULT;
1638
1639 spin_lock(&kvm->mmu_lock);
1640 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1641 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
1642 i++, offset += BITS_PER_LONG) {
1643 unsigned long mask = *dirty_bitmap_buffer++;
1644 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1645 if (!mask)
1646 continue;
1647
1648 mask &= atomic_long_fetch_andnot(mask, p);
1649
1650 /*
1651 * mask contains the bits that really have been cleared. This
1652 * never includes any bits beyond the length of the memslot (if
1653 * the length is not aligned to 64 pages), therefore it is not
1654 * a problem if userspace sets them in log->dirty_bitmap.
1655 */
1656 if (mask) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001657 flush = true;
David Brazdil0f672f62019-12-10 10:32:29 +00001658 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1659 offset, mask);
1660 }
1661 }
1662 spin_unlock(&kvm->mmu_lock);
1663
Olivier Deprez157378f2022-04-04 15:47:50 +02001664 if (flush)
1665 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1666
David Brazdil0f672f62019-12-10 10:32:29 +00001667 return 0;
1668}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001669
Olivier Deprez157378f2022-04-04 15:47:50 +02001670static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
1671 struct kvm_clear_dirty_log *log)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001672{
Olivier Deprez157378f2022-04-04 15:47:50 +02001673 int r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001674
Olivier Deprez157378f2022-04-04 15:47:50 +02001675 mutex_lock(&kvm->slots_lock);
1676
1677 r = kvm_clear_dirty_log_protect(kvm, log);
1678
1679 mutex_unlock(&kvm->slots_lock);
1680 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001681}
Olivier Deprez157378f2022-04-04 15:47:50 +02001682#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001683
1684struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1685{
1686 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1687}
1688EXPORT_SYMBOL_GPL(gfn_to_memslot);
1689
1690struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1691{
1692 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1693}
1694
1695bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1696{
1697 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1698
Olivier Deprez157378f2022-04-04 15:47:50 +02001699 return kvm_is_visible_memslot(memslot);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001700}
1701EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1702
Olivier Deprez157378f2022-04-04 15:47:50 +02001703bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1704{
1705 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1706
1707 return kvm_is_visible_memslot(memslot);
1708}
1709EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
1710
Olivier Deprez0e641232021-09-23 10:07:05 +02001711unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001712{
1713 struct vm_area_struct *vma;
1714 unsigned long addr, size;
1715
1716 size = PAGE_SIZE;
1717
Olivier Deprez0e641232021-09-23 10:07:05 +02001718 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001719 if (kvm_is_error_hva(addr))
1720 return PAGE_SIZE;
1721
Olivier Deprez157378f2022-04-04 15:47:50 +02001722 mmap_read_lock(current->mm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001723 vma = find_vma(current->mm, addr);
1724 if (!vma)
1725 goto out;
1726
1727 size = vma_kernel_pagesize(vma);
1728
1729out:
Olivier Deprez157378f2022-04-04 15:47:50 +02001730 mmap_read_unlock(current->mm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001731
1732 return size;
1733}
1734
1735static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1736{
1737 return slot->flags & KVM_MEM_READONLY;
1738}
1739
1740static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1741 gfn_t *nr_pages, bool write)
1742{
1743 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1744 return KVM_HVA_ERR_BAD;
1745
1746 if (memslot_is_readonly(slot) && write)
1747 return KVM_HVA_ERR_RO_BAD;
1748
1749 if (nr_pages)
1750 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1751
1752 return __gfn_to_hva_memslot(slot, gfn);
1753}
1754
1755static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1756 gfn_t *nr_pages)
1757{
1758 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1759}
1760
1761unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1762 gfn_t gfn)
1763{
1764 return gfn_to_hva_many(slot, gfn, NULL);
1765}
1766EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1767
1768unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1769{
1770 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1771}
1772EXPORT_SYMBOL_GPL(gfn_to_hva);
1773
1774unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1775{
1776 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1777}
1778EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1779
1780/*
David Brazdil0f672f62019-12-10 10:32:29 +00001781 * Return the hva of a @gfn and the R/W attribute if possible.
1782 *
1783 * @slot: the kvm_memory_slot which contains @gfn
1784 * @gfn: the gfn to be translated
1785 * @writable: used to return the read/write attribute of the @slot if the hva
1786 * is valid and @writable is not NULL
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001787 */
1788unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1789 gfn_t gfn, bool *writable)
1790{
1791 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1792
1793 if (!kvm_is_error_hva(hva) && writable)
1794 *writable = !memslot_is_readonly(slot);
1795
1796 return hva;
1797}
1798
1799unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1800{
1801 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1802
1803 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1804}
1805
1806unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1807{
1808 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1809
1810 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1811}
1812
1813static inline int check_user_page_hwpoison(unsigned long addr)
1814{
1815 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1816
1817 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1818 return rc == -EHWPOISON;
1819}
1820
1821/*
1822 * The fast path to get the writable pfn which will be stored in @pfn,
1823 * true indicates success, otherwise false is returned. It's also the
Olivier Deprez157378f2022-04-04 15:47:50 +02001824 * only part that runs if we can in atomic context.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001825 */
1826static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1827 bool *writable, kvm_pfn_t *pfn)
1828{
1829 struct page *page[1];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001830
1831 /*
1832 * Fast pin a writable pfn only if it is a write fault request
1833 * or the caller allows to map a writable pfn for a read fault
1834 * request.
1835 */
1836 if (!(write_fault || writable))
1837 return false;
1838
Olivier Deprez157378f2022-04-04 15:47:50 +02001839 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001840 *pfn = page_to_pfn(page[0]);
1841
1842 if (writable)
1843 *writable = true;
1844 return true;
1845 }
1846
1847 return false;
1848}
1849
1850/*
1851 * The slow path to get the pfn of the specified host virtual address,
1852 * 1 indicates success, -errno is returned if error is detected.
1853 */
1854static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1855 bool *writable, kvm_pfn_t *pfn)
1856{
1857 unsigned int flags = FOLL_HWPOISON;
1858 struct page *page;
1859 int npages = 0;
1860
1861 might_sleep();
1862
1863 if (writable)
1864 *writable = write_fault;
1865
1866 if (write_fault)
1867 flags |= FOLL_WRITE;
1868 if (async)
1869 flags |= FOLL_NOWAIT;
1870
1871 npages = get_user_pages_unlocked(addr, 1, &page, flags);
1872 if (npages != 1)
1873 return npages;
1874
1875 /* map read fault as writable if possible */
1876 if (unlikely(!write_fault) && writable) {
1877 struct page *wpage;
1878
Olivier Deprez157378f2022-04-04 15:47:50 +02001879 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001880 *writable = true;
1881 put_page(page);
1882 page = wpage;
1883 }
1884 }
1885 *pfn = page_to_pfn(page);
1886 return npages;
1887}
1888
1889static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1890{
1891 if (unlikely(!(vma->vm_flags & VM_READ)))
1892 return false;
1893
1894 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1895 return false;
1896
1897 return true;
1898}
1899
Olivier Deprez0e641232021-09-23 10:07:05 +02001900static int kvm_try_get_pfn(kvm_pfn_t pfn)
1901{
1902 if (kvm_is_reserved_pfn(pfn))
1903 return 1;
1904 return get_page_unless_zero(pfn_to_page(pfn));
1905}
1906
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001907static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1908 unsigned long addr, bool *async,
1909 bool write_fault, bool *writable,
1910 kvm_pfn_t *p_pfn)
1911{
Olivier Deprez0e641232021-09-23 10:07:05 +02001912 kvm_pfn_t pfn;
1913 pte_t *ptep;
1914 spinlock_t *ptl;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001915 int r;
1916
Olivier Deprez0e641232021-09-23 10:07:05 +02001917 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001918 if (r) {
1919 /*
1920 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1921 * not call the fault handler, so do it here.
1922 */
1923 bool unlocked = false;
Olivier Deprez157378f2022-04-04 15:47:50 +02001924 r = fixup_user_fault(current->mm, addr,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001925 (write_fault ? FAULT_FLAG_WRITE : 0),
1926 &unlocked);
1927 if (unlocked)
1928 return -EAGAIN;
1929 if (r)
1930 return r;
1931
Olivier Deprez0e641232021-09-23 10:07:05 +02001932 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001933 if (r)
1934 return r;
Olivier Deprez0e641232021-09-23 10:07:05 +02001935 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001936
Olivier Deprez0e641232021-09-23 10:07:05 +02001937 if (write_fault && !pte_write(*ptep)) {
1938 pfn = KVM_PFN_ERR_RO_FAULT;
1939 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001940 }
1941
1942 if (writable)
Olivier Deprez0e641232021-09-23 10:07:05 +02001943 *writable = pte_write(*ptep);
1944 pfn = pte_pfn(*ptep);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001945
1946 /*
1947 * Get a reference here because callers of *hva_to_pfn* and
1948 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1949 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1950 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1951 * simply do nothing for reserved pfns.
1952 *
1953 * Whoever called remap_pfn_range is also going to call e.g.
1954 * unmap_mapping_range before the underlying pages are freed,
1955 * causing a call to our MMU notifier.
Olivier Deprez0e641232021-09-23 10:07:05 +02001956 *
1957 * Certain IO or PFNMAP mappings can be backed with valid
1958 * struct pages, but be allocated without refcounting e.g.,
1959 * tail pages of non-compound higher order allocations, which
1960 * would then underflow the refcount when the caller does the
1961 * required put_page. Don't allow those pages here.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001962 */
Olivier Deprez0e641232021-09-23 10:07:05 +02001963 if (!kvm_try_get_pfn(pfn))
1964 r = -EFAULT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001965
Olivier Deprez0e641232021-09-23 10:07:05 +02001966out:
1967 pte_unmap_unlock(ptep, ptl);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001968 *p_pfn = pfn;
Olivier Deprez0e641232021-09-23 10:07:05 +02001969
1970 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001971}
1972
1973/*
1974 * Pin guest page in memory and return its pfn.
1975 * @addr: host virtual address which maps memory to the guest
1976 * @atomic: whether this function can sleep
1977 * @async: whether this function need to wait IO complete if the
1978 * host page is not in the memory
1979 * @write_fault: whether we should get a writable host page
1980 * @writable: whether it allows to map a writable host page for !@write_fault
1981 *
1982 * The function will map a writable host page for these two cases:
1983 * 1): @write_fault = true
1984 * 2): @write_fault = false && @writable, @writable will tell the caller
1985 * whether the mapping is writable.
1986 */
1987static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1988 bool write_fault, bool *writable)
1989{
1990 struct vm_area_struct *vma;
1991 kvm_pfn_t pfn = 0;
1992 int npages, r;
1993
1994 /* we can do it either atomically or asynchronously, not both */
1995 BUG_ON(atomic && async);
1996
1997 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
1998 return pfn;
1999
2000 if (atomic)
2001 return KVM_PFN_ERR_FAULT;
2002
2003 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2004 if (npages == 1)
2005 return pfn;
2006
Olivier Deprez157378f2022-04-04 15:47:50 +02002007 mmap_read_lock(current->mm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002008 if (npages == -EHWPOISON ||
2009 (!async && check_user_page_hwpoison(addr))) {
2010 pfn = KVM_PFN_ERR_HWPOISON;
2011 goto exit;
2012 }
2013
2014retry:
2015 vma = find_vma_intersection(current->mm, addr, addr + 1);
2016
2017 if (vma == NULL)
2018 pfn = KVM_PFN_ERR_FAULT;
2019 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2020 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
2021 if (r == -EAGAIN)
2022 goto retry;
2023 if (r < 0)
2024 pfn = KVM_PFN_ERR_FAULT;
2025 } else {
2026 if (async && vma_is_valid(vma, write_fault))
2027 *async = true;
2028 pfn = KVM_PFN_ERR_FAULT;
2029 }
2030exit:
Olivier Deprez157378f2022-04-04 15:47:50 +02002031 mmap_read_unlock(current->mm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002032 return pfn;
2033}
2034
2035kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
2036 bool atomic, bool *async, bool write_fault,
2037 bool *writable)
2038{
2039 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2040
2041 if (addr == KVM_HVA_ERR_RO_BAD) {
2042 if (writable)
2043 *writable = false;
2044 return KVM_PFN_ERR_RO_FAULT;
2045 }
2046
2047 if (kvm_is_error_hva(addr)) {
2048 if (writable)
2049 *writable = false;
2050 return KVM_PFN_NOSLOT;
2051 }
2052
2053 /* Do not map writable pfn in the readonly memslot. */
2054 if (writable && memslot_is_readonly(slot)) {
2055 *writable = false;
2056 writable = NULL;
2057 }
2058
2059 return hva_to_pfn(addr, atomic, async, write_fault,
2060 writable);
2061}
2062EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2063
2064kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2065 bool *writable)
2066{
2067 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2068 write_fault, writable);
2069}
2070EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2071
2072kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
2073{
2074 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
2075}
2076EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2077
2078kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
2079{
2080 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
2081}
2082EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2083
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002084kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2085{
2086 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2087}
2088EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2089
2090kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2091{
2092 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2093}
2094EXPORT_SYMBOL_GPL(gfn_to_pfn);
2095
2096kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2097{
2098 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2099}
2100EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2101
2102int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2103 struct page **pages, int nr_pages)
2104{
2105 unsigned long addr;
2106 gfn_t entry = 0;
2107
2108 addr = gfn_to_hva_many(slot, gfn, &entry);
2109 if (kvm_is_error_hva(addr))
2110 return -1;
2111
2112 if (entry < nr_pages)
2113 return 0;
2114
Olivier Deprez157378f2022-04-04 15:47:50 +02002115 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002116}
2117EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2118
2119static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2120{
2121 if (is_error_noslot_pfn(pfn))
2122 return KVM_ERR_PTR_BAD_PAGE;
2123
2124 if (kvm_is_reserved_pfn(pfn)) {
2125 WARN_ON(1);
2126 return KVM_ERR_PTR_BAD_PAGE;
2127 }
2128
2129 return pfn_to_page(pfn);
2130}
2131
2132struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2133{
2134 kvm_pfn_t pfn;
2135
2136 pfn = gfn_to_pfn(kvm, gfn);
2137
2138 return kvm_pfn_to_page(pfn);
2139}
2140EXPORT_SYMBOL_GPL(gfn_to_page);
2141
Olivier Deprez0e641232021-09-23 10:07:05 +02002142void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2143{
2144 if (pfn == 0)
2145 return;
2146
2147 if (cache)
2148 cache->pfn = cache->gfn = 0;
2149
2150 if (dirty)
2151 kvm_release_pfn_dirty(pfn);
2152 else
2153 kvm_release_pfn_clean(pfn);
2154}
2155
2156static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2157 struct gfn_to_pfn_cache *cache, u64 gen)
2158{
2159 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2160
2161 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2162 cache->gfn = gfn;
2163 cache->dirty = false;
2164 cache->generation = gen;
2165}
2166
2167static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
2168 struct kvm_host_map *map,
2169 struct gfn_to_pfn_cache *cache,
2170 bool atomic)
David Brazdil0f672f62019-12-10 10:32:29 +00002171{
2172 kvm_pfn_t pfn;
2173 void *hva = NULL;
2174 struct page *page = KVM_UNMAPPED_PAGE;
Olivier Deprez0e641232021-09-23 10:07:05 +02002175 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
2176 u64 gen = slots->generation;
David Brazdil0f672f62019-12-10 10:32:29 +00002177
2178 if (!map)
2179 return -EINVAL;
2180
Olivier Deprez0e641232021-09-23 10:07:05 +02002181 if (cache) {
2182 if (!cache->pfn || cache->gfn != gfn ||
2183 cache->generation != gen) {
2184 if (atomic)
2185 return -EAGAIN;
2186 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2187 }
2188 pfn = cache->pfn;
2189 } else {
2190 if (atomic)
2191 return -EAGAIN;
2192 pfn = gfn_to_pfn_memslot(slot, gfn);
2193 }
David Brazdil0f672f62019-12-10 10:32:29 +00002194 if (is_error_noslot_pfn(pfn))
2195 return -EINVAL;
2196
2197 if (pfn_valid(pfn)) {
2198 page = pfn_to_page(pfn);
Olivier Deprez0e641232021-09-23 10:07:05 +02002199 if (atomic)
2200 hva = kmap_atomic(page);
2201 else
2202 hva = kmap(page);
David Brazdil0f672f62019-12-10 10:32:29 +00002203#ifdef CONFIG_HAS_IOMEM
Olivier Deprez0e641232021-09-23 10:07:05 +02002204 } else if (!atomic) {
David Brazdil0f672f62019-12-10 10:32:29 +00002205 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
Olivier Deprez0e641232021-09-23 10:07:05 +02002206 } else {
2207 return -EINVAL;
David Brazdil0f672f62019-12-10 10:32:29 +00002208#endif
2209 }
2210
2211 if (!hva)
2212 return -EFAULT;
2213
2214 map->page = page;
2215 map->hva = hva;
2216 map->pfn = pfn;
2217 map->gfn = gfn;
2218
2219 return 0;
2220}
2221
Olivier Deprez0e641232021-09-23 10:07:05 +02002222int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2223 struct gfn_to_pfn_cache *cache, bool atomic)
2224{
2225 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2226 cache, atomic);
2227}
2228EXPORT_SYMBOL_GPL(kvm_map_gfn);
2229
David Brazdil0f672f62019-12-10 10:32:29 +00002230int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2231{
Olivier Deprez0e641232021-09-23 10:07:05 +02002232 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2233 NULL, false);
David Brazdil0f672f62019-12-10 10:32:29 +00002234}
2235EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2236
Olivier Deprez0e641232021-09-23 10:07:05 +02002237static void __kvm_unmap_gfn(struct kvm_memory_slot *memslot,
2238 struct kvm_host_map *map,
2239 struct gfn_to_pfn_cache *cache,
2240 bool dirty, bool atomic)
David Brazdil0f672f62019-12-10 10:32:29 +00002241{
2242 if (!map)
2243 return;
2244
2245 if (!map->hva)
2246 return;
2247
Olivier Deprez0e641232021-09-23 10:07:05 +02002248 if (map->page != KVM_UNMAPPED_PAGE) {
2249 if (atomic)
2250 kunmap_atomic(map->hva);
2251 else
2252 kunmap(map->page);
2253 }
David Brazdil0f672f62019-12-10 10:32:29 +00002254#ifdef CONFIG_HAS_IOMEM
Olivier Deprez0e641232021-09-23 10:07:05 +02002255 else if (!atomic)
David Brazdil0f672f62019-12-10 10:32:29 +00002256 memunmap(map->hva);
Olivier Deprez0e641232021-09-23 10:07:05 +02002257 else
2258 WARN_ONCE(1, "Unexpected unmapping in atomic context");
David Brazdil0f672f62019-12-10 10:32:29 +00002259#endif
2260
Olivier Deprez0e641232021-09-23 10:07:05 +02002261 if (dirty)
2262 mark_page_dirty_in_slot(memslot, map->gfn);
2263
2264 if (cache)
2265 cache->dirty |= dirty;
2266 else
2267 kvm_release_pfn(map->pfn, dirty, NULL);
David Brazdil0f672f62019-12-10 10:32:29 +00002268
2269 map->hva = NULL;
2270 map->page = NULL;
2271}
Olivier Deprez0e641232021-09-23 10:07:05 +02002272
Olivier Deprez157378f2022-04-04 15:47:50 +02002273int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
Olivier Deprez0e641232021-09-23 10:07:05 +02002274 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
2275{
2276 __kvm_unmap_gfn(gfn_to_memslot(vcpu->kvm, map->gfn), map,
2277 cache, dirty, atomic);
2278 return 0;
2279}
2280EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2281
2282void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2283{
2284 __kvm_unmap_gfn(kvm_vcpu_gfn_to_memslot(vcpu, map->gfn), map, NULL,
2285 dirty, false);
2286}
David Brazdil0f672f62019-12-10 10:32:29 +00002287EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2288
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002289struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2290{
2291 kvm_pfn_t pfn;
2292
2293 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2294
2295 return kvm_pfn_to_page(pfn);
2296}
2297EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2298
2299void kvm_release_page_clean(struct page *page)
2300{
2301 WARN_ON(is_error_page(page));
2302
2303 kvm_release_pfn_clean(page_to_pfn(page));
2304}
2305EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2306
2307void kvm_release_pfn_clean(kvm_pfn_t pfn)
2308{
2309 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2310 put_page(pfn_to_page(pfn));
2311}
2312EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2313
2314void kvm_release_page_dirty(struct page *page)
2315{
2316 WARN_ON(is_error_page(page));
2317
2318 kvm_release_pfn_dirty(page_to_pfn(page));
2319}
2320EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2321
2322void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2323{
2324 kvm_set_pfn_dirty(pfn);
2325 kvm_release_pfn_clean(pfn);
2326}
2327EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2328
2329void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2330{
Olivier Deprez157378f2022-04-04 15:47:50 +02002331 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2332 SetPageDirty(pfn_to_page(pfn));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002333}
2334EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2335
2336void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2337{
David Brazdil0f672f62019-12-10 10:32:29 +00002338 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002339 mark_page_accessed(pfn_to_page(pfn));
2340}
2341EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2342
2343void kvm_get_pfn(kvm_pfn_t pfn)
2344{
2345 if (!kvm_is_reserved_pfn(pfn))
2346 get_page(pfn_to_page(pfn));
2347}
2348EXPORT_SYMBOL_GPL(kvm_get_pfn);
2349
2350static int next_segment(unsigned long len, int offset)
2351{
2352 if (len > PAGE_SIZE - offset)
2353 return PAGE_SIZE - offset;
2354 else
2355 return len;
2356}
2357
2358static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2359 void *data, int offset, int len)
2360{
2361 int r;
2362 unsigned long addr;
2363
2364 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2365 if (kvm_is_error_hva(addr))
2366 return -EFAULT;
2367 r = __copy_from_user(data, (void __user *)addr + offset, len);
2368 if (r)
2369 return -EFAULT;
2370 return 0;
2371}
2372
2373int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2374 int len)
2375{
2376 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2377
2378 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2379}
2380EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2381
2382int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2383 int offset, int len)
2384{
2385 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2386
2387 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2388}
2389EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2390
2391int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2392{
2393 gfn_t gfn = gpa >> PAGE_SHIFT;
2394 int seg;
2395 int offset = offset_in_page(gpa);
2396 int ret;
2397
2398 while ((seg = next_segment(len, offset)) != 0) {
2399 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2400 if (ret < 0)
2401 return ret;
2402 offset = 0;
2403 len -= seg;
2404 data += seg;
2405 ++gfn;
2406 }
2407 return 0;
2408}
2409EXPORT_SYMBOL_GPL(kvm_read_guest);
2410
2411int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2412{
2413 gfn_t gfn = gpa >> PAGE_SHIFT;
2414 int seg;
2415 int offset = offset_in_page(gpa);
2416 int ret;
2417
2418 while ((seg = next_segment(len, offset)) != 0) {
2419 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2420 if (ret < 0)
2421 return ret;
2422 offset = 0;
2423 len -= seg;
2424 data += seg;
2425 ++gfn;
2426 }
2427 return 0;
2428}
2429EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2430
2431static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2432 void *data, int offset, unsigned long len)
2433{
2434 int r;
2435 unsigned long addr;
2436
2437 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2438 if (kvm_is_error_hva(addr))
2439 return -EFAULT;
2440 pagefault_disable();
2441 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2442 pagefault_enable();
2443 if (r)
2444 return -EFAULT;
2445 return 0;
2446}
2447
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002448int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2449 void *data, unsigned long len)
2450{
2451 gfn_t gfn = gpa >> PAGE_SHIFT;
2452 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2453 int offset = offset_in_page(gpa);
2454
2455 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2456}
2457EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2458
2459static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
2460 const void *data, int offset, int len)
2461{
2462 int r;
2463 unsigned long addr;
2464
2465 addr = gfn_to_hva_memslot(memslot, gfn);
2466 if (kvm_is_error_hva(addr))
2467 return -EFAULT;
2468 r = __copy_to_user((void __user *)addr + offset, data, len);
2469 if (r)
2470 return -EFAULT;
2471 mark_page_dirty_in_slot(memslot, gfn);
2472 return 0;
2473}
2474
2475int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2476 const void *data, int offset, int len)
2477{
2478 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2479
2480 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2481}
2482EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2483
2484int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2485 const void *data, int offset, int len)
2486{
2487 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2488
2489 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2490}
2491EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2492
2493int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2494 unsigned long len)
2495{
2496 gfn_t gfn = gpa >> PAGE_SHIFT;
2497 int seg;
2498 int offset = offset_in_page(gpa);
2499 int ret;
2500
2501 while ((seg = next_segment(len, offset)) != 0) {
2502 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2503 if (ret < 0)
2504 return ret;
2505 offset = 0;
2506 len -= seg;
2507 data += seg;
2508 ++gfn;
2509 }
2510 return 0;
2511}
2512EXPORT_SYMBOL_GPL(kvm_write_guest);
2513
2514int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2515 unsigned long len)
2516{
2517 gfn_t gfn = gpa >> PAGE_SHIFT;
2518 int seg;
2519 int offset = offset_in_page(gpa);
2520 int ret;
2521
2522 while ((seg = next_segment(len, offset)) != 0) {
2523 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2524 if (ret < 0)
2525 return ret;
2526 offset = 0;
2527 len -= seg;
2528 data += seg;
2529 ++gfn;
2530 }
2531 return 0;
2532}
2533EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2534
2535static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2536 struct gfn_to_hva_cache *ghc,
2537 gpa_t gpa, unsigned long len)
2538{
2539 int offset = offset_in_page(gpa);
2540 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2541 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2542 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2543 gfn_t nr_pages_avail;
2544
Olivier Deprez157378f2022-04-04 15:47:50 +02002545 /* Update ghc->generation before performing any error checks. */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002546 ghc->generation = slots->generation;
Olivier Deprez157378f2022-04-04 15:47:50 +02002547
2548 if (start_gfn > end_gfn) {
2549 ghc->hva = KVM_HVA_ERR_BAD;
2550 return -EINVAL;
2551 }
David Brazdil0f672f62019-12-10 10:32:29 +00002552
2553 /*
2554 * If the requested region crosses two memslots, we still
2555 * verify that the entire region is valid here.
2556 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002557 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
David Brazdil0f672f62019-12-10 10:32:29 +00002558 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2559 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2560 &nr_pages_avail);
2561 if (kvm_is_error_hva(ghc->hva))
Olivier Deprez157378f2022-04-04 15:47:50 +02002562 return -EFAULT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002563 }
David Brazdil0f672f62019-12-10 10:32:29 +00002564
2565 /* Use the slow path for cross page reads and writes. */
Olivier Deprez157378f2022-04-04 15:47:50 +02002566 if (nr_pages_needed == 1)
David Brazdil0f672f62019-12-10 10:32:29 +00002567 ghc->hva += offset;
2568 else
2569 ghc->memslot = NULL;
2570
Olivier Deprez157378f2022-04-04 15:47:50 +02002571 ghc->gpa = gpa;
2572 ghc->len = len;
2573 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002574}
2575
2576int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2577 gpa_t gpa, unsigned long len)
2578{
2579 struct kvm_memslots *slots = kvm_memslots(kvm);
2580 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2581}
2582EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2583
2584int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
David Brazdil0f672f62019-12-10 10:32:29 +00002585 void *data, unsigned int offset,
2586 unsigned long len)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002587{
2588 struct kvm_memslots *slots = kvm_memslots(kvm);
2589 int r;
2590 gpa_t gpa = ghc->gpa + offset;
2591
Olivier Deprez157378f2022-04-04 15:47:50 +02002592 if (WARN_ON_ONCE(len + offset > ghc->len))
2593 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002594
Olivier Deprez157378f2022-04-04 15:47:50 +02002595 if (slots->generation != ghc->generation) {
2596 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2597 return -EFAULT;
2598 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002599
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002600 if (kvm_is_error_hva(ghc->hva))
2601 return -EFAULT;
2602
Olivier Deprez0e641232021-09-23 10:07:05 +02002603 if (unlikely(!ghc->memslot))
2604 return kvm_write_guest(kvm, gpa, data, len);
2605
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002606 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2607 if (r)
2608 return -EFAULT;
2609 mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
2610
2611 return 0;
2612}
2613EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2614
2615int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2616 void *data, unsigned long len)
2617{
2618 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2619}
2620EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2621
Olivier Deprez157378f2022-04-04 15:47:50 +02002622int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2623 void *data, unsigned int offset,
2624 unsigned long len)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002625{
2626 struct kvm_memslots *slots = kvm_memslots(kvm);
2627 int r;
Olivier Deprez157378f2022-04-04 15:47:50 +02002628 gpa_t gpa = ghc->gpa + offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002629
Olivier Deprez157378f2022-04-04 15:47:50 +02002630 if (WARN_ON_ONCE(len + offset > ghc->len))
2631 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002632
Olivier Deprez157378f2022-04-04 15:47:50 +02002633 if (slots->generation != ghc->generation) {
2634 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2635 return -EFAULT;
2636 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002637
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002638 if (kvm_is_error_hva(ghc->hva))
2639 return -EFAULT;
2640
Olivier Deprez0e641232021-09-23 10:07:05 +02002641 if (unlikely(!ghc->memslot))
Olivier Deprez157378f2022-04-04 15:47:50 +02002642 return kvm_read_guest(kvm, gpa, data, len);
Olivier Deprez0e641232021-09-23 10:07:05 +02002643
Olivier Deprez157378f2022-04-04 15:47:50 +02002644 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002645 if (r)
2646 return -EFAULT;
2647
2648 return 0;
2649}
Olivier Deprez157378f2022-04-04 15:47:50 +02002650EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
2651
2652int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2653 void *data, unsigned long len)
2654{
2655 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
2656}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002657EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2658
2659int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2660{
2661 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2662
2663 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2664}
2665EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2666
2667int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2668{
2669 gfn_t gfn = gpa >> PAGE_SHIFT;
2670 int seg;
2671 int offset = offset_in_page(gpa);
2672 int ret;
2673
2674 while ((seg = next_segment(len, offset)) != 0) {
2675 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2676 if (ret < 0)
2677 return ret;
2678 offset = 0;
2679 len -= seg;
2680 ++gfn;
2681 }
2682 return 0;
2683}
2684EXPORT_SYMBOL_GPL(kvm_clear_guest);
2685
Olivier Deprez157378f2022-04-04 15:47:50 +02002686void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002687{
2688 if (memslot && memslot->dirty_bitmap) {
2689 unsigned long rel_gfn = gfn - memslot->base_gfn;
2690
2691 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2692 }
2693}
Olivier Deprez157378f2022-04-04 15:47:50 +02002694EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002695
2696void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2697{
2698 struct kvm_memory_slot *memslot;
2699
2700 memslot = gfn_to_memslot(kvm, gfn);
2701 mark_page_dirty_in_slot(memslot, gfn);
2702}
2703EXPORT_SYMBOL_GPL(mark_page_dirty);
2704
2705void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2706{
2707 struct kvm_memory_slot *memslot;
2708
2709 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2710 mark_page_dirty_in_slot(memslot, gfn);
2711}
2712EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2713
2714void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2715{
2716 if (!vcpu->sigset_active)
2717 return;
2718
2719 /*
2720 * This does a lockless modification of ->real_blocked, which is fine
2721 * because, only current can change ->real_blocked and all readers of
2722 * ->real_blocked don't care as long ->real_blocked is always a subset
2723 * of ->blocked.
2724 */
2725 sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
2726}
2727
2728void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2729{
2730 if (!vcpu->sigset_active)
2731 return;
2732
2733 sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
2734 sigemptyset(&current->real_blocked);
2735}
2736
2737static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2738{
David Brazdil0f672f62019-12-10 10:32:29 +00002739 unsigned int old, val, grow, grow_start;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002740
2741 old = val = vcpu->halt_poll_ns;
David Brazdil0f672f62019-12-10 10:32:29 +00002742 grow_start = READ_ONCE(halt_poll_ns_grow_start);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002743 grow = READ_ONCE(halt_poll_ns_grow);
David Brazdil0f672f62019-12-10 10:32:29 +00002744 if (!grow)
2745 goto out;
2746
2747 val *= grow;
2748 if (val < grow_start)
2749 val = grow_start;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002750
Olivier Deprez157378f2022-04-04 15:47:50 +02002751 if (val > vcpu->kvm->max_halt_poll_ns)
2752 val = vcpu->kvm->max_halt_poll_ns;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002753
2754 vcpu->halt_poll_ns = val;
David Brazdil0f672f62019-12-10 10:32:29 +00002755out:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002756 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2757}
2758
2759static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2760{
Olivier Deprez157378f2022-04-04 15:47:50 +02002761 unsigned int old, val, shrink, grow_start;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002762
2763 old = val = vcpu->halt_poll_ns;
2764 shrink = READ_ONCE(halt_poll_ns_shrink);
Olivier Deprez157378f2022-04-04 15:47:50 +02002765 grow_start = READ_ONCE(halt_poll_ns_grow_start);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002766 if (shrink == 0)
2767 val = 0;
2768 else
2769 val /= shrink;
2770
Olivier Deprez157378f2022-04-04 15:47:50 +02002771 if (val < grow_start)
2772 val = 0;
2773
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002774 vcpu->halt_poll_ns = val;
2775 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2776}
2777
2778static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2779{
2780 int ret = -EINTR;
2781 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2782
2783 if (kvm_arch_vcpu_runnable(vcpu)) {
2784 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2785 goto out;
2786 }
2787 if (kvm_cpu_has_pending_timer(vcpu))
2788 goto out;
2789 if (signal_pending(current))
2790 goto out;
2791
2792 ret = 0;
2793out:
2794 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2795 return ret;
2796}
2797
Olivier Deprez157378f2022-04-04 15:47:50 +02002798static inline void
2799update_halt_poll_stats(struct kvm_vcpu *vcpu, u64 poll_ns, bool waited)
2800{
2801 if (waited)
2802 vcpu->stat.halt_poll_fail_ns += poll_ns;
2803 else
2804 vcpu->stat.halt_poll_success_ns += poll_ns;
2805}
2806
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002807/*
2808 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2809 */
2810void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2811{
Olivier Deprez157378f2022-04-04 15:47:50 +02002812 ktime_t start, cur, poll_end;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002813 bool waited = false;
2814 u64 block_ns;
2815
David Brazdil0f672f62019-12-10 10:32:29 +00002816 kvm_arch_vcpu_blocking(vcpu);
2817
Olivier Deprez157378f2022-04-04 15:47:50 +02002818 start = cur = poll_end = ktime_get();
David Brazdil0f672f62019-12-10 10:32:29 +00002819 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002820 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2821
2822 ++vcpu->stat.halt_attempted_poll;
2823 do {
2824 /*
2825 * This sets KVM_REQ_UNHALT if an interrupt
2826 * arrives.
2827 */
2828 if (kvm_vcpu_check_block(vcpu) < 0) {
2829 ++vcpu->stat.halt_successful_poll;
2830 if (!vcpu_valid_wakeup(vcpu))
2831 ++vcpu->stat.halt_poll_invalid;
2832 goto out;
2833 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002834 poll_end = cur = ktime_get();
2835 } while (single_task_running() && !need_resched() &&
2836 ktime_before(cur, stop));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002837 }
2838
Olivier Deprez157378f2022-04-04 15:47:50 +02002839 prepare_to_rcuwait(&vcpu->wait);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002840 for (;;) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002841 set_current_state(TASK_INTERRUPTIBLE);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002842
2843 if (kvm_vcpu_check_block(vcpu) < 0)
2844 break;
2845
2846 waited = true;
2847 schedule();
2848 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002849 finish_rcuwait(&vcpu->wait);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002850 cur = ktime_get();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002851out:
David Brazdil0f672f62019-12-10 10:32:29 +00002852 kvm_arch_vcpu_unblocking(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002853 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2854
Olivier Deprez157378f2022-04-04 15:47:50 +02002855 update_halt_poll_stats(
2856 vcpu, ktime_to_ns(ktime_sub(poll_end, start)), waited);
2857
David Brazdil0f672f62019-12-10 10:32:29 +00002858 if (!kvm_arch_no_poll(vcpu)) {
2859 if (!vcpu_valid_wakeup(vcpu)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002860 shrink_halt_poll_ns(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02002861 } else if (vcpu->kvm->max_halt_poll_ns) {
David Brazdil0f672f62019-12-10 10:32:29 +00002862 if (block_ns <= vcpu->halt_poll_ns)
2863 ;
2864 /* we had a long block, shrink polling */
Olivier Deprez157378f2022-04-04 15:47:50 +02002865 else if (vcpu->halt_poll_ns &&
2866 block_ns > vcpu->kvm->max_halt_poll_ns)
David Brazdil0f672f62019-12-10 10:32:29 +00002867 shrink_halt_poll_ns(vcpu);
2868 /* we had a short halt and our poll time is too small */
Olivier Deprez157378f2022-04-04 15:47:50 +02002869 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
2870 block_ns < vcpu->kvm->max_halt_poll_ns)
David Brazdil0f672f62019-12-10 10:32:29 +00002871 grow_halt_poll_ns(vcpu);
2872 } else {
2873 vcpu->halt_poll_ns = 0;
2874 }
2875 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002876
2877 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2878 kvm_arch_vcpu_block_finish(vcpu);
2879}
2880EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2881
2882bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2883{
Olivier Deprez157378f2022-04-04 15:47:50 +02002884 struct rcuwait *waitp;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002885
Olivier Deprez157378f2022-04-04 15:47:50 +02002886 waitp = kvm_arch_vcpu_get_wait(vcpu);
2887 if (rcuwait_wake_up(waitp)) {
David Brazdil0f672f62019-12-10 10:32:29 +00002888 WRITE_ONCE(vcpu->ready, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002889 ++vcpu->stat.halt_wakeup;
2890 return true;
2891 }
2892
2893 return false;
2894}
2895EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2896
2897#ifndef CONFIG_S390
2898/*
2899 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2900 */
2901void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2902{
2903 int me;
2904 int cpu = vcpu->cpu;
2905
2906 if (kvm_vcpu_wake_up(vcpu))
2907 return;
2908
2909 me = get_cpu();
2910 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2911 if (kvm_arch_vcpu_should_kick(vcpu))
2912 smp_send_reschedule(cpu);
2913 put_cpu();
2914}
2915EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2916#endif /* !CONFIG_S390 */
2917
2918int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2919{
2920 struct pid *pid;
2921 struct task_struct *task = NULL;
2922 int ret = 0;
2923
2924 rcu_read_lock();
2925 pid = rcu_dereference(target->pid);
2926 if (pid)
2927 task = get_pid_task(pid, PIDTYPE_PID);
2928 rcu_read_unlock();
2929 if (!task)
2930 return ret;
2931 ret = yield_to(task, 1);
2932 put_task_struct(task);
2933
2934 return ret;
2935}
2936EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2937
2938/*
2939 * Helper that checks whether a VCPU is eligible for directed yield.
2940 * Most eligible candidate to yield is decided by following heuristics:
2941 *
2942 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2943 * (preempted lock holder), indicated by @in_spin_loop.
Olivier Deprez157378f2022-04-04 15:47:50 +02002944 * Set at the beginning and cleared at the end of interception/PLE handler.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002945 *
2946 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2947 * chance last time (mostly it has become eligible now since we have probably
2948 * yielded to lockholder in last iteration. This is done by toggling
2949 * @dy_eligible each time a VCPU checked for eligibility.)
2950 *
2951 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2952 * to preempted lock-holder could result in wrong VCPU selection and CPU
2953 * burning. Giving priority for a potential lock-holder increases lock
2954 * progress.
2955 *
2956 * Since algorithm is based on heuristics, accessing another VCPU data without
2957 * locking does not harm. It may result in trying to yield to same VCPU, fail
2958 * and continue with next VCPU and so on.
2959 */
2960static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2961{
2962#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2963 bool eligible;
2964
2965 eligible = !vcpu->spin_loop.in_spin_loop ||
2966 vcpu->spin_loop.dy_eligible;
2967
2968 if (vcpu->spin_loop.in_spin_loop)
2969 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2970
2971 return eligible;
2972#else
2973 return true;
2974#endif
2975}
2976
David Brazdil0f672f62019-12-10 10:32:29 +00002977/*
2978 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2979 * a vcpu_load/vcpu_put pair. However, for most architectures
2980 * kvm_arch_vcpu_runnable does not require vcpu_load.
2981 */
2982bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2983{
2984 return kvm_arch_vcpu_runnable(vcpu);
2985}
2986
2987static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2988{
2989 if (kvm_arch_dy_runnable(vcpu))
2990 return true;
2991
2992#ifdef CONFIG_KVM_ASYNC_PF
2993 if (!list_empty_careful(&vcpu->async_pf.done))
2994 return true;
2995#endif
2996
2997 return false;
2998}
2999
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003000void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3001{
3002 struct kvm *kvm = me->kvm;
3003 struct kvm_vcpu *vcpu;
3004 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3005 int yielded = 0;
3006 int try = 3;
3007 int pass;
3008 int i;
3009
3010 kvm_vcpu_set_in_spin_loop(me, true);
3011 /*
3012 * We boost the priority of a VCPU that is runnable but not
3013 * currently running, because it got preempted by something
3014 * else and called schedule in __vcpu_run. Hopefully that
3015 * VCPU is holding the lock that we need and will release it.
3016 * We approximate round-robin by starting at the last boosted VCPU.
3017 */
3018 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3019 kvm_for_each_vcpu(i, vcpu, kvm) {
3020 if (!pass && i <= last_boosted_vcpu) {
3021 i = last_boosted_vcpu;
3022 continue;
3023 } else if (pass && i > last_boosted_vcpu)
3024 break;
David Brazdil0f672f62019-12-10 10:32:29 +00003025 if (!READ_ONCE(vcpu->ready))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003026 continue;
3027 if (vcpu == me)
3028 continue;
Olivier Deprez157378f2022-04-04 15:47:50 +02003029 if (rcuwait_active(&vcpu->wait) &&
3030 !vcpu_dy_runnable(vcpu))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003031 continue;
David Brazdil0f672f62019-12-10 10:32:29 +00003032 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3033 !kvm_arch_vcpu_in_kernel(vcpu))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003034 continue;
3035 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3036 continue;
3037
3038 yielded = kvm_vcpu_yield_to(vcpu);
3039 if (yielded > 0) {
3040 kvm->last_boosted_vcpu = i;
3041 break;
3042 } else if (yielded < 0) {
3043 try--;
3044 if (!try)
3045 break;
3046 }
3047 }
3048 }
3049 kvm_vcpu_set_in_spin_loop(me, false);
3050
3051 /* Ensure vcpu is not eligible during next spinloop */
3052 kvm_vcpu_set_dy_eligible(me, false);
3053}
3054EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3055
3056static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3057{
3058 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3059 struct page *page;
3060
3061 if (vmf->pgoff == 0)
3062 page = virt_to_page(vcpu->run);
3063#ifdef CONFIG_X86
3064 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3065 page = virt_to_page(vcpu->arch.pio_data);
3066#endif
3067#ifdef CONFIG_KVM_MMIO
3068 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3069 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3070#endif
3071 else
3072 return kvm_arch_vcpu_fault(vcpu, vmf);
3073 get_page(page);
3074 vmf->page = page;
3075 return 0;
3076}
3077
3078static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3079 .fault = kvm_vcpu_fault,
3080};
3081
3082static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3083{
3084 vma->vm_ops = &kvm_vcpu_vm_ops;
3085 return 0;
3086}
3087
3088static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3089{
3090 struct kvm_vcpu *vcpu = filp->private_data;
3091
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003092 kvm_put_kvm(vcpu->kvm);
3093 return 0;
3094}
3095
3096static struct file_operations kvm_vcpu_fops = {
3097 .release = kvm_vcpu_release,
3098 .unlocked_ioctl = kvm_vcpu_ioctl,
3099 .mmap = kvm_vcpu_mmap,
3100 .llseek = noop_llseek,
3101 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3102};
3103
3104/*
3105 * Allocates an inode for the vcpu.
3106 */
3107static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3108{
3109 char name[8 + 1 + ITOA_MAX_LEN + 1];
3110
3111 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3112 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3113}
3114
David Brazdil0f672f62019-12-10 10:32:29 +00003115static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003116{
David Brazdil0f672f62019-12-10 10:32:29 +00003117#ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
Olivier Deprez157378f2022-04-04 15:47:50 +02003118 struct dentry *debugfs_dentry;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003119 char dir_name[ITOA_MAX_LEN * 2];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003120
3121 if (!debugfs_initialized())
David Brazdil0f672f62019-12-10 10:32:29 +00003122 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003123
3124 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
Olivier Deprez157378f2022-04-04 15:47:50 +02003125 debugfs_dentry = debugfs_create_dir(dir_name,
3126 vcpu->kvm->debugfs_dentry);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003127
Olivier Deprez157378f2022-04-04 15:47:50 +02003128 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
David Brazdil0f672f62019-12-10 10:32:29 +00003129#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003130}
3131
3132/*
3133 * Creates some virtual cpus. Good luck creating more than one.
3134 */
3135static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3136{
3137 int r;
3138 struct kvm_vcpu *vcpu;
Olivier Deprez157378f2022-04-04 15:47:50 +02003139 struct page *page;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003140
3141 if (id >= KVM_MAX_VCPU_ID)
3142 return -EINVAL;
3143
3144 mutex_lock(&kvm->lock);
3145 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3146 mutex_unlock(&kvm->lock);
3147 return -EINVAL;
3148 }
3149
3150 kvm->created_vcpus++;
3151 mutex_unlock(&kvm->lock);
3152
Olivier Deprez157378f2022-04-04 15:47:50 +02003153 r = kvm_arch_vcpu_precreate(kvm, id);
3154 if (r)
3155 goto vcpu_decrement;
3156
3157 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
3158 if (!vcpu) {
3159 r = -ENOMEM;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003160 goto vcpu_decrement;
3161 }
3162
Olivier Deprez157378f2022-04-04 15:47:50 +02003163 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3164 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3165 if (!page) {
3166 r = -ENOMEM;
3167 goto vcpu_free;
3168 }
3169 vcpu->run = page_address(page);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003170
Olivier Deprez157378f2022-04-04 15:47:50 +02003171 kvm_vcpu_init(vcpu, kvm, id);
3172
3173 r = kvm_arch_vcpu_create(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003174 if (r)
Olivier Deprez157378f2022-04-04 15:47:50 +02003175 goto vcpu_free_run_page;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003176
3177 mutex_lock(&kvm->lock);
3178 if (kvm_get_vcpu_by_id(kvm, id)) {
3179 r = -EEXIST;
3180 goto unlock_vcpu_destroy;
3181 }
3182
Olivier Deprez157378f2022-04-04 15:47:50 +02003183 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3184 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003185
3186 /* Now it's all set up, let userspace reach it */
3187 kvm_get_kvm(kvm);
3188 r = create_vcpu_fd(vcpu);
3189 if (r < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003190 kvm_put_kvm_no_destroy(kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003191 goto unlock_vcpu_destroy;
3192 }
3193
Olivier Deprez157378f2022-04-04 15:47:50 +02003194 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003195
3196 /*
3197 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3198 * before kvm->online_vcpu's incremented value.
3199 */
3200 smp_wmb();
3201 atomic_inc(&kvm->online_vcpus);
3202
3203 mutex_unlock(&kvm->lock);
3204 kvm_arch_vcpu_postcreate(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02003205 kvm_create_vcpu_debugfs(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003206 return r;
3207
3208unlock_vcpu_destroy:
3209 mutex_unlock(&kvm->lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003210 kvm_arch_vcpu_destroy(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02003211vcpu_free_run_page:
3212 free_page((unsigned long)vcpu->run);
3213vcpu_free:
3214 kmem_cache_free(kvm_vcpu_cache, vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003215vcpu_decrement:
3216 mutex_lock(&kvm->lock);
3217 kvm->created_vcpus--;
3218 mutex_unlock(&kvm->lock);
3219 return r;
3220}
3221
3222static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3223{
3224 if (sigset) {
3225 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3226 vcpu->sigset_active = 1;
3227 vcpu->sigset = *sigset;
3228 } else
3229 vcpu->sigset_active = 0;
3230 return 0;
3231}
3232
3233static long kvm_vcpu_ioctl(struct file *filp,
3234 unsigned int ioctl, unsigned long arg)
3235{
3236 struct kvm_vcpu *vcpu = filp->private_data;
3237 void __user *argp = (void __user *)arg;
3238 int r;
3239 struct kvm_fpu *fpu = NULL;
3240 struct kvm_sregs *kvm_sregs = NULL;
3241
3242 if (vcpu->kvm->mm != current->mm)
3243 return -EIO;
3244
3245 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3246 return -EINVAL;
3247
3248 /*
3249 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3250 * execution; mutex_lock() would break them.
3251 */
3252 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3253 if (r != -ENOIOCTLCMD)
3254 return r;
3255
3256 if (mutex_lock_killable(&vcpu->mutex))
3257 return -EINTR;
3258 switch (ioctl) {
3259 case KVM_RUN: {
3260 struct pid *oldpid;
3261 r = -EINVAL;
3262 if (arg)
3263 goto out;
3264 oldpid = rcu_access_pointer(vcpu->pid);
3265 if (unlikely(oldpid != task_pid(current))) {
3266 /* The thread running this VCPU changed. */
3267 struct pid *newpid;
3268
3269 r = kvm_arch_vcpu_run_pid_change(vcpu);
3270 if (r)
3271 break;
3272
3273 newpid = get_task_pid(current, PIDTYPE_PID);
3274 rcu_assign_pointer(vcpu->pid, newpid);
3275 if (oldpid)
3276 synchronize_rcu();
3277 put_pid(oldpid);
3278 }
Olivier Deprez157378f2022-04-04 15:47:50 +02003279 r = kvm_arch_vcpu_ioctl_run(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003280 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3281 break;
3282 }
3283 case KVM_GET_REGS: {
3284 struct kvm_regs *kvm_regs;
3285
3286 r = -ENOMEM;
David Brazdil0f672f62019-12-10 10:32:29 +00003287 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003288 if (!kvm_regs)
3289 goto out;
3290 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3291 if (r)
3292 goto out_free1;
3293 r = -EFAULT;
3294 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3295 goto out_free1;
3296 r = 0;
3297out_free1:
3298 kfree(kvm_regs);
3299 break;
3300 }
3301 case KVM_SET_REGS: {
3302 struct kvm_regs *kvm_regs;
3303
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003304 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3305 if (IS_ERR(kvm_regs)) {
3306 r = PTR_ERR(kvm_regs);
3307 goto out;
3308 }
3309 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3310 kfree(kvm_regs);
3311 break;
3312 }
3313 case KVM_GET_SREGS: {
David Brazdil0f672f62019-12-10 10:32:29 +00003314 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3315 GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003316 r = -ENOMEM;
3317 if (!kvm_sregs)
3318 goto out;
3319 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3320 if (r)
3321 goto out;
3322 r = -EFAULT;
3323 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3324 goto out;
3325 r = 0;
3326 break;
3327 }
3328 case KVM_SET_SREGS: {
3329 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3330 if (IS_ERR(kvm_sregs)) {
3331 r = PTR_ERR(kvm_sregs);
3332 kvm_sregs = NULL;
3333 goto out;
3334 }
3335 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3336 break;
3337 }
3338 case KVM_GET_MP_STATE: {
3339 struct kvm_mp_state mp_state;
3340
3341 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3342 if (r)
3343 goto out;
3344 r = -EFAULT;
3345 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3346 goto out;
3347 r = 0;
3348 break;
3349 }
3350 case KVM_SET_MP_STATE: {
3351 struct kvm_mp_state mp_state;
3352
3353 r = -EFAULT;
3354 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3355 goto out;
3356 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3357 break;
3358 }
3359 case KVM_TRANSLATE: {
3360 struct kvm_translation tr;
3361
3362 r = -EFAULT;
3363 if (copy_from_user(&tr, argp, sizeof(tr)))
3364 goto out;
3365 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3366 if (r)
3367 goto out;
3368 r = -EFAULT;
3369 if (copy_to_user(argp, &tr, sizeof(tr)))
3370 goto out;
3371 r = 0;
3372 break;
3373 }
3374 case KVM_SET_GUEST_DEBUG: {
3375 struct kvm_guest_debug dbg;
3376
3377 r = -EFAULT;
3378 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3379 goto out;
3380 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3381 break;
3382 }
3383 case KVM_SET_SIGNAL_MASK: {
3384 struct kvm_signal_mask __user *sigmask_arg = argp;
3385 struct kvm_signal_mask kvm_sigmask;
3386 sigset_t sigset, *p;
3387
3388 p = NULL;
3389 if (argp) {
3390 r = -EFAULT;
3391 if (copy_from_user(&kvm_sigmask, argp,
3392 sizeof(kvm_sigmask)))
3393 goto out;
3394 r = -EINVAL;
3395 if (kvm_sigmask.len != sizeof(sigset))
3396 goto out;
3397 r = -EFAULT;
3398 if (copy_from_user(&sigset, sigmask_arg->sigset,
3399 sizeof(sigset)))
3400 goto out;
3401 p = &sigset;
3402 }
3403 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3404 break;
3405 }
3406 case KVM_GET_FPU: {
David Brazdil0f672f62019-12-10 10:32:29 +00003407 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003408 r = -ENOMEM;
3409 if (!fpu)
3410 goto out;
3411 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3412 if (r)
3413 goto out;
3414 r = -EFAULT;
3415 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3416 goto out;
3417 r = 0;
3418 break;
3419 }
3420 case KVM_SET_FPU: {
3421 fpu = memdup_user(argp, sizeof(*fpu));
3422 if (IS_ERR(fpu)) {
3423 r = PTR_ERR(fpu);
3424 fpu = NULL;
3425 goto out;
3426 }
3427 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3428 break;
3429 }
3430 default:
3431 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3432 }
3433out:
3434 mutex_unlock(&vcpu->mutex);
3435 kfree(fpu);
3436 kfree(kvm_sregs);
3437 return r;
3438}
3439
3440#ifdef CONFIG_KVM_COMPAT
3441static long kvm_vcpu_compat_ioctl(struct file *filp,
3442 unsigned int ioctl, unsigned long arg)
3443{
3444 struct kvm_vcpu *vcpu = filp->private_data;
3445 void __user *argp = compat_ptr(arg);
3446 int r;
3447
3448 if (vcpu->kvm->mm != current->mm)
3449 return -EIO;
3450
3451 switch (ioctl) {
3452 case KVM_SET_SIGNAL_MASK: {
3453 struct kvm_signal_mask __user *sigmask_arg = argp;
3454 struct kvm_signal_mask kvm_sigmask;
3455 sigset_t sigset;
3456
3457 if (argp) {
3458 r = -EFAULT;
3459 if (copy_from_user(&kvm_sigmask, argp,
3460 sizeof(kvm_sigmask)))
3461 goto out;
3462 r = -EINVAL;
3463 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3464 goto out;
3465 r = -EFAULT;
Olivier Deprez157378f2022-04-04 15:47:50 +02003466 if (get_compat_sigset(&sigset,
3467 (compat_sigset_t __user *)sigmask_arg->sigset))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003468 goto out;
3469 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3470 } else
3471 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3472 break;
3473 }
3474 default:
3475 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3476 }
3477
3478out:
3479 return r;
3480}
3481#endif
3482
David Brazdil0f672f62019-12-10 10:32:29 +00003483static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3484{
3485 struct kvm_device *dev = filp->private_data;
3486
3487 if (dev->ops->mmap)
3488 return dev->ops->mmap(dev, vma);
3489
3490 return -ENODEV;
3491}
3492
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003493static int kvm_device_ioctl_attr(struct kvm_device *dev,
3494 int (*accessor)(struct kvm_device *dev,
3495 struct kvm_device_attr *attr),
3496 unsigned long arg)
3497{
3498 struct kvm_device_attr attr;
3499
3500 if (!accessor)
3501 return -EPERM;
3502
3503 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3504 return -EFAULT;
3505
3506 return accessor(dev, &attr);
3507}
3508
3509static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3510 unsigned long arg)
3511{
3512 struct kvm_device *dev = filp->private_data;
3513
David Brazdil0f672f62019-12-10 10:32:29 +00003514 if (dev->kvm->mm != current->mm)
3515 return -EIO;
3516
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003517 switch (ioctl) {
3518 case KVM_SET_DEVICE_ATTR:
3519 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3520 case KVM_GET_DEVICE_ATTR:
3521 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3522 case KVM_HAS_DEVICE_ATTR:
3523 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3524 default:
3525 if (dev->ops->ioctl)
3526 return dev->ops->ioctl(dev, ioctl, arg);
3527
3528 return -ENOTTY;
3529 }
3530}
3531
3532static int kvm_device_release(struct inode *inode, struct file *filp)
3533{
3534 struct kvm_device *dev = filp->private_data;
3535 struct kvm *kvm = dev->kvm;
3536
David Brazdil0f672f62019-12-10 10:32:29 +00003537 if (dev->ops->release) {
3538 mutex_lock(&kvm->lock);
3539 list_del(&dev->vm_node);
3540 dev->ops->release(dev);
3541 mutex_unlock(&kvm->lock);
3542 }
3543
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003544 kvm_put_kvm(kvm);
3545 return 0;
3546}
3547
3548static const struct file_operations kvm_device_fops = {
3549 .unlocked_ioctl = kvm_device_ioctl,
3550 .release = kvm_device_release,
3551 KVM_COMPAT(kvm_device_ioctl),
David Brazdil0f672f62019-12-10 10:32:29 +00003552 .mmap = kvm_device_mmap,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003553};
3554
3555struct kvm_device *kvm_device_from_filp(struct file *filp)
3556{
3557 if (filp->f_op != &kvm_device_fops)
3558 return NULL;
3559
3560 return filp->private_data;
3561}
3562
Olivier Deprez157378f2022-04-04 15:47:50 +02003563static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003564#ifdef CONFIG_KVM_MPIC
3565 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3566 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3567#endif
3568};
3569
Olivier Deprez157378f2022-04-04 15:47:50 +02003570int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003571{
3572 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3573 return -ENOSPC;
3574
3575 if (kvm_device_ops_table[type] != NULL)
3576 return -EEXIST;
3577
3578 kvm_device_ops_table[type] = ops;
3579 return 0;
3580}
3581
3582void kvm_unregister_device_ops(u32 type)
3583{
3584 if (kvm_device_ops_table[type] != NULL)
3585 kvm_device_ops_table[type] = NULL;
3586}
3587
3588static int kvm_ioctl_create_device(struct kvm *kvm,
3589 struct kvm_create_device *cd)
3590{
Olivier Deprez157378f2022-04-04 15:47:50 +02003591 const struct kvm_device_ops *ops = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003592 struct kvm_device *dev;
3593 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
David Brazdil0f672f62019-12-10 10:32:29 +00003594 int type;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003595 int ret;
3596
3597 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3598 return -ENODEV;
3599
David Brazdil0f672f62019-12-10 10:32:29 +00003600 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3601 ops = kvm_device_ops_table[type];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003602 if (ops == NULL)
3603 return -ENODEV;
3604
3605 if (test)
3606 return 0;
3607
David Brazdil0f672f62019-12-10 10:32:29 +00003608 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003609 if (!dev)
3610 return -ENOMEM;
3611
3612 dev->ops = ops;
3613 dev->kvm = kvm;
3614
3615 mutex_lock(&kvm->lock);
David Brazdil0f672f62019-12-10 10:32:29 +00003616 ret = ops->create(dev, type);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003617 if (ret < 0) {
3618 mutex_unlock(&kvm->lock);
3619 kfree(dev);
3620 return ret;
3621 }
3622 list_add(&dev->vm_node, &kvm->devices);
3623 mutex_unlock(&kvm->lock);
3624
3625 if (ops->init)
3626 ops->init(dev);
3627
David Brazdil0f672f62019-12-10 10:32:29 +00003628 kvm_get_kvm(kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003629 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3630 if (ret < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003631 kvm_put_kvm_no_destroy(kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003632 mutex_lock(&kvm->lock);
3633 list_del(&dev->vm_node);
3634 mutex_unlock(&kvm->lock);
3635 ops->destroy(dev);
3636 return ret;
3637 }
3638
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003639 cd->fd = ret;
3640 return 0;
3641}
3642
3643static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3644{
3645 switch (arg) {
3646 case KVM_CAP_USER_MEMORY:
3647 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3648 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3649 case KVM_CAP_INTERNAL_ERROR_DATA:
3650#ifdef CONFIG_HAVE_KVM_MSI
3651 case KVM_CAP_SIGNAL_MSI:
3652#endif
3653#ifdef CONFIG_HAVE_KVM_IRQFD
3654 case KVM_CAP_IRQFD:
3655 case KVM_CAP_IRQFD_RESAMPLE:
3656#endif
3657 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3658 case KVM_CAP_CHECK_EXTENSION_VM:
David Brazdil0f672f62019-12-10 10:32:29 +00003659 case KVM_CAP_ENABLE_CAP_VM:
Olivier Deprez157378f2022-04-04 15:47:50 +02003660 case KVM_CAP_HALT_POLL:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003661 return 1;
3662#ifdef CONFIG_KVM_MMIO
3663 case KVM_CAP_COALESCED_MMIO:
3664 return KVM_COALESCED_MMIO_PAGE_OFFSET;
David Brazdil0f672f62019-12-10 10:32:29 +00003665 case KVM_CAP_COALESCED_PIO:
3666 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003667#endif
Olivier Deprez157378f2022-04-04 15:47:50 +02003668#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3669 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
3670 return KVM_DIRTY_LOG_MANUAL_CAPS;
3671#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003672#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3673 case KVM_CAP_IRQ_ROUTING:
3674 return KVM_MAX_IRQ_ROUTES;
3675#endif
3676#if KVM_ADDRESS_SPACE_NUM > 1
3677 case KVM_CAP_MULTI_ADDRESS_SPACE:
3678 return KVM_ADDRESS_SPACE_NUM;
3679#endif
David Brazdil0f672f62019-12-10 10:32:29 +00003680 case KVM_CAP_NR_MEMSLOTS:
3681 return KVM_USER_MEM_SLOTS;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003682 default:
3683 break;
3684 }
3685 return kvm_vm_ioctl_check_extension(kvm, arg);
3686}
3687
David Brazdil0f672f62019-12-10 10:32:29 +00003688int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3689 struct kvm_enable_cap *cap)
3690{
3691 return -EINVAL;
3692}
3693
3694static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
3695 struct kvm_enable_cap *cap)
3696{
3697 switch (cap->cap) {
3698#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
Olivier Deprez157378f2022-04-04 15:47:50 +02003699 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
3700 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
3701
3702 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
3703 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
3704
3705 if (cap->flags || (cap->args[0] & ~allowed_options))
David Brazdil0f672f62019-12-10 10:32:29 +00003706 return -EINVAL;
3707 kvm->manual_dirty_log_protect = cap->args[0];
3708 return 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02003709 }
David Brazdil0f672f62019-12-10 10:32:29 +00003710#endif
Olivier Deprez157378f2022-04-04 15:47:50 +02003711 case KVM_CAP_HALT_POLL: {
3712 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
3713 return -EINVAL;
3714
3715 kvm->max_halt_poll_ns = cap->args[0];
3716 return 0;
3717 }
David Brazdil0f672f62019-12-10 10:32:29 +00003718 default:
3719 return kvm_vm_ioctl_enable_cap(kvm, cap);
3720 }
3721}
3722
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003723static long kvm_vm_ioctl(struct file *filp,
3724 unsigned int ioctl, unsigned long arg)
3725{
3726 struct kvm *kvm = filp->private_data;
3727 void __user *argp = (void __user *)arg;
3728 int r;
3729
3730 if (kvm->mm != current->mm)
3731 return -EIO;
3732 switch (ioctl) {
3733 case KVM_CREATE_VCPU:
3734 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3735 break;
David Brazdil0f672f62019-12-10 10:32:29 +00003736 case KVM_ENABLE_CAP: {
3737 struct kvm_enable_cap cap;
3738
3739 r = -EFAULT;
3740 if (copy_from_user(&cap, argp, sizeof(cap)))
3741 goto out;
3742 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
3743 break;
3744 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003745 case KVM_SET_USER_MEMORY_REGION: {
3746 struct kvm_userspace_memory_region kvm_userspace_mem;
3747
3748 r = -EFAULT;
3749 if (copy_from_user(&kvm_userspace_mem, argp,
3750 sizeof(kvm_userspace_mem)))
3751 goto out;
3752
3753 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3754 break;
3755 }
3756 case KVM_GET_DIRTY_LOG: {
3757 struct kvm_dirty_log log;
3758
3759 r = -EFAULT;
3760 if (copy_from_user(&log, argp, sizeof(log)))
3761 goto out;
3762 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3763 break;
3764 }
David Brazdil0f672f62019-12-10 10:32:29 +00003765#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3766 case KVM_CLEAR_DIRTY_LOG: {
3767 struct kvm_clear_dirty_log log;
3768
3769 r = -EFAULT;
3770 if (copy_from_user(&log, argp, sizeof(log)))
3771 goto out;
3772 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3773 break;
3774 }
3775#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003776#ifdef CONFIG_KVM_MMIO
3777 case KVM_REGISTER_COALESCED_MMIO: {
3778 struct kvm_coalesced_mmio_zone zone;
3779
3780 r = -EFAULT;
3781 if (copy_from_user(&zone, argp, sizeof(zone)))
3782 goto out;
3783 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3784 break;
3785 }
3786 case KVM_UNREGISTER_COALESCED_MMIO: {
3787 struct kvm_coalesced_mmio_zone zone;
3788
3789 r = -EFAULT;
3790 if (copy_from_user(&zone, argp, sizeof(zone)))
3791 goto out;
3792 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3793 break;
3794 }
3795#endif
3796 case KVM_IRQFD: {
3797 struct kvm_irqfd data;
3798
3799 r = -EFAULT;
3800 if (copy_from_user(&data, argp, sizeof(data)))
3801 goto out;
3802 r = kvm_irqfd(kvm, &data);
3803 break;
3804 }
3805 case KVM_IOEVENTFD: {
3806 struct kvm_ioeventfd data;
3807
3808 r = -EFAULT;
3809 if (copy_from_user(&data, argp, sizeof(data)))
3810 goto out;
3811 r = kvm_ioeventfd(kvm, &data);
3812 break;
3813 }
3814#ifdef CONFIG_HAVE_KVM_MSI
3815 case KVM_SIGNAL_MSI: {
3816 struct kvm_msi msi;
3817
3818 r = -EFAULT;
3819 if (copy_from_user(&msi, argp, sizeof(msi)))
3820 goto out;
3821 r = kvm_send_userspace_msi(kvm, &msi);
3822 break;
3823 }
3824#endif
3825#ifdef __KVM_HAVE_IRQ_LINE
3826 case KVM_IRQ_LINE_STATUS:
3827 case KVM_IRQ_LINE: {
3828 struct kvm_irq_level irq_event;
3829
3830 r = -EFAULT;
3831 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3832 goto out;
3833
3834 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3835 ioctl == KVM_IRQ_LINE_STATUS);
3836 if (r)
3837 goto out;
3838
3839 r = -EFAULT;
3840 if (ioctl == KVM_IRQ_LINE_STATUS) {
3841 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3842 goto out;
3843 }
3844
3845 r = 0;
3846 break;
3847 }
3848#endif
3849#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3850 case KVM_SET_GSI_ROUTING: {
3851 struct kvm_irq_routing routing;
3852 struct kvm_irq_routing __user *urouting;
3853 struct kvm_irq_routing_entry *entries = NULL;
3854
3855 r = -EFAULT;
3856 if (copy_from_user(&routing, argp, sizeof(routing)))
3857 goto out;
3858 r = -EINVAL;
3859 if (!kvm_arch_can_set_irq_routing(kvm))
3860 goto out;
3861 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3862 goto out;
3863 if (routing.flags)
3864 goto out;
3865 if (routing.nr) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003866 urouting = argp;
Olivier Deprez157378f2022-04-04 15:47:50 +02003867 entries = vmemdup_user(urouting->entries,
3868 array_size(sizeof(*entries),
3869 routing.nr));
3870 if (IS_ERR(entries)) {
3871 r = PTR_ERR(entries);
3872 goto out;
3873 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003874 }
3875 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3876 routing.flags);
Olivier Deprez157378f2022-04-04 15:47:50 +02003877 kvfree(entries);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003878 break;
3879 }
3880#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3881 case KVM_CREATE_DEVICE: {
3882 struct kvm_create_device cd;
3883
3884 r = -EFAULT;
3885 if (copy_from_user(&cd, argp, sizeof(cd)))
3886 goto out;
3887
3888 r = kvm_ioctl_create_device(kvm, &cd);
3889 if (r)
3890 goto out;
3891
3892 r = -EFAULT;
3893 if (copy_to_user(argp, &cd, sizeof(cd)))
3894 goto out;
3895
3896 r = 0;
3897 break;
3898 }
3899 case KVM_CHECK_EXTENSION:
3900 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3901 break;
3902 default:
3903 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3904 }
3905out:
3906 return r;
3907}
3908
3909#ifdef CONFIG_KVM_COMPAT
3910struct compat_kvm_dirty_log {
3911 __u32 slot;
3912 __u32 padding1;
3913 union {
3914 compat_uptr_t dirty_bitmap; /* one bit per page */
3915 __u64 padding2;
3916 };
3917};
3918
Olivier Deprez0e641232021-09-23 10:07:05 +02003919struct compat_kvm_clear_dirty_log {
3920 __u32 slot;
3921 __u32 num_pages;
3922 __u64 first_page;
3923 union {
3924 compat_uptr_t dirty_bitmap; /* one bit per page */
3925 __u64 padding2;
3926 };
3927};
3928
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003929static long kvm_vm_compat_ioctl(struct file *filp,
3930 unsigned int ioctl, unsigned long arg)
3931{
3932 struct kvm *kvm = filp->private_data;
3933 int r;
3934
3935 if (kvm->mm != current->mm)
3936 return -EIO;
3937 switch (ioctl) {
Olivier Deprez0e641232021-09-23 10:07:05 +02003938#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3939 case KVM_CLEAR_DIRTY_LOG: {
3940 struct compat_kvm_clear_dirty_log compat_log;
3941 struct kvm_clear_dirty_log log;
3942
3943 if (copy_from_user(&compat_log, (void __user *)arg,
3944 sizeof(compat_log)))
3945 return -EFAULT;
3946 log.slot = compat_log.slot;
3947 log.num_pages = compat_log.num_pages;
3948 log.first_page = compat_log.first_page;
3949 log.padding2 = compat_log.padding2;
3950 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3951
3952 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3953 break;
3954 }
3955#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003956 case KVM_GET_DIRTY_LOG: {
3957 struct compat_kvm_dirty_log compat_log;
3958 struct kvm_dirty_log log;
3959
3960 if (copy_from_user(&compat_log, (void __user *)arg,
3961 sizeof(compat_log)))
3962 return -EFAULT;
3963 log.slot = compat_log.slot;
3964 log.padding1 = compat_log.padding1;
3965 log.padding2 = compat_log.padding2;
3966 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3967
3968 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3969 break;
3970 }
3971 default:
3972 r = kvm_vm_ioctl(filp, ioctl, arg);
3973 }
3974 return r;
3975}
3976#endif
3977
3978static struct file_operations kvm_vm_fops = {
3979 .release = kvm_vm_release,
3980 .unlocked_ioctl = kvm_vm_ioctl,
3981 .llseek = noop_llseek,
3982 KVM_COMPAT(kvm_vm_compat_ioctl),
3983};
3984
3985static int kvm_dev_ioctl_create_vm(unsigned long type)
3986{
3987 int r;
3988 struct kvm *kvm;
3989 struct file *file;
3990
3991 kvm = kvm_create_vm(type);
3992 if (IS_ERR(kvm))
3993 return PTR_ERR(kvm);
3994#ifdef CONFIG_KVM_MMIO
3995 r = kvm_coalesced_mmio_init(kvm);
3996 if (r < 0)
3997 goto put_kvm;
3998#endif
3999 r = get_unused_fd_flags(O_CLOEXEC);
4000 if (r < 0)
4001 goto put_kvm;
4002
4003 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4004 if (IS_ERR(file)) {
4005 put_unused_fd(r);
4006 r = PTR_ERR(file);
4007 goto put_kvm;
4008 }
4009
4010 /*
4011 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4012 * already set, with ->release() being kvm_vm_release(). In error
4013 * cases it will be called by the final fput(file) and will take
4014 * care of doing kvm_put_kvm(kvm).
4015 */
4016 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4017 put_unused_fd(r);
4018 fput(file);
4019 return -ENOMEM;
4020 }
4021 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4022
4023 fd_install(r, file);
4024 return r;
4025
4026put_kvm:
4027 kvm_put_kvm(kvm);
4028 return r;
4029}
4030
4031static long kvm_dev_ioctl(struct file *filp,
4032 unsigned int ioctl, unsigned long arg)
4033{
4034 long r = -EINVAL;
4035
4036 switch (ioctl) {
4037 case KVM_GET_API_VERSION:
4038 if (arg)
4039 goto out;
4040 r = KVM_API_VERSION;
4041 break;
4042 case KVM_CREATE_VM:
4043 r = kvm_dev_ioctl_create_vm(arg);
4044 break;
4045 case KVM_CHECK_EXTENSION:
4046 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4047 break;
4048 case KVM_GET_VCPU_MMAP_SIZE:
4049 if (arg)
4050 goto out;
4051 r = PAGE_SIZE; /* struct kvm_run */
4052#ifdef CONFIG_X86
4053 r += PAGE_SIZE; /* pio data page */
4054#endif
4055#ifdef CONFIG_KVM_MMIO
4056 r += PAGE_SIZE; /* coalesced mmio ring page */
4057#endif
4058 break;
4059 case KVM_TRACE_ENABLE:
4060 case KVM_TRACE_PAUSE:
4061 case KVM_TRACE_DISABLE:
4062 r = -EOPNOTSUPP;
4063 break;
4064 default:
4065 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4066 }
4067out:
4068 return r;
4069}
4070
4071static struct file_operations kvm_chardev_ops = {
4072 .unlocked_ioctl = kvm_dev_ioctl,
4073 .llseek = noop_llseek,
4074 KVM_COMPAT(kvm_dev_ioctl),
4075};
4076
4077static struct miscdevice kvm_dev = {
4078 KVM_MINOR,
4079 "kvm",
4080 &kvm_chardev_ops,
4081};
4082
4083static void hardware_enable_nolock(void *junk)
4084{
4085 int cpu = raw_smp_processor_id();
4086 int r;
4087
4088 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4089 return;
4090
4091 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4092
4093 r = kvm_arch_hardware_enable();
4094
4095 if (r) {
4096 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4097 atomic_inc(&hardware_enable_failed);
4098 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4099 }
4100}
4101
4102static int kvm_starting_cpu(unsigned int cpu)
4103{
4104 raw_spin_lock(&kvm_count_lock);
4105 if (kvm_usage_count)
4106 hardware_enable_nolock(NULL);
4107 raw_spin_unlock(&kvm_count_lock);
4108 return 0;
4109}
4110
4111static void hardware_disable_nolock(void *junk)
4112{
4113 int cpu = raw_smp_processor_id();
4114
4115 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4116 return;
4117 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4118 kvm_arch_hardware_disable();
4119}
4120
4121static int kvm_dying_cpu(unsigned int cpu)
4122{
4123 raw_spin_lock(&kvm_count_lock);
4124 if (kvm_usage_count)
4125 hardware_disable_nolock(NULL);
4126 raw_spin_unlock(&kvm_count_lock);
4127 return 0;
4128}
4129
4130static void hardware_disable_all_nolock(void)
4131{
4132 BUG_ON(!kvm_usage_count);
4133
4134 kvm_usage_count--;
4135 if (!kvm_usage_count)
4136 on_each_cpu(hardware_disable_nolock, NULL, 1);
4137}
4138
4139static void hardware_disable_all(void)
4140{
4141 raw_spin_lock(&kvm_count_lock);
4142 hardware_disable_all_nolock();
4143 raw_spin_unlock(&kvm_count_lock);
4144}
4145
4146static int hardware_enable_all(void)
4147{
4148 int r = 0;
4149
4150 raw_spin_lock(&kvm_count_lock);
4151
4152 kvm_usage_count++;
4153 if (kvm_usage_count == 1) {
4154 atomic_set(&hardware_enable_failed, 0);
4155 on_each_cpu(hardware_enable_nolock, NULL, 1);
4156
4157 if (atomic_read(&hardware_enable_failed)) {
4158 hardware_disable_all_nolock();
4159 r = -EBUSY;
4160 }
4161 }
4162
4163 raw_spin_unlock(&kvm_count_lock);
4164
4165 return r;
4166}
4167
4168static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4169 void *v)
4170{
4171 /*
4172 * Some (well, at least mine) BIOSes hang on reboot if
4173 * in vmx root mode.
4174 *
4175 * And Intel TXT required VMX off for all cpu when system shutdown.
4176 */
4177 pr_info("kvm: exiting hardware virtualization\n");
4178 kvm_rebooting = true;
4179 on_each_cpu(hardware_disable_nolock, NULL, 1);
4180 return NOTIFY_OK;
4181}
4182
4183static struct notifier_block kvm_reboot_notifier = {
4184 .notifier_call = kvm_reboot,
4185 .priority = 0,
4186};
4187
4188static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4189{
4190 int i;
4191
4192 for (i = 0; i < bus->dev_count; i++) {
4193 struct kvm_io_device *pos = bus->range[i].dev;
4194
4195 kvm_iodevice_destructor(pos);
4196 }
4197 kfree(bus);
4198}
4199
4200static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4201 const struct kvm_io_range *r2)
4202{
4203 gpa_t addr1 = r1->addr;
4204 gpa_t addr2 = r2->addr;
4205
4206 if (addr1 < addr2)
4207 return -1;
4208
4209 /* If r2->len == 0, match the exact address. If r2->len != 0,
4210 * accept any overlapping write. Any order is acceptable for
4211 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4212 * we process all of them.
4213 */
4214 if (r2->len) {
4215 addr1 += r1->len;
4216 addr2 += r2->len;
4217 }
4218
4219 if (addr1 > addr2)
4220 return 1;
4221
4222 return 0;
4223}
4224
4225static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4226{
4227 return kvm_io_bus_cmp(p1, p2);
4228}
4229
4230static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4231 gpa_t addr, int len)
4232{
4233 struct kvm_io_range *range, key;
4234 int off;
4235
4236 key = (struct kvm_io_range) {
4237 .addr = addr,
4238 .len = len,
4239 };
4240
4241 range = bsearch(&key, bus->range, bus->dev_count,
4242 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4243 if (range == NULL)
4244 return -ENOENT;
4245
4246 off = range - bus->range;
4247
4248 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
4249 off--;
4250
4251 return off;
4252}
4253
4254static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4255 struct kvm_io_range *range, const void *val)
4256{
4257 int idx;
4258
4259 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4260 if (idx < 0)
4261 return -EOPNOTSUPP;
4262
4263 while (idx < bus->dev_count &&
4264 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4265 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
4266 range->len, val))
4267 return idx;
4268 idx++;
4269 }
4270
4271 return -EOPNOTSUPP;
4272}
4273
4274/* kvm_io_bus_write - called under kvm->slots_lock */
4275int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4276 int len, const void *val)
4277{
4278 struct kvm_io_bus *bus;
4279 struct kvm_io_range range;
4280 int r;
4281
4282 range = (struct kvm_io_range) {
4283 .addr = addr,
4284 .len = len,
4285 };
4286
4287 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4288 if (!bus)
4289 return -ENOMEM;
4290 r = __kvm_io_bus_write(vcpu, bus, &range, val);
4291 return r < 0 ? r : 0;
4292}
David Brazdil0f672f62019-12-10 10:32:29 +00004293EXPORT_SYMBOL_GPL(kvm_io_bus_write);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004294
4295/* kvm_io_bus_write_cookie - called under kvm->slots_lock */
4296int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4297 gpa_t addr, int len, const void *val, long cookie)
4298{
4299 struct kvm_io_bus *bus;
4300 struct kvm_io_range range;
4301
4302 range = (struct kvm_io_range) {
4303 .addr = addr,
4304 .len = len,
4305 };
4306
4307 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4308 if (!bus)
4309 return -ENOMEM;
4310
4311 /* First try the device referenced by cookie. */
4312 if ((cookie >= 0) && (cookie < bus->dev_count) &&
4313 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
4314 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
4315 val))
4316 return cookie;
4317
4318 /*
4319 * cookie contained garbage; fall back to search and return the
4320 * correct cookie value.
4321 */
4322 return __kvm_io_bus_write(vcpu, bus, &range, val);
4323}
4324
4325static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4326 struct kvm_io_range *range, void *val)
4327{
4328 int idx;
4329
4330 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4331 if (idx < 0)
4332 return -EOPNOTSUPP;
4333
4334 while (idx < bus->dev_count &&
4335 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4336 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4337 range->len, val))
4338 return idx;
4339 idx++;
4340 }
4341
4342 return -EOPNOTSUPP;
4343}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004344
4345/* kvm_io_bus_read - called under kvm->slots_lock */
4346int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4347 int len, void *val)
4348{
4349 struct kvm_io_bus *bus;
4350 struct kvm_io_range range;
4351 int r;
4352
4353 range = (struct kvm_io_range) {
4354 .addr = addr,
4355 .len = len,
4356 };
4357
4358 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4359 if (!bus)
4360 return -ENOMEM;
4361 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4362 return r < 0 ? r : 0;
4363}
4364
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004365/* Caller must hold slots_lock. */
4366int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4367 int len, struct kvm_io_device *dev)
4368{
4369 int i;
4370 struct kvm_io_bus *new_bus, *bus;
4371 struct kvm_io_range range;
4372
4373 bus = kvm_get_bus(kvm, bus_idx);
4374 if (!bus)
4375 return -ENOMEM;
4376
4377 /* exclude ioeventfd which is limited by maximum fd */
4378 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
4379 return -ENOSPC;
4380
David Brazdil0f672f62019-12-10 10:32:29 +00004381 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
4382 GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004383 if (!new_bus)
4384 return -ENOMEM;
4385
4386 range = (struct kvm_io_range) {
4387 .addr = addr,
4388 .len = len,
4389 .dev = dev,
4390 };
4391
4392 for (i = 0; i < bus->dev_count; i++)
4393 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4394 break;
4395
4396 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4397 new_bus->dev_count++;
4398 new_bus->range[i] = range;
4399 memcpy(new_bus->range + i + 1, bus->range + i,
4400 (bus->dev_count - i) * sizeof(struct kvm_io_range));
4401 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4402 synchronize_srcu_expedited(&kvm->srcu);
4403 kfree(bus);
4404
4405 return 0;
4406}
4407
4408/* Caller must hold slots_lock. */
Olivier Deprez0e641232021-09-23 10:07:05 +02004409int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4410 struct kvm_io_device *dev)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004411{
Olivier Deprez0e641232021-09-23 10:07:05 +02004412 int i, j;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004413 struct kvm_io_bus *new_bus, *bus;
4414
4415 bus = kvm_get_bus(kvm, bus_idx);
4416 if (!bus)
Olivier Deprez0e641232021-09-23 10:07:05 +02004417 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004418
4419 for (i = 0; i < bus->dev_count; i++)
4420 if (bus->range[i].dev == dev) {
4421 break;
4422 }
4423
4424 if (i == bus->dev_count)
Olivier Deprez0e641232021-09-23 10:07:05 +02004425 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004426
David Brazdil0f672f62019-12-10 10:32:29 +00004427 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
4428 GFP_KERNEL_ACCOUNT);
Olivier Deprez0e641232021-09-23 10:07:05 +02004429 if (new_bus) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004430 memcpy(new_bus, bus, struct_size(bus, range, i));
Olivier Deprez0e641232021-09-23 10:07:05 +02004431 new_bus->dev_count--;
4432 memcpy(new_bus->range + i, bus->range + i + 1,
Olivier Deprez157378f2022-04-04 15:47:50 +02004433 flex_array_size(new_bus, range, new_bus->dev_count - i));
4434 }
4435
4436 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4437 synchronize_srcu_expedited(&kvm->srcu);
4438
4439 /* Destroy the old bus _after_ installing the (null) bus. */
4440 if (!new_bus) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004441 pr_err("kvm: failed to shrink bus, removing it completely\n");
Olivier Deprez0e641232021-09-23 10:07:05 +02004442 for (j = 0; j < bus->dev_count; j++) {
4443 if (j == i)
4444 continue;
4445 kvm_iodevice_destructor(bus->range[j].dev);
4446 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004447 }
4448
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004449 kfree(bus);
Olivier Deprez0e641232021-09-23 10:07:05 +02004450 return new_bus ? 0 : -ENOMEM;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004451}
4452
4453struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4454 gpa_t addr)
4455{
4456 struct kvm_io_bus *bus;
4457 int dev_idx, srcu_idx;
4458 struct kvm_io_device *iodev = NULL;
4459
4460 srcu_idx = srcu_read_lock(&kvm->srcu);
4461
4462 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
4463 if (!bus)
4464 goto out_unlock;
4465
4466 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
4467 if (dev_idx < 0)
4468 goto out_unlock;
4469
4470 iodev = bus->range[dev_idx].dev;
4471
4472out_unlock:
4473 srcu_read_unlock(&kvm->srcu, srcu_idx);
4474
4475 return iodev;
4476}
4477EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4478
4479static int kvm_debugfs_open(struct inode *inode, struct file *file,
4480 int (*get)(void *, u64 *), int (*set)(void *, u64),
4481 const char *fmt)
4482{
4483 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4484 inode->i_private;
4485
4486 /* The debugfs files are a reference to the kvm struct which
4487 * is still valid when kvm_destroy_vm is called.
4488 * To avoid the race between open and the removal of the debugfs
4489 * directory we test against the users count.
4490 */
4491 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
4492 return -ENOENT;
4493
David Brazdil0f672f62019-12-10 10:32:29 +00004494 if (simple_attr_open(inode, file, get,
Olivier Deprez157378f2022-04-04 15:47:50 +02004495 KVM_DBGFS_GET_MODE(stat_data->dbgfs_item) & 0222
4496 ? set : NULL,
4497 fmt)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004498 kvm_put_kvm(stat_data->kvm);
4499 return -ENOMEM;
4500 }
4501
4502 return 0;
4503}
4504
4505static int kvm_debugfs_release(struct inode *inode, struct file *file)
4506{
4507 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4508 inode->i_private;
4509
4510 simple_attr_release(inode, file);
4511 kvm_put_kvm(stat_data->kvm);
4512
4513 return 0;
4514}
4515
Olivier Deprez157378f2022-04-04 15:47:50 +02004516static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004517{
Olivier Deprez157378f2022-04-04 15:47:50 +02004518 *val = *(ulong *)((void *)kvm + offset);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004519
4520 return 0;
4521}
4522
Olivier Deprez157378f2022-04-04 15:47:50 +02004523static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004524{
Olivier Deprez157378f2022-04-04 15:47:50 +02004525 *(ulong *)((void *)kvm + offset) = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004526
4527 return 0;
4528}
4529
Olivier Deprez157378f2022-04-04 15:47:50 +02004530static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004531{
4532 int i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004533 struct kvm_vcpu *vcpu;
4534
4535 *val = 0;
4536
Olivier Deprez157378f2022-04-04 15:47:50 +02004537 kvm_for_each_vcpu(i, vcpu, kvm)
4538 *val += *(u64 *)((void *)vcpu + offset);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004539
4540 return 0;
4541}
4542
Olivier Deprez157378f2022-04-04 15:47:50 +02004543static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004544{
4545 int i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004546 struct kvm_vcpu *vcpu;
4547
Olivier Deprez157378f2022-04-04 15:47:50 +02004548 kvm_for_each_vcpu(i, vcpu, kvm)
4549 *(u64 *)((void *)vcpu + offset) = 0;
4550
4551 return 0;
4552}
4553
4554static int kvm_stat_data_get(void *data, u64 *val)
4555{
4556 int r = -EFAULT;
4557 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4558
4559 switch (stat_data->dbgfs_item->kind) {
4560 case KVM_STAT_VM:
4561 r = kvm_get_stat_per_vm(stat_data->kvm,
4562 stat_data->dbgfs_item->offset, val);
4563 break;
4564 case KVM_STAT_VCPU:
4565 r = kvm_get_stat_per_vcpu(stat_data->kvm,
4566 stat_data->dbgfs_item->offset, val);
4567 break;
4568 }
4569
4570 return r;
4571}
4572
4573static int kvm_stat_data_clear(void *data, u64 val)
4574{
4575 int r = -EFAULT;
4576 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4577
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004578 if (val)
4579 return -EINVAL;
4580
Olivier Deprez157378f2022-04-04 15:47:50 +02004581 switch (stat_data->dbgfs_item->kind) {
4582 case KVM_STAT_VM:
4583 r = kvm_clear_stat_per_vm(stat_data->kvm,
4584 stat_data->dbgfs_item->offset);
4585 break;
4586 case KVM_STAT_VCPU:
4587 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
4588 stat_data->dbgfs_item->offset);
4589 break;
4590 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004591
Olivier Deprez157378f2022-04-04 15:47:50 +02004592 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004593}
4594
Olivier Deprez157378f2022-04-04 15:47:50 +02004595static int kvm_stat_data_open(struct inode *inode, struct file *file)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004596{
4597 __simple_attr_check_format("%llu\n", 0ull);
Olivier Deprez157378f2022-04-04 15:47:50 +02004598 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
4599 kvm_stat_data_clear, "%llu\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004600}
4601
Olivier Deprez157378f2022-04-04 15:47:50 +02004602static const struct file_operations stat_fops_per_vm = {
4603 .owner = THIS_MODULE,
4604 .open = kvm_stat_data_open,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004605 .release = kvm_debugfs_release,
Olivier Deprez157378f2022-04-04 15:47:50 +02004606 .read = simple_attr_read,
4607 .write = simple_attr_write,
4608 .llseek = no_llseek,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004609};
4610
4611static int vm_stat_get(void *_offset, u64 *val)
4612{
4613 unsigned offset = (long)_offset;
4614 struct kvm *kvm;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004615 u64 tmp_val;
4616
4617 *val = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00004618 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004619 list_for_each_entry(kvm, &vm_list, vm_list) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004620 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004621 *val += tmp_val;
4622 }
David Brazdil0f672f62019-12-10 10:32:29 +00004623 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004624 return 0;
4625}
4626
4627static int vm_stat_clear(void *_offset, u64 val)
4628{
4629 unsigned offset = (long)_offset;
4630 struct kvm *kvm;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004631
4632 if (val)
4633 return -EINVAL;
4634
David Brazdil0f672f62019-12-10 10:32:29 +00004635 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004636 list_for_each_entry(kvm, &vm_list, vm_list) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004637 kvm_clear_stat_per_vm(kvm, offset);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004638 }
David Brazdil0f672f62019-12-10 10:32:29 +00004639 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004640
4641 return 0;
4642}
4643
4644DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
4645
4646static int vcpu_stat_get(void *_offset, u64 *val)
4647{
4648 unsigned offset = (long)_offset;
4649 struct kvm *kvm;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004650 u64 tmp_val;
4651
4652 *val = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00004653 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004654 list_for_each_entry(kvm, &vm_list, vm_list) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004655 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004656 *val += tmp_val;
4657 }
David Brazdil0f672f62019-12-10 10:32:29 +00004658 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004659 return 0;
4660}
4661
4662static int vcpu_stat_clear(void *_offset, u64 val)
4663{
4664 unsigned offset = (long)_offset;
4665 struct kvm *kvm;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004666
4667 if (val)
4668 return -EINVAL;
4669
David Brazdil0f672f62019-12-10 10:32:29 +00004670 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004671 list_for_each_entry(kvm, &vm_list, vm_list) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004672 kvm_clear_stat_per_vcpu(kvm, offset);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004673 }
David Brazdil0f672f62019-12-10 10:32:29 +00004674 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004675
4676 return 0;
4677}
4678
4679DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4680 "%llu\n");
4681
4682static const struct file_operations *stat_fops[] = {
4683 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4684 [KVM_STAT_VM] = &vm_stat_fops,
4685};
4686
4687static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4688{
4689 struct kobj_uevent_env *env;
4690 unsigned long long created, active;
4691
4692 if (!kvm_dev.this_device || !kvm)
4693 return;
4694
David Brazdil0f672f62019-12-10 10:32:29 +00004695 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004696 if (type == KVM_EVENT_CREATE_VM) {
4697 kvm_createvm_count++;
4698 kvm_active_vms++;
4699 } else if (type == KVM_EVENT_DESTROY_VM) {
4700 kvm_active_vms--;
4701 }
4702 created = kvm_createvm_count;
4703 active = kvm_active_vms;
David Brazdil0f672f62019-12-10 10:32:29 +00004704 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004705
David Brazdil0f672f62019-12-10 10:32:29 +00004706 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004707 if (!env)
4708 return;
4709
4710 add_uevent_var(env, "CREATED=%llu", created);
4711 add_uevent_var(env, "COUNT=%llu", active);
4712
4713 if (type == KVM_EVENT_CREATE_VM) {
4714 add_uevent_var(env, "EVENT=create");
4715 kvm->userspace_pid = task_pid_nr(current);
4716 } else if (type == KVM_EVENT_DESTROY_VM) {
4717 add_uevent_var(env, "EVENT=destroy");
4718 }
4719 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
4720
Olivier Deprez0e641232021-09-23 10:07:05 +02004721 if (kvm->debugfs_dentry) {
David Brazdil0f672f62019-12-10 10:32:29 +00004722 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004723
4724 if (p) {
4725 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4726 if (!IS_ERR(tmp))
4727 add_uevent_var(env, "STATS_PATH=%s", tmp);
4728 kfree(p);
4729 }
4730 }
4731 /* no need for checks, since we are adding at most only 5 keys */
4732 env->envp[env->envp_idx++] = NULL;
4733 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4734 kfree(env);
4735}
4736
4737static void kvm_init_debug(void)
4738{
4739 struct kvm_stats_debugfs_item *p;
4740
4741 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4742
4743 kvm_debugfs_num_entries = 0;
4744 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004745 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
4746 kvm_debugfs_dir, (void *)(long)p->offset,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004747 stat_fops[p->kind]);
4748 }
4749}
4750
4751static int kvm_suspend(void)
4752{
4753 if (kvm_usage_count)
4754 hardware_disable_nolock(NULL);
4755 return 0;
4756}
4757
4758static void kvm_resume(void)
4759{
4760 if (kvm_usage_count) {
David Brazdil0f672f62019-12-10 10:32:29 +00004761#ifdef CONFIG_LOCKDEP
4762 WARN_ON(lockdep_is_held(&kvm_count_lock));
4763#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004764 hardware_enable_nolock(NULL);
4765 }
4766}
4767
4768static struct syscore_ops kvm_syscore_ops = {
4769 .suspend = kvm_suspend,
4770 .resume = kvm_resume,
4771};
4772
4773static inline
4774struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4775{
4776 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4777}
4778
4779static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4780{
4781 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4782
David Brazdil0f672f62019-12-10 10:32:29 +00004783 WRITE_ONCE(vcpu->preempted, false);
4784 WRITE_ONCE(vcpu->ready, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004785
Olivier Deprez157378f2022-04-04 15:47:50 +02004786 __this_cpu_write(kvm_running_vcpu, vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004787 kvm_arch_sched_in(vcpu, cpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004788 kvm_arch_vcpu_load(vcpu, cpu);
4789}
4790
4791static void kvm_sched_out(struct preempt_notifier *pn,
4792 struct task_struct *next)
4793{
4794 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4795
David Brazdil0f672f62019-12-10 10:32:29 +00004796 if (current->state == TASK_RUNNING) {
4797 WRITE_ONCE(vcpu->preempted, true);
4798 WRITE_ONCE(vcpu->ready, true);
4799 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004800 kvm_arch_vcpu_put(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02004801 __this_cpu_write(kvm_running_vcpu, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004802}
4803
Olivier Deprez157378f2022-04-04 15:47:50 +02004804/**
4805 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
4806 *
4807 * We can disable preemption locally around accessing the per-CPU variable,
4808 * and use the resolved vcpu pointer after enabling preemption again,
4809 * because even if the current thread is migrated to another CPU, reading
4810 * the per-CPU value later will give us the same value as we update the
4811 * per-CPU variable in the preempt notifier handlers.
4812 */
4813struct kvm_vcpu *kvm_get_running_vcpu(void)
David Brazdil0f672f62019-12-10 10:32:29 +00004814{
Olivier Deprez157378f2022-04-04 15:47:50 +02004815 struct kvm_vcpu *vcpu;
4816
4817 preempt_disable();
4818 vcpu = __this_cpu_read(kvm_running_vcpu);
4819 preempt_enable();
4820
4821 return vcpu;
4822}
4823EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
4824
4825/**
4826 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
4827 */
4828struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
4829{
4830 return &kvm_running_vcpu;
4831}
4832
4833struct kvm_cpu_compat_check {
4834 void *opaque;
4835 int *ret;
4836};
4837
4838static void check_processor_compat(void *data)
4839{
4840 struct kvm_cpu_compat_check *c = data;
4841
4842 *c->ret = kvm_arch_check_processor_compat(c->opaque);
David Brazdil0f672f62019-12-10 10:32:29 +00004843}
4844
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004845int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
4846 struct module *module)
4847{
Olivier Deprez157378f2022-04-04 15:47:50 +02004848 struct kvm_cpu_compat_check c;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004849 int r;
4850 int cpu;
4851
4852 r = kvm_arch_init(opaque);
4853 if (r)
4854 goto out_fail;
4855
4856 /*
4857 * kvm_arch_init makes sure there's at most one caller
4858 * for architectures that support multiple implementations,
4859 * like intel and amd on x86.
4860 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4861 * conflicts in case kvm is already setup for another implementation.
4862 */
4863 r = kvm_irqfd_init();
4864 if (r)
4865 goto out_irqfd;
4866
4867 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
4868 r = -ENOMEM;
4869 goto out_free_0;
4870 }
4871
Olivier Deprez157378f2022-04-04 15:47:50 +02004872 r = kvm_arch_hardware_setup(opaque);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004873 if (r < 0)
Olivier Deprez157378f2022-04-04 15:47:50 +02004874 goto out_free_1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004875
Olivier Deprez157378f2022-04-04 15:47:50 +02004876 c.ret = &r;
4877 c.opaque = opaque;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004878 for_each_online_cpu(cpu) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004879 smp_call_function_single(cpu, check_processor_compat, &c, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004880 if (r < 0)
Olivier Deprez157378f2022-04-04 15:47:50 +02004881 goto out_free_2;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004882 }
4883
4884 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
4885 kvm_starting_cpu, kvm_dying_cpu);
4886 if (r)
4887 goto out_free_2;
4888 register_reboot_notifier(&kvm_reboot_notifier);
4889
4890 /* A kmem cache lets us meet the alignment requirements of fx_save. */
4891 if (!vcpu_align)
4892 vcpu_align = __alignof__(struct kvm_vcpu);
4893 kvm_vcpu_cache =
4894 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4895 SLAB_ACCOUNT,
4896 offsetof(struct kvm_vcpu, arch),
4897 sizeof_field(struct kvm_vcpu, arch),
4898 NULL);
4899 if (!kvm_vcpu_cache) {
4900 r = -ENOMEM;
4901 goto out_free_3;
4902 }
4903
4904 r = kvm_async_pf_init();
4905 if (r)
4906 goto out_free;
4907
4908 kvm_chardev_ops.owner = module;
4909 kvm_vm_fops.owner = module;
4910 kvm_vcpu_fops.owner = module;
4911
4912 r = misc_register(&kvm_dev);
4913 if (r) {
4914 pr_err("kvm: misc device register failed\n");
4915 goto out_unreg;
4916 }
4917
4918 register_syscore_ops(&kvm_syscore_ops);
4919
4920 kvm_preempt_ops.sched_in = kvm_sched_in;
4921 kvm_preempt_ops.sched_out = kvm_sched_out;
4922
4923 kvm_init_debug();
4924
4925 r = kvm_vfio_ops_init();
4926 WARN_ON(r);
4927
4928 return 0;
4929
4930out_unreg:
4931 kvm_async_pf_deinit();
4932out_free:
4933 kmem_cache_destroy(kvm_vcpu_cache);
4934out_free_3:
4935 unregister_reboot_notifier(&kvm_reboot_notifier);
4936 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4937out_free_2:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004938 kvm_arch_hardware_unsetup();
Olivier Deprez157378f2022-04-04 15:47:50 +02004939out_free_1:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004940 free_cpumask_var(cpus_hardware_enabled);
4941out_free_0:
4942 kvm_irqfd_exit();
4943out_irqfd:
4944 kvm_arch_exit();
4945out_fail:
4946 return r;
4947}
4948EXPORT_SYMBOL_GPL(kvm_init);
4949
4950void kvm_exit(void)
4951{
4952 debugfs_remove_recursive(kvm_debugfs_dir);
4953 misc_deregister(&kvm_dev);
4954 kmem_cache_destroy(kvm_vcpu_cache);
4955 kvm_async_pf_deinit();
4956 unregister_syscore_ops(&kvm_syscore_ops);
4957 unregister_reboot_notifier(&kvm_reboot_notifier);
4958 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4959 on_each_cpu(hardware_disable_nolock, NULL, 1);
4960 kvm_arch_hardware_unsetup();
4961 kvm_arch_exit();
4962 kvm_irqfd_exit();
4963 free_cpumask_var(cpus_hardware_enabled);
4964 kvm_vfio_ops_exit();
4965}
4966EXPORT_SYMBOL_GPL(kvm_exit);
David Brazdil0f672f62019-12-10 10:32:29 +00004967
4968struct kvm_vm_worker_thread_context {
4969 struct kvm *kvm;
4970 struct task_struct *parent;
4971 struct completion init_done;
4972 kvm_vm_thread_fn_t thread_fn;
4973 uintptr_t data;
4974 int err;
4975};
4976
4977static int kvm_vm_worker_thread(void *context)
4978{
4979 /*
4980 * The init_context is allocated on the stack of the parent thread, so
4981 * we have to locally copy anything that is needed beyond initialization
4982 */
4983 struct kvm_vm_worker_thread_context *init_context = context;
4984 struct kvm *kvm = init_context->kvm;
4985 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4986 uintptr_t data = init_context->data;
4987 int err;
4988
4989 err = kthread_park(current);
4990 /* kthread_park(current) is never supposed to return an error */
4991 WARN_ON(err != 0);
4992 if (err)
4993 goto init_complete;
4994
4995 err = cgroup_attach_task_all(init_context->parent, current);
4996 if (err) {
4997 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4998 __func__, err);
4999 goto init_complete;
5000 }
5001
5002 set_user_nice(current, task_nice(init_context->parent));
5003
5004init_complete:
5005 init_context->err = err;
5006 complete(&init_context->init_done);
5007 init_context = NULL;
5008
5009 if (err)
5010 return err;
5011
5012 /* Wait to be woken up by the spawner before proceeding. */
5013 kthread_parkme();
5014
5015 if (!kthread_should_stop())
5016 err = thread_fn(kvm, data);
5017
5018 return err;
5019}
5020
5021int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5022 uintptr_t data, const char *name,
5023 struct task_struct **thread_ptr)
5024{
5025 struct kvm_vm_worker_thread_context init_context = {};
5026 struct task_struct *thread;
5027
5028 *thread_ptr = NULL;
5029 init_context.kvm = kvm;
5030 init_context.parent = current;
5031 init_context.thread_fn = thread_fn;
5032 init_context.data = data;
5033 init_completion(&init_context.init_done);
5034
5035 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5036 "%s-%d", name, task_pid_nr(current));
5037 if (IS_ERR(thread))
5038 return PTR_ERR(thread);
5039
5040 /* kthread_run is never supposed to return NULL */
5041 WARN_ON(thread == NULL);
5042
5043 wait_for_completion(&init_context.init_done);
5044
5045 if (!init_context.err)
5046 *thread_ptr = thread;
5047
5048 return init_context.err;
5049}