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 "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/uaccess.h>
56 #include <asm/pgtable.h>
57 
58 #include "coalesced_mmio.h"
59 #include "async_pf.h"
60 
61 #define CREATE_TRACE_POINTS
62 #include <trace/events/kvm.h>
63 
64 MODULE_AUTHOR("Qumranet");
65 MODULE_LICENSE("GPL");
66 
67 /*
68  * Ordering of locks:
69  *
70  * 		kvm->lock --> kvm->slots_lock --> kvm->irq_lock
71  */
72 
73 DEFINE_RAW_SPINLOCK(kvm_lock);
74 LIST_HEAD(vm_list);
75 
76 static cpumask_var_t cpus_hardware_enabled;
77 static int kvm_usage_count = 0;
78 static atomic_t hardware_enable_failed;
79 
80 struct kmem_cache *kvm_vcpu_cache;
81 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
82 
83 static __read_mostly struct preempt_ops kvm_preempt_ops;
84 
85 struct dentry *kvm_debugfs_dir;
86 
87 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
88 			   unsigned long arg);
89 #ifdef CONFIG_COMPAT
90 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
91 				  unsigned long arg);
92 #endif
93 static int hardware_enable_all(void);
94 static void hardware_disable_all(void);
95 
96 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
97 
98 bool kvm_rebooting;
99 EXPORT_SYMBOL_GPL(kvm_rebooting);
100 
101 static bool largepages_enabled = true;
102 
103 static struct page *hwpoison_page;
104 static pfn_t hwpoison_pfn;
105 
106 struct page *fault_page;
107 pfn_t fault_pfn;
108 
kvm_is_mmio_pfn(pfn_t pfn)109 inline int kvm_is_mmio_pfn(pfn_t pfn)
110 {
111 	if (pfn_valid(pfn)) {
112 		int reserved;
113 		struct page *tail = pfn_to_page(pfn);
114 		struct page *head = compound_trans_head(tail);
115 		reserved = PageReserved(head);
116 		if (head != tail) {
117 			/*
118 			 * "head" is not a dangling pointer
119 			 * (compound_trans_head takes care of that)
120 			 * but the hugepage may have been splitted
121 			 * from under us (and we may not hold a
122 			 * reference count on the head page so it can
123 			 * be reused before we run PageReferenced), so
124 			 * we've to check PageTail before returning
125 			 * what we just read.
126 			 */
127 			smp_rmb();
128 			if (PageTail(tail))
129 				return reserved;
130 		}
131 		return PageReserved(tail);
132 	}
133 
134 	return true;
135 }
136 
137 /*
138  * Switches to specified vcpu, until a matching vcpu_put()
139  */
vcpu_load(struct kvm_vcpu * vcpu)140 void vcpu_load(struct kvm_vcpu *vcpu)
141 {
142 	int cpu;
143 
144 	mutex_lock(&vcpu->mutex);
145 	if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
146 		/* The thread running this VCPU changed. */
147 		struct pid *oldpid = vcpu->pid;
148 		struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
149 		rcu_assign_pointer(vcpu->pid, newpid);
150 		synchronize_rcu();
151 		put_pid(oldpid);
152 	}
153 	cpu = get_cpu();
154 	preempt_notifier_register(&vcpu->preempt_notifier);
155 	kvm_arch_vcpu_load(vcpu, cpu);
156 	put_cpu();
157 }
158 
vcpu_put(struct kvm_vcpu * vcpu)159 void vcpu_put(struct kvm_vcpu *vcpu)
160 {
161 	preempt_disable();
162 	kvm_arch_vcpu_put(vcpu);
163 	preempt_notifier_unregister(&vcpu->preempt_notifier);
164 	preempt_enable();
165 	mutex_unlock(&vcpu->mutex);
166 }
167 
ack_flush(void * _completed)168 static void ack_flush(void *_completed)
169 {
170 }
171 
make_all_cpus_request(struct kvm * kvm,unsigned int req)172 static bool make_all_cpus_request(struct kvm *kvm, unsigned int req)
173 {
174 	int i, cpu, me;
175 	cpumask_var_t cpus;
176 	bool called = true;
177 	struct kvm_vcpu *vcpu;
178 
179 	zalloc_cpumask_var(&cpus, GFP_ATOMIC);
180 
181 	me = get_cpu();
182 	kvm_for_each_vcpu(i, vcpu, kvm) {
183 		kvm_make_request(req, vcpu);
184 		cpu = vcpu->cpu;
185 
186 		/* Set ->requests bit before we read ->mode */
187 		smp_mb();
188 
189 		if (cpus != NULL && cpu != -1 && cpu != me &&
190 		      kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
191 			cpumask_set_cpu(cpu, cpus);
192 	}
193 	if (unlikely(cpus == NULL))
194 		smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
195 	else if (!cpumask_empty(cpus))
196 		smp_call_function_many(cpus, ack_flush, NULL, 1);
197 	else
198 		called = false;
199 	put_cpu();
200 	free_cpumask_var(cpus);
201 	return called;
202 }
203 
kvm_flush_remote_tlbs(struct kvm * kvm)204 void kvm_flush_remote_tlbs(struct kvm *kvm)
205 {
206 	long dirty_count = kvm->tlbs_dirty;
207 
208 	smp_mb();
209 	if (make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
210 		++kvm->stat.remote_tlb_flush;
211 	cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
212 }
213 
kvm_reload_remote_mmus(struct kvm * kvm)214 void kvm_reload_remote_mmus(struct kvm *kvm)
215 {
216 	make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
217 }
218 
kvm_vcpu_init(struct kvm_vcpu * vcpu,struct kvm * kvm,unsigned id)219 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
220 {
221 	struct page *page;
222 	int r;
223 
224 	mutex_init(&vcpu->mutex);
225 	vcpu->cpu = -1;
226 	vcpu->kvm = kvm;
227 	vcpu->vcpu_id = id;
228 	vcpu->pid = NULL;
229 	init_waitqueue_head(&vcpu->wq);
230 	kvm_async_pf_vcpu_init(vcpu);
231 
232 	page = alloc_page(GFP_KERNEL | __GFP_ZERO);
233 	if (!page) {
234 		r = -ENOMEM;
235 		goto fail;
236 	}
237 	vcpu->run = page_address(page);
238 
239 	r = kvm_arch_vcpu_init(vcpu);
240 	if (r < 0)
241 		goto fail_free_run;
242 	return 0;
243 
244 fail_free_run:
245 	free_page((unsigned long)vcpu->run);
246 fail:
247 	return r;
248 }
249 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
250 
kvm_vcpu_uninit(struct kvm_vcpu * vcpu)251 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
252 {
253 	put_pid(vcpu->pid);
254 	kvm_arch_vcpu_uninit(vcpu);
255 	free_page((unsigned long)vcpu->run);
256 }
257 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
258 
259 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
mmu_notifier_to_kvm(struct mmu_notifier * mn)260 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
261 {
262 	return container_of(mn, struct kvm, mmu_notifier);
263 }
264 
kvm_mmu_notifier_invalidate_page(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long address)265 static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
266 					     struct mm_struct *mm,
267 					     unsigned long address)
268 {
269 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
270 	int need_tlb_flush, idx;
271 
272 	/*
273 	 * When ->invalidate_page runs, the linux pte has been zapped
274 	 * already but the page is still allocated until
275 	 * ->invalidate_page returns. So if we increase the sequence
276 	 * here the kvm page fault will notice if the spte can't be
277 	 * established because the page is going to be freed. If
278 	 * instead the kvm page fault establishes the spte before
279 	 * ->invalidate_page runs, kvm_unmap_hva will release it
280 	 * before returning.
281 	 *
282 	 * The sequence increase only need to be seen at spin_unlock
283 	 * time, and not at spin_lock time.
284 	 *
285 	 * Increasing the sequence after the spin_unlock would be
286 	 * unsafe because the kvm page fault could then establish the
287 	 * pte after kvm_unmap_hva returned, without noticing the page
288 	 * is going to be freed.
289 	 */
290 	idx = srcu_read_lock(&kvm->srcu);
291 	spin_lock(&kvm->mmu_lock);
292 
293 	kvm->mmu_notifier_seq++;
294 	need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
295 	/* we've to flush the tlb before the pages can be freed */
296 	if (need_tlb_flush)
297 		kvm_flush_remote_tlbs(kvm);
298 
299 	spin_unlock(&kvm->mmu_lock);
300 	srcu_read_unlock(&kvm->srcu, idx);
301 }
302 
kvm_mmu_notifier_change_pte(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long address,pte_t pte)303 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
304 					struct mm_struct *mm,
305 					unsigned long address,
306 					pte_t pte)
307 {
308 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
309 	int idx;
310 
311 	idx = srcu_read_lock(&kvm->srcu);
312 	spin_lock(&kvm->mmu_lock);
313 	kvm->mmu_notifier_seq++;
314 	kvm_set_spte_hva(kvm, address, pte);
315 	spin_unlock(&kvm->mmu_lock);
316 	srcu_read_unlock(&kvm->srcu, idx);
317 }
318 
kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long start,unsigned long end)319 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
320 						    struct mm_struct *mm,
321 						    unsigned long start,
322 						    unsigned long end)
323 {
324 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
325 	int need_tlb_flush = 0, idx;
326 
327 	idx = srcu_read_lock(&kvm->srcu);
328 	spin_lock(&kvm->mmu_lock);
329 	/*
330 	 * The count increase must become visible at unlock time as no
331 	 * spte can be established without taking the mmu_lock and
332 	 * count is also read inside the mmu_lock critical section.
333 	 */
334 	kvm->mmu_notifier_count++;
335 	for (; start < end; start += PAGE_SIZE)
336 		need_tlb_flush |= kvm_unmap_hva(kvm, start);
337 	need_tlb_flush |= kvm->tlbs_dirty;
338 	/* we've to flush the tlb before the pages can be freed */
339 	if (need_tlb_flush)
340 		kvm_flush_remote_tlbs(kvm);
341 
342 	spin_unlock(&kvm->mmu_lock);
343 	srcu_read_unlock(&kvm->srcu, idx);
344 }
345 
kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long start,unsigned long end)346 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
347 						  struct mm_struct *mm,
348 						  unsigned long start,
349 						  unsigned long end)
350 {
351 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
352 
353 	spin_lock(&kvm->mmu_lock);
354 	/*
355 	 * This sequence increase will notify the kvm page fault that
356 	 * the page that is going to be mapped in the spte could have
357 	 * been freed.
358 	 */
359 	kvm->mmu_notifier_seq++;
360 	smp_wmb();
361 	/*
362 	 * The above sequence increase must be visible before the
363 	 * below count decrease, which is ensured by the smp_wmb above
364 	 * in conjunction with the smp_rmb in mmu_notifier_retry().
365 	 */
366 	kvm->mmu_notifier_count--;
367 	spin_unlock(&kvm->mmu_lock);
368 
369 	BUG_ON(kvm->mmu_notifier_count < 0);
370 }
371 
kvm_mmu_notifier_clear_flush_young(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long address)372 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
373 					      struct mm_struct *mm,
374 					      unsigned long address)
375 {
376 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
377 	int young, idx;
378 
379 	idx = srcu_read_lock(&kvm->srcu);
380 	spin_lock(&kvm->mmu_lock);
381 
382 	young = kvm_age_hva(kvm, address);
383 	if (young)
384 		kvm_flush_remote_tlbs(kvm);
385 
386 	spin_unlock(&kvm->mmu_lock);
387 	srcu_read_unlock(&kvm->srcu, idx);
388 
389 	return young;
390 }
391 
kvm_mmu_notifier_test_young(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long address)392 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
393 				       struct mm_struct *mm,
394 				       unsigned long address)
395 {
396 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
397 	int young, idx;
398 
399 	idx = srcu_read_lock(&kvm->srcu);
400 	spin_lock(&kvm->mmu_lock);
401 	young = kvm_test_age_hva(kvm, address);
402 	spin_unlock(&kvm->mmu_lock);
403 	srcu_read_unlock(&kvm->srcu, idx);
404 
405 	return young;
406 }
407 
kvm_mmu_notifier_release(struct mmu_notifier * mn,struct mm_struct * mm)408 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
409 				     struct mm_struct *mm)
410 {
411 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
412 	int idx;
413 
414 	idx = srcu_read_lock(&kvm->srcu);
415 	kvm_arch_flush_shadow(kvm);
416 	srcu_read_unlock(&kvm->srcu, idx);
417 }
418 
419 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
420 	.invalidate_page	= kvm_mmu_notifier_invalidate_page,
421 	.invalidate_range_start	= kvm_mmu_notifier_invalidate_range_start,
422 	.invalidate_range_end	= kvm_mmu_notifier_invalidate_range_end,
423 	.clear_flush_young	= kvm_mmu_notifier_clear_flush_young,
424 	.test_young		= kvm_mmu_notifier_test_young,
425 	.change_pte		= kvm_mmu_notifier_change_pte,
426 	.release		= kvm_mmu_notifier_release,
427 };
428 
kvm_init_mmu_notifier(struct kvm * kvm)429 static int kvm_init_mmu_notifier(struct kvm *kvm)
430 {
431 	kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
432 	return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
433 }
434 
435 #else  /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
436 
kvm_init_mmu_notifier(struct kvm * kvm)437 static int kvm_init_mmu_notifier(struct kvm *kvm)
438 {
439 	return 0;
440 }
441 
442 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
443 
kvm_init_memslots_id(struct kvm * kvm)444 static void kvm_init_memslots_id(struct kvm *kvm)
445 {
446 	int i;
447 	struct kvm_memslots *slots = kvm->memslots;
448 
449 	for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
450 		slots->id_to_index[i] = slots->memslots[i].id = i;
451 }
452 
kvm_create_vm(unsigned long type)453 static struct kvm *kvm_create_vm(unsigned long type)
454 {
455 	int r, i;
456 	struct kvm *kvm = kvm_arch_alloc_vm();
457 
458 	if (!kvm)
459 		return ERR_PTR(-ENOMEM);
460 
461 	r = kvm_arch_init_vm(kvm, type);
462 	if (r)
463 		goto out_err_nodisable;
464 
465 	r = hardware_enable_all();
466 	if (r)
467 		goto out_err_nodisable;
468 
469 #ifdef CONFIG_HAVE_KVM_IRQCHIP
470 	INIT_HLIST_HEAD(&kvm->mask_notifier_list);
471 	INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
472 #endif
473 
474 	r = -ENOMEM;
475 	kvm->memslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
476 	if (!kvm->memslots)
477 		goto out_err_nosrcu;
478 	kvm_init_memslots_id(kvm);
479 	if (init_srcu_struct(&kvm->srcu))
480 		goto out_err_nosrcu;
481 	for (i = 0; i < KVM_NR_BUSES; i++) {
482 		kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
483 					GFP_KERNEL);
484 		if (!kvm->buses[i])
485 			goto out_err;
486 	}
487 
488 	spin_lock_init(&kvm->mmu_lock);
489 	kvm->mm = current->mm;
490 	atomic_inc(&kvm->mm->mm_count);
491 	kvm_eventfd_init(kvm);
492 	mutex_init(&kvm->lock);
493 	mutex_init(&kvm->irq_lock);
494 	mutex_init(&kvm->slots_lock);
495 	atomic_set(&kvm->users_count, 1);
496 
497 	r = kvm_init_mmu_notifier(kvm);
498 	if (r)
499 		goto out_err;
500 
501 	raw_spin_lock(&kvm_lock);
502 	list_add(&kvm->vm_list, &vm_list);
503 	raw_spin_unlock(&kvm_lock);
504 
505 	return kvm;
506 
507 out_err:
508 	cleanup_srcu_struct(&kvm->srcu);
509 out_err_nosrcu:
510 	hardware_disable_all();
511 out_err_nodisable:
512 	for (i = 0; i < KVM_NR_BUSES; i++)
513 		kfree(kvm->buses[i]);
514 	kfree(kvm->memslots);
515 	kvm_arch_free_vm(kvm);
516 	return ERR_PTR(r);
517 }
518 
kvm_destroy_dirty_bitmap(struct kvm_memory_slot * memslot)519 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
520 {
521 	if (!memslot->dirty_bitmap)
522 		return;
523 
524 	if (2 * kvm_dirty_bitmap_bytes(memslot) > PAGE_SIZE)
525 		vfree(memslot->dirty_bitmap_head);
526 	else
527 		kfree(memslot->dirty_bitmap_head);
528 
529 	memslot->dirty_bitmap = NULL;
530 	memslot->dirty_bitmap_head = NULL;
531 }
532 
533 /*
534  * Free any memory in @free but not in @dont.
535  */
kvm_free_physmem_slot(struct kvm_memory_slot * free,struct kvm_memory_slot * dont)536 static void kvm_free_physmem_slot(struct kvm_memory_slot *free,
537 				  struct kvm_memory_slot *dont)
538 {
539 	if (!dont || free->rmap != dont->rmap)
540 		vfree(free->rmap);
541 
542 	if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
543 		kvm_destroy_dirty_bitmap(free);
544 
545 	kvm_arch_free_memslot(free, dont);
546 
547 	free->npages = 0;
548 	free->rmap = NULL;
549 }
550 
kvm_free_physmem(struct kvm * kvm)551 void kvm_free_physmem(struct kvm *kvm)
552 {
553 	struct kvm_memslots *slots = kvm->memslots;
554 	struct kvm_memory_slot *memslot;
555 
556 	kvm_for_each_memslot(memslot, slots)
557 		kvm_free_physmem_slot(memslot, NULL);
558 
559 	kfree(kvm->memslots);
560 }
561 
kvm_destroy_vm(struct kvm * kvm)562 static void kvm_destroy_vm(struct kvm *kvm)
563 {
564 	int i;
565 	struct mm_struct *mm = kvm->mm;
566 
567 	kvm_arch_sync_events(kvm);
568 	raw_spin_lock(&kvm_lock);
569 	list_del(&kvm->vm_list);
570 	raw_spin_unlock(&kvm_lock);
571 	kvm_free_irq_routing(kvm);
572 	for (i = 0; i < KVM_NR_BUSES; i++)
573 		kvm_io_bus_destroy(kvm->buses[i]);
574 	kvm_coalesced_mmio_free(kvm);
575 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
576 	mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
577 #else
578 	kvm_arch_flush_shadow(kvm);
579 #endif
580 	kvm_arch_destroy_vm(kvm);
581 	kvm_free_physmem(kvm);
582 	cleanup_srcu_struct(&kvm->srcu);
583 	kvm_arch_free_vm(kvm);
584 	hardware_disable_all();
585 	mmdrop(mm);
586 }
587 
kvm_get_kvm(struct kvm * kvm)588 void kvm_get_kvm(struct kvm *kvm)
589 {
590 	atomic_inc(&kvm->users_count);
591 }
592 EXPORT_SYMBOL_GPL(kvm_get_kvm);
593 
kvm_put_kvm(struct kvm * kvm)594 void kvm_put_kvm(struct kvm *kvm)
595 {
596 	if (atomic_dec_and_test(&kvm->users_count))
597 		kvm_destroy_vm(kvm);
598 }
599 EXPORT_SYMBOL_GPL(kvm_put_kvm);
600 
601 
kvm_vm_release(struct inode * inode,struct file * filp)602 static int kvm_vm_release(struct inode *inode, struct file *filp)
603 {
604 	struct kvm *kvm = filp->private_data;
605 
606 	kvm_irqfd_release(kvm);
607 
608 	kvm_put_kvm(kvm);
609 	return 0;
610 }
611 
612 /*
613  * Allocation size is twice as large as the actual dirty bitmap size.
614  * This makes it possible to do double buffering: see x86's
615  * kvm_vm_ioctl_get_dirty_log().
616  */
kvm_create_dirty_bitmap(struct kvm_memory_slot * memslot)617 static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
618 {
619 #ifndef CONFIG_S390
620 	unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
621 
622 	if (dirty_bytes > PAGE_SIZE)
623 		memslot->dirty_bitmap = vzalloc(dirty_bytes);
624 	else
625 		memslot->dirty_bitmap = kzalloc(dirty_bytes, GFP_KERNEL);
626 
627 	if (!memslot->dirty_bitmap)
628 		return -ENOMEM;
629 
630 	memslot->dirty_bitmap_head = memslot->dirty_bitmap;
631 	memslot->nr_dirty_pages = 0;
632 #endif /* !CONFIG_S390 */
633 	return 0;
634 }
635 
cmp_memslot(const void * slot1,const void * slot2)636 static int cmp_memslot(const void *slot1, const void *slot2)
637 {
638 	struct kvm_memory_slot *s1, *s2;
639 
640 	s1 = (struct kvm_memory_slot *)slot1;
641 	s2 = (struct kvm_memory_slot *)slot2;
642 
643 	if (s1->npages < s2->npages)
644 		return 1;
645 	if (s1->npages > s2->npages)
646 		return -1;
647 
648 	return 0;
649 }
650 
651 /*
652  * Sort the memslots base on its size, so the larger slots
653  * will get better fit.
654  */
sort_memslots(struct kvm_memslots * slots)655 static void sort_memslots(struct kvm_memslots *slots)
656 {
657 	int i;
658 
659 	sort(slots->memslots, KVM_MEM_SLOTS_NUM,
660 	      sizeof(struct kvm_memory_slot), cmp_memslot, NULL);
661 
662 	for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
663 		slots->id_to_index[slots->memslots[i].id] = i;
664 }
665 
update_memslots(struct kvm_memslots * slots,struct kvm_memory_slot * new)666 void update_memslots(struct kvm_memslots *slots, struct kvm_memory_slot *new)
667 {
668 	if (new) {
669 		int id = new->id;
670 		struct kvm_memory_slot *old = id_to_memslot(slots, id);
671 		unsigned long npages = old->npages;
672 
673 		*old = *new;
674 		if (new->npages != npages)
675 			sort_memslots(slots);
676 	}
677 
678 	slots->generation++;
679 }
680 
681 /*
682  * Allocate some memory and give it an address in the guest physical address
683  * space.
684  *
685  * Discontiguous memory is allowed, mostly for framebuffers.
686  *
687  * Must be called holding mmap_sem for write.
688  */
__kvm_set_memory_region(struct kvm * kvm,struct kvm_userspace_memory_region * mem,int user_alloc)689 int __kvm_set_memory_region(struct kvm *kvm,
690 			    struct kvm_userspace_memory_region *mem,
691 			    int user_alloc)
692 {
693 	int r;
694 	gfn_t base_gfn;
695 	unsigned long npages;
696 	struct kvm_memory_slot *memslot, *slot;
697 	struct kvm_memory_slot old, new;
698 	struct kvm_memslots *slots, *old_memslots;
699 
700 	r = -EINVAL;
701 	/* General sanity checks */
702 	if (mem->memory_size & (PAGE_SIZE - 1))
703 		goto out;
704 	if (mem->guest_phys_addr & (PAGE_SIZE - 1))
705 		goto out;
706 	/* We can read the guest memory with __xxx_user() later on. */
707 	if (user_alloc &&
708 	    ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
709 	     !access_ok(VERIFY_WRITE,
710 			(void __user *)(unsigned long)mem->userspace_addr,
711 			mem->memory_size)))
712 		goto out;
713 	if (mem->slot >= KVM_MEM_SLOTS_NUM)
714 		goto out;
715 	if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
716 		goto out;
717 
718 	memslot = id_to_memslot(kvm->memslots, mem->slot);
719 	base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
720 	npages = mem->memory_size >> PAGE_SHIFT;
721 
722 	r = -EINVAL;
723 	if (npages > KVM_MEM_MAX_NR_PAGES)
724 		goto out;
725 
726 	if (!npages)
727 		mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
728 
729 	new = old = *memslot;
730 
731 	new.id = mem->slot;
732 	new.base_gfn = base_gfn;
733 	new.npages = npages;
734 	new.flags = mem->flags;
735 
736 	/* Disallow changing a memory slot's size. */
737 	r = -EINVAL;
738 	if (npages && old.npages && npages != old.npages)
739 		goto out_free;
740 
741 	/* Check for overlaps */
742 	r = -EEXIST;
743 	kvm_for_each_memslot(slot, kvm->memslots) {
744 		if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot)
745 			continue;
746 		if (!((base_gfn + npages <= slot->base_gfn) ||
747 		      (base_gfn >= slot->base_gfn + slot->npages)))
748 			goto out_free;
749 	}
750 
751 	/* Free page dirty bitmap if unneeded */
752 	if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
753 		new.dirty_bitmap = NULL;
754 
755 	r = -ENOMEM;
756 
757 	/* Allocate if a slot is being created */
758 	if (npages && !old.npages) {
759 		new.user_alloc = user_alloc;
760 		new.userspace_addr = mem->userspace_addr;
761 #ifndef CONFIG_S390
762 		new.rmap = vzalloc(npages * sizeof(*new.rmap));
763 		if (!new.rmap)
764 			goto out_free;
765 #endif /* not defined CONFIG_S390 */
766 		if (kvm_arch_create_memslot(&new, npages))
767 			goto out_free;
768 	}
769 
770 	/* Allocate page dirty bitmap if needed */
771 	if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
772 		if (kvm_create_dirty_bitmap(&new) < 0)
773 			goto out_free;
774 		/* destroy any largepage mappings for dirty tracking */
775 	}
776 
777 	if (!npages || base_gfn != old.base_gfn) {
778 		struct kvm_memory_slot *slot;
779 
780 		r = -ENOMEM;
781 		slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
782 				GFP_KERNEL);
783 		if (!slots)
784 			goto out_free;
785 		slot = id_to_memslot(slots, mem->slot);
786 		slot->flags |= KVM_MEMSLOT_INVALID;
787 
788 		update_memslots(slots, NULL);
789 
790 		old_memslots = kvm->memslots;
791 		rcu_assign_pointer(kvm->memslots, slots);
792 		synchronize_srcu_expedited(&kvm->srcu);
793 		/* slot was deleted or moved, clear iommu mapping */
794 		kvm_iommu_unmap_pages(kvm, &old);
795 		/* From this point no new shadow pages pointing to a deleted,
796 		 * or moved, memslot will be created.
797 		 *
798 		 * validation of sp->gfn happens in:
799 		 * 	- gfn_to_hva (kvm_read_guest, gfn_to_pfn)
800 		 * 	- kvm_is_visible_gfn (mmu_check_roots)
801 		 */
802 		kvm_arch_flush_shadow(kvm);
803 		kfree(old_memslots);
804 	}
805 
806 	r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
807 	if (r)
808 		goto out_free;
809 
810 	r = -ENOMEM;
811 	slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
812 			GFP_KERNEL);
813 	if (!slots)
814 		goto out_free;
815 
816 	/* map new memory slot into the iommu */
817 	if (npages) {
818 		r = kvm_iommu_map_pages(kvm, &new);
819 		if (r)
820 			goto out_slots;
821 	}
822 
823 	/* actual memory is freed via old in kvm_free_physmem_slot below */
824 	if (!npages) {
825 		new.rmap = NULL;
826 		new.dirty_bitmap = NULL;
827 		memset(&new.arch, 0, sizeof(new.arch));
828 	}
829 
830 	update_memslots(slots, &new);
831 	old_memslots = kvm->memslots;
832 	rcu_assign_pointer(kvm->memslots, slots);
833 	synchronize_srcu_expedited(&kvm->srcu);
834 
835 	kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
836 
837 	/*
838 	 * If the new memory slot is created, we need to clear all
839 	 * mmio sptes.
840 	 */
841 	if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT)
842 		kvm_arch_flush_shadow(kvm);
843 
844 	kvm_free_physmem_slot(&old, &new);
845 	kfree(old_memslots);
846 
847 	return 0;
848 
849 out_slots:
850 	kfree(slots);
851 out_free:
852 	kvm_free_physmem_slot(&new, &old);
853 out:
854 	return r;
855 
856 }
857 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
858 
kvm_set_memory_region(struct kvm * kvm,struct kvm_userspace_memory_region * mem,int user_alloc)859 int kvm_set_memory_region(struct kvm *kvm,
860 			  struct kvm_userspace_memory_region *mem,
861 			  int user_alloc)
862 {
863 	int r;
864 
865 	mutex_lock(&kvm->slots_lock);
866 	r = __kvm_set_memory_region(kvm, mem, user_alloc);
867 	mutex_unlock(&kvm->slots_lock);
868 	return r;
869 }
870 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
871 
kvm_vm_ioctl_set_memory_region(struct kvm * kvm,struct kvm_userspace_memory_region * mem,int user_alloc)872 int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
873 				   struct
874 				   kvm_userspace_memory_region *mem,
875 				   int user_alloc)
876 {
877 	if (mem->slot >= KVM_MEMORY_SLOTS)
878 		return -EINVAL;
879 	return kvm_set_memory_region(kvm, mem, user_alloc);
880 }
881 
kvm_get_dirty_log(struct kvm * kvm,struct kvm_dirty_log * log,int * is_dirty)882 int kvm_get_dirty_log(struct kvm *kvm,
883 			struct kvm_dirty_log *log, int *is_dirty)
884 {
885 	struct kvm_memory_slot *memslot;
886 	int r, i;
887 	unsigned long n;
888 	unsigned long any = 0;
889 
890 	r = -EINVAL;
891 	if (log->slot >= KVM_MEMORY_SLOTS)
892 		goto out;
893 
894 	memslot = id_to_memslot(kvm->memslots, log->slot);
895 	r = -ENOENT;
896 	if (!memslot->dirty_bitmap)
897 		goto out;
898 
899 	n = kvm_dirty_bitmap_bytes(memslot);
900 
901 	for (i = 0; !any && i < n/sizeof(long); ++i)
902 		any = memslot->dirty_bitmap[i];
903 
904 	r = -EFAULT;
905 	if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
906 		goto out;
907 
908 	if (any)
909 		*is_dirty = 1;
910 
911 	r = 0;
912 out:
913 	return r;
914 }
915 
kvm_largepages_enabled(void)916 bool kvm_largepages_enabled(void)
917 {
918 	return largepages_enabled;
919 }
920 
kvm_disable_largepages(void)921 void kvm_disable_largepages(void)
922 {
923 	largepages_enabled = false;
924 }
925 EXPORT_SYMBOL_GPL(kvm_disable_largepages);
926 
is_error_page(struct page * page)927 int is_error_page(struct page *page)
928 {
929 	return page == bad_page || page == hwpoison_page || page == fault_page;
930 }
931 EXPORT_SYMBOL_GPL(is_error_page);
932 
is_error_pfn(pfn_t pfn)933 int is_error_pfn(pfn_t pfn)
934 {
935 	return pfn == bad_pfn || pfn == hwpoison_pfn || pfn == fault_pfn;
936 }
937 EXPORT_SYMBOL_GPL(is_error_pfn);
938 
is_hwpoison_pfn(pfn_t pfn)939 int is_hwpoison_pfn(pfn_t pfn)
940 {
941 	return pfn == hwpoison_pfn;
942 }
943 EXPORT_SYMBOL_GPL(is_hwpoison_pfn);
944 
is_fault_pfn(pfn_t pfn)945 int is_fault_pfn(pfn_t pfn)
946 {
947 	return pfn == fault_pfn;
948 }
949 EXPORT_SYMBOL_GPL(is_fault_pfn);
950 
is_noslot_pfn(pfn_t pfn)951 int is_noslot_pfn(pfn_t pfn)
952 {
953 	return pfn == bad_pfn;
954 }
955 EXPORT_SYMBOL_GPL(is_noslot_pfn);
956 
is_invalid_pfn(pfn_t pfn)957 int is_invalid_pfn(pfn_t pfn)
958 {
959 	return pfn == hwpoison_pfn || pfn == fault_pfn;
960 }
961 EXPORT_SYMBOL_GPL(is_invalid_pfn);
962 
bad_hva(void)963 static inline unsigned long bad_hva(void)
964 {
965 	return PAGE_OFFSET;
966 }
967 
kvm_is_error_hva(unsigned long addr)968 int kvm_is_error_hva(unsigned long addr)
969 {
970 	return addr == bad_hva();
971 }
972 EXPORT_SYMBOL_GPL(kvm_is_error_hva);
973 
gfn_to_memslot(struct kvm * kvm,gfn_t gfn)974 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
975 {
976 	return __gfn_to_memslot(kvm_memslots(kvm), gfn);
977 }
978 EXPORT_SYMBOL_GPL(gfn_to_memslot);
979 
kvm_is_visible_gfn(struct kvm * kvm,gfn_t gfn)980 int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
981 {
982 	struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
983 
984 	if (!memslot || memslot->id >= KVM_MEMORY_SLOTS ||
985 	      memslot->flags & KVM_MEMSLOT_INVALID)
986 		return 0;
987 
988 	return 1;
989 }
990 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
991 
kvm_host_page_size(struct kvm * kvm,gfn_t gfn)992 unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
993 {
994 	struct vm_area_struct *vma;
995 	unsigned long addr, size;
996 
997 	size = PAGE_SIZE;
998 
999 	addr = gfn_to_hva(kvm, gfn);
1000 	if (kvm_is_error_hva(addr))
1001 		return PAGE_SIZE;
1002 
1003 	down_read(&current->mm->mmap_sem);
1004 	vma = find_vma(current->mm, addr);
1005 	if (!vma)
1006 		goto out;
1007 
1008 	size = vma_kernel_pagesize(vma);
1009 
1010 out:
1011 	up_read(&current->mm->mmap_sem);
1012 
1013 	return size;
1014 }
1015 
gfn_to_hva_many(struct kvm_memory_slot * slot,gfn_t gfn,gfn_t * nr_pages)1016 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1017 				     gfn_t *nr_pages)
1018 {
1019 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1020 		return bad_hva();
1021 
1022 	if (nr_pages)
1023 		*nr_pages = slot->npages - (gfn - slot->base_gfn);
1024 
1025 	return gfn_to_hva_memslot(slot, gfn);
1026 }
1027 
gfn_to_hva(struct kvm * kvm,gfn_t gfn)1028 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1029 {
1030 	return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1031 }
1032 EXPORT_SYMBOL_GPL(gfn_to_hva);
1033 
get_fault_pfn(void)1034 static pfn_t get_fault_pfn(void)
1035 {
1036 	get_page(fault_page);
1037 	return fault_pfn;
1038 }
1039 
get_user_page_nowait(struct task_struct * tsk,struct mm_struct * mm,unsigned long start,int write,struct page ** page)1040 int get_user_page_nowait(struct task_struct *tsk, struct mm_struct *mm,
1041 	unsigned long start, int write, struct page **page)
1042 {
1043 	int flags = FOLL_TOUCH | FOLL_NOWAIT | FOLL_HWPOISON | FOLL_GET;
1044 
1045 	if (write)
1046 		flags |= FOLL_WRITE;
1047 
1048 	return __get_user_pages(tsk, mm, start, 1, flags, page, NULL, NULL);
1049 }
1050 
check_user_page_hwpoison(unsigned long addr)1051 static inline int check_user_page_hwpoison(unsigned long addr)
1052 {
1053 	int rc, flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_WRITE;
1054 
1055 	rc = __get_user_pages(current, current->mm, addr, 1,
1056 			      flags, NULL, NULL, NULL);
1057 	return rc == -EHWPOISON;
1058 }
1059 
hva_to_pfn(struct kvm * kvm,unsigned long addr,bool atomic,bool * async,bool write_fault,bool * writable)1060 static pfn_t hva_to_pfn(struct kvm *kvm, unsigned long addr, bool atomic,
1061 			bool *async, bool write_fault, bool *writable)
1062 {
1063 	struct page *page[1];
1064 	int npages = 0;
1065 	pfn_t pfn;
1066 
1067 	/* we can do it either atomically or asynchronously, not both */
1068 	BUG_ON(atomic && async);
1069 
1070 	BUG_ON(!write_fault && !writable);
1071 
1072 	if (writable)
1073 		*writable = true;
1074 
1075 	if (atomic || async)
1076 		npages = __get_user_pages_fast(addr, 1, 1, page);
1077 
1078 	if (unlikely(npages != 1) && !atomic) {
1079 		might_sleep();
1080 
1081 		if (writable)
1082 			*writable = write_fault;
1083 
1084 		if (async) {
1085 			down_read(&current->mm->mmap_sem);
1086 			npages = get_user_page_nowait(current, current->mm,
1087 						     addr, write_fault, page);
1088 			up_read(&current->mm->mmap_sem);
1089 		} else
1090 			npages = get_user_pages_fast(addr, 1, write_fault,
1091 						     page);
1092 
1093 		/* map read fault as writable if possible */
1094 		if (unlikely(!write_fault) && npages == 1) {
1095 			struct page *wpage[1];
1096 
1097 			npages = __get_user_pages_fast(addr, 1, 1, wpage);
1098 			if (npages == 1) {
1099 				*writable = true;
1100 				put_page(page[0]);
1101 				page[0] = wpage[0];
1102 			}
1103 			npages = 1;
1104 		}
1105 	}
1106 
1107 	if (unlikely(npages != 1)) {
1108 		struct vm_area_struct *vma;
1109 
1110 		if (atomic)
1111 			return get_fault_pfn();
1112 
1113 		down_read(&current->mm->mmap_sem);
1114 		if (npages == -EHWPOISON ||
1115 			(!async && check_user_page_hwpoison(addr))) {
1116 			up_read(&current->mm->mmap_sem);
1117 			get_page(hwpoison_page);
1118 			return page_to_pfn(hwpoison_page);
1119 		}
1120 
1121 		vma = find_vma_intersection(current->mm, addr, addr+1);
1122 
1123 		if (vma == NULL)
1124 			pfn = get_fault_pfn();
1125 		else if ((vma->vm_flags & VM_PFNMAP)) {
1126 			pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) +
1127 				vma->vm_pgoff;
1128 			BUG_ON(!kvm_is_mmio_pfn(pfn));
1129 		} else {
1130 			if (async && (vma->vm_flags & VM_WRITE))
1131 				*async = true;
1132 			pfn = get_fault_pfn();
1133 		}
1134 		up_read(&current->mm->mmap_sem);
1135 	} else
1136 		pfn = page_to_pfn(page[0]);
1137 
1138 	return pfn;
1139 }
1140 
hva_to_pfn_atomic(struct kvm * kvm,unsigned long addr)1141 pfn_t hva_to_pfn_atomic(struct kvm *kvm, unsigned long addr)
1142 {
1143 	return hva_to_pfn(kvm, addr, true, NULL, true, NULL);
1144 }
1145 EXPORT_SYMBOL_GPL(hva_to_pfn_atomic);
1146 
__gfn_to_pfn(struct kvm * kvm,gfn_t gfn,bool atomic,bool * async,bool write_fault,bool * writable)1147 static pfn_t __gfn_to_pfn(struct kvm *kvm, gfn_t gfn, bool atomic, bool *async,
1148 			  bool write_fault, bool *writable)
1149 {
1150 	unsigned long addr;
1151 
1152 	if (async)
1153 		*async = false;
1154 
1155 	addr = gfn_to_hva(kvm, gfn);
1156 	if (kvm_is_error_hva(addr)) {
1157 		get_page(bad_page);
1158 		return page_to_pfn(bad_page);
1159 	}
1160 
1161 	return hva_to_pfn(kvm, addr, atomic, async, write_fault, writable);
1162 }
1163 
gfn_to_pfn_atomic(struct kvm * kvm,gfn_t gfn)1164 pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1165 {
1166 	return __gfn_to_pfn(kvm, gfn, true, NULL, true, NULL);
1167 }
1168 EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1169 
gfn_to_pfn_async(struct kvm * kvm,gfn_t gfn,bool * async,bool write_fault,bool * writable)1170 pfn_t gfn_to_pfn_async(struct kvm *kvm, gfn_t gfn, bool *async,
1171 		       bool write_fault, bool *writable)
1172 {
1173 	return __gfn_to_pfn(kvm, gfn, false, async, write_fault, writable);
1174 }
1175 EXPORT_SYMBOL_GPL(gfn_to_pfn_async);
1176 
gfn_to_pfn(struct kvm * kvm,gfn_t gfn)1177 pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1178 {
1179 	return __gfn_to_pfn(kvm, gfn, false, NULL, true, NULL);
1180 }
1181 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1182 
gfn_to_pfn_prot(struct kvm * kvm,gfn_t gfn,bool write_fault,bool * writable)1183 pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1184 		      bool *writable)
1185 {
1186 	return __gfn_to_pfn(kvm, gfn, false, NULL, write_fault, writable);
1187 }
1188 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1189 
gfn_to_pfn_memslot(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn)1190 pfn_t gfn_to_pfn_memslot(struct kvm *kvm,
1191 			 struct kvm_memory_slot *slot, gfn_t gfn)
1192 {
1193 	unsigned long addr = gfn_to_hva_memslot(slot, gfn);
1194 	return hva_to_pfn(kvm, addr, false, NULL, true, NULL);
1195 }
1196 
gfn_to_page_many_atomic(struct kvm * kvm,gfn_t gfn,struct page ** pages,int nr_pages)1197 int gfn_to_page_many_atomic(struct kvm *kvm, gfn_t gfn, struct page **pages,
1198 								  int nr_pages)
1199 {
1200 	unsigned long addr;
1201 	gfn_t entry;
1202 
1203 	addr = gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, &entry);
1204 	if (kvm_is_error_hva(addr))
1205 		return -1;
1206 
1207 	if (entry < nr_pages)
1208 		return 0;
1209 
1210 	return __get_user_pages_fast(addr, nr_pages, 1, pages);
1211 }
1212 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1213 
gfn_to_page(struct kvm * kvm,gfn_t gfn)1214 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1215 {
1216 	pfn_t pfn;
1217 
1218 	pfn = gfn_to_pfn(kvm, gfn);
1219 	if (!kvm_is_mmio_pfn(pfn))
1220 		return pfn_to_page(pfn);
1221 
1222 	WARN_ON(kvm_is_mmio_pfn(pfn));
1223 
1224 	get_page(bad_page);
1225 	return bad_page;
1226 }
1227 
1228 EXPORT_SYMBOL_GPL(gfn_to_page);
1229 
kvm_release_page_clean(struct page * page)1230 void kvm_release_page_clean(struct page *page)
1231 {
1232 	kvm_release_pfn_clean(page_to_pfn(page));
1233 }
1234 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1235 
kvm_release_pfn_clean(pfn_t pfn)1236 void kvm_release_pfn_clean(pfn_t pfn)
1237 {
1238 	if (!kvm_is_mmio_pfn(pfn))
1239 		put_page(pfn_to_page(pfn));
1240 }
1241 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1242 
kvm_release_page_dirty(struct page * page)1243 void kvm_release_page_dirty(struct page *page)
1244 {
1245 	kvm_release_pfn_dirty(page_to_pfn(page));
1246 }
1247 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1248 
kvm_release_pfn_dirty(pfn_t pfn)1249 void kvm_release_pfn_dirty(pfn_t pfn)
1250 {
1251 	kvm_set_pfn_dirty(pfn);
1252 	kvm_release_pfn_clean(pfn);
1253 }
1254 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
1255 
kvm_set_page_dirty(struct page * page)1256 void kvm_set_page_dirty(struct page *page)
1257 {
1258 	kvm_set_pfn_dirty(page_to_pfn(page));
1259 }
1260 EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
1261 
kvm_set_pfn_dirty(pfn_t pfn)1262 void kvm_set_pfn_dirty(pfn_t pfn)
1263 {
1264 	if (!kvm_is_mmio_pfn(pfn)) {
1265 		struct page *page = pfn_to_page(pfn);
1266 		if (!PageReserved(page))
1267 			SetPageDirty(page);
1268 	}
1269 }
1270 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1271 
kvm_set_pfn_accessed(pfn_t pfn)1272 void kvm_set_pfn_accessed(pfn_t pfn)
1273 {
1274 	if (!kvm_is_mmio_pfn(pfn))
1275 		mark_page_accessed(pfn_to_page(pfn));
1276 }
1277 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1278 
kvm_get_pfn(pfn_t pfn)1279 void kvm_get_pfn(pfn_t pfn)
1280 {
1281 	if (!kvm_is_mmio_pfn(pfn))
1282 		get_page(pfn_to_page(pfn));
1283 }
1284 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1285 
next_segment(unsigned long len,int offset)1286 static int next_segment(unsigned long len, int offset)
1287 {
1288 	if (len > PAGE_SIZE - offset)
1289 		return PAGE_SIZE - offset;
1290 	else
1291 		return len;
1292 }
1293 
kvm_read_guest_page(struct kvm * kvm,gfn_t gfn,void * data,int offset,int len)1294 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1295 			int len)
1296 {
1297 	int r;
1298 	unsigned long addr;
1299 
1300 	addr = gfn_to_hva(kvm, gfn);
1301 	if (kvm_is_error_hva(addr))
1302 		return -EFAULT;
1303 	r = __copy_from_user(data, (void __user *)addr + offset, len);
1304 	if (r)
1305 		return -EFAULT;
1306 	return 0;
1307 }
1308 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1309 
kvm_read_guest(struct kvm * kvm,gpa_t gpa,void * data,unsigned long len)1310 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1311 {
1312 	gfn_t gfn = gpa >> PAGE_SHIFT;
1313 	int seg;
1314 	int offset = offset_in_page(gpa);
1315 	int ret;
1316 
1317 	while ((seg = next_segment(len, offset)) != 0) {
1318 		ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1319 		if (ret < 0)
1320 			return ret;
1321 		offset = 0;
1322 		len -= seg;
1323 		data += seg;
1324 		++gfn;
1325 	}
1326 	return 0;
1327 }
1328 EXPORT_SYMBOL_GPL(kvm_read_guest);
1329 
kvm_read_guest_atomic(struct kvm * kvm,gpa_t gpa,void * data,unsigned long len)1330 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1331 			  unsigned long len)
1332 {
1333 	int r;
1334 	unsigned long addr;
1335 	gfn_t gfn = gpa >> PAGE_SHIFT;
1336 	int offset = offset_in_page(gpa);
1337 
1338 	addr = gfn_to_hva(kvm, gfn);
1339 	if (kvm_is_error_hva(addr))
1340 		return -EFAULT;
1341 	pagefault_disable();
1342 	r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1343 	pagefault_enable();
1344 	if (r)
1345 		return -EFAULT;
1346 	return 0;
1347 }
1348 EXPORT_SYMBOL(kvm_read_guest_atomic);
1349 
kvm_write_guest_page(struct kvm * kvm,gfn_t gfn,const void * data,int offset,int len)1350 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
1351 			 int offset, int len)
1352 {
1353 	int r;
1354 	unsigned long addr;
1355 
1356 	addr = gfn_to_hva(kvm, gfn);
1357 	if (kvm_is_error_hva(addr))
1358 		return -EFAULT;
1359 	r = __copy_to_user((void __user *)addr + offset, data, len);
1360 	if (r)
1361 		return -EFAULT;
1362 	mark_page_dirty(kvm, gfn);
1363 	return 0;
1364 }
1365 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1366 
kvm_write_guest(struct kvm * kvm,gpa_t gpa,const void * data,unsigned long len)1367 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1368 		    unsigned long len)
1369 {
1370 	gfn_t gfn = gpa >> PAGE_SHIFT;
1371 	int seg;
1372 	int offset = offset_in_page(gpa);
1373 	int ret;
1374 
1375 	while ((seg = next_segment(len, offset)) != 0) {
1376 		ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
1377 		if (ret < 0)
1378 			return ret;
1379 		offset = 0;
1380 		len -= seg;
1381 		data += seg;
1382 		++gfn;
1383 	}
1384 	return 0;
1385 }
1386 
kvm_gfn_to_hva_cache_init(struct kvm * kvm,struct gfn_to_hva_cache * ghc,gpa_t gpa,unsigned long len)1387 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1388 			      gpa_t gpa, unsigned long len)
1389 {
1390 	struct kvm_memslots *slots = kvm_memslots(kvm);
1391 	int offset = offset_in_page(gpa);
1392 	gfn_t start_gfn = gpa >> PAGE_SHIFT;
1393 	gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
1394 	gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
1395 	gfn_t nr_pages_avail;
1396 
1397 	ghc->gpa = gpa;
1398 	ghc->generation = slots->generation;
1399 	ghc->len = len;
1400 	ghc->memslot = gfn_to_memslot(kvm, start_gfn);
1401 	ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, &nr_pages_avail);
1402 	if (!kvm_is_error_hva(ghc->hva) && nr_pages_avail >= nr_pages_needed) {
1403 		ghc->hva += offset;
1404 	} else {
1405 		/*
1406 		 * If the requested region crosses two memslots, we still
1407 		 * verify that the entire region is valid here.
1408 		 */
1409 		while (start_gfn <= end_gfn) {
1410 			ghc->memslot = gfn_to_memslot(kvm, start_gfn);
1411 			ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
1412 						   &nr_pages_avail);
1413 			if (kvm_is_error_hva(ghc->hva))
1414 				return -EFAULT;
1415 			start_gfn += nr_pages_avail;
1416 		}
1417 		/* Use the slow path for cross page reads and writes. */
1418 		ghc->memslot = NULL;
1419 	}
1420 	return 0;
1421 }
1422 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
1423 
kvm_write_guest_cached(struct kvm * kvm,struct gfn_to_hva_cache * ghc,void * data,unsigned long len)1424 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1425 			   void *data, unsigned long len)
1426 {
1427 	struct kvm_memslots *slots = kvm_memslots(kvm);
1428 	int r;
1429 
1430 	BUG_ON(len > ghc->len);
1431 
1432 	if (slots->generation != ghc->generation)
1433 		kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
1434 
1435 	if (unlikely(!ghc->memslot))
1436 		return kvm_write_guest(kvm, ghc->gpa, data, len);
1437 
1438 	if (kvm_is_error_hva(ghc->hva))
1439 		return -EFAULT;
1440 
1441 	r = __copy_to_user((void __user *)ghc->hva, data, len);
1442 	if (r)
1443 		return -EFAULT;
1444 	mark_page_dirty_in_slot(kvm, ghc->memslot, ghc->gpa >> PAGE_SHIFT);
1445 
1446 	return 0;
1447 }
1448 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
1449 
kvm_read_guest_cached(struct kvm * kvm,struct gfn_to_hva_cache * ghc,void * data,unsigned long len)1450 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1451 			   void *data, unsigned long len)
1452 {
1453 	struct kvm_memslots *slots = kvm_memslots(kvm);
1454 	int r;
1455 
1456 	BUG_ON(len > ghc->len);
1457 
1458 	if (slots->generation != ghc->generation)
1459 		kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
1460 
1461 	if (unlikely(!ghc->memslot))
1462 		return kvm_read_guest(kvm, ghc->gpa, data, len);
1463 
1464 	if (kvm_is_error_hva(ghc->hva))
1465 		return -EFAULT;
1466 
1467 	r = __copy_from_user(data, (void __user *)ghc->hva, len);
1468 	if (r)
1469 		return -EFAULT;
1470 
1471 	return 0;
1472 }
1473 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
1474 
kvm_clear_guest_page(struct kvm * kvm,gfn_t gfn,int offset,int len)1475 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
1476 {
1477 	return kvm_write_guest_page(kvm, gfn, (const void *) empty_zero_page,
1478 				    offset, len);
1479 }
1480 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
1481 
kvm_clear_guest(struct kvm * kvm,gpa_t gpa,unsigned long len)1482 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
1483 {
1484 	gfn_t gfn = gpa >> PAGE_SHIFT;
1485 	int seg;
1486 	int offset = offset_in_page(gpa);
1487 	int ret;
1488 
1489         while ((seg = next_segment(len, offset)) != 0) {
1490 		ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
1491 		if (ret < 0)
1492 			return ret;
1493 		offset = 0;
1494 		len -= seg;
1495 		++gfn;
1496 	}
1497 	return 0;
1498 }
1499 EXPORT_SYMBOL_GPL(kvm_clear_guest);
1500 
mark_page_dirty_in_slot(struct kvm * kvm,struct kvm_memory_slot * memslot,gfn_t gfn)1501 void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
1502 			     gfn_t gfn)
1503 {
1504 	if (memslot && memslot->dirty_bitmap) {
1505 		unsigned long rel_gfn = gfn - memslot->base_gfn;
1506 
1507 		if (!test_and_set_bit_le(rel_gfn, memslot->dirty_bitmap))
1508 			memslot->nr_dirty_pages++;
1509 	}
1510 }
1511 
mark_page_dirty(struct kvm * kvm,gfn_t gfn)1512 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
1513 {
1514 	struct kvm_memory_slot *memslot;
1515 
1516 	memslot = gfn_to_memslot(kvm, gfn);
1517 	mark_page_dirty_in_slot(kvm, memslot, gfn);
1518 }
1519 
1520 /*
1521  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
1522  */
kvm_vcpu_block(struct kvm_vcpu * vcpu)1523 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
1524 {
1525 	DEFINE_WAIT(wait);
1526 
1527 	for (;;) {
1528 		prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
1529 
1530 		if (kvm_arch_vcpu_runnable(vcpu)) {
1531 			kvm_make_request(KVM_REQ_UNHALT, vcpu);
1532 			break;
1533 		}
1534 		if (kvm_cpu_has_pending_timer(vcpu))
1535 			break;
1536 		if (signal_pending(current))
1537 			break;
1538 
1539 		schedule();
1540 	}
1541 
1542 	finish_wait(&vcpu->wq, &wait);
1543 }
1544 
kvm_resched(struct kvm_vcpu * vcpu)1545 void kvm_resched(struct kvm_vcpu *vcpu)
1546 {
1547 	if (!need_resched())
1548 		return;
1549 	cond_resched();
1550 }
1551 EXPORT_SYMBOL_GPL(kvm_resched);
1552 
kvm_vcpu_on_spin(struct kvm_vcpu * me)1553 void kvm_vcpu_on_spin(struct kvm_vcpu *me)
1554 {
1555 	struct kvm *kvm = me->kvm;
1556 	struct kvm_vcpu *vcpu;
1557 	int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
1558 	int yielded = 0;
1559 	int pass;
1560 	int i;
1561 
1562 	/*
1563 	 * We boost the priority of a VCPU that is runnable but not
1564 	 * currently running, because it got preempted by something
1565 	 * else and called schedule in __vcpu_run.  Hopefully that
1566 	 * VCPU is holding the lock that we need and will release it.
1567 	 * We approximate round-robin by starting at the last boosted VCPU.
1568 	 */
1569 	for (pass = 0; pass < 2 && !yielded; pass++) {
1570 		kvm_for_each_vcpu(i, vcpu, kvm) {
1571 			struct task_struct *task = NULL;
1572 			struct pid *pid;
1573 			if (!pass && i < last_boosted_vcpu) {
1574 				i = last_boosted_vcpu;
1575 				continue;
1576 			} else if (pass && i > last_boosted_vcpu)
1577 				break;
1578 			if (vcpu == me)
1579 				continue;
1580 			if (waitqueue_active(&vcpu->wq))
1581 				continue;
1582 			rcu_read_lock();
1583 			pid = rcu_dereference(vcpu->pid);
1584 			if (pid)
1585 				task = get_pid_task(vcpu->pid, PIDTYPE_PID);
1586 			rcu_read_unlock();
1587 			if (!task)
1588 				continue;
1589 			if (task->flags & PF_VCPU) {
1590 				put_task_struct(task);
1591 				continue;
1592 			}
1593 			if (yield_to(task, 1)) {
1594 				put_task_struct(task);
1595 				kvm->last_boosted_vcpu = i;
1596 				yielded = 1;
1597 				break;
1598 			}
1599 			put_task_struct(task);
1600 		}
1601 	}
1602 }
1603 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
1604 
kvm_vcpu_fault(struct vm_area_struct * vma,struct vm_fault * vmf)1605 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1606 {
1607 	struct kvm_vcpu *vcpu = vma->vm_file->private_data;
1608 	struct page *page;
1609 
1610 	if (vmf->pgoff == 0)
1611 		page = virt_to_page(vcpu->run);
1612 #ifdef CONFIG_X86
1613 	else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
1614 		page = virt_to_page(vcpu->arch.pio_data);
1615 #endif
1616 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1617 	else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
1618 		page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
1619 #endif
1620 	else
1621 		return kvm_arch_vcpu_fault(vcpu, vmf);
1622 	get_page(page);
1623 	vmf->page = page;
1624 	return 0;
1625 }
1626 
1627 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
1628 	.fault = kvm_vcpu_fault,
1629 };
1630 
kvm_vcpu_mmap(struct file * file,struct vm_area_struct * vma)1631 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
1632 {
1633 	vma->vm_ops = &kvm_vcpu_vm_ops;
1634 	return 0;
1635 }
1636 
kvm_vcpu_release(struct inode * inode,struct file * filp)1637 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
1638 {
1639 	struct kvm_vcpu *vcpu = filp->private_data;
1640 
1641 	kvm_put_kvm(vcpu->kvm);
1642 	return 0;
1643 }
1644 
1645 static struct file_operations kvm_vcpu_fops = {
1646 	.release        = kvm_vcpu_release,
1647 	.unlocked_ioctl = kvm_vcpu_ioctl,
1648 #ifdef CONFIG_COMPAT
1649 	.compat_ioctl   = kvm_vcpu_compat_ioctl,
1650 #endif
1651 	.mmap           = kvm_vcpu_mmap,
1652 	.llseek		= noop_llseek,
1653 };
1654 
1655 /*
1656  * Allocates an inode for the vcpu.
1657  */
create_vcpu_fd(struct kvm_vcpu * vcpu)1658 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
1659 {
1660 	return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR);
1661 }
1662 
1663 /*
1664  * Creates some virtual cpus.  Good luck creating more than one.
1665  */
kvm_vm_ioctl_create_vcpu(struct kvm * kvm,u32 id)1666 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
1667 {
1668 	int r;
1669 	struct kvm_vcpu *vcpu, *v;
1670 
1671 	if (id >= KVM_MAX_VCPUS)
1672 		return -EINVAL;
1673 
1674 	vcpu = kvm_arch_vcpu_create(kvm, id);
1675 	if (IS_ERR(vcpu))
1676 		return PTR_ERR(vcpu);
1677 
1678 	preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
1679 
1680 	r = kvm_arch_vcpu_setup(vcpu);
1681 	if (r)
1682 		goto vcpu_destroy;
1683 
1684 	mutex_lock(&kvm->lock);
1685 	if (!kvm_vcpu_compatible(vcpu)) {
1686 		r = -EINVAL;
1687 		goto unlock_vcpu_destroy;
1688 	}
1689 	if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
1690 		r = -EINVAL;
1691 		goto unlock_vcpu_destroy;
1692 	}
1693 
1694 	kvm_for_each_vcpu(r, v, kvm)
1695 		if (v->vcpu_id == id) {
1696 			r = -EEXIST;
1697 			goto unlock_vcpu_destroy;
1698 		}
1699 
1700 	BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
1701 
1702 	/* Now it's all set up, let userspace reach it */
1703 	kvm_get_kvm(kvm);
1704 	r = create_vcpu_fd(vcpu);
1705 	if (r < 0) {
1706 		kvm_put_kvm(kvm);
1707 		goto unlock_vcpu_destroy;
1708 	}
1709 
1710 	kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
1711 	smp_wmb();
1712 	atomic_inc(&kvm->online_vcpus);
1713 
1714 	mutex_unlock(&kvm->lock);
1715 	return r;
1716 
1717 unlock_vcpu_destroy:
1718 	mutex_unlock(&kvm->lock);
1719 vcpu_destroy:
1720 	kvm_arch_vcpu_destroy(vcpu);
1721 	return r;
1722 }
1723 
kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu * vcpu,sigset_t * sigset)1724 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
1725 {
1726 	if (sigset) {
1727 		sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
1728 		vcpu->sigset_active = 1;
1729 		vcpu->sigset = *sigset;
1730 	} else
1731 		vcpu->sigset_active = 0;
1732 	return 0;
1733 }
1734 
kvm_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)1735 static long kvm_vcpu_ioctl(struct file *filp,
1736 			   unsigned int ioctl, unsigned long arg)
1737 {
1738 	struct kvm_vcpu *vcpu = filp->private_data;
1739 	void __user *argp = (void __user *)arg;
1740 	int r;
1741 	struct kvm_fpu *fpu = NULL;
1742 	struct kvm_sregs *kvm_sregs = NULL;
1743 
1744 	if (vcpu->kvm->mm != current->mm)
1745 		return -EIO;
1746 
1747 #if defined(CONFIG_S390) || defined(CONFIG_PPC)
1748 	/*
1749 	 * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
1750 	 * so vcpu_load() would break it.
1751 	 */
1752 	if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT)
1753 		return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1754 #endif
1755 
1756 
1757 	vcpu_load(vcpu);
1758 	switch (ioctl) {
1759 	case KVM_RUN:
1760 		r = -EINVAL;
1761 		if (arg)
1762 			goto out;
1763 		r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
1764 		trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
1765 		break;
1766 	case KVM_GET_REGS: {
1767 		struct kvm_regs *kvm_regs;
1768 
1769 		r = -ENOMEM;
1770 		kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1771 		if (!kvm_regs)
1772 			goto out;
1773 		r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
1774 		if (r)
1775 			goto out_free1;
1776 		r = -EFAULT;
1777 		if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
1778 			goto out_free1;
1779 		r = 0;
1780 out_free1:
1781 		kfree(kvm_regs);
1782 		break;
1783 	}
1784 	case KVM_SET_REGS: {
1785 		struct kvm_regs *kvm_regs;
1786 
1787 		r = -ENOMEM;
1788 		kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
1789 		if (IS_ERR(kvm_regs)) {
1790 			r = PTR_ERR(kvm_regs);
1791 			goto out;
1792 		}
1793 		r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
1794 		if (r)
1795 			goto out_free2;
1796 		r = 0;
1797 out_free2:
1798 		kfree(kvm_regs);
1799 		break;
1800 	}
1801 	case KVM_GET_SREGS: {
1802 		kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1803 		r = -ENOMEM;
1804 		if (!kvm_sregs)
1805 			goto out;
1806 		r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
1807 		if (r)
1808 			goto out;
1809 		r = -EFAULT;
1810 		if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
1811 			goto out;
1812 		r = 0;
1813 		break;
1814 	}
1815 	case KVM_SET_SREGS: {
1816 		kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
1817 		if (IS_ERR(kvm_sregs)) {
1818 			r = PTR_ERR(kvm_sregs);
1819 			goto out;
1820 		}
1821 		r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
1822 		if (r)
1823 			goto out;
1824 		r = 0;
1825 		break;
1826 	}
1827 	case KVM_GET_MP_STATE: {
1828 		struct kvm_mp_state mp_state;
1829 
1830 		r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
1831 		if (r)
1832 			goto out;
1833 		r = -EFAULT;
1834 		if (copy_to_user(argp, &mp_state, sizeof mp_state))
1835 			goto out;
1836 		r = 0;
1837 		break;
1838 	}
1839 	case KVM_SET_MP_STATE: {
1840 		struct kvm_mp_state mp_state;
1841 
1842 		r = -EFAULT;
1843 		if (copy_from_user(&mp_state, argp, sizeof mp_state))
1844 			goto out;
1845 		r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
1846 		if (r)
1847 			goto out;
1848 		r = 0;
1849 		break;
1850 	}
1851 	case KVM_TRANSLATE: {
1852 		struct kvm_translation tr;
1853 
1854 		r = -EFAULT;
1855 		if (copy_from_user(&tr, argp, sizeof tr))
1856 			goto out;
1857 		r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
1858 		if (r)
1859 			goto out;
1860 		r = -EFAULT;
1861 		if (copy_to_user(argp, &tr, sizeof tr))
1862 			goto out;
1863 		r = 0;
1864 		break;
1865 	}
1866 	case KVM_SET_GUEST_DEBUG: {
1867 		struct kvm_guest_debug dbg;
1868 
1869 		r = -EFAULT;
1870 		if (copy_from_user(&dbg, argp, sizeof dbg))
1871 			goto out;
1872 		r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
1873 		if (r)
1874 			goto out;
1875 		r = 0;
1876 		break;
1877 	}
1878 	case KVM_SET_SIGNAL_MASK: {
1879 		struct kvm_signal_mask __user *sigmask_arg = argp;
1880 		struct kvm_signal_mask kvm_sigmask;
1881 		sigset_t sigset, *p;
1882 
1883 		p = NULL;
1884 		if (argp) {
1885 			r = -EFAULT;
1886 			if (copy_from_user(&kvm_sigmask, argp,
1887 					   sizeof kvm_sigmask))
1888 				goto out;
1889 			r = -EINVAL;
1890 			if (kvm_sigmask.len != sizeof sigset)
1891 				goto out;
1892 			r = -EFAULT;
1893 			if (copy_from_user(&sigset, sigmask_arg->sigset,
1894 					   sizeof sigset))
1895 				goto out;
1896 			p = &sigset;
1897 		}
1898 		r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
1899 		break;
1900 	}
1901 	case KVM_GET_FPU: {
1902 		fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1903 		r = -ENOMEM;
1904 		if (!fpu)
1905 			goto out;
1906 		r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
1907 		if (r)
1908 			goto out;
1909 		r = -EFAULT;
1910 		if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
1911 			goto out;
1912 		r = 0;
1913 		break;
1914 	}
1915 	case KVM_SET_FPU: {
1916 		fpu = memdup_user(argp, sizeof(*fpu));
1917 		if (IS_ERR(fpu)) {
1918 			r = PTR_ERR(fpu);
1919 			goto out;
1920 		}
1921 		r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
1922 		if (r)
1923 			goto out;
1924 		r = 0;
1925 		break;
1926 	}
1927 	default:
1928 		r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1929 	}
1930 out:
1931 	vcpu_put(vcpu);
1932 	kfree(fpu);
1933 	kfree(kvm_sregs);
1934 	return r;
1935 }
1936 
1937 #ifdef CONFIG_COMPAT
kvm_vcpu_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)1938 static long kvm_vcpu_compat_ioctl(struct file *filp,
1939 				  unsigned int ioctl, unsigned long arg)
1940 {
1941 	struct kvm_vcpu *vcpu = filp->private_data;
1942 	void __user *argp = compat_ptr(arg);
1943 	int r;
1944 
1945 	if (vcpu->kvm->mm != current->mm)
1946 		return -EIO;
1947 
1948 	switch (ioctl) {
1949 	case KVM_SET_SIGNAL_MASK: {
1950 		struct kvm_signal_mask __user *sigmask_arg = argp;
1951 		struct kvm_signal_mask kvm_sigmask;
1952 		compat_sigset_t csigset;
1953 		sigset_t sigset;
1954 
1955 		if (argp) {
1956 			r = -EFAULT;
1957 			if (copy_from_user(&kvm_sigmask, argp,
1958 					   sizeof kvm_sigmask))
1959 				goto out;
1960 			r = -EINVAL;
1961 			if (kvm_sigmask.len != sizeof csigset)
1962 				goto out;
1963 			r = -EFAULT;
1964 			if (copy_from_user(&csigset, sigmask_arg->sigset,
1965 					   sizeof csigset))
1966 				goto out;
1967 		}
1968 		sigset_from_compat(&sigset, &csigset);
1969 		r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
1970 		break;
1971 	}
1972 	default:
1973 		r = kvm_vcpu_ioctl(filp, ioctl, arg);
1974 	}
1975 
1976 out:
1977 	return r;
1978 }
1979 #endif
1980 
kvm_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)1981 static long kvm_vm_ioctl(struct file *filp,
1982 			   unsigned int ioctl, unsigned long arg)
1983 {
1984 	struct kvm *kvm = filp->private_data;
1985 	void __user *argp = (void __user *)arg;
1986 	int r;
1987 
1988 	if (kvm->mm != current->mm)
1989 		return -EIO;
1990 	switch (ioctl) {
1991 	case KVM_CREATE_VCPU:
1992 		r = kvm_vm_ioctl_create_vcpu(kvm, arg);
1993 		if (r < 0)
1994 			goto out;
1995 		break;
1996 	case KVM_SET_USER_MEMORY_REGION: {
1997 		struct kvm_userspace_memory_region kvm_userspace_mem;
1998 
1999 		r = -EFAULT;
2000 		if (copy_from_user(&kvm_userspace_mem, argp,
2001 						sizeof kvm_userspace_mem))
2002 			goto out;
2003 
2004 		r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
2005 		if (r)
2006 			goto out;
2007 		break;
2008 	}
2009 	case KVM_GET_DIRTY_LOG: {
2010 		struct kvm_dirty_log log;
2011 
2012 		r = -EFAULT;
2013 		if (copy_from_user(&log, argp, sizeof log))
2014 			goto out;
2015 		r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2016 		if (r)
2017 			goto out;
2018 		break;
2019 	}
2020 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2021 	case KVM_REGISTER_COALESCED_MMIO: {
2022 		struct kvm_coalesced_mmio_zone zone;
2023 		r = -EFAULT;
2024 		if (copy_from_user(&zone, argp, sizeof zone))
2025 			goto out;
2026 		r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
2027 		if (r)
2028 			goto out;
2029 		r = 0;
2030 		break;
2031 	}
2032 	case KVM_UNREGISTER_COALESCED_MMIO: {
2033 		struct kvm_coalesced_mmio_zone zone;
2034 		r = -EFAULT;
2035 		if (copy_from_user(&zone, argp, sizeof zone))
2036 			goto out;
2037 		r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
2038 		if (r)
2039 			goto out;
2040 		r = 0;
2041 		break;
2042 	}
2043 #endif
2044 	case KVM_IRQFD: {
2045 		struct kvm_irqfd data;
2046 
2047 		r = -EFAULT;
2048 		if (copy_from_user(&data, argp, sizeof data))
2049 			goto out;
2050 		r = kvm_irqfd(kvm, data.fd, data.gsi, data.flags);
2051 		break;
2052 	}
2053 	case KVM_IOEVENTFD: {
2054 		struct kvm_ioeventfd data;
2055 
2056 		r = -EFAULT;
2057 		if (copy_from_user(&data, argp, sizeof data))
2058 			goto out;
2059 		r = kvm_ioeventfd(kvm, &data);
2060 		break;
2061 	}
2062 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
2063 	case KVM_SET_BOOT_CPU_ID:
2064 		r = 0;
2065 		mutex_lock(&kvm->lock);
2066 		if (atomic_read(&kvm->online_vcpus) != 0)
2067 			r = -EBUSY;
2068 		else
2069 			kvm->bsp_vcpu_id = arg;
2070 		mutex_unlock(&kvm->lock);
2071 		break;
2072 #endif
2073 	default:
2074 		r = kvm_arch_vm_ioctl(filp, ioctl, arg);
2075 		if (r == -ENOTTY)
2076 			r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
2077 	}
2078 out:
2079 	return r;
2080 }
2081 
2082 #ifdef CONFIG_COMPAT
2083 struct compat_kvm_dirty_log {
2084 	__u32 slot;
2085 	__u32 padding1;
2086 	union {
2087 		compat_uptr_t dirty_bitmap; /* one bit per page */
2088 		__u64 padding2;
2089 	};
2090 };
2091 
kvm_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)2092 static long kvm_vm_compat_ioctl(struct file *filp,
2093 			   unsigned int ioctl, unsigned long arg)
2094 {
2095 	struct kvm *kvm = filp->private_data;
2096 	int r;
2097 
2098 	if (kvm->mm != current->mm)
2099 		return -EIO;
2100 	switch (ioctl) {
2101 	case KVM_GET_DIRTY_LOG: {
2102 		struct compat_kvm_dirty_log compat_log;
2103 		struct kvm_dirty_log log;
2104 
2105 		r = -EFAULT;
2106 		if (copy_from_user(&compat_log, (void __user *)arg,
2107 				   sizeof(compat_log)))
2108 			goto out;
2109 		log.slot	 = compat_log.slot;
2110 		log.padding1	 = compat_log.padding1;
2111 		log.padding2	 = compat_log.padding2;
2112 		log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
2113 
2114 		r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2115 		if (r)
2116 			goto out;
2117 		break;
2118 	}
2119 	default:
2120 		r = kvm_vm_ioctl(filp, ioctl, arg);
2121 	}
2122 
2123 out:
2124 	return r;
2125 }
2126 #endif
2127 
kvm_vm_fault(struct vm_area_struct * vma,struct vm_fault * vmf)2128 static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2129 {
2130 	struct page *page[1];
2131 	unsigned long addr;
2132 	int npages;
2133 	gfn_t gfn = vmf->pgoff;
2134 	struct kvm *kvm = vma->vm_file->private_data;
2135 
2136 	addr = gfn_to_hva(kvm, gfn);
2137 	if (kvm_is_error_hva(addr))
2138 		return VM_FAULT_SIGBUS;
2139 
2140 	npages = get_user_pages(current, current->mm, addr, 1, 1, 0, page,
2141 				NULL);
2142 	if (unlikely(npages != 1))
2143 		return VM_FAULT_SIGBUS;
2144 
2145 	vmf->page = page[0];
2146 	return 0;
2147 }
2148 
2149 static const struct vm_operations_struct kvm_vm_vm_ops = {
2150 	.fault = kvm_vm_fault,
2151 };
2152 
kvm_vm_mmap(struct file * file,struct vm_area_struct * vma)2153 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
2154 {
2155 	vma->vm_ops = &kvm_vm_vm_ops;
2156 	return 0;
2157 }
2158 
2159 static struct file_operations kvm_vm_fops = {
2160 	.release        = kvm_vm_release,
2161 	.unlocked_ioctl = kvm_vm_ioctl,
2162 #ifdef CONFIG_COMPAT
2163 	.compat_ioctl   = kvm_vm_compat_ioctl,
2164 #endif
2165 	.mmap           = kvm_vm_mmap,
2166 	.llseek		= noop_llseek,
2167 };
2168 
kvm_dev_ioctl_create_vm(unsigned long type)2169 static int kvm_dev_ioctl_create_vm(unsigned long type)
2170 {
2171 	int r;
2172 	struct kvm *kvm;
2173 
2174 	kvm = kvm_create_vm(type);
2175 	if (IS_ERR(kvm))
2176 		return PTR_ERR(kvm);
2177 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2178 	r = kvm_coalesced_mmio_init(kvm);
2179 	if (r < 0) {
2180 		kvm_put_kvm(kvm);
2181 		return r;
2182 	}
2183 #endif
2184 	r = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
2185 	if (r < 0)
2186 		kvm_put_kvm(kvm);
2187 
2188 	return r;
2189 }
2190 
kvm_dev_ioctl_check_extension_generic(long arg)2191 static long kvm_dev_ioctl_check_extension_generic(long arg)
2192 {
2193 	switch (arg) {
2194 	case KVM_CAP_USER_MEMORY:
2195 	case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
2196 	case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
2197 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
2198 	case KVM_CAP_SET_BOOT_CPU_ID:
2199 #endif
2200 	case KVM_CAP_INTERNAL_ERROR_DATA:
2201 		return 1;
2202 #ifdef CONFIG_HAVE_KVM_IRQCHIP
2203 	case KVM_CAP_IRQ_ROUTING:
2204 		return KVM_MAX_IRQ_ROUTES;
2205 #endif
2206 	default:
2207 		break;
2208 	}
2209 	return kvm_dev_ioctl_check_extension(arg);
2210 }
2211 
kvm_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)2212 static long kvm_dev_ioctl(struct file *filp,
2213 			  unsigned int ioctl, unsigned long arg)
2214 {
2215 	long r = -EINVAL;
2216 
2217 	switch (ioctl) {
2218 	case KVM_GET_API_VERSION:
2219 		r = -EINVAL;
2220 		if (arg)
2221 			goto out;
2222 		r = KVM_API_VERSION;
2223 		break;
2224 	case KVM_CREATE_VM:
2225 		r = kvm_dev_ioctl_create_vm(arg);
2226 		break;
2227 	case KVM_CHECK_EXTENSION:
2228 		r = kvm_dev_ioctl_check_extension_generic(arg);
2229 		break;
2230 	case KVM_GET_VCPU_MMAP_SIZE:
2231 		r = -EINVAL;
2232 		if (arg)
2233 			goto out;
2234 		r = PAGE_SIZE;     /* struct kvm_run */
2235 #ifdef CONFIG_X86
2236 		r += PAGE_SIZE;    /* pio data page */
2237 #endif
2238 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2239 		r += PAGE_SIZE;    /* coalesced mmio ring page */
2240 #endif
2241 		break;
2242 	case KVM_TRACE_ENABLE:
2243 	case KVM_TRACE_PAUSE:
2244 	case KVM_TRACE_DISABLE:
2245 		r = -EOPNOTSUPP;
2246 		break;
2247 	default:
2248 		return kvm_arch_dev_ioctl(filp, ioctl, arg);
2249 	}
2250 out:
2251 	return r;
2252 }
2253 
2254 static struct file_operations kvm_chardev_ops = {
2255 	.unlocked_ioctl = kvm_dev_ioctl,
2256 	.compat_ioctl   = kvm_dev_ioctl,
2257 	.llseek		= noop_llseek,
2258 };
2259 
2260 static struct miscdevice kvm_dev = {
2261 	KVM_MINOR,
2262 	"kvm",
2263 	&kvm_chardev_ops,
2264 };
2265 
hardware_enable_nolock(void * junk)2266 static void hardware_enable_nolock(void *junk)
2267 {
2268 	int cpu = raw_smp_processor_id();
2269 	int r;
2270 
2271 	if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
2272 		return;
2273 
2274 	cpumask_set_cpu(cpu, cpus_hardware_enabled);
2275 
2276 	r = kvm_arch_hardware_enable(NULL);
2277 
2278 	if (r) {
2279 		cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2280 		atomic_inc(&hardware_enable_failed);
2281 		printk(KERN_INFO "kvm: enabling virtualization on "
2282 				 "CPU%d failed\n", cpu);
2283 	}
2284 }
2285 
hardware_enable(void * junk)2286 static void hardware_enable(void *junk)
2287 {
2288 	raw_spin_lock(&kvm_lock);
2289 	hardware_enable_nolock(junk);
2290 	raw_spin_unlock(&kvm_lock);
2291 }
2292 
hardware_disable_nolock(void * junk)2293 static void hardware_disable_nolock(void *junk)
2294 {
2295 	int cpu = raw_smp_processor_id();
2296 
2297 	if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
2298 		return;
2299 	cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2300 	kvm_arch_hardware_disable(NULL);
2301 }
2302 
hardware_disable(void * junk)2303 static void hardware_disable(void *junk)
2304 {
2305 	raw_spin_lock(&kvm_lock);
2306 	hardware_disable_nolock(junk);
2307 	raw_spin_unlock(&kvm_lock);
2308 }
2309 
hardware_disable_all_nolock(void)2310 static void hardware_disable_all_nolock(void)
2311 {
2312 	BUG_ON(!kvm_usage_count);
2313 
2314 	kvm_usage_count--;
2315 	if (!kvm_usage_count)
2316 		on_each_cpu(hardware_disable_nolock, NULL, 1);
2317 }
2318 
hardware_disable_all(void)2319 static void hardware_disable_all(void)
2320 {
2321 	raw_spin_lock(&kvm_lock);
2322 	hardware_disable_all_nolock();
2323 	raw_spin_unlock(&kvm_lock);
2324 }
2325 
hardware_enable_all(void)2326 static int hardware_enable_all(void)
2327 {
2328 	int r = 0;
2329 
2330 	raw_spin_lock(&kvm_lock);
2331 
2332 	kvm_usage_count++;
2333 	if (kvm_usage_count == 1) {
2334 		atomic_set(&hardware_enable_failed, 0);
2335 		on_each_cpu(hardware_enable_nolock, NULL, 1);
2336 
2337 		if (atomic_read(&hardware_enable_failed)) {
2338 			hardware_disable_all_nolock();
2339 			r = -EBUSY;
2340 		}
2341 	}
2342 
2343 	raw_spin_unlock(&kvm_lock);
2344 
2345 	return r;
2346 }
2347 
kvm_cpu_hotplug(struct notifier_block * notifier,unsigned long val,void * v)2348 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2349 			   void *v)
2350 {
2351 	int cpu = (long)v;
2352 
2353 	if (!kvm_usage_count)
2354 		return NOTIFY_OK;
2355 
2356 	val &= ~CPU_TASKS_FROZEN;
2357 	switch (val) {
2358 	case CPU_DYING:
2359 		printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2360 		       cpu);
2361 		hardware_disable(NULL);
2362 		break;
2363 	case CPU_STARTING:
2364 		printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2365 		       cpu);
2366 		hardware_enable(NULL);
2367 		break;
2368 	}
2369 	return NOTIFY_OK;
2370 }
2371 
2372 
kvm_spurious_fault(void)2373 asmlinkage void kvm_spurious_fault(void)
2374 {
2375 	/* Fault while not rebooting.  We want the trace. */
2376 	BUG();
2377 }
2378 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
2379 
kvm_reboot(struct notifier_block * notifier,unsigned long val,void * v)2380 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2381 		      void *v)
2382 {
2383 	/*
2384 	 * Some (well, at least mine) BIOSes hang on reboot if
2385 	 * in vmx root mode.
2386 	 *
2387 	 * And Intel TXT required VMX off for all cpu when system shutdown.
2388 	 */
2389 	printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2390 	kvm_rebooting = true;
2391 	on_each_cpu(hardware_disable_nolock, NULL, 1);
2392 	return NOTIFY_OK;
2393 }
2394 
2395 static struct notifier_block kvm_reboot_notifier = {
2396 	.notifier_call = kvm_reboot,
2397 	.priority = 0,
2398 };
2399 
kvm_io_bus_destroy(struct kvm_io_bus * bus)2400 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
2401 {
2402 	int i;
2403 
2404 	for (i = 0; i < bus->dev_count; i++) {
2405 		struct kvm_io_device *pos = bus->range[i].dev;
2406 
2407 		kvm_iodevice_destructor(pos);
2408 	}
2409 	kfree(bus);
2410 }
2411 
kvm_io_bus_sort_cmp(const void * p1,const void * p2)2412 int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
2413 {
2414 	const struct kvm_io_range *r1 = p1;
2415 	const struct kvm_io_range *r2 = p2;
2416 
2417 	if (r1->addr < r2->addr)
2418 		return -1;
2419 	if (r1->addr + r1->len > r2->addr + r2->len)
2420 		return 1;
2421 	return 0;
2422 }
2423 
kvm_io_bus_insert_dev(struct kvm_io_bus * bus,struct kvm_io_device * dev,gpa_t addr,int len)2424 int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
2425 			  gpa_t addr, int len)
2426 {
2427 	if (bus->dev_count == NR_IOBUS_DEVS)
2428 		return -ENOSPC;
2429 
2430 	bus->range[bus->dev_count++] = (struct kvm_io_range) {
2431 		.addr = addr,
2432 		.len = len,
2433 		.dev = dev,
2434 	};
2435 
2436 	sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
2437 		kvm_io_bus_sort_cmp, NULL);
2438 
2439 	return 0;
2440 }
2441 
kvm_io_bus_get_first_dev(struct kvm_io_bus * bus,gpa_t addr,int len)2442 int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
2443 			     gpa_t addr, int len)
2444 {
2445 	struct kvm_io_range *range, key;
2446 	int off;
2447 
2448 	key = (struct kvm_io_range) {
2449 		.addr = addr,
2450 		.len = len,
2451 	};
2452 
2453 	range = bsearch(&key, bus->range, bus->dev_count,
2454 			sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
2455 	if (range == NULL)
2456 		return -ENOENT;
2457 
2458 	off = range - bus->range;
2459 
2460 	while (off > 0 && kvm_io_bus_sort_cmp(&key, &bus->range[off-1]) == 0)
2461 		off--;
2462 
2463 	return off;
2464 }
2465 
2466 /* kvm_io_bus_write - called under kvm->slots_lock */
kvm_io_bus_write(struct kvm * kvm,enum kvm_bus bus_idx,gpa_t addr,int len,const void * val)2467 int kvm_io_bus_write(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2468 		     int len, const void *val)
2469 {
2470 	int idx;
2471 	struct kvm_io_bus *bus;
2472 	struct kvm_io_range range;
2473 
2474 	range = (struct kvm_io_range) {
2475 		.addr = addr,
2476 		.len = len,
2477 	};
2478 
2479 	bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
2480 	idx = kvm_io_bus_get_first_dev(bus, addr, len);
2481 	if (idx < 0)
2482 		return -EOPNOTSUPP;
2483 
2484 	while (idx < bus->dev_count &&
2485 		kvm_io_bus_sort_cmp(&range, &bus->range[idx]) == 0) {
2486 		if (!kvm_iodevice_write(bus->range[idx].dev, addr, len, val))
2487 			return 0;
2488 		idx++;
2489 	}
2490 
2491 	return -EOPNOTSUPP;
2492 }
2493 
2494 /* kvm_io_bus_read - called under kvm->slots_lock */
kvm_io_bus_read(struct kvm * kvm,enum kvm_bus bus_idx,gpa_t addr,int len,void * val)2495 int kvm_io_bus_read(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2496 		    int len, void *val)
2497 {
2498 	int idx;
2499 	struct kvm_io_bus *bus;
2500 	struct kvm_io_range range;
2501 
2502 	range = (struct kvm_io_range) {
2503 		.addr = addr,
2504 		.len = len,
2505 	};
2506 
2507 	bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
2508 	idx = kvm_io_bus_get_first_dev(bus, addr, len);
2509 	if (idx < 0)
2510 		return -EOPNOTSUPP;
2511 
2512 	while (idx < bus->dev_count &&
2513 		kvm_io_bus_sort_cmp(&range, &bus->range[idx]) == 0) {
2514 		if (!kvm_iodevice_read(bus->range[idx].dev, addr, len, val))
2515 			return 0;
2516 		idx++;
2517 	}
2518 
2519 	return -EOPNOTSUPP;
2520 }
2521 
2522 /* 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)2523 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2524 			    int len, struct kvm_io_device *dev)
2525 {
2526 	struct kvm_io_bus *new_bus, *bus;
2527 
2528 	bus = kvm->buses[bus_idx];
2529 	if (bus->dev_count > NR_IOBUS_DEVS-1)
2530 		return -ENOSPC;
2531 
2532 	new_bus = kmemdup(bus, sizeof(struct kvm_io_bus), GFP_KERNEL);
2533 	if (!new_bus)
2534 		return -ENOMEM;
2535 	kvm_io_bus_insert_dev(new_bus, dev, addr, len);
2536 	rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
2537 	synchronize_srcu_expedited(&kvm->srcu);
2538 	kfree(bus);
2539 
2540 	return 0;
2541 }
2542 
2543 /* Caller must hold slots_lock. */
kvm_io_bus_unregister_dev(struct kvm * kvm,enum kvm_bus bus_idx,struct kvm_io_device * dev)2544 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
2545 			      struct kvm_io_device *dev)
2546 {
2547 	int i, r;
2548 	struct kvm_io_bus *new_bus, *bus;
2549 
2550 	bus = kvm->buses[bus_idx];
2551 
2552 	new_bus = kmemdup(bus, sizeof(*bus), GFP_KERNEL);
2553 	if (!new_bus)
2554 		return -ENOMEM;
2555 
2556 	r = -ENOENT;
2557 	for (i = 0; i < new_bus->dev_count; i++)
2558 		if (new_bus->range[i].dev == dev) {
2559 			r = 0;
2560 			new_bus->dev_count--;
2561 			new_bus->range[i] = new_bus->range[new_bus->dev_count];
2562 			sort(new_bus->range, new_bus->dev_count,
2563 			     sizeof(struct kvm_io_range),
2564 			     kvm_io_bus_sort_cmp, NULL);
2565 			break;
2566 		}
2567 
2568 	if (r) {
2569 		kfree(new_bus);
2570 		return r;
2571 	}
2572 
2573 	rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
2574 	synchronize_srcu_expedited(&kvm->srcu);
2575 	kfree(bus);
2576 	return r;
2577 }
2578 
2579 static struct notifier_block kvm_cpu_notifier = {
2580 	.notifier_call = kvm_cpu_hotplug,
2581 };
2582 
vm_stat_get(void * _offset,u64 * val)2583 static int vm_stat_get(void *_offset, u64 *val)
2584 {
2585 	unsigned offset = (long)_offset;
2586 	struct kvm *kvm;
2587 
2588 	*val = 0;
2589 	raw_spin_lock(&kvm_lock);
2590 	list_for_each_entry(kvm, &vm_list, vm_list)
2591 		*val += *(u32 *)((void *)kvm + offset);
2592 	raw_spin_unlock(&kvm_lock);
2593 	return 0;
2594 }
2595 
2596 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
2597 
vcpu_stat_get(void * _offset,u64 * val)2598 static int vcpu_stat_get(void *_offset, u64 *val)
2599 {
2600 	unsigned offset = (long)_offset;
2601 	struct kvm *kvm;
2602 	struct kvm_vcpu *vcpu;
2603 	int i;
2604 
2605 	*val = 0;
2606 	raw_spin_lock(&kvm_lock);
2607 	list_for_each_entry(kvm, &vm_list, vm_list)
2608 		kvm_for_each_vcpu(i, vcpu, kvm)
2609 			*val += *(u32 *)((void *)vcpu + offset);
2610 
2611 	raw_spin_unlock(&kvm_lock);
2612 	return 0;
2613 }
2614 
2615 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
2616 
2617 static const struct file_operations *stat_fops[] = {
2618 	[KVM_STAT_VCPU] = &vcpu_stat_fops,
2619 	[KVM_STAT_VM]   = &vm_stat_fops,
2620 };
2621 
kvm_init_debug(void)2622 static int kvm_init_debug(void)
2623 {
2624 	int r = -EFAULT;
2625 	struct kvm_stats_debugfs_item *p;
2626 
2627 	kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
2628 	if (kvm_debugfs_dir == NULL)
2629 		goto out;
2630 
2631 	for (p = debugfs_entries; p->name; ++p) {
2632 		p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
2633 						(void *)(long)p->offset,
2634 						stat_fops[p->kind]);
2635 		if (p->dentry == NULL)
2636 			goto out_dir;
2637 	}
2638 
2639 	return 0;
2640 
2641 out_dir:
2642 	debugfs_remove_recursive(kvm_debugfs_dir);
2643 out:
2644 	return r;
2645 }
2646 
kvm_exit_debug(void)2647 static void kvm_exit_debug(void)
2648 {
2649 	struct kvm_stats_debugfs_item *p;
2650 
2651 	for (p = debugfs_entries; p->name; ++p)
2652 		debugfs_remove(p->dentry);
2653 	debugfs_remove(kvm_debugfs_dir);
2654 }
2655 
kvm_suspend(void)2656 static int kvm_suspend(void)
2657 {
2658 	if (kvm_usage_count)
2659 		hardware_disable_nolock(NULL);
2660 	return 0;
2661 }
2662 
kvm_resume(void)2663 static void kvm_resume(void)
2664 {
2665 	if (kvm_usage_count) {
2666 		WARN_ON(raw_spin_is_locked(&kvm_lock));
2667 		hardware_enable_nolock(NULL);
2668 	}
2669 }
2670 
2671 static struct syscore_ops kvm_syscore_ops = {
2672 	.suspend = kvm_suspend,
2673 	.resume = kvm_resume,
2674 };
2675 
2676 struct page *bad_page;
2677 pfn_t bad_pfn;
2678 
2679 static inline
preempt_notifier_to_vcpu(struct preempt_notifier * pn)2680 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
2681 {
2682 	return container_of(pn, struct kvm_vcpu, preempt_notifier);
2683 }
2684 
kvm_sched_in(struct preempt_notifier * pn,int cpu)2685 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
2686 {
2687 	struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2688 
2689 	kvm_arch_vcpu_load(vcpu, cpu);
2690 }
2691 
kvm_sched_out(struct preempt_notifier * pn,struct task_struct * next)2692 static void kvm_sched_out(struct preempt_notifier *pn,
2693 			  struct task_struct *next)
2694 {
2695 	struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2696 
2697 	kvm_arch_vcpu_put(vcpu);
2698 }
2699 
kvm_init(void * opaque,unsigned vcpu_size,unsigned vcpu_align,struct module * module)2700 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
2701 		  struct module *module)
2702 {
2703 	int r;
2704 	int cpu;
2705 
2706 	r = kvm_arch_init(opaque);
2707 	if (r)
2708 		goto out_fail;
2709 
2710 	bad_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2711 
2712 	if (bad_page == NULL) {
2713 		r = -ENOMEM;
2714 		goto out;
2715 	}
2716 
2717 	bad_pfn = page_to_pfn(bad_page);
2718 
2719 	hwpoison_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2720 
2721 	if (hwpoison_page == NULL) {
2722 		r = -ENOMEM;
2723 		goto out_free_0;
2724 	}
2725 
2726 	hwpoison_pfn = page_to_pfn(hwpoison_page);
2727 
2728 	fault_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2729 
2730 	if (fault_page == NULL) {
2731 		r = -ENOMEM;
2732 		goto out_free_0;
2733 	}
2734 
2735 	fault_pfn = page_to_pfn(fault_page);
2736 
2737 	if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
2738 		r = -ENOMEM;
2739 		goto out_free_0;
2740 	}
2741 
2742 	r = kvm_arch_hardware_setup();
2743 	if (r < 0)
2744 		goto out_free_0a;
2745 
2746 	for_each_online_cpu(cpu) {
2747 		smp_call_function_single(cpu,
2748 				kvm_arch_check_processor_compat,
2749 				&r, 1);
2750 		if (r < 0)
2751 			goto out_free_1;
2752 	}
2753 
2754 	r = register_cpu_notifier(&kvm_cpu_notifier);
2755 	if (r)
2756 		goto out_free_2;
2757 	register_reboot_notifier(&kvm_reboot_notifier);
2758 
2759 	/* A kmem cache lets us meet the alignment requirements of fx_save. */
2760 	if (!vcpu_align)
2761 		vcpu_align = __alignof__(struct kvm_vcpu);
2762 	kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
2763 					   0, NULL);
2764 	if (!kvm_vcpu_cache) {
2765 		r = -ENOMEM;
2766 		goto out_free_3;
2767 	}
2768 
2769 	r = kvm_async_pf_init();
2770 	if (r)
2771 		goto out_free;
2772 
2773 	kvm_chardev_ops.owner = module;
2774 	kvm_vm_fops.owner = module;
2775 	kvm_vcpu_fops.owner = module;
2776 
2777 	r = misc_register(&kvm_dev);
2778 	if (r) {
2779 		printk(KERN_ERR "kvm: misc device register failed\n");
2780 		goto out_unreg;
2781 	}
2782 
2783 	register_syscore_ops(&kvm_syscore_ops);
2784 
2785 	kvm_preempt_ops.sched_in = kvm_sched_in;
2786 	kvm_preempt_ops.sched_out = kvm_sched_out;
2787 
2788 	r = kvm_init_debug();
2789 	if (r) {
2790 		printk(KERN_ERR "kvm: create debugfs files failed\n");
2791 		goto out_undebugfs;
2792 	}
2793 
2794 	return 0;
2795 
2796 out_undebugfs:
2797 	unregister_syscore_ops(&kvm_syscore_ops);
2798 out_unreg:
2799 	kvm_async_pf_deinit();
2800 out_free:
2801 	kmem_cache_destroy(kvm_vcpu_cache);
2802 out_free_3:
2803 	unregister_reboot_notifier(&kvm_reboot_notifier);
2804 	unregister_cpu_notifier(&kvm_cpu_notifier);
2805 out_free_2:
2806 out_free_1:
2807 	kvm_arch_hardware_unsetup();
2808 out_free_0a:
2809 	free_cpumask_var(cpus_hardware_enabled);
2810 out_free_0:
2811 	if (fault_page)
2812 		__free_page(fault_page);
2813 	if (hwpoison_page)
2814 		__free_page(hwpoison_page);
2815 	__free_page(bad_page);
2816 out:
2817 	kvm_arch_exit();
2818 out_fail:
2819 	return r;
2820 }
2821 EXPORT_SYMBOL_GPL(kvm_init);
2822 
kvm_exit(void)2823 void kvm_exit(void)
2824 {
2825 	kvm_exit_debug();
2826 	misc_deregister(&kvm_dev);
2827 	kmem_cache_destroy(kvm_vcpu_cache);
2828 	kvm_async_pf_deinit();
2829 	unregister_syscore_ops(&kvm_syscore_ops);
2830 	unregister_reboot_notifier(&kvm_reboot_notifier);
2831 	unregister_cpu_notifier(&kvm_cpu_notifier);
2832 	on_each_cpu(hardware_disable_nolock, NULL, 1);
2833 	kvm_arch_hardware_unsetup();
2834 	kvm_arch_exit();
2835 	free_cpumask_var(cpus_hardware_enabled);
2836 	__free_page(hwpoison_page);
2837 	__free_page(bad_page);
2838 }
2839 EXPORT_SYMBOL_GPL(kvm_exit);
2840