blob: fc48298649c6cab15c1dd7c27091d63b17d621f1 [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>
58#include <asm/pgtable.h>
59
60#include "coalesced_mmio.h"
61#include "async_pf.h"
62#include "vfio.h"
63
64#define CREATE_TRACE_POINTS
65#include <trace/events/kvm.h>
66
67/* Worst case buffer size needed for holding an integer. */
68#define ITOA_MAX_LEN 12
69
70MODULE_AUTHOR("Qumranet");
71MODULE_LICENSE("GPL");
72
73/* Architectures should define their poll value according to the halt latency */
74unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
75module_param(halt_poll_ns, uint, 0644);
76EXPORT_SYMBOL_GPL(halt_poll_ns);
77
78/* Default doubles per-vcpu halt_poll_ns. */
79unsigned int halt_poll_ns_grow = 2;
80module_param(halt_poll_ns_grow, uint, 0644);
81EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
82
David Brazdil0f672f62019-12-10 10:32:29 +000083/* The start value to grow halt_poll_ns from */
84unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
85module_param(halt_poll_ns_grow_start, uint, 0644);
86EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
87
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000088/* Default resets per-vcpu halt_poll_ns . */
89unsigned int halt_poll_ns_shrink;
90module_param(halt_poll_ns_shrink, uint, 0644);
91EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
92
93/*
94 * Ordering of locks:
95 *
96 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
97 */
98
David Brazdil0f672f62019-12-10 10:32:29 +000099DEFINE_MUTEX(kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000100static DEFINE_RAW_SPINLOCK(kvm_count_lock);
101LIST_HEAD(vm_list);
102
103static cpumask_var_t cpus_hardware_enabled;
104static int kvm_usage_count;
105static atomic_t hardware_enable_failed;
106
107struct kmem_cache *kvm_vcpu_cache;
108EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
109
110static __read_mostly struct preempt_ops kvm_preempt_ops;
111
112struct dentry *kvm_debugfs_dir;
113EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
114
115static int kvm_debugfs_num_entries;
116static const struct file_operations *stat_fops_per_vm[];
117
118static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
119 unsigned long arg);
120#ifdef CONFIG_KVM_COMPAT
121static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
122 unsigned long arg);
123#define KVM_COMPAT(c) .compat_ioctl = (c)
124#else
David Brazdil0f672f62019-12-10 10:32:29 +0000125/*
126 * For architectures that don't implement a compat infrastructure,
127 * adopt a double line of defense:
128 * - Prevent a compat task from opening /dev/kvm
129 * - If the open has been done by a 64bit task, and the KVM fd
130 * passed to a compat task, let the ioctls fail.
131 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000132static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
133 unsigned long arg) { return -EINVAL; }
David Brazdil0f672f62019-12-10 10:32:29 +0000134
135static int kvm_no_compat_open(struct inode *inode, struct file *file)
136{
137 return is_compat_task() ? -ENODEV : 0;
138}
139#define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
140 .open = kvm_no_compat_open
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000141#endif
142static int hardware_enable_all(void);
143static void hardware_disable_all(void);
144
145static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
146
147static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
148
149__visible bool kvm_rebooting;
150EXPORT_SYMBOL_GPL(kvm_rebooting);
151
152static bool largepages_enabled = true;
153
154#define KVM_EVENT_CREATE_VM 0
155#define KVM_EVENT_DESTROY_VM 1
156static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
157static unsigned long long kvm_createvm_count;
158static unsigned long long kvm_active_vms;
159
Olivier Deprez0e641232021-09-23 10:07:05 +0200160__weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
161 unsigned long start, unsigned long end)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000162{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000163}
164
David Brazdil0f672f62019-12-10 10:32:29 +0000165bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
166{
167 /*
168 * The metadata used by is_zone_device_page() to determine whether or
169 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
170 * the device has been pinned, e.g. by get_user_pages(). WARN if the
171 * page_count() is zero to help detect bad usage of this helper.
172 */
173 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
174 return false;
175
176 return is_zone_device_page(pfn_to_page(pfn));
177}
178
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000179bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
180{
David Brazdil0f672f62019-12-10 10:32:29 +0000181 /*
182 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
183 * perspective they are "normal" pages, albeit with slightly different
184 * usage rules.
185 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000186 if (pfn_valid(pfn))
David Brazdil0f672f62019-12-10 10:32:29 +0000187 return PageReserved(pfn_to_page(pfn)) &&
Olivier Deprez0e641232021-09-23 10:07:05 +0200188 !is_zero_pfn(pfn) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000189 !kvm_is_zone_device_pfn(pfn);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000190
191 return true;
192}
193
194/*
195 * Switches to specified vcpu, until a matching vcpu_put()
196 */
197void vcpu_load(struct kvm_vcpu *vcpu)
198{
199 int cpu = get_cpu();
200 preempt_notifier_register(&vcpu->preempt_notifier);
201 kvm_arch_vcpu_load(vcpu, cpu);
202 put_cpu();
203}
204EXPORT_SYMBOL_GPL(vcpu_load);
205
206void vcpu_put(struct kvm_vcpu *vcpu)
207{
208 preempt_disable();
209 kvm_arch_vcpu_put(vcpu);
210 preempt_notifier_unregister(&vcpu->preempt_notifier);
211 preempt_enable();
212}
213EXPORT_SYMBOL_GPL(vcpu_put);
214
215/* TODO: merge with kvm_arch_vcpu_should_kick */
216static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
217{
218 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
219
220 /*
221 * We need to wait for the VCPU to reenable interrupts and get out of
222 * READING_SHADOW_PAGE_TABLES mode.
223 */
224 if (req & KVM_REQUEST_WAIT)
225 return mode != OUTSIDE_GUEST_MODE;
226
227 /*
228 * Need to kick a running VCPU, but otherwise there is nothing to do.
229 */
230 return mode == IN_GUEST_MODE;
231}
232
233static void ack_flush(void *_completed)
234{
235}
236
237static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
238{
239 if (unlikely(!cpus))
240 cpus = cpu_online_mask;
241
242 if (cpumask_empty(cpus))
243 return false;
244
245 smp_call_function_many(cpus, ack_flush, NULL, wait);
246 return true;
247}
248
249bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
250 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
251{
252 int i, cpu, me;
253 struct kvm_vcpu *vcpu;
254 bool called;
255
256 me = get_cpu();
257
258 kvm_for_each_vcpu(i, vcpu, kvm) {
David Brazdil0f672f62019-12-10 10:32:29 +0000259 if (vcpu_bitmap && !test_bit(i, vcpu_bitmap))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000260 continue;
261
262 kvm_make_request(req, vcpu);
263 cpu = vcpu->cpu;
264
265 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
266 continue;
267
268 if (tmp != NULL && cpu != -1 && cpu != me &&
269 kvm_request_needs_ipi(vcpu, req))
270 __cpumask_set_cpu(cpu, tmp);
271 }
272
273 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
274 put_cpu();
275
276 return called;
277}
278
279bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
280{
281 cpumask_var_t cpus;
282 bool called;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000283
284 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
285
David Brazdil0f672f62019-12-10 10:32:29 +0000286 called = kvm_make_vcpus_request_mask(kvm, req, NULL, cpus);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000287
288 free_cpumask_var(cpus);
289 return called;
290}
291
292#ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
293void kvm_flush_remote_tlbs(struct kvm *kvm)
294{
295 /*
296 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
297 * kvm_make_all_cpus_request.
298 */
299 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
300
301 /*
302 * We want to publish modifications to the page tables before reading
303 * mode. Pairs with a memory barrier in arch-specific code.
304 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
305 * and smp_mb in walk_shadow_page_lockless_begin/end.
306 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
307 *
308 * There is already an smp_mb__after_atomic() before
309 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
310 * barrier here.
311 */
312 if (!kvm_arch_flush_remote_tlb(kvm)
313 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
314 ++kvm->stat.remote_tlb_flush;
315 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
316}
317EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
318#endif
319
320void kvm_reload_remote_mmus(struct kvm *kvm)
321{
322 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
323}
324
325int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
326{
327 struct page *page;
328 int r;
329
330 mutex_init(&vcpu->mutex);
331 vcpu->cpu = -1;
332 vcpu->kvm = kvm;
333 vcpu->vcpu_id = id;
334 vcpu->pid = NULL;
335 init_swait_queue_head(&vcpu->wq);
336 kvm_async_pf_vcpu_init(vcpu);
337
338 vcpu->pre_pcpu = -1;
339 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
340
341 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
342 if (!page) {
343 r = -ENOMEM;
344 goto fail;
345 }
346 vcpu->run = page_address(page);
347
348 kvm_vcpu_set_in_spin_loop(vcpu, false);
349 kvm_vcpu_set_dy_eligible(vcpu, false);
350 vcpu->preempted = false;
David Brazdil0f672f62019-12-10 10:32:29 +0000351 vcpu->ready = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000352
353 r = kvm_arch_vcpu_init(vcpu);
354 if (r < 0)
355 goto fail_free_run;
356 return 0;
357
358fail_free_run:
359 free_page((unsigned long)vcpu->run);
360fail:
361 return r;
362}
363EXPORT_SYMBOL_GPL(kvm_vcpu_init);
364
365void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
366{
367 /*
368 * no need for rcu_read_lock as VCPU_RUN is the only place that
369 * will change the vcpu->pid pointer and on uninit all file
370 * descriptors are already gone.
371 */
372 put_pid(rcu_dereference_protected(vcpu->pid, 1));
373 kvm_arch_vcpu_uninit(vcpu);
374 free_page((unsigned long)vcpu->run);
375}
376EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
377
378#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
379static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
380{
381 return container_of(mn, struct kvm, mmu_notifier);
382}
383
Olivier Deprez0e641232021-09-23 10:07:05 +0200384static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
385 struct mm_struct *mm,
386 unsigned long start, unsigned long end)
387{
388 struct kvm *kvm = mmu_notifier_to_kvm(mn);
389 int idx;
390
391 idx = srcu_read_lock(&kvm->srcu);
392 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
393 srcu_read_unlock(&kvm->srcu, idx);
394}
395
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000396static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
397 struct mm_struct *mm,
398 unsigned long address,
399 pte_t pte)
400{
401 struct kvm *kvm = mmu_notifier_to_kvm(mn);
402 int idx;
403
404 idx = srcu_read_lock(&kvm->srcu);
405 spin_lock(&kvm->mmu_lock);
406 kvm->mmu_notifier_seq++;
David Brazdil0f672f62019-12-10 10:32:29 +0000407
408 if (kvm_set_spte_hva(kvm, address, pte))
409 kvm_flush_remote_tlbs(kvm);
410
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000411 spin_unlock(&kvm->mmu_lock);
412 srcu_read_unlock(&kvm->srcu, idx);
413}
414
415static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
David Brazdil0f672f62019-12-10 10:32:29 +0000416 const struct mmu_notifier_range *range)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000417{
418 struct kvm *kvm = mmu_notifier_to_kvm(mn);
419 int need_tlb_flush = 0, idx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000420
421 idx = srcu_read_lock(&kvm->srcu);
422 spin_lock(&kvm->mmu_lock);
423 /*
424 * The count increase must become visible at unlock time as no
425 * spte can be established without taking the mmu_lock and
426 * count is also read inside the mmu_lock critical section.
427 */
428 kvm->mmu_notifier_count++;
Olivier Deprez0e641232021-09-23 10:07:05 +0200429 need_tlb_flush = kvm_unmap_hva_range(kvm, range->start, range->end,
430 range->flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000431 /* we've to flush the tlb before the pages can be freed */
Olivier Deprez0e641232021-09-23 10:07:05 +0200432 if (need_tlb_flush || kvm->tlbs_dirty)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000433 kvm_flush_remote_tlbs(kvm);
434
435 spin_unlock(&kvm->mmu_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000436 srcu_read_unlock(&kvm->srcu, idx);
437
Olivier Deprez0e641232021-09-23 10:07:05 +0200438 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000439}
440
441static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
David Brazdil0f672f62019-12-10 10:32:29 +0000442 const struct mmu_notifier_range *range)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000443{
444 struct kvm *kvm = mmu_notifier_to_kvm(mn);
445
446 spin_lock(&kvm->mmu_lock);
447 /*
448 * This sequence increase will notify the kvm page fault that
449 * the page that is going to be mapped in the spte could have
450 * been freed.
451 */
452 kvm->mmu_notifier_seq++;
453 smp_wmb();
454 /*
455 * The above sequence increase must be visible before the
456 * below count decrease, which is ensured by the smp_wmb above
457 * in conjunction with the smp_rmb in mmu_notifier_retry().
458 */
459 kvm->mmu_notifier_count--;
460 spin_unlock(&kvm->mmu_lock);
461
462 BUG_ON(kvm->mmu_notifier_count < 0);
463}
464
465static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
466 struct mm_struct *mm,
467 unsigned long start,
468 unsigned long end)
469{
470 struct kvm *kvm = mmu_notifier_to_kvm(mn);
471 int young, idx;
472
473 idx = srcu_read_lock(&kvm->srcu);
474 spin_lock(&kvm->mmu_lock);
475
476 young = kvm_age_hva(kvm, start, end);
477 if (young)
478 kvm_flush_remote_tlbs(kvm);
479
480 spin_unlock(&kvm->mmu_lock);
481 srcu_read_unlock(&kvm->srcu, idx);
482
483 return young;
484}
485
486static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
487 struct mm_struct *mm,
488 unsigned long start,
489 unsigned long end)
490{
491 struct kvm *kvm = mmu_notifier_to_kvm(mn);
492 int young, idx;
493
494 idx = srcu_read_lock(&kvm->srcu);
495 spin_lock(&kvm->mmu_lock);
496 /*
497 * Even though we do not flush TLB, this will still adversely
498 * affect performance on pre-Haswell Intel EPT, where there is
499 * no EPT Access Bit to clear so that we have to tear down EPT
500 * tables instead. If we find this unacceptable, we can always
501 * add a parameter to kvm_age_hva so that it effectively doesn't
502 * do anything on clear_young.
503 *
504 * Also note that currently we never issue secondary TLB flushes
505 * from clear_young, leaving this job up to the regular system
506 * cadence. If we find this inaccurate, we might come up with a
507 * more sophisticated heuristic later.
508 */
509 young = kvm_age_hva(kvm, start, end);
510 spin_unlock(&kvm->mmu_lock);
511 srcu_read_unlock(&kvm->srcu, idx);
512
513 return young;
514}
515
516static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
517 struct mm_struct *mm,
518 unsigned long address)
519{
520 struct kvm *kvm = mmu_notifier_to_kvm(mn);
521 int young, idx;
522
523 idx = srcu_read_lock(&kvm->srcu);
524 spin_lock(&kvm->mmu_lock);
525 young = kvm_test_age_hva(kvm, address);
526 spin_unlock(&kvm->mmu_lock);
527 srcu_read_unlock(&kvm->srcu, idx);
528
529 return young;
530}
531
532static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
533 struct mm_struct *mm)
534{
535 struct kvm *kvm = mmu_notifier_to_kvm(mn);
536 int idx;
537
538 idx = srcu_read_lock(&kvm->srcu);
539 kvm_arch_flush_shadow_all(kvm);
540 srcu_read_unlock(&kvm->srcu, idx);
541}
542
543static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
Olivier Deprez0e641232021-09-23 10:07:05 +0200544 .invalidate_range = kvm_mmu_notifier_invalidate_range,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000545 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
546 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
547 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
548 .clear_young = kvm_mmu_notifier_clear_young,
549 .test_young = kvm_mmu_notifier_test_young,
550 .change_pte = kvm_mmu_notifier_change_pte,
551 .release = kvm_mmu_notifier_release,
552};
553
554static int kvm_init_mmu_notifier(struct kvm *kvm)
555{
556 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
557 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
558}
559
560#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
561
562static int kvm_init_mmu_notifier(struct kvm *kvm)
563{
564 return 0;
565}
566
567#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
568
569static struct kvm_memslots *kvm_alloc_memslots(void)
570{
571 int i;
572 struct kvm_memslots *slots;
573
David Brazdil0f672f62019-12-10 10:32:29 +0000574 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000575 if (!slots)
576 return NULL;
577
578 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
579 slots->id_to_index[i] = slots->memslots[i].id = i;
580
581 return slots;
582}
583
584static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
585{
586 if (!memslot->dirty_bitmap)
587 return;
588
589 kvfree(memslot->dirty_bitmap);
590 memslot->dirty_bitmap = NULL;
591}
592
593/*
594 * Free any memory in @free but not in @dont.
595 */
596static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
597 struct kvm_memory_slot *dont)
598{
599 if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
600 kvm_destroy_dirty_bitmap(free);
601
602 kvm_arch_free_memslot(kvm, free, dont);
603
604 free->npages = 0;
605}
606
607static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
608{
609 struct kvm_memory_slot *memslot;
610
611 if (!slots)
612 return;
613
614 kvm_for_each_memslot(memslot, slots)
615 kvm_free_memslot(kvm, memslot, NULL);
616
617 kvfree(slots);
618}
619
620static void kvm_destroy_vm_debugfs(struct kvm *kvm)
621{
622 int i;
623
624 if (!kvm->debugfs_dentry)
625 return;
626
627 debugfs_remove_recursive(kvm->debugfs_dentry);
628
629 if (kvm->debugfs_stat_data) {
630 for (i = 0; i < kvm_debugfs_num_entries; i++)
631 kfree(kvm->debugfs_stat_data[i]);
632 kfree(kvm->debugfs_stat_data);
633 }
634}
635
636static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
637{
Olivier Deprez0e641232021-09-23 10:07:05 +0200638 static DEFINE_MUTEX(kvm_debugfs_lock);
639 struct dentry *dent;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000640 char dir_name[ITOA_MAX_LEN * 2];
641 struct kvm_stat_data *stat_data;
642 struct kvm_stats_debugfs_item *p;
643
644 if (!debugfs_initialized())
645 return 0;
646
647 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
Olivier Deprez0e641232021-09-23 10:07:05 +0200648 mutex_lock(&kvm_debugfs_lock);
649 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
650 if (dent) {
651 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
652 dput(dent);
653 mutex_unlock(&kvm_debugfs_lock);
654 return 0;
655 }
656 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
657 mutex_unlock(&kvm_debugfs_lock);
658 if (IS_ERR(dent))
659 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000660
Olivier Deprez0e641232021-09-23 10:07:05 +0200661 kvm->debugfs_dentry = dent;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000662 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
663 sizeof(*kvm->debugfs_stat_data),
David Brazdil0f672f62019-12-10 10:32:29 +0000664 GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000665 if (!kvm->debugfs_stat_data)
666 return -ENOMEM;
667
668 for (p = debugfs_entries; p->name; p++) {
David Brazdil0f672f62019-12-10 10:32:29 +0000669 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000670 if (!stat_data)
671 return -ENOMEM;
672
673 stat_data->kvm = kvm;
674 stat_data->offset = p->offset;
David Brazdil0f672f62019-12-10 10:32:29 +0000675 stat_data->mode = p->mode ? p->mode : 0644;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000676 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
David Brazdil0f672f62019-12-10 10:32:29 +0000677 debugfs_create_file(p->name, stat_data->mode, kvm->debugfs_dentry,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000678 stat_data, stat_fops_per_vm[p->kind]);
679 }
680 return 0;
681}
682
David Brazdil0f672f62019-12-10 10:32:29 +0000683/*
684 * Called after the VM is otherwise initialized, but just before adding it to
685 * the vm_list.
686 */
687int __weak kvm_arch_post_init_vm(struct kvm *kvm)
688{
689 return 0;
690}
691
692/*
693 * Called just after removing the VM from the vm_list, but before doing any
694 * other destruction.
695 */
696void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
697{
698}
699
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000700static struct kvm *kvm_create_vm(unsigned long type)
701{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000702 struct kvm *kvm = kvm_arch_alloc_vm();
David Brazdil0f672f62019-12-10 10:32:29 +0000703 int r = -ENOMEM;
704 int i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000705
706 if (!kvm)
707 return ERR_PTR(-ENOMEM);
708
709 spin_lock_init(&kvm->mmu_lock);
710 mmgrab(current->mm);
711 kvm->mm = current->mm;
712 kvm_eventfd_init(kvm);
713 mutex_init(&kvm->lock);
714 mutex_init(&kvm->irq_lock);
715 mutex_init(&kvm->slots_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000716 INIT_LIST_HEAD(&kvm->devices);
717
David Brazdil0f672f62019-12-10 10:32:29 +0000718 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
719
720 if (init_srcu_struct(&kvm->srcu))
721 goto out_err_no_srcu;
722 if (init_srcu_struct(&kvm->irq_srcu))
723 goto out_err_no_irq_srcu;
724
725 refcount_set(&kvm->users_count, 1);
726 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
727 struct kvm_memslots *slots = kvm_alloc_memslots();
728
729 if (!slots)
730 goto out_err_no_arch_destroy_vm;
731 /* Generations must be different for each address space. */
732 slots->generation = i;
733 rcu_assign_pointer(kvm->memslots[i], slots);
734 }
735
736 for (i = 0; i < KVM_NR_BUSES; i++) {
737 rcu_assign_pointer(kvm->buses[i],
738 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
739 if (!kvm->buses[i])
740 goto out_err_no_arch_destroy_vm;
741 }
742
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000743 r = kvm_arch_init_vm(kvm, type);
744 if (r)
David Brazdil0f672f62019-12-10 10:32:29 +0000745 goto out_err_no_arch_destroy_vm;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000746
747 r = hardware_enable_all();
748 if (r)
749 goto out_err_no_disable;
750
751#ifdef CONFIG_HAVE_KVM_IRQFD
752 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
753#endif
754
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000755 r = kvm_init_mmu_notifier(kvm);
756 if (r)
David Brazdil0f672f62019-12-10 10:32:29 +0000757 goto out_err_no_mmu_notifier;
758
759 r = kvm_arch_post_init_vm(kvm);
760 if (r)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000761 goto out_err;
762
David Brazdil0f672f62019-12-10 10:32:29 +0000763 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000764 list_add(&kvm->vm_list, &vm_list);
David Brazdil0f672f62019-12-10 10:32:29 +0000765 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000766
767 preempt_notifier_inc();
768
769 return kvm;
770
771out_err:
David Brazdil0f672f62019-12-10 10:32:29 +0000772#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
773 if (kvm->mmu_notifier.ops)
774 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
775#endif
776out_err_no_mmu_notifier:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000777 hardware_disable_all();
778out_err_no_disable:
David Brazdil0f672f62019-12-10 10:32:29 +0000779 kvm_arch_destroy_vm(kvm);
780out_err_no_arch_destroy_vm:
781 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000782 for (i = 0; i < KVM_NR_BUSES; i++)
783 kfree(kvm_get_bus(kvm, i));
784 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
785 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
David Brazdil0f672f62019-12-10 10:32:29 +0000786 cleanup_srcu_struct(&kvm->irq_srcu);
787out_err_no_irq_srcu:
788 cleanup_srcu_struct(&kvm->srcu);
789out_err_no_srcu:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000790 kvm_arch_free_vm(kvm);
791 mmdrop(current->mm);
792 return ERR_PTR(r);
793}
794
795static void kvm_destroy_devices(struct kvm *kvm)
796{
797 struct kvm_device *dev, *tmp;
798
799 /*
800 * We do not need to take the kvm->lock here, because nobody else
801 * has a reference to the struct kvm at this point and therefore
802 * cannot access the devices list anyhow.
803 */
804 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
805 list_del(&dev->vm_node);
806 dev->ops->destroy(dev);
807 }
808}
809
810static void kvm_destroy_vm(struct kvm *kvm)
811{
812 int i;
813 struct mm_struct *mm = kvm->mm;
814
815 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
816 kvm_destroy_vm_debugfs(kvm);
817 kvm_arch_sync_events(kvm);
David Brazdil0f672f62019-12-10 10:32:29 +0000818 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000819 list_del(&kvm->vm_list);
David Brazdil0f672f62019-12-10 10:32:29 +0000820 mutex_unlock(&kvm_lock);
821 kvm_arch_pre_destroy_vm(kvm);
822
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000823 kvm_free_irq_routing(kvm);
824 for (i = 0; i < KVM_NR_BUSES; i++) {
825 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
826
827 if (bus)
828 kvm_io_bus_destroy(bus);
829 kvm->buses[i] = NULL;
830 }
831 kvm_coalesced_mmio_free(kvm);
832#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
833 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
834#else
835 kvm_arch_flush_shadow_all(kvm);
836#endif
837 kvm_arch_destroy_vm(kvm);
838 kvm_destroy_devices(kvm);
839 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
840 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
841 cleanup_srcu_struct(&kvm->irq_srcu);
842 cleanup_srcu_struct(&kvm->srcu);
843 kvm_arch_free_vm(kvm);
844 preempt_notifier_dec();
845 hardware_disable_all();
846 mmdrop(mm);
847}
848
849void kvm_get_kvm(struct kvm *kvm)
850{
851 refcount_inc(&kvm->users_count);
852}
853EXPORT_SYMBOL_GPL(kvm_get_kvm);
854
855void kvm_put_kvm(struct kvm *kvm)
856{
857 if (refcount_dec_and_test(&kvm->users_count))
858 kvm_destroy_vm(kvm);
859}
860EXPORT_SYMBOL_GPL(kvm_put_kvm);
861
862
863static int kvm_vm_release(struct inode *inode, struct file *filp)
864{
865 struct kvm *kvm = filp->private_data;
866
867 kvm_irqfd_release(kvm);
868
869 kvm_put_kvm(kvm);
870 return 0;
871}
872
873/*
874 * Allocation size is twice as large as the actual dirty bitmap size.
875 * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
876 */
877static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
878{
879 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
880
David Brazdil0f672f62019-12-10 10:32:29 +0000881 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000882 if (!memslot->dirty_bitmap)
883 return -ENOMEM;
884
885 return 0;
886}
887
888/*
889 * Insert memslot and re-sort memslots based on their GFN,
890 * so binary search could be used to lookup GFN.
891 * Sorting algorithm takes advantage of having initially
892 * sorted array and known changed memslot position.
893 */
894static void update_memslots(struct kvm_memslots *slots,
David Brazdil0f672f62019-12-10 10:32:29 +0000895 struct kvm_memory_slot *new,
896 enum kvm_mr_change change)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000897{
898 int id = new->id;
899 int i = slots->id_to_index[id];
900 struct kvm_memory_slot *mslots = slots->memslots;
901
902 WARN_ON(mslots[i].id != id);
David Brazdil0f672f62019-12-10 10:32:29 +0000903 switch (change) {
904 case KVM_MR_CREATE:
905 slots->used_slots++;
906 WARN_ON(mslots[i].npages || !new->npages);
907 break;
908 case KVM_MR_DELETE:
909 slots->used_slots--;
910 WARN_ON(new->npages || !mslots[i].npages);
911 break;
912 default:
913 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000914 }
915
916 while (i < KVM_MEM_SLOTS_NUM - 1 &&
917 new->base_gfn <= mslots[i + 1].base_gfn) {
918 if (!mslots[i + 1].npages)
919 break;
920 mslots[i] = mslots[i + 1];
921 slots->id_to_index[mslots[i].id] = i;
922 i++;
923 }
924
925 /*
926 * The ">=" is needed when creating a slot with base_gfn == 0,
927 * so that it moves before all those with base_gfn == npages == 0.
928 *
929 * On the other hand, if new->npages is zero, the above loop has
930 * already left i pointing to the beginning of the empty part of
931 * mslots, and the ">=" would move the hole backwards in this
932 * case---which is wrong. So skip the loop when deleting a slot.
933 */
934 if (new->npages) {
935 while (i > 0 &&
936 new->base_gfn >= mslots[i - 1].base_gfn) {
937 mslots[i] = mslots[i - 1];
938 slots->id_to_index[mslots[i].id] = i;
939 i--;
940 }
941 } else
942 WARN_ON_ONCE(i != slots->used_slots);
943
944 mslots[i] = *new;
945 slots->id_to_index[mslots[i].id] = i;
946}
947
948static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
949{
950 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
951
952#ifdef __KVM_HAVE_READONLY_MEM
953 valid_flags |= KVM_MEM_READONLY;
954#endif
955
956 if (mem->flags & ~valid_flags)
957 return -EINVAL;
958
959 return 0;
960}
961
962static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
963 int as_id, struct kvm_memslots *slots)
964{
965 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
David Brazdil0f672f62019-12-10 10:32:29 +0000966 u64 gen = old_memslots->generation;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000967
David Brazdil0f672f62019-12-10 10:32:29 +0000968 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
969 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000970
971 rcu_assign_pointer(kvm->memslots[as_id], slots);
972 synchronize_srcu_expedited(&kvm->srcu);
973
974 /*
David Brazdil0f672f62019-12-10 10:32:29 +0000975 * Increment the new memslot generation a second time, dropping the
976 * update in-progress flag and incrementing then generation based on
977 * the number of address spaces. This provides a unique and easily
978 * identifiable generation number while the memslots are in flux.
979 */
980 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
981
982 /*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000983 * Generations must be unique even across address spaces. We do not need
984 * a global counter for that, instead the generation space is evenly split
985 * across address spaces. For example, with two address spaces, address
David Brazdil0f672f62019-12-10 10:32:29 +0000986 * space 0 will use generations 0, 2, 4, ... while address space 1 will
987 * use generations 1, 3, 5, ...
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000988 */
David Brazdil0f672f62019-12-10 10:32:29 +0000989 gen += KVM_ADDRESS_SPACE_NUM;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000990
David Brazdil0f672f62019-12-10 10:32:29 +0000991 kvm_arch_memslots_updated(kvm, gen);
992
993 slots->generation = gen;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000994
995 return old_memslots;
996}
997
998/*
999 * Allocate some memory and give it an address in the guest physical address
1000 * space.
1001 *
1002 * Discontiguous memory is allowed, mostly for framebuffers.
1003 *
1004 * Must be called holding kvm->slots_lock for write.
1005 */
1006int __kvm_set_memory_region(struct kvm *kvm,
1007 const struct kvm_userspace_memory_region *mem)
1008{
1009 int r;
1010 gfn_t base_gfn;
1011 unsigned long npages;
1012 struct kvm_memory_slot *slot;
1013 struct kvm_memory_slot old, new;
1014 struct kvm_memslots *slots = NULL, *old_memslots;
1015 int as_id, id;
1016 enum kvm_mr_change change;
1017
1018 r = check_memory_region_flags(mem);
1019 if (r)
1020 goto out;
1021
1022 r = -EINVAL;
1023 as_id = mem->slot >> 16;
1024 id = (u16)mem->slot;
1025
1026 /* General sanity checks */
1027 if (mem->memory_size & (PAGE_SIZE - 1))
1028 goto out;
1029 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1030 goto out;
1031 /* We can read the guest memory with __xxx_user() later on. */
1032 if ((id < KVM_USER_MEM_SLOTS) &&
1033 ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
Olivier Deprez0e641232021-09-23 10:07:05 +02001034 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
David Brazdil0f672f62019-12-10 10:32:29 +00001035 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001036 mem->memory_size)))
1037 goto out;
1038 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1039 goto out;
1040 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1041 goto out;
1042
1043 slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1044 base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1045 npages = mem->memory_size >> PAGE_SHIFT;
1046
1047 if (npages > KVM_MEM_MAX_NR_PAGES)
1048 goto out;
1049
1050 new = old = *slot;
1051
1052 new.id = id;
1053 new.base_gfn = base_gfn;
1054 new.npages = npages;
1055 new.flags = mem->flags;
1056
1057 if (npages) {
1058 if (!old.npages)
1059 change = KVM_MR_CREATE;
1060 else { /* Modify an existing slot. */
1061 if ((mem->userspace_addr != old.userspace_addr) ||
1062 (npages != old.npages) ||
1063 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1064 goto out;
1065
1066 if (base_gfn != old.base_gfn)
1067 change = KVM_MR_MOVE;
1068 else if (new.flags != old.flags)
1069 change = KVM_MR_FLAGS_ONLY;
1070 else { /* Nothing to change. */
1071 r = 0;
1072 goto out;
1073 }
1074 }
1075 } else {
1076 if (!old.npages)
1077 goto out;
1078
1079 change = KVM_MR_DELETE;
1080 new.base_gfn = 0;
1081 new.flags = 0;
1082 }
1083
1084 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1085 /* Check for overlaps */
1086 r = -EEXIST;
1087 kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
1088 if (slot->id == id)
1089 continue;
1090 if (!((base_gfn + npages <= slot->base_gfn) ||
1091 (base_gfn >= slot->base_gfn + slot->npages)))
1092 goto out;
1093 }
1094 }
1095
1096 /* Free page dirty bitmap if unneeded */
1097 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1098 new.dirty_bitmap = NULL;
1099
1100 r = -ENOMEM;
1101 if (change == KVM_MR_CREATE) {
1102 new.userspace_addr = mem->userspace_addr;
1103
1104 if (kvm_arch_create_memslot(kvm, &new, npages))
1105 goto out_free;
1106 }
1107
1108 /* Allocate page dirty bitmap if needed */
1109 if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
1110 if (kvm_create_dirty_bitmap(&new) < 0)
1111 goto out_free;
1112 }
1113
David Brazdil0f672f62019-12-10 10:32:29 +00001114 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001115 if (!slots)
1116 goto out_free;
1117 memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
1118
1119 if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
1120 slot = id_to_memslot(slots, id);
1121 slot->flags |= KVM_MEMSLOT_INVALID;
1122
1123 old_memslots = install_new_memslots(kvm, as_id, slots);
1124
1125 /* From this point no new shadow pages pointing to a deleted,
1126 * or moved, memslot will be created.
1127 *
1128 * validation of sp->gfn happens in:
1129 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1130 * - kvm_is_visible_gfn (mmu_check_roots)
1131 */
1132 kvm_arch_flush_shadow_memslot(kvm, slot);
1133
1134 /*
1135 * We can re-use the old_memslots from above, the only difference
1136 * from the currently installed memslots is the invalid flag. This
1137 * will get overwritten by update_memslots anyway.
1138 */
1139 slots = old_memslots;
1140 }
1141
1142 r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
1143 if (r)
1144 goto out_slots;
1145
1146 /* actual memory is freed via old in kvm_free_memslot below */
1147 if (change == KVM_MR_DELETE) {
1148 new.dirty_bitmap = NULL;
1149 memset(&new.arch, 0, sizeof(new.arch));
1150 }
1151
David Brazdil0f672f62019-12-10 10:32:29 +00001152 update_memslots(slots, &new, change);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001153 old_memslots = install_new_memslots(kvm, as_id, slots);
1154
1155 kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
1156
1157 kvm_free_memslot(kvm, &old, &new);
1158 kvfree(old_memslots);
1159 return 0;
1160
1161out_slots:
1162 kvfree(slots);
1163out_free:
1164 kvm_free_memslot(kvm, &new, &old);
1165out:
1166 return r;
1167}
1168EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1169
1170int kvm_set_memory_region(struct kvm *kvm,
1171 const struct kvm_userspace_memory_region *mem)
1172{
1173 int r;
1174
1175 mutex_lock(&kvm->slots_lock);
1176 r = __kvm_set_memory_region(kvm, mem);
1177 mutex_unlock(&kvm->slots_lock);
1178 return r;
1179}
1180EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1181
1182static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1183 struct kvm_userspace_memory_region *mem)
1184{
1185 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1186 return -EINVAL;
1187
1188 return kvm_set_memory_region(kvm, mem);
1189}
1190
1191int kvm_get_dirty_log(struct kvm *kvm,
1192 struct kvm_dirty_log *log, int *is_dirty)
1193{
1194 struct kvm_memslots *slots;
1195 struct kvm_memory_slot *memslot;
1196 int i, as_id, id;
1197 unsigned long n;
1198 unsigned long any = 0;
1199
1200 as_id = log->slot >> 16;
1201 id = (u16)log->slot;
1202 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1203 return -EINVAL;
1204
1205 slots = __kvm_memslots(kvm, as_id);
1206 memslot = id_to_memslot(slots, id);
1207 if (!memslot->dirty_bitmap)
1208 return -ENOENT;
1209
1210 n = kvm_dirty_bitmap_bytes(memslot);
1211
1212 for (i = 0; !any && i < n/sizeof(long); ++i)
1213 any = memslot->dirty_bitmap[i];
1214
1215 if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1216 return -EFAULT;
1217
1218 if (any)
1219 *is_dirty = 1;
1220 return 0;
1221}
1222EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1223
1224#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1225/**
David Brazdil0f672f62019-12-10 10:32:29 +00001226 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1227 * and reenable dirty page tracking for the corresponding pages.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001228 * @kvm: pointer to kvm instance
1229 * @log: slot id and address to which we copy the log
David Brazdil0f672f62019-12-10 10:32:29 +00001230 * @flush: true if TLB flush is needed by caller
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001231 *
1232 * We need to keep it in mind that VCPU threads can write to the bitmap
1233 * concurrently. So, to avoid losing track of dirty pages we keep the
1234 * following order:
1235 *
1236 * 1. Take a snapshot of the bit and clear it if needed.
1237 * 2. Write protect the corresponding page.
1238 * 3. Copy the snapshot to the userspace.
1239 * 4. Upon return caller flushes TLB's if needed.
1240 *
1241 * Between 2 and 4, the guest may write to the page using the remaining TLB
1242 * entry. This is not a problem because the page is reported dirty using
1243 * the snapshot taken before and step 4 ensures that writes done after
1244 * exiting to userspace will be logged for the next call.
1245 *
1246 */
1247int kvm_get_dirty_log_protect(struct kvm *kvm,
David Brazdil0f672f62019-12-10 10:32:29 +00001248 struct kvm_dirty_log *log, bool *flush)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001249{
1250 struct kvm_memslots *slots;
1251 struct kvm_memory_slot *memslot;
1252 int i, as_id, id;
1253 unsigned long n;
1254 unsigned long *dirty_bitmap;
1255 unsigned long *dirty_bitmap_buffer;
1256
1257 as_id = log->slot >> 16;
1258 id = (u16)log->slot;
1259 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1260 return -EINVAL;
1261
1262 slots = __kvm_memslots(kvm, as_id);
1263 memslot = id_to_memslot(slots, id);
1264
1265 dirty_bitmap = memslot->dirty_bitmap;
1266 if (!dirty_bitmap)
1267 return -ENOENT;
1268
1269 n = kvm_dirty_bitmap_bytes(memslot);
David Brazdil0f672f62019-12-10 10:32:29 +00001270 *flush = false;
1271 if (kvm->manual_dirty_log_protect) {
1272 /*
1273 * Unlike kvm_get_dirty_log, we always return false in *flush,
1274 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1275 * is some code duplication between this function and
1276 * kvm_get_dirty_log, but hopefully all architecture
1277 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1278 * can be eliminated.
1279 */
1280 dirty_bitmap_buffer = dirty_bitmap;
1281 } else {
1282 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1283 memset(dirty_bitmap_buffer, 0, n);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001284
David Brazdil0f672f62019-12-10 10:32:29 +00001285 spin_lock(&kvm->mmu_lock);
1286 for (i = 0; i < n / sizeof(long); i++) {
1287 unsigned long mask;
1288 gfn_t offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001289
David Brazdil0f672f62019-12-10 10:32:29 +00001290 if (!dirty_bitmap[i])
1291 continue;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001292
David Brazdil0f672f62019-12-10 10:32:29 +00001293 *flush = true;
1294 mask = xchg(&dirty_bitmap[i], 0);
1295 dirty_bitmap_buffer[i] = mask;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001296
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001297 offset = i * BITS_PER_LONG;
1298 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1299 offset, mask);
1300 }
David Brazdil0f672f62019-12-10 10:32:29 +00001301 spin_unlock(&kvm->mmu_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001302 }
1303
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001304 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1305 return -EFAULT;
1306 return 0;
1307}
1308EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
David Brazdil0f672f62019-12-10 10:32:29 +00001309
1310/**
1311 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1312 * and reenable dirty page tracking for the corresponding pages.
1313 * @kvm: pointer to kvm instance
1314 * @log: slot id and address from which to fetch the bitmap of dirty pages
1315 * @flush: true if TLB flush is needed by caller
1316 */
1317int kvm_clear_dirty_log_protect(struct kvm *kvm,
1318 struct kvm_clear_dirty_log *log, bool *flush)
1319{
1320 struct kvm_memslots *slots;
1321 struct kvm_memory_slot *memslot;
1322 int as_id, id;
1323 gfn_t offset;
1324 unsigned long i, n;
1325 unsigned long *dirty_bitmap;
1326 unsigned long *dirty_bitmap_buffer;
1327
1328 as_id = log->slot >> 16;
1329 id = (u16)log->slot;
1330 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1331 return -EINVAL;
1332
1333 if (log->first_page & 63)
1334 return -EINVAL;
1335
1336 slots = __kvm_memslots(kvm, as_id);
1337 memslot = id_to_memslot(slots, id);
1338
1339 dirty_bitmap = memslot->dirty_bitmap;
1340 if (!dirty_bitmap)
1341 return -ENOENT;
1342
1343 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
1344
1345 if (log->first_page > memslot->npages ||
1346 log->num_pages > memslot->npages - log->first_page ||
1347 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1348 return -EINVAL;
1349
1350 *flush = false;
1351 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1352 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1353 return -EFAULT;
1354
1355 spin_lock(&kvm->mmu_lock);
1356 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1357 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
1358 i++, offset += BITS_PER_LONG) {
1359 unsigned long mask = *dirty_bitmap_buffer++;
1360 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1361 if (!mask)
1362 continue;
1363
1364 mask &= atomic_long_fetch_andnot(mask, p);
1365
1366 /*
1367 * mask contains the bits that really have been cleared. This
1368 * never includes any bits beyond the length of the memslot (if
1369 * the length is not aligned to 64 pages), therefore it is not
1370 * a problem if userspace sets them in log->dirty_bitmap.
1371 */
1372 if (mask) {
1373 *flush = true;
1374 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1375 offset, mask);
1376 }
1377 }
1378 spin_unlock(&kvm->mmu_lock);
1379
1380 return 0;
1381}
1382EXPORT_SYMBOL_GPL(kvm_clear_dirty_log_protect);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001383#endif
1384
1385bool kvm_largepages_enabled(void)
1386{
1387 return largepages_enabled;
1388}
1389
1390void kvm_disable_largepages(void)
1391{
1392 largepages_enabled = false;
1393}
1394EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1395
1396struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1397{
1398 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1399}
1400EXPORT_SYMBOL_GPL(gfn_to_memslot);
1401
1402struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1403{
1404 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1405}
1406
1407bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1408{
1409 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1410
1411 if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1412 memslot->flags & KVM_MEMSLOT_INVALID)
1413 return false;
1414
1415 return true;
1416}
1417EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1418
Olivier Deprez0e641232021-09-23 10:07:05 +02001419unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001420{
1421 struct vm_area_struct *vma;
1422 unsigned long addr, size;
1423
1424 size = PAGE_SIZE;
1425
Olivier Deprez0e641232021-09-23 10:07:05 +02001426 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001427 if (kvm_is_error_hva(addr))
1428 return PAGE_SIZE;
1429
1430 down_read(&current->mm->mmap_sem);
1431 vma = find_vma(current->mm, addr);
1432 if (!vma)
1433 goto out;
1434
1435 size = vma_kernel_pagesize(vma);
1436
1437out:
1438 up_read(&current->mm->mmap_sem);
1439
1440 return size;
1441}
1442
1443static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1444{
1445 return slot->flags & KVM_MEM_READONLY;
1446}
1447
1448static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1449 gfn_t *nr_pages, bool write)
1450{
1451 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1452 return KVM_HVA_ERR_BAD;
1453
1454 if (memslot_is_readonly(slot) && write)
1455 return KVM_HVA_ERR_RO_BAD;
1456
1457 if (nr_pages)
1458 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1459
1460 return __gfn_to_hva_memslot(slot, gfn);
1461}
1462
1463static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1464 gfn_t *nr_pages)
1465{
1466 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1467}
1468
1469unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1470 gfn_t gfn)
1471{
1472 return gfn_to_hva_many(slot, gfn, NULL);
1473}
1474EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1475
1476unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1477{
1478 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1479}
1480EXPORT_SYMBOL_GPL(gfn_to_hva);
1481
1482unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1483{
1484 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1485}
1486EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1487
1488/*
David Brazdil0f672f62019-12-10 10:32:29 +00001489 * Return the hva of a @gfn and the R/W attribute if possible.
1490 *
1491 * @slot: the kvm_memory_slot which contains @gfn
1492 * @gfn: the gfn to be translated
1493 * @writable: used to return the read/write attribute of the @slot if the hva
1494 * is valid and @writable is not NULL
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001495 */
1496unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1497 gfn_t gfn, bool *writable)
1498{
1499 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1500
1501 if (!kvm_is_error_hva(hva) && writable)
1502 *writable = !memslot_is_readonly(slot);
1503
1504 return hva;
1505}
1506
1507unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1508{
1509 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1510
1511 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1512}
1513
1514unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1515{
1516 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1517
1518 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1519}
1520
1521static inline int check_user_page_hwpoison(unsigned long addr)
1522{
1523 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1524
1525 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1526 return rc == -EHWPOISON;
1527}
1528
1529/*
1530 * The fast path to get the writable pfn which will be stored in @pfn,
1531 * true indicates success, otherwise false is returned. It's also the
1532 * only part that runs if we can are in atomic context.
1533 */
1534static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1535 bool *writable, kvm_pfn_t *pfn)
1536{
1537 struct page *page[1];
1538 int npages;
1539
1540 /*
1541 * Fast pin a writable pfn only if it is a write fault request
1542 * or the caller allows to map a writable pfn for a read fault
1543 * request.
1544 */
1545 if (!(write_fault || writable))
1546 return false;
1547
1548 npages = __get_user_pages_fast(addr, 1, 1, page);
1549 if (npages == 1) {
1550 *pfn = page_to_pfn(page[0]);
1551
1552 if (writable)
1553 *writable = true;
1554 return true;
1555 }
1556
1557 return false;
1558}
1559
1560/*
1561 * The slow path to get the pfn of the specified host virtual address,
1562 * 1 indicates success, -errno is returned if error is detected.
1563 */
1564static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1565 bool *writable, kvm_pfn_t *pfn)
1566{
1567 unsigned int flags = FOLL_HWPOISON;
1568 struct page *page;
1569 int npages = 0;
1570
1571 might_sleep();
1572
1573 if (writable)
1574 *writable = write_fault;
1575
1576 if (write_fault)
1577 flags |= FOLL_WRITE;
1578 if (async)
1579 flags |= FOLL_NOWAIT;
1580
1581 npages = get_user_pages_unlocked(addr, 1, &page, flags);
1582 if (npages != 1)
1583 return npages;
1584
1585 /* map read fault as writable if possible */
1586 if (unlikely(!write_fault) && writable) {
1587 struct page *wpage;
1588
1589 if (__get_user_pages_fast(addr, 1, 1, &wpage) == 1) {
1590 *writable = true;
1591 put_page(page);
1592 page = wpage;
1593 }
1594 }
1595 *pfn = page_to_pfn(page);
1596 return npages;
1597}
1598
1599static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1600{
1601 if (unlikely(!(vma->vm_flags & VM_READ)))
1602 return false;
1603
1604 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1605 return false;
1606
1607 return true;
1608}
1609
Olivier Deprez0e641232021-09-23 10:07:05 +02001610static int kvm_try_get_pfn(kvm_pfn_t pfn)
1611{
1612 if (kvm_is_reserved_pfn(pfn))
1613 return 1;
1614 return get_page_unless_zero(pfn_to_page(pfn));
1615}
1616
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001617static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1618 unsigned long addr, bool *async,
1619 bool write_fault, bool *writable,
1620 kvm_pfn_t *p_pfn)
1621{
Olivier Deprez0e641232021-09-23 10:07:05 +02001622 kvm_pfn_t pfn;
1623 pte_t *ptep;
1624 spinlock_t *ptl;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001625 int r;
1626
Olivier Deprez0e641232021-09-23 10:07:05 +02001627 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001628 if (r) {
1629 /*
1630 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1631 * not call the fault handler, so do it here.
1632 */
1633 bool unlocked = false;
1634 r = fixup_user_fault(current, current->mm, addr,
1635 (write_fault ? FAULT_FLAG_WRITE : 0),
1636 &unlocked);
1637 if (unlocked)
1638 return -EAGAIN;
1639 if (r)
1640 return r;
1641
Olivier Deprez0e641232021-09-23 10:07:05 +02001642 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001643 if (r)
1644 return r;
Olivier Deprez0e641232021-09-23 10:07:05 +02001645 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001646
Olivier Deprez0e641232021-09-23 10:07:05 +02001647 if (write_fault && !pte_write(*ptep)) {
1648 pfn = KVM_PFN_ERR_RO_FAULT;
1649 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001650 }
1651
1652 if (writable)
Olivier Deprez0e641232021-09-23 10:07:05 +02001653 *writable = pte_write(*ptep);
1654 pfn = pte_pfn(*ptep);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001655
1656 /*
1657 * Get a reference here because callers of *hva_to_pfn* and
1658 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1659 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1660 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1661 * simply do nothing for reserved pfns.
1662 *
1663 * Whoever called remap_pfn_range is also going to call e.g.
1664 * unmap_mapping_range before the underlying pages are freed,
1665 * causing a call to our MMU notifier.
Olivier Deprez0e641232021-09-23 10:07:05 +02001666 *
1667 * Certain IO or PFNMAP mappings can be backed with valid
1668 * struct pages, but be allocated without refcounting e.g.,
1669 * tail pages of non-compound higher order allocations, which
1670 * would then underflow the refcount when the caller does the
1671 * required put_page. Don't allow those pages here.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001672 */
Olivier Deprez0e641232021-09-23 10:07:05 +02001673 if (!kvm_try_get_pfn(pfn))
1674 r = -EFAULT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001675
Olivier Deprez0e641232021-09-23 10:07:05 +02001676out:
1677 pte_unmap_unlock(ptep, ptl);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001678 *p_pfn = pfn;
Olivier Deprez0e641232021-09-23 10:07:05 +02001679
1680 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001681}
1682
1683/*
1684 * Pin guest page in memory and return its pfn.
1685 * @addr: host virtual address which maps memory to the guest
1686 * @atomic: whether this function can sleep
1687 * @async: whether this function need to wait IO complete if the
1688 * host page is not in the memory
1689 * @write_fault: whether we should get a writable host page
1690 * @writable: whether it allows to map a writable host page for !@write_fault
1691 *
1692 * The function will map a writable host page for these two cases:
1693 * 1): @write_fault = true
1694 * 2): @write_fault = false && @writable, @writable will tell the caller
1695 * whether the mapping is writable.
1696 */
1697static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1698 bool write_fault, bool *writable)
1699{
1700 struct vm_area_struct *vma;
1701 kvm_pfn_t pfn = 0;
1702 int npages, r;
1703
1704 /* we can do it either atomically or asynchronously, not both */
1705 BUG_ON(atomic && async);
1706
1707 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
1708 return pfn;
1709
1710 if (atomic)
1711 return KVM_PFN_ERR_FAULT;
1712
1713 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1714 if (npages == 1)
1715 return pfn;
1716
1717 down_read(&current->mm->mmap_sem);
1718 if (npages == -EHWPOISON ||
1719 (!async && check_user_page_hwpoison(addr))) {
1720 pfn = KVM_PFN_ERR_HWPOISON;
1721 goto exit;
1722 }
1723
1724retry:
1725 vma = find_vma_intersection(current->mm, addr, addr + 1);
1726
1727 if (vma == NULL)
1728 pfn = KVM_PFN_ERR_FAULT;
1729 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1730 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
1731 if (r == -EAGAIN)
1732 goto retry;
1733 if (r < 0)
1734 pfn = KVM_PFN_ERR_FAULT;
1735 } else {
1736 if (async && vma_is_valid(vma, write_fault))
1737 *async = true;
1738 pfn = KVM_PFN_ERR_FAULT;
1739 }
1740exit:
1741 up_read(&current->mm->mmap_sem);
1742 return pfn;
1743}
1744
1745kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1746 bool atomic, bool *async, bool write_fault,
1747 bool *writable)
1748{
1749 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1750
1751 if (addr == KVM_HVA_ERR_RO_BAD) {
1752 if (writable)
1753 *writable = false;
1754 return KVM_PFN_ERR_RO_FAULT;
1755 }
1756
1757 if (kvm_is_error_hva(addr)) {
1758 if (writable)
1759 *writable = false;
1760 return KVM_PFN_NOSLOT;
1761 }
1762
1763 /* Do not map writable pfn in the readonly memslot. */
1764 if (writable && memslot_is_readonly(slot)) {
1765 *writable = false;
1766 writable = NULL;
1767 }
1768
1769 return hva_to_pfn(addr, atomic, async, write_fault,
1770 writable);
1771}
1772EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1773
1774kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1775 bool *writable)
1776{
1777 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1778 write_fault, writable);
1779}
1780EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1781
1782kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1783{
1784 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1785}
1786EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1787
1788kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1789{
1790 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1791}
1792EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1793
1794kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1795{
1796 return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1797}
1798EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1799
1800kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1801{
1802 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1803}
1804EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1805
1806kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1807{
1808 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1809}
1810EXPORT_SYMBOL_GPL(gfn_to_pfn);
1811
1812kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1813{
1814 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1815}
1816EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1817
1818int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1819 struct page **pages, int nr_pages)
1820{
1821 unsigned long addr;
1822 gfn_t entry = 0;
1823
1824 addr = gfn_to_hva_many(slot, gfn, &entry);
1825 if (kvm_is_error_hva(addr))
1826 return -1;
1827
1828 if (entry < nr_pages)
1829 return 0;
1830
1831 return __get_user_pages_fast(addr, nr_pages, 1, pages);
1832}
1833EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1834
1835static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
1836{
1837 if (is_error_noslot_pfn(pfn))
1838 return KVM_ERR_PTR_BAD_PAGE;
1839
1840 if (kvm_is_reserved_pfn(pfn)) {
1841 WARN_ON(1);
1842 return KVM_ERR_PTR_BAD_PAGE;
1843 }
1844
1845 return pfn_to_page(pfn);
1846}
1847
1848struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1849{
1850 kvm_pfn_t pfn;
1851
1852 pfn = gfn_to_pfn(kvm, gfn);
1853
1854 return kvm_pfn_to_page(pfn);
1855}
1856EXPORT_SYMBOL_GPL(gfn_to_page);
1857
Olivier Deprez0e641232021-09-23 10:07:05 +02001858void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
1859{
1860 if (pfn == 0)
1861 return;
1862
1863 if (cache)
1864 cache->pfn = cache->gfn = 0;
1865
1866 if (dirty)
1867 kvm_release_pfn_dirty(pfn);
1868 else
1869 kvm_release_pfn_clean(pfn);
1870}
1871
1872static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
1873 struct gfn_to_pfn_cache *cache, u64 gen)
1874{
1875 kvm_release_pfn(cache->pfn, cache->dirty, cache);
1876
1877 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
1878 cache->gfn = gfn;
1879 cache->dirty = false;
1880 cache->generation = gen;
1881}
1882
1883static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
1884 struct kvm_host_map *map,
1885 struct gfn_to_pfn_cache *cache,
1886 bool atomic)
David Brazdil0f672f62019-12-10 10:32:29 +00001887{
1888 kvm_pfn_t pfn;
1889 void *hva = NULL;
1890 struct page *page = KVM_UNMAPPED_PAGE;
Olivier Deprez0e641232021-09-23 10:07:05 +02001891 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
1892 u64 gen = slots->generation;
David Brazdil0f672f62019-12-10 10:32:29 +00001893
1894 if (!map)
1895 return -EINVAL;
1896
Olivier Deprez0e641232021-09-23 10:07:05 +02001897 if (cache) {
1898 if (!cache->pfn || cache->gfn != gfn ||
1899 cache->generation != gen) {
1900 if (atomic)
1901 return -EAGAIN;
1902 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
1903 }
1904 pfn = cache->pfn;
1905 } else {
1906 if (atomic)
1907 return -EAGAIN;
1908 pfn = gfn_to_pfn_memslot(slot, gfn);
1909 }
David Brazdil0f672f62019-12-10 10:32:29 +00001910 if (is_error_noslot_pfn(pfn))
1911 return -EINVAL;
1912
1913 if (pfn_valid(pfn)) {
1914 page = pfn_to_page(pfn);
Olivier Deprez0e641232021-09-23 10:07:05 +02001915 if (atomic)
1916 hva = kmap_atomic(page);
1917 else
1918 hva = kmap(page);
David Brazdil0f672f62019-12-10 10:32:29 +00001919#ifdef CONFIG_HAS_IOMEM
Olivier Deprez0e641232021-09-23 10:07:05 +02001920 } else if (!atomic) {
David Brazdil0f672f62019-12-10 10:32:29 +00001921 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
Olivier Deprez0e641232021-09-23 10:07:05 +02001922 } else {
1923 return -EINVAL;
David Brazdil0f672f62019-12-10 10:32:29 +00001924#endif
1925 }
1926
1927 if (!hva)
1928 return -EFAULT;
1929
1930 map->page = page;
1931 map->hva = hva;
1932 map->pfn = pfn;
1933 map->gfn = gfn;
1934
1935 return 0;
1936}
1937
Olivier Deprez0e641232021-09-23 10:07:05 +02001938int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
1939 struct gfn_to_pfn_cache *cache, bool atomic)
1940{
1941 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
1942 cache, atomic);
1943}
1944EXPORT_SYMBOL_GPL(kvm_map_gfn);
1945
David Brazdil0f672f62019-12-10 10:32:29 +00001946int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
1947{
Olivier Deprez0e641232021-09-23 10:07:05 +02001948 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
1949 NULL, false);
David Brazdil0f672f62019-12-10 10:32:29 +00001950}
1951EXPORT_SYMBOL_GPL(kvm_vcpu_map);
1952
Olivier Deprez0e641232021-09-23 10:07:05 +02001953static void __kvm_unmap_gfn(struct kvm_memory_slot *memslot,
1954 struct kvm_host_map *map,
1955 struct gfn_to_pfn_cache *cache,
1956 bool dirty, bool atomic)
David Brazdil0f672f62019-12-10 10:32:29 +00001957{
1958 if (!map)
1959 return;
1960
1961 if (!map->hva)
1962 return;
1963
Olivier Deprez0e641232021-09-23 10:07:05 +02001964 if (map->page != KVM_UNMAPPED_PAGE) {
1965 if (atomic)
1966 kunmap_atomic(map->hva);
1967 else
1968 kunmap(map->page);
1969 }
David Brazdil0f672f62019-12-10 10:32:29 +00001970#ifdef CONFIG_HAS_IOMEM
Olivier Deprez0e641232021-09-23 10:07:05 +02001971 else if (!atomic)
David Brazdil0f672f62019-12-10 10:32:29 +00001972 memunmap(map->hva);
Olivier Deprez0e641232021-09-23 10:07:05 +02001973 else
1974 WARN_ONCE(1, "Unexpected unmapping in atomic context");
David Brazdil0f672f62019-12-10 10:32:29 +00001975#endif
1976
Olivier Deprez0e641232021-09-23 10:07:05 +02001977 if (dirty)
1978 mark_page_dirty_in_slot(memslot, map->gfn);
1979
1980 if (cache)
1981 cache->dirty |= dirty;
1982 else
1983 kvm_release_pfn(map->pfn, dirty, NULL);
David Brazdil0f672f62019-12-10 10:32:29 +00001984
1985 map->hva = NULL;
1986 map->page = NULL;
1987}
Olivier Deprez0e641232021-09-23 10:07:05 +02001988
1989int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
1990 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
1991{
1992 __kvm_unmap_gfn(gfn_to_memslot(vcpu->kvm, map->gfn), map,
1993 cache, dirty, atomic);
1994 return 0;
1995}
1996EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
1997
1998void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
1999{
2000 __kvm_unmap_gfn(kvm_vcpu_gfn_to_memslot(vcpu, map->gfn), map, NULL,
2001 dirty, false);
2002}
David Brazdil0f672f62019-12-10 10:32:29 +00002003EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2004
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002005struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2006{
2007 kvm_pfn_t pfn;
2008
2009 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2010
2011 return kvm_pfn_to_page(pfn);
2012}
2013EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2014
2015void kvm_release_page_clean(struct page *page)
2016{
2017 WARN_ON(is_error_page(page));
2018
2019 kvm_release_pfn_clean(page_to_pfn(page));
2020}
2021EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2022
2023void kvm_release_pfn_clean(kvm_pfn_t pfn)
2024{
2025 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2026 put_page(pfn_to_page(pfn));
2027}
2028EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2029
2030void kvm_release_page_dirty(struct page *page)
2031{
2032 WARN_ON(is_error_page(page));
2033
2034 kvm_release_pfn_dirty(page_to_pfn(page));
2035}
2036EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2037
2038void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2039{
2040 kvm_set_pfn_dirty(pfn);
2041 kvm_release_pfn_clean(pfn);
2042}
2043EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2044
2045void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2046{
David Brazdil0f672f62019-12-10 10:32:29 +00002047 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002048 struct page *page = pfn_to_page(pfn);
2049
David Brazdil0f672f62019-12-10 10:32:29 +00002050 SetPageDirty(page);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002051 }
2052}
2053EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2054
2055void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2056{
David Brazdil0f672f62019-12-10 10:32:29 +00002057 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002058 mark_page_accessed(pfn_to_page(pfn));
2059}
2060EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2061
2062void kvm_get_pfn(kvm_pfn_t pfn)
2063{
2064 if (!kvm_is_reserved_pfn(pfn))
2065 get_page(pfn_to_page(pfn));
2066}
2067EXPORT_SYMBOL_GPL(kvm_get_pfn);
2068
2069static int next_segment(unsigned long len, int offset)
2070{
2071 if (len > PAGE_SIZE - offset)
2072 return PAGE_SIZE - offset;
2073 else
2074 return len;
2075}
2076
2077static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2078 void *data, int offset, int len)
2079{
2080 int r;
2081 unsigned long addr;
2082
2083 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2084 if (kvm_is_error_hva(addr))
2085 return -EFAULT;
2086 r = __copy_from_user(data, (void __user *)addr + offset, len);
2087 if (r)
2088 return -EFAULT;
2089 return 0;
2090}
2091
2092int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2093 int len)
2094{
2095 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2096
2097 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2098}
2099EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2100
2101int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2102 int offset, int len)
2103{
2104 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2105
2106 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2107}
2108EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2109
2110int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2111{
2112 gfn_t gfn = gpa >> PAGE_SHIFT;
2113 int seg;
2114 int offset = offset_in_page(gpa);
2115 int ret;
2116
2117 while ((seg = next_segment(len, offset)) != 0) {
2118 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2119 if (ret < 0)
2120 return ret;
2121 offset = 0;
2122 len -= seg;
2123 data += seg;
2124 ++gfn;
2125 }
2126 return 0;
2127}
2128EXPORT_SYMBOL_GPL(kvm_read_guest);
2129
2130int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2131{
2132 gfn_t gfn = gpa >> PAGE_SHIFT;
2133 int seg;
2134 int offset = offset_in_page(gpa);
2135 int ret;
2136
2137 while ((seg = next_segment(len, offset)) != 0) {
2138 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2139 if (ret < 0)
2140 return ret;
2141 offset = 0;
2142 len -= seg;
2143 data += seg;
2144 ++gfn;
2145 }
2146 return 0;
2147}
2148EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2149
2150static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2151 void *data, int offset, unsigned long len)
2152{
2153 int r;
2154 unsigned long addr;
2155
2156 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2157 if (kvm_is_error_hva(addr))
2158 return -EFAULT;
2159 pagefault_disable();
2160 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2161 pagefault_enable();
2162 if (r)
2163 return -EFAULT;
2164 return 0;
2165}
2166
2167int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
2168 unsigned long len)
2169{
2170 gfn_t gfn = gpa >> PAGE_SHIFT;
2171 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2172 int offset = offset_in_page(gpa);
2173
2174 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2175}
2176EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
2177
2178int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2179 void *data, unsigned long len)
2180{
2181 gfn_t gfn = gpa >> PAGE_SHIFT;
2182 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2183 int offset = offset_in_page(gpa);
2184
2185 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2186}
2187EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2188
2189static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
2190 const void *data, int offset, int len)
2191{
2192 int r;
2193 unsigned long addr;
2194
2195 addr = gfn_to_hva_memslot(memslot, gfn);
2196 if (kvm_is_error_hva(addr))
2197 return -EFAULT;
2198 r = __copy_to_user((void __user *)addr + offset, data, len);
2199 if (r)
2200 return -EFAULT;
2201 mark_page_dirty_in_slot(memslot, gfn);
2202 return 0;
2203}
2204
2205int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2206 const void *data, int offset, int len)
2207{
2208 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2209
2210 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2211}
2212EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2213
2214int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2215 const void *data, int offset, int len)
2216{
2217 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2218
2219 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2220}
2221EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2222
2223int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2224 unsigned long len)
2225{
2226 gfn_t gfn = gpa >> PAGE_SHIFT;
2227 int seg;
2228 int offset = offset_in_page(gpa);
2229 int ret;
2230
2231 while ((seg = next_segment(len, offset)) != 0) {
2232 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2233 if (ret < 0)
2234 return ret;
2235 offset = 0;
2236 len -= seg;
2237 data += seg;
2238 ++gfn;
2239 }
2240 return 0;
2241}
2242EXPORT_SYMBOL_GPL(kvm_write_guest);
2243
2244int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2245 unsigned long len)
2246{
2247 gfn_t gfn = gpa >> PAGE_SHIFT;
2248 int seg;
2249 int offset = offset_in_page(gpa);
2250 int ret;
2251
2252 while ((seg = next_segment(len, offset)) != 0) {
2253 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2254 if (ret < 0)
2255 return ret;
2256 offset = 0;
2257 len -= seg;
2258 data += seg;
2259 ++gfn;
2260 }
2261 return 0;
2262}
2263EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2264
2265static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2266 struct gfn_to_hva_cache *ghc,
2267 gpa_t gpa, unsigned long len)
2268{
2269 int offset = offset_in_page(gpa);
2270 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2271 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2272 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2273 gfn_t nr_pages_avail;
David Brazdil0f672f62019-12-10 10:32:29 +00002274 int r = start_gfn <= end_gfn ? 0 : -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002275
2276 ghc->gpa = gpa;
2277 ghc->generation = slots->generation;
2278 ghc->len = len;
David Brazdil0f672f62019-12-10 10:32:29 +00002279 ghc->hva = KVM_HVA_ERR_BAD;
2280
2281 /*
2282 * If the requested region crosses two memslots, we still
2283 * verify that the entire region is valid here.
2284 */
2285 while (!r && start_gfn <= end_gfn) {
2286 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2287 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2288 &nr_pages_avail);
2289 if (kvm_is_error_hva(ghc->hva))
2290 r = -EFAULT;
2291 start_gfn += nr_pages_avail;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002292 }
David Brazdil0f672f62019-12-10 10:32:29 +00002293
2294 /* Use the slow path for cross page reads and writes. */
2295 if (!r && nr_pages_needed == 1)
2296 ghc->hva += offset;
2297 else
2298 ghc->memslot = NULL;
2299
2300 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002301}
2302
2303int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2304 gpa_t gpa, unsigned long len)
2305{
2306 struct kvm_memslots *slots = kvm_memslots(kvm);
2307 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2308}
2309EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2310
2311int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
David Brazdil0f672f62019-12-10 10:32:29 +00002312 void *data, unsigned int offset,
2313 unsigned long len)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002314{
2315 struct kvm_memslots *slots = kvm_memslots(kvm);
2316 int r;
2317 gpa_t gpa = ghc->gpa + offset;
2318
2319 BUG_ON(len + offset > ghc->len);
2320
2321 if (slots->generation != ghc->generation)
2322 __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
2323
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002324 if (kvm_is_error_hva(ghc->hva))
2325 return -EFAULT;
2326
Olivier Deprez0e641232021-09-23 10:07:05 +02002327 if (unlikely(!ghc->memslot))
2328 return kvm_write_guest(kvm, gpa, data, len);
2329
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002330 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2331 if (r)
2332 return -EFAULT;
2333 mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
2334
2335 return 0;
2336}
2337EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2338
2339int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2340 void *data, unsigned long len)
2341{
2342 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2343}
2344EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2345
2346int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2347 void *data, unsigned long len)
2348{
2349 struct kvm_memslots *slots = kvm_memslots(kvm);
2350 int r;
2351
2352 BUG_ON(len > ghc->len);
2353
2354 if (slots->generation != ghc->generation)
2355 __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
2356
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002357 if (kvm_is_error_hva(ghc->hva))
2358 return -EFAULT;
2359
Olivier Deprez0e641232021-09-23 10:07:05 +02002360 if (unlikely(!ghc->memslot))
2361 return kvm_read_guest(kvm, ghc->gpa, data, len);
2362
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002363 r = __copy_from_user(data, (void __user *)ghc->hva, len);
2364 if (r)
2365 return -EFAULT;
2366
2367 return 0;
2368}
2369EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2370
2371int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2372{
2373 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2374
2375 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2376}
2377EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2378
2379int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2380{
2381 gfn_t gfn = gpa >> PAGE_SHIFT;
2382 int seg;
2383 int offset = offset_in_page(gpa);
2384 int ret;
2385
2386 while ((seg = next_segment(len, offset)) != 0) {
2387 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2388 if (ret < 0)
2389 return ret;
2390 offset = 0;
2391 len -= seg;
2392 ++gfn;
2393 }
2394 return 0;
2395}
2396EXPORT_SYMBOL_GPL(kvm_clear_guest);
2397
2398static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2399 gfn_t gfn)
2400{
2401 if (memslot && memslot->dirty_bitmap) {
2402 unsigned long rel_gfn = gfn - memslot->base_gfn;
2403
2404 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2405 }
2406}
2407
2408void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2409{
2410 struct kvm_memory_slot *memslot;
2411
2412 memslot = gfn_to_memslot(kvm, gfn);
2413 mark_page_dirty_in_slot(memslot, gfn);
2414}
2415EXPORT_SYMBOL_GPL(mark_page_dirty);
2416
2417void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2418{
2419 struct kvm_memory_slot *memslot;
2420
2421 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2422 mark_page_dirty_in_slot(memslot, gfn);
2423}
2424EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2425
2426void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2427{
2428 if (!vcpu->sigset_active)
2429 return;
2430
2431 /*
2432 * This does a lockless modification of ->real_blocked, which is fine
2433 * because, only current can change ->real_blocked and all readers of
2434 * ->real_blocked don't care as long ->real_blocked is always a subset
2435 * of ->blocked.
2436 */
2437 sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
2438}
2439
2440void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2441{
2442 if (!vcpu->sigset_active)
2443 return;
2444
2445 sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
2446 sigemptyset(&current->real_blocked);
2447}
2448
2449static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2450{
David Brazdil0f672f62019-12-10 10:32:29 +00002451 unsigned int old, val, grow, grow_start;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002452
2453 old = val = vcpu->halt_poll_ns;
David Brazdil0f672f62019-12-10 10:32:29 +00002454 grow_start = READ_ONCE(halt_poll_ns_grow_start);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002455 grow = READ_ONCE(halt_poll_ns_grow);
David Brazdil0f672f62019-12-10 10:32:29 +00002456 if (!grow)
2457 goto out;
2458
2459 val *= grow;
2460 if (val < grow_start)
2461 val = grow_start;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002462
2463 if (val > halt_poll_ns)
2464 val = halt_poll_ns;
2465
2466 vcpu->halt_poll_ns = val;
David Brazdil0f672f62019-12-10 10:32:29 +00002467out:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002468 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2469}
2470
2471static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2472{
2473 unsigned int old, val, shrink;
2474
2475 old = val = vcpu->halt_poll_ns;
2476 shrink = READ_ONCE(halt_poll_ns_shrink);
2477 if (shrink == 0)
2478 val = 0;
2479 else
2480 val /= shrink;
2481
2482 vcpu->halt_poll_ns = val;
2483 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2484}
2485
2486static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2487{
2488 int ret = -EINTR;
2489 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2490
2491 if (kvm_arch_vcpu_runnable(vcpu)) {
2492 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2493 goto out;
2494 }
2495 if (kvm_cpu_has_pending_timer(vcpu))
2496 goto out;
2497 if (signal_pending(current))
2498 goto out;
2499
2500 ret = 0;
2501out:
2502 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2503 return ret;
2504}
2505
2506/*
2507 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2508 */
2509void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2510{
2511 ktime_t start, cur;
2512 DECLARE_SWAITQUEUE(wait);
2513 bool waited = false;
2514 u64 block_ns;
2515
David Brazdil0f672f62019-12-10 10:32:29 +00002516 kvm_arch_vcpu_blocking(vcpu);
2517
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002518 start = cur = ktime_get();
David Brazdil0f672f62019-12-10 10:32:29 +00002519 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002520 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2521
2522 ++vcpu->stat.halt_attempted_poll;
2523 do {
2524 /*
2525 * This sets KVM_REQ_UNHALT if an interrupt
2526 * arrives.
2527 */
2528 if (kvm_vcpu_check_block(vcpu) < 0) {
2529 ++vcpu->stat.halt_successful_poll;
2530 if (!vcpu_valid_wakeup(vcpu))
2531 ++vcpu->stat.halt_poll_invalid;
2532 goto out;
2533 }
2534 cur = ktime_get();
2535 } while (single_task_running() && ktime_before(cur, stop));
2536 }
2537
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002538 for (;;) {
2539 prepare_to_swait_exclusive(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2540
2541 if (kvm_vcpu_check_block(vcpu) < 0)
2542 break;
2543
2544 waited = true;
2545 schedule();
2546 }
2547
2548 finish_swait(&vcpu->wq, &wait);
2549 cur = ktime_get();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002550out:
David Brazdil0f672f62019-12-10 10:32:29 +00002551 kvm_arch_vcpu_unblocking(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002552 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2553
David Brazdil0f672f62019-12-10 10:32:29 +00002554 if (!kvm_arch_no_poll(vcpu)) {
2555 if (!vcpu_valid_wakeup(vcpu)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002556 shrink_halt_poll_ns(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +00002557 } else if (halt_poll_ns) {
2558 if (block_ns <= vcpu->halt_poll_ns)
2559 ;
2560 /* we had a long block, shrink polling */
2561 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2562 shrink_halt_poll_ns(vcpu);
2563 /* we had a short halt and our poll time is too small */
2564 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2565 block_ns < halt_poll_ns)
2566 grow_halt_poll_ns(vcpu);
2567 } else {
2568 vcpu->halt_poll_ns = 0;
2569 }
2570 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002571
2572 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2573 kvm_arch_vcpu_block_finish(vcpu);
2574}
2575EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2576
2577bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2578{
2579 struct swait_queue_head *wqp;
2580
2581 wqp = kvm_arch_vcpu_wq(vcpu);
2582 if (swq_has_sleeper(wqp)) {
2583 swake_up_one(wqp);
David Brazdil0f672f62019-12-10 10:32:29 +00002584 WRITE_ONCE(vcpu->ready, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002585 ++vcpu->stat.halt_wakeup;
2586 return true;
2587 }
2588
2589 return false;
2590}
2591EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2592
2593#ifndef CONFIG_S390
2594/*
2595 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2596 */
2597void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2598{
2599 int me;
2600 int cpu = vcpu->cpu;
2601
2602 if (kvm_vcpu_wake_up(vcpu))
2603 return;
2604
2605 me = get_cpu();
2606 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2607 if (kvm_arch_vcpu_should_kick(vcpu))
2608 smp_send_reschedule(cpu);
2609 put_cpu();
2610}
2611EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2612#endif /* !CONFIG_S390 */
2613
2614int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2615{
2616 struct pid *pid;
2617 struct task_struct *task = NULL;
2618 int ret = 0;
2619
2620 rcu_read_lock();
2621 pid = rcu_dereference(target->pid);
2622 if (pid)
2623 task = get_pid_task(pid, PIDTYPE_PID);
2624 rcu_read_unlock();
2625 if (!task)
2626 return ret;
2627 ret = yield_to(task, 1);
2628 put_task_struct(task);
2629
2630 return ret;
2631}
2632EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2633
2634/*
2635 * Helper that checks whether a VCPU is eligible for directed yield.
2636 * Most eligible candidate to yield is decided by following heuristics:
2637 *
2638 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2639 * (preempted lock holder), indicated by @in_spin_loop.
2640 * Set at the beiginning and cleared at the end of interception/PLE handler.
2641 *
2642 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2643 * chance last time (mostly it has become eligible now since we have probably
2644 * yielded to lockholder in last iteration. This is done by toggling
2645 * @dy_eligible each time a VCPU checked for eligibility.)
2646 *
2647 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2648 * to preempted lock-holder could result in wrong VCPU selection and CPU
2649 * burning. Giving priority for a potential lock-holder increases lock
2650 * progress.
2651 *
2652 * Since algorithm is based on heuristics, accessing another VCPU data without
2653 * locking does not harm. It may result in trying to yield to same VCPU, fail
2654 * and continue with next VCPU and so on.
2655 */
2656static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2657{
2658#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2659 bool eligible;
2660
2661 eligible = !vcpu->spin_loop.in_spin_loop ||
2662 vcpu->spin_loop.dy_eligible;
2663
2664 if (vcpu->spin_loop.in_spin_loop)
2665 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2666
2667 return eligible;
2668#else
2669 return true;
2670#endif
2671}
2672
David Brazdil0f672f62019-12-10 10:32:29 +00002673/*
2674 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2675 * a vcpu_load/vcpu_put pair. However, for most architectures
2676 * kvm_arch_vcpu_runnable does not require vcpu_load.
2677 */
2678bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2679{
2680 return kvm_arch_vcpu_runnable(vcpu);
2681}
2682
2683static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2684{
2685 if (kvm_arch_dy_runnable(vcpu))
2686 return true;
2687
2688#ifdef CONFIG_KVM_ASYNC_PF
2689 if (!list_empty_careful(&vcpu->async_pf.done))
2690 return true;
2691#endif
2692
2693 return false;
2694}
2695
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002696void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
2697{
2698 struct kvm *kvm = me->kvm;
2699 struct kvm_vcpu *vcpu;
2700 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2701 int yielded = 0;
2702 int try = 3;
2703 int pass;
2704 int i;
2705
2706 kvm_vcpu_set_in_spin_loop(me, true);
2707 /*
2708 * We boost the priority of a VCPU that is runnable but not
2709 * currently running, because it got preempted by something
2710 * else and called schedule in __vcpu_run. Hopefully that
2711 * VCPU is holding the lock that we need and will release it.
2712 * We approximate round-robin by starting at the last boosted VCPU.
2713 */
2714 for (pass = 0; pass < 2 && !yielded && try; pass++) {
2715 kvm_for_each_vcpu(i, vcpu, kvm) {
2716 if (!pass && i <= last_boosted_vcpu) {
2717 i = last_boosted_vcpu;
2718 continue;
2719 } else if (pass && i > last_boosted_vcpu)
2720 break;
David Brazdil0f672f62019-12-10 10:32:29 +00002721 if (!READ_ONCE(vcpu->ready))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002722 continue;
2723 if (vcpu == me)
2724 continue;
David Brazdil0f672f62019-12-10 10:32:29 +00002725 if (swait_active(&vcpu->wq) && !vcpu_dy_runnable(vcpu))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002726 continue;
David Brazdil0f672f62019-12-10 10:32:29 +00002727 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
2728 !kvm_arch_vcpu_in_kernel(vcpu))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002729 continue;
2730 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2731 continue;
2732
2733 yielded = kvm_vcpu_yield_to(vcpu);
2734 if (yielded > 0) {
2735 kvm->last_boosted_vcpu = i;
2736 break;
2737 } else if (yielded < 0) {
2738 try--;
2739 if (!try)
2740 break;
2741 }
2742 }
2743 }
2744 kvm_vcpu_set_in_spin_loop(me, false);
2745
2746 /* Ensure vcpu is not eligible during next spinloop */
2747 kvm_vcpu_set_dy_eligible(me, false);
2748}
2749EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2750
2751static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
2752{
2753 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
2754 struct page *page;
2755
2756 if (vmf->pgoff == 0)
2757 page = virt_to_page(vcpu->run);
2758#ifdef CONFIG_X86
2759 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2760 page = virt_to_page(vcpu->arch.pio_data);
2761#endif
2762#ifdef CONFIG_KVM_MMIO
2763 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2764 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2765#endif
2766 else
2767 return kvm_arch_vcpu_fault(vcpu, vmf);
2768 get_page(page);
2769 vmf->page = page;
2770 return 0;
2771}
2772
2773static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2774 .fault = kvm_vcpu_fault,
2775};
2776
2777static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2778{
2779 vma->vm_ops = &kvm_vcpu_vm_ops;
2780 return 0;
2781}
2782
2783static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2784{
2785 struct kvm_vcpu *vcpu = filp->private_data;
2786
2787 debugfs_remove_recursive(vcpu->debugfs_dentry);
2788 kvm_put_kvm(vcpu->kvm);
2789 return 0;
2790}
2791
2792static struct file_operations kvm_vcpu_fops = {
2793 .release = kvm_vcpu_release,
2794 .unlocked_ioctl = kvm_vcpu_ioctl,
2795 .mmap = kvm_vcpu_mmap,
2796 .llseek = noop_llseek,
2797 KVM_COMPAT(kvm_vcpu_compat_ioctl),
2798};
2799
2800/*
2801 * Allocates an inode for the vcpu.
2802 */
2803static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2804{
2805 char name[8 + 1 + ITOA_MAX_LEN + 1];
2806
2807 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
2808 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2809}
2810
David Brazdil0f672f62019-12-10 10:32:29 +00002811static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002812{
David Brazdil0f672f62019-12-10 10:32:29 +00002813#ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002814 char dir_name[ITOA_MAX_LEN * 2];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002815
2816 if (!debugfs_initialized())
David Brazdil0f672f62019-12-10 10:32:29 +00002817 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002818
2819 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2820 vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
David Brazdil0f672f62019-12-10 10:32:29 +00002821 vcpu->kvm->debugfs_dentry);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002822
David Brazdil0f672f62019-12-10 10:32:29 +00002823 kvm_arch_create_vcpu_debugfs(vcpu);
2824#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002825}
2826
2827/*
2828 * Creates some virtual cpus. Good luck creating more than one.
2829 */
2830static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
2831{
2832 int r;
2833 struct kvm_vcpu *vcpu;
2834
2835 if (id >= KVM_MAX_VCPU_ID)
2836 return -EINVAL;
2837
2838 mutex_lock(&kvm->lock);
2839 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
2840 mutex_unlock(&kvm->lock);
2841 return -EINVAL;
2842 }
2843
2844 kvm->created_vcpus++;
2845 mutex_unlock(&kvm->lock);
2846
2847 vcpu = kvm_arch_vcpu_create(kvm, id);
2848 if (IS_ERR(vcpu)) {
2849 r = PTR_ERR(vcpu);
2850 goto vcpu_decrement;
2851 }
2852
2853 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2854
2855 r = kvm_arch_vcpu_setup(vcpu);
2856 if (r)
2857 goto vcpu_destroy;
2858
David Brazdil0f672f62019-12-10 10:32:29 +00002859 kvm_create_vcpu_debugfs(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002860
2861 mutex_lock(&kvm->lock);
2862 if (kvm_get_vcpu_by_id(kvm, id)) {
2863 r = -EEXIST;
2864 goto unlock_vcpu_destroy;
2865 }
2866
2867 BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
2868
2869 /* Now it's all set up, let userspace reach it */
2870 kvm_get_kvm(kvm);
2871 r = create_vcpu_fd(vcpu);
2872 if (r < 0) {
2873 kvm_put_kvm(kvm);
2874 goto unlock_vcpu_destroy;
2875 }
2876
2877 kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
2878
2879 /*
2880 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
2881 * before kvm->online_vcpu's incremented value.
2882 */
2883 smp_wmb();
2884 atomic_inc(&kvm->online_vcpus);
2885
2886 mutex_unlock(&kvm->lock);
2887 kvm_arch_vcpu_postcreate(vcpu);
2888 return r;
2889
2890unlock_vcpu_destroy:
2891 mutex_unlock(&kvm->lock);
2892 debugfs_remove_recursive(vcpu->debugfs_dentry);
2893vcpu_destroy:
2894 kvm_arch_vcpu_destroy(vcpu);
2895vcpu_decrement:
2896 mutex_lock(&kvm->lock);
2897 kvm->created_vcpus--;
2898 mutex_unlock(&kvm->lock);
2899 return r;
2900}
2901
2902static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2903{
2904 if (sigset) {
2905 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2906 vcpu->sigset_active = 1;
2907 vcpu->sigset = *sigset;
2908 } else
2909 vcpu->sigset_active = 0;
2910 return 0;
2911}
2912
2913static long kvm_vcpu_ioctl(struct file *filp,
2914 unsigned int ioctl, unsigned long arg)
2915{
2916 struct kvm_vcpu *vcpu = filp->private_data;
2917 void __user *argp = (void __user *)arg;
2918 int r;
2919 struct kvm_fpu *fpu = NULL;
2920 struct kvm_sregs *kvm_sregs = NULL;
2921
2922 if (vcpu->kvm->mm != current->mm)
2923 return -EIO;
2924
2925 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2926 return -EINVAL;
2927
2928 /*
2929 * Some architectures have vcpu ioctls that are asynchronous to vcpu
2930 * execution; mutex_lock() would break them.
2931 */
2932 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
2933 if (r != -ENOIOCTLCMD)
2934 return r;
2935
2936 if (mutex_lock_killable(&vcpu->mutex))
2937 return -EINTR;
2938 switch (ioctl) {
2939 case KVM_RUN: {
2940 struct pid *oldpid;
2941 r = -EINVAL;
2942 if (arg)
2943 goto out;
2944 oldpid = rcu_access_pointer(vcpu->pid);
2945 if (unlikely(oldpid != task_pid(current))) {
2946 /* The thread running this VCPU changed. */
2947 struct pid *newpid;
2948
2949 r = kvm_arch_vcpu_run_pid_change(vcpu);
2950 if (r)
2951 break;
2952
2953 newpid = get_task_pid(current, PIDTYPE_PID);
2954 rcu_assign_pointer(vcpu->pid, newpid);
2955 if (oldpid)
2956 synchronize_rcu();
2957 put_pid(oldpid);
2958 }
2959 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
2960 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
2961 break;
2962 }
2963 case KVM_GET_REGS: {
2964 struct kvm_regs *kvm_regs;
2965
2966 r = -ENOMEM;
David Brazdil0f672f62019-12-10 10:32:29 +00002967 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002968 if (!kvm_regs)
2969 goto out;
2970 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2971 if (r)
2972 goto out_free1;
2973 r = -EFAULT;
2974 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2975 goto out_free1;
2976 r = 0;
2977out_free1:
2978 kfree(kvm_regs);
2979 break;
2980 }
2981 case KVM_SET_REGS: {
2982 struct kvm_regs *kvm_regs;
2983
2984 r = -ENOMEM;
2985 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2986 if (IS_ERR(kvm_regs)) {
2987 r = PTR_ERR(kvm_regs);
2988 goto out;
2989 }
2990 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
2991 kfree(kvm_regs);
2992 break;
2993 }
2994 case KVM_GET_SREGS: {
David Brazdil0f672f62019-12-10 10:32:29 +00002995 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
2996 GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002997 r = -ENOMEM;
2998 if (!kvm_sregs)
2999 goto out;
3000 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3001 if (r)
3002 goto out;
3003 r = -EFAULT;
3004 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3005 goto out;
3006 r = 0;
3007 break;
3008 }
3009 case KVM_SET_SREGS: {
3010 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3011 if (IS_ERR(kvm_sregs)) {
3012 r = PTR_ERR(kvm_sregs);
3013 kvm_sregs = NULL;
3014 goto out;
3015 }
3016 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3017 break;
3018 }
3019 case KVM_GET_MP_STATE: {
3020 struct kvm_mp_state mp_state;
3021
3022 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3023 if (r)
3024 goto out;
3025 r = -EFAULT;
3026 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3027 goto out;
3028 r = 0;
3029 break;
3030 }
3031 case KVM_SET_MP_STATE: {
3032 struct kvm_mp_state mp_state;
3033
3034 r = -EFAULT;
3035 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3036 goto out;
3037 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3038 break;
3039 }
3040 case KVM_TRANSLATE: {
3041 struct kvm_translation tr;
3042
3043 r = -EFAULT;
3044 if (copy_from_user(&tr, argp, sizeof(tr)))
3045 goto out;
3046 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3047 if (r)
3048 goto out;
3049 r = -EFAULT;
3050 if (copy_to_user(argp, &tr, sizeof(tr)))
3051 goto out;
3052 r = 0;
3053 break;
3054 }
3055 case KVM_SET_GUEST_DEBUG: {
3056 struct kvm_guest_debug dbg;
3057
3058 r = -EFAULT;
3059 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3060 goto out;
3061 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3062 break;
3063 }
3064 case KVM_SET_SIGNAL_MASK: {
3065 struct kvm_signal_mask __user *sigmask_arg = argp;
3066 struct kvm_signal_mask kvm_sigmask;
3067 sigset_t sigset, *p;
3068
3069 p = NULL;
3070 if (argp) {
3071 r = -EFAULT;
3072 if (copy_from_user(&kvm_sigmask, argp,
3073 sizeof(kvm_sigmask)))
3074 goto out;
3075 r = -EINVAL;
3076 if (kvm_sigmask.len != sizeof(sigset))
3077 goto out;
3078 r = -EFAULT;
3079 if (copy_from_user(&sigset, sigmask_arg->sigset,
3080 sizeof(sigset)))
3081 goto out;
3082 p = &sigset;
3083 }
3084 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3085 break;
3086 }
3087 case KVM_GET_FPU: {
David Brazdil0f672f62019-12-10 10:32:29 +00003088 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003089 r = -ENOMEM;
3090 if (!fpu)
3091 goto out;
3092 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3093 if (r)
3094 goto out;
3095 r = -EFAULT;
3096 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3097 goto out;
3098 r = 0;
3099 break;
3100 }
3101 case KVM_SET_FPU: {
3102 fpu = memdup_user(argp, sizeof(*fpu));
3103 if (IS_ERR(fpu)) {
3104 r = PTR_ERR(fpu);
3105 fpu = NULL;
3106 goto out;
3107 }
3108 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3109 break;
3110 }
3111 default:
3112 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3113 }
3114out:
3115 mutex_unlock(&vcpu->mutex);
3116 kfree(fpu);
3117 kfree(kvm_sregs);
3118 return r;
3119}
3120
3121#ifdef CONFIG_KVM_COMPAT
3122static long kvm_vcpu_compat_ioctl(struct file *filp,
3123 unsigned int ioctl, unsigned long arg)
3124{
3125 struct kvm_vcpu *vcpu = filp->private_data;
3126 void __user *argp = compat_ptr(arg);
3127 int r;
3128
3129 if (vcpu->kvm->mm != current->mm)
3130 return -EIO;
3131
3132 switch (ioctl) {
3133 case KVM_SET_SIGNAL_MASK: {
3134 struct kvm_signal_mask __user *sigmask_arg = argp;
3135 struct kvm_signal_mask kvm_sigmask;
3136 sigset_t sigset;
3137
3138 if (argp) {
3139 r = -EFAULT;
3140 if (copy_from_user(&kvm_sigmask, argp,
3141 sizeof(kvm_sigmask)))
3142 goto out;
3143 r = -EINVAL;
3144 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3145 goto out;
3146 r = -EFAULT;
3147 if (get_compat_sigset(&sigset, (void *)sigmask_arg->sigset))
3148 goto out;
3149 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3150 } else
3151 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3152 break;
3153 }
3154 default:
3155 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3156 }
3157
3158out:
3159 return r;
3160}
3161#endif
3162
David Brazdil0f672f62019-12-10 10:32:29 +00003163static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3164{
3165 struct kvm_device *dev = filp->private_data;
3166
3167 if (dev->ops->mmap)
3168 return dev->ops->mmap(dev, vma);
3169
3170 return -ENODEV;
3171}
3172
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003173static int kvm_device_ioctl_attr(struct kvm_device *dev,
3174 int (*accessor)(struct kvm_device *dev,
3175 struct kvm_device_attr *attr),
3176 unsigned long arg)
3177{
3178 struct kvm_device_attr attr;
3179
3180 if (!accessor)
3181 return -EPERM;
3182
3183 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3184 return -EFAULT;
3185
3186 return accessor(dev, &attr);
3187}
3188
3189static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3190 unsigned long arg)
3191{
3192 struct kvm_device *dev = filp->private_data;
3193
David Brazdil0f672f62019-12-10 10:32:29 +00003194 if (dev->kvm->mm != current->mm)
3195 return -EIO;
3196
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003197 switch (ioctl) {
3198 case KVM_SET_DEVICE_ATTR:
3199 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3200 case KVM_GET_DEVICE_ATTR:
3201 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3202 case KVM_HAS_DEVICE_ATTR:
3203 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3204 default:
3205 if (dev->ops->ioctl)
3206 return dev->ops->ioctl(dev, ioctl, arg);
3207
3208 return -ENOTTY;
3209 }
3210}
3211
3212static int kvm_device_release(struct inode *inode, struct file *filp)
3213{
3214 struct kvm_device *dev = filp->private_data;
3215 struct kvm *kvm = dev->kvm;
3216
David Brazdil0f672f62019-12-10 10:32:29 +00003217 if (dev->ops->release) {
3218 mutex_lock(&kvm->lock);
3219 list_del(&dev->vm_node);
3220 dev->ops->release(dev);
3221 mutex_unlock(&kvm->lock);
3222 }
3223
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003224 kvm_put_kvm(kvm);
3225 return 0;
3226}
3227
3228static const struct file_operations kvm_device_fops = {
3229 .unlocked_ioctl = kvm_device_ioctl,
3230 .release = kvm_device_release,
3231 KVM_COMPAT(kvm_device_ioctl),
David Brazdil0f672f62019-12-10 10:32:29 +00003232 .mmap = kvm_device_mmap,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003233};
3234
3235struct kvm_device *kvm_device_from_filp(struct file *filp)
3236{
3237 if (filp->f_op != &kvm_device_fops)
3238 return NULL;
3239
3240 return filp->private_data;
3241}
3242
3243static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
3244#ifdef CONFIG_KVM_MPIC
3245 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3246 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3247#endif
3248};
3249
3250int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
3251{
3252 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3253 return -ENOSPC;
3254
3255 if (kvm_device_ops_table[type] != NULL)
3256 return -EEXIST;
3257
3258 kvm_device_ops_table[type] = ops;
3259 return 0;
3260}
3261
3262void kvm_unregister_device_ops(u32 type)
3263{
3264 if (kvm_device_ops_table[type] != NULL)
3265 kvm_device_ops_table[type] = NULL;
3266}
3267
3268static int kvm_ioctl_create_device(struct kvm *kvm,
3269 struct kvm_create_device *cd)
3270{
3271 struct kvm_device_ops *ops = NULL;
3272 struct kvm_device *dev;
3273 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
David Brazdil0f672f62019-12-10 10:32:29 +00003274 int type;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003275 int ret;
3276
3277 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3278 return -ENODEV;
3279
David Brazdil0f672f62019-12-10 10:32:29 +00003280 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3281 ops = kvm_device_ops_table[type];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003282 if (ops == NULL)
3283 return -ENODEV;
3284
3285 if (test)
3286 return 0;
3287
David Brazdil0f672f62019-12-10 10:32:29 +00003288 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003289 if (!dev)
3290 return -ENOMEM;
3291
3292 dev->ops = ops;
3293 dev->kvm = kvm;
3294
3295 mutex_lock(&kvm->lock);
David Brazdil0f672f62019-12-10 10:32:29 +00003296 ret = ops->create(dev, type);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003297 if (ret < 0) {
3298 mutex_unlock(&kvm->lock);
3299 kfree(dev);
3300 return ret;
3301 }
3302 list_add(&dev->vm_node, &kvm->devices);
3303 mutex_unlock(&kvm->lock);
3304
3305 if (ops->init)
3306 ops->init(dev);
3307
David Brazdil0f672f62019-12-10 10:32:29 +00003308 kvm_get_kvm(kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003309 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3310 if (ret < 0) {
David Brazdil0f672f62019-12-10 10:32:29 +00003311 kvm_put_kvm(kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003312 mutex_lock(&kvm->lock);
3313 list_del(&dev->vm_node);
3314 mutex_unlock(&kvm->lock);
3315 ops->destroy(dev);
3316 return ret;
3317 }
3318
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003319 cd->fd = ret;
3320 return 0;
3321}
3322
3323static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3324{
3325 switch (arg) {
3326 case KVM_CAP_USER_MEMORY:
3327 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3328 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3329 case KVM_CAP_INTERNAL_ERROR_DATA:
3330#ifdef CONFIG_HAVE_KVM_MSI
3331 case KVM_CAP_SIGNAL_MSI:
3332#endif
3333#ifdef CONFIG_HAVE_KVM_IRQFD
3334 case KVM_CAP_IRQFD:
3335 case KVM_CAP_IRQFD_RESAMPLE:
3336#endif
3337 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3338 case KVM_CAP_CHECK_EXTENSION_VM:
David Brazdil0f672f62019-12-10 10:32:29 +00003339 case KVM_CAP_ENABLE_CAP_VM:
3340#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3341 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
3342#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003343 return 1;
3344#ifdef CONFIG_KVM_MMIO
3345 case KVM_CAP_COALESCED_MMIO:
3346 return KVM_COALESCED_MMIO_PAGE_OFFSET;
David Brazdil0f672f62019-12-10 10:32:29 +00003347 case KVM_CAP_COALESCED_PIO:
3348 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003349#endif
3350#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3351 case KVM_CAP_IRQ_ROUTING:
3352 return KVM_MAX_IRQ_ROUTES;
3353#endif
3354#if KVM_ADDRESS_SPACE_NUM > 1
3355 case KVM_CAP_MULTI_ADDRESS_SPACE:
3356 return KVM_ADDRESS_SPACE_NUM;
3357#endif
David Brazdil0f672f62019-12-10 10:32:29 +00003358 case KVM_CAP_NR_MEMSLOTS:
3359 return KVM_USER_MEM_SLOTS;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003360 default:
3361 break;
3362 }
3363 return kvm_vm_ioctl_check_extension(kvm, arg);
3364}
3365
David Brazdil0f672f62019-12-10 10:32:29 +00003366int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3367 struct kvm_enable_cap *cap)
3368{
3369 return -EINVAL;
3370}
3371
3372static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
3373 struct kvm_enable_cap *cap)
3374{
3375 switch (cap->cap) {
3376#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3377 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
3378 if (cap->flags || (cap->args[0] & ~1))
3379 return -EINVAL;
3380 kvm->manual_dirty_log_protect = cap->args[0];
3381 return 0;
3382#endif
3383 default:
3384 return kvm_vm_ioctl_enable_cap(kvm, cap);
3385 }
3386}
3387
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003388static long kvm_vm_ioctl(struct file *filp,
3389 unsigned int ioctl, unsigned long arg)
3390{
3391 struct kvm *kvm = filp->private_data;
3392 void __user *argp = (void __user *)arg;
3393 int r;
3394
3395 if (kvm->mm != current->mm)
3396 return -EIO;
3397 switch (ioctl) {
3398 case KVM_CREATE_VCPU:
3399 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3400 break;
David Brazdil0f672f62019-12-10 10:32:29 +00003401 case KVM_ENABLE_CAP: {
3402 struct kvm_enable_cap cap;
3403
3404 r = -EFAULT;
3405 if (copy_from_user(&cap, argp, sizeof(cap)))
3406 goto out;
3407 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
3408 break;
3409 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003410 case KVM_SET_USER_MEMORY_REGION: {
3411 struct kvm_userspace_memory_region kvm_userspace_mem;
3412
3413 r = -EFAULT;
3414 if (copy_from_user(&kvm_userspace_mem, argp,
3415 sizeof(kvm_userspace_mem)))
3416 goto out;
3417
3418 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3419 break;
3420 }
3421 case KVM_GET_DIRTY_LOG: {
3422 struct kvm_dirty_log log;
3423
3424 r = -EFAULT;
3425 if (copy_from_user(&log, argp, sizeof(log)))
3426 goto out;
3427 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3428 break;
3429 }
David Brazdil0f672f62019-12-10 10:32:29 +00003430#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3431 case KVM_CLEAR_DIRTY_LOG: {
3432 struct kvm_clear_dirty_log log;
3433
3434 r = -EFAULT;
3435 if (copy_from_user(&log, argp, sizeof(log)))
3436 goto out;
3437 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3438 break;
3439 }
3440#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003441#ifdef CONFIG_KVM_MMIO
3442 case KVM_REGISTER_COALESCED_MMIO: {
3443 struct kvm_coalesced_mmio_zone zone;
3444
3445 r = -EFAULT;
3446 if (copy_from_user(&zone, argp, sizeof(zone)))
3447 goto out;
3448 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3449 break;
3450 }
3451 case KVM_UNREGISTER_COALESCED_MMIO: {
3452 struct kvm_coalesced_mmio_zone zone;
3453
3454 r = -EFAULT;
3455 if (copy_from_user(&zone, argp, sizeof(zone)))
3456 goto out;
3457 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3458 break;
3459 }
3460#endif
3461 case KVM_IRQFD: {
3462 struct kvm_irqfd data;
3463
3464 r = -EFAULT;
3465 if (copy_from_user(&data, argp, sizeof(data)))
3466 goto out;
3467 r = kvm_irqfd(kvm, &data);
3468 break;
3469 }
3470 case KVM_IOEVENTFD: {
3471 struct kvm_ioeventfd data;
3472
3473 r = -EFAULT;
3474 if (copy_from_user(&data, argp, sizeof(data)))
3475 goto out;
3476 r = kvm_ioeventfd(kvm, &data);
3477 break;
3478 }
3479#ifdef CONFIG_HAVE_KVM_MSI
3480 case KVM_SIGNAL_MSI: {
3481 struct kvm_msi msi;
3482
3483 r = -EFAULT;
3484 if (copy_from_user(&msi, argp, sizeof(msi)))
3485 goto out;
3486 r = kvm_send_userspace_msi(kvm, &msi);
3487 break;
3488 }
3489#endif
3490#ifdef __KVM_HAVE_IRQ_LINE
3491 case KVM_IRQ_LINE_STATUS:
3492 case KVM_IRQ_LINE: {
3493 struct kvm_irq_level irq_event;
3494
3495 r = -EFAULT;
3496 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3497 goto out;
3498
3499 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3500 ioctl == KVM_IRQ_LINE_STATUS);
3501 if (r)
3502 goto out;
3503
3504 r = -EFAULT;
3505 if (ioctl == KVM_IRQ_LINE_STATUS) {
3506 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3507 goto out;
3508 }
3509
3510 r = 0;
3511 break;
3512 }
3513#endif
3514#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3515 case KVM_SET_GSI_ROUTING: {
3516 struct kvm_irq_routing routing;
3517 struct kvm_irq_routing __user *urouting;
3518 struct kvm_irq_routing_entry *entries = NULL;
3519
3520 r = -EFAULT;
3521 if (copy_from_user(&routing, argp, sizeof(routing)))
3522 goto out;
3523 r = -EINVAL;
3524 if (!kvm_arch_can_set_irq_routing(kvm))
3525 goto out;
3526 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3527 goto out;
3528 if (routing.flags)
3529 goto out;
3530 if (routing.nr) {
3531 r = -ENOMEM;
3532 entries = vmalloc(array_size(sizeof(*entries),
3533 routing.nr));
3534 if (!entries)
3535 goto out;
3536 r = -EFAULT;
3537 urouting = argp;
3538 if (copy_from_user(entries, urouting->entries,
3539 routing.nr * sizeof(*entries)))
3540 goto out_free_irq_routing;
3541 }
3542 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3543 routing.flags);
3544out_free_irq_routing:
3545 vfree(entries);
3546 break;
3547 }
3548#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3549 case KVM_CREATE_DEVICE: {
3550 struct kvm_create_device cd;
3551
3552 r = -EFAULT;
3553 if (copy_from_user(&cd, argp, sizeof(cd)))
3554 goto out;
3555
3556 r = kvm_ioctl_create_device(kvm, &cd);
3557 if (r)
3558 goto out;
3559
3560 r = -EFAULT;
3561 if (copy_to_user(argp, &cd, sizeof(cd)))
3562 goto out;
3563
3564 r = 0;
3565 break;
3566 }
3567 case KVM_CHECK_EXTENSION:
3568 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3569 break;
3570 default:
3571 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3572 }
3573out:
3574 return r;
3575}
3576
3577#ifdef CONFIG_KVM_COMPAT
3578struct compat_kvm_dirty_log {
3579 __u32 slot;
3580 __u32 padding1;
3581 union {
3582 compat_uptr_t dirty_bitmap; /* one bit per page */
3583 __u64 padding2;
3584 };
3585};
3586
Olivier Deprez0e641232021-09-23 10:07:05 +02003587struct compat_kvm_clear_dirty_log {
3588 __u32 slot;
3589 __u32 num_pages;
3590 __u64 first_page;
3591 union {
3592 compat_uptr_t dirty_bitmap; /* one bit per page */
3593 __u64 padding2;
3594 };
3595};
3596
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003597static long kvm_vm_compat_ioctl(struct file *filp,
3598 unsigned int ioctl, unsigned long arg)
3599{
3600 struct kvm *kvm = filp->private_data;
3601 int r;
3602
3603 if (kvm->mm != current->mm)
3604 return -EIO;
3605 switch (ioctl) {
Olivier Deprez0e641232021-09-23 10:07:05 +02003606#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3607 case KVM_CLEAR_DIRTY_LOG: {
3608 struct compat_kvm_clear_dirty_log compat_log;
3609 struct kvm_clear_dirty_log log;
3610
3611 if (copy_from_user(&compat_log, (void __user *)arg,
3612 sizeof(compat_log)))
3613 return -EFAULT;
3614 log.slot = compat_log.slot;
3615 log.num_pages = compat_log.num_pages;
3616 log.first_page = compat_log.first_page;
3617 log.padding2 = compat_log.padding2;
3618 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3619
3620 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3621 break;
3622 }
3623#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003624 case KVM_GET_DIRTY_LOG: {
3625 struct compat_kvm_dirty_log compat_log;
3626 struct kvm_dirty_log log;
3627
3628 if (copy_from_user(&compat_log, (void __user *)arg,
3629 sizeof(compat_log)))
3630 return -EFAULT;
3631 log.slot = compat_log.slot;
3632 log.padding1 = compat_log.padding1;
3633 log.padding2 = compat_log.padding2;
3634 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3635
3636 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3637 break;
3638 }
3639 default:
3640 r = kvm_vm_ioctl(filp, ioctl, arg);
3641 }
3642 return r;
3643}
3644#endif
3645
3646static struct file_operations kvm_vm_fops = {
3647 .release = kvm_vm_release,
3648 .unlocked_ioctl = kvm_vm_ioctl,
3649 .llseek = noop_llseek,
3650 KVM_COMPAT(kvm_vm_compat_ioctl),
3651};
3652
3653static int kvm_dev_ioctl_create_vm(unsigned long type)
3654{
3655 int r;
3656 struct kvm *kvm;
3657 struct file *file;
3658
3659 kvm = kvm_create_vm(type);
3660 if (IS_ERR(kvm))
3661 return PTR_ERR(kvm);
3662#ifdef CONFIG_KVM_MMIO
3663 r = kvm_coalesced_mmio_init(kvm);
3664 if (r < 0)
3665 goto put_kvm;
3666#endif
3667 r = get_unused_fd_flags(O_CLOEXEC);
3668 if (r < 0)
3669 goto put_kvm;
3670
3671 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3672 if (IS_ERR(file)) {
3673 put_unused_fd(r);
3674 r = PTR_ERR(file);
3675 goto put_kvm;
3676 }
3677
3678 /*
3679 * Don't call kvm_put_kvm anymore at this point; file->f_op is
3680 * already set, with ->release() being kvm_vm_release(). In error
3681 * cases it will be called by the final fput(file) and will take
3682 * care of doing kvm_put_kvm(kvm).
3683 */
3684 if (kvm_create_vm_debugfs(kvm, r) < 0) {
3685 put_unused_fd(r);
3686 fput(file);
3687 return -ENOMEM;
3688 }
3689 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
3690
3691 fd_install(r, file);
3692 return r;
3693
3694put_kvm:
3695 kvm_put_kvm(kvm);
3696 return r;
3697}
3698
3699static long kvm_dev_ioctl(struct file *filp,
3700 unsigned int ioctl, unsigned long arg)
3701{
3702 long r = -EINVAL;
3703
3704 switch (ioctl) {
3705 case KVM_GET_API_VERSION:
3706 if (arg)
3707 goto out;
3708 r = KVM_API_VERSION;
3709 break;
3710 case KVM_CREATE_VM:
3711 r = kvm_dev_ioctl_create_vm(arg);
3712 break;
3713 case KVM_CHECK_EXTENSION:
3714 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3715 break;
3716 case KVM_GET_VCPU_MMAP_SIZE:
3717 if (arg)
3718 goto out;
3719 r = PAGE_SIZE; /* struct kvm_run */
3720#ifdef CONFIG_X86
3721 r += PAGE_SIZE; /* pio data page */
3722#endif
3723#ifdef CONFIG_KVM_MMIO
3724 r += PAGE_SIZE; /* coalesced mmio ring page */
3725#endif
3726 break;
3727 case KVM_TRACE_ENABLE:
3728 case KVM_TRACE_PAUSE:
3729 case KVM_TRACE_DISABLE:
3730 r = -EOPNOTSUPP;
3731 break;
3732 default:
3733 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3734 }
3735out:
3736 return r;
3737}
3738
3739static struct file_operations kvm_chardev_ops = {
3740 .unlocked_ioctl = kvm_dev_ioctl,
3741 .llseek = noop_llseek,
3742 KVM_COMPAT(kvm_dev_ioctl),
3743};
3744
3745static struct miscdevice kvm_dev = {
3746 KVM_MINOR,
3747 "kvm",
3748 &kvm_chardev_ops,
3749};
3750
3751static void hardware_enable_nolock(void *junk)
3752{
3753 int cpu = raw_smp_processor_id();
3754 int r;
3755
3756 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3757 return;
3758
3759 cpumask_set_cpu(cpu, cpus_hardware_enabled);
3760
3761 r = kvm_arch_hardware_enable();
3762
3763 if (r) {
3764 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3765 atomic_inc(&hardware_enable_failed);
3766 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3767 }
3768}
3769
3770static int kvm_starting_cpu(unsigned int cpu)
3771{
3772 raw_spin_lock(&kvm_count_lock);
3773 if (kvm_usage_count)
3774 hardware_enable_nolock(NULL);
3775 raw_spin_unlock(&kvm_count_lock);
3776 return 0;
3777}
3778
3779static void hardware_disable_nolock(void *junk)
3780{
3781 int cpu = raw_smp_processor_id();
3782
3783 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3784 return;
3785 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3786 kvm_arch_hardware_disable();
3787}
3788
3789static int kvm_dying_cpu(unsigned int cpu)
3790{
3791 raw_spin_lock(&kvm_count_lock);
3792 if (kvm_usage_count)
3793 hardware_disable_nolock(NULL);
3794 raw_spin_unlock(&kvm_count_lock);
3795 return 0;
3796}
3797
3798static void hardware_disable_all_nolock(void)
3799{
3800 BUG_ON(!kvm_usage_count);
3801
3802 kvm_usage_count--;
3803 if (!kvm_usage_count)
3804 on_each_cpu(hardware_disable_nolock, NULL, 1);
3805}
3806
3807static void hardware_disable_all(void)
3808{
3809 raw_spin_lock(&kvm_count_lock);
3810 hardware_disable_all_nolock();
3811 raw_spin_unlock(&kvm_count_lock);
3812}
3813
3814static int hardware_enable_all(void)
3815{
3816 int r = 0;
3817
3818 raw_spin_lock(&kvm_count_lock);
3819
3820 kvm_usage_count++;
3821 if (kvm_usage_count == 1) {
3822 atomic_set(&hardware_enable_failed, 0);
3823 on_each_cpu(hardware_enable_nolock, NULL, 1);
3824
3825 if (atomic_read(&hardware_enable_failed)) {
3826 hardware_disable_all_nolock();
3827 r = -EBUSY;
3828 }
3829 }
3830
3831 raw_spin_unlock(&kvm_count_lock);
3832
3833 return r;
3834}
3835
3836static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3837 void *v)
3838{
3839 /*
3840 * Some (well, at least mine) BIOSes hang on reboot if
3841 * in vmx root mode.
3842 *
3843 * And Intel TXT required VMX off for all cpu when system shutdown.
3844 */
3845 pr_info("kvm: exiting hardware virtualization\n");
3846 kvm_rebooting = true;
3847 on_each_cpu(hardware_disable_nolock, NULL, 1);
3848 return NOTIFY_OK;
3849}
3850
3851static struct notifier_block kvm_reboot_notifier = {
3852 .notifier_call = kvm_reboot,
3853 .priority = 0,
3854};
3855
3856static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3857{
3858 int i;
3859
3860 for (i = 0; i < bus->dev_count; i++) {
3861 struct kvm_io_device *pos = bus->range[i].dev;
3862
3863 kvm_iodevice_destructor(pos);
3864 }
3865 kfree(bus);
3866}
3867
3868static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
3869 const struct kvm_io_range *r2)
3870{
3871 gpa_t addr1 = r1->addr;
3872 gpa_t addr2 = r2->addr;
3873
3874 if (addr1 < addr2)
3875 return -1;
3876
3877 /* If r2->len == 0, match the exact address. If r2->len != 0,
3878 * accept any overlapping write. Any order is acceptable for
3879 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3880 * we process all of them.
3881 */
3882 if (r2->len) {
3883 addr1 += r1->len;
3884 addr2 += r2->len;
3885 }
3886
3887 if (addr1 > addr2)
3888 return 1;
3889
3890 return 0;
3891}
3892
3893static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3894{
3895 return kvm_io_bus_cmp(p1, p2);
3896}
3897
3898static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
3899 gpa_t addr, int len)
3900{
3901 struct kvm_io_range *range, key;
3902 int off;
3903
3904 key = (struct kvm_io_range) {
3905 .addr = addr,
3906 .len = len,
3907 };
3908
3909 range = bsearch(&key, bus->range, bus->dev_count,
3910 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3911 if (range == NULL)
3912 return -ENOENT;
3913
3914 off = range - bus->range;
3915
3916 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
3917 off--;
3918
3919 return off;
3920}
3921
3922static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3923 struct kvm_io_range *range, const void *val)
3924{
3925 int idx;
3926
3927 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3928 if (idx < 0)
3929 return -EOPNOTSUPP;
3930
3931 while (idx < bus->dev_count &&
3932 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3933 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
3934 range->len, val))
3935 return idx;
3936 idx++;
3937 }
3938
3939 return -EOPNOTSUPP;
3940}
3941
3942/* kvm_io_bus_write - called under kvm->slots_lock */
3943int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3944 int len, const void *val)
3945{
3946 struct kvm_io_bus *bus;
3947 struct kvm_io_range range;
3948 int r;
3949
3950 range = (struct kvm_io_range) {
3951 .addr = addr,
3952 .len = len,
3953 };
3954
3955 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3956 if (!bus)
3957 return -ENOMEM;
3958 r = __kvm_io_bus_write(vcpu, bus, &range, val);
3959 return r < 0 ? r : 0;
3960}
David Brazdil0f672f62019-12-10 10:32:29 +00003961EXPORT_SYMBOL_GPL(kvm_io_bus_write);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003962
3963/* kvm_io_bus_write_cookie - called under kvm->slots_lock */
3964int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
3965 gpa_t addr, int len, const void *val, long cookie)
3966{
3967 struct kvm_io_bus *bus;
3968 struct kvm_io_range range;
3969
3970 range = (struct kvm_io_range) {
3971 .addr = addr,
3972 .len = len,
3973 };
3974
3975 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3976 if (!bus)
3977 return -ENOMEM;
3978
3979 /* First try the device referenced by cookie. */
3980 if ((cookie >= 0) && (cookie < bus->dev_count) &&
3981 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
3982 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
3983 val))
3984 return cookie;
3985
3986 /*
3987 * cookie contained garbage; fall back to search and return the
3988 * correct cookie value.
3989 */
3990 return __kvm_io_bus_write(vcpu, bus, &range, val);
3991}
3992
3993static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3994 struct kvm_io_range *range, void *val)
3995{
3996 int idx;
3997
3998 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3999 if (idx < 0)
4000 return -EOPNOTSUPP;
4001
4002 while (idx < bus->dev_count &&
4003 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4004 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4005 range->len, val))
4006 return idx;
4007 idx++;
4008 }
4009
4010 return -EOPNOTSUPP;
4011}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004012
4013/* kvm_io_bus_read - called under kvm->slots_lock */
4014int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4015 int len, void *val)
4016{
4017 struct kvm_io_bus *bus;
4018 struct kvm_io_range range;
4019 int r;
4020
4021 range = (struct kvm_io_range) {
4022 .addr = addr,
4023 .len = len,
4024 };
4025
4026 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4027 if (!bus)
4028 return -ENOMEM;
4029 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4030 return r < 0 ? r : 0;
4031}
4032
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004033/* Caller must hold slots_lock. */
4034int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4035 int len, struct kvm_io_device *dev)
4036{
4037 int i;
4038 struct kvm_io_bus *new_bus, *bus;
4039 struct kvm_io_range range;
4040
4041 bus = kvm_get_bus(kvm, bus_idx);
4042 if (!bus)
4043 return -ENOMEM;
4044
4045 /* exclude ioeventfd which is limited by maximum fd */
4046 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
4047 return -ENOSPC;
4048
David Brazdil0f672f62019-12-10 10:32:29 +00004049 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
4050 GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004051 if (!new_bus)
4052 return -ENOMEM;
4053
4054 range = (struct kvm_io_range) {
4055 .addr = addr,
4056 .len = len,
4057 .dev = dev,
4058 };
4059
4060 for (i = 0; i < bus->dev_count; i++)
4061 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4062 break;
4063
4064 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4065 new_bus->dev_count++;
4066 new_bus->range[i] = range;
4067 memcpy(new_bus->range + i + 1, bus->range + i,
4068 (bus->dev_count - i) * sizeof(struct kvm_io_range));
4069 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4070 synchronize_srcu_expedited(&kvm->srcu);
4071 kfree(bus);
4072
4073 return 0;
4074}
4075
4076/* Caller must hold slots_lock. */
Olivier Deprez0e641232021-09-23 10:07:05 +02004077int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4078 struct kvm_io_device *dev)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004079{
Olivier Deprez0e641232021-09-23 10:07:05 +02004080 int i, j;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004081 struct kvm_io_bus *new_bus, *bus;
4082
4083 bus = kvm_get_bus(kvm, bus_idx);
4084 if (!bus)
Olivier Deprez0e641232021-09-23 10:07:05 +02004085 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004086
4087 for (i = 0; i < bus->dev_count; i++)
4088 if (bus->range[i].dev == dev) {
4089 break;
4090 }
4091
4092 if (i == bus->dev_count)
Olivier Deprez0e641232021-09-23 10:07:05 +02004093 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004094
David Brazdil0f672f62019-12-10 10:32:29 +00004095 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
4096 GFP_KERNEL_ACCOUNT);
Olivier Deprez0e641232021-09-23 10:07:05 +02004097 if (new_bus) {
4098 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4099 new_bus->dev_count--;
4100 memcpy(new_bus->range + i, bus->range + i + 1,
4101 (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
4102 } else {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004103 pr_err("kvm: failed to shrink bus, removing it completely\n");
Olivier Deprez0e641232021-09-23 10:07:05 +02004104 for (j = 0; j < bus->dev_count; j++) {
4105 if (j == i)
4106 continue;
4107 kvm_iodevice_destructor(bus->range[j].dev);
4108 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004109 }
4110
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004111 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4112 synchronize_srcu_expedited(&kvm->srcu);
4113 kfree(bus);
Olivier Deprez0e641232021-09-23 10:07:05 +02004114 return new_bus ? 0 : -ENOMEM;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004115}
4116
4117struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4118 gpa_t addr)
4119{
4120 struct kvm_io_bus *bus;
4121 int dev_idx, srcu_idx;
4122 struct kvm_io_device *iodev = NULL;
4123
4124 srcu_idx = srcu_read_lock(&kvm->srcu);
4125
4126 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
4127 if (!bus)
4128 goto out_unlock;
4129
4130 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
4131 if (dev_idx < 0)
4132 goto out_unlock;
4133
4134 iodev = bus->range[dev_idx].dev;
4135
4136out_unlock:
4137 srcu_read_unlock(&kvm->srcu, srcu_idx);
4138
4139 return iodev;
4140}
4141EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4142
4143static int kvm_debugfs_open(struct inode *inode, struct file *file,
4144 int (*get)(void *, u64 *), int (*set)(void *, u64),
4145 const char *fmt)
4146{
4147 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4148 inode->i_private;
4149
4150 /* The debugfs files are a reference to the kvm struct which
4151 * is still valid when kvm_destroy_vm is called.
4152 * To avoid the race between open and the removal of the debugfs
4153 * directory we test against the users count.
4154 */
4155 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
4156 return -ENOENT;
4157
David Brazdil0f672f62019-12-10 10:32:29 +00004158 if (simple_attr_open(inode, file, get,
4159 stat_data->mode & S_IWUGO ? set : NULL,
4160 fmt)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004161 kvm_put_kvm(stat_data->kvm);
4162 return -ENOMEM;
4163 }
4164
4165 return 0;
4166}
4167
4168static int kvm_debugfs_release(struct inode *inode, struct file *file)
4169{
4170 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4171 inode->i_private;
4172
4173 simple_attr_release(inode, file);
4174 kvm_put_kvm(stat_data->kvm);
4175
4176 return 0;
4177}
4178
4179static int vm_stat_get_per_vm(void *data, u64 *val)
4180{
4181 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4182
4183 *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
4184
4185 return 0;
4186}
4187
4188static int vm_stat_clear_per_vm(void *data, u64 val)
4189{
4190 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4191
4192 if (val)
4193 return -EINVAL;
4194
4195 *(ulong *)((void *)stat_data->kvm + stat_data->offset) = 0;
4196
4197 return 0;
4198}
4199
4200static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
4201{
4202 __simple_attr_check_format("%llu\n", 0ull);
4203 return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
4204 vm_stat_clear_per_vm, "%llu\n");
4205}
4206
4207static const struct file_operations vm_stat_get_per_vm_fops = {
4208 .owner = THIS_MODULE,
4209 .open = vm_stat_get_per_vm_open,
4210 .release = kvm_debugfs_release,
4211 .read = simple_attr_read,
4212 .write = simple_attr_write,
4213 .llseek = no_llseek,
4214};
4215
4216static int vcpu_stat_get_per_vm(void *data, u64 *val)
4217{
4218 int i;
4219 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4220 struct kvm_vcpu *vcpu;
4221
4222 *val = 0;
4223
4224 kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
4225 *val += *(u64 *)((void *)vcpu + stat_data->offset);
4226
4227 return 0;
4228}
4229
4230static int vcpu_stat_clear_per_vm(void *data, u64 val)
4231{
4232 int i;
4233 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4234 struct kvm_vcpu *vcpu;
4235
4236 if (val)
4237 return -EINVAL;
4238
4239 kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
4240 *(u64 *)((void *)vcpu + stat_data->offset) = 0;
4241
4242 return 0;
4243}
4244
4245static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
4246{
4247 __simple_attr_check_format("%llu\n", 0ull);
4248 return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
4249 vcpu_stat_clear_per_vm, "%llu\n");
4250}
4251
4252static const struct file_operations vcpu_stat_get_per_vm_fops = {
4253 .owner = THIS_MODULE,
4254 .open = vcpu_stat_get_per_vm_open,
4255 .release = kvm_debugfs_release,
4256 .read = simple_attr_read,
4257 .write = simple_attr_write,
4258 .llseek = no_llseek,
4259};
4260
4261static const struct file_operations *stat_fops_per_vm[] = {
4262 [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
4263 [KVM_STAT_VM] = &vm_stat_get_per_vm_fops,
4264};
4265
4266static int vm_stat_get(void *_offset, u64 *val)
4267{
4268 unsigned offset = (long)_offset;
4269 struct kvm *kvm;
4270 struct kvm_stat_data stat_tmp = {.offset = offset};
4271 u64 tmp_val;
4272
4273 *val = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00004274 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004275 list_for_each_entry(kvm, &vm_list, vm_list) {
4276 stat_tmp.kvm = kvm;
4277 vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
4278 *val += tmp_val;
4279 }
David Brazdil0f672f62019-12-10 10:32:29 +00004280 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004281 return 0;
4282}
4283
4284static int vm_stat_clear(void *_offset, u64 val)
4285{
4286 unsigned offset = (long)_offset;
4287 struct kvm *kvm;
4288 struct kvm_stat_data stat_tmp = {.offset = offset};
4289
4290 if (val)
4291 return -EINVAL;
4292
David Brazdil0f672f62019-12-10 10:32:29 +00004293 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004294 list_for_each_entry(kvm, &vm_list, vm_list) {
4295 stat_tmp.kvm = kvm;
4296 vm_stat_clear_per_vm((void *)&stat_tmp, 0);
4297 }
David Brazdil0f672f62019-12-10 10:32:29 +00004298 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004299
4300 return 0;
4301}
4302
4303DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
4304
4305static int vcpu_stat_get(void *_offset, u64 *val)
4306{
4307 unsigned offset = (long)_offset;
4308 struct kvm *kvm;
4309 struct kvm_stat_data stat_tmp = {.offset = offset};
4310 u64 tmp_val;
4311
4312 *val = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00004313 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004314 list_for_each_entry(kvm, &vm_list, vm_list) {
4315 stat_tmp.kvm = kvm;
4316 vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
4317 *val += tmp_val;
4318 }
David Brazdil0f672f62019-12-10 10:32:29 +00004319 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004320 return 0;
4321}
4322
4323static int vcpu_stat_clear(void *_offset, u64 val)
4324{
4325 unsigned offset = (long)_offset;
4326 struct kvm *kvm;
4327 struct kvm_stat_data stat_tmp = {.offset = offset};
4328
4329 if (val)
4330 return -EINVAL;
4331
David Brazdil0f672f62019-12-10 10:32:29 +00004332 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004333 list_for_each_entry(kvm, &vm_list, vm_list) {
4334 stat_tmp.kvm = kvm;
4335 vcpu_stat_clear_per_vm((void *)&stat_tmp, 0);
4336 }
David Brazdil0f672f62019-12-10 10:32:29 +00004337 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004338
4339 return 0;
4340}
4341
4342DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4343 "%llu\n");
4344
4345static const struct file_operations *stat_fops[] = {
4346 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4347 [KVM_STAT_VM] = &vm_stat_fops,
4348};
4349
4350static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4351{
4352 struct kobj_uevent_env *env;
4353 unsigned long long created, active;
4354
4355 if (!kvm_dev.this_device || !kvm)
4356 return;
4357
David Brazdil0f672f62019-12-10 10:32:29 +00004358 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004359 if (type == KVM_EVENT_CREATE_VM) {
4360 kvm_createvm_count++;
4361 kvm_active_vms++;
4362 } else if (type == KVM_EVENT_DESTROY_VM) {
4363 kvm_active_vms--;
4364 }
4365 created = kvm_createvm_count;
4366 active = kvm_active_vms;
David Brazdil0f672f62019-12-10 10:32:29 +00004367 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004368
David Brazdil0f672f62019-12-10 10:32:29 +00004369 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004370 if (!env)
4371 return;
4372
4373 add_uevent_var(env, "CREATED=%llu", created);
4374 add_uevent_var(env, "COUNT=%llu", active);
4375
4376 if (type == KVM_EVENT_CREATE_VM) {
4377 add_uevent_var(env, "EVENT=create");
4378 kvm->userspace_pid = task_pid_nr(current);
4379 } else if (type == KVM_EVENT_DESTROY_VM) {
4380 add_uevent_var(env, "EVENT=destroy");
4381 }
4382 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
4383
Olivier Deprez0e641232021-09-23 10:07:05 +02004384 if (kvm->debugfs_dentry) {
David Brazdil0f672f62019-12-10 10:32:29 +00004385 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004386
4387 if (p) {
4388 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4389 if (!IS_ERR(tmp))
4390 add_uevent_var(env, "STATS_PATH=%s", tmp);
4391 kfree(p);
4392 }
4393 }
4394 /* no need for checks, since we are adding at most only 5 keys */
4395 env->envp[env->envp_idx++] = NULL;
4396 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4397 kfree(env);
4398}
4399
4400static void kvm_init_debug(void)
4401{
4402 struct kvm_stats_debugfs_item *p;
4403
4404 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4405
4406 kvm_debugfs_num_entries = 0;
4407 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
David Brazdil0f672f62019-12-10 10:32:29 +00004408 int mode = p->mode ? p->mode : 0644;
4409 debugfs_create_file(p->name, mode, kvm_debugfs_dir,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004410 (void *)(long)p->offset,
4411 stat_fops[p->kind]);
4412 }
4413}
4414
4415static int kvm_suspend(void)
4416{
4417 if (kvm_usage_count)
4418 hardware_disable_nolock(NULL);
4419 return 0;
4420}
4421
4422static void kvm_resume(void)
4423{
4424 if (kvm_usage_count) {
David Brazdil0f672f62019-12-10 10:32:29 +00004425#ifdef CONFIG_LOCKDEP
4426 WARN_ON(lockdep_is_held(&kvm_count_lock));
4427#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004428 hardware_enable_nolock(NULL);
4429 }
4430}
4431
4432static struct syscore_ops kvm_syscore_ops = {
4433 .suspend = kvm_suspend,
4434 .resume = kvm_resume,
4435};
4436
4437static inline
4438struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4439{
4440 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4441}
4442
4443static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4444{
4445 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4446
David Brazdil0f672f62019-12-10 10:32:29 +00004447 WRITE_ONCE(vcpu->preempted, false);
4448 WRITE_ONCE(vcpu->ready, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004449
4450 kvm_arch_sched_in(vcpu, cpu);
4451
4452 kvm_arch_vcpu_load(vcpu, cpu);
4453}
4454
4455static void kvm_sched_out(struct preempt_notifier *pn,
4456 struct task_struct *next)
4457{
4458 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4459
David Brazdil0f672f62019-12-10 10:32:29 +00004460 if (current->state == TASK_RUNNING) {
4461 WRITE_ONCE(vcpu->preempted, true);
4462 WRITE_ONCE(vcpu->ready, true);
4463 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004464 kvm_arch_vcpu_put(vcpu);
4465}
4466
David Brazdil0f672f62019-12-10 10:32:29 +00004467static void check_processor_compat(void *rtn)
4468{
4469 *(int *)rtn = kvm_arch_check_processor_compat();
4470}
4471
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004472int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
4473 struct module *module)
4474{
4475 int r;
4476 int cpu;
4477
4478 r = kvm_arch_init(opaque);
4479 if (r)
4480 goto out_fail;
4481
4482 /*
4483 * kvm_arch_init makes sure there's at most one caller
4484 * for architectures that support multiple implementations,
4485 * like intel and amd on x86.
4486 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4487 * conflicts in case kvm is already setup for another implementation.
4488 */
4489 r = kvm_irqfd_init();
4490 if (r)
4491 goto out_irqfd;
4492
4493 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
4494 r = -ENOMEM;
4495 goto out_free_0;
4496 }
4497
4498 r = kvm_arch_hardware_setup();
4499 if (r < 0)
4500 goto out_free_0a;
4501
4502 for_each_online_cpu(cpu) {
David Brazdil0f672f62019-12-10 10:32:29 +00004503 smp_call_function_single(cpu, check_processor_compat, &r, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004504 if (r < 0)
4505 goto out_free_1;
4506 }
4507
4508 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
4509 kvm_starting_cpu, kvm_dying_cpu);
4510 if (r)
4511 goto out_free_2;
4512 register_reboot_notifier(&kvm_reboot_notifier);
4513
4514 /* A kmem cache lets us meet the alignment requirements of fx_save. */
4515 if (!vcpu_align)
4516 vcpu_align = __alignof__(struct kvm_vcpu);
4517 kvm_vcpu_cache =
4518 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4519 SLAB_ACCOUNT,
4520 offsetof(struct kvm_vcpu, arch),
4521 sizeof_field(struct kvm_vcpu, arch),
4522 NULL);
4523 if (!kvm_vcpu_cache) {
4524 r = -ENOMEM;
4525 goto out_free_3;
4526 }
4527
4528 r = kvm_async_pf_init();
4529 if (r)
4530 goto out_free;
4531
4532 kvm_chardev_ops.owner = module;
4533 kvm_vm_fops.owner = module;
4534 kvm_vcpu_fops.owner = module;
4535
4536 r = misc_register(&kvm_dev);
4537 if (r) {
4538 pr_err("kvm: misc device register failed\n");
4539 goto out_unreg;
4540 }
4541
4542 register_syscore_ops(&kvm_syscore_ops);
4543
4544 kvm_preempt_ops.sched_in = kvm_sched_in;
4545 kvm_preempt_ops.sched_out = kvm_sched_out;
4546
4547 kvm_init_debug();
4548
4549 r = kvm_vfio_ops_init();
4550 WARN_ON(r);
4551
4552 return 0;
4553
4554out_unreg:
4555 kvm_async_pf_deinit();
4556out_free:
4557 kmem_cache_destroy(kvm_vcpu_cache);
4558out_free_3:
4559 unregister_reboot_notifier(&kvm_reboot_notifier);
4560 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4561out_free_2:
4562out_free_1:
4563 kvm_arch_hardware_unsetup();
4564out_free_0a:
4565 free_cpumask_var(cpus_hardware_enabled);
4566out_free_0:
4567 kvm_irqfd_exit();
4568out_irqfd:
4569 kvm_arch_exit();
4570out_fail:
4571 return r;
4572}
4573EXPORT_SYMBOL_GPL(kvm_init);
4574
4575void kvm_exit(void)
4576{
4577 debugfs_remove_recursive(kvm_debugfs_dir);
4578 misc_deregister(&kvm_dev);
4579 kmem_cache_destroy(kvm_vcpu_cache);
4580 kvm_async_pf_deinit();
4581 unregister_syscore_ops(&kvm_syscore_ops);
4582 unregister_reboot_notifier(&kvm_reboot_notifier);
4583 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4584 on_each_cpu(hardware_disable_nolock, NULL, 1);
4585 kvm_arch_hardware_unsetup();
4586 kvm_arch_exit();
4587 kvm_irqfd_exit();
4588 free_cpumask_var(cpus_hardware_enabled);
4589 kvm_vfio_ops_exit();
4590}
4591EXPORT_SYMBOL_GPL(kvm_exit);
David Brazdil0f672f62019-12-10 10:32:29 +00004592
4593struct kvm_vm_worker_thread_context {
4594 struct kvm *kvm;
4595 struct task_struct *parent;
4596 struct completion init_done;
4597 kvm_vm_thread_fn_t thread_fn;
4598 uintptr_t data;
4599 int err;
4600};
4601
4602static int kvm_vm_worker_thread(void *context)
4603{
4604 /*
4605 * The init_context is allocated on the stack of the parent thread, so
4606 * we have to locally copy anything that is needed beyond initialization
4607 */
4608 struct kvm_vm_worker_thread_context *init_context = context;
4609 struct kvm *kvm = init_context->kvm;
4610 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4611 uintptr_t data = init_context->data;
4612 int err;
4613
4614 err = kthread_park(current);
4615 /* kthread_park(current) is never supposed to return an error */
4616 WARN_ON(err != 0);
4617 if (err)
4618 goto init_complete;
4619
4620 err = cgroup_attach_task_all(init_context->parent, current);
4621 if (err) {
4622 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4623 __func__, err);
4624 goto init_complete;
4625 }
4626
4627 set_user_nice(current, task_nice(init_context->parent));
4628
4629init_complete:
4630 init_context->err = err;
4631 complete(&init_context->init_done);
4632 init_context = NULL;
4633
4634 if (err)
4635 return err;
4636
4637 /* Wait to be woken up by the spawner before proceeding. */
4638 kthread_parkme();
4639
4640 if (!kthread_should_stop())
4641 err = thread_fn(kvm, data);
4642
4643 return err;
4644}
4645
4646int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4647 uintptr_t data, const char *name,
4648 struct task_struct **thread_ptr)
4649{
4650 struct kvm_vm_worker_thread_context init_context = {};
4651 struct task_struct *thread;
4652
4653 *thread_ptr = NULL;
4654 init_context.kvm = kvm;
4655 init_context.parent = current;
4656 init_context.thread_fn = thread_fn;
4657 init_context.data = data;
4658 init_completion(&init_context.init_done);
4659
4660 thread = kthread_run(kvm_vm_worker_thread, &init_context,
4661 "%s-%d", name, task_pid_nr(current));
4662 if (IS_ERR(thread))
4663 return PTR_ERR(thread);
4664
4665 /* kthread_run is never supposed to return NULL */
4666 WARN_ON(thread == NULL);
4667
4668 wait_for_completion(&init_context.init_done);
4669
4670 if (!init_context.err)
4671 *thread_ptr = thread;
4672
4673 return init_context.err;
4674}