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