xref: /linux/virt/kvm/kvm_main.c (revision 954a209f431c06b62718a49b403bd4c549f0d6fb)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine (KVM) Hypervisor
4  *
5  * Copyright (C) 2006 Qumranet, Inc.
6  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
7  *
8  * Authors:
9  *   Avi Kivity   <avi@qumranet.com>
10  *   Yaniv Kamay  <yaniv@qumranet.com>
11  */
12 
13 #include <kvm/iodev.h>
14 
15 #include <linux/kvm_host.h>
16 #include <linux/kvm.h>
17 #include <linux/module.h>
18 #include <linux/errno.h>
19 #include <linux/percpu.h>
20 #include <linux/mm.h>
21 #include <linux/miscdevice.h>
22 #include <linux/vmalloc.h>
23 #include <linux/reboot.h>
24 #include <linux/debugfs.h>
25 #include <linux/highmem.h>
26 #include <linux/file.h>
27 #include <linux/syscore_ops.h>
28 #include <linux/cpu.h>
29 #include <linux/sched/signal.h>
30 #include <linux/sched/mm.h>
31 #include <linux/sched/stat.h>
32 #include <linux/cpumask.h>
33 #include <linux/smp.h>
34 #include <linux/anon_inodes.h>
35 #include <linux/profile.h>
36 #include <linux/kvm_para.h>
37 #include <linux/pagemap.h>
38 #include <linux/mman.h>
39 #include <linux/swap.h>
40 #include <linux/bitops.h>
41 #include <linux/spinlock.h>
42 #include <linux/compat.h>
43 #include <linux/srcu.h>
44 #include <linux/hugetlb.h>
45 #include <linux/slab.h>
46 #include <linux/sort.h>
47 #include <linux/bsearch.h>
48 #include <linux/io.h>
49 #include <linux/lockdep.h>
50 #include <linux/kthread.h>
51 #include <linux/suspend.h>
52 
53 #include <asm/processor.h>
54 #include <asm/ioctl.h>
55 #include <linux/uaccess.h>
56 
57 #include "coalesced_mmio.h"
58 #include "async_pf.h"
59 #include "kvm_mm.h"
60 #include "vfio.h"
61 
62 #include <trace/events/ipi.h>
63 
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/kvm.h>
66 
67 #include <linux/kvm_dirty_ring.h>
68 
69 
70 /* Worst case buffer size needed for holding an integer. */
71 #define ITOA_MAX_LEN 12
72 
73 MODULE_AUTHOR("Qumranet");
74 MODULE_DESCRIPTION("Kernel-based Virtual Machine (KVM) Hypervisor");
75 MODULE_LICENSE("GPL");
76 
77 /* Architectures should define their poll value according to the halt latency */
78 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
79 module_param(halt_poll_ns, uint, 0644);
80 EXPORT_SYMBOL_GPL(halt_poll_ns);
81 
82 /* Default doubles per-vcpu halt_poll_ns. */
83 unsigned int halt_poll_ns_grow = 2;
84 module_param(halt_poll_ns_grow, uint, 0644);
85 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
86 
87 /* The start value to grow halt_poll_ns from */
88 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
89 module_param(halt_poll_ns_grow_start, uint, 0644);
90 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
91 
92 /* Default halves per-vcpu halt_poll_ns. */
93 unsigned int halt_poll_ns_shrink = 2;
94 module_param(halt_poll_ns_shrink, uint, 0644);
95 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
96 
97 /*
98  * Allow direct access (from KVM or the CPU) without MMU notifier protection
99  * to unpinned pages.
100  */
101 static bool allow_unsafe_mappings;
102 module_param(allow_unsafe_mappings, bool, 0444);
103 
104 /*
105  * Ordering of locks:
106  *
107  *	kvm->lock --> kvm->slots_lock --> kvm->irq_lock
108  */
109 
110 DEFINE_MUTEX(kvm_lock);
111 LIST_HEAD(vm_list);
112 
113 static struct kmem_cache *kvm_vcpu_cache;
114 
115 static __read_mostly struct preempt_ops kvm_preempt_ops;
116 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
117 
118 static struct dentry *kvm_debugfs_dir;
119 
120 static const struct file_operations stat_fops_per_vm;
121 
122 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
123 			   unsigned long arg);
124 #ifdef CONFIG_KVM_COMPAT
125 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
126 				  unsigned long arg);
127 #define KVM_COMPAT(c)	.compat_ioctl	= (c)
128 #else
129 /*
130  * For architectures that don't implement a compat infrastructure,
131  * adopt a double line of defense:
132  * - Prevent a compat task from opening /dev/kvm
133  * - If the open has been done by a 64bit task, and the KVM fd
134  *   passed to a compat task, let the ioctls fail.
135  */
kvm_no_compat_ioctl(struct file * file,unsigned int ioctl,unsigned long arg)136 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
137 				unsigned long arg) { return -EINVAL; }
138 
kvm_no_compat_open(struct inode * inode,struct file * file)139 static int kvm_no_compat_open(struct inode *inode, struct file *file)
140 {
141 	return is_compat_task() ? -ENODEV : 0;
142 }
143 #define KVM_COMPAT(c)	.compat_ioctl	= kvm_no_compat_ioctl,	\
144 			.open		= kvm_no_compat_open
145 #endif
146 static int kvm_enable_virtualization(void);
147 static void kvm_disable_virtualization(void);
148 
149 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
150 
151 #define KVM_EVENT_CREATE_VM 0
152 #define KVM_EVENT_DESTROY_VM 1
153 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
154 static unsigned long long kvm_createvm_count;
155 static unsigned long long kvm_active_vms;
156 
157 static DEFINE_PER_CPU(cpumask_var_t, cpu_kick_mask);
158 
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)159 __weak void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
160 {
161 }
162 
163 /*
164  * Switches to specified vcpu, until a matching vcpu_put()
165  */
vcpu_load(struct kvm_vcpu * vcpu)166 void vcpu_load(struct kvm_vcpu *vcpu)
167 {
168 	int cpu = get_cpu();
169 
170 	__this_cpu_write(kvm_running_vcpu, vcpu);
171 	preempt_notifier_register(&vcpu->preempt_notifier);
172 	kvm_arch_vcpu_load(vcpu, cpu);
173 	put_cpu();
174 }
175 EXPORT_SYMBOL_GPL(vcpu_load);
176 
vcpu_put(struct kvm_vcpu * vcpu)177 void vcpu_put(struct kvm_vcpu *vcpu)
178 {
179 	preempt_disable();
180 	kvm_arch_vcpu_put(vcpu);
181 	preempt_notifier_unregister(&vcpu->preempt_notifier);
182 	__this_cpu_write(kvm_running_vcpu, NULL);
183 	preempt_enable();
184 }
185 EXPORT_SYMBOL_GPL(vcpu_put);
186 
187 /* TODO: merge with kvm_arch_vcpu_should_kick */
kvm_request_needs_ipi(struct kvm_vcpu * vcpu,unsigned req)188 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
189 {
190 	int mode = kvm_vcpu_exiting_guest_mode(vcpu);
191 
192 	/*
193 	 * We need to wait for the VCPU to reenable interrupts and get out of
194 	 * READING_SHADOW_PAGE_TABLES mode.
195 	 */
196 	if (req & KVM_REQUEST_WAIT)
197 		return mode != OUTSIDE_GUEST_MODE;
198 
199 	/*
200 	 * Need to kick a running VCPU, but otherwise there is nothing to do.
201 	 */
202 	return mode == IN_GUEST_MODE;
203 }
204 
ack_kick(void * _completed)205 static void ack_kick(void *_completed)
206 {
207 }
208 
kvm_kick_many_cpus(struct cpumask * cpus,bool wait)209 static inline bool kvm_kick_many_cpus(struct cpumask *cpus, bool wait)
210 {
211 	if (cpumask_empty(cpus))
212 		return false;
213 
214 	smp_call_function_many(cpus, ack_kick, NULL, wait);
215 	return true;
216 }
217 
kvm_make_vcpu_request(struct kvm_vcpu * vcpu,unsigned int req,struct cpumask * tmp,int current_cpu)218 static void kvm_make_vcpu_request(struct kvm_vcpu *vcpu, unsigned int req,
219 				  struct cpumask *tmp, int current_cpu)
220 {
221 	int cpu;
222 
223 	if (likely(!(req & KVM_REQUEST_NO_ACTION)))
224 		__kvm_make_request(req, vcpu);
225 
226 	if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
227 		return;
228 
229 	/*
230 	 * Note, the vCPU could get migrated to a different pCPU at any point
231 	 * after kvm_request_needs_ipi(), which could result in sending an IPI
232 	 * to the previous pCPU.  But, that's OK because the purpose of the IPI
233 	 * is to ensure the vCPU returns to OUTSIDE_GUEST_MODE, which is
234 	 * satisfied if the vCPU migrates. Entering READING_SHADOW_PAGE_TABLES
235 	 * after this point is also OK, as the requirement is only that KVM wait
236 	 * for vCPUs that were reading SPTEs _before_ any changes were
237 	 * finalized. See kvm_vcpu_kick() for more details on handling requests.
238 	 */
239 	if (kvm_request_needs_ipi(vcpu, req)) {
240 		cpu = READ_ONCE(vcpu->cpu);
241 		if (cpu != -1 && cpu != current_cpu)
242 			__cpumask_set_cpu(cpu, tmp);
243 	}
244 }
245 
kvm_make_vcpus_request_mask(struct kvm * kvm,unsigned int req,unsigned long * vcpu_bitmap)246 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
247 				 unsigned long *vcpu_bitmap)
248 {
249 	struct kvm_vcpu *vcpu;
250 	struct cpumask *cpus;
251 	int i, me;
252 	bool called;
253 
254 	me = get_cpu();
255 
256 	cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
257 	cpumask_clear(cpus);
258 
259 	for_each_set_bit(i, vcpu_bitmap, KVM_MAX_VCPUS) {
260 		vcpu = kvm_get_vcpu(kvm, i);
261 		if (!vcpu)
262 			continue;
263 		kvm_make_vcpu_request(vcpu, req, cpus, me);
264 	}
265 
266 	called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
267 	put_cpu();
268 
269 	return called;
270 }
271 
kvm_make_all_cpus_request(struct kvm * kvm,unsigned int req)272 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
273 {
274 	struct kvm_vcpu *vcpu;
275 	struct cpumask *cpus;
276 	unsigned long i;
277 	bool called;
278 	int me;
279 
280 	me = get_cpu();
281 
282 	cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
283 	cpumask_clear(cpus);
284 
285 	kvm_for_each_vcpu(i, vcpu, kvm)
286 		kvm_make_vcpu_request(vcpu, req, cpus, me);
287 
288 	called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
289 	put_cpu();
290 
291 	return called;
292 }
293 EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
294 
kvm_flush_remote_tlbs(struct kvm * kvm)295 void kvm_flush_remote_tlbs(struct kvm *kvm)
296 {
297 	++kvm->stat.generic.remote_tlb_flush_requests;
298 
299 	/*
300 	 * We want to publish modifications to the page tables before reading
301 	 * mode. Pairs with a memory barrier in arch-specific code.
302 	 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
303 	 * and smp_mb in walk_shadow_page_lockless_begin/end.
304 	 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
305 	 *
306 	 * There is already an smp_mb__after_atomic() before
307 	 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
308 	 * barrier here.
309 	 */
310 	if (!kvm_arch_flush_remote_tlbs(kvm)
311 	    || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
312 		++kvm->stat.generic.remote_tlb_flush;
313 }
314 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
315 
kvm_flush_remote_tlbs_range(struct kvm * kvm,gfn_t gfn,u64 nr_pages)316 void kvm_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, u64 nr_pages)
317 {
318 	if (!kvm_arch_flush_remote_tlbs_range(kvm, gfn, nr_pages))
319 		return;
320 
321 	/*
322 	 * Fall back to a flushing entire TLBs if the architecture range-based
323 	 * TLB invalidation is unsupported or can't be performed for whatever
324 	 * reason.
325 	 */
326 	kvm_flush_remote_tlbs(kvm);
327 }
328 
kvm_flush_remote_tlbs_memslot(struct kvm * kvm,const struct kvm_memory_slot * memslot)329 void kvm_flush_remote_tlbs_memslot(struct kvm *kvm,
330 				   const struct kvm_memory_slot *memslot)
331 {
332 	/*
333 	 * All current use cases for flushing the TLBs for a specific memslot
334 	 * are related to dirty logging, and many do the TLB flush out of
335 	 * mmu_lock. The interaction between the various operations on memslot
336 	 * must be serialized by slots_locks to ensure the TLB flush from one
337 	 * operation is observed by any other operation on the same memslot.
338 	 */
339 	lockdep_assert_held(&kvm->slots_lock);
340 	kvm_flush_remote_tlbs_range(kvm, memslot->base_gfn, memslot->npages);
341 }
342 
kvm_flush_shadow_all(struct kvm * kvm)343 static void kvm_flush_shadow_all(struct kvm *kvm)
344 {
345 	kvm_arch_flush_shadow_all(kvm);
346 	kvm_arch_guest_memory_reclaimed(kvm);
347 }
348 
349 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache * mc,gfp_t gfp_flags)350 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
351 					       gfp_t gfp_flags)
352 {
353 	void *page;
354 
355 	gfp_flags |= mc->gfp_zero;
356 
357 	if (mc->kmem_cache)
358 		return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
359 
360 	page = (void *)__get_free_page(gfp_flags);
361 	if (page && mc->init_value)
362 		memset64(page, mc->init_value, PAGE_SIZE / sizeof(u64));
363 	return page;
364 }
365 
__kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache * mc,int capacity,int min)366 int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min)
367 {
368 	gfp_t gfp = mc->gfp_custom ? mc->gfp_custom : GFP_KERNEL_ACCOUNT;
369 	void *obj;
370 
371 	if (mc->nobjs >= min)
372 		return 0;
373 
374 	if (unlikely(!mc->objects)) {
375 		if (WARN_ON_ONCE(!capacity))
376 			return -EIO;
377 
378 		/*
379 		 * Custom init values can be used only for page allocations,
380 		 * and obviously conflict with __GFP_ZERO.
381 		 */
382 		if (WARN_ON_ONCE(mc->init_value && (mc->kmem_cache || mc->gfp_zero)))
383 			return -EIO;
384 
385 		mc->objects = kvmalloc_array(capacity, sizeof(void *), gfp);
386 		if (!mc->objects)
387 			return -ENOMEM;
388 
389 		mc->capacity = capacity;
390 	}
391 
392 	/* It is illegal to request a different capacity across topups. */
393 	if (WARN_ON_ONCE(mc->capacity != capacity))
394 		return -EIO;
395 
396 	while (mc->nobjs < mc->capacity) {
397 		obj = mmu_memory_cache_alloc_obj(mc, gfp);
398 		if (!obj)
399 			return mc->nobjs >= min ? 0 : -ENOMEM;
400 		mc->objects[mc->nobjs++] = obj;
401 	}
402 	return 0;
403 }
404 
kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache * mc,int min)405 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
406 {
407 	return __kvm_mmu_topup_memory_cache(mc, KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE, min);
408 }
409 
kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache * mc)410 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
411 {
412 	return mc->nobjs;
413 }
414 
kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache * mc)415 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
416 {
417 	while (mc->nobjs) {
418 		if (mc->kmem_cache)
419 			kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
420 		else
421 			free_page((unsigned long)mc->objects[--mc->nobjs]);
422 	}
423 
424 	kvfree(mc->objects);
425 
426 	mc->objects = NULL;
427 	mc->capacity = 0;
428 }
429 
kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache * mc)430 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
431 {
432 	void *p;
433 
434 	if (WARN_ON(!mc->nobjs))
435 		p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
436 	else
437 		p = mc->objects[--mc->nobjs];
438 	BUG_ON(!p);
439 	return p;
440 }
441 #endif
442 
kvm_vcpu_init(struct kvm_vcpu * vcpu,struct kvm * kvm,unsigned id)443 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
444 {
445 	mutex_init(&vcpu->mutex);
446 	vcpu->cpu = -1;
447 	vcpu->kvm = kvm;
448 	vcpu->vcpu_id = id;
449 	vcpu->pid = NULL;
450 	rwlock_init(&vcpu->pid_lock);
451 #ifndef __KVM_HAVE_ARCH_WQP
452 	rcuwait_init(&vcpu->wait);
453 #endif
454 	kvm_async_pf_vcpu_init(vcpu);
455 
456 	kvm_vcpu_set_in_spin_loop(vcpu, false);
457 	kvm_vcpu_set_dy_eligible(vcpu, false);
458 	vcpu->preempted = false;
459 	vcpu->ready = false;
460 	preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
461 	vcpu->last_used_slot = NULL;
462 
463 	/* Fill the stats id string for the vcpu */
464 	snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
465 		 task_pid_nr(current), id);
466 }
467 
kvm_vcpu_destroy(struct kvm_vcpu * vcpu)468 static void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
469 {
470 	kvm_arch_vcpu_destroy(vcpu);
471 	kvm_dirty_ring_free(&vcpu->dirty_ring);
472 
473 	/*
474 	 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
475 	 * the vcpu->pid pointer, and at destruction time all file descriptors
476 	 * are already gone.
477 	 */
478 	put_pid(vcpu->pid);
479 
480 	free_page((unsigned long)vcpu->run);
481 	kmem_cache_free(kvm_vcpu_cache, vcpu);
482 }
483 
kvm_destroy_vcpus(struct kvm * kvm)484 void kvm_destroy_vcpus(struct kvm *kvm)
485 {
486 	unsigned long i;
487 	struct kvm_vcpu *vcpu;
488 
489 	kvm_for_each_vcpu(i, vcpu, kvm) {
490 		kvm_vcpu_destroy(vcpu);
491 		xa_erase(&kvm->vcpu_array, i);
492 	}
493 
494 	atomic_set(&kvm->online_vcpus, 0);
495 }
496 EXPORT_SYMBOL_GPL(kvm_destroy_vcpus);
497 
498 #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER
mmu_notifier_to_kvm(struct mmu_notifier * mn)499 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
500 {
501 	return container_of(mn, struct kvm, mmu_notifier);
502 }
503 
504 typedef bool (*gfn_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
505 
506 typedef void (*on_lock_fn_t)(struct kvm *kvm);
507 
508 struct kvm_mmu_notifier_range {
509 	/*
510 	 * 64-bit addresses, as KVM notifiers can operate on host virtual
511 	 * addresses (unsigned long) and guest physical addresses (64-bit).
512 	 */
513 	u64 start;
514 	u64 end;
515 	union kvm_mmu_notifier_arg arg;
516 	gfn_handler_t handler;
517 	on_lock_fn_t on_lock;
518 	bool flush_on_ret;
519 	bool may_block;
520 };
521 
522 /*
523  * The inner-most helper returns a tuple containing the return value from the
524  * arch- and action-specific handler, plus a flag indicating whether or not at
525  * least one memslot was found, i.e. if the handler found guest memory.
526  *
527  * Note, most notifiers are averse to booleans, so even though KVM tracks the
528  * return from arch code as a bool, outer helpers will cast it to an int. :-(
529  */
530 typedef struct kvm_mmu_notifier_return {
531 	bool ret;
532 	bool found_memslot;
533 } kvm_mn_ret_t;
534 
535 /*
536  * Use a dedicated stub instead of NULL to indicate that there is no callback
537  * function/handler.  The compiler technically can't guarantee that a real
538  * function will have a non-zero address, and so it will generate code to
539  * check for !NULL, whereas comparing against a stub will be elided at compile
540  * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
541  */
kvm_null_fn(void)542 static void kvm_null_fn(void)
543 {
544 
545 }
546 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
547 
548 /* Iterate over each memslot intersecting [start, last] (inclusive) range */
549 #define kvm_for_each_memslot_in_hva_range(node, slots, start, last)	     \
550 	for (node = interval_tree_iter_first(&slots->hva_tree, start, last); \
551 	     node;							     \
552 	     node = interval_tree_iter_next(node, start, last))	     \
553 
__kvm_handle_hva_range(struct kvm * kvm,const struct kvm_mmu_notifier_range * range)554 static __always_inline kvm_mn_ret_t __kvm_handle_hva_range(struct kvm *kvm,
555 							   const struct kvm_mmu_notifier_range *range)
556 {
557 	struct kvm_mmu_notifier_return r = {
558 		.ret = false,
559 		.found_memslot = false,
560 	};
561 	struct kvm_gfn_range gfn_range;
562 	struct kvm_memory_slot *slot;
563 	struct kvm_memslots *slots;
564 	int i, idx;
565 
566 	if (WARN_ON_ONCE(range->end <= range->start))
567 		return r;
568 
569 	/* A null handler is allowed if and only if on_lock() is provided. */
570 	if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
571 			 IS_KVM_NULL_FN(range->handler)))
572 		return r;
573 
574 	idx = srcu_read_lock(&kvm->srcu);
575 
576 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
577 		struct interval_tree_node *node;
578 
579 		slots = __kvm_memslots(kvm, i);
580 		kvm_for_each_memslot_in_hva_range(node, slots,
581 						  range->start, range->end - 1) {
582 			unsigned long hva_start, hva_end;
583 
584 			slot = container_of(node, struct kvm_memory_slot, hva_node[slots->node_idx]);
585 			hva_start = max_t(unsigned long, range->start, slot->userspace_addr);
586 			hva_end = min_t(unsigned long, range->end,
587 					slot->userspace_addr + (slot->npages << PAGE_SHIFT));
588 
589 			/*
590 			 * To optimize for the likely case where the address
591 			 * range is covered by zero or one memslots, don't
592 			 * bother making these conditional (to avoid writes on
593 			 * the second or later invocation of the handler).
594 			 */
595 			gfn_range.arg = range->arg;
596 			gfn_range.may_block = range->may_block;
597 			/*
598 			 * HVA-based notifications aren't relevant to private
599 			 * mappings as they don't have a userspace mapping.
600 			 */
601 			gfn_range.attr_filter = KVM_FILTER_SHARED;
602 
603 			/*
604 			 * {gfn(page) | page intersects with [hva_start, hva_end)} =
605 			 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
606 			 */
607 			gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
608 			gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
609 			gfn_range.slot = slot;
610 
611 			if (!r.found_memslot) {
612 				r.found_memslot = true;
613 				KVM_MMU_LOCK(kvm);
614 				if (!IS_KVM_NULL_FN(range->on_lock))
615 					range->on_lock(kvm);
616 
617 				if (IS_KVM_NULL_FN(range->handler))
618 					goto mmu_unlock;
619 			}
620 			r.ret |= range->handler(kvm, &gfn_range);
621 		}
622 	}
623 
624 	if (range->flush_on_ret && r.ret)
625 		kvm_flush_remote_tlbs(kvm);
626 
627 mmu_unlock:
628 	if (r.found_memslot)
629 		KVM_MMU_UNLOCK(kvm);
630 
631 	srcu_read_unlock(&kvm->srcu, idx);
632 
633 	return r;
634 }
635 
kvm_handle_hva_range(struct mmu_notifier * mn,unsigned long start,unsigned long end,gfn_handler_t handler,bool flush_on_ret)636 static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
637 						unsigned long start,
638 						unsigned long end,
639 						gfn_handler_t handler,
640 						bool flush_on_ret)
641 {
642 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
643 	const struct kvm_mmu_notifier_range range = {
644 		.start		= start,
645 		.end		= end,
646 		.handler	= handler,
647 		.on_lock	= (void *)kvm_null_fn,
648 		.flush_on_ret	= flush_on_ret,
649 		.may_block	= false,
650 	};
651 
652 	return __kvm_handle_hva_range(kvm, &range).ret;
653 }
654 
kvm_handle_hva_range_no_flush(struct mmu_notifier * mn,unsigned long start,unsigned long end,gfn_handler_t handler)655 static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
656 							 unsigned long start,
657 							 unsigned long end,
658 							 gfn_handler_t handler)
659 {
660 	return kvm_handle_hva_range(mn, start, end, handler, false);
661 }
662 
kvm_mmu_invalidate_begin(struct kvm * kvm)663 void kvm_mmu_invalidate_begin(struct kvm *kvm)
664 {
665 	lockdep_assert_held_write(&kvm->mmu_lock);
666 	/*
667 	 * The count increase must become visible at unlock time as no
668 	 * spte can be established without taking the mmu_lock and
669 	 * count is also read inside the mmu_lock critical section.
670 	 */
671 	kvm->mmu_invalidate_in_progress++;
672 
673 	if (likely(kvm->mmu_invalidate_in_progress == 1)) {
674 		kvm->mmu_invalidate_range_start = INVALID_GPA;
675 		kvm->mmu_invalidate_range_end = INVALID_GPA;
676 	}
677 }
678 
kvm_mmu_invalidate_range_add(struct kvm * kvm,gfn_t start,gfn_t end)679 void kvm_mmu_invalidate_range_add(struct kvm *kvm, gfn_t start, gfn_t end)
680 {
681 	lockdep_assert_held_write(&kvm->mmu_lock);
682 
683 	WARN_ON_ONCE(!kvm->mmu_invalidate_in_progress);
684 
685 	if (likely(kvm->mmu_invalidate_range_start == INVALID_GPA)) {
686 		kvm->mmu_invalidate_range_start = start;
687 		kvm->mmu_invalidate_range_end = end;
688 	} else {
689 		/*
690 		 * Fully tracking multiple concurrent ranges has diminishing
691 		 * returns. Keep things simple and just find the minimal range
692 		 * which includes the current and new ranges. As there won't be
693 		 * enough information to subtract a range after its invalidate
694 		 * completes, any ranges invalidated concurrently will
695 		 * accumulate and persist until all outstanding invalidates
696 		 * complete.
697 		 */
698 		kvm->mmu_invalidate_range_start =
699 			min(kvm->mmu_invalidate_range_start, start);
700 		kvm->mmu_invalidate_range_end =
701 			max(kvm->mmu_invalidate_range_end, end);
702 	}
703 }
704 
kvm_mmu_unmap_gfn_range(struct kvm * kvm,struct kvm_gfn_range * range)705 bool kvm_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
706 {
707 	kvm_mmu_invalidate_range_add(kvm, range->start, range->end);
708 	return kvm_unmap_gfn_range(kvm, range);
709 }
710 
kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier * mn,const struct mmu_notifier_range * range)711 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
712 					const struct mmu_notifier_range *range)
713 {
714 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
715 	const struct kvm_mmu_notifier_range hva_range = {
716 		.start		= range->start,
717 		.end		= range->end,
718 		.handler	= kvm_mmu_unmap_gfn_range,
719 		.on_lock	= kvm_mmu_invalidate_begin,
720 		.flush_on_ret	= true,
721 		.may_block	= mmu_notifier_range_blockable(range),
722 	};
723 
724 	trace_kvm_unmap_hva_range(range->start, range->end);
725 
726 	/*
727 	 * Prevent memslot modification between range_start() and range_end()
728 	 * so that conditionally locking provides the same result in both
729 	 * functions.  Without that guarantee, the mmu_invalidate_in_progress
730 	 * adjustments will be imbalanced.
731 	 *
732 	 * Pairs with the decrement in range_end().
733 	 */
734 	spin_lock(&kvm->mn_invalidate_lock);
735 	kvm->mn_active_invalidate_count++;
736 	spin_unlock(&kvm->mn_invalidate_lock);
737 
738 	/*
739 	 * Invalidate pfn caches _before_ invalidating the secondary MMUs, i.e.
740 	 * before acquiring mmu_lock, to avoid holding mmu_lock while acquiring
741 	 * each cache's lock.  There are relatively few caches in existence at
742 	 * any given time, and the caches themselves can check for hva overlap,
743 	 * i.e. don't need to rely on memslot overlap checks for performance.
744 	 * Because this runs without holding mmu_lock, the pfn caches must use
745 	 * mn_active_invalidate_count (see above) instead of
746 	 * mmu_invalidate_in_progress.
747 	 */
748 	gfn_to_pfn_cache_invalidate_start(kvm, range->start, range->end);
749 
750 	/*
751 	 * If one or more memslots were found and thus zapped, notify arch code
752 	 * that guest memory has been reclaimed.  This needs to be done *after*
753 	 * dropping mmu_lock, as x86's reclaim path is slooooow.
754 	 */
755 	if (__kvm_handle_hva_range(kvm, &hva_range).found_memslot)
756 		kvm_arch_guest_memory_reclaimed(kvm);
757 
758 	return 0;
759 }
760 
kvm_mmu_invalidate_end(struct kvm * kvm)761 void kvm_mmu_invalidate_end(struct kvm *kvm)
762 {
763 	lockdep_assert_held_write(&kvm->mmu_lock);
764 
765 	/*
766 	 * This sequence increase will notify the kvm page fault that
767 	 * the page that is going to be mapped in the spte could have
768 	 * been freed.
769 	 */
770 	kvm->mmu_invalidate_seq++;
771 	smp_wmb();
772 	/*
773 	 * The above sequence increase must be visible before the
774 	 * below count decrease, which is ensured by the smp_wmb above
775 	 * in conjunction with the smp_rmb in mmu_invalidate_retry().
776 	 */
777 	kvm->mmu_invalidate_in_progress--;
778 	KVM_BUG_ON(kvm->mmu_invalidate_in_progress < 0, kvm);
779 
780 	/*
781 	 * Assert that at least one range was added between start() and end().
782 	 * Not adding a range isn't fatal, but it is a KVM bug.
783 	 */
784 	WARN_ON_ONCE(kvm->mmu_invalidate_range_start == INVALID_GPA);
785 }
786 
kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier * mn,const struct mmu_notifier_range * range)787 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
788 					const struct mmu_notifier_range *range)
789 {
790 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
791 	const struct kvm_mmu_notifier_range hva_range = {
792 		.start		= range->start,
793 		.end		= range->end,
794 		.handler	= (void *)kvm_null_fn,
795 		.on_lock	= kvm_mmu_invalidate_end,
796 		.flush_on_ret	= false,
797 		.may_block	= mmu_notifier_range_blockable(range),
798 	};
799 	bool wake;
800 
801 	__kvm_handle_hva_range(kvm, &hva_range);
802 
803 	/* Pairs with the increment in range_start(). */
804 	spin_lock(&kvm->mn_invalidate_lock);
805 	if (!WARN_ON_ONCE(!kvm->mn_active_invalidate_count))
806 		--kvm->mn_active_invalidate_count;
807 	wake = !kvm->mn_active_invalidate_count;
808 	spin_unlock(&kvm->mn_invalidate_lock);
809 
810 	/*
811 	 * There can only be one waiter, since the wait happens under
812 	 * slots_lock.
813 	 */
814 	if (wake)
815 		rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
816 }
817 
kvm_mmu_notifier_clear_flush_young(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long start,unsigned long end)818 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
819 					      struct mm_struct *mm,
820 					      unsigned long start,
821 					      unsigned long end)
822 {
823 	trace_kvm_age_hva(start, end);
824 
825 	return kvm_handle_hva_range(mn, start, end, kvm_age_gfn,
826 				    !IS_ENABLED(CONFIG_KVM_ELIDE_TLB_FLUSH_IF_YOUNG));
827 }
828 
kvm_mmu_notifier_clear_young(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long start,unsigned long end)829 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
830 					struct mm_struct *mm,
831 					unsigned long start,
832 					unsigned long end)
833 {
834 	trace_kvm_age_hva(start, end);
835 
836 	/*
837 	 * Even though we do not flush TLB, this will still adversely
838 	 * affect performance on pre-Haswell Intel EPT, where there is
839 	 * no EPT Access Bit to clear so that we have to tear down EPT
840 	 * tables instead. If we find this unacceptable, we can always
841 	 * add a parameter to kvm_age_hva so that it effectively doesn't
842 	 * do anything on clear_young.
843 	 *
844 	 * Also note that currently we never issue secondary TLB flushes
845 	 * from clear_young, leaving this job up to the regular system
846 	 * cadence. If we find this inaccurate, we might come up with a
847 	 * more sophisticated heuristic later.
848 	 */
849 	return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
850 }
851 
kvm_mmu_notifier_test_young(struct mmu_notifier * mn,struct mm_struct * mm,unsigned long address)852 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
853 				       struct mm_struct *mm,
854 				       unsigned long address)
855 {
856 	trace_kvm_test_age_hva(address);
857 
858 	return kvm_handle_hva_range_no_flush(mn, address, address + 1,
859 					     kvm_test_age_gfn);
860 }
861 
kvm_mmu_notifier_release(struct mmu_notifier * mn,struct mm_struct * mm)862 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
863 				     struct mm_struct *mm)
864 {
865 	struct kvm *kvm = mmu_notifier_to_kvm(mn);
866 	int idx;
867 
868 	idx = srcu_read_lock(&kvm->srcu);
869 	kvm_flush_shadow_all(kvm);
870 	srcu_read_unlock(&kvm->srcu, idx);
871 }
872 
873 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
874 	.invalidate_range_start	= kvm_mmu_notifier_invalidate_range_start,
875 	.invalidate_range_end	= kvm_mmu_notifier_invalidate_range_end,
876 	.clear_flush_young	= kvm_mmu_notifier_clear_flush_young,
877 	.clear_young		= kvm_mmu_notifier_clear_young,
878 	.test_young		= kvm_mmu_notifier_test_young,
879 	.release		= kvm_mmu_notifier_release,
880 };
881 
kvm_init_mmu_notifier(struct kvm * kvm)882 static int kvm_init_mmu_notifier(struct kvm *kvm)
883 {
884 	kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
885 	return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
886 }
887 
888 #else  /* !CONFIG_KVM_GENERIC_MMU_NOTIFIER */
889 
kvm_init_mmu_notifier(struct kvm * kvm)890 static int kvm_init_mmu_notifier(struct kvm *kvm)
891 {
892 	return 0;
893 }
894 
895 #endif /* CONFIG_KVM_GENERIC_MMU_NOTIFIER */
896 
897 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_pm_notifier_call(struct notifier_block * bl,unsigned long state,void * unused)898 static int kvm_pm_notifier_call(struct notifier_block *bl,
899 				unsigned long state,
900 				void *unused)
901 {
902 	struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
903 
904 	return kvm_arch_pm_notifier(kvm, state);
905 }
906 
kvm_init_pm_notifier(struct kvm * kvm)907 static void kvm_init_pm_notifier(struct kvm *kvm)
908 {
909 	kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
910 	/* Suspend KVM before we suspend ftrace, RCU, etc. */
911 	kvm->pm_notifier.priority = INT_MAX;
912 	register_pm_notifier(&kvm->pm_notifier);
913 }
914 
kvm_destroy_pm_notifier(struct kvm * kvm)915 static void kvm_destroy_pm_notifier(struct kvm *kvm)
916 {
917 	unregister_pm_notifier(&kvm->pm_notifier);
918 }
919 #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
kvm_init_pm_notifier(struct kvm * kvm)920 static void kvm_init_pm_notifier(struct kvm *kvm)
921 {
922 }
923 
kvm_destroy_pm_notifier(struct kvm * kvm)924 static void kvm_destroy_pm_notifier(struct kvm *kvm)
925 {
926 }
927 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
928 
kvm_destroy_dirty_bitmap(struct kvm_memory_slot * memslot)929 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
930 {
931 	if (!memslot->dirty_bitmap)
932 		return;
933 
934 	vfree(memslot->dirty_bitmap);
935 	memslot->dirty_bitmap = NULL;
936 }
937 
938 /* This does not remove the slot from struct kvm_memslots data structures */
kvm_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)939 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
940 {
941 	if (slot->flags & KVM_MEM_GUEST_MEMFD)
942 		kvm_gmem_unbind(slot);
943 
944 	kvm_destroy_dirty_bitmap(slot);
945 
946 	kvm_arch_free_memslot(kvm, slot);
947 
948 	kfree(slot);
949 }
950 
kvm_free_memslots(struct kvm * kvm,struct kvm_memslots * slots)951 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
952 {
953 	struct hlist_node *idnode;
954 	struct kvm_memory_slot *memslot;
955 	int bkt;
956 
957 	/*
958 	 * The same memslot objects live in both active and inactive sets,
959 	 * arbitrarily free using index '1' so the second invocation of this
960 	 * function isn't operating over a structure with dangling pointers
961 	 * (even though this function isn't actually touching them).
962 	 */
963 	if (!slots->node_idx)
964 		return;
965 
966 	hash_for_each_safe(slots->id_hash, bkt, idnode, memslot, id_node[1])
967 		kvm_free_memslot(kvm, memslot);
968 }
969 
kvm_stats_debugfs_mode(const struct _kvm_stats_desc * pdesc)970 static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
971 {
972 	switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
973 	case KVM_STATS_TYPE_INSTANT:
974 		return 0444;
975 	case KVM_STATS_TYPE_CUMULATIVE:
976 	case KVM_STATS_TYPE_PEAK:
977 	default:
978 		return 0644;
979 	}
980 }
981 
982 
kvm_destroy_vm_debugfs(struct kvm * kvm)983 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
984 {
985 	int i;
986 	int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
987 				      kvm_vcpu_stats_header.num_desc;
988 
989 	if (IS_ERR(kvm->debugfs_dentry))
990 		return;
991 
992 	debugfs_remove_recursive(kvm->debugfs_dentry);
993 
994 	if (kvm->debugfs_stat_data) {
995 		for (i = 0; i < kvm_debugfs_num_entries; i++)
996 			kfree(kvm->debugfs_stat_data[i]);
997 		kfree(kvm->debugfs_stat_data);
998 	}
999 }
1000 
kvm_create_vm_debugfs(struct kvm * kvm,const char * fdname)1001 static int kvm_create_vm_debugfs(struct kvm *kvm, const char *fdname)
1002 {
1003 	static DEFINE_MUTEX(kvm_debugfs_lock);
1004 	struct dentry *dent;
1005 	char dir_name[ITOA_MAX_LEN * 2];
1006 	struct kvm_stat_data *stat_data;
1007 	const struct _kvm_stats_desc *pdesc;
1008 	int i, ret = -ENOMEM;
1009 	int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
1010 				      kvm_vcpu_stats_header.num_desc;
1011 
1012 	if (!debugfs_initialized())
1013 		return 0;
1014 
1015 	snprintf(dir_name, sizeof(dir_name), "%d-%s", task_pid_nr(current), fdname);
1016 	mutex_lock(&kvm_debugfs_lock);
1017 	dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
1018 	if (dent) {
1019 		pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
1020 		dput(dent);
1021 		mutex_unlock(&kvm_debugfs_lock);
1022 		return 0;
1023 	}
1024 	dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
1025 	mutex_unlock(&kvm_debugfs_lock);
1026 	if (IS_ERR(dent))
1027 		return 0;
1028 
1029 	kvm->debugfs_dentry = dent;
1030 	kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
1031 					 sizeof(*kvm->debugfs_stat_data),
1032 					 GFP_KERNEL_ACCOUNT);
1033 	if (!kvm->debugfs_stat_data)
1034 		goto out_err;
1035 
1036 	for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
1037 		pdesc = &kvm_vm_stats_desc[i];
1038 		stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
1039 		if (!stat_data)
1040 			goto out_err;
1041 
1042 		stat_data->kvm = kvm;
1043 		stat_data->desc = pdesc;
1044 		stat_data->kind = KVM_STAT_VM;
1045 		kvm->debugfs_stat_data[i] = stat_data;
1046 		debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1047 				    kvm->debugfs_dentry, stat_data,
1048 				    &stat_fops_per_vm);
1049 	}
1050 
1051 	for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
1052 		pdesc = &kvm_vcpu_stats_desc[i];
1053 		stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
1054 		if (!stat_data)
1055 			goto out_err;
1056 
1057 		stat_data->kvm = kvm;
1058 		stat_data->desc = pdesc;
1059 		stat_data->kind = KVM_STAT_VCPU;
1060 		kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
1061 		debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1062 				    kvm->debugfs_dentry, stat_data,
1063 				    &stat_fops_per_vm);
1064 	}
1065 
1066 	kvm_arch_create_vm_debugfs(kvm);
1067 	return 0;
1068 out_err:
1069 	kvm_destroy_vm_debugfs(kvm);
1070 	return ret;
1071 }
1072 
1073 /*
1074  * Called just after removing the VM from the vm_list, but before doing any
1075  * other destruction.
1076  */
kvm_arch_pre_destroy_vm(struct kvm * kvm)1077 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
1078 {
1079 }
1080 
1081 /*
1082  * Called after per-vm debugfs created.  When called kvm->debugfs_dentry should
1083  * be setup already, so we can create arch-specific debugfs entries under it.
1084  * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
1085  * a per-arch destroy interface is not needed.
1086  */
kvm_arch_create_vm_debugfs(struct kvm * kvm)1087 void __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
1088 {
1089 }
1090 
kvm_create_vm(unsigned long type,const char * fdname)1091 static struct kvm *kvm_create_vm(unsigned long type, const char *fdname)
1092 {
1093 	struct kvm *kvm = kvm_arch_alloc_vm();
1094 	struct kvm_memslots *slots;
1095 	int r, i, j;
1096 
1097 	if (!kvm)
1098 		return ERR_PTR(-ENOMEM);
1099 
1100 	KVM_MMU_LOCK_INIT(kvm);
1101 	mmgrab(current->mm);
1102 	kvm->mm = current->mm;
1103 	kvm_eventfd_init(kvm);
1104 	mutex_init(&kvm->lock);
1105 	mutex_init(&kvm->irq_lock);
1106 	mutex_init(&kvm->slots_lock);
1107 	mutex_init(&kvm->slots_arch_lock);
1108 	spin_lock_init(&kvm->mn_invalidate_lock);
1109 	rcuwait_init(&kvm->mn_memslots_update_rcuwait);
1110 	xa_init(&kvm->vcpu_array);
1111 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
1112 	xa_init(&kvm->mem_attr_array);
1113 #endif
1114 
1115 	INIT_LIST_HEAD(&kvm->gpc_list);
1116 	spin_lock_init(&kvm->gpc_lock);
1117 
1118 	INIT_LIST_HEAD(&kvm->devices);
1119 	kvm->max_vcpus = KVM_MAX_VCPUS;
1120 
1121 	BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
1122 
1123 	/*
1124 	 * Force subsequent debugfs file creations to fail if the VM directory
1125 	 * is not created (by kvm_create_vm_debugfs()).
1126 	 */
1127 	kvm->debugfs_dentry = ERR_PTR(-ENOENT);
1128 
1129 	snprintf(kvm->stats_id, sizeof(kvm->stats_id), "kvm-%d",
1130 		 task_pid_nr(current));
1131 
1132 	r = -ENOMEM;
1133 	if (init_srcu_struct(&kvm->srcu))
1134 		goto out_err_no_srcu;
1135 	if (init_srcu_struct(&kvm->irq_srcu))
1136 		goto out_err_no_irq_srcu;
1137 
1138 	r = kvm_init_irq_routing(kvm);
1139 	if (r)
1140 		goto out_err_no_irq_routing;
1141 
1142 	refcount_set(&kvm->users_count, 1);
1143 
1144 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
1145 		for (j = 0; j < 2; j++) {
1146 			slots = &kvm->__memslots[i][j];
1147 
1148 			atomic_long_set(&slots->last_used_slot, (unsigned long)NULL);
1149 			slots->hva_tree = RB_ROOT_CACHED;
1150 			slots->gfn_tree = RB_ROOT;
1151 			hash_init(slots->id_hash);
1152 			slots->node_idx = j;
1153 
1154 			/* Generations must be different for each address space. */
1155 			slots->generation = i;
1156 		}
1157 
1158 		rcu_assign_pointer(kvm->memslots[i], &kvm->__memslots[i][0]);
1159 	}
1160 
1161 	r = -ENOMEM;
1162 	for (i = 0; i < KVM_NR_BUSES; i++) {
1163 		rcu_assign_pointer(kvm->buses[i],
1164 			kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
1165 		if (!kvm->buses[i])
1166 			goto out_err_no_arch_destroy_vm;
1167 	}
1168 
1169 	r = kvm_arch_init_vm(kvm, type);
1170 	if (r)
1171 		goto out_err_no_arch_destroy_vm;
1172 
1173 	r = kvm_enable_virtualization();
1174 	if (r)
1175 		goto out_err_no_disable;
1176 
1177 #ifdef CONFIG_HAVE_KVM_IRQCHIP
1178 	INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
1179 #endif
1180 
1181 	r = kvm_init_mmu_notifier(kvm);
1182 	if (r)
1183 		goto out_err_no_mmu_notifier;
1184 
1185 	r = kvm_coalesced_mmio_init(kvm);
1186 	if (r < 0)
1187 		goto out_no_coalesced_mmio;
1188 
1189 	r = kvm_create_vm_debugfs(kvm, fdname);
1190 	if (r)
1191 		goto out_err_no_debugfs;
1192 
1193 	mutex_lock(&kvm_lock);
1194 	list_add(&kvm->vm_list, &vm_list);
1195 	mutex_unlock(&kvm_lock);
1196 
1197 	preempt_notifier_inc();
1198 	kvm_init_pm_notifier(kvm);
1199 
1200 	return kvm;
1201 
1202 out_err_no_debugfs:
1203 	kvm_coalesced_mmio_free(kvm);
1204 out_no_coalesced_mmio:
1205 #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER
1206 	if (kvm->mmu_notifier.ops)
1207 		mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1208 #endif
1209 out_err_no_mmu_notifier:
1210 	kvm_disable_virtualization();
1211 out_err_no_disable:
1212 	kvm_arch_destroy_vm(kvm);
1213 out_err_no_arch_destroy_vm:
1214 	WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
1215 	for (i = 0; i < KVM_NR_BUSES; i++)
1216 		kfree(kvm_get_bus(kvm, i));
1217 	kvm_free_irq_routing(kvm);
1218 out_err_no_irq_routing:
1219 	cleanup_srcu_struct(&kvm->irq_srcu);
1220 out_err_no_irq_srcu:
1221 	cleanup_srcu_struct(&kvm->srcu);
1222 out_err_no_srcu:
1223 	kvm_arch_free_vm(kvm);
1224 	mmdrop(current->mm);
1225 	return ERR_PTR(r);
1226 }
1227 
kvm_destroy_devices(struct kvm * kvm)1228 static void kvm_destroy_devices(struct kvm *kvm)
1229 {
1230 	struct kvm_device *dev, *tmp;
1231 
1232 	/*
1233 	 * We do not need to take the kvm->lock here, because nobody else
1234 	 * has a reference to the struct kvm at this point and therefore
1235 	 * cannot access the devices list anyhow.
1236 	 *
1237 	 * The device list is generally managed as an rculist, but list_del()
1238 	 * is used intentionally here. If a bug in KVM introduced a reader that
1239 	 * was not backed by a reference on the kvm struct, the hope is that
1240 	 * it'd consume the poisoned forward pointer instead of suffering a
1241 	 * use-after-free, even though this cannot be guaranteed.
1242 	 */
1243 	list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1244 		list_del(&dev->vm_node);
1245 		dev->ops->destroy(dev);
1246 	}
1247 }
1248 
kvm_destroy_vm(struct kvm * kvm)1249 static void kvm_destroy_vm(struct kvm *kvm)
1250 {
1251 	int i;
1252 	struct mm_struct *mm = kvm->mm;
1253 
1254 	kvm_destroy_pm_notifier(kvm);
1255 	kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
1256 	kvm_destroy_vm_debugfs(kvm);
1257 	kvm_arch_sync_events(kvm);
1258 	mutex_lock(&kvm_lock);
1259 	list_del(&kvm->vm_list);
1260 	mutex_unlock(&kvm_lock);
1261 	kvm_arch_pre_destroy_vm(kvm);
1262 
1263 	kvm_free_irq_routing(kvm);
1264 	for (i = 0; i < KVM_NR_BUSES; i++) {
1265 		struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
1266 
1267 		if (bus)
1268 			kvm_io_bus_destroy(bus);
1269 		kvm->buses[i] = NULL;
1270 	}
1271 	kvm_coalesced_mmio_free(kvm);
1272 #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER
1273 	mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
1274 	/*
1275 	 * At this point, pending calls to invalidate_range_start()
1276 	 * have completed but no more MMU notifiers will run, so
1277 	 * mn_active_invalidate_count may remain unbalanced.
1278 	 * No threads can be waiting in kvm_swap_active_memslots() as the
1279 	 * last reference on KVM has been dropped, but freeing
1280 	 * memslots would deadlock without this manual intervention.
1281 	 *
1282 	 * If the count isn't unbalanced, i.e. KVM did NOT unregister its MMU
1283 	 * notifier between a start() and end(), then there shouldn't be any
1284 	 * in-progress invalidations.
1285 	 */
1286 	WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
1287 	if (kvm->mn_active_invalidate_count)
1288 		kvm->mn_active_invalidate_count = 0;
1289 	else
1290 		WARN_ON(kvm->mmu_invalidate_in_progress);
1291 #else
1292 	kvm_flush_shadow_all(kvm);
1293 #endif
1294 	kvm_arch_destroy_vm(kvm);
1295 	kvm_destroy_devices(kvm);
1296 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
1297 		kvm_free_memslots(kvm, &kvm->__memslots[i][0]);
1298 		kvm_free_memslots(kvm, &kvm->__memslots[i][1]);
1299 	}
1300 	cleanup_srcu_struct(&kvm->irq_srcu);
1301 	cleanup_srcu_struct(&kvm->srcu);
1302 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
1303 	xa_destroy(&kvm->mem_attr_array);
1304 #endif
1305 	kvm_arch_free_vm(kvm);
1306 	preempt_notifier_dec();
1307 	kvm_disable_virtualization();
1308 	mmdrop(mm);
1309 }
1310 
kvm_get_kvm(struct kvm * kvm)1311 void kvm_get_kvm(struct kvm *kvm)
1312 {
1313 	refcount_inc(&kvm->users_count);
1314 }
1315 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1316 
1317 /*
1318  * Make sure the vm is not during destruction, which is a safe version of
1319  * kvm_get_kvm().  Return true if kvm referenced successfully, false otherwise.
1320  */
kvm_get_kvm_safe(struct kvm * kvm)1321 bool kvm_get_kvm_safe(struct kvm *kvm)
1322 {
1323 	return refcount_inc_not_zero(&kvm->users_count);
1324 }
1325 EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
1326 
kvm_put_kvm(struct kvm * kvm)1327 void kvm_put_kvm(struct kvm *kvm)
1328 {
1329 	if (refcount_dec_and_test(&kvm->users_count))
1330 		kvm_destroy_vm(kvm);
1331 }
1332 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1333 
1334 /*
1335  * Used to put a reference that was taken on behalf of an object associated
1336  * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1337  * of the new file descriptor fails and the reference cannot be transferred to
1338  * its final owner.  In such cases, the caller is still actively using @kvm and
1339  * will fail miserably if the refcount unexpectedly hits zero.
1340  */
kvm_put_kvm_no_destroy(struct kvm * kvm)1341 void kvm_put_kvm_no_destroy(struct kvm *kvm)
1342 {
1343 	WARN_ON(refcount_dec_and_test(&kvm->users_count));
1344 }
1345 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
1346 
kvm_vm_release(struct inode * inode,struct file * filp)1347 static int kvm_vm_release(struct inode *inode, struct file *filp)
1348 {
1349 	struct kvm *kvm = filp->private_data;
1350 
1351 	kvm_irqfd_release(kvm);
1352 
1353 	kvm_put_kvm(kvm);
1354 	return 0;
1355 }
1356 
1357 /*
1358  * Allocation size is twice as large as the actual dirty bitmap size.
1359  * See kvm_vm_ioctl_get_dirty_log() why this is needed.
1360  */
kvm_alloc_dirty_bitmap(struct kvm_memory_slot * memslot)1361 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
1362 {
1363 	unsigned long dirty_bytes = kvm_dirty_bitmap_bytes(memslot);
1364 
1365 	memslot->dirty_bitmap = __vcalloc(2, dirty_bytes, GFP_KERNEL_ACCOUNT);
1366 	if (!memslot->dirty_bitmap)
1367 		return -ENOMEM;
1368 
1369 	return 0;
1370 }
1371 
kvm_get_inactive_memslots(struct kvm * kvm,int as_id)1372 static struct kvm_memslots *kvm_get_inactive_memslots(struct kvm *kvm, int as_id)
1373 {
1374 	struct kvm_memslots *active = __kvm_memslots(kvm, as_id);
1375 	int node_idx_inactive = active->node_idx ^ 1;
1376 
1377 	return &kvm->__memslots[as_id][node_idx_inactive];
1378 }
1379 
1380 /*
1381  * Helper to get the address space ID when one of memslot pointers may be NULL.
1382  * This also serves as a sanity that at least one of the pointers is non-NULL,
1383  * and that their address space IDs don't diverge.
1384  */
kvm_memslots_get_as_id(struct kvm_memory_slot * a,struct kvm_memory_slot * b)1385 static int kvm_memslots_get_as_id(struct kvm_memory_slot *a,
1386 				  struct kvm_memory_slot *b)
1387 {
1388 	if (WARN_ON_ONCE(!a && !b))
1389 		return 0;
1390 
1391 	if (!a)
1392 		return b->as_id;
1393 	if (!b)
1394 		return a->as_id;
1395 
1396 	WARN_ON_ONCE(a->as_id != b->as_id);
1397 	return a->as_id;
1398 }
1399 
kvm_insert_gfn_node(struct kvm_memslots * slots,struct kvm_memory_slot * slot)1400 static void kvm_insert_gfn_node(struct kvm_memslots *slots,
1401 				struct kvm_memory_slot *slot)
1402 {
1403 	struct rb_root *gfn_tree = &slots->gfn_tree;
1404 	struct rb_node **node, *parent;
1405 	int idx = slots->node_idx;
1406 
1407 	parent = NULL;
1408 	for (node = &gfn_tree->rb_node; *node; ) {
1409 		struct kvm_memory_slot *tmp;
1410 
1411 		tmp = container_of(*node, struct kvm_memory_slot, gfn_node[idx]);
1412 		parent = *node;
1413 		if (slot->base_gfn < tmp->base_gfn)
1414 			node = &(*node)->rb_left;
1415 		else if (slot->base_gfn > tmp->base_gfn)
1416 			node = &(*node)->rb_right;
1417 		else
1418 			BUG();
1419 	}
1420 
1421 	rb_link_node(&slot->gfn_node[idx], parent, node);
1422 	rb_insert_color(&slot->gfn_node[idx], gfn_tree);
1423 }
1424 
kvm_erase_gfn_node(struct kvm_memslots * slots,struct kvm_memory_slot * slot)1425 static void kvm_erase_gfn_node(struct kvm_memslots *slots,
1426 			       struct kvm_memory_slot *slot)
1427 {
1428 	rb_erase(&slot->gfn_node[slots->node_idx], &slots->gfn_tree);
1429 }
1430 
kvm_replace_gfn_node(struct kvm_memslots * slots,struct kvm_memory_slot * old,struct kvm_memory_slot * new)1431 static void kvm_replace_gfn_node(struct kvm_memslots *slots,
1432 				 struct kvm_memory_slot *old,
1433 				 struct kvm_memory_slot *new)
1434 {
1435 	int idx = slots->node_idx;
1436 
1437 	WARN_ON_ONCE(old->base_gfn != new->base_gfn);
1438 
1439 	rb_replace_node(&old->gfn_node[idx], &new->gfn_node[idx],
1440 			&slots->gfn_tree);
1441 }
1442 
1443 /*
1444  * Replace @old with @new in the inactive memslots.
1445  *
1446  * With NULL @old this simply adds @new.
1447  * With NULL @new this simply removes @old.
1448  *
1449  * If @new is non-NULL its hva_node[slots_idx] range has to be set
1450  * appropriately.
1451  */
kvm_replace_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * new)1452 static void kvm_replace_memslot(struct kvm *kvm,
1453 				struct kvm_memory_slot *old,
1454 				struct kvm_memory_slot *new)
1455 {
1456 	int as_id = kvm_memslots_get_as_id(old, new);
1457 	struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1458 	int idx = slots->node_idx;
1459 
1460 	if (old) {
1461 		hash_del(&old->id_node[idx]);
1462 		interval_tree_remove(&old->hva_node[idx], &slots->hva_tree);
1463 
1464 		if ((long)old == atomic_long_read(&slots->last_used_slot))
1465 			atomic_long_set(&slots->last_used_slot, (long)new);
1466 
1467 		if (!new) {
1468 			kvm_erase_gfn_node(slots, old);
1469 			return;
1470 		}
1471 	}
1472 
1473 	/*
1474 	 * Initialize @new's hva range.  Do this even when replacing an @old
1475 	 * slot, kvm_copy_memslot() deliberately does not touch node data.
1476 	 */
1477 	new->hva_node[idx].start = new->userspace_addr;
1478 	new->hva_node[idx].last = new->userspace_addr +
1479 				  (new->npages << PAGE_SHIFT) - 1;
1480 
1481 	/*
1482 	 * (Re)Add the new memslot.  There is no O(1) interval_tree_replace(),
1483 	 * hva_node needs to be swapped with remove+insert even though hva can't
1484 	 * change when replacing an existing slot.
1485 	 */
1486 	hash_add(slots->id_hash, &new->id_node[idx], new->id);
1487 	interval_tree_insert(&new->hva_node[idx], &slots->hva_tree);
1488 
1489 	/*
1490 	 * If the memslot gfn is unchanged, rb_replace_node() can be used to
1491 	 * switch the node in the gfn tree instead of removing the old and
1492 	 * inserting the new as two separate operations. Replacement is a
1493 	 * single O(1) operation versus two O(log(n)) operations for
1494 	 * remove+insert.
1495 	 */
1496 	if (old && old->base_gfn == new->base_gfn) {
1497 		kvm_replace_gfn_node(slots, old, new);
1498 	} else {
1499 		if (old)
1500 			kvm_erase_gfn_node(slots, old);
1501 		kvm_insert_gfn_node(slots, new);
1502 	}
1503 }
1504 
1505 /*
1506  * Flags that do not access any of the extra space of struct
1507  * kvm_userspace_memory_region2.  KVM_SET_USER_MEMORY_REGION_V1_FLAGS
1508  * only allows these.
1509  */
1510 #define KVM_SET_USER_MEMORY_REGION_V1_FLAGS \
1511 	(KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)
1512 
check_memory_region_flags(struct kvm * kvm,const struct kvm_userspace_memory_region2 * mem)1513 static int check_memory_region_flags(struct kvm *kvm,
1514 				     const struct kvm_userspace_memory_region2 *mem)
1515 {
1516 	u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1517 
1518 	if (kvm_arch_has_private_mem(kvm))
1519 		valid_flags |= KVM_MEM_GUEST_MEMFD;
1520 
1521 	/* Dirty logging private memory is not currently supported. */
1522 	if (mem->flags & KVM_MEM_GUEST_MEMFD)
1523 		valid_flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
1524 
1525 	/*
1526 	 * GUEST_MEMFD is incompatible with read-only memslots, as writes to
1527 	 * read-only memslots have emulated MMIO, not page fault, semantics,
1528 	 * and KVM doesn't allow emulated MMIO for private memory.
1529 	 */
1530 	if (kvm_arch_has_readonly_mem(kvm) &&
1531 	    !(mem->flags & KVM_MEM_GUEST_MEMFD))
1532 		valid_flags |= KVM_MEM_READONLY;
1533 
1534 	if (mem->flags & ~valid_flags)
1535 		return -EINVAL;
1536 
1537 	return 0;
1538 }
1539 
kvm_swap_active_memslots(struct kvm * kvm,int as_id)1540 static void kvm_swap_active_memslots(struct kvm *kvm, int as_id)
1541 {
1542 	struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1543 
1544 	/* Grab the generation from the activate memslots. */
1545 	u64 gen = __kvm_memslots(kvm, as_id)->generation;
1546 
1547 	WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1548 	slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1549 
1550 	/*
1551 	 * Do not store the new memslots while there are invalidations in
1552 	 * progress, otherwise the locking in invalidate_range_start and
1553 	 * invalidate_range_end will be unbalanced.
1554 	 */
1555 	spin_lock(&kvm->mn_invalidate_lock);
1556 	prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
1557 	while (kvm->mn_active_invalidate_count) {
1558 		set_current_state(TASK_UNINTERRUPTIBLE);
1559 		spin_unlock(&kvm->mn_invalidate_lock);
1560 		schedule();
1561 		spin_lock(&kvm->mn_invalidate_lock);
1562 	}
1563 	finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
1564 	rcu_assign_pointer(kvm->memslots[as_id], slots);
1565 	spin_unlock(&kvm->mn_invalidate_lock);
1566 
1567 	/*
1568 	 * Acquired in kvm_set_memslot. Must be released before synchronize
1569 	 * SRCU below in order to avoid deadlock with another thread
1570 	 * acquiring the slots_arch_lock in an srcu critical section.
1571 	 */
1572 	mutex_unlock(&kvm->slots_arch_lock);
1573 
1574 	synchronize_srcu_expedited(&kvm->srcu);
1575 
1576 	/*
1577 	 * Increment the new memslot generation a second time, dropping the
1578 	 * update in-progress flag and incrementing the generation based on
1579 	 * the number of address spaces.  This provides a unique and easily
1580 	 * identifiable generation number while the memslots are in flux.
1581 	 */
1582 	gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1583 
1584 	/*
1585 	 * Generations must be unique even across address spaces.  We do not need
1586 	 * a global counter for that, instead the generation space is evenly split
1587 	 * across address spaces.  For example, with two address spaces, address
1588 	 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1589 	 * use generations 1, 3, 5, ...
1590 	 */
1591 	gen += kvm_arch_nr_memslot_as_ids(kvm);
1592 
1593 	kvm_arch_memslots_updated(kvm, gen);
1594 
1595 	slots->generation = gen;
1596 }
1597 
kvm_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)1598 static int kvm_prepare_memory_region(struct kvm *kvm,
1599 				     const struct kvm_memory_slot *old,
1600 				     struct kvm_memory_slot *new,
1601 				     enum kvm_mr_change change)
1602 {
1603 	int r;
1604 
1605 	/*
1606 	 * If dirty logging is disabled, nullify the bitmap; the old bitmap
1607 	 * will be freed on "commit".  If logging is enabled in both old and
1608 	 * new, reuse the existing bitmap.  If logging is enabled only in the
1609 	 * new and KVM isn't using a ring buffer, allocate and initialize a
1610 	 * new bitmap.
1611 	 */
1612 	if (change != KVM_MR_DELETE) {
1613 		if (!(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
1614 			new->dirty_bitmap = NULL;
1615 		else if (old && old->dirty_bitmap)
1616 			new->dirty_bitmap = old->dirty_bitmap;
1617 		else if (kvm_use_dirty_bitmap(kvm)) {
1618 			r = kvm_alloc_dirty_bitmap(new);
1619 			if (r)
1620 				return r;
1621 
1622 			if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1623 				bitmap_set(new->dirty_bitmap, 0, new->npages);
1624 		}
1625 	}
1626 
1627 	r = kvm_arch_prepare_memory_region(kvm, old, new, change);
1628 
1629 	/* Free the bitmap on failure if it was allocated above. */
1630 	if (r && new && new->dirty_bitmap && (!old || !old->dirty_bitmap))
1631 		kvm_destroy_dirty_bitmap(new);
1632 
1633 	return r;
1634 }
1635 
kvm_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)1636 static void kvm_commit_memory_region(struct kvm *kvm,
1637 				     struct kvm_memory_slot *old,
1638 				     const struct kvm_memory_slot *new,
1639 				     enum kvm_mr_change change)
1640 {
1641 	int old_flags = old ? old->flags : 0;
1642 	int new_flags = new ? new->flags : 0;
1643 	/*
1644 	 * Update the total number of memslot pages before calling the arch
1645 	 * hook so that architectures can consume the result directly.
1646 	 */
1647 	if (change == KVM_MR_DELETE)
1648 		kvm->nr_memslot_pages -= old->npages;
1649 	else if (change == KVM_MR_CREATE)
1650 		kvm->nr_memslot_pages += new->npages;
1651 
1652 	if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES) {
1653 		int change = (new_flags & KVM_MEM_LOG_DIRTY_PAGES) ? 1 : -1;
1654 		atomic_set(&kvm->nr_memslots_dirty_logging,
1655 			   atomic_read(&kvm->nr_memslots_dirty_logging) + change);
1656 	}
1657 
1658 	kvm_arch_commit_memory_region(kvm, old, new, change);
1659 
1660 	switch (change) {
1661 	case KVM_MR_CREATE:
1662 		/* Nothing more to do. */
1663 		break;
1664 	case KVM_MR_DELETE:
1665 		/* Free the old memslot and all its metadata. */
1666 		kvm_free_memslot(kvm, old);
1667 		break;
1668 	case KVM_MR_MOVE:
1669 	case KVM_MR_FLAGS_ONLY:
1670 		/*
1671 		 * Free the dirty bitmap as needed; the below check encompasses
1672 		 * both the flags and whether a ring buffer is being used)
1673 		 */
1674 		if (old->dirty_bitmap && !new->dirty_bitmap)
1675 			kvm_destroy_dirty_bitmap(old);
1676 
1677 		/*
1678 		 * The final quirk.  Free the detached, old slot, but only its
1679 		 * memory, not any metadata.  Metadata, including arch specific
1680 		 * data, may be reused by @new.
1681 		 */
1682 		kfree(old);
1683 		break;
1684 	default:
1685 		BUG();
1686 	}
1687 }
1688 
1689 /*
1690  * Activate @new, which must be installed in the inactive slots by the caller,
1691  * by swapping the active slots and then propagating @new to @old once @old is
1692  * unreachable and can be safely modified.
1693  *
1694  * With NULL @old this simply adds @new to @active (while swapping the sets).
1695  * With NULL @new this simply removes @old from @active and frees it
1696  * (while also swapping the sets).
1697  */
kvm_activate_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * new)1698 static void kvm_activate_memslot(struct kvm *kvm,
1699 				 struct kvm_memory_slot *old,
1700 				 struct kvm_memory_slot *new)
1701 {
1702 	int as_id = kvm_memslots_get_as_id(old, new);
1703 
1704 	kvm_swap_active_memslots(kvm, as_id);
1705 
1706 	/* Propagate the new memslot to the now inactive memslots. */
1707 	kvm_replace_memslot(kvm, old, new);
1708 }
1709 
kvm_copy_memslot(struct kvm_memory_slot * dest,const struct kvm_memory_slot * src)1710 static void kvm_copy_memslot(struct kvm_memory_slot *dest,
1711 			     const struct kvm_memory_slot *src)
1712 {
1713 	dest->base_gfn = src->base_gfn;
1714 	dest->npages = src->npages;
1715 	dest->dirty_bitmap = src->dirty_bitmap;
1716 	dest->arch = src->arch;
1717 	dest->userspace_addr = src->userspace_addr;
1718 	dest->flags = src->flags;
1719 	dest->id = src->id;
1720 	dest->as_id = src->as_id;
1721 }
1722 
kvm_invalidate_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * invalid_slot)1723 static void kvm_invalidate_memslot(struct kvm *kvm,
1724 				   struct kvm_memory_slot *old,
1725 				   struct kvm_memory_slot *invalid_slot)
1726 {
1727 	/*
1728 	 * Mark the current slot INVALID.  As with all memslot modifications,
1729 	 * this must be done on an unreachable slot to avoid modifying the
1730 	 * current slot in the active tree.
1731 	 */
1732 	kvm_copy_memslot(invalid_slot, old);
1733 	invalid_slot->flags |= KVM_MEMSLOT_INVALID;
1734 	kvm_replace_memslot(kvm, old, invalid_slot);
1735 
1736 	/*
1737 	 * Activate the slot that is now marked INVALID, but don't propagate
1738 	 * the slot to the now inactive slots. The slot is either going to be
1739 	 * deleted or recreated as a new slot.
1740 	 */
1741 	kvm_swap_active_memslots(kvm, old->as_id);
1742 
1743 	/*
1744 	 * From this point no new shadow pages pointing to a deleted, or moved,
1745 	 * memslot will be created.  Validation of sp->gfn happens in:
1746 	 *	- gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1747 	 *	- kvm_is_visible_gfn (mmu_check_root)
1748 	 */
1749 	kvm_arch_flush_shadow_memslot(kvm, old);
1750 	kvm_arch_guest_memory_reclaimed(kvm);
1751 
1752 	/* Was released by kvm_swap_active_memslots(), reacquire. */
1753 	mutex_lock(&kvm->slots_arch_lock);
1754 
1755 	/*
1756 	 * Copy the arch-specific field of the newly-installed slot back to the
1757 	 * old slot as the arch data could have changed between releasing
1758 	 * slots_arch_lock in kvm_swap_active_memslots() and re-acquiring the lock
1759 	 * above.  Writers are required to retrieve memslots *after* acquiring
1760 	 * slots_arch_lock, thus the active slot's data is guaranteed to be fresh.
1761 	 */
1762 	old->arch = invalid_slot->arch;
1763 }
1764 
kvm_create_memslot(struct kvm * kvm,struct kvm_memory_slot * new)1765 static void kvm_create_memslot(struct kvm *kvm,
1766 			       struct kvm_memory_slot *new)
1767 {
1768 	/* Add the new memslot to the inactive set and activate. */
1769 	kvm_replace_memslot(kvm, NULL, new);
1770 	kvm_activate_memslot(kvm, NULL, new);
1771 }
1772 
kvm_delete_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * invalid_slot)1773 static void kvm_delete_memslot(struct kvm *kvm,
1774 			       struct kvm_memory_slot *old,
1775 			       struct kvm_memory_slot *invalid_slot)
1776 {
1777 	/*
1778 	 * Remove the old memslot (in the inactive memslots) by passing NULL as
1779 	 * the "new" slot, and for the invalid version in the active slots.
1780 	 */
1781 	kvm_replace_memslot(kvm, old, NULL);
1782 	kvm_activate_memslot(kvm, invalid_slot, NULL);
1783 }
1784 
kvm_move_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * new,struct kvm_memory_slot * invalid_slot)1785 static void kvm_move_memslot(struct kvm *kvm,
1786 			     struct kvm_memory_slot *old,
1787 			     struct kvm_memory_slot *new,
1788 			     struct kvm_memory_slot *invalid_slot)
1789 {
1790 	/*
1791 	 * Replace the old memslot in the inactive slots, and then swap slots
1792 	 * and replace the current INVALID with the new as well.
1793 	 */
1794 	kvm_replace_memslot(kvm, old, new);
1795 	kvm_activate_memslot(kvm, invalid_slot, new);
1796 }
1797 
kvm_update_flags_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * new)1798 static void kvm_update_flags_memslot(struct kvm *kvm,
1799 				     struct kvm_memory_slot *old,
1800 				     struct kvm_memory_slot *new)
1801 {
1802 	/*
1803 	 * Similar to the MOVE case, but the slot doesn't need to be zapped as
1804 	 * an intermediate step. Instead, the old memslot is simply replaced
1805 	 * with a new, updated copy in both memslot sets.
1806 	 */
1807 	kvm_replace_memslot(kvm, old, new);
1808 	kvm_activate_memslot(kvm, old, new);
1809 }
1810 
kvm_set_memslot(struct kvm * kvm,struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)1811 static int kvm_set_memslot(struct kvm *kvm,
1812 			   struct kvm_memory_slot *old,
1813 			   struct kvm_memory_slot *new,
1814 			   enum kvm_mr_change change)
1815 {
1816 	struct kvm_memory_slot *invalid_slot;
1817 	int r;
1818 
1819 	/*
1820 	 * Released in kvm_swap_active_memslots().
1821 	 *
1822 	 * Must be held from before the current memslots are copied until after
1823 	 * the new memslots are installed with rcu_assign_pointer, then
1824 	 * released before the synchronize srcu in kvm_swap_active_memslots().
1825 	 *
1826 	 * When modifying memslots outside of the slots_lock, must be held
1827 	 * before reading the pointer to the current memslots until after all
1828 	 * changes to those memslots are complete.
1829 	 *
1830 	 * These rules ensure that installing new memslots does not lose
1831 	 * changes made to the previous memslots.
1832 	 */
1833 	mutex_lock(&kvm->slots_arch_lock);
1834 
1835 	/*
1836 	 * Invalidate the old slot if it's being deleted or moved.  This is
1837 	 * done prior to actually deleting/moving the memslot to allow vCPUs to
1838 	 * continue running by ensuring there are no mappings or shadow pages
1839 	 * for the memslot when it is deleted/moved.  Without pre-invalidation
1840 	 * (and without a lock), a window would exist between effecting the
1841 	 * delete/move and committing the changes in arch code where KVM or a
1842 	 * guest could access a non-existent memslot.
1843 	 *
1844 	 * Modifications are done on a temporary, unreachable slot.  The old
1845 	 * slot needs to be preserved in case a later step fails and the
1846 	 * invalidation needs to be reverted.
1847 	 */
1848 	if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1849 		invalid_slot = kzalloc(sizeof(*invalid_slot), GFP_KERNEL_ACCOUNT);
1850 		if (!invalid_slot) {
1851 			mutex_unlock(&kvm->slots_arch_lock);
1852 			return -ENOMEM;
1853 		}
1854 		kvm_invalidate_memslot(kvm, old, invalid_slot);
1855 	}
1856 
1857 	r = kvm_prepare_memory_region(kvm, old, new, change);
1858 	if (r) {
1859 		/*
1860 		 * For DELETE/MOVE, revert the above INVALID change.  No
1861 		 * modifications required since the original slot was preserved
1862 		 * in the inactive slots.  Changing the active memslots also
1863 		 * release slots_arch_lock.
1864 		 */
1865 		if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1866 			kvm_activate_memslot(kvm, invalid_slot, old);
1867 			kfree(invalid_slot);
1868 		} else {
1869 			mutex_unlock(&kvm->slots_arch_lock);
1870 		}
1871 		return r;
1872 	}
1873 
1874 	/*
1875 	 * For DELETE and MOVE, the working slot is now active as the INVALID
1876 	 * version of the old slot.  MOVE is particularly special as it reuses
1877 	 * the old slot and returns a copy of the old slot (in working_slot).
1878 	 * For CREATE, there is no old slot.  For DELETE and FLAGS_ONLY, the
1879 	 * old slot is detached but otherwise preserved.
1880 	 */
1881 	if (change == KVM_MR_CREATE)
1882 		kvm_create_memslot(kvm, new);
1883 	else if (change == KVM_MR_DELETE)
1884 		kvm_delete_memslot(kvm, old, invalid_slot);
1885 	else if (change == KVM_MR_MOVE)
1886 		kvm_move_memslot(kvm, old, new, invalid_slot);
1887 	else if (change == KVM_MR_FLAGS_ONLY)
1888 		kvm_update_flags_memslot(kvm, old, new);
1889 	else
1890 		BUG();
1891 
1892 	/* Free the temporary INVALID slot used for DELETE and MOVE. */
1893 	if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1894 		kfree(invalid_slot);
1895 
1896 	/*
1897 	 * No need to refresh new->arch, changes after dropping slots_arch_lock
1898 	 * will directly hit the final, active memslot.  Architectures are
1899 	 * responsible for knowing that new->arch may be stale.
1900 	 */
1901 	kvm_commit_memory_region(kvm, old, new, change);
1902 
1903 	return 0;
1904 }
1905 
kvm_check_memslot_overlap(struct kvm_memslots * slots,int id,gfn_t start,gfn_t end)1906 static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,
1907 				      gfn_t start, gfn_t end)
1908 {
1909 	struct kvm_memslot_iter iter;
1910 
1911 	kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {
1912 		if (iter.slot->id != id)
1913 			return true;
1914 	}
1915 
1916 	return false;
1917 }
1918 
kvm_set_memory_region(struct kvm * kvm,const struct kvm_userspace_memory_region2 * mem)1919 static int kvm_set_memory_region(struct kvm *kvm,
1920 				 const struct kvm_userspace_memory_region2 *mem)
1921 {
1922 	struct kvm_memory_slot *old, *new;
1923 	struct kvm_memslots *slots;
1924 	enum kvm_mr_change change;
1925 	unsigned long npages;
1926 	gfn_t base_gfn;
1927 	int as_id, id;
1928 	int r;
1929 
1930 	lockdep_assert_held(&kvm->slots_lock);
1931 
1932 	r = check_memory_region_flags(kvm, mem);
1933 	if (r)
1934 		return r;
1935 
1936 	as_id = mem->slot >> 16;
1937 	id = (u16)mem->slot;
1938 
1939 	/* General sanity checks */
1940 	if ((mem->memory_size & (PAGE_SIZE - 1)) ||
1941 	    (mem->memory_size != (unsigned long)mem->memory_size))
1942 		return -EINVAL;
1943 	if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1944 		return -EINVAL;
1945 	/* We can read the guest memory with __xxx_user() later on. */
1946 	if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1947 	    (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1948 	     !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1949 			mem->memory_size))
1950 		return -EINVAL;
1951 	if (mem->flags & KVM_MEM_GUEST_MEMFD &&
1952 	    (mem->guest_memfd_offset & (PAGE_SIZE - 1) ||
1953 	     mem->guest_memfd_offset + mem->memory_size < mem->guest_memfd_offset))
1954 		return -EINVAL;
1955 	if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_MEM_SLOTS_NUM)
1956 		return -EINVAL;
1957 	if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1958 		return -EINVAL;
1959 
1960 	/*
1961 	 * The size of userspace-defined memory regions is restricted in order
1962 	 * to play nice with dirty bitmap operations, which are indexed with an
1963 	 * "unsigned int".  KVM's internal memory regions don't support dirty
1964 	 * logging, and so are exempt.
1965 	 */
1966 	if (id < KVM_USER_MEM_SLOTS &&
1967 	    (mem->memory_size >> PAGE_SHIFT) > KVM_MEM_MAX_NR_PAGES)
1968 		return -EINVAL;
1969 
1970 	slots = __kvm_memslots(kvm, as_id);
1971 
1972 	/*
1973 	 * Note, the old memslot (and the pointer itself!) may be invalidated
1974 	 * and/or destroyed by kvm_set_memslot().
1975 	 */
1976 	old = id_to_memslot(slots, id);
1977 
1978 	if (!mem->memory_size) {
1979 		if (!old || !old->npages)
1980 			return -EINVAL;
1981 
1982 		if (WARN_ON_ONCE(kvm->nr_memslot_pages < old->npages))
1983 			return -EIO;
1984 
1985 		return kvm_set_memslot(kvm, old, NULL, KVM_MR_DELETE);
1986 	}
1987 
1988 	base_gfn = (mem->guest_phys_addr >> PAGE_SHIFT);
1989 	npages = (mem->memory_size >> PAGE_SHIFT);
1990 
1991 	if (!old || !old->npages) {
1992 		change = KVM_MR_CREATE;
1993 
1994 		/*
1995 		 * To simplify KVM internals, the total number of pages across
1996 		 * all memslots must fit in an unsigned long.
1997 		 */
1998 		if ((kvm->nr_memslot_pages + npages) < kvm->nr_memslot_pages)
1999 			return -EINVAL;
2000 	} else { /* Modify an existing slot. */
2001 		/* Private memslots are immutable, they can only be deleted. */
2002 		if (mem->flags & KVM_MEM_GUEST_MEMFD)
2003 			return -EINVAL;
2004 		if ((mem->userspace_addr != old->userspace_addr) ||
2005 		    (npages != old->npages) ||
2006 		    ((mem->flags ^ old->flags) & KVM_MEM_READONLY))
2007 			return -EINVAL;
2008 
2009 		if (base_gfn != old->base_gfn)
2010 			change = KVM_MR_MOVE;
2011 		else if (mem->flags != old->flags)
2012 			change = KVM_MR_FLAGS_ONLY;
2013 		else /* Nothing to change. */
2014 			return 0;
2015 	}
2016 
2017 	if ((change == KVM_MR_CREATE || change == KVM_MR_MOVE) &&
2018 	    kvm_check_memslot_overlap(slots, id, base_gfn, base_gfn + npages))
2019 		return -EEXIST;
2020 
2021 	/* Allocate a slot that will persist in the memslot. */
2022 	new = kzalloc(sizeof(*new), GFP_KERNEL_ACCOUNT);
2023 	if (!new)
2024 		return -ENOMEM;
2025 
2026 	new->as_id = as_id;
2027 	new->id = id;
2028 	new->base_gfn = base_gfn;
2029 	new->npages = npages;
2030 	new->flags = mem->flags;
2031 	new->userspace_addr = mem->userspace_addr;
2032 	if (mem->flags & KVM_MEM_GUEST_MEMFD) {
2033 		r = kvm_gmem_bind(kvm, new, mem->guest_memfd, mem->guest_memfd_offset);
2034 		if (r)
2035 			goto out;
2036 	}
2037 
2038 	r = kvm_set_memslot(kvm, old, new, change);
2039 	if (r)
2040 		goto out_unbind;
2041 
2042 	return 0;
2043 
2044 out_unbind:
2045 	if (mem->flags & KVM_MEM_GUEST_MEMFD)
2046 		kvm_gmem_unbind(new);
2047 out:
2048 	kfree(new);
2049 	return r;
2050 }
2051 
kvm_set_internal_memslot(struct kvm * kvm,const struct kvm_userspace_memory_region2 * mem)2052 int kvm_set_internal_memslot(struct kvm *kvm,
2053 			     const struct kvm_userspace_memory_region2 *mem)
2054 {
2055 	if (WARN_ON_ONCE(mem->slot < KVM_USER_MEM_SLOTS))
2056 		return -EINVAL;
2057 
2058 	if (WARN_ON_ONCE(mem->flags))
2059 		return -EINVAL;
2060 
2061 	return kvm_set_memory_region(kvm, mem);
2062 }
2063 EXPORT_SYMBOL_GPL(kvm_set_internal_memslot);
2064 
kvm_vm_ioctl_set_memory_region(struct kvm * kvm,struct kvm_userspace_memory_region2 * mem)2065 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
2066 					  struct kvm_userspace_memory_region2 *mem)
2067 {
2068 	if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
2069 		return -EINVAL;
2070 
2071 	guard(mutex)(&kvm->slots_lock);
2072 	return kvm_set_memory_region(kvm, mem);
2073 }
2074 
2075 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
2076 /**
2077  * kvm_get_dirty_log - get a snapshot of dirty pages
2078  * @kvm:	pointer to kvm instance
2079  * @log:	slot id and address to which we copy the log
2080  * @is_dirty:	set to '1' if any dirty pages were found
2081  * @memslot:	set to the associated memslot, always valid on success
2082  */
kvm_get_dirty_log(struct kvm * kvm,struct kvm_dirty_log * log,int * is_dirty,struct kvm_memory_slot ** memslot)2083 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
2084 		      int *is_dirty, struct kvm_memory_slot **memslot)
2085 {
2086 	struct kvm_memslots *slots;
2087 	int i, as_id, id;
2088 	unsigned long n;
2089 	unsigned long any = 0;
2090 
2091 	/* Dirty ring tracking may be exclusive to dirty log tracking */
2092 	if (!kvm_use_dirty_bitmap(kvm))
2093 		return -ENXIO;
2094 
2095 	*memslot = NULL;
2096 	*is_dirty = 0;
2097 
2098 	as_id = log->slot >> 16;
2099 	id = (u16)log->slot;
2100 	if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_USER_MEM_SLOTS)
2101 		return -EINVAL;
2102 
2103 	slots = __kvm_memslots(kvm, as_id);
2104 	*memslot = id_to_memslot(slots, id);
2105 	if (!(*memslot) || !(*memslot)->dirty_bitmap)
2106 		return -ENOENT;
2107 
2108 	kvm_arch_sync_dirty_log(kvm, *memslot);
2109 
2110 	n = kvm_dirty_bitmap_bytes(*memslot);
2111 
2112 	for (i = 0; !any && i < n/sizeof(long); ++i)
2113 		any = (*memslot)->dirty_bitmap[i];
2114 
2115 	if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
2116 		return -EFAULT;
2117 
2118 	if (any)
2119 		*is_dirty = 1;
2120 	return 0;
2121 }
2122 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
2123 
2124 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2125 /**
2126  * kvm_get_dirty_log_protect - get a snapshot of dirty pages
2127  *	and reenable dirty page tracking for the corresponding pages.
2128  * @kvm:	pointer to kvm instance
2129  * @log:	slot id and address to which we copy the log
2130  *
2131  * We need to keep it in mind that VCPU threads can write to the bitmap
2132  * concurrently. So, to avoid losing track of dirty pages we keep the
2133  * following order:
2134  *
2135  *    1. Take a snapshot of the bit and clear it if needed.
2136  *    2. Write protect the corresponding page.
2137  *    3. Copy the snapshot to the userspace.
2138  *    4. Upon return caller flushes TLB's if needed.
2139  *
2140  * Between 2 and 4, the guest may write to the page using the remaining TLB
2141  * entry.  This is not a problem because the page is reported dirty using
2142  * the snapshot taken before and step 4 ensures that writes done after
2143  * exiting to userspace will be logged for the next call.
2144  *
2145  */
kvm_get_dirty_log_protect(struct kvm * kvm,struct kvm_dirty_log * log)2146 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
2147 {
2148 	struct kvm_memslots *slots;
2149 	struct kvm_memory_slot *memslot;
2150 	int i, as_id, id;
2151 	unsigned long n;
2152 	unsigned long *dirty_bitmap;
2153 	unsigned long *dirty_bitmap_buffer;
2154 	bool flush;
2155 
2156 	/* Dirty ring tracking may be exclusive to dirty log tracking */
2157 	if (!kvm_use_dirty_bitmap(kvm))
2158 		return -ENXIO;
2159 
2160 	as_id = log->slot >> 16;
2161 	id = (u16)log->slot;
2162 	if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_USER_MEM_SLOTS)
2163 		return -EINVAL;
2164 
2165 	slots = __kvm_memslots(kvm, as_id);
2166 	memslot = id_to_memslot(slots, id);
2167 	if (!memslot || !memslot->dirty_bitmap)
2168 		return -ENOENT;
2169 
2170 	dirty_bitmap = memslot->dirty_bitmap;
2171 
2172 	kvm_arch_sync_dirty_log(kvm, memslot);
2173 
2174 	n = kvm_dirty_bitmap_bytes(memslot);
2175 	flush = false;
2176 	if (kvm->manual_dirty_log_protect) {
2177 		/*
2178 		 * Unlike kvm_get_dirty_log, we always return false in *flush,
2179 		 * because no flush is needed until KVM_CLEAR_DIRTY_LOG.  There
2180 		 * is some code duplication between this function and
2181 		 * kvm_get_dirty_log, but hopefully all architecture
2182 		 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
2183 		 * can be eliminated.
2184 		 */
2185 		dirty_bitmap_buffer = dirty_bitmap;
2186 	} else {
2187 		dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2188 		memset(dirty_bitmap_buffer, 0, n);
2189 
2190 		KVM_MMU_LOCK(kvm);
2191 		for (i = 0; i < n / sizeof(long); i++) {
2192 			unsigned long mask;
2193 			gfn_t offset;
2194 
2195 			if (!dirty_bitmap[i])
2196 				continue;
2197 
2198 			flush = true;
2199 			mask = xchg(&dirty_bitmap[i], 0);
2200 			dirty_bitmap_buffer[i] = mask;
2201 
2202 			offset = i * BITS_PER_LONG;
2203 			kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2204 								offset, mask);
2205 		}
2206 		KVM_MMU_UNLOCK(kvm);
2207 	}
2208 
2209 	if (flush)
2210 		kvm_flush_remote_tlbs_memslot(kvm, memslot);
2211 
2212 	if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
2213 		return -EFAULT;
2214 	return 0;
2215 }
2216 
2217 
2218 /**
2219  * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
2220  * @kvm: kvm instance
2221  * @log: slot id and address to which we copy the log
2222  *
2223  * Steps 1-4 below provide general overview of dirty page logging. See
2224  * kvm_get_dirty_log_protect() function description for additional details.
2225  *
2226  * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
2227  * always flush the TLB (step 4) even if previous step failed  and the dirty
2228  * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
2229  * does not preclude user space subsequent dirty log read. Flushing TLB ensures
2230  * writes will be marked dirty for next log read.
2231  *
2232  *   1. Take a snapshot of the bit and clear it if needed.
2233  *   2. Write protect the corresponding page.
2234  *   3. Copy the snapshot to the userspace.
2235  *   4. Flush TLB's if needed.
2236  */
kvm_vm_ioctl_get_dirty_log(struct kvm * kvm,struct kvm_dirty_log * log)2237 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2238 				      struct kvm_dirty_log *log)
2239 {
2240 	int r;
2241 
2242 	mutex_lock(&kvm->slots_lock);
2243 
2244 	r = kvm_get_dirty_log_protect(kvm, log);
2245 
2246 	mutex_unlock(&kvm->slots_lock);
2247 	return r;
2248 }
2249 
2250 /**
2251  * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
2252  *	and reenable dirty page tracking for the corresponding pages.
2253  * @kvm:	pointer to kvm instance
2254  * @log:	slot id and address from which to fetch the bitmap of dirty pages
2255  */
kvm_clear_dirty_log_protect(struct kvm * kvm,struct kvm_clear_dirty_log * log)2256 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
2257 				       struct kvm_clear_dirty_log *log)
2258 {
2259 	struct kvm_memslots *slots;
2260 	struct kvm_memory_slot *memslot;
2261 	int as_id, id;
2262 	gfn_t offset;
2263 	unsigned long i, n;
2264 	unsigned long *dirty_bitmap;
2265 	unsigned long *dirty_bitmap_buffer;
2266 	bool flush;
2267 
2268 	/* Dirty ring tracking may be exclusive to dirty log tracking */
2269 	if (!kvm_use_dirty_bitmap(kvm))
2270 		return -ENXIO;
2271 
2272 	as_id = log->slot >> 16;
2273 	id = (u16)log->slot;
2274 	if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_USER_MEM_SLOTS)
2275 		return -EINVAL;
2276 
2277 	if (log->first_page & 63)
2278 		return -EINVAL;
2279 
2280 	slots = __kvm_memslots(kvm, as_id);
2281 	memslot = id_to_memslot(slots, id);
2282 	if (!memslot || !memslot->dirty_bitmap)
2283 		return -ENOENT;
2284 
2285 	dirty_bitmap = memslot->dirty_bitmap;
2286 
2287 	n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
2288 
2289 	if (log->first_page > memslot->npages ||
2290 	    log->num_pages > memslot->npages - log->first_page ||
2291 	    (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
2292 	    return -EINVAL;
2293 
2294 	kvm_arch_sync_dirty_log(kvm, memslot);
2295 
2296 	flush = false;
2297 	dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2298 	if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2299 		return -EFAULT;
2300 
2301 	KVM_MMU_LOCK(kvm);
2302 	for (offset = log->first_page, i = offset / BITS_PER_LONG,
2303 		 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2304 	     i++, offset += BITS_PER_LONG) {
2305 		unsigned long mask = *dirty_bitmap_buffer++;
2306 		atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2307 		if (!mask)
2308 			continue;
2309 
2310 		mask &= atomic_long_fetch_andnot(mask, p);
2311 
2312 		/*
2313 		 * mask contains the bits that really have been cleared.  This
2314 		 * never includes any bits beyond the length of the memslot (if
2315 		 * the length is not aligned to 64 pages), therefore it is not
2316 		 * a problem if userspace sets them in log->dirty_bitmap.
2317 		*/
2318 		if (mask) {
2319 			flush = true;
2320 			kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2321 								offset, mask);
2322 		}
2323 	}
2324 	KVM_MMU_UNLOCK(kvm);
2325 
2326 	if (flush)
2327 		kvm_flush_remote_tlbs_memslot(kvm, memslot);
2328 
2329 	return 0;
2330 }
2331 
kvm_vm_ioctl_clear_dirty_log(struct kvm * kvm,struct kvm_clear_dirty_log * log)2332 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2333 					struct kvm_clear_dirty_log *log)
2334 {
2335 	int r;
2336 
2337 	mutex_lock(&kvm->slots_lock);
2338 
2339 	r = kvm_clear_dirty_log_protect(kvm, log);
2340 
2341 	mutex_unlock(&kvm->slots_lock);
2342 	return r;
2343 }
2344 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2345 
2346 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
kvm_supported_mem_attributes(struct kvm * kvm)2347 static u64 kvm_supported_mem_attributes(struct kvm *kvm)
2348 {
2349 	if (!kvm || kvm_arch_has_private_mem(kvm))
2350 		return KVM_MEMORY_ATTRIBUTE_PRIVATE;
2351 
2352 	return 0;
2353 }
2354 
2355 /*
2356  * Returns true if _all_ gfns in the range [@start, @end) have attributes
2357  * such that the bits in @mask match @attrs.
2358  */
kvm_range_has_memory_attributes(struct kvm * kvm,gfn_t start,gfn_t end,unsigned long mask,unsigned long attrs)2359 bool kvm_range_has_memory_attributes(struct kvm *kvm, gfn_t start, gfn_t end,
2360 				     unsigned long mask, unsigned long attrs)
2361 {
2362 	XA_STATE(xas, &kvm->mem_attr_array, start);
2363 	unsigned long index;
2364 	void *entry;
2365 
2366 	mask &= kvm_supported_mem_attributes(kvm);
2367 	if (attrs & ~mask)
2368 		return false;
2369 
2370 	if (end == start + 1)
2371 		return (kvm_get_memory_attributes(kvm, start) & mask) == attrs;
2372 
2373 	guard(rcu)();
2374 	if (!attrs)
2375 		return !xas_find(&xas, end - 1);
2376 
2377 	for (index = start; index < end; index++) {
2378 		do {
2379 			entry = xas_next(&xas);
2380 		} while (xas_retry(&xas, entry));
2381 
2382 		if (xas.xa_index != index ||
2383 		    (xa_to_value(entry) & mask) != attrs)
2384 			return false;
2385 	}
2386 
2387 	return true;
2388 }
2389 
kvm_handle_gfn_range(struct kvm * kvm,struct kvm_mmu_notifier_range * range)2390 static __always_inline void kvm_handle_gfn_range(struct kvm *kvm,
2391 						 struct kvm_mmu_notifier_range *range)
2392 {
2393 	struct kvm_gfn_range gfn_range;
2394 	struct kvm_memory_slot *slot;
2395 	struct kvm_memslots *slots;
2396 	struct kvm_memslot_iter iter;
2397 	bool found_memslot = false;
2398 	bool ret = false;
2399 	int i;
2400 
2401 	gfn_range.arg = range->arg;
2402 	gfn_range.may_block = range->may_block;
2403 
2404 	/*
2405 	 * If/when KVM supports more attributes beyond private .vs shared, this
2406 	 * _could_ set KVM_FILTER_{SHARED,PRIVATE} appropriately if the entire target
2407 	 * range already has the desired private vs. shared state (it's unclear
2408 	 * if that is a net win).  For now, KVM reaches this point if and only
2409 	 * if the private flag is being toggled, i.e. all mappings are in play.
2410 	 */
2411 
2412 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
2413 		slots = __kvm_memslots(kvm, i);
2414 
2415 		kvm_for_each_memslot_in_gfn_range(&iter, slots, range->start, range->end) {
2416 			slot = iter.slot;
2417 			gfn_range.slot = slot;
2418 
2419 			gfn_range.start = max(range->start, slot->base_gfn);
2420 			gfn_range.end = min(range->end, slot->base_gfn + slot->npages);
2421 			if (gfn_range.start >= gfn_range.end)
2422 				continue;
2423 
2424 			if (!found_memslot) {
2425 				found_memslot = true;
2426 				KVM_MMU_LOCK(kvm);
2427 				if (!IS_KVM_NULL_FN(range->on_lock))
2428 					range->on_lock(kvm);
2429 			}
2430 
2431 			ret |= range->handler(kvm, &gfn_range);
2432 		}
2433 	}
2434 
2435 	if (range->flush_on_ret && ret)
2436 		kvm_flush_remote_tlbs(kvm);
2437 
2438 	if (found_memslot)
2439 		KVM_MMU_UNLOCK(kvm);
2440 }
2441 
kvm_pre_set_memory_attributes(struct kvm * kvm,struct kvm_gfn_range * range)2442 static bool kvm_pre_set_memory_attributes(struct kvm *kvm,
2443 					  struct kvm_gfn_range *range)
2444 {
2445 	/*
2446 	 * Unconditionally add the range to the invalidation set, regardless of
2447 	 * whether or not the arch callback actually needs to zap SPTEs.  E.g.
2448 	 * if KVM supports RWX attributes in the future and the attributes are
2449 	 * going from R=>RW, zapping isn't strictly necessary.  Unconditionally
2450 	 * adding the range allows KVM to require that MMU invalidations add at
2451 	 * least one range between begin() and end(), e.g. allows KVM to detect
2452 	 * bugs where the add() is missed.  Relaxing the rule *might* be safe,
2453 	 * but it's not obvious that allowing new mappings while the attributes
2454 	 * are in flux is desirable or worth the complexity.
2455 	 */
2456 	kvm_mmu_invalidate_range_add(kvm, range->start, range->end);
2457 
2458 	return kvm_arch_pre_set_memory_attributes(kvm, range);
2459 }
2460 
2461 /* Set @attributes for the gfn range [@start, @end). */
kvm_vm_set_mem_attributes(struct kvm * kvm,gfn_t start,gfn_t end,unsigned long attributes)2462 static int kvm_vm_set_mem_attributes(struct kvm *kvm, gfn_t start, gfn_t end,
2463 				     unsigned long attributes)
2464 {
2465 	struct kvm_mmu_notifier_range pre_set_range = {
2466 		.start = start,
2467 		.end = end,
2468 		.arg.attributes = attributes,
2469 		.handler = kvm_pre_set_memory_attributes,
2470 		.on_lock = kvm_mmu_invalidate_begin,
2471 		.flush_on_ret = true,
2472 		.may_block = true,
2473 	};
2474 	struct kvm_mmu_notifier_range post_set_range = {
2475 		.start = start,
2476 		.end = end,
2477 		.arg.attributes = attributes,
2478 		.handler = kvm_arch_post_set_memory_attributes,
2479 		.on_lock = kvm_mmu_invalidate_end,
2480 		.may_block = true,
2481 	};
2482 	unsigned long i;
2483 	void *entry;
2484 	int r = 0;
2485 
2486 	entry = attributes ? xa_mk_value(attributes) : NULL;
2487 
2488 	mutex_lock(&kvm->slots_lock);
2489 
2490 	/* Nothing to do if the entire range as the desired attributes. */
2491 	if (kvm_range_has_memory_attributes(kvm, start, end, ~0, attributes))
2492 		goto out_unlock;
2493 
2494 	/*
2495 	 * Reserve memory ahead of time to avoid having to deal with failures
2496 	 * partway through setting the new attributes.
2497 	 */
2498 	for (i = start; i < end; i++) {
2499 		r = xa_reserve(&kvm->mem_attr_array, i, GFP_KERNEL_ACCOUNT);
2500 		if (r)
2501 			goto out_unlock;
2502 	}
2503 
2504 	kvm_handle_gfn_range(kvm, &pre_set_range);
2505 
2506 	for (i = start; i < end; i++) {
2507 		r = xa_err(xa_store(&kvm->mem_attr_array, i, entry,
2508 				    GFP_KERNEL_ACCOUNT));
2509 		KVM_BUG_ON(r, kvm);
2510 	}
2511 
2512 	kvm_handle_gfn_range(kvm, &post_set_range);
2513 
2514 out_unlock:
2515 	mutex_unlock(&kvm->slots_lock);
2516 
2517 	return r;
2518 }
kvm_vm_ioctl_set_mem_attributes(struct kvm * kvm,struct kvm_memory_attributes * attrs)2519 static int kvm_vm_ioctl_set_mem_attributes(struct kvm *kvm,
2520 					   struct kvm_memory_attributes *attrs)
2521 {
2522 	gfn_t start, end;
2523 
2524 	/* flags is currently not used. */
2525 	if (attrs->flags)
2526 		return -EINVAL;
2527 	if (attrs->attributes & ~kvm_supported_mem_attributes(kvm))
2528 		return -EINVAL;
2529 	if (attrs->size == 0 || attrs->address + attrs->size < attrs->address)
2530 		return -EINVAL;
2531 	if (!PAGE_ALIGNED(attrs->address) || !PAGE_ALIGNED(attrs->size))
2532 		return -EINVAL;
2533 
2534 	start = attrs->address >> PAGE_SHIFT;
2535 	end = (attrs->address + attrs->size) >> PAGE_SHIFT;
2536 
2537 	/*
2538 	 * xarray tracks data using "unsigned long", and as a result so does
2539 	 * KVM.  For simplicity, supports generic attributes only on 64-bit
2540 	 * architectures.
2541 	 */
2542 	BUILD_BUG_ON(sizeof(attrs->attributes) != sizeof(unsigned long));
2543 
2544 	return kvm_vm_set_mem_attributes(kvm, start, end, attrs->attributes);
2545 }
2546 #endif /* CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES */
2547 
gfn_to_memslot(struct kvm * kvm,gfn_t gfn)2548 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2549 {
2550 	return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2551 }
2552 EXPORT_SYMBOL_GPL(gfn_to_memslot);
2553 
kvm_vcpu_gfn_to_memslot(struct kvm_vcpu * vcpu,gfn_t gfn)2554 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2555 {
2556 	struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
2557 	u64 gen = slots->generation;
2558 	struct kvm_memory_slot *slot;
2559 
2560 	/*
2561 	 * This also protects against using a memslot from a different address space,
2562 	 * since different address spaces have different generation numbers.
2563 	 */
2564 	if (unlikely(gen != vcpu->last_used_slot_gen)) {
2565 		vcpu->last_used_slot = NULL;
2566 		vcpu->last_used_slot_gen = gen;
2567 	}
2568 
2569 	slot = try_get_memslot(vcpu->last_used_slot, gfn);
2570 	if (slot)
2571 		return slot;
2572 
2573 	/*
2574 	 * Fall back to searching all memslots. We purposely use
2575 	 * search_memslots() instead of __gfn_to_memslot() to avoid
2576 	 * thrashing the VM-wide last_used_slot in kvm_memslots.
2577 	 */
2578 	slot = search_memslots(slots, gfn, false);
2579 	if (slot) {
2580 		vcpu->last_used_slot = slot;
2581 		return slot;
2582 	}
2583 
2584 	return NULL;
2585 }
2586 
kvm_is_visible_gfn(struct kvm * kvm,gfn_t gfn)2587 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
2588 {
2589 	struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
2590 
2591 	return kvm_is_visible_memslot(memslot);
2592 }
2593 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2594 
kvm_vcpu_is_visible_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)2595 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2596 {
2597 	struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2598 
2599 	return kvm_is_visible_memslot(memslot);
2600 }
2601 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2602 
kvm_host_page_size(struct kvm_vcpu * vcpu,gfn_t gfn)2603 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
2604 {
2605 	struct vm_area_struct *vma;
2606 	unsigned long addr, size;
2607 
2608 	size = PAGE_SIZE;
2609 
2610 	addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
2611 	if (kvm_is_error_hva(addr))
2612 		return PAGE_SIZE;
2613 
2614 	mmap_read_lock(current->mm);
2615 	vma = find_vma(current->mm, addr);
2616 	if (!vma)
2617 		goto out;
2618 
2619 	size = vma_kernel_pagesize(vma);
2620 
2621 out:
2622 	mmap_read_unlock(current->mm);
2623 
2624 	return size;
2625 }
2626 
memslot_is_readonly(const struct kvm_memory_slot * slot)2627 static bool memslot_is_readonly(const struct kvm_memory_slot *slot)
2628 {
2629 	return slot->flags & KVM_MEM_READONLY;
2630 }
2631 
__gfn_to_hva_many(const struct kvm_memory_slot * slot,gfn_t gfn,gfn_t * nr_pages,bool write)2632 static unsigned long __gfn_to_hva_many(const struct kvm_memory_slot *slot, gfn_t gfn,
2633 				       gfn_t *nr_pages, bool write)
2634 {
2635 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
2636 		return KVM_HVA_ERR_BAD;
2637 
2638 	if (memslot_is_readonly(slot) && write)
2639 		return KVM_HVA_ERR_RO_BAD;
2640 
2641 	if (nr_pages)
2642 		*nr_pages = slot->npages - (gfn - slot->base_gfn);
2643 
2644 	return __gfn_to_hva_memslot(slot, gfn);
2645 }
2646 
gfn_to_hva_many(struct kvm_memory_slot * slot,gfn_t gfn,gfn_t * nr_pages)2647 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2648 				     gfn_t *nr_pages)
2649 {
2650 	return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2651 }
2652 
gfn_to_hva_memslot(struct kvm_memory_slot * slot,gfn_t gfn)2653 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
2654 					gfn_t gfn)
2655 {
2656 	return gfn_to_hva_many(slot, gfn, NULL);
2657 }
2658 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2659 
gfn_to_hva(struct kvm * kvm,gfn_t gfn)2660 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2661 {
2662 	return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
2663 }
2664 EXPORT_SYMBOL_GPL(gfn_to_hva);
2665 
kvm_vcpu_gfn_to_hva(struct kvm_vcpu * vcpu,gfn_t gfn)2666 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2667 {
2668 	return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2669 }
2670 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2671 
2672 /*
2673  * Return the hva of a @gfn and the R/W attribute if possible.
2674  *
2675  * @slot: the kvm_memory_slot which contains @gfn
2676  * @gfn: the gfn to be translated
2677  * @writable: used to return the read/write attribute of the @slot if the hva
2678  * is valid and @writable is not NULL
2679  */
gfn_to_hva_memslot_prot(struct kvm_memory_slot * slot,gfn_t gfn,bool * writable)2680 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2681 				      gfn_t gfn, bool *writable)
2682 {
2683 	unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2684 
2685 	if (!kvm_is_error_hva(hva) && writable)
2686 		*writable = !memslot_is_readonly(slot);
2687 
2688 	return hva;
2689 }
2690 
gfn_to_hva_prot(struct kvm * kvm,gfn_t gfn,bool * writable)2691 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2692 {
2693 	struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2694 
2695 	return gfn_to_hva_memslot_prot(slot, gfn, writable);
2696 }
2697 
kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu * vcpu,gfn_t gfn,bool * writable)2698 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2699 {
2700 	struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2701 
2702 	return gfn_to_hva_memslot_prot(slot, gfn, writable);
2703 }
2704 
kvm_is_ad_tracked_page(struct page * page)2705 static bool kvm_is_ad_tracked_page(struct page *page)
2706 {
2707 	/*
2708 	 * Per page-flags.h, pages tagged PG_reserved "should in general not be
2709 	 * touched (e.g. set dirty) except by its owner".
2710 	 */
2711 	return !PageReserved(page);
2712 }
2713 
kvm_set_page_dirty(struct page * page)2714 static void kvm_set_page_dirty(struct page *page)
2715 {
2716 	if (kvm_is_ad_tracked_page(page))
2717 		SetPageDirty(page);
2718 }
2719 
kvm_set_page_accessed(struct page * page)2720 static void kvm_set_page_accessed(struct page *page)
2721 {
2722 	if (kvm_is_ad_tracked_page(page))
2723 		mark_page_accessed(page);
2724 }
2725 
kvm_release_page_clean(struct page * page)2726 void kvm_release_page_clean(struct page *page)
2727 {
2728 	if (!page)
2729 		return;
2730 
2731 	kvm_set_page_accessed(page);
2732 	put_page(page);
2733 }
2734 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2735 
kvm_release_page_dirty(struct page * page)2736 void kvm_release_page_dirty(struct page *page)
2737 {
2738 	if (!page)
2739 		return;
2740 
2741 	kvm_set_page_dirty(page);
2742 	kvm_release_page_clean(page);
2743 }
2744 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2745 
kvm_resolve_pfn(struct kvm_follow_pfn * kfp,struct page * page,struct follow_pfnmap_args * map,bool writable)2746 static kvm_pfn_t kvm_resolve_pfn(struct kvm_follow_pfn *kfp, struct page *page,
2747 				 struct follow_pfnmap_args *map, bool writable)
2748 {
2749 	kvm_pfn_t pfn;
2750 
2751 	WARN_ON_ONCE(!!page == !!map);
2752 
2753 	if (kfp->map_writable)
2754 		*kfp->map_writable = writable;
2755 
2756 	if (map)
2757 		pfn = map->pfn;
2758 	else
2759 		pfn = page_to_pfn(page);
2760 
2761 	*kfp->refcounted_page = page;
2762 
2763 	return pfn;
2764 }
2765 
2766 /*
2767  * The fast path to get the writable pfn which will be stored in @pfn,
2768  * true indicates success, otherwise false is returned.
2769  */
hva_to_pfn_fast(struct kvm_follow_pfn * kfp,kvm_pfn_t * pfn)2770 static bool hva_to_pfn_fast(struct kvm_follow_pfn *kfp, kvm_pfn_t *pfn)
2771 {
2772 	struct page *page;
2773 	bool r;
2774 
2775 	/*
2776 	 * Try the fast-only path when the caller wants to pin/get the page for
2777 	 * writing.  If the caller only wants to read the page, KVM must go
2778 	 * down the full, slow path in order to avoid racing an operation that
2779 	 * breaks Copy-on-Write (CoW), e.g. so that KVM doesn't end up pointing
2780 	 * at the old, read-only page while mm/ points at a new, writable page.
2781 	 */
2782 	if (!((kfp->flags & FOLL_WRITE) || kfp->map_writable))
2783 		return false;
2784 
2785 	if (kfp->pin)
2786 		r = pin_user_pages_fast(kfp->hva, 1, FOLL_WRITE, &page) == 1;
2787 	else
2788 		r = get_user_page_fast_only(kfp->hva, FOLL_WRITE, &page);
2789 
2790 	if (r) {
2791 		*pfn = kvm_resolve_pfn(kfp, page, NULL, true);
2792 		return true;
2793 	}
2794 
2795 	return false;
2796 }
2797 
2798 /*
2799  * The slow path to get the pfn of the specified host virtual address,
2800  * 1 indicates success, -errno is returned if error is detected.
2801  */
hva_to_pfn_slow(struct kvm_follow_pfn * kfp,kvm_pfn_t * pfn)2802 static int hva_to_pfn_slow(struct kvm_follow_pfn *kfp, kvm_pfn_t *pfn)
2803 {
2804 	/*
2805 	 * When a VCPU accesses a page that is not mapped into the secondary
2806 	 * MMU, we lookup the page using GUP to map it, so the guest VCPU can
2807 	 * make progress. We always want to honor NUMA hinting faults in that
2808 	 * case, because GUP usage corresponds to memory accesses from the VCPU.
2809 	 * Otherwise, we'd not trigger NUMA hinting faults once a page is
2810 	 * mapped into the secondary MMU and gets accessed by a VCPU.
2811 	 *
2812 	 * Note that get_user_page_fast_only() and FOLL_WRITE for now
2813 	 * implicitly honor NUMA hinting faults and don't need this flag.
2814 	 */
2815 	unsigned int flags = FOLL_HWPOISON | FOLL_HONOR_NUMA_FAULT | kfp->flags;
2816 	struct page *page, *wpage;
2817 	int npages;
2818 
2819 	if (kfp->pin)
2820 		npages = pin_user_pages_unlocked(kfp->hva, 1, &page, flags);
2821 	else
2822 		npages = get_user_pages_unlocked(kfp->hva, 1, &page, flags);
2823 	if (npages != 1)
2824 		return npages;
2825 
2826 	/*
2827 	 * Pinning is mutually exclusive with opportunistically mapping a read
2828 	 * fault as writable, as KVM should never pin pages when mapping memory
2829 	 * into the guest (pinning is only for direct accesses from KVM).
2830 	 */
2831 	if (WARN_ON_ONCE(kfp->map_writable && kfp->pin))
2832 		goto out;
2833 
2834 	/* map read fault as writable if possible */
2835 	if (!(flags & FOLL_WRITE) && kfp->map_writable &&
2836 	    get_user_page_fast_only(kfp->hva, FOLL_WRITE, &wpage)) {
2837 		put_page(page);
2838 		page = wpage;
2839 		flags |= FOLL_WRITE;
2840 	}
2841 
2842 out:
2843 	*pfn = kvm_resolve_pfn(kfp, page, NULL, flags & FOLL_WRITE);
2844 	return npages;
2845 }
2846 
vma_is_valid(struct vm_area_struct * vma,bool write_fault)2847 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2848 {
2849 	if (unlikely(!(vma->vm_flags & VM_READ)))
2850 		return false;
2851 
2852 	if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2853 		return false;
2854 
2855 	return true;
2856 }
2857 
hva_to_pfn_remapped(struct vm_area_struct * vma,struct kvm_follow_pfn * kfp,kvm_pfn_t * p_pfn)2858 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2859 			       struct kvm_follow_pfn *kfp, kvm_pfn_t *p_pfn)
2860 {
2861 	struct follow_pfnmap_args args = { .vma = vma, .address = kfp->hva };
2862 	bool write_fault = kfp->flags & FOLL_WRITE;
2863 	int r;
2864 
2865 	/*
2866 	 * Remapped memory cannot be pinned in any meaningful sense.  Bail if
2867 	 * the caller wants to pin the page, i.e. access the page outside of
2868 	 * MMU notifier protection, and unsafe umappings are disallowed.
2869 	 */
2870 	if (kfp->pin && !allow_unsafe_mappings)
2871 		return -EINVAL;
2872 
2873 	r = follow_pfnmap_start(&args);
2874 	if (r) {
2875 		/*
2876 		 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2877 		 * not call the fault handler, so do it here.
2878 		 */
2879 		bool unlocked = false;
2880 		r = fixup_user_fault(current->mm, kfp->hva,
2881 				     (write_fault ? FAULT_FLAG_WRITE : 0),
2882 				     &unlocked);
2883 		if (unlocked)
2884 			return -EAGAIN;
2885 		if (r)
2886 			return r;
2887 
2888 		r = follow_pfnmap_start(&args);
2889 		if (r)
2890 			return r;
2891 	}
2892 
2893 	if (write_fault && !args.writable) {
2894 		*p_pfn = KVM_PFN_ERR_RO_FAULT;
2895 		goto out;
2896 	}
2897 
2898 	*p_pfn = kvm_resolve_pfn(kfp, NULL, &args, args.writable);
2899 out:
2900 	follow_pfnmap_end(&args);
2901 	return r;
2902 }
2903 
hva_to_pfn(struct kvm_follow_pfn * kfp)2904 kvm_pfn_t hva_to_pfn(struct kvm_follow_pfn *kfp)
2905 {
2906 	struct vm_area_struct *vma;
2907 	kvm_pfn_t pfn;
2908 	int npages, r;
2909 
2910 	might_sleep();
2911 
2912 	if (WARN_ON_ONCE(!kfp->refcounted_page))
2913 		return KVM_PFN_ERR_FAULT;
2914 
2915 	if (hva_to_pfn_fast(kfp, &pfn))
2916 		return pfn;
2917 
2918 	npages = hva_to_pfn_slow(kfp, &pfn);
2919 	if (npages == 1)
2920 		return pfn;
2921 	if (npages == -EINTR || npages == -EAGAIN)
2922 		return KVM_PFN_ERR_SIGPENDING;
2923 	if (npages == -EHWPOISON)
2924 		return KVM_PFN_ERR_HWPOISON;
2925 
2926 	mmap_read_lock(current->mm);
2927 retry:
2928 	vma = vma_lookup(current->mm, kfp->hva);
2929 
2930 	if (vma == NULL)
2931 		pfn = KVM_PFN_ERR_FAULT;
2932 	else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2933 		r = hva_to_pfn_remapped(vma, kfp, &pfn);
2934 		if (r == -EAGAIN)
2935 			goto retry;
2936 		if (r < 0)
2937 			pfn = KVM_PFN_ERR_FAULT;
2938 	} else {
2939 		if ((kfp->flags & FOLL_NOWAIT) &&
2940 		    vma_is_valid(vma, kfp->flags & FOLL_WRITE))
2941 			pfn = KVM_PFN_ERR_NEEDS_IO;
2942 		else
2943 			pfn = KVM_PFN_ERR_FAULT;
2944 	}
2945 	mmap_read_unlock(current->mm);
2946 	return pfn;
2947 }
2948 
kvm_follow_pfn(struct kvm_follow_pfn * kfp)2949 static kvm_pfn_t kvm_follow_pfn(struct kvm_follow_pfn *kfp)
2950 {
2951 	kfp->hva = __gfn_to_hva_many(kfp->slot, kfp->gfn, NULL,
2952 				     kfp->flags & FOLL_WRITE);
2953 
2954 	if (kfp->hva == KVM_HVA_ERR_RO_BAD)
2955 		return KVM_PFN_ERR_RO_FAULT;
2956 
2957 	if (kvm_is_error_hva(kfp->hva))
2958 		return KVM_PFN_NOSLOT;
2959 
2960 	if (memslot_is_readonly(kfp->slot) && kfp->map_writable) {
2961 		*kfp->map_writable = false;
2962 		kfp->map_writable = NULL;
2963 	}
2964 
2965 	return hva_to_pfn(kfp);
2966 }
2967 
__kvm_faultin_pfn(const struct kvm_memory_slot * slot,gfn_t gfn,unsigned int foll,bool * writable,struct page ** refcounted_page)2968 kvm_pfn_t __kvm_faultin_pfn(const struct kvm_memory_slot *slot, gfn_t gfn,
2969 			    unsigned int foll, bool *writable,
2970 			    struct page **refcounted_page)
2971 {
2972 	struct kvm_follow_pfn kfp = {
2973 		.slot = slot,
2974 		.gfn = gfn,
2975 		.flags = foll,
2976 		.map_writable = writable,
2977 		.refcounted_page = refcounted_page,
2978 	};
2979 
2980 	if (WARN_ON_ONCE(!writable || !refcounted_page))
2981 		return KVM_PFN_ERR_FAULT;
2982 
2983 	*writable = false;
2984 	*refcounted_page = NULL;
2985 
2986 	return kvm_follow_pfn(&kfp);
2987 }
2988 EXPORT_SYMBOL_GPL(__kvm_faultin_pfn);
2989 
kvm_prefetch_pages(struct kvm_memory_slot * slot,gfn_t gfn,struct page ** pages,int nr_pages)2990 int kvm_prefetch_pages(struct kvm_memory_slot *slot, gfn_t gfn,
2991 		       struct page **pages, int nr_pages)
2992 {
2993 	unsigned long addr;
2994 	gfn_t entry = 0;
2995 
2996 	addr = gfn_to_hva_many(slot, gfn, &entry);
2997 	if (kvm_is_error_hva(addr))
2998 		return -1;
2999 
3000 	if (entry < nr_pages)
3001 		return 0;
3002 
3003 	return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
3004 }
3005 EXPORT_SYMBOL_GPL(kvm_prefetch_pages);
3006 
3007 /*
3008  * Don't use this API unless you are absolutely, positively certain that KVM
3009  * needs to get a struct page, e.g. to pin the page for firmware DMA.
3010  *
3011  * FIXME: Users of this API likely need to FOLL_PIN the page, not just elevate
3012  *	  its refcount.
3013  */
__gfn_to_page(struct kvm * kvm,gfn_t gfn,bool write)3014 struct page *__gfn_to_page(struct kvm *kvm, gfn_t gfn, bool write)
3015 {
3016 	struct page *refcounted_page = NULL;
3017 	struct kvm_follow_pfn kfp = {
3018 		.slot = gfn_to_memslot(kvm, gfn),
3019 		.gfn = gfn,
3020 		.flags = write ? FOLL_WRITE : 0,
3021 		.refcounted_page = &refcounted_page,
3022 	};
3023 
3024 	(void)kvm_follow_pfn(&kfp);
3025 	return refcounted_page;
3026 }
3027 EXPORT_SYMBOL_GPL(__gfn_to_page);
3028 
__kvm_vcpu_map(struct kvm_vcpu * vcpu,gfn_t gfn,struct kvm_host_map * map,bool writable)3029 int __kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
3030 		   bool writable)
3031 {
3032 	struct kvm_follow_pfn kfp = {
3033 		.slot = gfn_to_memslot(vcpu->kvm, gfn),
3034 		.gfn = gfn,
3035 		.flags = writable ? FOLL_WRITE : 0,
3036 		.refcounted_page = &map->pinned_page,
3037 		.pin = true,
3038 	};
3039 
3040 	map->pinned_page = NULL;
3041 	map->page = NULL;
3042 	map->hva = NULL;
3043 	map->gfn = gfn;
3044 	map->writable = writable;
3045 
3046 	map->pfn = kvm_follow_pfn(&kfp);
3047 	if (is_error_noslot_pfn(map->pfn))
3048 		return -EINVAL;
3049 
3050 	if (pfn_valid(map->pfn)) {
3051 		map->page = pfn_to_page(map->pfn);
3052 		map->hva = kmap(map->page);
3053 #ifdef CONFIG_HAS_IOMEM
3054 	} else {
3055 		map->hva = memremap(pfn_to_hpa(map->pfn), PAGE_SIZE, MEMREMAP_WB);
3056 #endif
3057 	}
3058 
3059 	return map->hva ? 0 : -EFAULT;
3060 }
3061 EXPORT_SYMBOL_GPL(__kvm_vcpu_map);
3062 
kvm_vcpu_unmap(struct kvm_vcpu * vcpu,struct kvm_host_map * map)3063 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map)
3064 {
3065 	if (!map->hva)
3066 		return;
3067 
3068 	if (map->page)
3069 		kunmap(map->page);
3070 #ifdef CONFIG_HAS_IOMEM
3071 	else
3072 		memunmap(map->hva);
3073 #endif
3074 
3075 	if (map->writable)
3076 		kvm_vcpu_mark_page_dirty(vcpu, map->gfn);
3077 
3078 	if (map->pinned_page) {
3079 		if (map->writable)
3080 			kvm_set_page_dirty(map->pinned_page);
3081 		kvm_set_page_accessed(map->pinned_page);
3082 		unpin_user_page(map->pinned_page);
3083 	}
3084 
3085 	map->hva = NULL;
3086 	map->page = NULL;
3087 	map->pinned_page = NULL;
3088 }
3089 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
3090 
next_segment(unsigned long len,int offset)3091 static int next_segment(unsigned long len, int offset)
3092 {
3093 	if (len > PAGE_SIZE - offset)
3094 		return PAGE_SIZE - offset;
3095 	else
3096 		return len;
3097 }
3098 
3099 /* Copy @len bytes from guest memory at '(@gfn * PAGE_SIZE) + @offset' to @data */
__kvm_read_guest_page(struct kvm_memory_slot * slot,gfn_t gfn,void * data,int offset,int len)3100 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
3101 				 void *data, int offset, int len)
3102 {
3103 	int r;
3104 	unsigned long addr;
3105 
3106 	if (WARN_ON_ONCE(offset + len > PAGE_SIZE))
3107 		return -EFAULT;
3108 
3109 	addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
3110 	if (kvm_is_error_hva(addr))
3111 		return -EFAULT;
3112 	r = __copy_from_user(data, (void __user *)addr + offset, len);
3113 	if (r)
3114 		return -EFAULT;
3115 	return 0;
3116 }
3117 
kvm_read_guest_page(struct kvm * kvm,gfn_t gfn,void * data,int offset,int len)3118 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
3119 			int len)
3120 {
3121 	struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
3122 
3123 	return __kvm_read_guest_page(slot, gfn, data, offset, len);
3124 }
3125 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
3126 
kvm_vcpu_read_guest_page(struct kvm_vcpu * vcpu,gfn_t gfn,void * data,int offset,int len)3127 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
3128 			     int offset, int len)
3129 {
3130 	struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3131 
3132 	return __kvm_read_guest_page(slot, gfn, data, offset, len);
3133 }
3134 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
3135 
kvm_read_guest(struct kvm * kvm,gpa_t gpa,void * data,unsigned long len)3136 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
3137 {
3138 	gfn_t gfn = gpa >> PAGE_SHIFT;
3139 	int seg;
3140 	int offset = offset_in_page(gpa);
3141 	int ret;
3142 
3143 	while ((seg = next_segment(len, offset)) != 0) {
3144 		ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
3145 		if (ret < 0)
3146 			return ret;
3147 		offset = 0;
3148 		len -= seg;
3149 		data += seg;
3150 		++gfn;
3151 	}
3152 	return 0;
3153 }
3154 EXPORT_SYMBOL_GPL(kvm_read_guest);
3155 
kvm_vcpu_read_guest(struct kvm_vcpu * vcpu,gpa_t gpa,void * data,unsigned long len)3156 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
3157 {
3158 	gfn_t gfn = gpa >> PAGE_SHIFT;
3159 	int seg;
3160 	int offset = offset_in_page(gpa);
3161 	int ret;
3162 
3163 	while ((seg = next_segment(len, offset)) != 0) {
3164 		ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
3165 		if (ret < 0)
3166 			return ret;
3167 		offset = 0;
3168 		len -= seg;
3169 		data += seg;
3170 		++gfn;
3171 	}
3172 	return 0;
3173 }
3174 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
3175 
__kvm_read_guest_atomic(struct kvm_memory_slot * slot,gfn_t gfn,void * data,int offset,unsigned long len)3176 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
3177 			           void *data, int offset, unsigned long len)
3178 {
3179 	int r;
3180 	unsigned long addr;
3181 
3182 	if (WARN_ON_ONCE(offset + len > PAGE_SIZE))
3183 		return -EFAULT;
3184 
3185 	addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
3186 	if (kvm_is_error_hva(addr))
3187 		return -EFAULT;
3188 	pagefault_disable();
3189 	r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
3190 	pagefault_enable();
3191 	if (r)
3192 		return -EFAULT;
3193 	return 0;
3194 }
3195 
kvm_vcpu_read_guest_atomic(struct kvm_vcpu * vcpu,gpa_t gpa,void * data,unsigned long len)3196 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
3197 			       void *data, unsigned long len)
3198 {
3199 	gfn_t gfn = gpa >> PAGE_SHIFT;
3200 	struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3201 	int offset = offset_in_page(gpa);
3202 
3203 	return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
3204 }
3205 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
3206 
3207 /* Copy @len bytes from @data into guest memory at '(@gfn * PAGE_SIZE) + @offset' */
__kvm_write_guest_page(struct kvm * kvm,struct kvm_memory_slot * memslot,gfn_t gfn,const void * data,int offset,int len)3208 static int __kvm_write_guest_page(struct kvm *kvm,
3209 				  struct kvm_memory_slot *memslot, gfn_t gfn,
3210 			          const void *data, int offset, int len)
3211 {
3212 	int r;
3213 	unsigned long addr;
3214 
3215 	if (WARN_ON_ONCE(offset + len > PAGE_SIZE))
3216 		return -EFAULT;
3217 
3218 	addr = gfn_to_hva_memslot(memslot, gfn);
3219 	if (kvm_is_error_hva(addr))
3220 		return -EFAULT;
3221 	r = __copy_to_user((void __user *)addr + offset, data, len);
3222 	if (r)
3223 		return -EFAULT;
3224 	mark_page_dirty_in_slot(kvm, memslot, gfn);
3225 	return 0;
3226 }
3227 
kvm_write_guest_page(struct kvm * kvm,gfn_t gfn,const void * data,int offset,int len)3228 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
3229 			 const void *data, int offset, int len)
3230 {
3231 	struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
3232 
3233 	return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
3234 }
3235 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
3236 
kvm_vcpu_write_guest_page(struct kvm_vcpu * vcpu,gfn_t gfn,const void * data,int offset,int len)3237 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
3238 			      const void *data, int offset, int len)
3239 {
3240 	struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3241 
3242 	return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
3243 }
3244 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
3245 
kvm_write_guest(struct kvm * kvm,gpa_t gpa,const void * data,unsigned long len)3246 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
3247 		    unsigned long len)
3248 {
3249 	gfn_t gfn = gpa >> PAGE_SHIFT;
3250 	int seg;
3251 	int offset = offset_in_page(gpa);
3252 	int ret;
3253 
3254 	while ((seg = next_segment(len, offset)) != 0) {
3255 		ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
3256 		if (ret < 0)
3257 			return ret;
3258 		offset = 0;
3259 		len -= seg;
3260 		data += seg;
3261 		++gfn;
3262 	}
3263 	return 0;
3264 }
3265 EXPORT_SYMBOL_GPL(kvm_write_guest);
3266 
kvm_vcpu_write_guest(struct kvm_vcpu * vcpu,gpa_t gpa,const void * data,unsigned long len)3267 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
3268 		         unsigned long len)
3269 {
3270 	gfn_t gfn = gpa >> PAGE_SHIFT;
3271 	int seg;
3272 	int offset = offset_in_page(gpa);
3273 	int ret;
3274 
3275 	while ((seg = next_segment(len, offset)) != 0) {
3276 		ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
3277 		if (ret < 0)
3278 			return ret;
3279 		offset = 0;
3280 		len -= seg;
3281 		data += seg;
3282 		++gfn;
3283 	}
3284 	return 0;
3285 }
3286 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
3287 
__kvm_gfn_to_hva_cache_init(struct kvm_memslots * slots,struct gfn_to_hva_cache * ghc,gpa_t gpa,unsigned long len)3288 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
3289 				       struct gfn_to_hva_cache *ghc,
3290 				       gpa_t gpa, unsigned long len)
3291 {
3292 	int offset = offset_in_page(gpa);
3293 	gfn_t start_gfn = gpa >> PAGE_SHIFT;
3294 	gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
3295 	gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
3296 	gfn_t nr_pages_avail;
3297 
3298 	/* Update ghc->generation before performing any error checks. */
3299 	ghc->generation = slots->generation;
3300 
3301 	if (start_gfn > end_gfn) {
3302 		ghc->hva = KVM_HVA_ERR_BAD;
3303 		return -EINVAL;
3304 	}
3305 
3306 	/*
3307 	 * If the requested region crosses two memslots, we still
3308 	 * verify that the entire region is valid here.
3309 	 */
3310 	for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
3311 		ghc->memslot = __gfn_to_memslot(slots, start_gfn);
3312 		ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
3313 					   &nr_pages_avail);
3314 		if (kvm_is_error_hva(ghc->hva))
3315 			return -EFAULT;
3316 	}
3317 
3318 	/* Use the slow path for cross page reads and writes. */
3319 	if (nr_pages_needed == 1)
3320 		ghc->hva += offset;
3321 	else
3322 		ghc->memslot = NULL;
3323 
3324 	ghc->gpa = gpa;
3325 	ghc->len = len;
3326 	return 0;
3327 }
3328 
kvm_gfn_to_hva_cache_init(struct kvm * kvm,struct gfn_to_hva_cache * ghc,gpa_t gpa,unsigned long len)3329 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3330 			      gpa_t gpa, unsigned long len)
3331 {
3332 	struct kvm_memslots *slots = kvm_memslots(kvm);
3333 	return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
3334 }
3335 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
3336 
kvm_write_guest_offset_cached(struct kvm * kvm,struct gfn_to_hva_cache * ghc,void * data,unsigned int offset,unsigned long len)3337 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3338 				  void *data, unsigned int offset,
3339 				  unsigned long len)
3340 {
3341 	struct kvm_memslots *slots = kvm_memslots(kvm);
3342 	int r;
3343 	gpa_t gpa = ghc->gpa + offset;
3344 
3345 	if (WARN_ON_ONCE(len + offset > ghc->len))
3346 		return -EINVAL;
3347 
3348 	if (slots->generation != ghc->generation) {
3349 		if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3350 			return -EFAULT;
3351 	}
3352 
3353 	if (kvm_is_error_hva(ghc->hva))
3354 		return -EFAULT;
3355 
3356 	if (unlikely(!ghc->memslot))
3357 		return kvm_write_guest(kvm, gpa, data, len);
3358 
3359 	r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
3360 	if (r)
3361 		return -EFAULT;
3362 	mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
3363 
3364 	return 0;
3365 }
3366 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
3367 
kvm_write_guest_cached(struct kvm * kvm,struct gfn_to_hva_cache * ghc,void * data,unsigned long len)3368 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3369 			   void *data, unsigned long len)
3370 {
3371 	return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
3372 }
3373 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
3374 
kvm_read_guest_offset_cached(struct kvm * kvm,struct gfn_to_hva_cache * ghc,void * data,unsigned int offset,unsigned long len)3375 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3376 				 void *data, unsigned int offset,
3377 				 unsigned long len)
3378 {
3379 	struct kvm_memslots *slots = kvm_memslots(kvm);
3380 	int r;
3381 	gpa_t gpa = ghc->gpa + offset;
3382 
3383 	if (WARN_ON_ONCE(len + offset > ghc->len))
3384 		return -EINVAL;
3385 
3386 	if (slots->generation != ghc->generation) {
3387 		if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3388 			return -EFAULT;
3389 	}
3390 
3391 	if (kvm_is_error_hva(ghc->hva))
3392 		return -EFAULT;
3393 
3394 	if (unlikely(!ghc->memslot))
3395 		return kvm_read_guest(kvm, gpa, data, len);
3396 
3397 	r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
3398 	if (r)
3399 		return -EFAULT;
3400 
3401 	return 0;
3402 }
3403 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3404 
kvm_read_guest_cached(struct kvm * kvm,struct gfn_to_hva_cache * ghc,void * data,unsigned long len)3405 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3406 			  void *data, unsigned long len)
3407 {
3408 	return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3409 }
3410 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
3411 
kvm_clear_guest(struct kvm * kvm,gpa_t gpa,unsigned long len)3412 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3413 {
3414 	const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3415 	gfn_t gfn = gpa >> PAGE_SHIFT;
3416 	int seg;
3417 	int offset = offset_in_page(gpa);
3418 	int ret;
3419 
3420 	while ((seg = next_segment(len, offset)) != 0) {
3421 		ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, seg);
3422 		if (ret < 0)
3423 			return ret;
3424 		offset = 0;
3425 		len -= seg;
3426 		++gfn;
3427 	}
3428 	return 0;
3429 }
3430 EXPORT_SYMBOL_GPL(kvm_clear_guest);
3431 
mark_page_dirty_in_slot(struct kvm * kvm,const struct kvm_memory_slot * memslot,gfn_t gfn)3432 void mark_page_dirty_in_slot(struct kvm *kvm,
3433 			     const struct kvm_memory_slot *memslot,
3434 		 	     gfn_t gfn)
3435 {
3436 	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
3437 
3438 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3439 	if (WARN_ON_ONCE(vcpu && vcpu->kvm != kvm))
3440 		return;
3441 
3442 	WARN_ON_ONCE(!vcpu && !kvm_arch_allow_write_without_running_vcpu(kvm));
3443 #endif
3444 
3445 	if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
3446 		unsigned long rel_gfn = gfn - memslot->base_gfn;
3447 		u32 slot = (memslot->as_id << 16) | memslot->id;
3448 
3449 		if (kvm->dirty_ring_size && vcpu)
3450 			kvm_dirty_ring_push(vcpu, slot, rel_gfn);
3451 		else if (memslot->dirty_bitmap)
3452 			set_bit_le(rel_gfn, memslot->dirty_bitmap);
3453 	}
3454 }
3455 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
3456 
mark_page_dirty(struct kvm * kvm,gfn_t gfn)3457 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3458 {
3459 	struct kvm_memory_slot *memslot;
3460 
3461 	memslot = gfn_to_memslot(kvm, gfn);
3462 	mark_page_dirty_in_slot(kvm, memslot, gfn);
3463 }
3464 EXPORT_SYMBOL_GPL(mark_page_dirty);
3465 
kvm_vcpu_mark_page_dirty(struct kvm_vcpu * vcpu,gfn_t gfn)3466 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3467 {
3468 	struct kvm_memory_slot *memslot;
3469 
3470 	memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3471 	mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
3472 }
3473 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3474 
kvm_sigset_activate(struct kvm_vcpu * vcpu)3475 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3476 {
3477 	if (!vcpu->sigset_active)
3478 		return;
3479 
3480 	/*
3481 	 * This does a lockless modification of ->real_blocked, which is fine
3482 	 * because, only current can change ->real_blocked and all readers of
3483 	 * ->real_blocked don't care as long ->real_blocked is always a subset
3484 	 * of ->blocked.
3485 	 */
3486 	sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
3487 }
3488 
kvm_sigset_deactivate(struct kvm_vcpu * vcpu)3489 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3490 {
3491 	if (!vcpu->sigset_active)
3492 		return;
3493 
3494 	sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
3495 	sigemptyset(&current->real_blocked);
3496 }
3497 
grow_halt_poll_ns(struct kvm_vcpu * vcpu)3498 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3499 {
3500 	unsigned int old, val, grow, grow_start;
3501 
3502 	old = val = vcpu->halt_poll_ns;
3503 	grow_start = READ_ONCE(halt_poll_ns_grow_start);
3504 	grow = READ_ONCE(halt_poll_ns_grow);
3505 	if (!grow)
3506 		goto out;
3507 
3508 	val *= grow;
3509 	if (val < grow_start)
3510 		val = grow_start;
3511 
3512 	vcpu->halt_poll_ns = val;
3513 out:
3514 	trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
3515 }
3516 
shrink_halt_poll_ns(struct kvm_vcpu * vcpu)3517 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3518 {
3519 	unsigned int old, val, shrink, grow_start;
3520 
3521 	old = val = vcpu->halt_poll_ns;
3522 	shrink = READ_ONCE(halt_poll_ns_shrink);
3523 	grow_start = READ_ONCE(halt_poll_ns_grow_start);
3524 	if (shrink == 0)
3525 		val = 0;
3526 	else
3527 		val /= shrink;
3528 
3529 	if (val < grow_start)
3530 		val = 0;
3531 
3532 	vcpu->halt_poll_ns = val;
3533 	trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
3534 }
3535 
kvm_vcpu_check_block(struct kvm_vcpu * vcpu)3536 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3537 {
3538 	int ret = -EINTR;
3539 	int idx = srcu_read_lock(&vcpu->kvm->srcu);
3540 
3541 	if (kvm_arch_vcpu_runnable(vcpu))
3542 		goto out;
3543 	if (kvm_cpu_has_pending_timer(vcpu))
3544 		goto out;
3545 	if (signal_pending(current))
3546 		goto out;
3547 	if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3548 		goto out;
3549 
3550 	ret = 0;
3551 out:
3552 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
3553 	return ret;
3554 }
3555 
3556 /*
3557  * Block the vCPU until the vCPU is runnable, an event arrives, or a signal is
3558  * pending.  This is mostly used when halting a vCPU, but may also be used
3559  * directly for other vCPU non-runnable states, e.g. x86's Wait-For-SIPI.
3560  */
kvm_vcpu_block(struct kvm_vcpu * vcpu)3561 bool kvm_vcpu_block(struct kvm_vcpu *vcpu)
3562 {
3563 	struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
3564 	bool waited = false;
3565 
3566 	vcpu->stat.generic.blocking = 1;
3567 
3568 	preempt_disable();
3569 	kvm_arch_vcpu_blocking(vcpu);
3570 	prepare_to_rcuwait(wait);
3571 	preempt_enable();
3572 
3573 	for (;;) {
3574 		set_current_state(TASK_INTERRUPTIBLE);
3575 
3576 		if (kvm_vcpu_check_block(vcpu) < 0)
3577 			break;
3578 
3579 		waited = true;
3580 		schedule();
3581 	}
3582 
3583 	preempt_disable();
3584 	finish_rcuwait(wait);
3585 	kvm_arch_vcpu_unblocking(vcpu);
3586 	preempt_enable();
3587 
3588 	vcpu->stat.generic.blocking = 0;
3589 
3590 	return waited;
3591 }
3592 
update_halt_poll_stats(struct kvm_vcpu * vcpu,ktime_t start,ktime_t end,bool success)3593 static inline void update_halt_poll_stats(struct kvm_vcpu *vcpu, ktime_t start,
3594 					  ktime_t end, bool success)
3595 {
3596 	struct kvm_vcpu_stat_generic *stats = &vcpu->stat.generic;
3597 	u64 poll_ns = ktime_to_ns(ktime_sub(end, start));
3598 
3599 	++vcpu->stat.generic.halt_attempted_poll;
3600 
3601 	if (success) {
3602 		++vcpu->stat.generic.halt_successful_poll;
3603 
3604 		if (!vcpu_valid_wakeup(vcpu))
3605 			++vcpu->stat.generic.halt_poll_invalid;
3606 
3607 		stats->halt_poll_success_ns += poll_ns;
3608 		KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_success_hist, poll_ns);
3609 	} else {
3610 		stats->halt_poll_fail_ns += poll_ns;
3611 		KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_fail_hist, poll_ns);
3612 	}
3613 }
3614 
kvm_vcpu_max_halt_poll_ns(struct kvm_vcpu * vcpu)3615 static unsigned int kvm_vcpu_max_halt_poll_ns(struct kvm_vcpu *vcpu)
3616 {
3617 	struct kvm *kvm = vcpu->kvm;
3618 
3619 	if (kvm->override_halt_poll_ns) {
3620 		/*
3621 		 * Ensure kvm->max_halt_poll_ns is not read before
3622 		 * kvm->override_halt_poll_ns.
3623 		 *
3624 		 * Pairs with the smp_wmb() when enabling KVM_CAP_HALT_POLL.
3625 		 */
3626 		smp_rmb();
3627 		return READ_ONCE(kvm->max_halt_poll_ns);
3628 	}
3629 
3630 	return READ_ONCE(halt_poll_ns);
3631 }
3632 
3633 /*
3634  * Emulate a vCPU halt condition, e.g. HLT on x86, WFI on arm, etc...  If halt
3635  * polling is enabled, busy wait for a short time before blocking to avoid the
3636  * expensive block+unblock sequence if a wake event arrives soon after the vCPU
3637  * is halted.
3638  */
kvm_vcpu_halt(struct kvm_vcpu * vcpu)3639 void kvm_vcpu_halt(struct kvm_vcpu *vcpu)
3640 {
3641 	unsigned int max_halt_poll_ns = kvm_vcpu_max_halt_poll_ns(vcpu);
3642 	bool halt_poll_allowed = !kvm_arch_no_poll(vcpu);
3643 	ktime_t start, cur, poll_end;
3644 	bool waited = false;
3645 	bool do_halt_poll;
3646 	u64 halt_ns;
3647 
3648 	if (vcpu->halt_poll_ns > max_halt_poll_ns)
3649 		vcpu->halt_poll_ns = max_halt_poll_ns;
3650 
3651 	do_halt_poll = halt_poll_allowed && vcpu->halt_poll_ns;
3652 
3653 	start = cur = poll_end = ktime_get();
3654 	if (do_halt_poll) {
3655 		ktime_t stop = ktime_add_ns(start, vcpu->halt_poll_ns);
3656 
3657 		do {
3658 			if (kvm_vcpu_check_block(vcpu) < 0)
3659 				goto out;
3660 			cpu_relax();
3661 			poll_end = cur = ktime_get();
3662 		} while (kvm_vcpu_can_poll(cur, stop));
3663 	}
3664 
3665 	waited = kvm_vcpu_block(vcpu);
3666 
3667 	cur = ktime_get();
3668 	if (waited) {
3669 		vcpu->stat.generic.halt_wait_ns +=
3670 			ktime_to_ns(cur) - ktime_to_ns(poll_end);
3671 		KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
3672 				ktime_to_ns(cur) - ktime_to_ns(poll_end));
3673 	}
3674 out:
3675 	/* The total time the vCPU was "halted", including polling time. */
3676 	halt_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3677 
3678 	/*
3679 	 * Note, halt-polling is considered successful so long as the vCPU was
3680 	 * never actually scheduled out, i.e. even if the wake event arrived
3681 	 * after of the halt-polling loop itself, but before the full wait.
3682 	 */
3683 	if (do_halt_poll)
3684 		update_halt_poll_stats(vcpu, start, poll_end, !waited);
3685 
3686 	if (halt_poll_allowed) {
3687 		/* Recompute the max halt poll time in case it changed. */
3688 		max_halt_poll_ns = kvm_vcpu_max_halt_poll_ns(vcpu);
3689 
3690 		if (!vcpu_valid_wakeup(vcpu)) {
3691 			shrink_halt_poll_ns(vcpu);
3692 		} else if (max_halt_poll_ns) {
3693 			if (halt_ns <= vcpu->halt_poll_ns)
3694 				;
3695 			/* we had a long block, shrink polling */
3696 			else if (vcpu->halt_poll_ns &&
3697 				 halt_ns > max_halt_poll_ns)
3698 				shrink_halt_poll_ns(vcpu);
3699 			/* we had a short halt and our poll time is too small */
3700 			else if (vcpu->halt_poll_ns < max_halt_poll_ns &&
3701 				 halt_ns < max_halt_poll_ns)
3702 				grow_halt_poll_ns(vcpu);
3703 		} else {
3704 			vcpu->halt_poll_ns = 0;
3705 		}
3706 	}
3707 
3708 	trace_kvm_vcpu_wakeup(halt_ns, waited, vcpu_valid_wakeup(vcpu));
3709 }
3710 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
3711 
kvm_vcpu_wake_up(struct kvm_vcpu * vcpu)3712 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3713 {
3714 	if (__kvm_vcpu_wake_up(vcpu)) {
3715 		WRITE_ONCE(vcpu->ready, true);
3716 		++vcpu->stat.generic.halt_wakeup;
3717 		return true;
3718 	}
3719 
3720 	return false;
3721 }
3722 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3723 
3724 #ifndef CONFIG_S390
3725 /*
3726  * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3727  */
kvm_vcpu_kick(struct kvm_vcpu * vcpu)3728 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3729 {
3730 	int me, cpu;
3731 
3732 	if (kvm_vcpu_wake_up(vcpu))
3733 		return;
3734 
3735 	me = get_cpu();
3736 	/*
3737 	 * The only state change done outside the vcpu mutex is IN_GUEST_MODE
3738 	 * to EXITING_GUEST_MODE.  Therefore the moderately expensive "should
3739 	 * kick" check does not need atomic operations if kvm_vcpu_kick is used
3740 	 * within the vCPU thread itself.
3741 	 */
3742 	if (vcpu == __this_cpu_read(kvm_running_vcpu)) {
3743 		if (vcpu->mode == IN_GUEST_MODE)
3744 			WRITE_ONCE(vcpu->mode, EXITING_GUEST_MODE);
3745 		goto out;
3746 	}
3747 
3748 	/*
3749 	 * Note, the vCPU could get migrated to a different pCPU at any point
3750 	 * after kvm_arch_vcpu_should_kick(), which could result in sending an
3751 	 * IPI to the previous pCPU.  But, that's ok because the purpose of the
3752 	 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the
3753 	 * vCPU also requires it to leave IN_GUEST_MODE.
3754 	 */
3755 	if (kvm_arch_vcpu_should_kick(vcpu)) {
3756 		cpu = READ_ONCE(vcpu->cpu);
3757 		if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3758 			smp_send_reschedule(cpu);
3759 	}
3760 out:
3761 	put_cpu();
3762 }
3763 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3764 #endif /* !CONFIG_S390 */
3765 
kvm_vcpu_yield_to(struct kvm_vcpu * target)3766 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3767 {
3768 	struct task_struct *task = NULL;
3769 	int ret;
3770 
3771 	if (!read_trylock(&target->pid_lock))
3772 		return 0;
3773 
3774 	if (target->pid)
3775 		task = get_pid_task(target->pid, PIDTYPE_PID);
3776 
3777 	read_unlock(&target->pid_lock);
3778 
3779 	if (!task)
3780 		return 0;
3781 	ret = yield_to(task, 1);
3782 	put_task_struct(task);
3783 
3784 	return ret;
3785 }
3786 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3787 
3788 /*
3789  * Helper that checks whether a VCPU is eligible for directed yield.
3790  * Most eligible candidate to yield is decided by following heuristics:
3791  *
3792  *  (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3793  *  (preempted lock holder), indicated by @in_spin_loop.
3794  *  Set at the beginning and cleared at the end of interception/PLE handler.
3795  *
3796  *  (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3797  *  chance last time (mostly it has become eligible now since we have probably
3798  *  yielded to lockholder in last iteration. This is done by toggling
3799  *  @dy_eligible each time a VCPU checked for eligibility.)
3800  *
3801  *  Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3802  *  to preempted lock-holder could result in wrong VCPU selection and CPU
3803  *  burning. Giving priority for a potential lock-holder increases lock
3804  *  progress.
3805  *
3806  *  Since algorithm is based on heuristics, accessing another VCPU data without
3807  *  locking does not harm. It may result in trying to yield to  same VCPU, fail
3808  *  and continue with next VCPU and so on.
3809  */
kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu * vcpu)3810 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3811 {
3812 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3813 	bool eligible;
3814 
3815 	eligible = !vcpu->spin_loop.in_spin_loop ||
3816 		    vcpu->spin_loop.dy_eligible;
3817 
3818 	if (vcpu->spin_loop.in_spin_loop)
3819 		kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3820 
3821 	return eligible;
3822 #else
3823 	return true;
3824 #endif
3825 }
3826 
3827 /*
3828  * Unlike kvm_arch_vcpu_runnable, this function is called outside
3829  * a vcpu_load/vcpu_put pair.  However, for most architectures
3830  * kvm_arch_vcpu_runnable does not require vcpu_load.
3831  */
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)3832 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3833 {
3834 	return kvm_arch_vcpu_runnable(vcpu);
3835 }
3836 
vcpu_dy_runnable(struct kvm_vcpu * vcpu)3837 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3838 {
3839 	if (kvm_arch_dy_runnable(vcpu))
3840 		return true;
3841 
3842 #ifdef CONFIG_KVM_ASYNC_PF
3843 	if (!list_empty_careful(&vcpu->async_pf.done))
3844 		return true;
3845 #endif
3846 
3847 	return false;
3848 }
3849 
3850 /*
3851  * By default, simply query the target vCPU's current mode when checking if a
3852  * vCPU was preempted in kernel mode.  All architectures except x86 (or more
3853  * specifical, except VMX) allow querying whether or not a vCPU is in kernel
3854  * mode even if the vCPU is NOT loaded, i.e. using kvm_arch_vcpu_in_kernel()
3855  * directly for cross-vCPU checks is functionally correct and accurate.
3856  */
kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu * vcpu)3857 bool __weak kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
3858 {
3859 	return kvm_arch_vcpu_in_kernel(vcpu);
3860 }
3861 
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)3862 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3863 {
3864 	return false;
3865 }
3866 
kvm_vcpu_on_spin(struct kvm_vcpu * me,bool yield_to_kernel_mode)3867 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3868 {
3869 	int nr_vcpus, start, i, idx, yielded;
3870 	struct kvm *kvm = me->kvm;
3871 	struct kvm_vcpu *vcpu;
3872 	int try = 3;
3873 
3874 	nr_vcpus = atomic_read(&kvm->online_vcpus);
3875 	if (nr_vcpus < 2)
3876 		return;
3877 
3878 	/* Pairs with the smp_wmb() in kvm_vm_ioctl_create_vcpu(). */
3879 	smp_rmb();
3880 
3881 	kvm_vcpu_set_in_spin_loop(me, true);
3882 
3883 	/*
3884 	 * The current vCPU ("me") is spinning in kernel mode, i.e. is likely
3885 	 * waiting for a resource to become available.  Attempt to yield to a
3886 	 * vCPU that is runnable, but not currently running, e.g. because the
3887 	 * vCPU was preempted by a higher priority task.  With luck, the vCPU
3888 	 * that was preempted is holding a lock or some other resource that the
3889 	 * current vCPU is waiting to acquire, and yielding to the other vCPU
3890 	 * will allow it to make forward progress and release the lock (or kick
3891 	 * the spinning vCPU, etc).
3892 	 *
3893 	 * Since KVM has no insight into what exactly the guest is doing,
3894 	 * approximate a round-robin selection by iterating over all vCPUs,
3895 	 * starting at the last boosted vCPU.  I.e. if N=kvm->last_boosted_vcpu,
3896 	 * iterate over vCPU[N+1]..vCPU[N-1], wrapping as needed.
3897 	 *
3898 	 * Note, this is inherently racy, e.g. if multiple vCPUs are spinning,
3899 	 * they may all try to yield to the same vCPU(s).  But as above, this
3900 	 * is all best effort due to KVM's lack of visibility into the guest.
3901 	 */
3902 	start = READ_ONCE(kvm->last_boosted_vcpu) + 1;
3903 	for (i = 0; i < nr_vcpus; i++) {
3904 		idx = (start + i) % nr_vcpus;
3905 		if (idx == me->vcpu_idx)
3906 			continue;
3907 
3908 		vcpu = xa_load(&kvm->vcpu_array, idx);
3909 		if (!READ_ONCE(vcpu->ready))
3910 			continue;
3911 		if (kvm_vcpu_is_blocking(vcpu) && !vcpu_dy_runnable(vcpu))
3912 			continue;
3913 
3914 		/*
3915 		 * Treat the target vCPU as being in-kernel if it has a pending
3916 		 * interrupt, as the vCPU trying to yield may be spinning
3917 		 * waiting on IPI delivery, i.e. the target vCPU is in-kernel
3918 		 * for the purposes of directed yield.
3919 		 */
3920 		if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3921 		    !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3922 		    !kvm_arch_vcpu_preempted_in_kernel(vcpu))
3923 			continue;
3924 
3925 		if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3926 			continue;
3927 
3928 		yielded = kvm_vcpu_yield_to(vcpu);
3929 		if (yielded > 0) {
3930 			WRITE_ONCE(kvm->last_boosted_vcpu, i);
3931 			break;
3932 		} else if (yielded < 0 && !--try) {
3933 			break;
3934 		}
3935 	}
3936 	kvm_vcpu_set_in_spin_loop(me, false);
3937 
3938 	/* Ensure vcpu is not eligible during next spinloop */
3939 	kvm_vcpu_set_dy_eligible(me, false);
3940 }
3941 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3942 
kvm_page_in_dirty_ring(struct kvm * kvm,unsigned long pgoff)3943 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3944 {
3945 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3946 	return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3947 	    (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3948 	     kvm->dirty_ring_size / PAGE_SIZE);
3949 #else
3950 	return false;
3951 #endif
3952 }
3953 
kvm_vcpu_fault(struct vm_fault * vmf)3954 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3955 {
3956 	struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3957 	struct page *page;
3958 
3959 	if (vmf->pgoff == 0)
3960 		page = virt_to_page(vcpu->run);
3961 #ifdef CONFIG_X86
3962 	else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3963 		page = virt_to_page(vcpu->arch.pio_data);
3964 #endif
3965 #ifdef CONFIG_KVM_MMIO
3966 	else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3967 		page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3968 #endif
3969 	else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3970 		page = kvm_dirty_ring_get_page(
3971 		    &vcpu->dirty_ring,
3972 		    vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3973 	else
3974 		return kvm_arch_vcpu_fault(vcpu, vmf);
3975 	get_page(page);
3976 	vmf->page = page;
3977 	return 0;
3978 }
3979 
3980 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3981 	.fault = kvm_vcpu_fault,
3982 };
3983 
kvm_vcpu_mmap(struct file * file,struct vm_area_struct * vma)3984 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3985 {
3986 	struct kvm_vcpu *vcpu = file->private_data;
3987 	unsigned long pages = vma_pages(vma);
3988 
3989 	if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3990 	     kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3991 	    ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3992 		return -EINVAL;
3993 
3994 	vma->vm_ops = &kvm_vcpu_vm_ops;
3995 	return 0;
3996 }
3997 
kvm_vcpu_release(struct inode * inode,struct file * filp)3998 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3999 {
4000 	struct kvm_vcpu *vcpu = filp->private_data;
4001 
4002 	kvm_put_kvm(vcpu->kvm);
4003 	return 0;
4004 }
4005 
4006 static struct file_operations kvm_vcpu_fops = {
4007 	.release        = kvm_vcpu_release,
4008 	.unlocked_ioctl = kvm_vcpu_ioctl,
4009 	.mmap           = kvm_vcpu_mmap,
4010 	.llseek		= noop_llseek,
4011 	KVM_COMPAT(kvm_vcpu_compat_ioctl),
4012 };
4013 
4014 /*
4015  * Allocates an inode for the vcpu.
4016  */
create_vcpu_fd(struct kvm_vcpu * vcpu)4017 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
4018 {
4019 	char name[8 + 1 + ITOA_MAX_LEN + 1];
4020 
4021 	snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
4022 	return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
4023 }
4024 
4025 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
vcpu_get_pid(void * data,u64 * val)4026 static int vcpu_get_pid(void *data, u64 *val)
4027 {
4028 	struct kvm_vcpu *vcpu = data;
4029 
4030 	read_lock(&vcpu->pid_lock);
4031 	*val = pid_nr(vcpu->pid);
4032 	read_unlock(&vcpu->pid_lock);
4033 	return 0;
4034 }
4035 
4036 DEFINE_SIMPLE_ATTRIBUTE(vcpu_get_pid_fops, vcpu_get_pid, NULL, "%llu\n");
4037 
kvm_create_vcpu_debugfs(struct kvm_vcpu * vcpu)4038 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
4039 {
4040 	struct dentry *debugfs_dentry;
4041 	char dir_name[ITOA_MAX_LEN * 2];
4042 
4043 	if (!debugfs_initialized())
4044 		return;
4045 
4046 	snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
4047 	debugfs_dentry = debugfs_create_dir(dir_name,
4048 					    vcpu->kvm->debugfs_dentry);
4049 	debugfs_create_file("pid", 0444, debugfs_dentry, vcpu,
4050 			    &vcpu_get_pid_fops);
4051 
4052 	kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
4053 }
4054 #endif
4055 
4056 /*
4057  * Creates some virtual cpus.  Good luck creating more than one.
4058  */
kvm_vm_ioctl_create_vcpu(struct kvm * kvm,unsigned long id)4059 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, unsigned long id)
4060 {
4061 	int r;
4062 	struct kvm_vcpu *vcpu;
4063 	struct page *page;
4064 
4065 	/*
4066 	 * KVM tracks vCPU IDs as 'int', be kind to userspace and reject
4067 	 * too-large values instead of silently truncating.
4068 	 *
4069 	 * Ensure KVM_MAX_VCPU_IDS isn't pushed above INT_MAX without first
4070 	 * changing the storage type (at the very least, IDs should be tracked
4071 	 * as unsigned ints).
4072 	 */
4073 	BUILD_BUG_ON(KVM_MAX_VCPU_IDS > INT_MAX);
4074 	if (id >= KVM_MAX_VCPU_IDS)
4075 		return -EINVAL;
4076 
4077 	mutex_lock(&kvm->lock);
4078 	if (kvm->created_vcpus >= kvm->max_vcpus) {
4079 		mutex_unlock(&kvm->lock);
4080 		return -EINVAL;
4081 	}
4082 
4083 	r = kvm_arch_vcpu_precreate(kvm, id);
4084 	if (r) {
4085 		mutex_unlock(&kvm->lock);
4086 		return r;
4087 	}
4088 
4089 	kvm->created_vcpus++;
4090 	mutex_unlock(&kvm->lock);
4091 
4092 	vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
4093 	if (!vcpu) {
4094 		r = -ENOMEM;
4095 		goto vcpu_decrement;
4096 	}
4097 
4098 	BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
4099 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
4100 	if (!page) {
4101 		r = -ENOMEM;
4102 		goto vcpu_free;
4103 	}
4104 	vcpu->run = page_address(page);
4105 
4106 	kvm_vcpu_init(vcpu, kvm, id);
4107 
4108 	r = kvm_arch_vcpu_create(vcpu);
4109 	if (r)
4110 		goto vcpu_free_run_page;
4111 
4112 	if (kvm->dirty_ring_size) {
4113 		r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
4114 					 id, kvm->dirty_ring_size);
4115 		if (r)
4116 			goto arch_vcpu_destroy;
4117 	}
4118 
4119 	mutex_lock(&kvm->lock);
4120 
4121 	if (kvm_get_vcpu_by_id(kvm, id)) {
4122 		r = -EEXIST;
4123 		goto unlock_vcpu_destroy;
4124 	}
4125 
4126 	vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
4127 	r = xa_insert(&kvm->vcpu_array, vcpu->vcpu_idx, vcpu, GFP_KERNEL_ACCOUNT);
4128 	WARN_ON_ONCE(r == -EBUSY);
4129 	if (r)
4130 		goto unlock_vcpu_destroy;
4131 
4132 	/*
4133 	 * Now it's all set up, let userspace reach it.  Grab the vCPU's mutex
4134 	 * so that userspace can't invoke vCPU ioctl()s until the vCPU is fully
4135 	 * visible (per online_vcpus), e.g. so that KVM doesn't get tricked
4136 	 * into a NULL-pointer dereference because KVM thinks the _current_
4137 	 * vCPU doesn't exist.  As a bonus, taking vcpu->mutex ensures lockdep
4138 	 * knows it's taken *inside* kvm->lock.
4139 	 */
4140 	mutex_lock(&vcpu->mutex);
4141 	kvm_get_kvm(kvm);
4142 	r = create_vcpu_fd(vcpu);
4143 	if (r < 0)
4144 		goto kvm_put_xa_erase;
4145 
4146 	/*
4147 	 * Pairs with smp_rmb() in kvm_get_vcpu.  Store the vcpu
4148 	 * pointer before kvm->online_vcpu's incremented value.
4149 	 */
4150 	smp_wmb();
4151 	atomic_inc(&kvm->online_vcpus);
4152 	mutex_unlock(&vcpu->mutex);
4153 
4154 	mutex_unlock(&kvm->lock);
4155 	kvm_arch_vcpu_postcreate(vcpu);
4156 	kvm_create_vcpu_debugfs(vcpu);
4157 	return r;
4158 
4159 kvm_put_xa_erase:
4160 	mutex_unlock(&vcpu->mutex);
4161 	kvm_put_kvm_no_destroy(kvm);
4162 	xa_erase(&kvm->vcpu_array, vcpu->vcpu_idx);
4163 unlock_vcpu_destroy:
4164 	mutex_unlock(&kvm->lock);
4165 	kvm_dirty_ring_free(&vcpu->dirty_ring);
4166 arch_vcpu_destroy:
4167 	kvm_arch_vcpu_destroy(vcpu);
4168 vcpu_free_run_page:
4169 	free_page((unsigned long)vcpu->run);
4170 vcpu_free:
4171 	kmem_cache_free(kvm_vcpu_cache, vcpu);
4172 vcpu_decrement:
4173 	mutex_lock(&kvm->lock);
4174 	kvm->created_vcpus--;
4175 	mutex_unlock(&kvm->lock);
4176 	return r;
4177 }
4178 
kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu * vcpu,sigset_t * sigset)4179 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
4180 {
4181 	if (sigset) {
4182 		sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
4183 		vcpu->sigset_active = 1;
4184 		vcpu->sigset = *sigset;
4185 	} else
4186 		vcpu->sigset_active = 0;
4187 	return 0;
4188 }
4189 
kvm_vcpu_stats_read(struct file * file,char __user * user_buffer,size_t size,loff_t * offset)4190 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
4191 			      size_t size, loff_t *offset)
4192 {
4193 	struct kvm_vcpu *vcpu = file->private_data;
4194 
4195 	return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
4196 			&kvm_vcpu_stats_desc[0], &vcpu->stat,
4197 			sizeof(vcpu->stat), user_buffer, size, offset);
4198 }
4199 
kvm_vcpu_stats_release(struct inode * inode,struct file * file)4200 static int kvm_vcpu_stats_release(struct inode *inode, struct file *file)
4201 {
4202 	struct kvm_vcpu *vcpu = file->private_data;
4203 
4204 	kvm_put_kvm(vcpu->kvm);
4205 	return 0;
4206 }
4207 
4208 static const struct file_operations kvm_vcpu_stats_fops = {
4209 	.owner = THIS_MODULE,
4210 	.read = kvm_vcpu_stats_read,
4211 	.release = kvm_vcpu_stats_release,
4212 	.llseek = noop_llseek,
4213 };
4214 
kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu * vcpu)4215 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
4216 {
4217 	int fd;
4218 	struct file *file;
4219 	char name[15 + ITOA_MAX_LEN + 1];
4220 
4221 	snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
4222 
4223 	fd = get_unused_fd_flags(O_CLOEXEC);
4224 	if (fd < 0)
4225 		return fd;
4226 
4227 	file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
4228 	if (IS_ERR(file)) {
4229 		put_unused_fd(fd);
4230 		return PTR_ERR(file);
4231 	}
4232 
4233 	kvm_get_kvm(vcpu->kvm);
4234 
4235 	file->f_mode |= FMODE_PREAD;
4236 	fd_install(fd, file);
4237 
4238 	return fd;
4239 }
4240 
4241 #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY
kvm_vcpu_pre_fault_memory(struct kvm_vcpu * vcpu,struct kvm_pre_fault_memory * range)4242 static int kvm_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
4243 				     struct kvm_pre_fault_memory *range)
4244 {
4245 	int idx;
4246 	long r;
4247 	u64 full_size;
4248 
4249 	if (range->flags)
4250 		return -EINVAL;
4251 
4252 	if (!PAGE_ALIGNED(range->gpa) ||
4253 	    !PAGE_ALIGNED(range->size) ||
4254 	    range->gpa + range->size <= range->gpa)
4255 		return -EINVAL;
4256 
4257 	vcpu_load(vcpu);
4258 	idx = srcu_read_lock(&vcpu->kvm->srcu);
4259 
4260 	full_size = range->size;
4261 	do {
4262 		if (signal_pending(current)) {
4263 			r = -EINTR;
4264 			break;
4265 		}
4266 
4267 		r = kvm_arch_vcpu_pre_fault_memory(vcpu, range);
4268 		if (WARN_ON_ONCE(r == 0 || r == -EIO))
4269 			break;
4270 
4271 		if (r < 0)
4272 			break;
4273 
4274 		range->size -= r;
4275 		range->gpa += r;
4276 		cond_resched();
4277 	} while (range->size);
4278 
4279 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
4280 	vcpu_put(vcpu);
4281 
4282 	/* Return success if at least one page was mapped successfully.  */
4283 	return full_size == range->size ? r : 0;
4284 }
4285 #endif
4286 
kvm_wait_for_vcpu_online(struct kvm_vcpu * vcpu)4287 static int kvm_wait_for_vcpu_online(struct kvm_vcpu *vcpu)
4288 {
4289 	struct kvm *kvm = vcpu->kvm;
4290 
4291 	/*
4292 	 * In practice, this happy path will always be taken, as a well-behaved
4293 	 * VMM will never invoke a vCPU ioctl() before KVM_CREATE_VCPU returns.
4294 	 */
4295 	if (likely(vcpu->vcpu_idx < atomic_read(&kvm->online_vcpus)))
4296 		return 0;
4297 
4298 	/*
4299 	 * Acquire and release the vCPU's mutex to wait for vCPU creation to
4300 	 * complete (kvm_vm_ioctl_create_vcpu() holds the mutex until the vCPU
4301 	 * is fully online).
4302 	 */
4303 	if (mutex_lock_killable(&vcpu->mutex))
4304 		return -EINTR;
4305 
4306 	mutex_unlock(&vcpu->mutex);
4307 
4308 	if (WARN_ON_ONCE(!kvm_get_vcpu(kvm, vcpu->vcpu_idx)))
4309 		return -EIO;
4310 
4311 	return 0;
4312 }
4313 
kvm_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4314 static long kvm_vcpu_ioctl(struct file *filp,
4315 			   unsigned int ioctl, unsigned long arg)
4316 {
4317 	struct kvm_vcpu *vcpu = filp->private_data;
4318 	void __user *argp = (void __user *)arg;
4319 	int r;
4320 	struct kvm_fpu *fpu = NULL;
4321 	struct kvm_sregs *kvm_sregs = NULL;
4322 
4323 	if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
4324 		return -EIO;
4325 
4326 	if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
4327 		return -EINVAL;
4328 
4329 	/*
4330 	 * Wait for the vCPU to be online before handling the ioctl(), as KVM
4331 	 * assumes the vCPU is reachable via vcpu_array, i.e. may dereference
4332 	 * a NULL pointer if userspace invokes an ioctl() before KVM is ready.
4333 	 */
4334 	r = kvm_wait_for_vcpu_online(vcpu);
4335 	if (r)
4336 		return r;
4337 
4338 	/*
4339 	 * Some architectures have vcpu ioctls that are asynchronous to vcpu
4340 	 * execution; mutex_lock() would break them.
4341 	 */
4342 	r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
4343 	if (r != -ENOIOCTLCMD)
4344 		return r;
4345 
4346 	if (mutex_lock_killable(&vcpu->mutex))
4347 		return -EINTR;
4348 	switch (ioctl) {
4349 	case KVM_RUN: {
4350 		struct pid *oldpid;
4351 		r = -EINVAL;
4352 		if (arg)
4353 			goto out;
4354 
4355 		/*
4356 		 * Note, vcpu->pid is primarily protected by vcpu->mutex. The
4357 		 * dedicated r/w lock allows other tasks, e.g. other vCPUs, to
4358 		 * read vcpu->pid while this vCPU is in KVM_RUN, e.g. to yield
4359 		 * directly to this vCPU
4360 		 */
4361 		oldpid = vcpu->pid;
4362 		if (unlikely(oldpid != task_pid(current))) {
4363 			/* The thread running this VCPU changed. */
4364 			struct pid *newpid;
4365 
4366 			r = kvm_arch_vcpu_run_pid_change(vcpu);
4367 			if (r)
4368 				break;
4369 
4370 			newpid = get_task_pid(current, PIDTYPE_PID);
4371 			write_lock(&vcpu->pid_lock);
4372 			vcpu->pid = newpid;
4373 			write_unlock(&vcpu->pid_lock);
4374 
4375 			put_pid(oldpid);
4376 		}
4377 		vcpu->wants_to_run = !READ_ONCE(vcpu->run->immediate_exit__unsafe);
4378 		r = kvm_arch_vcpu_ioctl_run(vcpu);
4379 		vcpu->wants_to_run = false;
4380 
4381 		trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
4382 		break;
4383 	}
4384 	case KVM_GET_REGS: {
4385 		struct kvm_regs *kvm_regs;
4386 
4387 		r = -ENOMEM;
4388 		kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
4389 		if (!kvm_regs)
4390 			goto out;
4391 		r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
4392 		if (r)
4393 			goto out_free1;
4394 		r = -EFAULT;
4395 		if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
4396 			goto out_free1;
4397 		r = 0;
4398 out_free1:
4399 		kfree(kvm_regs);
4400 		break;
4401 	}
4402 	case KVM_SET_REGS: {
4403 		struct kvm_regs *kvm_regs;
4404 
4405 		kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
4406 		if (IS_ERR(kvm_regs)) {
4407 			r = PTR_ERR(kvm_regs);
4408 			goto out;
4409 		}
4410 		r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
4411 		kfree(kvm_regs);
4412 		break;
4413 	}
4414 	case KVM_GET_SREGS: {
4415 		kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
4416 		r = -ENOMEM;
4417 		if (!kvm_sregs)
4418 			goto out;
4419 		r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
4420 		if (r)
4421 			goto out;
4422 		r = -EFAULT;
4423 		if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
4424 			goto out;
4425 		r = 0;
4426 		break;
4427 	}
4428 	case KVM_SET_SREGS: {
4429 		kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
4430 		if (IS_ERR(kvm_sregs)) {
4431 			r = PTR_ERR(kvm_sregs);
4432 			kvm_sregs = NULL;
4433 			goto out;
4434 		}
4435 		r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
4436 		break;
4437 	}
4438 	case KVM_GET_MP_STATE: {
4439 		struct kvm_mp_state mp_state;
4440 
4441 		r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
4442 		if (r)
4443 			goto out;
4444 		r = -EFAULT;
4445 		if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
4446 			goto out;
4447 		r = 0;
4448 		break;
4449 	}
4450 	case KVM_SET_MP_STATE: {
4451 		struct kvm_mp_state mp_state;
4452 
4453 		r = -EFAULT;
4454 		if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
4455 			goto out;
4456 		r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
4457 		break;
4458 	}
4459 	case KVM_TRANSLATE: {
4460 		struct kvm_translation tr;
4461 
4462 		r = -EFAULT;
4463 		if (copy_from_user(&tr, argp, sizeof(tr)))
4464 			goto out;
4465 		r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
4466 		if (r)
4467 			goto out;
4468 		r = -EFAULT;
4469 		if (copy_to_user(argp, &tr, sizeof(tr)))
4470 			goto out;
4471 		r = 0;
4472 		break;
4473 	}
4474 	case KVM_SET_GUEST_DEBUG: {
4475 		struct kvm_guest_debug dbg;
4476 
4477 		r = -EFAULT;
4478 		if (copy_from_user(&dbg, argp, sizeof(dbg)))
4479 			goto out;
4480 		r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
4481 		break;
4482 	}
4483 	case KVM_SET_SIGNAL_MASK: {
4484 		struct kvm_signal_mask __user *sigmask_arg = argp;
4485 		struct kvm_signal_mask kvm_sigmask;
4486 		sigset_t sigset, *p;
4487 
4488 		p = NULL;
4489 		if (argp) {
4490 			r = -EFAULT;
4491 			if (copy_from_user(&kvm_sigmask, argp,
4492 					   sizeof(kvm_sigmask)))
4493 				goto out;
4494 			r = -EINVAL;
4495 			if (kvm_sigmask.len != sizeof(sigset))
4496 				goto out;
4497 			r = -EFAULT;
4498 			if (copy_from_user(&sigset, sigmask_arg->sigset,
4499 					   sizeof(sigset)))
4500 				goto out;
4501 			p = &sigset;
4502 		}
4503 		r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
4504 		break;
4505 	}
4506 	case KVM_GET_FPU: {
4507 		fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
4508 		r = -ENOMEM;
4509 		if (!fpu)
4510 			goto out;
4511 		r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
4512 		if (r)
4513 			goto out;
4514 		r = -EFAULT;
4515 		if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
4516 			goto out;
4517 		r = 0;
4518 		break;
4519 	}
4520 	case KVM_SET_FPU: {
4521 		fpu = memdup_user(argp, sizeof(*fpu));
4522 		if (IS_ERR(fpu)) {
4523 			r = PTR_ERR(fpu);
4524 			fpu = NULL;
4525 			goto out;
4526 		}
4527 		r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
4528 		break;
4529 	}
4530 	case KVM_GET_STATS_FD: {
4531 		r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
4532 		break;
4533 	}
4534 #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY
4535 	case KVM_PRE_FAULT_MEMORY: {
4536 		struct kvm_pre_fault_memory range;
4537 
4538 		r = -EFAULT;
4539 		if (copy_from_user(&range, argp, sizeof(range)))
4540 			break;
4541 		r = kvm_vcpu_pre_fault_memory(vcpu, &range);
4542 		/* Pass back leftover range. */
4543 		if (copy_to_user(argp, &range, sizeof(range)))
4544 			r = -EFAULT;
4545 		break;
4546 	}
4547 #endif
4548 	default:
4549 		r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
4550 	}
4551 out:
4552 	mutex_unlock(&vcpu->mutex);
4553 	kfree(fpu);
4554 	kfree(kvm_sregs);
4555 	return r;
4556 }
4557 
4558 #ifdef CONFIG_KVM_COMPAT
kvm_vcpu_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4559 static long kvm_vcpu_compat_ioctl(struct file *filp,
4560 				  unsigned int ioctl, unsigned long arg)
4561 {
4562 	struct kvm_vcpu *vcpu = filp->private_data;
4563 	void __user *argp = compat_ptr(arg);
4564 	int r;
4565 
4566 	if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
4567 		return -EIO;
4568 
4569 	switch (ioctl) {
4570 	case KVM_SET_SIGNAL_MASK: {
4571 		struct kvm_signal_mask __user *sigmask_arg = argp;
4572 		struct kvm_signal_mask kvm_sigmask;
4573 		sigset_t sigset;
4574 
4575 		if (argp) {
4576 			r = -EFAULT;
4577 			if (copy_from_user(&kvm_sigmask, argp,
4578 					   sizeof(kvm_sigmask)))
4579 				goto out;
4580 			r = -EINVAL;
4581 			if (kvm_sigmask.len != sizeof(compat_sigset_t))
4582 				goto out;
4583 			r = -EFAULT;
4584 			if (get_compat_sigset(&sigset,
4585 					      (compat_sigset_t __user *)sigmask_arg->sigset))
4586 				goto out;
4587 			r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
4588 		} else
4589 			r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
4590 		break;
4591 	}
4592 	default:
4593 		r = kvm_vcpu_ioctl(filp, ioctl, arg);
4594 	}
4595 
4596 out:
4597 	return r;
4598 }
4599 #endif
4600 
kvm_device_mmap(struct file * filp,struct vm_area_struct * vma)4601 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
4602 {
4603 	struct kvm_device *dev = filp->private_data;
4604 
4605 	if (dev->ops->mmap)
4606 		return dev->ops->mmap(dev, vma);
4607 
4608 	return -ENODEV;
4609 }
4610 
kvm_device_ioctl_attr(struct kvm_device * dev,int (* accessor)(struct kvm_device * dev,struct kvm_device_attr * attr),unsigned long arg)4611 static int kvm_device_ioctl_attr(struct kvm_device *dev,
4612 				 int (*accessor)(struct kvm_device *dev,
4613 						 struct kvm_device_attr *attr),
4614 				 unsigned long arg)
4615 {
4616 	struct kvm_device_attr attr;
4617 
4618 	if (!accessor)
4619 		return -EPERM;
4620 
4621 	if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4622 		return -EFAULT;
4623 
4624 	return accessor(dev, &attr);
4625 }
4626 
kvm_device_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4627 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
4628 			     unsigned long arg)
4629 {
4630 	struct kvm_device *dev = filp->private_data;
4631 
4632 	if (dev->kvm->mm != current->mm || dev->kvm->vm_dead)
4633 		return -EIO;
4634 
4635 	switch (ioctl) {
4636 	case KVM_SET_DEVICE_ATTR:
4637 		return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
4638 	case KVM_GET_DEVICE_ATTR:
4639 		return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
4640 	case KVM_HAS_DEVICE_ATTR:
4641 		return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
4642 	default:
4643 		if (dev->ops->ioctl)
4644 			return dev->ops->ioctl(dev, ioctl, arg);
4645 
4646 		return -ENOTTY;
4647 	}
4648 }
4649 
kvm_device_release(struct inode * inode,struct file * filp)4650 static int kvm_device_release(struct inode *inode, struct file *filp)
4651 {
4652 	struct kvm_device *dev = filp->private_data;
4653 	struct kvm *kvm = dev->kvm;
4654 
4655 	if (dev->ops->release) {
4656 		mutex_lock(&kvm->lock);
4657 		list_del_rcu(&dev->vm_node);
4658 		synchronize_rcu();
4659 		dev->ops->release(dev);
4660 		mutex_unlock(&kvm->lock);
4661 	}
4662 
4663 	kvm_put_kvm(kvm);
4664 	return 0;
4665 }
4666 
4667 static struct file_operations kvm_device_fops = {
4668 	.unlocked_ioctl = kvm_device_ioctl,
4669 	.release = kvm_device_release,
4670 	KVM_COMPAT(kvm_device_ioctl),
4671 	.mmap = kvm_device_mmap,
4672 };
4673 
kvm_device_from_filp(struct file * filp)4674 struct kvm_device *kvm_device_from_filp(struct file *filp)
4675 {
4676 	if (filp->f_op != &kvm_device_fops)
4677 		return NULL;
4678 
4679 	return filp->private_data;
4680 }
4681 
4682 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
4683 #ifdef CONFIG_KVM_MPIC
4684 	[KVM_DEV_TYPE_FSL_MPIC_20]	= &kvm_mpic_ops,
4685 	[KVM_DEV_TYPE_FSL_MPIC_42]	= &kvm_mpic_ops,
4686 #endif
4687 };
4688 
kvm_register_device_ops(const struct kvm_device_ops * ops,u32 type)4689 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
4690 {
4691 	if (type >= ARRAY_SIZE(kvm_device_ops_table))
4692 		return -ENOSPC;
4693 
4694 	if (kvm_device_ops_table[type] != NULL)
4695 		return -EEXIST;
4696 
4697 	kvm_device_ops_table[type] = ops;
4698 	return 0;
4699 }
4700 
kvm_unregister_device_ops(u32 type)4701 void kvm_unregister_device_ops(u32 type)
4702 {
4703 	if (kvm_device_ops_table[type] != NULL)
4704 		kvm_device_ops_table[type] = NULL;
4705 }
4706 
kvm_ioctl_create_device(struct kvm * kvm,struct kvm_create_device * cd)4707 static int kvm_ioctl_create_device(struct kvm *kvm,
4708 				   struct kvm_create_device *cd)
4709 {
4710 	const struct kvm_device_ops *ops;
4711 	struct kvm_device *dev;
4712 	bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
4713 	int type;
4714 	int ret;
4715 
4716 	if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
4717 		return -ENODEV;
4718 
4719 	type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4720 	ops = kvm_device_ops_table[type];
4721 	if (ops == NULL)
4722 		return -ENODEV;
4723 
4724 	if (test)
4725 		return 0;
4726 
4727 	dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
4728 	if (!dev)
4729 		return -ENOMEM;
4730 
4731 	dev->ops = ops;
4732 	dev->kvm = kvm;
4733 
4734 	mutex_lock(&kvm->lock);
4735 	ret = ops->create(dev, type);
4736 	if (ret < 0) {
4737 		mutex_unlock(&kvm->lock);
4738 		kfree(dev);
4739 		return ret;
4740 	}
4741 	list_add_rcu(&dev->vm_node, &kvm->devices);
4742 	mutex_unlock(&kvm->lock);
4743 
4744 	if (ops->init)
4745 		ops->init(dev);
4746 
4747 	kvm_get_kvm(kvm);
4748 	ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
4749 	if (ret < 0) {
4750 		kvm_put_kvm_no_destroy(kvm);
4751 		mutex_lock(&kvm->lock);
4752 		list_del_rcu(&dev->vm_node);
4753 		synchronize_rcu();
4754 		if (ops->release)
4755 			ops->release(dev);
4756 		mutex_unlock(&kvm->lock);
4757 		if (ops->destroy)
4758 			ops->destroy(dev);
4759 		return ret;
4760 	}
4761 
4762 	cd->fd = ret;
4763 	return 0;
4764 }
4765 
kvm_vm_ioctl_check_extension_generic(struct kvm * kvm,long arg)4766 static int kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4767 {
4768 	switch (arg) {
4769 	case KVM_CAP_USER_MEMORY:
4770 	case KVM_CAP_USER_MEMORY2:
4771 	case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4772 	case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
4773 	case KVM_CAP_INTERNAL_ERROR_DATA:
4774 #ifdef CONFIG_HAVE_KVM_MSI
4775 	case KVM_CAP_SIGNAL_MSI:
4776 #endif
4777 #ifdef CONFIG_HAVE_KVM_IRQCHIP
4778 	case KVM_CAP_IRQFD:
4779 #endif
4780 	case KVM_CAP_IOEVENTFD_ANY_LENGTH:
4781 	case KVM_CAP_CHECK_EXTENSION_VM:
4782 	case KVM_CAP_ENABLE_CAP_VM:
4783 	case KVM_CAP_HALT_POLL:
4784 		return 1;
4785 #ifdef CONFIG_KVM_MMIO
4786 	case KVM_CAP_COALESCED_MMIO:
4787 		return KVM_COALESCED_MMIO_PAGE_OFFSET;
4788 	case KVM_CAP_COALESCED_PIO:
4789 		return 1;
4790 #endif
4791 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4792 	case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4793 		return KVM_DIRTY_LOG_MANUAL_CAPS;
4794 #endif
4795 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4796 	case KVM_CAP_IRQ_ROUTING:
4797 		return KVM_MAX_IRQ_ROUTES;
4798 #endif
4799 #if KVM_MAX_NR_ADDRESS_SPACES > 1
4800 	case KVM_CAP_MULTI_ADDRESS_SPACE:
4801 		if (kvm)
4802 			return kvm_arch_nr_memslot_as_ids(kvm);
4803 		return KVM_MAX_NR_ADDRESS_SPACES;
4804 #endif
4805 	case KVM_CAP_NR_MEMSLOTS:
4806 		return KVM_USER_MEM_SLOTS;
4807 	case KVM_CAP_DIRTY_LOG_RING:
4808 #ifdef CONFIG_HAVE_KVM_DIRTY_RING_TSO
4809 		return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4810 #else
4811 		return 0;
4812 #endif
4813 	case KVM_CAP_DIRTY_LOG_RING_ACQ_REL:
4814 #ifdef CONFIG_HAVE_KVM_DIRTY_RING_ACQ_REL
4815 		return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4816 #else
4817 		return 0;
4818 #endif
4819 #ifdef CONFIG_NEED_KVM_DIRTY_RING_WITH_BITMAP
4820 	case KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP:
4821 #endif
4822 	case KVM_CAP_BINARY_STATS_FD:
4823 	case KVM_CAP_SYSTEM_EVENT_DATA:
4824 	case KVM_CAP_DEVICE_CTRL:
4825 		return 1;
4826 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
4827 	case KVM_CAP_MEMORY_ATTRIBUTES:
4828 		return kvm_supported_mem_attributes(kvm);
4829 #endif
4830 #ifdef CONFIG_KVM_PRIVATE_MEM
4831 	case KVM_CAP_GUEST_MEMFD:
4832 		return !kvm || kvm_arch_has_private_mem(kvm);
4833 #endif
4834 	default:
4835 		break;
4836 	}
4837 	return kvm_vm_ioctl_check_extension(kvm, arg);
4838 }
4839 
kvm_vm_ioctl_enable_dirty_log_ring(struct kvm * kvm,u32 size)4840 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4841 {
4842 	int r;
4843 
4844 	if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4845 		return -EINVAL;
4846 
4847 	/* the size should be power of 2 */
4848 	if (!size || (size & (size - 1)))
4849 		return -EINVAL;
4850 
4851 	/* Should be bigger to keep the reserved entries, or a page */
4852 	if (size < kvm_dirty_ring_get_rsvd_entries() *
4853 	    sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4854 		return -EINVAL;
4855 
4856 	if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4857 	    sizeof(struct kvm_dirty_gfn))
4858 		return -E2BIG;
4859 
4860 	/* We only allow it to set once */
4861 	if (kvm->dirty_ring_size)
4862 		return -EINVAL;
4863 
4864 	mutex_lock(&kvm->lock);
4865 
4866 	if (kvm->created_vcpus) {
4867 		/* We don't allow to change this value after vcpu created */
4868 		r = -EINVAL;
4869 	} else {
4870 		kvm->dirty_ring_size = size;
4871 		r = 0;
4872 	}
4873 
4874 	mutex_unlock(&kvm->lock);
4875 	return r;
4876 }
4877 
kvm_vm_ioctl_reset_dirty_pages(struct kvm * kvm)4878 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4879 {
4880 	unsigned long i;
4881 	struct kvm_vcpu *vcpu;
4882 	int cleared = 0;
4883 
4884 	if (!kvm->dirty_ring_size)
4885 		return -EINVAL;
4886 
4887 	mutex_lock(&kvm->slots_lock);
4888 
4889 	kvm_for_each_vcpu(i, vcpu, kvm)
4890 		cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4891 
4892 	mutex_unlock(&kvm->slots_lock);
4893 
4894 	if (cleared)
4895 		kvm_flush_remote_tlbs(kvm);
4896 
4897 	return cleared;
4898 }
4899 
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)4900 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4901 						  struct kvm_enable_cap *cap)
4902 {
4903 	return -EINVAL;
4904 }
4905 
kvm_are_all_memslots_empty(struct kvm * kvm)4906 bool kvm_are_all_memslots_empty(struct kvm *kvm)
4907 {
4908 	int i;
4909 
4910 	lockdep_assert_held(&kvm->slots_lock);
4911 
4912 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
4913 		if (!kvm_memslots_empty(__kvm_memslots(kvm, i)))
4914 			return false;
4915 	}
4916 
4917 	return true;
4918 }
4919 EXPORT_SYMBOL_GPL(kvm_are_all_memslots_empty);
4920 
kvm_vm_ioctl_enable_cap_generic(struct kvm * kvm,struct kvm_enable_cap * cap)4921 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4922 					   struct kvm_enable_cap *cap)
4923 {
4924 	switch (cap->cap) {
4925 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4926 	case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4927 		u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4928 
4929 		if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4930 			allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4931 
4932 		if (cap->flags || (cap->args[0] & ~allowed_options))
4933 			return -EINVAL;
4934 		kvm->manual_dirty_log_protect = cap->args[0];
4935 		return 0;
4936 	}
4937 #endif
4938 	case KVM_CAP_HALT_POLL: {
4939 		if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4940 			return -EINVAL;
4941 
4942 		kvm->max_halt_poll_ns = cap->args[0];
4943 
4944 		/*
4945 		 * Ensure kvm->override_halt_poll_ns does not become visible
4946 		 * before kvm->max_halt_poll_ns.
4947 		 *
4948 		 * Pairs with the smp_rmb() in kvm_vcpu_max_halt_poll_ns().
4949 		 */
4950 		smp_wmb();
4951 		kvm->override_halt_poll_ns = true;
4952 
4953 		return 0;
4954 	}
4955 	case KVM_CAP_DIRTY_LOG_RING:
4956 	case KVM_CAP_DIRTY_LOG_RING_ACQ_REL:
4957 		if (!kvm_vm_ioctl_check_extension_generic(kvm, cap->cap))
4958 			return -EINVAL;
4959 
4960 		return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
4961 	case KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP: {
4962 		int r = -EINVAL;
4963 
4964 		if (!IS_ENABLED(CONFIG_NEED_KVM_DIRTY_RING_WITH_BITMAP) ||
4965 		    !kvm->dirty_ring_size || cap->flags)
4966 			return r;
4967 
4968 		mutex_lock(&kvm->slots_lock);
4969 
4970 		/*
4971 		 * For simplicity, allow enabling ring+bitmap if and only if
4972 		 * there are no memslots, e.g. to ensure all memslots allocate
4973 		 * a bitmap after the capability is enabled.
4974 		 */
4975 		if (kvm_are_all_memslots_empty(kvm)) {
4976 			kvm->dirty_ring_with_bitmap = true;
4977 			r = 0;
4978 		}
4979 
4980 		mutex_unlock(&kvm->slots_lock);
4981 
4982 		return r;
4983 	}
4984 	default:
4985 		return kvm_vm_ioctl_enable_cap(kvm, cap);
4986 	}
4987 }
4988 
kvm_vm_stats_read(struct file * file,char __user * user_buffer,size_t size,loff_t * offset)4989 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4990 			      size_t size, loff_t *offset)
4991 {
4992 	struct kvm *kvm = file->private_data;
4993 
4994 	return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4995 				&kvm_vm_stats_desc[0], &kvm->stat,
4996 				sizeof(kvm->stat), user_buffer, size, offset);
4997 }
4998 
kvm_vm_stats_release(struct inode * inode,struct file * file)4999 static int kvm_vm_stats_release(struct inode *inode, struct file *file)
5000 {
5001 	struct kvm *kvm = file->private_data;
5002 
5003 	kvm_put_kvm(kvm);
5004 	return 0;
5005 }
5006 
5007 static const struct file_operations kvm_vm_stats_fops = {
5008 	.owner = THIS_MODULE,
5009 	.read = kvm_vm_stats_read,
5010 	.release = kvm_vm_stats_release,
5011 	.llseek = noop_llseek,
5012 };
5013 
kvm_vm_ioctl_get_stats_fd(struct kvm * kvm)5014 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
5015 {
5016 	int fd;
5017 	struct file *file;
5018 
5019 	fd = get_unused_fd_flags(O_CLOEXEC);
5020 	if (fd < 0)
5021 		return fd;
5022 
5023 	file = anon_inode_getfile("kvm-vm-stats",
5024 			&kvm_vm_stats_fops, kvm, O_RDONLY);
5025 	if (IS_ERR(file)) {
5026 		put_unused_fd(fd);
5027 		return PTR_ERR(file);
5028 	}
5029 
5030 	kvm_get_kvm(kvm);
5031 
5032 	file->f_mode |= FMODE_PREAD;
5033 	fd_install(fd, file);
5034 
5035 	return fd;
5036 }
5037 
5038 #define SANITY_CHECK_MEM_REGION_FIELD(field)					\
5039 do {										\
5040 	BUILD_BUG_ON(offsetof(struct kvm_userspace_memory_region, field) !=		\
5041 		     offsetof(struct kvm_userspace_memory_region2, field));	\
5042 	BUILD_BUG_ON(sizeof_field(struct kvm_userspace_memory_region, field) !=		\
5043 		     sizeof_field(struct kvm_userspace_memory_region2, field));	\
5044 } while (0)
5045 
kvm_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5046 static long kvm_vm_ioctl(struct file *filp,
5047 			   unsigned int ioctl, unsigned long arg)
5048 {
5049 	struct kvm *kvm = filp->private_data;
5050 	void __user *argp = (void __user *)arg;
5051 	int r;
5052 
5053 	if (kvm->mm != current->mm || kvm->vm_dead)
5054 		return -EIO;
5055 	switch (ioctl) {
5056 	case KVM_CREATE_VCPU:
5057 		r = kvm_vm_ioctl_create_vcpu(kvm, arg);
5058 		break;
5059 	case KVM_ENABLE_CAP: {
5060 		struct kvm_enable_cap cap;
5061 
5062 		r = -EFAULT;
5063 		if (copy_from_user(&cap, argp, sizeof(cap)))
5064 			goto out;
5065 		r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
5066 		break;
5067 	}
5068 	case KVM_SET_USER_MEMORY_REGION2:
5069 	case KVM_SET_USER_MEMORY_REGION: {
5070 		struct kvm_userspace_memory_region2 mem;
5071 		unsigned long size;
5072 
5073 		if (ioctl == KVM_SET_USER_MEMORY_REGION) {
5074 			/*
5075 			 * Fields beyond struct kvm_userspace_memory_region shouldn't be
5076 			 * accessed, but avoid leaking kernel memory in case of a bug.
5077 			 */
5078 			memset(&mem, 0, sizeof(mem));
5079 			size = sizeof(struct kvm_userspace_memory_region);
5080 		} else {
5081 			size = sizeof(struct kvm_userspace_memory_region2);
5082 		}
5083 
5084 		/* Ensure the common parts of the two structs are identical. */
5085 		SANITY_CHECK_MEM_REGION_FIELD(slot);
5086 		SANITY_CHECK_MEM_REGION_FIELD(flags);
5087 		SANITY_CHECK_MEM_REGION_FIELD(guest_phys_addr);
5088 		SANITY_CHECK_MEM_REGION_FIELD(memory_size);
5089 		SANITY_CHECK_MEM_REGION_FIELD(userspace_addr);
5090 
5091 		r = -EFAULT;
5092 		if (copy_from_user(&mem, argp, size))
5093 			goto out;
5094 
5095 		r = -EINVAL;
5096 		if (ioctl == KVM_SET_USER_MEMORY_REGION &&
5097 		    (mem.flags & ~KVM_SET_USER_MEMORY_REGION_V1_FLAGS))
5098 			goto out;
5099 
5100 		r = kvm_vm_ioctl_set_memory_region(kvm, &mem);
5101 		break;
5102 	}
5103 	case KVM_GET_DIRTY_LOG: {
5104 		struct kvm_dirty_log log;
5105 
5106 		r = -EFAULT;
5107 		if (copy_from_user(&log, argp, sizeof(log)))
5108 			goto out;
5109 		r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
5110 		break;
5111 	}
5112 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
5113 	case KVM_CLEAR_DIRTY_LOG: {
5114 		struct kvm_clear_dirty_log log;
5115 
5116 		r = -EFAULT;
5117 		if (copy_from_user(&log, argp, sizeof(log)))
5118 			goto out;
5119 		r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
5120 		break;
5121 	}
5122 #endif
5123 #ifdef CONFIG_KVM_MMIO
5124 	case KVM_REGISTER_COALESCED_MMIO: {
5125 		struct kvm_coalesced_mmio_zone zone;
5126 
5127 		r = -EFAULT;
5128 		if (copy_from_user(&zone, argp, sizeof(zone)))
5129 			goto out;
5130 		r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
5131 		break;
5132 	}
5133 	case KVM_UNREGISTER_COALESCED_MMIO: {
5134 		struct kvm_coalesced_mmio_zone zone;
5135 
5136 		r = -EFAULT;
5137 		if (copy_from_user(&zone, argp, sizeof(zone)))
5138 			goto out;
5139 		r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
5140 		break;
5141 	}
5142 #endif
5143 	case KVM_IRQFD: {
5144 		struct kvm_irqfd data;
5145 
5146 		r = -EFAULT;
5147 		if (copy_from_user(&data, argp, sizeof(data)))
5148 			goto out;
5149 		r = kvm_irqfd(kvm, &data);
5150 		break;
5151 	}
5152 	case KVM_IOEVENTFD: {
5153 		struct kvm_ioeventfd data;
5154 
5155 		r = -EFAULT;
5156 		if (copy_from_user(&data, argp, sizeof(data)))
5157 			goto out;
5158 		r = kvm_ioeventfd(kvm, &data);
5159 		break;
5160 	}
5161 #ifdef CONFIG_HAVE_KVM_MSI
5162 	case KVM_SIGNAL_MSI: {
5163 		struct kvm_msi msi;
5164 
5165 		r = -EFAULT;
5166 		if (copy_from_user(&msi, argp, sizeof(msi)))
5167 			goto out;
5168 		r = kvm_send_userspace_msi(kvm, &msi);
5169 		break;
5170 	}
5171 #endif
5172 #ifdef __KVM_HAVE_IRQ_LINE
5173 	case KVM_IRQ_LINE_STATUS:
5174 	case KVM_IRQ_LINE: {
5175 		struct kvm_irq_level irq_event;
5176 
5177 		r = -EFAULT;
5178 		if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
5179 			goto out;
5180 
5181 		r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
5182 					ioctl == KVM_IRQ_LINE_STATUS);
5183 		if (r)
5184 			goto out;
5185 
5186 		r = -EFAULT;
5187 		if (ioctl == KVM_IRQ_LINE_STATUS) {
5188 			if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
5189 				goto out;
5190 		}
5191 
5192 		r = 0;
5193 		break;
5194 	}
5195 #endif
5196 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
5197 	case KVM_SET_GSI_ROUTING: {
5198 		struct kvm_irq_routing routing;
5199 		struct kvm_irq_routing __user *urouting;
5200 		struct kvm_irq_routing_entry *entries = NULL;
5201 
5202 		r = -EFAULT;
5203 		if (copy_from_user(&routing, argp, sizeof(routing)))
5204 			goto out;
5205 		r = -EINVAL;
5206 		if (!kvm_arch_can_set_irq_routing(kvm))
5207 			goto out;
5208 		if (routing.nr > KVM_MAX_IRQ_ROUTES)
5209 			goto out;
5210 		if (routing.flags)
5211 			goto out;
5212 		if (routing.nr) {
5213 			urouting = argp;
5214 			entries = vmemdup_array_user(urouting->entries,
5215 						     routing.nr, sizeof(*entries));
5216 			if (IS_ERR(entries)) {
5217 				r = PTR_ERR(entries);
5218 				goto out;
5219 			}
5220 		}
5221 		r = kvm_set_irq_routing(kvm, entries, routing.nr,
5222 					routing.flags);
5223 		kvfree(entries);
5224 		break;
5225 	}
5226 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
5227 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
5228 	case KVM_SET_MEMORY_ATTRIBUTES: {
5229 		struct kvm_memory_attributes attrs;
5230 
5231 		r = -EFAULT;
5232 		if (copy_from_user(&attrs, argp, sizeof(attrs)))
5233 			goto out;
5234 
5235 		r = kvm_vm_ioctl_set_mem_attributes(kvm, &attrs);
5236 		break;
5237 	}
5238 #endif /* CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES */
5239 	case KVM_CREATE_DEVICE: {
5240 		struct kvm_create_device cd;
5241 
5242 		r = -EFAULT;
5243 		if (copy_from_user(&cd, argp, sizeof(cd)))
5244 			goto out;
5245 
5246 		r = kvm_ioctl_create_device(kvm, &cd);
5247 		if (r)
5248 			goto out;
5249 
5250 		r = -EFAULT;
5251 		if (copy_to_user(argp, &cd, sizeof(cd)))
5252 			goto out;
5253 
5254 		r = 0;
5255 		break;
5256 	}
5257 	case KVM_CHECK_EXTENSION:
5258 		r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
5259 		break;
5260 	case KVM_RESET_DIRTY_RINGS:
5261 		r = kvm_vm_ioctl_reset_dirty_pages(kvm);
5262 		break;
5263 	case KVM_GET_STATS_FD:
5264 		r = kvm_vm_ioctl_get_stats_fd(kvm);
5265 		break;
5266 #ifdef CONFIG_KVM_PRIVATE_MEM
5267 	case KVM_CREATE_GUEST_MEMFD: {
5268 		struct kvm_create_guest_memfd guest_memfd;
5269 
5270 		r = -EFAULT;
5271 		if (copy_from_user(&guest_memfd, argp, sizeof(guest_memfd)))
5272 			goto out;
5273 
5274 		r = kvm_gmem_create(kvm, &guest_memfd);
5275 		break;
5276 	}
5277 #endif
5278 	default:
5279 		r = kvm_arch_vm_ioctl(filp, ioctl, arg);
5280 	}
5281 out:
5282 	return r;
5283 }
5284 
5285 #ifdef CONFIG_KVM_COMPAT
5286 struct compat_kvm_dirty_log {
5287 	__u32 slot;
5288 	__u32 padding1;
5289 	union {
5290 		compat_uptr_t dirty_bitmap; /* one bit per page */
5291 		__u64 padding2;
5292 	};
5293 };
5294 
5295 struct compat_kvm_clear_dirty_log {
5296 	__u32 slot;
5297 	__u32 num_pages;
5298 	__u64 first_page;
5299 	union {
5300 		compat_uptr_t dirty_bitmap; /* one bit per page */
5301 		__u64 padding2;
5302 	};
5303 };
5304 
kvm_arch_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5305 long __weak kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
5306 				     unsigned long arg)
5307 {
5308 	return -ENOTTY;
5309 }
5310 
kvm_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5311 static long kvm_vm_compat_ioctl(struct file *filp,
5312 			   unsigned int ioctl, unsigned long arg)
5313 {
5314 	struct kvm *kvm = filp->private_data;
5315 	int r;
5316 
5317 	if (kvm->mm != current->mm || kvm->vm_dead)
5318 		return -EIO;
5319 
5320 	r = kvm_arch_vm_compat_ioctl(filp, ioctl, arg);
5321 	if (r != -ENOTTY)
5322 		return r;
5323 
5324 	switch (ioctl) {
5325 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
5326 	case KVM_CLEAR_DIRTY_LOG: {
5327 		struct compat_kvm_clear_dirty_log compat_log;
5328 		struct kvm_clear_dirty_log log;
5329 
5330 		if (copy_from_user(&compat_log, (void __user *)arg,
5331 				   sizeof(compat_log)))
5332 			return -EFAULT;
5333 		log.slot	 = compat_log.slot;
5334 		log.num_pages	 = compat_log.num_pages;
5335 		log.first_page	 = compat_log.first_page;
5336 		log.padding2	 = compat_log.padding2;
5337 		log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
5338 
5339 		r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
5340 		break;
5341 	}
5342 #endif
5343 	case KVM_GET_DIRTY_LOG: {
5344 		struct compat_kvm_dirty_log compat_log;
5345 		struct kvm_dirty_log log;
5346 
5347 		if (copy_from_user(&compat_log, (void __user *)arg,
5348 				   sizeof(compat_log)))
5349 			return -EFAULT;
5350 		log.slot	 = compat_log.slot;
5351 		log.padding1	 = compat_log.padding1;
5352 		log.padding2	 = compat_log.padding2;
5353 		log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
5354 
5355 		r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
5356 		break;
5357 	}
5358 	default:
5359 		r = kvm_vm_ioctl(filp, ioctl, arg);
5360 	}
5361 	return r;
5362 }
5363 #endif
5364 
5365 static struct file_operations kvm_vm_fops = {
5366 	.release        = kvm_vm_release,
5367 	.unlocked_ioctl = kvm_vm_ioctl,
5368 	.llseek		= noop_llseek,
5369 	KVM_COMPAT(kvm_vm_compat_ioctl),
5370 };
5371 
file_is_kvm(struct file * file)5372 bool file_is_kvm(struct file *file)
5373 {
5374 	return file && file->f_op == &kvm_vm_fops;
5375 }
5376 EXPORT_SYMBOL_GPL(file_is_kvm);
5377 
kvm_dev_ioctl_create_vm(unsigned long type)5378 static int kvm_dev_ioctl_create_vm(unsigned long type)
5379 {
5380 	char fdname[ITOA_MAX_LEN + 1];
5381 	int r, fd;
5382 	struct kvm *kvm;
5383 	struct file *file;
5384 
5385 	fd = get_unused_fd_flags(O_CLOEXEC);
5386 	if (fd < 0)
5387 		return fd;
5388 
5389 	snprintf(fdname, sizeof(fdname), "%d", fd);
5390 
5391 	kvm = kvm_create_vm(type, fdname);
5392 	if (IS_ERR(kvm)) {
5393 		r = PTR_ERR(kvm);
5394 		goto put_fd;
5395 	}
5396 
5397 	file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
5398 	if (IS_ERR(file)) {
5399 		r = PTR_ERR(file);
5400 		goto put_kvm;
5401 	}
5402 
5403 	/*
5404 	 * Don't call kvm_put_kvm anymore at this point; file->f_op is
5405 	 * already set, with ->release() being kvm_vm_release().  In error
5406 	 * cases it will be called by the final fput(file) and will take
5407 	 * care of doing kvm_put_kvm(kvm).
5408 	 */
5409 	kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
5410 
5411 	fd_install(fd, file);
5412 	return fd;
5413 
5414 put_kvm:
5415 	kvm_put_kvm(kvm);
5416 put_fd:
5417 	put_unused_fd(fd);
5418 	return r;
5419 }
5420 
kvm_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5421 static long kvm_dev_ioctl(struct file *filp,
5422 			  unsigned int ioctl, unsigned long arg)
5423 {
5424 	int r = -EINVAL;
5425 
5426 	switch (ioctl) {
5427 	case KVM_GET_API_VERSION:
5428 		if (arg)
5429 			goto out;
5430 		r = KVM_API_VERSION;
5431 		break;
5432 	case KVM_CREATE_VM:
5433 		r = kvm_dev_ioctl_create_vm(arg);
5434 		break;
5435 	case KVM_CHECK_EXTENSION:
5436 		r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
5437 		break;
5438 	case KVM_GET_VCPU_MMAP_SIZE:
5439 		if (arg)
5440 			goto out;
5441 		r = PAGE_SIZE;     /* struct kvm_run */
5442 #ifdef CONFIG_X86
5443 		r += PAGE_SIZE;    /* pio data page */
5444 #endif
5445 #ifdef CONFIG_KVM_MMIO
5446 		r += PAGE_SIZE;    /* coalesced mmio ring page */
5447 #endif
5448 		break;
5449 	default:
5450 		return kvm_arch_dev_ioctl(filp, ioctl, arg);
5451 	}
5452 out:
5453 	return r;
5454 }
5455 
5456 static struct file_operations kvm_chardev_ops = {
5457 	.unlocked_ioctl = kvm_dev_ioctl,
5458 	.llseek		= noop_llseek,
5459 	KVM_COMPAT(kvm_dev_ioctl),
5460 };
5461 
5462 static struct miscdevice kvm_dev = {
5463 	KVM_MINOR,
5464 	"kvm",
5465 	&kvm_chardev_ops,
5466 };
5467 
5468 #ifdef CONFIG_KVM_GENERIC_HARDWARE_ENABLING
5469 static bool enable_virt_at_load = true;
5470 module_param(enable_virt_at_load, bool, 0444);
5471 
5472 __visible bool kvm_rebooting;
5473 EXPORT_SYMBOL_GPL(kvm_rebooting);
5474 
5475 static DEFINE_PER_CPU(bool, virtualization_enabled);
5476 static DEFINE_MUTEX(kvm_usage_lock);
5477 static int kvm_usage_count;
5478 
kvm_arch_enable_virtualization(void)5479 __weak void kvm_arch_enable_virtualization(void)
5480 {
5481 
5482 }
5483 
kvm_arch_disable_virtualization(void)5484 __weak void kvm_arch_disable_virtualization(void)
5485 {
5486 
5487 }
5488 
kvm_enable_virtualization_cpu(void)5489 static int kvm_enable_virtualization_cpu(void)
5490 {
5491 	if (__this_cpu_read(virtualization_enabled))
5492 		return 0;
5493 
5494 	if (kvm_arch_enable_virtualization_cpu()) {
5495 		pr_info("kvm: enabling virtualization on CPU%d failed\n",
5496 			raw_smp_processor_id());
5497 		return -EIO;
5498 	}
5499 
5500 	__this_cpu_write(virtualization_enabled, true);
5501 	return 0;
5502 }
5503 
kvm_online_cpu(unsigned int cpu)5504 static int kvm_online_cpu(unsigned int cpu)
5505 {
5506 	/*
5507 	 * Abort the CPU online process if hardware virtualization cannot
5508 	 * be enabled. Otherwise running VMs would encounter unrecoverable
5509 	 * errors when scheduled to this CPU.
5510 	 */
5511 	return kvm_enable_virtualization_cpu();
5512 }
5513 
kvm_disable_virtualization_cpu(void * ign)5514 static void kvm_disable_virtualization_cpu(void *ign)
5515 {
5516 	if (!__this_cpu_read(virtualization_enabled))
5517 		return;
5518 
5519 	kvm_arch_disable_virtualization_cpu();
5520 
5521 	__this_cpu_write(virtualization_enabled, false);
5522 }
5523 
kvm_offline_cpu(unsigned int cpu)5524 static int kvm_offline_cpu(unsigned int cpu)
5525 {
5526 	kvm_disable_virtualization_cpu(NULL);
5527 	return 0;
5528 }
5529 
kvm_shutdown(void)5530 static void kvm_shutdown(void)
5531 {
5532 	/*
5533 	 * Disable hardware virtualization and set kvm_rebooting to indicate
5534 	 * that KVM has asynchronously disabled hardware virtualization, i.e.
5535 	 * that relevant errors and exceptions aren't entirely unexpected.
5536 	 * Some flavors of hardware virtualization need to be disabled before
5537 	 * transferring control to firmware (to perform shutdown/reboot), e.g.
5538 	 * on x86, virtualization can block INIT interrupts, which are used by
5539 	 * firmware to pull APs back under firmware control.  Note, this path
5540 	 * is used for both shutdown and reboot scenarios, i.e. neither name is
5541 	 * 100% comprehensive.
5542 	 */
5543 	pr_info("kvm: exiting hardware virtualization\n");
5544 	kvm_rebooting = true;
5545 	on_each_cpu(kvm_disable_virtualization_cpu, NULL, 1);
5546 }
5547 
kvm_suspend(void)5548 static int kvm_suspend(void)
5549 {
5550 	/*
5551 	 * Secondary CPUs and CPU hotplug are disabled across the suspend/resume
5552 	 * callbacks, i.e. no need to acquire kvm_usage_lock to ensure the usage
5553 	 * count is stable.  Assert that kvm_usage_lock is not held to ensure
5554 	 * the system isn't suspended while KVM is enabling hardware.  Hardware
5555 	 * enabling can be preempted, but the task cannot be frozen until it has
5556 	 * dropped all locks (userspace tasks are frozen via a fake signal).
5557 	 */
5558 	lockdep_assert_not_held(&kvm_usage_lock);
5559 	lockdep_assert_irqs_disabled();
5560 
5561 	kvm_disable_virtualization_cpu(NULL);
5562 	return 0;
5563 }
5564 
kvm_resume(void)5565 static void kvm_resume(void)
5566 {
5567 	lockdep_assert_not_held(&kvm_usage_lock);
5568 	lockdep_assert_irqs_disabled();
5569 
5570 	WARN_ON_ONCE(kvm_enable_virtualization_cpu());
5571 }
5572 
5573 static struct syscore_ops kvm_syscore_ops = {
5574 	.suspend = kvm_suspend,
5575 	.resume = kvm_resume,
5576 	.shutdown = kvm_shutdown,
5577 };
5578 
kvm_enable_virtualization(void)5579 static int kvm_enable_virtualization(void)
5580 {
5581 	int r;
5582 
5583 	guard(mutex)(&kvm_usage_lock);
5584 
5585 	if (kvm_usage_count++)
5586 		return 0;
5587 
5588 	kvm_arch_enable_virtualization();
5589 
5590 	r = cpuhp_setup_state(CPUHP_AP_KVM_ONLINE, "kvm/cpu:online",
5591 			      kvm_online_cpu, kvm_offline_cpu);
5592 	if (r)
5593 		goto err_cpuhp;
5594 
5595 	register_syscore_ops(&kvm_syscore_ops);
5596 
5597 	/*
5598 	 * Undo virtualization enabling and bail if the system is going down.
5599 	 * If userspace initiated a forced reboot, e.g. reboot -f, then it's
5600 	 * possible for an in-flight operation to enable virtualization after
5601 	 * syscore_shutdown() is called, i.e. without kvm_shutdown() being
5602 	 * invoked.  Note, this relies on system_state being set _before_
5603 	 * kvm_shutdown(), e.g. to ensure either kvm_shutdown() is invoked
5604 	 * or this CPU observes the impending shutdown.  Which is why KVM uses
5605 	 * a syscore ops hook instead of registering a dedicated reboot
5606 	 * notifier (the latter runs before system_state is updated).
5607 	 */
5608 	if (system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF ||
5609 	    system_state == SYSTEM_RESTART) {
5610 		r = -EBUSY;
5611 		goto err_rebooting;
5612 	}
5613 
5614 	return 0;
5615 
5616 err_rebooting:
5617 	unregister_syscore_ops(&kvm_syscore_ops);
5618 	cpuhp_remove_state(CPUHP_AP_KVM_ONLINE);
5619 err_cpuhp:
5620 	kvm_arch_disable_virtualization();
5621 	--kvm_usage_count;
5622 	return r;
5623 }
5624 
kvm_disable_virtualization(void)5625 static void kvm_disable_virtualization(void)
5626 {
5627 	guard(mutex)(&kvm_usage_lock);
5628 
5629 	if (--kvm_usage_count)
5630 		return;
5631 
5632 	unregister_syscore_ops(&kvm_syscore_ops);
5633 	cpuhp_remove_state(CPUHP_AP_KVM_ONLINE);
5634 	kvm_arch_disable_virtualization();
5635 }
5636 
kvm_init_virtualization(void)5637 static int kvm_init_virtualization(void)
5638 {
5639 	if (enable_virt_at_load)
5640 		return kvm_enable_virtualization();
5641 
5642 	return 0;
5643 }
5644 
kvm_uninit_virtualization(void)5645 static void kvm_uninit_virtualization(void)
5646 {
5647 	if (enable_virt_at_load)
5648 		kvm_disable_virtualization();
5649 }
5650 #else /* CONFIG_KVM_GENERIC_HARDWARE_ENABLING */
kvm_enable_virtualization(void)5651 static int kvm_enable_virtualization(void)
5652 {
5653 	return 0;
5654 }
5655 
kvm_init_virtualization(void)5656 static int kvm_init_virtualization(void)
5657 {
5658 	return 0;
5659 }
5660 
kvm_disable_virtualization(void)5661 static void kvm_disable_virtualization(void)
5662 {
5663 
5664 }
5665 
kvm_uninit_virtualization(void)5666 static void kvm_uninit_virtualization(void)
5667 {
5668 
5669 }
5670 #endif /* CONFIG_KVM_GENERIC_HARDWARE_ENABLING */
5671 
kvm_iodevice_destructor(struct kvm_io_device * dev)5672 static void kvm_iodevice_destructor(struct kvm_io_device *dev)
5673 {
5674 	if (dev->ops->destructor)
5675 		dev->ops->destructor(dev);
5676 }
5677 
kvm_io_bus_destroy(struct kvm_io_bus * bus)5678 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
5679 {
5680 	int i;
5681 
5682 	for (i = 0; i < bus->dev_count; i++) {
5683 		struct kvm_io_device *pos = bus->range[i].dev;
5684 
5685 		kvm_iodevice_destructor(pos);
5686 	}
5687 	kfree(bus);
5688 }
5689 
kvm_io_bus_cmp(const struct kvm_io_range * r1,const struct kvm_io_range * r2)5690 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
5691 				 const struct kvm_io_range *r2)
5692 {
5693 	gpa_t addr1 = r1->addr;
5694 	gpa_t addr2 = r2->addr;
5695 
5696 	if (addr1 < addr2)
5697 		return -1;
5698 
5699 	/* If r2->len == 0, match the exact address.  If r2->len != 0,
5700 	 * accept any overlapping write.  Any order is acceptable for
5701 	 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
5702 	 * we process all of them.
5703 	 */
5704 	if (r2->len) {
5705 		addr1 += r1->len;
5706 		addr2 += r2->len;
5707 	}
5708 
5709 	if (addr1 > addr2)
5710 		return 1;
5711 
5712 	return 0;
5713 }
5714 
kvm_io_bus_sort_cmp(const void * p1,const void * p2)5715 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
5716 {
5717 	return kvm_io_bus_cmp(p1, p2);
5718 }
5719 
kvm_io_bus_get_first_dev(struct kvm_io_bus * bus,gpa_t addr,int len)5720 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
5721 			     gpa_t addr, int len)
5722 {
5723 	struct kvm_io_range *range, key;
5724 	int off;
5725 
5726 	key = (struct kvm_io_range) {
5727 		.addr = addr,
5728 		.len = len,
5729 	};
5730 
5731 	range = bsearch(&key, bus->range, bus->dev_count,
5732 			sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
5733 	if (range == NULL)
5734 		return -ENOENT;
5735 
5736 	off = range - bus->range;
5737 
5738 	while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
5739 		off--;
5740 
5741 	return off;
5742 }
5743 
__kvm_io_bus_write(struct kvm_vcpu * vcpu,struct kvm_io_bus * bus,struct kvm_io_range * range,const void * val)5744 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5745 			      struct kvm_io_range *range, const void *val)
5746 {
5747 	int idx;
5748 
5749 	idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5750 	if (idx < 0)
5751 		return -EOPNOTSUPP;
5752 
5753 	while (idx < bus->dev_count &&
5754 		kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5755 		if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
5756 					range->len, val))
5757 			return idx;
5758 		idx++;
5759 	}
5760 
5761 	return -EOPNOTSUPP;
5762 }
5763 
5764 /* 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)5765 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5766 		     int len, const void *val)
5767 {
5768 	struct kvm_io_bus *bus;
5769 	struct kvm_io_range range;
5770 	int r;
5771 
5772 	range = (struct kvm_io_range) {
5773 		.addr = addr,
5774 		.len = len,
5775 	};
5776 
5777 	bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5778 	if (!bus)
5779 		return -ENOMEM;
5780 	r = __kvm_io_bus_write(vcpu, bus, &range, val);
5781 	return r < 0 ? r : 0;
5782 }
5783 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
5784 
5785 /* 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)5786 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
5787 			    gpa_t addr, int len, const void *val, long cookie)
5788 {
5789 	struct kvm_io_bus *bus;
5790 	struct kvm_io_range range;
5791 
5792 	range = (struct kvm_io_range) {
5793 		.addr = addr,
5794 		.len = len,
5795 	};
5796 
5797 	bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5798 	if (!bus)
5799 		return -ENOMEM;
5800 
5801 	/* First try the device referenced by cookie. */
5802 	if ((cookie >= 0) && (cookie < bus->dev_count) &&
5803 	    (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
5804 		if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
5805 					val))
5806 			return cookie;
5807 
5808 	/*
5809 	 * cookie contained garbage; fall back to search and return the
5810 	 * correct cookie value.
5811 	 */
5812 	return __kvm_io_bus_write(vcpu, bus, &range, val);
5813 }
5814 
__kvm_io_bus_read(struct kvm_vcpu * vcpu,struct kvm_io_bus * bus,struct kvm_io_range * range,void * val)5815 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5816 			     struct kvm_io_range *range, void *val)
5817 {
5818 	int idx;
5819 
5820 	idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5821 	if (idx < 0)
5822 		return -EOPNOTSUPP;
5823 
5824 	while (idx < bus->dev_count &&
5825 		kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5826 		if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
5827 				       range->len, val))
5828 			return idx;
5829 		idx++;
5830 	}
5831 
5832 	return -EOPNOTSUPP;
5833 }
5834 
5835 /* 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)5836 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5837 		    int len, void *val)
5838 {
5839 	struct kvm_io_bus *bus;
5840 	struct kvm_io_range range;
5841 	int r;
5842 
5843 	range = (struct kvm_io_range) {
5844 		.addr = addr,
5845 		.len = len,
5846 	};
5847 
5848 	bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5849 	if (!bus)
5850 		return -ENOMEM;
5851 	r = __kvm_io_bus_read(vcpu, bus, &range, val);
5852 	return r < 0 ? r : 0;
5853 }
5854 
kvm_io_bus_register_dev(struct kvm * kvm,enum kvm_bus bus_idx,gpa_t addr,int len,struct kvm_io_device * dev)5855 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
5856 			    int len, struct kvm_io_device *dev)
5857 {
5858 	int i;
5859 	struct kvm_io_bus *new_bus, *bus;
5860 	struct kvm_io_range range;
5861 
5862 	lockdep_assert_held(&kvm->slots_lock);
5863 
5864 	bus = kvm_get_bus(kvm, bus_idx);
5865 	if (!bus)
5866 		return -ENOMEM;
5867 
5868 	/* exclude ioeventfd which is limited by maximum fd */
5869 	if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
5870 		return -ENOSPC;
5871 
5872 	new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
5873 			  GFP_KERNEL_ACCOUNT);
5874 	if (!new_bus)
5875 		return -ENOMEM;
5876 
5877 	range = (struct kvm_io_range) {
5878 		.addr = addr,
5879 		.len = len,
5880 		.dev = dev,
5881 	};
5882 
5883 	for (i = 0; i < bus->dev_count; i++)
5884 		if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
5885 			break;
5886 
5887 	memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
5888 	new_bus->dev_count++;
5889 	new_bus->range[i] = range;
5890 	memcpy(new_bus->range + i + 1, bus->range + i,
5891 		(bus->dev_count - i) * sizeof(struct kvm_io_range));
5892 	rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5893 	synchronize_srcu_expedited(&kvm->srcu);
5894 	kfree(bus);
5895 
5896 	return 0;
5897 }
5898 
kvm_io_bus_unregister_dev(struct kvm * kvm,enum kvm_bus bus_idx,struct kvm_io_device * dev)5899 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5900 			      struct kvm_io_device *dev)
5901 {
5902 	int i;
5903 	struct kvm_io_bus *new_bus, *bus;
5904 
5905 	lockdep_assert_held(&kvm->slots_lock);
5906 
5907 	bus = kvm_get_bus(kvm, bus_idx);
5908 	if (!bus)
5909 		return 0;
5910 
5911 	for (i = 0; i < bus->dev_count; i++) {
5912 		if (bus->range[i].dev == dev) {
5913 			break;
5914 		}
5915 	}
5916 
5917 	if (i == bus->dev_count)
5918 		return 0;
5919 
5920 	new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
5921 			  GFP_KERNEL_ACCOUNT);
5922 	if (new_bus) {
5923 		memcpy(new_bus, bus, struct_size(bus, range, i));
5924 		new_bus->dev_count--;
5925 		memcpy(new_bus->range + i, bus->range + i + 1,
5926 				flex_array_size(new_bus, range, new_bus->dev_count - i));
5927 	}
5928 
5929 	rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5930 	synchronize_srcu_expedited(&kvm->srcu);
5931 
5932 	/*
5933 	 * If NULL bus is installed, destroy the old bus, including all the
5934 	 * attached devices. Otherwise, destroy the caller's device only.
5935 	 */
5936 	if (!new_bus) {
5937 		pr_err("kvm: failed to shrink bus, removing it completely\n");
5938 		kvm_io_bus_destroy(bus);
5939 		return -ENOMEM;
5940 	}
5941 
5942 	kvm_iodevice_destructor(dev);
5943 	kfree(bus);
5944 	return 0;
5945 }
5946 
kvm_io_bus_get_dev(struct kvm * kvm,enum kvm_bus bus_idx,gpa_t addr)5947 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5948 					 gpa_t addr)
5949 {
5950 	struct kvm_io_bus *bus;
5951 	int dev_idx, srcu_idx;
5952 	struct kvm_io_device *iodev = NULL;
5953 
5954 	srcu_idx = srcu_read_lock(&kvm->srcu);
5955 
5956 	bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
5957 	if (!bus)
5958 		goto out_unlock;
5959 
5960 	dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5961 	if (dev_idx < 0)
5962 		goto out_unlock;
5963 
5964 	iodev = bus->range[dev_idx].dev;
5965 
5966 out_unlock:
5967 	srcu_read_unlock(&kvm->srcu, srcu_idx);
5968 
5969 	return iodev;
5970 }
5971 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5972 
kvm_debugfs_open(struct inode * inode,struct file * file,int (* get)(void *,u64 *),int (* set)(void *,u64),const char * fmt)5973 static int kvm_debugfs_open(struct inode *inode, struct file *file,
5974 			   int (*get)(void *, u64 *), int (*set)(void *, u64),
5975 			   const char *fmt)
5976 {
5977 	int ret;
5978 	struct kvm_stat_data *stat_data = inode->i_private;
5979 
5980 	/*
5981 	 * The debugfs files are a reference to the kvm struct which
5982         * is still valid when kvm_destroy_vm is called.  kvm_get_kvm_safe
5983         * avoids the race between open and the removal of the debugfs directory.
5984 	 */
5985 	if (!kvm_get_kvm_safe(stat_data->kvm))
5986 		return -ENOENT;
5987 
5988 	ret = simple_attr_open(inode, file, get,
5989 			       kvm_stats_debugfs_mode(stat_data->desc) & 0222
5990 			       ? set : NULL, fmt);
5991 	if (ret)
5992 		kvm_put_kvm(stat_data->kvm);
5993 
5994 	return ret;
5995 }
5996 
kvm_debugfs_release(struct inode * inode,struct file * file)5997 static int kvm_debugfs_release(struct inode *inode, struct file *file)
5998 {
5999 	struct kvm_stat_data *stat_data = inode->i_private;
6000 
6001 	simple_attr_release(inode, file);
6002 	kvm_put_kvm(stat_data->kvm);
6003 
6004 	return 0;
6005 }
6006 
kvm_get_stat_per_vm(struct kvm * kvm,size_t offset,u64 * val)6007 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
6008 {
6009 	*val = *(u64 *)((void *)(&kvm->stat) + offset);
6010 
6011 	return 0;
6012 }
6013 
kvm_clear_stat_per_vm(struct kvm * kvm,size_t offset)6014 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
6015 {
6016 	*(u64 *)((void *)(&kvm->stat) + offset) = 0;
6017 
6018 	return 0;
6019 }
6020 
kvm_get_stat_per_vcpu(struct kvm * kvm,size_t offset,u64 * val)6021 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
6022 {
6023 	unsigned long i;
6024 	struct kvm_vcpu *vcpu;
6025 
6026 	*val = 0;
6027 
6028 	kvm_for_each_vcpu(i, vcpu, kvm)
6029 		*val += *(u64 *)((void *)(&vcpu->stat) + offset);
6030 
6031 	return 0;
6032 }
6033 
kvm_clear_stat_per_vcpu(struct kvm * kvm,size_t offset)6034 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
6035 {
6036 	unsigned long i;
6037 	struct kvm_vcpu *vcpu;
6038 
6039 	kvm_for_each_vcpu(i, vcpu, kvm)
6040 		*(u64 *)((void *)(&vcpu->stat) + offset) = 0;
6041 
6042 	return 0;
6043 }
6044 
kvm_stat_data_get(void * data,u64 * val)6045 static int kvm_stat_data_get(void *data, u64 *val)
6046 {
6047 	int r = -EFAULT;
6048 	struct kvm_stat_data *stat_data = data;
6049 
6050 	switch (stat_data->kind) {
6051 	case KVM_STAT_VM:
6052 		r = kvm_get_stat_per_vm(stat_data->kvm,
6053 					stat_data->desc->desc.offset, val);
6054 		break;
6055 	case KVM_STAT_VCPU:
6056 		r = kvm_get_stat_per_vcpu(stat_data->kvm,
6057 					  stat_data->desc->desc.offset, val);
6058 		break;
6059 	}
6060 
6061 	return r;
6062 }
6063 
kvm_stat_data_clear(void * data,u64 val)6064 static int kvm_stat_data_clear(void *data, u64 val)
6065 {
6066 	int r = -EFAULT;
6067 	struct kvm_stat_data *stat_data = data;
6068 
6069 	if (val)
6070 		return -EINVAL;
6071 
6072 	switch (stat_data->kind) {
6073 	case KVM_STAT_VM:
6074 		r = kvm_clear_stat_per_vm(stat_data->kvm,
6075 					  stat_data->desc->desc.offset);
6076 		break;
6077 	case KVM_STAT_VCPU:
6078 		r = kvm_clear_stat_per_vcpu(stat_data->kvm,
6079 					    stat_data->desc->desc.offset);
6080 		break;
6081 	}
6082 
6083 	return r;
6084 }
6085 
kvm_stat_data_open(struct inode * inode,struct file * file)6086 static int kvm_stat_data_open(struct inode *inode, struct file *file)
6087 {
6088 	__simple_attr_check_format("%llu\n", 0ull);
6089 	return kvm_debugfs_open(inode, file, kvm_stat_data_get,
6090 				kvm_stat_data_clear, "%llu\n");
6091 }
6092 
6093 static const struct file_operations stat_fops_per_vm = {
6094 	.owner = THIS_MODULE,
6095 	.open = kvm_stat_data_open,
6096 	.release = kvm_debugfs_release,
6097 	.read = simple_attr_read,
6098 	.write = simple_attr_write,
6099 };
6100 
vm_stat_get(void * _offset,u64 * val)6101 static int vm_stat_get(void *_offset, u64 *val)
6102 {
6103 	unsigned offset = (long)_offset;
6104 	struct kvm *kvm;
6105 	u64 tmp_val;
6106 
6107 	*val = 0;
6108 	mutex_lock(&kvm_lock);
6109 	list_for_each_entry(kvm, &vm_list, vm_list) {
6110 		kvm_get_stat_per_vm(kvm, offset, &tmp_val);
6111 		*val += tmp_val;
6112 	}
6113 	mutex_unlock(&kvm_lock);
6114 	return 0;
6115 }
6116 
vm_stat_clear(void * _offset,u64 val)6117 static int vm_stat_clear(void *_offset, u64 val)
6118 {
6119 	unsigned offset = (long)_offset;
6120 	struct kvm *kvm;
6121 
6122 	if (val)
6123 		return -EINVAL;
6124 
6125 	mutex_lock(&kvm_lock);
6126 	list_for_each_entry(kvm, &vm_list, vm_list) {
6127 		kvm_clear_stat_per_vm(kvm, offset);
6128 	}
6129 	mutex_unlock(&kvm_lock);
6130 
6131 	return 0;
6132 }
6133 
6134 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
6135 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
6136 
vcpu_stat_get(void * _offset,u64 * val)6137 static int vcpu_stat_get(void *_offset, u64 *val)
6138 {
6139 	unsigned offset = (long)_offset;
6140 	struct kvm *kvm;
6141 	u64 tmp_val;
6142 
6143 	*val = 0;
6144 	mutex_lock(&kvm_lock);
6145 	list_for_each_entry(kvm, &vm_list, vm_list) {
6146 		kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
6147 		*val += tmp_val;
6148 	}
6149 	mutex_unlock(&kvm_lock);
6150 	return 0;
6151 }
6152 
vcpu_stat_clear(void * _offset,u64 val)6153 static int vcpu_stat_clear(void *_offset, u64 val)
6154 {
6155 	unsigned offset = (long)_offset;
6156 	struct kvm *kvm;
6157 
6158 	if (val)
6159 		return -EINVAL;
6160 
6161 	mutex_lock(&kvm_lock);
6162 	list_for_each_entry(kvm, &vm_list, vm_list) {
6163 		kvm_clear_stat_per_vcpu(kvm, offset);
6164 	}
6165 	mutex_unlock(&kvm_lock);
6166 
6167 	return 0;
6168 }
6169 
6170 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
6171 			"%llu\n");
6172 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
6173 
kvm_uevent_notify_change(unsigned int type,struct kvm * kvm)6174 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
6175 {
6176 	struct kobj_uevent_env *env;
6177 	unsigned long long created, active;
6178 
6179 	if (!kvm_dev.this_device || !kvm)
6180 		return;
6181 
6182 	mutex_lock(&kvm_lock);
6183 	if (type == KVM_EVENT_CREATE_VM) {
6184 		kvm_createvm_count++;
6185 		kvm_active_vms++;
6186 	} else if (type == KVM_EVENT_DESTROY_VM) {
6187 		kvm_active_vms--;
6188 	}
6189 	created = kvm_createvm_count;
6190 	active = kvm_active_vms;
6191 	mutex_unlock(&kvm_lock);
6192 
6193 	env = kzalloc(sizeof(*env), GFP_KERNEL);
6194 	if (!env)
6195 		return;
6196 
6197 	add_uevent_var(env, "CREATED=%llu", created);
6198 	add_uevent_var(env, "COUNT=%llu", active);
6199 
6200 	if (type == KVM_EVENT_CREATE_VM) {
6201 		add_uevent_var(env, "EVENT=create");
6202 		kvm->userspace_pid = task_pid_nr(current);
6203 	} else if (type == KVM_EVENT_DESTROY_VM) {
6204 		add_uevent_var(env, "EVENT=destroy");
6205 	}
6206 	add_uevent_var(env, "PID=%d", kvm->userspace_pid);
6207 
6208 	if (!IS_ERR(kvm->debugfs_dentry)) {
6209 		char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL);
6210 
6211 		if (p) {
6212 			tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
6213 			if (!IS_ERR(tmp))
6214 				add_uevent_var(env, "STATS_PATH=%s", tmp);
6215 			kfree(p);
6216 		}
6217 	}
6218 	/* no need for checks, since we are adding at most only 5 keys */
6219 	env->envp[env->envp_idx++] = NULL;
6220 	kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
6221 	kfree(env);
6222 }
6223 
kvm_init_debug(void)6224 static void kvm_init_debug(void)
6225 {
6226 	const struct file_operations *fops;
6227 	const struct _kvm_stats_desc *pdesc;
6228 	int i;
6229 
6230 	kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
6231 
6232 	for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
6233 		pdesc = &kvm_vm_stats_desc[i];
6234 		if (kvm_stats_debugfs_mode(pdesc) & 0222)
6235 			fops = &vm_stat_fops;
6236 		else
6237 			fops = &vm_stat_readonly_fops;
6238 		debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
6239 				kvm_debugfs_dir,
6240 				(void *)(long)pdesc->desc.offset, fops);
6241 	}
6242 
6243 	for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
6244 		pdesc = &kvm_vcpu_stats_desc[i];
6245 		if (kvm_stats_debugfs_mode(pdesc) & 0222)
6246 			fops = &vcpu_stat_fops;
6247 		else
6248 			fops = &vcpu_stat_readonly_fops;
6249 		debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
6250 				kvm_debugfs_dir,
6251 				(void *)(long)pdesc->desc.offset, fops);
6252 	}
6253 }
6254 
6255 static inline
preempt_notifier_to_vcpu(struct preempt_notifier * pn)6256 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
6257 {
6258 	return container_of(pn, struct kvm_vcpu, preempt_notifier);
6259 }
6260 
kvm_sched_in(struct preempt_notifier * pn,int cpu)6261 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
6262 {
6263 	struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
6264 
6265 	WRITE_ONCE(vcpu->preempted, false);
6266 	WRITE_ONCE(vcpu->ready, false);
6267 
6268 	__this_cpu_write(kvm_running_vcpu, vcpu);
6269 	kvm_arch_vcpu_load(vcpu, cpu);
6270 
6271 	WRITE_ONCE(vcpu->scheduled_out, false);
6272 }
6273 
kvm_sched_out(struct preempt_notifier * pn,struct task_struct * next)6274 static void kvm_sched_out(struct preempt_notifier *pn,
6275 			  struct task_struct *next)
6276 {
6277 	struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
6278 
6279 	WRITE_ONCE(vcpu->scheduled_out, true);
6280 
6281 	if (task_is_runnable(current) && vcpu->wants_to_run) {
6282 		WRITE_ONCE(vcpu->preempted, true);
6283 		WRITE_ONCE(vcpu->ready, true);
6284 	}
6285 	kvm_arch_vcpu_put(vcpu);
6286 	__this_cpu_write(kvm_running_vcpu, NULL);
6287 }
6288 
6289 /**
6290  * kvm_get_running_vcpu - get the vcpu running on the current CPU.
6291  *
6292  * We can disable preemption locally around accessing the per-CPU variable,
6293  * and use the resolved vcpu pointer after enabling preemption again,
6294  * because even if the current thread is migrated to another CPU, reading
6295  * the per-CPU value later will give us the same value as we update the
6296  * per-CPU variable in the preempt notifier handlers.
6297  */
kvm_get_running_vcpu(void)6298 struct kvm_vcpu *kvm_get_running_vcpu(void)
6299 {
6300 	struct kvm_vcpu *vcpu;
6301 
6302 	preempt_disable();
6303 	vcpu = __this_cpu_read(kvm_running_vcpu);
6304 	preempt_enable();
6305 
6306 	return vcpu;
6307 }
6308 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
6309 
6310 /**
6311  * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
6312  */
kvm_get_running_vcpus(void)6313 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
6314 {
6315         return &kvm_running_vcpu;
6316 }
6317 
6318 #ifdef CONFIG_GUEST_PERF_EVENTS
kvm_guest_state(void)6319 static unsigned int kvm_guest_state(void)
6320 {
6321 	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
6322 	unsigned int state;
6323 
6324 	if (!kvm_arch_pmi_in_guest(vcpu))
6325 		return 0;
6326 
6327 	state = PERF_GUEST_ACTIVE;
6328 	if (!kvm_arch_vcpu_in_kernel(vcpu))
6329 		state |= PERF_GUEST_USER;
6330 
6331 	return state;
6332 }
6333 
kvm_guest_get_ip(void)6334 static unsigned long kvm_guest_get_ip(void)
6335 {
6336 	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
6337 
6338 	/* Retrieving the IP must be guarded by a call to kvm_guest_state(). */
6339 	if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu)))
6340 		return 0;
6341 
6342 	return kvm_arch_vcpu_get_ip(vcpu);
6343 }
6344 
6345 static struct perf_guest_info_callbacks kvm_guest_cbs = {
6346 	.state			= kvm_guest_state,
6347 	.get_ip			= kvm_guest_get_ip,
6348 	.handle_intel_pt_intr	= NULL,
6349 };
6350 
kvm_register_perf_callbacks(unsigned int (* pt_intr_handler)(void))6351 void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void))
6352 {
6353 	kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler;
6354 	perf_register_guest_info_callbacks(&kvm_guest_cbs);
6355 }
kvm_unregister_perf_callbacks(void)6356 void kvm_unregister_perf_callbacks(void)
6357 {
6358 	perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6359 }
6360 #endif
6361 
kvm_init(unsigned vcpu_size,unsigned vcpu_align,struct module * module)6362 int kvm_init(unsigned vcpu_size, unsigned vcpu_align, struct module *module)
6363 {
6364 	int r;
6365 	int cpu;
6366 
6367 	/* A kmem cache lets us meet the alignment requirements of fx_save. */
6368 	if (!vcpu_align)
6369 		vcpu_align = __alignof__(struct kvm_vcpu);
6370 	kvm_vcpu_cache =
6371 		kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
6372 					   SLAB_ACCOUNT,
6373 					   offsetof(struct kvm_vcpu, arch),
6374 					   offsetofend(struct kvm_vcpu, stats_id)
6375 					   - offsetof(struct kvm_vcpu, arch),
6376 					   NULL);
6377 	if (!kvm_vcpu_cache)
6378 		return -ENOMEM;
6379 
6380 	for_each_possible_cpu(cpu) {
6381 		if (!alloc_cpumask_var_node(&per_cpu(cpu_kick_mask, cpu),
6382 					    GFP_KERNEL, cpu_to_node(cpu))) {
6383 			r = -ENOMEM;
6384 			goto err_cpu_kick_mask;
6385 		}
6386 	}
6387 
6388 	r = kvm_irqfd_init();
6389 	if (r)
6390 		goto err_irqfd;
6391 
6392 	r = kvm_async_pf_init();
6393 	if (r)
6394 		goto err_async_pf;
6395 
6396 	kvm_chardev_ops.owner = module;
6397 	kvm_vm_fops.owner = module;
6398 	kvm_vcpu_fops.owner = module;
6399 	kvm_device_fops.owner = module;
6400 
6401 	kvm_preempt_ops.sched_in = kvm_sched_in;
6402 	kvm_preempt_ops.sched_out = kvm_sched_out;
6403 
6404 	kvm_init_debug();
6405 
6406 	r = kvm_vfio_ops_init();
6407 	if (WARN_ON_ONCE(r))
6408 		goto err_vfio;
6409 
6410 	kvm_gmem_init(module);
6411 
6412 	r = kvm_init_virtualization();
6413 	if (r)
6414 		goto err_virt;
6415 
6416 	/*
6417 	 * Registration _must_ be the very last thing done, as this exposes
6418 	 * /dev/kvm to userspace, i.e. all infrastructure must be setup!
6419 	 */
6420 	r = misc_register(&kvm_dev);
6421 	if (r) {
6422 		pr_err("kvm: misc device register failed\n");
6423 		goto err_register;
6424 	}
6425 
6426 	return 0;
6427 
6428 err_register:
6429 	kvm_uninit_virtualization();
6430 err_virt:
6431 	kvm_vfio_ops_exit();
6432 err_vfio:
6433 	kvm_async_pf_deinit();
6434 err_async_pf:
6435 	kvm_irqfd_exit();
6436 err_irqfd:
6437 err_cpu_kick_mask:
6438 	for_each_possible_cpu(cpu)
6439 		free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
6440 	kmem_cache_destroy(kvm_vcpu_cache);
6441 	return r;
6442 }
6443 EXPORT_SYMBOL_GPL(kvm_init);
6444 
kvm_exit(void)6445 void kvm_exit(void)
6446 {
6447 	int cpu;
6448 
6449 	/*
6450 	 * Note, unregistering /dev/kvm doesn't strictly need to come first,
6451 	 * fops_get(), a.k.a. try_module_get(), prevents acquiring references
6452 	 * to KVM while the module is being stopped.
6453 	 */
6454 	misc_deregister(&kvm_dev);
6455 
6456 	kvm_uninit_virtualization();
6457 
6458 	debugfs_remove_recursive(kvm_debugfs_dir);
6459 	for_each_possible_cpu(cpu)
6460 		free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
6461 	kmem_cache_destroy(kvm_vcpu_cache);
6462 	kvm_vfio_ops_exit();
6463 	kvm_async_pf_deinit();
6464 	kvm_irqfd_exit();
6465 }
6466 EXPORT_SYMBOL_GPL(kvm_exit);
6467