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