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)
210 mask = vfs_poll(file, &poll->table);
212 vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
213 if (mask & EPOLLERR) {
214 vhost_poll_stop(poll);
220 EXPORT_SYMBOL_GPL(vhost_poll_start);
222 /* Stop polling a file. After this function returns, it becomes safe to drop the
223 * file reference. You must also flush afterwards. */
224 void vhost_poll_stop(struct vhost_poll *poll)
227 remove_wait_queue(poll->wqh, &poll->wait);
231 EXPORT_SYMBOL_GPL(vhost_poll_stop);
233 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
235 struct vhost_flush_struct flush;
238 init_completion(&flush.wait_event);
239 vhost_work_init(&flush.work, vhost_flush_work);
241 vhost_work_queue(dev, &flush.work);
242 wait_for_completion(&flush.wait_event);
245 EXPORT_SYMBOL_GPL(vhost_work_flush);
247 /* Flush any work that has been scheduled. When calling this, don't hold any
248 * locks that are also used by the callback. */
249 void vhost_poll_flush(struct vhost_poll *poll)
251 vhost_work_flush(poll->dev, &poll->work);
253 EXPORT_SYMBOL_GPL(vhost_poll_flush);
255 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
260 if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
261 /* We can only add the work to the list after we're
262 * sure it was not in the list.
263 * test_and_set_bit() implies a memory barrier.
265 llist_add(&work->node, &dev->work_list);
266 wake_up_process(dev->worker);
269 EXPORT_SYMBOL_GPL(vhost_work_queue);
271 /* A lockless hint for busy polling code to exit the loop */
272 bool vhost_has_work(struct vhost_dev *dev)
274 return !llist_empty(&dev->work_list);
276 EXPORT_SYMBOL_GPL(vhost_has_work);
278 void vhost_poll_queue(struct vhost_poll *poll)
280 vhost_work_queue(poll->dev, &poll->work);
282 EXPORT_SYMBOL_GPL(vhost_poll_queue);
284 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
288 for (j = 0; j < VHOST_NUM_ADDRS; j++)
289 vq->meta_iotlb[j] = NULL;
292 static void vhost_vq_meta_reset(struct vhost_dev *d)
296 for (i = 0; i < d->nvqs; ++i)
297 __vhost_vq_meta_reset(d->vqs[i]);
300 static void vhost_vq_reset(struct vhost_dev *dev,
301 struct vhost_virtqueue *vq)
307 vq->last_avail_idx = 0;
309 vq->last_used_idx = 0;
310 vq->signalled_used = 0;
311 vq->signalled_used_valid = false;
313 vq->log_used = false;
314 vq->log_addr = -1ull;
315 vq->private_data = NULL;
316 vq->acked_features = 0;
317 vq->acked_backend_features = 0;
319 vq->error_ctx = NULL;
323 vhost_disable_cross_endian(vq);
324 vhost_reset_is_le(vq);
325 vq->busyloop_timeout = 0;
328 __vhost_vq_meta_reset(vq);
331 static int vhost_worker(void *data)
333 struct vhost_dev *dev = data;
334 struct vhost_work *work, *work_next;
335 struct llist_node *node;
336 mm_segment_t oldfs = get_fs();
342 /* mb paired w/ kthread_stop */
343 set_current_state(TASK_INTERRUPTIBLE);
345 if (kthread_should_stop()) {
346 __set_current_state(TASK_RUNNING);
350 node = llist_del_all(&dev->work_list);
354 node = llist_reverse_order(node);
355 /* make sure flag is seen after deletion */
357 llist_for_each_entry_safe(work, work_next, node, node) {
358 clear_bit(VHOST_WORK_QUEUED, &work->flags);
359 __set_current_state(TASK_RUNNING);
370 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
380 /* Helper to allocate iovec buffers for all vqs. */
381 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
383 struct vhost_virtqueue *vq;
386 for (i = 0; i < dev->nvqs; ++i) {
388 vq->indirect = kmalloc_array(UIO_MAXIOV,
389 sizeof(*vq->indirect),
391 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
393 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
395 if (!vq->indirect || !vq->log || !vq->heads)
402 vhost_vq_free_iovecs(dev->vqs[i]);
406 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
410 for (i = 0; i < dev->nvqs; ++i)
411 vhost_vq_free_iovecs(dev->vqs[i]);
414 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
415 int pkts, int total_len)
417 struct vhost_dev *dev = vq->dev;
419 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
420 pkts >= dev->weight) {
421 vhost_poll_queue(&vq->poll);
427 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
429 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
432 size_t event __maybe_unused =
433 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
435 return sizeof(*vq->avail) +
436 sizeof(*vq->avail->ring) * num + event;
439 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
442 size_t event __maybe_unused =
443 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
445 return sizeof(*vq->used) +
446 sizeof(*vq->used->ring) * num + event;
449 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
452 return sizeof(*vq->desc) * num;
455 void vhost_dev_init(struct vhost_dev *dev,
456 struct vhost_virtqueue **vqs, int nvqs,
457 int iov_limit, int weight, int byte_weight)
459 struct vhost_virtqueue *vq;
464 mutex_init(&dev->mutex);
470 dev->iov_limit = iov_limit;
471 dev->weight = weight;
472 dev->byte_weight = byte_weight;
473 init_llist_head(&dev->work_list);
474 init_waitqueue_head(&dev->wait);
475 INIT_LIST_HEAD(&dev->read_list);
476 INIT_LIST_HEAD(&dev->pending_list);
477 spin_lock_init(&dev->iotlb_lock);
480 for (i = 0; i < dev->nvqs; ++i) {
486 mutex_init(&vq->mutex);
487 vhost_vq_reset(dev, vq);
489 vhost_poll_init(&vq->poll, vq->handle_kick,
493 EXPORT_SYMBOL_GPL(vhost_dev_init);
495 /* Caller should have device mutex */
496 long vhost_dev_check_owner(struct vhost_dev *dev)
498 /* Are you the owner? If not, I don't think you mean to do that */
499 return dev->mm == current->mm ? 0 : -EPERM;
501 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
503 struct vhost_attach_cgroups_struct {
504 struct vhost_work work;
505 struct task_struct *owner;
509 static void vhost_attach_cgroups_work(struct vhost_work *work)
511 struct vhost_attach_cgroups_struct *s;
513 s = container_of(work, struct vhost_attach_cgroups_struct, work);
514 s->ret = cgroup_attach_task_all(s->owner, current);
517 static int vhost_attach_cgroups(struct vhost_dev *dev)
519 struct vhost_attach_cgroups_struct attach;
521 attach.owner = current;
522 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
523 vhost_work_queue(dev, &attach.work);
524 vhost_work_flush(dev, &attach.work);
528 /* Caller should have device mutex */
529 bool vhost_dev_has_owner(struct vhost_dev *dev)
533 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
535 /* Caller should have device mutex */
536 long vhost_dev_set_owner(struct vhost_dev *dev)
538 struct task_struct *worker;
541 /* Is there an owner already? */
542 if (vhost_dev_has_owner(dev)) {
547 /* No owner, become one */
548 dev->mm = get_task_mm(current);
549 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
550 if (IS_ERR(worker)) {
551 err = PTR_ERR(worker);
555 dev->worker = worker;
556 wake_up_process(worker); /* avoid contributing to loadavg */
558 err = vhost_attach_cgroups(dev);
562 err = vhost_dev_alloc_iovecs(dev);
568 kthread_stop(worker);
577 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
579 struct vhost_umem *vhost_dev_reset_owner_prepare(void)
581 return kvzalloc(sizeof(struct vhost_umem), GFP_KERNEL);
583 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
585 /* Caller should have device mutex */
586 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_umem *umem)
590 vhost_dev_cleanup(dev);
592 /* Restore memory to default empty mapping. */
593 INIT_LIST_HEAD(&umem->umem_list);
595 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
596 * VQs aren't running.
598 for (i = 0; i < dev->nvqs; ++i)
599 dev->vqs[i]->umem = umem;
601 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
603 void vhost_dev_stop(struct vhost_dev *dev)
607 for (i = 0; i < dev->nvqs; ++i) {
608 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
609 vhost_poll_stop(&dev->vqs[i]->poll);
610 vhost_poll_flush(&dev->vqs[i]->poll);
614 EXPORT_SYMBOL_GPL(vhost_dev_stop);
616 static void vhost_umem_free(struct vhost_umem *umem,
617 struct vhost_umem_node *node)
619 vhost_umem_interval_tree_remove(node, &umem->umem_tree);
620 list_del(&node->link);
625 static void vhost_umem_clean(struct vhost_umem *umem)
627 struct vhost_umem_node *node, *tmp;
632 list_for_each_entry_safe(node, tmp, &umem->umem_list, link)
633 vhost_umem_free(umem, node);
638 static void vhost_clear_msg(struct vhost_dev *dev)
640 struct vhost_msg_node *node, *n;
642 spin_lock(&dev->iotlb_lock);
644 list_for_each_entry_safe(node, n, &dev->read_list, node) {
645 list_del(&node->node);
649 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
650 list_del(&node->node);
654 spin_unlock(&dev->iotlb_lock);
657 void vhost_dev_cleanup(struct vhost_dev *dev)
661 for (i = 0; i < dev->nvqs; ++i) {
662 if (dev->vqs[i]->error_ctx)
663 eventfd_ctx_put(dev->vqs[i]->error_ctx);
664 if (dev->vqs[i]->kick)
665 fput(dev->vqs[i]->kick);
666 if (dev->vqs[i]->call_ctx)
667 eventfd_ctx_put(dev->vqs[i]->call_ctx);
668 vhost_vq_reset(dev, dev->vqs[i]);
670 vhost_dev_free_iovecs(dev);
672 eventfd_ctx_put(dev->log_ctx);
674 /* No one will access memory at this point */
675 vhost_umem_clean(dev->umem);
677 vhost_umem_clean(dev->iotlb);
679 vhost_clear_msg(dev);
680 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
681 WARN_ON(!llist_empty(&dev->work_list));
683 kthread_stop(dev->worker);
690 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
692 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
694 u64 a = addr / VHOST_PAGE_SIZE / 8;
696 /* Make sure 64 bit math will not overflow. */
697 if (a > ULONG_MAX - (unsigned long)log_base ||
698 a + (unsigned long)log_base > ULONG_MAX)
701 return access_ok(log_base + a,
702 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
705 /* Make sure 64 bit math will not overflow. */
706 static bool vhost_overflow(u64 uaddr, u64 size)
708 if (uaddr > ULONG_MAX || size > ULONG_MAX)
714 return uaddr > ULONG_MAX - size + 1;
717 /* Caller should have vq mutex and device mutex. */
718 static bool vq_memory_access_ok(void __user *log_base, struct vhost_umem *umem,
721 struct vhost_umem_node *node;
726 list_for_each_entry(node, &umem->umem_list, link) {
727 unsigned long a = node->userspace_addr;
729 if (vhost_overflow(node->userspace_addr, node->size))
733 if (!access_ok((void __user *)a,
736 else if (log_all && !log_access_ok(log_base,
744 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
745 u64 addr, unsigned int size,
748 const struct vhost_umem_node *node = vq->meta_iotlb[type];
753 return (void *)(uintptr_t)(node->userspace_addr + addr - node->start);
756 /* Can we switch to this memory table? */
757 /* Caller should have device mutex but not vq mutex */
758 static bool memory_access_ok(struct vhost_dev *d, struct vhost_umem *umem,
763 for (i = 0; i < d->nvqs; ++i) {
767 mutex_lock(&d->vqs[i]->mutex);
768 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
769 /* If ring is inactive, will check when it's enabled. */
770 if (d->vqs[i]->private_data)
771 ok = vq_memory_access_ok(d->vqs[i]->log_base,
775 mutex_unlock(&d->vqs[i]->mutex);
782 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
783 struct iovec iov[], int iov_size, int access);
785 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
786 const void *from, unsigned size)
791 return __copy_to_user(to, from, size);
793 /* This function should be called after iotlb
794 * prefetch, which means we're sure that all vq
795 * could be access through iotlb. So -EAGAIN should
796 * not happen in this case.
799 void __user *uaddr = vhost_vq_meta_fetch(vq,
800 (u64)(uintptr_t)to, size,
804 return __copy_to_user(uaddr, from, size);
806 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
807 ARRAY_SIZE(vq->iotlb_iov),
811 iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
812 ret = copy_to_iter(from, size, &t);
820 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
821 void __user *from, unsigned size)
826 return __copy_from_user(to, from, size);
828 /* This function should be called after iotlb
829 * prefetch, which means we're sure that vq
830 * could be access through iotlb. So -EAGAIN should
831 * not happen in this case.
833 void __user *uaddr = vhost_vq_meta_fetch(vq,
834 (u64)(uintptr_t)from, size,
839 return __copy_from_user(to, uaddr, size);
841 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
842 ARRAY_SIZE(vq->iotlb_iov),
845 vq_err(vq, "IOTLB translation failure: uaddr "
846 "%p size 0x%llx\n", from,
847 (unsigned long long) size);
850 iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
851 ret = copy_from_iter(to, size, &f);
860 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
861 void __user *addr, unsigned int size,
866 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
867 ARRAY_SIZE(vq->iotlb_iov),
870 vq_err(vq, "IOTLB translation failure: uaddr "
871 "%p size 0x%llx\n", addr,
872 (unsigned long long) size);
876 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
877 vq_err(vq, "Non atomic userspace memory access: uaddr "
878 "%p size 0x%llx\n", addr,
879 (unsigned long long) size);
883 return vq->iotlb_iov[0].iov_base;
886 /* This function should be called after iotlb
887 * prefetch, which means we're sure that vq
888 * could be access through iotlb. So -EAGAIN should
889 * not happen in this case.
891 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
892 void *addr, unsigned int size,
895 void __user *uaddr = vhost_vq_meta_fetch(vq,
896 (u64)(uintptr_t)addr, size, type);
900 return __vhost_get_user_slow(vq, addr, size, type);
903 #define vhost_put_user(vq, x, ptr) \
907 ret = __put_user(x, ptr); \
909 __typeof__(ptr) to = \
910 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
911 sizeof(*ptr), VHOST_ADDR_USED); \
913 ret = __put_user(x, to); \
920 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
922 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
923 vhost_avail_event(vq));
926 static inline int vhost_put_used(struct vhost_virtqueue *vq,
927 struct vring_used_elem *head, int idx,
930 return vhost_copy_to_user(vq, vq->used->ring + idx, head,
931 count * sizeof(*head));
934 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
937 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
941 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
944 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
948 #define vhost_get_user(vq, x, ptr, type) \
952 ret = __get_user(x, ptr); \
954 __typeof__(ptr) from = \
955 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
959 ret = __get_user(x, from); \
966 #define vhost_get_avail(vq, x, ptr) \
967 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
969 #define vhost_get_used(vq, x, ptr) \
970 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
972 static void vhost_dev_lock_vqs(struct vhost_dev *d)
975 for (i = 0; i < d->nvqs; ++i)
976 mutex_lock_nested(&d->vqs[i]->mutex, i);
979 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
982 for (i = 0; i < d->nvqs; ++i)
983 mutex_unlock(&d->vqs[i]->mutex);
986 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
989 return vhost_get_avail(vq, *idx, &vq->avail->idx);
992 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
993 __virtio16 *head, int idx)
995 return vhost_get_avail(vq, *head,
996 &vq->avail->ring[idx & (vq->num - 1)]);
999 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1002 return vhost_get_avail(vq, *flags, &vq->avail->flags);
1005 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1008 return vhost_get_avail(vq, *event, vhost_used_event(vq));
1011 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1014 return vhost_get_used(vq, *idx, &vq->used->idx);
1017 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1018 struct vring_desc *desc, int idx)
1020 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1023 static int vhost_new_umem_range(struct vhost_umem *umem,
1024 u64 start, u64 size, u64 end,
1025 u64 userspace_addr, int perm)
1027 struct vhost_umem_node *tmp, *node;
1032 node = kmalloc(sizeof(*node), GFP_ATOMIC);
1036 if (umem->numem == max_iotlb_entries) {
1037 tmp = list_first_entry(&umem->umem_list, typeof(*tmp), link);
1038 vhost_umem_free(umem, tmp);
1041 node->start = start;
1044 node->userspace_addr = userspace_addr;
1046 INIT_LIST_HEAD(&node->link);
1047 list_add_tail(&node->link, &umem->umem_list);
1048 vhost_umem_interval_tree_insert(node, &umem->umem_tree);
1054 static void vhost_del_umem_range(struct vhost_umem *umem,
1057 struct vhost_umem_node *node;
1059 while ((node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1061 vhost_umem_free(umem, node);
1064 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1065 struct vhost_iotlb_msg *msg)
1067 struct vhost_msg_node *node, *n;
1069 spin_lock(&d->iotlb_lock);
1071 list_for_each_entry_safe(node, n, &d->pending_list, node) {
1072 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1073 if (msg->iova <= vq_msg->iova &&
1074 msg->iova + msg->size - 1 >= vq_msg->iova &&
1075 vq_msg->type == VHOST_IOTLB_MISS) {
1076 vhost_poll_queue(&node->vq->poll);
1077 list_del(&node->node);
1082 spin_unlock(&d->iotlb_lock);
1085 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1087 unsigned long a = uaddr;
1089 /* Make sure 64 bit math will not overflow. */
1090 if (vhost_overflow(uaddr, size))
1093 if ((access & VHOST_ACCESS_RO) &&
1094 !access_ok((void __user *)a, size))
1096 if ((access & VHOST_ACCESS_WO) &&
1097 !access_ok((void __user *)a, size))
1102 static int vhost_process_iotlb_msg(struct vhost_dev *dev,
1103 struct vhost_iotlb_msg *msg)
1107 mutex_lock(&dev->mutex);
1108 vhost_dev_lock_vqs(dev);
1109 switch (msg->type) {
1110 case VHOST_IOTLB_UPDATE:
1115 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1119 vhost_vq_meta_reset(dev);
1120 if (vhost_new_umem_range(dev->iotlb, msg->iova, msg->size,
1121 msg->iova + msg->size - 1,
1122 msg->uaddr, msg->perm)) {
1126 vhost_iotlb_notify_vq(dev, msg);
1128 case VHOST_IOTLB_INVALIDATE:
1133 vhost_vq_meta_reset(dev);
1134 vhost_del_umem_range(dev->iotlb, msg->iova,
1135 msg->iova + msg->size - 1);
1142 vhost_dev_unlock_vqs(dev);
1143 mutex_unlock(&dev->mutex);
1147 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1148 struct iov_iter *from)
1150 struct vhost_iotlb_msg msg;
1154 ret = copy_from_iter(&type, sizeof(type), from);
1155 if (ret != sizeof(type)) {
1161 case VHOST_IOTLB_MSG:
1162 /* There maybe a hole after type for V1 message type,
1165 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1167 case VHOST_IOTLB_MSG_V2:
1168 offset = sizeof(__u32);
1175 iov_iter_advance(from, offset);
1176 ret = copy_from_iter(&msg, sizeof(msg), from);
1177 if (ret != sizeof(msg)) {
1181 if (vhost_process_iotlb_msg(dev, &msg)) {
1186 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1187 sizeof(struct vhost_msg_v2);
1191 EXPORT_SYMBOL(vhost_chr_write_iter);
1193 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1198 poll_wait(file, &dev->wait, wait);
1200 if (!list_empty(&dev->read_list))
1201 mask |= EPOLLIN | EPOLLRDNORM;
1205 EXPORT_SYMBOL(vhost_chr_poll);
1207 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1211 struct vhost_msg_node *node;
1213 unsigned size = sizeof(struct vhost_msg);
1215 if (iov_iter_count(to) < size)
1220 prepare_to_wait(&dev->wait, &wait,
1221 TASK_INTERRUPTIBLE);
1223 node = vhost_dequeue_msg(dev, &dev->read_list);
1230 if (signal_pending(current)) {
1243 finish_wait(&dev->wait, &wait);
1246 struct vhost_iotlb_msg *msg;
1247 void *start = &node->msg;
1249 switch (node->msg.type) {
1250 case VHOST_IOTLB_MSG:
1251 size = sizeof(node->msg);
1252 msg = &node->msg.iotlb;
1254 case VHOST_IOTLB_MSG_V2:
1255 size = sizeof(node->msg_v2);
1256 msg = &node->msg_v2.iotlb;
1263 ret = copy_to_iter(start, size, to);
1264 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1268 vhost_enqueue_msg(dev, &dev->pending_list, node);
1273 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1275 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1277 struct vhost_dev *dev = vq->dev;
1278 struct vhost_msg_node *node;
1279 struct vhost_iotlb_msg *msg;
1280 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1282 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1287 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1288 msg = &node->msg_v2.iotlb;
1290 msg = &node->msg.iotlb;
1293 msg->type = VHOST_IOTLB_MISS;
1297 vhost_enqueue_msg(dev, &dev->read_list, node);
1302 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1303 struct vring_desc __user *desc,
1304 struct vring_avail __user *avail,
1305 struct vring_used __user *used)
1308 /* If an IOTLB device is present, the vring addresses are
1309 * GIOVAs. Access validation occurs at prefetch time. */
1313 return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1314 access_ok(avail, vhost_get_avail_size(vq, num)) &&
1315 access_ok(used, vhost_get_used_size(vq, num));
1318 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1319 const struct vhost_umem_node *node,
1322 int access = (type == VHOST_ADDR_USED) ?
1323 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1325 if (likely(node->perm & access))
1326 vq->meta_iotlb[type] = node;
1329 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1330 int access, u64 addr, u64 len, int type)
1332 const struct vhost_umem_node *node;
1333 struct vhost_umem *umem = vq->iotlb;
1334 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1336 if (vhost_vq_meta_fetch(vq, addr, len, type))
1340 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1343 if (node == NULL || node->start > addr) {
1344 vhost_iotlb_miss(vq, addr, access);
1346 } else if (!(node->perm & access)) {
1347 /* Report the possible access violation by
1348 * request another translation from userspace.
1353 size = node->size - addr + node->start;
1355 if (orig_addr == addr && size >= len)
1356 vhost_vq_meta_update(vq, node, type);
1365 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1367 unsigned int num = vq->num;
1372 return iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->desc,
1373 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1374 iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->avail,
1375 vhost_get_avail_size(vq, num),
1376 VHOST_ADDR_AVAIL) &&
1377 iotlb_access_ok(vq, VHOST_ACCESS_WO, (u64)(uintptr_t)vq->used,
1378 vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1380 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1382 /* Can we log writes? */
1383 /* Caller should have device mutex but not vq mutex */
1384 bool vhost_log_access_ok(struct vhost_dev *dev)
1386 return memory_access_ok(dev, dev->umem, 1);
1388 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1390 /* Verify access for write logging. */
1391 /* Caller should have vq mutex and device mutex */
1392 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1393 void __user *log_base)
1395 return vq_memory_access_ok(log_base, vq->umem,
1396 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1397 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
1398 vhost_get_used_size(vq, vq->num)));
1401 /* Can we start vq? */
1402 /* Caller should have vq mutex and device mutex */
1403 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1405 if (!vq_log_access_ok(vq, vq->log_base))
1408 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1410 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1412 static struct vhost_umem *vhost_umem_alloc(void)
1414 struct vhost_umem *umem = kvzalloc(sizeof(*umem), GFP_KERNEL);
1419 umem->umem_tree = RB_ROOT_CACHED;
1421 INIT_LIST_HEAD(&umem->umem_list);
1426 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1428 struct vhost_memory mem, *newmem;
1429 struct vhost_memory_region *region;
1430 struct vhost_umem *newumem, *oldumem;
1431 unsigned long size = offsetof(struct vhost_memory, regions);
1434 if (copy_from_user(&mem, m, size))
1438 if (mem.nregions > max_mem_regions)
1440 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1445 memcpy(newmem, &mem, size);
1446 if (copy_from_user(newmem->regions, m->regions,
1447 mem.nregions * sizeof *m->regions)) {
1452 newumem = vhost_umem_alloc();
1458 for (region = newmem->regions;
1459 region < newmem->regions + mem.nregions;
1461 if (vhost_new_umem_range(newumem,
1462 region->guest_phys_addr,
1463 region->memory_size,
1464 region->guest_phys_addr +
1465 region->memory_size - 1,
1466 region->userspace_addr,
1471 if (!memory_access_ok(d, newumem, 0))
1477 /* All memory accesses are done under some VQ mutex. */
1478 for (i = 0; i < d->nvqs; ++i) {
1479 mutex_lock(&d->vqs[i]->mutex);
1480 d->vqs[i]->umem = newumem;
1481 mutex_unlock(&d->vqs[i]->mutex);
1485 vhost_umem_clean(oldumem);
1489 vhost_umem_clean(newumem);
1494 static long vhost_vring_set_num(struct vhost_dev *d,
1495 struct vhost_virtqueue *vq,
1498 struct vhost_vring_state s;
1500 /* Resizing ring with an active backend?
1501 * You don't want to do that. */
1502 if (vq->private_data)
1505 if (copy_from_user(&s, argp, sizeof s))
1508 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
1515 static long vhost_vring_set_addr(struct vhost_dev *d,
1516 struct vhost_virtqueue *vq,
1519 struct vhost_vring_addr a;
1521 if (copy_from_user(&a, argp, sizeof a))
1523 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
1526 /* For 32bit, verify that the top 32bits of the user
1527 data are set to zero. */
1528 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1529 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1530 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
1533 /* Make sure it's safe to cast pointers to vring types. */
1534 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1535 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1536 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1537 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1538 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
1541 /* We only verify access here if backend is configured.
1542 * If it is not, we don't as size might not have been setup.
1543 * We will verify when backend is configured. */
1544 if (vq->private_data) {
1545 if (!vq_access_ok(vq, vq->num,
1546 (void __user *)(unsigned long)a.desc_user_addr,
1547 (void __user *)(unsigned long)a.avail_user_addr,
1548 (void __user *)(unsigned long)a.used_user_addr))
1551 /* Also validate log access for used ring if enabled. */
1552 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
1553 !log_access_ok(vq->log_base, a.log_guest_addr,
1554 vhost_get_used_size(vq, vq->num)))
1558 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1559 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1560 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1561 vq->log_addr = a.log_guest_addr;
1562 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1567 static long vhost_vring_set_num_addr(struct vhost_dev *d,
1568 struct vhost_virtqueue *vq,
1574 mutex_lock(&vq->mutex);
1577 case VHOST_SET_VRING_NUM:
1578 r = vhost_vring_set_num(d, vq, argp);
1580 case VHOST_SET_VRING_ADDR:
1581 r = vhost_vring_set_addr(d, vq, argp);
1587 mutex_unlock(&vq->mutex);
1591 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1593 struct file *eventfp, *filep = NULL;
1594 bool pollstart = false, pollstop = false;
1595 struct eventfd_ctx *ctx = NULL;
1596 u32 __user *idxp = argp;
1597 struct vhost_virtqueue *vq;
1598 struct vhost_vring_state s;
1599 struct vhost_vring_file f;
1603 r = get_user(idx, idxp);
1609 idx = array_index_nospec(idx, d->nvqs);
1612 if (ioctl == VHOST_SET_VRING_NUM ||
1613 ioctl == VHOST_SET_VRING_ADDR) {
1614 return vhost_vring_set_num_addr(d, vq, ioctl, argp);
1617 mutex_lock(&vq->mutex);
1620 case VHOST_SET_VRING_BASE:
1621 /* Moving base with an active backend?
1622 * You don't want to do that. */
1623 if (vq->private_data) {
1627 if (copy_from_user(&s, argp, sizeof s)) {
1631 if (s.num > 0xffff) {
1635 vq->last_avail_idx = s.num;
1636 /* Forget the cached index value. */
1637 vq->avail_idx = vq->last_avail_idx;
1639 case VHOST_GET_VRING_BASE:
1641 s.num = vq->last_avail_idx;
1642 if (copy_to_user(argp, &s, sizeof s))
1645 case VHOST_SET_VRING_KICK:
1646 if (copy_from_user(&f, argp, sizeof f)) {
1650 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1651 if (IS_ERR(eventfp)) {
1652 r = PTR_ERR(eventfp);
1655 if (eventfp != vq->kick) {
1656 pollstop = (filep = vq->kick) != NULL;
1657 pollstart = (vq->kick = eventfp) != NULL;
1661 case VHOST_SET_VRING_CALL:
1662 if (copy_from_user(&f, argp, sizeof f)) {
1666 ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1671 swap(ctx, vq->call_ctx);
1673 case VHOST_SET_VRING_ERR:
1674 if (copy_from_user(&f, argp, sizeof f)) {
1678 ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1683 swap(ctx, vq->error_ctx);
1685 case VHOST_SET_VRING_ENDIAN:
1686 r = vhost_set_vring_endian(vq, argp);
1688 case VHOST_GET_VRING_ENDIAN:
1689 r = vhost_get_vring_endian(vq, idx, argp);
1691 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1692 if (copy_from_user(&s, argp, sizeof(s))) {
1696 vq->busyloop_timeout = s.num;
1698 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1700 s.num = vq->busyloop_timeout;
1701 if (copy_to_user(argp, &s, sizeof(s)))
1708 if (pollstop && vq->handle_kick)
1709 vhost_poll_stop(&vq->poll);
1711 if (!IS_ERR_OR_NULL(ctx))
1712 eventfd_ctx_put(ctx);
1716 if (pollstart && vq->handle_kick)
1717 r = vhost_poll_start(&vq->poll, vq->kick);
1719 mutex_unlock(&vq->mutex);
1721 if (pollstop && vq->handle_kick)
1722 vhost_poll_flush(&vq->poll);
1725 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1727 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1729 struct vhost_umem *niotlb, *oiotlb;
1732 niotlb = vhost_umem_alloc();
1739 for (i = 0; i < d->nvqs; ++i) {
1740 struct vhost_virtqueue *vq = d->vqs[i];
1742 mutex_lock(&vq->mutex);
1744 __vhost_vq_meta_reset(vq);
1745 mutex_unlock(&vq->mutex);
1748 vhost_umem_clean(oiotlb);
1752 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1754 /* Caller must have device mutex */
1755 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1757 struct eventfd_ctx *ctx;
1762 /* If you are not the owner, you can become one */
1763 if (ioctl == VHOST_SET_OWNER) {
1764 r = vhost_dev_set_owner(d);
1768 /* You must be the owner to do anything else */
1769 r = vhost_dev_check_owner(d);
1774 case VHOST_SET_MEM_TABLE:
1775 r = vhost_set_memory(d, argp);
1777 case VHOST_SET_LOG_BASE:
1778 if (copy_from_user(&p, argp, sizeof p)) {
1782 if ((u64)(unsigned long)p != p) {
1786 for (i = 0; i < d->nvqs; ++i) {
1787 struct vhost_virtqueue *vq;
1788 void __user *base = (void __user *)(unsigned long)p;
1790 mutex_lock(&vq->mutex);
1791 /* If ring is inactive, will check when it's enabled. */
1792 if (vq->private_data && !vq_log_access_ok(vq, base))
1795 vq->log_base = base;
1796 mutex_unlock(&vq->mutex);
1799 case VHOST_SET_LOG_FD:
1800 r = get_user(fd, (int __user *)argp);
1803 ctx = fd == -1 ? NULL : eventfd_ctx_fdget(fd);
1808 swap(ctx, d->log_ctx);
1809 for (i = 0; i < d->nvqs; ++i) {
1810 mutex_lock(&d->vqs[i]->mutex);
1811 d->vqs[i]->log_ctx = d->log_ctx;
1812 mutex_unlock(&d->vqs[i]->mutex);
1815 eventfd_ctx_put(ctx);
1824 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1826 /* TODO: This is really inefficient. We need something like get_user()
1827 * (instruction directly accesses the data, with an exception table entry
1828 * returning -EFAULT). See Documentation/x86/exception-tables.rst.
1830 static int set_bit_to_user(int nr, void __user *addr)
1832 unsigned long log = (unsigned long)addr;
1835 int bit = nr + (log % PAGE_SIZE) * 8;
1838 r = get_user_pages_fast(log, 1, FOLL_WRITE, &page);
1842 base = kmap_atomic(page);
1844 kunmap_atomic(base);
1845 set_page_dirty_lock(page);
1850 static int log_write(void __user *log_base,
1851 u64 write_address, u64 write_length)
1853 u64 write_page = write_address / VHOST_PAGE_SIZE;
1858 write_length += write_address % VHOST_PAGE_SIZE;
1860 u64 base = (u64)(unsigned long)log_base;
1861 u64 log = base + write_page / 8;
1862 int bit = write_page % 8;
1863 if ((u64)(unsigned long)log != log)
1865 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1868 if (write_length <= VHOST_PAGE_SIZE)
1870 write_length -= VHOST_PAGE_SIZE;
1876 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1878 struct vhost_umem *umem = vq->umem;
1879 struct vhost_umem_node *u;
1880 u64 start, end, l, min;
1886 /* More than one GPAs can be mapped into a single HVA. So
1887 * iterate all possible umems here to be safe.
1889 list_for_each_entry(u, &umem->umem_list, link) {
1890 if (u->userspace_addr > hva - 1 + len ||
1891 u->userspace_addr - 1 + u->size < hva)
1893 start = max(u->userspace_addr, hva);
1894 end = min(u->userspace_addr - 1 + u->size,
1896 l = end - start + 1;
1897 r = log_write(vq->log_base,
1898 u->start + start - u->userspace_addr,
1916 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1918 struct iovec iov[64];
1922 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1924 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1925 len, iov, 64, VHOST_ACCESS_WO);
1929 for (i = 0; i < ret; i++) {
1930 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1939 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1940 unsigned int log_num, u64 len, struct iovec *iov, int count)
1944 /* Make sure data written is seen before log. */
1948 for (i = 0; i < count; i++) {
1949 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1957 for (i = 0; i < log_num; ++i) {
1958 u64 l = min(log[i].len, len);
1959 r = log_write(vq->log_base, log[i].addr, l);
1965 eventfd_signal(vq->log_ctx, 1);
1969 /* Length written exceeds what we have stored. This is a bug. */
1973 EXPORT_SYMBOL_GPL(vhost_log_write);
1975 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1978 if (vhost_put_used_flags(vq))
1980 if (unlikely(vq->log_used)) {
1981 /* Make sure the flag is seen before log. */
1983 /* Log used flag write. */
1984 used = &vq->used->flags;
1985 log_used(vq, (used - (void __user *)vq->used),
1986 sizeof vq->used->flags);
1988 eventfd_signal(vq->log_ctx, 1);
1993 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1995 if (vhost_put_avail_event(vq))
1997 if (unlikely(vq->log_used)) {
1999 /* Make sure the event is seen before log. */
2001 /* Log avail event write */
2002 used = vhost_avail_event(vq);
2003 log_used(vq, (used - (void __user *)vq->used),
2004 sizeof *vhost_avail_event(vq));
2006 eventfd_signal(vq->log_ctx, 1);
2011 int vhost_vq_init_access(struct vhost_virtqueue *vq)
2013 __virtio16 last_used_idx;
2015 bool is_le = vq->is_le;
2017 if (!vq->private_data)
2020 vhost_init_is_le(vq);
2022 r = vhost_update_used_flags(vq);
2025 vq->signalled_used_valid = false;
2027 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
2031 r = vhost_get_used_idx(vq, &last_used_idx);
2033 vq_err(vq, "Can't access used idx at %p\n",
2037 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2044 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2046 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2047 struct iovec iov[], int iov_size, int access)
2049 const struct vhost_umem_node *node;
2050 struct vhost_dev *dev = vq->dev;
2051 struct vhost_umem *umem = dev->iotlb ? dev->iotlb : dev->umem;
2053 u64 s = 0, last = addr + len - 1;
2056 while ((u64)len > s) {
2058 if (unlikely(ret >= iov_size)) {
2063 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
2065 if (node == NULL || node->start > addr) {
2066 if (umem != dev->iotlb) {
2072 } else if (!(node->perm & access)) {
2078 size = node->size - addr + node->start;
2079 _iov->iov_len = min((u64)len - s, size);
2080 _iov->iov_base = (void __user *)(unsigned long)
2081 (node->userspace_addr + addr - node->start);
2088 vhost_iotlb_miss(vq, addr, access);
2092 /* Each buffer in the virtqueues is actually a chain of descriptors. This
2093 * function returns the next descriptor in the chain,
2094 * or -1U if we're at the end. */
2095 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2099 /* If this descriptor says it doesn't chain, we're done. */
2100 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2103 /* Check they're not leading us off end of descriptors. */
2104 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2108 static int get_indirect(struct vhost_virtqueue *vq,
2109 struct iovec iov[], unsigned int iov_size,
2110 unsigned int *out_num, unsigned int *in_num,
2111 struct vhost_log *log, unsigned int *log_num,
2112 struct vring_desc *indirect)
2114 struct vring_desc desc;
2115 unsigned int i = 0, count, found = 0;
2116 u32 len = vhost32_to_cpu(vq, indirect->len);
2117 struct iov_iter from;
2121 if (unlikely(len % sizeof desc)) {
2122 vq_err(vq, "Invalid length in indirect descriptor: "
2123 "len 0x%llx not multiple of 0x%zx\n",
2124 (unsigned long long)len,
2129 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2130 UIO_MAXIOV, VHOST_ACCESS_RO);
2131 if (unlikely(ret < 0)) {
2133 vq_err(vq, "Translation failure %d in indirect.\n", ret);
2136 iov_iter_init(&from, READ, vq->indirect, ret, len);
2138 /* We will use the result as an address to read from, so most
2139 * architectures only need a compiler barrier here. */
2140 read_barrier_depends();
2142 count = len / sizeof desc;
2143 /* Buffers are chained via a 16 bit next field, so
2144 * we can have at most 2^16 of these. */
2145 if (unlikely(count > USHRT_MAX + 1)) {
2146 vq_err(vq, "Indirect buffer length too big: %d\n",
2152 unsigned iov_count = *in_num + *out_num;
2153 if (unlikely(++found > count)) {
2154 vq_err(vq, "Loop detected: last one at %u "
2155 "indirect size %u\n",
2159 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2160 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2161 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2164 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2165 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2166 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2170 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2171 access = VHOST_ACCESS_WO;
2173 access = VHOST_ACCESS_RO;
2175 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2176 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2177 iov_size - iov_count, access);
2178 if (unlikely(ret < 0)) {
2180 vq_err(vq, "Translation failure %d indirect idx %d\n",
2184 /* If this is an input descriptor, increment that count. */
2185 if (access == VHOST_ACCESS_WO) {
2187 if (unlikely(log && ret)) {
2188 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2189 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2193 /* If it's an output descriptor, they're all supposed
2194 * to come before any input descriptors. */
2195 if (unlikely(*in_num)) {
2196 vq_err(vq, "Indirect descriptor "
2197 "has out after in: idx %d\n", i);
2202 } while ((i = next_desc(vq, &desc)) != -1);
2206 /* This looks in the virtqueue and for the first available buffer, and converts
2207 * it to an iovec for convenient access. Since descriptors consist of some
2208 * number of output then some number of input descriptors, it's actually two
2209 * iovecs, but we pack them into one and note how many of each there were.
2211 * This function returns the descriptor number found, or vq->num (which is
2212 * never a valid descriptor number) if none was found. A negative code is
2213 * returned on error. */
2214 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2215 struct iovec iov[], unsigned int iov_size,
2216 unsigned int *out_num, unsigned int *in_num,
2217 struct vhost_log *log, unsigned int *log_num)
2219 struct vring_desc desc;
2220 unsigned int i, head, found = 0;
2222 __virtio16 avail_idx;
2223 __virtio16 ring_head;
2226 /* Check it isn't doing very strange things with descriptor numbers. */
2227 last_avail_idx = vq->last_avail_idx;
2229 if (vq->avail_idx == vq->last_avail_idx) {
2230 if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
2231 vq_err(vq, "Failed to access avail idx at %p\n",
2235 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2237 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2238 vq_err(vq, "Guest moved used index from %u to %u",
2239 last_avail_idx, vq->avail_idx);
2243 /* If there's nothing new since last we looked, return
2246 if (vq->avail_idx == last_avail_idx)
2249 /* Only get avail ring entries after they have been
2255 /* Grab the next descriptor number they're advertising, and increment
2256 * the index we've seen. */
2257 if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
2258 vq_err(vq, "Failed to read head: idx %d address %p\n",
2260 &vq->avail->ring[last_avail_idx % vq->num]);
2264 head = vhost16_to_cpu(vq, ring_head);
2266 /* If their number is silly, that's an error. */
2267 if (unlikely(head >= vq->num)) {
2268 vq_err(vq, "Guest says index %u > %u is available",
2273 /* When we start there are none of either input nor output. */
2274 *out_num = *in_num = 0;
2280 unsigned iov_count = *in_num + *out_num;
2281 if (unlikely(i >= vq->num)) {
2282 vq_err(vq, "Desc index is %u > %u, head = %u",
2286 if (unlikely(++found > vq->num)) {
2287 vq_err(vq, "Loop detected: last one at %u "
2288 "vq size %u head %u\n",
2292 ret = vhost_get_desc(vq, &desc, i);
2293 if (unlikely(ret)) {
2294 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2298 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2299 ret = get_indirect(vq, iov, iov_size,
2301 log, log_num, &desc);
2302 if (unlikely(ret < 0)) {
2304 vq_err(vq, "Failure detected "
2305 "in indirect descriptor at idx %d\n", i);
2311 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2312 access = VHOST_ACCESS_WO;
2314 access = VHOST_ACCESS_RO;
2315 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2316 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2317 iov_size - iov_count, access);
2318 if (unlikely(ret < 0)) {
2320 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2324 if (access == VHOST_ACCESS_WO) {
2325 /* If this is an input descriptor,
2326 * increment that count. */
2328 if (unlikely(log && ret)) {
2329 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2330 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2334 /* If it's an output descriptor, they're all supposed
2335 * to come before any input descriptors. */
2336 if (unlikely(*in_num)) {
2337 vq_err(vq, "Descriptor has out after in: "
2343 } while ((i = next_desc(vq, &desc)) != -1);
2345 /* On success, increment avail index. */
2346 vq->last_avail_idx++;
2348 /* Assume notifications from guest are disabled at this point,
2349 * if they aren't we would need to update avail_event index. */
2350 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2353 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2355 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2356 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2358 vq->last_avail_idx -= n;
2360 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2362 /* After we've used one of their buffers, we tell them about it. We'll then
2363 * want to notify the guest, using eventfd. */
2364 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2366 struct vring_used_elem heads = {
2367 cpu_to_vhost32(vq, head),
2368 cpu_to_vhost32(vq, len)
2371 return vhost_add_used_n(vq, &heads, 1);
2373 EXPORT_SYMBOL_GPL(vhost_add_used);
2375 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2376 struct vring_used_elem *heads,
2379 struct vring_used_elem __user *used;
2383 start = vq->last_used_idx & (vq->num - 1);
2384 used = vq->used->ring + start;
2385 if (vhost_put_used(vq, heads, start, count)) {
2386 vq_err(vq, "Failed to write used");
2389 if (unlikely(vq->log_used)) {
2390 /* Make sure data is seen before log. */
2392 /* Log used ring entry write. */
2393 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2394 count * sizeof *used);
2396 old = vq->last_used_idx;
2397 new = (vq->last_used_idx += count);
2398 /* If the driver never bothers to signal in a very long while,
2399 * used index might wrap around. If that happens, invalidate
2400 * signalled_used index we stored. TODO: make sure driver
2401 * signals at least once in 2^16 and remove this. */
2402 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2403 vq->signalled_used_valid = false;
2407 /* After we've used one of their buffers, we tell them about it. We'll then
2408 * want to notify the guest, using eventfd. */
2409 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2414 start = vq->last_used_idx & (vq->num - 1);
2415 n = vq->num - start;
2417 r = __vhost_add_used_n(vq, heads, n);
2423 r = __vhost_add_used_n(vq, heads, count);
2425 /* Make sure buffer is written before we update index. */
2427 if (vhost_put_used_idx(vq)) {
2428 vq_err(vq, "Failed to increment used idx");
2431 if (unlikely(vq->log_used)) {
2432 /* Make sure used idx is seen before log. */
2434 /* Log used index update. */
2435 log_used(vq, offsetof(struct vring_used, idx),
2436 sizeof vq->used->idx);
2438 eventfd_signal(vq->log_ctx, 1);
2442 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2444 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2449 /* Flush out used index updates. This is paired
2450 * with the barrier that the Guest executes when enabling
2454 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2455 unlikely(vq->avail_idx == vq->last_avail_idx))
2458 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2460 if (vhost_get_avail_flags(vq, &flags)) {
2461 vq_err(vq, "Failed to get flags");
2464 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2466 old = vq->signalled_used;
2467 v = vq->signalled_used_valid;
2468 new = vq->signalled_used = vq->last_used_idx;
2469 vq->signalled_used_valid = true;
2474 if (vhost_get_used_event(vq, &event)) {
2475 vq_err(vq, "Failed to get used event idx");
2478 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2481 /* This actually signals the guest, using eventfd. */
2482 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2484 /* Signal the Guest tell them we used something up. */
2485 if (vq->call_ctx && vhost_notify(dev, vq))
2486 eventfd_signal(vq->call_ctx, 1);
2488 EXPORT_SYMBOL_GPL(vhost_signal);
2490 /* And here's the combo meal deal. Supersize me! */
2491 void vhost_add_used_and_signal(struct vhost_dev *dev,
2492 struct vhost_virtqueue *vq,
2493 unsigned int head, int len)
2495 vhost_add_used(vq, head, len);
2496 vhost_signal(dev, vq);
2498 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2500 /* multi-buffer version of vhost_add_used_and_signal */
2501 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2502 struct vhost_virtqueue *vq,
2503 struct vring_used_elem *heads, unsigned count)
2505 vhost_add_used_n(vq, heads, count);
2506 vhost_signal(dev, vq);
2508 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2510 /* return true if we're sure that avaiable ring is empty */
2511 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2513 __virtio16 avail_idx;
2516 if (vq->avail_idx != vq->last_avail_idx)
2519 r = vhost_get_avail_idx(vq, &avail_idx);
2522 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2524 return vq->avail_idx == vq->last_avail_idx;
2526 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2528 /* OK, now we need to know about added descriptors. */
2529 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2531 __virtio16 avail_idx;
2534 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2536 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2537 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2538 r = vhost_update_used_flags(vq);
2540 vq_err(vq, "Failed to enable notification at %p: %d\n",
2541 &vq->used->flags, r);
2545 r = vhost_update_avail_event(vq, vq->avail_idx);
2547 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2548 vhost_avail_event(vq), r);
2552 /* They could have slipped one in as we were doing that: make
2553 * sure it's written, then check again. */
2555 r = vhost_get_avail_idx(vq, &avail_idx);
2557 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2558 &vq->avail->idx, r);
2562 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2564 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2566 /* We don't need to be notified again. */
2567 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2571 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2573 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2574 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2575 r = vhost_update_used_flags(vq);
2577 vq_err(vq, "Failed to enable notification at %p: %d\n",
2578 &vq->used->flags, r);
2581 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2583 /* Create a new message. */
2584 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2586 struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2590 /* Make sure all padding within the structure is initialized. */
2591 memset(&node->msg, 0, sizeof node->msg);
2593 node->msg.type = type;
2596 EXPORT_SYMBOL_GPL(vhost_new_msg);
2598 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2599 struct vhost_msg_node *node)
2601 spin_lock(&dev->iotlb_lock);
2602 list_add_tail(&node->node, head);
2603 spin_unlock(&dev->iotlb_lock);
2605 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2607 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2609 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2610 struct list_head *head)
2612 struct vhost_msg_node *node = NULL;
2614 spin_lock(&dev->iotlb_lock);
2615 if (!list_empty(head)) {
2616 node = list_first_entry(head, struct vhost_msg_node,
2618 list_del(&node->node);
2620 spin_unlock(&dev->iotlb_lock);
2624 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2627 static int __init vhost_init(void)
2632 static void __exit vhost_exit(void)
2636 module_init(vhost_init);
2637 module_exit(vhost_exit);
2639 MODULE_VERSION("0.0.1");
2640 MODULE_LICENSE("GPL v2");
2641 MODULE_AUTHOR("Michael S. Tsirkin");
2642 MODULE_DESCRIPTION("Host kernel accelerator for virtio");