xref: /linux/drivers/vhost/vhost.c (revision b1e06c19abd2efbdd080047b2e70195c04ac2139)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (C) 2009 Red Hat, Inc.
3  * Copyright (C) 2006 Rusty Russell IBM Corporation
4  *
5  * Author: Michael S. Tsirkin <mst@redhat.com>
6  *
7  * Inspiration, some code, and most witty comments come from
8  * Documentation/virtual/lguest/lguest.c, by Rusty Russell
9  *
10  * Generic code for virtio server in host kernel.
11  */
12 
13 #include <linux/eventfd.h>
14 #include <linux/vhost.h>
15 #include <linux/uio.h>
16 #include <linux/mm.h>
17 #include <linux/miscdevice.h>
18 #include <linux/mutex.h>
19 #include <linux/poll.h>
20 #include <linux/file.h>
21 #include <linux/highmem.h>
22 #include <linux/slab.h>
23 #include <linux/vmalloc.h>
24 #include <linux/kthread.h>
25 #include <linux/cgroup.h>
26 #include <linux/module.h>
27 #include <linux/sort.h>
28 #include <linux/sched/mm.h>
29 #include <linux/sched/signal.h>
30 #include <linux/sched/vhost_task.h>
31 #include <linux/interval_tree_generic.h>
32 #include <linux/nospec.h>
33 #include <linux/kcov.h>
34 
35 #include "vhost.h"
36 
37 static ushort max_mem_regions = 64;
38 module_param(max_mem_regions, ushort, 0444);
39 MODULE_PARM_DESC(max_mem_regions,
40 	"Maximum number of memory regions in memory map. (default: 64)");
41 static int max_iotlb_entries = 2048;
42 module_param(max_iotlb_entries, int, 0444);
43 MODULE_PARM_DESC(max_iotlb_entries,
44 	"Maximum number of iotlb entries. (default: 2048)");
45 static bool fork_from_owner_default = VHOST_FORK_OWNER_TASK;
46 
47 #ifdef CONFIG_VHOST_ENABLE_FORK_OWNER_CONTROL
48 module_param(fork_from_owner_default, bool, 0444);
49 MODULE_PARM_DESC(fork_from_owner_default,
50 		 "Set task mode as the default(default: Y)");
51 #endif
52 
53 enum {
54 	VHOST_MEMORY_F_LOG = 0x1,
55 };
56 
57 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
58 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
59 
60 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
vhost_disable_cross_endian(struct vhost_virtqueue * vq)61 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
62 {
63 	vq->user_be = !virtio_legacy_is_little_endian();
64 }
65 
vhost_enable_cross_endian_big(struct vhost_virtqueue * vq)66 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
67 {
68 	vq->user_be = true;
69 }
70 
vhost_enable_cross_endian_little(struct vhost_virtqueue * vq)71 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
72 {
73 	vq->user_be = false;
74 }
75 
vhost_set_vring_endian(struct vhost_virtqueue * vq,int __user * argp)76 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
77 {
78 	struct vhost_vring_state s;
79 
80 	if (vq->private_data)
81 		return -EBUSY;
82 
83 	if (copy_from_user(&s, argp, sizeof(s)))
84 		return -EFAULT;
85 
86 	if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
87 	    s.num != VHOST_VRING_BIG_ENDIAN)
88 		return -EINVAL;
89 
90 	if (s.num == VHOST_VRING_BIG_ENDIAN)
91 		vhost_enable_cross_endian_big(vq);
92 	else
93 		vhost_enable_cross_endian_little(vq);
94 
95 	return 0;
96 }
97 
vhost_get_vring_endian(struct vhost_virtqueue * vq,u32 idx,int __user * argp)98 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
99 				   int __user *argp)
100 {
101 	struct vhost_vring_state s = {
102 		.index = idx,
103 		.num = vq->user_be
104 	};
105 
106 	if (copy_to_user(argp, &s, sizeof(s)))
107 		return -EFAULT;
108 
109 	return 0;
110 }
111 
vhost_init_is_le(struct vhost_virtqueue * vq)112 static void vhost_init_is_le(struct vhost_virtqueue *vq)
113 {
114 	/* Note for legacy virtio: user_be is initialized at reset time
115 	 * according to the host endianness. If userspace does not set an
116 	 * explicit endianness, the default behavior is native endian, as
117 	 * expected by legacy virtio.
118 	 */
119 	vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
120 }
121 #else
vhost_disable_cross_endian(struct vhost_virtqueue * vq)122 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
123 {
124 }
125 
vhost_set_vring_endian(struct vhost_virtqueue * vq,int __user * argp)126 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
127 {
128 	return -ENOIOCTLCMD;
129 }
130 
vhost_get_vring_endian(struct vhost_virtqueue * vq,u32 idx,int __user * argp)131 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
132 				   int __user *argp)
133 {
134 	return -ENOIOCTLCMD;
135 }
136 
vhost_init_is_le(struct vhost_virtqueue * vq)137 static void vhost_init_is_le(struct vhost_virtqueue *vq)
138 {
139 	vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
140 		|| virtio_legacy_is_little_endian();
141 }
142 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
143 
vhost_reset_is_le(struct vhost_virtqueue * vq)144 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
145 {
146 	vhost_init_is_le(vq);
147 }
148 
149 struct vhost_flush_struct {
150 	struct vhost_work work;
151 	struct completion wait_event;
152 };
153 
vhost_flush_work(struct vhost_work * work)154 static void vhost_flush_work(struct vhost_work *work)
155 {
156 	struct vhost_flush_struct *s;
157 
158 	s = container_of(work, struct vhost_flush_struct, work);
159 	complete(&s->wait_event);
160 }
161 
vhost_poll_func(struct file * file,wait_queue_head_t * wqh,poll_table * pt)162 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
163 			    poll_table *pt)
164 {
165 	struct vhost_poll *poll;
166 
167 	poll = container_of(pt, struct vhost_poll, table);
168 	poll->wqh = wqh;
169 	add_wait_queue(wqh, &poll->wait);
170 }
171 
vhost_poll_wakeup(wait_queue_entry_t * wait,unsigned mode,int sync,void * key)172 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
173 			     void *key)
174 {
175 	struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
176 	struct vhost_work *work = &poll->work;
177 
178 	if (!(key_to_poll(key) & poll->mask))
179 		return 0;
180 
181 	if (!poll->dev->use_worker)
182 		work->fn(work);
183 	else
184 		vhost_poll_queue(poll);
185 
186 	return 0;
187 }
188 
vhost_work_init(struct vhost_work * work,vhost_work_fn_t fn)189 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
190 {
191 	clear_bit(VHOST_WORK_QUEUED, &work->flags);
192 	work->fn = fn;
193 }
194 EXPORT_SYMBOL_GPL(vhost_work_init);
195 
196 /* Init poll structure */
vhost_poll_init(struct vhost_poll * poll,vhost_work_fn_t fn,__poll_t mask,struct vhost_dev * dev,struct vhost_virtqueue * vq)197 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
198 		     __poll_t mask, struct vhost_dev *dev,
199 		     struct vhost_virtqueue *vq)
200 {
201 	init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
202 	init_poll_funcptr(&poll->table, vhost_poll_func);
203 	poll->mask = mask;
204 	poll->dev = dev;
205 	poll->wqh = NULL;
206 	poll->vq = vq;
207 
208 	vhost_work_init(&poll->work, fn);
209 }
210 EXPORT_SYMBOL_GPL(vhost_poll_init);
211 
212 /* Start polling a file. We add ourselves to file's wait queue. The caller must
213  * keep a reference to a file until after vhost_poll_stop is called. */
vhost_poll_start(struct vhost_poll * poll,struct file * file)214 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
215 {
216 	__poll_t mask;
217 
218 	if (poll->wqh)
219 		return 0;
220 
221 	mask = vfs_poll(file, &poll->table);
222 	if (mask)
223 		vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
224 	if (mask & EPOLLERR) {
225 		vhost_poll_stop(poll);
226 		return -EINVAL;
227 	}
228 
229 	return 0;
230 }
231 EXPORT_SYMBOL_GPL(vhost_poll_start);
232 
233 /* Stop polling a file. After this function returns, it becomes safe to drop the
234  * file reference. You must also flush afterwards. */
vhost_poll_stop(struct vhost_poll * poll)235 void vhost_poll_stop(struct vhost_poll *poll)
236 {
237 	if (poll->wqh) {
238 		remove_wait_queue(poll->wqh, &poll->wait);
239 		poll->wqh = NULL;
240 	}
241 }
242 EXPORT_SYMBOL_GPL(vhost_poll_stop);
243 
vhost_worker_queue(struct vhost_worker * worker,struct vhost_work * work)244 static void vhost_worker_queue(struct vhost_worker *worker,
245 			       struct vhost_work *work)
246 {
247 	if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
248 		/* We can only add the work to the list after we're
249 		 * sure it was not in the list.
250 		 * test_and_set_bit() implies a memory barrier.
251 		 */
252 		llist_add(&work->node, &worker->work_list);
253 		worker->ops->wakeup(worker);
254 	}
255 }
256 
vhost_vq_work_queue(struct vhost_virtqueue * vq,struct vhost_work * work)257 bool vhost_vq_work_queue(struct vhost_virtqueue *vq, struct vhost_work *work)
258 {
259 	struct vhost_worker *worker;
260 	bool queued = false;
261 
262 	rcu_read_lock();
263 	worker = rcu_dereference(vq->worker);
264 	if (worker) {
265 		queued = true;
266 		vhost_worker_queue(worker, work);
267 	}
268 	rcu_read_unlock();
269 
270 	return queued;
271 }
272 EXPORT_SYMBOL_GPL(vhost_vq_work_queue);
273 
274 /**
275  * __vhost_worker_flush - flush a worker
276  * @worker: worker to flush
277  *
278  * The worker's flush_mutex must be held.
279  */
__vhost_worker_flush(struct vhost_worker * worker)280 static void __vhost_worker_flush(struct vhost_worker *worker)
281 {
282 	struct vhost_flush_struct flush;
283 
284 	if (!worker->attachment_cnt || worker->killed)
285 		return;
286 
287 	init_completion(&flush.wait_event);
288 	vhost_work_init(&flush.work, vhost_flush_work);
289 
290 	vhost_worker_queue(worker, &flush.work);
291 	/*
292 	 * Drop mutex in case our worker is killed and it needs to take the
293 	 * mutex to force cleanup.
294 	 */
295 	mutex_unlock(&worker->mutex);
296 	wait_for_completion(&flush.wait_event);
297 	mutex_lock(&worker->mutex);
298 }
299 
vhost_worker_flush(struct vhost_worker * worker)300 static void vhost_worker_flush(struct vhost_worker *worker)
301 {
302 	mutex_lock(&worker->mutex);
303 	__vhost_worker_flush(worker);
304 	mutex_unlock(&worker->mutex);
305 }
306 
vhost_dev_flush(struct vhost_dev * dev)307 void vhost_dev_flush(struct vhost_dev *dev)
308 {
309 	struct vhost_worker *worker;
310 	unsigned long i;
311 
312 	xa_for_each(&dev->worker_xa, i, worker)
313 		vhost_worker_flush(worker);
314 }
315 EXPORT_SYMBOL_GPL(vhost_dev_flush);
316 
317 /* A lockless hint for busy polling code to exit the loop */
vhost_vq_has_work(struct vhost_virtqueue * vq)318 bool vhost_vq_has_work(struct vhost_virtqueue *vq)
319 {
320 	struct vhost_worker *worker;
321 	bool has_work = false;
322 
323 	rcu_read_lock();
324 	worker = rcu_dereference(vq->worker);
325 	if (worker && !llist_empty(&worker->work_list))
326 		has_work = true;
327 	rcu_read_unlock();
328 
329 	return has_work;
330 }
331 EXPORT_SYMBOL_GPL(vhost_vq_has_work);
332 
vhost_poll_queue(struct vhost_poll * poll)333 void vhost_poll_queue(struct vhost_poll *poll)
334 {
335 	vhost_vq_work_queue(poll->vq, &poll->work);
336 }
337 EXPORT_SYMBOL_GPL(vhost_poll_queue);
338 
__vhost_vq_meta_reset(struct vhost_virtqueue * vq)339 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
340 {
341 	int j;
342 
343 	for (j = 0; j < VHOST_NUM_ADDRS; j++)
344 		vq->meta_iotlb[j] = NULL;
345 }
346 
vhost_vq_meta_reset(struct vhost_dev * d)347 static void vhost_vq_meta_reset(struct vhost_dev *d)
348 {
349 	int i;
350 
351 	for (i = 0; i < d->nvqs; ++i)
352 		__vhost_vq_meta_reset(d->vqs[i]);
353 }
354 
vhost_vring_call_reset(struct vhost_vring_call * call_ctx)355 static void vhost_vring_call_reset(struct vhost_vring_call *call_ctx)
356 {
357 	call_ctx->ctx = NULL;
358 	memset(&call_ctx->producer, 0x0, sizeof(struct irq_bypass_producer));
359 }
360 
vhost_vq_is_setup(struct vhost_virtqueue * vq)361 bool vhost_vq_is_setup(struct vhost_virtqueue *vq)
362 {
363 	return vq->avail && vq->desc && vq->used && vhost_vq_access_ok(vq);
364 }
365 EXPORT_SYMBOL_GPL(vhost_vq_is_setup);
366 
vhost_vq_reset(struct vhost_dev * dev,struct vhost_virtqueue * vq)367 static void vhost_vq_reset(struct vhost_dev *dev,
368 			   struct vhost_virtqueue *vq)
369 {
370 	vq->num = 1;
371 	vq->desc = NULL;
372 	vq->avail = NULL;
373 	vq->used = NULL;
374 	vq->last_avail_idx = 0;
375 	vq->next_avail_head = 0;
376 	vq->avail_idx = 0;
377 	vq->last_used_idx = 0;
378 	vq->signalled_used = 0;
379 	vq->signalled_used_valid = false;
380 	vq->used_flags = 0;
381 	vq->log_used = false;
382 	vq->log_addr = -1ull;
383 	vq->private_data = NULL;
384 	virtio_features_zero(vq->acked_features_array);
385 	vq->acked_backend_features = 0;
386 	vq->log_base = NULL;
387 	vq->error_ctx = NULL;
388 	vq->kick = NULL;
389 	vq->log_ctx = NULL;
390 	vhost_disable_cross_endian(vq);
391 	vhost_reset_is_le(vq);
392 	vq->busyloop_timeout = 0;
393 	vq->umem = NULL;
394 	vq->iotlb = NULL;
395 	rcu_assign_pointer(vq->worker, NULL);
396 	vhost_vring_call_reset(&vq->call_ctx);
397 	__vhost_vq_meta_reset(vq);
398 }
399 
vhost_run_work_kthread_list(void * data)400 static int vhost_run_work_kthread_list(void *data)
401 {
402 	struct vhost_worker *worker = data;
403 	struct vhost_work *work, *work_next;
404 	struct vhost_dev *dev = worker->dev;
405 	struct llist_node *node;
406 
407 	kthread_use_mm(dev->mm);
408 
409 	for (;;) {
410 		/* mb paired w/ kthread_stop */
411 		set_current_state(TASK_INTERRUPTIBLE);
412 
413 		if (kthread_should_stop()) {
414 			__set_current_state(TASK_RUNNING);
415 			break;
416 		}
417 		node = llist_del_all(&worker->work_list);
418 		if (!node)
419 			schedule();
420 
421 		node = llist_reverse_order(node);
422 		/* make sure flag is seen after deletion */
423 		smp_wmb();
424 		llist_for_each_entry_safe(work, work_next, node, node) {
425 			clear_bit(VHOST_WORK_QUEUED, &work->flags);
426 			__set_current_state(TASK_RUNNING);
427 			kcov_remote_start_common(worker->kcov_handle);
428 			work->fn(work);
429 			kcov_remote_stop();
430 			cond_resched();
431 		}
432 	}
433 	kthread_unuse_mm(dev->mm);
434 
435 	return 0;
436 }
437 
vhost_run_work_list(void * data)438 static bool vhost_run_work_list(void *data)
439 {
440 	struct vhost_worker *worker = data;
441 	struct vhost_work *work, *work_next;
442 	struct llist_node *node;
443 
444 	node = llist_del_all(&worker->work_list);
445 	if (node) {
446 		__set_current_state(TASK_RUNNING);
447 
448 		node = llist_reverse_order(node);
449 		/* make sure flag is seen after deletion */
450 		smp_wmb();
451 		llist_for_each_entry_safe(work, work_next, node, node) {
452 			clear_bit(VHOST_WORK_QUEUED, &work->flags);
453 			kcov_remote_start_common(worker->kcov_handle);
454 			work->fn(work);
455 			kcov_remote_stop();
456 			cond_resched();
457 		}
458 	}
459 
460 	return !!node;
461 }
462 
vhost_worker_killed(void * data)463 static void vhost_worker_killed(void *data)
464 {
465 	struct vhost_worker *worker = data;
466 	struct vhost_dev *dev = worker->dev;
467 	struct vhost_virtqueue *vq;
468 	int i, attach_cnt = 0;
469 
470 	mutex_lock(&worker->mutex);
471 	worker->killed = true;
472 
473 	for (i = 0; i < dev->nvqs; i++) {
474 		vq = dev->vqs[i];
475 
476 		mutex_lock(&vq->mutex);
477 		if (worker ==
478 		    rcu_dereference_check(vq->worker,
479 					  lockdep_is_held(&vq->mutex))) {
480 			rcu_assign_pointer(vq->worker, NULL);
481 			attach_cnt++;
482 		}
483 		mutex_unlock(&vq->mutex);
484 	}
485 
486 	worker->attachment_cnt -= attach_cnt;
487 	if (attach_cnt)
488 		synchronize_rcu();
489 	/*
490 	 * Finish vhost_worker_flush calls and any other works that snuck in
491 	 * before the synchronize_rcu.
492 	 */
493 	vhost_run_work_list(worker);
494 	mutex_unlock(&worker->mutex);
495 }
496 
vhost_vq_free_iovecs(struct vhost_virtqueue * vq)497 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
498 {
499 	kfree(vq->indirect);
500 	vq->indirect = NULL;
501 	kfree(vq->log);
502 	vq->log = NULL;
503 	kfree(vq->heads);
504 	vq->heads = NULL;
505 	kfree(vq->nheads);
506 	vq->nheads = NULL;
507 }
508 
509 /* Helper to allocate iovec buffers for all vqs. */
vhost_dev_alloc_iovecs(struct vhost_dev * dev)510 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
511 {
512 	struct vhost_virtqueue *vq;
513 	int i;
514 
515 	for (i = 0; i < dev->nvqs; ++i) {
516 		vq = dev->vqs[i];
517 		vq->indirect = kmalloc_array(UIO_MAXIOV,
518 					     sizeof(*vq->indirect),
519 					     GFP_KERNEL);
520 		vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
521 					GFP_KERNEL);
522 		vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
523 					  GFP_KERNEL);
524 		vq->nheads = kmalloc_array(dev->iov_limit, sizeof(*vq->nheads),
525 					   GFP_KERNEL);
526 		if (!vq->indirect || !vq->log || !vq->heads || !vq->nheads)
527 			goto err_nomem;
528 	}
529 	return 0;
530 
531 err_nomem:
532 	for (; i >= 0; --i)
533 		vhost_vq_free_iovecs(dev->vqs[i]);
534 	return -ENOMEM;
535 }
536 
vhost_dev_free_iovecs(struct vhost_dev * dev)537 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
538 {
539 	int i;
540 
541 	for (i = 0; i < dev->nvqs; ++i)
542 		vhost_vq_free_iovecs(dev->vqs[i]);
543 }
544 
vhost_exceeds_weight(struct vhost_virtqueue * vq,int pkts,int total_len)545 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
546 			  int pkts, int total_len)
547 {
548 	struct vhost_dev *dev = vq->dev;
549 
550 	if ((dev->byte_weight && total_len >= dev->byte_weight) ||
551 	    pkts >= dev->weight) {
552 		vhost_poll_queue(&vq->poll);
553 		return true;
554 	}
555 
556 	return false;
557 }
558 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
559 
vhost_get_avail_size(struct vhost_virtqueue * vq,unsigned int num)560 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
561 				   unsigned int num)
562 {
563 	size_t event __maybe_unused =
564 	       vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
565 
566 	return size_add(struct_size(vq->avail, ring, num), event);
567 }
568 
vhost_get_used_size(struct vhost_virtqueue * vq,unsigned int num)569 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
570 				  unsigned int num)
571 {
572 	size_t event __maybe_unused =
573 	       vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
574 
575 	return size_add(struct_size(vq->used, ring, num), event);
576 }
577 
vhost_get_desc_size(struct vhost_virtqueue * vq,unsigned int num)578 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
579 				  unsigned int num)
580 {
581 	return sizeof(*vq->desc) * num;
582 }
583 
vhost_dev_init(struct vhost_dev * dev,struct vhost_virtqueue ** vqs,int nvqs,int iov_limit,int weight,int byte_weight,bool use_worker,int (* msg_handler)(struct vhost_dev * dev,u32 asid,struct vhost_iotlb_msg * msg))584 void vhost_dev_init(struct vhost_dev *dev,
585 		    struct vhost_virtqueue **vqs, int nvqs,
586 		    int iov_limit, int weight, int byte_weight,
587 		    bool use_worker,
588 		    int (*msg_handler)(struct vhost_dev *dev, u32 asid,
589 				       struct vhost_iotlb_msg *msg))
590 {
591 	struct vhost_virtqueue *vq;
592 	int i;
593 
594 	dev->vqs = vqs;
595 	dev->nvqs = nvqs;
596 	mutex_init(&dev->mutex);
597 	dev->log_ctx = NULL;
598 	dev->umem = NULL;
599 	dev->iotlb = NULL;
600 	dev->mm = NULL;
601 	dev->iov_limit = iov_limit;
602 	dev->weight = weight;
603 	dev->byte_weight = byte_weight;
604 	dev->use_worker = use_worker;
605 	dev->msg_handler = msg_handler;
606 	dev->fork_owner = fork_from_owner_default;
607 	init_waitqueue_head(&dev->wait);
608 	INIT_LIST_HEAD(&dev->read_list);
609 	INIT_LIST_HEAD(&dev->pending_list);
610 	spin_lock_init(&dev->iotlb_lock);
611 	xa_init_flags(&dev->worker_xa, XA_FLAGS_ALLOC);
612 
613 	for (i = 0; i < dev->nvqs; ++i) {
614 		vq = dev->vqs[i];
615 		vq->log = NULL;
616 		vq->indirect = NULL;
617 		vq->heads = NULL;
618 		vq->nheads = NULL;
619 		vq->dev = dev;
620 		mutex_init(&vq->mutex);
621 		vhost_vq_reset(dev, vq);
622 		if (vq->handle_kick)
623 			vhost_poll_init(&vq->poll, vq->handle_kick,
624 					EPOLLIN, dev, vq);
625 	}
626 }
627 EXPORT_SYMBOL_GPL(vhost_dev_init);
628 
629 /* Caller should have device mutex */
vhost_dev_check_owner(struct vhost_dev * dev)630 long vhost_dev_check_owner(struct vhost_dev *dev)
631 {
632 	/* Are you the owner? If not, I don't think you mean to do that */
633 	return dev->mm == current->mm ? 0 : -EPERM;
634 }
635 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
636 
637 struct vhost_attach_cgroups_struct {
638 	struct vhost_work work;
639 	struct task_struct *owner;
640 	int ret;
641 };
642 
vhost_attach_cgroups_work(struct vhost_work * work)643 static void vhost_attach_cgroups_work(struct vhost_work *work)
644 {
645 	struct vhost_attach_cgroups_struct *s;
646 
647 	s = container_of(work, struct vhost_attach_cgroups_struct, work);
648 	s->ret = cgroup_attach_task_all(s->owner, current);
649 }
650 
vhost_attach_task_to_cgroups(struct vhost_worker * worker)651 static int vhost_attach_task_to_cgroups(struct vhost_worker *worker)
652 {
653 	struct vhost_attach_cgroups_struct attach;
654 	int saved_cnt;
655 
656 	attach.owner = current;
657 
658 	vhost_work_init(&attach.work, vhost_attach_cgroups_work);
659 	vhost_worker_queue(worker, &attach.work);
660 
661 	mutex_lock(&worker->mutex);
662 
663 	/*
664 	 * Bypass attachment_cnt check in __vhost_worker_flush:
665 	 * Temporarily change it to INT_MAX to bypass the check
666 	 */
667 	saved_cnt = worker->attachment_cnt;
668 	worker->attachment_cnt = INT_MAX;
669 	__vhost_worker_flush(worker);
670 	worker->attachment_cnt = saved_cnt;
671 
672 	mutex_unlock(&worker->mutex);
673 
674 	return attach.ret;
675 }
676 
677 /* Caller should have device mutex */
vhost_dev_has_owner(struct vhost_dev * dev)678 bool vhost_dev_has_owner(struct vhost_dev *dev)
679 {
680 	return dev->mm;
681 }
682 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
683 
vhost_attach_mm(struct vhost_dev * dev)684 static void vhost_attach_mm(struct vhost_dev *dev)
685 {
686 	/* No owner, become one */
687 	if (dev->use_worker) {
688 		dev->mm = get_task_mm(current);
689 	} else {
690 		/* vDPA device does not use worker thread, so there's
691 		 * no need to hold the address space for mm. This helps
692 		 * to avoid deadlock in the case of mmap() which may
693 		 * hold the refcnt of the file and depends on release
694 		 * method to remove vma.
695 		 */
696 		dev->mm = current->mm;
697 		mmgrab(dev->mm);
698 	}
699 }
700 
vhost_detach_mm(struct vhost_dev * dev)701 static void vhost_detach_mm(struct vhost_dev *dev)
702 {
703 	if (!dev->mm)
704 		return;
705 
706 	if (dev->use_worker)
707 		mmput(dev->mm);
708 	else
709 		mmdrop(dev->mm);
710 
711 	dev->mm = NULL;
712 }
713 
vhost_worker_destroy(struct vhost_dev * dev,struct vhost_worker * worker)714 static void vhost_worker_destroy(struct vhost_dev *dev,
715 				 struct vhost_worker *worker)
716 {
717 	if (!worker)
718 		return;
719 
720 	WARN_ON(!llist_empty(&worker->work_list));
721 	xa_erase(&dev->worker_xa, worker->id);
722 	worker->ops->stop(worker);
723 	kfree(worker);
724 }
725 
vhost_workers_free(struct vhost_dev * dev)726 static void vhost_workers_free(struct vhost_dev *dev)
727 {
728 	struct vhost_worker *worker;
729 	unsigned long i;
730 
731 	if (!dev->use_worker)
732 		return;
733 
734 	for (i = 0; i < dev->nvqs; i++)
735 		rcu_assign_pointer(dev->vqs[i]->worker, NULL);
736 	/*
737 	 * Free the default worker we created and cleanup workers userspace
738 	 * created but couldn't clean up (it forgot or crashed).
739 	 */
740 	xa_for_each(&dev->worker_xa, i, worker)
741 		vhost_worker_destroy(dev, worker);
742 	xa_destroy(&dev->worker_xa);
743 }
744 
vhost_task_wakeup(struct vhost_worker * worker)745 static void vhost_task_wakeup(struct vhost_worker *worker)
746 {
747 	return vhost_task_wake(worker->vtsk);
748 }
749 
vhost_kthread_wakeup(struct vhost_worker * worker)750 static void vhost_kthread_wakeup(struct vhost_worker *worker)
751 {
752 	wake_up_process(worker->kthread_task);
753 }
754 
vhost_task_do_stop(struct vhost_worker * worker)755 static void vhost_task_do_stop(struct vhost_worker *worker)
756 {
757 	return vhost_task_stop(worker->vtsk);
758 }
759 
vhost_kthread_do_stop(struct vhost_worker * worker)760 static void vhost_kthread_do_stop(struct vhost_worker *worker)
761 {
762 	kthread_stop(worker->kthread_task);
763 }
764 
vhost_task_worker_create(struct vhost_worker * worker,struct vhost_dev * dev,const char * name)765 static int vhost_task_worker_create(struct vhost_worker *worker,
766 				    struct vhost_dev *dev, const char *name)
767 {
768 	struct vhost_task *vtsk;
769 	u32 id;
770 	int ret;
771 
772 	vtsk = vhost_task_create(vhost_run_work_list, vhost_worker_killed,
773 				 worker, name);
774 	if (IS_ERR(vtsk))
775 		return PTR_ERR(vtsk);
776 
777 	worker->vtsk = vtsk;
778 	vhost_task_start(vtsk);
779 	ret = xa_alloc(&dev->worker_xa, &id, worker, xa_limit_32b, GFP_KERNEL);
780 	if (ret < 0) {
781 		vhost_task_do_stop(worker);
782 		return ret;
783 	}
784 	worker->id = id;
785 	return 0;
786 }
787 
vhost_kthread_worker_create(struct vhost_worker * worker,struct vhost_dev * dev,const char * name)788 static int vhost_kthread_worker_create(struct vhost_worker *worker,
789 				       struct vhost_dev *dev, const char *name)
790 {
791 	struct task_struct *task;
792 	u32 id;
793 	int ret;
794 
795 	task = kthread_create(vhost_run_work_kthread_list, worker, "%s", name);
796 	if (IS_ERR(task))
797 		return PTR_ERR(task);
798 
799 	worker->kthread_task = task;
800 	wake_up_process(task);
801 	ret = xa_alloc(&dev->worker_xa, &id, worker, xa_limit_32b, GFP_KERNEL);
802 	if (ret < 0)
803 		goto stop_worker;
804 
805 	ret = vhost_attach_task_to_cgroups(worker);
806 	if (ret)
807 		goto stop_worker;
808 
809 	worker->id = id;
810 	return 0;
811 
812 stop_worker:
813 	vhost_kthread_do_stop(worker);
814 	return ret;
815 }
816 
817 static const struct vhost_worker_ops kthread_ops = {
818 	.create = vhost_kthread_worker_create,
819 	.stop = vhost_kthread_do_stop,
820 	.wakeup = vhost_kthread_wakeup,
821 };
822 
823 static const struct vhost_worker_ops vhost_task_ops = {
824 	.create = vhost_task_worker_create,
825 	.stop = vhost_task_do_stop,
826 	.wakeup = vhost_task_wakeup,
827 };
828 
vhost_worker_create(struct vhost_dev * dev)829 static struct vhost_worker *vhost_worker_create(struct vhost_dev *dev)
830 {
831 	struct vhost_worker *worker;
832 	char name[TASK_COMM_LEN];
833 	int ret;
834 	const struct vhost_worker_ops *ops = dev->fork_owner ? &vhost_task_ops :
835 							       &kthread_ops;
836 
837 	worker = kzalloc(sizeof(*worker), GFP_KERNEL_ACCOUNT);
838 	if (!worker)
839 		return NULL;
840 
841 	worker->dev = dev;
842 	worker->ops = ops;
843 	snprintf(name, sizeof(name), "vhost-%d", current->pid);
844 
845 	mutex_init(&worker->mutex);
846 	init_llist_head(&worker->work_list);
847 	worker->kcov_handle = kcov_common_handle();
848 	ret = ops->create(worker, dev, name);
849 	if (ret < 0)
850 		goto free_worker;
851 
852 	return worker;
853 
854 free_worker:
855 	kfree(worker);
856 	return NULL;
857 }
858 
859 /* Caller must have device mutex */
__vhost_vq_attach_worker(struct vhost_virtqueue * vq,struct vhost_worker * worker)860 static void __vhost_vq_attach_worker(struct vhost_virtqueue *vq,
861 				     struct vhost_worker *worker)
862 {
863 	struct vhost_worker *old_worker;
864 
865 	mutex_lock(&worker->mutex);
866 	if (worker->killed) {
867 		mutex_unlock(&worker->mutex);
868 		return;
869 	}
870 
871 	mutex_lock(&vq->mutex);
872 
873 	old_worker = rcu_dereference_check(vq->worker,
874 					   lockdep_is_held(&vq->mutex));
875 	rcu_assign_pointer(vq->worker, worker);
876 	worker->attachment_cnt++;
877 
878 	if (!old_worker) {
879 		mutex_unlock(&vq->mutex);
880 		mutex_unlock(&worker->mutex);
881 		return;
882 	}
883 	mutex_unlock(&vq->mutex);
884 	mutex_unlock(&worker->mutex);
885 
886 	/*
887 	 * Take the worker mutex to make sure we see the work queued from
888 	 * device wide flushes which doesn't use RCU for execution.
889 	 */
890 	mutex_lock(&old_worker->mutex);
891 	if (old_worker->killed) {
892 		mutex_unlock(&old_worker->mutex);
893 		return;
894 	}
895 
896 	/*
897 	 * We don't want to call synchronize_rcu for every vq during setup
898 	 * because it will slow down VM startup. If we haven't done
899 	 * VHOST_SET_VRING_KICK and not done the driver specific
900 	 * SET_ENDPOINT/RUNNING then we can skip the sync since there will
901 	 * not be any works queued for scsi and net.
902 	 */
903 	mutex_lock(&vq->mutex);
904 	if (!vhost_vq_get_backend(vq) && !vq->kick) {
905 		mutex_unlock(&vq->mutex);
906 
907 		old_worker->attachment_cnt--;
908 		mutex_unlock(&old_worker->mutex);
909 		/*
910 		 * vsock can queue anytime after VHOST_VSOCK_SET_GUEST_CID.
911 		 * Warn if it adds support for multiple workers but forgets to
912 		 * handle the early queueing case.
913 		 */
914 		WARN_ON(!old_worker->attachment_cnt &&
915 			!llist_empty(&old_worker->work_list));
916 		return;
917 	}
918 	mutex_unlock(&vq->mutex);
919 
920 	/* Make sure new vq queue/flush/poll calls see the new worker */
921 	synchronize_rcu();
922 	/* Make sure whatever was queued gets run */
923 	__vhost_worker_flush(old_worker);
924 	old_worker->attachment_cnt--;
925 	mutex_unlock(&old_worker->mutex);
926 }
927 
928  /* Caller must have device mutex */
vhost_vq_attach_worker(struct vhost_virtqueue * vq,struct vhost_vring_worker * info)929 static int vhost_vq_attach_worker(struct vhost_virtqueue *vq,
930 				  struct vhost_vring_worker *info)
931 {
932 	unsigned long index = info->worker_id;
933 	struct vhost_dev *dev = vq->dev;
934 	struct vhost_worker *worker;
935 
936 	if (!dev->use_worker)
937 		return -EINVAL;
938 
939 	worker = xa_find(&dev->worker_xa, &index, UINT_MAX, XA_PRESENT);
940 	if (!worker || worker->id != info->worker_id)
941 		return -ENODEV;
942 
943 	__vhost_vq_attach_worker(vq, worker);
944 	return 0;
945 }
946 
947 /* Caller must have device mutex */
vhost_new_worker(struct vhost_dev * dev,struct vhost_worker_state * info)948 static int vhost_new_worker(struct vhost_dev *dev,
949 			    struct vhost_worker_state *info)
950 {
951 	struct vhost_worker *worker;
952 
953 	worker = vhost_worker_create(dev);
954 	if (!worker)
955 		return -ENOMEM;
956 
957 	info->worker_id = worker->id;
958 	return 0;
959 }
960 
961 /* Caller must have device mutex */
vhost_free_worker(struct vhost_dev * dev,struct vhost_worker_state * info)962 static int vhost_free_worker(struct vhost_dev *dev,
963 			     struct vhost_worker_state *info)
964 {
965 	unsigned long index = info->worker_id;
966 	struct vhost_worker *worker;
967 
968 	worker = xa_find(&dev->worker_xa, &index, UINT_MAX, XA_PRESENT);
969 	if (!worker || worker->id != info->worker_id)
970 		return -ENODEV;
971 
972 	mutex_lock(&worker->mutex);
973 	if (worker->attachment_cnt || worker->killed) {
974 		mutex_unlock(&worker->mutex);
975 		return -EBUSY;
976 	}
977 	/*
978 	 * A flush might have raced and snuck in before attachment_cnt was set
979 	 * to zero. Make sure flushes are flushed from the queue before
980 	 * freeing.
981 	 */
982 	__vhost_worker_flush(worker);
983 	mutex_unlock(&worker->mutex);
984 
985 	vhost_worker_destroy(dev, worker);
986 	return 0;
987 }
988 
vhost_get_vq_from_user(struct vhost_dev * dev,void __user * argp,struct vhost_virtqueue ** vq,u32 * id)989 static int vhost_get_vq_from_user(struct vhost_dev *dev, void __user *argp,
990 				  struct vhost_virtqueue **vq, u32 *id)
991 {
992 	u32 __user *idxp = argp;
993 	u32 idx;
994 	long r;
995 
996 	r = get_user(idx, idxp);
997 	if (r < 0)
998 		return r;
999 
1000 	if (idx >= dev->nvqs)
1001 		return -ENOBUFS;
1002 
1003 	idx = array_index_nospec(idx, dev->nvqs);
1004 
1005 	*vq = dev->vqs[idx];
1006 	*id = idx;
1007 	return 0;
1008 }
1009 
1010 /* Caller must have device mutex */
vhost_worker_ioctl(struct vhost_dev * dev,unsigned int ioctl,void __user * argp)1011 long vhost_worker_ioctl(struct vhost_dev *dev, unsigned int ioctl,
1012 			void __user *argp)
1013 {
1014 	struct vhost_vring_worker ring_worker;
1015 	struct vhost_worker_state state;
1016 	struct vhost_worker *worker;
1017 	struct vhost_virtqueue *vq;
1018 	long ret;
1019 	u32 idx;
1020 
1021 	if (!dev->use_worker)
1022 		return -EINVAL;
1023 
1024 	if (!vhost_dev_has_owner(dev))
1025 		return -EINVAL;
1026 
1027 	ret = vhost_dev_check_owner(dev);
1028 	if (ret)
1029 		return ret;
1030 
1031 	switch (ioctl) {
1032 	/* dev worker ioctls */
1033 	case VHOST_NEW_WORKER:
1034 		/*
1035 		 * vhost_tasks will account for worker threads under the parent's
1036 		 * NPROC value but kthreads do not. To avoid userspace overflowing
1037 		 * the system with worker threads fork_owner must be true.
1038 		 */
1039 		if (!dev->fork_owner)
1040 			return -EFAULT;
1041 
1042 		ret = vhost_new_worker(dev, &state);
1043 		if (!ret && copy_to_user(argp, &state, sizeof(state)))
1044 			ret = -EFAULT;
1045 		return ret;
1046 	case VHOST_FREE_WORKER:
1047 		if (copy_from_user(&state, argp, sizeof(state)))
1048 			return -EFAULT;
1049 		return vhost_free_worker(dev, &state);
1050 	/* vring worker ioctls */
1051 	case VHOST_ATTACH_VRING_WORKER:
1052 	case VHOST_GET_VRING_WORKER:
1053 		break;
1054 	default:
1055 		return -ENOIOCTLCMD;
1056 	}
1057 
1058 	ret = vhost_get_vq_from_user(dev, argp, &vq, &idx);
1059 	if (ret)
1060 		return ret;
1061 
1062 	switch (ioctl) {
1063 	case VHOST_ATTACH_VRING_WORKER:
1064 		if (copy_from_user(&ring_worker, argp, sizeof(ring_worker))) {
1065 			ret = -EFAULT;
1066 			break;
1067 		}
1068 
1069 		ret = vhost_vq_attach_worker(vq, &ring_worker);
1070 		break;
1071 	case VHOST_GET_VRING_WORKER:
1072 		worker = rcu_dereference_check(vq->worker,
1073 					       lockdep_is_held(&dev->mutex));
1074 		if (!worker) {
1075 			ret = -EINVAL;
1076 			break;
1077 		}
1078 
1079 		ring_worker.index = idx;
1080 		ring_worker.worker_id = worker->id;
1081 
1082 		if (copy_to_user(argp, &ring_worker, sizeof(ring_worker)))
1083 			ret = -EFAULT;
1084 		break;
1085 	default:
1086 		ret = -ENOIOCTLCMD;
1087 		break;
1088 	}
1089 
1090 	return ret;
1091 }
1092 EXPORT_SYMBOL_GPL(vhost_worker_ioctl);
1093 
1094 /* Caller should have device mutex */
vhost_dev_set_owner(struct vhost_dev * dev)1095 long vhost_dev_set_owner(struct vhost_dev *dev)
1096 {
1097 	struct vhost_worker *worker;
1098 	int err, i;
1099 
1100 	/* Is there an owner already? */
1101 	if (vhost_dev_has_owner(dev)) {
1102 		err = -EBUSY;
1103 		goto err_mm;
1104 	}
1105 
1106 	vhost_attach_mm(dev);
1107 
1108 	err = vhost_dev_alloc_iovecs(dev);
1109 	if (err)
1110 		goto err_iovecs;
1111 
1112 	if (dev->use_worker) {
1113 		/*
1114 		 * This should be done last, because vsock can queue work
1115 		 * before VHOST_SET_OWNER so it simplifies the failure path
1116 		 * below since we don't have to worry about vsock queueing
1117 		 * while we free the worker.
1118 		 */
1119 		worker = vhost_worker_create(dev);
1120 		if (!worker) {
1121 			err = -ENOMEM;
1122 			goto err_worker;
1123 		}
1124 
1125 		for (i = 0; i < dev->nvqs; i++)
1126 			__vhost_vq_attach_worker(dev->vqs[i], worker);
1127 	}
1128 
1129 	return 0;
1130 
1131 err_worker:
1132 	vhost_dev_free_iovecs(dev);
1133 err_iovecs:
1134 	vhost_detach_mm(dev);
1135 err_mm:
1136 	return err;
1137 }
1138 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
1139 
iotlb_alloc(void)1140 static struct vhost_iotlb *iotlb_alloc(void)
1141 {
1142 	return vhost_iotlb_alloc(max_iotlb_entries,
1143 				 VHOST_IOTLB_FLAG_RETIRE);
1144 }
1145 
vhost_dev_reset_owner_prepare(void)1146 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void)
1147 {
1148 	return iotlb_alloc();
1149 }
1150 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
1151 
1152 /* Caller should have device mutex */
vhost_dev_reset_owner(struct vhost_dev * dev,struct vhost_iotlb * umem)1153 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem)
1154 {
1155 	int i;
1156 
1157 	vhost_dev_cleanup(dev);
1158 
1159 	dev->fork_owner = fork_from_owner_default;
1160 	dev->umem = umem;
1161 	/* We don't need VQ locks below since vhost_dev_cleanup makes sure
1162 	 * VQs aren't running.
1163 	 */
1164 	for (i = 0; i < dev->nvqs; ++i)
1165 		dev->vqs[i]->umem = umem;
1166 }
1167 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
1168 
vhost_dev_stop(struct vhost_dev * dev)1169 void vhost_dev_stop(struct vhost_dev *dev)
1170 {
1171 	int i;
1172 
1173 	for (i = 0; i < dev->nvqs; ++i) {
1174 		if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick)
1175 			vhost_poll_stop(&dev->vqs[i]->poll);
1176 	}
1177 
1178 	vhost_dev_flush(dev);
1179 }
1180 EXPORT_SYMBOL_GPL(vhost_dev_stop);
1181 
vhost_clear_msg(struct vhost_dev * dev)1182 void vhost_clear_msg(struct vhost_dev *dev)
1183 {
1184 	struct vhost_msg_node *node, *n;
1185 
1186 	spin_lock(&dev->iotlb_lock);
1187 
1188 	list_for_each_entry_safe(node, n, &dev->read_list, node) {
1189 		list_del(&node->node);
1190 		kfree(node);
1191 	}
1192 
1193 	list_for_each_entry_safe(node, n, &dev->pending_list, node) {
1194 		list_del(&node->node);
1195 		kfree(node);
1196 	}
1197 
1198 	spin_unlock(&dev->iotlb_lock);
1199 }
1200 EXPORT_SYMBOL_GPL(vhost_clear_msg);
1201 
vhost_dev_cleanup(struct vhost_dev * dev)1202 void vhost_dev_cleanup(struct vhost_dev *dev)
1203 {
1204 	int i;
1205 
1206 	for (i = 0; i < dev->nvqs; ++i) {
1207 		if (dev->vqs[i]->error_ctx)
1208 			eventfd_ctx_put(dev->vqs[i]->error_ctx);
1209 		if (dev->vqs[i]->kick)
1210 			fput(dev->vqs[i]->kick);
1211 		if (dev->vqs[i]->call_ctx.ctx)
1212 			eventfd_ctx_put(dev->vqs[i]->call_ctx.ctx);
1213 		vhost_vq_reset(dev, dev->vqs[i]);
1214 	}
1215 	vhost_dev_free_iovecs(dev);
1216 	if (dev->log_ctx)
1217 		eventfd_ctx_put(dev->log_ctx);
1218 	dev->log_ctx = NULL;
1219 	/* No one will access memory at this point */
1220 	vhost_iotlb_free(dev->umem);
1221 	dev->umem = NULL;
1222 	vhost_iotlb_free(dev->iotlb);
1223 	dev->iotlb = NULL;
1224 	vhost_clear_msg(dev);
1225 	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
1226 	vhost_workers_free(dev);
1227 	vhost_detach_mm(dev);
1228 }
1229 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
1230 
log_access_ok(void __user * log_base,u64 addr,unsigned long sz)1231 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
1232 {
1233 	u64 a = addr / VHOST_PAGE_SIZE / 8;
1234 
1235 	/* Make sure 64 bit math will not overflow. */
1236 	if (a > ULONG_MAX - (unsigned long)log_base ||
1237 	    a + (unsigned long)log_base > ULONG_MAX)
1238 		return false;
1239 
1240 	return access_ok(log_base + a,
1241 			 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
1242 }
1243 
1244 /* Make sure 64 bit math will not overflow. */
vhost_overflow(u64 uaddr,u64 size)1245 static bool vhost_overflow(u64 uaddr, u64 size)
1246 {
1247 	if (uaddr > ULONG_MAX || size > ULONG_MAX)
1248 		return true;
1249 
1250 	if (!size)
1251 		return false;
1252 
1253 	return uaddr > ULONG_MAX - size + 1;
1254 }
1255 
1256 /* Caller should have vq mutex and device mutex. */
vq_memory_access_ok(void __user * log_base,struct vhost_iotlb * umem,int log_all)1257 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem,
1258 				int log_all)
1259 {
1260 	struct vhost_iotlb_map *map;
1261 
1262 	if (!umem)
1263 		return false;
1264 
1265 	list_for_each_entry(map, &umem->list, link) {
1266 		unsigned long a = map->addr;
1267 
1268 		if (vhost_overflow(map->addr, map->size))
1269 			return false;
1270 
1271 
1272 		if (!access_ok((void __user *)a, map->size))
1273 			return false;
1274 		else if (log_all && !log_access_ok(log_base,
1275 						   map->start,
1276 						   map->size))
1277 			return false;
1278 	}
1279 	return true;
1280 }
1281 
vhost_vq_meta_fetch(struct vhost_virtqueue * vq,u64 addr,unsigned int size,int type)1282 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
1283 					       u64 addr, unsigned int size,
1284 					       int type)
1285 {
1286 	const struct vhost_iotlb_map *map = vq->meta_iotlb[type];
1287 
1288 	if (!map)
1289 		return NULL;
1290 
1291 	return (void __user *)(uintptr_t)(map->addr + addr - map->start);
1292 }
1293 
1294 /* Can we switch to this memory table? */
1295 /* Caller should have device mutex but not vq mutex */
memory_access_ok(struct vhost_dev * d,struct vhost_iotlb * umem,int log_all)1296 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem,
1297 			     int log_all)
1298 {
1299 	int i;
1300 
1301 	for (i = 0; i < d->nvqs; ++i) {
1302 		bool ok;
1303 		bool log;
1304 
1305 		mutex_lock(&d->vqs[i]->mutex);
1306 		log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
1307 		/* If ring is inactive, will check when it's enabled. */
1308 		if (d->vqs[i]->private_data)
1309 			ok = vq_memory_access_ok(d->vqs[i]->log_base,
1310 						 umem, log);
1311 		else
1312 			ok = true;
1313 		mutex_unlock(&d->vqs[i]->mutex);
1314 		if (!ok)
1315 			return false;
1316 	}
1317 	return true;
1318 }
1319 
1320 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1321 			  struct iovec iov[], int iov_size, int access);
1322 
vhost_copy_to_user(struct vhost_virtqueue * vq,void __user * to,const void * from,unsigned size)1323 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
1324 			      const void *from, unsigned size)
1325 {
1326 	int ret;
1327 
1328 	if (!vq->iotlb)
1329 		return __copy_to_user(to, from, size);
1330 	else {
1331 		/* This function should be called after iotlb
1332 		 * prefetch, which means we're sure that all vq
1333 		 * could be access through iotlb. So -EAGAIN should
1334 		 * not happen in this case.
1335 		 */
1336 		struct iov_iter t;
1337 		void __user *uaddr = vhost_vq_meta_fetch(vq,
1338 				     (u64)(uintptr_t)to, size,
1339 				     VHOST_ADDR_USED);
1340 
1341 		if (uaddr)
1342 			return __copy_to_user(uaddr, from, size);
1343 
1344 		ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
1345 				     ARRAY_SIZE(vq->iotlb_iov),
1346 				     VHOST_ACCESS_WO);
1347 		if (ret < 0)
1348 			goto out;
1349 		iov_iter_init(&t, ITER_DEST, vq->iotlb_iov, ret, size);
1350 		ret = copy_to_iter(from, size, &t);
1351 		if (ret == size)
1352 			ret = 0;
1353 	}
1354 out:
1355 	return ret;
1356 }
1357 
vhost_copy_from_user(struct vhost_virtqueue * vq,void * to,void __user * from,unsigned size)1358 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
1359 				void __user *from, unsigned size)
1360 {
1361 	int ret;
1362 
1363 	if (!vq->iotlb)
1364 		return __copy_from_user(to, from, size);
1365 	else {
1366 		/* This function should be called after iotlb
1367 		 * prefetch, which means we're sure that vq
1368 		 * could be access through iotlb. So -EAGAIN should
1369 		 * not happen in this case.
1370 		 */
1371 		void __user *uaddr = vhost_vq_meta_fetch(vq,
1372 				     (u64)(uintptr_t)from, size,
1373 				     VHOST_ADDR_DESC);
1374 		struct iov_iter f;
1375 
1376 		if (uaddr)
1377 			return __copy_from_user(to, uaddr, size);
1378 
1379 		ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
1380 				     ARRAY_SIZE(vq->iotlb_iov),
1381 				     VHOST_ACCESS_RO);
1382 		if (ret < 0) {
1383 			vq_err(vq, "IOTLB translation failure: uaddr "
1384 			       "%p size 0x%llx\n", from,
1385 			       (unsigned long long) size);
1386 			goto out;
1387 		}
1388 		iov_iter_init(&f, ITER_SOURCE, vq->iotlb_iov, ret, size);
1389 		ret = copy_from_iter(to, size, &f);
1390 		if (ret == size)
1391 			ret = 0;
1392 	}
1393 
1394 out:
1395 	return ret;
1396 }
1397 
__vhost_get_user_slow(struct vhost_virtqueue * vq,void __user * addr,unsigned int size,int type)1398 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
1399 					  void __user *addr, unsigned int size,
1400 					  int type)
1401 {
1402 	int ret;
1403 
1404 	ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
1405 			     ARRAY_SIZE(vq->iotlb_iov),
1406 			     VHOST_ACCESS_RO);
1407 	if (ret < 0) {
1408 		vq_err(vq, "IOTLB translation failure: uaddr "
1409 			"%p size 0x%llx\n", addr,
1410 			(unsigned long long) size);
1411 		return NULL;
1412 	}
1413 
1414 	if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
1415 		vq_err(vq, "Non atomic userspace memory access: uaddr "
1416 			"%p size 0x%llx\n", addr,
1417 			(unsigned long long) size);
1418 		return NULL;
1419 	}
1420 
1421 	return vq->iotlb_iov[0].iov_base;
1422 }
1423 
1424 /* This function should be called after iotlb
1425  * prefetch, which means we're sure that vq
1426  * could be access through iotlb. So -EAGAIN should
1427  * not happen in this case.
1428  */
__vhost_get_user(struct vhost_virtqueue * vq,void __user * addr,unsigned int size,int type)1429 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
1430 					    void __user *addr, unsigned int size,
1431 					    int type)
1432 {
1433 	void __user *uaddr = vhost_vq_meta_fetch(vq,
1434 			     (u64)(uintptr_t)addr, size, type);
1435 	if (uaddr)
1436 		return uaddr;
1437 
1438 	return __vhost_get_user_slow(vq, addr, size, type);
1439 }
1440 
1441 #define vhost_put_user(vq, x, ptr)		\
1442 ({ \
1443 	int ret; \
1444 	if (!vq->iotlb) { \
1445 		ret = __put_user(x, ptr); \
1446 	} else { \
1447 		__typeof__(ptr) to = \
1448 			(__typeof__(ptr)) __vhost_get_user(vq, ptr,	\
1449 					  sizeof(*ptr), VHOST_ADDR_USED); \
1450 		if (to != NULL) \
1451 			ret = __put_user(x, to); \
1452 		else \
1453 			ret = -EFAULT;	\
1454 	} \
1455 	ret; \
1456 })
1457 
vhost_put_avail_event(struct vhost_virtqueue * vq)1458 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
1459 {
1460 	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
1461 			      vhost_avail_event(vq));
1462 }
1463 
vhost_put_used(struct vhost_virtqueue * vq,struct vring_used_elem * head,int idx,int count)1464 static inline int vhost_put_used(struct vhost_virtqueue *vq,
1465 				 struct vring_used_elem *head, int idx,
1466 				 int count)
1467 {
1468 	return vhost_copy_to_user(vq, vq->used->ring + idx, head,
1469 				  count * sizeof(*head));
1470 }
1471 
vhost_put_used_flags(struct vhost_virtqueue * vq)1472 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
1473 
1474 {
1475 	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
1476 			      &vq->used->flags);
1477 }
1478 
vhost_put_used_idx(struct vhost_virtqueue * vq)1479 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
1480 
1481 {
1482 	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
1483 			      &vq->used->idx);
1484 }
1485 
1486 #define vhost_get_user(vq, x, ptr, type)		\
1487 ({ \
1488 	int ret; \
1489 	if (!vq->iotlb) { \
1490 		ret = __get_user(x, ptr); \
1491 	} else { \
1492 		__typeof__(ptr) from = \
1493 			(__typeof__(ptr)) __vhost_get_user(vq, ptr, \
1494 							   sizeof(*ptr), \
1495 							   type); \
1496 		if (from != NULL) \
1497 			ret = __get_user(x, from); \
1498 		else \
1499 			ret = -EFAULT; \
1500 	} \
1501 	ret; \
1502 })
1503 
1504 #define vhost_get_avail(vq, x, ptr) \
1505 	vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
1506 
1507 #define vhost_get_used(vq, x, ptr) \
1508 	vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
1509 
vhost_dev_lock_vqs(struct vhost_dev * d)1510 static void vhost_dev_lock_vqs(struct vhost_dev *d)
1511 {
1512 	int i = 0;
1513 	for (i = 0; i < d->nvqs; ++i)
1514 		mutex_lock_nested(&d->vqs[i]->mutex, i);
1515 }
1516 
vhost_dev_unlock_vqs(struct vhost_dev * d)1517 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
1518 {
1519 	int i = 0;
1520 	for (i = 0; i < d->nvqs; ++i)
1521 		mutex_unlock(&d->vqs[i]->mutex);
1522 }
1523 
vhost_get_avail_idx(struct vhost_virtqueue * vq)1524 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq)
1525 {
1526 	__virtio16 idx;
1527 	int r;
1528 
1529 	r = vhost_get_avail(vq, idx, &vq->avail->idx);
1530 	if (unlikely(r < 0)) {
1531 		vq_err(vq, "Failed to access available index at %p (%d)\n",
1532 		       &vq->avail->idx, r);
1533 		return r;
1534 	}
1535 
1536 	/* Check it isn't doing very strange thing with available indexes */
1537 	vq->avail_idx = vhost16_to_cpu(vq, idx);
1538 	if (unlikely((u16)(vq->avail_idx - vq->last_avail_idx) > vq->num)) {
1539 		vq_err(vq, "Invalid available index change from %u to %u",
1540 		       vq->last_avail_idx, vq->avail_idx);
1541 		return -EINVAL;
1542 	}
1543 
1544 	/* We're done if there is nothing new */
1545 	if (vq->avail_idx == vq->last_avail_idx)
1546 		return 0;
1547 
1548 	/*
1549 	 * We updated vq->avail_idx so we need a memory barrier between
1550 	 * the index read above and the caller reading avail ring entries.
1551 	 */
1552 	smp_rmb();
1553 	return 1;
1554 }
1555 
vhost_get_avail_head(struct vhost_virtqueue * vq,__virtio16 * head,int idx)1556 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
1557 				       __virtio16 *head, int idx)
1558 {
1559 	return vhost_get_avail(vq, *head,
1560 			       &vq->avail->ring[idx & (vq->num - 1)]);
1561 }
1562 
vhost_get_avail_flags(struct vhost_virtqueue * vq,__virtio16 * flags)1563 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1564 					__virtio16 *flags)
1565 {
1566 	return vhost_get_avail(vq, *flags, &vq->avail->flags);
1567 }
1568 
vhost_get_used_event(struct vhost_virtqueue * vq,__virtio16 * event)1569 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1570 				       __virtio16 *event)
1571 {
1572 	return vhost_get_avail(vq, *event, vhost_used_event(vq));
1573 }
1574 
vhost_get_used_idx(struct vhost_virtqueue * vq,__virtio16 * idx)1575 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1576 				     __virtio16 *idx)
1577 {
1578 	return vhost_get_used(vq, *idx, &vq->used->idx);
1579 }
1580 
vhost_get_desc(struct vhost_virtqueue * vq,struct vring_desc * desc,int idx)1581 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1582 				 struct vring_desc *desc, int idx)
1583 {
1584 	return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1585 }
1586 
vhost_iotlb_notify_vq(struct vhost_dev * d,struct vhost_iotlb_msg * msg)1587 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1588 				  struct vhost_iotlb_msg *msg)
1589 {
1590 	struct vhost_msg_node *node, *n;
1591 
1592 	spin_lock(&d->iotlb_lock);
1593 
1594 	list_for_each_entry_safe(node, n, &d->pending_list, node) {
1595 		struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1596 		if (msg->iova <= vq_msg->iova &&
1597 		    msg->iova + msg->size - 1 >= vq_msg->iova &&
1598 		    vq_msg->type == VHOST_IOTLB_MISS) {
1599 			vhost_poll_queue(&node->vq->poll);
1600 			list_del(&node->node);
1601 			kfree(node);
1602 		}
1603 	}
1604 
1605 	spin_unlock(&d->iotlb_lock);
1606 }
1607 
umem_access_ok(u64 uaddr,u64 size,int access)1608 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1609 {
1610 	unsigned long a = uaddr;
1611 
1612 	/* Make sure 64 bit math will not overflow. */
1613 	if (vhost_overflow(uaddr, size))
1614 		return false;
1615 
1616 	if ((access & VHOST_ACCESS_RO) &&
1617 	    !access_ok((void __user *)a, size))
1618 		return false;
1619 	if ((access & VHOST_ACCESS_WO) &&
1620 	    !access_ok((void __user *)a, size))
1621 		return false;
1622 	return true;
1623 }
1624 
vhost_process_iotlb_msg(struct vhost_dev * dev,u32 asid,struct vhost_iotlb_msg * msg)1625 static int vhost_process_iotlb_msg(struct vhost_dev *dev, u32 asid,
1626 				   struct vhost_iotlb_msg *msg)
1627 {
1628 	int ret = 0;
1629 
1630 	if (asid != 0)
1631 		return -EINVAL;
1632 
1633 	mutex_lock(&dev->mutex);
1634 	vhost_dev_lock_vqs(dev);
1635 	switch (msg->type) {
1636 	case VHOST_IOTLB_UPDATE:
1637 		if (!dev->iotlb) {
1638 			ret = -EFAULT;
1639 			break;
1640 		}
1641 		if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1642 			ret = -EFAULT;
1643 			break;
1644 		}
1645 		vhost_vq_meta_reset(dev);
1646 		if (vhost_iotlb_add_range(dev->iotlb, msg->iova,
1647 					  msg->iova + msg->size - 1,
1648 					  msg->uaddr, msg->perm)) {
1649 			ret = -ENOMEM;
1650 			break;
1651 		}
1652 		vhost_iotlb_notify_vq(dev, msg);
1653 		break;
1654 	case VHOST_IOTLB_INVALIDATE:
1655 		if (!dev->iotlb) {
1656 			ret = -EFAULT;
1657 			break;
1658 		}
1659 		vhost_vq_meta_reset(dev);
1660 		vhost_iotlb_del_range(dev->iotlb, msg->iova,
1661 				      msg->iova + msg->size - 1);
1662 		break;
1663 	default:
1664 		ret = -EINVAL;
1665 		break;
1666 	}
1667 
1668 	vhost_dev_unlock_vqs(dev);
1669 	mutex_unlock(&dev->mutex);
1670 
1671 	return ret;
1672 }
vhost_chr_write_iter(struct vhost_dev * dev,struct iov_iter * from)1673 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1674 			     struct iov_iter *from)
1675 {
1676 	struct vhost_iotlb_msg msg;
1677 	size_t offset;
1678 	int type, ret;
1679 	u32 asid = 0;
1680 
1681 	ret = copy_from_iter(&type, sizeof(type), from);
1682 	if (ret != sizeof(type)) {
1683 		ret = -EINVAL;
1684 		goto done;
1685 	}
1686 
1687 	switch (type) {
1688 	case VHOST_IOTLB_MSG:
1689 		/* There maybe a hole after type for V1 message type,
1690 		 * so skip it here.
1691 		 */
1692 		offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1693 		break;
1694 	case VHOST_IOTLB_MSG_V2:
1695 		if (vhost_backend_has_feature(dev->vqs[0],
1696 					      VHOST_BACKEND_F_IOTLB_ASID)) {
1697 			ret = copy_from_iter(&asid, sizeof(asid), from);
1698 			if (ret != sizeof(asid)) {
1699 				ret = -EINVAL;
1700 				goto done;
1701 			}
1702 			offset = 0;
1703 		} else
1704 			offset = sizeof(__u32);
1705 		break;
1706 	default:
1707 		ret = -EINVAL;
1708 		goto done;
1709 	}
1710 
1711 	iov_iter_advance(from, offset);
1712 	ret = copy_from_iter(&msg, sizeof(msg), from);
1713 	if (ret != sizeof(msg)) {
1714 		ret = -EINVAL;
1715 		goto done;
1716 	}
1717 
1718 	if (msg.type == VHOST_IOTLB_UPDATE && msg.size == 0) {
1719 		ret = -EINVAL;
1720 		goto done;
1721 	}
1722 
1723 	if (dev->msg_handler)
1724 		ret = dev->msg_handler(dev, asid, &msg);
1725 	else
1726 		ret = vhost_process_iotlb_msg(dev, asid, &msg);
1727 	if (ret) {
1728 		ret = -EFAULT;
1729 		goto done;
1730 	}
1731 
1732 	ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1733 	      sizeof(struct vhost_msg_v2);
1734 done:
1735 	return ret;
1736 }
1737 EXPORT_SYMBOL(vhost_chr_write_iter);
1738 
vhost_chr_poll(struct file * file,struct vhost_dev * dev,poll_table * wait)1739 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1740 			    poll_table *wait)
1741 {
1742 	__poll_t mask = 0;
1743 
1744 	poll_wait(file, &dev->wait, wait);
1745 
1746 	if (!list_empty(&dev->read_list))
1747 		mask |= EPOLLIN | EPOLLRDNORM;
1748 
1749 	return mask;
1750 }
1751 EXPORT_SYMBOL(vhost_chr_poll);
1752 
vhost_chr_read_iter(struct vhost_dev * dev,struct iov_iter * to,int noblock)1753 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1754 			    int noblock)
1755 {
1756 	DEFINE_WAIT(wait);
1757 	struct vhost_msg_node *node;
1758 	ssize_t ret = 0;
1759 	unsigned size = sizeof(struct vhost_msg);
1760 
1761 	if (iov_iter_count(to) < size)
1762 		return 0;
1763 
1764 	while (1) {
1765 		if (!noblock)
1766 			prepare_to_wait(&dev->wait, &wait,
1767 					TASK_INTERRUPTIBLE);
1768 
1769 		node = vhost_dequeue_msg(dev, &dev->read_list);
1770 		if (node)
1771 			break;
1772 		if (noblock) {
1773 			ret = -EAGAIN;
1774 			break;
1775 		}
1776 		if (signal_pending(current)) {
1777 			ret = -ERESTARTSYS;
1778 			break;
1779 		}
1780 		if (!dev->iotlb) {
1781 			ret = -EBADFD;
1782 			break;
1783 		}
1784 
1785 		schedule();
1786 	}
1787 
1788 	if (!noblock)
1789 		finish_wait(&dev->wait, &wait);
1790 
1791 	if (node) {
1792 		struct vhost_iotlb_msg *msg;
1793 		void *start = &node->msg;
1794 
1795 		switch (node->msg.type) {
1796 		case VHOST_IOTLB_MSG:
1797 			size = sizeof(node->msg);
1798 			msg = &node->msg.iotlb;
1799 			break;
1800 		case VHOST_IOTLB_MSG_V2:
1801 			size = sizeof(node->msg_v2);
1802 			msg = &node->msg_v2.iotlb;
1803 			break;
1804 		default:
1805 			BUG();
1806 			break;
1807 		}
1808 
1809 		ret = copy_to_iter(start, size, to);
1810 		if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1811 			kfree(node);
1812 			return ret;
1813 		}
1814 		vhost_enqueue_msg(dev, &dev->pending_list, node);
1815 	}
1816 
1817 	return ret;
1818 }
1819 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1820 
vhost_iotlb_miss(struct vhost_virtqueue * vq,u64 iova,int access)1821 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1822 {
1823 	struct vhost_dev *dev = vq->dev;
1824 	struct vhost_msg_node *node;
1825 	struct vhost_iotlb_msg *msg;
1826 	bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1827 
1828 	node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1829 	if (!node)
1830 		return -ENOMEM;
1831 
1832 	if (v2) {
1833 		node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1834 		msg = &node->msg_v2.iotlb;
1835 	} else {
1836 		msg = &node->msg.iotlb;
1837 	}
1838 
1839 	msg->type = VHOST_IOTLB_MISS;
1840 	msg->iova = iova;
1841 	msg->perm = access;
1842 
1843 	vhost_enqueue_msg(dev, &dev->read_list, node);
1844 
1845 	return 0;
1846 }
1847 
vq_access_ok(struct vhost_virtqueue * vq,unsigned int num,vring_desc_t __user * desc,vring_avail_t __user * avail,vring_used_t __user * used)1848 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1849 			 vring_desc_t __user *desc,
1850 			 vring_avail_t __user *avail,
1851 			 vring_used_t __user *used)
1852 
1853 {
1854 	/* If an IOTLB device is present, the vring addresses are
1855 	 * GIOVAs. Access validation occurs at prefetch time. */
1856 	if (vq->iotlb)
1857 		return true;
1858 
1859 	return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1860 	       access_ok(avail, vhost_get_avail_size(vq, num)) &&
1861 	       access_ok(used, vhost_get_used_size(vq, num));
1862 }
1863 
vhost_vq_meta_update(struct vhost_virtqueue * vq,const struct vhost_iotlb_map * map,int type)1864 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1865 				 const struct vhost_iotlb_map *map,
1866 				 int type)
1867 {
1868 	int access = (type == VHOST_ADDR_USED) ?
1869 		     VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1870 
1871 	if (likely(map->perm & access))
1872 		vq->meta_iotlb[type] = map;
1873 }
1874 
iotlb_access_ok(struct vhost_virtqueue * vq,int access,u64 addr,u64 len,int type)1875 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1876 			    int access, u64 addr, u64 len, int type)
1877 {
1878 	const struct vhost_iotlb_map *map;
1879 	struct vhost_iotlb *umem = vq->iotlb;
1880 	u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1881 
1882 	if (vhost_vq_meta_fetch(vq, addr, len, type))
1883 		return true;
1884 
1885 	while (len > s) {
1886 		map = vhost_iotlb_itree_first(umem, addr, last);
1887 		if (map == NULL || map->start > addr) {
1888 			vhost_iotlb_miss(vq, addr, access);
1889 			return false;
1890 		} else if (!(map->perm & access)) {
1891 			/* Report the possible access violation by
1892 			 * request another translation from userspace.
1893 			 */
1894 			return false;
1895 		}
1896 
1897 		size = map->size - addr + map->start;
1898 
1899 		if (orig_addr == addr && size >= len)
1900 			vhost_vq_meta_update(vq, map, type);
1901 
1902 		s += size;
1903 		addr += size;
1904 	}
1905 
1906 	return true;
1907 }
1908 
vq_meta_prefetch(struct vhost_virtqueue * vq)1909 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1910 {
1911 	unsigned int num = vq->num;
1912 
1913 	if (!vq->iotlb)
1914 		return 1;
1915 
1916 	return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc,
1917 			       vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1918 	       iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail,
1919 			       vhost_get_avail_size(vq, num),
1920 			       VHOST_ADDR_AVAIL) &&
1921 	       iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used,
1922 			       vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1923 }
1924 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1925 
1926 /* Can we log writes? */
1927 /* Caller should have device mutex but not vq mutex */
vhost_log_access_ok(struct vhost_dev * dev)1928 bool vhost_log_access_ok(struct vhost_dev *dev)
1929 {
1930 	return memory_access_ok(dev, dev->umem, 1);
1931 }
1932 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1933 
vq_log_used_access_ok(struct vhost_virtqueue * vq,void __user * log_base,bool log_used,u64 log_addr)1934 static bool vq_log_used_access_ok(struct vhost_virtqueue *vq,
1935 				  void __user *log_base,
1936 				  bool log_used,
1937 				  u64 log_addr)
1938 {
1939 	/* If an IOTLB device is present, log_addr is a GIOVA that
1940 	 * will never be logged by log_used(). */
1941 	if (vq->iotlb)
1942 		return true;
1943 
1944 	return !log_used || log_access_ok(log_base, log_addr,
1945 					  vhost_get_used_size(vq, vq->num));
1946 }
1947 
1948 /* Verify access for write logging. */
1949 /* Caller should have vq mutex and device mutex */
vq_log_access_ok(struct vhost_virtqueue * vq,void __user * log_base)1950 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1951 			     void __user *log_base)
1952 {
1953 	return vq_memory_access_ok(log_base, vq->umem,
1954 				   vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1955 		vq_log_used_access_ok(vq, log_base, vq->log_used, vq->log_addr);
1956 }
1957 
1958 /* Can we start vq? */
1959 /* Caller should have vq mutex and device mutex */
vhost_vq_access_ok(struct vhost_virtqueue * vq)1960 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1961 {
1962 	if (!vq_log_access_ok(vq, vq->log_base))
1963 		return false;
1964 
1965 	return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1966 }
1967 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1968 
vhost_set_memory(struct vhost_dev * d,struct vhost_memory __user * m)1969 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1970 {
1971 	struct vhost_memory mem, *newmem;
1972 	struct vhost_memory_region *region;
1973 	struct vhost_iotlb *newumem, *oldumem;
1974 	unsigned long size = offsetof(struct vhost_memory, regions);
1975 	int i;
1976 
1977 	if (copy_from_user(&mem, m, size))
1978 		return -EFAULT;
1979 	if (mem.padding)
1980 		return -EOPNOTSUPP;
1981 	if (mem.nregions > max_mem_regions)
1982 		return -E2BIG;
1983 	newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1984 			GFP_KERNEL);
1985 	if (!newmem)
1986 		return -ENOMEM;
1987 
1988 	memcpy(newmem, &mem, size);
1989 	if (copy_from_user(newmem->regions, m->regions,
1990 			   flex_array_size(newmem, regions, mem.nregions))) {
1991 		kvfree(newmem);
1992 		return -EFAULT;
1993 	}
1994 
1995 	newumem = iotlb_alloc();
1996 	if (!newumem) {
1997 		kvfree(newmem);
1998 		return -ENOMEM;
1999 	}
2000 
2001 	for (region = newmem->regions;
2002 	     region < newmem->regions + mem.nregions;
2003 	     region++) {
2004 		if (vhost_iotlb_add_range(newumem,
2005 					  region->guest_phys_addr,
2006 					  region->guest_phys_addr +
2007 					  region->memory_size - 1,
2008 					  region->userspace_addr,
2009 					  VHOST_MAP_RW))
2010 			goto err;
2011 	}
2012 
2013 	if (!memory_access_ok(d, newumem, 0))
2014 		goto err;
2015 
2016 	oldumem = d->umem;
2017 	d->umem = newumem;
2018 
2019 	/* All memory accesses are done under some VQ mutex. */
2020 	for (i = 0; i < d->nvqs; ++i) {
2021 		mutex_lock(&d->vqs[i]->mutex);
2022 		d->vqs[i]->umem = newumem;
2023 		mutex_unlock(&d->vqs[i]->mutex);
2024 	}
2025 
2026 	kvfree(newmem);
2027 	vhost_iotlb_free(oldumem);
2028 	return 0;
2029 
2030 err:
2031 	vhost_iotlb_free(newumem);
2032 	kvfree(newmem);
2033 	return -EFAULT;
2034 }
2035 
vhost_vring_set_num(struct vhost_dev * d,struct vhost_virtqueue * vq,void __user * argp)2036 static long vhost_vring_set_num(struct vhost_dev *d,
2037 				struct vhost_virtqueue *vq,
2038 				void __user *argp)
2039 {
2040 	struct vhost_vring_state s;
2041 
2042 	/* Resizing ring with an active backend?
2043 	 * You don't want to do that. */
2044 	if (vq->private_data)
2045 		return -EBUSY;
2046 
2047 	if (copy_from_user(&s, argp, sizeof s))
2048 		return -EFAULT;
2049 
2050 	if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
2051 		return -EINVAL;
2052 	vq->num = s.num;
2053 
2054 	return 0;
2055 }
2056 
vhost_vring_set_addr(struct vhost_dev * d,struct vhost_virtqueue * vq,void __user * argp)2057 static long vhost_vring_set_addr(struct vhost_dev *d,
2058 				 struct vhost_virtqueue *vq,
2059 				 void __user *argp)
2060 {
2061 	struct vhost_vring_addr a;
2062 
2063 	if (copy_from_user(&a, argp, sizeof a))
2064 		return -EFAULT;
2065 	if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
2066 		return -EOPNOTSUPP;
2067 
2068 	/* For 32bit, verify that the top 32bits of the user
2069 	   data are set to zero. */
2070 	if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
2071 	    (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
2072 	    (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
2073 		return -EFAULT;
2074 
2075 	/* Make sure it's safe to cast pointers to vring types. */
2076 	BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
2077 	BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
2078 	if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
2079 	    (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
2080 	    (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
2081 		return -EINVAL;
2082 
2083 	/* We only verify access here if backend is configured.
2084 	 * If it is not, we don't as size might not have been setup.
2085 	 * We will verify when backend is configured. */
2086 	if (vq->private_data) {
2087 		if (!vq_access_ok(vq, vq->num,
2088 			(void __user *)(unsigned long)a.desc_user_addr,
2089 			(void __user *)(unsigned long)a.avail_user_addr,
2090 			(void __user *)(unsigned long)a.used_user_addr))
2091 			return -EINVAL;
2092 
2093 		/* Also validate log access for used ring if enabled. */
2094 		if (!vq_log_used_access_ok(vq, vq->log_base,
2095 				a.flags & (0x1 << VHOST_VRING_F_LOG),
2096 				a.log_guest_addr))
2097 			return -EINVAL;
2098 	}
2099 
2100 	vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
2101 	vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
2102 	vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
2103 	vq->log_addr = a.log_guest_addr;
2104 	vq->used = (void __user *)(unsigned long)a.used_user_addr;
2105 
2106 	return 0;
2107 }
2108 
vhost_vring_set_num_addr(struct vhost_dev * d,struct vhost_virtqueue * vq,unsigned int ioctl,void __user * argp)2109 static long vhost_vring_set_num_addr(struct vhost_dev *d,
2110 				     struct vhost_virtqueue *vq,
2111 				     unsigned int ioctl,
2112 				     void __user *argp)
2113 {
2114 	long r;
2115 
2116 	mutex_lock(&vq->mutex);
2117 
2118 	switch (ioctl) {
2119 	case VHOST_SET_VRING_NUM:
2120 		r = vhost_vring_set_num(d, vq, argp);
2121 		break;
2122 	case VHOST_SET_VRING_ADDR:
2123 		r = vhost_vring_set_addr(d, vq, argp);
2124 		break;
2125 	default:
2126 		BUG();
2127 	}
2128 
2129 	mutex_unlock(&vq->mutex);
2130 
2131 	return r;
2132 }
vhost_vring_ioctl(struct vhost_dev * d,unsigned int ioctl,void __user * argp)2133 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
2134 {
2135 	struct file *eventfp, *filep = NULL;
2136 	bool pollstart = false, pollstop = false;
2137 	struct eventfd_ctx *ctx = NULL;
2138 	struct vhost_virtqueue *vq;
2139 	struct vhost_vring_state s;
2140 	struct vhost_vring_file f;
2141 	u32 idx;
2142 	long r;
2143 
2144 	r = vhost_get_vq_from_user(d, argp, &vq, &idx);
2145 	if (r < 0)
2146 		return r;
2147 
2148 	if (ioctl == VHOST_SET_VRING_NUM ||
2149 	    ioctl == VHOST_SET_VRING_ADDR) {
2150 		return vhost_vring_set_num_addr(d, vq, ioctl, argp);
2151 	}
2152 
2153 	mutex_lock(&vq->mutex);
2154 
2155 	switch (ioctl) {
2156 	case VHOST_SET_VRING_BASE:
2157 		/* Moving base with an active backend?
2158 		 * You don't want to do that. */
2159 		if (vq->private_data) {
2160 			r = -EBUSY;
2161 			break;
2162 		}
2163 		if (copy_from_user(&s, argp, sizeof s)) {
2164 			r = -EFAULT;
2165 			break;
2166 		}
2167 		if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) {
2168 			vq->next_avail_head = vq->last_avail_idx =
2169 					      s.num & 0xffff;
2170 			vq->last_used_idx = (s.num >> 16) & 0xffff;
2171 		} else {
2172 			if (s.num > 0xffff) {
2173 				r = -EINVAL;
2174 				break;
2175 			}
2176 			vq->next_avail_head = vq->last_avail_idx = s.num;
2177 		}
2178 		/* Forget the cached index value. */
2179 		vq->avail_idx = vq->last_avail_idx;
2180 		break;
2181 	case VHOST_GET_VRING_BASE:
2182 		s.index = idx;
2183 		if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED))
2184 			s.num = (u32)vq->last_avail_idx | ((u32)vq->last_used_idx << 16);
2185 		else
2186 			s.num = vq->last_avail_idx;
2187 		if (copy_to_user(argp, &s, sizeof s))
2188 			r = -EFAULT;
2189 		break;
2190 	case VHOST_SET_VRING_KICK:
2191 		if (copy_from_user(&f, argp, sizeof f)) {
2192 			r = -EFAULT;
2193 			break;
2194 		}
2195 		eventfp = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_fget(f.fd);
2196 		if (IS_ERR(eventfp)) {
2197 			r = PTR_ERR(eventfp);
2198 			break;
2199 		}
2200 		if (eventfp != vq->kick) {
2201 			pollstop = (filep = vq->kick) != NULL;
2202 			pollstart = (vq->kick = eventfp) != NULL;
2203 		} else
2204 			filep = eventfp;
2205 		break;
2206 	case VHOST_SET_VRING_CALL:
2207 		if (copy_from_user(&f, argp, sizeof f)) {
2208 			r = -EFAULT;
2209 			break;
2210 		}
2211 		ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
2212 		if (IS_ERR(ctx)) {
2213 			r = PTR_ERR(ctx);
2214 			break;
2215 		}
2216 
2217 		swap(ctx, vq->call_ctx.ctx);
2218 		break;
2219 	case VHOST_SET_VRING_ERR:
2220 		if (copy_from_user(&f, argp, sizeof f)) {
2221 			r = -EFAULT;
2222 			break;
2223 		}
2224 		ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
2225 		if (IS_ERR(ctx)) {
2226 			r = PTR_ERR(ctx);
2227 			break;
2228 		}
2229 		swap(ctx, vq->error_ctx);
2230 		break;
2231 	case VHOST_SET_VRING_ENDIAN:
2232 		r = vhost_set_vring_endian(vq, argp);
2233 		break;
2234 	case VHOST_GET_VRING_ENDIAN:
2235 		r = vhost_get_vring_endian(vq, idx, argp);
2236 		break;
2237 	case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
2238 		if (copy_from_user(&s, argp, sizeof(s))) {
2239 			r = -EFAULT;
2240 			break;
2241 		}
2242 		vq->busyloop_timeout = s.num;
2243 		break;
2244 	case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
2245 		s.index = idx;
2246 		s.num = vq->busyloop_timeout;
2247 		if (copy_to_user(argp, &s, sizeof(s)))
2248 			r = -EFAULT;
2249 		break;
2250 	default:
2251 		r = -ENOIOCTLCMD;
2252 	}
2253 
2254 	if (pollstop && vq->handle_kick)
2255 		vhost_poll_stop(&vq->poll);
2256 
2257 	if (!IS_ERR_OR_NULL(ctx))
2258 		eventfd_ctx_put(ctx);
2259 	if (filep)
2260 		fput(filep);
2261 
2262 	if (pollstart && vq->handle_kick)
2263 		r = vhost_poll_start(&vq->poll, vq->kick);
2264 
2265 	mutex_unlock(&vq->mutex);
2266 
2267 	if (pollstop && vq->handle_kick)
2268 		vhost_dev_flush(vq->poll.dev);
2269 	return r;
2270 }
2271 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
2272 
vhost_init_device_iotlb(struct vhost_dev * d)2273 int vhost_init_device_iotlb(struct vhost_dev *d)
2274 {
2275 	struct vhost_iotlb *niotlb, *oiotlb;
2276 	int i;
2277 
2278 	niotlb = iotlb_alloc();
2279 	if (!niotlb)
2280 		return -ENOMEM;
2281 
2282 	oiotlb = d->iotlb;
2283 	d->iotlb = niotlb;
2284 
2285 	for (i = 0; i < d->nvqs; ++i) {
2286 		struct vhost_virtqueue *vq = d->vqs[i];
2287 
2288 		mutex_lock(&vq->mutex);
2289 		vq->iotlb = niotlb;
2290 		__vhost_vq_meta_reset(vq);
2291 		mutex_unlock(&vq->mutex);
2292 	}
2293 
2294 	vhost_iotlb_free(oiotlb);
2295 
2296 	return 0;
2297 }
2298 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
2299 
2300 /* Caller must have device mutex */
vhost_dev_ioctl(struct vhost_dev * d,unsigned int ioctl,void __user * argp)2301 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
2302 {
2303 	struct eventfd_ctx *ctx;
2304 	u64 p;
2305 	long r;
2306 	int i, fd;
2307 
2308 	/* If you are not the owner, you can become one */
2309 	if (ioctl == VHOST_SET_OWNER) {
2310 		r = vhost_dev_set_owner(d);
2311 		goto done;
2312 	}
2313 
2314 #ifdef CONFIG_VHOST_ENABLE_FORK_OWNER_CONTROL
2315 	if (ioctl == VHOST_SET_FORK_FROM_OWNER) {
2316 		/* Only allow modification before owner is set */
2317 		if (vhost_dev_has_owner(d)) {
2318 			r = -EBUSY;
2319 			goto done;
2320 		}
2321 		u8 fork_owner_val;
2322 
2323 		if (get_user(fork_owner_val, (u8 __user *)argp)) {
2324 			r = -EFAULT;
2325 			goto done;
2326 		}
2327 		if (fork_owner_val != VHOST_FORK_OWNER_TASK &&
2328 		    fork_owner_val != VHOST_FORK_OWNER_KTHREAD) {
2329 			r = -EINVAL;
2330 			goto done;
2331 		}
2332 		d->fork_owner = !!fork_owner_val;
2333 		r = 0;
2334 		goto done;
2335 	}
2336 	if (ioctl == VHOST_GET_FORK_FROM_OWNER) {
2337 		u8 fork_owner_val = d->fork_owner;
2338 
2339 		if (fork_owner_val != VHOST_FORK_OWNER_TASK &&
2340 		    fork_owner_val != VHOST_FORK_OWNER_KTHREAD) {
2341 			r = -EINVAL;
2342 			goto done;
2343 		}
2344 		if (put_user(fork_owner_val, (u8 __user *)argp)) {
2345 			r = -EFAULT;
2346 			goto done;
2347 		}
2348 		r = 0;
2349 		goto done;
2350 	}
2351 #endif
2352 
2353 	/* You must be the owner to do anything else */
2354 	r = vhost_dev_check_owner(d);
2355 	if (r)
2356 		goto done;
2357 
2358 	switch (ioctl) {
2359 	case VHOST_SET_MEM_TABLE:
2360 		r = vhost_set_memory(d, argp);
2361 		break;
2362 	case VHOST_SET_LOG_BASE:
2363 		if (copy_from_user(&p, argp, sizeof p)) {
2364 			r = -EFAULT;
2365 			break;
2366 		}
2367 		if ((u64)(unsigned long)p != p) {
2368 			r = -EFAULT;
2369 			break;
2370 		}
2371 		for (i = 0; i < d->nvqs; ++i) {
2372 			struct vhost_virtqueue *vq;
2373 			void __user *base = (void __user *)(unsigned long)p;
2374 			vq = d->vqs[i];
2375 			mutex_lock(&vq->mutex);
2376 			/* If ring is inactive, will check when it's enabled. */
2377 			if (vq->private_data && !vq_log_access_ok(vq, base))
2378 				r = -EFAULT;
2379 			else
2380 				vq->log_base = base;
2381 			mutex_unlock(&vq->mutex);
2382 		}
2383 		break;
2384 	case VHOST_SET_LOG_FD:
2385 		r = get_user(fd, (int __user *)argp);
2386 		if (r < 0)
2387 			break;
2388 		ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd);
2389 		if (IS_ERR(ctx)) {
2390 			r = PTR_ERR(ctx);
2391 			break;
2392 		}
2393 		swap(ctx, d->log_ctx);
2394 		for (i = 0; i < d->nvqs; ++i) {
2395 			mutex_lock(&d->vqs[i]->mutex);
2396 			d->vqs[i]->log_ctx = d->log_ctx;
2397 			mutex_unlock(&d->vqs[i]->mutex);
2398 		}
2399 		if (ctx)
2400 			eventfd_ctx_put(ctx);
2401 		break;
2402 	default:
2403 		r = -ENOIOCTLCMD;
2404 		break;
2405 	}
2406 done:
2407 	return r;
2408 }
2409 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
2410 
2411 /* TODO: This is really inefficient.  We need something like get_user()
2412  * (instruction directly accesses the data, with an exception table entry
2413  * returning -EFAULT). See Documentation/arch/x86/exception-tables.rst.
2414  */
set_bit_to_user(int nr,void __user * addr)2415 static int set_bit_to_user(int nr, void __user *addr)
2416 {
2417 	unsigned long log = (unsigned long)addr;
2418 	struct page *page;
2419 	void *base;
2420 	int bit = nr + (log % PAGE_SIZE) * 8;
2421 	int r;
2422 
2423 	r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page);
2424 	if (r < 0)
2425 		return r;
2426 	BUG_ON(r != 1);
2427 	base = kmap_atomic(page);
2428 	set_bit(bit, base);
2429 	kunmap_atomic(base);
2430 	unpin_user_pages_dirty_lock(&page, 1, true);
2431 	return 0;
2432 }
2433 
log_write(void __user * log_base,u64 write_address,u64 write_length)2434 static int log_write(void __user *log_base,
2435 		     u64 write_address, u64 write_length)
2436 {
2437 	u64 write_page = write_address / VHOST_PAGE_SIZE;
2438 	int r;
2439 
2440 	if (!write_length)
2441 		return 0;
2442 	write_length += write_address % VHOST_PAGE_SIZE;
2443 	for (;;) {
2444 		u64 base = (u64)(unsigned long)log_base;
2445 		u64 log = base + write_page / 8;
2446 		int bit = write_page % 8;
2447 		if ((u64)(unsigned long)log != log)
2448 			return -EFAULT;
2449 		r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
2450 		if (r < 0)
2451 			return r;
2452 		if (write_length <= VHOST_PAGE_SIZE)
2453 			break;
2454 		write_length -= VHOST_PAGE_SIZE;
2455 		write_page += 1;
2456 	}
2457 	return r;
2458 }
2459 
log_write_hva(struct vhost_virtqueue * vq,u64 hva,u64 len)2460 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
2461 {
2462 	struct vhost_iotlb *umem = vq->umem;
2463 	struct vhost_iotlb_map *u;
2464 	u64 start, end, l, min;
2465 	int r;
2466 	bool hit = false;
2467 
2468 	while (len) {
2469 		min = len;
2470 		/* More than one GPAs can be mapped into a single HVA. So
2471 		 * iterate all possible umems here to be safe.
2472 		 */
2473 		list_for_each_entry(u, &umem->list, link) {
2474 			if (u->addr > hva - 1 + len ||
2475 			    u->addr - 1 + u->size < hva)
2476 				continue;
2477 			start = max(u->addr, hva);
2478 			end = min(u->addr - 1 + u->size, hva - 1 + len);
2479 			l = end - start + 1;
2480 			r = log_write(vq->log_base,
2481 				      u->start + start - u->addr,
2482 				      l);
2483 			if (r < 0)
2484 				return r;
2485 			hit = true;
2486 			min = min(l, min);
2487 		}
2488 
2489 		if (!hit)
2490 			return -EFAULT;
2491 
2492 		len -= min;
2493 		hva += min;
2494 	}
2495 
2496 	return 0;
2497 }
2498 
log_used(struct vhost_virtqueue * vq,u64 used_offset,u64 len)2499 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
2500 {
2501 	struct iovec *iov = vq->log_iov;
2502 	int i, ret;
2503 
2504 	if (!vq->iotlb)
2505 		return log_write(vq->log_base, vq->log_addr + used_offset, len);
2506 
2507 	ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
2508 			     len, iov, 64, VHOST_ACCESS_WO);
2509 	if (ret < 0)
2510 		return ret;
2511 
2512 	for (i = 0; i < ret; i++) {
2513 		ret = log_write_hva(vq,	(uintptr_t)iov[i].iov_base,
2514 				    iov[i].iov_len);
2515 		if (ret)
2516 			return ret;
2517 	}
2518 
2519 	return 0;
2520 }
2521 
2522 /*
2523  * vhost_log_write() - Log in dirty page bitmap
2524  * @vq:      vhost virtqueue.
2525  * @log:     Array of dirty memory in GPA.
2526  * @log_num: Size of vhost_log arrary.
2527  * @len:     The total length of memory buffer to log in the dirty bitmap.
2528  *	     Some drivers may only partially use pages shared via the last
2529  *	     vring descriptor (i.e. vhost-net RX buffer).
2530  *	     Use (len == U64_MAX) to indicate the driver would log all
2531  *           pages of vring descriptors.
2532  * @iov:     Array of dirty memory in HVA.
2533  * @count:   Size of iovec array.
2534  */
vhost_log_write(struct vhost_virtqueue * vq,struct vhost_log * log,unsigned int log_num,u64 len,struct iovec * iov,int count)2535 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
2536 		    unsigned int log_num, u64 len, struct iovec *iov, int count)
2537 {
2538 	int i, r;
2539 
2540 	/* Make sure data written is seen before log. */
2541 	smp_wmb();
2542 
2543 	if (vq->iotlb) {
2544 		for (i = 0; i < count; i++) {
2545 			r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
2546 					  iov[i].iov_len);
2547 			if (r < 0)
2548 				return r;
2549 		}
2550 		return 0;
2551 	}
2552 
2553 	for (i = 0; i < log_num; ++i) {
2554 		u64 l = min(log[i].len, len);
2555 		r = log_write(vq->log_base, log[i].addr, l);
2556 		if (r < 0)
2557 			return r;
2558 
2559 		if (len != U64_MAX)
2560 			len -= l;
2561 	}
2562 
2563 	if (vq->log_ctx)
2564 		eventfd_signal(vq->log_ctx);
2565 
2566 	return 0;
2567 }
2568 EXPORT_SYMBOL_GPL(vhost_log_write);
2569 
vhost_update_used_flags(struct vhost_virtqueue * vq)2570 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
2571 {
2572 	void __user *used;
2573 	if (vhost_put_used_flags(vq))
2574 		return -EFAULT;
2575 	if (unlikely(vq->log_used)) {
2576 		/* Make sure the flag is seen before log. */
2577 		smp_wmb();
2578 		/* Log used flag write. */
2579 		used = &vq->used->flags;
2580 		log_used(vq, (used - (void __user *)vq->used),
2581 			 sizeof vq->used->flags);
2582 		if (vq->log_ctx)
2583 			eventfd_signal(vq->log_ctx);
2584 	}
2585 	return 0;
2586 }
2587 
vhost_update_avail_event(struct vhost_virtqueue * vq)2588 static int vhost_update_avail_event(struct vhost_virtqueue *vq)
2589 {
2590 	if (vhost_put_avail_event(vq))
2591 		return -EFAULT;
2592 	if (unlikely(vq->log_used)) {
2593 		void __user *used;
2594 		/* Make sure the event is seen before log. */
2595 		smp_wmb();
2596 		/* Log avail event write */
2597 		used = vhost_avail_event(vq);
2598 		log_used(vq, (used - (void __user *)vq->used),
2599 			 sizeof *vhost_avail_event(vq));
2600 		if (vq->log_ctx)
2601 			eventfd_signal(vq->log_ctx);
2602 	}
2603 	return 0;
2604 }
2605 
vhost_vq_init_access(struct vhost_virtqueue * vq)2606 int vhost_vq_init_access(struct vhost_virtqueue *vq)
2607 {
2608 	__virtio16 last_used_idx;
2609 	int r;
2610 	bool is_le = vq->is_le;
2611 
2612 	if (!vq->private_data)
2613 		return 0;
2614 
2615 	vhost_init_is_le(vq);
2616 
2617 	r = vhost_update_used_flags(vq);
2618 	if (r)
2619 		goto err;
2620 	vq->signalled_used_valid = false;
2621 	if (!vq->iotlb &&
2622 	    !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
2623 		r = -EFAULT;
2624 		goto err;
2625 	}
2626 	r = vhost_get_used_idx(vq, &last_used_idx);
2627 	if (r) {
2628 		vq_err(vq, "Can't access used idx at %p\n",
2629 		       &vq->used->idx);
2630 		goto err;
2631 	}
2632 	vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2633 	return 0;
2634 
2635 err:
2636 	vq->is_le = is_le;
2637 	return r;
2638 }
2639 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2640 
translate_desc(struct vhost_virtqueue * vq,u64 addr,u32 len,struct iovec iov[],int iov_size,int access)2641 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2642 			  struct iovec iov[], int iov_size, int access)
2643 {
2644 	const struct vhost_iotlb_map *map;
2645 	struct vhost_dev *dev = vq->dev;
2646 	struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
2647 	struct iovec *_iov;
2648 	u64 s = 0, last = addr + len - 1;
2649 	int ret = 0;
2650 
2651 	while ((u64)len > s) {
2652 		u64 size;
2653 		if (unlikely(ret >= iov_size)) {
2654 			ret = -ENOBUFS;
2655 			break;
2656 		}
2657 
2658 		map = vhost_iotlb_itree_first(umem, addr, last);
2659 		if (map == NULL || map->start > addr) {
2660 			if (umem != dev->iotlb) {
2661 				ret = -EFAULT;
2662 				break;
2663 			}
2664 			ret = -EAGAIN;
2665 			break;
2666 		} else if (!(map->perm & access)) {
2667 			ret = -EPERM;
2668 			break;
2669 		}
2670 
2671 		_iov = iov + ret;
2672 		size = map->size - addr + map->start;
2673 		_iov->iov_len = min((u64)len - s, size);
2674 		_iov->iov_base = (void __user *)(unsigned long)
2675 				 (map->addr + addr - map->start);
2676 		s += size;
2677 		addr += size;
2678 		++ret;
2679 	}
2680 
2681 	if (ret == -EAGAIN)
2682 		vhost_iotlb_miss(vq, addr, access);
2683 	return ret;
2684 }
2685 
2686 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
2687  * function returns the next descriptor in the chain,
2688  * or -1U if we're at the end. */
next_desc(struct vhost_virtqueue * vq,struct vring_desc * desc)2689 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2690 {
2691 	unsigned int next;
2692 
2693 	/* If this descriptor says it doesn't chain, we're done. */
2694 	if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2695 		return -1U;
2696 
2697 	/* Check they're not leading us off end of descriptors. */
2698 	next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2699 	return next;
2700 }
2701 
get_indirect(struct vhost_virtqueue * vq,struct iovec iov[],unsigned int iov_size,unsigned int * out_num,unsigned int * in_num,struct vhost_log * log,unsigned int * log_num,struct vring_desc * indirect)2702 static int get_indirect(struct vhost_virtqueue *vq,
2703 			struct iovec iov[], unsigned int iov_size,
2704 			unsigned int *out_num, unsigned int *in_num,
2705 			struct vhost_log *log, unsigned int *log_num,
2706 			struct vring_desc *indirect)
2707 {
2708 	struct vring_desc desc;
2709 	unsigned int i = 0, count, found = 0;
2710 	u32 len = vhost32_to_cpu(vq, indirect->len);
2711 	struct iov_iter from;
2712 	int ret, access;
2713 
2714 	/* Sanity check */
2715 	if (unlikely(len % sizeof desc)) {
2716 		vq_err(vq, "Invalid length in indirect descriptor: "
2717 		       "len 0x%llx not multiple of 0x%zx\n",
2718 		       (unsigned long long)len,
2719 		       sizeof desc);
2720 		return -EINVAL;
2721 	}
2722 
2723 	ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2724 			     UIO_MAXIOV, VHOST_ACCESS_RO);
2725 	if (unlikely(ret < 0)) {
2726 		if (ret != -EAGAIN)
2727 			vq_err(vq, "Translation failure %d in indirect.\n", ret);
2728 		return ret;
2729 	}
2730 	iov_iter_init(&from, ITER_SOURCE, vq->indirect, ret, len);
2731 	count = len / sizeof desc;
2732 	/* Buffers are chained via a 16 bit next field, so
2733 	 * we can have at most 2^16 of these. */
2734 	if (unlikely(count > USHRT_MAX + 1)) {
2735 		vq_err(vq, "Indirect buffer length too big: %d\n",
2736 		       indirect->len);
2737 		return -E2BIG;
2738 	}
2739 
2740 	do {
2741 		unsigned iov_count = *in_num + *out_num;
2742 		if (unlikely(++found > count)) {
2743 			vq_err(vq, "Loop detected: last one at %u "
2744 			       "indirect size %u\n",
2745 			       i, count);
2746 			return -EINVAL;
2747 		}
2748 		if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2749 			vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2750 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2751 			return -EINVAL;
2752 		}
2753 		if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2754 			vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2755 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2756 			return -EINVAL;
2757 		}
2758 
2759 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2760 			access = VHOST_ACCESS_WO;
2761 		else
2762 			access = VHOST_ACCESS_RO;
2763 
2764 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2765 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
2766 				     iov_size - iov_count, access);
2767 		if (unlikely(ret < 0)) {
2768 			if (ret != -EAGAIN)
2769 				vq_err(vq, "Translation failure %d indirect idx %d\n",
2770 					ret, i);
2771 			return ret;
2772 		}
2773 		/* If this is an input descriptor, increment that count. */
2774 		if (access == VHOST_ACCESS_WO) {
2775 			*in_num += ret;
2776 			if (unlikely(log && ret)) {
2777 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2778 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2779 				++*log_num;
2780 			}
2781 		} else {
2782 			/* If it's an output descriptor, they're all supposed
2783 			 * to come before any input descriptors. */
2784 			if (unlikely(*in_num)) {
2785 				vq_err(vq, "Indirect descriptor "
2786 				       "has out after in: idx %d\n", i);
2787 				return -EINVAL;
2788 			}
2789 			*out_num += ret;
2790 		}
2791 	} while ((i = next_desc(vq, &desc)) != -1);
2792 	return 0;
2793 }
2794 
2795 /* This looks in the virtqueue and for the first available buffer, and converts
2796  * it to an iovec for convenient access.  Since descriptors consist of some
2797  * number of output then some number of input descriptors, it's actually two
2798  * iovecs, but we pack them into one and note how many of each there were.
2799  *
2800  * This function returns the descriptor number found, or vq->num (which is
2801  * never a valid descriptor number) if none was found.  A negative code is
2802  * returned on error. */
vhost_get_vq_desc(struct vhost_virtqueue * vq,struct iovec iov[],unsigned int iov_size,unsigned int * out_num,unsigned int * in_num,struct vhost_log * log,unsigned int * log_num)2803 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2804 		      struct iovec iov[], unsigned int iov_size,
2805 		      unsigned int *out_num, unsigned int *in_num,
2806 		      struct vhost_log *log, unsigned int *log_num)
2807 {
2808 	bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER);
2809 	struct vring_desc desc;
2810 	unsigned int i, head, found = 0;
2811 	u16 last_avail_idx = vq->last_avail_idx;
2812 	__virtio16 ring_head;
2813 	int ret, access, c = 0;
2814 
2815 	if (vq->avail_idx == vq->last_avail_idx) {
2816 		ret = vhost_get_avail_idx(vq);
2817 		if (unlikely(ret < 0))
2818 			return ret;
2819 
2820 		if (!ret)
2821 			return vq->num;
2822 	}
2823 
2824 	if (in_order)
2825 		head = vq->next_avail_head & (vq->num - 1);
2826 	else {
2827 		/* Grab the next descriptor number they're
2828 		 * advertising, and increment the index we've seen. */
2829 		if (unlikely(vhost_get_avail_head(vq, &ring_head,
2830 						  last_avail_idx))) {
2831 			vq_err(vq, "Failed to read head: idx %d address %p\n",
2832 				last_avail_idx,
2833 				&vq->avail->ring[last_avail_idx % vq->num]);
2834 			return -EFAULT;
2835 		}
2836 		head = vhost16_to_cpu(vq, ring_head);
2837 	}
2838 
2839 	/* If their number is silly, that's an error. */
2840 	if (unlikely(head >= vq->num)) {
2841 		vq_err(vq, "Guest says index %u > %u is available",
2842 		       head, vq->num);
2843 		return -EINVAL;
2844 	}
2845 
2846 	/* When we start there are none of either input nor output. */
2847 	*out_num = *in_num = 0;
2848 	if (unlikely(log))
2849 		*log_num = 0;
2850 
2851 	i = head;
2852 	do {
2853 		unsigned iov_count = *in_num + *out_num;
2854 		if (unlikely(i >= vq->num)) {
2855 			vq_err(vq, "Desc index is %u > %u, head = %u",
2856 			       i, vq->num, head);
2857 			return -EINVAL;
2858 		}
2859 		if (unlikely(++found > vq->num)) {
2860 			vq_err(vq, "Loop detected: last one at %u "
2861 			       "vq size %u head %u\n",
2862 			       i, vq->num, head);
2863 			return -EINVAL;
2864 		}
2865 		ret = vhost_get_desc(vq, &desc, i);
2866 		if (unlikely(ret)) {
2867 			vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2868 			       i, vq->desc + i);
2869 			return -EFAULT;
2870 		}
2871 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2872 			ret = get_indirect(vq, iov, iov_size,
2873 					   out_num, in_num,
2874 					   log, log_num, &desc);
2875 			if (unlikely(ret < 0)) {
2876 				if (ret != -EAGAIN)
2877 					vq_err(vq, "Failure detected "
2878 						"in indirect descriptor at idx %d\n", i);
2879 				return ret;
2880 			}
2881 			++c;
2882 			continue;
2883 		}
2884 
2885 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2886 			access = VHOST_ACCESS_WO;
2887 		else
2888 			access = VHOST_ACCESS_RO;
2889 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2890 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
2891 				     iov_size - iov_count, access);
2892 		if (unlikely(ret < 0)) {
2893 			if (ret != -EAGAIN)
2894 				vq_err(vq, "Translation failure %d descriptor idx %d\n",
2895 					ret, i);
2896 			return ret;
2897 		}
2898 		if (access == VHOST_ACCESS_WO) {
2899 			/* If this is an input descriptor,
2900 			 * increment that count. */
2901 			*in_num += ret;
2902 			if (unlikely(log && ret)) {
2903 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2904 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2905 				++*log_num;
2906 			}
2907 		} else {
2908 			/* If it's an output descriptor, they're all supposed
2909 			 * to come before any input descriptors. */
2910 			if (unlikely(*in_num)) {
2911 				vq_err(vq, "Descriptor has out after in: "
2912 				       "idx %d\n", i);
2913 				return -EINVAL;
2914 			}
2915 			*out_num += ret;
2916 		}
2917 		++c;
2918 	} while ((i = next_desc(vq, &desc)) != -1);
2919 
2920 	/* On success, increment avail index. */
2921 	vq->last_avail_idx++;
2922 	vq->next_avail_head += c;
2923 
2924 	/* Assume notifications from guest are disabled at this point,
2925 	 * if they aren't we would need to update avail_event index. */
2926 	BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2927 	return head;
2928 }
2929 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2930 
2931 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
vhost_discard_vq_desc(struct vhost_virtqueue * vq,int n)2932 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2933 {
2934 	vq->last_avail_idx -= n;
2935 }
2936 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2937 
2938 /* After we've used one of their buffers, we tell them about it.  We'll then
2939  * want to notify the guest, using eventfd. */
vhost_add_used(struct vhost_virtqueue * vq,unsigned int head,int len)2940 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2941 {
2942 	struct vring_used_elem heads = {
2943 		cpu_to_vhost32(vq, head),
2944 		cpu_to_vhost32(vq, len)
2945 	};
2946 	u16 nheads = 1;
2947 
2948 	return vhost_add_used_n(vq, &heads, &nheads, 1);
2949 }
2950 EXPORT_SYMBOL_GPL(vhost_add_used);
2951 
__vhost_add_used_n(struct vhost_virtqueue * vq,struct vring_used_elem * heads,unsigned count)2952 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2953 			    struct vring_used_elem *heads,
2954 			    unsigned count)
2955 {
2956 	vring_used_elem_t __user *used;
2957 	u16 old, new;
2958 	int start;
2959 
2960 	start = vq->last_used_idx & (vq->num - 1);
2961 	used = vq->used->ring + start;
2962 	if (vhost_put_used(vq, heads, start, count)) {
2963 		vq_err(vq, "Failed to write used");
2964 		return -EFAULT;
2965 	}
2966 	if (unlikely(vq->log_used)) {
2967 		/* Make sure data is seen before log. */
2968 		smp_wmb();
2969 		/* Log used ring entry write. */
2970 		log_used(vq, ((void __user *)used - (void __user *)vq->used),
2971 			 count * sizeof *used);
2972 	}
2973 	old = vq->last_used_idx;
2974 	new = (vq->last_used_idx += count);
2975 	/* If the driver never bothers to signal in a very long while,
2976 	 * used index might wrap around. If that happens, invalidate
2977 	 * signalled_used index we stored. TODO: make sure driver
2978 	 * signals at least once in 2^16 and remove this. */
2979 	if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2980 		vq->signalled_used_valid = false;
2981 	return 0;
2982 }
2983 
vhost_add_used_n_ooo(struct vhost_virtqueue * vq,struct vring_used_elem * heads,unsigned count)2984 static int vhost_add_used_n_ooo(struct vhost_virtqueue *vq,
2985 				struct vring_used_elem *heads,
2986 				unsigned count)
2987 {
2988 	int start, n, r;
2989 
2990 	start = vq->last_used_idx & (vq->num - 1);
2991 	n = vq->num - start;
2992 	if (n < count) {
2993 		r = __vhost_add_used_n(vq, heads, n);
2994 		if (r < 0)
2995 			return r;
2996 		heads += n;
2997 		count -= n;
2998 	}
2999 	return __vhost_add_used_n(vq, heads, count);
3000 }
3001 
vhost_add_used_n_in_order(struct vhost_virtqueue * vq,struct vring_used_elem * heads,const u16 * nheads,unsigned count)3002 static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,
3003 				     struct vring_used_elem *heads,
3004 				     const u16 *nheads,
3005 				     unsigned count)
3006 {
3007 	vring_used_elem_t __user *used;
3008 	u16 old, new = vq->last_used_idx;
3009 	int start, i;
3010 
3011 	if (!nheads)
3012 		return -EINVAL;
3013 
3014 	start = vq->last_used_idx & (vq->num - 1);
3015 	used = vq->used->ring + start;
3016 
3017 	for (i = 0; i < count; i++) {
3018 		if (vhost_put_used(vq, &heads[i], start, 1)) {
3019 			vq_err(vq, "Failed to write used");
3020 			return -EFAULT;
3021 		}
3022 		start += nheads[i];
3023 		new += nheads[i];
3024 		if (start >= vq->num)
3025 			start -= vq->num;
3026 	}
3027 
3028 	if (unlikely(vq->log_used)) {
3029 		/* Make sure data is seen before log. */
3030 		smp_wmb();
3031 		/* Log used ring entry write. */
3032 		log_used(vq, ((void __user *)used - (void __user *)vq->used),
3033 			 (vq->num - start) * sizeof *used);
3034 		if (start + count > vq->num)
3035 			log_used(vq, 0,
3036 				 (start + count - vq->num) * sizeof *used);
3037 	}
3038 
3039 	old = vq->last_used_idx;
3040 	vq->last_used_idx = new;
3041 	/* If the driver never bothers to signal in a very long while,
3042 	 * used index might wrap around. If that happens, invalidate
3043 	 * signalled_used index we stored. TODO: make sure driver
3044 	 * signals at least once in 2^16 and remove this. */
3045 	if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
3046 		vq->signalled_used_valid = false;
3047 	return 0;
3048 }
3049 
3050 /* After we've used one of their buffers, we tell them about it.  We'll then
3051  * want to notify the guest, using eventfd. */
vhost_add_used_n(struct vhost_virtqueue * vq,struct vring_used_elem * heads,u16 * nheads,unsigned count)3052 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
3053 		     u16 *nheads, unsigned count)
3054 {
3055 	bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER);
3056 	int r;
3057 
3058 	if (!in_order || !nheads)
3059 		r = vhost_add_used_n_ooo(vq, heads, count);
3060 	else
3061 		r = vhost_add_used_n_in_order(vq, heads, nheads, count);
3062 
3063 	if (r < 0)
3064 		return r;
3065 
3066 	/* Make sure buffer is written before we update index. */
3067 	smp_wmb();
3068 	if (vhost_put_used_idx(vq)) {
3069 		vq_err(vq, "Failed to increment used idx");
3070 		return -EFAULT;
3071 	}
3072 	if (unlikely(vq->log_used)) {
3073 		/* Make sure used idx is seen before log. */
3074 		smp_wmb();
3075 		/* Log used index update. */
3076 		log_used(vq, offsetof(struct vring_used, idx),
3077 			 sizeof vq->used->idx);
3078 		if (vq->log_ctx)
3079 			eventfd_signal(vq->log_ctx);
3080 	}
3081 	return r;
3082 }
3083 EXPORT_SYMBOL_GPL(vhost_add_used_n);
3084 
vhost_notify(struct vhost_dev * dev,struct vhost_virtqueue * vq)3085 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3086 {
3087 	__u16 old, new;
3088 	__virtio16 event;
3089 	bool v;
3090 	/* Flush out used index updates. This is paired
3091 	 * with the barrier that the Guest executes when enabling
3092 	 * interrupts. */
3093 	smp_mb();
3094 
3095 	if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
3096 	    unlikely(vq->avail_idx == vq->last_avail_idx))
3097 		return true;
3098 
3099 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3100 		__virtio16 flags;
3101 		if (vhost_get_avail_flags(vq, &flags)) {
3102 			vq_err(vq, "Failed to get flags");
3103 			return true;
3104 		}
3105 		return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
3106 	}
3107 	old = vq->signalled_used;
3108 	v = vq->signalled_used_valid;
3109 	new = vq->signalled_used = vq->last_used_idx;
3110 	vq->signalled_used_valid = true;
3111 
3112 	if (unlikely(!v))
3113 		return true;
3114 
3115 	if (vhost_get_used_event(vq, &event)) {
3116 		vq_err(vq, "Failed to get used event idx");
3117 		return true;
3118 	}
3119 	return vring_need_event(vhost16_to_cpu(vq, event), new, old);
3120 }
3121 
3122 /* This actually signals the guest, using eventfd. */
vhost_signal(struct vhost_dev * dev,struct vhost_virtqueue * vq)3123 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3124 {
3125 	/* Signal the Guest tell them we used something up. */
3126 	if (vq->call_ctx.ctx && vhost_notify(dev, vq))
3127 		eventfd_signal(vq->call_ctx.ctx);
3128 }
3129 EXPORT_SYMBOL_GPL(vhost_signal);
3130 
3131 /* And here's the combo meal deal.  Supersize me! */
vhost_add_used_and_signal(struct vhost_dev * dev,struct vhost_virtqueue * vq,unsigned int head,int len)3132 void vhost_add_used_and_signal(struct vhost_dev *dev,
3133 			       struct vhost_virtqueue *vq,
3134 			       unsigned int head, int len)
3135 {
3136 	vhost_add_used(vq, head, len);
3137 	vhost_signal(dev, vq);
3138 }
3139 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
3140 
3141 /* multi-buffer version of vhost_add_used_and_signal */
vhost_add_used_and_signal_n(struct vhost_dev * dev,struct vhost_virtqueue * vq,struct vring_used_elem * heads,u16 * nheads,unsigned count)3142 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
3143 				 struct vhost_virtqueue *vq,
3144 				 struct vring_used_elem *heads,
3145 				 u16 *nheads,
3146 				 unsigned count)
3147 {
3148 	vhost_add_used_n(vq, heads, nheads, count);
3149 	vhost_signal(dev, vq);
3150 }
3151 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
3152 
3153 /* return true if we're sure that available ring is empty */
vhost_vq_avail_empty(struct vhost_dev * dev,struct vhost_virtqueue * vq)3154 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3155 {
3156 	int r;
3157 
3158 	if (vq->avail_idx != vq->last_avail_idx)
3159 		return false;
3160 
3161 	r = vhost_get_avail_idx(vq);
3162 
3163 	/* Note: we treat error as non-empty here */
3164 	return r == 0;
3165 }
3166 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
3167 
3168 /* OK, now we need to know about added descriptors. */
vhost_enable_notify(struct vhost_dev * dev,struct vhost_virtqueue * vq)3169 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3170 {
3171 	int r;
3172 
3173 	if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
3174 		return false;
3175 	vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
3176 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3177 		r = vhost_update_used_flags(vq);
3178 		if (r) {
3179 			vq_err(vq, "Failed to enable notification at %p: %d\n",
3180 			       &vq->used->flags, r);
3181 			return false;
3182 		}
3183 	} else {
3184 		r = vhost_update_avail_event(vq);
3185 		if (r) {
3186 			vq_err(vq, "Failed to update avail event index at %p: %d\n",
3187 			       vhost_avail_event(vq), r);
3188 			return false;
3189 		}
3190 	}
3191 	/* They could have slipped one in as we were doing that: make
3192 	 * sure it's written, then check again. */
3193 	smp_mb();
3194 
3195 	r = vhost_get_avail_idx(vq);
3196 	/* Note: we treat error as empty here */
3197 	if (unlikely(r < 0))
3198 		return false;
3199 
3200 	return r;
3201 }
3202 EXPORT_SYMBOL_GPL(vhost_enable_notify);
3203 
3204 /* We don't need to be notified again. */
vhost_disable_notify(struct vhost_dev * dev,struct vhost_virtqueue * vq)3205 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3206 {
3207 	int r;
3208 
3209 	if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
3210 		return;
3211 	vq->used_flags |= VRING_USED_F_NO_NOTIFY;
3212 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3213 		r = vhost_update_used_flags(vq);
3214 		if (r)
3215 			vq_err(vq, "Failed to disable notification at %p: %d\n",
3216 			       &vq->used->flags, r);
3217 	}
3218 }
3219 EXPORT_SYMBOL_GPL(vhost_disable_notify);
3220 
3221 /* Create a new message. */
vhost_new_msg(struct vhost_virtqueue * vq,int type)3222 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
3223 {
3224 	/* Make sure all padding within the structure is initialized. */
3225 	struct vhost_msg_node *node = kzalloc(sizeof(*node), GFP_KERNEL);
3226 	if (!node)
3227 		return NULL;
3228 
3229 	node->vq = vq;
3230 	node->msg.type = type;
3231 	return node;
3232 }
3233 EXPORT_SYMBOL_GPL(vhost_new_msg);
3234 
vhost_enqueue_msg(struct vhost_dev * dev,struct list_head * head,struct vhost_msg_node * node)3235 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
3236 		       struct vhost_msg_node *node)
3237 {
3238 	spin_lock(&dev->iotlb_lock);
3239 	list_add_tail(&node->node, head);
3240 	spin_unlock(&dev->iotlb_lock);
3241 
3242 	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
3243 }
3244 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
3245 
vhost_dequeue_msg(struct vhost_dev * dev,struct list_head * head)3246 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
3247 					 struct list_head *head)
3248 {
3249 	struct vhost_msg_node *node = NULL;
3250 
3251 	spin_lock(&dev->iotlb_lock);
3252 	if (!list_empty(head)) {
3253 		node = list_first_entry(head, struct vhost_msg_node,
3254 					node);
3255 		list_del(&node->node);
3256 	}
3257 	spin_unlock(&dev->iotlb_lock);
3258 
3259 	return node;
3260 }
3261 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
3262 
vhost_set_backend_features(struct vhost_dev * dev,u64 features)3263 void vhost_set_backend_features(struct vhost_dev *dev, u64 features)
3264 {
3265 	struct vhost_virtqueue *vq;
3266 	int i;
3267 
3268 	mutex_lock(&dev->mutex);
3269 	for (i = 0; i < dev->nvqs; ++i) {
3270 		vq = dev->vqs[i];
3271 		mutex_lock(&vq->mutex);
3272 		vq->acked_backend_features = features;
3273 		mutex_unlock(&vq->mutex);
3274 	}
3275 	mutex_unlock(&dev->mutex);
3276 }
3277 EXPORT_SYMBOL_GPL(vhost_set_backend_features);
3278 
vhost_init(void)3279 static int __init vhost_init(void)
3280 {
3281 	return 0;
3282 }
3283 
vhost_exit(void)3284 static void __exit vhost_exit(void)
3285 {
3286 }
3287 
3288 module_init(vhost_init);
3289 module_exit(vhost_exit);
3290 
3291 MODULE_VERSION("0.0.1");
3292 MODULE_LICENSE("GPL v2");
3293 MODULE_AUTHOR("Michael S. Tsirkin");
3294 MODULE_DESCRIPTION("Host kernel accelerator for virtio");
3295