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