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