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