xref: /openbmc/linux/drivers/vhost/vhost.c (revision f9a82c48)
1 /* Copyright (C) 2009 Red Hat, Inc.
2  * Copyright (C) 2006 Rusty Russell IBM Corporation
3  *
4  * Author: Michael S. Tsirkin <mst@redhat.com>
5  *
6  * Inspiration, some code, and most witty comments come from
7  * Documentation/virtual/lguest/lguest.c, by Rusty Russell
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.
10  *
11  * Generic code for virtio server in host kernel.
12  */
13 
14 #include <linux/eventfd.h>
15 #include <linux/vhost.h>
16 #include <linux/uio.h>
17 #include <linux/mm.h>
18 #include <linux/mmu_context.h>
19 #include <linux/miscdevice.h>
20 #include <linux/mutex.h>
21 #include <linux/poll.h>
22 #include <linux/file.h>
23 #include <linux/highmem.h>
24 #include <linux/slab.h>
25 #include <linux/vmalloc.h>
26 #include <linux/kthread.h>
27 #include <linux/cgroup.h>
28 #include <linux/module.h>
29 #include <linux/sort.h>
30 #include <linux/sched/mm.h>
31 #include <linux/sched/signal.h>
32 #include <linux/interval_tree_generic.h>
33 #include <linux/nospec.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 
46 enum {
47 	VHOST_MEMORY_F_LOG = 0x1,
48 };
49 
50 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
51 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
52 
53 INTERVAL_TREE_DEFINE(struct vhost_umem_node,
54 		     rb, __u64, __subtree_last,
55 		     START, LAST, static inline, vhost_umem_interval_tree);
56 
57 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
58 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
59 {
60 	vq->user_be = !virtio_legacy_is_little_endian();
61 }
62 
63 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
64 {
65 	vq->user_be = true;
66 }
67 
68 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
69 {
70 	vq->user_be = false;
71 }
72 
73 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
74 {
75 	struct vhost_vring_state s;
76 
77 	if (vq->private_data)
78 		return -EBUSY;
79 
80 	if (copy_from_user(&s, argp, sizeof(s)))
81 		return -EFAULT;
82 
83 	if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
84 	    s.num != VHOST_VRING_BIG_ENDIAN)
85 		return -EINVAL;
86 
87 	if (s.num == VHOST_VRING_BIG_ENDIAN)
88 		vhost_enable_cross_endian_big(vq);
89 	else
90 		vhost_enable_cross_endian_little(vq);
91 
92 	return 0;
93 }
94 
95 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
96 				   int __user *argp)
97 {
98 	struct vhost_vring_state s = {
99 		.index = idx,
100 		.num = vq->user_be
101 	};
102 
103 	if (copy_to_user(argp, &s, sizeof(s)))
104 		return -EFAULT;
105 
106 	return 0;
107 }
108 
109 static void vhost_init_is_le(struct vhost_virtqueue *vq)
110 {
111 	/* Note for legacy virtio: user_be is initialized at reset time
112 	 * according to the host endianness. If userspace does not set an
113 	 * explicit endianness, the default behavior is native endian, as
114 	 * expected by legacy virtio.
115 	 */
116 	vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
117 }
118 #else
119 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
120 {
121 }
122 
123 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
124 {
125 	return -ENOIOCTLCMD;
126 }
127 
128 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
129 				   int __user *argp)
130 {
131 	return -ENOIOCTLCMD;
132 }
133 
134 static void vhost_init_is_le(struct vhost_virtqueue *vq)
135 {
136 	vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
137 		|| virtio_legacy_is_little_endian();
138 }
139 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
140 
141 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
142 {
143 	vhost_init_is_le(vq);
144 }
145 
146 struct vhost_flush_struct {
147 	struct vhost_work work;
148 	struct completion wait_event;
149 };
150 
151 static void vhost_flush_work(struct vhost_work *work)
152 {
153 	struct vhost_flush_struct *s;
154 
155 	s = container_of(work, struct vhost_flush_struct, work);
156 	complete(&s->wait_event);
157 }
158 
159 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
160 			    poll_table *pt)
161 {
162 	struct vhost_poll *poll;
163 
164 	poll = container_of(pt, struct vhost_poll, table);
165 	poll->wqh = wqh;
166 	add_wait_queue(wqh, &poll->wait);
167 }
168 
169 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
170 			     void *key)
171 {
172 	struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
173 
174 	if (!(key_to_poll(key) & poll->mask))
175 		return 0;
176 
177 	vhost_poll_queue(poll);
178 	return 0;
179 }
180 
181 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
182 {
183 	clear_bit(VHOST_WORK_QUEUED, &work->flags);
184 	work->fn = fn;
185 }
186 EXPORT_SYMBOL_GPL(vhost_work_init);
187 
188 /* Init poll structure */
189 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
190 		     __poll_t mask, struct vhost_dev *dev)
191 {
192 	init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
193 	init_poll_funcptr(&poll->table, vhost_poll_func);
194 	poll->mask = mask;
195 	poll->dev = dev;
196 	poll->wqh = NULL;
197 
198 	vhost_work_init(&poll->work, fn);
199 }
200 EXPORT_SYMBOL_GPL(vhost_poll_init);
201 
202 /* Start polling a file. We add ourselves to file's wait queue. The caller must
203  * keep a reference to a file until after vhost_poll_stop is called. */
204 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
205 {
206 	__poll_t mask;
207 	int ret = 0;
208 
209 	if (poll->wqh)
210 		return 0;
211 
212 	mask = vfs_poll(file, &poll->table);
213 	if (mask)
214 		vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
215 	if (mask & EPOLLERR) {
216 		vhost_poll_stop(poll);
217 		ret = -EINVAL;
218 	}
219 
220 	return ret;
221 }
222 EXPORT_SYMBOL_GPL(vhost_poll_start);
223 
224 /* Stop polling a file. After this function returns, it becomes safe to drop the
225  * file reference. You must also flush afterwards. */
226 void vhost_poll_stop(struct vhost_poll *poll)
227 {
228 	if (poll->wqh) {
229 		remove_wait_queue(poll->wqh, &poll->wait);
230 		poll->wqh = NULL;
231 	}
232 }
233 EXPORT_SYMBOL_GPL(vhost_poll_stop);
234 
235 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
236 {
237 	struct vhost_flush_struct flush;
238 
239 	if (dev->worker) {
240 		init_completion(&flush.wait_event);
241 		vhost_work_init(&flush.work, vhost_flush_work);
242 
243 		vhost_work_queue(dev, &flush.work);
244 		wait_for_completion(&flush.wait_event);
245 	}
246 }
247 EXPORT_SYMBOL_GPL(vhost_work_flush);
248 
249 /* Flush any work that has been scheduled. When calling this, don't hold any
250  * locks that are also used by the callback. */
251 void vhost_poll_flush(struct vhost_poll *poll)
252 {
253 	vhost_work_flush(poll->dev, &poll->work);
254 }
255 EXPORT_SYMBOL_GPL(vhost_poll_flush);
256 
257 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
258 {
259 	if (!dev->worker)
260 		return;
261 
262 	if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
263 		/* We can only add the work to the list after we're
264 		 * sure it was not in the list.
265 		 * test_and_set_bit() implies a memory barrier.
266 		 */
267 		llist_add(&work->node, &dev->work_list);
268 		wake_up_process(dev->worker);
269 	}
270 }
271 EXPORT_SYMBOL_GPL(vhost_work_queue);
272 
273 /* A lockless hint for busy polling code to exit the loop */
274 bool vhost_has_work(struct vhost_dev *dev)
275 {
276 	return !llist_empty(&dev->work_list);
277 }
278 EXPORT_SYMBOL_GPL(vhost_has_work);
279 
280 void vhost_poll_queue(struct vhost_poll *poll)
281 {
282 	vhost_work_queue(poll->dev, &poll->work);
283 }
284 EXPORT_SYMBOL_GPL(vhost_poll_queue);
285 
286 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
287 {
288 	int j;
289 
290 	for (j = 0; j < VHOST_NUM_ADDRS; j++)
291 		vq->meta_iotlb[j] = NULL;
292 }
293 
294 static void vhost_vq_meta_reset(struct vhost_dev *d)
295 {
296 	int i;
297 
298 	for (i = 0; i < d->nvqs; ++i)
299 		__vhost_vq_meta_reset(d->vqs[i]);
300 }
301 
302 static void vhost_vq_reset(struct vhost_dev *dev,
303 			   struct vhost_virtqueue *vq)
304 {
305 	vq->num = 1;
306 	vq->desc = NULL;
307 	vq->avail = NULL;
308 	vq->used = NULL;
309 	vq->last_avail_idx = 0;
310 	vq->avail_idx = 0;
311 	vq->last_used_idx = 0;
312 	vq->signalled_used = 0;
313 	vq->signalled_used_valid = false;
314 	vq->used_flags = 0;
315 	vq->log_used = false;
316 	vq->log_addr = -1ull;
317 	vq->private_data = NULL;
318 	vq->acked_features = 0;
319 	vq->acked_backend_features = 0;
320 	vq->log_base = NULL;
321 	vq->error_ctx = NULL;
322 	vq->kick = NULL;
323 	vq->call_ctx = NULL;
324 	vq->log_ctx = NULL;
325 	vhost_reset_is_le(vq);
326 	vhost_disable_cross_endian(vq);
327 	vq->busyloop_timeout = 0;
328 	vq->umem = NULL;
329 	vq->iotlb = NULL;
330 	__vhost_vq_meta_reset(vq);
331 }
332 
333 static int vhost_worker(void *data)
334 {
335 	struct vhost_dev *dev = data;
336 	struct vhost_work *work, *work_next;
337 	struct llist_node *node;
338 	mm_segment_t oldfs = get_fs();
339 
340 	set_fs(USER_DS);
341 	use_mm(dev->mm);
342 
343 	for (;;) {
344 		/* mb paired w/ kthread_stop */
345 		set_current_state(TASK_INTERRUPTIBLE);
346 
347 		if (kthread_should_stop()) {
348 			__set_current_state(TASK_RUNNING);
349 			break;
350 		}
351 
352 		node = llist_del_all(&dev->work_list);
353 		if (!node)
354 			schedule();
355 
356 		node = llist_reverse_order(node);
357 		/* make sure flag is seen after deletion */
358 		smp_wmb();
359 		llist_for_each_entry_safe(work, work_next, node, node) {
360 			clear_bit(VHOST_WORK_QUEUED, &work->flags);
361 			__set_current_state(TASK_RUNNING);
362 			work->fn(work);
363 			if (need_resched())
364 				schedule();
365 		}
366 	}
367 	unuse_mm(dev->mm);
368 	set_fs(oldfs);
369 	return 0;
370 }
371 
372 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
373 {
374 	kfree(vq->indirect);
375 	vq->indirect = NULL;
376 	kfree(vq->log);
377 	vq->log = NULL;
378 	kfree(vq->heads);
379 	vq->heads = NULL;
380 }
381 
382 /* Helper to allocate iovec buffers for all vqs. */
383 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
384 {
385 	struct vhost_virtqueue *vq;
386 	int i;
387 
388 	for (i = 0; i < dev->nvqs; ++i) {
389 		vq = dev->vqs[i];
390 		vq->indirect = kmalloc_array(UIO_MAXIOV,
391 					     sizeof(*vq->indirect),
392 					     GFP_KERNEL);
393 		vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
394 					GFP_KERNEL);
395 		vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
396 					  GFP_KERNEL);
397 		if (!vq->indirect || !vq->log || !vq->heads)
398 			goto err_nomem;
399 	}
400 	return 0;
401 
402 err_nomem:
403 	for (; i >= 0; --i)
404 		vhost_vq_free_iovecs(dev->vqs[i]);
405 	return -ENOMEM;
406 }
407 
408 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
409 {
410 	int i;
411 
412 	for (i = 0; i < dev->nvqs; ++i)
413 		vhost_vq_free_iovecs(dev->vqs[i]);
414 }
415 
416 void vhost_dev_init(struct vhost_dev *dev,
417 		    struct vhost_virtqueue **vqs, int nvqs, int iov_limit)
418 {
419 	struct vhost_virtqueue *vq;
420 	int i;
421 
422 	dev->vqs = vqs;
423 	dev->nvqs = nvqs;
424 	mutex_init(&dev->mutex);
425 	dev->log_ctx = NULL;
426 	dev->umem = NULL;
427 	dev->iotlb = NULL;
428 	dev->mm = NULL;
429 	dev->worker = NULL;
430 	dev->iov_limit = iov_limit;
431 	init_llist_head(&dev->work_list);
432 	init_waitqueue_head(&dev->wait);
433 	INIT_LIST_HEAD(&dev->read_list);
434 	INIT_LIST_HEAD(&dev->pending_list);
435 	spin_lock_init(&dev->iotlb_lock);
436 
437 
438 	for (i = 0; i < dev->nvqs; ++i) {
439 		vq = dev->vqs[i];
440 		vq->log = NULL;
441 		vq->indirect = NULL;
442 		vq->heads = NULL;
443 		vq->dev = dev;
444 		mutex_init(&vq->mutex);
445 		vhost_vq_reset(dev, vq);
446 		if (vq->handle_kick)
447 			vhost_poll_init(&vq->poll, vq->handle_kick,
448 					EPOLLIN, dev);
449 	}
450 }
451 EXPORT_SYMBOL_GPL(vhost_dev_init);
452 
453 /* Caller should have device mutex */
454 long vhost_dev_check_owner(struct vhost_dev *dev)
455 {
456 	/* Are you the owner? If not, I don't think you mean to do that */
457 	return dev->mm == current->mm ? 0 : -EPERM;
458 }
459 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
460 
461 struct vhost_attach_cgroups_struct {
462 	struct vhost_work work;
463 	struct task_struct *owner;
464 	int ret;
465 };
466 
467 static void vhost_attach_cgroups_work(struct vhost_work *work)
468 {
469 	struct vhost_attach_cgroups_struct *s;
470 
471 	s = container_of(work, struct vhost_attach_cgroups_struct, work);
472 	s->ret = cgroup_attach_task_all(s->owner, current);
473 }
474 
475 static int vhost_attach_cgroups(struct vhost_dev *dev)
476 {
477 	struct vhost_attach_cgroups_struct attach;
478 
479 	attach.owner = current;
480 	vhost_work_init(&attach.work, vhost_attach_cgroups_work);
481 	vhost_work_queue(dev, &attach.work);
482 	vhost_work_flush(dev, &attach.work);
483 	return attach.ret;
484 }
485 
486 /* Caller should have device mutex */
487 bool vhost_dev_has_owner(struct vhost_dev *dev)
488 {
489 	return dev->mm;
490 }
491 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
492 
493 /* Caller should have device mutex */
494 long vhost_dev_set_owner(struct vhost_dev *dev)
495 {
496 	struct task_struct *worker;
497 	int err;
498 
499 	/* Is there an owner already? */
500 	if (vhost_dev_has_owner(dev)) {
501 		err = -EBUSY;
502 		goto err_mm;
503 	}
504 
505 	/* No owner, become one */
506 	dev->mm = get_task_mm(current);
507 	worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
508 	if (IS_ERR(worker)) {
509 		err = PTR_ERR(worker);
510 		goto err_worker;
511 	}
512 
513 	dev->worker = worker;
514 	wake_up_process(worker);	/* avoid contributing to loadavg */
515 
516 	err = vhost_attach_cgroups(dev);
517 	if (err)
518 		goto err_cgroup;
519 
520 	err = vhost_dev_alloc_iovecs(dev);
521 	if (err)
522 		goto err_cgroup;
523 
524 	return 0;
525 err_cgroup:
526 	kthread_stop(worker);
527 	dev->worker = NULL;
528 err_worker:
529 	if (dev->mm)
530 		mmput(dev->mm);
531 	dev->mm = NULL;
532 err_mm:
533 	return err;
534 }
535 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
536 
537 struct vhost_umem *vhost_dev_reset_owner_prepare(void)
538 {
539 	return kvzalloc(sizeof(struct vhost_umem), GFP_KERNEL);
540 }
541 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
542 
543 /* Caller should have device mutex */
544 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_umem *umem)
545 {
546 	int i;
547 
548 	vhost_dev_cleanup(dev);
549 
550 	/* Restore memory to default empty mapping. */
551 	INIT_LIST_HEAD(&umem->umem_list);
552 	dev->umem = umem;
553 	/* We don't need VQ locks below since vhost_dev_cleanup makes sure
554 	 * VQs aren't running.
555 	 */
556 	for (i = 0; i < dev->nvqs; ++i)
557 		dev->vqs[i]->umem = umem;
558 }
559 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
560 
561 void vhost_dev_stop(struct vhost_dev *dev)
562 {
563 	int i;
564 
565 	for (i = 0; i < dev->nvqs; ++i) {
566 		if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
567 			vhost_poll_stop(&dev->vqs[i]->poll);
568 			vhost_poll_flush(&dev->vqs[i]->poll);
569 		}
570 	}
571 }
572 EXPORT_SYMBOL_GPL(vhost_dev_stop);
573 
574 static void vhost_umem_free(struct vhost_umem *umem,
575 			    struct vhost_umem_node *node)
576 {
577 	vhost_umem_interval_tree_remove(node, &umem->umem_tree);
578 	list_del(&node->link);
579 	kfree(node);
580 	umem->numem--;
581 }
582 
583 static void vhost_umem_clean(struct vhost_umem *umem)
584 {
585 	struct vhost_umem_node *node, *tmp;
586 
587 	if (!umem)
588 		return;
589 
590 	list_for_each_entry_safe(node, tmp, &umem->umem_list, link)
591 		vhost_umem_free(umem, node);
592 
593 	kvfree(umem);
594 }
595 
596 static void vhost_clear_msg(struct vhost_dev *dev)
597 {
598 	struct vhost_msg_node *node, *n;
599 
600 	spin_lock(&dev->iotlb_lock);
601 
602 	list_for_each_entry_safe(node, n, &dev->read_list, node) {
603 		list_del(&node->node);
604 		kfree(node);
605 	}
606 
607 	list_for_each_entry_safe(node, n, &dev->pending_list, node) {
608 		list_del(&node->node);
609 		kfree(node);
610 	}
611 
612 	spin_unlock(&dev->iotlb_lock);
613 }
614 
615 void vhost_dev_cleanup(struct vhost_dev *dev)
616 {
617 	int i;
618 
619 	for (i = 0; i < dev->nvqs; ++i) {
620 		if (dev->vqs[i]->error_ctx)
621 			eventfd_ctx_put(dev->vqs[i]->error_ctx);
622 		if (dev->vqs[i]->kick)
623 			fput(dev->vqs[i]->kick);
624 		if (dev->vqs[i]->call_ctx)
625 			eventfd_ctx_put(dev->vqs[i]->call_ctx);
626 		vhost_vq_reset(dev, dev->vqs[i]);
627 	}
628 	vhost_dev_free_iovecs(dev);
629 	if (dev->log_ctx)
630 		eventfd_ctx_put(dev->log_ctx);
631 	dev->log_ctx = NULL;
632 	/* No one will access memory at this point */
633 	vhost_umem_clean(dev->umem);
634 	dev->umem = NULL;
635 	vhost_umem_clean(dev->iotlb);
636 	dev->iotlb = NULL;
637 	vhost_clear_msg(dev);
638 	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
639 	WARN_ON(!llist_empty(&dev->work_list));
640 	if (dev->worker) {
641 		kthread_stop(dev->worker);
642 		dev->worker = NULL;
643 	}
644 	if (dev->mm)
645 		mmput(dev->mm);
646 	dev->mm = NULL;
647 }
648 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
649 
650 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
651 {
652 	u64 a = addr / VHOST_PAGE_SIZE / 8;
653 
654 	/* Make sure 64 bit math will not overflow. */
655 	if (a > ULONG_MAX - (unsigned long)log_base ||
656 	    a + (unsigned long)log_base > ULONG_MAX)
657 		return false;
658 
659 	return access_ok(log_base + a,
660 			 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
661 }
662 
663 static bool vhost_overflow(u64 uaddr, u64 size)
664 {
665 	/* Make sure 64 bit math will not overflow. */
666 	return uaddr > ULONG_MAX || size > ULONG_MAX || uaddr > ULONG_MAX - size;
667 }
668 
669 /* Caller should have vq mutex and device mutex. */
670 static bool vq_memory_access_ok(void __user *log_base, struct vhost_umem *umem,
671 				int log_all)
672 {
673 	struct vhost_umem_node *node;
674 
675 	if (!umem)
676 		return false;
677 
678 	list_for_each_entry(node, &umem->umem_list, link) {
679 		unsigned long a = node->userspace_addr;
680 
681 		if (vhost_overflow(node->userspace_addr, node->size))
682 			return false;
683 
684 
685 		if (!access_ok((void __user *)a,
686 				    node->size))
687 			return false;
688 		else if (log_all && !log_access_ok(log_base,
689 						   node->start,
690 						   node->size))
691 			return false;
692 	}
693 	return true;
694 }
695 
696 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
697 					       u64 addr, unsigned int size,
698 					       int type)
699 {
700 	const struct vhost_umem_node *node = vq->meta_iotlb[type];
701 
702 	if (!node)
703 		return NULL;
704 
705 	return (void *)(uintptr_t)(node->userspace_addr + addr - node->start);
706 }
707 
708 /* Can we switch to this memory table? */
709 /* Caller should have device mutex but not vq mutex */
710 static bool memory_access_ok(struct vhost_dev *d, struct vhost_umem *umem,
711 			     int log_all)
712 {
713 	int i;
714 
715 	for (i = 0; i < d->nvqs; ++i) {
716 		bool ok;
717 		bool log;
718 
719 		mutex_lock(&d->vqs[i]->mutex);
720 		log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
721 		/* If ring is inactive, will check when it's enabled. */
722 		if (d->vqs[i]->private_data)
723 			ok = vq_memory_access_ok(d->vqs[i]->log_base,
724 						 umem, log);
725 		else
726 			ok = true;
727 		mutex_unlock(&d->vqs[i]->mutex);
728 		if (!ok)
729 			return false;
730 	}
731 	return true;
732 }
733 
734 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
735 			  struct iovec iov[], int iov_size, int access);
736 
737 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
738 			      const void *from, unsigned size)
739 {
740 	int ret;
741 
742 	if (!vq->iotlb)
743 		return __copy_to_user(to, from, size);
744 	else {
745 		/* This function should be called after iotlb
746 		 * prefetch, which means we're sure that all vq
747 		 * could be access through iotlb. So -EAGAIN should
748 		 * not happen in this case.
749 		 */
750 		struct iov_iter t;
751 		void __user *uaddr = vhost_vq_meta_fetch(vq,
752 				     (u64)(uintptr_t)to, size,
753 				     VHOST_ADDR_USED);
754 
755 		if (uaddr)
756 			return __copy_to_user(uaddr, from, size);
757 
758 		ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
759 				     ARRAY_SIZE(vq->iotlb_iov),
760 				     VHOST_ACCESS_WO);
761 		if (ret < 0)
762 			goto out;
763 		iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
764 		ret = copy_to_iter(from, size, &t);
765 		if (ret == size)
766 			ret = 0;
767 	}
768 out:
769 	return ret;
770 }
771 
772 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
773 				void __user *from, unsigned size)
774 {
775 	int ret;
776 
777 	if (!vq->iotlb)
778 		return __copy_from_user(to, from, size);
779 	else {
780 		/* This function should be called after iotlb
781 		 * prefetch, which means we're sure that vq
782 		 * could be access through iotlb. So -EAGAIN should
783 		 * not happen in this case.
784 		 */
785 		void __user *uaddr = vhost_vq_meta_fetch(vq,
786 				     (u64)(uintptr_t)from, size,
787 				     VHOST_ADDR_DESC);
788 		struct iov_iter f;
789 
790 		if (uaddr)
791 			return __copy_from_user(to, uaddr, size);
792 
793 		ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
794 				     ARRAY_SIZE(vq->iotlb_iov),
795 				     VHOST_ACCESS_RO);
796 		if (ret < 0) {
797 			vq_err(vq, "IOTLB translation failure: uaddr "
798 			       "%p size 0x%llx\n", from,
799 			       (unsigned long long) size);
800 			goto out;
801 		}
802 		iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
803 		ret = copy_from_iter(to, size, &f);
804 		if (ret == size)
805 			ret = 0;
806 	}
807 
808 out:
809 	return ret;
810 }
811 
812 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
813 					  void __user *addr, unsigned int size,
814 					  int type)
815 {
816 	int ret;
817 
818 	ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
819 			     ARRAY_SIZE(vq->iotlb_iov),
820 			     VHOST_ACCESS_RO);
821 	if (ret < 0) {
822 		vq_err(vq, "IOTLB translation failure: uaddr "
823 			"%p size 0x%llx\n", addr,
824 			(unsigned long long) size);
825 		return NULL;
826 	}
827 
828 	if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
829 		vq_err(vq, "Non atomic userspace memory access: uaddr "
830 			"%p size 0x%llx\n", addr,
831 			(unsigned long long) size);
832 		return NULL;
833 	}
834 
835 	return vq->iotlb_iov[0].iov_base;
836 }
837 
838 /* This function should be called after iotlb
839  * prefetch, which means we're sure that vq
840  * could be access through iotlb. So -EAGAIN should
841  * not happen in this case.
842  */
843 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
844 					    void *addr, unsigned int size,
845 					    int type)
846 {
847 	void __user *uaddr = vhost_vq_meta_fetch(vq,
848 			     (u64)(uintptr_t)addr, size, type);
849 	if (uaddr)
850 		return uaddr;
851 
852 	return __vhost_get_user_slow(vq, addr, size, type);
853 }
854 
855 #define vhost_put_user(vq, x, ptr)		\
856 ({ \
857 	int ret = -EFAULT; \
858 	if (!vq->iotlb) { \
859 		ret = __put_user(x, ptr); \
860 	} else { \
861 		__typeof__(ptr) to = \
862 			(__typeof__(ptr)) __vhost_get_user(vq, ptr,	\
863 					  sizeof(*ptr), VHOST_ADDR_USED); \
864 		if (to != NULL) \
865 			ret = __put_user(x, to); \
866 		else \
867 			ret = -EFAULT;	\
868 	} \
869 	ret; \
870 })
871 
872 #define vhost_get_user(vq, x, ptr, type)		\
873 ({ \
874 	int ret; \
875 	if (!vq->iotlb) { \
876 		ret = __get_user(x, ptr); \
877 	} else { \
878 		__typeof__(ptr) from = \
879 			(__typeof__(ptr)) __vhost_get_user(vq, ptr, \
880 							   sizeof(*ptr), \
881 							   type); \
882 		if (from != NULL) \
883 			ret = __get_user(x, from); \
884 		else \
885 			ret = -EFAULT; \
886 	} \
887 	ret; \
888 })
889 
890 #define vhost_get_avail(vq, x, ptr) \
891 	vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
892 
893 #define vhost_get_used(vq, x, ptr) \
894 	vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
895 
896 static void vhost_dev_lock_vqs(struct vhost_dev *d)
897 {
898 	int i = 0;
899 	for (i = 0; i < d->nvqs; ++i)
900 		mutex_lock_nested(&d->vqs[i]->mutex, i);
901 }
902 
903 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
904 {
905 	int i = 0;
906 	for (i = 0; i < d->nvqs; ++i)
907 		mutex_unlock(&d->vqs[i]->mutex);
908 }
909 
910 static int vhost_new_umem_range(struct vhost_umem *umem,
911 				u64 start, u64 size, u64 end,
912 				u64 userspace_addr, int perm)
913 {
914 	struct vhost_umem_node *tmp, *node = kmalloc(sizeof(*node), GFP_ATOMIC);
915 
916 	if (!node)
917 		return -ENOMEM;
918 
919 	if (umem->numem == max_iotlb_entries) {
920 		tmp = list_first_entry(&umem->umem_list, typeof(*tmp), link);
921 		vhost_umem_free(umem, tmp);
922 	}
923 
924 	node->start = start;
925 	node->size = size;
926 	node->last = end;
927 	node->userspace_addr = userspace_addr;
928 	node->perm = perm;
929 	INIT_LIST_HEAD(&node->link);
930 	list_add_tail(&node->link, &umem->umem_list);
931 	vhost_umem_interval_tree_insert(node, &umem->umem_tree);
932 	umem->numem++;
933 
934 	return 0;
935 }
936 
937 static void vhost_del_umem_range(struct vhost_umem *umem,
938 				 u64 start, u64 end)
939 {
940 	struct vhost_umem_node *node;
941 
942 	while ((node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
943 							   start, end)))
944 		vhost_umem_free(umem, node);
945 }
946 
947 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
948 				  struct vhost_iotlb_msg *msg)
949 {
950 	struct vhost_msg_node *node, *n;
951 
952 	spin_lock(&d->iotlb_lock);
953 
954 	list_for_each_entry_safe(node, n, &d->pending_list, node) {
955 		struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
956 		if (msg->iova <= vq_msg->iova &&
957 		    msg->iova + msg->size - 1 >= vq_msg->iova &&
958 		    vq_msg->type == VHOST_IOTLB_MISS) {
959 			vhost_poll_queue(&node->vq->poll);
960 			list_del(&node->node);
961 			kfree(node);
962 		}
963 	}
964 
965 	spin_unlock(&d->iotlb_lock);
966 }
967 
968 static bool umem_access_ok(u64 uaddr, u64 size, int access)
969 {
970 	unsigned long a = uaddr;
971 
972 	/* Make sure 64 bit math will not overflow. */
973 	if (vhost_overflow(uaddr, size))
974 		return false;
975 
976 	if ((access & VHOST_ACCESS_RO) &&
977 	    !access_ok((void __user *)a, size))
978 		return false;
979 	if ((access & VHOST_ACCESS_WO) &&
980 	    !access_ok((void __user *)a, size))
981 		return false;
982 	return true;
983 }
984 
985 static int vhost_process_iotlb_msg(struct vhost_dev *dev,
986 				   struct vhost_iotlb_msg *msg)
987 {
988 	int ret = 0;
989 
990 	mutex_lock(&dev->mutex);
991 	vhost_dev_lock_vqs(dev);
992 	switch (msg->type) {
993 	case VHOST_IOTLB_UPDATE:
994 		if (!dev->iotlb) {
995 			ret = -EFAULT;
996 			break;
997 		}
998 		if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
999 			ret = -EFAULT;
1000 			break;
1001 		}
1002 		vhost_vq_meta_reset(dev);
1003 		if (vhost_new_umem_range(dev->iotlb, msg->iova, msg->size,
1004 					 msg->iova + msg->size - 1,
1005 					 msg->uaddr, msg->perm)) {
1006 			ret = -ENOMEM;
1007 			break;
1008 		}
1009 		vhost_iotlb_notify_vq(dev, msg);
1010 		break;
1011 	case VHOST_IOTLB_INVALIDATE:
1012 		if (!dev->iotlb) {
1013 			ret = -EFAULT;
1014 			break;
1015 		}
1016 		vhost_vq_meta_reset(dev);
1017 		vhost_del_umem_range(dev->iotlb, msg->iova,
1018 				     msg->iova + msg->size - 1);
1019 		break;
1020 	default:
1021 		ret = -EINVAL;
1022 		break;
1023 	}
1024 
1025 	vhost_dev_unlock_vqs(dev);
1026 	mutex_unlock(&dev->mutex);
1027 
1028 	return ret;
1029 }
1030 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1031 			     struct iov_iter *from)
1032 {
1033 	struct vhost_iotlb_msg msg;
1034 	size_t offset;
1035 	int type, ret;
1036 
1037 	ret = copy_from_iter(&type, sizeof(type), from);
1038 	if (ret != sizeof(type)) {
1039 		ret = -EINVAL;
1040 		goto done;
1041 	}
1042 
1043 	switch (type) {
1044 	case VHOST_IOTLB_MSG:
1045 		/* There maybe a hole after type for V1 message type,
1046 		 * so skip it here.
1047 		 */
1048 		offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1049 		break;
1050 	case VHOST_IOTLB_MSG_V2:
1051 		offset = sizeof(__u32);
1052 		break;
1053 	default:
1054 		ret = -EINVAL;
1055 		goto done;
1056 	}
1057 
1058 	iov_iter_advance(from, offset);
1059 	ret = copy_from_iter(&msg, sizeof(msg), from);
1060 	if (ret != sizeof(msg)) {
1061 		ret = -EINVAL;
1062 		goto done;
1063 	}
1064 	if (vhost_process_iotlb_msg(dev, &msg)) {
1065 		ret = -EFAULT;
1066 		goto done;
1067 	}
1068 
1069 	ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1070 	      sizeof(struct vhost_msg_v2);
1071 done:
1072 	return ret;
1073 }
1074 EXPORT_SYMBOL(vhost_chr_write_iter);
1075 
1076 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1077 			    poll_table *wait)
1078 {
1079 	__poll_t mask = 0;
1080 
1081 	poll_wait(file, &dev->wait, wait);
1082 
1083 	if (!list_empty(&dev->read_list))
1084 		mask |= EPOLLIN | EPOLLRDNORM;
1085 
1086 	return mask;
1087 }
1088 EXPORT_SYMBOL(vhost_chr_poll);
1089 
1090 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1091 			    int noblock)
1092 {
1093 	DEFINE_WAIT(wait);
1094 	struct vhost_msg_node *node;
1095 	ssize_t ret = 0;
1096 	unsigned size = sizeof(struct vhost_msg);
1097 
1098 	if (iov_iter_count(to) < size)
1099 		return 0;
1100 
1101 	while (1) {
1102 		if (!noblock)
1103 			prepare_to_wait(&dev->wait, &wait,
1104 					TASK_INTERRUPTIBLE);
1105 
1106 		node = vhost_dequeue_msg(dev, &dev->read_list);
1107 		if (node)
1108 			break;
1109 		if (noblock) {
1110 			ret = -EAGAIN;
1111 			break;
1112 		}
1113 		if (signal_pending(current)) {
1114 			ret = -ERESTARTSYS;
1115 			break;
1116 		}
1117 		if (!dev->iotlb) {
1118 			ret = -EBADFD;
1119 			break;
1120 		}
1121 
1122 		schedule();
1123 	}
1124 
1125 	if (!noblock)
1126 		finish_wait(&dev->wait, &wait);
1127 
1128 	if (node) {
1129 		struct vhost_iotlb_msg *msg;
1130 		void *start = &node->msg;
1131 
1132 		switch (node->msg.type) {
1133 		case VHOST_IOTLB_MSG:
1134 			size = sizeof(node->msg);
1135 			msg = &node->msg.iotlb;
1136 			break;
1137 		case VHOST_IOTLB_MSG_V2:
1138 			size = sizeof(node->msg_v2);
1139 			msg = &node->msg_v2.iotlb;
1140 			break;
1141 		default:
1142 			BUG();
1143 			break;
1144 		}
1145 
1146 		ret = copy_to_iter(start, size, to);
1147 		if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1148 			kfree(node);
1149 			return ret;
1150 		}
1151 		vhost_enqueue_msg(dev, &dev->pending_list, node);
1152 	}
1153 
1154 	return ret;
1155 }
1156 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1157 
1158 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1159 {
1160 	struct vhost_dev *dev = vq->dev;
1161 	struct vhost_msg_node *node;
1162 	struct vhost_iotlb_msg *msg;
1163 	bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1164 
1165 	node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1166 	if (!node)
1167 		return -ENOMEM;
1168 
1169 	if (v2) {
1170 		node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1171 		msg = &node->msg_v2.iotlb;
1172 	} else {
1173 		msg = &node->msg.iotlb;
1174 	}
1175 
1176 	msg->type = VHOST_IOTLB_MISS;
1177 	msg->iova = iova;
1178 	msg->perm = access;
1179 
1180 	vhost_enqueue_msg(dev, &dev->read_list, node);
1181 
1182 	return 0;
1183 }
1184 
1185 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1186 			 struct vring_desc __user *desc,
1187 			 struct vring_avail __user *avail,
1188 			 struct vring_used __user *used)
1189 
1190 {
1191 	size_t s __maybe_unused = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1192 
1193 	return access_ok(desc, num * sizeof *desc) &&
1194 	       access_ok(avail,
1195 			 sizeof *avail + num * sizeof *avail->ring + s) &&
1196 	       access_ok(used,
1197 			sizeof *used + num * sizeof *used->ring + s);
1198 }
1199 
1200 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1201 				 const struct vhost_umem_node *node,
1202 				 int type)
1203 {
1204 	int access = (type == VHOST_ADDR_USED) ?
1205 		     VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1206 
1207 	if (likely(node->perm & access))
1208 		vq->meta_iotlb[type] = node;
1209 }
1210 
1211 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1212 			    int access, u64 addr, u64 len, int type)
1213 {
1214 	const struct vhost_umem_node *node;
1215 	struct vhost_umem *umem = vq->iotlb;
1216 	u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1217 
1218 	if (vhost_vq_meta_fetch(vq, addr, len, type))
1219 		return true;
1220 
1221 	while (len > s) {
1222 		node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1223 							   addr,
1224 							   last);
1225 		if (node == NULL || node->start > addr) {
1226 			vhost_iotlb_miss(vq, addr, access);
1227 			return false;
1228 		} else if (!(node->perm & access)) {
1229 			/* Report the possible access violation by
1230 			 * request another translation from userspace.
1231 			 */
1232 			return false;
1233 		}
1234 
1235 		size = node->size - addr + node->start;
1236 
1237 		if (orig_addr == addr && size >= len)
1238 			vhost_vq_meta_update(vq, node, type);
1239 
1240 		s += size;
1241 		addr += size;
1242 	}
1243 
1244 	return true;
1245 }
1246 
1247 int vq_iotlb_prefetch(struct vhost_virtqueue *vq)
1248 {
1249 	size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1250 	unsigned int num = vq->num;
1251 
1252 	if (!vq->iotlb)
1253 		return 1;
1254 
1255 	return iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->desc,
1256 			       num * sizeof(*vq->desc), VHOST_ADDR_DESC) &&
1257 	       iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->avail,
1258 			       sizeof *vq->avail +
1259 			       num * sizeof(*vq->avail->ring) + s,
1260 			       VHOST_ADDR_AVAIL) &&
1261 	       iotlb_access_ok(vq, VHOST_ACCESS_WO, (u64)(uintptr_t)vq->used,
1262 			       sizeof *vq->used +
1263 			       num * sizeof(*vq->used->ring) + s,
1264 			       VHOST_ADDR_USED);
1265 }
1266 EXPORT_SYMBOL_GPL(vq_iotlb_prefetch);
1267 
1268 /* Can we log writes? */
1269 /* Caller should have device mutex but not vq mutex */
1270 bool vhost_log_access_ok(struct vhost_dev *dev)
1271 {
1272 	return memory_access_ok(dev, dev->umem, 1);
1273 }
1274 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1275 
1276 /* Verify access for write logging. */
1277 /* Caller should have vq mutex and device mutex */
1278 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1279 			     void __user *log_base)
1280 {
1281 	size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1282 
1283 	return vq_memory_access_ok(log_base, vq->umem,
1284 				   vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1285 		(!vq->log_used || log_access_ok(log_base, vq->log_addr,
1286 					sizeof *vq->used +
1287 					vq->num * sizeof *vq->used->ring + s));
1288 }
1289 
1290 /* Can we start vq? */
1291 /* Caller should have vq mutex and device mutex */
1292 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1293 {
1294 	if (!vq_log_access_ok(vq, vq->log_base))
1295 		return false;
1296 
1297 	/* Access validation occurs at prefetch time with IOTLB */
1298 	if (vq->iotlb)
1299 		return true;
1300 
1301 	return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1302 }
1303 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1304 
1305 static struct vhost_umem *vhost_umem_alloc(void)
1306 {
1307 	struct vhost_umem *umem = kvzalloc(sizeof(*umem), GFP_KERNEL);
1308 
1309 	if (!umem)
1310 		return NULL;
1311 
1312 	umem->umem_tree = RB_ROOT_CACHED;
1313 	umem->numem = 0;
1314 	INIT_LIST_HEAD(&umem->umem_list);
1315 
1316 	return umem;
1317 }
1318 
1319 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1320 {
1321 	struct vhost_memory mem, *newmem;
1322 	struct vhost_memory_region *region;
1323 	struct vhost_umem *newumem, *oldumem;
1324 	unsigned long size = offsetof(struct vhost_memory, regions);
1325 	int i;
1326 
1327 	if (copy_from_user(&mem, m, size))
1328 		return -EFAULT;
1329 	if (mem.padding)
1330 		return -EOPNOTSUPP;
1331 	if (mem.nregions > max_mem_regions)
1332 		return -E2BIG;
1333 	newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1334 			GFP_KERNEL);
1335 	if (!newmem)
1336 		return -ENOMEM;
1337 
1338 	memcpy(newmem, &mem, size);
1339 	if (copy_from_user(newmem->regions, m->regions,
1340 			   mem.nregions * sizeof *m->regions)) {
1341 		kvfree(newmem);
1342 		return -EFAULT;
1343 	}
1344 
1345 	newumem = vhost_umem_alloc();
1346 	if (!newumem) {
1347 		kvfree(newmem);
1348 		return -ENOMEM;
1349 	}
1350 
1351 	for (region = newmem->regions;
1352 	     region < newmem->regions + mem.nregions;
1353 	     region++) {
1354 		if (vhost_new_umem_range(newumem,
1355 					 region->guest_phys_addr,
1356 					 region->memory_size,
1357 					 region->guest_phys_addr +
1358 					 region->memory_size - 1,
1359 					 region->userspace_addr,
1360 					 VHOST_ACCESS_RW))
1361 			goto err;
1362 	}
1363 
1364 	if (!memory_access_ok(d, newumem, 0))
1365 		goto err;
1366 
1367 	oldumem = d->umem;
1368 	d->umem = newumem;
1369 
1370 	/* All memory accesses are done under some VQ mutex. */
1371 	for (i = 0; i < d->nvqs; ++i) {
1372 		mutex_lock(&d->vqs[i]->mutex);
1373 		d->vqs[i]->umem = newumem;
1374 		mutex_unlock(&d->vqs[i]->mutex);
1375 	}
1376 
1377 	kvfree(newmem);
1378 	vhost_umem_clean(oldumem);
1379 	return 0;
1380 
1381 err:
1382 	vhost_umem_clean(newumem);
1383 	kvfree(newmem);
1384 	return -EFAULT;
1385 }
1386 
1387 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1388 {
1389 	struct file *eventfp, *filep = NULL;
1390 	bool pollstart = false, pollstop = false;
1391 	struct eventfd_ctx *ctx = NULL;
1392 	u32 __user *idxp = argp;
1393 	struct vhost_virtqueue *vq;
1394 	struct vhost_vring_state s;
1395 	struct vhost_vring_file f;
1396 	struct vhost_vring_addr a;
1397 	u32 idx;
1398 	long r;
1399 
1400 	r = get_user(idx, idxp);
1401 	if (r < 0)
1402 		return r;
1403 	if (idx >= d->nvqs)
1404 		return -ENOBUFS;
1405 
1406 	idx = array_index_nospec(idx, d->nvqs);
1407 	vq = d->vqs[idx];
1408 
1409 	mutex_lock(&vq->mutex);
1410 
1411 	switch (ioctl) {
1412 	case VHOST_SET_VRING_NUM:
1413 		/* Resizing ring with an active backend?
1414 		 * You don't want to do that. */
1415 		if (vq->private_data) {
1416 			r = -EBUSY;
1417 			break;
1418 		}
1419 		if (copy_from_user(&s, argp, sizeof s)) {
1420 			r = -EFAULT;
1421 			break;
1422 		}
1423 		if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
1424 			r = -EINVAL;
1425 			break;
1426 		}
1427 		vq->num = s.num;
1428 		break;
1429 	case VHOST_SET_VRING_BASE:
1430 		/* Moving base with an active backend?
1431 		 * You don't want to do that. */
1432 		if (vq->private_data) {
1433 			r = -EBUSY;
1434 			break;
1435 		}
1436 		if (copy_from_user(&s, argp, sizeof s)) {
1437 			r = -EFAULT;
1438 			break;
1439 		}
1440 		if (s.num > 0xffff) {
1441 			r = -EINVAL;
1442 			break;
1443 		}
1444 		vq->last_avail_idx = s.num;
1445 		/* Forget the cached index value. */
1446 		vq->avail_idx = vq->last_avail_idx;
1447 		break;
1448 	case VHOST_GET_VRING_BASE:
1449 		s.index = idx;
1450 		s.num = vq->last_avail_idx;
1451 		if (copy_to_user(argp, &s, sizeof s))
1452 			r = -EFAULT;
1453 		break;
1454 	case VHOST_SET_VRING_ADDR:
1455 		if (copy_from_user(&a, argp, sizeof a)) {
1456 			r = -EFAULT;
1457 			break;
1458 		}
1459 		if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
1460 			r = -EOPNOTSUPP;
1461 			break;
1462 		}
1463 		/* For 32bit, verify that the top 32bits of the user
1464 		   data are set to zero. */
1465 		if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1466 		    (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1467 		    (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
1468 			r = -EFAULT;
1469 			break;
1470 		}
1471 
1472 		/* Make sure it's safe to cast pointers to vring types. */
1473 		BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1474 		BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1475 		if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1476 		    (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1477 		    (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1))) {
1478 			r = -EINVAL;
1479 			break;
1480 		}
1481 
1482 		/* We only verify access here if backend is configured.
1483 		 * If it is not, we don't as size might not have been setup.
1484 		 * We will verify when backend is configured. */
1485 		if (vq->private_data) {
1486 			if (!vq_access_ok(vq, vq->num,
1487 				(void __user *)(unsigned long)a.desc_user_addr,
1488 				(void __user *)(unsigned long)a.avail_user_addr,
1489 				(void __user *)(unsigned long)a.used_user_addr)) {
1490 				r = -EINVAL;
1491 				break;
1492 			}
1493 
1494 			/* Also validate log access for used ring if enabled. */
1495 			if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
1496 			    !log_access_ok(vq->log_base, a.log_guest_addr,
1497 					   sizeof *vq->used +
1498 					   vq->num * sizeof *vq->used->ring)) {
1499 				r = -EINVAL;
1500 				break;
1501 			}
1502 		}
1503 
1504 		vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1505 		vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1506 		vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1507 		vq->log_addr = a.log_guest_addr;
1508 		vq->used = (void __user *)(unsigned long)a.used_user_addr;
1509 		break;
1510 	case VHOST_SET_VRING_KICK:
1511 		if (copy_from_user(&f, argp, sizeof f)) {
1512 			r = -EFAULT;
1513 			break;
1514 		}
1515 		eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1516 		if (IS_ERR(eventfp)) {
1517 			r = PTR_ERR(eventfp);
1518 			break;
1519 		}
1520 		if (eventfp != vq->kick) {
1521 			pollstop = (filep = vq->kick) != NULL;
1522 			pollstart = (vq->kick = eventfp) != NULL;
1523 		} else
1524 			filep = eventfp;
1525 		break;
1526 	case VHOST_SET_VRING_CALL:
1527 		if (copy_from_user(&f, argp, sizeof f)) {
1528 			r = -EFAULT;
1529 			break;
1530 		}
1531 		ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1532 		if (IS_ERR(ctx)) {
1533 			r = PTR_ERR(ctx);
1534 			break;
1535 		}
1536 		swap(ctx, vq->call_ctx);
1537 		break;
1538 	case VHOST_SET_VRING_ERR:
1539 		if (copy_from_user(&f, argp, sizeof f)) {
1540 			r = -EFAULT;
1541 			break;
1542 		}
1543 		ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1544 		if (IS_ERR(ctx)) {
1545 			r = PTR_ERR(ctx);
1546 			break;
1547 		}
1548 		swap(ctx, vq->error_ctx);
1549 		break;
1550 	case VHOST_SET_VRING_ENDIAN:
1551 		r = vhost_set_vring_endian(vq, argp);
1552 		break;
1553 	case VHOST_GET_VRING_ENDIAN:
1554 		r = vhost_get_vring_endian(vq, idx, argp);
1555 		break;
1556 	case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1557 		if (copy_from_user(&s, argp, sizeof(s))) {
1558 			r = -EFAULT;
1559 			break;
1560 		}
1561 		vq->busyloop_timeout = s.num;
1562 		break;
1563 	case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1564 		s.index = idx;
1565 		s.num = vq->busyloop_timeout;
1566 		if (copy_to_user(argp, &s, sizeof(s)))
1567 			r = -EFAULT;
1568 		break;
1569 	default:
1570 		r = -ENOIOCTLCMD;
1571 	}
1572 
1573 	if (pollstop && vq->handle_kick)
1574 		vhost_poll_stop(&vq->poll);
1575 
1576 	if (!IS_ERR_OR_NULL(ctx))
1577 		eventfd_ctx_put(ctx);
1578 	if (filep)
1579 		fput(filep);
1580 
1581 	if (pollstart && vq->handle_kick)
1582 		r = vhost_poll_start(&vq->poll, vq->kick);
1583 
1584 	mutex_unlock(&vq->mutex);
1585 
1586 	if (pollstop && vq->handle_kick)
1587 		vhost_poll_flush(&vq->poll);
1588 	return r;
1589 }
1590 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1591 
1592 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1593 {
1594 	struct vhost_umem *niotlb, *oiotlb;
1595 	int i;
1596 
1597 	niotlb = vhost_umem_alloc();
1598 	if (!niotlb)
1599 		return -ENOMEM;
1600 
1601 	oiotlb = d->iotlb;
1602 	d->iotlb = niotlb;
1603 
1604 	for (i = 0; i < d->nvqs; ++i) {
1605 		struct vhost_virtqueue *vq = d->vqs[i];
1606 
1607 		mutex_lock(&vq->mutex);
1608 		vq->iotlb = niotlb;
1609 		__vhost_vq_meta_reset(vq);
1610 		mutex_unlock(&vq->mutex);
1611 	}
1612 
1613 	vhost_umem_clean(oiotlb);
1614 
1615 	return 0;
1616 }
1617 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1618 
1619 /* Caller must have device mutex */
1620 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1621 {
1622 	struct eventfd_ctx *ctx;
1623 	u64 p;
1624 	long r;
1625 	int i, fd;
1626 
1627 	/* If you are not the owner, you can become one */
1628 	if (ioctl == VHOST_SET_OWNER) {
1629 		r = vhost_dev_set_owner(d);
1630 		goto done;
1631 	}
1632 
1633 	/* You must be the owner to do anything else */
1634 	r = vhost_dev_check_owner(d);
1635 	if (r)
1636 		goto done;
1637 
1638 	switch (ioctl) {
1639 	case VHOST_SET_MEM_TABLE:
1640 		r = vhost_set_memory(d, argp);
1641 		break;
1642 	case VHOST_SET_LOG_BASE:
1643 		if (copy_from_user(&p, argp, sizeof p)) {
1644 			r = -EFAULT;
1645 			break;
1646 		}
1647 		if ((u64)(unsigned long)p != p) {
1648 			r = -EFAULT;
1649 			break;
1650 		}
1651 		for (i = 0; i < d->nvqs; ++i) {
1652 			struct vhost_virtqueue *vq;
1653 			void __user *base = (void __user *)(unsigned long)p;
1654 			vq = d->vqs[i];
1655 			mutex_lock(&vq->mutex);
1656 			/* If ring is inactive, will check when it's enabled. */
1657 			if (vq->private_data && !vq_log_access_ok(vq, base))
1658 				r = -EFAULT;
1659 			else
1660 				vq->log_base = base;
1661 			mutex_unlock(&vq->mutex);
1662 		}
1663 		break;
1664 	case VHOST_SET_LOG_FD:
1665 		r = get_user(fd, (int __user *)argp);
1666 		if (r < 0)
1667 			break;
1668 		ctx = fd == -1 ? NULL : eventfd_ctx_fdget(fd);
1669 		if (IS_ERR(ctx)) {
1670 			r = PTR_ERR(ctx);
1671 			break;
1672 		}
1673 		swap(ctx, d->log_ctx);
1674 		for (i = 0; i < d->nvqs; ++i) {
1675 			mutex_lock(&d->vqs[i]->mutex);
1676 			d->vqs[i]->log_ctx = d->log_ctx;
1677 			mutex_unlock(&d->vqs[i]->mutex);
1678 		}
1679 		if (ctx)
1680 			eventfd_ctx_put(ctx);
1681 		break;
1682 	default:
1683 		r = -ENOIOCTLCMD;
1684 		break;
1685 	}
1686 done:
1687 	return r;
1688 }
1689 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1690 
1691 /* TODO: This is really inefficient.  We need something like get_user()
1692  * (instruction directly accesses the data, with an exception table entry
1693  * returning -EFAULT). See Documentation/x86/exception-tables.txt.
1694  */
1695 static int set_bit_to_user(int nr, void __user *addr)
1696 {
1697 	unsigned long log = (unsigned long)addr;
1698 	struct page *page;
1699 	void *base;
1700 	int bit = nr + (log % PAGE_SIZE) * 8;
1701 	int r;
1702 
1703 	r = get_user_pages_fast(log, 1, 1, &page);
1704 	if (r < 0)
1705 		return r;
1706 	BUG_ON(r != 1);
1707 	base = kmap_atomic(page);
1708 	set_bit(bit, base);
1709 	kunmap_atomic(base);
1710 	set_page_dirty_lock(page);
1711 	put_page(page);
1712 	return 0;
1713 }
1714 
1715 static int log_write(void __user *log_base,
1716 		     u64 write_address, u64 write_length)
1717 {
1718 	u64 write_page = write_address / VHOST_PAGE_SIZE;
1719 	int r;
1720 
1721 	if (!write_length)
1722 		return 0;
1723 	write_length += write_address % VHOST_PAGE_SIZE;
1724 	for (;;) {
1725 		u64 base = (u64)(unsigned long)log_base;
1726 		u64 log = base + write_page / 8;
1727 		int bit = write_page % 8;
1728 		if ((u64)(unsigned long)log != log)
1729 			return -EFAULT;
1730 		r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1731 		if (r < 0)
1732 			return r;
1733 		if (write_length <= VHOST_PAGE_SIZE)
1734 			break;
1735 		write_length -= VHOST_PAGE_SIZE;
1736 		write_page += 1;
1737 	}
1738 	return r;
1739 }
1740 
1741 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1742 {
1743 	struct vhost_umem *umem = vq->umem;
1744 	struct vhost_umem_node *u;
1745 	u64 start, end, l, min;
1746 	int r;
1747 	bool hit = false;
1748 
1749 	while (len) {
1750 		min = len;
1751 		/* More than one GPAs can be mapped into a single HVA. So
1752 		 * iterate all possible umems here to be safe.
1753 		 */
1754 		list_for_each_entry(u, &umem->umem_list, link) {
1755 			if (u->userspace_addr > hva - 1 + len ||
1756 			    u->userspace_addr - 1 + u->size < hva)
1757 				continue;
1758 			start = max(u->userspace_addr, hva);
1759 			end = min(u->userspace_addr - 1 + u->size,
1760 				  hva - 1 + len);
1761 			l = end - start + 1;
1762 			r = log_write(vq->log_base,
1763 				      u->start + start - u->userspace_addr,
1764 				      l);
1765 			if (r < 0)
1766 				return r;
1767 			hit = true;
1768 			min = min(l, min);
1769 		}
1770 
1771 		if (!hit)
1772 			return -EFAULT;
1773 
1774 		len -= min;
1775 		hva += min;
1776 	}
1777 
1778 	return 0;
1779 }
1780 
1781 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1782 {
1783 	struct iovec iov[64];
1784 	int i, ret;
1785 
1786 	if (!vq->iotlb)
1787 		return log_write(vq->log_base, vq->log_addr + used_offset, len);
1788 
1789 	ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1790 			     len, iov, 64, VHOST_ACCESS_WO);
1791 	if (ret < 0)
1792 		return ret;
1793 
1794 	for (i = 0; i < ret; i++) {
1795 		ret = log_write_hva(vq,	(uintptr_t)iov[i].iov_base,
1796 				    iov[i].iov_len);
1797 		if (ret)
1798 			return ret;
1799 	}
1800 
1801 	return 0;
1802 }
1803 
1804 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1805 		    unsigned int log_num, u64 len, struct iovec *iov, int count)
1806 {
1807 	int i, r;
1808 
1809 	/* Make sure data written is seen before log. */
1810 	smp_wmb();
1811 
1812 	if (vq->iotlb) {
1813 		for (i = 0; i < count; i++) {
1814 			r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1815 					  iov[i].iov_len);
1816 			if (r < 0)
1817 				return r;
1818 		}
1819 		return 0;
1820 	}
1821 
1822 	for (i = 0; i < log_num; ++i) {
1823 		u64 l = min(log[i].len, len);
1824 		r = log_write(vq->log_base, log[i].addr, l);
1825 		if (r < 0)
1826 			return r;
1827 		len -= l;
1828 		if (!len) {
1829 			if (vq->log_ctx)
1830 				eventfd_signal(vq->log_ctx, 1);
1831 			return 0;
1832 		}
1833 	}
1834 	/* Length written exceeds what we have stored. This is a bug. */
1835 	BUG();
1836 	return 0;
1837 }
1838 EXPORT_SYMBOL_GPL(vhost_log_write);
1839 
1840 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1841 {
1842 	void __user *used;
1843 	if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
1844 			   &vq->used->flags) < 0)
1845 		return -EFAULT;
1846 	if (unlikely(vq->log_used)) {
1847 		/* Make sure the flag is seen before log. */
1848 		smp_wmb();
1849 		/* Log used flag write. */
1850 		used = &vq->used->flags;
1851 		log_used(vq, (used - (void __user *)vq->used),
1852 			 sizeof vq->used->flags);
1853 		if (vq->log_ctx)
1854 			eventfd_signal(vq->log_ctx, 1);
1855 	}
1856 	return 0;
1857 }
1858 
1859 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1860 {
1861 	if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
1862 			   vhost_avail_event(vq)))
1863 		return -EFAULT;
1864 	if (unlikely(vq->log_used)) {
1865 		void __user *used;
1866 		/* Make sure the event is seen before log. */
1867 		smp_wmb();
1868 		/* Log avail event write */
1869 		used = vhost_avail_event(vq);
1870 		log_used(vq, (used - (void __user *)vq->used),
1871 			 sizeof *vhost_avail_event(vq));
1872 		if (vq->log_ctx)
1873 			eventfd_signal(vq->log_ctx, 1);
1874 	}
1875 	return 0;
1876 }
1877 
1878 int vhost_vq_init_access(struct vhost_virtqueue *vq)
1879 {
1880 	__virtio16 last_used_idx;
1881 	int r;
1882 	bool is_le = vq->is_le;
1883 
1884 	if (!vq->private_data)
1885 		return 0;
1886 
1887 	vhost_init_is_le(vq);
1888 
1889 	r = vhost_update_used_flags(vq);
1890 	if (r)
1891 		goto err;
1892 	vq->signalled_used_valid = false;
1893 	if (!vq->iotlb &&
1894 	    !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
1895 		r = -EFAULT;
1896 		goto err;
1897 	}
1898 	r = vhost_get_used(vq, last_used_idx, &vq->used->idx);
1899 	if (r) {
1900 		vq_err(vq, "Can't access used idx at %p\n",
1901 		       &vq->used->idx);
1902 		goto err;
1903 	}
1904 	vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1905 	return 0;
1906 
1907 err:
1908 	vq->is_le = is_le;
1909 	return r;
1910 }
1911 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
1912 
1913 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1914 			  struct iovec iov[], int iov_size, int access)
1915 {
1916 	const struct vhost_umem_node *node;
1917 	struct vhost_dev *dev = vq->dev;
1918 	struct vhost_umem *umem = dev->iotlb ? dev->iotlb : dev->umem;
1919 	struct iovec *_iov;
1920 	u64 s = 0;
1921 	int ret = 0;
1922 
1923 	while ((u64)len > s) {
1924 		u64 size;
1925 		if (unlikely(ret >= iov_size)) {
1926 			ret = -ENOBUFS;
1927 			break;
1928 		}
1929 
1930 		node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1931 							addr, addr + len - 1);
1932 		if (node == NULL || node->start > addr) {
1933 			if (umem != dev->iotlb) {
1934 				ret = -EFAULT;
1935 				break;
1936 			}
1937 			ret = -EAGAIN;
1938 			break;
1939 		} else if (!(node->perm & access)) {
1940 			ret = -EPERM;
1941 			break;
1942 		}
1943 
1944 		_iov = iov + ret;
1945 		size = node->size - addr + node->start;
1946 		_iov->iov_len = min((u64)len - s, size);
1947 		_iov->iov_base = (void __user *)(unsigned long)
1948 			(node->userspace_addr + addr - node->start);
1949 		s += size;
1950 		addr += size;
1951 		++ret;
1952 	}
1953 
1954 	if (ret == -EAGAIN)
1955 		vhost_iotlb_miss(vq, addr, access);
1956 	return ret;
1957 }
1958 
1959 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
1960  * function returns the next descriptor in the chain,
1961  * or -1U if we're at the end. */
1962 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1963 {
1964 	unsigned int next;
1965 
1966 	/* If this descriptor says it doesn't chain, we're done. */
1967 	if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1968 		return -1U;
1969 
1970 	/* Check they're not leading us off end of descriptors. */
1971 	next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
1972 	return next;
1973 }
1974 
1975 static int get_indirect(struct vhost_virtqueue *vq,
1976 			struct iovec iov[], unsigned int iov_size,
1977 			unsigned int *out_num, unsigned int *in_num,
1978 			struct vhost_log *log, unsigned int *log_num,
1979 			struct vring_desc *indirect)
1980 {
1981 	struct vring_desc desc;
1982 	unsigned int i = 0, count, found = 0;
1983 	u32 len = vhost32_to_cpu(vq, indirect->len);
1984 	struct iov_iter from;
1985 	int ret, access;
1986 
1987 	/* Sanity check */
1988 	if (unlikely(len % sizeof desc)) {
1989 		vq_err(vq, "Invalid length in indirect descriptor: "
1990 		       "len 0x%llx not multiple of 0x%zx\n",
1991 		       (unsigned long long)len,
1992 		       sizeof desc);
1993 		return -EINVAL;
1994 	}
1995 
1996 	ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
1997 			     UIO_MAXIOV, VHOST_ACCESS_RO);
1998 	if (unlikely(ret < 0)) {
1999 		if (ret != -EAGAIN)
2000 			vq_err(vq, "Translation failure %d in indirect.\n", ret);
2001 		return ret;
2002 	}
2003 	iov_iter_init(&from, READ, vq->indirect, ret, len);
2004 
2005 	/* We will use the result as an address to read from, so most
2006 	 * architectures only need a compiler barrier here. */
2007 	read_barrier_depends();
2008 
2009 	count = len / sizeof desc;
2010 	/* Buffers are chained via a 16 bit next field, so
2011 	 * we can have at most 2^16 of these. */
2012 	if (unlikely(count > USHRT_MAX + 1)) {
2013 		vq_err(vq, "Indirect buffer length too big: %d\n",
2014 		       indirect->len);
2015 		return -E2BIG;
2016 	}
2017 
2018 	do {
2019 		unsigned iov_count = *in_num + *out_num;
2020 		if (unlikely(++found > count)) {
2021 			vq_err(vq, "Loop detected: last one at %u "
2022 			       "indirect size %u\n",
2023 			       i, count);
2024 			return -EINVAL;
2025 		}
2026 		if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2027 			vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2028 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2029 			return -EINVAL;
2030 		}
2031 		if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2032 			vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2033 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2034 			return -EINVAL;
2035 		}
2036 
2037 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2038 			access = VHOST_ACCESS_WO;
2039 		else
2040 			access = VHOST_ACCESS_RO;
2041 
2042 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2043 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
2044 				     iov_size - iov_count, access);
2045 		if (unlikely(ret < 0)) {
2046 			if (ret != -EAGAIN)
2047 				vq_err(vq, "Translation failure %d indirect idx %d\n",
2048 					ret, i);
2049 			return ret;
2050 		}
2051 		/* If this is an input descriptor, increment that count. */
2052 		if (access == VHOST_ACCESS_WO) {
2053 			*in_num += ret;
2054 			if (unlikely(log)) {
2055 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2056 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2057 				++*log_num;
2058 			}
2059 		} else {
2060 			/* If it's an output descriptor, they're all supposed
2061 			 * to come before any input descriptors. */
2062 			if (unlikely(*in_num)) {
2063 				vq_err(vq, "Indirect descriptor "
2064 				       "has out after in: idx %d\n", i);
2065 				return -EINVAL;
2066 			}
2067 			*out_num += ret;
2068 		}
2069 	} while ((i = next_desc(vq, &desc)) != -1);
2070 	return 0;
2071 }
2072 
2073 /* This looks in the virtqueue and for the first available buffer, and converts
2074  * it to an iovec for convenient access.  Since descriptors consist of some
2075  * number of output then some number of input descriptors, it's actually two
2076  * iovecs, but we pack them into one and note how many of each there were.
2077  *
2078  * This function returns the descriptor number found, or vq->num (which is
2079  * never a valid descriptor number) if none was found.  A negative code is
2080  * returned on error. */
2081 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2082 		      struct iovec iov[], unsigned int iov_size,
2083 		      unsigned int *out_num, unsigned int *in_num,
2084 		      struct vhost_log *log, unsigned int *log_num)
2085 {
2086 	struct vring_desc desc;
2087 	unsigned int i, head, found = 0;
2088 	u16 last_avail_idx;
2089 	__virtio16 avail_idx;
2090 	__virtio16 ring_head;
2091 	int ret, access;
2092 
2093 	/* Check it isn't doing very strange things with descriptor numbers. */
2094 	last_avail_idx = vq->last_avail_idx;
2095 
2096 	if (vq->avail_idx == vq->last_avail_idx) {
2097 		if (unlikely(vhost_get_avail(vq, avail_idx, &vq->avail->idx))) {
2098 			vq_err(vq, "Failed to access avail idx at %p\n",
2099 				&vq->avail->idx);
2100 			return -EFAULT;
2101 		}
2102 		vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2103 
2104 		if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2105 			vq_err(vq, "Guest moved used index from %u to %u",
2106 				last_avail_idx, vq->avail_idx);
2107 			return -EFAULT;
2108 		}
2109 
2110 		/* If there's nothing new since last we looked, return
2111 		 * invalid.
2112 		 */
2113 		if (vq->avail_idx == last_avail_idx)
2114 			return vq->num;
2115 
2116 		/* Only get avail ring entries after they have been
2117 		 * exposed by guest.
2118 		 */
2119 		smp_rmb();
2120 	}
2121 
2122 	/* Grab the next descriptor number they're advertising, and increment
2123 	 * the index we've seen. */
2124 	if (unlikely(vhost_get_avail(vq, ring_head,
2125 		     &vq->avail->ring[last_avail_idx & (vq->num - 1)]))) {
2126 		vq_err(vq, "Failed to read head: idx %d address %p\n",
2127 		       last_avail_idx,
2128 		       &vq->avail->ring[last_avail_idx % vq->num]);
2129 		return -EFAULT;
2130 	}
2131 
2132 	head = vhost16_to_cpu(vq, ring_head);
2133 
2134 	/* If their number is silly, that's an error. */
2135 	if (unlikely(head >= vq->num)) {
2136 		vq_err(vq, "Guest says index %u > %u is available",
2137 		       head, vq->num);
2138 		return -EINVAL;
2139 	}
2140 
2141 	/* When we start there are none of either input nor output. */
2142 	*out_num = *in_num = 0;
2143 	if (unlikely(log))
2144 		*log_num = 0;
2145 
2146 	i = head;
2147 	do {
2148 		unsigned iov_count = *in_num + *out_num;
2149 		if (unlikely(i >= vq->num)) {
2150 			vq_err(vq, "Desc index is %u > %u, head = %u",
2151 			       i, vq->num, head);
2152 			return -EINVAL;
2153 		}
2154 		if (unlikely(++found > vq->num)) {
2155 			vq_err(vq, "Loop detected: last one at %u "
2156 			       "vq size %u head %u\n",
2157 			       i, vq->num, head);
2158 			return -EINVAL;
2159 		}
2160 		ret = vhost_copy_from_user(vq, &desc, vq->desc + i,
2161 					   sizeof desc);
2162 		if (unlikely(ret)) {
2163 			vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2164 			       i, vq->desc + i);
2165 			return -EFAULT;
2166 		}
2167 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2168 			ret = get_indirect(vq, iov, iov_size,
2169 					   out_num, in_num,
2170 					   log, log_num, &desc);
2171 			if (unlikely(ret < 0)) {
2172 				if (ret != -EAGAIN)
2173 					vq_err(vq, "Failure detected "
2174 						"in indirect descriptor at idx %d\n", i);
2175 				return ret;
2176 			}
2177 			continue;
2178 		}
2179 
2180 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2181 			access = VHOST_ACCESS_WO;
2182 		else
2183 			access = VHOST_ACCESS_RO;
2184 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2185 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
2186 				     iov_size - iov_count, access);
2187 		if (unlikely(ret < 0)) {
2188 			if (ret != -EAGAIN)
2189 				vq_err(vq, "Translation failure %d descriptor idx %d\n",
2190 					ret, i);
2191 			return ret;
2192 		}
2193 		if (access == VHOST_ACCESS_WO) {
2194 			/* If this is an input descriptor,
2195 			 * increment that count. */
2196 			*in_num += ret;
2197 			if (unlikely(log)) {
2198 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2199 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2200 				++*log_num;
2201 			}
2202 		} else {
2203 			/* If it's an output descriptor, they're all supposed
2204 			 * to come before any input descriptors. */
2205 			if (unlikely(*in_num)) {
2206 				vq_err(vq, "Descriptor has out after in: "
2207 				       "idx %d\n", i);
2208 				return -EINVAL;
2209 			}
2210 			*out_num += ret;
2211 		}
2212 	} while ((i = next_desc(vq, &desc)) != -1);
2213 
2214 	/* On success, increment avail index. */
2215 	vq->last_avail_idx++;
2216 
2217 	/* Assume notifications from guest are disabled at this point,
2218 	 * if they aren't we would need to update avail_event index. */
2219 	BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2220 	return head;
2221 }
2222 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2223 
2224 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2225 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2226 {
2227 	vq->last_avail_idx -= n;
2228 }
2229 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2230 
2231 /* After we've used one of their buffers, we tell them about it.  We'll then
2232  * want to notify the guest, using eventfd. */
2233 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2234 {
2235 	struct vring_used_elem heads = {
2236 		cpu_to_vhost32(vq, head),
2237 		cpu_to_vhost32(vq, len)
2238 	};
2239 
2240 	return vhost_add_used_n(vq, &heads, 1);
2241 }
2242 EXPORT_SYMBOL_GPL(vhost_add_used);
2243 
2244 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2245 			    struct vring_used_elem *heads,
2246 			    unsigned count)
2247 {
2248 	struct vring_used_elem __user *used;
2249 	u16 old, new;
2250 	int start;
2251 
2252 	start = vq->last_used_idx & (vq->num - 1);
2253 	used = vq->used->ring + start;
2254 	if (count == 1) {
2255 		if (vhost_put_user(vq, heads[0].id, &used->id)) {
2256 			vq_err(vq, "Failed to write used id");
2257 			return -EFAULT;
2258 		}
2259 		if (vhost_put_user(vq, heads[0].len, &used->len)) {
2260 			vq_err(vq, "Failed to write used len");
2261 			return -EFAULT;
2262 		}
2263 	} else if (vhost_copy_to_user(vq, used, heads, count * sizeof *used)) {
2264 		vq_err(vq, "Failed to write used");
2265 		return -EFAULT;
2266 	}
2267 	if (unlikely(vq->log_used)) {
2268 		/* Make sure data is seen before log. */
2269 		smp_wmb();
2270 		/* Log used ring entry write. */
2271 		log_used(vq, ((void __user *)used - (void __user *)vq->used),
2272 			 count * sizeof *used);
2273 	}
2274 	old = vq->last_used_idx;
2275 	new = (vq->last_used_idx += count);
2276 	/* If the driver never bothers to signal in a very long while,
2277 	 * used index might wrap around. If that happens, invalidate
2278 	 * signalled_used index we stored. TODO: make sure driver
2279 	 * signals at least once in 2^16 and remove this. */
2280 	if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2281 		vq->signalled_used_valid = false;
2282 	return 0;
2283 }
2284 
2285 /* After we've used one of their buffers, we tell them about it.  We'll then
2286  * want to notify the guest, using eventfd. */
2287 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2288 		     unsigned count)
2289 {
2290 	int start, n, r;
2291 
2292 	start = vq->last_used_idx & (vq->num - 1);
2293 	n = vq->num - start;
2294 	if (n < count) {
2295 		r = __vhost_add_used_n(vq, heads, n);
2296 		if (r < 0)
2297 			return r;
2298 		heads += n;
2299 		count -= n;
2300 	}
2301 	r = __vhost_add_used_n(vq, heads, count);
2302 
2303 	/* Make sure buffer is written before we update index. */
2304 	smp_wmb();
2305 	if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
2306 			   &vq->used->idx)) {
2307 		vq_err(vq, "Failed to increment used idx");
2308 		return -EFAULT;
2309 	}
2310 	if (unlikely(vq->log_used)) {
2311 		/* Make sure used idx is seen before log. */
2312 		smp_wmb();
2313 		/* Log used index update. */
2314 		log_used(vq, offsetof(struct vring_used, idx),
2315 			 sizeof vq->used->idx);
2316 		if (vq->log_ctx)
2317 			eventfd_signal(vq->log_ctx, 1);
2318 	}
2319 	return r;
2320 }
2321 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2322 
2323 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2324 {
2325 	__u16 old, new;
2326 	__virtio16 event;
2327 	bool v;
2328 	/* Flush out used index updates. This is paired
2329 	 * with the barrier that the Guest executes when enabling
2330 	 * interrupts. */
2331 	smp_mb();
2332 
2333 	if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2334 	    unlikely(vq->avail_idx == vq->last_avail_idx))
2335 		return true;
2336 
2337 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2338 		__virtio16 flags;
2339 		if (vhost_get_avail(vq, flags, &vq->avail->flags)) {
2340 			vq_err(vq, "Failed to get flags");
2341 			return true;
2342 		}
2343 		return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2344 	}
2345 	old = vq->signalled_used;
2346 	v = vq->signalled_used_valid;
2347 	new = vq->signalled_used = vq->last_used_idx;
2348 	vq->signalled_used_valid = true;
2349 
2350 	if (unlikely(!v))
2351 		return true;
2352 
2353 	if (vhost_get_avail(vq, event, vhost_used_event(vq))) {
2354 		vq_err(vq, "Failed to get used event idx");
2355 		return true;
2356 	}
2357 	return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2358 }
2359 
2360 /* This actually signals the guest, using eventfd. */
2361 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2362 {
2363 	/* Signal the Guest tell them we used something up. */
2364 	if (vq->call_ctx && vhost_notify(dev, vq))
2365 		eventfd_signal(vq->call_ctx, 1);
2366 }
2367 EXPORT_SYMBOL_GPL(vhost_signal);
2368 
2369 /* And here's the combo meal deal.  Supersize me! */
2370 void vhost_add_used_and_signal(struct vhost_dev *dev,
2371 			       struct vhost_virtqueue *vq,
2372 			       unsigned int head, int len)
2373 {
2374 	vhost_add_used(vq, head, len);
2375 	vhost_signal(dev, vq);
2376 }
2377 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2378 
2379 /* multi-buffer version of vhost_add_used_and_signal */
2380 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2381 				 struct vhost_virtqueue *vq,
2382 				 struct vring_used_elem *heads, unsigned count)
2383 {
2384 	vhost_add_used_n(vq, heads, count);
2385 	vhost_signal(dev, vq);
2386 }
2387 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2388 
2389 /* return true if we're sure that avaiable ring is empty */
2390 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2391 {
2392 	__virtio16 avail_idx;
2393 	int r;
2394 
2395 	if (vq->avail_idx != vq->last_avail_idx)
2396 		return false;
2397 
2398 	r = vhost_get_avail(vq, avail_idx, &vq->avail->idx);
2399 	if (unlikely(r))
2400 		return false;
2401 	vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2402 
2403 	return vq->avail_idx == vq->last_avail_idx;
2404 }
2405 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2406 
2407 /* OK, now we need to know about added descriptors. */
2408 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2409 {
2410 	__virtio16 avail_idx;
2411 	int r;
2412 
2413 	if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2414 		return false;
2415 	vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2416 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2417 		r = vhost_update_used_flags(vq);
2418 		if (r) {
2419 			vq_err(vq, "Failed to enable notification at %p: %d\n",
2420 			       &vq->used->flags, r);
2421 			return false;
2422 		}
2423 	} else {
2424 		r = vhost_update_avail_event(vq, vq->avail_idx);
2425 		if (r) {
2426 			vq_err(vq, "Failed to update avail event index at %p: %d\n",
2427 			       vhost_avail_event(vq), r);
2428 			return false;
2429 		}
2430 	}
2431 	/* They could have slipped one in as we were doing that: make
2432 	 * sure it's written, then check again. */
2433 	smp_mb();
2434 	r = vhost_get_avail(vq, avail_idx, &vq->avail->idx);
2435 	if (r) {
2436 		vq_err(vq, "Failed to check avail idx at %p: %d\n",
2437 		       &vq->avail->idx, r);
2438 		return false;
2439 	}
2440 
2441 	return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2442 }
2443 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2444 
2445 /* We don't need to be notified again. */
2446 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2447 {
2448 	int r;
2449 
2450 	if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2451 		return;
2452 	vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2453 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2454 		r = vhost_update_used_flags(vq);
2455 		if (r)
2456 			vq_err(vq, "Failed to enable notification at %p: %d\n",
2457 			       &vq->used->flags, r);
2458 	}
2459 }
2460 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2461 
2462 /* Create a new message. */
2463 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2464 {
2465 	struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2466 	if (!node)
2467 		return NULL;
2468 
2469 	/* Make sure all padding within the structure is initialized. */
2470 	memset(&node->msg, 0, sizeof node->msg);
2471 	node->vq = vq;
2472 	node->msg.type = type;
2473 	return node;
2474 }
2475 EXPORT_SYMBOL_GPL(vhost_new_msg);
2476 
2477 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2478 		       struct vhost_msg_node *node)
2479 {
2480 	spin_lock(&dev->iotlb_lock);
2481 	list_add_tail(&node->node, head);
2482 	spin_unlock(&dev->iotlb_lock);
2483 
2484 	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2485 }
2486 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2487 
2488 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2489 					 struct list_head *head)
2490 {
2491 	struct vhost_msg_node *node = NULL;
2492 
2493 	spin_lock(&dev->iotlb_lock);
2494 	if (!list_empty(head)) {
2495 		node = list_first_entry(head, struct vhost_msg_node,
2496 					node);
2497 		list_del(&node->node);
2498 	}
2499 	spin_unlock(&dev->iotlb_lock);
2500 
2501 	return node;
2502 }
2503 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2504 
2505 
2506 static int __init vhost_init(void)
2507 {
2508 	return 0;
2509 }
2510 
2511 static void __exit vhost_exit(void)
2512 {
2513 }
2514 
2515 module_init(vhost_init);
2516 module_exit(vhost_exit);
2517 
2518 MODULE_VERSION("0.0.1");
2519 MODULE_LICENSE("GPL v2");
2520 MODULE_AUTHOR("Michael S. Tsirkin");
2521 MODULE_DESCRIPTION("Host kernel accelerator for virtio");
2522