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