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