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