]> git.ipfire.org Git - thirdparty/kernel/stable.git/blame - virt/kvm/kvm_main.c
KVM: nVMX: clean up posted interrupt descriptor try_cmpxchg
[thirdparty/kernel/stable.git] / virt / kvm / kvm_main.c
CommitLineData
20c8ccb1 1// SPDX-License-Identifier: GPL-2.0-only
6aa8b732
AK
2/*
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.
9611c187 9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
6aa8b732
AK
10 *
11 * Authors:
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
6aa8b732
AK
14 */
15
af669ac6 16#include <kvm/iodev.h>
6aa8b732 17
edf88417 18#include <linux/kvm_host.h>
6aa8b732
AK
19#include <linux/kvm.h>
20#include <linux/module.h>
21#include <linux/errno.h>
6aa8b732 22#include <linux/percpu.h>
6aa8b732
AK
23#include <linux/mm.h>
24#include <linux/miscdevice.h>
25#include <linux/vmalloc.h>
6aa8b732 26#include <linux/reboot.h>
6aa8b732
AK
27#include <linux/debugfs.h>
28#include <linux/highmem.h>
29#include <linux/file.h>
fb3600cc 30#include <linux/syscore_ops.h>
774c47f1 31#include <linux/cpu.h>
174cd4b1 32#include <linux/sched/signal.h>
6e84f315 33#include <linux/sched/mm.h>
03441a34 34#include <linux/sched/stat.h>
d9e368d6
AK
35#include <linux/cpumask.h>
36#include <linux/smp.h>
d6d28168 37#include <linux/anon_inodes.h>
04d2cc77 38#include <linux/profile.h>
7aa81cc0 39#include <linux/kvm_para.h>
6fc138d2 40#include <linux/pagemap.h>
8d4e1288 41#include <linux/mman.h>
35149e21 42#include <linux/swap.h>
e56d532f 43#include <linux/bitops.h>
547de29e 44#include <linux/spinlock.h>
6ff5894c 45#include <linux/compat.h>
bc6678a3 46#include <linux/srcu.h>
8f0b1ab6 47#include <linux/hugetlb.h>
5a0e3ad6 48#include <linux/slab.h>
743eeb0b
SL
49#include <linux/sort.h>
50#include <linux/bsearch.h>
c011d23b 51#include <linux/io.h>
2eb06c30 52#include <linux/lockdep.h>
c57c8046 53#include <linux/kthread.h>
2fdef3a2 54#include <linux/suspend.h>
6aa8b732 55
e495606d 56#include <asm/processor.h>
2ea75be3 57#include <asm/ioctl.h>
7c0f6ba6 58#include <linux/uaccess.h>
6aa8b732 59
5f94c174 60#include "coalesced_mmio.h"
af585b92 61#include "async_pf.h"
982ed0de 62#include "kvm_mm.h"
3c3c29fd 63#include "vfio.h"
5f94c174 64
229456fc
MT
65#define CREATE_TRACE_POINTS
66#include <trace/events/kvm.h>
67
fb04a1ed
PX
68#include <linux/kvm_dirty_ring.h>
69
536a6f88
JF
70/* Worst case buffer size needed for holding an integer. */
71#define ITOA_MAX_LEN 12
72
6aa8b732
AK
73MODULE_AUTHOR("Qumranet");
74MODULE_LICENSE("GPL");
75
920552b2 76/* Architectures should define their poll value according to the halt latency */
ec76d819 77unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
039c5d1b 78module_param(halt_poll_ns, uint, 0644);
ec76d819 79EXPORT_SYMBOL_GPL(halt_poll_ns);
f7819512 80
aca6ff29 81/* Default doubles per-vcpu halt_poll_ns. */
ec76d819 82unsigned int halt_poll_ns_grow = 2;
039c5d1b 83module_param(halt_poll_ns_grow, uint, 0644);
ec76d819 84EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
aca6ff29 85
49113d36
NW
86/* The start value to grow halt_poll_ns from */
87unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
88module_param(halt_poll_ns_grow_start, uint, 0644);
89EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
90
aca6ff29 91/* Default resets per-vcpu halt_poll_ns . */
ec76d819 92unsigned int halt_poll_ns_shrink;
039c5d1b 93module_param(halt_poll_ns_shrink, uint, 0644);
ec76d819 94EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
aca6ff29 95
fa40a821
MT
96/*
97 * Ordering of locks:
98 *
b7d409de 99 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
fa40a821
MT
100 */
101
0d9ce162 102DEFINE_MUTEX(kvm_lock);
4a937f96 103static DEFINE_RAW_SPINLOCK(kvm_count_lock);
e9b11c17 104LIST_HEAD(vm_list);
133de902 105
7f59f492 106static cpumask_var_t cpus_hardware_enabled;
f4fee932 107static int kvm_usage_count;
10474ae8 108static atomic_t hardware_enable_failed;
1b6c0168 109
aaba298c 110static struct kmem_cache *kvm_vcpu_cache;
1165f5fe 111
15ad7146 112static __read_mostly struct preempt_ops kvm_preempt_ops;
7495e22b 113static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
15ad7146 114
76f7c879 115struct dentry *kvm_debugfs_dir;
e23a808b 116EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
6aa8b732 117
09cbcef6 118static const struct file_operations stat_fops_per_vm;
536a6f88 119
5f6de5cb
DM
120static struct file_operations kvm_chardev_ops;
121
bccf2150
AK
122static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
123 unsigned long arg);
de8e5d74 124#ifdef CONFIG_KVM_COMPAT
1dda606c
AG
125static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
126 unsigned long arg);
7ddfd3e0
MZ
127#define KVM_COMPAT(c) .compat_ioctl = (c)
128#else
9cb09e7c
MZ
129/*
130 * For architectures that don't implement a compat infrastructure,
131 * adopt a double line of defense:
132 * - Prevent a compat task from opening /dev/kvm
133 * - If the open has been done by a 64bit task, and the KVM fd
134 * passed to a compat task, let the ioctls fail.
135 */
7ddfd3e0
MZ
136static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
137 unsigned long arg) { return -EINVAL; }
b9876e6d
MZ
138
139static int kvm_no_compat_open(struct inode *inode, struct file *file)
140{
141 return is_compat_task() ? -ENODEV : 0;
142}
143#define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
144 .open = kvm_no_compat_open
1dda606c 145#endif
10474ae8
AG
146static int hardware_enable_all(void);
147static void hardware_disable_all(void);
bccf2150 148
e93f8a0f 149static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
7940876e 150
52480137 151__visible bool kvm_rebooting;
b7c4145b 152EXPORT_SYMBOL_GPL(kvm_rebooting);
4ecac3fd 153
286de8f6
CI
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
baff59cc
VK
160static DEFINE_PER_CPU(cpumask_var_t, cpu_kick_mask);
161
e649b3f0
ET
162__weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
163 unsigned long start, unsigned long end)
b1394e74
RK
164{
165}
166
683412cc
MZ
167__weak void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
168{
169}
170
284dc493 171bool kvm_is_zone_device_page(struct page *page)
a78986aa
SC
172{
173 /*
174 * The metadata used by is_zone_device_page() to determine whether or
175 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
176 * the device has been pinned, e.g. by get_user_pages(). WARN if the
177 * page_count() is zero to help detect bad usage of this helper.
178 */
284dc493 179 if (WARN_ON_ONCE(!page_count(page)))
a78986aa
SC
180 return false;
181
284dc493 182 return is_zone_device_page(page);
a78986aa
SC
183}
184
b14b2690
SC
185/*
186 * Returns a 'struct page' if the pfn is "valid" and backed by a refcounted
187 * page, NULL otherwise. Note, the list of refcounted PG_reserved page types
188 * is likely incomplete, it has been compiled purely through people wanting to
189 * back guest with a certain type of memory and encountering issues.
190 */
191struct page *kvm_pfn_to_refcounted_page(kvm_pfn_t pfn)
cbff90a7 192{
b14b2690
SC
193 struct page *page;
194
195 if (!pfn_valid(pfn))
196 return NULL;
197
198 page = pfn_to_page(pfn);
199 if (!PageReserved(page))
200 return page;
201
202 /* The ZERO_PAGE(s) is marked PG_reserved, but is refcounted. */
203 if (is_zero_pfn(pfn))
204 return page;
205
a78986aa
SC
206 /*
207 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
208 * perspective they are "normal" pages, albeit with slightly different
209 * usage rules.
210 */
b14b2690
SC
211 if (kvm_is_zone_device_page(page))
212 return page;
cbff90a7 213
b14b2690 214 return NULL;
cbff90a7
BAY
215}
216
bccf2150
AK
217/*
218 * Switches to specified vcpu, until a matching vcpu_put()
219 */
ec7660cc 220void vcpu_load(struct kvm_vcpu *vcpu)
6aa8b732 221{
ec7660cc 222 int cpu = get_cpu();
7495e22b
PB
223
224 __this_cpu_write(kvm_running_vcpu, vcpu);
15ad7146 225 preempt_notifier_register(&vcpu->preempt_notifier);
313a3dc7 226 kvm_arch_vcpu_load(vcpu, cpu);
15ad7146 227 put_cpu();
6aa8b732 228}
2f1fe811 229EXPORT_SYMBOL_GPL(vcpu_load);
6aa8b732 230
313a3dc7 231void vcpu_put(struct kvm_vcpu *vcpu)
6aa8b732 232{
15ad7146 233 preempt_disable();
313a3dc7 234 kvm_arch_vcpu_put(vcpu);
15ad7146 235 preempt_notifier_unregister(&vcpu->preempt_notifier);
7495e22b 236 __this_cpu_write(kvm_running_vcpu, NULL);
15ad7146 237 preempt_enable();
6aa8b732 238}
2f1fe811 239EXPORT_SYMBOL_GPL(vcpu_put);
6aa8b732 240
7a97cec2
PB
241/* TODO: merge with kvm_arch_vcpu_should_kick */
242static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
243{
244 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
245
246 /*
247 * We need to wait for the VCPU to reenable interrupts and get out of
248 * READING_SHADOW_PAGE_TABLES mode.
249 */
250 if (req & KVM_REQUEST_WAIT)
251 return mode != OUTSIDE_GUEST_MODE;
252
253 /*
254 * Need to kick a running VCPU, but otherwise there is nothing to do.
255 */
256 return mode == IN_GUEST_MODE;
257}
258
f24b44e4 259static void ack_kick(void *_completed)
d9e368d6 260{
d9e368d6
AK
261}
262
620b2438 263static inline bool kvm_kick_many_cpus(struct cpumask *cpus, bool wait)
b49defe8 264{
b49defe8
PB
265 if (cpumask_empty(cpus))
266 return false;
267
f24b44e4 268 smp_call_function_many(cpus, ack_kick, NULL, wait);
b49defe8
PB
269 return true;
270}
271
b56bd8e0
JL
272static void kvm_make_vcpu_request(struct kvm_vcpu *vcpu, unsigned int req,
273 struct cpumask *tmp, int current_cpu)
ae0946cd
VK
274{
275 int cpu;
276
df06dae3
SC
277 if (likely(!(req & KVM_REQUEST_NO_ACTION)))
278 __kvm_make_request(req, vcpu);
ae0946cd
VK
279
280 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
281 return;
282
ae0946cd
VK
283 /*
284 * Note, the vCPU could get migrated to a different pCPU at any point
285 * after kvm_request_needs_ipi(), which could result in sending an IPI
286 * to the previous pCPU. But, that's OK because the purpose of the IPI
287 * is to ensure the vCPU returns to OUTSIDE_GUEST_MODE, which is
288 * satisfied if the vCPU migrates. Entering READING_SHADOW_PAGE_TABLES
289 * after this point is also OK, as the requirement is only that KVM wait
290 * for vCPUs that were reading SPTEs _before_ any changes were
291 * finalized. See kvm_vcpu_kick() for more details on handling requests.
292 */
293 if (kvm_request_needs_ipi(vcpu, req)) {
294 cpu = READ_ONCE(vcpu->cpu);
295 if (cpu != -1 && cpu != current_cpu)
296 __cpumask_set_cpu(cpu, tmp);
297 }
298}
299
7053df4e 300bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
620b2438 301 unsigned long *vcpu_bitmap)
d9e368d6 302{
d9e368d6 303 struct kvm_vcpu *vcpu;
620b2438 304 struct cpumask *cpus;
ae0946cd 305 int i, me;
7053df4e 306 bool called;
6ef7a1bc 307
3cba4130 308 me = get_cpu();
7053df4e 309
620b2438
VK
310 cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
311 cpumask_clear(cpus);
312
ae0946cd
VK
313 for_each_set_bit(i, vcpu_bitmap, KVM_MAX_VCPUS) {
314 vcpu = kvm_get_vcpu(kvm, i);
381cecc5 315 if (!vcpu)
7053df4e 316 continue;
b56bd8e0 317 kvm_make_vcpu_request(vcpu, req, cpus, me);
49846896 318 }
7053df4e 319
620b2438 320 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
3cba4130 321 put_cpu();
7053df4e
VK
322
323 return called;
324}
325
54163a34
SS
326bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
327 struct kvm_vcpu *except)
7053df4e 328{
ae0946cd 329 struct kvm_vcpu *vcpu;
baff59cc 330 struct cpumask *cpus;
46808a4c 331 unsigned long i;
7053df4e 332 bool called;
46808a4c 333 int me;
7053df4e 334
ae0946cd
VK
335 me = get_cpu();
336
baff59cc
VK
337 cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
338 cpumask_clear(cpus);
339
ae0946cd
VK
340 kvm_for_each_vcpu(i, vcpu, kvm) {
341 if (vcpu == except)
342 continue;
b56bd8e0 343 kvm_make_vcpu_request(vcpu, req, cpus, me);
ae0946cd
VK
344 }
345
346 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
347 put_cpu();
7053df4e 348
49846896 349 return called;
d9e368d6
AK
350}
351
54163a34
SS
352bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
353{
354 return kvm_make_all_cpus_request_except(kvm, req, NULL);
355}
a2486020 356EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
54163a34 357
a6d51016 358#ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
49846896 359void kvm_flush_remote_tlbs(struct kvm *kvm)
2e53d63a 360{
3cc4e148 361 ++kvm->stat.generic.remote_tlb_flush_requests;
6bc6db00 362
4ae3cb3a
LT
363 /*
364 * We want to publish modifications to the page tables before reading
365 * mode. Pairs with a memory barrier in arch-specific code.
366 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
367 * and smp_mb in walk_shadow_page_lockless_begin/end.
368 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
369 *
370 * There is already an smp_mb__after_atomic() before
371 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
372 * barrier here.
373 */
b08660e5
TL
374 if (!kvm_arch_flush_remote_tlb(kvm)
375 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
0193cc90 376 ++kvm->stat.generic.remote_tlb_flush;
2e53d63a 377}
2ba9f0d8 378EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
a6d51016 379#endif
2e53d63a 380
683412cc
MZ
381static void kvm_flush_shadow_all(struct kvm *kvm)
382{
383 kvm_arch_flush_shadow_all(kvm);
384 kvm_arch_guest_memory_reclaimed(kvm);
385}
386
6926f95a
SC
387#ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
388static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
389 gfp_t gfp_flags)
390{
391 gfp_flags |= mc->gfp_zero;
392
393 if (mc->kmem_cache)
394 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
395 else
396 return (void *)__get_free_page(gfp_flags);
397}
398
837f66c7 399int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min)
6926f95a 400{
837f66c7 401 gfp_t gfp = GFP_KERNEL_ACCOUNT;
6926f95a
SC
402 void *obj;
403
404 if (mc->nobjs >= min)
405 return 0;
837f66c7
DM
406
407 if (unlikely(!mc->objects)) {
408 if (WARN_ON_ONCE(!capacity))
409 return -EIO;
410
411 mc->objects = kvmalloc_array(sizeof(void *), capacity, gfp);
412 if (!mc->objects)
413 return -ENOMEM;
414
415 mc->capacity = capacity;
416 }
417
418 /* It is illegal to request a different capacity across topups. */
419 if (WARN_ON_ONCE(mc->capacity != capacity))
420 return -EIO;
421
422 while (mc->nobjs < mc->capacity) {
423 obj = mmu_memory_cache_alloc_obj(mc, gfp);
6926f95a
SC
424 if (!obj)
425 return mc->nobjs >= min ? 0 : -ENOMEM;
426 mc->objects[mc->nobjs++] = obj;
427 }
428 return 0;
429}
430
837f66c7
DM
431int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
432{
433 return __kvm_mmu_topup_memory_cache(mc, KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE, min);
434}
435
6926f95a
SC
436int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
437{
438 return mc->nobjs;
439}
440
441void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
442{
443 while (mc->nobjs) {
444 if (mc->kmem_cache)
445 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
446 else
447 free_page((unsigned long)mc->objects[--mc->nobjs]);
448 }
837f66c7
DM
449
450 kvfree(mc->objects);
451
452 mc->objects = NULL;
453 mc->capacity = 0;
6926f95a
SC
454}
455
456void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
457{
458 void *p;
459
460 if (WARN_ON(!mc->nobjs))
461 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
462 else
463 p = mc->objects[--mc->nobjs];
464 BUG_ON(!p);
465 return p;
466}
467#endif
468
8bd826d6 469static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
fb3f0f51 470{
fb3f0f51
RR
471 mutex_init(&vcpu->mutex);
472 vcpu->cpu = -1;
fb3f0f51
RR
473 vcpu->kvm = kvm;
474 vcpu->vcpu_id = id;
34bb10b7 475 vcpu->pid = NULL;
510958e9 476#ifndef __KVM_HAVE_ARCH_WQP
da4ad88c 477 rcuwait_init(&vcpu->wait);
510958e9 478#endif
af585b92 479 kvm_async_pf_vcpu_init(vcpu);
fb3f0f51 480
4c088493
R
481 kvm_vcpu_set_in_spin_loop(vcpu, false);
482 kvm_vcpu_set_dy_eligible(vcpu, false);
3a08a8f9 483 vcpu->preempted = false;
d73eb57b 484 vcpu->ready = false;
d5c48deb 485 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
a54d8066 486 vcpu->last_used_slot = NULL;
fb3f0f51 487}
fb3f0f51 488
27592ae8 489static void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
4543bdc0
SC
490{
491 kvm_arch_vcpu_destroy(vcpu);
5593473a 492 kvm_dirty_ring_free(&vcpu->dirty_ring);
e529ef66 493
9941d224
SC
494 /*
495 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
496 * the vcpu->pid pointer, and at destruction time all file descriptors
497 * are already gone.
498 */
499 put_pid(rcu_dereference_protected(vcpu->pid, 1));
500
8bd826d6 501 free_page((unsigned long)vcpu->run);
e529ef66 502 kmem_cache_free(kvm_vcpu_cache, vcpu);
4543bdc0 503}
27592ae8
MZ
504
505void kvm_destroy_vcpus(struct kvm *kvm)
506{
46808a4c 507 unsigned long i;
27592ae8
MZ
508 struct kvm_vcpu *vcpu;
509
510 kvm_for_each_vcpu(i, vcpu, kvm) {
511 kvm_vcpu_destroy(vcpu);
c5b07754 512 xa_erase(&kvm->vcpu_array, i);
27592ae8
MZ
513 }
514
515 atomic_set(&kvm->online_vcpus, 0);
516}
517EXPORT_SYMBOL_GPL(kvm_destroy_vcpus);
4543bdc0 518
e930bffe
AA
519#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
520static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
521{
522 return container_of(mn, struct kvm, mmu_notifier);
523}
524
e649b3f0
ET
525static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
526 struct mm_struct *mm,
527 unsigned long start, unsigned long end)
528{
529 struct kvm *kvm = mmu_notifier_to_kvm(mn);
530 int idx;
531
532 idx = srcu_read_lock(&kvm->srcu);
533 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
534 srcu_read_unlock(&kvm->srcu, idx);
535}
536
3039bcc7
SC
537typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
538
f922bd9b
SC
539typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
540 unsigned long end);
541
683412cc
MZ
542typedef void (*on_unlock_fn_t)(struct kvm *kvm);
543
3039bcc7
SC
544struct kvm_hva_range {
545 unsigned long start;
546 unsigned long end;
547 pte_t pte;
548 hva_handler_t handler;
f922bd9b 549 on_lock_fn_t on_lock;
683412cc 550 on_unlock_fn_t on_unlock;
3039bcc7
SC
551 bool flush_on_ret;
552 bool may_block;
553};
554
f922bd9b
SC
555/*
556 * Use a dedicated stub instead of NULL to indicate that there is no callback
557 * function/handler. The compiler technically can't guarantee that a real
558 * function will have a non-zero address, and so it will generate code to
559 * check for !NULL, whereas comparing against a stub will be elided at compile
560 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
561 */
562static void kvm_null_fn(void)
563{
564
565}
566#define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
567
ed922739
MS
568/* Iterate over each memslot intersecting [start, last] (inclusive) range */
569#define kvm_for_each_memslot_in_hva_range(node, slots, start, last) \
570 for (node = interval_tree_iter_first(&slots->hva_tree, start, last); \
571 node; \
572 node = interval_tree_iter_next(node, start, last)) \
573
3039bcc7
SC
574static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
575 const struct kvm_hva_range *range)
576{
8931a454 577 bool ret = false, locked = false;
f922bd9b 578 struct kvm_gfn_range gfn_range;
3039bcc7
SC
579 struct kvm_memory_slot *slot;
580 struct kvm_memslots *slots;
3039bcc7
SC
581 int i, idx;
582
ed922739
MS
583 if (WARN_ON_ONCE(range->end <= range->start))
584 return 0;
585
f922bd9b
SC
586 /* A null handler is allowed if and only if on_lock() is provided. */
587 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
588 IS_KVM_NULL_FN(range->handler)))
589 return 0;
590
3039bcc7
SC
591 idx = srcu_read_lock(&kvm->srcu);
592
593 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
ed922739
MS
594 struct interval_tree_node *node;
595
3039bcc7 596 slots = __kvm_memslots(kvm, i);
ed922739
MS
597 kvm_for_each_memslot_in_hva_range(node, slots,
598 range->start, range->end - 1) {
3039bcc7
SC
599 unsigned long hva_start, hva_end;
600
a54d8066 601 slot = container_of(node, struct kvm_memory_slot, hva_node[slots->node_idx]);
3039bcc7
SC
602 hva_start = max(range->start, slot->userspace_addr);
603 hva_end = min(range->end, slot->userspace_addr +
604 (slot->npages << PAGE_SHIFT));
3039bcc7
SC
605
606 /*
607 * To optimize for the likely case where the address
608 * range is covered by zero or one memslots, don't
609 * bother making these conditional (to avoid writes on
610 * the second or later invocation of the handler).
611 */
612 gfn_range.pte = range->pte;
613 gfn_range.may_block = range->may_block;
614
615 /*
616 * {gfn(page) | page intersects with [hva_start, hva_end)} =
617 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
618 */
619 gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
620 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
621 gfn_range.slot = slot;
622
8931a454
SC
623 if (!locked) {
624 locked = true;
625 KVM_MMU_LOCK(kvm);
071064f1
PB
626 if (!IS_KVM_NULL_FN(range->on_lock))
627 range->on_lock(kvm, range->start, range->end);
628 if (IS_KVM_NULL_FN(range->handler))
629 break;
8931a454 630 }
3039bcc7
SC
631 ret |= range->handler(kvm, &gfn_range);
632 }
633 }
634
6bc6db00 635 if (range->flush_on_ret && ret)
3039bcc7
SC
636 kvm_flush_remote_tlbs(kvm);
637
683412cc 638 if (locked) {
8931a454 639 KVM_MMU_UNLOCK(kvm);
683412cc
MZ
640 if (!IS_KVM_NULL_FN(range->on_unlock))
641 range->on_unlock(kvm);
642 }
f922bd9b 643
3039bcc7
SC
644 srcu_read_unlock(&kvm->srcu, idx);
645
646 /* The notifiers are averse to booleans. :-( */
647 return (int)ret;
648}
649
650static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
651 unsigned long start,
652 unsigned long end,
653 pte_t pte,
654 hva_handler_t handler)
655{
656 struct kvm *kvm = mmu_notifier_to_kvm(mn);
657 const struct kvm_hva_range range = {
658 .start = start,
659 .end = end,
660 .pte = pte,
661 .handler = handler,
f922bd9b 662 .on_lock = (void *)kvm_null_fn,
683412cc 663 .on_unlock = (void *)kvm_null_fn,
3039bcc7
SC
664 .flush_on_ret = true,
665 .may_block = false,
666 };
3039bcc7 667
f922bd9b 668 return __kvm_handle_hva_range(kvm, &range);
3039bcc7
SC
669}
670
671static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
672 unsigned long start,
673 unsigned long end,
674 hva_handler_t handler)
675{
676 struct kvm *kvm = mmu_notifier_to_kvm(mn);
677 const struct kvm_hva_range range = {
678 .start = start,
679 .end = end,
680 .pte = __pte(0),
681 .handler = handler,
f922bd9b 682 .on_lock = (void *)kvm_null_fn,
683412cc 683 .on_unlock = (void *)kvm_null_fn,
3039bcc7
SC
684 .flush_on_ret = false,
685 .may_block = false,
686 };
3039bcc7 687
f922bd9b 688 return __kvm_handle_hva_range(kvm, &range);
3039bcc7 689}
3da0dd43
IE
690static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
691 struct mm_struct *mm,
692 unsigned long address,
693 pte_t pte)
694{
695 struct kvm *kvm = mmu_notifier_to_kvm(mn);
696
501b9185
SC
697 trace_kvm_set_spte_hva(address);
698
c13fda23 699 /*
52ac8b35 700 * .change_pte() must be surrounded by .invalidate_range_{start,end}().
071064f1
PB
701 * If mmu_notifier_count is zero, then no in-progress invalidations,
702 * including this one, found a relevant memslot at start(); rechecking
703 * memslots here is unnecessary. Note, a false positive (count elevated
704 * by a different invalidation) is sub-optimal but functionally ok.
c13fda23 705 */
52ac8b35 706 WARN_ON_ONCE(!READ_ONCE(kvm->mn_active_invalidate_count));
071064f1
PB
707 if (!READ_ONCE(kvm->mmu_notifier_count))
708 return;
c13fda23 709
3039bcc7 710 kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
3da0dd43
IE
711}
712
edb298c6 713void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
f922bd9b 714 unsigned long end)
e930bffe 715{
e930bffe
AA
716 /*
717 * The count increase must become visible at unlock time as no
718 * spte can be established without taking the mmu_lock and
719 * count is also read inside the mmu_lock critical section.
720 */
721 kvm->mmu_notifier_count++;
4a42d848 722 if (likely(kvm->mmu_notifier_count == 1)) {
f922bd9b
SC
723 kvm->mmu_notifier_range_start = start;
724 kvm->mmu_notifier_range_end = end;
4a42d848
DS
725 } else {
726 /*
a413a625 727 * Fully tracking multiple concurrent ranges has diminishing
4a42d848
DS
728 * returns. Keep things simple and just find the minimal range
729 * which includes the current and new ranges. As there won't be
730 * enough information to subtract a range after its invalidate
731 * completes, any ranges invalidated concurrently will
732 * accumulate and persist until all outstanding invalidates
733 * complete.
734 */
735 kvm->mmu_notifier_range_start =
f922bd9b 736 min(kvm->mmu_notifier_range_start, start);
4a42d848 737 kvm->mmu_notifier_range_end =
f922bd9b 738 max(kvm->mmu_notifier_range_end, end);
4a42d848 739 }
f922bd9b 740}
3039bcc7 741
f922bd9b
SC
742static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
743 const struct mmu_notifier_range *range)
744{
745 struct kvm *kvm = mmu_notifier_to_kvm(mn);
746 const struct kvm_hva_range hva_range = {
747 .start = range->start,
748 .end = range->end,
749 .pte = __pte(0),
750 .handler = kvm_unmap_gfn_range,
751 .on_lock = kvm_inc_notifier_count,
683412cc 752 .on_unlock = kvm_arch_guest_memory_reclaimed,
f922bd9b
SC
753 .flush_on_ret = true,
754 .may_block = mmu_notifier_range_blockable(range),
755 };
565f3be2 756
f922bd9b
SC
757 trace_kvm_unmap_hva_range(range->start, range->end);
758
52ac8b35
PB
759 /*
760 * Prevent memslot modification between range_start() and range_end()
761 * so that conditionally locking provides the same result in both
762 * functions. Without that guarantee, the mmu_notifier_count
763 * adjustments will be imbalanced.
764 *
765 * Pairs with the decrement in range_end().
766 */
767 spin_lock(&kvm->mn_invalidate_lock);
768 kvm->mn_active_invalidate_count++;
769 spin_unlock(&kvm->mn_invalidate_lock);
770
58cd407c
SC
771 /*
772 * Invalidate pfn caches _before_ invalidating the secondary MMUs, i.e.
773 * before acquiring mmu_lock, to avoid holding mmu_lock while acquiring
774 * each cache's lock. There are relatively few caches in existence at
775 * any given time, and the caches themselves can check for hva overlap,
776 * i.e. don't need to rely on memslot overlap checks for performance.
777 * Because this runs without holding mmu_lock, the pfn caches must use
778 * mn_active_invalidate_count (see above) instead of mmu_notifier_count.
779 */
982ed0de
DW
780 gfn_to_pfn_cache_invalidate_start(kvm, range->start, range->end,
781 hva_range.may_block);
782
f922bd9b 783 __kvm_handle_hva_range(kvm, &hva_range);
93065ac7 784
e649b3f0 785 return 0;
e930bffe
AA
786}
787
edb298c6 788void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
f922bd9b 789 unsigned long end)
e930bffe 790{
e930bffe
AA
791 /*
792 * This sequence increase will notify the kvm page fault that
793 * the page that is going to be mapped in the spte could have
794 * been freed.
795 */
796 kvm->mmu_notifier_seq++;
a355aa54 797 smp_wmb();
e930bffe
AA
798 /*
799 * The above sequence increase must be visible before the
a355aa54
PM
800 * below count decrease, which is ensured by the smp_wmb above
801 * in conjunction with the smp_rmb in mmu_notifier_retry().
e930bffe
AA
802 */
803 kvm->mmu_notifier_count--;
f922bd9b
SC
804}
805
806static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
807 const struct mmu_notifier_range *range)
808{
809 struct kvm *kvm = mmu_notifier_to_kvm(mn);
810 const struct kvm_hva_range hva_range = {
811 .start = range->start,
812 .end = range->end,
813 .pte = __pte(0),
814 .handler = (void *)kvm_null_fn,
815 .on_lock = kvm_dec_notifier_count,
683412cc 816 .on_unlock = (void *)kvm_null_fn,
f922bd9b
SC
817 .flush_on_ret = false,
818 .may_block = mmu_notifier_range_blockable(range),
819 };
52ac8b35 820 bool wake;
f922bd9b
SC
821
822 __kvm_handle_hva_range(kvm, &hva_range);
e930bffe 823
52ac8b35
PB
824 /* Pairs with the increment in range_start(). */
825 spin_lock(&kvm->mn_invalidate_lock);
826 wake = (--kvm->mn_active_invalidate_count == 0);
827 spin_unlock(&kvm->mn_invalidate_lock);
828
829 /*
830 * There can only be one waiter, since the wait happens under
831 * slots_lock.
832 */
833 if (wake)
834 rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
835
e930bffe
AA
836 BUG_ON(kvm->mmu_notifier_count < 0);
837}
838
839static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
840 struct mm_struct *mm,
57128468
ALC
841 unsigned long start,
842 unsigned long end)
e930bffe 843{
501b9185
SC
844 trace_kvm_age_hva(start, end);
845
3039bcc7 846 return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
e930bffe
AA
847}
848
1d7715c6
VD
849static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
850 struct mm_struct *mm,
851 unsigned long start,
852 unsigned long end)
853{
501b9185
SC
854 trace_kvm_age_hva(start, end);
855
1d7715c6
VD
856 /*
857 * Even though we do not flush TLB, this will still adversely
858 * affect performance on pre-Haswell Intel EPT, where there is
859 * no EPT Access Bit to clear so that we have to tear down EPT
860 * tables instead. If we find this unacceptable, we can always
861 * add a parameter to kvm_age_hva so that it effectively doesn't
862 * do anything on clear_young.
863 *
864 * Also note that currently we never issue secondary TLB flushes
865 * from clear_young, leaving this job up to the regular system
866 * cadence. If we find this inaccurate, we might come up with a
867 * more sophisticated heuristic later.
868 */
3039bcc7 869 return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
1d7715c6
VD
870}
871
8ee53820
AA
872static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
873 struct mm_struct *mm,
874 unsigned long address)
875{
501b9185
SC
876 trace_kvm_test_age_hva(address);
877
3039bcc7
SC
878 return kvm_handle_hva_range_no_flush(mn, address, address + 1,
879 kvm_test_age_gfn);
8ee53820
AA
880}
881
85db06e5
MT
882static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
883 struct mm_struct *mm)
884{
885 struct kvm *kvm = mmu_notifier_to_kvm(mn);
eda2beda
LJ
886 int idx;
887
888 idx = srcu_read_lock(&kvm->srcu);
683412cc 889 kvm_flush_shadow_all(kvm);
eda2beda 890 srcu_read_unlock(&kvm->srcu, idx);
85db06e5
MT
891}
892
e930bffe 893static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
e649b3f0 894 .invalidate_range = kvm_mmu_notifier_invalidate_range,
e930bffe
AA
895 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
896 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
897 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
1d7715c6 898 .clear_young = kvm_mmu_notifier_clear_young,
8ee53820 899 .test_young = kvm_mmu_notifier_test_young,
3da0dd43 900 .change_pte = kvm_mmu_notifier_change_pte,
85db06e5 901 .release = kvm_mmu_notifier_release,
e930bffe 902};
4c07b0a4
AK
903
904static int kvm_init_mmu_notifier(struct kvm *kvm)
905{
906 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
907 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
908}
909
910#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
911
912static int kvm_init_mmu_notifier(struct kvm *kvm)
913{
914 return 0;
915}
916
e930bffe
AA
917#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
918
2fdef3a2
SS
919#ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
920static int kvm_pm_notifier_call(struct notifier_block *bl,
921 unsigned long state,
922 void *unused)
923{
924 struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
925
926 return kvm_arch_pm_notifier(kvm, state);
927}
928
929static void kvm_init_pm_notifier(struct kvm *kvm)
930{
931 kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
932 /* Suspend KVM before we suspend ftrace, RCU, etc. */
933 kvm->pm_notifier.priority = INT_MAX;
934 register_pm_notifier(&kvm->pm_notifier);
935}
936
937static void kvm_destroy_pm_notifier(struct kvm *kvm)
938{
939 unregister_pm_notifier(&kvm->pm_notifier);
940}
941#else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
942static void kvm_init_pm_notifier(struct kvm *kvm)
943{
944}
945
946static void kvm_destroy_pm_notifier(struct kvm *kvm)
947{
948}
949#endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
950
a47d2b07
PB
951static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
952{
953 if (!memslot->dirty_bitmap)
954 return;
955
956 kvfree(memslot->dirty_bitmap);
957 memslot->dirty_bitmap = NULL;
958}
959
a54d8066 960/* This does not remove the slot from struct kvm_memslots data structures */
e96c81ee 961static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
a47d2b07 962{
e96c81ee 963 kvm_destroy_dirty_bitmap(slot);
a47d2b07 964
e96c81ee 965 kvm_arch_free_memslot(kvm, slot);
a47d2b07 966
a54d8066 967 kfree(slot);
a47d2b07
PB
968}
969
970static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
971{
a54d8066 972 struct hlist_node *idnode;
a47d2b07 973 struct kvm_memory_slot *memslot;
a54d8066 974 int bkt;
a47d2b07 975
a54d8066
MS
976 /*
977 * The same memslot objects live in both active and inactive sets,
978 * arbitrarily free using index '1' so the second invocation of this
979 * function isn't operating over a structure with dangling pointers
980 * (even though this function isn't actually touching them).
981 */
982 if (!slots->node_idx)
a47d2b07
PB
983 return;
984
a54d8066 985 hash_for_each_safe(slots->id_hash, bkt, idnode, memslot, id_node[1])
e96c81ee 986 kvm_free_memslot(kvm, memslot);
bf3e05bc
XG
987}
988
bc9e9e67
JZ
989static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
990{
991 switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
992 case KVM_STATS_TYPE_INSTANT:
993 return 0444;
994 case KVM_STATS_TYPE_CUMULATIVE:
995 case KVM_STATS_TYPE_PEAK:
996 default:
997 return 0644;
998 }
999}
1000
1001
536a6f88
JF
1002static void kvm_destroy_vm_debugfs(struct kvm *kvm)
1003{
1004 int i;
bc9e9e67
JZ
1005 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
1006 kvm_vcpu_stats_header.num_desc;
536a6f88 1007
a44a4cc1 1008 if (IS_ERR(kvm->debugfs_dentry))
536a6f88
JF
1009 return;
1010
1011 debugfs_remove_recursive(kvm->debugfs_dentry);
1012
9d5a1dce
LC
1013 if (kvm->debugfs_stat_data) {
1014 for (i = 0; i < kvm_debugfs_num_entries; i++)
1015 kfree(kvm->debugfs_stat_data[i]);
1016 kfree(kvm->debugfs_stat_data);
1017 }
536a6f88
JF
1018}
1019
1020static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
1021{
85cd39af
PB
1022 static DEFINE_MUTEX(kvm_debugfs_lock);
1023 struct dentry *dent;
536a6f88
JF
1024 char dir_name[ITOA_MAX_LEN * 2];
1025 struct kvm_stat_data *stat_data;
bc9e9e67 1026 const struct _kvm_stats_desc *pdesc;
3165af73 1027 int i, ret;
bc9e9e67
JZ
1028 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
1029 kvm_vcpu_stats_header.num_desc;
536a6f88
JF
1030
1031 if (!debugfs_initialized())
1032 return 0;
1033
1034 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
85cd39af
PB
1035 mutex_lock(&kvm_debugfs_lock);
1036 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
1037 if (dent) {
1038 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
1039 dput(dent);
1040 mutex_unlock(&kvm_debugfs_lock);
1041 return 0;
1042 }
1043 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
1044 mutex_unlock(&kvm_debugfs_lock);
1045 if (IS_ERR(dent))
1046 return 0;
536a6f88 1047
85cd39af 1048 kvm->debugfs_dentry = dent;
536a6f88
JF
1049 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
1050 sizeof(*kvm->debugfs_stat_data),
b12ce36a 1051 GFP_KERNEL_ACCOUNT);
536a6f88
JF
1052 if (!kvm->debugfs_stat_data)
1053 return -ENOMEM;
1054
bc9e9e67
JZ
1055 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
1056 pdesc = &kvm_vm_stats_desc[i];
b12ce36a 1057 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
536a6f88
JF
1058 if (!stat_data)
1059 return -ENOMEM;
1060
1061 stat_data->kvm = kvm;
bc9e9e67
JZ
1062 stat_data->desc = pdesc;
1063 stat_data->kind = KVM_STAT_VM;
1064 kvm->debugfs_stat_data[i] = stat_data;
1065 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1066 kvm->debugfs_dentry, stat_data,
1067 &stat_fops_per_vm);
1068 }
1069
1070 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
1071 pdesc = &kvm_vcpu_stats_desc[i];
b12ce36a 1072 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
536a6f88
JF
1073 if (!stat_data)
1074 return -ENOMEM;
1075
1076 stat_data->kvm = kvm;
bc9e9e67
JZ
1077 stat_data->desc = pdesc;
1078 stat_data->kind = KVM_STAT_VCPU;
004d62eb 1079 kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
bc9e9e67 1080 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
09cbcef6
MP
1081 kvm->debugfs_dentry, stat_data,
1082 &stat_fops_per_vm);
536a6f88 1083 }
3165af73
PX
1084
1085 ret = kvm_arch_create_vm_debugfs(kvm);
1086 if (ret) {
1087 kvm_destroy_vm_debugfs(kvm);
1088 return i;
1089 }
1090
536a6f88
JF
1091 return 0;
1092}
1093
1aa9b957
JS
1094/*
1095 * Called after the VM is otherwise initialized, but just before adding it to
1096 * the vm_list.
1097 */
1098int __weak kvm_arch_post_init_vm(struct kvm *kvm)
1099{
1100 return 0;
1101}
1102
1103/*
1104 * Called just after removing the VM from the vm_list, but before doing any
1105 * other destruction.
1106 */
1107void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
1108{
1109}
1110
3165af73
PX
1111/*
1112 * Called after per-vm debugfs created. When called kvm->debugfs_dentry should
1113 * be setup already, so we can create arch-specific debugfs entries under it.
1114 * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
1115 * a per-arch destroy interface is not needed.
1116 */
1117int __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
1118{
1119 return 0;
1120}
1121
e08b9637 1122static struct kvm *kvm_create_vm(unsigned long type)
6aa8b732 1123{
d89f5eff 1124 struct kvm *kvm = kvm_arch_alloc_vm();
a54d8066 1125 struct kvm_memslots *slots;
9121923c 1126 int r = -ENOMEM;
a54d8066 1127 int i, j;
6aa8b732 1128
d89f5eff
JK
1129 if (!kvm)
1130 return ERR_PTR(-ENOMEM);
1131
531810ca 1132 KVM_MMU_LOCK_INIT(kvm);
f1f10076 1133 mmgrab(current->mm);
e9ad4ec8
PB
1134 kvm->mm = current->mm;
1135 kvm_eventfd_init(kvm);
1136 mutex_init(&kvm->lock);
1137 mutex_init(&kvm->irq_lock);
1138 mutex_init(&kvm->slots_lock);
b10a038e 1139 mutex_init(&kvm->slots_arch_lock);
52ac8b35
PB
1140 spin_lock_init(&kvm->mn_invalidate_lock);
1141 rcuwait_init(&kvm->mn_memslots_update_rcuwait);
c5b07754 1142 xa_init(&kvm->vcpu_array);
52ac8b35 1143
982ed0de
DW
1144 INIT_LIST_HEAD(&kvm->gpc_list);
1145 spin_lock_init(&kvm->gpc_lock);
52ac8b35 1146
e9ad4ec8 1147 INIT_LIST_HEAD(&kvm->devices);
f502cc56 1148 kvm->max_vcpus = KVM_MAX_VCPUS;
e9ad4ec8 1149
1e702d9a
AW
1150 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
1151
5c697c36
SC
1152 /*
1153 * Force subsequent debugfs file creations to fail if the VM directory
1154 * is not created (by kvm_create_vm_debugfs()).
1155 */
1156 kvm->debugfs_dentry = ERR_PTR(-ENOENT);
1157
8a44119a
PB
1158 if (init_srcu_struct(&kvm->srcu))
1159 goto out_err_no_srcu;
1160 if (init_srcu_struct(&kvm->irq_srcu))
1161 goto out_err_no_irq_srcu;
1162
e2d3fcaf 1163 refcount_set(&kvm->users_count, 1);
f481b069 1164 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
a54d8066
MS
1165 for (j = 0; j < 2; j++) {
1166 slots = &kvm->__memslots[i][j];
9121923c 1167
a54d8066
MS
1168 atomic_long_set(&slots->last_used_slot, (unsigned long)NULL);
1169 slots->hva_tree = RB_ROOT_CACHED;
1170 slots->gfn_tree = RB_ROOT;
1171 hash_init(slots->id_hash);
1172 slots->node_idx = j;
1173
1174 /* Generations must be different for each address space. */
1175 slots->generation = i;
1176 }
1177
1178 rcu_assign_pointer(kvm->memslots[i], &kvm->__memslots[i][0]);
f481b069 1179 }
00f034a1 1180
e93f8a0f 1181 for (i = 0; i < KVM_NR_BUSES; i++) {
4a12f951 1182 rcu_assign_pointer(kvm->buses[i],
b12ce36a 1183 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
57e7fbee 1184 if (!kvm->buses[i])
a97b0e77 1185 goto out_err_no_arch_destroy_vm;
e93f8a0f 1186 }
e930bffe 1187
acd05785
DM
1188 kvm->max_halt_poll_ns = halt_poll_ns;
1189
e08b9637 1190 r = kvm_arch_init_vm(kvm, type);
d89f5eff 1191 if (r)
a97b0e77 1192 goto out_err_no_arch_destroy_vm;
10474ae8
AG
1193
1194 r = hardware_enable_all();
1195 if (r)
719d93cd 1196 goto out_err_no_disable;
10474ae8 1197
c77dcacb 1198#ifdef CONFIG_HAVE_KVM_IRQFD
136bdfee 1199 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
75858a84 1200#endif
6aa8b732 1201
74b5c5bf 1202 r = kvm_init_mmu_notifier(kvm);
1aa9b957
JS
1203 if (r)
1204 goto out_err_no_mmu_notifier;
1205
1206 r = kvm_arch_post_init_vm(kvm);
74b5c5bf
MW
1207 if (r)
1208 goto out_err;
1209
0d9ce162 1210 mutex_lock(&kvm_lock);
5e58cfe4 1211 list_add(&kvm->vm_list, &vm_list);
0d9ce162 1212 mutex_unlock(&kvm_lock);
d89f5eff 1213
2ecd9d29 1214 preempt_notifier_inc();
2fdef3a2 1215 kvm_init_pm_notifier(kvm);
2ecd9d29 1216
5f6de5cb
DM
1217 /*
1218 * When the fd passed to this ioctl() is opened it pins the module,
1219 * but try_module_get() also prevents getting a reference if the module
1220 * is in MODULE_STATE_GOING (e.g. if someone ran "rmmod --wait").
1221 */
1222 if (!try_module_get(kvm_chardev_ops.owner)) {
1223 r = -ENODEV;
1224 goto out_err;
1225 }
1226
f17abe9a 1227 return kvm;
10474ae8
AG
1228
1229out_err:
1aa9b957
JS
1230#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1231 if (kvm->mmu_notifier.ops)
1232 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1233#endif
1234out_err_no_mmu_notifier:
10474ae8 1235 hardware_disable_all();
719d93cd 1236out_err_no_disable:
a97b0e77 1237 kvm_arch_destroy_vm(kvm);
a97b0e77 1238out_err_no_arch_destroy_vm:
e2d3fcaf 1239 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
e93f8a0f 1240 for (i = 0; i < KVM_NR_BUSES; i++)
3898da94 1241 kfree(kvm_get_bus(kvm, i));
8a44119a
PB
1242 cleanup_srcu_struct(&kvm->irq_srcu);
1243out_err_no_irq_srcu:
1244 cleanup_srcu_struct(&kvm->srcu);
1245out_err_no_srcu:
d89f5eff 1246 kvm_arch_free_vm(kvm);
e9ad4ec8 1247 mmdrop(current->mm);
10474ae8 1248 return ERR_PTR(r);
f17abe9a
AK
1249}
1250
07f0a7bd
SW
1251static void kvm_destroy_devices(struct kvm *kvm)
1252{
e6e3b5a6 1253 struct kvm_device *dev, *tmp;
07f0a7bd 1254
a28ebea2
CD
1255 /*
1256 * We do not need to take the kvm->lock here, because nobody else
1257 * has a reference to the struct kvm at this point and therefore
1258 * cannot access the devices list anyhow.
1259 */
e6e3b5a6
GT
1260 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1261 list_del(&dev->vm_node);
07f0a7bd
SW
1262 dev->ops->destroy(dev);
1263 }
1264}
1265
f17abe9a
AK
1266static void kvm_destroy_vm(struct kvm *kvm)
1267{
e93f8a0f 1268 int i;
6d4e4c4f
AK
1269 struct mm_struct *mm = kvm->mm;
1270
2fdef3a2 1271 kvm_destroy_pm_notifier(kvm);
286de8f6 1272 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
536a6f88 1273 kvm_destroy_vm_debugfs(kvm);
ad8ba2cd 1274 kvm_arch_sync_events(kvm);
0d9ce162 1275 mutex_lock(&kvm_lock);
133de902 1276 list_del(&kvm->vm_list);
0d9ce162 1277 mutex_unlock(&kvm_lock);
1aa9b957
JS
1278 kvm_arch_pre_destroy_vm(kvm);
1279
399ec807 1280 kvm_free_irq_routing(kvm);
df630b8c 1281 for (i = 0; i < KVM_NR_BUSES; i++) {
3898da94 1282 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
4a12f951 1283
4a12f951
CB
1284 if (bus)
1285 kvm_io_bus_destroy(bus);
df630b8c
PX
1286 kvm->buses[i] = NULL;
1287 }
980da6ce 1288 kvm_coalesced_mmio_free(kvm);
e930bffe
AA
1289#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1290 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
52ac8b35
PB
1291 /*
1292 * At this point, pending calls to invalidate_range_start()
1293 * have completed but no more MMU notifiers will run, so
1294 * mn_active_invalidate_count may remain unbalanced.
1295 * No threads can be waiting in install_new_memslots as the
1296 * last reference on KVM has been dropped, but freeing
1297 * memslots would deadlock without this manual intervention.
1298 */
1299 WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
1300 kvm->mn_active_invalidate_count = 0;
f00be0ca 1301#else
683412cc 1302 kvm_flush_shadow_all(kvm);
5f94c174 1303#endif
d19a9cd2 1304 kvm_arch_destroy_vm(kvm);
07f0a7bd 1305 kvm_destroy_devices(kvm);
a54d8066
MS
1306 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1307 kvm_free_memslots(kvm, &kvm->__memslots[i][0]);
1308 kvm_free_memslots(kvm, &kvm->__memslots[i][1]);
1309 }
820b3fcd 1310 cleanup_srcu_struct(&kvm->irq_srcu);
d89f5eff
JK
1311 cleanup_srcu_struct(&kvm->srcu);
1312 kvm_arch_free_vm(kvm);
2ecd9d29 1313 preempt_notifier_dec();
10474ae8 1314 hardware_disable_all();
6d4e4c4f 1315 mmdrop(mm);
5f6de5cb 1316 module_put(kvm_chardev_ops.owner);
f17abe9a
AK
1317}
1318
d39f13b0
IE
1319void kvm_get_kvm(struct kvm *kvm)
1320{
e3736c3e 1321 refcount_inc(&kvm->users_count);
d39f13b0
IE
1322}
1323EXPORT_SYMBOL_GPL(kvm_get_kvm);
1324
605c7130
PX
1325/*
1326 * Make sure the vm is not during destruction, which is a safe version of
1327 * kvm_get_kvm(). Return true if kvm referenced successfully, false otherwise.
1328 */
1329bool kvm_get_kvm_safe(struct kvm *kvm)
1330{
1331 return refcount_inc_not_zero(&kvm->users_count);
1332}
1333EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
1334
d39f13b0
IE
1335void kvm_put_kvm(struct kvm *kvm)
1336{
e3736c3e 1337 if (refcount_dec_and_test(&kvm->users_count))
d39f13b0
IE
1338 kvm_destroy_vm(kvm);
1339}
1340EXPORT_SYMBOL_GPL(kvm_put_kvm);
1341
149487bd
SC
1342/*
1343 * Used to put a reference that was taken on behalf of an object associated
1344 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1345 * of the new file descriptor fails and the reference cannot be transferred to
1346 * its final owner. In such cases, the caller is still actively using @kvm and
1347 * will fail miserably if the refcount unexpectedly hits zero.
1348 */
1349void kvm_put_kvm_no_destroy(struct kvm *kvm)
1350{
1351 WARN_ON(refcount_dec_and_test(&kvm->users_count));
1352}
1353EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
d39f13b0 1354
f17abe9a
AK
1355static int kvm_vm_release(struct inode *inode, struct file *filp)
1356{
1357 struct kvm *kvm = filp->private_data;
1358
721eecbf
GH
1359 kvm_irqfd_release(kvm);
1360
d39f13b0 1361 kvm_put_kvm(kvm);
6aa8b732
AK
1362 return 0;
1363}
1364
515a0127
TY
1365/*
1366 * Allocation size is twice as large as the actual dirty bitmap size.
0dff0846 1367 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
515a0127 1368 */
3c9bd400 1369static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
a36a57b1 1370{
37b2a651 1371 unsigned long dirty_bytes = kvm_dirty_bitmap_bytes(memslot);
a36a57b1 1372
37b2a651 1373 memslot->dirty_bitmap = __vcalloc(2, dirty_bytes, GFP_KERNEL_ACCOUNT);
a36a57b1
TY
1374 if (!memslot->dirty_bitmap)
1375 return -ENOMEM;
1376
a36a57b1
TY
1377 return 0;
1378}
1379
a54d8066 1380static struct kvm_memslots *kvm_get_inactive_memslots(struct kvm *kvm, int as_id)
bf3e05bc 1381{
a54d8066
MS
1382 struct kvm_memslots *active = __kvm_memslots(kvm, as_id);
1383 int node_idx_inactive = active->node_idx ^ 1;
0e60b079 1384
a54d8066 1385 return &kvm->__memslots[as_id][node_idx_inactive];
0577d1ab
SC
1386}
1387
1388/*
a54d8066
MS
1389 * Helper to get the address space ID when one of memslot pointers may be NULL.
1390 * This also serves as a sanity that at least one of the pointers is non-NULL,
1391 * and that their address space IDs don't diverge.
0577d1ab 1392 */
a54d8066
MS
1393static int kvm_memslots_get_as_id(struct kvm_memory_slot *a,
1394 struct kvm_memory_slot *b)
0577d1ab 1395{
a54d8066
MS
1396 if (WARN_ON_ONCE(!a && !b))
1397 return 0;
0577d1ab 1398
a54d8066
MS
1399 if (!a)
1400 return b->as_id;
1401 if (!b)
1402 return a->as_id;
0577d1ab 1403
a54d8066
MS
1404 WARN_ON_ONCE(a->as_id != b->as_id);
1405 return a->as_id;
0577d1ab 1406}
efbeec70 1407
a54d8066
MS
1408static void kvm_insert_gfn_node(struct kvm_memslots *slots,
1409 struct kvm_memory_slot *slot)
0577d1ab 1410{
a54d8066
MS
1411 struct rb_root *gfn_tree = &slots->gfn_tree;
1412 struct rb_node **node, *parent;
1413 int idx = slots->node_idx;
0577d1ab 1414
a54d8066
MS
1415 parent = NULL;
1416 for (node = &gfn_tree->rb_node; *node; ) {
1417 struct kvm_memory_slot *tmp;
f85e2cb5 1418
a54d8066
MS
1419 tmp = container_of(*node, struct kvm_memory_slot, gfn_node[idx]);
1420 parent = *node;
1421 if (slot->base_gfn < tmp->base_gfn)
1422 node = &(*node)->rb_left;
1423 else if (slot->base_gfn > tmp->base_gfn)
1424 node = &(*node)->rb_right;
1425 else
1426 BUG();
0577d1ab 1427 }
a54d8066
MS
1428
1429 rb_link_node(&slot->gfn_node[idx], parent, node);
1430 rb_insert_color(&slot->gfn_node[idx], gfn_tree);
0577d1ab
SC
1431}
1432
a54d8066
MS
1433static void kvm_erase_gfn_node(struct kvm_memslots *slots,
1434 struct kvm_memory_slot *slot)
0577d1ab 1435{
a54d8066
MS
1436 rb_erase(&slot->gfn_node[slots->node_idx], &slots->gfn_tree);
1437}
0577d1ab 1438
a54d8066
MS
1439static void kvm_replace_gfn_node(struct kvm_memslots *slots,
1440 struct kvm_memory_slot *old,
1441 struct kvm_memory_slot *new)
1442{
1443 int idx = slots->node_idx;
0577d1ab 1444
a54d8066 1445 WARN_ON_ONCE(old->base_gfn != new->base_gfn);
0577d1ab 1446
a54d8066
MS
1447 rb_replace_node(&old->gfn_node[idx], &new->gfn_node[idx],
1448 &slots->gfn_tree);
0577d1ab
SC
1449}
1450
1451/*
a54d8066 1452 * Replace @old with @new in the inactive memslots.
0577d1ab 1453 *
a54d8066
MS
1454 * With NULL @old this simply adds @new.
1455 * With NULL @new this simply removes @old.
0577d1ab 1456 *
a54d8066
MS
1457 * If @new is non-NULL its hva_node[slots_idx] range has to be set
1458 * appropriately.
0577d1ab 1459 */
a54d8066
MS
1460static void kvm_replace_memslot(struct kvm *kvm,
1461 struct kvm_memory_slot *old,
1462 struct kvm_memory_slot *new)
0577d1ab 1463{
a54d8066
MS
1464 int as_id = kvm_memslots_get_as_id(old, new);
1465 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1466 int idx = slots->node_idx;
0577d1ab 1467
a54d8066
MS
1468 if (old) {
1469 hash_del(&old->id_node[idx]);
1470 interval_tree_remove(&old->hva_node[idx], &slots->hva_tree);
0577d1ab 1471
a54d8066
MS
1472 if ((long)old == atomic_long_read(&slots->last_used_slot))
1473 atomic_long_set(&slots->last_used_slot, (long)new);
0577d1ab 1474
a54d8066
MS
1475 if (!new) {
1476 kvm_erase_gfn_node(slots, old);
1e8617d3 1477 return;
a54d8066
MS
1478 }
1479 }
1e8617d3 1480
a54d8066
MS
1481 /*
1482 * Initialize @new's hva range. Do this even when replacing an @old
1483 * slot, kvm_copy_memslot() deliberately does not touch node data.
1484 */
1485 new->hva_node[idx].start = new->userspace_addr;
1486 new->hva_node[idx].last = new->userspace_addr +
1487 (new->npages << PAGE_SHIFT) - 1;
1488
1489 /*
1490 * (Re)Add the new memslot. There is no O(1) interval_tree_replace(),
1491 * hva_node needs to be swapped with remove+insert even though hva can't
1492 * change when replacing an existing slot.
1493 */
1494 hash_add(slots->id_hash, &new->id_node[idx], new->id);
1495 interval_tree_insert(&new->hva_node[idx], &slots->hva_tree);
1496
1497 /*
1498 * If the memslot gfn is unchanged, rb_replace_node() can be used to
1499 * switch the node in the gfn tree instead of removing the old and
1500 * inserting the new as two separate operations. Replacement is a
1501 * single O(1) operation versus two O(log(n)) operations for
1502 * remove+insert.
1503 */
1504 if (old && old->base_gfn == new->base_gfn) {
1505 kvm_replace_gfn_node(slots, old, new);
1506 } else {
1507 if (old)
1508 kvm_erase_gfn_node(slots, old);
1509 kvm_insert_gfn_node(slots, new);
0577d1ab 1510 }
bf3e05bc
XG
1511}
1512
09170a49 1513static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
a50d64d6 1514{
4d8b81ab
XG
1515 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1516
0f8a4de3 1517#ifdef __KVM_HAVE_READONLY_MEM
4d8b81ab
XG
1518 valid_flags |= KVM_MEM_READONLY;
1519#endif
1520
1521 if (mem->flags & ~valid_flags)
a50d64d6
XG
1522 return -EINVAL;
1523
1524 return 0;
1525}
1526
a54d8066 1527static void kvm_swap_active_memslots(struct kvm *kvm, int as_id)
7ec4fb44 1528{
a54d8066
MS
1529 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1530
1531 /* Grab the generation from the activate memslots. */
1532 u64 gen = __kvm_memslots(kvm, as_id)->generation;
7ec4fb44 1533
361209e0
SC
1534 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1535 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
ee3d1570 1536
52ac8b35
PB
1537 /*
1538 * Do not store the new memslots while there are invalidations in
071064f1
PB
1539 * progress, otherwise the locking in invalidate_range_start and
1540 * invalidate_range_end will be unbalanced.
52ac8b35
PB
1541 */
1542 spin_lock(&kvm->mn_invalidate_lock);
1543 prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
1544 while (kvm->mn_active_invalidate_count) {
1545 set_current_state(TASK_UNINTERRUPTIBLE);
1546 spin_unlock(&kvm->mn_invalidate_lock);
1547 schedule();
1548 spin_lock(&kvm->mn_invalidate_lock);
1549 }
1550 finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
f481b069 1551 rcu_assign_pointer(kvm->memslots[as_id], slots);
52ac8b35 1552 spin_unlock(&kvm->mn_invalidate_lock);
b10a038e
BG
1553
1554 /*
1555 * Acquired in kvm_set_memslot. Must be released before synchronize
1556 * SRCU below in order to avoid deadlock with another thread
1557 * acquiring the slots_arch_lock in an srcu critical section.
1558 */
1559 mutex_unlock(&kvm->slots_arch_lock);
1560
7ec4fb44 1561 synchronize_srcu_expedited(&kvm->srcu);
e59dbe09 1562
ee3d1570 1563 /*
361209e0 1564 * Increment the new memslot generation a second time, dropping the
00116795 1565 * update in-progress flag and incrementing the generation based on
361209e0
SC
1566 * the number of address spaces. This provides a unique and easily
1567 * identifiable generation number while the memslots are in flux.
1568 */
1569 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1570
1571 /*
4bd518f1
PB
1572 * Generations must be unique even across address spaces. We do not need
1573 * a global counter for that, instead the generation space is evenly split
1574 * across address spaces. For example, with two address spaces, address
164bf7e5
SC
1575 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1576 * use generations 1, 3, 5, ...
ee3d1570 1577 */
164bf7e5 1578 gen += KVM_ADDRESS_SPACE_NUM;
ee3d1570 1579
15248258 1580 kvm_arch_memslots_updated(kvm, gen);
ee3d1570 1581
15248258 1582 slots->generation = gen;
7ec4fb44
GN
1583}
1584
07921665
SC
1585static int kvm_prepare_memory_region(struct kvm *kvm,
1586 const struct kvm_memory_slot *old,
1587 struct kvm_memory_slot *new,
1588 enum kvm_mr_change change)
ddc12f2a 1589{
07921665
SC
1590 int r;
1591
1592 /*
1593 * If dirty logging is disabled, nullify the bitmap; the old bitmap
1594 * will be freed on "commit". If logging is enabled in both old and
1595 * new, reuse the existing bitmap. If logging is enabled only in the
1596 * new and KVM isn't using a ring buffer, allocate and initialize a
1597 * new bitmap.
1598 */
244893fa
SC
1599 if (change != KVM_MR_DELETE) {
1600 if (!(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
1601 new->dirty_bitmap = NULL;
1602 else if (old && old->dirty_bitmap)
1603 new->dirty_bitmap = old->dirty_bitmap;
1604 else if (!kvm->dirty_ring_size) {
1605 r = kvm_alloc_dirty_bitmap(new);
1606 if (r)
1607 return r;
1608
1609 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1610 bitmap_set(new->dirty_bitmap, 0, new->npages);
1611 }
07921665
SC
1612 }
1613
1614 r = kvm_arch_prepare_memory_region(kvm, old, new, change);
1615
1616 /* Free the bitmap on failure if it was allocated above. */
c87661f8 1617 if (r && new && new->dirty_bitmap && (!old || !old->dirty_bitmap))
07921665
SC
1618 kvm_destroy_dirty_bitmap(new);
1619
1620 return r;
ddc12f2a
BG
1621}
1622
07921665
SC
1623static void kvm_commit_memory_region(struct kvm *kvm,
1624 struct kvm_memory_slot *old,
1625 const struct kvm_memory_slot *new,
1626 enum kvm_mr_change change)
ddc12f2a 1627{
07921665
SC
1628 /*
1629 * Update the total number of memslot pages before calling the arch
1630 * hook so that architectures can consume the result directly.
1631 */
1632 if (change == KVM_MR_DELETE)
1633 kvm->nr_memslot_pages -= old->npages;
1634 else if (change == KVM_MR_CREATE)
1635 kvm->nr_memslot_pages += new->npages;
1636
1637 kvm_arch_commit_memory_region(kvm, old, new, change);
1638
a54d8066
MS
1639 switch (change) {
1640 case KVM_MR_CREATE:
1641 /* Nothing more to do. */
1642 break;
1643 case KVM_MR_DELETE:
1644 /* Free the old memslot and all its metadata. */
1645 kvm_free_memslot(kvm, old);
1646 break;
1647 case KVM_MR_MOVE:
1648 case KVM_MR_FLAGS_ONLY:
1649 /*
1650 * Free the dirty bitmap as needed; the below check encompasses
1651 * both the flags and whether a ring buffer is being used)
1652 */
1653 if (old->dirty_bitmap && !new->dirty_bitmap)
1654 kvm_destroy_dirty_bitmap(old);
1655
1656 /*
1657 * The final quirk. Free the detached, old slot, but only its
1658 * memory, not any metadata. Metadata, including arch specific
1659 * data, may be reused by @new.
1660 */
1661 kfree(old);
1662 break;
1663 default:
1664 BUG();
1665 }
ddc12f2a
BG
1666}
1667
36947254 1668/*
a54d8066
MS
1669 * Activate @new, which must be installed in the inactive slots by the caller,
1670 * by swapping the active slots and then propagating @new to @old once @old is
1671 * unreachable and can be safely modified.
1672 *
1673 * With NULL @old this simply adds @new to @active (while swapping the sets).
1674 * With NULL @new this simply removes @old from @active and frees it
1675 * (while also swapping the sets).
36947254 1676 */
a54d8066
MS
1677static void kvm_activate_memslot(struct kvm *kvm,
1678 struct kvm_memory_slot *old,
1679 struct kvm_memory_slot *new)
36947254 1680{
a54d8066 1681 int as_id = kvm_memslots_get_as_id(old, new);
36947254 1682
a54d8066
MS
1683 kvm_swap_active_memslots(kvm, as_id);
1684
1685 /* Propagate the new memslot to the now inactive memslots. */
1686 kvm_replace_memslot(kvm, old, new);
1687}
1688
1689static void kvm_copy_memslot(struct kvm_memory_slot *dest,
1690 const struct kvm_memory_slot *src)
1691{
1692 dest->base_gfn = src->base_gfn;
1693 dest->npages = src->npages;
1694 dest->dirty_bitmap = src->dirty_bitmap;
1695 dest->arch = src->arch;
1696 dest->userspace_addr = src->userspace_addr;
1697 dest->flags = src->flags;
1698 dest->id = src->id;
1699 dest->as_id = src->as_id;
1700}
1701
1702static void kvm_invalidate_memslot(struct kvm *kvm,
1703 struct kvm_memory_slot *old,
244893fa 1704 struct kvm_memory_slot *invalid_slot)
a54d8066 1705{
07921665 1706 /*
a54d8066
MS
1707 * Mark the current slot INVALID. As with all memslot modifications,
1708 * this must be done on an unreachable slot to avoid modifying the
1709 * current slot in the active tree.
07921665 1710 */
244893fa
SC
1711 kvm_copy_memslot(invalid_slot, old);
1712 invalid_slot->flags |= KVM_MEMSLOT_INVALID;
1713 kvm_replace_memslot(kvm, old, invalid_slot);
a54d8066
MS
1714
1715 /*
1716 * Activate the slot that is now marked INVALID, but don't propagate
1717 * the slot to the now inactive slots. The slot is either going to be
1718 * deleted or recreated as a new slot.
1719 */
1720 kvm_swap_active_memslots(kvm, old->as_id);
1721
1722 /*
1723 * From this point no new shadow pages pointing to a deleted, or moved,
1724 * memslot will be created. Validation of sp->gfn happens in:
1725 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1726 * - kvm_is_visible_gfn (mmu_check_root)
1727 */
bcb63dcd 1728 kvm_arch_flush_shadow_memslot(kvm, old);
683412cc 1729 kvm_arch_guest_memory_reclaimed(kvm);
a54d8066
MS
1730
1731 /* Was released by kvm_swap_active_memslots, reacquire. */
1732 mutex_lock(&kvm->slots_arch_lock);
1733
1734 /*
1735 * Copy the arch-specific field of the newly-installed slot back to the
1736 * old slot as the arch data could have changed between releasing
1737 * slots_arch_lock in install_new_memslots() and re-acquiring the lock
1738 * above. Writers are required to retrieve memslots *after* acquiring
1739 * slots_arch_lock, thus the active slot's data is guaranteed to be fresh.
1740 */
244893fa 1741 old->arch = invalid_slot->arch;
a54d8066
MS
1742}
1743
1744static void kvm_create_memslot(struct kvm *kvm,
244893fa 1745 struct kvm_memory_slot *new)
a54d8066 1746{
244893fa
SC
1747 /* Add the new memslot to the inactive set and activate. */
1748 kvm_replace_memslot(kvm, NULL, new);
1749 kvm_activate_memslot(kvm, NULL, new);
a54d8066
MS
1750}
1751
1752static void kvm_delete_memslot(struct kvm *kvm,
1753 struct kvm_memory_slot *old,
1754 struct kvm_memory_slot *invalid_slot)
1755{
1756 /*
1757 * Remove the old memslot (in the inactive memslots) by passing NULL as
244893fa 1758 * the "new" slot, and for the invalid version in the active slots.
a54d8066
MS
1759 */
1760 kvm_replace_memslot(kvm, old, NULL);
a54d8066 1761 kvm_activate_memslot(kvm, invalid_slot, NULL);
a54d8066 1762}
36947254 1763
244893fa
SC
1764static void kvm_move_memslot(struct kvm *kvm,
1765 struct kvm_memory_slot *old,
1766 struct kvm_memory_slot *new,
1767 struct kvm_memory_slot *invalid_slot)
a54d8066 1768{
a54d8066 1769 /*
244893fa
SC
1770 * Replace the old memslot in the inactive slots, and then swap slots
1771 * and replace the current INVALID with the new as well.
a54d8066 1772 */
244893fa
SC
1773 kvm_replace_memslot(kvm, old, new);
1774 kvm_activate_memslot(kvm, invalid_slot, new);
a54d8066 1775}
36947254 1776
a54d8066
MS
1777static void kvm_update_flags_memslot(struct kvm *kvm,
1778 struct kvm_memory_slot *old,
244893fa 1779 struct kvm_memory_slot *new)
a54d8066
MS
1780{
1781 /*
1782 * Similar to the MOVE case, but the slot doesn't need to be zapped as
1783 * an intermediate step. Instead, the old memslot is simply replaced
1784 * with a new, updated copy in both memslot sets.
1785 */
244893fa
SC
1786 kvm_replace_memslot(kvm, old, new);
1787 kvm_activate_memslot(kvm, old, new);
36947254
SC
1788}
1789
cf47f50b 1790static int kvm_set_memslot(struct kvm *kvm,
a54d8066 1791 struct kvm_memory_slot *old,
ce5f0215 1792 struct kvm_memory_slot *new,
cf47f50b
SC
1793 enum kvm_mr_change change)
1794{
244893fa 1795 struct kvm_memory_slot *invalid_slot;
cf47f50b
SC
1796 int r;
1797
b10a038e 1798 /*
a54d8066 1799 * Released in kvm_swap_active_memslots.
b10a038e
BG
1800 *
1801 * Must be held from before the current memslots are copied until
1802 * after the new memslots are installed with rcu_assign_pointer,
a54d8066 1803 * then released before the synchronize srcu in kvm_swap_active_memslots.
b10a038e
BG
1804 *
1805 * When modifying memslots outside of the slots_lock, must be held
1806 * before reading the pointer to the current memslots until after all
1807 * changes to those memslots are complete.
1808 *
1809 * These rules ensure that installing new memslots does not lose
1810 * changes made to the previous memslots.
1811 */
1812 mutex_lock(&kvm->slots_arch_lock);
1813
a54d8066
MS
1814 /*
1815 * Invalidate the old slot if it's being deleted or moved. This is
1816 * done prior to actually deleting/moving the memslot to allow vCPUs to
1817 * continue running by ensuring there are no mappings or shadow pages
1818 * for the memslot when it is deleted/moved. Without pre-invalidation
1819 * (and without a lock), a window would exist between effecting the
1820 * delete/move and committing the changes in arch code where KVM or a
1821 * guest could access a non-existent memslot.
244893fa
SC
1822 *
1823 * Modifications are done on a temporary, unreachable slot. The old
1824 * slot needs to be preserved in case a later step fails and the
1825 * invalidation needs to be reverted.
a54d8066 1826 */
cf47f50b 1827 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
244893fa
SC
1828 invalid_slot = kzalloc(sizeof(*invalid_slot), GFP_KERNEL_ACCOUNT);
1829 if (!invalid_slot) {
1830 mutex_unlock(&kvm->slots_arch_lock);
1831 return -ENOMEM;
1832 }
1833 kvm_invalidate_memslot(kvm, old, invalid_slot);
1834 }
b10a038e 1835
a54d8066
MS
1836 r = kvm_prepare_memory_region(kvm, old, new, change);
1837 if (r) {
b10a038e 1838 /*
a54d8066
MS
1839 * For DELETE/MOVE, revert the above INVALID change. No
1840 * modifications required since the original slot was preserved
1841 * in the inactive slots. Changing the active memslots also
1842 * release slots_arch_lock.
b10a038e 1843 */
244893fa
SC
1844 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1845 kvm_activate_memslot(kvm, invalid_slot, old);
1846 kfree(invalid_slot);
1847 } else {
a54d8066 1848 mutex_unlock(&kvm->slots_arch_lock);
244893fa 1849 }
a54d8066 1850 return r;
cf47f50b
SC
1851 }
1852
bda44d84 1853 /*
a54d8066
MS
1854 * For DELETE and MOVE, the working slot is now active as the INVALID
1855 * version of the old slot. MOVE is particularly special as it reuses
1856 * the old slot and returns a copy of the old slot (in working_slot).
1857 * For CREATE, there is no old slot. For DELETE and FLAGS_ONLY, the
1858 * old slot is detached but otherwise preserved.
bda44d84 1859 */
a54d8066 1860 if (change == KVM_MR_CREATE)
244893fa 1861 kvm_create_memslot(kvm, new);
a54d8066 1862 else if (change == KVM_MR_DELETE)
244893fa 1863 kvm_delete_memslot(kvm, old, invalid_slot);
a54d8066 1864 else if (change == KVM_MR_MOVE)
244893fa 1865 kvm_move_memslot(kvm, old, new, invalid_slot);
a54d8066 1866 else if (change == KVM_MR_FLAGS_ONLY)
244893fa 1867 kvm_update_flags_memslot(kvm, old, new);
a54d8066
MS
1868 else
1869 BUG();
cf47f50b 1870
244893fa
SC
1871 /* Free the temporary INVALID slot used for DELETE and MOVE. */
1872 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1873 kfree(invalid_slot);
bda44d84 1874
a54d8066
MS
1875 /*
1876 * No need to refresh new->arch, changes after dropping slots_arch_lock
a413a625 1877 * will directly hit the final, active memslot. Architectures are
a54d8066
MS
1878 * responsible for knowing that new->arch may be stale.
1879 */
1880 kvm_commit_memory_region(kvm, old, new, change);
cf47f50b 1881
cf47f50b 1882 return 0;
cf47f50b
SC
1883}
1884
44401a20
MS
1885static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,
1886 gfn_t start, gfn_t end)
5c0b4f3d 1887{
44401a20 1888 struct kvm_memslot_iter iter;
5c0b4f3d 1889
44401a20
MS
1890 kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {
1891 if (iter.slot->id != id)
1892 return true;
1893 }
5c0b4f3d 1894
44401a20 1895 return false;
5c0b4f3d
SC
1896}
1897
6aa8b732
AK
1898/*
1899 * Allocate some memory and give it an address in the guest physical address
1900 * space.
1901 *
1902 * Discontiguous memory is allowed, mostly for framebuffers.
f78e0e2e 1903 *
02d5d55b 1904 * Must be called holding kvm->slots_lock for write.
6aa8b732 1905 */
f78e0e2e 1906int __kvm_set_memory_region(struct kvm *kvm,
09170a49 1907 const struct kvm_userspace_memory_region *mem)
6aa8b732 1908{
244893fa 1909 struct kvm_memory_slot *old, *new;
44401a20 1910 struct kvm_memslots *slots;
f64c0398 1911 enum kvm_mr_change change;
0f9bdef3
SC
1912 unsigned long npages;
1913 gfn_t base_gfn;
163da372
SC
1914 int as_id, id;
1915 int r;
6aa8b732 1916
a50d64d6
XG
1917 r = check_memory_region_flags(mem);
1918 if (r)
71a4c30b 1919 return r;
a50d64d6 1920
f481b069
PB
1921 as_id = mem->slot >> 16;
1922 id = (u16)mem->slot;
1923
6aa8b732 1924 /* General sanity checks */
6b285a55
SC
1925 if ((mem->memory_size & (PAGE_SIZE - 1)) ||
1926 (mem->memory_size != (unsigned long)mem->memory_size))
71a4c30b 1927 return -EINVAL;
6aa8b732 1928 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
71a4c30b 1929 return -EINVAL;
fa3d315a 1930 /* We can read the guest memory with __xxx_user() later on. */
09d952c9 1931 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
139bc8a6 1932 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
96d4f267 1933 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
09d952c9 1934 mem->memory_size))
71a4c30b 1935 return -EINVAL;
f481b069 1936 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
71a4c30b 1937 return -EINVAL;
6aa8b732 1938 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
71a4c30b 1939 return -EINVAL;
0f9bdef3
SC
1940 if ((mem->memory_size >> PAGE_SHIFT) > KVM_MEM_MAX_NR_PAGES)
1941 return -EINVAL;
6aa8b732 1942
44401a20 1943 slots = __kvm_memslots(kvm, as_id);
6aa8b732 1944
5c0b4f3d 1945 /*
7cd08553
SC
1946 * Note, the old memslot (and the pointer itself!) may be invalidated
1947 * and/or destroyed by kvm_set_memslot().
5c0b4f3d 1948 */
44401a20 1949 old = id_to_memslot(slots, id);
163da372 1950
47ea7d90 1951 if (!mem->memory_size) {
7cd08553 1952 if (!old || !old->npages)
47ea7d90 1953 return -EINVAL;
5c0b4f3d 1954
7cd08553 1955 if (WARN_ON_ONCE(kvm->nr_memslot_pages < old->npages))
47ea7d90 1956 return -EIO;
6aa8b732 1957
244893fa 1958 return kvm_set_memslot(kvm, old, NULL, KVM_MR_DELETE);
47ea7d90 1959 }
5c0b4f3d 1960
0f9bdef3
SC
1961 base_gfn = (mem->guest_phys_addr >> PAGE_SHIFT);
1962 npages = (mem->memory_size >> PAGE_SHIFT);
163da372 1963
7cd08553 1964 if (!old || !old->npages) {
5c0b4f3d 1965 change = KVM_MR_CREATE;
afa319a5
SC
1966
1967 /*
1968 * To simplify KVM internals, the total number of pages across
1969 * all memslots must fit in an unsigned long.
1970 */
0f9bdef3 1971 if ((kvm->nr_memslot_pages + npages) < kvm->nr_memslot_pages)
afa319a5 1972 return -EINVAL;
5c0b4f3d 1973 } else { /* Modify an existing slot. */
0f9bdef3
SC
1974 if ((mem->userspace_addr != old->userspace_addr) ||
1975 (npages != old->npages) ||
1976 ((mem->flags ^ old->flags) & KVM_MEM_READONLY))
71a4c30b 1977 return -EINVAL;
09170a49 1978
0f9bdef3 1979 if (base_gfn != old->base_gfn)
5c0b4f3d 1980 change = KVM_MR_MOVE;
0f9bdef3 1981 else if (mem->flags != old->flags)
5c0b4f3d
SC
1982 change = KVM_MR_FLAGS_ONLY;
1983 else /* Nothing to change. */
1984 return 0;
09170a49 1985 }
6aa8b732 1986
44401a20 1987 if ((change == KVM_MR_CREATE || change == KVM_MR_MOVE) &&
0f9bdef3 1988 kvm_check_memslot_overlap(slots, id, base_gfn, base_gfn + npages))
44401a20 1989 return -EEXIST;
6aa8b732 1990
244893fa
SC
1991 /* Allocate a slot that will persist in the memslot. */
1992 new = kzalloc(sizeof(*new), GFP_KERNEL_ACCOUNT);
1993 if (!new)
1994 return -ENOMEM;
3c9bd400 1995
244893fa
SC
1996 new->as_id = as_id;
1997 new->id = id;
1998 new->base_gfn = base_gfn;
1999 new->npages = npages;
2000 new->flags = mem->flags;
2001 new->userspace_addr = mem->userspace_addr;
6aa8b732 2002
244893fa 2003 r = kvm_set_memslot(kvm, old, new, change);
cf47f50b 2004 if (r)
244893fa 2005 kfree(new);
6aa8b732 2006 return r;
210c7c4d 2007}
f78e0e2e
SY
2008EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
2009
2010int kvm_set_memory_region(struct kvm *kvm,
09170a49 2011 const struct kvm_userspace_memory_region *mem)
f78e0e2e
SY
2012{
2013 int r;
2014
79fac95e 2015 mutex_lock(&kvm->slots_lock);
47ae31e2 2016 r = __kvm_set_memory_region(kvm, mem);
79fac95e 2017 mutex_unlock(&kvm->slots_lock);
f78e0e2e
SY
2018 return r;
2019}
210c7c4d
IE
2020EXPORT_SYMBOL_GPL(kvm_set_memory_region);
2021
7940876e
SH
2022static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
2023 struct kvm_userspace_memory_region *mem)
210c7c4d 2024{
f481b069 2025 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
e0d62c7f 2026 return -EINVAL;
09170a49 2027
47ae31e2 2028 return kvm_set_memory_region(kvm, mem);
6aa8b732
AK
2029}
2030
0dff0846 2031#ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
2a49f61d
SC
2032/**
2033 * kvm_get_dirty_log - get a snapshot of dirty pages
2034 * @kvm: pointer to kvm instance
2035 * @log: slot id and address to which we copy the log
2036 * @is_dirty: set to '1' if any dirty pages were found
2037 * @memslot: set to the associated memslot, always valid on success
2038 */
2039int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
2040 int *is_dirty, struct kvm_memory_slot **memslot)
6aa8b732 2041{
9f6b8029 2042 struct kvm_memslots *slots;
843574a3 2043 int i, as_id, id;
87bf6e7d 2044 unsigned long n;
6aa8b732
AK
2045 unsigned long any = 0;
2046
b2cc64c4
PX
2047 /* Dirty ring tracking is exclusive to dirty log tracking */
2048 if (kvm->dirty_ring_size)
2049 return -ENXIO;
2050
2a49f61d
SC
2051 *memslot = NULL;
2052 *is_dirty = 0;
2053
f481b069
PB
2054 as_id = log->slot >> 16;
2055 id = (u16)log->slot;
2056 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
843574a3 2057 return -EINVAL;
6aa8b732 2058
f481b069 2059 slots = __kvm_memslots(kvm, as_id);
2a49f61d 2060 *memslot = id_to_memslot(slots, id);
0577d1ab 2061 if (!(*memslot) || !(*memslot)->dirty_bitmap)
843574a3 2062 return -ENOENT;
6aa8b732 2063
2a49f61d
SC
2064 kvm_arch_sync_dirty_log(kvm, *memslot);
2065
2066 n = kvm_dirty_bitmap_bytes(*memslot);
6aa8b732 2067
cd1a4a98 2068 for (i = 0; !any && i < n/sizeof(long); ++i)
2a49f61d 2069 any = (*memslot)->dirty_bitmap[i];
6aa8b732 2070
2a49f61d 2071 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
843574a3 2072 return -EFAULT;
6aa8b732 2073
5bb064dc
ZX
2074 if (any)
2075 *is_dirty = 1;
843574a3 2076 return 0;
6aa8b732 2077}
2ba9f0d8 2078EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
6aa8b732 2079
0dff0846 2080#else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
ba0513b5 2081/**
b8b00220 2082 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
2a31b9db 2083 * and reenable dirty page tracking for the corresponding pages.
ba0513b5
MS
2084 * @kvm: pointer to kvm instance
2085 * @log: slot id and address to which we copy the log
ba0513b5
MS
2086 *
2087 * We need to keep it in mind that VCPU threads can write to the bitmap
2088 * concurrently. So, to avoid losing track of dirty pages we keep the
2089 * following order:
2090 *
2091 * 1. Take a snapshot of the bit and clear it if needed.
2092 * 2. Write protect the corresponding page.
2093 * 3. Copy the snapshot to the userspace.
2094 * 4. Upon return caller flushes TLB's if needed.
2095 *
2096 * Between 2 and 4, the guest may write to the page using the remaining TLB
2097 * entry. This is not a problem because the page is reported dirty using
2098 * the snapshot taken before and step 4 ensures that writes done after
2099 * exiting to userspace will be logged for the next call.
2100 *
2101 */
0dff0846 2102static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
ba0513b5 2103{
9f6b8029 2104 struct kvm_memslots *slots;
ba0513b5 2105 struct kvm_memory_slot *memslot;
58d6db34 2106 int i, as_id, id;
ba0513b5
MS
2107 unsigned long n;
2108 unsigned long *dirty_bitmap;
2109 unsigned long *dirty_bitmap_buffer;
0dff0846 2110 bool flush;
ba0513b5 2111
b2cc64c4
PX
2112 /* Dirty ring tracking is exclusive to dirty log tracking */
2113 if (kvm->dirty_ring_size)
2114 return -ENXIO;
2115
f481b069
PB
2116 as_id = log->slot >> 16;
2117 id = (u16)log->slot;
2118 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
58d6db34 2119 return -EINVAL;
ba0513b5 2120
f481b069
PB
2121 slots = __kvm_memslots(kvm, as_id);
2122 memslot = id_to_memslot(slots, id);
0577d1ab
SC
2123 if (!memslot || !memslot->dirty_bitmap)
2124 return -ENOENT;
ba0513b5
MS
2125
2126 dirty_bitmap = memslot->dirty_bitmap;
ba0513b5 2127
0dff0846
SC
2128 kvm_arch_sync_dirty_log(kvm, memslot);
2129
ba0513b5 2130 n = kvm_dirty_bitmap_bytes(memslot);
0dff0846 2131 flush = false;
2a31b9db
PB
2132 if (kvm->manual_dirty_log_protect) {
2133 /*
2134 * Unlike kvm_get_dirty_log, we always return false in *flush,
2135 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
2136 * is some code duplication between this function and
2137 * kvm_get_dirty_log, but hopefully all architecture
2138 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
2139 * can be eliminated.
2140 */
2141 dirty_bitmap_buffer = dirty_bitmap;
2142 } else {
2143 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2144 memset(dirty_bitmap_buffer, 0, n);
ba0513b5 2145
531810ca 2146 KVM_MMU_LOCK(kvm);
2a31b9db
PB
2147 for (i = 0; i < n / sizeof(long); i++) {
2148 unsigned long mask;
2149 gfn_t offset;
ba0513b5 2150
2a31b9db
PB
2151 if (!dirty_bitmap[i])
2152 continue;
2153
0dff0846 2154 flush = true;
2a31b9db
PB
2155 mask = xchg(&dirty_bitmap[i], 0);
2156 dirty_bitmap_buffer[i] = mask;
2157
a67794ca
LT
2158 offset = i * BITS_PER_LONG;
2159 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2160 offset, mask);
2a31b9db 2161 }
531810ca 2162 KVM_MMU_UNLOCK(kvm);
2a31b9db
PB
2163 }
2164
0dff0846
SC
2165 if (flush)
2166 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2167
2a31b9db
PB
2168 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
2169 return -EFAULT;
2170 return 0;
2171}
0dff0846
SC
2172
2173
2174/**
2175 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
2176 * @kvm: kvm instance
2177 * @log: slot id and address to which we copy the log
2178 *
2179 * Steps 1-4 below provide general overview of dirty page logging. See
2180 * kvm_get_dirty_log_protect() function description for additional details.
2181 *
2182 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
2183 * always flush the TLB (step 4) even if previous step failed and the dirty
2184 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
2185 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
2186 * writes will be marked dirty for next log read.
2187 *
2188 * 1. Take a snapshot of the bit and clear it if needed.
2189 * 2. Write protect the corresponding page.
2190 * 3. Copy the snapshot to the userspace.
2191 * 4. Flush TLB's if needed.
2192 */
2193static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2194 struct kvm_dirty_log *log)
2195{
2196 int r;
2197
2198 mutex_lock(&kvm->slots_lock);
2199
2200 r = kvm_get_dirty_log_protect(kvm, log);
2201
2202 mutex_unlock(&kvm->slots_lock);
2203 return r;
2204}
2a31b9db
PB
2205
2206/**
2207 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
2208 * and reenable dirty page tracking for the corresponding pages.
2209 * @kvm: pointer to kvm instance
2210 * @log: slot id and address from which to fetch the bitmap of dirty pages
2211 */
0dff0846
SC
2212static int kvm_clear_dirty_log_protect(struct kvm *kvm,
2213 struct kvm_clear_dirty_log *log)
2a31b9db
PB
2214{
2215 struct kvm_memslots *slots;
2216 struct kvm_memory_slot *memslot;
98938aa8 2217 int as_id, id;
2a31b9db 2218 gfn_t offset;
98938aa8 2219 unsigned long i, n;
2a31b9db
PB
2220 unsigned long *dirty_bitmap;
2221 unsigned long *dirty_bitmap_buffer;
0dff0846 2222 bool flush;
2a31b9db 2223
b2cc64c4
PX
2224 /* Dirty ring tracking is exclusive to dirty log tracking */
2225 if (kvm->dirty_ring_size)
2226 return -ENXIO;
2227
2a31b9db
PB
2228 as_id = log->slot >> 16;
2229 id = (u16)log->slot;
2230 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2231 return -EINVAL;
2232
76d58e0f 2233 if (log->first_page & 63)
2a31b9db
PB
2234 return -EINVAL;
2235
2236 slots = __kvm_memslots(kvm, as_id);
2237 memslot = id_to_memslot(slots, id);
0577d1ab
SC
2238 if (!memslot || !memslot->dirty_bitmap)
2239 return -ENOENT;
2a31b9db
PB
2240
2241 dirty_bitmap = memslot->dirty_bitmap;
2a31b9db 2242
4ddc9204 2243 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
98938aa8
TB
2244
2245 if (log->first_page > memslot->npages ||
76d58e0f
PB
2246 log->num_pages > memslot->npages - log->first_page ||
2247 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
2248 return -EINVAL;
98938aa8 2249
0dff0846
SC
2250 kvm_arch_sync_dirty_log(kvm, memslot);
2251
2252 flush = false;
2a31b9db
PB
2253 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2254 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2255 return -EFAULT;
ba0513b5 2256
531810ca 2257 KVM_MMU_LOCK(kvm);
53eac7a8
PX
2258 for (offset = log->first_page, i = offset / BITS_PER_LONG,
2259 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2a31b9db
PB
2260 i++, offset += BITS_PER_LONG) {
2261 unsigned long mask = *dirty_bitmap_buffer++;
2262 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2263 if (!mask)
ba0513b5
MS
2264 continue;
2265
2a31b9db 2266 mask &= atomic_long_fetch_andnot(mask, p);
ba0513b5 2267
2a31b9db
PB
2268 /*
2269 * mask contains the bits that really have been cleared. This
2270 * never includes any bits beyond the length of the memslot (if
2271 * the length is not aligned to 64 pages), therefore it is not
2272 * a problem if userspace sets them in log->dirty_bitmap.
2273 */
58d2930f 2274 if (mask) {
0dff0846 2275 flush = true;
58d2930f
TY
2276 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2277 offset, mask);
2278 }
ba0513b5 2279 }
531810ca 2280 KVM_MMU_UNLOCK(kvm);
2a31b9db 2281
0dff0846
SC
2282 if (flush)
2283 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2284
58d6db34 2285 return 0;
ba0513b5 2286}
0dff0846
SC
2287
2288static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2289 struct kvm_clear_dirty_log *log)
2290{
2291 int r;
2292
2293 mutex_lock(&kvm->slots_lock);
2294
2295 r = kvm_clear_dirty_log_protect(kvm, log);
2296
2297 mutex_unlock(&kvm->slots_lock);
2298 return r;
2299}
2300#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
ba0513b5 2301
49c7754c
GN
2302struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2303{
2304 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2305}
a1f4d395 2306EXPORT_SYMBOL_GPL(gfn_to_memslot);
6aa8b732 2307
8e73485c
PB
2308struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2309{
fe22ed82 2310 struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
a54d8066 2311 u64 gen = slots->generation;
fe22ed82 2312 struct kvm_memory_slot *slot;
fe22ed82 2313
a54d8066
MS
2314 /*
2315 * This also protects against using a memslot from a different address space,
2316 * since different address spaces have different generation numbers.
2317 */
2318 if (unlikely(gen != vcpu->last_used_slot_gen)) {
2319 vcpu->last_used_slot = NULL;
2320 vcpu->last_used_slot_gen = gen;
2321 }
2322
2323 slot = try_get_memslot(vcpu->last_used_slot, gfn);
fe22ed82
DM
2324 if (slot)
2325 return slot;
2326
2327 /*
2328 * Fall back to searching all memslots. We purposely use
2329 * search_memslots() instead of __gfn_to_memslot() to avoid
a54d8066 2330 * thrashing the VM-wide last_used_slot in kvm_memslots.
fe22ed82 2331 */
a54d8066 2332 slot = search_memslots(slots, gfn, false);
fe22ed82 2333 if (slot) {
a54d8066 2334 vcpu->last_used_slot = slot;
fe22ed82
DM
2335 return slot;
2336 }
2337
2338 return NULL;
8e73485c
PB
2339}
2340
33e94154 2341bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
e0d62c7f 2342{
bf3e05bc 2343 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
e0d62c7f 2344
c36b7150 2345 return kvm_is_visible_memslot(memslot);
e0d62c7f
IE
2346}
2347EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2348
995decb6
VK
2349bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2350{
2351 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2352
2353 return kvm_is_visible_memslot(memslot);
2354}
2355EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2356
f9b84e19 2357unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
8f0b1ab6
JR
2358{
2359 struct vm_area_struct *vma;
2360 unsigned long addr, size;
2361
2362 size = PAGE_SIZE;
2363
42cde48b 2364 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
8f0b1ab6
JR
2365 if (kvm_is_error_hva(addr))
2366 return PAGE_SIZE;
2367
d8ed45c5 2368 mmap_read_lock(current->mm);
8f0b1ab6
JR
2369 vma = find_vma(current->mm, addr);
2370 if (!vma)
2371 goto out;
2372
2373 size = vma_kernel_pagesize(vma);
2374
2375out:
d8ed45c5 2376 mmap_read_unlock(current->mm);
8f0b1ab6
JR
2377
2378 return size;
2379}
2380
8283e36a 2381static bool memslot_is_readonly(const struct kvm_memory_slot *slot)
4d8b81ab
XG
2382{
2383 return slot->flags & KVM_MEM_READONLY;
2384}
2385
8283e36a 2386static unsigned long __gfn_to_hva_many(const struct kvm_memory_slot *slot, gfn_t gfn,
4d8b81ab 2387 gfn_t *nr_pages, bool write)
539cb660 2388{
bc6678a3 2389 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
ca3a490c 2390 return KVM_HVA_ERR_BAD;
48987781 2391
4d8b81ab
XG
2392 if (memslot_is_readonly(slot) && write)
2393 return KVM_HVA_ERR_RO_BAD;
48987781
XG
2394
2395 if (nr_pages)
2396 *nr_pages = slot->npages - (gfn - slot->base_gfn);
2397
4d8b81ab 2398 return __gfn_to_hva_memslot(slot, gfn);
539cb660 2399}
48987781 2400
4d8b81ab
XG
2401static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2402 gfn_t *nr_pages)
2403{
2404 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
539cb660 2405}
48987781 2406
4d8b81ab 2407unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
7940876e 2408 gfn_t gfn)
4d8b81ab
XG
2409{
2410 return gfn_to_hva_many(slot, gfn, NULL);
2411}
2412EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2413
48987781
XG
2414unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2415{
49c7754c 2416 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
48987781 2417}
0d150298 2418EXPORT_SYMBOL_GPL(gfn_to_hva);
539cb660 2419
8e73485c
PB
2420unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2421{
2422 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2423}
2424EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2425
86ab8cff 2426/*
970c0d4b
WY
2427 * Return the hva of a @gfn and the R/W attribute if possible.
2428 *
2429 * @slot: the kvm_memory_slot which contains @gfn
2430 * @gfn: the gfn to be translated
2431 * @writable: used to return the read/write attribute of the @slot if the hva
2432 * is valid and @writable is not NULL
86ab8cff 2433 */
64d83126
CD
2434unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2435 gfn_t gfn, bool *writable)
86ab8cff 2436{
a2ac07fe
GN
2437 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2438
2439 if (!kvm_is_error_hva(hva) && writable)
ba6a3541
PB
2440 *writable = !memslot_is_readonly(slot);
2441
a2ac07fe 2442 return hva;
86ab8cff
XG
2443}
2444
64d83126
CD
2445unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2446{
2447 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2448
2449 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2450}
2451
8e73485c
PB
2452unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2453{
2454 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2455
2456 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2457}
2458
fafc3dba
HY
2459static inline int check_user_page_hwpoison(unsigned long addr)
2460{
0d731759 2461 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
fafc3dba 2462
0d731759 2463 rc = get_user_pages(addr, 1, flags, NULL, NULL);
fafc3dba
HY
2464 return rc == -EHWPOISON;
2465}
2466
2fc84311 2467/*
b9b33da2
PB
2468 * The fast path to get the writable pfn which will be stored in @pfn,
2469 * true indicates success, otherwise false is returned. It's also the
311497e0 2470 * only part that runs if we can in atomic context.
2fc84311 2471 */
b9b33da2
PB
2472static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2473 bool *writable, kvm_pfn_t *pfn)
954bbbc2 2474{
8d4e1288 2475 struct page *page[1];
954bbbc2 2476
12ce13fe
XG
2477 /*
2478 * Fast pin a writable pfn only if it is a write fault request
2479 * or the caller allows to map a writable pfn for a read fault
2480 * request.
2481 */
2482 if (!(write_fault || writable))
2483 return false;
612819c3 2484
dadbb612 2485 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2fc84311 2486 *pfn = page_to_pfn(page[0]);
612819c3 2487
2fc84311
XG
2488 if (writable)
2489 *writable = true;
2490 return true;
2491 }
af585b92 2492
2fc84311
XG
2493 return false;
2494}
612819c3 2495
2fc84311
XG
2496/*
2497 * The slow path to get the pfn of the specified host virtual address,
2498 * 1 indicates success, -errno is returned if error is detected.
2499 */
2500static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
ba049e93 2501 bool *writable, kvm_pfn_t *pfn)
2fc84311 2502{
ce53053c
AV
2503 unsigned int flags = FOLL_HWPOISON;
2504 struct page *page;
2fc84311 2505 int npages = 0;
612819c3 2506
2fc84311
XG
2507 might_sleep();
2508
2509 if (writable)
2510 *writable = write_fault;
2511
ce53053c
AV
2512 if (write_fault)
2513 flags |= FOLL_WRITE;
2514 if (async)
2515 flags |= FOLL_NOWAIT;
d4944b0e 2516
ce53053c 2517 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2fc84311
XG
2518 if (npages != 1)
2519 return npages;
2520
2521 /* map read fault as writable if possible */
12ce13fe 2522 if (unlikely(!write_fault) && writable) {
ce53053c 2523 struct page *wpage;
2fc84311 2524
dadbb612 2525 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2fc84311 2526 *writable = true;
ce53053c
AV
2527 put_page(page);
2528 page = wpage;
612819c3 2529 }
887c08ac 2530 }
ce53053c 2531 *pfn = page_to_pfn(page);
2fc84311
XG
2532 return npages;
2533}
539cb660 2534
4d8b81ab
XG
2535static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2536{
2537 if (unlikely(!(vma->vm_flags & VM_READ)))
2538 return false;
2e2e3738 2539
4d8b81ab
XG
2540 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2541 return false;
887c08ac 2542
4d8b81ab
XG
2543 return true;
2544}
bf998156 2545
f8be156b
NP
2546static int kvm_try_get_pfn(kvm_pfn_t pfn)
2547{
b14b2690
SC
2548 struct page *page = kvm_pfn_to_refcounted_page(pfn);
2549
2550 if (!page)
f8be156b 2551 return 1;
b14b2690
SC
2552
2553 return get_page_unless_zero(page);
f8be156b
NP
2554}
2555
92176a8e 2556static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1625566e
XT
2557 unsigned long addr, bool write_fault,
2558 bool *writable, kvm_pfn_t *p_pfn)
92176a8e 2559{
a9545779 2560 kvm_pfn_t pfn;
bd2fae8d
PB
2561 pte_t *ptep;
2562 spinlock_t *ptl;
add6a0cd
PB
2563 int r;
2564
9fd6dad1 2565 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
add6a0cd
PB
2566 if (r) {
2567 /*
2568 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2569 * not call the fault handler, so do it here.
2570 */
2571 bool unlocked = false;
64019a2e 2572 r = fixup_user_fault(current->mm, addr,
add6a0cd
PB
2573 (write_fault ? FAULT_FLAG_WRITE : 0),
2574 &unlocked);
a8387d0b
PB
2575 if (unlocked)
2576 return -EAGAIN;
add6a0cd
PB
2577 if (r)
2578 return r;
2579
9fd6dad1 2580 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
add6a0cd
PB
2581 if (r)
2582 return r;
bd2fae8d 2583 }
add6a0cd 2584
bd2fae8d
PB
2585 if (write_fault && !pte_write(*ptep)) {
2586 pfn = KVM_PFN_ERR_RO_FAULT;
2587 goto out;
add6a0cd
PB
2588 }
2589
a340b3e2 2590 if (writable)
bd2fae8d
PB
2591 *writable = pte_write(*ptep);
2592 pfn = pte_pfn(*ptep);
add6a0cd
PB
2593
2594 /*
2595 * Get a reference here because callers of *hva_to_pfn* and
2596 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2597 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
36c3ce6c 2598 * set, but the kvm_try_get_pfn/kvm_release_pfn_clean pair will
add6a0cd
PB
2599 * simply do nothing for reserved pfns.
2600 *
2601 * Whoever called remap_pfn_range is also going to call e.g.
2602 * unmap_mapping_range before the underlying pages are freed,
2603 * causing a call to our MMU notifier.
f8be156b
NP
2604 *
2605 * Certain IO or PFNMAP mappings can be backed with valid
2606 * struct pages, but be allocated without refcounting e.g.,
2607 * tail pages of non-compound higher order allocations, which
2608 * would then underflow the refcount when the caller does the
2609 * required put_page. Don't allow those pages here.
add6a0cd 2610 */
f8be156b
NP
2611 if (!kvm_try_get_pfn(pfn))
2612 r = -EFAULT;
add6a0cd 2613
bd2fae8d
PB
2614out:
2615 pte_unmap_unlock(ptep, ptl);
add6a0cd 2616 *p_pfn = pfn;
f8be156b
NP
2617
2618 return r;
92176a8e
PB
2619}
2620
12ce13fe
XG
2621/*
2622 * Pin guest page in memory and return its pfn.
2623 * @addr: host virtual address which maps memory to the guest
2624 * @atomic: whether this function can sleep
2625 * @async: whether this function need to wait IO complete if the
2626 * host page is not in the memory
2627 * @write_fault: whether we should get a writable host page
2628 * @writable: whether it allows to map a writable host page for !@write_fault
2629 *
2630 * The function will map a writable host page for these two cases:
2631 * 1): @write_fault = true
2632 * 2): @write_fault = false && @writable, @writable will tell the caller
2633 * whether the mapping is writable.
2634 */
982ed0de
DW
2635kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2636 bool write_fault, bool *writable)
2fc84311
XG
2637{
2638 struct vm_area_struct *vma;
943dfea8 2639 kvm_pfn_t pfn;
92176a8e 2640 int npages, r;
2e2e3738 2641
2fc84311
XG
2642 /* we can do it either atomically or asynchronously, not both */
2643 BUG_ON(atomic && async);
8d4e1288 2644
b9b33da2 2645 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2fc84311
XG
2646 return pfn;
2647
2648 if (atomic)
2649 return KVM_PFN_ERR_FAULT;
2650
2651 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2652 if (npages == 1)
2653 return pfn;
8d4e1288 2654
d8ed45c5 2655 mmap_read_lock(current->mm);
2fc84311
XG
2656 if (npages == -EHWPOISON ||
2657 (!async && check_user_page_hwpoison(addr))) {
2658 pfn = KVM_PFN_ERR_HWPOISON;
2659 goto exit;
2660 }
2661
a8387d0b 2662retry:
fc98c03b 2663 vma = vma_lookup(current->mm, addr);
2fc84311
XG
2664
2665 if (vma == NULL)
2666 pfn = KVM_PFN_ERR_FAULT;
92176a8e 2667 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1625566e 2668 r = hva_to_pfn_remapped(vma, addr, write_fault, writable, &pfn);
a8387d0b
PB
2669 if (r == -EAGAIN)
2670 goto retry;
92176a8e
PB
2671 if (r < 0)
2672 pfn = KVM_PFN_ERR_FAULT;
2fc84311 2673 } else {
4d8b81ab 2674 if (async && vma_is_valid(vma, write_fault))
2fc84311
XG
2675 *async = true;
2676 pfn = KVM_PFN_ERR_FAULT;
2677 }
2678exit:
d8ed45c5 2679 mmap_read_unlock(current->mm);
2e2e3738 2680 return pfn;
35149e21
AL
2681}
2682
8283e36a 2683kvm_pfn_t __gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn,
ba049e93 2684 bool atomic, bool *async, bool write_fault,
4a42d848 2685 bool *writable, hva_t *hva)
887c08ac 2686{
4d8b81ab
XG
2687 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2688
4a42d848
DS
2689 if (hva)
2690 *hva = addr;
2691
b2740d35
PB
2692 if (addr == KVM_HVA_ERR_RO_BAD) {
2693 if (writable)
2694 *writable = false;
4d8b81ab 2695 return KVM_PFN_ERR_RO_FAULT;
b2740d35 2696 }
4d8b81ab 2697
b2740d35
PB
2698 if (kvm_is_error_hva(addr)) {
2699 if (writable)
2700 *writable = false;
81c52c56 2701 return KVM_PFN_NOSLOT;
b2740d35 2702 }
4d8b81ab
XG
2703
2704 /* Do not map writable pfn in the readonly memslot. */
2705 if (writable && memslot_is_readonly(slot)) {
2706 *writable = false;
2707 writable = NULL;
2708 }
2709
2710 return hva_to_pfn(addr, atomic, async, write_fault,
2711 writable);
887c08ac 2712}
3520469d 2713EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
887c08ac 2714
ba049e93 2715kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
612819c3
MT
2716 bool *writable)
2717{
e37afc6e 2718 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
4a42d848 2719 write_fault, writable, NULL);
612819c3
MT
2720}
2721EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2722
8283e36a 2723kvm_pfn_t gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn)
506f0d6f 2724{
4a42d848 2725 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
506f0d6f 2726}
e37afc6e 2727EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
506f0d6f 2728
8283e36a 2729kvm_pfn_t gfn_to_pfn_memslot_atomic(const struct kvm_memory_slot *slot, gfn_t gfn)
506f0d6f 2730{
4a42d848 2731 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
506f0d6f 2732}
037d92dc 2733EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
506f0d6f 2734
ba049e93 2735kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
8e73485c
PB
2736{
2737 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2738}
2739EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2740
ba049e93 2741kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
e37afc6e
PB
2742{
2743 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2744}
2745EXPORT_SYMBOL_GPL(gfn_to_pfn);
2746
ba049e93 2747kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8e73485c
PB
2748{
2749 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2750}
2751EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2752
d9ef13c2
PB
2753int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2754 struct page **pages, int nr_pages)
48987781
XG
2755{
2756 unsigned long addr;
076b925d 2757 gfn_t entry = 0;
48987781 2758
d9ef13c2 2759 addr = gfn_to_hva_many(slot, gfn, &entry);
48987781
XG
2760 if (kvm_is_error_hva(addr))
2761 return -1;
2762
2763 if (entry < nr_pages)
2764 return 0;
2765
dadbb612 2766 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
48987781
XG
2767}
2768EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2769
b1624f99
SC
2770/*
2771 * Do not use this helper unless you are absolutely certain the gfn _must_ be
2772 * backed by 'struct page'. A valid example is if the backing memslot is
2773 * controlled by KVM. Note, if the returned page is valid, it's refcount has
2774 * been elevated by gfn_to_pfn().
2775 */
2776struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
a2766325 2777{
b14b2690 2778 struct page *page;
b1624f99
SC
2779 kvm_pfn_t pfn;
2780
2781 pfn = gfn_to_pfn(kvm, gfn);
2782
81c52c56 2783 if (is_error_noslot_pfn(pfn))
cb9aaa30 2784 return KVM_ERR_PTR_BAD_PAGE;
a2766325 2785
b14b2690
SC
2786 page = kvm_pfn_to_refcounted_page(pfn);
2787 if (!page)
6cede2e6 2788 return KVM_ERR_PTR_BAD_PAGE;
a2766325 2789
b14b2690 2790 return page;
a2766325 2791}
954bbbc2
AK
2792EXPORT_SYMBOL_GPL(gfn_to_page);
2793
357a18ad 2794void kvm_release_pfn(kvm_pfn_t pfn, bool dirty)
91724814 2795{
91724814
BO
2796 if (dirty)
2797 kvm_release_pfn_dirty(pfn);
2798 else
2799 kvm_release_pfn_clean(pfn);
2800}
2801
357a18ad 2802int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
e45adf66
KA
2803{
2804 kvm_pfn_t pfn;
2805 void *hva = NULL;
2806 struct page *page = KVM_UNMAPPED_PAGE;
2807
2808 if (!map)
2809 return -EINVAL;
2810
357a18ad 2811 pfn = gfn_to_pfn(vcpu->kvm, gfn);
e45adf66
KA
2812 if (is_error_noslot_pfn(pfn))
2813 return -EINVAL;
2814
2815 if (pfn_valid(pfn)) {
2816 page = pfn_to_page(pfn);
357a18ad 2817 hva = kmap(page);
d30b214d 2818#ifdef CONFIG_HAS_IOMEM
91724814 2819 } else {
357a18ad 2820 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
d30b214d 2821#endif
e45adf66
KA
2822 }
2823
2824 if (!hva)
2825 return -EFAULT;
2826
2827 map->page = page;
2828 map->hva = hva;
2829 map->pfn = pfn;
2830 map->gfn = gfn;
2831
2832 return 0;
2833}
e45adf66
KA
2834EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2835
357a18ad 2836void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
e45adf66
KA
2837{
2838 if (!map)
2839 return;
2840
2841 if (!map->hva)
2842 return;
2843
357a18ad
DW
2844 if (map->page != KVM_UNMAPPED_PAGE)
2845 kunmap(map->page);
eb1f2f38 2846#ifdef CONFIG_HAS_IOMEM
91724814 2847 else
357a18ad 2848 memunmap(map->hva);
eb1f2f38 2849#endif
e45adf66 2850
91724814 2851 if (dirty)
357a18ad 2852 kvm_vcpu_mark_page_dirty(vcpu, map->gfn);
91724814 2853
357a18ad 2854 kvm_release_pfn(map->pfn, dirty);
e45adf66
KA
2855
2856 map->hva = NULL;
2857 map->page = NULL;
2858}
2859EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2860
8e1c6914
SC
2861static bool kvm_is_ad_tracked_page(struct page *page)
2862{
2863 /*
2864 * Per page-flags.h, pages tagged PG_reserved "should in general not be
2865 * touched (e.g. set dirty) except by its owner".
2866 */
2867 return !PageReserved(page);
2868}
2869
2870static void kvm_set_page_dirty(struct page *page)
2871{
2872 if (kvm_is_ad_tracked_page(page))
2873 SetPageDirty(page);
2874}
2875
2876static void kvm_set_page_accessed(struct page *page)
2877{
2878 if (kvm_is_ad_tracked_page(page))
2879 mark_page_accessed(page);
2880}
2881
b4231d61
IE
2882void kvm_release_page_clean(struct page *page)
2883{
32cad84f
XG
2884 WARN_ON(is_error_page(page));
2885
8e1c6914
SC
2886 kvm_set_page_accessed(page);
2887 put_page(page);
b4231d61
IE
2888}
2889EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2890
ba049e93 2891void kvm_release_pfn_clean(kvm_pfn_t pfn)
35149e21 2892{
b14b2690
SC
2893 struct page *page;
2894
2895 if (is_error_noslot_pfn(pfn))
2896 return;
2897
2898 page = kvm_pfn_to_refcounted_page(pfn);
2899 if (!page)
2900 return;
2901
2902 kvm_release_page_clean(page);
35149e21
AL
2903}
2904EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2905
b4231d61 2906void kvm_release_page_dirty(struct page *page)
8a7ae055 2907{
a2766325
XG
2908 WARN_ON(is_error_page(page));
2909
8e1c6914
SC
2910 kvm_set_page_dirty(page);
2911 kvm_release_page_clean(page);
35149e21
AL
2912}
2913EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2914
f7a6509f 2915void kvm_release_pfn_dirty(kvm_pfn_t pfn)
35149e21 2916{
b14b2690
SC
2917 struct page *page;
2918
2919 if (is_error_noslot_pfn(pfn))
2920 return;
2921
2922 page = kvm_pfn_to_refcounted_page(pfn);
2923 if (!page)
2924 return;
2925
2926 kvm_release_page_dirty(page);
35149e21 2927}
f7a6509f 2928EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
35149e21 2929
8e1c6914
SC
2930/*
2931 * Note, checking for an error/noslot pfn is the caller's responsibility when
2932 * directly marking a page dirty/accessed. Unlike the "release" helpers, the
2933 * "set" helpers are not to be used when the pfn might point at garbage.
2934 */
ba049e93 2935void kvm_set_pfn_dirty(kvm_pfn_t pfn)
35149e21 2936{
8e1c6914
SC
2937 if (WARN_ON(is_error_noslot_pfn(pfn)))
2938 return;
2939
2940 if (pfn_valid(pfn))
2941 kvm_set_page_dirty(pfn_to_page(pfn));
8a7ae055 2942}
35149e21
AL
2943EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2944
ba049e93 2945void kvm_set_pfn_accessed(kvm_pfn_t pfn)
35149e21 2946{
8e1c6914
SC
2947 if (WARN_ON(is_error_noslot_pfn(pfn)))
2948 return;
2949
2950 if (pfn_valid(pfn))
2951 kvm_set_page_accessed(pfn_to_page(pfn));
35149e21
AL
2952}
2953EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2954
195aefde
IE
2955static int next_segment(unsigned long len, int offset)
2956{
2957 if (len > PAGE_SIZE - offset)
2958 return PAGE_SIZE - offset;
2959 else
2960 return len;
2961}
2962
8e73485c
PB
2963static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2964 void *data, int offset, int len)
195aefde 2965{
e0506bcb
IE
2966 int r;
2967 unsigned long addr;
195aefde 2968
8e73485c 2969 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
e0506bcb
IE
2970 if (kvm_is_error_hva(addr))
2971 return -EFAULT;
3180a7fc 2972 r = __copy_from_user(data, (void __user *)addr + offset, len);
e0506bcb 2973 if (r)
195aefde 2974 return -EFAULT;
195aefde
IE
2975 return 0;
2976}
8e73485c
PB
2977
2978int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2979 int len)
2980{
2981 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2982
2983 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2984}
195aefde
IE
2985EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2986
8e73485c
PB
2987int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2988 int offset, int len)
2989{
2990 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2991
2992 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2993}
2994EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2995
195aefde
IE
2996int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2997{
2998 gfn_t gfn = gpa >> PAGE_SHIFT;
2999 int seg;
3000 int offset = offset_in_page(gpa);
3001 int ret;
3002
3003 while ((seg = next_segment(len, offset)) != 0) {
3004 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
3005 if (ret < 0)
3006 return ret;
3007 offset = 0;
3008 len -= seg;
3009 data += seg;
3010 ++gfn;
3011 }
3012 return 0;
3013}
3014EXPORT_SYMBOL_GPL(kvm_read_guest);
3015
8e73485c 3016int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
7ec54588 3017{
7ec54588 3018 gfn_t gfn = gpa >> PAGE_SHIFT;
8e73485c 3019 int seg;
7ec54588 3020 int offset = offset_in_page(gpa);
8e73485c
PB
3021 int ret;
3022
3023 while ((seg = next_segment(len, offset)) != 0) {
3024 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
3025 if (ret < 0)
3026 return ret;
3027 offset = 0;
3028 len -= seg;
3029 data += seg;
3030 ++gfn;
3031 }
3032 return 0;
3033}
3034EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
7ec54588 3035
8e73485c
PB
3036static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
3037 void *data, int offset, unsigned long len)
3038{
3039 int r;
3040 unsigned long addr;
3041
3042 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
7ec54588
MT
3043 if (kvm_is_error_hva(addr))
3044 return -EFAULT;
0aac03f0 3045 pagefault_disable();
3180a7fc 3046 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
0aac03f0 3047 pagefault_enable();
7ec54588
MT
3048 if (r)
3049 return -EFAULT;
3050 return 0;
3051}
7ec54588 3052
8e73485c
PB
3053int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
3054 void *data, unsigned long len)
3055{
3056 gfn_t gfn = gpa >> PAGE_SHIFT;
3057 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3058 int offset = offset_in_page(gpa);
3059
3060 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
3061}
3062EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
3063
28bd726a
PX
3064static int __kvm_write_guest_page(struct kvm *kvm,
3065 struct kvm_memory_slot *memslot, gfn_t gfn,
8e73485c 3066 const void *data, int offset, int len)
195aefde 3067{
e0506bcb
IE
3068 int r;
3069 unsigned long addr;
195aefde 3070
251eb841 3071 addr = gfn_to_hva_memslot(memslot, gfn);
e0506bcb
IE
3072 if (kvm_is_error_hva(addr))
3073 return -EFAULT;
8b0cedff 3074 r = __copy_to_user((void __user *)addr + offset, data, len);
e0506bcb 3075 if (r)
195aefde 3076 return -EFAULT;
28bd726a 3077 mark_page_dirty_in_slot(kvm, memslot, gfn);
195aefde
IE
3078 return 0;
3079}
8e73485c
PB
3080
3081int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
3082 const void *data, int offset, int len)
3083{
3084 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
3085
28bd726a 3086 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
8e73485c 3087}
195aefde
IE
3088EXPORT_SYMBOL_GPL(kvm_write_guest_page);
3089
8e73485c
PB
3090int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
3091 const void *data, int offset, int len)
3092{
3093 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3094
28bd726a 3095 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
8e73485c
PB
3096}
3097EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
3098
195aefde
IE
3099int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
3100 unsigned long len)
3101{
3102 gfn_t gfn = gpa >> PAGE_SHIFT;
3103 int seg;
3104 int offset = offset_in_page(gpa);
3105 int ret;
3106
3107 while ((seg = next_segment(len, offset)) != 0) {
3108 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
3109 if (ret < 0)
3110 return ret;
3111 offset = 0;
3112 len -= seg;
3113 data += seg;
3114 ++gfn;
3115 }
3116 return 0;
3117}
ff651cb6 3118EXPORT_SYMBOL_GPL(kvm_write_guest);
195aefde 3119
8e73485c
PB
3120int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
3121 unsigned long len)
3122{
3123 gfn_t gfn = gpa >> PAGE_SHIFT;
3124 int seg;
3125 int offset = offset_in_page(gpa);
3126 int ret;
3127
3128 while ((seg = next_segment(len, offset)) != 0) {
3129 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
3130 if (ret < 0)
3131 return ret;
3132 offset = 0;
3133 len -= seg;
3134 data += seg;
3135 ++gfn;
3136 }
3137 return 0;
3138}
3139EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
3140
5a2d4365
PB
3141static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
3142 struct gfn_to_hva_cache *ghc,
3143 gpa_t gpa, unsigned long len)
49c7754c 3144{
49c7754c 3145 int offset = offset_in_page(gpa);
8f964525
AH
3146 gfn_t start_gfn = gpa >> PAGE_SHIFT;
3147 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
3148 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
3149 gfn_t nr_pages_avail;
49c7754c 3150
6ad1e29f 3151 /* Update ghc->generation before performing any error checks. */
49c7754c 3152 ghc->generation = slots->generation;
6ad1e29f
SC
3153
3154 if (start_gfn > end_gfn) {
3155 ghc->hva = KVM_HVA_ERR_BAD;
3156 return -EINVAL;
3157 }
f1b9dd5e
JM
3158
3159 /*
3160 * If the requested region crosses two memslots, we still
3161 * verify that the entire region is valid here.
3162 */
6ad1e29f 3163 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
f1b9dd5e
JM
3164 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
3165 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
3166 &nr_pages_avail);
3167 if (kvm_is_error_hva(ghc->hva))
6ad1e29f 3168 return -EFAULT;
f1b9dd5e
JM
3169 }
3170
3171 /* Use the slow path for cross page reads and writes. */
6ad1e29f 3172 if (nr_pages_needed == 1)
49c7754c 3173 ghc->hva += offset;
f1b9dd5e 3174 else
8f964525 3175 ghc->memslot = NULL;
f1b9dd5e 3176
6ad1e29f
SC
3177 ghc->gpa = gpa;
3178 ghc->len = len;
3179 return 0;
49c7754c 3180}
5a2d4365 3181
4e335d9e 3182int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
5a2d4365
PB
3183 gpa_t gpa, unsigned long len)
3184{
4e335d9e 3185 struct kvm_memslots *slots = kvm_memslots(kvm);
5a2d4365
PB
3186 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
3187}
4e335d9e 3188EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
49c7754c 3189
4e335d9e 3190int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
7a86dab8
JM
3191 void *data, unsigned int offset,
3192 unsigned long len)
49c7754c 3193{
4e335d9e 3194 struct kvm_memslots *slots = kvm_memslots(kvm);
49c7754c 3195 int r;
4ec6e863 3196 gpa_t gpa = ghc->gpa + offset;
49c7754c 3197
5f25e71e
PB
3198 if (WARN_ON_ONCE(len + offset > ghc->len))
3199 return -EINVAL;
8f964525 3200
dc9ce71e
SC
3201 if (slots->generation != ghc->generation) {
3202 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3203 return -EFAULT;
3204 }
8f964525 3205
49c7754c
GN
3206 if (kvm_is_error_hva(ghc->hva))
3207 return -EFAULT;
3208
fcfbc617
SC
3209 if (unlikely(!ghc->memslot))
3210 return kvm_write_guest(kvm, gpa, data, len);
3211
4ec6e863 3212 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
49c7754c
GN
3213 if (r)
3214 return -EFAULT;
28bd726a 3215 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
49c7754c
GN
3216
3217 return 0;
3218}
4e335d9e 3219EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
4ec6e863 3220
4e335d9e
PB
3221int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3222 void *data, unsigned long len)
4ec6e863 3223{
4e335d9e 3224 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
4ec6e863 3225}
4e335d9e 3226EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
49c7754c 3227
0958f0ce
VK
3228int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3229 void *data, unsigned int offset,
3230 unsigned long len)
e03b644f 3231{
4e335d9e 3232 struct kvm_memslots *slots = kvm_memslots(kvm);
e03b644f 3233 int r;
0958f0ce 3234 gpa_t gpa = ghc->gpa + offset;
e03b644f 3235
5f25e71e
PB
3236 if (WARN_ON_ONCE(len + offset > ghc->len))
3237 return -EINVAL;
8f964525 3238
dc9ce71e
SC
3239 if (slots->generation != ghc->generation) {
3240 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3241 return -EFAULT;
3242 }
8f964525 3243
e03b644f
GN
3244 if (kvm_is_error_hva(ghc->hva))
3245 return -EFAULT;
3246
fcfbc617 3247 if (unlikely(!ghc->memslot))
0958f0ce 3248 return kvm_read_guest(kvm, gpa, data, len);
fcfbc617 3249
0958f0ce 3250 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
e03b644f
GN
3251 if (r)
3252 return -EFAULT;
3253
3254 return 0;
3255}
0958f0ce
VK
3256EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3257
3258int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3259 void *data, unsigned long len)
3260{
3261 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3262}
4e335d9e 3263EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
e03b644f 3264
195aefde
IE
3265int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3266{
2f541442 3267 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
195aefde
IE
3268 gfn_t gfn = gpa >> PAGE_SHIFT;
3269 int seg;
3270 int offset = offset_in_page(gpa);
3271 int ret;
3272
bfda0e84 3273 while ((seg = next_segment(len, offset)) != 0) {
2f541442 3274 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
195aefde
IE
3275 if (ret < 0)
3276 return ret;
3277 offset = 0;
3278 len -= seg;
3279 ++gfn;
3280 }
3281 return 0;
3282}
3283EXPORT_SYMBOL_GPL(kvm_clear_guest);
3284
28bd726a 3285void mark_page_dirty_in_slot(struct kvm *kvm,
8283e36a 3286 const struct kvm_memory_slot *memslot,
28bd726a 3287 gfn_t gfn)
6aa8b732 3288{
2efd61a6
DW
3289 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
3290
e09fccb5 3291#ifdef CONFIG_HAVE_KVM_DIRTY_RING
2efd61a6
DW
3292 if (WARN_ON_ONCE(!vcpu) || WARN_ON_ONCE(vcpu->kvm != kvm))
3293 return;
e09fccb5 3294#endif
2efd61a6 3295
044c59c4 3296 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
7e9d619d 3297 unsigned long rel_gfn = gfn - memslot->base_gfn;
fb04a1ed 3298 u32 slot = (memslot->as_id << 16) | memslot->id;
6aa8b732 3299
fb04a1ed 3300 if (kvm->dirty_ring_size)
2efd61a6 3301 kvm_dirty_ring_push(&vcpu->dirty_ring,
fb04a1ed
PX
3302 slot, rel_gfn);
3303 else
3304 set_bit_le(rel_gfn, memslot->dirty_bitmap);
6aa8b732
AK
3305 }
3306}
a6a0b05d 3307EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
6aa8b732 3308
49c7754c
GN
3309void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3310{
3311 struct kvm_memory_slot *memslot;
3312
3313 memslot = gfn_to_memslot(kvm, gfn);
28bd726a 3314 mark_page_dirty_in_slot(kvm, memslot, gfn);
49c7754c 3315}
2ba9f0d8 3316EXPORT_SYMBOL_GPL(mark_page_dirty);
49c7754c 3317
8e73485c
PB
3318void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3319{
3320 struct kvm_memory_slot *memslot;
3321
3322 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
28bd726a 3323 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
8e73485c
PB
3324}
3325EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3326
20b7035c
JS
3327void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3328{
3329 if (!vcpu->sigset_active)
3330 return;
3331
3332 /*
3333 * This does a lockless modification of ->real_blocked, which is fine
3334 * because, only current can change ->real_blocked and all readers of
3335 * ->real_blocked don't care as long ->real_blocked is always a subset
3336 * of ->blocked.
3337 */
3338 sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
3339}
3340
3341void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3342{
3343 if (!vcpu->sigset_active)
3344 return;
3345
3346 sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
3347 sigemptyset(&current->real_blocked);
3348}
3349
aca6ff29
WL
3350static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3351{
dee339b5 3352 unsigned int old, val, grow, grow_start;
aca6ff29 3353
2cbd7824 3354 old = val = vcpu->halt_poll_ns;
dee339b5 3355 grow_start = READ_ONCE(halt_poll_ns_grow_start);
6b6de68c 3356 grow = READ_ONCE(halt_poll_ns_grow);
7fa08e71
NW
3357 if (!grow)
3358 goto out;
3359
dee339b5
NW
3360 val *= grow;
3361 if (val < grow_start)
3362 val = grow_start;
aca6ff29 3363
258785ef
DM
3364 if (val > vcpu->kvm->max_halt_poll_ns)
3365 val = vcpu->kvm->max_halt_poll_ns;
313f636d 3366
aca6ff29 3367 vcpu->halt_poll_ns = val;
7fa08e71 3368out:
2cbd7824 3369 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
aca6ff29
WL
3370}
3371
3372static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3373{
ae232ea4 3374 unsigned int old, val, shrink, grow_start;
aca6ff29 3375
2cbd7824 3376 old = val = vcpu->halt_poll_ns;
6b6de68c 3377 shrink = READ_ONCE(halt_poll_ns_shrink);
ae232ea4 3378 grow_start = READ_ONCE(halt_poll_ns_grow_start);
6b6de68c 3379 if (shrink == 0)
aca6ff29
WL
3380 val = 0;
3381 else
6b6de68c 3382 val /= shrink;
aca6ff29 3383
ae232ea4
SS
3384 if (val < grow_start)
3385 val = 0;
3386
aca6ff29 3387 vcpu->halt_poll_ns = val;
2cbd7824 3388 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
aca6ff29
WL
3389}
3390
f7819512
PB
3391static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3392{
50c28f21
JS
3393 int ret = -EINTR;
3394 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3395
f7819512
PB
3396 if (kvm_arch_vcpu_runnable(vcpu)) {
3397 kvm_make_request(KVM_REQ_UNHALT, vcpu);
50c28f21 3398 goto out;
f7819512
PB
3399 }
3400 if (kvm_cpu_has_pending_timer(vcpu))
50c28f21 3401 goto out;
f7819512 3402 if (signal_pending(current))
50c28f21 3403 goto out;
084071d5
MT
3404 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3405 goto out;
f7819512 3406
50c28f21
JS
3407 ret = 0;
3408out:
3409 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3410 return ret;
f7819512
PB
3411}
3412
fac42688
SC
3413/*
3414 * Block the vCPU until the vCPU is runnable, an event arrives, or a signal is
3415 * pending. This is mostly used when halting a vCPU, but may also be used
3416 * directly for other vCPU non-runnable states, e.g. x86's Wait-For-SIPI.
3417 */
3418bool kvm_vcpu_block(struct kvm_vcpu *vcpu)
cb953129 3419{
fac42688
SC
3420 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
3421 bool waited = false;
3422
c3858335
JZ
3423 vcpu->stat.generic.blocking = 1;
3424
18869f26 3425 preempt_disable();
fac42688 3426 kvm_arch_vcpu_blocking(vcpu);
fac42688 3427 prepare_to_rcuwait(wait);
18869f26
ML
3428 preempt_enable();
3429
fac42688
SC
3430 for (;;) {
3431 set_current_state(TASK_INTERRUPTIBLE);
3432
3433 if (kvm_vcpu_check_block(vcpu) < 0)
3434 break;
3435
3436 waited = true;
3437 schedule();
3438 }
fac42688 3439
18869f26
ML
3440 preempt_disable();
3441 finish_rcuwait(wait);
fac42688 3442 kvm_arch_vcpu_unblocking(vcpu);
18869f26 3443 preempt_enable();
fac42688 3444
c3858335
JZ
3445 vcpu->stat.generic.blocking = 0;
3446
fac42688
SC
3447 return waited;
3448}
3449
29e72893
SC
3450static inline void update_halt_poll_stats(struct kvm_vcpu *vcpu, ktime_t start,
3451 ktime_t end, bool success)
cb953129 3452{
30c94347 3453 struct kvm_vcpu_stat_generic *stats = &vcpu->stat.generic;
29e72893
SC
3454 u64 poll_ns = ktime_to_ns(ktime_sub(end, start));
3455
30c94347
SC
3456 ++vcpu->stat.generic.halt_attempted_poll;
3457
3458 if (success) {
3459 ++vcpu->stat.generic.halt_successful_poll;
3460
3461 if (!vcpu_valid_wakeup(vcpu))
3462 ++vcpu->stat.generic.halt_poll_invalid;
3463
3464 stats->halt_poll_success_ns += poll_ns;
3465 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_success_hist, poll_ns);
3466 } else {
3467 stats->halt_poll_fail_ns += poll_ns;
3468 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_fail_hist, poll_ns);
3469 }
cb953129
DM
3470}
3471
b6958ce4 3472/*
fac42688
SC
3473 * Emulate a vCPU halt condition, e.g. HLT on x86, WFI on arm, etc... If halt
3474 * polling is enabled, busy wait for a short time before blocking to avoid the
3475 * expensive block+unblock sequence if a wake event arrives soon after the vCPU
3476 * is halted.
b6958ce4 3477 */
91b99ea7 3478void kvm_vcpu_halt(struct kvm_vcpu *vcpu)
d3bef15f 3479{
6f390916 3480 bool halt_poll_allowed = !kvm_arch_no_poll(vcpu);
8df6a61c 3481 bool do_halt_poll = halt_poll_allowed && vcpu->halt_poll_ns;
cb953129 3482 ktime_t start, cur, poll_end;
f7819512 3483 bool waited = false;
91b99ea7 3484 u64 halt_ns;
07ab0f8d 3485
cb953129 3486 start = cur = poll_end = ktime_get();
8df6a61c 3487 if (do_halt_poll) {
109a9826 3488 ktime_t stop = ktime_add_ns(start, vcpu->halt_poll_ns);
f95ef0cd 3489
f7819512
PB
3490 do {
3491 /*
3492 * This sets KVM_REQ_UNHALT if an interrupt
3493 * arrives.
3494 */
30c94347 3495 if (kvm_vcpu_check_block(vcpu) < 0)
f7819512 3496 goto out;
74775654 3497 cpu_relax();
cb953129 3498 poll_end = cur = ktime_get();
6bd5b743 3499 } while (kvm_vcpu_can_poll(cur, stop));
f7819512 3500 }
e5c239cf 3501
fac42688 3502 waited = kvm_vcpu_block(vcpu);
8ccba534 3503
f7819512 3504 cur = ktime_get();
87bcc5fa
JZ
3505 if (waited) {
3506 vcpu->stat.generic.halt_wait_ns +=
3507 ktime_to_ns(cur) - ktime_to_ns(poll_end);
8ccba534
JZ
3508 KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
3509 ktime_to_ns(cur) - ktime_to_ns(poll_end));
87bcc5fa 3510 }
f7819512 3511out:
91b99ea7
SC
3512 /* The total time the vCPU was "halted", including polling time. */
3513 halt_ns = ktime_to_ns(cur) - ktime_to_ns(start);
aca6ff29 3514
29e72893
SC
3515 /*
3516 * Note, halt-polling is considered successful so long as the vCPU was
3517 * never actually scheduled out, i.e. even if the wake event arrived
3518 * after of the halt-polling loop itself, but before the full wait.
3519 */
8df6a61c 3520 if (do_halt_poll)
29e72893 3521 update_halt_poll_stats(vcpu, start, poll_end, !waited);
cb953129 3522
6f390916 3523 if (halt_poll_allowed) {
44551b2f 3524 if (!vcpu_valid_wakeup(vcpu)) {
aca6ff29 3525 shrink_halt_poll_ns(vcpu);
acd05785 3526 } else if (vcpu->kvm->max_halt_poll_ns) {
91b99ea7 3527 if (halt_ns <= vcpu->halt_poll_ns)
44551b2f
WL
3528 ;
3529 /* we had a long block, shrink polling */
acd05785 3530 else if (vcpu->halt_poll_ns &&
91b99ea7 3531 halt_ns > vcpu->kvm->max_halt_poll_ns)
44551b2f
WL
3532 shrink_halt_poll_ns(vcpu);
3533 /* we had a short halt and our poll time is too small */
acd05785 3534 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
91b99ea7 3535 halt_ns < vcpu->kvm->max_halt_poll_ns)
44551b2f
WL
3536 grow_halt_poll_ns(vcpu);
3537 } else {
3538 vcpu->halt_poll_ns = 0;
3539 }
3540 }
aca6ff29 3541
91b99ea7 3542 trace_kvm_vcpu_wakeup(halt_ns, waited, vcpu_valid_wakeup(vcpu));
b6958ce4 3543}
91b99ea7 3544EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
b6958ce4 3545
178f02ff 3546bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
b6d33834 3547{
d92a5d1c 3548 if (__kvm_vcpu_wake_up(vcpu)) {
d73eb57b 3549 WRITE_ONCE(vcpu->ready, true);
0193cc90 3550 ++vcpu->stat.generic.halt_wakeup;
178f02ff 3551 return true;
b6d33834
CD
3552 }
3553
178f02ff 3554 return false;
dd1a4cc1
RK
3555}
3556EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3557
0266c894 3558#ifndef CONFIG_S390
dd1a4cc1
RK
3559/*
3560 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3561 */
3562void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3563{
85b64045 3564 int me, cpu;
dd1a4cc1 3565
178f02ff
RK
3566 if (kvm_vcpu_wake_up(vcpu))
3567 return;
3568
aefdc2ed
PB
3569 me = get_cpu();
3570 /*
3571 * The only state change done outside the vcpu mutex is IN_GUEST_MODE
3572 * to EXITING_GUEST_MODE. Therefore the moderately expensive "should
3573 * kick" check does not need atomic operations if kvm_vcpu_kick is used
3574 * within the vCPU thread itself.
3575 */
3576 if (vcpu == __this_cpu_read(kvm_running_vcpu)) {
3577 if (vcpu->mode == IN_GUEST_MODE)
3578 WRITE_ONCE(vcpu->mode, EXITING_GUEST_MODE);
3579 goto out;
3580 }
3581
85b64045
SC
3582 /*
3583 * Note, the vCPU could get migrated to a different pCPU at any point
3584 * after kvm_arch_vcpu_should_kick(), which could result in sending an
3585 * IPI to the previous pCPU. But, that's ok because the purpose of the
3586 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the
3587 * vCPU also requires it to leave IN_GUEST_MODE.
3588 */
85b64045
SC
3589 if (kvm_arch_vcpu_should_kick(vcpu)) {
3590 cpu = READ_ONCE(vcpu->cpu);
3591 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
b6d33834 3592 smp_send_reschedule(cpu);
85b64045 3593 }
aefdc2ed 3594out:
b6d33834
CD
3595 put_cpu();
3596}
a20ed54d 3597EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
0266c894 3598#endif /* !CONFIG_S390 */
b6d33834 3599
fa93384f 3600int kvm_vcpu_yield_to(struct kvm_vcpu *target)
41628d33
KW
3601{
3602 struct pid *pid;
3603 struct task_struct *task = NULL;
fa93384f 3604 int ret = 0;
41628d33
KW
3605
3606 rcu_read_lock();
3607 pid = rcu_dereference(target->pid);
3608 if (pid)
27fbe64b 3609 task = get_pid_task(pid, PIDTYPE_PID);
41628d33
KW
3610 rcu_read_unlock();
3611 if (!task)
c45c528e 3612 return ret;
c45c528e 3613 ret = yield_to(task, 1);
41628d33 3614 put_task_struct(task);
c45c528e
R
3615
3616 return ret;
41628d33
KW
3617}
3618EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3619
06e48c51
R
3620/*
3621 * Helper that checks whether a VCPU is eligible for directed yield.
3622 * Most eligible candidate to yield is decided by following heuristics:
3623 *
3624 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3625 * (preempted lock holder), indicated by @in_spin_loop.
656012c7 3626 * Set at the beginning and cleared at the end of interception/PLE handler.
06e48c51
R
3627 *
3628 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3629 * chance last time (mostly it has become eligible now since we have probably
3630 * yielded to lockholder in last iteration. This is done by toggling
3631 * @dy_eligible each time a VCPU checked for eligibility.)
3632 *
3633 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3634 * to preempted lock-holder could result in wrong VCPU selection and CPU
3635 * burning. Giving priority for a potential lock-holder increases lock
3636 * progress.
3637 *
3638 * Since algorithm is based on heuristics, accessing another VCPU data without
3639 * locking does not harm. It may result in trying to yield to same VCPU, fail
3640 * and continue with next VCPU and so on.
3641 */
7940876e 3642static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
06e48c51 3643{
4a55dd72 3644#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
06e48c51
R
3645 bool eligible;
3646
3647 eligible = !vcpu->spin_loop.in_spin_loop ||
34656113 3648 vcpu->spin_loop.dy_eligible;
06e48c51
R
3649
3650 if (vcpu->spin_loop.in_spin_loop)
3651 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3652
3653 return eligible;
4a55dd72
SW
3654#else
3655 return true;
06e48c51 3656#endif
4a55dd72 3657}
c45c528e 3658
17e433b5
WL
3659/*
3660 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3661 * a vcpu_load/vcpu_put pair. However, for most architectures
3662 * kvm_arch_vcpu_runnable does not require vcpu_load.
3663 */
3664bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3665{
3666 return kvm_arch_vcpu_runnable(vcpu);
3667}
3668
3669static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3670{
3671 if (kvm_arch_dy_runnable(vcpu))
3672 return true;
3673
3674#ifdef CONFIG_KVM_ASYNC_PF
3675 if (!list_empty_careful(&vcpu->async_pf.done))
3676 return true;
3677#endif
3678
3679 return false;
3680}
3681
52acd22f
WL
3682bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3683{
3684 return false;
3685}
3686
199b5763 3687void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
d255f4f2 3688{
217ece61
RR
3689 struct kvm *kvm = me->kvm;
3690 struct kvm_vcpu *vcpu;
3691 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
46808a4c 3692 unsigned long i;
217ece61 3693 int yielded = 0;
c45c528e 3694 int try = 3;
217ece61 3695 int pass;
d255f4f2 3696
4c088493 3697 kvm_vcpu_set_in_spin_loop(me, true);
217ece61
RR
3698 /*
3699 * We boost the priority of a VCPU that is runnable but not
3700 * currently running, because it got preempted by something
3701 * else and called schedule in __vcpu_run. Hopefully that
3702 * VCPU is holding the lock that we need and will release it.
3703 * We approximate round-robin by starting at the last boosted VCPU.
3704 */
c45c528e 3705 for (pass = 0; pass < 2 && !yielded && try; pass++) {
217ece61 3706 kvm_for_each_vcpu(i, vcpu, kvm) {
5cfc2aab 3707 if (!pass && i <= last_boosted_vcpu) {
217ece61
RR
3708 i = last_boosted_vcpu;
3709 continue;
3710 } else if (pass && i > last_boosted_vcpu)
3711 break;
d73eb57b 3712 if (!READ_ONCE(vcpu->ready))
7bc7ae25 3713 continue;
217ece61
RR
3714 if (vcpu == me)
3715 continue;
d92a5d1c 3716 if (kvm_vcpu_is_blocking(vcpu) && !vcpu_dy_runnable(vcpu))
217ece61 3717 continue;
046ddeed 3718 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
52acd22f
WL
3719 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3720 !kvm_arch_vcpu_in_kernel(vcpu))
199b5763 3721 continue;
06e48c51
R
3722 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3723 continue;
c45c528e
R
3724
3725 yielded = kvm_vcpu_yield_to(vcpu);
3726 if (yielded > 0) {
217ece61 3727 kvm->last_boosted_vcpu = i;
217ece61 3728 break;
c45c528e
R
3729 } else if (yielded < 0) {
3730 try--;
3731 if (!try)
3732 break;
217ece61 3733 }
217ece61
RR
3734 }
3735 }
4c088493 3736 kvm_vcpu_set_in_spin_loop(me, false);
06e48c51
R
3737
3738 /* Ensure vcpu is not eligible during next spinloop */
3739 kvm_vcpu_set_dy_eligible(me, false);
d255f4f2
ZE
3740}
3741EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3742
fb04a1ed
PX
3743static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3744{
dc70ec21 3745#ifdef CONFIG_HAVE_KVM_DIRTY_RING
fb04a1ed
PX
3746 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3747 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3748 kvm->dirty_ring_size / PAGE_SIZE);
3749#else
3750 return false;
3751#endif
3752}
3753
1499fa80 3754static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
9a2bb7f4 3755{
11bac800 3756 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
9a2bb7f4
AK
3757 struct page *page;
3758
e4a533a4 3759 if (vmf->pgoff == 0)
039576c0 3760 page = virt_to_page(vcpu->run);
09566765 3761#ifdef CONFIG_X86
e4a533a4 3762 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
ad312c7c 3763 page = virt_to_page(vcpu->arch.pio_data);
5f94c174 3764#endif
4b4357e0 3765#ifdef CONFIG_KVM_MMIO
5f94c174
LV
3766 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3767 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
09566765 3768#endif
fb04a1ed
PX
3769 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3770 page = kvm_dirty_ring_get_page(
3771 &vcpu->dirty_ring,
3772 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
039576c0 3773 else
5b1c1493 3774 return kvm_arch_vcpu_fault(vcpu, vmf);
9a2bb7f4 3775 get_page(page);
e4a533a4
NP
3776 vmf->page = page;
3777 return 0;
9a2bb7f4
AK
3778}
3779
f0f37e2f 3780static const struct vm_operations_struct kvm_vcpu_vm_ops = {
e4a533a4 3781 .fault = kvm_vcpu_fault,
9a2bb7f4
AK
3782};
3783
3784static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3785{
fb04a1ed 3786 struct kvm_vcpu *vcpu = file->private_data;
11476d27 3787 unsigned long pages = vma_pages(vma);
fb04a1ed
PX
3788
3789 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3790 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3791 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3792 return -EINVAL;
3793
9a2bb7f4
AK
3794 vma->vm_ops = &kvm_vcpu_vm_ops;
3795 return 0;
3796}
3797
bccf2150
AK
3798static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3799{
3800 struct kvm_vcpu *vcpu = filp->private_data;
3801
66c0b394 3802 kvm_put_kvm(vcpu->kvm);
bccf2150
AK
3803 return 0;
3804}
3805
70375c2d 3806static const struct file_operations kvm_vcpu_fops = {
bccf2150
AK
3807 .release = kvm_vcpu_release,
3808 .unlocked_ioctl = kvm_vcpu_ioctl,
9a2bb7f4 3809 .mmap = kvm_vcpu_mmap,
6038f373 3810 .llseek = noop_llseek,
7ddfd3e0 3811 KVM_COMPAT(kvm_vcpu_compat_ioctl),
bccf2150
AK
3812};
3813
3814/*
3815 * Allocates an inode for the vcpu.
3816 */
3817static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3818{
e46b4692
MY
3819 char name[8 + 1 + ITOA_MAX_LEN + 1];
3820
3821 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3822 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
bccf2150
AK
3823}
3824
3e7093d0 3825static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
45b5939e 3826{
741cbbae 3827#ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
d56f5136 3828 struct dentry *debugfs_dentry;
45b5939e 3829 char dir_name[ITOA_MAX_LEN * 2];
45b5939e 3830
45b5939e 3831 if (!debugfs_initialized())
3e7093d0 3832 return;
45b5939e
LC
3833
3834 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
d56f5136
PB
3835 debugfs_dentry = debugfs_create_dir(dir_name,
3836 vcpu->kvm->debugfs_dentry);
45b5939e 3837
d56f5136 3838 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
741cbbae 3839#endif
45b5939e
LC
3840}
3841
c5ea7660
AK
3842/*
3843 * Creates some virtual cpus. Good luck creating more than one.
3844 */
73880c80 3845static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
c5ea7660
AK
3846{
3847 int r;
e09fefde 3848 struct kvm_vcpu *vcpu;
8bd826d6 3849 struct page *page;
c5ea7660 3850
a1c42dde 3851 if (id >= KVM_MAX_VCPU_IDS)
338c7dba
AH
3852 return -EINVAL;
3853
6c7caebc 3854 mutex_lock(&kvm->lock);
f502cc56 3855 if (kvm->created_vcpus >= kvm->max_vcpus) {
6c7caebc
PB
3856 mutex_unlock(&kvm->lock);
3857 return -EINVAL;
3858 }
3859
1d5e740d
ZG
3860 r = kvm_arch_vcpu_precreate(kvm, id);
3861 if (r) {
3862 mutex_unlock(&kvm->lock);
3863 return r;
3864 }
3865
6c7caebc
PB
3866 kvm->created_vcpus++;
3867 mutex_unlock(&kvm->lock);
3868
85f47930 3869 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
e529ef66
SC
3870 if (!vcpu) {
3871 r = -ENOMEM;
6c7caebc
PB
3872 goto vcpu_decrement;
3873 }
c5ea7660 3874
fcd97ad5 3875 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
93bb59ca 3876 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
8bd826d6
SC
3877 if (!page) {
3878 r = -ENOMEM;
e529ef66 3879 goto vcpu_free;
8bd826d6
SC
3880 }
3881 vcpu->run = page_address(page);
3882
3883 kvm_vcpu_init(vcpu, kvm, id);
e529ef66
SC
3884
3885 r = kvm_arch_vcpu_create(vcpu);
3886 if (r)
8bd826d6 3887 goto vcpu_free_run_page;
e529ef66 3888
fb04a1ed
PX
3889 if (kvm->dirty_ring_size) {
3890 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3891 id, kvm->dirty_ring_size);
3892 if (r)
3893 goto arch_vcpu_destroy;
3894 }
3895
11ec2804 3896 mutex_lock(&kvm->lock);
e09fefde
DH
3897 if (kvm_get_vcpu_by_id(kvm, id)) {
3898 r = -EEXIST;
3899 goto unlock_vcpu_destroy;
3900 }
73880c80 3901
8750e72a 3902 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
c5b07754
MZ
3903 r = xa_insert(&kvm->vcpu_array, vcpu->vcpu_idx, vcpu, GFP_KERNEL_ACCOUNT);
3904 BUG_ON(r == -EBUSY);
3905 if (r)
3906 goto unlock_vcpu_destroy;
c5ea7660 3907
ce55c049
JZ
3908 /* Fill the stats id string for the vcpu */
3909 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3910 task_pid_nr(current), id);
3911
fb3f0f51 3912 /* Now it's all set up, let userspace reach it */
66c0b394 3913 kvm_get_kvm(kvm);
bccf2150 3914 r = create_vcpu_fd(vcpu);
73880c80 3915 if (r < 0) {
c5b07754 3916 xa_erase(&kvm->vcpu_array, vcpu->vcpu_idx);
149487bd 3917 kvm_put_kvm_no_destroy(kvm);
d780592b 3918 goto unlock_vcpu_destroy;
73880c80
GN
3919 }
3920
dd489240 3921 /*
c5b07754
MZ
3922 * Pairs with smp_rmb() in kvm_get_vcpu. Store the vcpu
3923 * pointer before kvm->online_vcpu's incremented value.
dd489240 3924 */
73880c80
GN
3925 smp_wmb();
3926 atomic_inc(&kvm->online_vcpus);
3927
73880c80 3928 mutex_unlock(&kvm->lock);
42897d86 3929 kvm_arch_vcpu_postcreate(vcpu);
63d04348 3930 kvm_create_vcpu_debugfs(vcpu);
fb3f0f51 3931 return r;
39c3b86e 3932
d780592b 3933unlock_vcpu_destroy:
7d8fece6 3934 mutex_unlock(&kvm->lock);
fb04a1ed
PX
3935 kvm_dirty_ring_free(&vcpu->dirty_ring);
3936arch_vcpu_destroy:
d40ccc62 3937 kvm_arch_vcpu_destroy(vcpu);
8bd826d6
SC
3938vcpu_free_run_page:
3939 free_page((unsigned long)vcpu->run);
e529ef66
SC
3940vcpu_free:
3941 kmem_cache_free(kvm_vcpu_cache, vcpu);
6c7caebc
PB
3942vcpu_decrement:
3943 mutex_lock(&kvm->lock);
3944 kvm->created_vcpus--;
3945 mutex_unlock(&kvm->lock);
c5ea7660
AK
3946 return r;
3947}
3948
1961d276
AK
3949static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3950{
3951 if (sigset) {
3952 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3953 vcpu->sigset_active = 1;
3954 vcpu->sigset = *sigset;
3955 } else
3956 vcpu->sigset_active = 0;
3957 return 0;
3958}
3959
ce55c049
JZ
3960static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3961 size_t size, loff_t *offset)
3962{
3963 struct kvm_vcpu *vcpu = file->private_data;
3964
3965 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3966 &kvm_vcpu_stats_desc[0], &vcpu->stat,
3967 sizeof(vcpu->stat), user_buffer, size, offset);
3968}
3969
3970static const struct file_operations kvm_vcpu_stats_fops = {
3971 .read = kvm_vcpu_stats_read,
3972 .llseek = noop_llseek,
3973};
3974
3975static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3976{
3977 int fd;
3978 struct file *file;
3979 char name[15 + ITOA_MAX_LEN + 1];
3980
3981 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3982
3983 fd = get_unused_fd_flags(O_CLOEXEC);
3984 if (fd < 0)
3985 return fd;
3986
3987 file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3988 if (IS_ERR(file)) {
3989 put_unused_fd(fd);
3990 return PTR_ERR(file);
3991 }
3992 file->f_mode |= FMODE_PREAD;
3993 fd_install(fd, file);
3994
3995 return fd;
3996}
3997
bccf2150
AK
3998static long kvm_vcpu_ioctl(struct file *filp,
3999 unsigned int ioctl, unsigned long arg)
6aa8b732 4000{
bccf2150 4001 struct kvm_vcpu *vcpu = filp->private_data;
2f366987 4002 void __user *argp = (void __user *)arg;
313a3dc7 4003 int r;
fa3795a7
DH
4004 struct kvm_fpu *fpu = NULL;
4005 struct kvm_sregs *kvm_sregs = NULL;
6aa8b732 4006
f4d31653 4007 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
6d4e4c4f 4008 return -EIO;
2122ff5e 4009
2ea75be3
DM
4010 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
4011 return -EINVAL;
4012
2122ff5e 4013 /*
5cb0944c
PB
4014 * Some architectures have vcpu ioctls that are asynchronous to vcpu
4015 * execution; mutex_lock() would break them.
2122ff5e 4016 */
5cb0944c
PB
4017 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
4018 if (r != -ENOIOCTLCMD)
9fc77441 4019 return r;
2122ff5e 4020
ec7660cc
CD
4021 if (mutex_lock_killable(&vcpu->mutex))
4022 return -EINTR;
6aa8b732 4023 switch (ioctl) {
0e4524a5
CB
4024 case KVM_RUN: {
4025 struct pid *oldpid;
f0fe5108
AK
4026 r = -EINVAL;
4027 if (arg)
4028 goto out;
0e4524a5 4029 oldpid = rcu_access_pointer(vcpu->pid);
71dbc8a9 4030 if (unlikely(oldpid != task_pid(current))) {
7a72f7a1 4031 /* The thread running this VCPU changed. */
bd2a6394 4032 struct pid *newpid;
f95ef0cd 4033
bd2a6394
CD
4034 r = kvm_arch_vcpu_run_pid_change(vcpu);
4035 if (r)
4036 break;
4037
4038 newpid = get_task_pid(current, PIDTYPE_PID);
7a72f7a1
CB
4039 rcu_assign_pointer(vcpu->pid, newpid);
4040 if (oldpid)
4041 synchronize_rcu();
4042 put_pid(oldpid);
4043 }
1b94f6f8 4044 r = kvm_arch_vcpu_ioctl_run(vcpu);
64be5007 4045 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
6aa8b732 4046 break;
0e4524a5 4047 }
6aa8b732 4048 case KVM_GET_REGS: {
3e4bb3ac 4049 struct kvm_regs *kvm_regs;
6aa8b732 4050
3e4bb3ac 4051 r = -ENOMEM;
b12ce36a 4052 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3e4bb3ac 4053 if (!kvm_regs)
6aa8b732 4054 goto out;
3e4bb3ac
XZ
4055 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
4056 if (r)
4057 goto out_free1;
6aa8b732 4058 r = -EFAULT;
3e4bb3ac
XZ
4059 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
4060 goto out_free1;
6aa8b732 4061 r = 0;
3e4bb3ac
XZ
4062out_free1:
4063 kfree(kvm_regs);
6aa8b732
AK
4064 break;
4065 }
4066 case KVM_SET_REGS: {
3e4bb3ac 4067 struct kvm_regs *kvm_regs;
6aa8b732 4068
ff5c2c03
SL
4069 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
4070 if (IS_ERR(kvm_regs)) {
4071 r = PTR_ERR(kvm_regs);
6aa8b732 4072 goto out;
ff5c2c03 4073 }
3e4bb3ac 4074 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3e4bb3ac 4075 kfree(kvm_regs);
6aa8b732
AK
4076 break;
4077 }
4078 case KVM_GET_SREGS: {
b12ce36a
BG
4079 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
4080 GFP_KERNEL_ACCOUNT);
fa3795a7
DH
4081 r = -ENOMEM;
4082 if (!kvm_sregs)
4083 goto out;
4084 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
6aa8b732
AK
4085 if (r)
4086 goto out;
4087 r = -EFAULT;
fa3795a7 4088 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
6aa8b732
AK
4089 goto out;
4090 r = 0;
4091 break;
4092 }
4093 case KVM_SET_SREGS: {
ff5c2c03
SL
4094 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
4095 if (IS_ERR(kvm_sregs)) {
4096 r = PTR_ERR(kvm_sregs);
18595411 4097 kvm_sregs = NULL;
6aa8b732 4098 goto out;
ff5c2c03 4099 }
fa3795a7 4100 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
6aa8b732
AK
4101 break;
4102 }
62d9f0db
MT
4103 case KVM_GET_MP_STATE: {
4104 struct kvm_mp_state mp_state;
4105
4106 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
4107 if (r)
4108 goto out;
4109 r = -EFAULT;
893bdbf1 4110 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
62d9f0db
MT
4111 goto out;
4112 r = 0;
4113 break;
4114 }
4115 case KVM_SET_MP_STATE: {
4116 struct kvm_mp_state mp_state;
4117
4118 r = -EFAULT;
893bdbf1 4119 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
62d9f0db
MT
4120 goto out;
4121 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
62d9f0db
MT
4122 break;
4123 }
6aa8b732
AK
4124 case KVM_TRANSLATE: {
4125 struct kvm_translation tr;
4126
4127 r = -EFAULT;
893bdbf1 4128 if (copy_from_user(&tr, argp, sizeof(tr)))
6aa8b732 4129 goto out;
8b006791 4130 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
6aa8b732
AK
4131 if (r)
4132 goto out;
4133 r = -EFAULT;
893bdbf1 4134 if (copy_to_user(argp, &tr, sizeof(tr)))
6aa8b732
AK
4135 goto out;
4136 r = 0;
4137 break;
4138 }
d0bfb940
JK
4139 case KVM_SET_GUEST_DEBUG: {
4140 struct kvm_guest_debug dbg;
6aa8b732
AK
4141
4142 r = -EFAULT;
893bdbf1 4143 if (copy_from_user(&dbg, argp, sizeof(dbg)))
6aa8b732 4144 goto out;
d0bfb940 4145 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
6aa8b732
AK
4146 break;
4147 }
1961d276
AK
4148 case KVM_SET_SIGNAL_MASK: {
4149 struct kvm_signal_mask __user *sigmask_arg = argp;
4150 struct kvm_signal_mask kvm_sigmask;
4151 sigset_t sigset, *p;
4152
4153 p = NULL;
4154 if (argp) {
4155 r = -EFAULT;
4156 if (copy_from_user(&kvm_sigmask, argp,
893bdbf1 4157 sizeof(kvm_sigmask)))
1961d276
AK
4158 goto out;
4159 r = -EINVAL;
893bdbf1 4160 if (kvm_sigmask.len != sizeof(sigset))
1961d276
AK
4161 goto out;
4162 r = -EFAULT;
4163 if (copy_from_user(&sigset, sigmask_arg->sigset,
893bdbf1 4164 sizeof(sigset)))
1961d276
AK
4165 goto out;
4166 p = &sigset;
4167 }
376d41ff 4168 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
1961d276
AK
4169 break;
4170 }
b8836737 4171 case KVM_GET_FPU: {
b12ce36a 4172 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
fa3795a7
DH
4173 r = -ENOMEM;
4174 if (!fpu)
4175 goto out;
4176 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
b8836737
AK
4177 if (r)
4178 goto out;
4179 r = -EFAULT;
fa3795a7 4180 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
b8836737
AK
4181 goto out;
4182 r = 0;
4183 break;
4184 }
4185 case KVM_SET_FPU: {
ff5c2c03
SL
4186 fpu = memdup_user(argp, sizeof(*fpu));
4187 if (IS_ERR(fpu)) {
4188 r = PTR_ERR(fpu);
18595411 4189 fpu = NULL;
b8836737 4190 goto out;
ff5c2c03 4191 }
fa3795a7 4192 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
b8836737
AK
4193 break;
4194 }
ce55c049
JZ
4195 case KVM_GET_STATS_FD: {
4196 r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
4197 break;
4198 }
bccf2150 4199 default:
313a3dc7 4200 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
bccf2150
AK
4201 }
4202out:
ec7660cc 4203 mutex_unlock(&vcpu->mutex);
fa3795a7
DH
4204 kfree(fpu);
4205 kfree(kvm_sregs);
bccf2150
AK
4206 return r;
4207}
4208
de8e5d74 4209#ifdef CONFIG_KVM_COMPAT
1dda606c
AG
4210static long kvm_vcpu_compat_ioctl(struct file *filp,
4211 unsigned int ioctl, unsigned long arg)
4212{
4213 struct kvm_vcpu *vcpu = filp->private_data;
4214 void __user *argp = compat_ptr(arg);
4215 int r;
4216
f4d31653 4217 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
1dda606c
AG
4218 return -EIO;
4219
4220 switch (ioctl) {
4221 case KVM_SET_SIGNAL_MASK: {
4222 struct kvm_signal_mask __user *sigmask_arg = argp;
4223 struct kvm_signal_mask kvm_sigmask;
1dda606c
AG
4224 sigset_t sigset;
4225
4226 if (argp) {
4227 r = -EFAULT;
4228 if (copy_from_user(&kvm_sigmask, argp,
893bdbf1 4229 sizeof(kvm_sigmask)))
1dda606c
AG
4230 goto out;
4231 r = -EINVAL;
3968cf62 4232 if (kvm_sigmask.len != sizeof(compat_sigset_t))
1dda606c
AG
4233 goto out;
4234 r = -EFAULT;
1393b4aa
PB
4235 if (get_compat_sigset(&sigset,
4236 (compat_sigset_t __user *)sigmask_arg->sigset))
1dda606c 4237 goto out;
760a9a30
AC
4238 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
4239 } else
4240 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
1dda606c
AG
4241 break;
4242 }
4243 default:
4244 r = kvm_vcpu_ioctl(filp, ioctl, arg);
4245 }
4246
4247out:
4248 return r;
4249}
4250#endif
4251
a1cd3f08
CLG
4252static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
4253{
4254 struct kvm_device *dev = filp->private_data;
4255
4256 if (dev->ops->mmap)
4257 return dev->ops->mmap(dev, vma);
4258
4259 return -ENODEV;
4260}
4261
852b6d57
SW
4262static int kvm_device_ioctl_attr(struct kvm_device *dev,
4263 int (*accessor)(struct kvm_device *dev,
4264 struct kvm_device_attr *attr),
4265 unsigned long arg)
4266{
4267 struct kvm_device_attr attr;
4268
4269 if (!accessor)
4270 return -EPERM;
4271
4272 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4273 return -EFAULT;
4274
4275 return accessor(dev, &attr);
4276}
4277
4278static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
4279 unsigned long arg)
4280{
4281 struct kvm_device *dev = filp->private_data;
4282
f4d31653 4283 if (dev->kvm->mm != current->mm || dev->kvm->vm_dead)
ddba9180
SC
4284 return -EIO;
4285
852b6d57
SW
4286 switch (ioctl) {
4287 case KVM_SET_DEVICE_ATTR:
4288 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
4289 case KVM_GET_DEVICE_ATTR:
4290 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
4291 case KVM_HAS_DEVICE_ATTR:
4292 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
4293 default:
4294 if (dev->ops->ioctl)
4295 return dev->ops->ioctl(dev, ioctl, arg);
4296
4297 return -ENOTTY;
4298 }
4299}
4300
852b6d57
SW
4301static int kvm_device_release(struct inode *inode, struct file *filp)
4302{
4303 struct kvm_device *dev = filp->private_data;
4304 struct kvm *kvm = dev->kvm;
4305
2bde9b3e
CLG
4306 if (dev->ops->release) {
4307 mutex_lock(&kvm->lock);
4308 list_del(&dev->vm_node);
4309 dev->ops->release(dev);
4310 mutex_unlock(&kvm->lock);
4311 }
4312
852b6d57
SW
4313 kvm_put_kvm(kvm);
4314 return 0;
4315}
4316
4317static const struct file_operations kvm_device_fops = {
4318 .unlocked_ioctl = kvm_device_ioctl,
4319 .release = kvm_device_release,
7ddfd3e0 4320 KVM_COMPAT(kvm_device_ioctl),
a1cd3f08 4321 .mmap = kvm_device_mmap,
852b6d57
SW
4322};
4323
4324struct kvm_device *kvm_device_from_filp(struct file *filp)
4325{
4326 if (filp->f_op != &kvm_device_fops)
4327 return NULL;
4328
4329 return filp->private_data;
4330}
4331
8538cb22 4332static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
5df554ad 4333#ifdef CONFIG_KVM_MPIC
d60eacb0
WD
4334 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
4335 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
5975a2e0 4336#endif
d60eacb0
WD
4337};
4338
8538cb22 4339int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
d60eacb0
WD
4340{
4341 if (type >= ARRAY_SIZE(kvm_device_ops_table))
4342 return -ENOSPC;
4343
4344 if (kvm_device_ops_table[type] != NULL)
4345 return -EEXIST;
4346
4347 kvm_device_ops_table[type] = ops;
4348 return 0;
4349}
4350
571ee1b6
WL
4351void kvm_unregister_device_ops(u32 type)
4352{
4353 if (kvm_device_ops_table[type] != NULL)
4354 kvm_device_ops_table[type] = NULL;
4355}
4356
852b6d57
SW
4357static int kvm_ioctl_create_device(struct kvm *kvm,
4358 struct kvm_create_device *cd)
4359{
8538cb22 4360 const struct kvm_device_ops *ops = NULL;
852b6d57
SW
4361 struct kvm_device *dev;
4362 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
1d487e9b 4363 int type;
852b6d57
SW
4364 int ret;
4365
d60eacb0
WD
4366 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
4367 return -ENODEV;
4368
1d487e9b
PB
4369 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4370 ops = kvm_device_ops_table[type];
d60eacb0 4371 if (ops == NULL)
852b6d57 4372 return -ENODEV;
852b6d57
SW
4373
4374 if (test)
4375 return 0;
4376
b12ce36a 4377 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
852b6d57
SW
4378 if (!dev)
4379 return -ENOMEM;
4380
4381 dev->ops = ops;
4382 dev->kvm = kvm;
852b6d57 4383
a28ebea2 4384 mutex_lock(&kvm->lock);
1d487e9b 4385 ret = ops->create(dev, type);
852b6d57 4386 if (ret < 0) {
a28ebea2 4387 mutex_unlock(&kvm->lock);
852b6d57
SW
4388 kfree(dev);
4389 return ret;
4390 }
a28ebea2
CD
4391 list_add(&dev->vm_node, &kvm->devices);
4392 mutex_unlock(&kvm->lock);
852b6d57 4393
023e9fdd
CD
4394 if (ops->init)
4395 ops->init(dev);
4396
cfa39381 4397 kvm_get_kvm(kvm);
24009b05 4398 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
852b6d57 4399 if (ret < 0) {
149487bd 4400 kvm_put_kvm_no_destroy(kvm);
a28ebea2
CD
4401 mutex_lock(&kvm->lock);
4402 list_del(&dev->vm_node);
e8bc2427
AK
4403 if (ops->release)
4404 ops->release(dev);
a28ebea2 4405 mutex_unlock(&kvm->lock);
e8bc2427
AK
4406 if (ops->destroy)
4407 ops->destroy(dev);
852b6d57
SW
4408 return ret;
4409 }
4410
852b6d57
SW
4411 cd->fd = ret;
4412 return 0;
4413}
4414
92b591a4
AG
4415static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4416{
4417 switch (arg) {
4418 case KVM_CAP_USER_MEMORY:
4419 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4420 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
92b591a4
AG
4421 case KVM_CAP_INTERNAL_ERROR_DATA:
4422#ifdef CONFIG_HAVE_KVM_MSI
4423 case KVM_CAP_SIGNAL_MSI:
4424#endif
297e2105 4425#ifdef CONFIG_HAVE_KVM_IRQFD
dc9be0fa 4426 case KVM_CAP_IRQFD:
92b591a4
AG
4427 case KVM_CAP_IRQFD_RESAMPLE:
4428#endif
e9ea5069 4429 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
92b591a4 4430 case KVM_CAP_CHECK_EXTENSION_VM:
e5d83c74 4431 case KVM_CAP_ENABLE_CAP_VM:
acd05785 4432 case KVM_CAP_HALT_POLL:
92b591a4 4433 return 1;
4b4357e0 4434#ifdef CONFIG_KVM_MMIO
30422558
PB
4435 case KVM_CAP_COALESCED_MMIO:
4436 return KVM_COALESCED_MMIO_PAGE_OFFSET;
0804c849
PH
4437 case KVM_CAP_COALESCED_PIO:
4438 return 1;
30422558 4439#endif
3c9bd400
JZ
4440#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4441 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4442 return KVM_DIRTY_LOG_MANUAL_CAPS;
4443#endif
92b591a4
AG
4444#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4445 case KVM_CAP_IRQ_ROUTING:
4446 return KVM_MAX_IRQ_ROUTES;
f481b069
PB
4447#endif
4448#if KVM_ADDRESS_SPACE_NUM > 1
4449 case KVM_CAP_MULTI_ADDRESS_SPACE:
4450 return KVM_ADDRESS_SPACE_NUM;
92b591a4 4451#endif
c110ae57
PB
4452 case KVM_CAP_NR_MEMSLOTS:
4453 return KVM_USER_MEM_SLOTS;
fb04a1ed 4454 case KVM_CAP_DIRTY_LOG_RING:
dc70ec21 4455#ifdef CONFIG_HAVE_KVM_DIRTY_RING
fb04a1ed
PX
4456 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4457#else
4458 return 0;
4459#endif
ce55c049 4460 case KVM_CAP_BINARY_STATS_FD:
d495f942 4461 case KVM_CAP_SYSTEM_EVENT_DATA:
ce55c049 4462 return 1;
92b591a4
AG
4463 default:
4464 break;
4465 }
4466 return kvm_vm_ioctl_check_extension(kvm, arg);
4467}
4468
fb04a1ed
PX
4469static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4470{
4471 int r;
4472
4473 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4474 return -EINVAL;
4475
4476 /* the size should be power of 2 */
4477 if (!size || (size & (size - 1)))
4478 return -EINVAL;
4479
4480 /* Should be bigger to keep the reserved entries, or a page */
4481 if (size < kvm_dirty_ring_get_rsvd_entries() *
4482 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4483 return -EINVAL;
4484
4485 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4486 sizeof(struct kvm_dirty_gfn))
4487 return -E2BIG;
4488
4489 /* We only allow it to set once */
4490 if (kvm->dirty_ring_size)
4491 return -EINVAL;
4492
4493 mutex_lock(&kvm->lock);
4494
4495 if (kvm->created_vcpus) {
4496 /* We don't allow to change this value after vcpu created */
4497 r = -EINVAL;
4498 } else {
4499 kvm->dirty_ring_size = size;
4500 r = 0;
4501 }
4502
4503 mutex_unlock(&kvm->lock);
4504 return r;
4505}
4506
4507static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4508{
46808a4c 4509 unsigned long i;
fb04a1ed
PX
4510 struct kvm_vcpu *vcpu;
4511 int cleared = 0;
4512
4513 if (!kvm->dirty_ring_size)
4514 return -EINVAL;
4515
4516 mutex_lock(&kvm->slots_lock);
4517
4518 kvm_for_each_vcpu(i, vcpu, kvm)
4519 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4520
4521 mutex_unlock(&kvm->slots_lock);
4522
4523 if (cleared)
4524 kvm_flush_remote_tlbs(kvm);
4525
4526 return cleared;
4527}
4528
e5d83c74
PB
4529int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4530 struct kvm_enable_cap *cap)
4531{
4532 return -EINVAL;
4533}
4534
4535static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4536 struct kvm_enable_cap *cap)
4537{
4538 switch (cap->cap) {
2a31b9db 4539#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3c9bd400
JZ
4540 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4541 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4542
4543 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4544 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4545
4546 if (cap->flags || (cap->args[0] & ~allowed_options))
2a31b9db
PB
4547 return -EINVAL;
4548 kvm->manual_dirty_log_protect = cap->args[0];
4549 return 0;
3c9bd400 4550 }
2a31b9db 4551#endif
acd05785
DM
4552 case KVM_CAP_HALT_POLL: {
4553 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4554 return -EINVAL;
4555
4556 kvm->max_halt_poll_ns = cap->args[0];
4557 return 0;
4558 }
fb04a1ed
PX
4559 case KVM_CAP_DIRTY_LOG_RING:
4560 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
e5d83c74
PB
4561 default:
4562 return kvm_vm_ioctl_enable_cap(kvm, cap);
4563 }
4564}
4565
fcfe1bae
JZ
4566static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4567 size_t size, loff_t *offset)
4568{
4569 struct kvm *kvm = file->private_data;
4570
4571 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4572 &kvm_vm_stats_desc[0], &kvm->stat,
4573 sizeof(kvm->stat), user_buffer, size, offset);
4574}
4575
4576static const struct file_operations kvm_vm_stats_fops = {
4577 .read = kvm_vm_stats_read,
4578 .llseek = noop_llseek,
4579};
4580
4581static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4582{
4583 int fd;
4584 struct file *file;
4585
4586 fd = get_unused_fd_flags(O_CLOEXEC);
4587 if (fd < 0)
4588 return fd;
4589
4590 file = anon_inode_getfile("kvm-vm-stats",
4591 &kvm_vm_stats_fops, kvm, O_RDONLY);
4592 if (IS_ERR(file)) {
4593 put_unused_fd(fd);
4594 return PTR_ERR(file);
4595 }
4596 file->f_mode |= FMODE_PREAD;
4597 fd_install(fd, file);
4598
4599 return fd;
4600}
4601
bccf2150
AK
4602static long kvm_vm_ioctl(struct file *filp,
4603 unsigned int ioctl, unsigned long arg)
4604{
4605 struct kvm *kvm = filp->private_data;
4606 void __user *argp = (void __user *)arg;
1fe779f8 4607 int r;
bccf2150 4608
f4d31653 4609 if (kvm->mm != current->mm || kvm->vm_dead)
6d4e4c4f 4610 return -EIO;
bccf2150
AK
4611 switch (ioctl) {
4612 case KVM_CREATE_VCPU:
4613 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
bccf2150 4614 break;
e5d83c74
PB
4615 case KVM_ENABLE_CAP: {
4616 struct kvm_enable_cap cap;
4617
4618 r = -EFAULT;
4619 if (copy_from_user(&cap, argp, sizeof(cap)))
4620 goto out;
4621 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4622 break;
4623 }
6fc138d2
IE
4624 case KVM_SET_USER_MEMORY_REGION: {
4625 struct kvm_userspace_memory_region kvm_userspace_mem;
4626
4627 r = -EFAULT;
4628 if (copy_from_user(&kvm_userspace_mem, argp,
893bdbf1 4629 sizeof(kvm_userspace_mem)))
6fc138d2
IE
4630 goto out;
4631
47ae31e2 4632 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
6aa8b732
AK
4633 break;
4634 }
4635 case KVM_GET_DIRTY_LOG: {
4636 struct kvm_dirty_log log;
4637
4638 r = -EFAULT;
893bdbf1 4639 if (copy_from_user(&log, argp, sizeof(log)))
6aa8b732 4640 goto out;
2c6f5df9 4641 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
6aa8b732
AK
4642 break;
4643 }
2a31b9db
PB
4644#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4645 case KVM_CLEAR_DIRTY_LOG: {
4646 struct kvm_clear_dirty_log log;
4647
4648 r = -EFAULT;
4649 if (copy_from_user(&log, argp, sizeof(log)))
4650 goto out;
4651 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4652 break;
4653 }
4654#endif
4b4357e0 4655#ifdef CONFIG_KVM_MMIO
5f94c174
LV
4656 case KVM_REGISTER_COALESCED_MMIO: {
4657 struct kvm_coalesced_mmio_zone zone;
f95ef0cd 4658
5f94c174 4659 r = -EFAULT;
893bdbf1 4660 if (copy_from_user(&zone, argp, sizeof(zone)))
5f94c174 4661 goto out;
5f94c174 4662 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
5f94c174
LV
4663 break;
4664 }
4665 case KVM_UNREGISTER_COALESCED_MMIO: {
4666 struct kvm_coalesced_mmio_zone zone;
f95ef0cd 4667
5f94c174 4668 r = -EFAULT;
893bdbf1 4669 if (copy_from_user(&zone, argp, sizeof(zone)))
5f94c174 4670 goto out;
5f94c174 4671 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
5f94c174
LV
4672 break;
4673 }
4674#endif
721eecbf
GH
4675 case KVM_IRQFD: {
4676 struct kvm_irqfd data;
4677
4678 r = -EFAULT;
893bdbf1 4679 if (copy_from_user(&data, argp, sizeof(data)))
721eecbf 4680 goto out;
d4db2935 4681 r = kvm_irqfd(kvm, &data);
721eecbf
GH
4682 break;
4683 }
d34e6b17
GH
4684 case KVM_IOEVENTFD: {
4685 struct kvm_ioeventfd data;
4686
4687 r = -EFAULT;
893bdbf1 4688 if (copy_from_user(&data, argp, sizeof(data)))
d34e6b17
GH
4689 goto out;
4690 r = kvm_ioeventfd(kvm, &data);
4691 break;
4692 }
07975ad3
JK
4693#ifdef CONFIG_HAVE_KVM_MSI
4694 case KVM_SIGNAL_MSI: {
4695 struct kvm_msi msi;
4696
4697 r = -EFAULT;
893bdbf1 4698 if (copy_from_user(&msi, argp, sizeof(msi)))
07975ad3
JK
4699 goto out;
4700 r = kvm_send_userspace_msi(kvm, &msi);
4701 break;
4702 }
23d43cf9
CD
4703#endif
4704#ifdef __KVM_HAVE_IRQ_LINE
4705 case KVM_IRQ_LINE_STATUS:
4706 case KVM_IRQ_LINE: {
4707 struct kvm_irq_level irq_event;
4708
4709 r = -EFAULT;
893bdbf1 4710 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
23d43cf9
CD
4711 goto out;
4712
aa2fbe6d
YZ
4713 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4714 ioctl == KVM_IRQ_LINE_STATUS);
23d43cf9
CD
4715 if (r)
4716 goto out;
4717
4718 r = -EFAULT;
4719 if (ioctl == KVM_IRQ_LINE_STATUS) {
893bdbf1 4720 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
23d43cf9
CD
4721 goto out;
4722 }
4723
4724 r = 0;
4725 break;
4726 }
73880c80 4727#endif
aa8d5944
AG
4728#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4729 case KVM_SET_GSI_ROUTING: {
4730 struct kvm_irq_routing routing;
4731 struct kvm_irq_routing __user *urouting;
f8c1b85b 4732 struct kvm_irq_routing_entry *entries = NULL;
aa8d5944
AG
4733
4734 r = -EFAULT;
4735 if (copy_from_user(&routing, argp, sizeof(routing)))
4736 goto out;
4737 r = -EINVAL;
5c0aea0e
DH
4738 if (!kvm_arch_can_set_irq_routing(kvm))
4739 goto out;
caf1ff26 4740 if (routing.nr > KVM_MAX_IRQ_ROUTES)
aa8d5944
AG
4741 goto out;
4742 if (routing.flags)
4743 goto out;
f8c1b85b 4744 if (routing.nr) {
f8c1b85b 4745 urouting = argp;
7ec28e26
DE
4746 entries = vmemdup_user(urouting->entries,
4747 array_size(sizeof(*entries),
4748 routing.nr));
4749 if (IS_ERR(entries)) {
4750 r = PTR_ERR(entries);
4751 goto out;
4752 }
f8c1b85b 4753 }
aa8d5944
AG
4754 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4755 routing.flags);
7ec28e26 4756 kvfree(entries);
aa8d5944
AG
4757 break;
4758 }
4759#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
852b6d57
SW
4760 case KVM_CREATE_DEVICE: {
4761 struct kvm_create_device cd;
4762
4763 r = -EFAULT;
4764 if (copy_from_user(&cd, argp, sizeof(cd)))
4765 goto out;
4766
4767 r = kvm_ioctl_create_device(kvm, &cd);
4768 if (r)
4769 goto out;
4770
4771 r = -EFAULT;
4772 if (copy_to_user(argp, &cd, sizeof(cd)))
4773 goto out;
4774
4775 r = 0;
4776 break;
4777 }
92b591a4
AG
4778 case KVM_CHECK_EXTENSION:
4779 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4780 break;
fb04a1ed
PX
4781 case KVM_RESET_DIRTY_RINGS:
4782 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4783 break;
fcfe1bae
JZ
4784 case KVM_GET_STATS_FD:
4785 r = kvm_vm_ioctl_get_stats_fd(kvm);
4786 break;
f17abe9a 4787 default:
1fe779f8 4788 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
f17abe9a
AK
4789 }
4790out:
4791 return r;
4792}
4793
de8e5d74 4794#ifdef CONFIG_KVM_COMPAT
6ff5894c
AB
4795struct compat_kvm_dirty_log {
4796 __u32 slot;
4797 __u32 padding1;
4798 union {
4799 compat_uptr_t dirty_bitmap; /* one bit per page */
4800 __u64 padding2;
4801 };
4802};
4803
8750f9bb
PB
4804struct compat_kvm_clear_dirty_log {
4805 __u32 slot;
4806 __u32 num_pages;
4807 __u64 first_page;
4808 union {
4809 compat_uptr_t dirty_bitmap; /* one bit per page */
4810 __u64 padding2;
4811 };
4812};
4813
6ff5894c
AB
4814static long kvm_vm_compat_ioctl(struct file *filp,
4815 unsigned int ioctl, unsigned long arg)
4816{
4817 struct kvm *kvm = filp->private_data;
4818 int r;
4819
f4d31653 4820 if (kvm->mm != current->mm || kvm->vm_dead)
6ff5894c
AB
4821 return -EIO;
4822 switch (ioctl) {
8750f9bb
PB
4823#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4824 case KVM_CLEAR_DIRTY_LOG: {
4825 struct compat_kvm_clear_dirty_log compat_log;
4826 struct kvm_clear_dirty_log log;
4827
4828 if (copy_from_user(&compat_log, (void __user *)arg,
4829 sizeof(compat_log)))
4830 return -EFAULT;
4831 log.slot = compat_log.slot;
4832 log.num_pages = compat_log.num_pages;
4833 log.first_page = compat_log.first_page;
4834 log.padding2 = compat_log.padding2;
4835 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4836
4837 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4838 break;
4839 }
4840#endif
6ff5894c
AB
4841 case KVM_GET_DIRTY_LOG: {
4842 struct compat_kvm_dirty_log compat_log;
4843 struct kvm_dirty_log log;
4844
6ff5894c
AB
4845 if (copy_from_user(&compat_log, (void __user *)arg,
4846 sizeof(compat_log)))
f6a3b168 4847 return -EFAULT;
6ff5894c
AB
4848 log.slot = compat_log.slot;
4849 log.padding1 = compat_log.padding1;
4850 log.padding2 = compat_log.padding2;
4851 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4852
4853 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
6ff5894c
AB
4854 break;
4855 }
4856 default:
4857 r = kvm_vm_ioctl(filp, ioctl, arg);
4858 }
6ff5894c
AB
4859 return r;
4860}
4861#endif
4862
70375c2d 4863static const struct file_operations kvm_vm_fops = {
f17abe9a
AK
4864 .release = kvm_vm_release,
4865 .unlocked_ioctl = kvm_vm_ioctl,
6038f373 4866 .llseek = noop_llseek,
7ddfd3e0 4867 KVM_COMPAT(kvm_vm_compat_ioctl),
f17abe9a
AK
4868};
4869
54526d1f
NT
4870bool file_is_kvm(struct file *file)
4871{
4872 return file && file->f_op == &kvm_vm_fops;
4873}
4874EXPORT_SYMBOL_GPL(file_is_kvm);
4875
e08b9637 4876static int kvm_dev_ioctl_create_vm(unsigned long type)
f17abe9a 4877{
aac87636 4878 int r;
f17abe9a 4879 struct kvm *kvm;
506cfba9 4880 struct file *file;
f17abe9a 4881
e08b9637 4882 kvm = kvm_create_vm(type);
d6d28168
AK
4883 if (IS_ERR(kvm))
4884 return PTR_ERR(kvm);
4b4357e0 4885#ifdef CONFIG_KVM_MMIO
6ce5a090 4886 r = kvm_coalesced_mmio_init(kvm);
78588335
ME
4887 if (r < 0)
4888 goto put_kvm;
6ce5a090 4889#endif
506cfba9 4890 r = get_unused_fd_flags(O_CLOEXEC);
78588335
ME
4891 if (r < 0)
4892 goto put_kvm;
4893
fcfe1bae
JZ
4894 snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4895 "kvm-%d", task_pid_nr(current));
4896
506cfba9
AV
4897 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4898 if (IS_ERR(file)) {
4899 put_unused_fd(r);
78588335
ME
4900 r = PTR_ERR(file);
4901 goto put_kvm;
506cfba9 4902 }
536a6f88 4903
525df861
PB
4904 /*
4905 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4906 * already set, with ->release() being kvm_vm_release(). In error
4907 * cases it will be called by the final fput(file) and will take
4908 * care of doing kvm_put_kvm(kvm).
4909 */
536a6f88 4910 if (kvm_create_vm_debugfs(kvm, r) < 0) {
506cfba9
AV
4911 put_unused_fd(r);
4912 fput(file);
536a6f88
JF
4913 return -ENOMEM;
4914 }
286de8f6 4915 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
f17abe9a 4916
506cfba9 4917 fd_install(r, file);
aac87636 4918 return r;
78588335
ME
4919
4920put_kvm:
4921 kvm_put_kvm(kvm);
4922 return r;
f17abe9a
AK
4923}
4924
4925static long kvm_dev_ioctl(struct file *filp,
4926 unsigned int ioctl, unsigned long arg)
4927{
07c45a36 4928 long r = -EINVAL;
f17abe9a
AK
4929
4930 switch (ioctl) {
4931 case KVM_GET_API_VERSION:
f0fe5108
AK
4932 if (arg)
4933 goto out;
f17abe9a
AK
4934 r = KVM_API_VERSION;
4935 break;
4936 case KVM_CREATE_VM:
e08b9637 4937 r = kvm_dev_ioctl_create_vm(arg);
f17abe9a 4938 break;
018d00d2 4939 case KVM_CHECK_EXTENSION:
784aa3d7 4940 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
5d308f45 4941 break;
07c45a36 4942 case KVM_GET_VCPU_MMAP_SIZE:
07c45a36
AK
4943 if (arg)
4944 goto out;
adb1ff46
AK
4945 r = PAGE_SIZE; /* struct kvm_run */
4946#ifdef CONFIG_X86
4947 r += PAGE_SIZE; /* pio data page */
5f94c174 4948#endif
4b4357e0 4949#ifdef CONFIG_KVM_MMIO
5f94c174 4950 r += PAGE_SIZE; /* coalesced mmio ring page */
adb1ff46 4951#endif
07c45a36 4952 break;
d4c9ff2d
FEL
4953 case KVM_TRACE_ENABLE:
4954 case KVM_TRACE_PAUSE:
4955 case KVM_TRACE_DISABLE:
2023a29c 4956 r = -EOPNOTSUPP;
d4c9ff2d 4957 break;
6aa8b732 4958 default:
043405e1 4959 return kvm_arch_dev_ioctl(filp, ioctl, arg);
6aa8b732
AK
4960 }
4961out:
4962 return r;
4963}
4964
6aa8b732 4965static struct file_operations kvm_chardev_ops = {
6aa8b732 4966 .unlocked_ioctl = kvm_dev_ioctl,
6038f373 4967 .llseek = noop_llseek,
7ddfd3e0 4968 KVM_COMPAT(kvm_dev_ioctl),
6aa8b732
AK
4969};
4970
4971static struct miscdevice kvm_dev = {
bbe4432e 4972 KVM_MINOR,
6aa8b732
AK
4973 "kvm",
4974 &kvm_chardev_ops,
4975};
4976
75b7127c 4977static void hardware_enable_nolock(void *junk)
1b6c0168
AK
4978{
4979 int cpu = raw_smp_processor_id();
10474ae8 4980 int r;
1b6c0168 4981
7f59f492 4982 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
1b6c0168 4983 return;
10474ae8 4984
7f59f492 4985 cpumask_set_cpu(cpu, cpus_hardware_enabled);
10474ae8 4986
13a34e06 4987 r = kvm_arch_hardware_enable();
10474ae8
AG
4988
4989 if (r) {
4990 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4991 atomic_inc(&hardware_enable_failed);
1170adc6 4992 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
10474ae8 4993 }
1b6c0168
AK
4994}
4995
8c18b2d2 4996static int kvm_starting_cpu(unsigned int cpu)
75b7127c 4997{
4a937f96 4998 raw_spin_lock(&kvm_count_lock);
4fa92fb2
PB
4999 if (kvm_usage_count)
5000 hardware_enable_nolock(NULL);
4a937f96 5001 raw_spin_unlock(&kvm_count_lock);
8c18b2d2 5002 return 0;
75b7127c
TY
5003}
5004
5005static void hardware_disable_nolock(void *junk)
1b6c0168
AK
5006{
5007 int cpu = raw_smp_processor_id();
5008
7f59f492 5009 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
1b6c0168 5010 return;
7f59f492 5011 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
13a34e06 5012 kvm_arch_hardware_disable();
1b6c0168
AK
5013}
5014
8c18b2d2 5015static int kvm_dying_cpu(unsigned int cpu)
75b7127c 5016{
4a937f96 5017 raw_spin_lock(&kvm_count_lock);
4fa92fb2
PB
5018 if (kvm_usage_count)
5019 hardware_disable_nolock(NULL);
4a937f96 5020 raw_spin_unlock(&kvm_count_lock);
8c18b2d2 5021 return 0;
75b7127c
TY
5022}
5023
10474ae8
AG
5024static void hardware_disable_all_nolock(void)
5025{
5026 BUG_ON(!kvm_usage_count);
5027
5028 kvm_usage_count--;
5029 if (!kvm_usage_count)
75b7127c 5030 on_each_cpu(hardware_disable_nolock, NULL, 1);
10474ae8
AG
5031}
5032
5033static void hardware_disable_all(void)
5034{
4a937f96 5035 raw_spin_lock(&kvm_count_lock);
10474ae8 5036 hardware_disable_all_nolock();
4a937f96 5037 raw_spin_unlock(&kvm_count_lock);
10474ae8
AG
5038}
5039
5040static int hardware_enable_all(void)
5041{
5042 int r = 0;
5043
4a937f96 5044 raw_spin_lock(&kvm_count_lock);
10474ae8
AG
5045
5046 kvm_usage_count++;
5047 if (kvm_usage_count == 1) {
5048 atomic_set(&hardware_enable_failed, 0);
75b7127c 5049 on_each_cpu(hardware_enable_nolock, NULL, 1);
10474ae8
AG
5050
5051 if (atomic_read(&hardware_enable_failed)) {
5052 hardware_disable_all_nolock();
5053 r = -EBUSY;
5054 }
5055 }
5056
4a937f96 5057 raw_spin_unlock(&kvm_count_lock);
10474ae8
AG
5058
5059 return r;
5060}
5061
9a2b85c6 5062static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
d77c26fc 5063 void *v)
9a2b85c6 5064{
8e1c1815
SY
5065 /*
5066 * Some (well, at least mine) BIOSes hang on reboot if
5067 * in vmx root mode.
5068 *
5069 * And Intel TXT required VMX off for all cpu when system shutdown.
5070 */
1170adc6 5071 pr_info("kvm: exiting hardware virtualization\n");
8e1c1815 5072 kvm_rebooting = true;
75b7127c 5073 on_each_cpu(hardware_disable_nolock, NULL, 1);
9a2b85c6
RR
5074 return NOTIFY_OK;
5075}
5076
5077static struct notifier_block kvm_reboot_notifier = {
5078 .notifier_call = kvm_reboot,
5079 .priority = 0,
5080};
5081
e93f8a0f 5082static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
2eeb2e94
GH
5083{
5084 int i;
5085
5086 for (i = 0; i < bus->dev_count; i++) {
743eeb0b 5087 struct kvm_io_device *pos = bus->range[i].dev;
2eeb2e94
GH
5088
5089 kvm_iodevice_destructor(pos);
5090 }
e93f8a0f 5091 kfree(bus);
2eeb2e94
GH
5092}
5093
c21fbff1 5094static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
20e87b72 5095 const struct kvm_io_range *r2)
743eeb0b 5096{
8f4216c7
JW
5097 gpa_t addr1 = r1->addr;
5098 gpa_t addr2 = r2->addr;
5099
5100 if (addr1 < addr2)
743eeb0b 5101 return -1;
8f4216c7
JW
5102
5103 /* If r2->len == 0, match the exact address. If r2->len != 0,
5104 * accept any overlapping write. Any order is acceptable for
5105 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
5106 * we process all of them.
5107 */
5108 if (r2->len) {
5109 addr1 += r1->len;
5110 addr2 += r2->len;
5111 }
5112
5113 if (addr1 > addr2)
743eeb0b 5114 return 1;
8f4216c7 5115
743eeb0b
SL
5116 return 0;
5117}
5118
a343c9b7
PB
5119static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
5120{
c21fbff1 5121 return kvm_io_bus_cmp(p1, p2);
a343c9b7
PB
5122}
5123
39369f7a 5124static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
743eeb0b
SL
5125 gpa_t addr, int len)
5126{
5127 struct kvm_io_range *range, key;
5128 int off;
5129
5130 key = (struct kvm_io_range) {
5131 .addr = addr,
5132 .len = len,
5133 };
5134
5135 range = bsearch(&key, bus->range, bus->dev_count,
5136 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
5137 if (range == NULL)
5138 return -ENOENT;
5139
5140 off = range - bus->range;
5141
c21fbff1 5142 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
743eeb0b
SL
5143 off--;
5144
5145 return off;
5146}
5147
e32edf4f 5148static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
126a5af5
CH
5149 struct kvm_io_range *range, const void *val)
5150{
5151 int idx;
5152
5153 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5154 if (idx < 0)
5155 return -EOPNOTSUPP;
5156
5157 while (idx < bus->dev_count &&
c21fbff1 5158 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
e32edf4f 5159 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
126a5af5
CH
5160 range->len, val))
5161 return idx;
5162 idx++;
5163 }
5164
5165 return -EOPNOTSUPP;
5166}
5167
bda9020e 5168/* kvm_io_bus_write - called under kvm->slots_lock */
e32edf4f 5169int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
bda9020e 5170 int len, const void *val)
2eeb2e94 5171{
90d83dc3 5172 struct kvm_io_bus *bus;
743eeb0b 5173 struct kvm_io_range range;
126a5af5 5174 int r;
743eeb0b
SL
5175
5176 range = (struct kvm_io_range) {
5177 .addr = addr,
5178 .len = len,
5179 };
90d83dc3 5180
e32edf4f 5181 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
90db1043
DH
5182 if (!bus)
5183 return -ENOMEM;
e32edf4f 5184 r = __kvm_io_bus_write(vcpu, bus, &range, val);
126a5af5
CH
5185 return r < 0 ? r : 0;
5186}
a2420107 5187EXPORT_SYMBOL_GPL(kvm_io_bus_write);
126a5af5
CH
5188
5189/* kvm_io_bus_write_cookie - called under kvm->slots_lock */
e32edf4f
NN
5190int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
5191 gpa_t addr, int len, const void *val, long cookie)
126a5af5
CH
5192{
5193 struct kvm_io_bus *bus;
5194 struct kvm_io_range range;
5195
5196 range = (struct kvm_io_range) {
5197 .addr = addr,
5198 .len = len,
5199 };
5200
e32edf4f 5201 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
90db1043
DH
5202 if (!bus)
5203 return -ENOMEM;
126a5af5
CH
5204
5205 /* First try the device referenced by cookie. */
5206 if ((cookie >= 0) && (cookie < bus->dev_count) &&
c21fbff1 5207 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
e32edf4f 5208 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
126a5af5
CH
5209 val))
5210 return cookie;
5211
5212 /*
5213 * cookie contained garbage; fall back to search and return the
5214 * correct cookie value.
5215 */
e32edf4f 5216 return __kvm_io_bus_write(vcpu, bus, &range, val);
126a5af5
CH
5217}
5218
e32edf4f
NN
5219static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5220 struct kvm_io_range *range, void *val)
126a5af5
CH
5221{
5222 int idx;
5223
5224 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
743eeb0b
SL
5225 if (idx < 0)
5226 return -EOPNOTSUPP;
5227
5228 while (idx < bus->dev_count &&
c21fbff1 5229 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
e32edf4f 5230 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
126a5af5
CH
5231 range->len, val))
5232 return idx;
743eeb0b
SL
5233 idx++;
5234 }
5235
bda9020e
MT
5236 return -EOPNOTSUPP;
5237}
2eeb2e94 5238
bda9020e 5239/* kvm_io_bus_read - called under kvm->slots_lock */
e32edf4f 5240int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
e93f8a0f 5241 int len, void *val)
bda9020e 5242{
90d83dc3 5243 struct kvm_io_bus *bus;
743eeb0b 5244 struct kvm_io_range range;
126a5af5 5245 int r;
743eeb0b
SL
5246
5247 range = (struct kvm_io_range) {
5248 .addr = addr,
5249 .len = len,
5250 };
e93f8a0f 5251
e32edf4f 5252 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
90db1043
DH
5253 if (!bus)
5254 return -ENOMEM;
e32edf4f 5255 r = __kvm_io_bus_read(vcpu, bus, &range, val);
126a5af5
CH
5256 return r < 0 ? r : 0;
5257}
743eeb0b 5258
79fac95e 5259/* Caller must hold slots_lock. */
743eeb0b
SL
5260int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
5261 int len, struct kvm_io_device *dev)
6c474694 5262{
d4c67a7a 5263 int i;
e93f8a0f 5264 struct kvm_io_bus *new_bus, *bus;
d4c67a7a 5265 struct kvm_io_range range;
090b7aff 5266
4a12f951 5267 bus = kvm_get_bus(kvm, bus_idx);
90db1043
DH
5268 if (!bus)
5269 return -ENOMEM;
5270
6ea34c9b
AK
5271 /* exclude ioeventfd which is limited by maximum fd */
5272 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
090b7aff 5273 return -ENOSPC;
2eeb2e94 5274
90952cd3 5275 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
b12ce36a 5276 GFP_KERNEL_ACCOUNT);
e93f8a0f
MT
5277 if (!new_bus)
5278 return -ENOMEM;
d4c67a7a
GH
5279
5280 range = (struct kvm_io_range) {
5281 .addr = addr,
5282 .len = len,
5283 .dev = dev,
5284 };
5285
5286 for (i = 0; i < bus->dev_count; i++)
5287 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
5288 break;
5289
5290 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
5291 new_bus->dev_count++;
5292 new_bus->range[i] = range;
5293 memcpy(new_bus->range + i + 1, bus->range + i,
5294 (bus->dev_count - i) * sizeof(struct kvm_io_range));
e93f8a0f
MT
5295 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5296 synchronize_srcu_expedited(&kvm->srcu);
5297 kfree(bus);
090b7aff
GH
5298
5299 return 0;
5300}
5301
5d3c4c79
SC
5302int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5303 struct kvm_io_device *dev)
090b7aff 5304{
f6588660 5305 int i, j;
e93f8a0f 5306 struct kvm_io_bus *new_bus, *bus;
090b7aff 5307
7c896d37
SC
5308 lockdep_assert_held(&kvm->slots_lock);
5309
4a12f951 5310 bus = kvm_get_bus(kvm, bus_idx);
df630b8c 5311 if (!bus)
5d3c4c79 5312 return 0;
df630b8c 5313
7c896d37 5314 for (i = 0; i < bus->dev_count; i++) {
a1300716 5315 if (bus->range[i].dev == dev) {
090b7aff
GH
5316 break;
5317 }
7c896d37 5318 }
e93f8a0f 5319
90db1043 5320 if (i == bus->dev_count)
5d3c4c79 5321 return 0;
a1300716 5322
90952cd3 5323 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
b12ce36a 5324 GFP_KERNEL_ACCOUNT);
f6588660 5325 if (new_bus) {
871c433b 5326 memcpy(new_bus, bus, struct_size(bus, range, i));
f6588660
RK
5327 new_bus->dev_count--;
5328 memcpy(new_bus->range + i, bus->range + i + 1,
871c433b 5329 flex_array_size(new_bus, range, new_bus->dev_count - i));
2ee37574
SC
5330 }
5331
5332 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5333 synchronize_srcu_expedited(&kvm->srcu);
5334
5335 /* Destroy the old bus _after_ installing the (null) bus. */
5336 if (!new_bus) {
90db1043 5337 pr_err("kvm: failed to shrink bus, removing it completely\n");
f6588660
RK
5338 for (j = 0; j < bus->dev_count; j++) {
5339 if (j == i)
5340 continue;
5341 kvm_iodevice_destructor(bus->range[j].dev);
5342 }
90db1043 5343 }
a1300716 5344
e93f8a0f 5345 kfree(bus);
5d3c4c79 5346 return new_bus ? 0 : -ENOMEM;
2eeb2e94
GH
5347}
5348
8a39d006
AP
5349struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5350 gpa_t addr)
5351{
5352 struct kvm_io_bus *bus;
5353 int dev_idx, srcu_idx;
5354 struct kvm_io_device *iodev = NULL;
5355
5356 srcu_idx = srcu_read_lock(&kvm->srcu);
5357
5358 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
90db1043
DH
5359 if (!bus)
5360 goto out_unlock;
8a39d006
AP
5361
5362 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5363 if (dev_idx < 0)
5364 goto out_unlock;
5365
5366 iodev = bus->range[dev_idx].dev;
5367
5368out_unlock:
5369 srcu_read_unlock(&kvm->srcu, srcu_idx);
5370
5371 return iodev;
5372}
5373EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5374
536a6f88
JF
5375static int kvm_debugfs_open(struct inode *inode, struct file *file,
5376 int (*get)(void *, u64 *), int (*set)(void *, u64),
5377 const char *fmt)
5378{
5379 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5380 inode->i_private;
5381
605c7130
PX
5382 /*
5383 * The debugfs files are a reference to the kvm struct which
5384 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe
5385 * avoids the race between open and the removal of the debugfs directory.
536a6f88 5386 */
605c7130 5387 if (!kvm_get_kvm_safe(stat_data->kvm))
536a6f88
JF
5388 return -ENOENT;
5389
833b45de 5390 if (simple_attr_open(inode, file, get,
bc9e9e67 5391 kvm_stats_debugfs_mode(stat_data->desc) & 0222
09cbcef6
MP
5392 ? set : NULL,
5393 fmt)) {
536a6f88
JF
5394 kvm_put_kvm(stat_data->kvm);
5395 return -ENOMEM;
5396 }
5397
5398 return 0;
5399}
5400
5401static int kvm_debugfs_release(struct inode *inode, struct file *file)
5402{
5403 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5404 inode->i_private;
5405
5406 simple_attr_release(inode, file);
5407 kvm_put_kvm(stat_data->kvm);
5408
5409 return 0;
5410}
5411
09cbcef6 5412static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
536a6f88 5413{
bc9e9e67 5414 *val = *(u64 *)((void *)(&kvm->stat) + offset);
536a6f88 5415
09cbcef6
MP
5416 return 0;
5417}
5418
5419static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
5420{
bc9e9e67 5421 *(u64 *)((void *)(&kvm->stat) + offset) = 0;
536a6f88
JF
5422
5423 return 0;
5424}
5425
09cbcef6 5426static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
ce35ef27 5427{
46808a4c 5428 unsigned long i;
09cbcef6 5429 struct kvm_vcpu *vcpu;
ce35ef27 5430
09cbcef6 5431 *val = 0;
ce35ef27 5432
09cbcef6 5433 kvm_for_each_vcpu(i, vcpu, kvm)
bc9e9e67 5434 *val += *(u64 *)((void *)(&vcpu->stat) + offset);
ce35ef27
SJS
5435
5436 return 0;
5437}
5438
09cbcef6 5439static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
536a6f88 5440{
46808a4c 5441 unsigned long i;
09cbcef6 5442 struct kvm_vcpu *vcpu;
536a6f88 5443
09cbcef6 5444 kvm_for_each_vcpu(i, vcpu, kvm)
bc9e9e67 5445 *(u64 *)((void *)(&vcpu->stat) + offset) = 0;
09cbcef6
MP
5446
5447 return 0;
5448}
536a6f88 5449
09cbcef6 5450static int kvm_stat_data_get(void *data, u64 *val)
536a6f88 5451{
09cbcef6 5452 int r = -EFAULT;
536a6f88 5453 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
536a6f88 5454
bc9e9e67 5455 switch (stat_data->kind) {
09cbcef6
MP
5456 case KVM_STAT_VM:
5457 r = kvm_get_stat_per_vm(stat_data->kvm,
bc9e9e67 5458 stat_data->desc->desc.offset, val);
09cbcef6
MP
5459 break;
5460 case KVM_STAT_VCPU:
5461 r = kvm_get_stat_per_vcpu(stat_data->kvm,
bc9e9e67 5462 stat_data->desc->desc.offset, val);
09cbcef6
MP
5463 break;
5464 }
536a6f88 5465
09cbcef6 5466 return r;
536a6f88
JF
5467}
5468
09cbcef6 5469static int kvm_stat_data_clear(void *data, u64 val)
ce35ef27 5470{
09cbcef6 5471 int r = -EFAULT;
ce35ef27 5472 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
ce35ef27
SJS
5473
5474 if (val)
5475 return -EINVAL;
5476
bc9e9e67 5477 switch (stat_data->kind) {
09cbcef6
MP
5478 case KVM_STAT_VM:
5479 r = kvm_clear_stat_per_vm(stat_data->kvm,
bc9e9e67 5480 stat_data->desc->desc.offset);
09cbcef6
MP
5481 break;
5482 case KVM_STAT_VCPU:
5483 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
bc9e9e67 5484 stat_data->desc->desc.offset);
09cbcef6
MP
5485 break;
5486 }
ce35ef27 5487
09cbcef6 5488 return r;
ce35ef27
SJS
5489}
5490
09cbcef6 5491static int kvm_stat_data_open(struct inode *inode, struct file *file)
536a6f88
JF
5492{
5493 __simple_attr_check_format("%llu\n", 0ull);
09cbcef6
MP
5494 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5495 kvm_stat_data_clear, "%llu\n");
536a6f88
JF
5496}
5497
09cbcef6
MP
5498static const struct file_operations stat_fops_per_vm = {
5499 .owner = THIS_MODULE,
5500 .open = kvm_stat_data_open,
536a6f88 5501 .release = kvm_debugfs_release,
09cbcef6
MP
5502 .read = simple_attr_read,
5503 .write = simple_attr_write,
5504 .llseek = no_llseek,
536a6f88
JF
5505};
5506
8b88b099 5507static int vm_stat_get(void *_offset, u64 *val)
ba1389b7
AK
5508{
5509 unsigned offset = (long)_offset;
ba1389b7 5510 struct kvm *kvm;
536a6f88 5511 u64 tmp_val;
ba1389b7 5512
8b88b099 5513 *val = 0;
0d9ce162 5514 mutex_lock(&kvm_lock);
536a6f88 5515 list_for_each_entry(kvm, &vm_list, vm_list) {
09cbcef6 5516 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
536a6f88
JF
5517 *val += tmp_val;
5518 }
0d9ce162 5519 mutex_unlock(&kvm_lock);
8b88b099 5520 return 0;
ba1389b7
AK
5521}
5522
ce35ef27
SJS
5523static int vm_stat_clear(void *_offset, u64 val)
5524{
5525 unsigned offset = (long)_offset;
5526 struct kvm *kvm;
ce35ef27
SJS
5527
5528 if (val)
5529 return -EINVAL;
5530
0d9ce162 5531 mutex_lock(&kvm_lock);
ce35ef27 5532 list_for_each_entry(kvm, &vm_list, vm_list) {
09cbcef6 5533 kvm_clear_stat_per_vm(kvm, offset);
ce35ef27 5534 }
0d9ce162 5535 mutex_unlock(&kvm_lock);
ce35ef27
SJS
5536
5537 return 0;
5538}
5539
5540DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
bc9e9e67 5541DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
ba1389b7 5542
8b88b099 5543static int vcpu_stat_get(void *_offset, u64 *val)
1165f5fe
AK
5544{
5545 unsigned offset = (long)_offset;
1165f5fe 5546 struct kvm *kvm;
536a6f88 5547 u64 tmp_val;
1165f5fe 5548
8b88b099 5549 *val = 0;
0d9ce162 5550 mutex_lock(&kvm_lock);
536a6f88 5551 list_for_each_entry(kvm, &vm_list, vm_list) {
09cbcef6 5552 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
536a6f88
JF
5553 *val += tmp_val;
5554 }
0d9ce162 5555 mutex_unlock(&kvm_lock);
8b88b099 5556 return 0;
1165f5fe
AK
5557}
5558
ce35ef27
SJS
5559static int vcpu_stat_clear(void *_offset, u64 val)
5560{
5561 unsigned offset = (long)_offset;
5562 struct kvm *kvm;
ce35ef27
SJS
5563
5564 if (val)
5565 return -EINVAL;
5566
0d9ce162 5567 mutex_lock(&kvm_lock);
ce35ef27 5568 list_for_each_entry(kvm, &vm_list, vm_list) {
09cbcef6 5569 kvm_clear_stat_per_vcpu(kvm, offset);
ce35ef27 5570 }
0d9ce162 5571 mutex_unlock(&kvm_lock);
ce35ef27
SJS
5572
5573 return 0;
5574}
5575
5576DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5577 "%llu\n");
bc9e9e67 5578DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
1165f5fe 5579
286de8f6
CI
5580static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5581{
5582 struct kobj_uevent_env *env;
286de8f6
CI
5583 unsigned long long created, active;
5584
5585 if (!kvm_dev.this_device || !kvm)
5586 return;
5587
0d9ce162 5588 mutex_lock(&kvm_lock);
286de8f6
CI
5589 if (type == KVM_EVENT_CREATE_VM) {
5590 kvm_createvm_count++;
5591 kvm_active_vms++;
5592 } else if (type == KVM_EVENT_DESTROY_VM) {
5593 kvm_active_vms--;
5594 }
5595 created = kvm_createvm_count;
5596 active = kvm_active_vms;
0d9ce162 5597 mutex_unlock(&kvm_lock);
286de8f6 5598
b12ce36a 5599 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
286de8f6
CI
5600 if (!env)
5601 return;
5602
5603 add_uevent_var(env, "CREATED=%llu", created);
5604 add_uevent_var(env, "COUNT=%llu", active);
5605
fdeaf7e3 5606 if (type == KVM_EVENT_CREATE_VM) {
286de8f6 5607 add_uevent_var(env, "EVENT=create");
fdeaf7e3
CI
5608 kvm->userspace_pid = task_pid_nr(current);
5609 } else if (type == KVM_EVENT_DESTROY_VM) {
286de8f6 5610 add_uevent_var(env, "EVENT=destroy");
fdeaf7e3
CI
5611 }
5612 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
286de8f6 5613
a44a4cc1 5614 if (!IS_ERR(kvm->debugfs_dentry)) {
b12ce36a 5615 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
fdeaf7e3
CI
5616
5617 if (p) {
5618 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5619 if (!IS_ERR(tmp))
5620 add_uevent_var(env, "STATS_PATH=%s", tmp);
5621 kfree(p);
286de8f6
CI
5622 }
5623 }
5624 /* no need for checks, since we are adding at most only 5 keys */
5625 env->envp[env->envp_idx++] = NULL;
5626 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5627 kfree(env);
286de8f6
CI
5628}
5629
929f45e3 5630static void kvm_init_debug(void)
6aa8b732 5631{
bc9e9e67
JZ
5632 const struct file_operations *fops;
5633 const struct _kvm_stats_desc *pdesc;
5634 int i;
6aa8b732 5635
76f7c879 5636 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4f69b680 5637
bc9e9e67
JZ
5638 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
5639 pdesc = &kvm_vm_stats_desc[i];
5640 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5641 fops = &vm_stat_fops;
5642 else
5643 fops = &vm_stat_readonly_fops;
5644 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5645 kvm_debugfs_dir,
5646 (void *)(long)pdesc->desc.offset, fops);
5647 }
5648
5649 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
5650 pdesc = &kvm_vcpu_stats_desc[i];
5651 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5652 fops = &vcpu_stat_fops;
5653 else
5654 fops = &vcpu_stat_readonly_fops;
5655 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5656 kvm_debugfs_dir,
5657 (void *)(long)pdesc->desc.offset, fops);
4f69b680 5658 }
6aa8b732
AK
5659}
5660
fb3600cc 5661static int kvm_suspend(void)
59ae6c6b 5662{
10474ae8 5663 if (kvm_usage_count)
75b7127c 5664 hardware_disable_nolock(NULL);
59ae6c6b
AK
5665 return 0;
5666}
5667
fb3600cc 5668static void kvm_resume(void)
59ae6c6b 5669{
ca84d1a2 5670 if (kvm_usage_count) {
4cb9a998 5671 lockdep_assert_not_held(&kvm_count_lock);
75b7127c 5672 hardware_enable_nolock(NULL);
ca84d1a2 5673 }
59ae6c6b
AK
5674}
5675
fb3600cc 5676static struct syscore_ops kvm_syscore_ops = {
59ae6c6b
AK
5677 .suspend = kvm_suspend,
5678 .resume = kvm_resume,
5679};
5680
15ad7146
AK
5681static inline
5682struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5683{
5684 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5685}
5686
5687static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5688{
5689 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
f95ef0cd 5690
046ddeed 5691 WRITE_ONCE(vcpu->preempted, false);
d73eb57b 5692 WRITE_ONCE(vcpu->ready, false);
15ad7146 5693
7495e22b 5694 __this_cpu_write(kvm_running_vcpu, vcpu);
e790d9ef 5695 kvm_arch_sched_in(vcpu, cpu);
e9b11c17 5696 kvm_arch_vcpu_load(vcpu, cpu);
15ad7146
AK
5697}
5698
5699static void kvm_sched_out(struct preempt_notifier *pn,
5700 struct task_struct *next)
5701{
5702 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5703
3ba9f93b 5704 if (current->on_rq) {
046ddeed 5705 WRITE_ONCE(vcpu->preempted, true);
d73eb57b
WL
5706 WRITE_ONCE(vcpu->ready, true);
5707 }
e9b11c17 5708 kvm_arch_vcpu_put(vcpu);
7495e22b
PB
5709 __this_cpu_write(kvm_running_vcpu, NULL);
5710}
5711
5712/**
5713 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
1f03b2bc
MZ
5714 *
5715 * We can disable preemption locally around accessing the per-CPU variable,
5716 * and use the resolved vcpu pointer after enabling preemption again,
5717 * because even if the current thread is migrated to another CPU, reading
5718 * the per-CPU value later will give us the same value as we update the
5719 * per-CPU variable in the preempt notifier handlers.
7495e22b
PB
5720 */
5721struct kvm_vcpu *kvm_get_running_vcpu(void)
5722{
1f03b2bc
MZ
5723 struct kvm_vcpu *vcpu;
5724
5725 preempt_disable();
5726 vcpu = __this_cpu_read(kvm_running_vcpu);
5727 preempt_enable();
5728
5729 return vcpu;
7495e22b 5730}
379a3c8e 5731EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
7495e22b
PB
5732
5733/**
5734 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5735 */
5736struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5737{
5738 return &kvm_running_vcpu;
15ad7146
AK
5739}
5740
e1bfc245
SC
5741#ifdef CONFIG_GUEST_PERF_EVENTS
5742static unsigned int kvm_guest_state(void)
5743{
5744 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5745 unsigned int state;
5746
5747 if (!kvm_arch_pmi_in_guest(vcpu))
5748 return 0;
5749
5750 state = PERF_GUEST_ACTIVE;
5751 if (!kvm_arch_vcpu_in_kernel(vcpu))
5752 state |= PERF_GUEST_USER;
5753
5754 return state;
5755}
5756
5757static unsigned long kvm_guest_get_ip(void)
5758{
5759 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5760
5761 /* Retrieving the IP must be guarded by a call to kvm_guest_state(). */
5762 if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu)))
5763 return 0;
5764
5765 return kvm_arch_vcpu_get_ip(vcpu);
5766}
5767
5768static struct perf_guest_info_callbacks kvm_guest_cbs = {
5769 .state = kvm_guest_state,
5770 .get_ip = kvm_guest_get_ip,
5771 .handle_intel_pt_intr = NULL,
5772};
5773
5774void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void))
5775{
5776 kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler;
5777 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5778}
5779void kvm_unregister_perf_callbacks(void)
5780{
5781 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5782}
5783#endif
5784
b9904085
SC
5785struct kvm_cpu_compat_check {
5786 void *opaque;
5787 int *ret;
5788};
5789
5790static void check_processor_compat(void *data)
f257d6dc 5791{
b9904085
SC
5792 struct kvm_cpu_compat_check *c = data;
5793
5794 *c->ret = kvm_arch_check_processor_compat(c->opaque);
f257d6dc
SC
5795}
5796
0ee75bea 5797int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
c16f862d 5798 struct module *module)
6aa8b732 5799{
b9904085 5800 struct kvm_cpu_compat_check c;
6aa8b732 5801 int r;
002c7f7c 5802 int cpu;
6aa8b732 5803
f8c16bba
ZX
5804 r = kvm_arch_init(opaque);
5805 if (r)
d2308784 5806 goto out_fail;
cb498ea2 5807
7dac16c3
AH
5808 /*
5809 * kvm_arch_init makes sure there's at most one caller
5810 * for architectures that support multiple implementations,
5811 * like intel and amd on x86.
36343f6e
PB
5812 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5813 * conflicts in case kvm is already setup for another implementation.
7dac16c3 5814 */
36343f6e
PB
5815 r = kvm_irqfd_init();
5816 if (r)
5817 goto out_irqfd;
7dac16c3 5818
8437a617 5819 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
7f59f492
RR
5820 r = -ENOMEM;
5821 goto out_free_0;
5822 }
5823
b9904085 5824 r = kvm_arch_hardware_setup(opaque);
6aa8b732 5825 if (r < 0)
faf0be22 5826 goto out_free_1;
6aa8b732 5827
b9904085
SC
5828 c.ret = &r;
5829 c.opaque = opaque;
002c7f7c 5830 for_each_online_cpu(cpu) {
b9904085 5831 smp_call_function_single(cpu, check_processor_compat, &c, 1);
002c7f7c 5832 if (r < 0)
faf0be22 5833 goto out_free_2;
002c7f7c
YS
5834 }
5835
73c1b41e 5836 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
8c18b2d2 5837 kvm_starting_cpu, kvm_dying_cpu);
774c47f1 5838 if (r)
d2308784 5839 goto out_free_2;
6aa8b732
AK
5840 register_reboot_notifier(&kvm_reboot_notifier);
5841
c16f862d 5842 /* A kmem cache lets us meet the alignment requirements of fx_save. */
0ee75bea
AK
5843 if (!vcpu_align)
5844 vcpu_align = __alignof__(struct kvm_vcpu);
46515736
PB
5845 kvm_vcpu_cache =
5846 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5847 SLAB_ACCOUNT,
5848 offsetof(struct kvm_vcpu, arch),
ce55c049
JZ
5849 offsetofend(struct kvm_vcpu, stats_id)
5850 - offsetof(struct kvm_vcpu, arch),
46515736 5851 NULL);
c16f862d
RR
5852 if (!kvm_vcpu_cache) {
5853 r = -ENOMEM;
fb3600cc 5854 goto out_free_3;
c16f862d
RR
5855 }
5856
baff59cc
VK
5857 for_each_possible_cpu(cpu) {
5858 if (!alloc_cpumask_var_node(&per_cpu(cpu_kick_mask, cpu),
5859 GFP_KERNEL, cpu_to_node(cpu))) {
5860 r = -ENOMEM;
5861 goto out_free_4;
5862 }
5863 }
5864
af585b92
GN
5865 r = kvm_async_pf_init();
5866 if (r)
baff59cc 5867 goto out_free_5;
af585b92 5868
6aa8b732
AK
5869 kvm_chardev_ops.owner = module;
5870
5871 r = misc_register(&kvm_dev);
5872 if (r) {
1170adc6 5873 pr_err("kvm: misc device register failed\n");
af585b92 5874 goto out_unreg;
6aa8b732
AK
5875 }
5876
fb3600cc
RW
5877 register_syscore_ops(&kvm_syscore_ops);
5878
15ad7146
AK
5879 kvm_preempt_ops.sched_in = kvm_sched_in;
5880 kvm_preempt_ops.sched_out = kvm_sched_out;
5881
929f45e3 5882 kvm_init_debug();
0ea4ed8e 5883
3c3c29fd
PB
5884 r = kvm_vfio_ops_init();
5885 WARN_ON(r);
5886
c7addb90 5887 return 0;
6aa8b732 5888
af585b92
GN
5889out_unreg:
5890 kvm_async_pf_deinit();
baff59cc
VK
5891out_free_5:
5892 for_each_possible_cpu(cpu)
5893 free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5894out_free_4:
c16f862d 5895 kmem_cache_destroy(kvm_vcpu_cache);
d2308784 5896out_free_3:
6aa8b732 5897 unregister_reboot_notifier(&kvm_reboot_notifier);
8c18b2d2 5898 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
d2308784 5899out_free_2:
e9b11c17 5900 kvm_arch_hardware_unsetup();
faf0be22 5901out_free_1:
7f59f492 5902 free_cpumask_var(cpus_hardware_enabled);
d2308784 5903out_free_0:
a0f155e9 5904 kvm_irqfd_exit();
36343f6e 5905out_irqfd:
7dac16c3
AH
5906 kvm_arch_exit();
5907out_fail:
6aa8b732
AK
5908 return r;
5909}
cb498ea2 5910EXPORT_SYMBOL_GPL(kvm_init);
6aa8b732 5911
cb498ea2 5912void kvm_exit(void)
6aa8b732 5913{
baff59cc
VK
5914 int cpu;
5915
4bd33b56 5916 debugfs_remove_recursive(kvm_debugfs_dir);
6aa8b732 5917 misc_deregister(&kvm_dev);
baff59cc
VK
5918 for_each_possible_cpu(cpu)
5919 free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
c16f862d 5920 kmem_cache_destroy(kvm_vcpu_cache);
af585b92 5921 kvm_async_pf_deinit();
fb3600cc 5922 unregister_syscore_ops(&kvm_syscore_ops);
6aa8b732 5923 unregister_reboot_notifier(&kvm_reboot_notifier);
8c18b2d2 5924 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
75b7127c 5925 on_each_cpu(hardware_disable_nolock, NULL, 1);
e9b11c17 5926 kvm_arch_hardware_unsetup();
f8c16bba 5927 kvm_arch_exit();
a0f155e9 5928 kvm_irqfd_exit();
7f59f492 5929 free_cpumask_var(cpus_hardware_enabled);
571ee1b6 5930 kvm_vfio_ops_exit();
6aa8b732 5931}
cb498ea2 5932EXPORT_SYMBOL_GPL(kvm_exit);
c57c8046
JS
5933
5934struct kvm_vm_worker_thread_context {
5935 struct kvm *kvm;
5936 struct task_struct *parent;
5937 struct completion init_done;
5938 kvm_vm_thread_fn_t thread_fn;
5939 uintptr_t data;
5940 int err;
5941};
5942
5943static int kvm_vm_worker_thread(void *context)
5944{
5945 /*
5946 * The init_context is allocated on the stack of the parent thread, so
5947 * we have to locally copy anything that is needed beyond initialization
5948 */
5949 struct kvm_vm_worker_thread_context *init_context = context;
e45cce30 5950 struct task_struct *parent;
c57c8046
JS
5951 struct kvm *kvm = init_context->kvm;
5952 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5953 uintptr_t data = init_context->data;
5954 int err;
5955
5956 err = kthread_park(current);
5957 /* kthread_park(current) is never supposed to return an error */
5958 WARN_ON(err != 0);
5959 if (err)
5960 goto init_complete;
5961
5962 err = cgroup_attach_task_all(init_context->parent, current);
5963 if (err) {
5964 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5965 __func__, err);
5966 goto init_complete;
5967 }
5968
5969 set_user_nice(current, task_nice(init_context->parent));
5970
5971init_complete:
5972 init_context->err = err;
5973 complete(&init_context->init_done);
5974 init_context = NULL;
5975
5976 if (err)
e45cce30 5977 goto out;
c57c8046
JS
5978
5979 /* Wait to be woken up by the spawner before proceeding. */
5980 kthread_parkme();
5981
5982 if (!kthread_should_stop())
5983 err = thread_fn(kvm, data);
5984
e45cce30
VS
5985out:
5986 /*
5987 * Move kthread back to its original cgroup to prevent it lingering in
5988 * the cgroup of the VM process, after the latter finishes its
5989 * execution.
5990 *
5991 * kthread_stop() waits on the 'exited' completion condition which is
5992 * set in exit_mm(), via mm_release(), in do_exit(). However, the
5993 * kthread is removed from the cgroup in the cgroup_exit() which is
5994 * called after the exit_mm(). This causes the kthread_stop() to return
5995 * before the kthread actually quits the cgroup.
5996 */
5997 rcu_read_lock();
5998 parent = rcu_dereference(current->real_parent);
5999 get_task_struct(parent);
6000 rcu_read_unlock();
6001 cgroup_attach_task_all(parent, current);
6002 put_task_struct(parent);
6003
c57c8046
JS
6004 return err;
6005}
6006
6007int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
6008 uintptr_t data, const char *name,
6009 struct task_struct **thread_ptr)
6010{
6011 struct kvm_vm_worker_thread_context init_context = {};
6012 struct task_struct *thread;
6013
6014 *thread_ptr = NULL;
6015 init_context.kvm = kvm;
6016 init_context.parent = current;
6017 init_context.thread_fn = thread_fn;
6018 init_context.data = data;
6019 init_completion(&init_context.init_done);
6020
6021 thread = kthread_run(kvm_vm_worker_thread, &init_context,
6022 "%s-%d", name, task_pid_nr(current));
6023 if (IS_ERR(thread))
6024 return PTR_ERR(thread);
6025
6026 /* kthread_run is never supposed to return NULL */
6027 WARN_ON(thread == NULL);
6028
6029 wait_for_completion(&init_context.init_done);
6030
6031 if (!init_context.err)
6032 *thread_ptr = thread;
6033
6034 return init_context.err;
6035}