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