1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (C) 2009 Red Hat, Inc.
3 * Copyright (C) 2006 Rusty Russell IBM Corporation
5 * Author: Michael S. Tsirkin <mst@redhat.com>
7 * Inspiration, some code, and most witty comments come from
8 * Documentation/virtual/lguest/lguest.c, by Rusty Russell
10 * Generic code for virtio server in host kernel.
13 #include <linux/eventfd.h>
14 #include <linux/vhost.h>
15 #include <linux/uio.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>
36 static ushort max_mem_regions = 64;
37 module_param(max_mem_regions, ushort, 0444);
38 MODULE_PARM_DESC(max_mem_regions,
39 "Maximum number of memory regions in memory map. (default: 64)");
40 static int max_iotlb_entries = 2048;
41 module_param(max_iotlb_entries, int, 0444);
42 MODULE_PARM_DESC(max_iotlb_entries,
43 "Maximum number of iotlb entries. (default: 2048)");
46 VHOST_MEMORY_F_LOG = 0x1,
49 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
50 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
52 INTERVAL_TREE_DEFINE(struct vhost_umem_node,
53 rb, __u64, __subtree_last,
54 START, LAST, static inline, vhost_umem_interval_tree);
56 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
57 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
59 vq->user_be = !virtio_legacy_is_little_endian();
62 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
67 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
72 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
74 struct vhost_vring_state s;
79 if (copy_from_user(&s, argp, sizeof(s)))
82 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
83 s.num != VHOST_VRING_BIG_ENDIAN)
86 if (s.num == VHOST_VRING_BIG_ENDIAN)
87 vhost_enable_cross_endian_big(vq);
89 vhost_enable_cross_endian_little(vq);
94 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
97 struct vhost_vring_state s = {
102 if (copy_to_user(argp, &s, sizeof(s)))
108 static void vhost_init_is_le(struct vhost_virtqueue *vq)
110 /* Note for legacy virtio: user_be is initialized at reset time
111 * according to the host endianness. If userspace does not set an
112 * explicit endianness, the default behavior is native endian, as
113 * expected by legacy virtio.
115 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
118 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
122 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
127 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
133 static void vhost_init_is_le(struct vhost_virtqueue *vq)
135 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
136 || virtio_legacy_is_little_endian();
138 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
140 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
142 vhost_init_is_le(vq);
145 struct vhost_flush_struct {
146 struct vhost_work work;
147 struct completion wait_event;
150 static void vhost_flush_work(struct vhost_work *work)
152 struct vhost_flush_struct *s;
154 s = container_of(work, struct vhost_flush_struct, work);
155 complete(&s->wait_event);
158 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
161 struct vhost_poll *poll;
163 poll = container_of(pt, struct vhost_poll, table);
165 add_wait_queue(wqh, &poll->wait);
168 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
171 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
173 if (!(key_to_poll(key) & poll->mask))
176 vhost_poll_queue(poll);
180 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
182 clear_bit(VHOST_WORK_QUEUED, &work->flags);
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 __poll_t 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 = vfs_poll(file, &poll->table);
213 vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
214 if (mask & EPOLLERR) {
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.
264 * test_and_set_bit() implies a memory barrier.
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_meta_reset(struct vhost_virtqueue *vq)
289 for (j = 0; j < VHOST_NUM_ADDRS; j++)
290 vq->meta_iotlb[j] = NULL;
293 static void vhost_vq_meta_reset(struct vhost_dev *d)
297 for (i = 0; i < d->nvqs; ++i)
298 __vhost_vq_meta_reset(d->vqs[i]);
301 static void vhost_vq_reset(struct vhost_dev *dev,
302 struct vhost_virtqueue *vq)
308 vq->last_avail_idx = 0;
310 vq->last_used_idx = 0;
311 vq->signalled_used = 0;
312 vq->signalled_used_valid = false;
314 vq->log_used = false;
315 vq->log_addr = -1ull;
316 vq->private_data = NULL;
317 vq->acked_features = 0;
318 vq->acked_backend_features = 0;
320 vq->error_ctx = NULL;
324 vhost_reset_is_le(vq);
325 vhost_disable_cross_endian(vq);
326 vq->busyloop_timeout = 0;
329 __vhost_vq_meta_reset(vq);
332 static int vhost_worker(void *data)
334 struct vhost_dev *dev = data;
335 struct vhost_work *work, *work_next;
336 struct llist_node *node;
337 mm_segment_t oldfs = get_fs();
343 /* mb paired w/ kthread_stop */
344 set_current_state(TASK_INTERRUPTIBLE);
346 if (kthread_should_stop()) {
347 __set_current_state(TASK_RUNNING);
351 node = llist_del_all(&dev->work_list);
355 node = llist_reverse_order(node);
356 /* make sure flag is seen after deletion */
358 llist_for_each_entry_safe(work, work_next, node, node) {
359 clear_bit(VHOST_WORK_QUEUED, &work->flags);
360 __set_current_state(TASK_RUNNING);
371 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
381 /* Helper to allocate iovec buffers for all vqs. */
382 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
384 struct vhost_virtqueue *vq;
387 for (i = 0; i < dev->nvqs; ++i) {
389 vq->indirect = kmalloc_array(UIO_MAXIOV,
390 sizeof(*vq->indirect),
392 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
394 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
396 if (!vq->indirect || !vq->log || !vq->heads)
403 vhost_vq_free_iovecs(dev->vqs[i]);
407 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
411 for (i = 0; i < dev->nvqs; ++i)
412 vhost_vq_free_iovecs(dev->vqs[i]);
415 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
416 int pkts, int total_len)
418 struct vhost_dev *dev = vq->dev;
420 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
421 pkts >= dev->weight) {
422 vhost_poll_queue(&vq->poll);
428 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
430 void vhost_dev_init(struct vhost_dev *dev,
431 struct vhost_virtqueue **vqs, int nvqs,
432 int iov_limit, int weight, int byte_weight)
434 struct vhost_virtqueue *vq;
439 mutex_init(&dev->mutex);
445 dev->iov_limit = iov_limit;
446 dev->weight = weight;
447 dev->byte_weight = byte_weight;
448 init_llist_head(&dev->work_list);
449 init_waitqueue_head(&dev->wait);
450 INIT_LIST_HEAD(&dev->read_list);
451 INIT_LIST_HEAD(&dev->pending_list);
452 spin_lock_init(&dev->iotlb_lock);
455 for (i = 0; i < dev->nvqs; ++i) {
461 mutex_init(&vq->mutex);
462 vhost_vq_reset(dev, vq);
464 vhost_poll_init(&vq->poll, vq->handle_kick,
468 EXPORT_SYMBOL_GPL(vhost_dev_init);
470 /* Caller should have device mutex */
471 long vhost_dev_check_owner(struct vhost_dev *dev)
473 /* Are you the owner? If not, I don't think you mean to do that */
474 return dev->mm == current->mm ? 0 : -EPERM;
476 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
478 struct vhost_attach_cgroups_struct {
479 struct vhost_work work;
480 struct task_struct *owner;
484 static void vhost_attach_cgroups_work(struct vhost_work *work)
486 struct vhost_attach_cgroups_struct *s;
488 s = container_of(work, struct vhost_attach_cgroups_struct, work);
489 s->ret = cgroup_attach_task_all(s->owner, current);
492 static int vhost_attach_cgroups(struct vhost_dev *dev)
494 struct vhost_attach_cgroups_struct attach;
496 attach.owner = current;
497 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
498 vhost_work_queue(dev, &attach.work);
499 vhost_work_flush(dev, &attach.work);
503 /* Caller should have device mutex */
504 bool vhost_dev_has_owner(struct vhost_dev *dev)
508 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
510 /* Caller should have device mutex */
511 long vhost_dev_set_owner(struct vhost_dev *dev)
513 struct task_struct *worker;
516 /* Is there an owner already? */
517 if (vhost_dev_has_owner(dev)) {
522 /* No owner, become one */
523 dev->mm = get_task_mm(current);
524 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
525 if (IS_ERR(worker)) {
526 err = PTR_ERR(worker);
530 dev->worker = worker;
531 wake_up_process(worker); /* avoid contributing to loadavg */
533 err = vhost_attach_cgroups(dev);
537 err = vhost_dev_alloc_iovecs(dev);
543 kthread_stop(worker);
552 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
554 struct vhost_umem *vhost_dev_reset_owner_prepare(void)
556 return kvzalloc(sizeof(struct vhost_umem), GFP_KERNEL);
558 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
560 /* Caller should have device mutex */
561 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_umem *umem)
565 vhost_dev_cleanup(dev);
567 /* Restore memory to default empty mapping. */
568 INIT_LIST_HEAD(&umem->umem_list);
570 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
571 * VQs aren't running.
573 for (i = 0; i < dev->nvqs; ++i)
574 dev->vqs[i]->umem = umem;
576 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
578 void vhost_dev_stop(struct vhost_dev *dev)
582 for (i = 0; i < dev->nvqs; ++i) {
583 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
584 vhost_poll_stop(&dev->vqs[i]->poll);
585 vhost_poll_flush(&dev->vqs[i]->poll);
589 EXPORT_SYMBOL_GPL(vhost_dev_stop);
591 static void vhost_umem_free(struct vhost_umem *umem,
592 struct vhost_umem_node *node)
594 vhost_umem_interval_tree_remove(node, &umem->umem_tree);
595 list_del(&node->link);
600 static void vhost_umem_clean(struct vhost_umem *umem)
602 struct vhost_umem_node *node, *tmp;
607 list_for_each_entry_safe(node, tmp, &umem->umem_list, link)
608 vhost_umem_free(umem, node);
613 static void vhost_clear_msg(struct vhost_dev *dev)
615 struct vhost_msg_node *node, *n;
617 spin_lock(&dev->iotlb_lock);
619 list_for_each_entry_safe(node, n, &dev->read_list, node) {
620 list_del(&node->node);
624 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
625 list_del(&node->node);
629 spin_unlock(&dev->iotlb_lock);
632 void vhost_dev_cleanup(struct vhost_dev *dev)
636 for (i = 0; i < dev->nvqs; ++i) {
637 if (dev->vqs[i]->error_ctx)
638 eventfd_ctx_put(dev->vqs[i]->error_ctx);
639 if (dev->vqs[i]->kick)
640 fput(dev->vqs[i]->kick);
641 if (dev->vqs[i]->call_ctx)
642 eventfd_ctx_put(dev->vqs[i]->call_ctx);
643 vhost_vq_reset(dev, dev->vqs[i]);
645 vhost_dev_free_iovecs(dev);
647 eventfd_ctx_put(dev->log_ctx);
649 /* No one will access memory at this point */
650 vhost_umem_clean(dev->umem);
652 vhost_umem_clean(dev->iotlb);
654 vhost_clear_msg(dev);
655 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
656 WARN_ON(!llist_empty(&dev->work_list));
658 kthread_stop(dev->worker);
665 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
667 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
669 u64 a = addr / VHOST_PAGE_SIZE / 8;
671 /* Make sure 64 bit math will not overflow. */
672 if (a > ULONG_MAX - (unsigned long)log_base ||
673 a + (unsigned long)log_base > ULONG_MAX)
676 return access_ok(log_base + a,
677 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
680 static bool vhost_overflow(u64 uaddr, u64 size)
682 /* Make sure 64 bit math will not overflow. */
683 return uaddr > ULONG_MAX || size > ULONG_MAX || uaddr > ULONG_MAX - size;
686 /* Caller should have vq mutex and device mutex. */
687 static bool vq_memory_access_ok(void __user *log_base, struct vhost_umem *umem,
690 struct vhost_umem_node *node;
695 list_for_each_entry(node, &umem->umem_list, link) {
696 unsigned long a = node->userspace_addr;
698 if (vhost_overflow(node->userspace_addr, node->size))
702 if (!access_ok((void __user *)a,
705 else if (log_all && !log_access_ok(log_base,
713 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
714 u64 addr, unsigned int size,
717 const struct vhost_umem_node *node = vq->meta_iotlb[type];
722 return (void *)(uintptr_t)(node->userspace_addr + addr - node->start);
725 /* Can we switch to this memory table? */
726 /* Caller should have device mutex but not vq mutex */
727 static bool memory_access_ok(struct vhost_dev *d, struct vhost_umem *umem,
732 for (i = 0; i < d->nvqs; ++i) {
736 mutex_lock(&d->vqs[i]->mutex);
737 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
738 /* If ring is inactive, will check when it's enabled. */
739 if (d->vqs[i]->private_data)
740 ok = vq_memory_access_ok(d->vqs[i]->log_base,
744 mutex_unlock(&d->vqs[i]->mutex);
751 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
752 struct iovec iov[], int iov_size, int access);
754 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
755 const void *from, unsigned size)
760 return __copy_to_user(to, from, size);
762 /* This function should be called after iotlb
763 * prefetch, which means we're sure that all vq
764 * could be access through iotlb. So -EAGAIN should
765 * not happen in this case.
768 void __user *uaddr = vhost_vq_meta_fetch(vq,
769 (u64)(uintptr_t)to, size,
773 return __copy_to_user(uaddr, from, size);
775 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
776 ARRAY_SIZE(vq->iotlb_iov),
780 iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
781 ret = copy_to_iter(from, size, &t);
789 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
790 void __user *from, unsigned size)
795 return __copy_from_user(to, from, size);
797 /* This function should be called after iotlb
798 * prefetch, which means we're sure that vq
799 * could be access through iotlb. So -EAGAIN should
800 * not happen in this case.
802 void __user *uaddr = vhost_vq_meta_fetch(vq,
803 (u64)(uintptr_t)from, size,
808 return __copy_from_user(to, uaddr, size);
810 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
811 ARRAY_SIZE(vq->iotlb_iov),
814 vq_err(vq, "IOTLB translation failure: uaddr "
815 "%p size 0x%llx\n", from,
816 (unsigned long long) size);
819 iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
820 ret = copy_from_iter(to, size, &f);
829 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
830 void __user *addr, unsigned int size,
835 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
836 ARRAY_SIZE(vq->iotlb_iov),
839 vq_err(vq, "IOTLB translation failure: uaddr "
840 "%p size 0x%llx\n", addr,
841 (unsigned long long) size);
845 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
846 vq_err(vq, "Non atomic userspace memory access: uaddr "
847 "%p size 0x%llx\n", addr,
848 (unsigned long long) size);
852 return vq->iotlb_iov[0].iov_base;
855 /* This function should be called after iotlb
856 * prefetch, which means we're sure that vq
857 * could be access through iotlb. So -EAGAIN should
858 * not happen in this case.
860 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
861 void *addr, unsigned int size,
864 void __user *uaddr = vhost_vq_meta_fetch(vq,
865 (u64)(uintptr_t)addr, size, type);
869 return __vhost_get_user_slow(vq, addr, size, type);
872 #define vhost_put_user(vq, x, ptr) \
876 ret = __put_user(x, ptr); \
878 __typeof__(ptr) to = \
879 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
880 sizeof(*ptr), VHOST_ADDR_USED); \
882 ret = __put_user(x, to); \
889 #define vhost_get_user(vq, x, ptr, type) \
893 ret = __get_user(x, ptr); \
895 __typeof__(ptr) from = \
896 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
900 ret = __get_user(x, from); \
907 #define vhost_get_avail(vq, x, ptr) \
908 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
910 #define vhost_get_used(vq, x, ptr) \
911 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
913 static void vhost_dev_lock_vqs(struct vhost_dev *d)
916 for (i = 0; i < d->nvqs; ++i)
917 mutex_lock_nested(&d->vqs[i]->mutex, i);
920 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
923 for (i = 0; i < d->nvqs; ++i)
924 mutex_unlock(&d->vqs[i]->mutex);
927 static int vhost_new_umem_range(struct vhost_umem *umem,
928 u64 start, u64 size, u64 end,
929 u64 userspace_addr, int perm)
931 struct vhost_umem_node *tmp, *node;
936 node = kmalloc(sizeof(*node), GFP_ATOMIC);
940 if (umem->numem == max_iotlb_entries) {
941 tmp = list_first_entry(&umem->umem_list, typeof(*tmp), link);
942 vhost_umem_free(umem, tmp);
948 node->userspace_addr = userspace_addr;
950 INIT_LIST_HEAD(&node->link);
951 list_add_tail(&node->link, &umem->umem_list);
952 vhost_umem_interval_tree_insert(node, &umem->umem_tree);
958 static void vhost_del_umem_range(struct vhost_umem *umem,
961 struct vhost_umem_node *node;
963 while ((node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
965 vhost_umem_free(umem, node);
968 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
969 struct vhost_iotlb_msg *msg)
971 struct vhost_msg_node *node, *n;
973 spin_lock(&d->iotlb_lock);
975 list_for_each_entry_safe(node, n, &d->pending_list, node) {
976 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
977 if (msg->iova <= vq_msg->iova &&
978 msg->iova + msg->size - 1 >= vq_msg->iova &&
979 vq_msg->type == VHOST_IOTLB_MISS) {
980 vhost_poll_queue(&node->vq->poll);
981 list_del(&node->node);
986 spin_unlock(&d->iotlb_lock);
989 static bool umem_access_ok(u64 uaddr, u64 size, int access)
991 unsigned long a = uaddr;
993 /* Make sure 64 bit math will not overflow. */
994 if (vhost_overflow(uaddr, size))
997 if ((access & VHOST_ACCESS_RO) &&
998 !access_ok((void __user *)a, size))
1000 if ((access & VHOST_ACCESS_WO) &&
1001 !access_ok((void __user *)a, size))
1006 static int vhost_process_iotlb_msg(struct vhost_dev *dev,
1007 struct vhost_iotlb_msg *msg)
1011 mutex_lock(&dev->mutex);
1012 vhost_dev_lock_vqs(dev);
1013 switch (msg->type) {
1014 case VHOST_IOTLB_UPDATE:
1019 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1023 vhost_vq_meta_reset(dev);
1024 if (vhost_new_umem_range(dev->iotlb, msg->iova, msg->size,
1025 msg->iova + msg->size - 1,
1026 msg->uaddr, msg->perm)) {
1030 vhost_iotlb_notify_vq(dev, msg);
1032 case VHOST_IOTLB_INVALIDATE:
1037 vhost_vq_meta_reset(dev);
1038 vhost_del_umem_range(dev->iotlb, msg->iova,
1039 msg->iova + msg->size - 1);
1046 vhost_dev_unlock_vqs(dev);
1047 mutex_unlock(&dev->mutex);
1051 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1052 struct iov_iter *from)
1054 struct vhost_iotlb_msg msg;
1058 ret = copy_from_iter(&type, sizeof(type), from);
1059 if (ret != sizeof(type)) {
1065 case VHOST_IOTLB_MSG:
1066 /* There maybe a hole after type for V1 message type,
1069 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1071 case VHOST_IOTLB_MSG_V2:
1072 offset = sizeof(__u32);
1079 iov_iter_advance(from, offset);
1080 ret = copy_from_iter(&msg, sizeof(msg), from);
1081 if (ret != sizeof(msg)) {
1085 if (vhost_process_iotlb_msg(dev, &msg)) {
1090 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1091 sizeof(struct vhost_msg_v2);
1095 EXPORT_SYMBOL(vhost_chr_write_iter);
1097 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1102 poll_wait(file, &dev->wait, wait);
1104 if (!list_empty(&dev->read_list))
1105 mask |= EPOLLIN | EPOLLRDNORM;
1109 EXPORT_SYMBOL(vhost_chr_poll);
1111 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1115 struct vhost_msg_node *node;
1117 unsigned size = sizeof(struct vhost_msg);
1119 if (iov_iter_count(to) < size)
1124 prepare_to_wait(&dev->wait, &wait,
1125 TASK_INTERRUPTIBLE);
1127 node = vhost_dequeue_msg(dev, &dev->read_list);
1134 if (signal_pending(current)) {
1147 finish_wait(&dev->wait, &wait);
1150 struct vhost_iotlb_msg *msg;
1151 void *start = &node->msg;
1153 switch (node->msg.type) {
1154 case VHOST_IOTLB_MSG:
1155 size = sizeof(node->msg);
1156 msg = &node->msg.iotlb;
1158 case VHOST_IOTLB_MSG_V2:
1159 size = sizeof(node->msg_v2);
1160 msg = &node->msg_v2.iotlb;
1167 ret = copy_to_iter(start, size, to);
1168 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1172 vhost_enqueue_msg(dev, &dev->pending_list, node);
1177 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1179 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1181 struct vhost_dev *dev = vq->dev;
1182 struct vhost_msg_node *node;
1183 struct vhost_iotlb_msg *msg;
1184 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1186 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1191 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1192 msg = &node->msg_v2.iotlb;
1194 msg = &node->msg.iotlb;
1197 msg->type = VHOST_IOTLB_MISS;
1201 vhost_enqueue_msg(dev, &dev->read_list, node);
1206 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1207 struct vring_desc __user *desc,
1208 struct vring_avail __user *avail,
1209 struct vring_used __user *used)
1212 size_t s __maybe_unused = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1214 return access_ok(desc, num * sizeof *desc) &&
1216 sizeof *avail + num * sizeof *avail->ring + s) &&
1218 sizeof *used + num * sizeof *used->ring + s);
1221 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1222 const struct vhost_umem_node *node,
1225 int access = (type == VHOST_ADDR_USED) ?
1226 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1228 if (likely(node->perm & access))
1229 vq->meta_iotlb[type] = node;
1232 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1233 int access, u64 addr, u64 len, int type)
1235 const struct vhost_umem_node *node;
1236 struct vhost_umem *umem = vq->iotlb;
1237 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1239 if (vhost_vq_meta_fetch(vq, addr, len, type))
1243 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1246 if (node == NULL || node->start > addr) {
1247 vhost_iotlb_miss(vq, addr, access);
1249 } else if (!(node->perm & access)) {
1250 /* Report the possible access violation by
1251 * request another translation from userspace.
1256 size = node->size - addr + node->start;
1258 if (orig_addr == addr && size >= len)
1259 vhost_vq_meta_update(vq, node, type);
1268 int vq_iotlb_prefetch(struct vhost_virtqueue *vq)
1270 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1271 unsigned int num = vq->num;
1276 return iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->desc,
1277 num * sizeof(*vq->desc), VHOST_ADDR_DESC) &&
1278 iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->avail,
1280 num * sizeof(*vq->avail->ring) + s,
1281 VHOST_ADDR_AVAIL) &&
1282 iotlb_access_ok(vq, VHOST_ACCESS_WO, (u64)(uintptr_t)vq->used,
1284 num * sizeof(*vq->used->ring) + s,
1287 EXPORT_SYMBOL_GPL(vq_iotlb_prefetch);
1289 /* Can we log writes? */
1290 /* Caller should have device mutex but not vq mutex */
1291 bool vhost_log_access_ok(struct vhost_dev *dev)
1293 return memory_access_ok(dev, dev->umem, 1);
1295 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1297 /* Verify access for write logging. */
1298 /* Caller should have vq mutex and device mutex */
1299 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1300 void __user *log_base)
1302 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1304 return vq_memory_access_ok(log_base, vq->umem,
1305 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1306 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
1308 vq->num * sizeof *vq->used->ring + s));
1311 /* Can we start vq? */
1312 /* Caller should have vq mutex and device mutex */
1313 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1315 if (!vq_log_access_ok(vq, vq->log_base))
1318 /* Access validation occurs at prefetch time with IOTLB */
1322 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1324 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1326 static struct vhost_umem *vhost_umem_alloc(void)
1328 struct vhost_umem *umem = kvzalloc(sizeof(*umem), GFP_KERNEL);
1333 umem->umem_tree = RB_ROOT_CACHED;
1335 INIT_LIST_HEAD(&umem->umem_list);
1340 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1342 struct vhost_memory mem, *newmem;
1343 struct vhost_memory_region *region;
1344 struct vhost_umem *newumem, *oldumem;
1345 unsigned long size = offsetof(struct vhost_memory, regions);
1348 if (copy_from_user(&mem, m, size))
1352 if (mem.nregions > max_mem_regions)
1354 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1359 memcpy(newmem, &mem, size);
1360 if (copy_from_user(newmem->regions, m->regions,
1361 mem.nregions * sizeof *m->regions)) {
1366 newumem = vhost_umem_alloc();
1372 for (region = newmem->regions;
1373 region < newmem->regions + mem.nregions;
1375 if (vhost_new_umem_range(newumem,
1376 region->guest_phys_addr,
1377 region->memory_size,
1378 region->guest_phys_addr +
1379 region->memory_size - 1,
1380 region->userspace_addr,
1385 if (!memory_access_ok(d, newumem, 0))
1391 /* All memory accesses are done under some VQ mutex. */
1392 for (i = 0; i < d->nvqs; ++i) {
1393 mutex_lock(&d->vqs[i]->mutex);
1394 d->vqs[i]->umem = newumem;
1395 mutex_unlock(&d->vqs[i]->mutex);
1399 vhost_umem_clean(oldumem);
1403 vhost_umem_clean(newumem);
1408 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1410 struct file *eventfp, *filep = NULL;
1411 bool pollstart = false, pollstop = false;
1412 struct eventfd_ctx *ctx = NULL;
1413 u32 __user *idxp = argp;
1414 struct vhost_virtqueue *vq;
1415 struct vhost_vring_state s;
1416 struct vhost_vring_file f;
1417 struct vhost_vring_addr a;
1421 r = get_user(idx, idxp);
1427 idx = array_index_nospec(idx, d->nvqs);
1430 mutex_lock(&vq->mutex);
1433 case VHOST_SET_VRING_NUM:
1434 /* Resizing ring with an active backend?
1435 * You don't want to do that. */
1436 if (vq->private_data) {
1440 if (copy_from_user(&s, argp, sizeof s)) {
1444 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
1450 case VHOST_SET_VRING_BASE:
1451 /* Moving base with an active backend?
1452 * You don't want to do that. */
1453 if (vq->private_data) {
1457 if (copy_from_user(&s, argp, sizeof s)) {
1461 if (s.num > 0xffff) {
1465 vq->last_avail_idx = s.num;
1466 /* Forget the cached index value. */
1467 vq->avail_idx = vq->last_avail_idx;
1469 case VHOST_GET_VRING_BASE:
1471 s.num = vq->last_avail_idx;
1472 if (copy_to_user(argp, &s, sizeof s))
1475 case VHOST_SET_VRING_ADDR:
1476 if (copy_from_user(&a, argp, sizeof a)) {
1480 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
1484 /* For 32bit, verify that the top 32bits of the user
1485 data are set to zero. */
1486 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1487 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1488 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
1493 /* Make sure it's safe to cast pointers to vring types. */
1494 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1495 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1496 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1497 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1498 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1))) {
1503 /* We only verify access here if backend is configured.
1504 * If it is not, we don't as size might not have been setup.
1505 * We will verify when backend is configured. */
1506 if (vq->private_data) {
1507 if (!vq_access_ok(vq, vq->num,
1508 (void __user *)(unsigned long)a.desc_user_addr,
1509 (void __user *)(unsigned long)a.avail_user_addr,
1510 (void __user *)(unsigned long)a.used_user_addr)) {
1515 /* Also validate log access for used ring if enabled. */
1516 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
1517 !log_access_ok(vq->log_base, a.log_guest_addr,
1519 vq->num * sizeof *vq->used->ring)) {
1525 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1526 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1527 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1528 vq->log_addr = a.log_guest_addr;
1529 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1531 case VHOST_SET_VRING_KICK:
1532 if (copy_from_user(&f, argp, sizeof f)) {
1536 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1537 if (IS_ERR(eventfp)) {
1538 r = PTR_ERR(eventfp);
1541 if (eventfp != vq->kick) {
1542 pollstop = (filep = vq->kick) != NULL;
1543 pollstart = (vq->kick = eventfp) != NULL;
1547 case VHOST_SET_VRING_CALL:
1548 if (copy_from_user(&f, argp, sizeof f)) {
1552 ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1557 swap(ctx, vq->call_ctx);
1559 case VHOST_SET_VRING_ERR:
1560 if (copy_from_user(&f, argp, sizeof f)) {
1564 ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1569 swap(ctx, vq->error_ctx);
1571 case VHOST_SET_VRING_ENDIAN:
1572 r = vhost_set_vring_endian(vq, argp);
1574 case VHOST_GET_VRING_ENDIAN:
1575 r = vhost_get_vring_endian(vq, idx, argp);
1577 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1578 if (copy_from_user(&s, argp, sizeof(s))) {
1582 vq->busyloop_timeout = s.num;
1584 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1586 s.num = vq->busyloop_timeout;
1587 if (copy_to_user(argp, &s, sizeof(s)))
1594 if (pollstop && vq->handle_kick)
1595 vhost_poll_stop(&vq->poll);
1597 if (!IS_ERR_OR_NULL(ctx))
1598 eventfd_ctx_put(ctx);
1602 if (pollstart && vq->handle_kick)
1603 r = vhost_poll_start(&vq->poll, vq->kick);
1605 mutex_unlock(&vq->mutex);
1607 if (pollstop && vq->handle_kick)
1608 vhost_poll_flush(&vq->poll);
1611 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1613 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1615 struct vhost_umem *niotlb, *oiotlb;
1618 niotlb = vhost_umem_alloc();
1625 for (i = 0; i < d->nvqs; ++i) {
1626 struct vhost_virtqueue *vq = d->vqs[i];
1628 mutex_lock(&vq->mutex);
1630 __vhost_vq_meta_reset(vq);
1631 mutex_unlock(&vq->mutex);
1634 vhost_umem_clean(oiotlb);
1638 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1640 /* Caller must have device mutex */
1641 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1643 struct eventfd_ctx *ctx;
1648 /* If you are not the owner, you can become one */
1649 if (ioctl == VHOST_SET_OWNER) {
1650 r = vhost_dev_set_owner(d);
1654 /* You must be the owner to do anything else */
1655 r = vhost_dev_check_owner(d);
1660 case VHOST_SET_MEM_TABLE:
1661 r = vhost_set_memory(d, argp);
1663 case VHOST_SET_LOG_BASE:
1664 if (copy_from_user(&p, argp, sizeof p)) {
1668 if ((u64)(unsigned long)p != p) {
1672 for (i = 0; i < d->nvqs; ++i) {
1673 struct vhost_virtqueue *vq;
1674 void __user *base = (void __user *)(unsigned long)p;
1676 mutex_lock(&vq->mutex);
1677 /* If ring is inactive, will check when it's enabled. */
1678 if (vq->private_data && !vq_log_access_ok(vq, base))
1681 vq->log_base = base;
1682 mutex_unlock(&vq->mutex);
1685 case VHOST_SET_LOG_FD:
1686 r = get_user(fd, (int __user *)argp);
1689 ctx = fd == -1 ? NULL : eventfd_ctx_fdget(fd);
1694 swap(ctx, d->log_ctx);
1695 for (i = 0; i < d->nvqs; ++i) {
1696 mutex_lock(&d->vqs[i]->mutex);
1697 d->vqs[i]->log_ctx = d->log_ctx;
1698 mutex_unlock(&d->vqs[i]->mutex);
1701 eventfd_ctx_put(ctx);
1710 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1712 /* TODO: This is really inefficient. We need something like get_user()
1713 * (instruction directly accesses the data, with an exception table entry
1714 * returning -EFAULT). See Documentation/x86/exception-tables.rst.
1716 static int set_bit_to_user(int nr, void __user *addr)
1718 unsigned long log = (unsigned long)addr;
1721 int bit = nr + (log % PAGE_SIZE) * 8;
1724 r = get_user_pages_fast(log, 1, FOLL_WRITE, &page);
1728 base = kmap_atomic(page);
1730 kunmap_atomic(base);
1731 set_page_dirty_lock(page);
1736 static int log_write(void __user *log_base,
1737 u64 write_address, u64 write_length)
1739 u64 write_page = write_address / VHOST_PAGE_SIZE;
1744 write_length += write_address % VHOST_PAGE_SIZE;
1746 u64 base = (u64)(unsigned long)log_base;
1747 u64 log = base + write_page / 8;
1748 int bit = write_page % 8;
1749 if ((u64)(unsigned long)log != log)
1751 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1754 if (write_length <= VHOST_PAGE_SIZE)
1756 write_length -= VHOST_PAGE_SIZE;
1762 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1764 struct vhost_umem *umem = vq->umem;
1765 struct vhost_umem_node *u;
1766 u64 start, end, l, min;
1772 /* More than one GPAs can be mapped into a single HVA. So
1773 * iterate all possible umems here to be safe.
1775 list_for_each_entry(u, &umem->umem_list, link) {
1776 if (u->userspace_addr > hva - 1 + len ||
1777 u->userspace_addr - 1 + u->size < hva)
1779 start = max(u->userspace_addr, hva);
1780 end = min(u->userspace_addr - 1 + u->size,
1782 l = end - start + 1;
1783 r = log_write(vq->log_base,
1784 u->start + start - u->userspace_addr,
1802 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1804 struct iovec iov[64];
1808 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1810 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1811 len, iov, 64, VHOST_ACCESS_WO);
1815 for (i = 0; i < ret; i++) {
1816 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1825 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1826 unsigned int log_num, u64 len, struct iovec *iov, int count)
1830 /* Make sure data written is seen before log. */
1834 for (i = 0; i < count; i++) {
1835 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1843 for (i = 0; i < log_num; ++i) {
1844 u64 l = min(log[i].len, len);
1845 r = log_write(vq->log_base, log[i].addr, l);
1851 eventfd_signal(vq->log_ctx, 1);
1855 /* Length written exceeds what we have stored. This is a bug. */
1859 EXPORT_SYMBOL_GPL(vhost_log_write);
1861 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1864 if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
1865 &vq->used->flags) < 0)
1867 if (unlikely(vq->log_used)) {
1868 /* Make sure the flag is seen before log. */
1870 /* Log used flag write. */
1871 used = &vq->used->flags;
1872 log_used(vq, (used - (void __user *)vq->used),
1873 sizeof vq->used->flags);
1875 eventfd_signal(vq->log_ctx, 1);
1880 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1882 if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
1883 vhost_avail_event(vq)))
1885 if (unlikely(vq->log_used)) {
1887 /* Make sure the event is seen before log. */
1889 /* Log avail event write */
1890 used = vhost_avail_event(vq);
1891 log_used(vq, (used - (void __user *)vq->used),
1892 sizeof *vhost_avail_event(vq));
1894 eventfd_signal(vq->log_ctx, 1);
1899 int vhost_vq_init_access(struct vhost_virtqueue *vq)
1901 __virtio16 last_used_idx;
1903 bool is_le = vq->is_le;
1905 if (!vq->private_data)
1908 vhost_init_is_le(vq);
1910 r = vhost_update_used_flags(vq);
1913 vq->signalled_used_valid = false;
1915 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
1919 r = vhost_get_used(vq, last_used_idx, &vq->used->idx);
1921 vq_err(vq, "Can't access used idx at %p\n",
1925 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1932 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
1934 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1935 struct iovec iov[], int iov_size, int access)
1937 const struct vhost_umem_node *node;
1938 struct vhost_dev *dev = vq->dev;
1939 struct vhost_umem *umem = dev->iotlb ? dev->iotlb : dev->umem;
1944 while ((u64)len > s) {
1946 if (unlikely(ret >= iov_size)) {
1951 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1952 addr, addr + len - 1);
1953 if (node == NULL || node->start > addr) {
1954 if (umem != dev->iotlb) {
1960 } else if (!(node->perm & access)) {
1966 size = node->size - addr + node->start;
1967 _iov->iov_len = min((u64)len - s, size);
1968 _iov->iov_base = (void __user *)(unsigned long)
1969 (node->userspace_addr + addr - node->start);
1976 vhost_iotlb_miss(vq, addr, access);
1980 /* Each buffer in the virtqueues is actually a chain of descriptors. This
1981 * function returns the next descriptor in the chain,
1982 * or -1U if we're at the end. */
1983 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1987 /* If this descriptor says it doesn't chain, we're done. */
1988 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1991 /* Check they're not leading us off end of descriptors. */
1992 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
1996 static int get_indirect(struct vhost_virtqueue *vq,
1997 struct iovec iov[], unsigned int iov_size,
1998 unsigned int *out_num, unsigned int *in_num,
1999 struct vhost_log *log, unsigned int *log_num,
2000 struct vring_desc *indirect)
2002 struct vring_desc desc;
2003 unsigned int i = 0, count, found = 0;
2004 u32 len = vhost32_to_cpu(vq, indirect->len);
2005 struct iov_iter from;
2009 if (unlikely(len % sizeof desc)) {
2010 vq_err(vq, "Invalid length in indirect descriptor: "
2011 "len 0x%llx not multiple of 0x%zx\n",
2012 (unsigned long long)len,
2017 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2018 UIO_MAXIOV, VHOST_ACCESS_RO);
2019 if (unlikely(ret < 0)) {
2021 vq_err(vq, "Translation failure %d in indirect.\n", ret);
2024 iov_iter_init(&from, READ, vq->indirect, ret, len);
2026 /* We will use the result as an address to read from, so most
2027 * architectures only need a compiler barrier here. */
2028 read_barrier_depends();
2030 count = len / sizeof desc;
2031 /* Buffers are chained via a 16 bit next field, so
2032 * we can have at most 2^16 of these. */
2033 if (unlikely(count > USHRT_MAX + 1)) {
2034 vq_err(vq, "Indirect buffer length too big: %d\n",
2040 unsigned iov_count = *in_num + *out_num;
2041 if (unlikely(++found > count)) {
2042 vq_err(vq, "Loop detected: last one at %u "
2043 "indirect size %u\n",
2047 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2048 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2049 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2052 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2053 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2054 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2058 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2059 access = VHOST_ACCESS_WO;
2061 access = VHOST_ACCESS_RO;
2063 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2064 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2065 iov_size - iov_count, access);
2066 if (unlikely(ret < 0)) {
2068 vq_err(vq, "Translation failure %d indirect idx %d\n",
2072 /* If this is an input descriptor, increment that count. */
2073 if (access == VHOST_ACCESS_WO) {
2075 if (unlikely(log)) {
2076 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2077 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2081 /* If it's an output descriptor, they're all supposed
2082 * to come before any input descriptors. */
2083 if (unlikely(*in_num)) {
2084 vq_err(vq, "Indirect descriptor "
2085 "has out after in: idx %d\n", i);
2090 } while ((i = next_desc(vq, &desc)) != -1);
2094 /* This looks in the virtqueue and for the first available buffer, and converts
2095 * it to an iovec for convenient access. Since descriptors consist of some
2096 * number of output then some number of input descriptors, it's actually two
2097 * iovecs, but we pack them into one and note how many of each there were.
2099 * This function returns the descriptor number found, or vq->num (which is
2100 * never a valid descriptor number) if none was found. A negative code is
2101 * returned on error. */
2102 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2103 struct iovec iov[], unsigned int iov_size,
2104 unsigned int *out_num, unsigned int *in_num,
2105 struct vhost_log *log, unsigned int *log_num)
2107 struct vring_desc desc;
2108 unsigned int i, head, found = 0;
2110 __virtio16 avail_idx;
2111 __virtio16 ring_head;
2114 /* Check it isn't doing very strange things with descriptor numbers. */
2115 last_avail_idx = vq->last_avail_idx;
2117 if (vq->avail_idx == vq->last_avail_idx) {
2118 if (unlikely(vhost_get_avail(vq, avail_idx, &vq->avail->idx))) {
2119 vq_err(vq, "Failed to access avail idx at %p\n",
2123 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2125 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2126 vq_err(vq, "Guest moved used index from %u to %u",
2127 last_avail_idx, vq->avail_idx);
2131 /* If there's nothing new since last we looked, return
2134 if (vq->avail_idx == last_avail_idx)
2137 /* Only get avail ring entries after they have been
2143 /* Grab the next descriptor number they're advertising, and increment
2144 * the index we've seen. */
2145 if (unlikely(vhost_get_avail(vq, ring_head,
2146 &vq->avail->ring[last_avail_idx & (vq->num - 1)]))) {
2147 vq_err(vq, "Failed to read head: idx %d address %p\n",
2149 &vq->avail->ring[last_avail_idx % vq->num]);
2153 head = vhost16_to_cpu(vq, ring_head);
2155 /* If their number is silly, that's an error. */
2156 if (unlikely(head >= vq->num)) {
2157 vq_err(vq, "Guest says index %u > %u is available",
2162 /* When we start there are none of either input nor output. */
2163 *out_num = *in_num = 0;
2169 unsigned iov_count = *in_num + *out_num;
2170 if (unlikely(i >= vq->num)) {
2171 vq_err(vq, "Desc index is %u > %u, head = %u",
2175 if (unlikely(++found > vq->num)) {
2176 vq_err(vq, "Loop detected: last one at %u "
2177 "vq size %u head %u\n",
2181 ret = vhost_copy_from_user(vq, &desc, vq->desc + i,
2183 if (unlikely(ret)) {
2184 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2188 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2189 ret = get_indirect(vq, iov, iov_size,
2191 log, log_num, &desc);
2192 if (unlikely(ret < 0)) {
2194 vq_err(vq, "Failure detected "
2195 "in indirect descriptor at idx %d\n", i);
2201 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2202 access = VHOST_ACCESS_WO;
2204 access = VHOST_ACCESS_RO;
2205 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2206 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2207 iov_size - iov_count, access);
2208 if (unlikely(ret < 0)) {
2210 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2214 if (access == VHOST_ACCESS_WO) {
2215 /* If this is an input descriptor,
2216 * increment that count. */
2218 if (unlikely(log)) {
2219 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2220 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2224 /* If it's an output descriptor, they're all supposed
2225 * to come before any input descriptors. */
2226 if (unlikely(*in_num)) {
2227 vq_err(vq, "Descriptor has out after in: "
2233 } while ((i = next_desc(vq, &desc)) != -1);
2235 /* On success, increment avail index. */
2236 vq->last_avail_idx++;
2238 /* Assume notifications from guest are disabled at this point,
2239 * if they aren't we would need to update avail_event index. */
2240 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2243 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2245 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2246 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2248 vq->last_avail_idx -= n;
2250 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2252 /* After we've used one of their buffers, we tell them about it. We'll then
2253 * want to notify the guest, using eventfd. */
2254 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2256 struct vring_used_elem heads = {
2257 cpu_to_vhost32(vq, head),
2258 cpu_to_vhost32(vq, len)
2261 return vhost_add_used_n(vq, &heads, 1);
2263 EXPORT_SYMBOL_GPL(vhost_add_used);
2265 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2266 struct vring_used_elem *heads,
2269 struct vring_used_elem __user *used;
2273 start = vq->last_used_idx & (vq->num - 1);
2274 used = vq->used->ring + start;
2276 if (vhost_put_user(vq, heads[0].id, &used->id)) {
2277 vq_err(vq, "Failed to write used id");
2280 if (vhost_put_user(vq, heads[0].len, &used->len)) {
2281 vq_err(vq, "Failed to write used len");
2284 } else if (vhost_copy_to_user(vq, used, heads, count * sizeof *used)) {
2285 vq_err(vq, "Failed to write used");
2288 if (unlikely(vq->log_used)) {
2289 /* Make sure data is seen before log. */
2291 /* Log used ring entry write. */
2292 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2293 count * sizeof *used);
2295 old = vq->last_used_idx;
2296 new = (vq->last_used_idx += count);
2297 /* If the driver never bothers to signal in a very long while,
2298 * used index might wrap around. If that happens, invalidate
2299 * signalled_used index we stored. TODO: make sure driver
2300 * signals at least once in 2^16 and remove this. */
2301 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2302 vq->signalled_used_valid = false;
2306 /* After we've used one of their buffers, we tell them about it. We'll then
2307 * want to notify the guest, using eventfd. */
2308 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2313 start = vq->last_used_idx & (vq->num - 1);
2314 n = vq->num - start;
2316 r = __vhost_add_used_n(vq, heads, n);
2322 r = __vhost_add_used_n(vq, heads, count);
2324 /* Make sure buffer is written before we update index. */
2326 if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
2328 vq_err(vq, "Failed to increment used idx");
2331 if (unlikely(vq->log_used)) {
2332 /* Make sure used idx is seen before log. */
2334 /* Log used index update. */
2335 log_used(vq, offsetof(struct vring_used, idx),
2336 sizeof vq->used->idx);
2338 eventfd_signal(vq->log_ctx, 1);
2342 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2344 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2349 /* Flush out used index updates. This is paired
2350 * with the barrier that the Guest executes when enabling
2354 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2355 unlikely(vq->avail_idx == vq->last_avail_idx))
2358 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2360 if (vhost_get_avail(vq, flags, &vq->avail->flags)) {
2361 vq_err(vq, "Failed to get flags");
2364 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2366 old = vq->signalled_used;
2367 v = vq->signalled_used_valid;
2368 new = vq->signalled_used = vq->last_used_idx;
2369 vq->signalled_used_valid = true;
2374 if (vhost_get_avail(vq, event, vhost_used_event(vq))) {
2375 vq_err(vq, "Failed to get used event idx");
2378 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2381 /* This actually signals the guest, using eventfd. */
2382 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2384 /* Signal the Guest tell them we used something up. */
2385 if (vq->call_ctx && vhost_notify(dev, vq))
2386 eventfd_signal(vq->call_ctx, 1);
2388 EXPORT_SYMBOL_GPL(vhost_signal);
2390 /* And here's the combo meal deal. Supersize me! */
2391 void vhost_add_used_and_signal(struct vhost_dev *dev,
2392 struct vhost_virtqueue *vq,
2393 unsigned int head, int len)
2395 vhost_add_used(vq, head, len);
2396 vhost_signal(dev, vq);
2398 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2400 /* multi-buffer version of vhost_add_used_and_signal */
2401 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2402 struct vhost_virtqueue *vq,
2403 struct vring_used_elem *heads, unsigned count)
2405 vhost_add_used_n(vq, heads, count);
2406 vhost_signal(dev, vq);
2408 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2410 /* return true if we're sure that avaiable ring is empty */
2411 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2413 __virtio16 avail_idx;
2416 if (vq->avail_idx != vq->last_avail_idx)
2419 r = vhost_get_avail(vq, avail_idx, &vq->avail->idx);
2422 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2424 return vq->avail_idx == vq->last_avail_idx;
2426 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2428 /* OK, now we need to know about added descriptors. */
2429 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2431 __virtio16 avail_idx;
2434 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2436 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2437 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2438 r = vhost_update_used_flags(vq);
2440 vq_err(vq, "Failed to enable notification at %p: %d\n",
2441 &vq->used->flags, r);
2445 r = vhost_update_avail_event(vq, vq->avail_idx);
2447 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2448 vhost_avail_event(vq), r);
2452 /* They could have slipped one in as we were doing that: make
2453 * sure it's written, then check again. */
2455 r = vhost_get_avail(vq, avail_idx, &vq->avail->idx);
2457 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2458 &vq->avail->idx, r);
2462 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2464 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2466 /* We don't need to be notified again. */
2467 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2471 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2473 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2474 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2475 r = vhost_update_used_flags(vq);
2477 vq_err(vq, "Failed to enable notification at %p: %d\n",
2478 &vq->used->flags, r);
2481 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2483 /* Create a new message. */
2484 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2486 struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2490 /* Make sure all padding within the structure is initialized. */
2491 memset(&node->msg, 0, sizeof node->msg);
2493 node->msg.type = type;
2496 EXPORT_SYMBOL_GPL(vhost_new_msg);
2498 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2499 struct vhost_msg_node *node)
2501 spin_lock(&dev->iotlb_lock);
2502 list_add_tail(&node->node, head);
2503 spin_unlock(&dev->iotlb_lock);
2505 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2507 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2509 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2510 struct list_head *head)
2512 struct vhost_msg_node *node = NULL;
2514 spin_lock(&dev->iotlb_lock);
2515 if (!list_empty(head)) {
2516 node = list_first_entry(head, struct vhost_msg_node,
2518 list_del(&node->node);
2520 spin_unlock(&dev->iotlb_lock);
2524 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2527 static int __init vhost_init(void)
2532 static void __exit vhost_exit(void)
2536 module_init(vhost_init);
2537 module_exit(vhost_exit);
2539 MODULE_VERSION("0.0.1");
2540 MODULE_LICENSE("GPL v2");
2541 MODULE_AUTHOR("Michael S. Tsirkin");
2542 MODULE_DESCRIPTION("Host kernel accelerator for virtio");