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