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