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