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