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