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