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