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