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