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