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