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