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