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