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