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