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