1 /* Copyright (C) 2009 Red Hat, Inc.
2 * Copyright (C) 2006 Rusty Russell IBM Corporation
4 * Author: Michael S. Tsirkin <mst@redhat.com>
6 * Inspiration, some code, and most witty comments come from
7 * Documentation/virtual/lguest/lguest.c, by Rusty Russell
9 * This work is licensed under the terms of the GNU GPL, version 2.
11 * Generic code for virtio server in host kernel.
14 #include <linux/eventfd.h>
15 #include <linux/vhost.h>
16 #include <linux/uio.h>
18 #include <linux/mmu_context.h>
19 #include <linux/miscdevice.h>
20 #include <linux/mutex.h>
21 #include <linux/poll.h>
22 #include <linux/file.h>
23 #include <linux/highmem.h>
24 #include <linux/slab.h>
25 #include <linux/vmalloc.h>
26 #include <linux/kthread.h>
27 #include <linux/cgroup.h>
28 #include <linux/module.h>
29 #include <linux/sort.h>
30 #include <linux/interval_tree_generic.h>
31 #include <linux/nospec.h>
35 static ushort max_mem_regions = 64;
36 module_param(max_mem_regions, ushort, 0444);
37 MODULE_PARM_DESC(max_mem_regions,
38 "Maximum number of memory regions in memory map. (default: 64)");
39 static int max_iotlb_entries = 2048;
40 module_param(max_iotlb_entries, int, 0444);
41 MODULE_PARM_DESC(max_iotlb_entries,
42 "Maximum number of iotlb entries. (default: 2048)");
45 VHOST_MEMORY_F_LOG = 0x1,
48 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
49 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
51 INTERVAL_TREE_DEFINE(struct vhost_umem_node,
52 rb, __u64, __subtree_last,
53 START, LAST, , vhost_umem_interval_tree);
55 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
56 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
58 vq->user_be = !virtio_legacy_is_little_endian();
61 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
66 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
71 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
73 struct vhost_vring_state s;
78 if (copy_from_user(&s, argp, sizeof(s)))
81 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
82 s.num != VHOST_VRING_BIG_ENDIAN)
85 if (s.num == VHOST_VRING_BIG_ENDIAN)
86 vhost_enable_cross_endian_big(vq);
88 vhost_enable_cross_endian_little(vq);
93 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
96 struct vhost_vring_state s = {
101 if (copy_to_user(argp, &s, sizeof(s)))
107 static void vhost_init_is_le(struct vhost_virtqueue *vq)
109 /* Note for legacy virtio: user_be is initialized at reset time
110 * according to the host endianness. If userspace does not set an
111 * explicit endianness, the default behavior is native endian, as
112 * expected by legacy virtio.
114 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
117 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
121 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
126 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
132 static void vhost_init_is_le(struct vhost_virtqueue *vq)
134 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
135 || virtio_legacy_is_little_endian();
137 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
139 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
141 vhost_init_is_le(vq);
144 struct vhost_flush_struct {
145 struct vhost_work work;
146 struct completion wait_event;
149 static void vhost_flush_work(struct vhost_work *work)
151 struct vhost_flush_struct *s;
153 s = container_of(work, struct vhost_flush_struct, work);
154 complete(&s->wait_event);
157 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
160 struct vhost_poll *poll;
162 poll = container_of(pt, struct vhost_poll, table);
164 add_wait_queue(wqh, &poll->wait);
167 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
170 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
172 if (!((unsigned long)key & poll->mask))
175 vhost_poll_queue(poll);
179 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
181 clear_bit(VHOST_WORK_QUEUED, &work->flags);
183 init_waitqueue_head(&work->done);
185 EXPORT_SYMBOL_GPL(vhost_work_init);
187 /* Init poll structure */
188 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
189 unsigned long mask, struct vhost_dev *dev)
191 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
192 init_poll_funcptr(&poll->table, vhost_poll_func);
197 vhost_work_init(&poll->work, fn);
199 EXPORT_SYMBOL_GPL(vhost_poll_init);
201 /* Start polling a file. We add ourselves to file's wait queue. The caller must
202 * keep a reference to a file until after vhost_poll_stop is called. */
203 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
211 mask = file->f_op->poll(file, &poll->table);
213 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
214 if (mask & POLLERR) {
215 vhost_poll_stop(poll);
221 EXPORT_SYMBOL_GPL(vhost_poll_start);
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)
228 remove_wait_queue(poll->wqh, &poll->wait);
232 EXPORT_SYMBOL_GPL(vhost_poll_stop);
234 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
236 struct vhost_flush_struct flush;
239 init_completion(&flush.wait_event);
240 vhost_work_init(&flush.work, vhost_flush_work);
242 vhost_work_queue(dev, &flush.work);
243 wait_for_completion(&flush.wait_event);
246 EXPORT_SYMBOL_GPL(vhost_work_flush);
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)
252 vhost_work_flush(poll->dev, &poll->work);
254 EXPORT_SYMBOL_GPL(vhost_poll_flush);
256 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
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.
266 llist_add(&work->node, &dev->work_list);
267 wake_up_process(dev->worker);
270 EXPORT_SYMBOL_GPL(vhost_work_queue);
272 /* A lockless hint for busy polling code to exit the loop */
273 bool vhost_has_work(struct vhost_dev *dev)
275 return !llist_empty(&dev->work_list);
277 EXPORT_SYMBOL_GPL(vhost_has_work);
279 void vhost_poll_queue(struct vhost_poll *poll)
281 vhost_work_queue(poll->dev, &poll->work);
283 EXPORT_SYMBOL_GPL(vhost_poll_queue);
285 static void vhost_vq_reset(struct vhost_dev *dev,
286 struct vhost_virtqueue *vq)
292 vq->last_avail_idx = 0;
294 vq->last_used_idx = 0;
295 vq->signalled_used = 0;
296 vq->signalled_used_valid = false;
298 vq->log_used = false;
299 vq->log_addr = -1ull;
300 vq->private_data = NULL;
301 vq->acked_features = 0;
303 vq->error_ctx = NULL;
309 vhost_disable_cross_endian(vq);
310 vhost_reset_is_le(vq);
311 vq->busyloop_timeout = 0;
316 static int vhost_worker(void *data)
318 struct vhost_dev *dev = data;
319 struct vhost_work *work, *work_next;
320 struct llist_node *node;
321 mm_segment_t oldfs = get_fs();
327 /* mb paired w/ kthread_stop */
328 set_current_state(TASK_INTERRUPTIBLE);
330 if (kthread_should_stop()) {
331 __set_current_state(TASK_RUNNING);
335 node = llist_del_all(&dev->work_list);
339 node = llist_reverse_order(node);
340 /* make sure flag is seen after deletion */
342 llist_for_each_entry_safe(work, work_next, node, node) {
343 clear_bit(VHOST_WORK_QUEUED, &work->flags);
344 __set_current_state(TASK_RUNNING);
355 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
365 /* Helper to allocate iovec buffers for all vqs. */
366 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
368 struct vhost_virtqueue *vq;
371 for (i = 0; i < dev->nvqs; ++i) {
373 vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
375 vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
376 vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
377 if (!vq->indirect || !vq->log || !vq->heads)
384 vhost_vq_free_iovecs(dev->vqs[i]);
388 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
392 for (i = 0; i < dev->nvqs; ++i)
393 vhost_vq_free_iovecs(dev->vqs[i]);
396 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
397 int pkts, int total_len)
399 struct vhost_dev *dev = vq->dev;
401 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
402 pkts >= dev->weight) {
403 vhost_poll_queue(&vq->poll);
409 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
411 void vhost_dev_init(struct vhost_dev *dev,
412 struct vhost_virtqueue **vqs, int nvqs,
413 int weight, int byte_weight)
415 struct vhost_virtqueue *vq;
420 mutex_init(&dev->mutex);
422 dev->log_file = NULL;
427 dev->weight = weight;
428 dev->byte_weight = byte_weight;
429 init_llist_head(&dev->work_list);
430 init_waitqueue_head(&dev->wait);
431 INIT_LIST_HEAD(&dev->read_list);
432 INIT_LIST_HEAD(&dev->pending_list);
433 spin_lock_init(&dev->iotlb_lock);
436 for (i = 0; i < dev->nvqs; ++i) {
442 mutex_init(&vq->mutex);
443 vhost_vq_reset(dev, vq);
445 vhost_poll_init(&vq->poll, vq->handle_kick,
449 EXPORT_SYMBOL_GPL(vhost_dev_init);
451 /* Caller should have device mutex */
452 long vhost_dev_check_owner(struct vhost_dev *dev)
454 /* Are you the owner? If not, I don't think you mean to do that */
455 return dev->mm == current->mm ? 0 : -EPERM;
457 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
459 struct vhost_attach_cgroups_struct {
460 struct vhost_work work;
461 struct task_struct *owner;
465 static void vhost_attach_cgroups_work(struct vhost_work *work)
467 struct vhost_attach_cgroups_struct *s;
469 s = container_of(work, struct vhost_attach_cgroups_struct, work);
470 s->ret = cgroup_attach_task_all(s->owner, current);
473 static int vhost_attach_cgroups(struct vhost_dev *dev)
475 struct vhost_attach_cgroups_struct attach;
477 attach.owner = current;
478 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
479 vhost_work_queue(dev, &attach.work);
480 vhost_work_flush(dev, &attach.work);
484 /* Caller should have device mutex */
485 bool vhost_dev_has_owner(struct vhost_dev *dev)
489 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
491 /* Caller should have device mutex */
492 long vhost_dev_set_owner(struct vhost_dev *dev)
494 struct task_struct *worker;
497 /* Is there an owner already? */
498 if (vhost_dev_has_owner(dev)) {
503 /* No owner, become one */
504 dev->mm = get_task_mm(current);
505 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
506 if (IS_ERR(worker)) {
507 err = PTR_ERR(worker);
511 dev->worker = worker;
512 wake_up_process(worker); /* avoid contributing to loadavg */
514 err = vhost_attach_cgroups(dev);
518 err = vhost_dev_alloc_iovecs(dev);
524 kthread_stop(worker);
533 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
535 static void *vhost_kvzalloc(unsigned long size)
537 void *n = kzalloc(size, GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
544 struct vhost_umem *vhost_dev_reset_owner_prepare(void)
546 return vhost_kvzalloc(sizeof(struct vhost_umem));
548 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
550 /* Caller should have device mutex */
551 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_umem *umem)
555 vhost_dev_cleanup(dev, true);
557 /* Restore memory to default empty mapping. */
558 INIT_LIST_HEAD(&umem->umem_list);
560 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
561 * VQs aren't running.
563 for (i = 0; i < dev->nvqs; ++i)
564 dev->vqs[i]->umem = umem;
566 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
568 void vhost_dev_stop(struct vhost_dev *dev)
572 for (i = 0; i < dev->nvqs; ++i) {
573 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
574 vhost_poll_stop(&dev->vqs[i]->poll);
575 vhost_poll_flush(&dev->vqs[i]->poll);
579 EXPORT_SYMBOL_GPL(vhost_dev_stop);
581 static void vhost_umem_free(struct vhost_umem *umem,
582 struct vhost_umem_node *node)
584 vhost_umem_interval_tree_remove(node, &umem->umem_tree);
585 list_del(&node->link);
590 static void vhost_umem_clean(struct vhost_umem *umem)
592 struct vhost_umem_node *node, *tmp;
597 list_for_each_entry_safe(node, tmp, &umem->umem_list, link)
598 vhost_umem_free(umem, node);
603 static void vhost_clear_msg(struct vhost_dev *dev)
605 struct vhost_msg_node *node, *n;
607 spin_lock(&dev->iotlb_lock);
609 list_for_each_entry_safe(node, n, &dev->read_list, node) {
610 list_del(&node->node);
614 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
615 list_del(&node->node);
619 spin_unlock(&dev->iotlb_lock);
622 /* Caller should have device mutex if and only if locked is set */
623 void vhost_dev_cleanup(struct vhost_dev *dev, bool locked)
627 for (i = 0; i < dev->nvqs; ++i) {
628 if (dev->vqs[i]->error_ctx)
629 eventfd_ctx_put(dev->vqs[i]->error_ctx);
630 if (dev->vqs[i]->error)
631 fput(dev->vqs[i]->error);
632 if (dev->vqs[i]->kick)
633 fput(dev->vqs[i]->kick);
634 if (dev->vqs[i]->call_ctx)
635 eventfd_ctx_put(dev->vqs[i]->call_ctx);
636 if (dev->vqs[i]->call)
637 fput(dev->vqs[i]->call);
638 vhost_vq_reset(dev, dev->vqs[i]);
640 vhost_dev_free_iovecs(dev);
642 eventfd_ctx_put(dev->log_ctx);
646 dev->log_file = NULL;
647 /* No one will access memory at this point */
648 vhost_umem_clean(dev->umem);
650 vhost_umem_clean(dev->iotlb);
652 vhost_clear_msg(dev);
653 wake_up_interruptible_poll(&dev->wait, POLLIN | POLLRDNORM);
654 WARN_ON(!llist_empty(&dev->work_list));
656 kthread_stop(dev->worker);
663 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
665 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
667 u64 a = addr / VHOST_PAGE_SIZE / 8;
669 /* Make sure 64 bit math will not overflow. */
670 if (a > ULONG_MAX - (unsigned long)log_base ||
671 a + (unsigned long)log_base > ULONG_MAX)
674 return access_ok(VERIFY_WRITE, log_base + a,
675 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
678 /* Make sure 64 bit math will not overflow. */
679 static bool vhost_overflow(u64 uaddr, u64 size)
681 if (uaddr > ULONG_MAX || size > ULONG_MAX)
687 return uaddr > ULONG_MAX - size + 1;
690 /* Caller should have vq mutex and device mutex. */
691 static int vq_memory_access_ok(void __user *log_base, struct vhost_umem *umem,
694 struct vhost_umem_node *node;
699 list_for_each_entry(node, &umem->umem_list, link) {
700 unsigned long a = node->userspace_addr;
702 if (vhost_overflow(node->userspace_addr, node->size))
706 if (!access_ok(VERIFY_WRITE, (void __user *)a,
709 else if (log_all && !log_access_ok(log_base,
717 /* Can we switch to this memory table? */
718 /* Caller should have device mutex but not vq mutex */
719 static int memory_access_ok(struct vhost_dev *d, struct vhost_umem *umem,
724 for (i = 0; i < d->nvqs; ++i) {
728 mutex_lock(&d->vqs[i]->mutex);
729 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
730 /* If ring is inactive, will check when it's enabled. */
731 if (d->vqs[i]->private_data)
732 ok = vq_memory_access_ok(d->vqs[i]->log_base,
736 mutex_unlock(&d->vqs[i]->mutex);
743 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
744 struct iovec iov[], int iov_size, int access);
746 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void *to,
747 const void *from, unsigned size)
752 return __copy_to_user(to, from, size);
754 /* This function should be called after iotlb
755 * prefetch, which means we're sure that all vq
756 * could be access through iotlb. So -EAGAIN should
757 * not happen in this case.
759 /* TODO: more fast path */
761 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
762 ARRAY_SIZE(vq->iotlb_iov),
766 iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
767 ret = copy_to_iter(from, size, &t);
775 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
776 void *from, unsigned size)
781 return __copy_from_user(to, from, size);
783 /* This function should be called after iotlb
784 * prefetch, which means we're sure that vq
785 * could be access through iotlb. So -EAGAIN should
786 * not happen in this case.
788 /* TODO: more fast path */
790 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
791 ARRAY_SIZE(vq->iotlb_iov),
794 vq_err(vq, "IOTLB translation failure: uaddr "
795 "%p size 0x%llx\n", from,
796 (unsigned long long) size);
799 iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
800 ret = copy_from_iter(to, size, &f);
809 static void __user *__vhost_get_user(struct vhost_virtqueue *vq,
810 void *addr, unsigned size)
814 /* This function should be called after iotlb
815 * prefetch, which means we're sure that vq
816 * could be access through iotlb. So -EAGAIN should
817 * not happen in this case.
819 /* TODO: more fast path */
820 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
821 ARRAY_SIZE(vq->iotlb_iov),
824 vq_err(vq, "IOTLB translation failure: uaddr "
825 "%p size 0x%llx\n", addr,
826 (unsigned long long) size);
830 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
831 vq_err(vq, "Non atomic userspace memory access: uaddr "
832 "%p size 0x%llx\n", addr,
833 (unsigned long long) size);
837 return vq->iotlb_iov[0].iov_base;
840 #define vhost_put_user(vq, x, ptr) \
844 ret = __put_user(x, ptr); \
846 __typeof__(ptr) to = \
847 (__typeof__(ptr)) __vhost_get_user(vq, ptr, sizeof(*ptr)); \
849 ret = __put_user(x, to); \
856 #define vhost_get_user(vq, x, ptr) \
860 ret = __get_user(x, ptr); \
862 __typeof__(ptr) from = \
863 (__typeof__(ptr)) __vhost_get_user(vq, ptr, sizeof(*ptr)); \
865 ret = __get_user(x, from); \
872 static void vhost_dev_lock_vqs(struct vhost_dev *d)
875 for (i = 0; i < d->nvqs; ++i)
876 mutex_lock_nested(&d->vqs[i]->mutex, i);
879 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
882 for (i = 0; i < d->nvqs; ++i)
883 mutex_unlock(&d->vqs[i]->mutex);
886 static int vhost_new_umem_range(struct vhost_umem *umem,
887 u64 start, u64 size, u64 end,
888 u64 userspace_addr, int perm)
890 struct vhost_umem_node *tmp, *node;
895 node = kmalloc(sizeof(*node), GFP_ATOMIC);
899 if (umem->numem == max_iotlb_entries) {
900 tmp = list_first_entry(&umem->umem_list, typeof(*tmp), link);
901 vhost_umem_free(umem, tmp);
907 node->userspace_addr = userspace_addr;
909 INIT_LIST_HEAD(&node->link);
910 list_add_tail(&node->link, &umem->umem_list);
911 vhost_umem_interval_tree_insert(node, &umem->umem_tree);
917 static void vhost_del_umem_range(struct vhost_umem *umem,
920 struct vhost_umem_node *node;
922 while ((node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
924 vhost_umem_free(umem, node);
927 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
928 struct vhost_iotlb_msg *msg)
930 struct vhost_msg_node *node, *n;
932 spin_lock(&d->iotlb_lock);
934 list_for_each_entry_safe(node, n, &d->pending_list, node) {
935 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
936 if (msg->iova <= vq_msg->iova &&
937 msg->iova + msg->size - 1 >= vq_msg->iova &&
938 vq_msg->type == VHOST_IOTLB_MISS) {
939 vhost_poll_queue(&node->vq->poll);
940 list_del(&node->node);
945 spin_unlock(&d->iotlb_lock);
948 static int umem_access_ok(u64 uaddr, u64 size, int access)
950 unsigned long a = uaddr;
952 /* Make sure 64 bit math will not overflow. */
953 if (vhost_overflow(uaddr, size))
956 if ((access & VHOST_ACCESS_RO) &&
957 !access_ok(VERIFY_READ, (void __user *)a, size))
959 if ((access & VHOST_ACCESS_WO) &&
960 !access_ok(VERIFY_WRITE, (void __user *)a, size))
965 int vhost_process_iotlb_msg(struct vhost_dev *dev,
966 struct vhost_iotlb_msg *msg)
970 mutex_lock(&dev->mutex);
971 vhost_dev_lock_vqs(dev);
973 case VHOST_IOTLB_UPDATE:
978 if (umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
982 if (vhost_new_umem_range(dev->iotlb, msg->iova, msg->size,
983 msg->iova + msg->size - 1,
984 msg->uaddr, msg->perm)) {
988 vhost_iotlb_notify_vq(dev, msg);
990 case VHOST_IOTLB_INVALIDATE:
991 vhost_del_umem_range(dev->iotlb, msg->iova,
992 msg->iova + msg->size - 1);
999 vhost_dev_unlock_vqs(dev);
1000 mutex_unlock(&dev->mutex);
1004 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1005 struct iov_iter *from)
1007 struct vhost_msg_node node;
1008 unsigned size = sizeof(struct vhost_msg);
1012 if (iov_iter_count(from) < size)
1014 ret = copy_from_iter(&node.msg, size, from);
1018 switch (node.msg.type) {
1019 case VHOST_IOTLB_MSG:
1020 err = vhost_process_iotlb_msg(dev, &node.msg.iotlb);
1032 EXPORT_SYMBOL(vhost_chr_write_iter);
1034 unsigned int vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1037 unsigned int mask = 0;
1039 poll_wait(file, &dev->wait, wait);
1041 if (!list_empty(&dev->read_list))
1042 mask |= POLLIN | POLLRDNORM;
1046 EXPORT_SYMBOL(vhost_chr_poll);
1048 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1052 struct vhost_msg_node *node;
1054 unsigned size = sizeof(struct vhost_msg);
1056 if (iov_iter_count(to) < size)
1061 prepare_to_wait(&dev->wait, &wait,
1062 TASK_INTERRUPTIBLE);
1064 node = vhost_dequeue_msg(dev, &dev->read_list);
1071 if (signal_pending(current)) {
1084 finish_wait(&dev->wait, &wait);
1087 ret = copy_to_iter(&node->msg, size, to);
1089 if (ret != size || node->msg.type != VHOST_IOTLB_MISS) {
1094 vhost_enqueue_msg(dev, &dev->pending_list, node);
1099 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1101 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1103 struct vhost_dev *dev = vq->dev;
1104 struct vhost_msg_node *node;
1105 struct vhost_iotlb_msg *msg;
1107 node = vhost_new_msg(vq, VHOST_IOTLB_MISS);
1111 msg = &node->msg.iotlb;
1112 msg->type = VHOST_IOTLB_MISS;
1116 vhost_enqueue_msg(dev, &dev->read_list, node);
1121 static int vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1122 struct vring_desc __user *desc,
1123 struct vring_avail __user *avail,
1124 struct vring_used __user *used)
1127 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1129 return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
1130 access_ok(VERIFY_READ, avail,
1131 sizeof *avail + num * sizeof *avail->ring + s) &&
1132 access_ok(VERIFY_WRITE, used,
1133 sizeof *used + num * sizeof *used->ring + s);
1136 static int iotlb_access_ok(struct vhost_virtqueue *vq,
1137 int access, u64 addr, u64 len)
1139 const struct vhost_umem_node *node;
1140 struct vhost_umem *umem = vq->iotlb;
1144 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1147 if (node == NULL || node->start > addr) {
1148 vhost_iotlb_miss(vq, addr, access);
1150 } else if (!(node->perm & access)) {
1151 /* Report the possible access violation by
1152 * request another translation from userspace.
1157 size = node->size - addr + node->start;
1165 int vq_iotlb_prefetch(struct vhost_virtqueue *vq)
1167 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1168 unsigned int num = vq->num;
1173 return iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->desc,
1174 num * sizeof *vq->desc) &&
1175 iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->avail,
1177 num * sizeof *vq->avail->ring + s) &&
1178 iotlb_access_ok(vq, VHOST_ACCESS_WO, (u64)(uintptr_t)vq->used,
1180 num * sizeof *vq->used->ring + s);
1182 EXPORT_SYMBOL_GPL(vq_iotlb_prefetch);
1184 /* Can we log writes? */
1185 /* Caller should have device mutex but not vq mutex */
1186 int vhost_log_access_ok(struct vhost_dev *dev)
1188 return memory_access_ok(dev, dev->umem, 1);
1190 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1192 /* Verify access for write logging. */
1193 /* Caller should have vq mutex and device mutex */
1194 static int vq_log_access_ok(struct vhost_virtqueue *vq,
1195 void __user *log_base)
1197 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1199 return vq_memory_access_ok(log_base, vq->umem,
1200 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1201 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
1203 vq->num * sizeof *vq->used->ring + s));
1206 /* Can we start vq? */
1207 /* Caller should have vq mutex and device mutex */
1208 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
1210 if (!vq_log_access_ok(vq, vq->log_base))
1213 /* Access validation occurs at prefetch time with IOTLB */
1217 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1219 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1221 static struct vhost_umem *vhost_umem_alloc(void)
1223 struct vhost_umem *umem = vhost_kvzalloc(sizeof(*umem));
1228 umem->umem_tree = RB_ROOT;
1230 INIT_LIST_HEAD(&umem->umem_list);
1235 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1237 struct vhost_memory mem, *newmem;
1238 struct vhost_memory_region *region;
1239 struct vhost_umem *newumem, *oldumem;
1240 unsigned long size = offsetof(struct vhost_memory, regions);
1243 if (copy_from_user(&mem, m, size))
1247 if (mem.nregions > max_mem_regions)
1249 newmem = vhost_kvzalloc(size + mem.nregions * sizeof(*m->regions));
1253 memcpy(newmem, &mem, size);
1254 if (copy_from_user(newmem->regions, m->regions,
1255 mem.nregions * sizeof *m->regions)) {
1260 newumem = vhost_umem_alloc();
1266 for (region = newmem->regions;
1267 region < newmem->regions + mem.nregions;
1269 if (vhost_new_umem_range(newumem,
1270 region->guest_phys_addr,
1271 region->memory_size,
1272 region->guest_phys_addr +
1273 region->memory_size - 1,
1274 region->userspace_addr,
1279 if (!memory_access_ok(d, newumem, 0))
1285 /* All memory accesses are done under some VQ mutex. */
1286 for (i = 0; i < d->nvqs; ++i) {
1287 mutex_lock(&d->vqs[i]->mutex);
1288 d->vqs[i]->umem = newumem;
1289 mutex_unlock(&d->vqs[i]->mutex);
1293 vhost_umem_clean(oldumem);
1297 vhost_umem_clean(newumem);
1302 long vhost_vring_ioctl(struct vhost_dev *d, int ioctl, void __user *argp)
1304 struct file *eventfp, *filep = NULL;
1305 bool pollstart = false, pollstop = false;
1306 struct eventfd_ctx *ctx = NULL;
1307 u32 __user *idxp = argp;
1308 struct vhost_virtqueue *vq;
1309 struct vhost_vring_state s;
1310 struct vhost_vring_file f;
1311 struct vhost_vring_addr a;
1315 r = get_user(idx, idxp);
1321 idx = array_index_nospec(idx, d->nvqs);
1324 mutex_lock(&vq->mutex);
1327 case VHOST_SET_VRING_NUM:
1328 /* Resizing ring with an active backend?
1329 * You don't want to do that. */
1330 if (vq->private_data) {
1334 if (copy_from_user(&s, argp, sizeof s)) {
1338 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
1344 case VHOST_SET_VRING_BASE:
1345 /* Moving base with an active backend?
1346 * You don't want to do that. */
1347 if (vq->private_data) {
1351 if (copy_from_user(&s, argp, sizeof s)) {
1355 if (s.num > 0xffff) {
1359 vq->last_avail_idx = s.num;
1360 /* Forget the cached index value. */
1361 vq->avail_idx = vq->last_avail_idx;
1363 case VHOST_GET_VRING_BASE:
1365 s.num = vq->last_avail_idx;
1366 if (copy_to_user(argp, &s, sizeof s))
1369 case VHOST_SET_VRING_ADDR:
1370 if (copy_from_user(&a, argp, sizeof a)) {
1374 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
1378 /* For 32bit, verify that the top 32bits of the user
1379 data are set to zero. */
1380 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1381 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1382 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
1387 /* Make sure it's safe to cast pointers to vring types. */
1388 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1389 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1390 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1391 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1392 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1))) {
1397 /* We only verify access here if backend is configured.
1398 * If it is not, we don't as size might not have been setup.
1399 * We will verify when backend is configured. */
1400 if (vq->private_data) {
1401 if (!vq_access_ok(vq, vq->num,
1402 (void __user *)(unsigned long)a.desc_user_addr,
1403 (void __user *)(unsigned long)a.avail_user_addr,
1404 (void __user *)(unsigned long)a.used_user_addr)) {
1409 /* Also validate log access for used ring if enabled. */
1410 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
1411 !log_access_ok(vq->log_base, a.log_guest_addr,
1413 vq->num * sizeof *vq->used->ring)) {
1419 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1420 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1421 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1422 vq->log_addr = a.log_guest_addr;
1423 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1425 case VHOST_SET_VRING_KICK:
1426 if (copy_from_user(&f, argp, sizeof f)) {
1430 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1431 if (IS_ERR(eventfp)) {
1432 r = PTR_ERR(eventfp);
1435 if (eventfp != vq->kick) {
1436 pollstop = (filep = vq->kick) != NULL;
1437 pollstart = (vq->kick = eventfp) != NULL;
1441 case VHOST_SET_VRING_CALL:
1442 if (copy_from_user(&f, argp, sizeof f)) {
1446 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1447 if (IS_ERR(eventfp)) {
1448 r = PTR_ERR(eventfp);
1451 if (eventfp != vq->call) {
1455 vq->call_ctx = eventfp ?
1456 eventfd_ctx_fileget(eventfp) : NULL;
1460 case VHOST_SET_VRING_ERR:
1461 if (copy_from_user(&f, argp, sizeof f)) {
1465 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1466 if (IS_ERR(eventfp)) {
1467 r = PTR_ERR(eventfp);
1470 if (eventfp != vq->error) {
1472 vq->error = eventfp;
1473 ctx = vq->error_ctx;
1474 vq->error_ctx = eventfp ?
1475 eventfd_ctx_fileget(eventfp) : NULL;
1479 case VHOST_SET_VRING_ENDIAN:
1480 r = vhost_set_vring_endian(vq, argp);
1482 case VHOST_GET_VRING_ENDIAN:
1483 r = vhost_get_vring_endian(vq, idx, argp);
1485 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1486 if (copy_from_user(&s, argp, sizeof(s))) {
1490 vq->busyloop_timeout = s.num;
1492 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1494 s.num = vq->busyloop_timeout;
1495 if (copy_to_user(argp, &s, sizeof(s)))
1502 if (pollstop && vq->handle_kick)
1503 vhost_poll_stop(&vq->poll);
1506 eventfd_ctx_put(ctx);
1510 if (pollstart && vq->handle_kick)
1511 r = vhost_poll_start(&vq->poll, vq->kick);
1513 mutex_unlock(&vq->mutex);
1515 if (pollstop && vq->handle_kick)
1516 vhost_poll_flush(&vq->poll);
1519 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1521 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1523 struct vhost_umem *niotlb, *oiotlb;
1526 niotlb = vhost_umem_alloc();
1533 for (i = 0; i < d->nvqs; ++i) {
1534 mutex_lock(&d->vqs[i]->mutex);
1535 d->vqs[i]->iotlb = niotlb;
1536 mutex_unlock(&d->vqs[i]->mutex);
1539 vhost_umem_clean(oiotlb);
1543 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1545 /* Caller must have device mutex */
1546 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1548 struct file *eventfp, *filep = NULL;
1549 struct eventfd_ctx *ctx = NULL;
1554 /* If you are not the owner, you can become one */
1555 if (ioctl == VHOST_SET_OWNER) {
1556 r = vhost_dev_set_owner(d);
1560 /* You must be the owner to do anything else */
1561 r = vhost_dev_check_owner(d);
1566 case VHOST_SET_MEM_TABLE:
1567 r = vhost_set_memory(d, argp);
1569 case VHOST_SET_LOG_BASE:
1570 if (copy_from_user(&p, argp, sizeof p)) {
1574 if ((u64)(unsigned long)p != p) {
1578 for (i = 0; i < d->nvqs; ++i) {
1579 struct vhost_virtqueue *vq;
1580 void __user *base = (void __user *)(unsigned long)p;
1582 mutex_lock(&vq->mutex);
1583 /* If ring is inactive, will check when it's enabled. */
1584 if (vq->private_data && !vq_log_access_ok(vq, base))
1587 vq->log_base = base;
1588 mutex_unlock(&vq->mutex);
1591 case VHOST_SET_LOG_FD:
1592 r = get_user(fd, (int __user *)argp);
1595 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
1596 if (IS_ERR(eventfp)) {
1597 r = PTR_ERR(eventfp);
1600 if (eventfp != d->log_file) {
1601 filep = d->log_file;
1602 d->log_file = eventfp;
1604 d->log_ctx = eventfp ?
1605 eventfd_ctx_fileget(eventfp) : NULL;
1608 for (i = 0; i < d->nvqs; ++i) {
1609 mutex_lock(&d->vqs[i]->mutex);
1610 d->vqs[i]->log_ctx = d->log_ctx;
1611 mutex_unlock(&d->vqs[i]->mutex);
1614 eventfd_ctx_put(ctx);
1625 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1627 /* TODO: This is really inefficient. We need something like get_user()
1628 * (instruction directly accesses the data, with an exception table entry
1629 * returning -EFAULT). See Documentation/x86/exception-tables.txt.
1631 static int set_bit_to_user(int nr, void __user *addr)
1633 unsigned long log = (unsigned long)addr;
1636 int bit = nr + (log % PAGE_SIZE) * 8;
1639 r = get_user_pages_fast(log, 1, 1, &page);
1643 base = kmap_atomic(page);
1645 kunmap_atomic(base);
1646 set_page_dirty_lock(page);
1651 static int log_write(void __user *log_base,
1652 u64 write_address, u64 write_length)
1654 u64 write_page = write_address / VHOST_PAGE_SIZE;
1659 write_length += write_address % VHOST_PAGE_SIZE;
1661 u64 base = (u64)(unsigned long)log_base;
1662 u64 log = base + write_page / 8;
1663 int bit = write_page % 8;
1664 if ((u64)(unsigned long)log != log)
1666 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1669 if (write_length <= VHOST_PAGE_SIZE)
1671 write_length -= VHOST_PAGE_SIZE;
1677 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1679 struct vhost_umem *umem = vq->umem;
1680 struct vhost_umem_node *u;
1681 u64 start, end, l, min;
1687 /* More than one GPAs can be mapped into a single HVA. So
1688 * iterate all possible umems here to be safe.
1690 list_for_each_entry(u, &umem->umem_list, link) {
1691 if (u->userspace_addr > hva - 1 + len ||
1692 u->userspace_addr - 1 + u->size < hva)
1694 start = max(u->userspace_addr, hva);
1695 end = min(u->userspace_addr - 1 + u->size,
1697 l = end - start + 1;
1698 r = log_write(vq->log_base,
1699 u->start + start - u->userspace_addr,
1717 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1719 struct iovec iov[64];
1723 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1725 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1726 len, iov, 64, VHOST_ACCESS_WO);
1730 for (i = 0; i < ret; i++) {
1731 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1740 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1741 unsigned int log_num, u64 len, struct iovec *iov, int count)
1745 /* Make sure data written is seen before log. */
1749 for (i = 0; i < count; i++) {
1750 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1758 for (i = 0; i < log_num; ++i) {
1759 u64 l = min(log[i].len, len);
1760 r = log_write(vq->log_base, log[i].addr, l);
1766 eventfd_signal(vq->log_ctx, 1);
1770 /* Length written exceeds what we have stored. This is a bug. */
1774 EXPORT_SYMBOL_GPL(vhost_log_write);
1776 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1779 if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
1780 &vq->used->flags) < 0)
1782 if (unlikely(vq->log_used)) {
1783 /* Make sure the flag is seen before log. */
1785 /* Log used flag write. */
1786 used = &vq->used->flags;
1787 log_used(vq, (used - (void __user *)vq->used),
1788 sizeof vq->used->flags);
1790 eventfd_signal(vq->log_ctx, 1);
1795 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1797 if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
1798 vhost_avail_event(vq)))
1800 if (unlikely(vq->log_used)) {
1802 /* Make sure the event is seen before log. */
1804 /* Log avail event write */
1805 used = vhost_avail_event(vq);
1806 log_used(vq, (used - (void __user *)vq->used),
1807 sizeof *vhost_avail_event(vq));
1809 eventfd_signal(vq->log_ctx, 1);
1814 int vhost_vq_init_access(struct vhost_virtqueue *vq)
1816 __virtio16 last_used_idx;
1818 bool is_le = vq->is_le;
1820 if (!vq->private_data)
1823 vhost_init_is_le(vq);
1825 r = vhost_update_used_flags(vq);
1828 vq->signalled_used_valid = false;
1830 !access_ok(VERIFY_READ, &vq->used->idx, sizeof vq->used->idx)) {
1834 r = vhost_get_user(vq, last_used_idx, &vq->used->idx);
1836 vq_err(vq, "Can't access used idx at %p\n",
1840 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1847 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
1849 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1850 struct iovec iov[], int iov_size, int access)
1852 const struct vhost_umem_node *node;
1853 struct vhost_dev *dev = vq->dev;
1854 struct vhost_umem *umem = dev->iotlb ? dev->iotlb : dev->umem;
1859 while ((u64)len > s) {
1861 if (unlikely(ret >= iov_size)) {
1866 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1867 addr, addr + len - 1);
1868 if (node == NULL || node->start > addr) {
1869 if (umem != dev->iotlb) {
1875 } else if (!(node->perm & access)) {
1881 size = node->size - addr + node->start;
1882 _iov->iov_len = min((u64)len - s, size);
1883 _iov->iov_base = (void __user *)(unsigned long)
1884 (node->userspace_addr + addr - node->start);
1891 vhost_iotlb_miss(vq, addr, access);
1895 /* Each buffer in the virtqueues is actually a chain of descriptors. This
1896 * function returns the next descriptor in the chain,
1897 * or -1U if we're at the end. */
1898 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1902 /* If this descriptor says it doesn't chain, we're done. */
1903 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1906 /* Check they're not leading us off end of descriptors. */
1907 next = vhost16_to_cpu(vq, desc->next);
1908 /* Make sure compiler knows to grab that: we don't want it changing! */
1909 /* We will use the result as an index in an array, so most
1910 * architectures only need a compiler barrier here. */
1911 read_barrier_depends();
1916 static int get_indirect(struct vhost_virtqueue *vq,
1917 struct iovec iov[], unsigned int iov_size,
1918 unsigned int *out_num, unsigned int *in_num,
1919 struct vhost_log *log, unsigned int *log_num,
1920 struct vring_desc *indirect)
1922 struct vring_desc desc;
1923 unsigned int i = 0, count, found = 0;
1924 u32 len = vhost32_to_cpu(vq, indirect->len);
1925 struct iov_iter from;
1929 if (unlikely(len % sizeof desc)) {
1930 vq_err(vq, "Invalid length in indirect descriptor: "
1931 "len 0x%llx not multiple of 0x%zx\n",
1932 (unsigned long long)len,
1937 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
1938 UIO_MAXIOV, VHOST_ACCESS_RO);
1939 if (unlikely(ret < 0)) {
1941 vq_err(vq, "Translation failure %d in indirect.\n", ret);
1944 iov_iter_init(&from, READ, vq->indirect, ret, len);
1946 /* We will use the result as an address to read from, so most
1947 * architectures only need a compiler barrier here. */
1948 read_barrier_depends();
1950 count = len / sizeof desc;
1951 /* Buffers are chained via a 16 bit next field, so
1952 * we can have at most 2^16 of these. */
1953 if (unlikely(count > USHRT_MAX + 1)) {
1954 vq_err(vq, "Indirect buffer length too big: %d\n",
1960 unsigned iov_count = *in_num + *out_num;
1961 if (unlikely(++found > count)) {
1962 vq_err(vq, "Loop detected: last one at %u "
1963 "indirect size %u\n",
1967 if (unlikely(copy_from_iter(&desc, sizeof(desc), &from) !=
1969 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1970 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1973 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
1974 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1975 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1979 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
1980 access = VHOST_ACCESS_WO;
1982 access = VHOST_ACCESS_RO;
1984 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1985 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1986 iov_size - iov_count, access);
1987 if (unlikely(ret < 0)) {
1989 vq_err(vq, "Translation failure %d indirect idx %d\n",
1993 /* If this is an input descriptor, increment that count. */
1994 if (access == VHOST_ACCESS_WO) {
1996 if (unlikely(log && ret)) {
1997 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1998 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2002 /* If it's an output descriptor, they're all supposed
2003 * to come before any input descriptors. */
2004 if (unlikely(*in_num)) {
2005 vq_err(vq, "Indirect descriptor "
2006 "has out after in: idx %d\n", i);
2011 } while ((i = next_desc(vq, &desc)) != -1);
2015 /* This looks in the virtqueue and for the first available buffer, and converts
2016 * it to an iovec for convenient access. Since descriptors consist of some
2017 * number of output then some number of input descriptors, it's actually two
2018 * iovecs, but we pack them into one and note how many of each there were.
2020 * This function returns the descriptor number found, or vq->num (which is
2021 * never a valid descriptor number) if none was found. A negative code is
2022 * returned on error. */
2023 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2024 struct iovec iov[], unsigned int iov_size,
2025 unsigned int *out_num, unsigned int *in_num,
2026 struct vhost_log *log, unsigned int *log_num)
2028 struct vring_desc desc;
2029 unsigned int i, head, found = 0;
2031 __virtio16 avail_idx;
2032 __virtio16 ring_head;
2035 /* Check it isn't doing very strange things with descriptor numbers. */
2036 last_avail_idx = vq->last_avail_idx;
2037 if (unlikely(vhost_get_user(vq, avail_idx, &vq->avail->idx))) {
2038 vq_err(vq, "Failed to access avail idx at %p\n",
2042 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2044 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2045 vq_err(vq, "Guest moved used index from %u to %u",
2046 last_avail_idx, vq->avail_idx);
2050 /* If there's nothing new since last we looked, return invalid. */
2051 if (vq->avail_idx == last_avail_idx)
2054 /* Only get avail ring entries after they have been exposed by guest. */
2057 /* Grab the next descriptor number they're advertising, and increment
2058 * the index we've seen. */
2059 if (unlikely(vhost_get_user(vq, ring_head,
2060 &vq->avail->ring[last_avail_idx & (vq->num - 1)]))) {
2061 vq_err(vq, "Failed to read head: idx %d address %p\n",
2063 &vq->avail->ring[last_avail_idx % vq->num]);
2067 head = vhost16_to_cpu(vq, ring_head);
2069 /* If their number is silly, that's an error. */
2070 if (unlikely(head >= vq->num)) {
2071 vq_err(vq, "Guest says index %u > %u is available",
2076 /* When we start there are none of either input nor output. */
2077 *out_num = *in_num = 0;
2083 unsigned iov_count = *in_num + *out_num;
2084 if (unlikely(i >= vq->num)) {
2085 vq_err(vq, "Desc index is %u > %u, head = %u",
2089 if (unlikely(++found > vq->num)) {
2090 vq_err(vq, "Loop detected: last one at %u "
2091 "vq size %u head %u\n",
2095 ret = vhost_copy_from_user(vq, &desc, vq->desc + i,
2097 if (unlikely(ret)) {
2098 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2102 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2103 ret = get_indirect(vq, iov, iov_size,
2105 log, log_num, &desc);
2106 if (unlikely(ret < 0)) {
2108 vq_err(vq, "Failure detected "
2109 "in indirect descriptor at idx %d\n", i);
2115 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2116 access = VHOST_ACCESS_WO;
2118 access = VHOST_ACCESS_RO;
2119 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2120 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2121 iov_size - iov_count, access);
2122 if (unlikely(ret < 0)) {
2124 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2128 if (access == VHOST_ACCESS_WO) {
2129 /* If this is an input descriptor,
2130 * increment that count. */
2132 if (unlikely(log && ret)) {
2133 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2134 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2138 /* If it's an output descriptor, they're all supposed
2139 * to come before any input descriptors. */
2140 if (unlikely(*in_num)) {
2141 vq_err(vq, "Descriptor has out after in: "
2147 } while ((i = next_desc(vq, &desc)) != -1);
2149 /* On success, increment avail index. */
2150 vq->last_avail_idx++;
2152 /* Assume notifications from guest are disabled at this point,
2153 * if they aren't we would need to update avail_event index. */
2154 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2157 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2159 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2160 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2162 vq->last_avail_idx -= n;
2164 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2166 /* After we've used one of their buffers, we tell them about it. We'll then
2167 * want to notify the guest, using eventfd. */
2168 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2170 struct vring_used_elem heads = {
2171 cpu_to_vhost32(vq, head),
2172 cpu_to_vhost32(vq, len)
2175 return vhost_add_used_n(vq, &heads, 1);
2177 EXPORT_SYMBOL_GPL(vhost_add_used);
2179 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2180 struct vring_used_elem *heads,
2183 struct vring_used_elem __user *used;
2187 start = vq->last_used_idx & (vq->num - 1);
2188 used = vq->used->ring + start;
2190 if (vhost_put_user(vq, heads[0].id, &used->id)) {
2191 vq_err(vq, "Failed to write used id");
2194 if (vhost_put_user(vq, heads[0].len, &used->len)) {
2195 vq_err(vq, "Failed to write used len");
2198 } else if (vhost_copy_to_user(vq, used, heads, count * sizeof *used)) {
2199 vq_err(vq, "Failed to write used");
2202 if (unlikely(vq->log_used)) {
2203 /* Make sure data is seen before log. */
2205 /* Log used ring entry write. */
2206 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2207 count * sizeof *used);
2209 old = vq->last_used_idx;
2210 new = (vq->last_used_idx += count);
2211 /* If the driver never bothers to signal in a very long while,
2212 * used index might wrap around. If that happens, invalidate
2213 * signalled_used index we stored. TODO: make sure driver
2214 * signals at least once in 2^16 and remove this. */
2215 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2216 vq->signalled_used_valid = false;
2220 /* After we've used one of their buffers, we tell them about it. We'll then
2221 * want to notify the guest, using eventfd. */
2222 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2227 start = vq->last_used_idx & (vq->num - 1);
2228 n = vq->num - start;
2230 r = __vhost_add_used_n(vq, heads, n);
2236 r = __vhost_add_used_n(vq, heads, count);
2238 /* Make sure buffer is written before we update index. */
2240 if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
2242 vq_err(vq, "Failed to increment used idx");
2245 if (unlikely(vq->log_used)) {
2246 /* Make sure used idx is seen before log. */
2248 /* Log used index update. */
2249 log_used(vq, offsetof(struct vring_used, idx),
2250 sizeof vq->used->idx);
2252 eventfd_signal(vq->log_ctx, 1);
2256 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2258 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2263 /* Flush out used index updates. This is paired
2264 * with the barrier that the Guest executes when enabling
2268 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2269 unlikely(vq->avail_idx == vq->last_avail_idx))
2272 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2274 if (vhost_get_user(vq, flags, &vq->avail->flags)) {
2275 vq_err(vq, "Failed to get flags");
2278 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2280 old = vq->signalled_used;
2281 v = vq->signalled_used_valid;
2282 new = vq->signalled_used = vq->last_used_idx;
2283 vq->signalled_used_valid = true;
2288 if (vhost_get_user(vq, event, vhost_used_event(vq))) {
2289 vq_err(vq, "Failed to get used event idx");
2292 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2295 /* This actually signals the guest, using eventfd. */
2296 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2298 /* Signal the Guest tell them we used something up. */
2299 if (vq->call_ctx && vhost_notify(dev, vq))
2300 eventfd_signal(vq->call_ctx, 1);
2302 EXPORT_SYMBOL_GPL(vhost_signal);
2304 /* And here's the combo meal deal. Supersize me! */
2305 void vhost_add_used_and_signal(struct vhost_dev *dev,
2306 struct vhost_virtqueue *vq,
2307 unsigned int head, int len)
2309 vhost_add_used(vq, head, len);
2310 vhost_signal(dev, vq);
2312 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2314 /* multi-buffer version of vhost_add_used_and_signal */
2315 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2316 struct vhost_virtqueue *vq,
2317 struct vring_used_elem *heads, unsigned count)
2319 vhost_add_used_n(vq, heads, count);
2320 vhost_signal(dev, vq);
2322 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2324 /* return true if we're sure that avaiable ring is empty */
2325 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2327 __virtio16 avail_idx;
2330 r = vhost_get_user(vq, avail_idx, &vq->avail->idx);
2334 return vhost16_to_cpu(vq, avail_idx) == vq->avail_idx;
2336 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2338 /* OK, now we need to know about added descriptors. */
2339 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2341 __virtio16 avail_idx;
2344 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2346 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2347 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2348 r = vhost_update_used_flags(vq);
2350 vq_err(vq, "Failed to enable notification at %p: %d\n",
2351 &vq->used->flags, r);
2355 r = vhost_update_avail_event(vq, vq->avail_idx);
2357 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2358 vhost_avail_event(vq), r);
2362 /* They could have slipped one in as we were doing that: make
2363 * sure it's written, then check again. */
2365 r = vhost_get_user(vq, avail_idx, &vq->avail->idx);
2367 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2368 &vq->avail->idx, r);
2372 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2374 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2376 /* We don't need to be notified again. */
2377 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2381 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2383 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2384 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2385 r = vhost_update_used_flags(vq);
2387 vq_err(vq, "Failed to enable notification at %p: %d\n",
2388 &vq->used->flags, r);
2391 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2393 /* Create a new message. */
2394 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2396 struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2400 /* Make sure all padding within the structure is initialized. */
2401 memset(&node->msg, 0, sizeof node->msg);
2403 node->msg.type = type;
2406 EXPORT_SYMBOL_GPL(vhost_new_msg);
2408 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2409 struct vhost_msg_node *node)
2411 spin_lock(&dev->iotlb_lock);
2412 list_add_tail(&node->node, head);
2413 spin_unlock(&dev->iotlb_lock);
2415 wake_up_interruptible_poll(&dev->wait, POLLIN | POLLRDNORM);
2417 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2419 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2420 struct list_head *head)
2422 struct vhost_msg_node *node = NULL;
2424 spin_lock(&dev->iotlb_lock);
2425 if (!list_empty(head)) {
2426 node = list_first_entry(head, struct vhost_msg_node,
2428 list_del(&node->node);
2430 spin_unlock(&dev->iotlb_lock);
2434 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2437 static int __init vhost_init(void)
2442 static void __exit vhost_exit(void)
2446 module_init(vhost_init);
2447 module_exit(vhost_exit);
2449 MODULE_VERSION("0.0.1");
2450 MODULE_LICENSE("GPL v2");
2451 MODULE_AUTHOR("Michael S. Tsirkin");
2452 MODULE_DESCRIPTION("Host kernel accelerator for virtio");