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