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>
33 #include <linux/kcov.h>
37 static ushort max_mem_regions = 64;
38 module_param(max_mem_regions, ushort, 0444);
39 MODULE_PARM_DESC(max_mem_regions,
40 "Maximum number of memory regions in memory map. (default: 64)");
41 static int max_iotlb_entries = 2048;
42 module_param(max_iotlb_entries, int, 0444);
43 MODULE_PARM_DESC(max_iotlb_entries,
44 "Maximum number of iotlb entries. (default: 2048)");
47 VHOST_MEMORY_F_LOG = 0x1,
50 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
51 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
53 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
54 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
56 vq->user_be = !virtio_legacy_is_little_endian();
59 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
64 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
69 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
71 struct vhost_vring_state s;
76 if (copy_from_user(&s, argp, sizeof(s)))
79 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
80 s.num != VHOST_VRING_BIG_ENDIAN)
83 if (s.num == VHOST_VRING_BIG_ENDIAN)
84 vhost_enable_cross_endian_big(vq);
86 vhost_enable_cross_endian_little(vq);
91 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
94 struct vhost_vring_state s = {
99 if (copy_to_user(argp, &s, sizeof(s)))
105 static void vhost_init_is_le(struct vhost_virtqueue *vq)
107 /* Note for legacy virtio: user_be is initialized at reset time
108 * according to the host endianness. If userspace does not set an
109 * explicit endianness, the default behavior is native endian, as
110 * expected by legacy virtio.
112 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
115 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
119 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
124 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
130 static void vhost_init_is_le(struct vhost_virtqueue *vq)
132 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
133 || virtio_legacy_is_little_endian();
135 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
137 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
139 vhost_init_is_le(vq);
142 struct vhost_flush_struct {
143 struct vhost_work work;
144 struct completion wait_event;
147 static void vhost_flush_work(struct vhost_work *work)
149 struct vhost_flush_struct *s;
151 s = container_of(work, struct vhost_flush_struct, work);
152 complete(&s->wait_event);
155 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
158 struct vhost_poll *poll;
160 poll = container_of(pt, struct vhost_poll, table);
162 add_wait_queue(wqh, &poll->wait);
165 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
168 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
170 if (!(key_to_poll(key) & poll->mask))
173 vhost_poll_queue(poll);
177 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
179 clear_bit(VHOST_WORK_QUEUED, &work->flags);
182 EXPORT_SYMBOL_GPL(vhost_work_init);
184 /* Init poll structure */
185 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
186 __poll_t mask, struct vhost_dev *dev)
188 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
189 init_poll_funcptr(&poll->table, vhost_poll_func);
194 vhost_work_init(&poll->work, fn);
196 EXPORT_SYMBOL_GPL(vhost_poll_init);
198 /* Start polling a file. We add ourselves to file's wait queue. The caller must
199 * keep a reference to a file until after vhost_poll_stop is called. */
200 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
207 mask = vfs_poll(file, &poll->table);
209 vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
210 if (mask & EPOLLERR) {
211 vhost_poll_stop(poll);
217 EXPORT_SYMBOL_GPL(vhost_poll_start);
219 /* Stop polling a file. After this function returns, it becomes safe to drop the
220 * file reference. You must also flush afterwards. */
221 void vhost_poll_stop(struct vhost_poll *poll)
224 remove_wait_queue(poll->wqh, &poll->wait);
228 EXPORT_SYMBOL_GPL(vhost_poll_stop);
230 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
232 struct vhost_flush_struct flush;
235 init_completion(&flush.wait_event);
236 vhost_work_init(&flush.work, vhost_flush_work);
238 vhost_work_queue(dev, &flush.work);
239 wait_for_completion(&flush.wait_event);
242 EXPORT_SYMBOL_GPL(vhost_work_flush);
244 /* Flush any work that has been scheduled. When calling this, don't hold any
245 * locks that are also used by the callback. */
246 void vhost_poll_flush(struct vhost_poll *poll)
248 vhost_work_flush(poll->dev, &poll->work);
250 EXPORT_SYMBOL_GPL(vhost_poll_flush);
252 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
257 if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
258 /* We can only add the work to the list after we're
259 * sure it was not in the list.
260 * test_and_set_bit() implies a memory barrier.
262 llist_add(&work->node, &dev->work_list);
263 wake_up_process(dev->worker);
266 EXPORT_SYMBOL_GPL(vhost_work_queue);
268 /* A lockless hint for busy polling code to exit the loop */
269 bool vhost_has_work(struct vhost_dev *dev)
271 return !llist_empty(&dev->work_list);
273 EXPORT_SYMBOL_GPL(vhost_has_work);
275 void vhost_poll_queue(struct vhost_poll *poll)
277 vhost_work_queue(poll->dev, &poll->work);
279 EXPORT_SYMBOL_GPL(vhost_poll_queue);
281 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
285 for (j = 0; j < VHOST_NUM_ADDRS; j++)
286 vq->meta_iotlb[j] = NULL;
289 static void vhost_vq_meta_reset(struct vhost_dev *d)
293 for (i = 0; i < d->nvqs; ++i)
294 __vhost_vq_meta_reset(d->vqs[i]);
297 static void vhost_vq_reset(struct vhost_dev *dev,
298 struct vhost_virtqueue *vq)
304 vq->last_avail_idx = 0;
306 vq->last_used_idx = 0;
307 vq->signalled_used = 0;
308 vq->signalled_used_valid = false;
310 vq->log_used = false;
311 vq->log_addr = -1ull;
312 vq->private_data = NULL;
313 vq->acked_features = 0;
314 vq->acked_backend_features = 0;
316 vq->error_ctx = NULL;
320 vhost_reset_is_le(vq);
321 vhost_disable_cross_endian(vq);
322 vq->busyloop_timeout = 0;
325 __vhost_vq_meta_reset(vq);
328 static int vhost_worker(void *data)
330 struct vhost_dev *dev = data;
331 struct vhost_work *work, *work_next;
332 struct llist_node *node;
333 mm_segment_t oldfs = get_fs();
339 /* mb paired w/ kthread_stop */
340 set_current_state(TASK_INTERRUPTIBLE);
342 if (kthread_should_stop()) {
343 __set_current_state(TASK_RUNNING);
347 node = llist_del_all(&dev->work_list);
351 node = llist_reverse_order(node);
352 /* make sure flag is seen after deletion */
354 llist_for_each_entry_safe(work, work_next, node, node) {
355 clear_bit(VHOST_WORK_QUEUED, &work->flags);
356 __set_current_state(TASK_RUNNING);
357 kcov_remote_start_common(dev->kcov_handle);
369 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
379 /* Helper to allocate iovec buffers for all vqs. */
380 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
382 struct vhost_virtqueue *vq;
385 for (i = 0; i < dev->nvqs; ++i) {
387 vq->indirect = kmalloc_array(UIO_MAXIOV,
388 sizeof(*vq->indirect),
390 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
392 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
394 if (!vq->indirect || !vq->log || !vq->heads)
401 vhost_vq_free_iovecs(dev->vqs[i]);
405 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
409 for (i = 0; i < dev->nvqs; ++i)
410 vhost_vq_free_iovecs(dev->vqs[i]);
413 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
414 int pkts, int total_len)
416 struct vhost_dev *dev = vq->dev;
418 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
419 pkts >= dev->weight) {
420 vhost_poll_queue(&vq->poll);
426 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
428 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
431 size_t event __maybe_unused =
432 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
434 return sizeof(*vq->avail) +
435 sizeof(*vq->avail->ring) * num + event;
438 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
441 size_t event __maybe_unused =
442 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
444 return sizeof(*vq->used) +
445 sizeof(*vq->used->ring) * num + event;
448 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
451 return sizeof(*vq->desc) * num;
454 void vhost_dev_init(struct vhost_dev *dev,
455 struct vhost_virtqueue **vqs, int nvqs,
456 int iov_limit, int weight, int byte_weight,
457 int (*msg_handler)(struct vhost_dev *dev,
458 struct vhost_iotlb_msg *msg))
460 struct vhost_virtqueue *vq;
465 mutex_init(&dev->mutex);
471 dev->iov_limit = iov_limit;
472 dev->weight = weight;
473 dev->byte_weight = byte_weight;
474 dev->msg_handler = msg_handler;
475 init_llist_head(&dev->work_list);
476 init_waitqueue_head(&dev->wait);
477 INIT_LIST_HEAD(&dev->read_list);
478 INIT_LIST_HEAD(&dev->pending_list);
479 spin_lock_init(&dev->iotlb_lock);
482 for (i = 0; i < dev->nvqs; ++i) {
488 mutex_init(&vq->mutex);
489 vhost_vq_reset(dev, vq);
491 vhost_poll_init(&vq->poll, vq->handle_kick,
495 EXPORT_SYMBOL_GPL(vhost_dev_init);
497 /* Caller should have device mutex */
498 long vhost_dev_check_owner(struct vhost_dev *dev)
500 /* Are you the owner? If not, I don't think you mean to do that */
501 return dev->mm == current->mm ? 0 : -EPERM;
503 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
505 struct vhost_attach_cgroups_struct {
506 struct vhost_work work;
507 struct task_struct *owner;
511 static void vhost_attach_cgroups_work(struct vhost_work *work)
513 struct vhost_attach_cgroups_struct *s;
515 s = container_of(work, struct vhost_attach_cgroups_struct, work);
516 s->ret = cgroup_attach_task_all(s->owner, current);
519 static int vhost_attach_cgroups(struct vhost_dev *dev)
521 struct vhost_attach_cgroups_struct attach;
523 attach.owner = current;
524 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
525 vhost_work_queue(dev, &attach.work);
526 vhost_work_flush(dev, &attach.work);
530 /* Caller should have device mutex */
531 bool vhost_dev_has_owner(struct vhost_dev *dev)
535 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
537 /* Caller should have device mutex */
538 long vhost_dev_set_owner(struct vhost_dev *dev)
540 struct task_struct *worker;
543 /* Is there an owner already? */
544 if (vhost_dev_has_owner(dev)) {
549 /* No owner, become one */
550 dev->mm = get_task_mm(current);
551 dev->kcov_handle = kcov_common_handle();
552 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
553 if (IS_ERR(worker)) {
554 err = PTR_ERR(worker);
558 dev->worker = worker;
559 wake_up_process(worker); /* avoid contributing to loadavg */
561 err = vhost_attach_cgroups(dev);
565 err = vhost_dev_alloc_iovecs(dev);
571 kthread_stop(worker);
577 dev->kcov_handle = 0;
581 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
583 static struct vhost_iotlb *iotlb_alloc(void)
585 return vhost_iotlb_alloc(max_iotlb_entries,
586 VHOST_IOTLB_FLAG_RETIRE);
589 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void)
591 return iotlb_alloc();
593 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
595 /* Caller should have device mutex */
596 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem)
600 vhost_dev_cleanup(dev);
603 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
604 * VQs aren't running.
606 for (i = 0; i < dev->nvqs; ++i)
607 dev->vqs[i]->umem = umem;
609 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
611 void vhost_dev_stop(struct vhost_dev *dev)
615 for (i = 0; i < dev->nvqs; ++i) {
616 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
617 vhost_poll_stop(&dev->vqs[i]->poll);
618 vhost_poll_flush(&dev->vqs[i]->poll);
622 EXPORT_SYMBOL_GPL(vhost_dev_stop);
624 static void vhost_clear_msg(struct vhost_dev *dev)
626 struct vhost_msg_node *node, *n;
628 spin_lock(&dev->iotlb_lock);
630 list_for_each_entry_safe(node, n, &dev->read_list, node) {
631 list_del(&node->node);
635 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
636 list_del(&node->node);
640 spin_unlock(&dev->iotlb_lock);
643 void vhost_dev_cleanup(struct vhost_dev *dev)
647 for (i = 0; i < dev->nvqs; ++i) {
648 if (dev->vqs[i]->error_ctx)
649 eventfd_ctx_put(dev->vqs[i]->error_ctx);
650 if (dev->vqs[i]->kick)
651 fput(dev->vqs[i]->kick);
652 if (dev->vqs[i]->call_ctx)
653 eventfd_ctx_put(dev->vqs[i]->call_ctx);
654 vhost_vq_reset(dev, dev->vqs[i]);
656 vhost_dev_free_iovecs(dev);
658 eventfd_ctx_put(dev->log_ctx);
660 /* No one will access memory at this point */
661 vhost_iotlb_free(dev->umem);
663 vhost_iotlb_free(dev->iotlb);
665 vhost_clear_msg(dev);
666 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
667 WARN_ON(!llist_empty(&dev->work_list));
669 kthread_stop(dev->worker);
671 dev->kcov_handle = 0;
677 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
679 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
681 u64 a = addr / VHOST_PAGE_SIZE / 8;
683 /* Make sure 64 bit math will not overflow. */
684 if (a > ULONG_MAX - (unsigned long)log_base ||
685 a + (unsigned long)log_base > ULONG_MAX)
688 return access_ok(log_base + a,
689 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
692 static bool vhost_overflow(u64 uaddr, u64 size)
694 /* Make sure 64 bit math will not overflow. */
695 return uaddr > ULONG_MAX || size > ULONG_MAX || uaddr > ULONG_MAX - size;
698 /* Caller should have vq mutex and device mutex. */
699 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem,
702 struct vhost_iotlb_map *map;
707 list_for_each_entry(map, &umem->list, link) {
708 unsigned long a = map->addr;
710 if (vhost_overflow(map->addr, map->size))
714 if (!access_ok((void __user *)a, map->size))
716 else if (log_all && !log_access_ok(log_base,
724 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
725 u64 addr, unsigned int size,
728 const struct vhost_iotlb_map *map = vq->meta_iotlb[type];
733 return (void *)(uintptr_t)(map->addr + addr - map->start);
736 /* Can we switch to this memory table? */
737 /* Caller should have device mutex but not vq mutex */
738 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem,
743 for (i = 0; i < d->nvqs; ++i) {
747 mutex_lock(&d->vqs[i]->mutex);
748 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
749 /* If ring is inactive, will check when it's enabled. */
750 if (d->vqs[i]->private_data)
751 ok = vq_memory_access_ok(d->vqs[i]->log_base,
755 mutex_unlock(&d->vqs[i]->mutex);
762 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
763 struct iovec iov[], int iov_size, int access);
765 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
766 const void *from, unsigned size)
771 return __copy_to_user(to, from, size);
773 /* This function should be called after iotlb
774 * prefetch, which means we're sure that all vq
775 * could be access through iotlb. So -EAGAIN should
776 * not happen in this case.
779 void __user *uaddr = vhost_vq_meta_fetch(vq,
780 (u64)(uintptr_t)to, size,
784 return __copy_to_user(uaddr, from, size);
786 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
787 ARRAY_SIZE(vq->iotlb_iov),
791 iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
792 ret = copy_to_iter(from, size, &t);
800 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
801 void __user *from, unsigned size)
806 return __copy_from_user(to, from, size);
808 /* This function should be called after iotlb
809 * prefetch, which means we're sure that vq
810 * could be access through iotlb. So -EAGAIN should
811 * not happen in this case.
813 void __user *uaddr = vhost_vq_meta_fetch(vq,
814 (u64)(uintptr_t)from, size,
819 return __copy_from_user(to, uaddr, size);
821 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
822 ARRAY_SIZE(vq->iotlb_iov),
825 vq_err(vq, "IOTLB translation failure: uaddr "
826 "%p size 0x%llx\n", from,
827 (unsigned long long) size);
830 iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
831 ret = copy_from_iter(to, size, &f);
840 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
841 void __user *addr, unsigned int size,
846 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
847 ARRAY_SIZE(vq->iotlb_iov),
850 vq_err(vq, "IOTLB translation failure: uaddr "
851 "%p size 0x%llx\n", addr,
852 (unsigned long long) size);
856 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
857 vq_err(vq, "Non atomic userspace memory access: uaddr "
858 "%p size 0x%llx\n", addr,
859 (unsigned long long) size);
863 return vq->iotlb_iov[0].iov_base;
866 /* This function should be called after iotlb
867 * prefetch, which means we're sure that vq
868 * could be access through iotlb. So -EAGAIN should
869 * not happen in this case.
871 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
872 void *addr, unsigned int size,
875 void __user *uaddr = vhost_vq_meta_fetch(vq,
876 (u64)(uintptr_t)addr, size, type);
880 return __vhost_get_user_slow(vq, addr, size, type);
883 #define vhost_put_user(vq, x, ptr) \
887 ret = __put_user(x, ptr); \
889 __typeof__(ptr) to = \
890 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
891 sizeof(*ptr), VHOST_ADDR_USED); \
893 ret = __put_user(x, to); \
900 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
902 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
903 vhost_avail_event(vq));
906 static inline int vhost_put_used(struct vhost_virtqueue *vq,
907 struct vring_used_elem *head, int idx,
910 return vhost_copy_to_user(vq, vq->used->ring + idx, head,
911 count * sizeof(*head));
914 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
917 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
921 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
924 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
928 #define vhost_get_user(vq, x, ptr, type) \
932 ret = __get_user(x, ptr); \
934 __typeof__(ptr) from = \
935 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
939 ret = __get_user(x, from); \
946 #define vhost_get_avail(vq, x, ptr) \
947 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
949 #define vhost_get_used(vq, x, ptr) \
950 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
952 static void vhost_dev_lock_vqs(struct vhost_dev *d)
955 for (i = 0; i < d->nvqs; ++i)
956 mutex_lock_nested(&d->vqs[i]->mutex, i);
959 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
962 for (i = 0; i < d->nvqs; ++i)
963 mutex_unlock(&d->vqs[i]->mutex);
966 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
969 return vhost_get_avail(vq, *idx, &vq->avail->idx);
972 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
973 __virtio16 *head, int idx)
975 return vhost_get_avail(vq, *head,
976 &vq->avail->ring[idx & (vq->num - 1)]);
979 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
982 return vhost_get_avail(vq, *flags, &vq->avail->flags);
985 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
988 return vhost_get_avail(vq, *event, vhost_used_event(vq));
991 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
994 return vhost_get_used(vq, *idx, &vq->used->idx);
997 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
998 struct vring_desc *desc, int idx)
1000 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1003 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1004 struct vhost_iotlb_msg *msg)
1006 struct vhost_msg_node *node, *n;
1008 spin_lock(&d->iotlb_lock);
1010 list_for_each_entry_safe(node, n, &d->pending_list, node) {
1011 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1012 if (msg->iova <= vq_msg->iova &&
1013 msg->iova + msg->size - 1 >= vq_msg->iova &&
1014 vq_msg->type == VHOST_IOTLB_MISS) {
1015 vhost_poll_queue(&node->vq->poll);
1016 list_del(&node->node);
1021 spin_unlock(&d->iotlb_lock);
1024 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1026 unsigned long a = uaddr;
1028 /* Make sure 64 bit math will not overflow. */
1029 if (vhost_overflow(uaddr, size))
1032 if ((access & VHOST_ACCESS_RO) &&
1033 !access_ok((void __user *)a, size))
1035 if ((access & VHOST_ACCESS_WO) &&
1036 !access_ok((void __user *)a, size))
1041 static int vhost_process_iotlb_msg(struct vhost_dev *dev,
1042 struct vhost_iotlb_msg *msg)
1046 mutex_lock(&dev->mutex);
1047 vhost_dev_lock_vqs(dev);
1048 switch (msg->type) {
1049 case VHOST_IOTLB_UPDATE:
1054 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1058 vhost_vq_meta_reset(dev);
1059 if (vhost_iotlb_add_range(dev->iotlb, msg->iova,
1060 msg->iova + msg->size - 1,
1061 msg->uaddr, msg->perm)) {
1065 vhost_iotlb_notify_vq(dev, msg);
1067 case VHOST_IOTLB_INVALIDATE:
1072 vhost_vq_meta_reset(dev);
1073 vhost_iotlb_del_range(dev->iotlb, msg->iova,
1074 msg->iova + msg->size - 1);
1081 vhost_dev_unlock_vqs(dev);
1082 mutex_unlock(&dev->mutex);
1086 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1087 struct iov_iter *from)
1089 struct vhost_iotlb_msg msg;
1093 ret = copy_from_iter(&type, sizeof(type), from);
1094 if (ret != sizeof(type)) {
1100 case VHOST_IOTLB_MSG:
1101 /* There maybe a hole after type for V1 message type,
1104 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1106 case VHOST_IOTLB_MSG_V2:
1107 offset = sizeof(__u32);
1114 iov_iter_advance(from, offset);
1115 ret = copy_from_iter(&msg, sizeof(msg), from);
1116 if (ret != sizeof(msg)) {
1121 if (dev->msg_handler)
1122 ret = dev->msg_handler(dev, &msg);
1124 ret = vhost_process_iotlb_msg(dev, &msg);
1130 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1131 sizeof(struct vhost_msg_v2);
1135 EXPORT_SYMBOL(vhost_chr_write_iter);
1137 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1142 poll_wait(file, &dev->wait, wait);
1144 if (!list_empty(&dev->read_list))
1145 mask |= EPOLLIN | EPOLLRDNORM;
1149 EXPORT_SYMBOL(vhost_chr_poll);
1151 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1155 struct vhost_msg_node *node;
1157 unsigned size = sizeof(struct vhost_msg);
1159 if (iov_iter_count(to) < size)
1164 prepare_to_wait(&dev->wait, &wait,
1165 TASK_INTERRUPTIBLE);
1167 node = vhost_dequeue_msg(dev, &dev->read_list);
1174 if (signal_pending(current)) {
1187 finish_wait(&dev->wait, &wait);
1190 struct vhost_iotlb_msg *msg;
1191 void *start = &node->msg;
1193 switch (node->msg.type) {
1194 case VHOST_IOTLB_MSG:
1195 size = sizeof(node->msg);
1196 msg = &node->msg.iotlb;
1198 case VHOST_IOTLB_MSG_V2:
1199 size = sizeof(node->msg_v2);
1200 msg = &node->msg_v2.iotlb;
1207 ret = copy_to_iter(start, size, to);
1208 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1212 vhost_enqueue_msg(dev, &dev->pending_list, node);
1217 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1219 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1221 struct vhost_dev *dev = vq->dev;
1222 struct vhost_msg_node *node;
1223 struct vhost_iotlb_msg *msg;
1224 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1226 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1231 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1232 msg = &node->msg_v2.iotlb;
1234 msg = &node->msg.iotlb;
1237 msg->type = VHOST_IOTLB_MISS;
1241 vhost_enqueue_msg(dev, &dev->read_list, node);
1246 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1247 struct vring_desc __user *desc,
1248 struct vring_avail __user *avail,
1249 struct vring_used __user *used)
1252 return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1253 access_ok(avail, vhost_get_avail_size(vq, num)) &&
1254 access_ok(used, vhost_get_used_size(vq, num));
1257 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1258 const struct vhost_iotlb_map *map,
1261 int access = (type == VHOST_ADDR_USED) ?
1262 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1264 if (likely(map->perm & access))
1265 vq->meta_iotlb[type] = map;
1268 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1269 int access, u64 addr, u64 len, int type)
1271 const struct vhost_iotlb_map *map;
1272 struct vhost_iotlb *umem = vq->iotlb;
1273 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1275 if (vhost_vq_meta_fetch(vq, addr, len, type))
1279 map = vhost_iotlb_itree_first(umem, addr, last);
1280 if (map == NULL || map->start > addr) {
1281 vhost_iotlb_miss(vq, addr, access);
1283 } else if (!(map->perm & access)) {
1284 /* Report the possible access violation by
1285 * request another translation from userspace.
1290 size = map->size - addr + map->start;
1292 if (orig_addr == addr && size >= len)
1293 vhost_vq_meta_update(vq, map, type);
1302 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1304 unsigned int num = vq->num;
1309 return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc,
1310 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1311 iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail,
1312 vhost_get_avail_size(vq, num),
1313 VHOST_ADDR_AVAIL) &&
1314 iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used,
1315 vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1317 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1319 /* Can we log writes? */
1320 /* Caller should have device mutex but not vq mutex */
1321 bool vhost_log_access_ok(struct vhost_dev *dev)
1323 return memory_access_ok(dev, dev->umem, 1);
1325 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1327 /* Verify access for write logging. */
1328 /* Caller should have vq mutex and device mutex */
1329 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1330 void __user *log_base)
1332 return vq_memory_access_ok(log_base, vq->umem,
1333 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1334 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
1335 vhost_get_used_size(vq, vq->num)));
1338 /* Can we start vq? */
1339 /* Caller should have vq mutex and device mutex */
1340 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1342 if (!vq_log_access_ok(vq, vq->log_base))
1345 /* Access validation occurs at prefetch time with IOTLB */
1349 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1351 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1353 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1355 struct vhost_memory mem, *newmem;
1356 struct vhost_memory_region *region;
1357 struct vhost_iotlb *newumem, *oldumem;
1358 unsigned long size = offsetof(struct vhost_memory, regions);
1361 if (copy_from_user(&mem, m, size))
1365 if (mem.nregions > max_mem_regions)
1367 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1372 memcpy(newmem, &mem, size);
1373 if (copy_from_user(newmem->regions, m->regions,
1374 mem.nregions * sizeof *m->regions)) {
1379 newumem = iotlb_alloc();
1385 for (region = newmem->regions;
1386 region < newmem->regions + mem.nregions;
1388 if (vhost_iotlb_add_range(newumem,
1389 region->guest_phys_addr,
1390 region->guest_phys_addr +
1391 region->memory_size - 1,
1392 region->userspace_addr,
1397 if (!memory_access_ok(d, newumem, 0))
1403 /* All memory accesses are done under some VQ mutex. */
1404 for (i = 0; i < d->nvqs; ++i) {
1405 mutex_lock(&d->vqs[i]->mutex);
1406 d->vqs[i]->umem = newumem;
1407 mutex_unlock(&d->vqs[i]->mutex);
1411 vhost_iotlb_free(oldumem);
1415 vhost_iotlb_free(newumem);
1420 static long vhost_vring_set_num(struct vhost_dev *d,
1421 struct vhost_virtqueue *vq,
1424 struct vhost_vring_state s;
1426 /* Resizing ring with an active backend?
1427 * You don't want to do that. */
1428 if (vq->private_data)
1431 if (copy_from_user(&s, argp, sizeof s))
1434 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
1441 static long vhost_vring_set_addr(struct vhost_dev *d,
1442 struct vhost_virtqueue *vq,
1445 struct vhost_vring_addr a;
1447 if (copy_from_user(&a, argp, sizeof a))
1449 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
1452 /* For 32bit, verify that the top 32bits of the user
1453 data are set to zero. */
1454 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1455 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1456 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
1459 /* Make sure it's safe to cast pointers to vring types. */
1460 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1461 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1462 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1463 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1464 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
1467 /* We only verify access here if backend is configured.
1468 * If it is not, we don't as size might not have been setup.
1469 * We will verify when backend is configured. */
1470 if (vq->private_data) {
1471 if (!vq_access_ok(vq, vq->num,
1472 (void __user *)(unsigned long)a.desc_user_addr,
1473 (void __user *)(unsigned long)a.avail_user_addr,
1474 (void __user *)(unsigned long)a.used_user_addr))
1477 /* Also validate log access for used ring if enabled. */
1478 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
1479 !log_access_ok(vq->log_base, a.log_guest_addr,
1481 vq->num * sizeof *vq->used->ring))
1485 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1486 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1487 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1488 vq->log_addr = a.log_guest_addr;
1489 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1494 static long vhost_vring_set_num_addr(struct vhost_dev *d,
1495 struct vhost_virtqueue *vq,
1501 mutex_lock(&vq->mutex);
1504 case VHOST_SET_VRING_NUM:
1505 r = vhost_vring_set_num(d, vq, argp);
1507 case VHOST_SET_VRING_ADDR:
1508 r = vhost_vring_set_addr(d, vq, argp);
1514 mutex_unlock(&vq->mutex);
1518 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1520 struct file *eventfp, *filep = NULL;
1521 bool pollstart = false, pollstop = false;
1522 struct eventfd_ctx *ctx = NULL;
1523 u32 __user *idxp = argp;
1524 struct vhost_virtqueue *vq;
1525 struct vhost_vring_state s;
1526 struct vhost_vring_file f;
1530 r = get_user(idx, idxp);
1536 idx = array_index_nospec(idx, d->nvqs);
1539 if (ioctl == VHOST_SET_VRING_NUM ||
1540 ioctl == VHOST_SET_VRING_ADDR) {
1541 return vhost_vring_set_num_addr(d, vq, ioctl, argp);
1544 mutex_lock(&vq->mutex);
1547 case VHOST_SET_VRING_BASE:
1548 /* Moving base with an active backend?
1549 * You don't want to do that. */
1550 if (vq->private_data) {
1554 if (copy_from_user(&s, argp, sizeof s)) {
1558 if (s.num > 0xffff) {
1562 vq->last_avail_idx = s.num;
1563 /* Forget the cached index value. */
1564 vq->avail_idx = vq->last_avail_idx;
1566 case VHOST_GET_VRING_BASE:
1568 s.num = vq->last_avail_idx;
1569 if (copy_to_user(argp, &s, sizeof s))
1572 case VHOST_SET_VRING_KICK:
1573 if (copy_from_user(&f, argp, sizeof f)) {
1577 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1578 if (IS_ERR(eventfp)) {
1579 r = PTR_ERR(eventfp);
1582 if (eventfp != vq->kick) {
1583 pollstop = (filep = vq->kick) != NULL;
1584 pollstart = (vq->kick = eventfp) != NULL;
1588 case VHOST_SET_VRING_CALL:
1589 if (copy_from_user(&f, argp, sizeof f)) {
1593 ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1598 swap(ctx, vq->call_ctx);
1600 case VHOST_SET_VRING_ERR:
1601 if (copy_from_user(&f, argp, sizeof f)) {
1605 ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1610 swap(ctx, vq->error_ctx);
1612 case VHOST_SET_VRING_ENDIAN:
1613 r = vhost_set_vring_endian(vq, argp);
1615 case VHOST_GET_VRING_ENDIAN:
1616 r = vhost_get_vring_endian(vq, idx, argp);
1618 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1619 if (copy_from_user(&s, argp, sizeof(s))) {
1623 vq->busyloop_timeout = s.num;
1625 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1627 s.num = vq->busyloop_timeout;
1628 if (copy_to_user(argp, &s, sizeof(s)))
1635 if (pollstop && vq->handle_kick)
1636 vhost_poll_stop(&vq->poll);
1638 if (!IS_ERR_OR_NULL(ctx))
1639 eventfd_ctx_put(ctx);
1643 if (pollstart && vq->handle_kick)
1644 r = vhost_poll_start(&vq->poll, vq->kick);
1646 mutex_unlock(&vq->mutex);
1648 if (pollstop && vq->handle_kick)
1649 vhost_poll_flush(&vq->poll);
1652 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1654 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1656 struct vhost_iotlb *niotlb, *oiotlb;
1659 niotlb = iotlb_alloc();
1666 for (i = 0; i < d->nvqs; ++i) {
1667 struct vhost_virtqueue *vq = d->vqs[i];
1669 mutex_lock(&vq->mutex);
1671 __vhost_vq_meta_reset(vq);
1672 mutex_unlock(&vq->mutex);
1675 vhost_iotlb_free(oiotlb);
1679 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1681 /* Caller must have device mutex */
1682 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1684 struct eventfd_ctx *ctx;
1689 /* If you are not the owner, you can become one */
1690 if (ioctl == VHOST_SET_OWNER) {
1691 r = vhost_dev_set_owner(d);
1695 /* You must be the owner to do anything else */
1696 r = vhost_dev_check_owner(d);
1701 case VHOST_SET_MEM_TABLE:
1702 r = vhost_set_memory(d, argp);
1704 case VHOST_SET_LOG_BASE:
1705 if (copy_from_user(&p, argp, sizeof p)) {
1709 if ((u64)(unsigned long)p != p) {
1713 for (i = 0; i < d->nvqs; ++i) {
1714 struct vhost_virtqueue *vq;
1715 void __user *base = (void __user *)(unsigned long)p;
1717 mutex_lock(&vq->mutex);
1718 /* If ring is inactive, will check when it's enabled. */
1719 if (vq->private_data && !vq_log_access_ok(vq, base))
1722 vq->log_base = base;
1723 mutex_unlock(&vq->mutex);
1726 case VHOST_SET_LOG_FD:
1727 r = get_user(fd, (int __user *)argp);
1730 ctx = fd == -1 ? NULL : eventfd_ctx_fdget(fd);
1735 swap(ctx, d->log_ctx);
1736 for (i = 0; i < d->nvqs; ++i) {
1737 mutex_lock(&d->vqs[i]->mutex);
1738 d->vqs[i]->log_ctx = d->log_ctx;
1739 mutex_unlock(&d->vqs[i]->mutex);
1742 eventfd_ctx_put(ctx);
1751 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1753 /* TODO: This is really inefficient. We need something like get_user()
1754 * (instruction directly accesses the data, with an exception table entry
1755 * returning -EFAULT). See Documentation/x86/exception-tables.rst.
1757 static int set_bit_to_user(int nr, void __user *addr)
1759 unsigned long log = (unsigned long)addr;
1762 int bit = nr + (log % PAGE_SIZE) * 8;
1765 r = get_user_pages_fast(log, 1, FOLL_WRITE, &page);
1769 base = kmap_atomic(page);
1771 kunmap_atomic(base);
1772 set_page_dirty_lock(page);
1777 static int log_write(void __user *log_base,
1778 u64 write_address, u64 write_length)
1780 u64 write_page = write_address / VHOST_PAGE_SIZE;
1785 write_length += write_address % VHOST_PAGE_SIZE;
1787 u64 base = (u64)(unsigned long)log_base;
1788 u64 log = base + write_page / 8;
1789 int bit = write_page % 8;
1790 if ((u64)(unsigned long)log != log)
1792 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1795 if (write_length <= VHOST_PAGE_SIZE)
1797 write_length -= VHOST_PAGE_SIZE;
1803 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1805 struct vhost_iotlb *umem = vq->umem;
1806 struct vhost_iotlb_map *u;
1807 u64 start, end, l, min;
1813 /* More than one GPAs can be mapped into a single HVA. So
1814 * iterate all possible umems here to be safe.
1816 list_for_each_entry(u, &umem->list, link) {
1817 if (u->addr > hva - 1 + len ||
1818 u->addr - 1 + u->size < hva)
1820 start = max(u->addr, hva);
1821 end = min(u->addr - 1 + u->size, hva - 1 + len);
1822 l = end - start + 1;
1823 r = log_write(vq->log_base,
1824 u->start + start - u->addr,
1842 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1844 struct iovec iov[64];
1848 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1850 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1851 len, iov, 64, VHOST_ACCESS_WO);
1855 for (i = 0; i < ret; i++) {
1856 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1865 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1866 unsigned int log_num, u64 len, struct iovec *iov, int count)
1870 /* Make sure data written is seen before log. */
1874 for (i = 0; i < count; i++) {
1875 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1883 for (i = 0; i < log_num; ++i) {
1884 u64 l = min(log[i].len, len);
1885 r = log_write(vq->log_base, log[i].addr, l);
1891 eventfd_signal(vq->log_ctx, 1);
1895 /* Length written exceeds what we have stored. This is a bug. */
1899 EXPORT_SYMBOL_GPL(vhost_log_write);
1901 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1904 if (vhost_put_used_flags(vq))
1906 if (unlikely(vq->log_used)) {
1907 /* Make sure the flag is seen before log. */
1909 /* Log used flag write. */
1910 used = &vq->used->flags;
1911 log_used(vq, (used - (void __user *)vq->used),
1912 sizeof vq->used->flags);
1914 eventfd_signal(vq->log_ctx, 1);
1919 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1921 if (vhost_put_avail_event(vq))
1923 if (unlikely(vq->log_used)) {
1925 /* Make sure the event is seen before log. */
1927 /* Log avail event write */
1928 used = vhost_avail_event(vq);
1929 log_used(vq, (used - (void __user *)vq->used),
1930 sizeof *vhost_avail_event(vq));
1932 eventfd_signal(vq->log_ctx, 1);
1937 int vhost_vq_init_access(struct vhost_virtqueue *vq)
1939 __virtio16 last_used_idx;
1941 bool is_le = vq->is_le;
1943 if (!vq->private_data)
1946 vhost_init_is_le(vq);
1948 r = vhost_update_used_flags(vq);
1951 vq->signalled_used_valid = false;
1953 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
1957 r = vhost_get_used_idx(vq, &last_used_idx);
1959 vq_err(vq, "Can't access used idx at %p\n",
1963 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1970 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
1972 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1973 struct iovec iov[], int iov_size, int access)
1975 const struct vhost_iotlb_map *map;
1976 struct vhost_dev *dev = vq->dev;
1977 struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
1982 while ((u64)len > s) {
1984 if (unlikely(ret >= iov_size)) {
1989 map = vhost_iotlb_itree_first(umem, addr, addr + len - 1);
1990 if (map == NULL || map->start > addr) {
1991 if (umem != dev->iotlb) {
1997 } else if (!(map->perm & access)) {
2003 size = map->size - addr + map->start;
2004 _iov->iov_len = min((u64)len - s, size);
2005 _iov->iov_base = (void __user *)(unsigned long)
2006 (map->addr + addr - map->start);
2013 vhost_iotlb_miss(vq, addr, access);
2017 /* Each buffer in the virtqueues is actually a chain of descriptors. This
2018 * function returns the next descriptor in the chain,
2019 * or -1U if we're at the end. */
2020 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2024 /* If this descriptor says it doesn't chain, we're done. */
2025 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2028 /* Check they're not leading us off end of descriptors. */
2029 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2033 static int get_indirect(struct vhost_virtqueue *vq,
2034 struct iovec iov[], unsigned int iov_size,
2035 unsigned int *out_num, unsigned int *in_num,
2036 struct vhost_log *log, unsigned int *log_num,
2037 struct vring_desc *indirect)
2039 struct vring_desc desc;
2040 unsigned int i = 0, count, found = 0;
2041 u32 len = vhost32_to_cpu(vq, indirect->len);
2042 struct iov_iter from;
2046 if (unlikely(len % sizeof desc)) {
2047 vq_err(vq, "Invalid length in indirect descriptor: "
2048 "len 0x%llx not multiple of 0x%zx\n",
2049 (unsigned long long)len,
2054 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2055 UIO_MAXIOV, VHOST_ACCESS_RO);
2056 if (unlikely(ret < 0)) {
2058 vq_err(vq, "Translation failure %d in indirect.\n", ret);
2061 iov_iter_init(&from, READ, vq->indirect, ret, len);
2063 /* We will use the result as an address to read from, so most
2064 * architectures only need a compiler barrier here. */
2065 read_barrier_depends();
2067 count = len / sizeof desc;
2068 /* Buffers are chained via a 16 bit next field, so
2069 * we can have at most 2^16 of these. */
2070 if (unlikely(count > USHRT_MAX + 1)) {
2071 vq_err(vq, "Indirect buffer length too big: %d\n",
2077 unsigned iov_count = *in_num + *out_num;
2078 if (unlikely(++found > count)) {
2079 vq_err(vq, "Loop detected: last one at %u "
2080 "indirect size %u\n",
2084 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2085 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2086 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2089 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2090 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2091 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2095 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2096 access = VHOST_ACCESS_WO;
2098 access = VHOST_ACCESS_RO;
2100 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2101 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2102 iov_size - iov_count, access);
2103 if (unlikely(ret < 0)) {
2105 vq_err(vq, "Translation failure %d indirect idx %d\n",
2109 /* If this is an input descriptor, increment that count. */
2110 if (access == VHOST_ACCESS_WO) {
2112 if (unlikely(log && ret)) {
2113 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2114 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2118 /* If it's an output descriptor, they're all supposed
2119 * to come before any input descriptors. */
2120 if (unlikely(*in_num)) {
2121 vq_err(vq, "Indirect descriptor "
2122 "has out after in: idx %d\n", i);
2127 } while ((i = next_desc(vq, &desc)) != -1);
2131 /* This looks in the virtqueue and for the first available buffer, and converts
2132 * it to an iovec for convenient access. Since descriptors consist of some
2133 * number of output then some number of input descriptors, it's actually two
2134 * iovecs, but we pack them into one and note how many of each there were.
2136 * This function returns the descriptor number found, or vq->num (which is
2137 * never a valid descriptor number) if none was found. A negative code is
2138 * returned on error. */
2139 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2140 struct iovec iov[], unsigned int iov_size,
2141 unsigned int *out_num, unsigned int *in_num,
2142 struct vhost_log *log, unsigned int *log_num)
2144 struct vring_desc desc;
2145 unsigned int i, head, found = 0;
2147 __virtio16 avail_idx;
2148 __virtio16 ring_head;
2151 /* Check it isn't doing very strange things with descriptor numbers. */
2152 last_avail_idx = vq->last_avail_idx;
2154 if (vq->avail_idx == vq->last_avail_idx) {
2155 if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
2156 vq_err(vq, "Failed to access avail idx at %p\n",
2160 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2162 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2163 vq_err(vq, "Guest moved used index from %u to %u",
2164 last_avail_idx, vq->avail_idx);
2168 /* If there's nothing new since last we looked, return
2171 if (vq->avail_idx == last_avail_idx)
2174 /* Only get avail ring entries after they have been
2180 /* Grab the next descriptor number they're advertising, and increment
2181 * the index we've seen. */
2182 if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
2183 vq_err(vq, "Failed to read head: idx %d address %p\n",
2185 &vq->avail->ring[last_avail_idx % vq->num]);
2189 head = vhost16_to_cpu(vq, ring_head);
2191 /* If their number is silly, that's an error. */
2192 if (unlikely(head >= vq->num)) {
2193 vq_err(vq, "Guest says index %u > %u is available",
2198 /* When we start there are none of either input nor output. */
2199 *out_num = *in_num = 0;
2205 unsigned iov_count = *in_num + *out_num;
2206 if (unlikely(i >= vq->num)) {
2207 vq_err(vq, "Desc index is %u > %u, head = %u",
2211 if (unlikely(++found > vq->num)) {
2212 vq_err(vq, "Loop detected: last one at %u "
2213 "vq size %u head %u\n",
2217 ret = vhost_get_desc(vq, &desc, i);
2218 if (unlikely(ret)) {
2219 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2223 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2224 ret = get_indirect(vq, iov, iov_size,
2226 log, log_num, &desc);
2227 if (unlikely(ret < 0)) {
2229 vq_err(vq, "Failure detected "
2230 "in indirect descriptor at idx %d\n", i);
2236 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2237 access = VHOST_ACCESS_WO;
2239 access = VHOST_ACCESS_RO;
2240 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2241 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2242 iov_size - iov_count, access);
2243 if (unlikely(ret < 0)) {
2245 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2249 if (access == VHOST_ACCESS_WO) {
2250 /* If this is an input descriptor,
2251 * increment that count. */
2253 if (unlikely(log && ret)) {
2254 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2255 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2259 /* If it's an output descriptor, they're all supposed
2260 * to come before any input descriptors. */
2261 if (unlikely(*in_num)) {
2262 vq_err(vq, "Descriptor has out after in: "
2268 } while ((i = next_desc(vq, &desc)) != -1);
2270 /* On success, increment avail index. */
2271 vq->last_avail_idx++;
2273 /* Assume notifications from guest are disabled at this point,
2274 * if they aren't we would need to update avail_event index. */
2275 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2278 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2280 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2281 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2283 vq->last_avail_idx -= n;
2285 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2287 /* After we've used one of their buffers, we tell them about it. We'll then
2288 * want to notify the guest, using eventfd. */
2289 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2291 struct vring_used_elem heads = {
2292 cpu_to_vhost32(vq, head),
2293 cpu_to_vhost32(vq, len)
2296 return vhost_add_used_n(vq, &heads, 1);
2298 EXPORT_SYMBOL_GPL(vhost_add_used);
2300 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2301 struct vring_used_elem *heads,
2304 struct vring_used_elem __user *used;
2308 start = vq->last_used_idx & (vq->num - 1);
2309 used = vq->used->ring + start;
2310 if (vhost_put_used(vq, heads, start, count)) {
2311 vq_err(vq, "Failed to write used");
2314 if (unlikely(vq->log_used)) {
2315 /* Make sure data is seen before log. */
2317 /* Log used ring entry write. */
2318 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2319 count * sizeof *used);
2321 old = vq->last_used_idx;
2322 new = (vq->last_used_idx += count);
2323 /* If the driver never bothers to signal in a very long while,
2324 * used index might wrap around. If that happens, invalidate
2325 * signalled_used index we stored. TODO: make sure driver
2326 * signals at least once in 2^16 and remove this. */
2327 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2328 vq->signalled_used_valid = false;
2332 /* After we've used one of their buffers, we tell them about it. We'll then
2333 * want to notify the guest, using eventfd. */
2334 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2339 start = vq->last_used_idx & (vq->num - 1);
2340 n = vq->num - start;
2342 r = __vhost_add_used_n(vq, heads, n);
2348 r = __vhost_add_used_n(vq, heads, count);
2350 /* Make sure buffer is written before we update index. */
2352 if (vhost_put_used_idx(vq)) {
2353 vq_err(vq, "Failed to increment used idx");
2356 if (unlikely(vq->log_used)) {
2357 /* Make sure used idx is seen before log. */
2359 /* Log used index update. */
2360 log_used(vq, offsetof(struct vring_used, idx),
2361 sizeof vq->used->idx);
2363 eventfd_signal(vq->log_ctx, 1);
2367 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2369 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2374 /* Flush out used index updates. This is paired
2375 * with the barrier that the Guest executes when enabling
2379 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2380 unlikely(vq->avail_idx == vq->last_avail_idx))
2383 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2385 if (vhost_get_avail_flags(vq, &flags)) {
2386 vq_err(vq, "Failed to get flags");
2389 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2391 old = vq->signalled_used;
2392 v = vq->signalled_used_valid;
2393 new = vq->signalled_used = vq->last_used_idx;
2394 vq->signalled_used_valid = true;
2399 if (vhost_get_used_event(vq, &event)) {
2400 vq_err(vq, "Failed to get used event idx");
2403 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2406 /* This actually signals the guest, using eventfd. */
2407 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2409 /* Signal the Guest tell them we used something up. */
2410 if (vq->call_ctx && vhost_notify(dev, vq))
2411 eventfd_signal(vq->call_ctx, 1);
2413 EXPORT_SYMBOL_GPL(vhost_signal);
2415 /* And here's the combo meal deal. Supersize me! */
2416 void vhost_add_used_and_signal(struct vhost_dev *dev,
2417 struct vhost_virtqueue *vq,
2418 unsigned int head, int len)
2420 vhost_add_used(vq, head, len);
2421 vhost_signal(dev, vq);
2423 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2425 /* multi-buffer version of vhost_add_used_and_signal */
2426 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2427 struct vhost_virtqueue *vq,
2428 struct vring_used_elem *heads, unsigned count)
2430 vhost_add_used_n(vq, heads, count);
2431 vhost_signal(dev, vq);
2433 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2435 /* return true if we're sure that avaiable ring is empty */
2436 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2438 __virtio16 avail_idx;
2441 if (vq->avail_idx != vq->last_avail_idx)
2444 r = vhost_get_avail_idx(vq, &avail_idx);
2447 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2449 return vq->avail_idx == vq->last_avail_idx;
2451 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2453 /* OK, now we need to know about added descriptors. */
2454 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2456 __virtio16 avail_idx;
2459 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2461 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2462 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2463 r = vhost_update_used_flags(vq);
2465 vq_err(vq, "Failed to enable notification at %p: %d\n",
2466 &vq->used->flags, r);
2470 r = vhost_update_avail_event(vq, vq->avail_idx);
2472 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2473 vhost_avail_event(vq), r);
2477 /* They could have slipped one in as we were doing that: make
2478 * sure it's written, then check again. */
2480 r = vhost_get_avail_idx(vq, &avail_idx);
2482 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2483 &vq->avail->idx, r);
2487 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2489 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2491 /* We don't need to be notified again. */
2492 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2496 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2498 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2499 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2500 r = vhost_update_used_flags(vq);
2502 vq_err(vq, "Failed to enable notification at %p: %d\n",
2503 &vq->used->flags, r);
2506 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2508 /* Create a new message. */
2509 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2511 struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2515 /* Make sure all padding within the structure is initialized. */
2516 memset(&node->msg, 0, sizeof node->msg);
2518 node->msg.type = type;
2521 EXPORT_SYMBOL_GPL(vhost_new_msg);
2523 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2524 struct vhost_msg_node *node)
2526 spin_lock(&dev->iotlb_lock);
2527 list_add_tail(&node->node, head);
2528 spin_unlock(&dev->iotlb_lock);
2530 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2532 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2534 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2535 struct list_head *head)
2537 struct vhost_msg_node *node = NULL;
2539 spin_lock(&dev->iotlb_lock);
2540 if (!list_empty(head)) {
2541 node = list_first_entry(head, struct vhost_msg_node,
2543 list_del(&node->node);
2545 spin_unlock(&dev->iotlb_lock);
2549 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2552 static int __init vhost_init(void)
2557 static void __exit vhost_exit(void)
2561 module_init(vhost_init);
2562 module_exit(vhost_exit);
2564 MODULE_VERSION("0.0.1");
2565 MODULE_LICENSE("GPL v2");
2566 MODULE_AUTHOR("Michael S. Tsirkin");
2567 MODULE_DESCRIPTION("Host kernel accelerator for virtio");