1 // SPDX-License-Identifier: GPL-2.0-only
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.
9  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10  *
11  * Authors:
12  *   Avi Kivity   <avi@qumranet.com>
13  *   Yaniv Kamay  <yaniv@qumranet.com>
14  */
15 
16 #include <kvm/iodev.h>
17 
18 #include <linux/kvm_host.h>
19 #include <linux/kvm.h>
20 #include <linux/module.h>
21 #include <linux/errno.h>
22 #include <linux/percpu.h>
23 #include <linux/mm.h>
24 #include <linux/miscdevice.h>
25 #include <linux/vmalloc.h>
26 #include <linux/reboot.h>
27 #include <linux/debugfs.h>
28 #include <linux/highmem.h>
29 #include <linux/file.h>
30 #include <linux/syscore_ops.h>
31 #include <linux/cpu.h>
32 #include <linux/sched/signal.h>
33 #include <linux/sched/mm.h>
34 #include <linux/sched/stat.h>
35 #include <linux/cpumask.h>
36 #include <linux/smp.h>
37 #include <linux/anon_inodes.h>
38 #include <linux/profile.h>
39 #include <linux/kvm_para.h>
40 #include <linux/pagemap.h>
41 #include <linux/mman.h>
42 #include <linux/swap.h>
43 #include <linux/bitops.h>
44 #include <linux/spinlock.h>
45 #include <linux/compat.h>
46 #include <linux/srcu.h>
47 #include <linux/hugetlb.h>
48 #include <linux/slab.h>
49 #include <linux/sort.h>
50 #include <linux/bsearch.h>
51 #include <linux/io.h>
52 #include <linux/lockdep.h>
53 #include <linux/kthread.h>
54 #include <linux/suspend.h>
55 
56 #include <asm/processor.h>
57 #include <asm/ioctl.h>
58 #include <linux/uaccess.h>
59 
60 #include "coalesced_mmio.h"
61 #include "async_pf.h"
62 #include "kvm_mm.h"
63 #include "vfio.h"
64 
65 #define CREATE_TRACE_POINTS
66 #include <trace/events/kvm.h>
67 
68 #include <linux/kvm_dirty_ring.h>
69 
70 /* Worst case buffer size needed for holding an integer. */
71 #define ITOA_MAX_LEN 12
72 
73 MODULE_AUTHOR("Qumranet");
74 MODULE_LICENSE("GPL");
75 
76 /* Architectures should define their poll value according to the halt latency */
77 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
78 module_param(halt_poll_ns, uint, 0644);
79 EXPORT_SYMBOL_GPL(halt_poll_ns);
80 
81 /* Default doubles per-vcpu halt_poll_ns. */
82 unsigned int halt_poll_ns_grow = 2;
83 module_param(halt_poll_ns_grow, uint, 0644);
84 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
85 
86 /* The start value to grow halt_poll_ns from */
87 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
88 module_param(halt_poll_ns_grow_start, uint, 0644);
89 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
90 
91 /* Default resets per-vcpu halt_poll_ns . */
92 unsigned int halt_poll_ns_shrink;
93 module_param(halt_poll_ns_shrink, uint, 0644);
94 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
95 
96 /*
97  * Ordering of locks:
98  *
99  *	kvm->lock --> kvm->slots_lock --> kvm->irq_lock
100  */
101 
102 DEFINE_MUTEX(kvm_lock);
103 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
104 LIST_HEAD(vm_list);
105 
106 static cpumask_var_t cpus_hardware_enabled;
107 static int kvm_usage_count;
108 static atomic_t hardware_enable_failed;
109 
110 static struct kmem_cache *kvm_vcpu_cache;
111 
112 static __read_mostly struct preempt_ops kvm_preempt_ops;
113 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
114 
115 struct dentry *kvm_debugfs_dir;
116 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
117 
118 static const struct file_operations stat_fops_per_vm;
119 
120 static struct file_operations kvm_chardev_ops;
121 
122 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
123 			   unsigned long arg);
124 #ifdef CONFIG_KVM_COMPAT
125 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
126 				  unsigned long arg);
127 #define KVM_COMPAT(c)	.compat_ioctl	= (c)
128 #else
129 /*
130  * For architectures that don't implement a compat infrastructure,
131  * adopt a double line of defense:
132  * - Prevent a compat task from opening /dev/kvm
133  * - If the open has been done by a 64bit task, and the KVM fd
134  *   passed to a compat task, let the ioctls fail.
135  */
kvm_no_compat_ioctl(struct file * file,unsigned int ioctl,unsigned long arg)136 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
137 				unsigned long arg) { return -EINVAL; }
138 
kvm_no_compat_open(struct inode * inode,struct file * file)139 static int kvm_no_compat_open(struct inode *inode, struct file *file)
140 {
141 	return is_compat_task() ? -ENODEV : 0;
142 }
143 #define KVM_COMPAT(c)	.compat_ioctl	= kvm_no_compat_ioctl,	\
144 			.open		= kvm_no_compat_open
145 #endif
146 static int hardware_enable_all(void);
147 static void hardware_disable_all(void);
148 
149 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
150 
151 __visible bool kvm_rebooting;
152 EXPORT_SYMBOL_GPL(kvm_rebooting);
153 
154 #define KVM_EVENT_CREATE_VM 0
155 #define KVM_EVENT_DESTROY_VM 1
156 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
157 static unsigned long long kvm_createvm_count;
158 static unsigned long long kvm_active_vms;
159 
160 static DEFINE_PER_CPU(cpumask_var_t, cpu_kick_mask);
161 
kvm_arch_mmu_notifier_invalidate_range(struct kvm * kvm,unsigned long start,unsigned long end)162 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
163 						   unsigned long start, unsigned long end)
164 {
165 }
166 
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)167 __weak void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
168 {
169 }
170 
kvm_is_zone_device_pfn(kvm_pfn_t pfn)171 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
172 {
173 	/*
174 	 * The metadata used by is_zone_device_page() to determine whether or
175 	 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
176 	 * the device has been pinned, e.g. by get_user_pages().  WARN if the
177 	 * page_count() is zero to help detect bad usage of this helper.
178 	 */
179 	if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
180 		return false;
181 
182 	return is_zone_device_page(pfn_to_page(pfn));
183 }
184 
kvm_is_reserved_pfn(kvm_pfn_t pfn)185 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
186 {
187 	/*
188 	 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
189 	 * perspective they are "normal" pages, albeit with slightly different
190 	 * usage rules.
191 	 */
192 	if (pfn_valid(pfn))
193 		return PageReserved(pfn_to_page(pfn)) &&
194 		       !is_zero_pfn(pfn) &&
195 		       !kvm_is_zone_device_pfn(pfn);
196 
197 	return true;
198 }
199 
200 /*
201  * Switches to specified vcpu, until a matching vcpu_put()
202  */
vcpu_load(struct kvm_vcpu * vcpu)203 void vcpu_load(struct kvm_vcpu *vcpu)
204 {
205 	int cpu = get_cpu();
206 
207 	__this_cpu_write(kvm_running_vcpu, vcpu);
208 	preempt_notifier_register(&vcpu->preempt_notifier);
209 	kvm_arch_vcpu_load(vcpu, cpu);
210 	put_cpu();
211 }
212 EXPORT_SYMBOL_GPL(vcpu_load);
213 
vcpu_put(struct kvm_vcpu * vcpu)214 void vcpu_put(struct kvm_vcpu *vcpu)
215 {
216 	preempt_disable();
217 	kvm_arch_vcpu_put(vcpu);
218 	preempt_notifier_unregister(&vcpu->preempt_notifier);
219 	__this_cpu_write(kvm_running_vcpu, NULL);
220 	preempt_enable();
221 }
222 EXPORT_SYMBOL_GPL(vcpu_put);
223 
224 /* TODO: merge with kvm_arch_vcpu_should_kick */
kvm_request_needs_ipi(struct kvm_vcpu * vcpu,unsigned req)225 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
226 {
227 	int mode = kvm_vcpu_exiting_guest_mode(vcpu);
228 
229 	/*
230 	 * We need to wait for the VCPU to reenable interrupts and get out of
231 	 * READING_SHADOW_PAGE_TABLES mode.
232 	 */
233 	if (req & KVM_REQUEST_WAIT)
234 		return mode != OUTSIDE_GUEST_MODE;
235 
236 	/*
237 	 * Need to kick a running VCPU, but otherwise there is nothing to do.
238 	 */
239 	return mode == IN_GUEST_MODE;
240 }
241 
ack_flush(void * _completed)242 static void ack_flush(void *_completed)
243 {
244 }
245 
kvm_kick_many_cpus(struct cpumask * cpus,bool wait)246 static inline bool kvm_kick_many_cpus(struct cpumask *cpus, bool wait)
247 {
248 	if (cpumask_empty(cpus))
249 		return false;
250 
251 	smp_call_function_many(cpus, ack_flush, NULL, wait);
252 	return true;
253 }
254 
kvm_make_vcpu_request(struct kvm_vcpu * vcpu,unsigned int req,struct cpumask * tmp,int current_cpu)255 static void kvm_make_vcpu_request(struct kvm_vcpu *vcpu, unsigned int req,
256 				  struct cpumask *tmp, int current_cpu)
257 {
258 	int cpu;
259 
260 	if (likely(!(req & KVM_REQUEST_NO_ACTION)))
261 		__kvm_make_request(req, vcpu);
262 
263 	if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
264 		return;
265 
266 	/*
267 	 * Note, the vCPU could get migrated to a different pCPU at any point
268 	 * after kvm_request_needs_ipi(), which could result in sending an IPI
269 	 * to the previous pCPU.  But, that's OK because the purpose of the IPI
270 	 * is to ensure the vCPU returns to OUTSIDE_GUEST_MODE, which is
271 	 * satisfied if the vCPU migrates. Entering READING_SHADOW_PAGE_TABLES
272 	 * after this point is also OK, as the requirement is only that KVM wait
273 	 * for vCPUs that were reading SPTEs _before_ any changes were
274 	 * finalized. See kvm_vcpu_kick() for more details on handling requests.
275 	 */
276 	if (kvm_request_needs_ipi(vcpu, req)) {
277 		cpu = READ_ONCE(vcpu->cpu);
278 		if (cpu != -1 && cpu != current_cpu)
279 			__cpumask_set_cpu(cpu, tmp);
280 	}
281 }
282 
kvm_make_vcpus_request_mask(struct kvm * kvm,unsigned int req,unsigned long * vcpu_bitmap)283 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
284 				 unsigned long *vcpu_bitmap)
285 {
286 	struct kvm_vcpu *vcpu;
287 	struct cpumask *cpus;
288 	int i, me;
289 	bool called;
290 
291 	me = get_cpu();
292 
293 	cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
294 	cpumask_clear(cpus);
295 
296 	for_each_set_bit(i, vcpu_bitmap, KVM_MAX_VCPUS) {
297 		vcpu = kvm_get_vcpu(kvm, i);
298 		if (!vcpu)
299 			continue;
300 		kvm_make_vcpu_request(vcpu, req, cpus, me);
301 	}
302 
303 	called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
304 	put_cpu();
305 
306 	return called;
307 }
308 
kvm_make_all_cpus_request_except(struct kvm * kvm,unsigned int req,struct kvm_vcpu * except)309 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
310 				      struct kvm_vcpu *except)
311 {
312 	struct kvm_vcpu *vcpu;
313 	struct cpumask *cpus;
314 	unsigned long i;
315 	bool called;
316 	int me;
317 
318 	me = get_cpu();
319 
320 	cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
321 	cpumask_clear(cpus);
322 
323 	kvm_for_each_vcpu(i, vcpu, kvm) {
324 		if (vcpu == except)
325 			continue;
326 		kvm_make_vcpu_request(vcpu, req, cpus, me);
327 	}
328 
329 	called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
330 	put_cpu();
331 
332 	return called;
333 }
334 
kvm_make_all_cpus_request(struct kvm * kvm,unsigned int req)335 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
336 {
337 	return kvm_make_all_cpus_request_except(kvm, req, NULL);
338 }
339 EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
340 
341 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
kvm_flush_remote_tlbs(struct kvm * kvm)342 void kvm_flush_remote_tlbs(struct kvm *kvm)
343 {
344 	++kvm->stat.generic.remote_tlb_flush_requests;
345 
346 	/*
347 	 * We want to publish modifications to the page tables before reading
348 	 * mode. Pairs with a memory barrier in arch-specific code.
349 	 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
350 	 * and smp_mb in walk_shadow_page_lockless_begin/end.
351 	 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
352 	 *
353 	 * There is already an smp_mb__after_atomic() before
354 	 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
355 	 * barrier here.
356 	 */
357 	if (!kvm_arch_flush_remote_tlb(kvm)
358 	    || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
359 		++kvm->stat.generic.remote_tlb_flush;
360 }
361 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
362 #endif
363 
kvm_flush_shadow_all(struct kvm * kvm)364 static void kvm_flush_shadow_all(struct kvm *kvm)
365 {
366 	kvm_arch_flush_shadow_all(kvm);
367 	kvm_arch_guest_memory_reclaimed(kvm);
368 }
369 
370 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache * mc,gfp_t gfp_flags)371 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
372 					       gfp_t gfp_flags)
373 {
374 	gfp_flags |= mc->gfp_zero;
375 
376 	if (mc->kmem_cache)
377 		return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
378 	else
379 		return (void *)__get_free_page(gfp_flags);
380 }
381 
kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache * mc,int min)382 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
383 {
384 	void *obj;
385 
386 	if (mc->nobjs >= min)
387 		return 0;
388 	while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
389 		obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
390 		if (!obj)
391 			return mc->nobjs >= min ? 0 : -ENOMEM;
392 		mc->objects[mc->nobjs++] = obj;
393 	}
394 	return 0;
395 }
396 
kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache * mc)397 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
398 {
399 	return mc->nobjs;
400 }
401 
kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache * mc)402 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
403 {
404 	while (mc->nobjs) {
405 		if (mc->kmem_cache)
406 			kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
407 		else
408 			free_page((unsigned long)mc->objects[--mc->nobjs]);
409 	}
410 }
411 
kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache * mc)412 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
413 {
414 	void *p;
415 
416 	if (WARN_ON(!mc->nobjs))
417 		p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
418 	else
419 		p = mc->objects[--mc->nobjs];
420 	BUG_ON(!p);
421 	return p;
422 }
423 #endif
424 
kvm_vcpu_init(struct kvm_vcpu * vcpu,struct kvm * kvm,unsigned id)425 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
426 {
427 	mutex_init(&vcpu->mutex);
428 	vcpu->cpu = -1;
429 	vcpu->kvm = kvm;
430 	vcpu->vcpu_id = id;
431 	vcpu->pid = NULL;
432 #ifndef __KVM_HAVE_ARCH_WQP
433 	rcuwait_init(&vcpu->wait);
434 #endif
435 	kvm_async_pf_vcpu_init(vcpu);
436 
437 	kvm_vcpu_set_in_spin_loop(vcpu, false);
438 	kvm_vcpu_set_dy_eligible(vcpu, false);
439 	vcpu->preempted = false;
440 	vcpu->ready = false;
441 	preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
442 	vcpu->last_used_slot = NULL;
443 }
444 
kvm_vcpu_destroy(struct kvm_vcpu * vcpu)445 static void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
446 {
447 	kvm_arch_vcpu_destroy(vcpu);
448 	kvm_dirty_ring_free(&vcpu->dirty_ring);
449 
450 	/*
451 	 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
452 	 * the vcpu->pid pointer, and at destruction time all file descriptors
453 	 * are already gone.
454 	 */
455 	put_pid(rcu_dereference_protected(vcpu->pid, 1));
456 
457 	free_page((unsigned long)vcpu->run);
458 	kmem_cache_free(kvm_vcpu_cache, vcpu);
459 }
460 
kvm_destroy_vcpus(struct kvm * kvm)461 void kvm_destroy_vcpus(struct kvm *kvm)
462 {
463 	unsigned long i;
464 	struct kvm_vcpu *vcpu;
465 
466 	kvm_for_each_vcpu(i, vcpu, kvm) {
467 		kvm_vcpu_destroy(vcpu);
468 		xa_erase(&kvm->vcpu_array, i);
469 	}
470 
471 	atomic_set(&kvm->online_vcpus, 0);
472 }
473 EXPORT_SYMBOL_GPL(kvm_destroy_vcpus);
474 
475 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
mmu_notifier_to_kvm(struct mmu_notifier * mn)476 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
477 {
478 	return container_of(mn, struct kvm, mmu_notifier);
479 }
480 
kvm_mmu_notifier_invalidate_range(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long start,unsigned long end)481 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
482 					      struct mm_struct *mm,
483 					      unsigned long start, unsigned long end)
484 {
485 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
486 	int idx;
487 
488 	idx = srcu_read_lock(&kvm->srcu);
489 	kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
490 	srcu_read_unlock(&kvm->srcu, idx);
491 }
492 
493 typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
494 
495 typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
496 			     unsigned long end);
497 
498 typedef void (*on_unlock_fn_t)(struct kvm *kvm);
499 
500 struct kvm_hva_range {
501 	unsigned long start;
502 	unsigned long end;
503 	pte_t pte;
504 	hva_handler_t handler;
505 	on_lock_fn_t on_lock;
506 	on_unlock_fn_t on_unlock;
507 	bool flush_on_ret;
508 	bool may_block;
509 };
510 
511 /*
512  * Use a dedicated stub instead of NULL to indicate that there is no callback
513  * function/handler.  The compiler technically can't guarantee that a real
514  * function will have a non-zero address, and so it will generate code to
515  * check for !NULL, whereas comparing against a stub will be elided at compile
516  * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
517  */
kvm_null_fn(void)518 static void kvm_null_fn(void)
519 {
520 
521 }
522 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
523 
524 /* Iterate over each memslot intersecting [start, last] (inclusive) range */
525 #define kvm_for_each_memslot_in_hva_range(node, slots, start, last)	     \
526 	for (node = interval_tree_iter_first(&slots->hva_tree, start, last); \
527 	     node;							     \
528 	     node = interval_tree_iter_next(node, start, last))	     \
529 
__kvm_handle_hva_range(struct kvm * kvm,const struct kvm_hva_range * range)530 static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
531 						  const struct kvm_hva_range *range)
532 {
533 	bool ret = false, locked = false;
534 	struct kvm_gfn_range gfn_range;
535 	struct kvm_memory_slot *slot;
536 	struct kvm_memslots *slots;
537 	int i, idx;
538 
539 	if (WARN_ON_ONCE(range->end <= range->start))
540 		return 0;
541 
542 	/* A null handler is allowed if and only if on_lock() is provided. */
543 	if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
544 			 IS_KVM_NULL_FN(range->handler)))
545 		return 0;
546 
547 	idx = srcu_read_lock(&kvm->srcu);
548 
549 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
550 		struct interval_tree_node *node;
551 
552 		slots = __kvm_memslots(kvm, i);
553 		kvm_for_each_memslot_in_hva_range(node, slots,
554 						  range->start, range->end - 1) {
555 			unsigned long hva_start, hva_end;
556 
557 			slot = container_of(node, struct kvm_memory_slot, hva_node[slots->node_idx]);
558 			hva_start = max(range->start, slot->userspace_addr);
559 			hva_end = min(range->end, slot->userspace_addr +
560 						  (slot->npages << PAGE_SHIFT));
561 
562 			/*
563 			 * To optimize for the likely case where the address
564 			 * range is covered by zero or one memslots, don't
565 			 * bother making these conditional (to avoid writes on
566 			 * the second or later invocation of the handler).
567 			 */
568 			gfn_range.pte = range->pte;
569 			gfn_range.may_block = range->may_block;
570 
571 			/*
572 			 * {gfn(page) | page intersects with [hva_start, hva_end)} =
573 			 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
574 			 */
575 			gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
576 			gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
577 			gfn_range.slot = slot;
578 
579 			if (!locked) {
580 				locked = true;
581 				KVM_MMU_LOCK(kvm);
582 				if (!IS_KVM_NULL_FN(range->on_lock))
583 					range->on_lock(kvm, range->start, range->end);
584 				if (IS_KVM_NULL_FN(range->handler))
585 					break;
586 			}
587 			ret |= range->handler(kvm, &gfn_range);
588 		}
589 	}
590 
591 	if (range->flush_on_ret && ret)
592 		kvm_flush_remote_tlbs(kvm);
593 
594 	if (locked) {
595 		KVM_MMU_UNLOCK(kvm);
596 		if (!IS_KVM_NULL_FN(range->on_unlock))
597 			range->on_unlock(kvm);
598 	}
599 
600 	srcu_read_unlock(&kvm->srcu, idx);
601 
602 	/* The notifiers are averse to booleans. :-( */
603 	return (int)ret;
604 }
605 
kvm_handle_hva_range(struct mmu_notifier * mn,unsigned long start,unsigned long end,pte_t pte,hva_handler_t handler)606 static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
607 						unsigned long start,
608 						unsigned long end,
609 						pte_t pte,
610 						hva_handler_t handler)
611 {
612 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
613 	const struct kvm_hva_range range = {
614 		.start		= start,
615 		.end		= end,
616 		.pte		= pte,
617 		.handler	= handler,
618 		.on_lock	= (void *)kvm_null_fn,
619 		.on_unlock	= (void *)kvm_null_fn,
620 		.flush_on_ret	= true,
621 		.may_block	= false,
622 	};
623 
624 	return __kvm_handle_hva_range(kvm, &range);
625 }
626 
kvm_handle_hva_range_no_flush(struct mmu_notifier * mn,unsigned long start,unsigned long end,hva_handler_t handler)627 static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
628 							 unsigned long start,
629 							 unsigned long end,
630 							 hva_handler_t handler)
631 {
632 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
633 	const struct kvm_hva_range range = {
634 		.start		= start,
635 		.end		= end,
636 		.pte		= __pte(0),
637 		.handler	= handler,
638 		.on_lock	= (void *)kvm_null_fn,
639 		.on_unlock	= (void *)kvm_null_fn,
640 		.flush_on_ret	= false,
641 		.may_block	= false,
642 	};
643 
644 	return __kvm_handle_hva_range(kvm, &range);
645 }
kvm_mmu_notifier_change_pte(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long address,pte_t pte)646 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
647 					struct mm_struct *mm,
648 					unsigned long address,
649 					pte_t pte)
650 {
651 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
652 
653 	trace_kvm_set_spte_hva(address);
654 
655 	/*
656 	 * .change_pte() must be surrounded by .invalidate_range_{start,end}().
657 	 * If mmu_notifier_count is zero, then no in-progress invalidations,
658 	 * including this one, found a relevant memslot at start(); rechecking
659 	 * memslots here is unnecessary.  Note, a false positive (count elevated
660 	 * by a different invalidation) is sub-optimal but functionally ok.
661 	 */
662 	WARN_ON_ONCE(!READ_ONCE(kvm->mn_active_invalidate_count));
663 	if (!READ_ONCE(kvm->mmu_notifier_count))
664 		return;
665 
666 	kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
667 }
668 
kvm_inc_notifier_count(struct kvm * kvm,unsigned long start,unsigned long end)669 void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
670 				   unsigned long end)
671 {
672 	/*
673 	 * The count increase must become visible at unlock time as no
674 	 * spte can be established without taking the mmu_lock and
675 	 * count is also read inside the mmu_lock critical section.
676 	 */
677 	kvm->mmu_notifier_count++;
678 	if (likely(kvm->mmu_notifier_count == 1)) {
679 		kvm->mmu_notifier_range_start = start;
680 		kvm->mmu_notifier_range_end = end;
681 	} else {
682 		/*
683 		 * Fully tracking multiple concurrent ranges has diminishing
684 		 * returns. Keep things simple and just find the minimal range
685 		 * which includes the current and new ranges. As there won't be
686 		 * enough information to subtract a range after its invalidate
687 		 * completes, any ranges invalidated concurrently will
688 		 * accumulate and persist until all outstanding invalidates
689 		 * complete.
690 		 */
691 		kvm->mmu_notifier_range_start =
692 			min(kvm->mmu_notifier_range_start, start);
693 		kvm->mmu_notifier_range_end =
694 			max(kvm->mmu_notifier_range_end, end);
695 	}
696 }
697 
kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier * mn,const struct mmu_notifier_range * range)698 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
699 					const struct mmu_notifier_range *range)
700 {
701 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
702 	const struct kvm_hva_range hva_range = {
703 		.start		= range->start,
704 		.end		= range->end,
705 		.pte		= __pte(0),
706 		.handler	= kvm_unmap_gfn_range,
707 		.on_lock	= kvm_inc_notifier_count,
708 		.on_unlock	= kvm_arch_guest_memory_reclaimed,
709 		.flush_on_ret	= true,
710 		.may_block	= mmu_notifier_range_blockable(range),
711 	};
712 
713 	trace_kvm_unmap_hva_range(range->start, range->end);
714 
715 	/*
716 	 * Prevent memslot modification between range_start() and range_end()
717 	 * so that conditionally locking provides the same result in both
718 	 * functions.  Without that guarantee, the mmu_notifier_count
719 	 * adjustments will be imbalanced.
720 	 *
721 	 * Pairs with the decrement in range_end().
722 	 */
723 	spin_lock(&kvm->mn_invalidate_lock);
724 	kvm->mn_active_invalidate_count++;
725 	spin_unlock(&kvm->mn_invalidate_lock);
726 
727 	/*
728 	 * Invalidate pfn caches _before_ invalidating the secondary MMUs, i.e.
729 	 * before acquiring mmu_lock, to avoid holding mmu_lock while acquiring
730 	 * each cache's lock.  There are relatively few caches in existence at
731 	 * any given time, and the caches themselves can check for hva overlap,
732 	 * i.e. don't need to rely on memslot overlap checks for performance.
733 	 * Because this runs without holding mmu_lock, the pfn caches must use
734 	 * mn_active_invalidate_count (see above) instead of mmu_notifier_count.
735 	 */
736 	gfn_to_pfn_cache_invalidate_start(kvm, range->start, range->end,
737 					  hva_range.may_block);
738 
739 	__kvm_handle_hva_range(kvm, &hva_range);
740 
741 	return 0;
742 }
743 
kvm_dec_notifier_count(struct kvm * kvm,unsigned long start,unsigned long end)744 void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
745 				   unsigned long end)
746 {
747 	/*
748 	 * This sequence increase will notify the kvm page fault that
749 	 * the page that is going to be mapped in the spte could have
750 	 * been freed.
751 	 */
752 	kvm->mmu_notifier_seq++;
753 	smp_wmb();
754 	/*
755 	 * The above sequence increase must be visible before the
756 	 * below count decrease, which is ensured by the smp_wmb above
757 	 * in conjunction with the smp_rmb in mmu_notifier_retry().
758 	 */
759 	kvm->mmu_notifier_count--;
760 }
761 
kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier * mn,const struct mmu_notifier_range * range)762 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
763 					const struct mmu_notifier_range *range)
764 {
765 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
766 	const struct kvm_hva_range hva_range = {
767 		.start		= range->start,
768 		.end		= range->end,
769 		.pte		= __pte(0),
770 		.handler	= (void *)kvm_null_fn,
771 		.on_lock	= kvm_dec_notifier_count,
772 		.on_unlock	= (void *)kvm_null_fn,
773 		.flush_on_ret	= false,
774 		.may_block	= mmu_notifier_range_blockable(range),
775 	};
776 	bool wake;
777 
778 	__kvm_handle_hva_range(kvm, &hva_range);
779 
780 	/* Pairs with the increment in range_start(). */
781 	spin_lock(&kvm->mn_invalidate_lock);
782 	wake = (--kvm->mn_active_invalidate_count == 0);
783 	spin_unlock(&kvm->mn_invalidate_lock);
784 
785 	/*
786 	 * There can only be one waiter, since the wait happens under
787 	 * slots_lock.
788 	 */
789 	if (wake)
790 		rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
791 
792 	BUG_ON(kvm->mmu_notifier_count < 0);
793 }
794 
kvm_mmu_notifier_clear_flush_young(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long start,unsigned long end)795 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
796 					      struct mm_struct *mm,
797 					      unsigned long start,
798 					      unsigned long end)
799 {
800 	trace_kvm_age_hva(start, end);
801 
802 	return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
803 }
804 
kvm_mmu_notifier_clear_young(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long start,unsigned long end)805 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
806 					struct mm_struct *mm,
807 					unsigned long start,
808 					unsigned long end)
809 {
810 	trace_kvm_age_hva(start, end);
811 
812 	/*
813 	 * Even though we do not flush TLB, this will still adversely
814 	 * affect performance on pre-Haswell Intel EPT, where there is
815 	 * no EPT Access Bit to clear so that we have to tear down EPT
816 	 * tables instead. If we find this unacceptable, we can always
817 	 * add a parameter to kvm_age_hva so that it effectively doesn't
818 	 * do anything on clear_young.
819 	 *
820 	 * Also note that currently we never issue secondary TLB flushes
821 	 * from clear_young, leaving this job up to the regular system
822 	 * cadence. If we find this inaccurate, we might come up with a
823 	 * more sophisticated heuristic later.
824 	 */
825 	return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
826 }
827 
kvm_mmu_notifier_test_young(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long address)828 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
829 				       struct mm_struct *mm,
830 				       unsigned long address)
831 {
832 	trace_kvm_test_age_hva(address);
833 
834 	return kvm_handle_hva_range_no_flush(mn, address, address + 1,
835 					     kvm_test_age_gfn);
836 }
837 
kvm_mmu_notifier_release(struct mmu_notifier * mn,struct mm_struct * mm)838 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
839 				     struct mm_struct *mm)
840 {
841 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
842 	int idx;
843 
844 	idx = srcu_read_lock(&kvm->srcu);
845 	kvm_flush_shadow_all(kvm);
846 	srcu_read_unlock(&kvm->srcu, idx);
847 }
848 
849 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
850 	.invalidate_range	= kvm_mmu_notifier_invalidate_range,
851 	.invalidate_range_start	= kvm_mmu_notifier_invalidate_range_start,
852 	.invalidate_range_end	= kvm_mmu_notifier_invalidate_range_end,
853 	.clear_flush_young	= kvm_mmu_notifier_clear_flush_young,
854 	.clear_young		= kvm_mmu_notifier_clear_young,
855 	.test_young		= kvm_mmu_notifier_test_young,
856 	.change_pte		= kvm_mmu_notifier_change_pte,
857 	.release		= kvm_mmu_notifier_release,
858 };
859 
kvm_init_mmu_notifier(struct kvm * kvm)860 static int kvm_init_mmu_notifier(struct kvm *kvm)
861 {
862 	kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
863 	return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
864 }
865 
866 #else  /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
867 
kvm_init_mmu_notifier(struct kvm * kvm)868 static int kvm_init_mmu_notifier(struct kvm *kvm)
869 {
870 	return 0;
871 }
872 
873 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
874 
875 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_pm_notifier_call(struct notifier_block * bl,unsigned long state,void * unused)876 static int kvm_pm_notifier_call(struct notifier_block *bl,
877 				unsigned long state,
878 				void *unused)
879 {
880 	struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
881 
882 	return kvm_arch_pm_notifier(kvm, state);
883 }
884 
kvm_init_pm_notifier(struct kvm * kvm)885 static void kvm_init_pm_notifier(struct kvm *kvm)
886 {
887 	kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
888 	/* Suspend KVM before we suspend ftrace, RCU, etc. */
889 	kvm->pm_notifier.priority = INT_MAX;
890 	register_pm_notifier(&kvm->pm_notifier);
891 }
892 
kvm_destroy_pm_notifier(struct kvm * kvm)893 static void kvm_destroy_pm_notifier(struct kvm *kvm)
894 {
895 	unregister_pm_notifier(&kvm->pm_notifier);
896 }
897 #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
kvm_init_pm_notifier(struct kvm * kvm)898 static void kvm_init_pm_notifier(struct kvm *kvm)
899 {
900 }
901 
kvm_destroy_pm_notifier(struct kvm * kvm)902 static void kvm_destroy_pm_notifier(struct kvm *kvm)
903 {
904 }
905 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
906 
kvm_destroy_dirty_bitmap(struct kvm_memory_slot * memslot)907 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
908 {
909 	if (!memslot->dirty_bitmap)
910 		return;
911 
912 	kvfree(memslot->dirty_bitmap);
913 	memslot->dirty_bitmap = NULL;
914 }
915 
916 /* This does not remove the slot from struct kvm_memslots data structures */
kvm_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)917 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
918 {
919 	kvm_destroy_dirty_bitmap(slot);
920 
921 	kvm_arch_free_memslot(kvm, slot);
922 
923 	kfree(slot);
924 }
925 
kvm_free_memslots(struct kvm * kvm,struct kvm_memslots * slots)926 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
927 {
928 	struct hlist_node *idnode;
929 	struct kvm_memory_slot *memslot;
930 	int bkt;
931 
932 	/*
933 	 * The same memslot objects live in both active and inactive sets,
934 	 * arbitrarily free using index '1' so the second invocation of this
935 	 * function isn't operating over a structure with dangling pointers
936 	 * (even though this function isn't actually touching them).
937 	 */
938 	if (!slots->node_idx)
939 		return;
940 
941 	hash_for_each_safe(slots->id_hash, bkt, idnode, memslot, id_node[1])
942 		kvm_free_memslot(kvm, memslot);
943 }
944 
kvm_stats_debugfs_mode(const struct _kvm_stats_desc * pdesc)945 static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
946 {
947 	switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
948 	case KVM_STATS_TYPE_INSTANT:
949 		return 0444;
950 	case KVM_STATS_TYPE_CUMULATIVE:
951 	case KVM_STATS_TYPE_PEAK:
952 	default:
953 		return 0644;
954 	}
955 }
956 
957 
kvm_destroy_vm_debugfs(struct kvm * kvm)958 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
959 {
960 	int i;
961 	int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
962 				      kvm_vcpu_stats_header.num_desc;
963 
964 	if (IS_ERR(kvm->debugfs_dentry))
965 		return;
966 
967 	debugfs_remove_recursive(kvm->debugfs_dentry);
968 
969 	if (kvm->debugfs_stat_data) {
970 		for (i = 0; i < kvm_debugfs_num_entries; i++)
971 			kfree(kvm->debugfs_stat_data[i]);
972 		kfree(kvm->debugfs_stat_data);
973 	}
974 }
975 
kvm_create_vm_debugfs(struct kvm * kvm,int fd)976 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
977 {
978 	static DEFINE_MUTEX(kvm_debugfs_lock);
979 	struct dentry *dent;
980 	char dir_name[ITOA_MAX_LEN * 2];
981 	struct kvm_stat_data *stat_data;
982 	const struct _kvm_stats_desc *pdesc;
983 	int i, ret;
984 	int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
985 				      kvm_vcpu_stats_header.num_desc;
986 
987 	if (!debugfs_initialized())
988 		return 0;
989 
990 	snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
991 	mutex_lock(&kvm_debugfs_lock);
992 	dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
993 	if (dent) {
994 		pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
995 		dput(dent);
996 		mutex_unlock(&kvm_debugfs_lock);
997 		return 0;
998 	}
999 	dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
1000 	mutex_unlock(&kvm_debugfs_lock);
1001 	if (IS_ERR(dent))
1002 		return 0;
1003 
1004 	kvm->debugfs_dentry = dent;
1005 	kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
1006 					 sizeof(*kvm->debugfs_stat_data),
1007 					 GFP_KERNEL_ACCOUNT);
1008 	if (!kvm->debugfs_stat_data)
1009 		return -ENOMEM;
1010 
1011 	for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
1012 		pdesc = &kvm_vm_stats_desc[i];
1013 		stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
1014 		if (!stat_data)
1015 			return -ENOMEM;
1016 
1017 		stat_data->kvm = kvm;
1018 		stat_data->desc = pdesc;
1019 		stat_data->kind = KVM_STAT_VM;
1020 		kvm->debugfs_stat_data[i] = stat_data;
1021 		debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1022 				    kvm->debugfs_dentry, stat_data,
1023 				    &stat_fops_per_vm);
1024 	}
1025 
1026 	for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
1027 		pdesc = &kvm_vcpu_stats_desc[i];
1028 		stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
1029 		if (!stat_data)
1030 			return -ENOMEM;
1031 
1032 		stat_data->kvm = kvm;
1033 		stat_data->desc = pdesc;
1034 		stat_data->kind = KVM_STAT_VCPU;
1035 		kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
1036 		debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1037 				    kvm->debugfs_dentry, stat_data,
1038 				    &stat_fops_per_vm);
1039 	}
1040 
1041 	ret = kvm_arch_create_vm_debugfs(kvm);
1042 	if (ret) {
1043 		kvm_destroy_vm_debugfs(kvm);
1044 		return i;
1045 	}
1046 
1047 	return 0;
1048 }
1049 
1050 /*
1051  * Called after the VM is otherwise initialized, but just before adding it to
1052  * the vm_list.
1053  */
kvm_arch_post_init_vm(struct kvm * kvm)1054 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
1055 {
1056 	return 0;
1057 }
1058 
1059 /*
1060  * Called just after removing the VM from the vm_list, but before doing any
1061  * other destruction.
1062  */
kvm_arch_pre_destroy_vm(struct kvm * kvm)1063 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
1064 {
1065 }
1066 
1067 /*
1068  * Called after per-vm debugfs created.  When called kvm->debugfs_dentry should
1069  * be setup already, so we can create arch-specific debugfs entries under it.
1070  * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
1071  * a per-arch destroy interface is not needed.
1072  */
kvm_arch_create_vm_debugfs(struct kvm * kvm)1073 int __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
1074 {
1075 	return 0;
1076 }
1077 
kvm_create_vm(unsigned long type)1078 static struct kvm *kvm_create_vm(unsigned long type)
1079 {
1080 	struct kvm *kvm = kvm_arch_alloc_vm();
1081 	struct kvm_memslots *slots;
1082 	int r = -ENOMEM;
1083 	int i, j;
1084 
1085 	if (!kvm)
1086 		return ERR_PTR(-ENOMEM);
1087 
1088 	/* KVM is pinned via open("/dev/kvm"), the fd passed to this ioctl(). */
1089 	__module_get(kvm_chardev_ops.owner);
1090 
1091 	KVM_MMU_LOCK_INIT(kvm);
1092 	mmgrab(current->mm);
1093 	kvm->mm = current->mm;
1094 	kvm_eventfd_init(kvm);
1095 	mutex_init(&kvm->lock);
1096 	mutex_init(&kvm->irq_lock);
1097 	mutex_init(&kvm->slots_lock);
1098 	mutex_init(&kvm->slots_arch_lock);
1099 	spin_lock_init(&kvm->mn_invalidate_lock);
1100 	rcuwait_init(&kvm->mn_memslots_update_rcuwait);
1101 	xa_init(&kvm->vcpu_array);
1102 
1103 	INIT_LIST_HEAD(&kvm->gpc_list);
1104 	spin_lock_init(&kvm->gpc_lock);
1105 
1106 	INIT_LIST_HEAD(&kvm->devices);
1107 	kvm->max_vcpus = KVM_MAX_VCPUS;
1108 
1109 	BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
1110 
1111 	/*
1112 	 * Force subsequent debugfs file creations to fail if the VM directory
1113 	 * is not created (by kvm_create_vm_debugfs()).
1114 	 */
1115 	kvm->debugfs_dentry = ERR_PTR(-ENOENT);
1116 
1117 	if (init_srcu_struct(&kvm->srcu))
1118 		goto out_err_no_srcu;
1119 	if (init_srcu_struct(&kvm->irq_srcu))
1120 		goto out_err_no_irq_srcu;
1121 
1122 	refcount_set(&kvm->users_count, 1);
1123 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1124 		for (j = 0; j < 2; j++) {
1125 			slots = &kvm->__memslots[i][j];
1126 
1127 			atomic_long_set(&slots->last_used_slot, (unsigned long)NULL);
1128 			slots->hva_tree = RB_ROOT_CACHED;
1129 			slots->gfn_tree = RB_ROOT;
1130 			hash_init(slots->id_hash);
1131 			slots->node_idx = j;
1132 
1133 			/* Generations must be different for each address space. */
1134 			slots->generation = i;
1135 		}
1136 
1137 		rcu_assign_pointer(kvm->memslots[i], &kvm->__memslots[i][0]);
1138 	}
1139 
1140 	for (i = 0; i < KVM_NR_BUSES; i++) {
1141 		rcu_assign_pointer(kvm->buses[i],
1142 			kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
1143 		if (!kvm->buses[i])
1144 			goto out_err_no_arch_destroy_vm;
1145 	}
1146 
1147 	kvm->max_halt_poll_ns = halt_poll_ns;
1148 
1149 	r = kvm_arch_init_vm(kvm, type);
1150 	if (r)
1151 		goto out_err_no_arch_destroy_vm;
1152 
1153 	r = hardware_enable_all();
1154 	if (r)
1155 		goto out_err_no_disable;
1156 
1157 #ifdef CONFIG_HAVE_KVM_IRQFD
1158 	INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
1159 #endif
1160 
1161 	r = kvm_init_mmu_notifier(kvm);
1162 	if (r)
1163 		goto out_err_no_mmu_notifier;
1164 
1165 	r = kvm_arch_post_init_vm(kvm);
1166 	if (r)
1167 		goto out_err;
1168 
1169 	mutex_lock(&kvm_lock);
1170 	list_add(&kvm->vm_list, &vm_list);
1171 	mutex_unlock(&kvm_lock);
1172 
1173 	preempt_notifier_inc();
1174 	kvm_init_pm_notifier(kvm);
1175 
1176 	return kvm;
1177 
1178 out_err:
1179 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1180 	if (kvm->mmu_notifier.ops)
1181 		mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1182 #endif
1183 out_err_no_mmu_notifier:
1184 	hardware_disable_all();
1185 out_err_no_disable:
1186 	kvm_arch_destroy_vm(kvm);
1187 out_err_no_arch_destroy_vm:
1188 	WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
1189 	for (i = 0; i < KVM_NR_BUSES; i++)
1190 		kfree(kvm_get_bus(kvm, i));
1191 	cleanup_srcu_struct(&kvm->irq_srcu);
1192 out_err_no_irq_srcu:
1193 	cleanup_srcu_struct(&kvm->srcu);
1194 out_err_no_srcu:
1195 	kvm_arch_free_vm(kvm);
1196 	mmdrop(current->mm);
1197 	module_put(kvm_chardev_ops.owner);
1198 	return ERR_PTR(r);
1199 }
1200 
kvm_destroy_devices(struct kvm * kvm)1201 static void kvm_destroy_devices(struct kvm *kvm)
1202 {
1203 	struct kvm_device *dev, *tmp;
1204 
1205 	/*
1206 	 * We do not need to take the kvm->lock here, because nobody else
1207 	 * has a reference to the struct kvm at this point and therefore
1208 	 * cannot access the devices list anyhow.
1209 	 */
1210 	list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1211 		list_del(&dev->vm_node);
1212 		dev->ops->destroy(dev);
1213 	}
1214 }
1215 
kvm_destroy_vm(struct kvm * kvm)1216 static void kvm_destroy_vm(struct kvm *kvm)
1217 {
1218 	int i;
1219 	struct mm_struct *mm = kvm->mm;
1220 
1221 	kvm_destroy_pm_notifier(kvm);
1222 	kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
1223 	kvm_destroy_vm_debugfs(kvm);
1224 	kvm_arch_sync_events(kvm);
1225 	mutex_lock(&kvm_lock);
1226 	list_del(&kvm->vm_list);
1227 	mutex_unlock(&kvm_lock);
1228 	kvm_arch_pre_destroy_vm(kvm);
1229 
1230 	kvm_free_irq_routing(kvm);
1231 	for (i = 0; i < KVM_NR_BUSES; i++) {
1232 		struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
1233 
1234 		if (bus)
1235 			kvm_io_bus_destroy(bus);
1236 		kvm->buses[i] = NULL;
1237 	}
1238 	kvm_coalesced_mmio_free(kvm);
1239 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1240 	mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
1241 	/*
1242 	 * At this point, pending calls to invalidate_range_start()
1243 	 * have completed but no more MMU notifiers will run, so
1244 	 * mn_active_invalidate_count may remain unbalanced.
1245 	 * No threads can be waiting in install_new_memslots as the
1246 	 * last reference on KVM has been dropped, but freeing
1247 	 * memslots would deadlock without this manual intervention.
1248 	 */
1249 	WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
1250 	kvm->mn_active_invalidate_count = 0;
1251 #else
1252 	kvm_flush_shadow_all(kvm);
1253 #endif
1254 	kvm_arch_destroy_vm(kvm);
1255 	kvm_destroy_devices(kvm);
1256 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1257 		kvm_free_memslots(kvm, &kvm->__memslots[i][0]);
1258 		kvm_free_memslots(kvm, &kvm->__memslots[i][1]);
1259 	}
1260 	cleanup_srcu_struct(&kvm->irq_srcu);
1261 	cleanup_srcu_struct(&kvm->srcu);
1262 	kvm_arch_free_vm(kvm);
1263 	preempt_notifier_dec();
1264 	hardware_disable_all();
1265 	mmdrop(mm);
1266 	module_put(kvm_chardev_ops.owner);
1267 }
1268 
kvm_get_kvm(struct kvm * kvm)1269 void kvm_get_kvm(struct kvm *kvm)
1270 {
1271 	refcount_inc(&kvm->users_count);
1272 }
1273 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1274 
1275 /*
1276  * Make sure the vm is not during destruction, which is a safe version of
1277  * kvm_get_kvm().  Return true if kvm referenced successfully, false otherwise.
1278  */
kvm_get_kvm_safe(struct kvm * kvm)1279 bool kvm_get_kvm_safe(struct kvm *kvm)
1280 {
1281 	return refcount_inc_not_zero(&kvm->users_count);
1282 }
1283 EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
1284 
kvm_put_kvm(struct kvm * kvm)1285 void kvm_put_kvm(struct kvm *kvm)
1286 {
1287 	if (refcount_dec_and_test(&kvm->users_count))
1288 		kvm_destroy_vm(kvm);
1289 }
1290 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1291 
1292 /*
1293  * Used to put a reference that was taken on behalf of an object associated
1294  * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1295  * of the new file descriptor fails and the reference cannot be transferred to
1296  * its final owner.  In such cases, the caller is still actively using @kvm and
1297  * will fail miserably if the refcount unexpectedly hits zero.
1298  */
kvm_put_kvm_no_destroy(struct kvm * kvm)1299 void kvm_put_kvm_no_destroy(struct kvm *kvm)
1300 {
1301 	WARN_ON(refcount_dec_and_test(&kvm->users_count));
1302 }
1303 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
1304 
kvm_vm_release(struct inode * inode,struct file * filp)1305 static int kvm_vm_release(struct inode *inode, struct file *filp)
1306 {
1307 	struct kvm *kvm = filp->private_data;
1308 
1309 	kvm_irqfd_release(kvm);
1310 
1311 	kvm_put_kvm(kvm);
1312 	return 0;
1313 }
1314 
1315 /*
1316  * Allocation size is twice as large as the actual dirty bitmap size.
1317  * See kvm_vm_ioctl_get_dirty_log() why this is needed.
1318  */
kvm_alloc_dirty_bitmap(struct kvm_memory_slot * memslot)1319 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
1320 {
1321 	unsigned long dirty_bytes = kvm_dirty_bitmap_bytes(memslot);
1322 
1323 	memslot->dirty_bitmap = __vcalloc(2, dirty_bytes, GFP_KERNEL_ACCOUNT);
1324 	if (!memslot->dirty_bitmap)
1325 		return -ENOMEM;
1326 
1327 	return 0;
1328 }
1329 
kvm_get_inactive_memslots(struct kvm * kvm,int as_id)1330 static struct kvm_memslots *kvm_get_inactive_memslots(struct kvm *kvm, int as_id)
1331 {
1332 	struct kvm_memslots *active = __kvm_memslots(kvm, as_id);
1333 	int node_idx_inactive = active->node_idx ^ 1;
1334 
1335 	return &kvm->__memslots[as_id][node_idx_inactive];
1336 }
1337 
1338 /*
1339  * Helper to get the address space ID when one of memslot pointers may be NULL.
1340  * This also serves as a sanity that at least one of the pointers is non-NULL,
1341  * and that their address space IDs don't diverge.
1342  */
kvm_memslots_get_as_id(struct kvm_memory_slot * a,struct kvm_memory_slot * b)1343 static int kvm_memslots_get_as_id(struct kvm_memory_slot *a,
1344 				  struct kvm_memory_slot *b)
1345 {
1346 	if (WARN_ON_ONCE(!a && !b))
1347 		return 0;
1348 
1349 	if (!a)
1350 		return b->as_id;
1351 	if (!b)
1352 		return a->as_id;
1353 
1354 	WARN_ON_ONCE(a->as_id != b->as_id);
1355 	return a->as_id;
1356 }
1357 
kvm_insert_gfn_node(struct kvm_memslots * slots,struct kvm_memory_slot * slot)1358 static void kvm_insert_gfn_node(struct kvm_memslots *slots,
1359 				struct kvm_memory_slot *slot)
1360 {
1361 	struct rb_root *gfn_tree = &slots->gfn_tree;
1362 	struct rb_node **node, *parent;
1363 	int idx = slots->node_idx;
1364 
1365 	parent = NULL;
1366 	for (node = &gfn_tree->rb_node; *node; ) {
1367 		struct kvm_memory_slot *tmp;
1368 
1369 		tmp = container_of(*node, struct kvm_memory_slot, gfn_node[idx]);
1370 		parent = *node;
1371 		if (slot->base_gfn < tmp->base_gfn)
1372 			node = &(*node)->rb_left;
1373 		else if (slot->base_gfn > tmp->base_gfn)
1374 			node = &(*node)->rb_right;
1375 		else
1376 			BUG();
1377 	}
1378 
1379 	rb_link_node(&slot->gfn_node[idx], parent, node);
1380 	rb_insert_color(&slot->gfn_node[idx], gfn_tree);
1381 }
1382 
kvm_erase_gfn_node(struct kvm_memslots * slots,struct kvm_memory_slot * slot)1383 static void kvm_erase_gfn_node(struct kvm_memslots *slots,
1384 			       struct kvm_memory_slot *slot)
1385 {
1386 	rb_erase(&slot->gfn_node[slots->node_idx], &slots->gfn_tree);
1387 }
1388 
kvm_replace_gfn_node(struct kvm_memslots * slots,struct kvm_memory_slot * old,struct kvm_memory_slot * new)1389 static void kvm_replace_gfn_node(struct kvm_memslots *slots,
1390 				 struct kvm_memory_slot *old,
1391 				 struct kvm_memory_slot *new)
1392 {
1393 	int idx = slots->node_idx;
1394 
1395 	WARN_ON_ONCE(old->base_gfn != new->base_gfn);
1396 
1397 	rb_replace_node(&old->gfn_node[idx], &new->gfn_node[idx],
1398 			&slots->gfn_tree);
1399 }
1400 
1401 /*
1402  * Replace @old with @new in the inactive memslots.
1403  *
1404  * With NULL @old this simply adds @new.
1405  * With NULL @new this simply removes @old.
1406  *
1407  * If @new is non-NULL its hva_node[slots_idx] range has to be set
1408  * appropriately.
1409  */
kvm_replace_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * new)1410 static void kvm_replace_memslot(struct kvm *kvm,
1411 				struct kvm_memory_slot *old,
1412 				struct kvm_memory_slot *new)
1413 {
1414 	int as_id = kvm_memslots_get_as_id(old, new);
1415 	struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1416 	int idx = slots->node_idx;
1417 
1418 	if (old) {
1419 		hash_del(&old->id_node[idx]);
1420 		interval_tree_remove(&old->hva_node[idx], &slots->hva_tree);
1421 
1422 		if ((long)old == atomic_long_read(&slots->last_used_slot))
1423 			atomic_long_set(&slots->last_used_slot, (long)new);
1424 
1425 		if (!new) {
1426 			kvm_erase_gfn_node(slots, old);
1427 			return;
1428 		}
1429 	}
1430 
1431 	/*
1432 	 * Initialize @new's hva range.  Do this even when replacing an @old
1433 	 * slot, kvm_copy_memslot() deliberately does not touch node data.
1434 	 */
1435 	new->hva_node[idx].start = new->userspace_addr;
1436 	new->hva_node[idx].last = new->userspace_addr +
1437 				  (new->npages << PAGE_SHIFT) - 1;
1438 
1439 	/*
1440 	 * (Re)Add the new memslot.  There is no O(1) interval_tree_replace(),
1441 	 * hva_node needs to be swapped with remove+insert even though hva can't
1442 	 * change when replacing an existing slot.
1443 	 */
1444 	hash_add(slots->id_hash, &new->id_node[idx], new->id);
1445 	interval_tree_insert(&new->hva_node[idx], &slots->hva_tree);
1446 
1447 	/*
1448 	 * If the memslot gfn is unchanged, rb_replace_node() can be used to
1449 	 * switch the node in the gfn tree instead of removing the old and
1450 	 * inserting the new as two separate operations. Replacement is a
1451 	 * single O(1) operation versus two O(log(n)) operations for
1452 	 * remove+insert.
1453 	 */
1454 	if (old && old->base_gfn == new->base_gfn) {
1455 		kvm_replace_gfn_node(slots, old, new);
1456 	} else {
1457 		if (old)
1458 			kvm_erase_gfn_node(slots, old);
1459 		kvm_insert_gfn_node(slots, new);
1460 	}
1461 }
1462 
check_memory_region_flags(const struct kvm_userspace_memory_region * mem)1463 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1464 {
1465 	u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1466 
1467 #ifdef __KVM_HAVE_READONLY_MEM
1468 	valid_flags |= KVM_MEM_READONLY;
1469 #endif
1470 
1471 	if (mem->flags & ~valid_flags)
1472 		return -EINVAL;
1473 
1474 	return 0;
1475 }
1476 
kvm_swap_active_memslots(struct kvm * kvm,int as_id)1477 static void kvm_swap_active_memslots(struct kvm *kvm, int as_id)
1478 {
1479 	struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1480 
1481 	/* Grab the generation from the activate memslots. */
1482 	u64 gen = __kvm_memslots(kvm, as_id)->generation;
1483 
1484 	WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1485 	slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1486 
1487 	/*
1488 	 * Do not store the new memslots while there are invalidations in
1489 	 * progress, otherwise the locking in invalidate_range_start and
1490 	 * invalidate_range_end will be unbalanced.
1491 	 */
1492 	spin_lock(&kvm->mn_invalidate_lock);
1493 	prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
1494 	while (kvm->mn_active_invalidate_count) {
1495 		set_current_state(TASK_UNINTERRUPTIBLE);
1496 		spin_unlock(&kvm->mn_invalidate_lock);
1497 		schedule();
1498 		spin_lock(&kvm->mn_invalidate_lock);
1499 	}
1500 	finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
1501 	rcu_assign_pointer(kvm->memslots[as_id], slots);
1502 	spin_unlock(&kvm->mn_invalidate_lock);
1503 
1504 	/*
1505 	 * Acquired in kvm_set_memslot. Must be released before synchronize
1506 	 * SRCU below in order to avoid deadlock with another thread
1507 	 * acquiring the slots_arch_lock in an srcu critical section.
1508 	 */
1509 	mutex_unlock(&kvm->slots_arch_lock);
1510 
1511 	synchronize_srcu_expedited(&kvm->srcu);
1512 
1513 	/*
1514 	 * Increment the new memslot generation a second time, dropping the
1515 	 * update in-progress flag and incrementing the generation based on
1516 	 * the number of address spaces.  This provides a unique and easily
1517 	 * identifiable generation number while the memslots are in flux.
1518 	 */
1519 	gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1520 
1521 	/*
1522 	 * Generations must be unique even across address spaces.  We do not need
1523 	 * a global counter for that, instead the generation space is evenly split
1524 	 * across address spaces.  For example, with two address spaces, address
1525 	 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1526 	 * use generations 1, 3, 5, ...
1527 	 */
1528 	gen += KVM_ADDRESS_SPACE_NUM;
1529 
1530 	kvm_arch_memslots_updated(kvm, gen);
1531 
1532 	slots->generation = gen;
1533 }
1534 
kvm_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)1535 static int kvm_prepare_memory_region(struct kvm *kvm,
1536 				     const struct kvm_memory_slot *old,
1537 				     struct kvm_memory_slot *new,
1538 				     enum kvm_mr_change change)
1539 {
1540 	int r;
1541 
1542 	/*
1543 	 * If dirty logging is disabled, nullify the bitmap; the old bitmap
1544 	 * will be freed on "commit".  If logging is enabled in both old and
1545 	 * new, reuse the existing bitmap.  If logging is enabled only in the
1546 	 * new and KVM isn't using a ring buffer, allocate and initialize a
1547 	 * new bitmap.
1548 	 */
1549 	if (change != KVM_MR_DELETE) {
1550 		if (!(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
1551 			new->dirty_bitmap = NULL;
1552 		else if (old && old->dirty_bitmap)
1553 			new->dirty_bitmap = old->dirty_bitmap;
1554 		else if (!kvm->dirty_ring_size) {
1555 			r = kvm_alloc_dirty_bitmap(new);
1556 			if (r)
1557 				return r;
1558 
1559 			if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1560 				bitmap_set(new->dirty_bitmap, 0, new->npages);
1561 		}
1562 	}
1563 
1564 	r = kvm_arch_prepare_memory_region(kvm, old, new, change);
1565 
1566 	/* Free the bitmap on failure if it was allocated above. */
1567 	if (r && new && new->dirty_bitmap && (!old || !old->dirty_bitmap))
1568 		kvm_destroy_dirty_bitmap(new);
1569 
1570 	return r;
1571 }
1572 
kvm_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)1573 static void kvm_commit_memory_region(struct kvm *kvm,
1574 				     struct kvm_memory_slot *old,
1575 				     const struct kvm_memory_slot *new,
1576 				     enum kvm_mr_change change)
1577 {
1578 	/*
1579 	 * Update the total number of memslot pages before calling the arch
1580 	 * hook so that architectures can consume the result directly.
1581 	 */
1582 	if (change == KVM_MR_DELETE)
1583 		kvm->nr_memslot_pages -= old->npages;
1584 	else if (change == KVM_MR_CREATE)
1585 		kvm->nr_memslot_pages += new->npages;
1586 
1587 	kvm_arch_commit_memory_region(kvm, old, new, change);
1588 
1589 	switch (change) {
1590 	case KVM_MR_CREATE:
1591 		/* Nothing more to do. */
1592 		break;
1593 	case KVM_MR_DELETE:
1594 		/* Free the old memslot and all its metadata. */
1595 		kvm_free_memslot(kvm, old);
1596 		break;
1597 	case KVM_MR_MOVE:
1598 	case KVM_MR_FLAGS_ONLY:
1599 		/*
1600 		 * Free the dirty bitmap as needed; the below check encompasses
1601 		 * both the flags and whether a ring buffer is being used)
1602 		 */
1603 		if (old->dirty_bitmap && !new->dirty_bitmap)
1604 			kvm_destroy_dirty_bitmap(old);
1605 
1606 		/*
1607 		 * The final quirk.  Free the detached, old slot, but only its
1608 		 * memory, not any metadata.  Metadata, including arch specific
1609 		 * data, may be reused by @new.
1610 		 */
1611 		kfree(old);
1612 		break;
1613 	default:
1614 		BUG();
1615 	}
1616 }
1617 
1618 /*
1619  * Activate @new, which must be installed in the inactive slots by the caller,
1620  * by swapping the active slots and then propagating @new to @old once @old is
1621  * unreachable and can be safely modified.
1622  *
1623  * With NULL @old this simply adds @new to @active (while swapping the sets).
1624  * With NULL @new this simply removes @old from @active and frees it
1625  * (while also swapping the sets).
1626  */
kvm_activate_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * new)1627 static void kvm_activate_memslot(struct kvm *kvm,
1628 				 struct kvm_memory_slot *old,
1629 				 struct kvm_memory_slot *new)
1630 {
1631 	int as_id = kvm_memslots_get_as_id(old, new);
1632 
1633 	kvm_swap_active_memslots(kvm, as_id);
1634 
1635 	/* Propagate the new memslot to the now inactive memslots. */
1636 	kvm_replace_memslot(kvm, old, new);
1637 }
1638 
kvm_copy_memslot(struct kvm_memory_slot * dest,const struct kvm_memory_slot * src)1639 static void kvm_copy_memslot(struct kvm_memory_slot *dest,
1640 			     const struct kvm_memory_slot *src)
1641 {
1642 	dest->base_gfn = src->base_gfn;
1643 	dest->npages = src->npages;
1644 	dest->dirty_bitmap = src->dirty_bitmap;
1645 	dest->arch = src->arch;
1646 	dest->userspace_addr = src->userspace_addr;
1647 	dest->flags = src->flags;
1648 	dest->id = src->id;
1649 	dest->as_id = src->as_id;
1650 }
1651 
kvm_invalidate_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * invalid_slot)1652 static void kvm_invalidate_memslot(struct kvm *kvm,
1653 				   struct kvm_memory_slot *old,
1654 				   struct kvm_memory_slot *invalid_slot)
1655 {
1656 	/*
1657 	 * Mark the current slot INVALID.  As with all memslot modifications,
1658 	 * this must be done on an unreachable slot to avoid modifying the
1659 	 * current slot in the active tree.
1660 	 */
1661 	kvm_copy_memslot(invalid_slot, old);
1662 	invalid_slot->flags |= KVM_MEMSLOT_INVALID;
1663 	kvm_replace_memslot(kvm, old, invalid_slot);
1664 
1665 	/*
1666 	 * Activate the slot that is now marked INVALID, but don't propagate
1667 	 * the slot to the now inactive slots. The slot is either going to be
1668 	 * deleted or recreated as a new slot.
1669 	 */
1670 	kvm_swap_active_memslots(kvm, old->as_id);
1671 
1672 	/*
1673 	 * From this point no new shadow pages pointing to a deleted, or moved,
1674 	 * memslot will be created.  Validation of sp->gfn happens in:
1675 	 *	- gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1676 	 *	- kvm_is_visible_gfn (mmu_check_root)
1677 	 */
1678 	kvm_arch_flush_shadow_memslot(kvm, old);
1679 	kvm_arch_guest_memory_reclaimed(kvm);
1680 
1681 	/* Was released by kvm_swap_active_memslots, reacquire. */
1682 	mutex_lock(&kvm->slots_arch_lock);
1683 
1684 	/*
1685 	 * Copy the arch-specific field of the newly-installed slot back to the
1686 	 * old slot as the arch data could have changed between releasing
1687 	 * slots_arch_lock in install_new_memslots() and re-acquiring the lock
1688 	 * above.  Writers are required to retrieve memslots *after* acquiring
1689 	 * slots_arch_lock, thus the active slot's data is guaranteed to be fresh.
1690 	 */
1691 	old->arch = invalid_slot->arch;
1692 }
1693 
kvm_create_memslot(struct kvm * kvm,struct kvm_memory_slot * new)1694 static void kvm_create_memslot(struct kvm *kvm,
1695 			       struct kvm_memory_slot *new)
1696 {
1697 	/* Add the new memslot to the inactive set and activate. */
1698 	kvm_replace_memslot(kvm, NULL, new);
1699 	kvm_activate_memslot(kvm, NULL, new);
1700 }
1701 
kvm_delete_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * invalid_slot)1702 static void kvm_delete_memslot(struct kvm *kvm,
1703 			       struct kvm_memory_slot *old,
1704 			       struct kvm_memory_slot *invalid_slot)
1705 {
1706 	/*
1707 	 * Remove the old memslot (in the inactive memslots) by passing NULL as
1708 	 * the "new" slot, and for the invalid version in the active slots.
1709 	 */
1710 	kvm_replace_memslot(kvm, old, NULL);
1711 	kvm_activate_memslot(kvm, invalid_slot, NULL);
1712 }
1713 
kvm_move_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * new,struct kvm_memory_slot * invalid_slot)1714 static void kvm_move_memslot(struct kvm *kvm,
1715 			     struct kvm_memory_slot *old,
1716 			     struct kvm_memory_slot *new,
1717 			     struct kvm_memory_slot *invalid_slot)
1718 {
1719 	/*
1720 	 * Replace the old memslot in the inactive slots, and then swap slots
1721 	 * and replace the current INVALID with the new as well.
1722 	 */
1723 	kvm_replace_memslot(kvm, old, new);
1724 	kvm_activate_memslot(kvm, invalid_slot, new);
1725 }
1726 
kvm_update_flags_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * new)1727 static void kvm_update_flags_memslot(struct kvm *kvm,
1728 				     struct kvm_memory_slot *old,
1729 				     struct kvm_memory_slot *new)
1730 {
1731 	/*
1732 	 * Similar to the MOVE case, but the slot doesn't need to be zapped as
1733 	 * an intermediate step. Instead, the old memslot is simply replaced
1734 	 * with a new, updated copy in both memslot sets.
1735 	 */
1736 	kvm_replace_memslot(kvm, old, new);
1737 	kvm_activate_memslot(kvm, old, new);
1738 }
1739 
kvm_set_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)1740 static int kvm_set_memslot(struct kvm *kvm,
1741 			   struct kvm_memory_slot *old,
1742 			   struct kvm_memory_slot *new,
1743 			   enum kvm_mr_change change)
1744 {
1745 	struct kvm_memory_slot *invalid_slot;
1746 	int r;
1747 
1748 	/*
1749 	 * Released in kvm_swap_active_memslots.
1750 	 *
1751 	 * Must be held from before the current memslots are copied until
1752 	 * after the new memslots are installed with rcu_assign_pointer,
1753 	 * then released before the synchronize srcu in kvm_swap_active_memslots.
1754 	 *
1755 	 * When modifying memslots outside of the slots_lock, must be held
1756 	 * before reading the pointer to the current memslots until after all
1757 	 * changes to those memslots are complete.
1758 	 *
1759 	 * These rules ensure that installing new memslots does not lose
1760 	 * changes made to the previous memslots.
1761 	 */
1762 	mutex_lock(&kvm->slots_arch_lock);
1763 
1764 	/*
1765 	 * Invalidate the old slot if it's being deleted or moved.  This is
1766 	 * done prior to actually deleting/moving the memslot to allow vCPUs to
1767 	 * continue running by ensuring there are no mappings or shadow pages
1768 	 * for the memslot when it is deleted/moved.  Without pre-invalidation
1769 	 * (and without a lock), a window would exist between effecting the
1770 	 * delete/move and committing the changes in arch code where KVM or a
1771 	 * guest could access a non-existent memslot.
1772 	 *
1773 	 * Modifications are done on a temporary, unreachable slot.  The old
1774 	 * slot needs to be preserved in case a later step fails and the
1775 	 * invalidation needs to be reverted.
1776 	 */
1777 	if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1778 		invalid_slot = kzalloc(sizeof(*invalid_slot), GFP_KERNEL_ACCOUNT);
1779 		if (!invalid_slot) {
1780 			mutex_unlock(&kvm->slots_arch_lock);
1781 			return -ENOMEM;
1782 		}
1783 		kvm_invalidate_memslot(kvm, old, invalid_slot);
1784 	}
1785 
1786 	r = kvm_prepare_memory_region(kvm, old, new, change);
1787 	if (r) {
1788 		/*
1789 		 * For DELETE/MOVE, revert the above INVALID change.  No
1790 		 * modifications required since the original slot was preserved
1791 		 * in the inactive slots.  Changing the active memslots also
1792 		 * release slots_arch_lock.
1793 		 */
1794 		if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1795 			kvm_activate_memslot(kvm, invalid_slot, old);
1796 			kfree(invalid_slot);
1797 		} else {
1798 			mutex_unlock(&kvm->slots_arch_lock);
1799 		}
1800 		return r;
1801 	}
1802 
1803 	/*
1804 	 * For DELETE and MOVE, the working slot is now active as the INVALID
1805 	 * version of the old slot.  MOVE is particularly special as it reuses
1806 	 * the old slot and returns a copy of the old slot (in working_slot).
1807 	 * For CREATE, there is no old slot.  For DELETE and FLAGS_ONLY, the
1808 	 * old slot is detached but otherwise preserved.
1809 	 */
1810 	if (change == KVM_MR_CREATE)
1811 		kvm_create_memslot(kvm, new);
1812 	else if (change == KVM_MR_DELETE)
1813 		kvm_delete_memslot(kvm, old, invalid_slot);
1814 	else if (change == KVM_MR_MOVE)
1815 		kvm_move_memslot(kvm, old, new, invalid_slot);
1816 	else if (change == KVM_MR_FLAGS_ONLY)
1817 		kvm_update_flags_memslot(kvm, old, new);
1818 	else
1819 		BUG();
1820 
1821 	/* Free the temporary INVALID slot used for DELETE and MOVE. */
1822 	if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1823 		kfree(invalid_slot);
1824 
1825 	/*
1826 	 * No need to refresh new->arch, changes after dropping slots_arch_lock
1827 	 * will directly hit the final, active memslot.  Architectures are
1828 	 * responsible for knowing that new->arch may be stale.
1829 	 */
1830 	kvm_commit_memory_region(kvm, old, new, change);
1831 
1832 	return 0;
1833 }
1834 
kvm_check_memslot_overlap(struct kvm_memslots * slots,int id,gfn_t start,gfn_t end)1835 static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,
1836 				      gfn_t start, gfn_t end)
1837 {
1838 	struct kvm_memslot_iter iter;
1839 
1840 	kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {
1841 		if (iter.slot->id != id)
1842 			return true;
1843 	}
1844 
1845 	return false;
1846 }
1847 
1848 /*
1849  * Allocate some memory and give it an address in the guest physical address
1850  * space.
1851  *
1852  * Discontiguous memory is allowed, mostly for framebuffers.
1853  *
1854  * Must be called holding kvm->slots_lock for write.
1855  */
__kvm_set_memory_region(struct kvm * kvm,const struct kvm_userspace_memory_region * mem)1856 int __kvm_set_memory_region(struct kvm *kvm,
1857 			    const struct kvm_userspace_memory_region *mem)
1858 {
1859 	struct kvm_memory_slot *old, *new;
1860 	struct kvm_memslots *slots;
1861 	enum kvm_mr_change change;
1862 	unsigned long npages;
1863 	gfn_t base_gfn;
1864 	int as_id, id;
1865 	int r;
1866 
1867 	r = check_memory_region_flags(mem);
1868 	if (r)
1869 		return r;
1870 
1871 	as_id = mem->slot >> 16;
1872 	id = (u16)mem->slot;
1873 
1874 	/* General sanity checks */
1875 	if ((mem->memory_size & (PAGE_SIZE - 1)) ||
1876 	    (mem->memory_size != (unsigned long)mem->memory_size))
1877 		return -EINVAL;
1878 	if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1879 		return -EINVAL;
1880 	/* We can read the guest memory with __xxx_user() later on. */
1881 	if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1882 	    (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1883 	     !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1884 			mem->memory_size))
1885 		return -EINVAL;
1886 	if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1887 		return -EINVAL;
1888 	if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1889 		return -EINVAL;
1890 	if ((mem->memory_size >> PAGE_SHIFT) > KVM_MEM_MAX_NR_PAGES)
1891 		return -EINVAL;
1892 
1893 	slots = __kvm_memslots(kvm, as_id);
1894 
1895 	/*
1896 	 * Note, the old memslot (and the pointer itself!) may be invalidated
1897 	 * and/or destroyed by kvm_set_memslot().
1898 	 */
1899 	old = id_to_memslot(slots, id);
1900 
1901 	if (!mem->memory_size) {
1902 		if (!old || !old->npages)
1903 			return -EINVAL;
1904 
1905 		if (WARN_ON_ONCE(kvm->nr_memslot_pages < old->npages))
1906 			return -EIO;
1907 
1908 		return kvm_set_memslot(kvm, old, NULL, KVM_MR_DELETE);
1909 	}
1910 
1911 	base_gfn = (mem->guest_phys_addr >> PAGE_SHIFT);
1912 	npages = (mem->memory_size >> PAGE_SHIFT);
1913 
1914 	if (!old || !old->npages) {
1915 		change = KVM_MR_CREATE;
1916 
1917 		/*
1918 		 * To simplify KVM internals, the total number of pages across
1919 		 * all memslots must fit in an unsigned long.
1920 		 */
1921 		if ((kvm->nr_memslot_pages + npages) < kvm->nr_memslot_pages)
1922 			return -EINVAL;
1923 	} else { /* Modify an existing slot. */
1924 		if ((mem->userspace_addr != old->userspace_addr) ||
1925 		    (npages != old->npages) ||
1926 		    ((mem->flags ^ old->flags) & KVM_MEM_READONLY))
1927 			return -EINVAL;
1928 
1929 		if (base_gfn != old->base_gfn)
1930 			change = KVM_MR_MOVE;
1931 		else if (mem->flags != old->flags)
1932 			change = KVM_MR_FLAGS_ONLY;
1933 		else /* Nothing to change. */
1934 			return 0;
1935 	}
1936 
1937 	if ((change == KVM_MR_CREATE || change == KVM_MR_MOVE) &&
1938 	    kvm_check_memslot_overlap(slots, id, base_gfn, base_gfn + npages))
1939 		return -EEXIST;
1940 
1941 	/* Allocate a slot that will persist in the memslot. */
1942 	new = kzalloc(sizeof(*new), GFP_KERNEL_ACCOUNT);
1943 	if (!new)
1944 		return -ENOMEM;
1945 
1946 	new->as_id = as_id;
1947 	new->id = id;
1948 	new->base_gfn = base_gfn;
1949 	new->npages = npages;
1950 	new->flags = mem->flags;
1951 	new->userspace_addr = mem->userspace_addr;
1952 
1953 	r = kvm_set_memslot(kvm, old, new, change);
1954 	if (r)
1955 		kfree(new);
1956 	return r;
1957 }
1958 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1959 
kvm_set_memory_region(struct kvm * kvm,const struct kvm_userspace_memory_region * mem)1960 int kvm_set_memory_region(struct kvm *kvm,
1961 			  const struct kvm_userspace_memory_region *mem)
1962 {
1963 	int r;
1964 
1965 	mutex_lock(&kvm->slots_lock);
1966 	r = __kvm_set_memory_region(kvm, mem);
1967 	mutex_unlock(&kvm->slots_lock);
1968 	return r;
1969 }
1970 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1971 
kvm_vm_ioctl_set_memory_region(struct kvm * kvm,struct kvm_userspace_memory_region * mem)1972 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1973 					  struct kvm_userspace_memory_region *mem)
1974 {
1975 	if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1976 		return -EINVAL;
1977 
1978 	return kvm_set_memory_region(kvm, mem);
1979 }
1980 
1981 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1982 /**
1983  * kvm_get_dirty_log - get a snapshot of dirty pages
1984  * @kvm:	pointer to kvm instance
1985  * @log:	slot id and address to which we copy the log
1986  * @is_dirty:	set to '1' if any dirty pages were found
1987  * @memslot:	set to the associated memslot, always valid on success
1988  */
kvm_get_dirty_log(struct kvm * kvm,struct kvm_dirty_log * log,int * is_dirty,struct kvm_memory_slot ** memslot)1989 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1990 		      int *is_dirty, struct kvm_memory_slot **memslot)
1991 {
1992 	struct kvm_memslots *slots;
1993 	int i, as_id, id;
1994 	unsigned long n;
1995 	unsigned long any = 0;
1996 
1997 	/* Dirty ring tracking is exclusive to dirty log tracking */
1998 	if (kvm->dirty_ring_size)
1999 		return -ENXIO;
2000 
2001 	*memslot = NULL;
2002 	*is_dirty = 0;
2003 
2004 	as_id = log->slot >> 16;
2005 	id = (u16)log->slot;
2006 	if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2007 		return -EINVAL;
2008 
2009 	slots = __kvm_memslots(kvm, as_id);
2010 	*memslot = id_to_memslot(slots, id);
2011 	if (!(*memslot) || !(*memslot)->dirty_bitmap)
2012 		return -ENOENT;
2013 
2014 	kvm_arch_sync_dirty_log(kvm, *memslot);
2015 
2016 	n = kvm_dirty_bitmap_bytes(*memslot);
2017 
2018 	for (i = 0; !any && i < n/sizeof(long); ++i)
2019 		any = (*memslot)->dirty_bitmap[i];
2020 
2021 	if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
2022 		return -EFAULT;
2023 
2024 	if (any)
2025 		*is_dirty = 1;
2026 	return 0;
2027 }
2028 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
2029 
2030 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2031 /**
2032  * kvm_get_dirty_log_protect - get a snapshot of dirty pages
2033  *	and reenable dirty page tracking for the corresponding pages.
2034  * @kvm:	pointer to kvm instance
2035  * @log:	slot id and address to which we copy the log
2036  *
2037  * We need to keep it in mind that VCPU threads can write to the bitmap
2038  * concurrently. So, to avoid losing track of dirty pages we keep the
2039  * following order:
2040  *
2041  *    1. Take a snapshot of the bit and clear it if needed.
2042  *    2. Write protect the corresponding page.
2043  *    3. Copy the snapshot to the userspace.
2044  *    4. Upon return caller flushes TLB's if needed.
2045  *
2046  * Between 2 and 4, the guest may write to the page using the remaining TLB
2047  * entry.  This is not a problem because the page is reported dirty using
2048  * the snapshot taken before and step 4 ensures that writes done after
2049  * exiting to userspace will be logged for the next call.
2050  *
2051  */
kvm_get_dirty_log_protect(struct kvm * kvm,struct kvm_dirty_log * log)2052 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
2053 {
2054 	struct kvm_memslots *slots;
2055 	struct kvm_memory_slot *memslot;
2056 	int i, as_id, id;
2057 	unsigned long n;
2058 	unsigned long *dirty_bitmap;
2059 	unsigned long *dirty_bitmap_buffer;
2060 	bool flush;
2061 
2062 	/* Dirty ring tracking is exclusive to dirty log tracking */
2063 	if (kvm->dirty_ring_size)
2064 		return -ENXIO;
2065 
2066 	as_id = log->slot >> 16;
2067 	id = (u16)log->slot;
2068 	if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2069 		return -EINVAL;
2070 
2071 	slots = __kvm_memslots(kvm, as_id);
2072 	memslot = id_to_memslot(slots, id);
2073 	if (!memslot || !memslot->dirty_bitmap)
2074 		return -ENOENT;
2075 
2076 	dirty_bitmap = memslot->dirty_bitmap;
2077 
2078 	kvm_arch_sync_dirty_log(kvm, memslot);
2079 
2080 	n = kvm_dirty_bitmap_bytes(memslot);
2081 	flush = false;
2082 	if (kvm->manual_dirty_log_protect) {
2083 		/*
2084 		 * Unlike kvm_get_dirty_log, we always return false in *flush,
2085 		 * because no flush is needed until KVM_CLEAR_DIRTY_LOG.  There
2086 		 * is some code duplication between this function and
2087 		 * kvm_get_dirty_log, but hopefully all architecture
2088 		 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
2089 		 * can be eliminated.
2090 		 */
2091 		dirty_bitmap_buffer = dirty_bitmap;
2092 	} else {
2093 		dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2094 		memset(dirty_bitmap_buffer, 0, n);
2095 
2096 		KVM_MMU_LOCK(kvm);
2097 		for (i = 0; i < n / sizeof(long); i++) {
2098 			unsigned long mask;
2099 			gfn_t offset;
2100 
2101 			if (!dirty_bitmap[i])
2102 				continue;
2103 
2104 			flush = true;
2105 			mask = xchg(&dirty_bitmap[i], 0);
2106 			dirty_bitmap_buffer[i] = mask;
2107 
2108 			offset = i * BITS_PER_LONG;
2109 			kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2110 								offset, mask);
2111 		}
2112 		KVM_MMU_UNLOCK(kvm);
2113 	}
2114 
2115 	if (flush)
2116 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2117 
2118 	if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
2119 		return -EFAULT;
2120 	return 0;
2121 }
2122 
2123 
2124 /**
2125  * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
2126  * @kvm: kvm instance
2127  * @log: slot id and address to which we copy the log
2128  *
2129  * Steps 1-4 below provide general overview of dirty page logging. See
2130  * kvm_get_dirty_log_protect() function description for additional details.
2131  *
2132  * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
2133  * always flush the TLB (step 4) even if previous step failed  and the dirty
2134  * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
2135  * does not preclude user space subsequent dirty log read. Flushing TLB ensures
2136  * writes will be marked dirty for next log read.
2137  *
2138  *   1. Take a snapshot of the bit and clear it if needed.
2139  *   2. Write protect the corresponding page.
2140  *   3. Copy the snapshot to the userspace.
2141  *   4. Flush TLB's if needed.
2142  */
kvm_vm_ioctl_get_dirty_log(struct kvm * kvm,struct kvm_dirty_log * log)2143 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2144 				      struct kvm_dirty_log *log)
2145 {
2146 	int r;
2147 
2148 	mutex_lock(&kvm->slots_lock);
2149 
2150 	r = kvm_get_dirty_log_protect(kvm, log);
2151 
2152 	mutex_unlock(&kvm->slots_lock);
2153 	return r;
2154 }
2155 
2156 /**
2157  * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
2158  *	and reenable dirty page tracking for the corresponding pages.
2159  * @kvm:	pointer to kvm instance
2160  * @log:	slot id and address from which to fetch the bitmap of dirty pages
2161  */
kvm_clear_dirty_log_protect(struct kvm * kvm,struct kvm_clear_dirty_log * log)2162 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
2163 				       struct kvm_clear_dirty_log *log)
2164 {
2165 	struct kvm_memslots *slots;
2166 	struct kvm_memory_slot *memslot;
2167 	int as_id, id;
2168 	gfn_t offset;
2169 	unsigned long i, n;
2170 	unsigned long *dirty_bitmap;
2171 	unsigned long *dirty_bitmap_buffer;
2172 	bool flush;
2173 
2174 	/* Dirty ring tracking is exclusive to dirty log tracking */
2175 	if (kvm->dirty_ring_size)
2176 		return -ENXIO;
2177 
2178 	as_id = log->slot >> 16;
2179 	id = (u16)log->slot;
2180 	if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2181 		return -EINVAL;
2182 
2183 	if (log->first_page & 63)
2184 		return -EINVAL;
2185 
2186 	slots = __kvm_memslots(kvm, as_id);
2187 	memslot = id_to_memslot(slots, id);
2188 	if (!memslot || !memslot->dirty_bitmap)
2189 		return -ENOENT;
2190 
2191 	dirty_bitmap = memslot->dirty_bitmap;
2192 
2193 	n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
2194 
2195 	if (log->first_page > memslot->npages ||
2196 	    log->num_pages > memslot->npages - log->first_page ||
2197 	    (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
2198 	    return -EINVAL;
2199 
2200 	kvm_arch_sync_dirty_log(kvm, memslot);
2201 
2202 	flush = false;
2203 	dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2204 	if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2205 		return -EFAULT;
2206 
2207 	KVM_MMU_LOCK(kvm);
2208 	for (offset = log->first_page, i = offset / BITS_PER_LONG,
2209 		 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2210 	     i++, offset += BITS_PER_LONG) {
2211 		unsigned long mask = *dirty_bitmap_buffer++;
2212 		atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2213 		if (!mask)
2214 			continue;
2215 
2216 		mask &= atomic_long_fetch_andnot(mask, p);
2217 
2218 		/*
2219 		 * mask contains the bits that really have been cleared.  This
2220 		 * never includes any bits beyond the length of the memslot (if
2221 		 * the length is not aligned to 64 pages), therefore it is not
2222 		 * a problem if userspace sets them in log->dirty_bitmap.
2223 		*/
2224 		if (mask) {
2225 			flush = true;
2226 			kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2227 								offset, mask);
2228 		}
2229 	}
2230 	KVM_MMU_UNLOCK(kvm);
2231 
2232 	if (flush)
2233 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2234 
2235 	return 0;
2236 }
2237 
kvm_vm_ioctl_clear_dirty_log(struct kvm * kvm,struct kvm_clear_dirty_log * log)2238 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2239 					struct kvm_clear_dirty_log *log)
2240 {
2241 	int r;
2242 
2243 	mutex_lock(&kvm->slots_lock);
2244 
2245 	r = kvm_clear_dirty_log_protect(kvm, log);
2246 
2247 	mutex_unlock(&kvm->slots_lock);
2248 	return r;
2249 }
2250 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2251 
gfn_to_memslot(struct kvm * kvm,gfn_t gfn)2252 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2253 {
2254 	return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2255 }
2256 EXPORT_SYMBOL_GPL(gfn_to_memslot);
2257 
kvm_vcpu_gfn_to_memslot(struct kvm_vcpu * vcpu,gfn_t gfn)2258 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2259 {
2260 	struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
2261 	u64 gen = slots->generation;
2262 	struct kvm_memory_slot *slot;
2263 
2264 	/*
2265 	 * This also protects against using a memslot from a different address space,
2266 	 * since different address spaces have different generation numbers.
2267 	 */
2268 	if (unlikely(gen != vcpu->last_used_slot_gen)) {
2269 		vcpu->last_used_slot = NULL;
2270 		vcpu->last_used_slot_gen = gen;
2271 	}
2272 
2273 	slot = try_get_memslot(vcpu->last_used_slot, gfn);
2274 	if (slot)
2275 		return slot;
2276 
2277 	/*
2278 	 * Fall back to searching all memslots. We purposely use
2279 	 * search_memslots() instead of __gfn_to_memslot() to avoid
2280 	 * thrashing the VM-wide last_used_slot in kvm_memslots.
2281 	 */
2282 	slot = search_memslots(slots, gfn, false);
2283 	if (slot) {
2284 		vcpu->last_used_slot = slot;
2285 		return slot;
2286 	}
2287 
2288 	return NULL;
2289 }
2290 
kvm_is_visible_gfn(struct kvm * kvm,gfn_t gfn)2291 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
2292 {
2293 	struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
2294 
2295 	return kvm_is_visible_memslot(memslot);
2296 }
2297 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2298 
kvm_vcpu_is_visible_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)2299 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2300 {
2301 	struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2302 
2303 	return kvm_is_visible_memslot(memslot);
2304 }
2305 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2306 
kvm_host_page_size(struct kvm_vcpu * vcpu,gfn_t gfn)2307 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
2308 {
2309 	struct vm_area_struct *vma;
2310 	unsigned long addr, size;
2311 
2312 	size = PAGE_SIZE;
2313 
2314 	addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
2315 	if (kvm_is_error_hva(addr))
2316 		return PAGE_SIZE;
2317 
2318 	mmap_read_lock(current->mm);
2319 	vma = find_vma(current->mm, addr);
2320 	if (!vma)
2321 		goto out;
2322 
2323 	size = vma_kernel_pagesize(vma);
2324 
2325 out:
2326 	mmap_read_unlock(current->mm);
2327 
2328 	return size;
2329 }
2330 
memslot_is_readonly(const struct kvm_memory_slot * slot)2331 static bool memslot_is_readonly(const struct kvm_memory_slot *slot)
2332 {
2333 	return slot->flags & KVM_MEM_READONLY;
2334 }
2335 
__gfn_to_hva_many(const struct kvm_memory_slot * slot,gfn_t gfn,gfn_t * nr_pages,bool write)2336 static unsigned long __gfn_to_hva_many(const struct kvm_memory_slot *slot, gfn_t gfn,
2337 				       gfn_t *nr_pages, bool write)
2338 {
2339 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
2340 		return KVM_HVA_ERR_BAD;
2341 
2342 	if (memslot_is_readonly(slot) && write)
2343 		return KVM_HVA_ERR_RO_BAD;
2344 
2345 	if (nr_pages)
2346 		*nr_pages = slot->npages - (gfn - slot->base_gfn);
2347 
2348 	return __gfn_to_hva_memslot(slot, gfn);
2349 }
2350 
gfn_to_hva_many(struct kvm_memory_slot * slot,gfn_t gfn,gfn_t * nr_pages)2351 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2352 				     gfn_t *nr_pages)
2353 {
2354 	return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2355 }
2356 
gfn_to_hva_memslot(struct kvm_memory_slot * slot,gfn_t gfn)2357 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
2358 					gfn_t gfn)
2359 {
2360 	return gfn_to_hva_many(slot, gfn, NULL);
2361 }
2362 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2363 
gfn_to_hva(struct kvm * kvm,gfn_t gfn)2364 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2365 {
2366 	return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
2367 }
2368 EXPORT_SYMBOL_GPL(gfn_to_hva);
2369 
kvm_vcpu_gfn_to_hva(struct kvm_vcpu * vcpu,gfn_t gfn)2370 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2371 {
2372 	return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2373 }
2374 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2375 
2376 /*
2377  * Return the hva of a @gfn and the R/W attribute if possible.
2378  *
2379  * @slot: the kvm_memory_slot which contains @gfn
2380  * @gfn: the gfn to be translated
2381  * @writable: used to return the read/write attribute of the @slot if the hva
2382  * is valid and @writable is not NULL
2383  */
gfn_to_hva_memslot_prot(struct kvm_memory_slot * slot,gfn_t gfn,bool * writable)2384 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2385 				      gfn_t gfn, bool *writable)
2386 {
2387 	unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2388 
2389 	if (!kvm_is_error_hva(hva) && writable)
2390 		*writable = !memslot_is_readonly(slot);
2391 
2392 	return hva;
2393 }
2394 
gfn_to_hva_prot(struct kvm * kvm,gfn_t gfn,bool * writable)2395 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2396 {
2397 	struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2398 
2399 	return gfn_to_hva_memslot_prot(slot, gfn, writable);
2400 }
2401 
kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu * vcpu,gfn_t gfn,bool * writable)2402 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2403 {
2404 	struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2405 
2406 	return gfn_to_hva_memslot_prot(slot, gfn, writable);
2407 }
2408 
check_user_page_hwpoison(unsigned long addr)2409 static inline int check_user_page_hwpoison(unsigned long addr)
2410 {
2411 	int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
2412 
2413 	rc = get_user_pages(addr, 1, flags, NULL, NULL);
2414 	return rc == -EHWPOISON;
2415 }
2416 
2417 /*
2418  * The fast path to get the writable pfn which will be stored in @pfn,
2419  * true indicates success, otherwise false is returned.  It's also the
2420  * only part that runs if we can in atomic context.
2421  */
hva_to_pfn_fast(unsigned long addr,bool write_fault,bool * writable,kvm_pfn_t * pfn)2422 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2423 			    bool *writable, kvm_pfn_t *pfn)
2424 {
2425 	struct page *page[1];
2426 
2427 	/*
2428 	 * Fast pin a writable pfn only if it is a write fault request
2429 	 * or the caller allows to map a writable pfn for a read fault
2430 	 * request.
2431 	 */
2432 	if (!(write_fault || writable))
2433 		return false;
2434 
2435 	if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2436 		*pfn = page_to_pfn(page[0]);
2437 
2438 		if (writable)
2439 			*writable = true;
2440 		return true;
2441 	}
2442 
2443 	return false;
2444 }
2445 
2446 /*
2447  * The slow path to get the pfn of the specified host virtual address,
2448  * 1 indicates success, -errno is returned if error is detected.
2449  */
hva_to_pfn_slow(unsigned long addr,bool * async,bool write_fault,bool * writable,kvm_pfn_t * pfn)2450 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
2451 			   bool *writable, kvm_pfn_t *pfn)
2452 {
2453 	unsigned int flags = FOLL_HWPOISON;
2454 	struct page *page;
2455 	int npages = 0;
2456 
2457 	might_sleep();
2458 
2459 	if (writable)
2460 		*writable = write_fault;
2461 
2462 	if (write_fault)
2463 		flags |= FOLL_WRITE;
2464 	if (async)
2465 		flags |= FOLL_NOWAIT;
2466 
2467 	npages = get_user_pages_unlocked(addr, 1, &page, flags);
2468 	if (npages != 1)
2469 		return npages;
2470 
2471 	/* map read fault as writable if possible */
2472 	if (unlikely(!write_fault) && writable) {
2473 		struct page *wpage;
2474 
2475 		if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2476 			*writable = true;
2477 			put_page(page);
2478 			page = wpage;
2479 		}
2480 	}
2481 	*pfn = page_to_pfn(page);
2482 	return npages;
2483 }
2484 
vma_is_valid(struct vm_area_struct * vma,bool write_fault)2485 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2486 {
2487 	if (unlikely(!(vma->vm_flags & VM_READ)))
2488 		return false;
2489 
2490 	if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2491 		return false;
2492 
2493 	return true;
2494 }
2495 
kvm_try_get_pfn(kvm_pfn_t pfn)2496 static int kvm_try_get_pfn(kvm_pfn_t pfn)
2497 {
2498 	if (kvm_is_reserved_pfn(pfn))
2499 		return 1;
2500 	return get_page_unless_zero(pfn_to_page(pfn));
2501 }
2502 
hva_to_pfn_remapped(struct vm_area_struct * vma,unsigned long addr,bool write_fault,bool * writable,kvm_pfn_t * p_pfn)2503 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2504 			       unsigned long addr, bool write_fault,
2505 			       bool *writable, kvm_pfn_t *p_pfn)
2506 {
2507 	kvm_pfn_t pfn;
2508 	pte_t *ptep;
2509 	spinlock_t *ptl;
2510 	int r;
2511 
2512 	r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2513 	if (r) {
2514 		/*
2515 		 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2516 		 * not call the fault handler, so do it here.
2517 		 */
2518 		bool unlocked = false;
2519 		r = fixup_user_fault(current->mm, addr,
2520 				     (write_fault ? FAULT_FLAG_WRITE : 0),
2521 				     &unlocked);
2522 		if (unlocked)
2523 			return -EAGAIN;
2524 		if (r)
2525 			return r;
2526 
2527 		r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2528 		if (r)
2529 			return r;
2530 	}
2531 
2532 	if (write_fault && !pte_write(*ptep)) {
2533 		pfn = KVM_PFN_ERR_RO_FAULT;
2534 		goto out;
2535 	}
2536 
2537 	if (writable)
2538 		*writable = pte_write(*ptep);
2539 	pfn = pte_pfn(*ptep);
2540 
2541 	/*
2542 	 * Get a reference here because callers of *hva_to_pfn* and
2543 	 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2544 	 * returned pfn.  This is only needed if the VMA has VM_MIXEDMAP
2545 	 * set, but the kvm_try_get_pfn/kvm_release_pfn_clean pair will
2546 	 * simply do nothing for reserved pfns.
2547 	 *
2548 	 * Whoever called remap_pfn_range is also going to call e.g.
2549 	 * unmap_mapping_range before the underlying pages are freed,
2550 	 * causing a call to our MMU notifier.
2551 	 *
2552 	 * Certain IO or PFNMAP mappings can be backed with valid
2553 	 * struct pages, but be allocated without refcounting e.g.,
2554 	 * tail pages of non-compound higher order allocations, which
2555 	 * would then underflow the refcount when the caller does the
2556 	 * required put_page. Don't allow those pages here.
2557 	 */
2558 	if (!kvm_try_get_pfn(pfn))
2559 		r = -EFAULT;
2560 
2561 out:
2562 	pte_unmap_unlock(ptep, ptl);
2563 	*p_pfn = pfn;
2564 
2565 	return r;
2566 }
2567 
2568 /*
2569  * Pin guest page in memory and return its pfn.
2570  * @addr: host virtual address which maps memory to the guest
2571  * @atomic: whether this function can sleep
2572  * @async: whether this function need to wait IO complete if the
2573  *         host page is not in the memory
2574  * @write_fault: whether we should get a writable host page
2575  * @writable: whether it allows to map a writable host page for !@write_fault
2576  *
2577  * The function will map a writable host page for these two cases:
2578  * 1): @write_fault = true
2579  * 2): @write_fault = false && @writable, @writable will tell the caller
2580  *     whether the mapping is writable.
2581  */
hva_to_pfn(unsigned long addr,bool atomic,bool * async,bool write_fault,bool * writable)2582 kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2583 		     bool write_fault, bool *writable)
2584 {
2585 	struct vm_area_struct *vma;
2586 	kvm_pfn_t pfn = 0;
2587 	int npages, r;
2588 
2589 	/* we can do it either atomically or asynchronously, not both */
2590 	BUG_ON(atomic && async);
2591 
2592 	if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2593 		return pfn;
2594 
2595 	if (atomic)
2596 		return KVM_PFN_ERR_FAULT;
2597 
2598 	npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2599 	if (npages == 1)
2600 		return pfn;
2601 
2602 	mmap_read_lock(current->mm);
2603 	if (npages == -EHWPOISON ||
2604 	      (!async && check_user_page_hwpoison(addr))) {
2605 		pfn = KVM_PFN_ERR_HWPOISON;
2606 		goto exit;
2607 	}
2608 
2609 retry:
2610 	vma = vma_lookup(current->mm, addr);
2611 
2612 	if (vma == NULL)
2613 		pfn = KVM_PFN_ERR_FAULT;
2614 	else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2615 		r = hva_to_pfn_remapped(vma, addr, write_fault, writable, &pfn);
2616 		if (r == -EAGAIN)
2617 			goto retry;
2618 		if (r < 0)
2619 			pfn = KVM_PFN_ERR_FAULT;
2620 	} else {
2621 		if (async && vma_is_valid(vma, write_fault))
2622 			*async = true;
2623 		pfn = KVM_PFN_ERR_FAULT;
2624 	}
2625 exit:
2626 	mmap_read_unlock(current->mm);
2627 	return pfn;
2628 }
2629 
__gfn_to_pfn_memslot(const struct kvm_memory_slot * slot,gfn_t gfn,bool atomic,bool * async,bool write_fault,bool * writable,hva_t * hva)2630 kvm_pfn_t __gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn,
2631 			       bool atomic, bool *async, bool write_fault,
2632 			       bool *writable, hva_t *hva)
2633 {
2634 	unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2635 
2636 	if (hva)
2637 		*hva = addr;
2638 
2639 	if (addr == KVM_HVA_ERR_RO_BAD) {
2640 		if (writable)
2641 			*writable = false;
2642 		return KVM_PFN_ERR_RO_FAULT;
2643 	}
2644 
2645 	if (kvm_is_error_hva(addr)) {
2646 		if (writable)
2647 			*writable = false;
2648 		return KVM_PFN_NOSLOT;
2649 	}
2650 
2651 	/* Do not map writable pfn in the readonly memslot. */
2652 	if (writable && memslot_is_readonly(slot)) {
2653 		*writable = false;
2654 		writable = NULL;
2655 	}
2656 
2657 	return hva_to_pfn(addr, atomic, async, write_fault,
2658 			  writable);
2659 }
2660 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2661 
gfn_to_pfn_prot(struct kvm * kvm,gfn_t gfn,bool write_fault,bool * writable)2662 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2663 		      bool *writable)
2664 {
2665 	return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2666 				    write_fault, writable, NULL);
2667 }
2668 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2669 
gfn_to_pfn_memslot(const struct kvm_memory_slot * slot,gfn_t gfn)2670 kvm_pfn_t gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn)
2671 {
2672 	return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2673 }
2674 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2675 
gfn_to_pfn_memslot_atomic(const struct kvm_memory_slot * slot,gfn_t gfn)2676 kvm_pfn_t gfn_to_pfn_memslot_atomic(const struct kvm_memory_slot *slot, gfn_t gfn)
2677 {
2678 	return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2679 }
2680 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2681 
kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu * vcpu,gfn_t gfn)2682 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2683 {
2684 	return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2685 }
2686 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2687 
gfn_to_pfn(struct kvm * kvm,gfn_t gfn)2688 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2689 {
2690 	return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2691 }
2692 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2693 
kvm_vcpu_gfn_to_pfn(struct kvm_vcpu * vcpu,gfn_t gfn)2694 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2695 {
2696 	return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2697 }
2698 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2699 
gfn_to_page_many_atomic(struct kvm_memory_slot * slot,gfn_t gfn,struct page ** pages,int nr_pages)2700 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2701 			    struct page **pages, int nr_pages)
2702 {
2703 	unsigned long addr;
2704 	gfn_t entry = 0;
2705 
2706 	addr = gfn_to_hva_many(slot, gfn, &entry);
2707 	if (kvm_is_error_hva(addr))
2708 		return -1;
2709 
2710 	if (entry < nr_pages)
2711 		return 0;
2712 
2713 	return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2714 }
2715 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2716 
kvm_pfn_to_page(kvm_pfn_t pfn)2717 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2718 {
2719 	if (is_error_noslot_pfn(pfn))
2720 		return KVM_ERR_PTR_BAD_PAGE;
2721 
2722 	if (kvm_is_reserved_pfn(pfn)) {
2723 		WARN_ON(1);
2724 		return KVM_ERR_PTR_BAD_PAGE;
2725 	}
2726 
2727 	return pfn_to_page(pfn);
2728 }
2729 
gfn_to_page(struct kvm * kvm,gfn_t gfn)2730 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2731 {
2732 	kvm_pfn_t pfn;
2733 
2734 	pfn = gfn_to_pfn(kvm, gfn);
2735 
2736 	return kvm_pfn_to_page(pfn);
2737 }
2738 EXPORT_SYMBOL_GPL(gfn_to_page);
2739 
kvm_release_pfn(kvm_pfn_t pfn,bool dirty)2740 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty)
2741 {
2742 	if (pfn == 0)
2743 		return;
2744 
2745 	if (dirty)
2746 		kvm_release_pfn_dirty(pfn);
2747 	else
2748 		kvm_release_pfn_clean(pfn);
2749 }
2750 
kvm_vcpu_map(struct kvm_vcpu * vcpu,gfn_t gfn,struct kvm_host_map * map)2751 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2752 {
2753 	kvm_pfn_t pfn;
2754 	void *hva = NULL;
2755 	struct page *page = KVM_UNMAPPED_PAGE;
2756 
2757 	if (!map)
2758 		return -EINVAL;
2759 
2760 	pfn = gfn_to_pfn(vcpu->kvm, gfn);
2761 	if (is_error_noslot_pfn(pfn))
2762 		return -EINVAL;
2763 
2764 	if (pfn_valid(pfn)) {
2765 		page = pfn_to_page(pfn);
2766 		hva = kmap(page);
2767 #ifdef CONFIG_HAS_IOMEM
2768 	} else {
2769 		hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2770 #endif
2771 	}
2772 
2773 	if (!hva)
2774 		return -EFAULT;
2775 
2776 	map->page = page;
2777 	map->hva = hva;
2778 	map->pfn = pfn;
2779 	map->gfn = gfn;
2780 
2781 	return 0;
2782 }
2783 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2784 
kvm_vcpu_unmap(struct kvm_vcpu * vcpu,struct kvm_host_map * map,bool dirty)2785 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2786 {
2787 	if (!map)
2788 		return;
2789 
2790 	if (!map->hva)
2791 		return;
2792 
2793 	if (map->page != KVM_UNMAPPED_PAGE)
2794 		kunmap(map->page);
2795 #ifdef CONFIG_HAS_IOMEM
2796 	else
2797 		memunmap(map->hva);
2798 #endif
2799 
2800 	if (dirty)
2801 		kvm_vcpu_mark_page_dirty(vcpu, map->gfn);
2802 
2803 	kvm_release_pfn(map->pfn, dirty);
2804 
2805 	map->hva = NULL;
2806 	map->page = NULL;
2807 }
2808 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2809 
kvm_vcpu_gfn_to_page(struct kvm_vcpu * vcpu,gfn_t gfn)2810 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2811 {
2812 	kvm_pfn_t pfn;
2813 
2814 	pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2815 
2816 	return kvm_pfn_to_page(pfn);
2817 }
2818 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2819 
kvm_release_page_clean(struct page * page)2820 void kvm_release_page_clean(struct page *page)
2821 {
2822 	WARN_ON(is_error_page(page));
2823 
2824 	kvm_release_pfn_clean(page_to_pfn(page));
2825 }
2826 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2827 
kvm_release_pfn_clean(kvm_pfn_t pfn)2828 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2829 {
2830 	if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2831 		put_page(pfn_to_page(pfn));
2832 }
2833 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2834 
kvm_release_page_dirty(struct page * page)2835 void kvm_release_page_dirty(struct page *page)
2836 {
2837 	WARN_ON(is_error_page(page));
2838 
2839 	kvm_release_pfn_dirty(page_to_pfn(page));
2840 }
2841 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2842 
kvm_release_pfn_dirty(kvm_pfn_t pfn)2843 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2844 {
2845 	kvm_set_pfn_dirty(pfn);
2846 	kvm_release_pfn_clean(pfn);
2847 }
2848 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2849 
kvm_is_ad_tracked_pfn(kvm_pfn_t pfn)2850 static bool kvm_is_ad_tracked_pfn(kvm_pfn_t pfn)
2851 {
2852 	if (!pfn_valid(pfn))
2853 		return false;
2854 
2855 	/*
2856 	 * Per page-flags.h, pages tagged PG_reserved "should in general not be
2857 	 * touched (e.g. set dirty) except by its owner".
2858 	 */
2859 	return !PageReserved(pfn_to_page(pfn));
2860 }
2861 
kvm_set_pfn_dirty(kvm_pfn_t pfn)2862 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2863 {
2864 	if (kvm_is_ad_tracked_pfn(pfn))
2865 		SetPageDirty(pfn_to_page(pfn));
2866 }
2867 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2868 
kvm_set_pfn_accessed(kvm_pfn_t pfn)2869 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2870 {
2871 	if (kvm_is_ad_tracked_pfn(pfn))
2872 		mark_page_accessed(pfn_to_page(pfn));
2873 }
2874 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2875 
next_segment(unsigned long len,int offset)2876 static int next_segment(unsigned long len, int offset)
2877 {
2878 	if (len > PAGE_SIZE - offset)
2879 		return PAGE_SIZE - offset;
2880 	else
2881 		return len;
2882 }
2883 
__kvm_read_guest_page(struct kvm_memory_slot * slot,gfn_t gfn,void * data,int offset,int len)2884 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2885 				 void *data, int offset, int len)
2886 {
2887 	int r;
2888 	unsigned long addr;
2889 
2890 	addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2891 	if (kvm_is_error_hva(addr))
2892 		return -EFAULT;
2893 	r = __copy_from_user(data, (void __user *)addr + offset, len);
2894 	if (r)
2895 		return -EFAULT;
2896 	return 0;
2897 }
2898 
kvm_read_guest_page(struct kvm * kvm,gfn_t gfn,void * data,int offset,int len)2899 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2900 			int len)
2901 {
2902 	struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2903 
2904 	return __kvm_read_guest_page(slot, gfn, data, offset, len);
2905 }
2906 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2907 
kvm_vcpu_read_guest_page(struct kvm_vcpu * vcpu,gfn_t gfn,void * data,int offset,int len)2908 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2909 			     int offset, int len)
2910 {
2911 	struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2912 
2913 	return __kvm_read_guest_page(slot, gfn, data, offset, len);
2914 }
2915 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2916 
kvm_read_guest(struct kvm * kvm,gpa_t gpa,void * data,unsigned long len)2917 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2918 {
2919 	gfn_t gfn = gpa >> PAGE_SHIFT;
2920 	int seg;
2921 	int offset = offset_in_page(gpa);
2922 	int ret;
2923 
2924 	while ((seg = next_segment(len, offset)) != 0) {
2925 		ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2926 		if (ret < 0)
2927 			return ret;
2928 		offset = 0;
2929 		len -= seg;
2930 		data += seg;
2931 		++gfn;
2932 	}
2933 	return 0;
2934 }
2935 EXPORT_SYMBOL_GPL(kvm_read_guest);
2936 
kvm_vcpu_read_guest(struct kvm_vcpu * vcpu,gpa_t gpa,void * data,unsigned long len)2937 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2938 {
2939 	gfn_t gfn = gpa >> PAGE_SHIFT;
2940 	int seg;
2941 	int offset = offset_in_page(gpa);
2942 	int ret;
2943 
2944 	while ((seg = next_segment(len, offset)) != 0) {
2945 		ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2946 		if (ret < 0)
2947 			return ret;
2948 		offset = 0;
2949 		len -= seg;
2950 		data += seg;
2951 		++gfn;
2952 	}
2953 	return 0;
2954 }
2955 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2956 
__kvm_read_guest_atomic(struct kvm_memory_slot * slot,gfn_t gfn,void * data,int offset,unsigned long len)2957 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2958 			           void *data, int offset, unsigned long len)
2959 {
2960 	int r;
2961 	unsigned long addr;
2962 
2963 	addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2964 	if (kvm_is_error_hva(addr))
2965 		return -EFAULT;
2966 	pagefault_disable();
2967 	r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2968 	pagefault_enable();
2969 	if (r)
2970 		return -EFAULT;
2971 	return 0;
2972 }
2973 
kvm_vcpu_read_guest_atomic(struct kvm_vcpu * vcpu,gpa_t gpa,void * data,unsigned long len)2974 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2975 			       void *data, unsigned long len)
2976 {
2977 	gfn_t gfn = gpa >> PAGE_SHIFT;
2978 	struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2979 	int offset = offset_in_page(gpa);
2980 
2981 	return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2982 }
2983 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2984 
__kvm_write_guest_page(struct kvm * kvm,struct kvm_memory_slot * memslot,gfn_t gfn,const void * data,int offset,int len)2985 static int __kvm_write_guest_page(struct kvm *kvm,
2986 				  struct kvm_memory_slot *memslot, gfn_t gfn,
2987 			          const void *data, int offset, int len)
2988 {
2989 	int r;
2990 	unsigned long addr;
2991 
2992 	addr = gfn_to_hva_memslot(memslot, gfn);
2993 	if (kvm_is_error_hva(addr))
2994 		return -EFAULT;
2995 	r = __copy_to_user((void __user *)addr + offset, data, len);
2996 	if (r)
2997 		return -EFAULT;
2998 	mark_page_dirty_in_slot(kvm, memslot, gfn);
2999 	return 0;
3000 }
3001 
kvm_write_guest_page(struct kvm * kvm,gfn_t gfn,const void * data,int offset,int len)3002 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
3003 			 const void *data, int offset, int len)
3004 {
3005 	struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
3006 
3007 	return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
3008 }
3009 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
3010 
kvm_vcpu_write_guest_page(struct kvm_vcpu * vcpu,gfn_t gfn,const void * data,int offset,int len)3011 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
3012 			      const void *data, int offset, int len)
3013 {
3014 	struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3015 
3016 	return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
3017 }
3018 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
3019 
kvm_write_guest(struct kvm * kvm,gpa_t gpa,const void * data,unsigned long len)3020 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
3021 		    unsigned long len)
3022 {
3023 	gfn_t gfn = gpa >> PAGE_SHIFT;
3024 	int seg;
3025 	int offset = offset_in_page(gpa);
3026 	int ret;
3027 
3028 	while ((seg = next_segment(len, offset)) != 0) {
3029 		ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
3030 		if (ret < 0)
3031 			return ret;
3032 		offset = 0;
3033 		len -= seg;
3034 		data += seg;
3035 		++gfn;
3036 	}
3037 	return 0;
3038 }
3039 EXPORT_SYMBOL_GPL(kvm_write_guest);
3040 
kvm_vcpu_write_guest(struct kvm_vcpu * vcpu,gpa_t gpa,const void * data,unsigned long len)3041 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
3042 		         unsigned long len)
3043 {
3044 	gfn_t gfn = gpa >> PAGE_SHIFT;
3045 	int seg;
3046 	int offset = offset_in_page(gpa);
3047 	int ret;
3048 
3049 	while ((seg = next_segment(len, offset)) != 0) {
3050 		ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
3051 		if (ret < 0)
3052 			return ret;
3053 		offset = 0;
3054 		len -= seg;
3055 		data += seg;
3056 		++gfn;
3057 	}
3058 	return 0;
3059 }
3060 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
3061 
__kvm_gfn_to_hva_cache_init(struct kvm_memslots * slots,struct gfn_to_hva_cache * ghc,gpa_t gpa,unsigned long len)3062 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
3063 				       struct gfn_to_hva_cache *ghc,
3064 				       gpa_t gpa, unsigned long len)
3065 {
3066 	int offset = offset_in_page(gpa);
3067 	gfn_t start_gfn = gpa >> PAGE_SHIFT;
3068 	gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
3069 	gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
3070 	gfn_t nr_pages_avail;
3071 
3072 	/* Update ghc->generation before performing any error checks. */
3073 	ghc->generation = slots->generation;
3074 
3075 	if (start_gfn > end_gfn) {
3076 		ghc->hva = KVM_HVA_ERR_BAD;
3077 		return -EINVAL;
3078 	}
3079 
3080 	/*
3081 	 * If the requested region crosses two memslots, we still
3082 	 * verify that the entire region is valid here.
3083 	 */
3084 	for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
3085 		ghc->memslot = __gfn_to_memslot(slots, start_gfn);
3086 		ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
3087 					   &nr_pages_avail);
3088 		if (kvm_is_error_hva(ghc->hva))
3089 			return -EFAULT;
3090 	}
3091 
3092 	/* Use the slow path for cross page reads and writes. */
3093 	if (nr_pages_needed == 1)
3094 		ghc->hva += offset;
3095 	else
3096 		ghc->memslot = NULL;
3097 
3098 	ghc->gpa = gpa;
3099 	ghc->len = len;
3100 	return 0;
3101 }
3102 
kvm_gfn_to_hva_cache_init(struct kvm * kvm,struct gfn_to_hva_cache * ghc,gpa_t gpa,unsigned long len)3103 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3104 			      gpa_t gpa, unsigned long len)
3105 {
3106 	struct kvm_memslots *slots = kvm_memslots(kvm);
3107 	return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
3108 }
3109 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
3110 
kvm_write_guest_offset_cached(struct kvm * kvm,struct gfn_to_hva_cache * ghc,void * data,unsigned int offset,unsigned long len)3111 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3112 				  void *data, unsigned int offset,
3113 				  unsigned long len)
3114 {
3115 	struct kvm_memslots *slots = kvm_memslots(kvm);
3116 	int r;
3117 	gpa_t gpa = ghc->gpa + offset;
3118 
3119 	if (WARN_ON_ONCE(len + offset > ghc->len))
3120 		return -EINVAL;
3121 
3122 	if (slots->generation != ghc->generation) {
3123 		if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3124 			return -EFAULT;
3125 	}
3126 
3127 	if (kvm_is_error_hva(ghc->hva))
3128 		return -EFAULT;
3129 
3130 	if (unlikely(!ghc->memslot))
3131 		return kvm_write_guest(kvm, gpa, data, len);
3132 
3133 	r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
3134 	if (r)
3135 		return -EFAULT;
3136 	mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
3137 
3138 	return 0;
3139 }
3140 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
3141 
kvm_write_guest_cached(struct kvm * kvm,struct gfn_to_hva_cache * ghc,void * data,unsigned long len)3142 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3143 			   void *data, unsigned long len)
3144 {
3145 	return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
3146 }
3147 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
3148 
kvm_read_guest_offset_cached(struct kvm * kvm,struct gfn_to_hva_cache * ghc,void * data,unsigned int offset,unsigned long len)3149 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3150 				 void *data, unsigned int offset,
3151 				 unsigned long len)
3152 {
3153 	struct kvm_memslots *slots = kvm_memslots(kvm);
3154 	int r;
3155 	gpa_t gpa = ghc->gpa + offset;
3156 
3157 	if (WARN_ON_ONCE(len + offset > ghc->len))
3158 		return -EINVAL;
3159 
3160 	if (slots->generation != ghc->generation) {
3161 		if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3162 			return -EFAULT;
3163 	}
3164 
3165 	if (kvm_is_error_hva(ghc->hva))
3166 		return -EFAULT;
3167 
3168 	if (unlikely(!ghc->memslot))
3169 		return kvm_read_guest(kvm, gpa, data, len);
3170 
3171 	r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
3172 	if (r)
3173 		return -EFAULT;
3174 
3175 	return 0;
3176 }
3177 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3178 
kvm_read_guest_cached(struct kvm * kvm,struct gfn_to_hva_cache * ghc,void * data,unsigned long len)3179 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3180 			  void *data, unsigned long len)
3181 {
3182 	return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3183 }
3184 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
3185 
kvm_clear_guest(struct kvm * kvm,gpa_t gpa,unsigned long len)3186 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3187 {
3188 	const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3189 	gfn_t gfn = gpa >> PAGE_SHIFT;
3190 	int seg;
3191 	int offset = offset_in_page(gpa);
3192 	int ret;
3193 
3194 	while ((seg = next_segment(len, offset)) != 0) {
3195 		ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
3196 		if (ret < 0)
3197 			return ret;
3198 		offset = 0;
3199 		len -= seg;
3200 		++gfn;
3201 	}
3202 	return 0;
3203 }
3204 EXPORT_SYMBOL_GPL(kvm_clear_guest);
3205 
mark_page_dirty_in_slot(struct kvm * kvm,const struct kvm_memory_slot * memslot,gfn_t gfn)3206 void mark_page_dirty_in_slot(struct kvm *kvm,
3207 			     const struct kvm_memory_slot *memslot,
3208 		 	     gfn_t gfn)
3209 {
3210 	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
3211 
3212 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3213 	if (WARN_ON_ONCE(!vcpu) || WARN_ON_ONCE(vcpu->kvm != kvm))
3214 		return;
3215 #endif
3216 
3217 	if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
3218 		unsigned long rel_gfn = gfn - memslot->base_gfn;
3219 		u32 slot = (memslot->as_id << 16) | memslot->id;
3220 
3221 		if (kvm->dirty_ring_size)
3222 			kvm_dirty_ring_push(&vcpu->dirty_ring,
3223 					    slot, rel_gfn);
3224 		else
3225 			set_bit_le(rel_gfn, memslot->dirty_bitmap);
3226 	}
3227 }
3228 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
3229 
mark_page_dirty(struct kvm * kvm,gfn_t gfn)3230 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3231 {
3232 	struct kvm_memory_slot *memslot;
3233 
3234 	memslot = gfn_to_memslot(kvm, gfn);
3235 	mark_page_dirty_in_slot(kvm, memslot, gfn);
3236 }
3237 EXPORT_SYMBOL_GPL(mark_page_dirty);
3238 
kvm_vcpu_mark_page_dirty(struct kvm_vcpu * vcpu,gfn_t gfn)3239 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3240 {
3241 	struct kvm_memory_slot *memslot;
3242 
3243 	memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3244 	mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
3245 }
3246 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3247 
kvm_sigset_activate(struct kvm_vcpu * vcpu)3248 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3249 {
3250 	if (!vcpu->sigset_active)
3251 		return;
3252 
3253 	/*
3254 	 * This does a lockless modification of ->real_blocked, which is fine
3255 	 * because, only current can change ->real_blocked and all readers of
3256 	 * ->real_blocked don't care as long ->real_blocked is always a subset
3257 	 * of ->blocked.
3258 	 */
3259 	sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
3260 }
3261 
kvm_sigset_deactivate(struct kvm_vcpu * vcpu)3262 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3263 {
3264 	if (!vcpu->sigset_active)
3265 		return;
3266 
3267 	sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
3268 	sigemptyset(&current->real_blocked);
3269 }
3270 
grow_halt_poll_ns(struct kvm_vcpu * vcpu)3271 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3272 {
3273 	unsigned int old, val, grow, grow_start;
3274 
3275 	old = val = vcpu->halt_poll_ns;
3276 	grow_start = READ_ONCE(halt_poll_ns_grow_start);
3277 	grow = READ_ONCE(halt_poll_ns_grow);
3278 	if (!grow)
3279 		goto out;
3280 
3281 	val *= grow;
3282 	if (val < grow_start)
3283 		val = grow_start;
3284 
3285 	if (val > vcpu->kvm->max_halt_poll_ns)
3286 		val = vcpu->kvm->max_halt_poll_ns;
3287 
3288 	vcpu->halt_poll_ns = val;
3289 out:
3290 	trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
3291 }
3292 
shrink_halt_poll_ns(struct kvm_vcpu * vcpu)3293 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3294 {
3295 	unsigned int old, val, shrink, grow_start;
3296 
3297 	old = val = vcpu->halt_poll_ns;
3298 	shrink = READ_ONCE(halt_poll_ns_shrink);
3299 	grow_start = READ_ONCE(halt_poll_ns_grow_start);
3300 	if (shrink == 0)
3301 		val = 0;
3302 	else
3303 		val /= shrink;
3304 
3305 	if (val < grow_start)
3306 		val = 0;
3307 
3308 	vcpu->halt_poll_ns = val;
3309 	trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
3310 }
3311 
kvm_vcpu_check_block(struct kvm_vcpu * vcpu)3312 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3313 {
3314 	int ret = -EINTR;
3315 	int idx = srcu_read_lock(&vcpu->kvm->srcu);
3316 
3317 	if (kvm_arch_vcpu_runnable(vcpu)) {
3318 		kvm_make_request(KVM_REQ_UNHALT, vcpu);
3319 		goto out;
3320 	}
3321 	if (kvm_cpu_has_pending_timer(vcpu))
3322 		goto out;
3323 	if (signal_pending(current))
3324 		goto out;
3325 	if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3326 		goto out;
3327 
3328 	ret = 0;
3329 out:
3330 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
3331 	return ret;
3332 }
3333 
3334 /*
3335  * Block the vCPU until the vCPU is runnable, an event arrives, or a signal is
3336  * pending.  This is mostly used when halting a vCPU, but may also be used
3337  * directly for other vCPU non-runnable states, e.g. x86's Wait-For-SIPI.
3338  */
kvm_vcpu_block(struct kvm_vcpu * vcpu)3339 bool kvm_vcpu_block(struct kvm_vcpu *vcpu)
3340 {
3341 	struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
3342 	bool waited = false;
3343 
3344 	vcpu->stat.generic.blocking = 1;
3345 
3346 	preempt_disable();
3347 	kvm_arch_vcpu_blocking(vcpu);
3348 	prepare_to_rcuwait(wait);
3349 	preempt_enable();
3350 
3351 	for (;;) {
3352 		set_current_state(TASK_INTERRUPTIBLE);
3353 
3354 		if (kvm_vcpu_check_block(vcpu) < 0)
3355 			break;
3356 
3357 		waited = true;
3358 		schedule();
3359 	}
3360 
3361 	preempt_disable();
3362 	finish_rcuwait(wait);
3363 	kvm_arch_vcpu_unblocking(vcpu);
3364 	preempt_enable();
3365 
3366 	vcpu->stat.generic.blocking = 0;
3367 
3368 	return waited;
3369 }
3370 
update_halt_poll_stats(struct kvm_vcpu * vcpu,ktime_t start,ktime_t end,bool success)3371 static inline void update_halt_poll_stats(struct kvm_vcpu *vcpu, ktime_t start,
3372 					  ktime_t end, bool success)
3373 {
3374 	struct kvm_vcpu_stat_generic *stats = &vcpu->stat.generic;
3375 	u64 poll_ns = ktime_to_ns(ktime_sub(end, start));
3376 
3377 	++vcpu->stat.generic.halt_attempted_poll;
3378 
3379 	if (success) {
3380 		++vcpu->stat.generic.halt_successful_poll;
3381 
3382 		if (!vcpu_valid_wakeup(vcpu))
3383 			++vcpu->stat.generic.halt_poll_invalid;
3384 
3385 		stats->halt_poll_success_ns += poll_ns;
3386 		KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_success_hist, poll_ns);
3387 	} else {
3388 		stats->halt_poll_fail_ns += poll_ns;
3389 		KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_fail_hist, poll_ns);
3390 	}
3391 }
3392 
3393 /*
3394  * Emulate a vCPU halt condition, e.g. HLT on x86, WFI on arm, etc...  If halt
3395  * polling is enabled, busy wait for a short time before blocking to avoid the
3396  * expensive block+unblock sequence if a wake event arrives soon after the vCPU
3397  * is halted.
3398  */
kvm_vcpu_halt(struct kvm_vcpu * vcpu)3399 void kvm_vcpu_halt(struct kvm_vcpu *vcpu)
3400 {
3401 	bool halt_poll_allowed = !kvm_arch_no_poll(vcpu);
3402 	bool do_halt_poll = halt_poll_allowed && vcpu->halt_poll_ns;
3403 	ktime_t start, cur, poll_end;
3404 	bool waited = false;
3405 	u64 halt_ns;
3406 
3407 	start = cur = poll_end = ktime_get();
3408 	if (do_halt_poll) {
3409 		ktime_t stop = ktime_add_ns(start, vcpu->halt_poll_ns);
3410 
3411 		do {
3412 			/*
3413 			 * This sets KVM_REQ_UNHALT if an interrupt
3414 			 * arrives.
3415 			 */
3416 			if (kvm_vcpu_check_block(vcpu) < 0)
3417 				goto out;
3418 			cpu_relax();
3419 			poll_end = cur = ktime_get();
3420 		} while (kvm_vcpu_can_poll(cur, stop));
3421 	}
3422 
3423 	waited = kvm_vcpu_block(vcpu);
3424 
3425 	cur = ktime_get();
3426 	if (waited) {
3427 		vcpu->stat.generic.halt_wait_ns +=
3428 			ktime_to_ns(cur) - ktime_to_ns(poll_end);
3429 		KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
3430 				ktime_to_ns(cur) - ktime_to_ns(poll_end));
3431 	}
3432 out:
3433 	/* The total time the vCPU was "halted", including polling time. */
3434 	halt_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3435 
3436 	/*
3437 	 * Note, halt-polling is considered successful so long as the vCPU was
3438 	 * never actually scheduled out, i.e. even if the wake event arrived
3439 	 * after of the halt-polling loop itself, but before the full wait.
3440 	 */
3441 	if (do_halt_poll)
3442 		update_halt_poll_stats(vcpu, start, poll_end, !waited);
3443 
3444 	if (halt_poll_allowed) {
3445 		if (!vcpu_valid_wakeup(vcpu)) {
3446 			shrink_halt_poll_ns(vcpu);
3447 		} else if (vcpu->kvm->max_halt_poll_ns) {
3448 			if (halt_ns <= vcpu->halt_poll_ns)
3449 				;
3450 			/* we had a long block, shrink polling */
3451 			else if (vcpu->halt_poll_ns &&
3452 				 halt_ns > vcpu->kvm->max_halt_poll_ns)
3453 				shrink_halt_poll_ns(vcpu);
3454 			/* we had a short halt and our poll time is too small */
3455 			else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3456 				 halt_ns < vcpu->kvm->max_halt_poll_ns)
3457 				grow_halt_poll_ns(vcpu);
3458 		} else {
3459 			vcpu->halt_poll_ns = 0;
3460 		}
3461 	}
3462 
3463 	trace_kvm_vcpu_wakeup(halt_ns, waited, vcpu_valid_wakeup(vcpu));
3464 }
3465 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
3466 
kvm_vcpu_wake_up(struct kvm_vcpu * vcpu)3467 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3468 {
3469 	if (__kvm_vcpu_wake_up(vcpu)) {
3470 		WRITE_ONCE(vcpu->ready, true);
3471 		++vcpu->stat.generic.halt_wakeup;
3472 		return true;
3473 	}
3474 
3475 	return false;
3476 }
3477 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3478 
3479 #ifndef CONFIG_S390
3480 /*
3481  * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3482  */
kvm_vcpu_kick(struct kvm_vcpu * vcpu)3483 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3484 {
3485 	int me, cpu;
3486 
3487 	if (kvm_vcpu_wake_up(vcpu))
3488 		return;
3489 
3490 	me = get_cpu();
3491 	/*
3492 	 * The only state change done outside the vcpu mutex is IN_GUEST_MODE
3493 	 * to EXITING_GUEST_MODE.  Therefore the moderately expensive "should
3494 	 * kick" check does not need atomic operations if kvm_vcpu_kick is used
3495 	 * within the vCPU thread itself.
3496 	 */
3497 	if (vcpu == __this_cpu_read(kvm_running_vcpu)) {
3498 		if (vcpu->mode == IN_GUEST_MODE)
3499 			WRITE_ONCE(vcpu->mode, EXITING_GUEST_MODE);
3500 		goto out;
3501 	}
3502 
3503 	/*
3504 	 * Note, the vCPU could get migrated to a different pCPU at any point
3505 	 * after kvm_arch_vcpu_should_kick(), which could result in sending an
3506 	 * IPI to the previous pCPU.  But, that's ok because the purpose of the
3507 	 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the
3508 	 * vCPU also requires it to leave IN_GUEST_MODE.
3509 	 */
3510 	if (kvm_arch_vcpu_should_kick(vcpu)) {
3511 		cpu = READ_ONCE(vcpu->cpu);
3512 		if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3513 			smp_send_reschedule(cpu);
3514 	}
3515 out:
3516 	put_cpu();
3517 }
3518 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3519 #endif /* !CONFIG_S390 */
3520 
kvm_vcpu_yield_to(struct kvm_vcpu * target)3521 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3522 {
3523 	struct pid *pid;
3524 	struct task_struct *task = NULL;
3525 	int ret = 0;
3526 
3527 	rcu_read_lock();
3528 	pid = rcu_dereference(target->pid);
3529 	if (pid)
3530 		task = get_pid_task(pid, PIDTYPE_PID);
3531 	rcu_read_unlock();
3532 	if (!task)
3533 		return ret;
3534 	ret = yield_to(task, 1);
3535 	put_task_struct(task);
3536 
3537 	return ret;
3538 }
3539 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3540 
3541 /*
3542  * Helper that checks whether a VCPU is eligible for directed yield.
3543  * Most eligible candidate to yield is decided by following heuristics:
3544  *
3545  *  (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3546  *  (preempted lock holder), indicated by @in_spin_loop.
3547  *  Set at the beginning and cleared at the end of interception/PLE handler.
3548  *
3549  *  (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3550  *  chance last time (mostly it has become eligible now since we have probably
3551  *  yielded to lockholder in last iteration. This is done by toggling
3552  *  @dy_eligible each time a VCPU checked for eligibility.)
3553  *
3554  *  Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3555  *  to preempted lock-holder could result in wrong VCPU selection and CPU
3556  *  burning. Giving priority for a potential lock-holder increases lock
3557  *  progress.
3558  *
3559  *  Since algorithm is based on heuristics, accessing another VCPU data without
3560  *  locking does not harm. It may result in trying to yield to  same VCPU, fail
3561  *  and continue with next VCPU and so on.
3562  */
kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu * vcpu)3563 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3564 {
3565 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3566 	bool eligible;
3567 
3568 	eligible = !vcpu->spin_loop.in_spin_loop ||
3569 		    vcpu->spin_loop.dy_eligible;
3570 
3571 	if (vcpu->spin_loop.in_spin_loop)
3572 		kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3573 
3574 	return eligible;
3575 #else
3576 	return true;
3577 #endif
3578 }
3579 
3580 /*
3581  * Unlike kvm_arch_vcpu_runnable, this function is called outside
3582  * a vcpu_load/vcpu_put pair.  However, for most architectures
3583  * kvm_arch_vcpu_runnable does not require vcpu_load.
3584  */
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)3585 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3586 {
3587 	return kvm_arch_vcpu_runnable(vcpu);
3588 }
3589 
vcpu_dy_runnable(struct kvm_vcpu * vcpu)3590 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3591 {
3592 	if (kvm_arch_dy_runnable(vcpu))
3593 		return true;
3594 
3595 #ifdef CONFIG_KVM_ASYNC_PF
3596 	if (!list_empty_careful(&vcpu->async_pf.done))
3597 		return true;
3598 #endif
3599 
3600 	return false;
3601 }
3602 
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)3603 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3604 {
3605 	return false;
3606 }
3607 
kvm_vcpu_on_spin(struct kvm_vcpu * me,bool yield_to_kernel_mode)3608 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3609 {
3610 	struct kvm *kvm = me->kvm;
3611 	struct kvm_vcpu *vcpu;
3612 	int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3613 	unsigned long i;
3614 	int yielded = 0;
3615 	int try = 3;
3616 	int pass;
3617 
3618 	kvm_vcpu_set_in_spin_loop(me, true);
3619 	/*
3620 	 * We boost the priority of a VCPU that is runnable but not
3621 	 * currently running, because it got preempted by something
3622 	 * else and called schedule in __vcpu_run.  Hopefully that
3623 	 * VCPU is holding the lock that we need and will release it.
3624 	 * We approximate round-robin by starting at the last boosted VCPU.
3625 	 */
3626 	for (pass = 0; pass < 2 && !yielded && try; pass++) {
3627 		kvm_for_each_vcpu(i, vcpu, kvm) {
3628 			if (!pass && i <= last_boosted_vcpu) {
3629 				i = last_boosted_vcpu;
3630 				continue;
3631 			} else if (pass && i > last_boosted_vcpu)
3632 				break;
3633 			if (!READ_ONCE(vcpu->ready))
3634 				continue;
3635 			if (vcpu == me)
3636 				continue;
3637 			if (kvm_vcpu_is_blocking(vcpu) && !vcpu_dy_runnable(vcpu))
3638 				continue;
3639 			if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3640 			    !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3641 			    !kvm_arch_vcpu_in_kernel(vcpu))
3642 				continue;
3643 			if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3644 				continue;
3645 
3646 			yielded = kvm_vcpu_yield_to(vcpu);
3647 			if (yielded > 0) {
3648 				kvm->last_boosted_vcpu = i;
3649 				break;
3650 			} else if (yielded < 0) {
3651 				try--;
3652 				if (!try)
3653 					break;
3654 			}
3655 		}
3656 	}
3657 	kvm_vcpu_set_in_spin_loop(me, false);
3658 
3659 	/* Ensure vcpu is not eligible during next spinloop */
3660 	kvm_vcpu_set_dy_eligible(me, false);
3661 }
3662 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3663 
kvm_page_in_dirty_ring(struct kvm * kvm,unsigned long pgoff)3664 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3665 {
3666 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3667 	return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3668 	    (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3669 	     kvm->dirty_ring_size / PAGE_SIZE);
3670 #else
3671 	return false;
3672 #endif
3673 }
3674 
kvm_vcpu_fault(struct vm_fault * vmf)3675 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3676 {
3677 	struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3678 	struct page *page;
3679 
3680 	if (vmf->pgoff == 0)
3681 		page = virt_to_page(vcpu->run);
3682 #ifdef CONFIG_X86
3683 	else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3684 		page = virt_to_page(vcpu->arch.pio_data);
3685 #endif
3686 #ifdef CONFIG_KVM_MMIO
3687 	else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3688 		page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3689 #endif
3690 	else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3691 		page = kvm_dirty_ring_get_page(
3692 		    &vcpu->dirty_ring,
3693 		    vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3694 	else
3695 		return kvm_arch_vcpu_fault(vcpu, vmf);
3696 	get_page(page);
3697 	vmf->page = page;
3698 	return 0;
3699 }
3700 
3701 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3702 	.fault = kvm_vcpu_fault,
3703 };
3704 
kvm_vcpu_mmap(struct file * file,struct vm_area_struct * vma)3705 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3706 {
3707 	struct kvm_vcpu *vcpu = file->private_data;
3708 	unsigned long pages = vma_pages(vma);
3709 
3710 	if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3711 	     kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3712 	    ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3713 		return -EINVAL;
3714 
3715 	vma->vm_ops = &kvm_vcpu_vm_ops;
3716 	return 0;
3717 }
3718 
kvm_vcpu_release(struct inode * inode,struct file * filp)3719 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3720 {
3721 	struct kvm_vcpu *vcpu = filp->private_data;
3722 
3723 	kvm_put_kvm(vcpu->kvm);
3724 	return 0;
3725 }
3726 
3727 static const struct file_operations kvm_vcpu_fops = {
3728 	.release        = kvm_vcpu_release,
3729 	.unlocked_ioctl = kvm_vcpu_ioctl,
3730 	.mmap           = kvm_vcpu_mmap,
3731 	.llseek		= noop_llseek,
3732 	KVM_COMPAT(kvm_vcpu_compat_ioctl),
3733 };
3734 
3735 /*
3736  * Allocates an inode for the vcpu.
3737  */
create_vcpu_fd(struct kvm_vcpu * vcpu)3738 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3739 {
3740 	char name[8 + 1 + ITOA_MAX_LEN + 1];
3741 
3742 	snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3743 	return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3744 }
3745 
kvm_create_vcpu_debugfs(struct kvm_vcpu * vcpu)3746 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3747 {
3748 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3749 	struct dentry *debugfs_dentry;
3750 	char dir_name[ITOA_MAX_LEN * 2];
3751 
3752 	if (!debugfs_initialized())
3753 		return;
3754 
3755 	snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3756 	debugfs_dentry = debugfs_create_dir(dir_name,
3757 					    vcpu->kvm->debugfs_dentry);
3758 
3759 	kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3760 #endif
3761 }
3762 
3763 /*
3764  * Creates some virtual cpus.  Good luck creating more than one.
3765  */
kvm_vm_ioctl_create_vcpu(struct kvm * kvm,u32 id)3766 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3767 {
3768 	int r;
3769 	struct kvm_vcpu *vcpu;
3770 	struct page *page;
3771 
3772 	if (id >= KVM_MAX_VCPU_IDS)
3773 		return -EINVAL;
3774 
3775 	mutex_lock(&kvm->lock);
3776 	if (kvm->created_vcpus >= kvm->max_vcpus) {
3777 		mutex_unlock(&kvm->lock);
3778 		return -EINVAL;
3779 	}
3780 
3781 	kvm->created_vcpus++;
3782 	mutex_unlock(&kvm->lock);
3783 
3784 	r = kvm_arch_vcpu_precreate(kvm, id);
3785 	if (r)
3786 		goto vcpu_decrement;
3787 
3788 	vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3789 	if (!vcpu) {
3790 		r = -ENOMEM;
3791 		goto vcpu_decrement;
3792 	}
3793 
3794 	BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3795 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3796 	if (!page) {
3797 		r = -ENOMEM;
3798 		goto vcpu_free;
3799 	}
3800 	vcpu->run = page_address(page);
3801 
3802 	kvm_vcpu_init(vcpu, kvm, id);
3803 
3804 	r = kvm_arch_vcpu_create(vcpu);
3805 	if (r)
3806 		goto vcpu_free_run_page;
3807 
3808 	if (kvm->dirty_ring_size) {
3809 		r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3810 					 id, kvm->dirty_ring_size);
3811 		if (r)
3812 			goto arch_vcpu_destroy;
3813 	}
3814 
3815 	mutex_lock(&kvm->lock);
3816 	if (kvm_get_vcpu_by_id(kvm, id)) {
3817 		r = -EEXIST;
3818 		goto unlock_vcpu_destroy;
3819 	}
3820 
3821 	vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3822 	r = xa_insert(&kvm->vcpu_array, vcpu->vcpu_idx, vcpu, GFP_KERNEL_ACCOUNT);
3823 	BUG_ON(r == -EBUSY);
3824 	if (r)
3825 		goto unlock_vcpu_destroy;
3826 
3827 	/* Fill the stats id string for the vcpu */
3828 	snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3829 		 task_pid_nr(current), id);
3830 
3831 	/* Now it's all set up, let userspace reach it */
3832 	kvm_get_kvm(kvm);
3833 	r = create_vcpu_fd(vcpu);
3834 	if (r < 0) {
3835 		xa_erase(&kvm->vcpu_array, vcpu->vcpu_idx);
3836 		kvm_put_kvm_no_destroy(kvm);
3837 		goto unlock_vcpu_destroy;
3838 	}
3839 
3840 	/*
3841 	 * Pairs with smp_rmb() in kvm_get_vcpu.  Store the vcpu
3842 	 * pointer before kvm->online_vcpu's incremented value.
3843 	 */
3844 	smp_wmb();
3845 	atomic_inc(&kvm->online_vcpus);
3846 
3847 	mutex_unlock(&kvm->lock);
3848 	kvm_arch_vcpu_postcreate(vcpu);
3849 	kvm_create_vcpu_debugfs(vcpu);
3850 	return r;
3851 
3852 unlock_vcpu_destroy:
3853 	mutex_unlock(&kvm->lock);
3854 	kvm_dirty_ring_free(&vcpu->dirty_ring);
3855 arch_vcpu_destroy:
3856 	kvm_arch_vcpu_destroy(vcpu);
3857 vcpu_free_run_page:
3858 	free_page((unsigned long)vcpu->run);
3859 vcpu_free:
3860 	kmem_cache_free(kvm_vcpu_cache, vcpu);
3861 vcpu_decrement:
3862 	mutex_lock(&kvm->lock);
3863 	kvm->created_vcpus--;
3864 	mutex_unlock(&kvm->lock);
3865 	return r;
3866 }
3867 
kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu * vcpu,sigset_t * sigset)3868 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3869 {
3870 	if (sigset) {
3871 		sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3872 		vcpu->sigset_active = 1;
3873 		vcpu->sigset = *sigset;
3874 	} else
3875 		vcpu->sigset_active = 0;
3876 	return 0;
3877 }
3878 
kvm_vcpu_stats_read(struct file * file,char __user * user_buffer,size_t size,loff_t * offset)3879 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3880 			      size_t size, loff_t *offset)
3881 {
3882 	struct kvm_vcpu *vcpu = file->private_data;
3883 
3884 	return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3885 			&kvm_vcpu_stats_desc[0], &vcpu->stat,
3886 			sizeof(vcpu->stat), user_buffer, size, offset);
3887 }
3888 
3889 static const struct file_operations kvm_vcpu_stats_fops = {
3890 	.read = kvm_vcpu_stats_read,
3891 	.llseek = noop_llseek,
3892 };
3893 
kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu * vcpu)3894 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3895 {
3896 	int fd;
3897 	struct file *file;
3898 	char name[15 + ITOA_MAX_LEN + 1];
3899 
3900 	snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3901 
3902 	fd = get_unused_fd_flags(O_CLOEXEC);
3903 	if (fd < 0)
3904 		return fd;
3905 
3906 	file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3907 	if (IS_ERR(file)) {
3908 		put_unused_fd(fd);
3909 		return PTR_ERR(file);
3910 	}
3911 	file->f_mode |= FMODE_PREAD;
3912 	fd_install(fd, file);
3913 
3914 	return fd;
3915 }
3916 
kvm_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)3917 static long kvm_vcpu_ioctl(struct file *filp,
3918 			   unsigned int ioctl, unsigned long arg)
3919 {
3920 	struct kvm_vcpu *vcpu = filp->private_data;
3921 	void __user *argp = (void __user *)arg;
3922 	int r;
3923 	struct kvm_fpu *fpu = NULL;
3924 	struct kvm_sregs *kvm_sregs = NULL;
3925 
3926 	if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
3927 		return -EIO;
3928 
3929 	if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3930 		return -EINVAL;
3931 
3932 	/*
3933 	 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3934 	 * execution; mutex_lock() would break them.
3935 	 */
3936 	r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3937 	if (r != -ENOIOCTLCMD)
3938 		return r;
3939 
3940 	if (mutex_lock_killable(&vcpu->mutex))
3941 		return -EINTR;
3942 	switch (ioctl) {
3943 	case KVM_RUN: {
3944 		struct pid *oldpid;
3945 		r = -EINVAL;
3946 		if (arg)
3947 			goto out;
3948 		oldpid = rcu_access_pointer(vcpu->pid);
3949 		if (unlikely(oldpid != task_pid(current))) {
3950 			/* The thread running this VCPU changed. */
3951 			struct pid *newpid;
3952 
3953 			r = kvm_arch_vcpu_run_pid_change(vcpu);
3954 			if (r)
3955 				break;
3956 
3957 			newpid = get_task_pid(current, PIDTYPE_PID);
3958 			rcu_assign_pointer(vcpu->pid, newpid);
3959 			if (oldpid)
3960 				synchronize_rcu();
3961 			put_pid(oldpid);
3962 		}
3963 		r = kvm_arch_vcpu_ioctl_run(vcpu);
3964 		trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3965 		break;
3966 	}
3967 	case KVM_GET_REGS: {
3968 		struct kvm_regs *kvm_regs;
3969 
3970 		r = -ENOMEM;
3971 		kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3972 		if (!kvm_regs)
3973 			goto out;
3974 		r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3975 		if (r)
3976 			goto out_free1;
3977 		r = -EFAULT;
3978 		if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3979 			goto out_free1;
3980 		r = 0;
3981 out_free1:
3982 		kfree(kvm_regs);
3983 		break;
3984 	}
3985 	case KVM_SET_REGS: {
3986 		struct kvm_regs *kvm_regs;
3987 
3988 		kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3989 		if (IS_ERR(kvm_regs)) {
3990 			r = PTR_ERR(kvm_regs);
3991 			goto out;
3992 		}
3993 		r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3994 		kfree(kvm_regs);
3995 		break;
3996 	}
3997 	case KVM_GET_SREGS: {
3998 		kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3999 				    GFP_KERNEL_ACCOUNT);
4000 		r = -ENOMEM;
4001 		if (!kvm_sregs)
4002 			goto out;
4003 		r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
4004 		if (r)
4005 			goto out;
4006 		r = -EFAULT;
4007 		if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
4008 			goto out;
4009 		r = 0;
4010 		break;
4011 	}
4012 	case KVM_SET_SREGS: {
4013 		kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
4014 		if (IS_ERR(kvm_sregs)) {
4015 			r = PTR_ERR(kvm_sregs);
4016 			kvm_sregs = NULL;
4017 			goto out;
4018 		}
4019 		r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
4020 		break;
4021 	}
4022 	case KVM_GET_MP_STATE: {
4023 		struct kvm_mp_state mp_state;
4024 
4025 		r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
4026 		if (r)
4027 			goto out;
4028 		r = -EFAULT;
4029 		if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
4030 			goto out;
4031 		r = 0;
4032 		break;
4033 	}
4034 	case KVM_SET_MP_STATE: {
4035 		struct kvm_mp_state mp_state;
4036 
4037 		r = -EFAULT;
4038 		if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
4039 			goto out;
4040 		r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
4041 		break;
4042 	}
4043 	case KVM_TRANSLATE: {
4044 		struct kvm_translation tr;
4045 
4046 		r = -EFAULT;
4047 		if (copy_from_user(&tr, argp, sizeof(tr)))
4048 			goto out;
4049 		r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
4050 		if (r)
4051 			goto out;
4052 		r = -EFAULT;
4053 		if (copy_to_user(argp, &tr, sizeof(tr)))
4054 			goto out;
4055 		r = 0;
4056 		break;
4057 	}
4058 	case KVM_SET_GUEST_DEBUG: {
4059 		struct kvm_guest_debug dbg;
4060 
4061 		r = -EFAULT;
4062 		if (copy_from_user(&dbg, argp, sizeof(dbg)))
4063 			goto out;
4064 		r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
4065 		break;
4066 	}
4067 	case KVM_SET_SIGNAL_MASK: {
4068 		struct kvm_signal_mask __user *sigmask_arg = argp;
4069 		struct kvm_signal_mask kvm_sigmask;
4070 		sigset_t sigset, *p;
4071 
4072 		p = NULL;
4073 		if (argp) {
4074 			r = -EFAULT;
4075 			if (copy_from_user(&kvm_sigmask, argp,
4076 					   sizeof(kvm_sigmask)))
4077 				goto out;
4078 			r = -EINVAL;
4079 			if (kvm_sigmask.len != sizeof(sigset))
4080 				goto out;
4081 			r = -EFAULT;
4082 			if (copy_from_user(&sigset, sigmask_arg->sigset,
4083 					   sizeof(sigset)))
4084 				goto out;
4085 			p = &sigset;
4086 		}
4087 		r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
4088 		break;
4089 	}
4090 	case KVM_GET_FPU: {
4091 		fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
4092 		r = -ENOMEM;
4093 		if (!fpu)
4094 			goto out;
4095 		r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
4096 		if (r)
4097 			goto out;
4098 		r = -EFAULT;
4099 		if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
4100 			goto out;
4101 		r = 0;
4102 		break;
4103 	}
4104 	case KVM_SET_FPU: {
4105 		fpu = memdup_user(argp, sizeof(*fpu));
4106 		if (IS_ERR(fpu)) {
4107 			r = PTR_ERR(fpu);
4108 			fpu = NULL;
4109 			goto out;
4110 		}
4111 		r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
4112 		break;
4113 	}
4114 	case KVM_GET_STATS_FD: {
4115 		r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
4116 		break;
4117 	}
4118 	default:
4119 		r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
4120 	}
4121 out:
4122 	mutex_unlock(&vcpu->mutex);
4123 	kfree(fpu);
4124 	kfree(kvm_sregs);
4125 	return r;
4126 }
4127 
4128 #ifdef CONFIG_KVM_COMPAT
kvm_vcpu_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4129 static long kvm_vcpu_compat_ioctl(struct file *filp,
4130 				  unsigned int ioctl, unsigned long arg)
4131 {
4132 	struct kvm_vcpu *vcpu = filp->private_data;
4133 	void __user *argp = compat_ptr(arg);
4134 	int r;
4135 
4136 	if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
4137 		return -EIO;
4138 
4139 	switch (ioctl) {
4140 	case KVM_SET_SIGNAL_MASK: {
4141 		struct kvm_signal_mask __user *sigmask_arg = argp;
4142 		struct kvm_signal_mask kvm_sigmask;
4143 		sigset_t sigset;
4144 
4145 		if (argp) {
4146 			r = -EFAULT;
4147 			if (copy_from_user(&kvm_sigmask, argp,
4148 					   sizeof(kvm_sigmask)))
4149 				goto out;
4150 			r = -EINVAL;
4151 			if (kvm_sigmask.len != sizeof(compat_sigset_t))
4152 				goto out;
4153 			r = -EFAULT;
4154 			if (get_compat_sigset(&sigset,
4155 					      (compat_sigset_t __user *)sigmask_arg->sigset))
4156 				goto out;
4157 			r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
4158 		} else
4159 			r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
4160 		break;
4161 	}
4162 	default:
4163 		r = kvm_vcpu_ioctl(filp, ioctl, arg);
4164 	}
4165 
4166 out:
4167 	return r;
4168 }
4169 #endif
4170 
kvm_device_mmap(struct file * filp,struct vm_area_struct * vma)4171 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
4172 {
4173 	struct kvm_device *dev = filp->private_data;
4174 
4175 	if (dev->ops->mmap)
4176 		return dev->ops->mmap(dev, vma);
4177 
4178 	return -ENODEV;
4179 }
4180 
kvm_device_ioctl_attr(struct kvm_device * dev,int (* accessor)(struct kvm_device * dev,struct kvm_device_attr * attr),unsigned long arg)4181 static int kvm_device_ioctl_attr(struct kvm_device *dev,
4182 				 int (*accessor)(struct kvm_device *dev,
4183 						 struct kvm_device_attr *attr),
4184 				 unsigned long arg)
4185 {
4186 	struct kvm_device_attr attr;
4187 
4188 	if (!accessor)
4189 		return -EPERM;
4190 
4191 	if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4192 		return -EFAULT;
4193 
4194 	return accessor(dev, &attr);
4195 }
4196 
kvm_device_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4197 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
4198 			     unsigned long arg)
4199 {
4200 	struct kvm_device *dev = filp->private_data;
4201 
4202 	if (dev->kvm->mm != current->mm || dev->kvm->vm_dead)
4203 		return -EIO;
4204 
4205 	switch (ioctl) {
4206 	case KVM_SET_DEVICE_ATTR:
4207 		return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
4208 	case KVM_GET_DEVICE_ATTR:
4209 		return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
4210 	case KVM_HAS_DEVICE_ATTR:
4211 		return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
4212 	default:
4213 		if (dev->ops->ioctl)
4214 			return dev->ops->ioctl(dev, ioctl, arg);
4215 
4216 		return -ENOTTY;
4217 	}
4218 }
4219 
kvm_device_release(struct inode * inode,struct file * filp)4220 static int kvm_device_release(struct inode *inode, struct file *filp)
4221 {
4222 	struct kvm_device *dev = filp->private_data;
4223 	struct kvm *kvm = dev->kvm;
4224 
4225 	if (dev->ops->release) {
4226 		mutex_lock(&kvm->lock);
4227 		list_del(&dev->vm_node);
4228 		dev->ops->release(dev);
4229 		mutex_unlock(&kvm->lock);
4230 	}
4231 
4232 	kvm_put_kvm(kvm);
4233 	return 0;
4234 }
4235 
4236 static const struct file_operations kvm_device_fops = {
4237 	.unlocked_ioctl = kvm_device_ioctl,
4238 	.release = kvm_device_release,
4239 	KVM_COMPAT(kvm_device_ioctl),
4240 	.mmap = kvm_device_mmap,
4241 };
4242 
kvm_device_from_filp(struct file * filp)4243 struct kvm_device *kvm_device_from_filp(struct file *filp)
4244 {
4245 	if (filp->f_op != &kvm_device_fops)
4246 		return NULL;
4247 
4248 	return filp->private_data;
4249 }
4250 
4251 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
4252 #ifdef CONFIG_KVM_MPIC
4253 	[KVM_DEV_TYPE_FSL_MPIC_20]	= &kvm_mpic_ops,
4254 	[KVM_DEV_TYPE_FSL_MPIC_42]	= &kvm_mpic_ops,
4255 #endif
4256 };
4257 
kvm_register_device_ops(const struct kvm_device_ops * ops,u32 type)4258 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
4259 {
4260 	if (type >= ARRAY_SIZE(kvm_device_ops_table))
4261 		return -ENOSPC;
4262 
4263 	if (kvm_device_ops_table[type] != NULL)
4264 		return -EEXIST;
4265 
4266 	kvm_device_ops_table[type] = ops;
4267 	return 0;
4268 }
4269 
kvm_unregister_device_ops(u32 type)4270 void kvm_unregister_device_ops(u32 type)
4271 {
4272 	if (kvm_device_ops_table[type] != NULL)
4273 		kvm_device_ops_table[type] = NULL;
4274 }
4275 
kvm_ioctl_create_device(struct kvm * kvm,struct kvm_create_device * cd)4276 static int kvm_ioctl_create_device(struct kvm *kvm,
4277 				   struct kvm_create_device *cd)
4278 {
4279 	const struct kvm_device_ops *ops = NULL;
4280 	struct kvm_device *dev;
4281 	bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
4282 	int type;
4283 	int ret;
4284 
4285 	if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
4286 		return -ENODEV;
4287 
4288 	type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4289 	ops = kvm_device_ops_table[type];
4290 	if (ops == NULL)
4291 		return -ENODEV;
4292 
4293 	if (test)
4294 		return 0;
4295 
4296 	dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
4297 	if (!dev)
4298 		return -ENOMEM;
4299 
4300 	dev->ops = ops;
4301 	dev->kvm = kvm;
4302 
4303 	mutex_lock(&kvm->lock);
4304 	ret = ops->create(dev, type);
4305 	if (ret < 0) {
4306 		mutex_unlock(&kvm->lock);
4307 		kfree(dev);
4308 		return ret;
4309 	}
4310 	list_add(&dev->vm_node, &kvm->devices);
4311 	mutex_unlock(&kvm->lock);
4312 
4313 	if (ops->init)
4314 		ops->init(dev);
4315 
4316 	kvm_get_kvm(kvm);
4317 	ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
4318 	if (ret < 0) {
4319 		kvm_put_kvm_no_destroy(kvm);
4320 		mutex_lock(&kvm->lock);
4321 		list_del(&dev->vm_node);
4322 		if (ops->release)
4323 			ops->release(dev);
4324 		mutex_unlock(&kvm->lock);
4325 		if (ops->destroy)
4326 			ops->destroy(dev);
4327 		return ret;
4328 	}
4329 
4330 	cd->fd = ret;
4331 	return 0;
4332 }
4333 
kvm_vm_ioctl_check_extension_generic(struct kvm * kvm,long arg)4334 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4335 {
4336 	switch (arg) {
4337 	case KVM_CAP_USER_MEMORY:
4338 	case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4339 	case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
4340 	case KVM_CAP_INTERNAL_ERROR_DATA:
4341 #ifdef CONFIG_HAVE_KVM_MSI
4342 	case KVM_CAP_SIGNAL_MSI:
4343 #endif
4344 #ifdef CONFIG_HAVE_KVM_IRQFD
4345 	case KVM_CAP_IRQFD:
4346 	case KVM_CAP_IRQFD_RESAMPLE:
4347 #endif
4348 	case KVM_CAP_IOEVENTFD_ANY_LENGTH:
4349 	case KVM_CAP_CHECK_EXTENSION_VM:
4350 	case KVM_CAP_ENABLE_CAP_VM:
4351 	case KVM_CAP_HALT_POLL:
4352 		return 1;
4353 #ifdef CONFIG_KVM_MMIO
4354 	case KVM_CAP_COALESCED_MMIO:
4355 		return KVM_COALESCED_MMIO_PAGE_OFFSET;
4356 	case KVM_CAP_COALESCED_PIO:
4357 		return 1;
4358 #endif
4359 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4360 	case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4361 		return KVM_DIRTY_LOG_MANUAL_CAPS;
4362 #endif
4363 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4364 	case KVM_CAP_IRQ_ROUTING:
4365 		return KVM_MAX_IRQ_ROUTES;
4366 #endif
4367 #if KVM_ADDRESS_SPACE_NUM > 1
4368 	case KVM_CAP_MULTI_ADDRESS_SPACE:
4369 		return KVM_ADDRESS_SPACE_NUM;
4370 #endif
4371 	case KVM_CAP_NR_MEMSLOTS:
4372 		return KVM_USER_MEM_SLOTS;
4373 	case KVM_CAP_DIRTY_LOG_RING:
4374 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
4375 		return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4376 #else
4377 		return 0;
4378 #endif
4379 	case KVM_CAP_BINARY_STATS_FD:
4380 	case KVM_CAP_SYSTEM_EVENT_DATA:
4381 		return 1;
4382 	default:
4383 		break;
4384 	}
4385 	return kvm_vm_ioctl_check_extension(kvm, arg);
4386 }
4387 
kvm_vm_ioctl_enable_dirty_log_ring(struct kvm * kvm,u32 size)4388 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4389 {
4390 	int r;
4391 
4392 	if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4393 		return -EINVAL;
4394 
4395 	/* the size should be power of 2 */
4396 	if (!size || (size & (size - 1)))
4397 		return -EINVAL;
4398 
4399 	/* Should be bigger to keep the reserved entries, or a page */
4400 	if (size < kvm_dirty_ring_get_rsvd_entries() *
4401 	    sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4402 		return -EINVAL;
4403 
4404 	if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4405 	    sizeof(struct kvm_dirty_gfn))
4406 		return -E2BIG;
4407 
4408 	/* We only allow it to set once */
4409 	if (kvm->dirty_ring_size)
4410 		return -EINVAL;
4411 
4412 	mutex_lock(&kvm->lock);
4413 
4414 	if (kvm->created_vcpus) {
4415 		/* We don't allow to change this value after vcpu created */
4416 		r = -EINVAL;
4417 	} else {
4418 		kvm->dirty_ring_size = size;
4419 		r = 0;
4420 	}
4421 
4422 	mutex_unlock(&kvm->lock);
4423 	return r;
4424 }
4425 
kvm_vm_ioctl_reset_dirty_pages(struct kvm * kvm)4426 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4427 {
4428 	unsigned long i;
4429 	struct kvm_vcpu *vcpu;
4430 	int cleared = 0;
4431 
4432 	if (!kvm->dirty_ring_size)
4433 		return -EINVAL;
4434 
4435 	mutex_lock(&kvm->slots_lock);
4436 
4437 	kvm_for_each_vcpu(i, vcpu, kvm)
4438 		cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4439 
4440 	mutex_unlock(&kvm->slots_lock);
4441 
4442 	if (cleared)
4443 		kvm_flush_remote_tlbs(kvm);
4444 
4445 	return cleared;
4446 }
4447 
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)4448 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4449 						  struct kvm_enable_cap *cap)
4450 {
4451 	return -EINVAL;
4452 }
4453 
kvm_vm_ioctl_enable_cap_generic(struct kvm * kvm,struct kvm_enable_cap * cap)4454 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4455 					   struct kvm_enable_cap *cap)
4456 {
4457 	switch (cap->cap) {
4458 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4459 	case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4460 		u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4461 
4462 		if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4463 			allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4464 
4465 		if (cap->flags || (cap->args[0] & ~allowed_options))
4466 			return -EINVAL;
4467 		kvm->manual_dirty_log_protect = cap->args[0];
4468 		return 0;
4469 	}
4470 #endif
4471 	case KVM_CAP_HALT_POLL: {
4472 		if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4473 			return -EINVAL;
4474 
4475 		kvm->max_halt_poll_ns = cap->args[0];
4476 		return 0;
4477 	}
4478 	case KVM_CAP_DIRTY_LOG_RING:
4479 		return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
4480 	default:
4481 		return kvm_vm_ioctl_enable_cap(kvm, cap);
4482 	}
4483 }
4484 
kvm_vm_stats_read(struct file * file,char __user * user_buffer,size_t size,loff_t * offset)4485 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4486 			      size_t size, loff_t *offset)
4487 {
4488 	struct kvm *kvm = file->private_data;
4489 
4490 	return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4491 				&kvm_vm_stats_desc[0], &kvm->stat,
4492 				sizeof(kvm->stat), user_buffer, size, offset);
4493 }
4494 
4495 static const struct file_operations kvm_vm_stats_fops = {
4496 	.read = kvm_vm_stats_read,
4497 	.llseek = noop_llseek,
4498 };
4499 
kvm_vm_ioctl_get_stats_fd(struct kvm * kvm)4500 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4501 {
4502 	int fd;
4503 	struct file *file;
4504 
4505 	fd = get_unused_fd_flags(O_CLOEXEC);
4506 	if (fd < 0)
4507 		return fd;
4508 
4509 	file = anon_inode_getfile("kvm-vm-stats",
4510 			&kvm_vm_stats_fops, kvm, O_RDONLY);
4511 	if (IS_ERR(file)) {
4512 		put_unused_fd(fd);
4513 		return PTR_ERR(file);
4514 	}
4515 	file->f_mode |= FMODE_PREAD;
4516 	fd_install(fd, file);
4517 
4518 	return fd;
4519 }
4520 
kvm_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4521 static long kvm_vm_ioctl(struct file *filp,
4522 			   unsigned int ioctl, unsigned long arg)
4523 {
4524 	struct kvm *kvm = filp->private_data;
4525 	void __user *argp = (void __user *)arg;
4526 	int r;
4527 
4528 	if (kvm->mm != current->mm || kvm->vm_dead)
4529 		return -EIO;
4530 	switch (ioctl) {
4531 	case KVM_CREATE_VCPU:
4532 		r = kvm_vm_ioctl_create_vcpu(kvm, arg);
4533 		break;
4534 	case KVM_ENABLE_CAP: {
4535 		struct kvm_enable_cap cap;
4536 
4537 		r = -EFAULT;
4538 		if (copy_from_user(&cap, argp, sizeof(cap)))
4539 			goto out;
4540 		r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4541 		break;
4542 	}
4543 	case KVM_SET_USER_MEMORY_REGION: {
4544 		struct kvm_userspace_memory_region kvm_userspace_mem;
4545 
4546 		r = -EFAULT;
4547 		if (copy_from_user(&kvm_userspace_mem, argp,
4548 						sizeof(kvm_userspace_mem)))
4549 			goto out;
4550 
4551 		r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
4552 		break;
4553 	}
4554 	case KVM_GET_DIRTY_LOG: {
4555 		struct kvm_dirty_log log;
4556 
4557 		r = -EFAULT;
4558 		if (copy_from_user(&log, argp, sizeof(log)))
4559 			goto out;
4560 		r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4561 		break;
4562 	}
4563 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4564 	case KVM_CLEAR_DIRTY_LOG: {
4565 		struct kvm_clear_dirty_log log;
4566 
4567 		r = -EFAULT;
4568 		if (copy_from_user(&log, argp, sizeof(log)))
4569 			goto out;
4570 		r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4571 		break;
4572 	}
4573 #endif
4574 #ifdef CONFIG_KVM_MMIO
4575 	case KVM_REGISTER_COALESCED_MMIO: {
4576 		struct kvm_coalesced_mmio_zone zone;
4577 
4578 		r = -EFAULT;
4579 		if (copy_from_user(&zone, argp, sizeof(zone)))
4580 			goto out;
4581 		r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
4582 		break;
4583 	}
4584 	case KVM_UNREGISTER_COALESCED_MMIO: {
4585 		struct kvm_coalesced_mmio_zone zone;
4586 
4587 		r = -EFAULT;
4588 		if (copy_from_user(&zone, argp, sizeof(zone)))
4589 			goto out;
4590 		r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
4591 		break;
4592 	}
4593 #endif
4594 	case KVM_IRQFD: {
4595 		struct kvm_irqfd data;
4596 
4597 		r = -EFAULT;
4598 		if (copy_from_user(&data, argp, sizeof(data)))
4599 			goto out;
4600 		r = kvm_irqfd(kvm, &data);
4601 		break;
4602 	}
4603 	case KVM_IOEVENTFD: {
4604 		struct kvm_ioeventfd data;
4605 
4606 		r = -EFAULT;
4607 		if (copy_from_user(&data, argp, sizeof(data)))
4608 			goto out;
4609 		r = kvm_ioeventfd(kvm, &data);
4610 		break;
4611 	}
4612 #ifdef CONFIG_HAVE_KVM_MSI
4613 	case KVM_SIGNAL_MSI: {
4614 		struct kvm_msi msi;
4615 
4616 		r = -EFAULT;
4617 		if (copy_from_user(&msi, argp, sizeof(msi)))
4618 			goto out;
4619 		r = kvm_send_userspace_msi(kvm, &msi);
4620 		break;
4621 	}
4622 #endif
4623 #ifdef __KVM_HAVE_IRQ_LINE
4624 	case KVM_IRQ_LINE_STATUS:
4625 	case KVM_IRQ_LINE: {
4626 		struct kvm_irq_level irq_event;
4627 
4628 		r = -EFAULT;
4629 		if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
4630 			goto out;
4631 
4632 		r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4633 					ioctl == KVM_IRQ_LINE_STATUS);
4634 		if (r)
4635 			goto out;
4636 
4637 		r = -EFAULT;
4638 		if (ioctl == KVM_IRQ_LINE_STATUS) {
4639 			if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
4640 				goto out;
4641 		}
4642 
4643 		r = 0;
4644 		break;
4645 	}
4646 #endif
4647 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4648 	case KVM_SET_GSI_ROUTING: {
4649 		struct kvm_irq_routing routing;
4650 		struct kvm_irq_routing __user *urouting;
4651 		struct kvm_irq_routing_entry *entries = NULL;
4652 
4653 		r = -EFAULT;
4654 		if (copy_from_user(&routing, argp, sizeof(routing)))
4655 			goto out;
4656 		r = -EINVAL;
4657 		if (!kvm_arch_can_set_irq_routing(kvm))
4658 			goto out;
4659 		if (routing.nr > KVM_MAX_IRQ_ROUTES)
4660 			goto out;
4661 		if (routing.flags)
4662 			goto out;
4663 		if (routing.nr) {
4664 			urouting = argp;
4665 			entries = vmemdup_user(urouting->entries,
4666 					       array_size(sizeof(*entries),
4667 							  routing.nr));
4668 			if (IS_ERR(entries)) {
4669 				r = PTR_ERR(entries);
4670 				goto out;
4671 			}
4672 		}
4673 		r = kvm_set_irq_routing(kvm, entries, routing.nr,
4674 					routing.flags);
4675 		kvfree(entries);
4676 		break;
4677 	}
4678 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
4679 	case KVM_CREATE_DEVICE: {
4680 		struct kvm_create_device cd;
4681 
4682 		r = -EFAULT;
4683 		if (copy_from_user(&cd, argp, sizeof(cd)))
4684 			goto out;
4685 
4686 		r = kvm_ioctl_create_device(kvm, &cd);
4687 		if (r)
4688 			goto out;
4689 
4690 		r = -EFAULT;
4691 		if (copy_to_user(argp, &cd, sizeof(cd)))
4692 			goto out;
4693 
4694 		r = 0;
4695 		break;
4696 	}
4697 	case KVM_CHECK_EXTENSION:
4698 		r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4699 		break;
4700 	case KVM_RESET_DIRTY_RINGS:
4701 		r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4702 		break;
4703 	case KVM_GET_STATS_FD:
4704 		r = kvm_vm_ioctl_get_stats_fd(kvm);
4705 		break;
4706 	default:
4707 		r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4708 	}
4709 out:
4710 	return r;
4711 }
4712 
4713 #ifdef CONFIG_KVM_COMPAT
4714 struct compat_kvm_dirty_log {
4715 	__u32 slot;
4716 	__u32 padding1;
4717 	union {
4718 		compat_uptr_t dirty_bitmap; /* one bit per page */
4719 		__u64 padding2;
4720 	};
4721 };
4722 
4723 struct compat_kvm_clear_dirty_log {
4724 	__u32 slot;
4725 	__u32 num_pages;
4726 	__u64 first_page;
4727 	union {
4728 		compat_uptr_t dirty_bitmap; /* one bit per page */
4729 		__u64 padding2;
4730 	};
4731 };
4732 
kvm_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4733 static long kvm_vm_compat_ioctl(struct file *filp,
4734 			   unsigned int ioctl, unsigned long arg)
4735 {
4736 	struct kvm *kvm = filp->private_data;
4737 	int r;
4738 
4739 	if (kvm->mm != current->mm || kvm->vm_dead)
4740 		return -EIO;
4741 	switch (ioctl) {
4742 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4743 	case KVM_CLEAR_DIRTY_LOG: {
4744 		struct compat_kvm_clear_dirty_log compat_log;
4745 		struct kvm_clear_dirty_log log;
4746 
4747 		if (copy_from_user(&compat_log, (void __user *)arg,
4748 				   sizeof(compat_log)))
4749 			return -EFAULT;
4750 		log.slot	 = compat_log.slot;
4751 		log.num_pages	 = compat_log.num_pages;
4752 		log.first_page	 = compat_log.first_page;
4753 		log.padding2	 = compat_log.padding2;
4754 		log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4755 
4756 		r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4757 		break;
4758 	}
4759 #endif
4760 	case KVM_GET_DIRTY_LOG: {
4761 		struct compat_kvm_dirty_log compat_log;
4762 		struct kvm_dirty_log log;
4763 
4764 		if (copy_from_user(&compat_log, (void __user *)arg,
4765 				   sizeof(compat_log)))
4766 			return -EFAULT;
4767 		log.slot	 = compat_log.slot;
4768 		log.padding1	 = compat_log.padding1;
4769 		log.padding2	 = compat_log.padding2;
4770 		log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4771 
4772 		r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4773 		break;
4774 	}
4775 	default:
4776 		r = kvm_vm_ioctl(filp, ioctl, arg);
4777 	}
4778 	return r;
4779 }
4780 #endif
4781 
4782 static const struct file_operations kvm_vm_fops = {
4783 	.release        = kvm_vm_release,
4784 	.unlocked_ioctl = kvm_vm_ioctl,
4785 	.llseek		= noop_llseek,
4786 	KVM_COMPAT(kvm_vm_compat_ioctl),
4787 };
4788 
file_is_kvm(struct file * file)4789 bool file_is_kvm(struct file *file)
4790 {
4791 	return file && file->f_op == &kvm_vm_fops;
4792 }
4793 EXPORT_SYMBOL_GPL(file_is_kvm);
4794 
kvm_dev_ioctl_create_vm(unsigned long type)4795 static int kvm_dev_ioctl_create_vm(unsigned long type)
4796 {
4797 	int r;
4798 	struct kvm *kvm;
4799 	struct file *file;
4800 
4801 	kvm = kvm_create_vm(type);
4802 	if (IS_ERR(kvm))
4803 		return PTR_ERR(kvm);
4804 #ifdef CONFIG_KVM_MMIO
4805 	r = kvm_coalesced_mmio_init(kvm);
4806 	if (r < 0)
4807 		goto put_kvm;
4808 #endif
4809 	r = get_unused_fd_flags(O_CLOEXEC);
4810 	if (r < 0)
4811 		goto put_kvm;
4812 
4813 	snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4814 			"kvm-%d", task_pid_nr(current));
4815 
4816 	file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4817 	if (IS_ERR(file)) {
4818 		put_unused_fd(r);
4819 		r = PTR_ERR(file);
4820 		goto put_kvm;
4821 	}
4822 
4823 	/*
4824 	 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4825 	 * already set, with ->release() being kvm_vm_release().  In error
4826 	 * cases it will be called by the final fput(file) and will take
4827 	 * care of doing kvm_put_kvm(kvm).
4828 	 */
4829 	if (kvm_create_vm_debugfs(kvm, r) < 0) {
4830 		put_unused_fd(r);
4831 		fput(file);
4832 		return -ENOMEM;
4833 	}
4834 	kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4835 
4836 	fd_install(r, file);
4837 	return r;
4838 
4839 put_kvm:
4840 	kvm_put_kvm(kvm);
4841 	return r;
4842 }
4843 
kvm_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4844 static long kvm_dev_ioctl(struct file *filp,
4845 			  unsigned int ioctl, unsigned long arg)
4846 {
4847 	long r = -EINVAL;
4848 
4849 	switch (ioctl) {
4850 	case KVM_GET_API_VERSION:
4851 		if (arg)
4852 			goto out;
4853 		r = KVM_API_VERSION;
4854 		break;
4855 	case KVM_CREATE_VM:
4856 		r = kvm_dev_ioctl_create_vm(arg);
4857 		break;
4858 	case KVM_CHECK_EXTENSION:
4859 		r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4860 		break;
4861 	case KVM_GET_VCPU_MMAP_SIZE:
4862 		if (arg)
4863 			goto out;
4864 		r = PAGE_SIZE;     /* struct kvm_run */
4865 #ifdef CONFIG_X86
4866 		r += PAGE_SIZE;    /* pio data page */
4867 #endif
4868 #ifdef CONFIG_KVM_MMIO
4869 		r += PAGE_SIZE;    /* coalesced mmio ring page */
4870 #endif
4871 		break;
4872 	case KVM_TRACE_ENABLE:
4873 	case KVM_TRACE_PAUSE:
4874 	case KVM_TRACE_DISABLE:
4875 		r = -EOPNOTSUPP;
4876 		break;
4877 	default:
4878 		return kvm_arch_dev_ioctl(filp, ioctl, arg);
4879 	}
4880 out:
4881 	return r;
4882 }
4883 
4884 static struct file_operations kvm_chardev_ops = {
4885 	.unlocked_ioctl = kvm_dev_ioctl,
4886 	.llseek		= noop_llseek,
4887 	KVM_COMPAT(kvm_dev_ioctl),
4888 };
4889 
4890 static struct miscdevice kvm_dev = {
4891 	KVM_MINOR,
4892 	"kvm",
4893 	&kvm_chardev_ops,
4894 };
4895 
hardware_enable_nolock(void * junk)4896 static void hardware_enable_nolock(void *junk)
4897 {
4898 	int cpu = raw_smp_processor_id();
4899 	int r;
4900 
4901 	if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4902 		return;
4903 
4904 	cpumask_set_cpu(cpu, cpus_hardware_enabled);
4905 
4906 	r = kvm_arch_hardware_enable();
4907 
4908 	if (r) {
4909 		cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4910 		atomic_inc(&hardware_enable_failed);
4911 		pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4912 	}
4913 }
4914 
kvm_starting_cpu(unsigned int cpu)4915 static int kvm_starting_cpu(unsigned int cpu)
4916 {
4917 	raw_spin_lock(&kvm_count_lock);
4918 	if (kvm_usage_count)
4919 		hardware_enable_nolock(NULL);
4920 	raw_spin_unlock(&kvm_count_lock);
4921 	return 0;
4922 }
4923 
hardware_disable_nolock(void * junk)4924 static void hardware_disable_nolock(void *junk)
4925 {
4926 	int cpu = raw_smp_processor_id();
4927 
4928 	if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4929 		return;
4930 	cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4931 	kvm_arch_hardware_disable();
4932 }
4933 
kvm_dying_cpu(unsigned int cpu)4934 static int kvm_dying_cpu(unsigned int cpu)
4935 {
4936 	raw_spin_lock(&kvm_count_lock);
4937 	if (kvm_usage_count)
4938 		hardware_disable_nolock(NULL);
4939 	raw_spin_unlock(&kvm_count_lock);
4940 	return 0;
4941 }
4942 
hardware_disable_all_nolock(void)4943 static void hardware_disable_all_nolock(void)
4944 {
4945 	BUG_ON(!kvm_usage_count);
4946 
4947 	kvm_usage_count--;
4948 	if (!kvm_usage_count)
4949 		on_each_cpu(hardware_disable_nolock, NULL, 1);
4950 }
4951 
hardware_disable_all(void)4952 static void hardware_disable_all(void)
4953 {
4954 	raw_spin_lock(&kvm_count_lock);
4955 	hardware_disable_all_nolock();
4956 	raw_spin_unlock(&kvm_count_lock);
4957 }
4958 
hardware_enable_all(void)4959 static int hardware_enable_all(void)
4960 {
4961 	int r = 0;
4962 
4963 	raw_spin_lock(&kvm_count_lock);
4964 
4965 	kvm_usage_count++;
4966 	if (kvm_usage_count == 1) {
4967 		atomic_set(&hardware_enable_failed, 0);
4968 		on_each_cpu(hardware_enable_nolock, NULL, 1);
4969 
4970 		if (atomic_read(&hardware_enable_failed)) {
4971 			hardware_disable_all_nolock();
4972 			r = -EBUSY;
4973 		}
4974 	}
4975 
4976 	raw_spin_unlock(&kvm_count_lock);
4977 
4978 	return r;
4979 }
4980 
kvm_reboot(struct notifier_block * notifier,unsigned long val,void * v)4981 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4982 		      void *v)
4983 {
4984 	/*
4985 	 * Some (well, at least mine) BIOSes hang on reboot if
4986 	 * in vmx root mode.
4987 	 *
4988 	 * And Intel TXT required VMX off for all cpu when system shutdown.
4989 	 */
4990 	pr_info("kvm: exiting hardware virtualization\n");
4991 	kvm_rebooting = true;
4992 	on_each_cpu(hardware_disable_nolock, NULL, 1);
4993 	return NOTIFY_OK;
4994 }
4995 
4996 static struct notifier_block kvm_reboot_notifier = {
4997 	.notifier_call = kvm_reboot,
4998 	.priority = 0,
4999 };
5000 
kvm_io_bus_destroy(struct kvm_io_bus * bus)5001 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
5002 {
5003 	int i;
5004 
5005 	for (i = 0; i < bus->dev_count; i++) {
5006 		struct kvm_io_device *pos = bus->range[i].dev;
5007 
5008 		kvm_iodevice_destructor(pos);
5009 	}
5010 	kfree(bus);
5011 }
5012 
kvm_io_bus_cmp(const struct kvm_io_range * r1,const struct kvm_io_range * r2)5013 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
5014 				 const struct kvm_io_range *r2)
5015 {
5016 	gpa_t addr1 = r1->addr;
5017 	gpa_t addr2 = r2->addr;
5018 
5019 	if (addr1 < addr2)
5020 		return -1;
5021 
5022 	/* If r2->len == 0, match the exact address.  If r2->len != 0,
5023 	 * accept any overlapping write.  Any order is acceptable for
5024 	 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
5025 	 * we process all of them.
5026 	 */
5027 	if (r2->len) {
5028 		addr1 += r1->len;
5029 		addr2 += r2->len;
5030 	}
5031 
5032 	if (addr1 > addr2)
5033 		return 1;
5034 
5035 	return 0;
5036 }
5037 
kvm_io_bus_sort_cmp(const void * p1,const void * p2)5038 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
5039 {
5040 	return kvm_io_bus_cmp(p1, p2);
5041 }
5042 
kvm_io_bus_get_first_dev(struct kvm_io_bus * bus,gpa_t addr,int len)5043 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
5044 			     gpa_t addr, int len)
5045 {
5046 	struct kvm_io_range *range, key;
5047 	int off;
5048 
5049 	key = (struct kvm_io_range) {
5050 		.addr = addr,
5051 		.len = len,
5052 	};
5053 
5054 	range = bsearch(&key, bus->range, bus->dev_count,
5055 			sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
5056 	if (range == NULL)
5057 		return -ENOENT;
5058 
5059 	off = range - bus->range;
5060 
5061 	while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
5062 		off--;
5063 
5064 	return off;
5065 }
5066 
__kvm_io_bus_write(struct kvm_vcpu * vcpu,struct kvm_io_bus * bus,struct kvm_io_range * range,const void * val)5067 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5068 			      struct kvm_io_range *range, const void *val)
5069 {
5070 	int idx;
5071 
5072 	idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5073 	if (idx < 0)
5074 		return -EOPNOTSUPP;
5075 
5076 	while (idx < bus->dev_count &&
5077 		kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5078 		if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
5079 					range->len, val))
5080 			return idx;
5081 		idx++;
5082 	}
5083 
5084 	return -EOPNOTSUPP;
5085 }
5086 
5087 /* kvm_io_bus_write - called under kvm->slots_lock */
kvm_io_bus_write(struct kvm_vcpu * vcpu,enum kvm_bus bus_idx,gpa_t addr,int len,const void * val)5088 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5089 		     int len, const void *val)
5090 {
5091 	struct kvm_io_bus *bus;
5092 	struct kvm_io_range range;
5093 	int r;
5094 
5095 	range = (struct kvm_io_range) {
5096 		.addr = addr,
5097 		.len = len,
5098 	};
5099 
5100 	bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5101 	if (!bus)
5102 		return -ENOMEM;
5103 	r = __kvm_io_bus_write(vcpu, bus, &range, val);
5104 	return r < 0 ? r : 0;
5105 }
5106 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
5107 
5108 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
kvm_io_bus_write_cookie(struct kvm_vcpu * vcpu,enum kvm_bus bus_idx,gpa_t addr,int len,const void * val,long cookie)5109 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
5110 			    gpa_t addr, int len, const void *val, long cookie)
5111 {
5112 	struct kvm_io_bus *bus;
5113 	struct kvm_io_range range;
5114 
5115 	range = (struct kvm_io_range) {
5116 		.addr = addr,
5117 		.len = len,
5118 	};
5119 
5120 	bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5121 	if (!bus)
5122 		return -ENOMEM;
5123 
5124 	/* First try the device referenced by cookie. */
5125 	if ((cookie >= 0) && (cookie < bus->dev_count) &&
5126 	    (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
5127 		if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
5128 					val))
5129 			return cookie;
5130 
5131 	/*
5132 	 * cookie contained garbage; fall back to search and return the
5133 	 * correct cookie value.
5134 	 */
5135 	return __kvm_io_bus_write(vcpu, bus, &range, val);
5136 }
5137 
__kvm_io_bus_read(struct kvm_vcpu * vcpu,struct kvm_io_bus * bus,struct kvm_io_range * range,void * val)5138 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5139 			     struct kvm_io_range *range, void *val)
5140 {
5141 	int idx;
5142 
5143 	idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5144 	if (idx < 0)
5145 		return -EOPNOTSUPP;
5146 
5147 	while (idx < bus->dev_count &&
5148 		kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5149 		if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
5150 				       range->len, val))
5151 			return idx;
5152 		idx++;
5153 	}
5154 
5155 	return -EOPNOTSUPP;
5156 }
5157 
5158 /* kvm_io_bus_read - called under kvm->slots_lock */
kvm_io_bus_read(struct kvm_vcpu * vcpu,enum kvm_bus bus_idx,gpa_t addr,int len,void * val)5159 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5160 		    int len, void *val)
5161 {
5162 	struct kvm_io_bus *bus;
5163 	struct kvm_io_range range;
5164 	int r;
5165 
5166 	range = (struct kvm_io_range) {
5167 		.addr = addr,
5168 		.len = len,
5169 	};
5170 
5171 	bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5172 	if (!bus)
5173 		return -ENOMEM;
5174 	r = __kvm_io_bus_read(vcpu, bus, &range, val);
5175 	return r < 0 ? r : 0;
5176 }
5177 
5178 /* Caller must hold slots_lock. */
kvm_io_bus_register_dev(struct kvm * kvm,enum kvm_bus bus_idx,gpa_t addr,int len,struct kvm_io_device * dev)5179 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
5180 			    int len, struct kvm_io_device *dev)
5181 {
5182 	int i;
5183 	struct kvm_io_bus *new_bus, *bus;
5184 	struct kvm_io_range range;
5185 
5186 	bus = kvm_get_bus(kvm, bus_idx);
5187 	if (!bus)
5188 		return -ENOMEM;
5189 
5190 	/* exclude ioeventfd which is limited by maximum fd */
5191 	if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
5192 		return -ENOSPC;
5193 
5194 	new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
5195 			  GFP_KERNEL_ACCOUNT);
5196 	if (!new_bus)
5197 		return -ENOMEM;
5198 
5199 	range = (struct kvm_io_range) {
5200 		.addr = addr,
5201 		.len = len,
5202 		.dev = dev,
5203 	};
5204 
5205 	for (i = 0; i < bus->dev_count; i++)
5206 		if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
5207 			break;
5208 
5209 	memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
5210 	new_bus->dev_count++;
5211 	new_bus->range[i] = range;
5212 	memcpy(new_bus->range + i + 1, bus->range + i,
5213 		(bus->dev_count - i) * sizeof(struct kvm_io_range));
5214 	rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5215 	synchronize_srcu_expedited(&kvm->srcu);
5216 	kfree(bus);
5217 
5218 	return 0;
5219 }
5220 
kvm_io_bus_unregister_dev(struct kvm * kvm,enum kvm_bus bus_idx,struct kvm_io_device * dev)5221 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5222 			      struct kvm_io_device *dev)
5223 {
5224 	int i, j;
5225 	struct kvm_io_bus *new_bus, *bus;
5226 
5227 	lockdep_assert_held(&kvm->slots_lock);
5228 
5229 	bus = kvm_get_bus(kvm, bus_idx);
5230 	if (!bus)
5231 		return 0;
5232 
5233 	for (i = 0; i < bus->dev_count; i++) {
5234 		if (bus->range[i].dev == dev) {
5235 			break;
5236 		}
5237 	}
5238 
5239 	if (i == bus->dev_count)
5240 		return 0;
5241 
5242 	new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
5243 			  GFP_KERNEL_ACCOUNT);
5244 	if (new_bus) {
5245 		memcpy(new_bus, bus, struct_size(bus, range, i));
5246 		new_bus->dev_count--;
5247 		memcpy(new_bus->range + i, bus->range + i + 1,
5248 				flex_array_size(new_bus, range, new_bus->dev_count - i));
5249 	}
5250 
5251 	rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5252 	synchronize_srcu_expedited(&kvm->srcu);
5253 
5254 	/* Destroy the old bus _after_ installing the (null) bus. */
5255 	if (!new_bus) {
5256 		pr_err("kvm: failed to shrink bus, removing it completely\n");
5257 		for (j = 0; j < bus->dev_count; j++) {
5258 			if (j == i)
5259 				continue;
5260 			kvm_iodevice_destructor(bus->range[j].dev);
5261 		}
5262 	}
5263 
5264 	kfree(bus);
5265 	return new_bus ? 0 : -ENOMEM;
5266 }
5267 
kvm_io_bus_get_dev(struct kvm * kvm,enum kvm_bus bus_idx,gpa_t addr)5268 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5269 					 gpa_t addr)
5270 {
5271 	struct kvm_io_bus *bus;
5272 	int dev_idx, srcu_idx;
5273 	struct kvm_io_device *iodev = NULL;
5274 
5275 	srcu_idx = srcu_read_lock(&kvm->srcu);
5276 
5277 	bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
5278 	if (!bus)
5279 		goto out_unlock;
5280 
5281 	dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5282 	if (dev_idx < 0)
5283 		goto out_unlock;
5284 
5285 	iodev = bus->range[dev_idx].dev;
5286 
5287 out_unlock:
5288 	srcu_read_unlock(&kvm->srcu, srcu_idx);
5289 
5290 	return iodev;
5291 }
5292 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5293 
kvm_debugfs_open(struct inode * inode,struct file * file,int (* get)(void *,u64 *),int (* set)(void *,u64),const char * fmt)5294 static int kvm_debugfs_open(struct inode *inode, struct file *file,
5295 			   int (*get)(void *, u64 *), int (*set)(void *, u64),
5296 			   const char *fmt)
5297 {
5298 	struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5299 					  inode->i_private;
5300 
5301 	/*
5302 	 * The debugfs files are a reference to the kvm struct which
5303         * is still valid when kvm_destroy_vm is called.  kvm_get_kvm_safe
5304         * avoids the race between open and the removal of the debugfs directory.
5305 	 */
5306 	if (!kvm_get_kvm_safe(stat_data->kvm))
5307 		return -ENOENT;
5308 
5309 	if (simple_attr_open(inode, file, get,
5310 		    kvm_stats_debugfs_mode(stat_data->desc) & 0222
5311 		    ? set : NULL,
5312 		    fmt)) {
5313 		kvm_put_kvm(stat_data->kvm);
5314 		return -ENOMEM;
5315 	}
5316 
5317 	return 0;
5318 }
5319 
kvm_debugfs_release(struct inode * inode,struct file * file)5320 static int kvm_debugfs_release(struct inode *inode, struct file *file)
5321 {
5322 	struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5323 					  inode->i_private;
5324 
5325 	simple_attr_release(inode, file);
5326 	kvm_put_kvm(stat_data->kvm);
5327 
5328 	return 0;
5329 }
5330 
kvm_get_stat_per_vm(struct kvm * kvm,size_t offset,u64 * val)5331 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
5332 {
5333 	*val = *(u64 *)((void *)(&kvm->stat) + offset);
5334 
5335 	return 0;
5336 }
5337 
kvm_clear_stat_per_vm(struct kvm * kvm,size_t offset)5338 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
5339 {
5340 	*(u64 *)((void *)(&kvm->stat) + offset) = 0;
5341 
5342 	return 0;
5343 }
5344 
kvm_get_stat_per_vcpu(struct kvm * kvm,size_t offset,u64 * val)5345 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
5346 {
5347 	unsigned long i;
5348 	struct kvm_vcpu *vcpu;
5349 
5350 	*val = 0;
5351 
5352 	kvm_for_each_vcpu(i, vcpu, kvm)
5353 		*val += *(u64 *)((void *)(&vcpu->stat) + offset);
5354 
5355 	return 0;
5356 }
5357 
kvm_clear_stat_per_vcpu(struct kvm * kvm,size_t offset)5358 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
5359 {
5360 	unsigned long i;
5361 	struct kvm_vcpu *vcpu;
5362 
5363 	kvm_for_each_vcpu(i, vcpu, kvm)
5364 		*(u64 *)((void *)(&vcpu->stat) + offset) = 0;
5365 
5366 	return 0;
5367 }
5368 
kvm_stat_data_get(void * data,u64 * val)5369 static int kvm_stat_data_get(void *data, u64 *val)
5370 {
5371 	int r = -EFAULT;
5372 	struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5373 
5374 	switch (stat_data->kind) {
5375 	case KVM_STAT_VM:
5376 		r = kvm_get_stat_per_vm(stat_data->kvm,
5377 					stat_data->desc->desc.offset, val);
5378 		break;
5379 	case KVM_STAT_VCPU:
5380 		r = kvm_get_stat_per_vcpu(stat_data->kvm,
5381 					  stat_data->desc->desc.offset, val);
5382 		break;
5383 	}
5384 
5385 	return r;
5386 }
5387 
kvm_stat_data_clear(void * data,u64 val)5388 static int kvm_stat_data_clear(void *data, u64 val)
5389 {
5390 	int r = -EFAULT;
5391 	struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5392 
5393 	if (val)
5394 		return -EINVAL;
5395 
5396 	switch (stat_data->kind) {
5397 	case KVM_STAT_VM:
5398 		r = kvm_clear_stat_per_vm(stat_data->kvm,
5399 					  stat_data->desc->desc.offset);
5400 		break;
5401 	case KVM_STAT_VCPU:
5402 		r = kvm_clear_stat_per_vcpu(stat_data->kvm,
5403 					    stat_data->desc->desc.offset);
5404 		break;
5405 	}
5406 
5407 	return r;
5408 }
5409 
kvm_stat_data_open(struct inode * inode,struct file * file)5410 static int kvm_stat_data_open(struct inode *inode, struct file *file)
5411 {
5412 	__simple_attr_check_format("%llu\n", 0ull);
5413 	return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5414 				kvm_stat_data_clear, "%llu\n");
5415 }
5416 
5417 static const struct file_operations stat_fops_per_vm = {
5418 	.owner = THIS_MODULE,
5419 	.open = kvm_stat_data_open,
5420 	.release = kvm_debugfs_release,
5421 	.read = simple_attr_read,
5422 	.write = simple_attr_write,
5423 	.llseek = no_llseek,
5424 };
5425 
vm_stat_get(void * _offset,u64 * val)5426 static int vm_stat_get(void *_offset, u64 *val)
5427 {
5428 	unsigned offset = (long)_offset;
5429 	struct kvm *kvm;
5430 	u64 tmp_val;
5431 
5432 	*val = 0;
5433 	mutex_lock(&kvm_lock);
5434 	list_for_each_entry(kvm, &vm_list, vm_list) {
5435 		kvm_get_stat_per_vm(kvm, offset, &tmp_val);
5436 		*val += tmp_val;
5437 	}
5438 	mutex_unlock(&kvm_lock);
5439 	return 0;
5440 }
5441 
vm_stat_clear(void * _offset,u64 val)5442 static int vm_stat_clear(void *_offset, u64 val)
5443 {
5444 	unsigned offset = (long)_offset;
5445 	struct kvm *kvm;
5446 
5447 	if (val)
5448 		return -EINVAL;
5449 
5450 	mutex_lock(&kvm_lock);
5451 	list_for_each_entry(kvm, &vm_list, vm_list) {
5452 		kvm_clear_stat_per_vm(kvm, offset);
5453 	}
5454 	mutex_unlock(&kvm_lock);
5455 
5456 	return 0;
5457 }
5458 
5459 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
5460 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
5461 
vcpu_stat_get(void * _offset,u64 * val)5462 static int vcpu_stat_get(void *_offset, u64 *val)
5463 {
5464 	unsigned offset = (long)_offset;
5465 	struct kvm *kvm;
5466 	u64 tmp_val;
5467 
5468 	*val = 0;
5469 	mutex_lock(&kvm_lock);
5470 	list_for_each_entry(kvm, &vm_list, vm_list) {
5471 		kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
5472 		*val += tmp_val;
5473 	}
5474 	mutex_unlock(&kvm_lock);
5475 	return 0;
5476 }
5477 
vcpu_stat_clear(void * _offset,u64 val)5478 static int vcpu_stat_clear(void *_offset, u64 val)
5479 {
5480 	unsigned offset = (long)_offset;
5481 	struct kvm *kvm;
5482 
5483 	if (val)
5484 		return -EINVAL;
5485 
5486 	mutex_lock(&kvm_lock);
5487 	list_for_each_entry(kvm, &vm_list, vm_list) {
5488 		kvm_clear_stat_per_vcpu(kvm, offset);
5489 	}
5490 	mutex_unlock(&kvm_lock);
5491 
5492 	return 0;
5493 }
5494 
5495 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5496 			"%llu\n");
5497 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
5498 
kvm_uevent_notify_change(unsigned int type,struct kvm * kvm)5499 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5500 {
5501 	struct kobj_uevent_env *env;
5502 	unsigned long long created, active;
5503 
5504 	if (!kvm_dev.this_device || !kvm)
5505 		return;
5506 
5507 	mutex_lock(&kvm_lock);
5508 	if (type == KVM_EVENT_CREATE_VM) {
5509 		kvm_createvm_count++;
5510 		kvm_active_vms++;
5511 	} else if (type == KVM_EVENT_DESTROY_VM) {
5512 		kvm_active_vms--;
5513 	}
5514 	created = kvm_createvm_count;
5515 	active = kvm_active_vms;
5516 	mutex_unlock(&kvm_lock);
5517 
5518 	env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
5519 	if (!env)
5520 		return;
5521 
5522 	add_uevent_var(env, "CREATED=%llu", created);
5523 	add_uevent_var(env, "COUNT=%llu", active);
5524 
5525 	if (type == KVM_EVENT_CREATE_VM) {
5526 		add_uevent_var(env, "EVENT=create");
5527 		kvm->userspace_pid = task_pid_nr(current);
5528 	} else if (type == KVM_EVENT_DESTROY_VM) {
5529 		add_uevent_var(env, "EVENT=destroy");
5530 	}
5531 	add_uevent_var(env, "PID=%d", kvm->userspace_pid);
5532 
5533 	if (!IS_ERR(kvm->debugfs_dentry)) {
5534 		char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
5535 
5536 		if (p) {
5537 			tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5538 			if (!IS_ERR(tmp))
5539 				add_uevent_var(env, "STATS_PATH=%s", tmp);
5540 			kfree(p);
5541 		}
5542 	}
5543 	/* no need for checks, since we are adding at most only 5 keys */
5544 	env->envp[env->envp_idx++] = NULL;
5545 	kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5546 	kfree(env);
5547 }
5548 
kvm_init_debug(void)5549 static void kvm_init_debug(void)
5550 {
5551 	const struct file_operations *fops;
5552 	const struct _kvm_stats_desc *pdesc;
5553 	int i;
5554 
5555 	kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
5556 
5557 	for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
5558 		pdesc = &kvm_vm_stats_desc[i];
5559 		if (kvm_stats_debugfs_mode(pdesc) & 0222)
5560 			fops = &vm_stat_fops;
5561 		else
5562 			fops = &vm_stat_readonly_fops;
5563 		debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5564 				kvm_debugfs_dir,
5565 				(void *)(long)pdesc->desc.offset, fops);
5566 	}
5567 
5568 	for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
5569 		pdesc = &kvm_vcpu_stats_desc[i];
5570 		if (kvm_stats_debugfs_mode(pdesc) & 0222)
5571 			fops = &vcpu_stat_fops;
5572 		else
5573 			fops = &vcpu_stat_readonly_fops;
5574 		debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5575 				kvm_debugfs_dir,
5576 				(void *)(long)pdesc->desc.offset, fops);
5577 	}
5578 }
5579 
kvm_suspend(void)5580 static int kvm_suspend(void)
5581 {
5582 	if (kvm_usage_count)
5583 		hardware_disable_nolock(NULL);
5584 	return 0;
5585 }
5586 
kvm_resume(void)5587 static void kvm_resume(void)
5588 {
5589 	if (kvm_usage_count) {
5590 		lockdep_assert_not_held(&kvm_count_lock);
5591 		hardware_enable_nolock(NULL);
5592 	}
5593 }
5594 
5595 static struct syscore_ops kvm_syscore_ops = {
5596 	.suspend = kvm_suspend,
5597 	.resume = kvm_resume,
5598 };
5599 
5600 static inline
preempt_notifier_to_vcpu(struct preempt_notifier * pn)5601 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5602 {
5603 	return container_of(pn, struct kvm_vcpu, preempt_notifier);
5604 }
5605 
kvm_sched_in(struct preempt_notifier * pn,int cpu)5606 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5607 {
5608 	struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5609 
5610 	WRITE_ONCE(vcpu->preempted, false);
5611 	WRITE_ONCE(vcpu->ready, false);
5612 
5613 	__this_cpu_write(kvm_running_vcpu, vcpu);
5614 	kvm_arch_sched_in(vcpu, cpu);
5615 	kvm_arch_vcpu_load(vcpu, cpu);
5616 }
5617 
kvm_sched_out(struct preempt_notifier * pn,struct task_struct * next)5618 static void kvm_sched_out(struct preempt_notifier *pn,
5619 			  struct task_struct *next)
5620 {
5621 	struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5622 
5623 	if (current->on_rq) {
5624 		WRITE_ONCE(vcpu->preempted, true);
5625 		WRITE_ONCE(vcpu->ready, true);
5626 	}
5627 	kvm_arch_vcpu_put(vcpu);
5628 	__this_cpu_write(kvm_running_vcpu, NULL);
5629 }
5630 
5631 /**
5632  * kvm_get_running_vcpu - get the vcpu running on the current CPU.
5633  *
5634  * We can disable preemption locally around accessing the per-CPU variable,
5635  * and use the resolved vcpu pointer after enabling preemption again,
5636  * because even if the current thread is migrated to another CPU, reading
5637  * the per-CPU value later will give us the same value as we update the
5638  * per-CPU variable in the preempt notifier handlers.
5639  */
kvm_get_running_vcpu(void)5640 struct kvm_vcpu *kvm_get_running_vcpu(void)
5641 {
5642 	struct kvm_vcpu *vcpu;
5643 
5644 	preempt_disable();
5645 	vcpu = __this_cpu_read(kvm_running_vcpu);
5646 	preempt_enable();
5647 
5648 	return vcpu;
5649 }
5650 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
5651 
5652 /**
5653  * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5654  */
kvm_get_running_vcpus(void)5655 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5656 {
5657         return &kvm_running_vcpu;
5658 }
5659 
5660 #ifdef CONFIG_GUEST_PERF_EVENTS
kvm_guest_state(void)5661 static unsigned int kvm_guest_state(void)
5662 {
5663 	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5664 	unsigned int state;
5665 
5666 	if (!kvm_arch_pmi_in_guest(vcpu))
5667 		return 0;
5668 
5669 	state = PERF_GUEST_ACTIVE;
5670 	if (!kvm_arch_vcpu_in_kernel(vcpu))
5671 		state |= PERF_GUEST_USER;
5672 
5673 	return state;
5674 }
5675 
kvm_guest_get_ip(void)5676 static unsigned long kvm_guest_get_ip(void)
5677 {
5678 	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5679 
5680 	/* Retrieving the IP must be guarded by a call to kvm_guest_state(). */
5681 	if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu)))
5682 		return 0;
5683 
5684 	return kvm_arch_vcpu_get_ip(vcpu);
5685 }
5686 
5687 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5688 	.state			= kvm_guest_state,
5689 	.get_ip			= kvm_guest_get_ip,
5690 	.handle_intel_pt_intr	= NULL,
5691 };
5692 
kvm_register_perf_callbacks(unsigned int (* pt_intr_handler)(void))5693 void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void))
5694 {
5695 	kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler;
5696 	perf_register_guest_info_callbacks(&kvm_guest_cbs);
5697 }
kvm_unregister_perf_callbacks(void)5698 void kvm_unregister_perf_callbacks(void)
5699 {
5700 	perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5701 }
5702 #endif
5703 
5704 struct kvm_cpu_compat_check {
5705 	void *opaque;
5706 	int *ret;
5707 };
5708 
check_processor_compat(void * data)5709 static void check_processor_compat(void *data)
5710 {
5711 	struct kvm_cpu_compat_check *c = data;
5712 
5713 	*c->ret = kvm_arch_check_processor_compat(c->opaque);
5714 }
5715 
kvm_init(void * opaque,unsigned vcpu_size,unsigned vcpu_align,struct module * module)5716 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
5717 		  struct module *module)
5718 {
5719 	struct kvm_cpu_compat_check c;
5720 	int r;
5721 	int cpu;
5722 
5723 	r = kvm_arch_init(opaque);
5724 	if (r)
5725 		goto out_fail;
5726 
5727 	/*
5728 	 * kvm_arch_init makes sure there's at most one caller
5729 	 * for architectures that support multiple implementations,
5730 	 * like intel and amd on x86.
5731 	 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5732 	 * conflicts in case kvm is already setup for another implementation.
5733 	 */
5734 	r = kvm_irqfd_init();
5735 	if (r)
5736 		goto out_irqfd;
5737 
5738 	if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
5739 		r = -ENOMEM;
5740 		goto out_free_0;
5741 	}
5742 
5743 	r = kvm_arch_hardware_setup(opaque);
5744 	if (r < 0)
5745 		goto out_free_1;
5746 
5747 	c.ret = &r;
5748 	c.opaque = opaque;
5749 	for_each_online_cpu(cpu) {
5750 		smp_call_function_single(cpu, check_processor_compat, &c, 1);
5751 		if (r < 0)
5752 			goto out_free_2;
5753 	}
5754 
5755 	r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
5756 				      kvm_starting_cpu, kvm_dying_cpu);
5757 	if (r)
5758 		goto out_free_2;
5759 	register_reboot_notifier(&kvm_reboot_notifier);
5760 
5761 	/* A kmem cache lets us meet the alignment requirements of fx_save. */
5762 	if (!vcpu_align)
5763 		vcpu_align = __alignof__(struct kvm_vcpu);
5764 	kvm_vcpu_cache =
5765 		kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5766 					   SLAB_ACCOUNT,
5767 					   offsetof(struct kvm_vcpu, arch),
5768 					   offsetofend(struct kvm_vcpu, stats_id)
5769 					   - offsetof(struct kvm_vcpu, arch),
5770 					   NULL);
5771 	if (!kvm_vcpu_cache) {
5772 		r = -ENOMEM;
5773 		goto out_free_3;
5774 	}
5775 
5776 	for_each_possible_cpu(cpu) {
5777 		if (!alloc_cpumask_var_node(&per_cpu(cpu_kick_mask, cpu),
5778 					    GFP_KERNEL, cpu_to_node(cpu))) {
5779 			r = -ENOMEM;
5780 			goto out_free_4;
5781 		}
5782 	}
5783 
5784 	r = kvm_async_pf_init();
5785 	if (r)
5786 		goto out_free_5;
5787 
5788 	kvm_chardev_ops.owner = module;
5789 
5790 	r = misc_register(&kvm_dev);
5791 	if (r) {
5792 		pr_err("kvm: misc device register failed\n");
5793 		goto out_unreg;
5794 	}
5795 
5796 	register_syscore_ops(&kvm_syscore_ops);
5797 
5798 	kvm_preempt_ops.sched_in = kvm_sched_in;
5799 	kvm_preempt_ops.sched_out = kvm_sched_out;
5800 
5801 	kvm_init_debug();
5802 
5803 	r = kvm_vfio_ops_init();
5804 	WARN_ON(r);
5805 
5806 	return 0;
5807 
5808 out_unreg:
5809 	kvm_async_pf_deinit();
5810 out_free_5:
5811 	for_each_possible_cpu(cpu)
5812 		free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5813 out_free_4:
5814 	kmem_cache_destroy(kvm_vcpu_cache);
5815 out_free_3:
5816 	unregister_reboot_notifier(&kvm_reboot_notifier);
5817 	cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5818 out_free_2:
5819 	kvm_arch_hardware_unsetup();
5820 out_free_1:
5821 	free_cpumask_var(cpus_hardware_enabled);
5822 out_free_0:
5823 	kvm_irqfd_exit();
5824 out_irqfd:
5825 	kvm_arch_exit();
5826 out_fail:
5827 	return r;
5828 }
5829 EXPORT_SYMBOL_GPL(kvm_init);
5830 
kvm_exit(void)5831 void kvm_exit(void)
5832 {
5833 	int cpu;
5834 
5835 	debugfs_remove_recursive(kvm_debugfs_dir);
5836 	misc_deregister(&kvm_dev);
5837 	for_each_possible_cpu(cpu)
5838 		free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5839 	kmem_cache_destroy(kvm_vcpu_cache);
5840 	kvm_async_pf_deinit();
5841 	unregister_syscore_ops(&kvm_syscore_ops);
5842 	unregister_reboot_notifier(&kvm_reboot_notifier);
5843 	cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5844 	on_each_cpu(hardware_disable_nolock, NULL, 1);
5845 	kvm_arch_hardware_unsetup();
5846 	kvm_arch_exit();
5847 	kvm_irqfd_exit();
5848 	free_cpumask_var(cpus_hardware_enabled);
5849 	kvm_vfio_ops_exit();
5850 }
5851 EXPORT_SYMBOL_GPL(kvm_exit);
5852 
5853 struct kvm_vm_worker_thread_context {
5854 	struct kvm *kvm;
5855 	struct task_struct *parent;
5856 	struct completion init_done;
5857 	kvm_vm_thread_fn_t thread_fn;
5858 	uintptr_t data;
5859 	int err;
5860 };
5861 
kvm_vm_worker_thread(void * context)5862 static int kvm_vm_worker_thread(void *context)
5863 {
5864 	/*
5865 	 * The init_context is allocated on the stack of the parent thread, so
5866 	 * we have to locally copy anything that is needed beyond initialization
5867 	 */
5868 	struct kvm_vm_worker_thread_context *init_context = context;
5869 	struct task_struct *parent;
5870 	struct kvm *kvm = init_context->kvm;
5871 	kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5872 	uintptr_t data = init_context->data;
5873 	int err;
5874 
5875 	err = kthread_park(current);
5876 	/* kthread_park(current) is never supposed to return an error */
5877 	WARN_ON(err != 0);
5878 	if (err)
5879 		goto init_complete;
5880 
5881 	err = cgroup_attach_task_all(init_context->parent, current);
5882 	if (err) {
5883 		kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5884 			__func__, err);
5885 		goto init_complete;
5886 	}
5887 
5888 	set_user_nice(current, task_nice(init_context->parent));
5889 
5890 init_complete:
5891 	init_context->err = err;
5892 	complete(&init_context->init_done);
5893 	init_context = NULL;
5894 
5895 	if (err)
5896 		goto out;
5897 
5898 	/* Wait to be woken up by the spawner before proceeding. */
5899 	kthread_parkme();
5900 
5901 	if (!kthread_should_stop())
5902 		err = thread_fn(kvm, data);
5903 
5904 out:
5905 	/*
5906 	 * Move kthread back to its original cgroup to prevent it lingering in
5907 	 * the cgroup of the VM process, after the latter finishes its
5908 	 * execution.
5909 	 *
5910 	 * kthread_stop() waits on the 'exited' completion condition which is
5911 	 * set in exit_mm(), via mm_release(), in do_exit(). However, the
5912 	 * kthread is removed from the cgroup in the cgroup_exit() which is
5913 	 * called after the exit_mm(). This causes the kthread_stop() to return
5914 	 * before the kthread actually quits the cgroup.
5915 	 */
5916 	rcu_read_lock();
5917 	parent = rcu_dereference(current->real_parent);
5918 	get_task_struct(parent);
5919 	rcu_read_unlock();
5920 	cgroup_attach_task_all(parent, current);
5921 	put_task_struct(parent);
5922 
5923 	return err;
5924 }
5925 
kvm_vm_create_worker_thread(struct kvm * kvm,kvm_vm_thread_fn_t thread_fn,uintptr_t data,const char * name,struct task_struct ** thread_ptr)5926 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5927 				uintptr_t data, const char *name,
5928 				struct task_struct **thread_ptr)
5929 {
5930 	struct kvm_vm_worker_thread_context init_context = {};
5931 	struct task_struct *thread;
5932 
5933 	*thread_ptr = NULL;
5934 	init_context.kvm = kvm;
5935 	init_context.parent = current;
5936 	init_context.thread_fn = thread_fn;
5937 	init_context.data = data;
5938 	init_completion(&init_context.init_done);
5939 
5940 	thread = kthread_run(kvm_vm_worker_thread, &init_context,
5941 			     "%s-%d", name, task_pid_nr(current));
5942 	if (IS_ERR(thread))
5943 		return PTR_ERR(thread);
5944 
5945 	/* kthread_run is never supposed to return NULL */
5946 	WARN_ON(thread == NULL);
5947 
5948 	wait_for_completion(&init_context.init_done);
5949 
5950 	if (!init_context.err)
5951 		*thread_ptr = thread;
5952 
5953 	return init_context.err;
5954 }
5955