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