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