KVM: Drop kvm_arch_vcpu_init() and kvm_arch_vcpu_uninit()
[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>
3e021bf5 58#include <asm/pgtable.h>
6aa8b732 59
5f94c174 60#include "coalesced_mmio.h"
af585b92 61#include "async_pf.h"
3c3c29fd 62#include "vfio.h"
5f94c174 63
229456fc
MT
64#define CREATE_TRACE_POINTS
65#include <trace/events/kvm.h>
66
536a6f88
JF
67/* Worst case buffer size needed for holding an integer. */
68#define ITOA_MAX_LEN 12
69
6aa8b732
AK
70MODULE_AUTHOR("Qumranet");
71MODULE_LICENSE("GPL");
72
920552b2 73/* Architectures should define their poll value according to the halt latency */
ec76d819 74unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
039c5d1b 75module_param(halt_poll_ns, uint, 0644);
ec76d819 76EXPORT_SYMBOL_GPL(halt_poll_ns);
f7819512 77
aca6ff29 78/* Default doubles per-vcpu halt_poll_ns. */
ec76d819 79unsigned int halt_poll_ns_grow = 2;
039c5d1b 80module_param(halt_poll_ns_grow, uint, 0644);
ec76d819 81EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
aca6ff29 82
49113d36
NW
83/* The start value to grow halt_poll_ns from */
84unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
85module_param(halt_poll_ns_grow_start, uint, 0644);
86EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
87
aca6ff29 88/* Default resets per-vcpu halt_poll_ns . */
ec76d819 89unsigned int halt_poll_ns_shrink;
039c5d1b 90module_param(halt_poll_ns_shrink, uint, 0644);
ec76d819 91EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
aca6ff29 92
fa40a821
MT
93/*
94 * Ordering of locks:
95 *
b7d409de 96 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
fa40a821
MT
97 */
98
0d9ce162 99DEFINE_MUTEX(kvm_lock);
4a937f96 100static DEFINE_RAW_SPINLOCK(kvm_count_lock);
e9b11c17 101LIST_HEAD(vm_list);
133de902 102
7f59f492 103static cpumask_var_t cpus_hardware_enabled;
f4fee932 104static int kvm_usage_count;
10474ae8 105static atomic_t hardware_enable_failed;
1b6c0168 106
aaba298c 107static struct kmem_cache *kvm_vcpu_cache;
1165f5fe 108
15ad7146
AK
109static __read_mostly struct preempt_ops kvm_preempt_ops;
110
76f7c879 111struct dentry *kvm_debugfs_dir;
e23a808b 112EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
6aa8b732 113
536a6f88 114static int kvm_debugfs_num_entries;
09cbcef6 115static const struct file_operations stat_fops_per_vm;
536a6f88 116
bccf2150
AK
117static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
118 unsigned long arg);
de8e5d74 119#ifdef CONFIG_KVM_COMPAT
1dda606c
AG
120static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
121 unsigned long arg);
7ddfd3e0
MZ
122#define KVM_COMPAT(c) .compat_ioctl = (c)
123#else
9cb09e7c
MZ
124/*
125 * For architectures that don't implement a compat infrastructure,
126 * adopt a double line of defense:
127 * - Prevent a compat task from opening /dev/kvm
128 * - If the open has been done by a 64bit task, and the KVM fd
129 * passed to a compat task, let the ioctls fail.
130 */
7ddfd3e0
MZ
131static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
132 unsigned long arg) { return -EINVAL; }
b9876e6d
MZ
133
134static int kvm_no_compat_open(struct inode *inode, struct file *file)
135{
136 return is_compat_task() ? -ENODEV : 0;
137}
138#define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
139 .open = kvm_no_compat_open
1dda606c 140#endif
10474ae8
AG
141static int hardware_enable_all(void);
142static void hardware_disable_all(void);
bccf2150 143
e93f8a0f 144static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
7940876e 145
bc009e43 146static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
e93f8a0f 147
52480137 148__visible bool kvm_rebooting;
b7c4145b 149EXPORT_SYMBOL_GPL(kvm_rebooting);
4ecac3fd 150
54dee993
MT
151static bool largepages_enabled = true;
152
286de8f6
CI
153#define KVM_EVENT_CREATE_VM 0
154#define KVM_EVENT_DESTROY_VM 1
155static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
156static unsigned long long kvm_createvm_count;
157static unsigned long long kvm_active_vms;
158
93065ac7
MH
159__weak int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
160 unsigned long start, unsigned long end, bool blockable)
b1394e74 161{
93065ac7 162 return 0;
b1394e74
RK
163}
164
a78986aa
SC
165bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
166{
167 /*
168 * The metadata used by is_zone_device_page() to determine whether or
169 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
170 * the device has been pinned, e.g. by get_user_pages(). WARN if the
171 * page_count() is zero to help detect bad usage of this helper.
172 */
173 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
174 return false;
175
176 return is_zone_device_page(pfn_to_page(pfn));
177}
178
ba049e93 179bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
cbff90a7 180{
a78986aa
SC
181 /*
182 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
183 * perspective they are "normal" pages, albeit with slightly different
184 * usage rules.
185 */
11feeb49 186 if (pfn_valid(pfn))
a78986aa
SC
187 return PageReserved(pfn_to_page(pfn)) &&
188 !kvm_is_zone_device_pfn(pfn);
cbff90a7
BAY
189
190 return true;
191}
192
bccf2150
AK
193/*
194 * Switches to specified vcpu, until a matching vcpu_put()
195 */
ec7660cc 196void vcpu_load(struct kvm_vcpu *vcpu)
6aa8b732 197{
ec7660cc 198 int cpu = get_cpu();
15ad7146 199 preempt_notifier_register(&vcpu->preempt_notifier);
313a3dc7 200 kvm_arch_vcpu_load(vcpu, cpu);
15ad7146 201 put_cpu();
6aa8b732 202}
2f1fe811 203EXPORT_SYMBOL_GPL(vcpu_load);
6aa8b732 204
313a3dc7 205void vcpu_put(struct kvm_vcpu *vcpu)
6aa8b732 206{
15ad7146 207 preempt_disable();
313a3dc7 208 kvm_arch_vcpu_put(vcpu);
15ad7146
AK
209 preempt_notifier_unregister(&vcpu->preempt_notifier);
210 preempt_enable();
6aa8b732 211}
2f1fe811 212EXPORT_SYMBOL_GPL(vcpu_put);
6aa8b732 213
7a97cec2
PB
214/* TODO: merge with kvm_arch_vcpu_should_kick */
215static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
216{
217 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
218
219 /*
220 * We need to wait for the VCPU to reenable interrupts and get out of
221 * READING_SHADOW_PAGE_TABLES mode.
222 */
223 if (req & KVM_REQUEST_WAIT)
224 return mode != OUTSIDE_GUEST_MODE;
225
226 /*
227 * Need to kick a running VCPU, but otherwise there is nothing to do.
228 */
229 return mode == IN_GUEST_MODE;
230}
231
d9e368d6
AK
232static void ack_flush(void *_completed)
233{
d9e368d6
AK
234}
235
b49defe8
PB
236static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
237{
238 if (unlikely(!cpus))
239 cpus = cpu_online_mask;
240
241 if (cpumask_empty(cpus))
242 return false;
243
244 smp_call_function_many(cpus, ack_flush, NULL, wait);
245 return true;
246}
247
7053df4e
VK
248bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
249 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
d9e368d6 250{
597a5f55 251 int i, cpu, me;
d9e368d6 252 struct kvm_vcpu *vcpu;
7053df4e 253 bool called;
6ef7a1bc 254
3cba4130 255 me = get_cpu();
7053df4e 256
988a2cae 257 kvm_for_each_vcpu(i, vcpu, kvm) {
a812297c 258 if (vcpu_bitmap && !test_bit(i, vcpu_bitmap))
7053df4e
VK
259 continue;
260
3cba4130 261 kvm_make_request(req, vcpu);
d9e368d6 262 cpu = vcpu->cpu;
6b7e2d09 263
178f02ff
RK
264 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
265 continue;
6c6e8360 266
7053df4e 267 if (tmp != NULL && cpu != -1 && cpu != me &&
7a97cec2 268 kvm_request_needs_ipi(vcpu, req))
7053df4e 269 __cpumask_set_cpu(cpu, tmp);
49846896 270 }
7053df4e
VK
271
272 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
3cba4130 273 put_cpu();
7053df4e
VK
274
275 return called;
276}
277
278bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
279{
280 cpumask_var_t cpus;
281 bool called;
7053df4e
VK
282
283 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
284
a812297c 285 called = kvm_make_vcpus_request_mask(kvm, req, NULL, cpus);
7053df4e 286
6ef7a1bc 287 free_cpumask_var(cpus);
49846896 288 return called;
d9e368d6
AK
289}
290
a6d51016 291#ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
49846896 292void kvm_flush_remote_tlbs(struct kvm *kvm)
2e53d63a 293{
4ae3cb3a
LT
294 /*
295 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
296 * kvm_make_all_cpus_request.
297 */
298 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
299
300 /*
301 * We want to publish modifications to the page tables before reading
302 * mode. Pairs with a memory barrier in arch-specific code.
303 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
304 * and smp_mb in walk_shadow_page_lockless_begin/end.
305 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
306 *
307 * There is already an smp_mb__after_atomic() before
308 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
309 * barrier here.
310 */
b08660e5
TL
311 if (!kvm_arch_flush_remote_tlb(kvm)
312 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
49846896 313 ++kvm->stat.remote_tlb_flush;
a086f6a1 314 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
2e53d63a 315}
2ba9f0d8 316EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
a6d51016 317#endif
2e53d63a 318
49846896
RR
319void kvm_reload_remote_mmus(struct kvm *kvm)
320{
445b8236 321 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
49846896 322}
2e53d63a 323
aaba298c 324static int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
fb3f0f51
RR
325{
326 struct page *page;
fb3f0f51
RR
327
328 mutex_init(&vcpu->mutex);
329 vcpu->cpu = -1;
fb3f0f51
RR
330 vcpu->kvm = kvm;
331 vcpu->vcpu_id = id;
34bb10b7 332 vcpu->pid = NULL;
8577370f 333 init_swait_queue_head(&vcpu->wq);
af585b92 334 kvm_async_pf_vcpu_init(vcpu);
fb3f0f51 335
bf9f6ac8
FW
336 vcpu->pre_pcpu = -1;
337 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
338
fb3f0f51 339 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
ddd259c9
SC
340 if (!page)
341 return -ENOMEM;
fb3f0f51
RR
342 vcpu->run = page_address(page);
343
4c088493
R
344 kvm_vcpu_set_in_spin_loop(vcpu, false);
345 kvm_vcpu_set_dy_eligible(vcpu, false);
3a08a8f9 346 vcpu->preempted = false;
d73eb57b 347 vcpu->ready = false;
d5c48deb 348 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
4c088493 349
fb3f0f51 350 return 0;
fb3f0f51 351}
fb3f0f51 352
aaba298c 353static void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
fb3f0f51 354{
0e4524a5
CB
355 /*
356 * no need for rcu_read_lock as VCPU_RUN is the only place that
357 * will change the vcpu->pid pointer and on uninit all file
358 * descriptors are already gone.
359 */
360 put_pid(rcu_dereference_protected(vcpu->pid, 1));
fb3f0f51
RR
361 free_page((unsigned long)vcpu->run);
362}
fb3f0f51 363
4543bdc0
SC
364void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
365{
366 kvm_arch_vcpu_destroy(vcpu);
e529ef66
SC
367
368 kvm_vcpu_uninit(vcpu);
369 kmem_cache_free(kvm_vcpu_cache, vcpu);
4543bdc0
SC
370}
371EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
372
e930bffe
AA
373#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
374static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
375{
376 return container_of(mn, struct kvm, mmu_notifier);
377}
378
3da0dd43
IE
379static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
380 struct mm_struct *mm,
381 unsigned long address,
382 pte_t pte)
383{
384 struct kvm *kvm = mmu_notifier_to_kvm(mn);
bc6678a3 385 int idx;
3da0dd43 386
bc6678a3 387 idx = srcu_read_lock(&kvm->srcu);
3da0dd43
IE
388 spin_lock(&kvm->mmu_lock);
389 kvm->mmu_notifier_seq++;
0cf853c5
LT
390
391 if (kvm_set_spte_hva(kvm, address, pte))
392 kvm_flush_remote_tlbs(kvm);
393
3da0dd43 394 spin_unlock(&kvm->mmu_lock);
bc6678a3 395 srcu_read_unlock(&kvm->srcu, idx);
3da0dd43
IE
396}
397
93065ac7 398static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
5d6527a7 399 const struct mmu_notifier_range *range)
e930bffe
AA
400{
401 struct kvm *kvm = mmu_notifier_to_kvm(mn);
bc6678a3 402 int need_tlb_flush = 0, idx;
93065ac7 403 int ret;
e930bffe 404
bc6678a3 405 idx = srcu_read_lock(&kvm->srcu);
e930bffe
AA
406 spin_lock(&kvm->mmu_lock);
407 /*
408 * The count increase must become visible at unlock time as no
409 * spte can be established without taking the mmu_lock and
410 * count is also read inside the mmu_lock critical section.
411 */
412 kvm->mmu_notifier_count++;
5d6527a7 413 need_tlb_flush = kvm_unmap_hva_range(kvm, range->start, range->end);
a4ee1ca4 414 need_tlb_flush |= kvm->tlbs_dirty;
e930bffe
AA
415 /* we've to flush the tlb before the pages can be freed */
416 if (need_tlb_flush)
417 kvm_flush_remote_tlbs(kvm);
565f3be2
TY
418
419 spin_unlock(&kvm->mmu_lock);
b1394e74 420
5d6527a7 421 ret = kvm_arch_mmu_notifier_invalidate_range(kvm, range->start,
dfcd6660
JG
422 range->end,
423 mmu_notifier_range_blockable(range));
b1394e74 424
565f3be2 425 srcu_read_unlock(&kvm->srcu, idx);
93065ac7
MH
426
427 return ret;
e930bffe
AA
428}
429
430static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
5d6527a7 431 const struct mmu_notifier_range *range)
e930bffe
AA
432{
433 struct kvm *kvm = mmu_notifier_to_kvm(mn);
434
435 spin_lock(&kvm->mmu_lock);
436 /*
437 * This sequence increase will notify the kvm page fault that
438 * the page that is going to be mapped in the spte could have
439 * been freed.
440 */
441 kvm->mmu_notifier_seq++;
a355aa54 442 smp_wmb();
e930bffe
AA
443 /*
444 * The above sequence increase must be visible before the
a355aa54
PM
445 * below count decrease, which is ensured by the smp_wmb above
446 * in conjunction with the smp_rmb in mmu_notifier_retry().
e930bffe
AA
447 */
448 kvm->mmu_notifier_count--;
449 spin_unlock(&kvm->mmu_lock);
450
451 BUG_ON(kvm->mmu_notifier_count < 0);
452}
453
454static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
455 struct mm_struct *mm,
57128468
ALC
456 unsigned long start,
457 unsigned long end)
e930bffe
AA
458{
459 struct kvm *kvm = mmu_notifier_to_kvm(mn);
bc6678a3 460 int young, idx;
e930bffe 461
bc6678a3 462 idx = srcu_read_lock(&kvm->srcu);
e930bffe 463 spin_lock(&kvm->mmu_lock);
e930bffe 464
57128468 465 young = kvm_age_hva(kvm, start, end);
e930bffe
AA
466 if (young)
467 kvm_flush_remote_tlbs(kvm);
468
565f3be2
TY
469 spin_unlock(&kvm->mmu_lock);
470 srcu_read_unlock(&kvm->srcu, idx);
471
e930bffe
AA
472 return young;
473}
474
1d7715c6
VD
475static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
476 struct mm_struct *mm,
477 unsigned long start,
478 unsigned long end)
479{
480 struct kvm *kvm = mmu_notifier_to_kvm(mn);
481 int young, idx;
482
483 idx = srcu_read_lock(&kvm->srcu);
484 spin_lock(&kvm->mmu_lock);
485 /*
486 * Even though we do not flush TLB, this will still adversely
487 * affect performance on pre-Haswell Intel EPT, where there is
488 * no EPT Access Bit to clear so that we have to tear down EPT
489 * tables instead. If we find this unacceptable, we can always
490 * add a parameter to kvm_age_hva so that it effectively doesn't
491 * do anything on clear_young.
492 *
493 * Also note that currently we never issue secondary TLB flushes
494 * from clear_young, leaving this job up to the regular system
495 * cadence. If we find this inaccurate, we might come up with a
496 * more sophisticated heuristic later.
497 */
498 young = kvm_age_hva(kvm, start, end);
499 spin_unlock(&kvm->mmu_lock);
500 srcu_read_unlock(&kvm->srcu, idx);
501
502 return young;
503}
504
8ee53820
AA
505static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
506 struct mm_struct *mm,
507 unsigned long address)
508{
509 struct kvm *kvm = mmu_notifier_to_kvm(mn);
510 int young, idx;
511
512 idx = srcu_read_lock(&kvm->srcu);
513 spin_lock(&kvm->mmu_lock);
514 young = kvm_test_age_hva(kvm, address);
515 spin_unlock(&kvm->mmu_lock);
516 srcu_read_unlock(&kvm->srcu, idx);
517
518 return young;
519}
520
85db06e5
MT
521static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
522 struct mm_struct *mm)
523{
524 struct kvm *kvm = mmu_notifier_to_kvm(mn);
eda2beda
LJ
525 int idx;
526
527 idx = srcu_read_lock(&kvm->srcu);
2df72e9b 528 kvm_arch_flush_shadow_all(kvm);
eda2beda 529 srcu_read_unlock(&kvm->srcu, idx);
85db06e5
MT
530}
531
e930bffe 532static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
e930bffe
AA
533 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
534 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
535 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
1d7715c6 536 .clear_young = kvm_mmu_notifier_clear_young,
8ee53820 537 .test_young = kvm_mmu_notifier_test_young,
3da0dd43 538 .change_pte = kvm_mmu_notifier_change_pte,
85db06e5 539 .release = kvm_mmu_notifier_release,
e930bffe 540};
4c07b0a4
AK
541
542static int kvm_init_mmu_notifier(struct kvm *kvm)
543{
544 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
545 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
546}
547
548#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
549
550static int kvm_init_mmu_notifier(struct kvm *kvm)
551{
552 return 0;
553}
554
e930bffe
AA
555#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
556
a47d2b07 557static struct kvm_memslots *kvm_alloc_memslots(void)
bf3e05bc
XG
558{
559 int i;
a47d2b07 560 struct kvm_memslots *slots;
bf3e05bc 561
b12ce36a 562 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
a47d2b07
PB
563 if (!slots)
564 return NULL;
565
bf3e05bc 566 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
f85e2cb5 567 slots->id_to_index[i] = slots->memslots[i].id = i;
a47d2b07
PB
568
569 return slots;
570}
571
572static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
573{
574 if (!memslot->dirty_bitmap)
575 return;
576
577 kvfree(memslot->dirty_bitmap);
578 memslot->dirty_bitmap = NULL;
579}
580
581/*
582 * Free any memory in @free but not in @dont.
583 */
584static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
585 struct kvm_memory_slot *dont)
586{
587 if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
588 kvm_destroy_dirty_bitmap(free);
589
590 kvm_arch_free_memslot(kvm, free, dont);
591
592 free->npages = 0;
593}
594
595static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
596{
597 struct kvm_memory_slot *memslot;
598
599 if (!slots)
600 return;
601
602 kvm_for_each_memslot(memslot, slots)
603 kvm_free_memslot(kvm, memslot, NULL);
604
605 kvfree(slots);
bf3e05bc
XG
606}
607
536a6f88
JF
608static void kvm_destroy_vm_debugfs(struct kvm *kvm)
609{
610 int i;
611
612 if (!kvm->debugfs_dentry)
613 return;
614
615 debugfs_remove_recursive(kvm->debugfs_dentry);
616
9d5a1dce
LC
617 if (kvm->debugfs_stat_data) {
618 for (i = 0; i < kvm_debugfs_num_entries; i++)
619 kfree(kvm->debugfs_stat_data[i]);
620 kfree(kvm->debugfs_stat_data);
621 }
536a6f88
JF
622}
623
624static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
625{
626 char dir_name[ITOA_MAX_LEN * 2];
627 struct kvm_stat_data *stat_data;
628 struct kvm_stats_debugfs_item *p;
629
630 if (!debugfs_initialized())
631 return 0;
632
633 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
929f45e3 634 kvm->debugfs_dentry = debugfs_create_dir(dir_name, kvm_debugfs_dir);
536a6f88
JF
635
636 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
637 sizeof(*kvm->debugfs_stat_data),
b12ce36a 638 GFP_KERNEL_ACCOUNT);
536a6f88
JF
639 if (!kvm->debugfs_stat_data)
640 return -ENOMEM;
641
642 for (p = debugfs_entries; p->name; p++) {
b12ce36a 643 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
536a6f88
JF
644 if (!stat_data)
645 return -ENOMEM;
646
647 stat_data->kvm = kvm;
09cbcef6 648 stat_data->dbgfs_item = p;
536a6f88 649 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
09cbcef6
MP
650 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
651 kvm->debugfs_dentry, stat_data,
652 &stat_fops_per_vm);
536a6f88
JF
653 }
654 return 0;
655}
656
1aa9b957
JS
657/*
658 * Called after the VM is otherwise initialized, but just before adding it to
659 * the vm_list.
660 */
661int __weak kvm_arch_post_init_vm(struct kvm *kvm)
662{
663 return 0;
664}
665
666/*
667 * Called just after removing the VM from the vm_list, but before doing any
668 * other destruction.
669 */
670void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
671{
672}
673
e08b9637 674static struct kvm *kvm_create_vm(unsigned long type)
6aa8b732 675{
d89f5eff 676 struct kvm *kvm = kvm_arch_alloc_vm();
9121923c
JM
677 int r = -ENOMEM;
678 int i;
6aa8b732 679
d89f5eff
JK
680 if (!kvm)
681 return ERR_PTR(-ENOMEM);
682
e9ad4ec8 683 spin_lock_init(&kvm->mmu_lock);
f1f10076 684 mmgrab(current->mm);
e9ad4ec8
PB
685 kvm->mm = current->mm;
686 kvm_eventfd_init(kvm);
687 mutex_init(&kvm->lock);
688 mutex_init(&kvm->irq_lock);
689 mutex_init(&kvm->slots_lock);
e9ad4ec8
PB
690 INIT_LIST_HEAD(&kvm->devices);
691
1e702d9a
AW
692 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
693
8a44119a
PB
694 if (init_srcu_struct(&kvm->srcu))
695 goto out_err_no_srcu;
696 if (init_srcu_struct(&kvm->irq_srcu))
697 goto out_err_no_irq_srcu;
698
e2d3fcaf 699 refcount_set(&kvm->users_count, 1);
f481b069 700 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
4bd518f1 701 struct kvm_memslots *slots = kvm_alloc_memslots();
9121923c 702
4bd518f1 703 if (!slots)
a97b0e77 704 goto out_err_no_arch_destroy_vm;
0e32958e 705 /* Generations must be different for each address space. */
164bf7e5 706 slots->generation = i;
4bd518f1 707 rcu_assign_pointer(kvm->memslots[i], slots);
f481b069 708 }
00f034a1 709
e93f8a0f 710 for (i = 0; i < KVM_NR_BUSES; i++) {
4a12f951 711 rcu_assign_pointer(kvm->buses[i],
b12ce36a 712 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
57e7fbee 713 if (!kvm->buses[i])
a97b0e77 714 goto out_err_no_arch_destroy_vm;
e93f8a0f 715 }
e930bffe 716
e08b9637 717 r = kvm_arch_init_vm(kvm, type);
d89f5eff 718 if (r)
a97b0e77 719 goto out_err_no_arch_destroy_vm;
10474ae8
AG
720
721 r = hardware_enable_all();
722 if (r)
719d93cd 723 goto out_err_no_disable;
10474ae8 724
c77dcacb 725#ifdef CONFIG_HAVE_KVM_IRQFD
136bdfee 726 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
75858a84 727#endif
6aa8b732 728
74b5c5bf 729 r = kvm_init_mmu_notifier(kvm);
1aa9b957
JS
730 if (r)
731 goto out_err_no_mmu_notifier;
732
733 r = kvm_arch_post_init_vm(kvm);
74b5c5bf
MW
734 if (r)
735 goto out_err;
736
0d9ce162 737 mutex_lock(&kvm_lock);
5e58cfe4 738 list_add(&kvm->vm_list, &vm_list);
0d9ce162 739 mutex_unlock(&kvm_lock);
d89f5eff 740
2ecd9d29
PZ
741 preempt_notifier_inc();
742
f17abe9a 743 return kvm;
10474ae8
AG
744
745out_err:
1aa9b957
JS
746#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
747 if (kvm->mmu_notifier.ops)
748 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
749#endif
750out_err_no_mmu_notifier:
10474ae8 751 hardware_disable_all();
719d93cd 752out_err_no_disable:
a97b0e77 753 kvm_arch_destroy_vm(kvm);
a97b0e77 754out_err_no_arch_destroy_vm:
e2d3fcaf 755 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
e93f8a0f 756 for (i = 0; i < KVM_NR_BUSES; i++)
3898da94 757 kfree(kvm_get_bus(kvm, i));
f481b069 758 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
3898da94 759 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
8a44119a
PB
760 cleanup_srcu_struct(&kvm->irq_srcu);
761out_err_no_irq_srcu:
762 cleanup_srcu_struct(&kvm->srcu);
763out_err_no_srcu:
d89f5eff 764 kvm_arch_free_vm(kvm);
e9ad4ec8 765 mmdrop(current->mm);
10474ae8 766 return ERR_PTR(r);
f17abe9a
AK
767}
768
07f0a7bd
SW
769static void kvm_destroy_devices(struct kvm *kvm)
770{
e6e3b5a6 771 struct kvm_device *dev, *tmp;
07f0a7bd 772
a28ebea2
CD
773 /*
774 * We do not need to take the kvm->lock here, because nobody else
775 * has a reference to the struct kvm at this point and therefore
776 * cannot access the devices list anyhow.
777 */
e6e3b5a6
GT
778 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
779 list_del(&dev->vm_node);
07f0a7bd
SW
780 dev->ops->destroy(dev);
781 }
782}
783
f17abe9a
AK
784static void kvm_destroy_vm(struct kvm *kvm)
785{
e93f8a0f 786 int i;
6d4e4c4f
AK
787 struct mm_struct *mm = kvm->mm;
788
286de8f6 789 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
536a6f88 790 kvm_destroy_vm_debugfs(kvm);
ad8ba2cd 791 kvm_arch_sync_events(kvm);
0d9ce162 792 mutex_lock(&kvm_lock);
133de902 793 list_del(&kvm->vm_list);
0d9ce162 794 mutex_unlock(&kvm_lock);
1aa9b957
JS
795 kvm_arch_pre_destroy_vm(kvm);
796
399ec807 797 kvm_free_irq_routing(kvm);
df630b8c 798 for (i = 0; i < KVM_NR_BUSES; i++) {
3898da94 799 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
4a12f951 800
4a12f951
CB
801 if (bus)
802 kvm_io_bus_destroy(bus);
df630b8c
PX
803 kvm->buses[i] = NULL;
804 }
980da6ce 805 kvm_coalesced_mmio_free(kvm);
e930bffe
AA
806#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
807 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
f00be0ca 808#else
2df72e9b 809 kvm_arch_flush_shadow_all(kvm);
5f94c174 810#endif
d19a9cd2 811 kvm_arch_destroy_vm(kvm);
07f0a7bd 812 kvm_destroy_devices(kvm);
f481b069 813 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
3898da94 814 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
820b3fcd 815 cleanup_srcu_struct(&kvm->irq_srcu);
d89f5eff
JK
816 cleanup_srcu_struct(&kvm->srcu);
817 kvm_arch_free_vm(kvm);
2ecd9d29 818 preempt_notifier_dec();
10474ae8 819 hardware_disable_all();
6d4e4c4f 820 mmdrop(mm);
f17abe9a
AK
821}
822
d39f13b0
IE
823void kvm_get_kvm(struct kvm *kvm)
824{
e3736c3e 825 refcount_inc(&kvm->users_count);
d39f13b0
IE
826}
827EXPORT_SYMBOL_GPL(kvm_get_kvm);
828
829void kvm_put_kvm(struct kvm *kvm)
830{
e3736c3e 831 if (refcount_dec_and_test(&kvm->users_count))
d39f13b0
IE
832 kvm_destroy_vm(kvm);
833}
834EXPORT_SYMBOL_GPL(kvm_put_kvm);
835
149487bd
SC
836/*
837 * Used to put a reference that was taken on behalf of an object associated
838 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
839 * of the new file descriptor fails and the reference cannot be transferred to
840 * its final owner. In such cases, the caller is still actively using @kvm and
841 * will fail miserably if the refcount unexpectedly hits zero.
842 */
843void kvm_put_kvm_no_destroy(struct kvm *kvm)
844{
845 WARN_ON(refcount_dec_and_test(&kvm->users_count));
846}
847EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
d39f13b0 848
f17abe9a
AK
849static int kvm_vm_release(struct inode *inode, struct file *filp)
850{
851 struct kvm *kvm = filp->private_data;
852
721eecbf
GH
853 kvm_irqfd_release(kvm);
854
d39f13b0 855 kvm_put_kvm(kvm);
6aa8b732
AK
856 return 0;
857}
858
515a0127
TY
859/*
860 * Allocation size is twice as large as the actual dirty bitmap size.
93474b25 861 * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
515a0127 862 */
a36a57b1
TY
863static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
864{
515a0127 865 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
a36a57b1 866
b12ce36a 867 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
a36a57b1
TY
868 if (!memslot->dirty_bitmap)
869 return -ENOMEM;
870
a36a57b1
TY
871 return 0;
872}
873
bf3e05bc 874/*
0e60b079
IM
875 * Insert memslot and re-sort memslots based on their GFN,
876 * so binary search could be used to lookup GFN.
877 * Sorting algorithm takes advantage of having initially
878 * sorted array and known changed memslot position.
bf3e05bc 879 */
5cc15027 880static void update_memslots(struct kvm_memslots *slots,
31fc4f95
WY
881 struct kvm_memory_slot *new,
882 enum kvm_mr_change change)
bf3e05bc 883{
8593176c
PB
884 int id = new->id;
885 int i = slots->id_to_index[id];
063584d4 886 struct kvm_memory_slot *mslots = slots->memslots;
f85e2cb5 887
8593176c 888 WARN_ON(mslots[i].id != id);
31fc4f95
WY
889 switch (change) {
890 case KVM_MR_CREATE:
891 slots->used_slots++;
892 WARN_ON(mslots[i].npages || !new->npages);
893 break;
894 case KVM_MR_DELETE:
895 slots->used_slots--;
896 WARN_ON(new->npages || !mslots[i].npages);
897 break;
898 default:
899 break;
9c1a5d38 900 }
0e60b079 901
7f379cff 902 while (i < KVM_MEM_SLOTS_NUM - 1 &&
0e60b079
IM
903 new->base_gfn <= mslots[i + 1].base_gfn) {
904 if (!mslots[i + 1].npages)
905 break;
7f379cff
IM
906 mslots[i] = mslots[i + 1];
907 slots->id_to_index[mslots[i].id] = i;
908 i++;
909 }
efbeec70
PB
910
911 /*
912 * The ">=" is needed when creating a slot with base_gfn == 0,
913 * so that it moves before all those with base_gfn == npages == 0.
914 *
915 * On the other hand, if new->npages is zero, the above loop has
916 * already left i pointing to the beginning of the empty part of
917 * mslots, and the ">=" would move the hole backwards in this
918 * case---which is wrong. So skip the loop when deleting a slot.
919 */
920 if (new->npages) {
921 while (i > 0 &&
922 new->base_gfn >= mslots[i - 1].base_gfn) {
923 mslots[i] = mslots[i - 1];
924 slots->id_to_index[mslots[i].id] = i;
925 i--;
926 }
dbaff309
PB
927 } else
928 WARN_ON_ONCE(i != slots->used_slots);
f85e2cb5 929
8593176c
PB
930 mslots[i] = *new;
931 slots->id_to_index[mslots[i].id] = i;
bf3e05bc
XG
932}
933
09170a49 934static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
a50d64d6 935{
4d8b81ab
XG
936 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
937
0f8a4de3 938#ifdef __KVM_HAVE_READONLY_MEM
4d8b81ab
XG
939 valid_flags |= KVM_MEM_READONLY;
940#endif
941
942 if (mem->flags & ~valid_flags)
a50d64d6
XG
943 return -EINVAL;
944
945 return 0;
946}
947
7ec4fb44 948static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
f481b069 949 int as_id, struct kvm_memslots *slots)
7ec4fb44 950{
f481b069 951 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
361209e0 952 u64 gen = old_memslots->generation;
7ec4fb44 953
361209e0
SC
954 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
955 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
ee3d1570 956
f481b069 957 rcu_assign_pointer(kvm->memslots[as_id], slots);
7ec4fb44 958 synchronize_srcu_expedited(&kvm->srcu);
e59dbe09 959
ee3d1570 960 /*
361209e0 961 * Increment the new memslot generation a second time, dropping the
00116795 962 * update in-progress flag and incrementing the generation based on
361209e0
SC
963 * the number of address spaces. This provides a unique and easily
964 * identifiable generation number while the memslots are in flux.
965 */
966 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
967
968 /*
4bd518f1
PB
969 * Generations must be unique even across address spaces. We do not need
970 * a global counter for that, instead the generation space is evenly split
971 * across address spaces. For example, with two address spaces, address
164bf7e5
SC
972 * space 0 will use generations 0, 2, 4, ... while address space 1 will
973 * use generations 1, 3, 5, ...
ee3d1570 974 */
164bf7e5 975 gen += KVM_ADDRESS_SPACE_NUM;
ee3d1570 976
15248258 977 kvm_arch_memslots_updated(kvm, gen);
ee3d1570 978
15248258 979 slots->generation = gen;
e59dbe09
TY
980
981 return old_memslots;
7ec4fb44
GN
982}
983
6aa8b732
AK
984/*
985 * Allocate some memory and give it an address in the guest physical address
986 * space.
987 *
988 * Discontiguous memory is allowed, mostly for framebuffers.
f78e0e2e 989 *
02d5d55b 990 * Must be called holding kvm->slots_lock for write.
6aa8b732 991 */
f78e0e2e 992int __kvm_set_memory_region(struct kvm *kvm,
09170a49 993 const struct kvm_userspace_memory_region *mem)
6aa8b732 994{
8234b22e 995 int r;
6aa8b732 996 gfn_t base_gfn;
28bcb112 997 unsigned long npages;
a843fac2 998 struct kvm_memory_slot *slot;
6aa8b732 999 struct kvm_memory_slot old, new;
b7f69c55 1000 struct kvm_memslots *slots = NULL, *old_memslots;
f481b069 1001 int as_id, id;
f64c0398 1002 enum kvm_mr_change change;
6aa8b732 1003
a50d64d6
XG
1004 r = check_memory_region_flags(mem);
1005 if (r)
1006 goto out;
1007
6aa8b732 1008 r = -EINVAL;
f481b069
PB
1009 as_id = mem->slot >> 16;
1010 id = (u16)mem->slot;
1011
6aa8b732
AK
1012 /* General sanity checks */
1013 if (mem->memory_size & (PAGE_SIZE - 1))
1014 goto out;
1015 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1016 goto out;
fa3d315a 1017 /* We can read the guest memory with __xxx_user() later on. */
f481b069 1018 if ((id < KVM_USER_MEM_SLOTS) &&
fa3d315a 1019 ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
96d4f267 1020 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
9e3bb6b6 1021 mem->memory_size)))
78749809 1022 goto out;
f481b069 1023 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
6aa8b732
AK
1024 goto out;
1025 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1026 goto out;
1027
f481b069 1028 slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
6aa8b732
AK
1029 base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1030 npages = mem->memory_size >> PAGE_SHIFT;
1031
660c22c4
TY
1032 if (npages > KVM_MEM_MAX_NR_PAGES)
1033 goto out;
1034
a843fac2 1035 new = old = *slot;
6aa8b732 1036
f481b069 1037 new.id = id;
6aa8b732
AK
1038 new.base_gfn = base_gfn;
1039 new.npages = npages;
1040 new.flags = mem->flags;
1041
f64c0398
TY
1042 if (npages) {
1043 if (!old.npages)
1044 change = KVM_MR_CREATE;
1045 else { /* Modify an existing slot. */
1046 if ((mem->userspace_addr != old.userspace_addr) ||
75d61fbc
TY
1047 (npages != old.npages) ||
1048 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
f64c0398
TY
1049 goto out;
1050
1051 if (base_gfn != old.base_gfn)
1052 change = KVM_MR_MOVE;
1053 else if (new.flags != old.flags)
1054 change = KVM_MR_FLAGS_ONLY;
1055 else { /* Nothing to change. */
1056 r = 0;
1057 goto out;
1058 }
1059 }
09170a49
PB
1060 } else {
1061 if (!old.npages)
1062 goto out;
1063
f64c0398 1064 change = KVM_MR_DELETE;
09170a49
PB
1065 new.base_gfn = 0;
1066 new.flags = 0;
1067 }
6aa8b732 1068
f64c0398 1069 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
0a706bee
TY
1070 /* Check for overlaps */
1071 r = -EEXIST;
f481b069 1072 kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
b28676bb 1073 if (slot->id == id)
0a706bee
TY
1074 continue;
1075 if (!((base_gfn + npages <= slot->base_gfn) ||
1076 (base_gfn >= slot->base_gfn + slot->npages)))
1077 goto out;
1078 }
6aa8b732 1079 }
6aa8b732 1080
6aa8b732
AK
1081 /* Free page dirty bitmap if unneeded */
1082 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
8b6d44c7 1083 new.dirty_bitmap = NULL;
6aa8b732
AK
1084
1085 r = -ENOMEM;
f64c0398 1086 if (change == KVM_MR_CREATE) {
189a2f7b 1087 new.userspace_addr = mem->userspace_addr;
d89cc617 1088
5587027c 1089 if (kvm_arch_create_memslot(kvm, &new, npages))
db3fe4eb 1090 goto out_free;
6aa8b732 1091 }
ec04b260 1092
6aa8b732
AK
1093 /* Allocate page dirty bitmap if needed */
1094 if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
a36a57b1 1095 if (kvm_create_dirty_bitmap(&new) < 0)
f78e0e2e 1096 goto out_free;
6aa8b732
AK
1097 }
1098
b12ce36a 1099 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
f2a81036
PB
1100 if (!slots)
1101 goto out_free;
f481b069 1102 memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
f2a81036 1103
f64c0398 1104 if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
f481b069 1105 slot = id_to_memslot(slots, id);
28a37544
XG
1106 slot->flags |= KVM_MEMSLOT_INVALID;
1107
f481b069 1108 old_memslots = install_new_memslots(kvm, as_id, slots);
bc6678a3 1109
12d6e753
MT
1110 /* From this point no new shadow pages pointing to a deleted,
1111 * or moved, memslot will be created.
bc6678a3
MT
1112 *
1113 * validation of sp->gfn happens in:
b7d409de 1114 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
668effb6 1115 * - kvm_is_visible_gfn (mmu_check_root)
bc6678a3 1116 */
2df72e9b 1117 kvm_arch_flush_shadow_memslot(kvm, slot);
f2a81036
PB
1118
1119 /*
1120 * We can re-use the old_memslots from above, the only difference
1121 * from the currently installed memslots is the invalid flag. This
1122 * will get overwritten by update_memslots anyway.
1123 */
b7f69c55 1124 slots = old_memslots;
bc6678a3 1125 }
34d4cb8f 1126
7b6195a9 1127 r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
f7784b8e 1128 if (r)
b7f69c55 1129 goto out_slots;
f7784b8e 1130
a47d2b07 1131 /* actual memory is freed via old in kvm_free_memslot below */
f64c0398 1132 if (change == KVM_MR_DELETE) {
bc6678a3 1133 new.dirty_bitmap = NULL;
db3fe4eb 1134 memset(&new.arch, 0, sizeof(new.arch));
bc6678a3
MT
1135 }
1136
31fc4f95 1137 update_memslots(slots, &new, change);
f481b069 1138 old_memslots = install_new_memslots(kvm, as_id, slots);
3ad82a7e 1139
f36f3f28 1140 kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
82ce2c96 1141
a47d2b07 1142 kvm_free_memslot(kvm, &old, &new);
74496134 1143 kvfree(old_memslots);
6aa8b732
AK
1144 return 0;
1145
e40f193f 1146out_slots:
74496134 1147 kvfree(slots);
f78e0e2e 1148out_free:
a47d2b07 1149 kvm_free_memslot(kvm, &new, &old);
6aa8b732
AK
1150out:
1151 return r;
210c7c4d 1152}
f78e0e2e
SY
1153EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1154
1155int kvm_set_memory_region(struct kvm *kvm,
09170a49 1156 const struct kvm_userspace_memory_region *mem)
f78e0e2e
SY
1157{
1158 int r;
1159
79fac95e 1160 mutex_lock(&kvm->slots_lock);
47ae31e2 1161 r = __kvm_set_memory_region(kvm, mem);
79fac95e 1162 mutex_unlock(&kvm->slots_lock);
f78e0e2e
SY
1163 return r;
1164}
210c7c4d
IE
1165EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1166
7940876e
SH
1167static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1168 struct kvm_userspace_memory_region *mem)
210c7c4d 1169{
f481b069 1170 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
e0d62c7f 1171 return -EINVAL;
09170a49 1172
47ae31e2 1173 return kvm_set_memory_region(kvm, mem);
6aa8b732
AK
1174}
1175
5bb064dc
ZX
1176int kvm_get_dirty_log(struct kvm *kvm,
1177 struct kvm_dirty_log *log, int *is_dirty)
6aa8b732 1178{
9f6b8029 1179 struct kvm_memslots *slots;
6aa8b732 1180 struct kvm_memory_slot *memslot;
843574a3 1181 int i, as_id, id;
87bf6e7d 1182 unsigned long n;
6aa8b732
AK
1183 unsigned long any = 0;
1184
f481b069
PB
1185 as_id = log->slot >> 16;
1186 id = (u16)log->slot;
1187 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
843574a3 1188 return -EINVAL;
6aa8b732 1189
f481b069
PB
1190 slots = __kvm_memslots(kvm, as_id);
1191 memslot = id_to_memslot(slots, id);
6aa8b732 1192 if (!memslot->dirty_bitmap)
843574a3 1193 return -ENOENT;
6aa8b732 1194
87bf6e7d 1195 n = kvm_dirty_bitmap_bytes(memslot);
6aa8b732 1196
cd1a4a98 1197 for (i = 0; !any && i < n/sizeof(long); ++i)
6aa8b732
AK
1198 any = memslot->dirty_bitmap[i];
1199
6aa8b732 1200 if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
843574a3 1201 return -EFAULT;
6aa8b732 1202
5bb064dc
ZX
1203 if (any)
1204 *is_dirty = 1;
843574a3 1205 return 0;
6aa8b732 1206}
2ba9f0d8 1207EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
6aa8b732 1208
ba0513b5
MS
1209#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1210/**
b8b00220 1211 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
2a31b9db 1212 * and reenable dirty page tracking for the corresponding pages.
ba0513b5
MS
1213 * @kvm: pointer to kvm instance
1214 * @log: slot id and address to which we copy the log
b8b00220 1215 * @flush: true if TLB flush is needed by caller
ba0513b5
MS
1216 *
1217 * We need to keep it in mind that VCPU threads can write to the bitmap
1218 * concurrently. So, to avoid losing track of dirty pages we keep the
1219 * following order:
1220 *
1221 * 1. Take a snapshot of the bit and clear it if needed.
1222 * 2. Write protect the corresponding page.
1223 * 3. Copy the snapshot to the userspace.
1224 * 4. Upon return caller flushes TLB's if needed.
1225 *
1226 * Between 2 and 4, the guest may write to the page using the remaining TLB
1227 * entry. This is not a problem because the page is reported dirty using
1228 * the snapshot taken before and step 4 ensures that writes done after
1229 * exiting to userspace will be logged for the next call.
1230 *
1231 */
1232int kvm_get_dirty_log_protect(struct kvm *kvm,
8fe65a82 1233 struct kvm_dirty_log *log, bool *flush)
ba0513b5 1234{
9f6b8029 1235 struct kvm_memslots *slots;
ba0513b5 1236 struct kvm_memory_slot *memslot;
58d6db34 1237 int i, as_id, id;
ba0513b5
MS
1238 unsigned long n;
1239 unsigned long *dirty_bitmap;
1240 unsigned long *dirty_bitmap_buffer;
1241
f481b069
PB
1242 as_id = log->slot >> 16;
1243 id = (u16)log->slot;
1244 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
58d6db34 1245 return -EINVAL;
ba0513b5 1246
f481b069
PB
1247 slots = __kvm_memslots(kvm, as_id);
1248 memslot = id_to_memslot(slots, id);
ba0513b5
MS
1249
1250 dirty_bitmap = memslot->dirty_bitmap;
ba0513b5 1251 if (!dirty_bitmap)
58d6db34 1252 return -ENOENT;
ba0513b5
MS
1253
1254 n = kvm_dirty_bitmap_bytes(memslot);
2a31b9db
PB
1255 *flush = false;
1256 if (kvm->manual_dirty_log_protect) {
1257 /*
1258 * Unlike kvm_get_dirty_log, we always return false in *flush,
1259 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1260 * is some code duplication between this function and
1261 * kvm_get_dirty_log, but hopefully all architecture
1262 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1263 * can be eliminated.
1264 */
1265 dirty_bitmap_buffer = dirty_bitmap;
1266 } else {
1267 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1268 memset(dirty_bitmap_buffer, 0, n);
ba0513b5 1269
2a31b9db
PB
1270 spin_lock(&kvm->mmu_lock);
1271 for (i = 0; i < n / sizeof(long); i++) {
1272 unsigned long mask;
1273 gfn_t offset;
ba0513b5 1274
2a31b9db
PB
1275 if (!dirty_bitmap[i])
1276 continue;
1277
1278 *flush = true;
1279 mask = xchg(&dirty_bitmap[i], 0);
1280 dirty_bitmap_buffer[i] = mask;
1281
a67794ca
LT
1282 offset = i * BITS_PER_LONG;
1283 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1284 offset, mask);
2a31b9db
PB
1285 }
1286 spin_unlock(&kvm->mmu_lock);
1287 }
1288
1289 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1290 return -EFAULT;
1291 return 0;
1292}
1293EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
1294
1295/**
1296 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1297 * and reenable dirty page tracking for the corresponding pages.
1298 * @kvm: pointer to kvm instance
1299 * @log: slot id and address from which to fetch the bitmap of dirty pages
b8b00220 1300 * @flush: true if TLB flush is needed by caller
2a31b9db
PB
1301 */
1302int kvm_clear_dirty_log_protect(struct kvm *kvm,
1303 struct kvm_clear_dirty_log *log, bool *flush)
1304{
1305 struct kvm_memslots *slots;
1306 struct kvm_memory_slot *memslot;
98938aa8 1307 int as_id, id;
2a31b9db 1308 gfn_t offset;
98938aa8 1309 unsigned long i, n;
2a31b9db
PB
1310 unsigned long *dirty_bitmap;
1311 unsigned long *dirty_bitmap_buffer;
1312
1313 as_id = log->slot >> 16;
1314 id = (u16)log->slot;
1315 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1316 return -EINVAL;
1317
76d58e0f 1318 if (log->first_page & 63)
2a31b9db
PB
1319 return -EINVAL;
1320
1321 slots = __kvm_memslots(kvm, as_id);
1322 memslot = id_to_memslot(slots, id);
1323
1324 dirty_bitmap = memslot->dirty_bitmap;
1325 if (!dirty_bitmap)
1326 return -ENOENT;
1327
4ddc9204 1328 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
98938aa8
TB
1329
1330 if (log->first_page > memslot->npages ||
76d58e0f
PB
1331 log->num_pages > memslot->npages - log->first_page ||
1332 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1333 return -EINVAL;
98938aa8 1334
8fe65a82 1335 *flush = false;
2a31b9db
PB
1336 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1337 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1338 return -EFAULT;
ba0513b5 1339
2a31b9db 1340 spin_lock(&kvm->mmu_lock);
53eac7a8
PX
1341 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1342 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2a31b9db
PB
1343 i++, offset += BITS_PER_LONG) {
1344 unsigned long mask = *dirty_bitmap_buffer++;
1345 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1346 if (!mask)
ba0513b5
MS
1347 continue;
1348
2a31b9db 1349 mask &= atomic_long_fetch_andnot(mask, p);
ba0513b5 1350
2a31b9db
PB
1351 /*
1352 * mask contains the bits that really have been cleared. This
1353 * never includes any bits beyond the length of the memslot (if
1354 * the length is not aligned to 64 pages), therefore it is not
1355 * a problem if userspace sets them in log->dirty_bitmap.
1356 */
58d2930f 1357 if (mask) {
2a31b9db 1358 *flush = true;
58d2930f
TY
1359 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1360 offset, mask);
1361 }
ba0513b5 1362 }
ba0513b5 1363 spin_unlock(&kvm->mmu_lock);
2a31b9db 1364
58d6db34 1365 return 0;
ba0513b5 1366}
2a31b9db 1367EXPORT_SYMBOL_GPL(kvm_clear_dirty_log_protect);
ba0513b5
MS
1368#endif
1369
db3fe4eb
TY
1370bool kvm_largepages_enabled(void)
1371{
1372 return largepages_enabled;
1373}
1374
54dee993
MT
1375void kvm_disable_largepages(void)
1376{
1377 largepages_enabled = false;
1378}
1379EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1380
49c7754c
GN
1381struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1382{
1383 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1384}
a1f4d395 1385EXPORT_SYMBOL_GPL(gfn_to_memslot);
6aa8b732 1386
8e73485c
PB
1387struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1388{
1389 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1390}
1391
33e94154 1392bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
e0d62c7f 1393{
bf3e05bc 1394 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
e0d62c7f 1395
bbacc0c1 1396 if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
bf3e05bc 1397 memslot->flags & KVM_MEMSLOT_INVALID)
33e94154 1398 return false;
e0d62c7f 1399
33e94154 1400 return true;
e0d62c7f
IE
1401}
1402EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1403
8f0b1ab6
JR
1404unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
1405{
1406 struct vm_area_struct *vma;
1407 unsigned long addr, size;
1408
1409 size = PAGE_SIZE;
1410
1411 addr = gfn_to_hva(kvm, gfn);
1412 if (kvm_is_error_hva(addr))
1413 return PAGE_SIZE;
1414
1415 down_read(&current->mm->mmap_sem);
1416 vma = find_vma(current->mm, addr);
1417 if (!vma)
1418 goto out;
1419
1420 size = vma_kernel_pagesize(vma);
1421
1422out:
1423 up_read(&current->mm->mmap_sem);
1424
1425 return size;
1426}
1427
4d8b81ab
XG
1428static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1429{
1430 return slot->flags & KVM_MEM_READONLY;
1431}
1432
4d8b81ab
XG
1433static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1434 gfn_t *nr_pages, bool write)
539cb660 1435{
bc6678a3 1436 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
ca3a490c 1437 return KVM_HVA_ERR_BAD;
48987781 1438
4d8b81ab
XG
1439 if (memslot_is_readonly(slot) && write)
1440 return KVM_HVA_ERR_RO_BAD;
48987781
XG
1441
1442 if (nr_pages)
1443 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1444
4d8b81ab 1445 return __gfn_to_hva_memslot(slot, gfn);
539cb660 1446}
48987781 1447
4d8b81ab
XG
1448static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1449 gfn_t *nr_pages)
1450{
1451 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
539cb660 1452}
48987781 1453
4d8b81ab 1454unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
7940876e 1455 gfn_t gfn)
4d8b81ab
XG
1456{
1457 return gfn_to_hva_many(slot, gfn, NULL);
1458}
1459EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1460
48987781
XG
1461unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1462{
49c7754c 1463 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
48987781 1464}
0d150298 1465EXPORT_SYMBOL_GPL(gfn_to_hva);
539cb660 1466
8e73485c
PB
1467unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1468{
1469 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1470}
1471EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1472
86ab8cff 1473/*
970c0d4b
WY
1474 * Return the hva of a @gfn and the R/W attribute if possible.
1475 *
1476 * @slot: the kvm_memory_slot which contains @gfn
1477 * @gfn: the gfn to be translated
1478 * @writable: used to return the read/write attribute of the @slot if the hva
1479 * is valid and @writable is not NULL
86ab8cff 1480 */
64d83126
CD
1481unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1482 gfn_t gfn, bool *writable)
86ab8cff 1483{
a2ac07fe
GN
1484 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1485
1486 if (!kvm_is_error_hva(hva) && writable)
ba6a3541
PB
1487 *writable = !memslot_is_readonly(slot);
1488
a2ac07fe 1489 return hva;
86ab8cff
XG
1490}
1491
64d83126
CD
1492unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1493{
1494 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1495
1496 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1497}
1498
8e73485c
PB
1499unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1500{
1501 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1502
1503 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1504}
1505
fafc3dba
HY
1506static inline int check_user_page_hwpoison(unsigned long addr)
1507{
0d731759 1508 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
fafc3dba 1509
0d731759 1510 rc = get_user_pages(addr, 1, flags, NULL, NULL);
fafc3dba
HY
1511 return rc == -EHWPOISON;
1512}
1513
2fc84311 1514/*
b9b33da2
PB
1515 * The fast path to get the writable pfn which will be stored in @pfn,
1516 * true indicates success, otherwise false is returned. It's also the
311497e0 1517 * only part that runs if we can in atomic context.
2fc84311 1518 */
b9b33da2
PB
1519static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1520 bool *writable, kvm_pfn_t *pfn)
954bbbc2 1521{
8d4e1288 1522 struct page *page[1];
2fc84311 1523 int npages;
954bbbc2 1524
12ce13fe
XG
1525 /*
1526 * Fast pin a writable pfn only if it is a write fault request
1527 * or the caller allows to map a writable pfn for a read fault
1528 * request.
1529 */
1530 if (!(write_fault || writable))
1531 return false;
612819c3 1532
2fc84311
XG
1533 npages = __get_user_pages_fast(addr, 1, 1, page);
1534 if (npages == 1) {
1535 *pfn = page_to_pfn(page[0]);
612819c3 1536
2fc84311
XG
1537 if (writable)
1538 *writable = true;
1539 return true;
1540 }
af585b92 1541
2fc84311
XG
1542 return false;
1543}
612819c3 1544
2fc84311
XG
1545/*
1546 * The slow path to get the pfn of the specified host virtual address,
1547 * 1 indicates success, -errno is returned if error is detected.
1548 */
1549static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
ba049e93 1550 bool *writable, kvm_pfn_t *pfn)
2fc84311 1551{
ce53053c
AV
1552 unsigned int flags = FOLL_HWPOISON;
1553 struct page *page;
2fc84311 1554 int npages = 0;
612819c3 1555
2fc84311
XG
1556 might_sleep();
1557
1558 if (writable)
1559 *writable = write_fault;
1560
ce53053c
AV
1561 if (write_fault)
1562 flags |= FOLL_WRITE;
1563 if (async)
1564 flags |= FOLL_NOWAIT;
d4944b0e 1565
ce53053c 1566 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2fc84311
XG
1567 if (npages != 1)
1568 return npages;
1569
1570 /* map read fault as writable if possible */
12ce13fe 1571 if (unlikely(!write_fault) && writable) {
ce53053c 1572 struct page *wpage;
2fc84311 1573
ce53053c 1574 if (__get_user_pages_fast(addr, 1, 1, &wpage) == 1) {
2fc84311 1575 *writable = true;
ce53053c
AV
1576 put_page(page);
1577 page = wpage;
612819c3 1578 }
887c08ac 1579 }
ce53053c 1580 *pfn = page_to_pfn(page);
2fc84311
XG
1581 return npages;
1582}
539cb660 1583
4d8b81ab
XG
1584static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1585{
1586 if (unlikely(!(vma->vm_flags & VM_READ)))
1587 return false;
2e2e3738 1588
4d8b81ab
XG
1589 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1590 return false;
887c08ac 1591
4d8b81ab
XG
1592 return true;
1593}
bf998156 1594
92176a8e
PB
1595static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1596 unsigned long addr, bool *async,
a340b3e2
KA
1597 bool write_fault, bool *writable,
1598 kvm_pfn_t *p_pfn)
92176a8e 1599{
add6a0cd
PB
1600 unsigned long pfn;
1601 int r;
1602
1603 r = follow_pfn(vma, addr, &pfn);
1604 if (r) {
1605 /*
1606 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1607 * not call the fault handler, so do it here.
1608 */
1609 bool unlocked = false;
1610 r = fixup_user_fault(current, current->mm, addr,
1611 (write_fault ? FAULT_FLAG_WRITE : 0),
1612 &unlocked);
1613 if (unlocked)
1614 return -EAGAIN;
1615 if (r)
1616 return r;
1617
1618 r = follow_pfn(vma, addr, &pfn);
1619 if (r)
1620 return r;
1621
1622 }
1623
a340b3e2
KA
1624 if (writable)
1625 *writable = true;
add6a0cd
PB
1626
1627 /*
1628 * Get a reference here because callers of *hva_to_pfn* and
1629 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1630 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1631 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1632 * simply do nothing for reserved pfns.
1633 *
1634 * Whoever called remap_pfn_range is also going to call e.g.
1635 * unmap_mapping_range before the underlying pages are freed,
1636 * causing a call to our MMU notifier.
1637 */
1638 kvm_get_pfn(pfn);
1639
1640 *p_pfn = pfn;
92176a8e
PB
1641 return 0;
1642}
1643
12ce13fe
XG
1644/*
1645 * Pin guest page in memory and return its pfn.
1646 * @addr: host virtual address which maps memory to the guest
1647 * @atomic: whether this function can sleep
1648 * @async: whether this function need to wait IO complete if the
1649 * host page is not in the memory
1650 * @write_fault: whether we should get a writable host page
1651 * @writable: whether it allows to map a writable host page for !@write_fault
1652 *
1653 * The function will map a writable host page for these two cases:
1654 * 1): @write_fault = true
1655 * 2): @write_fault = false && @writable, @writable will tell the caller
1656 * whether the mapping is writable.
1657 */
ba049e93 1658static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2fc84311
XG
1659 bool write_fault, bool *writable)
1660{
1661 struct vm_area_struct *vma;
ba049e93 1662 kvm_pfn_t pfn = 0;
92176a8e 1663 int npages, r;
2e2e3738 1664
2fc84311
XG
1665 /* we can do it either atomically or asynchronously, not both */
1666 BUG_ON(atomic && async);
8d4e1288 1667
b9b33da2 1668 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2fc84311
XG
1669 return pfn;
1670
1671 if (atomic)
1672 return KVM_PFN_ERR_FAULT;
1673
1674 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1675 if (npages == 1)
1676 return pfn;
8d4e1288 1677
2fc84311
XG
1678 down_read(&current->mm->mmap_sem);
1679 if (npages == -EHWPOISON ||
1680 (!async && check_user_page_hwpoison(addr))) {
1681 pfn = KVM_PFN_ERR_HWPOISON;
1682 goto exit;
1683 }
1684
add6a0cd 1685retry:
2fc84311
XG
1686 vma = find_vma_intersection(current->mm, addr, addr + 1);
1687
1688 if (vma == NULL)
1689 pfn = KVM_PFN_ERR_FAULT;
92176a8e 1690 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
a340b3e2 1691 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
add6a0cd
PB
1692 if (r == -EAGAIN)
1693 goto retry;
92176a8e
PB
1694 if (r < 0)
1695 pfn = KVM_PFN_ERR_FAULT;
2fc84311 1696 } else {
4d8b81ab 1697 if (async && vma_is_valid(vma, write_fault))
2fc84311
XG
1698 *async = true;
1699 pfn = KVM_PFN_ERR_FAULT;
1700 }
1701exit:
1702 up_read(&current->mm->mmap_sem);
2e2e3738 1703 return pfn;
35149e21
AL
1704}
1705
ba049e93
DW
1706kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1707 bool atomic, bool *async, bool write_fault,
1708 bool *writable)
887c08ac 1709{
4d8b81ab
XG
1710 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1711
b2740d35
PB
1712 if (addr == KVM_HVA_ERR_RO_BAD) {
1713 if (writable)
1714 *writable = false;
4d8b81ab 1715 return KVM_PFN_ERR_RO_FAULT;
b2740d35 1716 }
4d8b81ab 1717
b2740d35
PB
1718 if (kvm_is_error_hva(addr)) {
1719 if (writable)
1720 *writable = false;
81c52c56 1721 return KVM_PFN_NOSLOT;
b2740d35 1722 }
4d8b81ab
XG
1723
1724 /* Do not map writable pfn in the readonly memslot. */
1725 if (writable && memslot_is_readonly(slot)) {
1726 *writable = false;
1727 writable = NULL;
1728 }
1729
1730 return hva_to_pfn(addr, atomic, async, write_fault,
1731 writable);
887c08ac 1732}
3520469d 1733EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
887c08ac 1734
ba049e93 1735kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
612819c3
MT
1736 bool *writable)
1737{
e37afc6e
PB
1738 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1739 write_fault, writable);
612819c3
MT
1740}
1741EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1742
ba049e93 1743kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
506f0d6f 1744{
4d8b81ab 1745 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
506f0d6f 1746}
e37afc6e 1747EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
506f0d6f 1748
ba049e93 1749kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
506f0d6f 1750{
4d8b81ab 1751 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
506f0d6f 1752}
037d92dc 1753EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
506f0d6f 1754
ba049e93 1755kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
e37afc6e
PB
1756{
1757 return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1758}
1759EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1760
ba049e93 1761kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
8e73485c
PB
1762{
1763 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1764}
1765EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1766
ba049e93 1767kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
e37afc6e
PB
1768{
1769 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1770}
1771EXPORT_SYMBOL_GPL(gfn_to_pfn);
1772
ba049e93 1773kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8e73485c
PB
1774{
1775 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1776}
1777EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1778
d9ef13c2
PB
1779int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1780 struct page **pages, int nr_pages)
48987781
XG
1781{
1782 unsigned long addr;
076b925d 1783 gfn_t entry = 0;
48987781 1784
d9ef13c2 1785 addr = gfn_to_hva_many(slot, gfn, &entry);
48987781
XG
1786 if (kvm_is_error_hva(addr))
1787 return -1;
1788
1789 if (entry < nr_pages)
1790 return 0;
1791
1792 return __get_user_pages_fast(addr, nr_pages, 1, pages);
1793}
1794EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1795
ba049e93 1796static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
a2766325 1797{
81c52c56 1798 if (is_error_noslot_pfn(pfn))
cb9aaa30 1799 return KVM_ERR_PTR_BAD_PAGE;
a2766325 1800
bf4bea8e 1801 if (kvm_is_reserved_pfn(pfn)) {
cb9aaa30 1802 WARN_ON(1);
6cede2e6 1803 return KVM_ERR_PTR_BAD_PAGE;
cb9aaa30 1804 }
a2766325
XG
1805
1806 return pfn_to_page(pfn);
1807}
1808
35149e21
AL
1809struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1810{
ba049e93 1811 kvm_pfn_t pfn;
2e2e3738
AL
1812
1813 pfn = gfn_to_pfn(kvm, gfn);
2e2e3738 1814
a2766325 1815 return kvm_pfn_to_page(pfn);
954bbbc2
AK
1816}
1817EXPORT_SYMBOL_GPL(gfn_to_page);
1818
e45adf66
KA
1819static int __kvm_map_gfn(struct kvm_memory_slot *slot, gfn_t gfn,
1820 struct kvm_host_map *map)
1821{
1822 kvm_pfn_t pfn;
1823 void *hva = NULL;
1824 struct page *page = KVM_UNMAPPED_PAGE;
1825
1826 if (!map)
1827 return -EINVAL;
1828
1829 pfn = gfn_to_pfn_memslot(slot, gfn);
1830 if (is_error_noslot_pfn(pfn))
1831 return -EINVAL;
1832
1833 if (pfn_valid(pfn)) {
1834 page = pfn_to_page(pfn);
1835 hva = kmap(page);
d30b214d 1836#ifdef CONFIG_HAS_IOMEM
e45adf66
KA
1837 } else {
1838 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
d30b214d 1839#endif
e45adf66
KA
1840 }
1841
1842 if (!hva)
1843 return -EFAULT;
1844
1845 map->page = page;
1846 map->hva = hva;
1847 map->pfn = pfn;
1848 map->gfn = gfn;
1849
1850 return 0;
1851}
1852
1853int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
1854{
1855 return __kvm_map_gfn(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, map);
1856}
1857EXPORT_SYMBOL_GPL(kvm_vcpu_map);
1858
1859void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
1860 bool dirty)
1861{
1862 if (!map)
1863 return;
1864
1865 if (!map->hva)
1866 return;
1867
b614c602 1868 if (map->page != KVM_UNMAPPED_PAGE)
e45adf66 1869 kunmap(map->page);
eb1f2f38 1870#ifdef CONFIG_HAS_IOMEM
e45adf66
KA
1871 else
1872 memunmap(map->hva);
eb1f2f38 1873#endif
e45adf66
KA
1874
1875 if (dirty) {
1876 kvm_vcpu_mark_page_dirty(vcpu, map->gfn);
1877 kvm_release_pfn_dirty(map->pfn);
1878 } else {
1879 kvm_release_pfn_clean(map->pfn);
1880 }
1881
1882 map->hva = NULL;
1883 map->page = NULL;
1884}
1885EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
1886
8e73485c
PB
1887struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
1888{
ba049e93 1889 kvm_pfn_t pfn;
8e73485c
PB
1890
1891 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
1892
1893 return kvm_pfn_to_page(pfn);
1894}
1895EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
1896
b4231d61
IE
1897void kvm_release_page_clean(struct page *page)
1898{
32cad84f
XG
1899 WARN_ON(is_error_page(page));
1900
35149e21 1901 kvm_release_pfn_clean(page_to_pfn(page));
b4231d61
IE
1902}
1903EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1904
ba049e93 1905void kvm_release_pfn_clean(kvm_pfn_t pfn)
35149e21 1906{
bf4bea8e 1907 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2e2e3738 1908 put_page(pfn_to_page(pfn));
35149e21
AL
1909}
1910EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1911
b4231d61 1912void kvm_release_page_dirty(struct page *page)
8a7ae055 1913{
a2766325
XG
1914 WARN_ON(is_error_page(page));
1915
35149e21
AL
1916 kvm_release_pfn_dirty(page_to_pfn(page));
1917}
1918EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1919
f7a6509f 1920void kvm_release_pfn_dirty(kvm_pfn_t pfn)
35149e21
AL
1921{
1922 kvm_set_pfn_dirty(pfn);
1923 kvm_release_pfn_clean(pfn);
1924}
f7a6509f 1925EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
35149e21 1926
ba049e93 1927void kvm_set_pfn_dirty(kvm_pfn_t pfn)
35149e21 1928{
d29c03a5
ML
1929 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
1930 SetPageDirty(pfn_to_page(pfn));
8a7ae055 1931}
35149e21
AL
1932EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1933
ba049e93 1934void kvm_set_pfn_accessed(kvm_pfn_t pfn)
35149e21 1935{
a78986aa 1936 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2e2e3738 1937 mark_page_accessed(pfn_to_page(pfn));
35149e21
AL
1938}
1939EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1940
ba049e93 1941void kvm_get_pfn(kvm_pfn_t pfn)
35149e21 1942{
bf4bea8e 1943 if (!kvm_is_reserved_pfn(pfn))
2e2e3738 1944 get_page(pfn_to_page(pfn));
35149e21
AL
1945}
1946EXPORT_SYMBOL_GPL(kvm_get_pfn);
8a7ae055 1947
195aefde
IE
1948static int next_segment(unsigned long len, int offset)
1949{
1950 if (len > PAGE_SIZE - offset)
1951 return PAGE_SIZE - offset;
1952 else
1953 return len;
1954}
1955
8e73485c
PB
1956static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
1957 void *data, int offset, int len)
195aefde 1958{
e0506bcb
IE
1959 int r;
1960 unsigned long addr;
195aefde 1961
8e73485c 1962 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
e0506bcb
IE
1963 if (kvm_is_error_hva(addr))
1964 return -EFAULT;
3180a7fc 1965 r = __copy_from_user(data, (void __user *)addr + offset, len);
e0506bcb 1966 if (r)
195aefde 1967 return -EFAULT;
195aefde
IE
1968 return 0;
1969}
8e73485c
PB
1970
1971int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1972 int len)
1973{
1974 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1975
1976 return __kvm_read_guest_page(slot, gfn, data, offset, len);
1977}
195aefde
IE
1978EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1979
8e73485c
PB
1980int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
1981 int offset, int len)
1982{
1983 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1984
1985 return __kvm_read_guest_page(slot, gfn, data, offset, len);
1986}
1987EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
1988
195aefde
IE
1989int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1990{
1991 gfn_t gfn = gpa >> PAGE_SHIFT;
1992 int seg;
1993 int offset = offset_in_page(gpa);
1994 int ret;
1995
1996 while ((seg = next_segment(len, offset)) != 0) {
1997 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1998 if (ret < 0)
1999 return ret;
2000 offset = 0;
2001 len -= seg;
2002 data += seg;
2003 ++gfn;
2004 }
2005 return 0;
2006}
2007EXPORT_SYMBOL_GPL(kvm_read_guest);
2008
8e73485c 2009int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
7ec54588 2010{
7ec54588 2011 gfn_t gfn = gpa >> PAGE_SHIFT;
8e73485c 2012 int seg;
7ec54588 2013 int offset = offset_in_page(gpa);
8e73485c
PB
2014 int ret;
2015
2016 while ((seg = next_segment(len, offset)) != 0) {
2017 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2018 if (ret < 0)
2019 return ret;
2020 offset = 0;
2021 len -= seg;
2022 data += seg;
2023 ++gfn;
2024 }
2025 return 0;
2026}
2027EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
7ec54588 2028
8e73485c
PB
2029static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2030 void *data, int offset, unsigned long len)
2031{
2032 int r;
2033 unsigned long addr;
2034
2035 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
7ec54588
MT
2036 if (kvm_is_error_hva(addr))
2037 return -EFAULT;
0aac03f0 2038 pagefault_disable();
3180a7fc 2039 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
0aac03f0 2040 pagefault_enable();
7ec54588
MT
2041 if (r)
2042 return -EFAULT;
2043 return 0;
2044}
7ec54588 2045
8e73485c
PB
2046int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
2047 unsigned long len)
2048{
2049 gfn_t gfn = gpa >> PAGE_SHIFT;
2050 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2051 int offset = offset_in_page(gpa);
2052
2053 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2054}
2055EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
2056
2057int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2058 void *data, unsigned long len)
2059{
2060 gfn_t gfn = gpa >> PAGE_SHIFT;
2061 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2062 int offset = offset_in_page(gpa);
2063
2064 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2065}
2066EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2067
2068static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
2069 const void *data, int offset, int len)
195aefde 2070{
e0506bcb
IE
2071 int r;
2072 unsigned long addr;
195aefde 2073
251eb841 2074 addr = gfn_to_hva_memslot(memslot, gfn);
e0506bcb
IE
2075 if (kvm_is_error_hva(addr))
2076 return -EFAULT;
8b0cedff 2077 r = __copy_to_user((void __user *)addr + offset, data, len);
e0506bcb 2078 if (r)
195aefde 2079 return -EFAULT;
bc009e43 2080 mark_page_dirty_in_slot(memslot, gfn);
195aefde
IE
2081 return 0;
2082}
8e73485c
PB
2083
2084int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2085 const void *data, int offset, int len)
2086{
2087 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2088
2089 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2090}
195aefde
IE
2091EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2092
8e73485c
PB
2093int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2094 const void *data, int offset, int len)
2095{
2096 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2097
2098 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2099}
2100EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2101
195aefde
IE
2102int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2103 unsigned long len)
2104{
2105 gfn_t gfn = gpa >> PAGE_SHIFT;
2106 int seg;
2107 int offset = offset_in_page(gpa);
2108 int ret;
2109
2110 while ((seg = next_segment(len, offset)) != 0) {
2111 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2112 if (ret < 0)
2113 return ret;
2114 offset = 0;
2115 len -= seg;
2116 data += seg;
2117 ++gfn;
2118 }
2119 return 0;
2120}
ff651cb6 2121EXPORT_SYMBOL_GPL(kvm_write_guest);
195aefde 2122
8e73485c
PB
2123int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2124 unsigned long len)
2125{
2126 gfn_t gfn = gpa >> PAGE_SHIFT;
2127 int seg;
2128 int offset = offset_in_page(gpa);
2129 int ret;
2130
2131 while ((seg = next_segment(len, offset)) != 0) {
2132 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2133 if (ret < 0)
2134 return ret;
2135 offset = 0;
2136 len -= seg;
2137 data += seg;
2138 ++gfn;
2139 }
2140 return 0;
2141}
2142EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2143
5a2d4365
PB
2144static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2145 struct gfn_to_hva_cache *ghc,
2146 gpa_t gpa, unsigned long len)
49c7754c 2147{
49c7754c 2148 int offset = offset_in_page(gpa);
8f964525
AH
2149 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2150 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2151 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2152 gfn_t nr_pages_avail;
f1b9dd5e 2153 int r = start_gfn <= end_gfn ? 0 : -EINVAL;
49c7754c
GN
2154
2155 ghc->gpa = gpa;
2156 ghc->generation = slots->generation;
8f964525 2157 ghc->len = len;
f1b9dd5e
JM
2158 ghc->hva = KVM_HVA_ERR_BAD;
2159
2160 /*
2161 * If the requested region crosses two memslots, we still
2162 * verify that the entire region is valid here.
2163 */
2164 while (!r && start_gfn <= end_gfn) {
2165 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2166 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2167 &nr_pages_avail);
2168 if (kvm_is_error_hva(ghc->hva))
2169 r = -EFAULT;
2170 start_gfn += nr_pages_avail;
2171 }
2172
2173 /* Use the slow path for cross page reads and writes. */
2174 if (!r && nr_pages_needed == 1)
49c7754c 2175 ghc->hva += offset;
f1b9dd5e 2176 else
8f964525 2177 ghc->memslot = NULL;
f1b9dd5e
JM
2178
2179 return r;
49c7754c 2180}
5a2d4365 2181
4e335d9e 2182int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
5a2d4365
PB
2183 gpa_t gpa, unsigned long len)
2184{
4e335d9e 2185 struct kvm_memslots *slots = kvm_memslots(kvm);
5a2d4365
PB
2186 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2187}
4e335d9e 2188EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
49c7754c 2189
4e335d9e 2190int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
7a86dab8
JM
2191 void *data, unsigned int offset,
2192 unsigned long len)
49c7754c 2193{
4e335d9e 2194 struct kvm_memslots *slots = kvm_memslots(kvm);
49c7754c 2195 int r;
4ec6e863 2196 gpa_t gpa = ghc->gpa + offset;
49c7754c 2197
4ec6e863 2198 BUG_ON(len + offset > ghc->len);
8f964525 2199
49c7754c 2200 if (slots->generation != ghc->generation)
5a2d4365 2201 __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
8f964525
AH
2202
2203 if (unlikely(!ghc->memslot))
4e335d9e 2204 return kvm_write_guest(kvm, gpa, data, len);
49c7754c
GN
2205
2206 if (kvm_is_error_hva(ghc->hva))
2207 return -EFAULT;
2208
4ec6e863 2209 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
49c7754c
GN
2210 if (r)
2211 return -EFAULT;
4ec6e863 2212 mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
49c7754c
GN
2213
2214 return 0;
2215}
4e335d9e 2216EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
4ec6e863 2217
4e335d9e
PB
2218int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2219 void *data, unsigned long len)
4ec6e863 2220{
4e335d9e 2221 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
4ec6e863 2222}
4e335d9e 2223EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
49c7754c 2224
4e335d9e
PB
2225int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2226 void *data, unsigned long len)
e03b644f 2227{
4e335d9e 2228 struct kvm_memslots *slots = kvm_memslots(kvm);
e03b644f
GN
2229 int r;
2230
8f964525
AH
2231 BUG_ON(len > ghc->len);
2232
e03b644f 2233 if (slots->generation != ghc->generation)
5a2d4365 2234 __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
8f964525
AH
2235
2236 if (unlikely(!ghc->memslot))
4e335d9e 2237 return kvm_read_guest(kvm, ghc->gpa, data, len);
e03b644f
GN
2238
2239 if (kvm_is_error_hva(ghc->hva))
2240 return -EFAULT;
2241
2242 r = __copy_from_user(data, (void __user *)ghc->hva, len);
2243 if (r)
2244 return -EFAULT;
2245
2246 return 0;
2247}
4e335d9e 2248EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
e03b644f 2249
195aefde
IE
2250int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2251{
8a3caa6d
HC
2252 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2253
2254 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
195aefde
IE
2255}
2256EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2257
2258int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2259{
2260 gfn_t gfn = gpa >> PAGE_SHIFT;
2261 int seg;
2262 int offset = offset_in_page(gpa);
2263 int ret;
2264
bfda0e84 2265 while ((seg = next_segment(len, offset)) != 0) {
195aefde
IE
2266 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2267 if (ret < 0)
2268 return ret;
2269 offset = 0;
2270 len -= seg;
2271 ++gfn;
2272 }
2273 return 0;
2274}
2275EXPORT_SYMBOL_GPL(kvm_clear_guest);
2276
bc009e43 2277static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
7940876e 2278 gfn_t gfn)
6aa8b732 2279{
7e9d619d
RR
2280 if (memslot && memslot->dirty_bitmap) {
2281 unsigned long rel_gfn = gfn - memslot->base_gfn;
6aa8b732 2282
b74ca3b3 2283 set_bit_le(rel_gfn, memslot->dirty_bitmap);
6aa8b732
AK
2284 }
2285}
2286
49c7754c
GN
2287void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2288{
2289 struct kvm_memory_slot *memslot;
2290
2291 memslot = gfn_to_memslot(kvm, gfn);
bc009e43 2292 mark_page_dirty_in_slot(memslot, gfn);
49c7754c 2293}
2ba9f0d8 2294EXPORT_SYMBOL_GPL(mark_page_dirty);
49c7754c 2295
8e73485c
PB
2296void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2297{
2298 struct kvm_memory_slot *memslot;
2299
2300 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2301 mark_page_dirty_in_slot(memslot, gfn);
2302}
2303EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2304
20b7035c
JS
2305void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2306{
2307 if (!vcpu->sigset_active)
2308 return;
2309
2310 /*
2311 * This does a lockless modification of ->real_blocked, which is fine
2312 * because, only current can change ->real_blocked and all readers of
2313 * ->real_blocked don't care as long ->real_blocked is always a subset
2314 * of ->blocked.
2315 */
2316 sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
2317}
2318
2319void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2320{
2321 if (!vcpu->sigset_active)
2322 return;
2323
2324 sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
2325 sigemptyset(&current->real_blocked);
2326}
2327
aca6ff29
WL
2328static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2329{
dee339b5 2330 unsigned int old, val, grow, grow_start;
aca6ff29 2331
2cbd7824 2332 old = val = vcpu->halt_poll_ns;
dee339b5 2333 grow_start = READ_ONCE(halt_poll_ns_grow_start);
6b6de68c 2334 grow = READ_ONCE(halt_poll_ns_grow);
7fa08e71
NW
2335 if (!grow)
2336 goto out;
2337
dee339b5
NW
2338 val *= grow;
2339 if (val < grow_start)
2340 val = grow_start;
aca6ff29 2341
313f636d
DM
2342 if (val > halt_poll_ns)
2343 val = halt_poll_ns;
2344
aca6ff29 2345 vcpu->halt_poll_ns = val;
7fa08e71 2346out:
2cbd7824 2347 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
aca6ff29
WL
2348}
2349
2350static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2351{
6b6de68c 2352 unsigned int old, val, shrink;
aca6ff29 2353
2cbd7824 2354 old = val = vcpu->halt_poll_ns;
6b6de68c
CB
2355 shrink = READ_ONCE(halt_poll_ns_shrink);
2356 if (shrink == 0)
aca6ff29
WL
2357 val = 0;
2358 else
6b6de68c 2359 val /= shrink;
aca6ff29
WL
2360
2361 vcpu->halt_poll_ns = val;
2cbd7824 2362 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
aca6ff29
WL
2363}
2364
f7819512
PB
2365static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2366{
50c28f21
JS
2367 int ret = -EINTR;
2368 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2369
f7819512
PB
2370 if (kvm_arch_vcpu_runnable(vcpu)) {
2371 kvm_make_request(KVM_REQ_UNHALT, vcpu);
50c28f21 2372 goto out;
f7819512
PB
2373 }
2374 if (kvm_cpu_has_pending_timer(vcpu))
50c28f21 2375 goto out;
f7819512 2376 if (signal_pending(current))
50c28f21 2377 goto out;
f7819512 2378
50c28f21
JS
2379 ret = 0;
2380out:
2381 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2382 return ret;
f7819512
PB
2383}
2384
b6958ce4
ED
2385/*
2386 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2387 */
8776e519 2388void kvm_vcpu_block(struct kvm_vcpu *vcpu)
d3bef15f 2389{
f7819512 2390 ktime_t start, cur;
8577370f 2391 DECLARE_SWAITQUEUE(wait);
f7819512 2392 bool waited = false;
aca6ff29 2393 u64 block_ns;
f7819512 2394
07ab0f8d
MZ
2395 kvm_arch_vcpu_blocking(vcpu);
2396
f7819512 2397 start = cur = ktime_get();
cdd6ad3a 2398 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
19020f8a 2399 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
f95ef0cd 2400
62bea5bf 2401 ++vcpu->stat.halt_attempted_poll;
f7819512
PB
2402 do {
2403 /*
2404 * This sets KVM_REQ_UNHALT if an interrupt
2405 * arrives.
2406 */
2407 if (kvm_vcpu_check_block(vcpu) < 0) {
2408 ++vcpu->stat.halt_successful_poll;
3491caf2
CB
2409 if (!vcpu_valid_wakeup(vcpu))
2410 ++vcpu->stat.halt_poll_invalid;
f7819512
PB
2411 goto out;
2412 }
2413 cur = ktime_get();
2414 } while (single_task_running() && ktime_before(cur, stop));
2415 }
e5c239cf
MT
2416
2417 for (;;) {
b3dae109 2418 prepare_to_swait_exclusive(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
e5c239cf 2419
f7819512 2420 if (kvm_vcpu_check_block(vcpu) < 0)
e5c239cf
MT
2421 break;
2422
f7819512 2423 waited = true;
b6958ce4 2424 schedule();
b6958ce4 2425 }
d3bef15f 2426
8577370f 2427 finish_swait(&vcpu->wq, &wait);
f7819512 2428 cur = ktime_get();
f7819512 2429out:
07ab0f8d 2430 kvm_arch_vcpu_unblocking(vcpu);
aca6ff29
WL
2431 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2432
44551b2f
WL
2433 if (!kvm_arch_no_poll(vcpu)) {
2434 if (!vcpu_valid_wakeup(vcpu)) {
aca6ff29 2435 shrink_halt_poll_ns(vcpu);
44551b2f
WL
2436 } else if (halt_poll_ns) {
2437 if (block_ns <= vcpu->halt_poll_ns)
2438 ;
2439 /* we had a long block, shrink polling */
2440 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2441 shrink_halt_poll_ns(vcpu);
2442 /* we had a short halt and our poll time is too small */
2443 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2444 block_ns < halt_poll_ns)
2445 grow_halt_poll_ns(vcpu);
2446 } else {
2447 vcpu->halt_poll_ns = 0;
2448 }
2449 }
aca6ff29 2450
3491caf2
CB
2451 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2452 kvm_arch_vcpu_block_finish(vcpu);
b6958ce4 2453}
2ba9f0d8 2454EXPORT_SYMBOL_GPL(kvm_vcpu_block);
b6958ce4 2455
178f02ff 2456bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
b6d33834 2457{
8577370f 2458 struct swait_queue_head *wqp;
b6d33834
CD
2459
2460 wqp = kvm_arch_vcpu_wq(vcpu);
5e0018b3 2461 if (swq_has_sleeper(wqp)) {
b3dae109 2462 swake_up_one(wqp);
d73eb57b 2463 WRITE_ONCE(vcpu->ready, true);
b6d33834 2464 ++vcpu->stat.halt_wakeup;
178f02ff 2465 return true;
b6d33834
CD
2466 }
2467
178f02ff 2468 return false;
dd1a4cc1
RK
2469}
2470EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2471
0266c894 2472#ifndef CONFIG_S390
dd1a4cc1
RK
2473/*
2474 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2475 */
2476void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2477{
2478 int me;
2479 int cpu = vcpu->cpu;
2480
178f02ff
RK
2481 if (kvm_vcpu_wake_up(vcpu))
2482 return;
2483
b6d33834
CD
2484 me = get_cpu();
2485 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2486 if (kvm_arch_vcpu_should_kick(vcpu))
2487 smp_send_reschedule(cpu);
2488 put_cpu();
2489}
a20ed54d 2490EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
0266c894 2491#endif /* !CONFIG_S390 */
b6d33834 2492
fa93384f 2493int kvm_vcpu_yield_to(struct kvm_vcpu *target)
41628d33
KW
2494{
2495 struct pid *pid;
2496 struct task_struct *task = NULL;
fa93384f 2497 int ret = 0;
41628d33
KW
2498
2499 rcu_read_lock();
2500 pid = rcu_dereference(target->pid);
2501 if (pid)
27fbe64b 2502 task = get_pid_task(pid, PIDTYPE_PID);
41628d33
KW
2503 rcu_read_unlock();
2504 if (!task)
c45c528e 2505 return ret;
c45c528e 2506 ret = yield_to(task, 1);
41628d33 2507 put_task_struct(task);
c45c528e
R
2508
2509 return ret;
41628d33
KW
2510}
2511EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2512
06e48c51
R
2513/*
2514 * Helper that checks whether a VCPU is eligible for directed yield.
2515 * Most eligible candidate to yield is decided by following heuristics:
2516 *
2517 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2518 * (preempted lock holder), indicated by @in_spin_loop.
2519 * Set at the beiginning and cleared at the end of interception/PLE handler.
2520 *
2521 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2522 * chance last time (mostly it has become eligible now since we have probably
2523 * yielded to lockholder in last iteration. This is done by toggling
2524 * @dy_eligible each time a VCPU checked for eligibility.)
2525 *
2526 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2527 * to preempted lock-holder could result in wrong VCPU selection and CPU
2528 * burning. Giving priority for a potential lock-holder increases lock
2529 * progress.
2530 *
2531 * Since algorithm is based on heuristics, accessing another VCPU data without
2532 * locking does not harm. It may result in trying to yield to same VCPU, fail
2533 * and continue with next VCPU and so on.
2534 */
7940876e 2535static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
06e48c51 2536{
4a55dd72 2537#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
06e48c51
R
2538 bool eligible;
2539
2540 eligible = !vcpu->spin_loop.in_spin_loop ||
34656113 2541 vcpu->spin_loop.dy_eligible;
06e48c51
R
2542
2543 if (vcpu->spin_loop.in_spin_loop)
2544 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2545
2546 return eligible;
4a55dd72
SW
2547#else
2548 return true;
06e48c51 2549#endif
4a55dd72 2550}
c45c528e 2551
17e433b5
WL
2552/*
2553 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2554 * a vcpu_load/vcpu_put pair. However, for most architectures
2555 * kvm_arch_vcpu_runnable does not require vcpu_load.
2556 */
2557bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2558{
2559 return kvm_arch_vcpu_runnable(vcpu);
2560}
2561
2562static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2563{
2564 if (kvm_arch_dy_runnable(vcpu))
2565 return true;
2566
2567#ifdef CONFIG_KVM_ASYNC_PF
2568 if (!list_empty_careful(&vcpu->async_pf.done))
2569 return true;
2570#endif
2571
2572 return false;
2573}
2574
199b5763 2575void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
d255f4f2 2576{
217ece61
RR
2577 struct kvm *kvm = me->kvm;
2578 struct kvm_vcpu *vcpu;
2579 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2580 int yielded = 0;
c45c528e 2581 int try = 3;
217ece61
RR
2582 int pass;
2583 int i;
d255f4f2 2584
4c088493 2585 kvm_vcpu_set_in_spin_loop(me, true);
217ece61
RR
2586 /*
2587 * We boost the priority of a VCPU that is runnable but not
2588 * currently running, because it got preempted by something
2589 * else and called schedule in __vcpu_run. Hopefully that
2590 * VCPU is holding the lock that we need and will release it.
2591 * We approximate round-robin by starting at the last boosted VCPU.
2592 */
c45c528e 2593 for (pass = 0; pass < 2 && !yielded && try; pass++) {
217ece61 2594 kvm_for_each_vcpu(i, vcpu, kvm) {
5cfc2aab 2595 if (!pass && i <= last_boosted_vcpu) {
217ece61
RR
2596 i = last_boosted_vcpu;
2597 continue;
2598 } else if (pass && i > last_boosted_vcpu)
2599 break;
d73eb57b 2600 if (!READ_ONCE(vcpu->ready))
7bc7ae25 2601 continue;
217ece61
RR
2602 if (vcpu == me)
2603 continue;
17e433b5 2604 if (swait_active(&vcpu->wq) && !vcpu_dy_runnable(vcpu))
217ece61 2605 continue;
046ddeed
WL
2606 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
2607 !kvm_arch_vcpu_in_kernel(vcpu))
199b5763 2608 continue;
06e48c51
R
2609 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2610 continue;
c45c528e
R
2611
2612 yielded = kvm_vcpu_yield_to(vcpu);
2613 if (yielded > 0) {
217ece61 2614 kvm->last_boosted_vcpu = i;
217ece61 2615 break;
c45c528e
R
2616 } else if (yielded < 0) {
2617 try--;
2618 if (!try)
2619 break;
217ece61 2620 }
217ece61
RR
2621 }
2622 }
4c088493 2623 kvm_vcpu_set_in_spin_loop(me, false);
06e48c51
R
2624
2625 /* Ensure vcpu is not eligible during next spinloop */
2626 kvm_vcpu_set_dy_eligible(me, false);
d255f4f2
ZE
2627}
2628EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2629
1499fa80 2630static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
9a2bb7f4 2631{
11bac800 2632 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
9a2bb7f4
AK
2633 struct page *page;
2634
e4a533a4 2635 if (vmf->pgoff == 0)
039576c0 2636 page = virt_to_page(vcpu->run);
09566765 2637#ifdef CONFIG_X86
e4a533a4 2638 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
ad312c7c 2639 page = virt_to_page(vcpu->arch.pio_data);
5f94c174 2640#endif
4b4357e0 2641#ifdef CONFIG_KVM_MMIO
5f94c174
LV
2642 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2643 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
09566765 2644#endif
039576c0 2645 else
5b1c1493 2646 return kvm_arch_vcpu_fault(vcpu, vmf);
9a2bb7f4 2647 get_page(page);
e4a533a4 2648 vmf->page = page;
2649 return 0;
9a2bb7f4
AK
2650}
2651
f0f37e2f 2652static const struct vm_operations_struct kvm_vcpu_vm_ops = {
e4a533a4 2653 .fault = kvm_vcpu_fault,
9a2bb7f4
AK
2654};
2655
2656static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2657{
2658 vma->vm_ops = &kvm_vcpu_vm_ops;
2659 return 0;
2660}
2661
bccf2150
AK
2662static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2663{
2664 struct kvm_vcpu *vcpu = filp->private_data;
2665
45b5939e 2666 debugfs_remove_recursive(vcpu->debugfs_dentry);
66c0b394 2667 kvm_put_kvm(vcpu->kvm);
bccf2150
AK
2668 return 0;
2669}
2670
3d3aab1b 2671static struct file_operations kvm_vcpu_fops = {
bccf2150
AK
2672 .release = kvm_vcpu_release,
2673 .unlocked_ioctl = kvm_vcpu_ioctl,
9a2bb7f4 2674 .mmap = kvm_vcpu_mmap,
6038f373 2675 .llseek = noop_llseek,
7ddfd3e0 2676 KVM_COMPAT(kvm_vcpu_compat_ioctl),
bccf2150
AK
2677};
2678
2679/*
2680 * Allocates an inode for the vcpu.
2681 */
2682static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2683{
e46b4692
MY
2684 char name[8 + 1 + ITOA_MAX_LEN + 1];
2685
2686 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
2687 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
bccf2150
AK
2688}
2689
3e7093d0 2690static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
45b5939e 2691{
741cbbae 2692#ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
45b5939e 2693 char dir_name[ITOA_MAX_LEN * 2];
45b5939e 2694
45b5939e 2695 if (!debugfs_initialized())
3e7093d0 2696 return;
45b5939e
LC
2697
2698 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2699 vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
3e7093d0 2700 vcpu->kvm->debugfs_dentry);
45b5939e 2701
3e7093d0 2702 kvm_arch_create_vcpu_debugfs(vcpu);
741cbbae 2703#endif
45b5939e
LC
2704}
2705
c5ea7660
AK
2706/*
2707 * Creates some virtual cpus. Good luck creating more than one.
2708 */
73880c80 2709static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
c5ea7660
AK
2710{
2711 int r;
e09fefde 2712 struct kvm_vcpu *vcpu;
c5ea7660 2713
0b1b1dfd 2714 if (id >= KVM_MAX_VCPU_ID)
338c7dba
AH
2715 return -EINVAL;
2716
6c7caebc
PB
2717 mutex_lock(&kvm->lock);
2718 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
2719 mutex_unlock(&kvm->lock);
2720 return -EINVAL;
2721 }
2722
2723 kvm->created_vcpus++;
2724 mutex_unlock(&kvm->lock);
2725
897cc38e
SC
2726 r = kvm_arch_vcpu_precreate(kvm, id);
2727 if (r)
2728 goto vcpu_decrement;
2729
e529ef66
SC
2730 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
2731 if (!vcpu) {
2732 r = -ENOMEM;
6c7caebc
PB
2733 goto vcpu_decrement;
2734 }
c5ea7660 2735
e529ef66
SC
2736 r = kvm_vcpu_init(vcpu, kvm, id);
2737 if (r)
2738 goto vcpu_free;
2739
2740 r = kvm_arch_vcpu_create(vcpu);
2741 if (r)
2742 goto vcpu_uninit;
2743
3e7093d0 2744 kvm_create_vcpu_debugfs(vcpu);
45b5939e 2745
11ec2804 2746 mutex_lock(&kvm->lock);
e09fefde
DH
2747 if (kvm_get_vcpu_by_id(kvm, id)) {
2748 r = -EEXIST;
2749 goto unlock_vcpu_destroy;
2750 }
73880c80 2751
8750e72a
RK
2752 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
2753 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
c5ea7660 2754
fb3f0f51 2755 /* Now it's all set up, let userspace reach it */
66c0b394 2756 kvm_get_kvm(kvm);
bccf2150 2757 r = create_vcpu_fd(vcpu);
73880c80 2758 if (r < 0) {
149487bd 2759 kvm_put_kvm_no_destroy(kvm);
d780592b 2760 goto unlock_vcpu_destroy;
73880c80
GN
2761 }
2762
8750e72a 2763 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
dd489240
PB
2764
2765 /*
2766 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
2767 * before kvm->online_vcpu's incremented value.
2768 */
73880c80
GN
2769 smp_wmb();
2770 atomic_inc(&kvm->online_vcpus);
2771
73880c80 2772 mutex_unlock(&kvm->lock);
42897d86 2773 kvm_arch_vcpu_postcreate(vcpu);
fb3f0f51 2774 return r;
39c3b86e 2775
d780592b 2776unlock_vcpu_destroy:
7d8fece6 2777 mutex_unlock(&kvm->lock);
45b5939e 2778 debugfs_remove_recursive(vcpu->debugfs_dentry);
d40ccc62 2779 kvm_arch_vcpu_destroy(vcpu);
e529ef66
SC
2780vcpu_uninit:
2781 kvm_vcpu_uninit(vcpu);
2782vcpu_free:
2783 kmem_cache_free(kvm_vcpu_cache, vcpu);
6c7caebc
PB
2784vcpu_decrement:
2785 mutex_lock(&kvm->lock);
2786 kvm->created_vcpus--;
2787 mutex_unlock(&kvm->lock);
c5ea7660
AK
2788 return r;
2789}
2790
1961d276
AK
2791static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2792{
2793 if (sigset) {
2794 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2795 vcpu->sigset_active = 1;
2796 vcpu->sigset = *sigset;
2797 } else
2798 vcpu->sigset_active = 0;
2799 return 0;
2800}
2801
bccf2150
AK
2802static long kvm_vcpu_ioctl(struct file *filp,
2803 unsigned int ioctl, unsigned long arg)
6aa8b732 2804{
bccf2150 2805 struct kvm_vcpu *vcpu = filp->private_data;
2f366987 2806 void __user *argp = (void __user *)arg;
313a3dc7 2807 int r;
fa3795a7
DH
2808 struct kvm_fpu *fpu = NULL;
2809 struct kvm_sregs *kvm_sregs = NULL;
6aa8b732 2810
6d4e4c4f
AK
2811 if (vcpu->kvm->mm != current->mm)
2812 return -EIO;
2122ff5e 2813
2ea75be3
DM
2814 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2815 return -EINVAL;
2816
2122ff5e 2817 /*
5cb0944c
PB
2818 * Some architectures have vcpu ioctls that are asynchronous to vcpu
2819 * execution; mutex_lock() would break them.
2122ff5e 2820 */
5cb0944c
PB
2821 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
2822 if (r != -ENOIOCTLCMD)
9fc77441 2823 return r;
2122ff5e 2824
ec7660cc
CD
2825 if (mutex_lock_killable(&vcpu->mutex))
2826 return -EINTR;
6aa8b732 2827 switch (ioctl) {
0e4524a5
CB
2828 case KVM_RUN: {
2829 struct pid *oldpid;
f0fe5108
AK
2830 r = -EINVAL;
2831 if (arg)
2832 goto out;
0e4524a5 2833 oldpid = rcu_access_pointer(vcpu->pid);
71dbc8a9 2834 if (unlikely(oldpid != task_pid(current))) {
7a72f7a1 2835 /* The thread running this VCPU changed. */
bd2a6394 2836 struct pid *newpid;
f95ef0cd 2837
bd2a6394
CD
2838 r = kvm_arch_vcpu_run_pid_change(vcpu);
2839 if (r)
2840 break;
2841
2842 newpid = get_task_pid(current, PIDTYPE_PID);
7a72f7a1
CB
2843 rcu_assign_pointer(vcpu->pid, newpid);
2844 if (oldpid)
2845 synchronize_rcu();
2846 put_pid(oldpid);
2847 }
b6c7a5dc 2848 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
64be5007 2849 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
6aa8b732 2850 break;
0e4524a5 2851 }
6aa8b732 2852 case KVM_GET_REGS: {
3e4bb3ac 2853 struct kvm_regs *kvm_regs;
6aa8b732 2854
3e4bb3ac 2855 r = -ENOMEM;
b12ce36a 2856 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3e4bb3ac 2857 if (!kvm_regs)
6aa8b732 2858 goto out;
3e4bb3ac
XZ
2859 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2860 if (r)
2861 goto out_free1;
6aa8b732 2862 r = -EFAULT;
3e4bb3ac
XZ
2863 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2864 goto out_free1;
6aa8b732 2865 r = 0;
3e4bb3ac
XZ
2866out_free1:
2867 kfree(kvm_regs);
6aa8b732
AK
2868 break;
2869 }
2870 case KVM_SET_REGS: {
3e4bb3ac 2871 struct kvm_regs *kvm_regs;
6aa8b732 2872
3e4bb3ac 2873 r = -ENOMEM;
ff5c2c03
SL
2874 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2875 if (IS_ERR(kvm_regs)) {
2876 r = PTR_ERR(kvm_regs);
6aa8b732 2877 goto out;
ff5c2c03 2878 }
3e4bb3ac 2879 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3e4bb3ac 2880 kfree(kvm_regs);
6aa8b732
AK
2881 break;
2882 }
2883 case KVM_GET_SREGS: {
b12ce36a
BG
2884 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
2885 GFP_KERNEL_ACCOUNT);
fa3795a7
DH
2886 r = -ENOMEM;
2887 if (!kvm_sregs)
2888 goto out;
2889 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
6aa8b732
AK
2890 if (r)
2891 goto out;
2892 r = -EFAULT;
fa3795a7 2893 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
6aa8b732
AK
2894 goto out;
2895 r = 0;
2896 break;
2897 }
2898 case KVM_SET_SREGS: {
ff5c2c03
SL
2899 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
2900 if (IS_ERR(kvm_sregs)) {
2901 r = PTR_ERR(kvm_sregs);
18595411 2902 kvm_sregs = NULL;
6aa8b732 2903 goto out;
ff5c2c03 2904 }
fa3795a7 2905 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
6aa8b732
AK
2906 break;
2907 }
62d9f0db
MT
2908 case KVM_GET_MP_STATE: {
2909 struct kvm_mp_state mp_state;
2910
2911 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
2912 if (r)
2913 goto out;
2914 r = -EFAULT;
893bdbf1 2915 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
62d9f0db
MT
2916 goto out;
2917 r = 0;
2918 break;
2919 }
2920 case KVM_SET_MP_STATE: {
2921 struct kvm_mp_state mp_state;
2922
2923 r = -EFAULT;
893bdbf1 2924 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
62d9f0db
MT
2925 goto out;
2926 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
62d9f0db
MT
2927 break;
2928 }
6aa8b732
AK
2929 case KVM_TRANSLATE: {
2930 struct kvm_translation tr;
2931
2932 r = -EFAULT;
893bdbf1 2933 if (copy_from_user(&tr, argp, sizeof(tr)))
6aa8b732 2934 goto out;
8b006791 2935 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
6aa8b732
AK
2936 if (r)
2937 goto out;
2938 r = -EFAULT;
893bdbf1 2939 if (copy_to_user(argp, &tr, sizeof(tr)))
6aa8b732
AK
2940 goto out;
2941 r = 0;
2942 break;
2943 }
d0bfb940
JK
2944 case KVM_SET_GUEST_DEBUG: {
2945 struct kvm_guest_debug dbg;
6aa8b732
AK
2946
2947 r = -EFAULT;
893bdbf1 2948 if (copy_from_user(&dbg, argp, sizeof(dbg)))
6aa8b732 2949 goto out;
d0bfb940 2950 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
6aa8b732
AK
2951 break;
2952 }
1961d276
AK
2953 case KVM_SET_SIGNAL_MASK: {
2954 struct kvm_signal_mask __user *sigmask_arg = argp;
2955 struct kvm_signal_mask kvm_sigmask;
2956 sigset_t sigset, *p;
2957
2958 p = NULL;
2959 if (argp) {
2960 r = -EFAULT;
2961 if (copy_from_user(&kvm_sigmask, argp,
893bdbf1 2962 sizeof(kvm_sigmask)))
1961d276
AK
2963 goto out;
2964 r = -EINVAL;
893bdbf1 2965 if (kvm_sigmask.len != sizeof(sigset))
1961d276
AK
2966 goto out;
2967 r = -EFAULT;
2968 if (copy_from_user(&sigset, sigmask_arg->sigset,
893bdbf1 2969 sizeof(sigset)))
1961d276
AK
2970 goto out;
2971 p = &sigset;
2972 }
376d41ff 2973 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
1961d276
AK
2974 break;
2975 }
b8836737 2976 case KVM_GET_FPU: {
b12ce36a 2977 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
fa3795a7
DH
2978 r = -ENOMEM;
2979 if (!fpu)
2980 goto out;
2981 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
b8836737
AK
2982 if (r)
2983 goto out;
2984 r = -EFAULT;
fa3795a7 2985 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
b8836737
AK
2986 goto out;
2987 r = 0;
2988 break;
2989 }
2990 case KVM_SET_FPU: {
ff5c2c03
SL
2991 fpu = memdup_user(argp, sizeof(*fpu));
2992 if (IS_ERR(fpu)) {
2993 r = PTR_ERR(fpu);
18595411 2994 fpu = NULL;
b8836737 2995 goto out;
ff5c2c03 2996 }
fa3795a7 2997 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
b8836737
AK
2998 break;
2999 }
bccf2150 3000 default:
313a3dc7 3001 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
bccf2150
AK
3002 }
3003out:
ec7660cc 3004 mutex_unlock(&vcpu->mutex);
fa3795a7
DH
3005 kfree(fpu);
3006 kfree(kvm_sregs);
bccf2150
AK
3007 return r;
3008}
3009
de8e5d74 3010#ifdef CONFIG_KVM_COMPAT
1dda606c
AG
3011static long kvm_vcpu_compat_ioctl(struct file *filp,
3012 unsigned int ioctl, unsigned long arg)
3013{
3014 struct kvm_vcpu *vcpu = filp->private_data;
3015 void __user *argp = compat_ptr(arg);
3016 int r;
3017
3018 if (vcpu->kvm->mm != current->mm)
3019 return -EIO;
3020
3021 switch (ioctl) {
3022 case KVM_SET_SIGNAL_MASK: {
3023 struct kvm_signal_mask __user *sigmask_arg = argp;
3024 struct kvm_signal_mask kvm_sigmask;
1dda606c
AG
3025 sigset_t sigset;
3026
3027 if (argp) {
3028 r = -EFAULT;
3029 if (copy_from_user(&kvm_sigmask, argp,
893bdbf1 3030 sizeof(kvm_sigmask)))
1dda606c
AG
3031 goto out;
3032 r = -EINVAL;
3968cf62 3033 if (kvm_sigmask.len != sizeof(compat_sigset_t))
1dda606c
AG
3034 goto out;
3035 r = -EFAULT;
3968cf62 3036 if (get_compat_sigset(&sigset, (void *)sigmask_arg->sigset))
1dda606c 3037 goto out;
760a9a30
AC
3038 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3039 } else
3040 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
1dda606c
AG
3041 break;
3042 }
3043 default:
3044 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3045 }
3046
3047out:
3048 return r;
3049}
3050#endif
3051
a1cd3f08
CLG
3052static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3053{
3054 struct kvm_device *dev = filp->private_data;
3055
3056 if (dev->ops->mmap)
3057 return dev->ops->mmap(dev, vma);
3058
3059 return -ENODEV;
3060}
3061
852b6d57
SW
3062static int kvm_device_ioctl_attr(struct kvm_device *dev,
3063 int (*accessor)(struct kvm_device *dev,
3064 struct kvm_device_attr *attr),
3065 unsigned long arg)
3066{
3067 struct kvm_device_attr attr;
3068
3069 if (!accessor)
3070 return -EPERM;
3071
3072 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3073 return -EFAULT;
3074
3075 return accessor(dev, &attr);
3076}
3077
3078static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3079 unsigned long arg)
3080{
3081 struct kvm_device *dev = filp->private_data;
3082
ddba9180
SC
3083 if (dev->kvm->mm != current->mm)
3084 return -EIO;
3085
852b6d57
SW
3086 switch (ioctl) {
3087 case KVM_SET_DEVICE_ATTR:
3088 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3089 case KVM_GET_DEVICE_ATTR:
3090 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3091 case KVM_HAS_DEVICE_ATTR:
3092 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3093 default:
3094 if (dev->ops->ioctl)
3095 return dev->ops->ioctl(dev, ioctl, arg);
3096
3097 return -ENOTTY;
3098 }
3099}
3100
852b6d57
SW
3101static int kvm_device_release(struct inode *inode, struct file *filp)
3102{
3103 struct kvm_device *dev = filp->private_data;
3104 struct kvm *kvm = dev->kvm;
3105
2bde9b3e
CLG
3106 if (dev->ops->release) {
3107 mutex_lock(&kvm->lock);
3108 list_del(&dev->vm_node);
3109 dev->ops->release(dev);
3110 mutex_unlock(&kvm->lock);
3111 }
3112
852b6d57
SW
3113 kvm_put_kvm(kvm);
3114 return 0;
3115}
3116
3117static const struct file_operations kvm_device_fops = {
3118 .unlocked_ioctl = kvm_device_ioctl,
3119 .release = kvm_device_release,
7ddfd3e0 3120 KVM_COMPAT(kvm_device_ioctl),
a1cd3f08 3121 .mmap = kvm_device_mmap,
852b6d57
SW
3122};
3123
3124struct kvm_device *kvm_device_from_filp(struct file *filp)
3125{
3126 if (filp->f_op != &kvm_device_fops)
3127 return NULL;
3128
3129 return filp->private_data;
3130}
3131
8538cb22 3132static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
5df554ad 3133#ifdef CONFIG_KVM_MPIC
d60eacb0
WD
3134 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3135 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
5975a2e0 3136#endif
d60eacb0
WD
3137};
3138
8538cb22 3139int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
d60eacb0
WD
3140{
3141 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3142 return -ENOSPC;
3143
3144 if (kvm_device_ops_table[type] != NULL)
3145 return -EEXIST;
3146
3147 kvm_device_ops_table[type] = ops;
3148 return 0;
3149}
3150
571ee1b6
WL
3151void kvm_unregister_device_ops(u32 type)
3152{
3153 if (kvm_device_ops_table[type] != NULL)
3154 kvm_device_ops_table[type] = NULL;
3155}
3156
852b6d57
SW
3157static int kvm_ioctl_create_device(struct kvm *kvm,
3158 struct kvm_create_device *cd)
3159{
8538cb22 3160 const struct kvm_device_ops *ops = NULL;
852b6d57
SW
3161 struct kvm_device *dev;
3162 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
1d487e9b 3163 int type;
852b6d57
SW
3164 int ret;
3165
d60eacb0
WD
3166 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3167 return -ENODEV;
3168
1d487e9b
PB
3169 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3170 ops = kvm_device_ops_table[type];
d60eacb0 3171 if (ops == NULL)
852b6d57 3172 return -ENODEV;
852b6d57
SW
3173
3174 if (test)
3175 return 0;
3176
b12ce36a 3177 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
852b6d57
SW
3178 if (!dev)
3179 return -ENOMEM;
3180
3181 dev->ops = ops;
3182 dev->kvm = kvm;
852b6d57 3183
a28ebea2 3184 mutex_lock(&kvm->lock);
1d487e9b 3185 ret = ops->create(dev, type);
852b6d57 3186 if (ret < 0) {
a28ebea2 3187 mutex_unlock(&kvm->lock);
852b6d57
SW
3188 kfree(dev);
3189 return ret;
3190 }
a28ebea2
CD
3191 list_add(&dev->vm_node, &kvm->devices);
3192 mutex_unlock(&kvm->lock);
852b6d57 3193
023e9fdd
CD
3194 if (ops->init)
3195 ops->init(dev);
3196
cfa39381 3197 kvm_get_kvm(kvm);
24009b05 3198 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
852b6d57 3199 if (ret < 0) {
149487bd 3200 kvm_put_kvm_no_destroy(kvm);
a28ebea2
CD
3201 mutex_lock(&kvm->lock);
3202 list_del(&dev->vm_node);
3203 mutex_unlock(&kvm->lock);
a0f1d21c 3204 ops->destroy(dev);
852b6d57
SW
3205 return ret;
3206 }
3207
852b6d57
SW
3208 cd->fd = ret;
3209 return 0;
3210}
3211
92b591a4
AG
3212static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3213{
3214 switch (arg) {
3215 case KVM_CAP_USER_MEMORY:
3216 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3217 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
92b591a4
AG
3218 case KVM_CAP_INTERNAL_ERROR_DATA:
3219#ifdef CONFIG_HAVE_KVM_MSI
3220 case KVM_CAP_SIGNAL_MSI:
3221#endif
297e2105 3222#ifdef CONFIG_HAVE_KVM_IRQFD
dc9be0fa 3223 case KVM_CAP_IRQFD:
92b591a4
AG
3224 case KVM_CAP_IRQFD_RESAMPLE:
3225#endif
e9ea5069 3226 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
92b591a4 3227 case KVM_CAP_CHECK_EXTENSION_VM:
e5d83c74 3228 case KVM_CAP_ENABLE_CAP_VM:
2a31b9db 3229#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
d7547c55 3230 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
2a31b9db 3231#endif
92b591a4 3232 return 1;
4b4357e0 3233#ifdef CONFIG_KVM_MMIO
30422558
PB
3234 case KVM_CAP_COALESCED_MMIO:
3235 return KVM_COALESCED_MMIO_PAGE_OFFSET;
0804c849
PH
3236 case KVM_CAP_COALESCED_PIO:
3237 return 1;
30422558 3238#endif
92b591a4
AG
3239#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3240 case KVM_CAP_IRQ_ROUTING:
3241 return KVM_MAX_IRQ_ROUTES;
f481b069
PB
3242#endif
3243#if KVM_ADDRESS_SPACE_NUM > 1
3244 case KVM_CAP_MULTI_ADDRESS_SPACE:
3245 return KVM_ADDRESS_SPACE_NUM;
92b591a4 3246#endif
c110ae57
PB
3247 case KVM_CAP_NR_MEMSLOTS:
3248 return KVM_USER_MEM_SLOTS;
92b591a4
AG
3249 default:
3250 break;
3251 }
3252 return kvm_vm_ioctl_check_extension(kvm, arg);
3253}
3254
e5d83c74
PB
3255int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3256 struct kvm_enable_cap *cap)
3257{
3258 return -EINVAL;
3259}
3260
3261static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
3262 struct kvm_enable_cap *cap)
3263{
3264 switch (cap->cap) {
2a31b9db 3265#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
d7547c55 3266 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
2a31b9db
PB
3267 if (cap->flags || (cap->args[0] & ~1))
3268 return -EINVAL;
3269 kvm->manual_dirty_log_protect = cap->args[0];
3270 return 0;
3271#endif
e5d83c74
PB
3272 default:
3273 return kvm_vm_ioctl_enable_cap(kvm, cap);
3274 }
3275}
3276
bccf2150
AK
3277static long kvm_vm_ioctl(struct file *filp,
3278 unsigned int ioctl, unsigned long arg)
3279{
3280 struct kvm *kvm = filp->private_data;
3281 void __user *argp = (void __user *)arg;
1fe779f8 3282 int r;
bccf2150 3283
6d4e4c4f
AK
3284 if (kvm->mm != current->mm)
3285 return -EIO;
bccf2150
AK
3286 switch (ioctl) {
3287 case KVM_CREATE_VCPU:
3288 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
bccf2150 3289 break;
e5d83c74
PB
3290 case KVM_ENABLE_CAP: {
3291 struct kvm_enable_cap cap;
3292
3293 r = -EFAULT;
3294 if (copy_from_user(&cap, argp, sizeof(cap)))
3295 goto out;
3296 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
3297 break;
3298 }
6fc138d2
IE
3299 case KVM_SET_USER_MEMORY_REGION: {
3300 struct kvm_userspace_memory_region kvm_userspace_mem;
3301
3302 r = -EFAULT;
3303 if (copy_from_user(&kvm_userspace_mem, argp,
893bdbf1 3304 sizeof(kvm_userspace_mem)))
6fc138d2
IE
3305 goto out;
3306
47ae31e2 3307 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
6aa8b732
AK
3308 break;
3309 }
3310 case KVM_GET_DIRTY_LOG: {
3311 struct kvm_dirty_log log;
3312
3313 r = -EFAULT;
893bdbf1 3314 if (copy_from_user(&log, argp, sizeof(log)))
6aa8b732 3315 goto out;
2c6f5df9 3316 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
6aa8b732
AK
3317 break;
3318 }
2a31b9db
PB
3319#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3320 case KVM_CLEAR_DIRTY_LOG: {
3321 struct kvm_clear_dirty_log log;
3322
3323 r = -EFAULT;
3324 if (copy_from_user(&log, argp, sizeof(log)))
3325 goto out;
3326 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3327 break;
3328 }
3329#endif
4b4357e0 3330#ifdef CONFIG_KVM_MMIO
5f94c174
LV
3331 case KVM_REGISTER_COALESCED_MMIO: {
3332 struct kvm_coalesced_mmio_zone zone;
f95ef0cd 3333
5f94c174 3334 r = -EFAULT;
893bdbf1 3335 if (copy_from_user(&zone, argp, sizeof(zone)))
5f94c174 3336 goto out;
5f94c174 3337 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
5f94c174
LV
3338 break;
3339 }
3340 case KVM_UNREGISTER_COALESCED_MMIO: {
3341 struct kvm_coalesced_mmio_zone zone;
f95ef0cd 3342
5f94c174 3343 r = -EFAULT;
893bdbf1 3344 if (copy_from_user(&zone, argp, sizeof(zone)))
5f94c174 3345 goto out;
5f94c174 3346 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
5f94c174
LV
3347 break;
3348 }
3349#endif
721eecbf
GH
3350 case KVM_IRQFD: {
3351 struct kvm_irqfd data;
3352
3353 r = -EFAULT;
893bdbf1 3354 if (copy_from_user(&data, argp, sizeof(data)))
721eecbf 3355 goto out;
d4db2935 3356 r = kvm_irqfd(kvm, &data);
721eecbf
GH
3357 break;
3358 }
d34e6b17
GH
3359 case KVM_IOEVENTFD: {
3360 struct kvm_ioeventfd data;
3361
3362 r = -EFAULT;
893bdbf1 3363 if (copy_from_user(&data, argp, sizeof(data)))
d34e6b17
GH
3364 goto out;
3365 r = kvm_ioeventfd(kvm, &data);
3366 break;
3367 }
07975ad3
JK
3368#ifdef CONFIG_HAVE_KVM_MSI
3369 case KVM_SIGNAL_MSI: {
3370 struct kvm_msi msi;
3371
3372 r = -EFAULT;
893bdbf1 3373 if (copy_from_user(&msi, argp, sizeof(msi)))
07975ad3
JK
3374 goto out;
3375 r = kvm_send_userspace_msi(kvm, &msi);
3376 break;
3377 }
23d43cf9
CD
3378#endif
3379#ifdef __KVM_HAVE_IRQ_LINE
3380 case KVM_IRQ_LINE_STATUS:
3381 case KVM_IRQ_LINE: {
3382 struct kvm_irq_level irq_event;
3383
3384 r = -EFAULT;
893bdbf1 3385 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
23d43cf9
CD
3386 goto out;
3387
aa2fbe6d
YZ
3388 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3389 ioctl == KVM_IRQ_LINE_STATUS);
23d43cf9
CD
3390 if (r)
3391 goto out;
3392
3393 r = -EFAULT;
3394 if (ioctl == KVM_IRQ_LINE_STATUS) {
893bdbf1 3395 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
23d43cf9
CD
3396 goto out;
3397 }
3398
3399 r = 0;
3400 break;
3401 }
73880c80 3402#endif
aa8d5944
AG
3403#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3404 case KVM_SET_GSI_ROUTING: {
3405 struct kvm_irq_routing routing;
3406 struct kvm_irq_routing __user *urouting;
f8c1b85b 3407 struct kvm_irq_routing_entry *entries = NULL;
aa8d5944
AG
3408
3409 r = -EFAULT;
3410 if (copy_from_user(&routing, argp, sizeof(routing)))
3411 goto out;
3412 r = -EINVAL;
5c0aea0e
DH
3413 if (!kvm_arch_can_set_irq_routing(kvm))
3414 goto out;
caf1ff26 3415 if (routing.nr > KVM_MAX_IRQ_ROUTES)
aa8d5944
AG
3416 goto out;
3417 if (routing.flags)
3418 goto out;
f8c1b85b
PB
3419 if (routing.nr) {
3420 r = -ENOMEM;
42bc47b3
KC
3421 entries = vmalloc(array_size(sizeof(*entries),
3422 routing.nr));
f8c1b85b
PB
3423 if (!entries)
3424 goto out;
3425 r = -EFAULT;
3426 urouting = argp;
3427 if (copy_from_user(entries, urouting->entries,
3428 routing.nr * sizeof(*entries)))
3429 goto out_free_irq_routing;
3430 }
aa8d5944
AG
3431 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3432 routing.flags);
a642a175 3433out_free_irq_routing:
aa8d5944
AG
3434 vfree(entries);
3435 break;
3436 }
3437#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
852b6d57
SW
3438 case KVM_CREATE_DEVICE: {
3439 struct kvm_create_device cd;
3440
3441 r = -EFAULT;
3442 if (copy_from_user(&cd, argp, sizeof(cd)))
3443 goto out;
3444
3445 r = kvm_ioctl_create_device(kvm, &cd);
3446 if (r)
3447 goto out;
3448
3449 r = -EFAULT;
3450 if (copy_to_user(argp, &cd, sizeof(cd)))
3451 goto out;
3452
3453 r = 0;
3454 break;
3455 }
92b591a4
AG
3456 case KVM_CHECK_EXTENSION:
3457 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3458 break;
f17abe9a 3459 default:
1fe779f8 3460 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
f17abe9a
AK
3461 }
3462out:
3463 return r;
3464}
3465
de8e5d74 3466#ifdef CONFIG_KVM_COMPAT
6ff5894c
AB
3467struct compat_kvm_dirty_log {
3468 __u32 slot;
3469 __u32 padding1;
3470 union {
3471 compat_uptr_t dirty_bitmap; /* one bit per page */
3472 __u64 padding2;
3473 };
3474};
3475
3476static long kvm_vm_compat_ioctl(struct file *filp,
3477 unsigned int ioctl, unsigned long arg)
3478{
3479 struct kvm *kvm = filp->private_data;
3480 int r;
3481
3482 if (kvm->mm != current->mm)
3483 return -EIO;
3484 switch (ioctl) {
3485 case KVM_GET_DIRTY_LOG: {
3486 struct compat_kvm_dirty_log compat_log;
3487 struct kvm_dirty_log log;
3488
6ff5894c
AB
3489 if (copy_from_user(&compat_log, (void __user *)arg,
3490 sizeof(compat_log)))
f6a3b168 3491 return -EFAULT;
6ff5894c
AB
3492 log.slot = compat_log.slot;
3493 log.padding1 = compat_log.padding1;
3494 log.padding2 = compat_log.padding2;
3495 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3496
3497 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
6ff5894c
AB
3498 break;
3499 }
3500 default:
3501 r = kvm_vm_ioctl(filp, ioctl, arg);
3502 }
6ff5894c
AB
3503 return r;
3504}
3505#endif
3506
3d3aab1b 3507static struct file_operations kvm_vm_fops = {
f17abe9a
AK
3508 .release = kvm_vm_release,
3509 .unlocked_ioctl = kvm_vm_ioctl,
6038f373 3510 .llseek = noop_llseek,
7ddfd3e0 3511 KVM_COMPAT(kvm_vm_compat_ioctl),
f17abe9a
AK
3512};
3513
e08b9637 3514static int kvm_dev_ioctl_create_vm(unsigned long type)
f17abe9a 3515{
aac87636 3516 int r;
f17abe9a 3517 struct kvm *kvm;
506cfba9 3518 struct file *file;
f17abe9a 3519
e08b9637 3520 kvm = kvm_create_vm(type);
d6d28168
AK
3521 if (IS_ERR(kvm))
3522 return PTR_ERR(kvm);
4b4357e0 3523#ifdef CONFIG_KVM_MMIO
6ce5a090 3524 r = kvm_coalesced_mmio_init(kvm);
78588335
ME
3525 if (r < 0)
3526 goto put_kvm;
6ce5a090 3527#endif
506cfba9 3528 r = get_unused_fd_flags(O_CLOEXEC);
78588335
ME
3529 if (r < 0)
3530 goto put_kvm;
3531
506cfba9
AV
3532 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3533 if (IS_ERR(file)) {
3534 put_unused_fd(r);
78588335
ME
3535 r = PTR_ERR(file);
3536 goto put_kvm;
506cfba9 3537 }
536a6f88 3538
525df861
PB
3539 /*
3540 * Don't call kvm_put_kvm anymore at this point; file->f_op is
3541 * already set, with ->release() being kvm_vm_release(). In error
3542 * cases it will be called by the final fput(file) and will take
3543 * care of doing kvm_put_kvm(kvm).
3544 */
536a6f88 3545 if (kvm_create_vm_debugfs(kvm, r) < 0) {
506cfba9
AV
3546 put_unused_fd(r);
3547 fput(file);
536a6f88
JF
3548 return -ENOMEM;
3549 }
286de8f6 3550 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
f17abe9a 3551
506cfba9 3552 fd_install(r, file);
aac87636 3553 return r;
78588335
ME
3554
3555put_kvm:
3556 kvm_put_kvm(kvm);
3557 return r;
f17abe9a
AK
3558}
3559
3560static long kvm_dev_ioctl(struct file *filp,
3561 unsigned int ioctl, unsigned long arg)
3562{
07c45a36 3563 long r = -EINVAL;
f17abe9a
AK
3564
3565 switch (ioctl) {
3566 case KVM_GET_API_VERSION:
f0fe5108
AK
3567 if (arg)
3568 goto out;
f17abe9a
AK
3569 r = KVM_API_VERSION;
3570 break;
3571 case KVM_CREATE_VM:
e08b9637 3572 r = kvm_dev_ioctl_create_vm(arg);
f17abe9a 3573 break;
018d00d2 3574 case KVM_CHECK_EXTENSION:
784aa3d7 3575 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
5d308f45 3576 break;
07c45a36 3577 case KVM_GET_VCPU_MMAP_SIZE:
07c45a36
AK
3578 if (arg)
3579 goto out;
adb1ff46
AK
3580 r = PAGE_SIZE; /* struct kvm_run */
3581#ifdef CONFIG_X86
3582 r += PAGE_SIZE; /* pio data page */
5f94c174 3583#endif
4b4357e0 3584#ifdef CONFIG_KVM_MMIO
5f94c174 3585 r += PAGE_SIZE; /* coalesced mmio ring page */
adb1ff46 3586#endif
07c45a36 3587 break;
d4c9ff2d
FEL
3588 case KVM_TRACE_ENABLE:
3589 case KVM_TRACE_PAUSE:
3590 case KVM_TRACE_DISABLE:
2023a29c 3591 r = -EOPNOTSUPP;
d4c9ff2d 3592 break;
6aa8b732 3593 default:
043405e1 3594 return kvm_arch_dev_ioctl(filp, ioctl, arg);
6aa8b732
AK
3595 }
3596out:
3597 return r;
3598}
3599
6aa8b732 3600static struct file_operations kvm_chardev_ops = {
6aa8b732 3601 .unlocked_ioctl = kvm_dev_ioctl,
6038f373 3602 .llseek = noop_llseek,
7ddfd3e0 3603 KVM_COMPAT(kvm_dev_ioctl),
6aa8b732
AK
3604};
3605
3606static struct miscdevice kvm_dev = {
bbe4432e 3607 KVM_MINOR,
6aa8b732
AK
3608 "kvm",
3609 &kvm_chardev_ops,
3610};
3611
75b7127c 3612static void hardware_enable_nolock(void *junk)
1b6c0168
AK
3613{
3614 int cpu = raw_smp_processor_id();
10474ae8 3615 int r;
1b6c0168 3616
7f59f492 3617 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
1b6c0168 3618 return;
10474ae8 3619
7f59f492 3620 cpumask_set_cpu(cpu, cpus_hardware_enabled);
10474ae8 3621
13a34e06 3622 r = kvm_arch_hardware_enable();
10474ae8
AG
3623
3624 if (r) {
3625 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3626 atomic_inc(&hardware_enable_failed);
1170adc6 3627 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
10474ae8 3628 }
1b6c0168
AK
3629}
3630
8c18b2d2 3631static int kvm_starting_cpu(unsigned int cpu)
75b7127c 3632{
4a937f96 3633 raw_spin_lock(&kvm_count_lock);
4fa92fb2
PB
3634 if (kvm_usage_count)
3635 hardware_enable_nolock(NULL);
4a937f96 3636 raw_spin_unlock(&kvm_count_lock);
8c18b2d2 3637 return 0;
75b7127c
TY
3638}
3639
3640static void hardware_disable_nolock(void *junk)
1b6c0168
AK
3641{
3642 int cpu = raw_smp_processor_id();
3643
7f59f492 3644 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
1b6c0168 3645 return;
7f59f492 3646 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
13a34e06 3647 kvm_arch_hardware_disable();
1b6c0168
AK
3648}
3649
8c18b2d2 3650static int kvm_dying_cpu(unsigned int cpu)
75b7127c 3651{
4a937f96 3652 raw_spin_lock(&kvm_count_lock);
4fa92fb2
PB
3653 if (kvm_usage_count)
3654 hardware_disable_nolock(NULL);
4a937f96 3655 raw_spin_unlock(&kvm_count_lock);
8c18b2d2 3656 return 0;
75b7127c
TY
3657}
3658
10474ae8
AG
3659static void hardware_disable_all_nolock(void)
3660{
3661 BUG_ON(!kvm_usage_count);
3662
3663 kvm_usage_count--;
3664 if (!kvm_usage_count)
75b7127c 3665 on_each_cpu(hardware_disable_nolock, NULL, 1);
10474ae8
AG
3666}
3667
3668static void hardware_disable_all(void)
3669{
4a937f96 3670 raw_spin_lock(&kvm_count_lock);
10474ae8 3671 hardware_disable_all_nolock();
4a937f96 3672 raw_spin_unlock(&kvm_count_lock);
10474ae8
AG
3673}
3674
3675static int hardware_enable_all(void)
3676{
3677 int r = 0;
3678
4a937f96 3679 raw_spin_lock(&kvm_count_lock);
10474ae8
AG
3680
3681 kvm_usage_count++;
3682 if (kvm_usage_count == 1) {
3683 atomic_set(&hardware_enable_failed, 0);
75b7127c 3684 on_each_cpu(hardware_enable_nolock, NULL, 1);
10474ae8
AG
3685
3686 if (atomic_read(&hardware_enable_failed)) {
3687 hardware_disable_all_nolock();
3688 r = -EBUSY;
3689 }
3690 }
3691
4a937f96 3692 raw_spin_unlock(&kvm_count_lock);
10474ae8
AG
3693
3694 return r;
3695}
3696
9a2b85c6 3697static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
d77c26fc 3698 void *v)
9a2b85c6 3699{
8e1c1815
SY
3700 /*
3701 * Some (well, at least mine) BIOSes hang on reboot if
3702 * in vmx root mode.
3703 *
3704 * And Intel TXT required VMX off for all cpu when system shutdown.
3705 */
1170adc6 3706 pr_info("kvm: exiting hardware virtualization\n");
8e1c1815 3707 kvm_rebooting = true;
75b7127c 3708 on_each_cpu(hardware_disable_nolock, NULL, 1);
9a2b85c6
RR
3709 return NOTIFY_OK;
3710}
3711
3712static struct notifier_block kvm_reboot_notifier = {
3713 .notifier_call = kvm_reboot,
3714 .priority = 0,
3715};
3716
e93f8a0f 3717static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
2eeb2e94
GH
3718{
3719 int i;
3720
3721 for (i = 0; i < bus->dev_count; i++) {
743eeb0b 3722 struct kvm_io_device *pos = bus->range[i].dev;
2eeb2e94
GH
3723
3724 kvm_iodevice_destructor(pos);
3725 }
e93f8a0f 3726 kfree(bus);
2eeb2e94
GH
3727}
3728
c21fbff1 3729static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
20e87b72 3730 const struct kvm_io_range *r2)
743eeb0b 3731{
8f4216c7
JW
3732 gpa_t addr1 = r1->addr;
3733 gpa_t addr2 = r2->addr;
3734
3735 if (addr1 < addr2)
743eeb0b 3736 return -1;
8f4216c7
JW
3737
3738 /* If r2->len == 0, match the exact address. If r2->len != 0,
3739 * accept any overlapping write. Any order is acceptable for
3740 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3741 * we process all of them.
3742 */
3743 if (r2->len) {
3744 addr1 += r1->len;
3745 addr2 += r2->len;
3746 }
3747
3748 if (addr1 > addr2)
743eeb0b 3749 return 1;
8f4216c7 3750
743eeb0b
SL
3751 return 0;
3752}
3753
a343c9b7
PB
3754static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3755{
c21fbff1 3756 return kvm_io_bus_cmp(p1, p2);
a343c9b7
PB
3757}
3758
39369f7a 3759static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
743eeb0b
SL
3760 gpa_t addr, int len)
3761{
3762 struct kvm_io_range *range, key;
3763 int off;
3764
3765 key = (struct kvm_io_range) {
3766 .addr = addr,
3767 .len = len,
3768 };
3769
3770 range = bsearch(&key, bus->range, bus->dev_count,
3771 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3772 if (range == NULL)
3773 return -ENOENT;
3774
3775 off = range - bus->range;
3776
c21fbff1 3777 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
743eeb0b
SL
3778 off--;
3779
3780 return off;
3781}
3782
e32edf4f 3783static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
126a5af5
CH
3784 struct kvm_io_range *range, const void *val)
3785{
3786 int idx;
3787
3788 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3789 if (idx < 0)
3790 return -EOPNOTSUPP;
3791
3792 while (idx < bus->dev_count &&
c21fbff1 3793 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
e32edf4f 3794 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
126a5af5
CH
3795 range->len, val))
3796 return idx;
3797 idx++;
3798 }
3799
3800 return -EOPNOTSUPP;
3801}
3802
bda9020e 3803/* kvm_io_bus_write - called under kvm->slots_lock */
e32edf4f 3804int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
bda9020e 3805 int len, const void *val)
2eeb2e94 3806{
90d83dc3 3807 struct kvm_io_bus *bus;
743eeb0b 3808 struct kvm_io_range range;
126a5af5 3809 int r;
743eeb0b
SL
3810
3811 range = (struct kvm_io_range) {
3812 .addr = addr,
3813 .len = len,
3814 };
90d83dc3 3815
e32edf4f 3816 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
90db1043
DH
3817 if (!bus)
3818 return -ENOMEM;
e32edf4f 3819 r = __kvm_io_bus_write(vcpu, bus, &range, val);
126a5af5
CH
3820 return r < 0 ? r : 0;
3821}
a2420107 3822EXPORT_SYMBOL_GPL(kvm_io_bus_write);
126a5af5
CH
3823
3824/* kvm_io_bus_write_cookie - called under kvm->slots_lock */
e32edf4f
NN
3825int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
3826 gpa_t addr, int len, const void *val, long cookie)
126a5af5
CH
3827{
3828 struct kvm_io_bus *bus;
3829 struct kvm_io_range range;
3830
3831 range = (struct kvm_io_range) {
3832 .addr = addr,
3833 .len = len,
3834 };
3835
e32edf4f 3836 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
90db1043
DH
3837 if (!bus)
3838 return -ENOMEM;
126a5af5
CH
3839
3840 /* First try the device referenced by cookie. */
3841 if ((cookie >= 0) && (cookie < bus->dev_count) &&
c21fbff1 3842 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
e32edf4f 3843 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
126a5af5
CH
3844 val))
3845 return cookie;
3846
3847 /*
3848 * cookie contained garbage; fall back to search and return the
3849 * correct cookie value.
3850 */
e32edf4f 3851 return __kvm_io_bus_write(vcpu, bus, &range, val);
126a5af5
CH
3852}
3853
e32edf4f
NN
3854static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3855 struct kvm_io_range *range, void *val)
126a5af5
CH
3856{
3857 int idx;
3858
3859 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
743eeb0b
SL
3860 if (idx < 0)
3861 return -EOPNOTSUPP;
3862
3863 while (idx < bus->dev_count &&
c21fbff1 3864 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
e32edf4f 3865 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
126a5af5
CH
3866 range->len, val))
3867 return idx;
743eeb0b
SL
3868 idx++;
3869 }
3870
bda9020e
MT
3871 return -EOPNOTSUPP;
3872}
2eeb2e94 3873
bda9020e 3874/* kvm_io_bus_read - called under kvm->slots_lock */
e32edf4f 3875int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
e93f8a0f 3876 int len, void *val)
bda9020e 3877{
90d83dc3 3878 struct kvm_io_bus *bus;
743eeb0b 3879 struct kvm_io_range range;
126a5af5 3880 int r;
743eeb0b
SL
3881
3882 range = (struct kvm_io_range) {
3883 .addr = addr,
3884 .len = len,
3885 };
e93f8a0f 3886
e32edf4f 3887 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
90db1043
DH
3888 if (!bus)
3889 return -ENOMEM;
e32edf4f 3890 r = __kvm_io_bus_read(vcpu, bus, &range, val);
126a5af5
CH
3891 return r < 0 ? r : 0;
3892}
743eeb0b 3893
79fac95e 3894/* Caller must hold slots_lock. */
743eeb0b
SL
3895int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3896 int len, struct kvm_io_device *dev)
6c474694 3897{
d4c67a7a 3898 int i;
e93f8a0f 3899 struct kvm_io_bus *new_bus, *bus;
d4c67a7a 3900 struct kvm_io_range range;
090b7aff 3901
4a12f951 3902 bus = kvm_get_bus(kvm, bus_idx);
90db1043
DH
3903 if (!bus)
3904 return -ENOMEM;
3905
6ea34c9b
AK
3906 /* exclude ioeventfd which is limited by maximum fd */
3907 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
090b7aff 3908 return -ENOSPC;
2eeb2e94 3909
90952cd3 3910 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
b12ce36a 3911 GFP_KERNEL_ACCOUNT);
e93f8a0f
MT
3912 if (!new_bus)
3913 return -ENOMEM;
d4c67a7a
GH
3914
3915 range = (struct kvm_io_range) {
3916 .addr = addr,
3917 .len = len,
3918 .dev = dev,
3919 };
3920
3921 for (i = 0; i < bus->dev_count; i++)
3922 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
3923 break;
3924
3925 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3926 new_bus->dev_count++;
3927 new_bus->range[i] = range;
3928 memcpy(new_bus->range + i + 1, bus->range + i,
3929 (bus->dev_count - i) * sizeof(struct kvm_io_range));
e93f8a0f
MT
3930 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3931 synchronize_srcu_expedited(&kvm->srcu);
3932 kfree(bus);
090b7aff
GH
3933
3934 return 0;
3935}
3936
79fac95e 3937/* Caller must hold slots_lock. */
90db1043
DH
3938void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3939 struct kvm_io_device *dev)
090b7aff 3940{
90db1043 3941 int i;
e93f8a0f 3942 struct kvm_io_bus *new_bus, *bus;
090b7aff 3943
4a12f951 3944 bus = kvm_get_bus(kvm, bus_idx);
df630b8c 3945 if (!bus)
90db1043 3946 return;
df630b8c 3947
a1300716
AK
3948 for (i = 0; i < bus->dev_count; i++)
3949 if (bus->range[i].dev == dev) {
090b7aff
GH
3950 break;
3951 }
e93f8a0f 3952
90db1043
DH
3953 if (i == bus->dev_count)
3954 return;
a1300716 3955
90952cd3 3956 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
b12ce36a 3957 GFP_KERNEL_ACCOUNT);
90db1043
DH
3958 if (!new_bus) {
3959 pr_err("kvm: failed to shrink bus, removing it completely\n");
3960 goto broken;
3961 }
a1300716
AK
3962
3963 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3964 new_bus->dev_count--;
3965 memcpy(new_bus->range + i, bus->range + i + 1,
3966 (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
e93f8a0f 3967
90db1043 3968broken:
e93f8a0f
MT
3969 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3970 synchronize_srcu_expedited(&kvm->srcu);
3971 kfree(bus);
90db1043 3972 return;
2eeb2e94
GH
3973}
3974
8a39d006
AP
3975struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3976 gpa_t addr)
3977{
3978 struct kvm_io_bus *bus;
3979 int dev_idx, srcu_idx;
3980 struct kvm_io_device *iodev = NULL;
3981
3982 srcu_idx = srcu_read_lock(&kvm->srcu);
3983
3984 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
90db1043
DH
3985 if (!bus)
3986 goto out_unlock;
8a39d006
AP
3987
3988 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
3989 if (dev_idx < 0)
3990 goto out_unlock;
3991
3992 iodev = bus->range[dev_idx].dev;
3993
3994out_unlock:
3995 srcu_read_unlock(&kvm->srcu, srcu_idx);
3996
3997 return iodev;
3998}
3999EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4000
536a6f88
JF
4001static int kvm_debugfs_open(struct inode *inode, struct file *file,
4002 int (*get)(void *, u64 *), int (*set)(void *, u64),
4003 const char *fmt)
4004{
4005 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4006 inode->i_private;
4007
4008 /* The debugfs files are a reference to the kvm struct which
4009 * is still valid when kvm_destroy_vm is called.
4010 * To avoid the race between open and the removal of the debugfs
4011 * directory we test against the users count.
4012 */
e3736c3e 4013 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
536a6f88
JF
4014 return -ENOENT;
4015
833b45de 4016 if (simple_attr_open(inode, file, get,
09cbcef6
MP
4017 KVM_DBGFS_GET_MODE(stat_data->dbgfs_item) & 0222
4018 ? set : NULL,
4019 fmt)) {
536a6f88
JF
4020 kvm_put_kvm(stat_data->kvm);
4021 return -ENOMEM;
4022 }
4023
4024 return 0;
4025}
4026
4027static int kvm_debugfs_release(struct inode *inode, struct file *file)
4028{
4029 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4030 inode->i_private;
4031
4032 simple_attr_release(inode, file);
4033 kvm_put_kvm(stat_data->kvm);
4034
4035 return 0;
4036}
4037
09cbcef6 4038static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
536a6f88 4039{
09cbcef6 4040 *val = *(ulong *)((void *)kvm + offset);
536a6f88 4041
09cbcef6
MP
4042 return 0;
4043}
4044
4045static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
4046{
4047 *(ulong *)((void *)kvm + offset) = 0;
536a6f88
JF
4048
4049 return 0;
4050}
4051
09cbcef6 4052static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
ce35ef27 4053{
09cbcef6
MP
4054 int i;
4055 struct kvm_vcpu *vcpu;
ce35ef27 4056
09cbcef6 4057 *val = 0;
ce35ef27 4058
09cbcef6
MP
4059 kvm_for_each_vcpu(i, vcpu, kvm)
4060 *val += *(u64 *)((void *)vcpu + offset);
ce35ef27
SJS
4061
4062 return 0;
4063}
4064
09cbcef6 4065static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
536a6f88 4066{
09cbcef6
MP
4067 int i;
4068 struct kvm_vcpu *vcpu;
536a6f88 4069
09cbcef6
MP
4070 kvm_for_each_vcpu(i, vcpu, kvm)
4071 *(u64 *)((void *)vcpu + offset) = 0;
4072
4073 return 0;
4074}
536a6f88 4075
09cbcef6 4076static int kvm_stat_data_get(void *data, u64 *val)
536a6f88 4077{
09cbcef6 4078 int r = -EFAULT;
536a6f88 4079 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
536a6f88 4080
09cbcef6
MP
4081 switch (stat_data->dbgfs_item->kind) {
4082 case KVM_STAT_VM:
4083 r = kvm_get_stat_per_vm(stat_data->kvm,
4084 stat_data->dbgfs_item->offset, val);
4085 break;
4086 case KVM_STAT_VCPU:
4087 r = kvm_get_stat_per_vcpu(stat_data->kvm,
4088 stat_data->dbgfs_item->offset, val);
4089 break;
4090 }
536a6f88 4091
09cbcef6 4092 return r;
536a6f88
JF
4093}
4094
09cbcef6 4095static int kvm_stat_data_clear(void *data, u64 val)
ce35ef27 4096{
09cbcef6 4097 int r = -EFAULT;
ce35ef27 4098 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
ce35ef27
SJS
4099
4100 if (val)
4101 return -EINVAL;
4102
09cbcef6
MP
4103 switch (stat_data->dbgfs_item->kind) {
4104 case KVM_STAT_VM:
4105 r = kvm_clear_stat_per_vm(stat_data->kvm,
4106 stat_data->dbgfs_item->offset);
4107 break;
4108 case KVM_STAT_VCPU:
4109 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
4110 stat_data->dbgfs_item->offset);
4111 break;
4112 }
ce35ef27 4113
09cbcef6 4114 return r;
ce35ef27
SJS
4115}
4116
09cbcef6 4117static int kvm_stat_data_open(struct inode *inode, struct file *file)
536a6f88
JF
4118{
4119 __simple_attr_check_format("%llu\n", 0ull);
09cbcef6
MP
4120 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
4121 kvm_stat_data_clear, "%llu\n");
536a6f88
JF
4122}
4123
09cbcef6
MP
4124static const struct file_operations stat_fops_per_vm = {
4125 .owner = THIS_MODULE,
4126 .open = kvm_stat_data_open,
536a6f88 4127 .release = kvm_debugfs_release,
09cbcef6
MP
4128 .read = simple_attr_read,
4129 .write = simple_attr_write,
4130 .llseek = no_llseek,
536a6f88
JF
4131};
4132
8b88b099 4133static int vm_stat_get(void *_offset, u64 *val)
ba1389b7
AK
4134{
4135 unsigned offset = (long)_offset;
ba1389b7 4136 struct kvm *kvm;
536a6f88 4137 u64 tmp_val;
ba1389b7 4138
8b88b099 4139 *val = 0;
0d9ce162 4140 mutex_lock(&kvm_lock);
536a6f88 4141 list_for_each_entry(kvm, &vm_list, vm_list) {
09cbcef6 4142 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
536a6f88
JF
4143 *val += tmp_val;
4144 }
0d9ce162 4145 mutex_unlock(&kvm_lock);
8b88b099 4146 return 0;
ba1389b7
AK
4147}
4148
ce35ef27
SJS
4149static int vm_stat_clear(void *_offset, u64 val)
4150{
4151 unsigned offset = (long)_offset;
4152 struct kvm *kvm;
ce35ef27
SJS
4153
4154 if (val)
4155 return -EINVAL;
4156
0d9ce162 4157 mutex_lock(&kvm_lock);
ce35ef27 4158 list_for_each_entry(kvm, &vm_list, vm_list) {
09cbcef6 4159 kvm_clear_stat_per_vm(kvm, offset);
ce35ef27 4160 }
0d9ce162 4161 mutex_unlock(&kvm_lock);
ce35ef27
SJS
4162
4163 return 0;
4164}
4165
4166DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
ba1389b7 4167
8b88b099 4168static int vcpu_stat_get(void *_offset, u64 *val)
1165f5fe
AK
4169{
4170 unsigned offset = (long)_offset;
1165f5fe 4171 struct kvm *kvm;
536a6f88 4172 u64 tmp_val;
1165f5fe 4173
8b88b099 4174 *val = 0;
0d9ce162 4175 mutex_lock(&kvm_lock);
536a6f88 4176 list_for_each_entry(kvm, &vm_list, vm_list) {
09cbcef6 4177 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
536a6f88
JF
4178 *val += tmp_val;
4179 }
0d9ce162 4180 mutex_unlock(&kvm_lock);
8b88b099 4181 return 0;
1165f5fe
AK
4182}
4183
ce35ef27
SJS
4184static int vcpu_stat_clear(void *_offset, u64 val)
4185{
4186 unsigned offset = (long)_offset;
4187 struct kvm *kvm;
ce35ef27
SJS
4188
4189 if (val)
4190 return -EINVAL;
4191
0d9ce162 4192 mutex_lock(&kvm_lock);
ce35ef27 4193 list_for_each_entry(kvm, &vm_list, vm_list) {
09cbcef6 4194 kvm_clear_stat_per_vcpu(kvm, offset);
ce35ef27 4195 }
0d9ce162 4196 mutex_unlock(&kvm_lock);
ce35ef27
SJS
4197
4198 return 0;
4199}
4200
4201DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4202 "%llu\n");
ba1389b7 4203
828c0950 4204static const struct file_operations *stat_fops[] = {
ba1389b7
AK
4205 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4206 [KVM_STAT_VM] = &vm_stat_fops,
4207};
1165f5fe 4208
286de8f6
CI
4209static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4210{
4211 struct kobj_uevent_env *env;
286de8f6
CI
4212 unsigned long long created, active;
4213
4214 if (!kvm_dev.this_device || !kvm)
4215 return;
4216
0d9ce162 4217 mutex_lock(&kvm_lock);
286de8f6
CI
4218 if (type == KVM_EVENT_CREATE_VM) {
4219 kvm_createvm_count++;
4220 kvm_active_vms++;
4221 } else if (type == KVM_EVENT_DESTROY_VM) {
4222 kvm_active_vms--;
4223 }
4224 created = kvm_createvm_count;
4225 active = kvm_active_vms;
0d9ce162 4226 mutex_unlock(&kvm_lock);
286de8f6 4227
b12ce36a 4228 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
286de8f6
CI
4229 if (!env)
4230 return;
4231
4232 add_uevent_var(env, "CREATED=%llu", created);
4233 add_uevent_var(env, "COUNT=%llu", active);
4234
fdeaf7e3 4235 if (type == KVM_EVENT_CREATE_VM) {
286de8f6 4236 add_uevent_var(env, "EVENT=create");
fdeaf7e3
CI
4237 kvm->userspace_pid = task_pid_nr(current);
4238 } else if (type == KVM_EVENT_DESTROY_VM) {
286de8f6 4239 add_uevent_var(env, "EVENT=destroy");
fdeaf7e3
CI
4240 }
4241 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
286de8f6 4242
8ed0579c 4243 if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
b12ce36a 4244 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
fdeaf7e3
CI
4245
4246 if (p) {
4247 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4248 if (!IS_ERR(tmp))
4249 add_uevent_var(env, "STATS_PATH=%s", tmp);
4250 kfree(p);
286de8f6
CI
4251 }
4252 }
4253 /* no need for checks, since we are adding at most only 5 keys */
4254 env->envp[env->envp_idx++] = NULL;
4255 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4256 kfree(env);
286de8f6
CI
4257}
4258
929f45e3 4259static void kvm_init_debug(void)
6aa8b732
AK
4260{
4261 struct kvm_stats_debugfs_item *p;
4262
76f7c879 4263 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4f69b680 4264
536a6f88
JF
4265 kvm_debugfs_num_entries = 0;
4266 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
09cbcef6
MP
4267 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
4268 kvm_debugfs_dir, (void *)(long)p->offset,
929f45e3 4269 stat_fops[p->kind]);
4f69b680 4270 }
6aa8b732
AK
4271}
4272
fb3600cc 4273static int kvm_suspend(void)
59ae6c6b 4274{
10474ae8 4275 if (kvm_usage_count)
75b7127c 4276 hardware_disable_nolock(NULL);
59ae6c6b
AK
4277 return 0;
4278}
4279
fb3600cc 4280static void kvm_resume(void)
59ae6c6b 4281{
ca84d1a2 4282 if (kvm_usage_count) {
2eb06c30
WL
4283#ifdef CONFIG_LOCKDEP
4284 WARN_ON(lockdep_is_held(&kvm_count_lock));
4285#endif
75b7127c 4286 hardware_enable_nolock(NULL);
ca84d1a2 4287 }
59ae6c6b
AK
4288}
4289
fb3600cc 4290static struct syscore_ops kvm_syscore_ops = {
59ae6c6b
AK
4291 .suspend = kvm_suspend,
4292 .resume = kvm_resume,
4293};
4294
15ad7146
AK
4295static inline
4296struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4297{
4298 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4299}
4300
4301static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4302{
4303 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
f95ef0cd 4304
046ddeed 4305 WRITE_ONCE(vcpu->preempted, false);
d73eb57b 4306 WRITE_ONCE(vcpu->ready, false);
15ad7146 4307
e790d9ef
RK
4308 kvm_arch_sched_in(vcpu, cpu);
4309
e9b11c17 4310 kvm_arch_vcpu_load(vcpu, cpu);
15ad7146
AK
4311}
4312
4313static void kvm_sched_out(struct preempt_notifier *pn,
4314 struct task_struct *next)
4315{
4316 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4317
d73eb57b 4318 if (current->state == TASK_RUNNING) {
046ddeed 4319 WRITE_ONCE(vcpu->preempted, true);
d73eb57b
WL
4320 WRITE_ONCE(vcpu->ready, true);
4321 }
e9b11c17 4322 kvm_arch_vcpu_put(vcpu);
15ad7146
AK
4323}
4324
f257d6dc
SC
4325static void check_processor_compat(void *rtn)
4326{
4327 *(int *)rtn = kvm_arch_check_processor_compat();
4328}
4329
0ee75bea 4330int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
c16f862d 4331 struct module *module)
6aa8b732
AK
4332{
4333 int r;
002c7f7c 4334 int cpu;
6aa8b732 4335
f8c16bba
ZX
4336 r = kvm_arch_init(opaque);
4337 if (r)
d2308784 4338 goto out_fail;
cb498ea2 4339
7dac16c3
AH
4340 /*
4341 * kvm_arch_init makes sure there's at most one caller
4342 * for architectures that support multiple implementations,
4343 * like intel and amd on x86.
36343f6e
PB
4344 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4345 * conflicts in case kvm is already setup for another implementation.
7dac16c3 4346 */
36343f6e
PB
4347 r = kvm_irqfd_init();
4348 if (r)
4349 goto out_irqfd;
7dac16c3 4350
8437a617 4351 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
7f59f492
RR
4352 r = -ENOMEM;
4353 goto out_free_0;
4354 }
4355
e9b11c17 4356 r = kvm_arch_hardware_setup();
6aa8b732 4357 if (r < 0)
faf0be22 4358 goto out_free_1;
6aa8b732 4359
002c7f7c 4360 for_each_online_cpu(cpu) {
f257d6dc 4361 smp_call_function_single(cpu, check_processor_compat, &r, 1);
002c7f7c 4362 if (r < 0)
faf0be22 4363 goto out_free_2;
002c7f7c
YS
4364 }
4365
73c1b41e 4366 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
8c18b2d2 4367 kvm_starting_cpu, kvm_dying_cpu);
774c47f1 4368 if (r)
d2308784 4369 goto out_free_2;
6aa8b732
AK
4370 register_reboot_notifier(&kvm_reboot_notifier);
4371
c16f862d 4372 /* A kmem cache lets us meet the alignment requirements of fx_save. */
0ee75bea
AK
4373 if (!vcpu_align)
4374 vcpu_align = __alignof__(struct kvm_vcpu);
46515736
PB
4375 kvm_vcpu_cache =
4376 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4377 SLAB_ACCOUNT,
4378 offsetof(struct kvm_vcpu, arch),
4379 sizeof_field(struct kvm_vcpu, arch),
4380 NULL);
c16f862d
RR
4381 if (!kvm_vcpu_cache) {
4382 r = -ENOMEM;
fb3600cc 4383 goto out_free_3;
c16f862d
RR
4384 }
4385
af585b92
GN
4386 r = kvm_async_pf_init();
4387 if (r)
4388 goto out_free;
4389
6aa8b732 4390 kvm_chardev_ops.owner = module;
3d3aab1b
CB
4391 kvm_vm_fops.owner = module;
4392 kvm_vcpu_fops.owner = module;
6aa8b732
AK
4393
4394 r = misc_register(&kvm_dev);
4395 if (r) {
1170adc6 4396 pr_err("kvm: misc device register failed\n");
af585b92 4397 goto out_unreg;
6aa8b732
AK
4398 }
4399
fb3600cc
RW
4400 register_syscore_ops(&kvm_syscore_ops);
4401
15ad7146
AK
4402 kvm_preempt_ops.sched_in = kvm_sched_in;
4403 kvm_preempt_ops.sched_out = kvm_sched_out;
4404
929f45e3 4405 kvm_init_debug();
0ea4ed8e 4406
3c3c29fd
PB
4407 r = kvm_vfio_ops_init();
4408 WARN_ON(r);
4409
c7addb90 4410 return 0;
6aa8b732 4411
af585b92
GN
4412out_unreg:
4413 kvm_async_pf_deinit();
6aa8b732 4414out_free:
c16f862d 4415 kmem_cache_destroy(kvm_vcpu_cache);
d2308784 4416out_free_3:
6aa8b732 4417 unregister_reboot_notifier(&kvm_reboot_notifier);
8c18b2d2 4418 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
d2308784 4419out_free_2:
e9b11c17 4420 kvm_arch_hardware_unsetup();
faf0be22 4421out_free_1:
7f59f492 4422 free_cpumask_var(cpus_hardware_enabled);
d2308784 4423out_free_0:
a0f155e9 4424 kvm_irqfd_exit();
36343f6e 4425out_irqfd:
7dac16c3
AH
4426 kvm_arch_exit();
4427out_fail:
6aa8b732
AK
4428 return r;
4429}
cb498ea2 4430EXPORT_SYMBOL_GPL(kvm_init);
6aa8b732 4431
cb498ea2 4432void kvm_exit(void)
6aa8b732 4433{
4bd33b56 4434 debugfs_remove_recursive(kvm_debugfs_dir);
6aa8b732 4435 misc_deregister(&kvm_dev);
c16f862d 4436 kmem_cache_destroy(kvm_vcpu_cache);
af585b92 4437 kvm_async_pf_deinit();
fb3600cc 4438 unregister_syscore_ops(&kvm_syscore_ops);
6aa8b732 4439 unregister_reboot_notifier(&kvm_reboot_notifier);
8c18b2d2 4440 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
75b7127c 4441 on_each_cpu(hardware_disable_nolock, NULL, 1);
e9b11c17 4442 kvm_arch_hardware_unsetup();
f8c16bba 4443 kvm_arch_exit();
a0f155e9 4444 kvm_irqfd_exit();
7f59f492 4445 free_cpumask_var(cpus_hardware_enabled);
571ee1b6 4446 kvm_vfio_ops_exit();
6aa8b732 4447}
cb498ea2 4448EXPORT_SYMBOL_GPL(kvm_exit);
c57c8046
JS
4449
4450struct kvm_vm_worker_thread_context {
4451 struct kvm *kvm;
4452 struct task_struct *parent;
4453 struct completion init_done;
4454 kvm_vm_thread_fn_t thread_fn;
4455 uintptr_t data;
4456 int err;
4457};
4458
4459static int kvm_vm_worker_thread(void *context)
4460{
4461 /*
4462 * The init_context is allocated on the stack of the parent thread, so
4463 * we have to locally copy anything that is needed beyond initialization
4464 */
4465 struct kvm_vm_worker_thread_context *init_context = context;
4466 struct kvm *kvm = init_context->kvm;
4467 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4468 uintptr_t data = init_context->data;
4469 int err;
4470
4471 err = kthread_park(current);
4472 /* kthread_park(current) is never supposed to return an error */
4473 WARN_ON(err != 0);
4474 if (err)
4475 goto init_complete;
4476
4477 err = cgroup_attach_task_all(init_context->parent, current);
4478 if (err) {
4479 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4480 __func__, err);
4481 goto init_complete;
4482 }
4483
4484 set_user_nice(current, task_nice(init_context->parent));
4485
4486init_complete:
4487 init_context->err = err;
4488 complete(&init_context->init_done);
4489 init_context = NULL;
4490
4491 if (err)
4492 return err;
4493
4494 /* Wait to be woken up by the spawner before proceeding. */
4495 kthread_parkme();
4496
4497 if (!kthread_should_stop())
4498 err = thread_fn(kvm, data);
4499
4500 return err;
4501}
4502
4503int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4504 uintptr_t data, const char *name,
4505 struct task_struct **thread_ptr)
4506{
4507 struct kvm_vm_worker_thread_context init_context = {};
4508 struct task_struct *thread;
4509
4510 *thread_ptr = NULL;
4511 init_context.kvm = kvm;
4512 init_context.parent = current;
4513 init_context.thread_fn = thread_fn;
4514 init_context.data = data;
4515 init_completion(&init_context.init_done);
4516
4517 thread = kthread_run(kvm_vm_worker_thread, &init_context,
4518 "%s-%d", name, task_pid_nr(current));
4519 if (IS_ERR(thread))
4520 return PTR_ERR(thread);
4521
4522 /* kthread_run is never supposed to return NULL */
4523 WARN_ON(thread == NULL);
4524
4525 wait_for_completion(&init_context.init_done);
4526
4527 if (!init_context.err)
4528 *thread_ptr = thread;
4529
4530 return init_context.err;
4531}