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