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