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