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