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