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/miscdevice.h>
18 #include <linux/mutex.h>
19 #include <linux/poll.h>
20 #include <linux/file.h>
21 #include <linux/highmem.h>
22 #include <linux/slab.h>
23 #include <linux/vmalloc.h>
24 #include <linux/kthread.h>
25 #include <linux/cgroup.h>
26 #include <linux/module.h>
27 #include <linux/sort.h>
28 #include <linux/sched/mm.h>
29 #include <linux/sched/signal.h>
30 #include <linux/interval_tree_generic.h>
31 #include <linux/nospec.h>
32 #include <linux/kcov.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 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
53 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
55 vq->user_be = !virtio_legacy_is_little_endian();
58 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
63 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
68 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
70 struct vhost_vring_state s;
75 if (copy_from_user(&s, argp, sizeof(s)))
78 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
79 s.num != VHOST_VRING_BIG_ENDIAN)
82 if (s.num == VHOST_VRING_BIG_ENDIAN)
83 vhost_enable_cross_endian_big(vq);
85 vhost_enable_cross_endian_little(vq);
90 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
93 struct vhost_vring_state s = {
98 if (copy_to_user(argp, &s, sizeof(s)))
104 static void vhost_init_is_le(struct vhost_virtqueue *vq)
106 /* Note for legacy virtio: user_be is initialized at reset time
107 * according to the host endianness. If userspace does not set an
108 * explicit endianness, the default behavior is native endian, as
109 * expected by legacy virtio.
111 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
114 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
118 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
123 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
129 static void vhost_init_is_le(struct vhost_virtqueue *vq)
131 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
132 || virtio_legacy_is_little_endian();
134 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
136 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
138 vhost_init_is_le(vq);
141 struct vhost_flush_struct {
142 struct vhost_work work;
143 struct completion wait_event;
146 static void vhost_flush_work(struct vhost_work *work)
148 struct vhost_flush_struct *s;
150 s = container_of(work, struct vhost_flush_struct, work);
151 complete(&s->wait_event);
154 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
157 struct vhost_poll *poll;
159 poll = container_of(pt, struct vhost_poll, table);
161 add_wait_queue(wqh, &poll->wait);
164 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
167 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
168 struct vhost_work *work = &poll->work;
170 if (!(key_to_poll(key) & poll->mask))
173 if (!poll->dev->use_worker)
176 vhost_poll_queue(poll);
181 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
183 clear_bit(VHOST_WORK_QUEUED, &work->flags);
186 EXPORT_SYMBOL_GPL(vhost_work_init);
188 /* Init poll structure */
189 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
190 __poll_t mask, struct vhost_dev *dev)
192 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
193 init_poll_funcptr(&poll->table, vhost_poll_func);
198 vhost_work_init(&poll->work, fn);
200 EXPORT_SYMBOL_GPL(vhost_poll_init);
202 /* Start polling a file. We add ourselves to file's wait queue. The caller must
203 * keep a reference to a file until after vhost_poll_stop is called. */
204 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
211 mask = vfs_poll(file, &poll->table);
213 vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
214 if (mask & EPOLLERR) {
215 vhost_poll_stop(poll);
221 EXPORT_SYMBOL_GPL(vhost_poll_start);
223 /* Stop polling a file. After this function returns, it becomes safe to drop the
224 * file reference. You must also flush afterwards. */
225 void vhost_poll_stop(struct vhost_poll *poll)
228 remove_wait_queue(poll->wqh, &poll->wait);
232 EXPORT_SYMBOL_GPL(vhost_poll_stop);
234 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
236 struct vhost_flush_struct flush;
239 init_completion(&flush.wait_event);
240 vhost_work_init(&flush.work, vhost_flush_work);
242 vhost_work_queue(dev, &flush.work);
243 wait_for_completion(&flush.wait_event);
246 EXPORT_SYMBOL_GPL(vhost_work_flush);
248 /* Flush any work that has been scheduled. When calling this, don't hold any
249 * locks that are also used by the callback. */
250 void vhost_poll_flush(struct vhost_poll *poll)
252 vhost_work_flush(poll->dev, &poll->work);
254 EXPORT_SYMBOL_GPL(vhost_poll_flush);
256 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
261 if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
262 /* We can only add the work to the list after we're
263 * sure it was not in the list.
264 * test_and_set_bit() implies a memory barrier.
266 llist_add(&work->node, &dev->work_list);
267 wake_up_process(dev->worker);
270 EXPORT_SYMBOL_GPL(vhost_work_queue);
272 /* A lockless hint for busy polling code to exit the loop */
273 bool vhost_has_work(struct vhost_dev *dev)
275 return !llist_empty(&dev->work_list);
277 EXPORT_SYMBOL_GPL(vhost_has_work);
279 void vhost_poll_queue(struct vhost_poll *poll)
281 vhost_work_queue(poll->dev, &poll->work);
283 EXPORT_SYMBOL_GPL(vhost_poll_queue);
285 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
289 for (j = 0; j < VHOST_NUM_ADDRS; j++)
290 vq->meta_iotlb[j] = NULL;
293 static void vhost_vq_meta_reset(struct vhost_dev *d)
297 for (i = 0; i < d->nvqs; ++i)
298 __vhost_vq_meta_reset(d->vqs[i]);
301 static void vhost_vring_call_reset(struct vhost_vring_call *call_ctx)
303 call_ctx->ctx = NULL;
304 memset(&call_ctx->producer, 0x0, sizeof(struct irq_bypass_producer));
305 spin_lock_init(&call_ctx->ctx_lock);
308 static void vhost_vq_reset(struct vhost_dev *dev,
309 struct vhost_virtqueue *vq)
315 vq->last_avail_idx = 0;
317 vq->last_used_idx = 0;
318 vq->signalled_used = 0;
319 vq->signalled_used_valid = false;
321 vq->log_used = false;
322 vq->log_addr = -1ull;
323 vq->private_data = NULL;
324 vq->acked_features = 0;
325 vq->acked_backend_features = 0;
327 vq->error_ctx = NULL;
330 vhost_reset_is_le(vq);
331 vhost_disable_cross_endian(vq);
332 vq->busyloop_timeout = 0;
335 vhost_vring_call_reset(&vq->call_ctx);
336 __vhost_vq_meta_reset(vq);
339 static int vhost_worker(void *data)
341 struct vhost_dev *dev = data;
342 struct vhost_work *work, *work_next;
343 struct llist_node *node;
345 kthread_use_mm(dev->mm);
348 /* mb paired w/ kthread_stop */
349 set_current_state(TASK_INTERRUPTIBLE);
351 if (kthread_should_stop()) {
352 __set_current_state(TASK_RUNNING);
356 node = llist_del_all(&dev->work_list);
360 node = llist_reverse_order(node);
361 /* make sure flag is seen after deletion */
363 llist_for_each_entry_safe(work, work_next, node, node) {
364 clear_bit(VHOST_WORK_QUEUED, &work->flags);
365 __set_current_state(TASK_RUNNING);
366 kcov_remote_start_common(dev->kcov_handle);
373 kthread_unuse_mm(dev->mm);
377 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
387 /* Helper to allocate iovec buffers for all vqs. */
388 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
390 struct vhost_virtqueue *vq;
393 for (i = 0; i < dev->nvqs; ++i) {
395 vq->indirect = kmalloc_array(UIO_MAXIOV,
396 sizeof(*vq->indirect),
398 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
400 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
402 if (!vq->indirect || !vq->log || !vq->heads)
409 vhost_vq_free_iovecs(dev->vqs[i]);
413 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
417 for (i = 0; i < dev->nvqs; ++i)
418 vhost_vq_free_iovecs(dev->vqs[i]);
421 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
422 int pkts, int total_len)
424 struct vhost_dev *dev = vq->dev;
426 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
427 pkts >= dev->weight) {
428 vhost_poll_queue(&vq->poll);
434 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
436 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
439 size_t event __maybe_unused =
440 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
442 return sizeof(*vq->avail) +
443 sizeof(*vq->avail->ring) * num + event;
446 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
449 size_t event __maybe_unused =
450 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
452 return sizeof(*vq->used) +
453 sizeof(*vq->used->ring) * num + event;
456 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
459 return sizeof(*vq->desc) * num;
462 void vhost_dev_init(struct vhost_dev *dev,
463 struct vhost_virtqueue **vqs, int nvqs,
464 int iov_limit, int weight, int byte_weight,
466 int (*msg_handler)(struct vhost_dev *dev,
467 struct vhost_iotlb_msg *msg))
469 struct vhost_virtqueue *vq;
474 mutex_init(&dev->mutex);
480 dev->iov_limit = iov_limit;
481 dev->weight = weight;
482 dev->byte_weight = byte_weight;
483 dev->use_worker = use_worker;
484 dev->msg_handler = msg_handler;
485 init_llist_head(&dev->work_list);
486 init_waitqueue_head(&dev->wait);
487 INIT_LIST_HEAD(&dev->read_list);
488 INIT_LIST_HEAD(&dev->pending_list);
489 spin_lock_init(&dev->iotlb_lock);
492 for (i = 0; i < dev->nvqs; ++i) {
498 mutex_init(&vq->mutex);
499 vhost_vq_reset(dev, vq);
501 vhost_poll_init(&vq->poll, vq->handle_kick,
505 EXPORT_SYMBOL_GPL(vhost_dev_init);
507 /* Caller should have device mutex */
508 long vhost_dev_check_owner(struct vhost_dev *dev)
510 /* Are you the owner? If not, I don't think you mean to do that */
511 return dev->mm == current->mm ? 0 : -EPERM;
513 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
515 struct vhost_attach_cgroups_struct {
516 struct vhost_work work;
517 struct task_struct *owner;
521 static void vhost_attach_cgroups_work(struct vhost_work *work)
523 struct vhost_attach_cgroups_struct *s;
525 s = container_of(work, struct vhost_attach_cgroups_struct, work);
526 s->ret = cgroup_attach_task_all(s->owner, current);
529 static int vhost_attach_cgroups(struct vhost_dev *dev)
531 struct vhost_attach_cgroups_struct attach;
533 attach.owner = current;
534 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
535 vhost_work_queue(dev, &attach.work);
536 vhost_work_flush(dev, &attach.work);
540 /* Caller should have device mutex */
541 bool vhost_dev_has_owner(struct vhost_dev *dev)
545 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
547 static void vhost_attach_mm(struct vhost_dev *dev)
549 /* No owner, become one */
550 if (dev->use_worker) {
551 dev->mm = get_task_mm(current);
553 /* vDPA device does not use worker thead, so there's
554 * no need to hold the address space for mm. This help
555 * to avoid deadlock in the case of mmap() which may
556 * held the refcnt of the file and depends on release
557 * method to remove vma.
559 dev->mm = current->mm;
564 static void vhost_detach_mm(struct vhost_dev *dev)
577 /* Caller should have device mutex */
578 long vhost_dev_set_owner(struct vhost_dev *dev)
580 struct task_struct *worker;
583 /* Is there an owner already? */
584 if (vhost_dev_has_owner(dev)) {
589 vhost_attach_mm(dev);
591 dev->kcov_handle = kcov_common_handle();
592 if (dev->use_worker) {
593 worker = kthread_create(vhost_worker, dev,
594 "vhost-%d", current->pid);
595 if (IS_ERR(worker)) {
596 err = PTR_ERR(worker);
600 dev->worker = worker;
601 wake_up_process(worker); /* avoid contributing to loadavg */
603 err = vhost_attach_cgroups(dev);
608 err = vhost_dev_alloc_iovecs(dev);
615 kthread_stop(dev->worker);
619 vhost_detach_mm(dev);
620 dev->kcov_handle = 0;
624 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
626 static struct vhost_iotlb *iotlb_alloc(void)
628 return vhost_iotlb_alloc(max_iotlb_entries,
629 VHOST_IOTLB_FLAG_RETIRE);
632 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void)
634 return iotlb_alloc();
636 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
638 /* Caller should have device mutex */
639 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem)
643 vhost_dev_cleanup(dev);
646 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
647 * VQs aren't running.
649 for (i = 0; i < dev->nvqs; ++i)
650 dev->vqs[i]->umem = umem;
652 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
654 void vhost_dev_stop(struct vhost_dev *dev)
658 for (i = 0; i < dev->nvqs; ++i) {
659 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
660 vhost_poll_stop(&dev->vqs[i]->poll);
661 vhost_poll_flush(&dev->vqs[i]->poll);
665 EXPORT_SYMBOL_GPL(vhost_dev_stop);
667 static void vhost_clear_msg(struct vhost_dev *dev)
669 struct vhost_msg_node *node, *n;
671 spin_lock(&dev->iotlb_lock);
673 list_for_each_entry_safe(node, n, &dev->read_list, node) {
674 list_del(&node->node);
678 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
679 list_del(&node->node);
683 spin_unlock(&dev->iotlb_lock);
686 void vhost_dev_cleanup(struct vhost_dev *dev)
690 for (i = 0; i < dev->nvqs; ++i) {
691 if (dev->vqs[i]->error_ctx)
692 eventfd_ctx_put(dev->vqs[i]->error_ctx);
693 if (dev->vqs[i]->kick)
694 fput(dev->vqs[i]->kick);
695 if (dev->vqs[i]->call_ctx.ctx)
696 eventfd_ctx_put(dev->vqs[i]->call_ctx.ctx);
697 vhost_vq_reset(dev, dev->vqs[i]);
699 vhost_dev_free_iovecs(dev);
701 eventfd_ctx_put(dev->log_ctx);
703 /* No one will access memory at this point */
704 vhost_iotlb_free(dev->umem);
706 vhost_iotlb_free(dev->iotlb);
708 vhost_clear_msg(dev);
709 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
710 WARN_ON(!llist_empty(&dev->work_list));
712 kthread_stop(dev->worker);
714 dev->kcov_handle = 0;
716 vhost_detach_mm(dev);
718 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
720 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
722 u64 a = addr / VHOST_PAGE_SIZE / 8;
724 /* Make sure 64 bit math will not overflow. */
725 if (a > ULONG_MAX - (unsigned long)log_base ||
726 a + (unsigned long)log_base > ULONG_MAX)
729 return access_ok(log_base + a,
730 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
733 static bool vhost_overflow(u64 uaddr, u64 size)
735 /* Make sure 64 bit math will not overflow. */
736 return uaddr > ULONG_MAX || size > ULONG_MAX || uaddr > ULONG_MAX - size;
739 /* Caller should have vq mutex and device mutex. */
740 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem,
743 struct vhost_iotlb_map *map;
748 list_for_each_entry(map, &umem->list, link) {
749 unsigned long a = map->addr;
751 if (vhost_overflow(map->addr, map->size))
755 if (!access_ok((void __user *)a, map->size))
757 else if (log_all && !log_access_ok(log_base,
765 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
766 u64 addr, unsigned int size,
769 const struct vhost_iotlb_map *map = vq->meta_iotlb[type];
774 return (void __user *)(uintptr_t)(map->addr + addr - map->start);
777 /* Can we switch to this memory table? */
778 /* Caller should have device mutex but not vq mutex */
779 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem,
784 for (i = 0; i < d->nvqs; ++i) {
788 mutex_lock(&d->vqs[i]->mutex);
789 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
790 /* If ring is inactive, will check when it's enabled. */
791 if (d->vqs[i]->private_data)
792 ok = vq_memory_access_ok(d->vqs[i]->log_base,
796 mutex_unlock(&d->vqs[i]->mutex);
803 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
804 struct iovec iov[], int iov_size, int access);
806 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
807 const void *from, unsigned size)
812 return __copy_to_user(to, from, size);
814 /* This function should be called after iotlb
815 * prefetch, which means we're sure that all vq
816 * could be access through iotlb. So -EAGAIN should
817 * not happen in this case.
820 void __user *uaddr = vhost_vq_meta_fetch(vq,
821 (u64)(uintptr_t)to, size,
825 return __copy_to_user(uaddr, from, size);
827 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
828 ARRAY_SIZE(vq->iotlb_iov),
832 iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
833 ret = copy_to_iter(from, size, &t);
841 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
842 void __user *from, unsigned size)
847 return __copy_from_user(to, from, size);
849 /* This function should be called after iotlb
850 * prefetch, which means we're sure that vq
851 * could be access through iotlb. So -EAGAIN should
852 * not happen in this case.
854 void __user *uaddr = vhost_vq_meta_fetch(vq,
855 (u64)(uintptr_t)from, size,
860 return __copy_from_user(to, uaddr, size);
862 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
863 ARRAY_SIZE(vq->iotlb_iov),
866 vq_err(vq, "IOTLB translation failure: uaddr "
867 "%p size 0x%llx\n", from,
868 (unsigned long long) size);
871 iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
872 ret = copy_from_iter(to, size, &f);
881 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
882 void __user *addr, unsigned int size,
887 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
888 ARRAY_SIZE(vq->iotlb_iov),
891 vq_err(vq, "IOTLB translation failure: uaddr "
892 "%p size 0x%llx\n", addr,
893 (unsigned long long) size);
897 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
898 vq_err(vq, "Non atomic userspace memory access: uaddr "
899 "%p size 0x%llx\n", addr,
900 (unsigned long long) size);
904 return vq->iotlb_iov[0].iov_base;
907 /* This function should be called after iotlb
908 * prefetch, which means we're sure that vq
909 * could be access through iotlb. So -EAGAIN should
910 * not happen in this case.
912 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
913 void __user *addr, unsigned int size,
916 void __user *uaddr = vhost_vq_meta_fetch(vq,
917 (u64)(uintptr_t)addr, size, type);
921 return __vhost_get_user_slow(vq, addr, size, type);
924 #define vhost_put_user(vq, x, ptr) \
928 ret = __put_user(x, ptr); \
930 __typeof__(ptr) to = \
931 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
932 sizeof(*ptr), VHOST_ADDR_USED); \
934 ret = __put_user(x, to); \
941 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
943 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
944 vhost_avail_event(vq));
947 static inline int vhost_put_used(struct vhost_virtqueue *vq,
948 struct vring_used_elem *head, int idx,
951 return vhost_copy_to_user(vq, vq->used->ring + idx, head,
952 count * sizeof(*head));
955 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
958 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
962 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
965 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
969 #define vhost_get_user(vq, x, ptr, type) \
973 ret = __get_user(x, ptr); \
975 __typeof__(ptr) from = \
976 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
980 ret = __get_user(x, from); \
987 #define vhost_get_avail(vq, x, ptr) \
988 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
990 #define vhost_get_used(vq, x, ptr) \
991 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
993 static void vhost_dev_lock_vqs(struct vhost_dev *d)
996 for (i = 0; i < d->nvqs; ++i)
997 mutex_lock_nested(&d->vqs[i]->mutex, i);
1000 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
1003 for (i = 0; i < d->nvqs; ++i)
1004 mutex_unlock(&d->vqs[i]->mutex);
1007 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
1010 return vhost_get_avail(vq, *idx, &vq->avail->idx);
1013 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
1014 __virtio16 *head, int idx)
1016 return vhost_get_avail(vq, *head,
1017 &vq->avail->ring[idx & (vq->num - 1)]);
1020 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1023 return vhost_get_avail(vq, *flags, &vq->avail->flags);
1026 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1029 return vhost_get_avail(vq, *event, vhost_used_event(vq));
1032 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1035 return vhost_get_used(vq, *idx, &vq->used->idx);
1038 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1039 struct vring_desc *desc, int idx)
1041 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1044 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1045 struct vhost_iotlb_msg *msg)
1047 struct vhost_msg_node *node, *n;
1049 spin_lock(&d->iotlb_lock);
1051 list_for_each_entry_safe(node, n, &d->pending_list, node) {
1052 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1053 if (msg->iova <= vq_msg->iova &&
1054 msg->iova + msg->size - 1 >= vq_msg->iova &&
1055 vq_msg->type == VHOST_IOTLB_MISS) {
1056 vhost_poll_queue(&node->vq->poll);
1057 list_del(&node->node);
1062 spin_unlock(&d->iotlb_lock);
1065 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1067 unsigned long a = uaddr;
1069 /* Make sure 64 bit math will not overflow. */
1070 if (vhost_overflow(uaddr, size))
1073 if ((access & VHOST_ACCESS_RO) &&
1074 !access_ok((void __user *)a, size))
1076 if ((access & VHOST_ACCESS_WO) &&
1077 !access_ok((void __user *)a, size))
1082 static int vhost_process_iotlb_msg(struct vhost_dev *dev,
1083 struct vhost_iotlb_msg *msg)
1087 mutex_lock(&dev->mutex);
1088 vhost_dev_lock_vqs(dev);
1089 switch (msg->type) {
1090 case VHOST_IOTLB_UPDATE:
1095 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1099 vhost_vq_meta_reset(dev);
1100 if (vhost_iotlb_add_range(dev->iotlb, msg->iova,
1101 msg->iova + msg->size - 1,
1102 msg->uaddr, msg->perm)) {
1106 vhost_iotlb_notify_vq(dev, msg);
1108 case VHOST_IOTLB_INVALIDATE:
1113 vhost_vq_meta_reset(dev);
1114 vhost_iotlb_del_range(dev->iotlb, msg->iova,
1115 msg->iova + msg->size - 1);
1122 vhost_dev_unlock_vqs(dev);
1123 mutex_unlock(&dev->mutex);
1127 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1128 struct iov_iter *from)
1130 struct vhost_iotlb_msg msg;
1134 ret = copy_from_iter(&type, sizeof(type), from);
1135 if (ret != sizeof(type)) {
1141 case VHOST_IOTLB_MSG:
1142 /* There maybe a hole after type for V1 message type,
1145 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1147 case VHOST_IOTLB_MSG_V2:
1148 offset = sizeof(__u32);
1155 iov_iter_advance(from, offset);
1156 ret = copy_from_iter(&msg, sizeof(msg), from);
1157 if (ret != sizeof(msg)) {
1162 if (dev->msg_handler)
1163 ret = dev->msg_handler(dev, &msg);
1165 ret = vhost_process_iotlb_msg(dev, &msg);
1171 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1172 sizeof(struct vhost_msg_v2);
1176 EXPORT_SYMBOL(vhost_chr_write_iter);
1178 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1183 poll_wait(file, &dev->wait, wait);
1185 if (!list_empty(&dev->read_list))
1186 mask |= EPOLLIN | EPOLLRDNORM;
1190 EXPORT_SYMBOL(vhost_chr_poll);
1192 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1196 struct vhost_msg_node *node;
1198 unsigned size = sizeof(struct vhost_msg);
1200 if (iov_iter_count(to) < size)
1205 prepare_to_wait(&dev->wait, &wait,
1206 TASK_INTERRUPTIBLE);
1208 node = vhost_dequeue_msg(dev, &dev->read_list);
1215 if (signal_pending(current)) {
1228 finish_wait(&dev->wait, &wait);
1231 struct vhost_iotlb_msg *msg;
1232 void *start = &node->msg;
1234 switch (node->msg.type) {
1235 case VHOST_IOTLB_MSG:
1236 size = sizeof(node->msg);
1237 msg = &node->msg.iotlb;
1239 case VHOST_IOTLB_MSG_V2:
1240 size = sizeof(node->msg_v2);
1241 msg = &node->msg_v2.iotlb;
1248 ret = copy_to_iter(start, size, to);
1249 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1253 vhost_enqueue_msg(dev, &dev->pending_list, node);
1258 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1260 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1262 struct vhost_dev *dev = vq->dev;
1263 struct vhost_msg_node *node;
1264 struct vhost_iotlb_msg *msg;
1265 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1267 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1272 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1273 msg = &node->msg_v2.iotlb;
1275 msg = &node->msg.iotlb;
1278 msg->type = VHOST_IOTLB_MISS;
1282 vhost_enqueue_msg(dev, &dev->read_list, node);
1287 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1288 vring_desc_t __user *desc,
1289 vring_avail_t __user *avail,
1290 vring_used_t __user *used)
1293 /* If an IOTLB device is present, the vring addresses are
1294 * GIOVAs. Access validation occurs at prefetch time. */
1298 return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1299 access_ok(avail, vhost_get_avail_size(vq, num)) &&
1300 access_ok(used, vhost_get_used_size(vq, num));
1303 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1304 const struct vhost_iotlb_map *map,
1307 int access = (type == VHOST_ADDR_USED) ?
1308 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1310 if (likely(map->perm & access))
1311 vq->meta_iotlb[type] = map;
1314 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1315 int access, u64 addr, u64 len, int type)
1317 const struct vhost_iotlb_map *map;
1318 struct vhost_iotlb *umem = vq->iotlb;
1319 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1321 if (vhost_vq_meta_fetch(vq, addr, len, type))
1325 map = vhost_iotlb_itree_first(umem, addr, last);
1326 if (map == NULL || map->start > addr) {
1327 vhost_iotlb_miss(vq, addr, access);
1329 } else if (!(map->perm & access)) {
1330 /* Report the possible access violation by
1331 * request another translation from userspace.
1336 size = map->size - addr + map->start;
1338 if (orig_addr == addr && size >= len)
1339 vhost_vq_meta_update(vq, map, type);
1348 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1350 unsigned int num = vq->num;
1355 return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc,
1356 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1357 iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail,
1358 vhost_get_avail_size(vq, num),
1359 VHOST_ADDR_AVAIL) &&
1360 iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used,
1361 vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1363 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1365 /* Can we log writes? */
1366 /* Caller should have device mutex but not vq mutex */
1367 bool vhost_log_access_ok(struct vhost_dev *dev)
1369 return memory_access_ok(dev, dev->umem, 1);
1371 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1373 static bool vq_log_used_access_ok(struct vhost_virtqueue *vq,
1374 void __user *log_base,
1378 /* If an IOTLB device is present, log_addr is a GIOVA that
1379 * will never be logged by log_used(). */
1383 return !log_used || log_access_ok(log_base, log_addr,
1384 vhost_get_used_size(vq, vq->num));
1387 /* Verify access for write logging. */
1388 /* Caller should have vq mutex and device mutex */
1389 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1390 void __user *log_base)
1392 return vq_memory_access_ok(log_base, vq->umem,
1393 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1394 vq_log_used_access_ok(vq, log_base, vq->log_used, vq->log_addr);
1397 /* Can we start vq? */
1398 /* Caller should have vq mutex and device mutex */
1399 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1401 if (!vq_log_access_ok(vq, vq->log_base))
1404 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1406 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1408 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1410 struct vhost_memory mem, *newmem;
1411 struct vhost_memory_region *region;
1412 struct vhost_iotlb *newumem, *oldumem;
1413 unsigned long size = offsetof(struct vhost_memory, regions);
1416 if (copy_from_user(&mem, m, size))
1420 if (mem.nregions > max_mem_regions)
1422 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1427 memcpy(newmem, &mem, size);
1428 if (copy_from_user(newmem->regions, m->regions,
1429 flex_array_size(newmem, regions, mem.nregions))) {
1434 newumem = iotlb_alloc();
1440 for (region = newmem->regions;
1441 region < newmem->regions + mem.nregions;
1443 if (vhost_iotlb_add_range(newumem,
1444 region->guest_phys_addr,
1445 region->guest_phys_addr +
1446 region->memory_size - 1,
1447 region->userspace_addr,
1452 if (!memory_access_ok(d, newumem, 0))
1458 /* All memory accesses are done under some VQ mutex. */
1459 for (i = 0; i < d->nvqs; ++i) {
1460 mutex_lock(&d->vqs[i]->mutex);
1461 d->vqs[i]->umem = newumem;
1462 mutex_unlock(&d->vqs[i]->mutex);
1466 vhost_iotlb_free(oldumem);
1470 vhost_iotlb_free(newumem);
1475 static long vhost_vring_set_num(struct vhost_dev *d,
1476 struct vhost_virtqueue *vq,
1479 struct vhost_vring_state s;
1481 /* Resizing ring with an active backend?
1482 * You don't want to do that. */
1483 if (vq->private_data)
1486 if (copy_from_user(&s, argp, sizeof s))
1489 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
1496 static long vhost_vring_set_addr(struct vhost_dev *d,
1497 struct vhost_virtqueue *vq,
1500 struct vhost_vring_addr a;
1502 if (copy_from_user(&a, argp, sizeof a))
1504 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
1507 /* For 32bit, verify that the top 32bits of the user
1508 data are set to zero. */
1509 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1510 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1511 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
1514 /* Make sure it's safe to cast pointers to vring types. */
1515 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1516 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1517 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1518 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1519 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
1522 /* We only verify access here if backend is configured.
1523 * If it is not, we don't as size might not have been setup.
1524 * We will verify when backend is configured. */
1525 if (vq->private_data) {
1526 if (!vq_access_ok(vq, vq->num,
1527 (void __user *)(unsigned long)a.desc_user_addr,
1528 (void __user *)(unsigned long)a.avail_user_addr,
1529 (void __user *)(unsigned long)a.used_user_addr))
1532 /* Also validate log access for used ring if enabled. */
1533 if (!vq_log_used_access_ok(vq, vq->log_base,
1534 a.flags & (0x1 << VHOST_VRING_F_LOG),
1539 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1540 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1541 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1542 vq->log_addr = a.log_guest_addr;
1543 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1548 static long vhost_vring_set_num_addr(struct vhost_dev *d,
1549 struct vhost_virtqueue *vq,
1555 mutex_lock(&vq->mutex);
1558 case VHOST_SET_VRING_NUM:
1559 r = vhost_vring_set_num(d, vq, argp);
1561 case VHOST_SET_VRING_ADDR:
1562 r = vhost_vring_set_addr(d, vq, argp);
1568 mutex_unlock(&vq->mutex);
1572 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1574 struct file *eventfp, *filep = NULL;
1575 bool pollstart = false, pollstop = false;
1576 struct eventfd_ctx *ctx = NULL;
1577 u32 __user *idxp = argp;
1578 struct vhost_virtqueue *vq;
1579 struct vhost_vring_state s;
1580 struct vhost_vring_file f;
1584 r = get_user(idx, idxp);
1590 idx = array_index_nospec(idx, d->nvqs);
1593 if (ioctl == VHOST_SET_VRING_NUM ||
1594 ioctl == VHOST_SET_VRING_ADDR) {
1595 return vhost_vring_set_num_addr(d, vq, ioctl, argp);
1598 mutex_lock(&vq->mutex);
1601 case VHOST_SET_VRING_BASE:
1602 /* Moving base with an active backend?
1603 * You don't want to do that. */
1604 if (vq->private_data) {
1608 if (copy_from_user(&s, argp, sizeof s)) {
1612 if (s.num > 0xffff) {
1616 vq->last_avail_idx = s.num;
1617 /* Forget the cached index value. */
1618 vq->avail_idx = vq->last_avail_idx;
1620 case VHOST_GET_VRING_BASE:
1622 s.num = vq->last_avail_idx;
1623 if (copy_to_user(argp, &s, sizeof s))
1626 case VHOST_SET_VRING_KICK:
1627 if (copy_from_user(&f, argp, sizeof f)) {
1631 eventfp = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_fget(f.fd);
1632 if (IS_ERR(eventfp)) {
1633 r = PTR_ERR(eventfp);
1636 if (eventfp != vq->kick) {
1637 pollstop = (filep = vq->kick) != NULL;
1638 pollstart = (vq->kick = eventfp) != NULL;
1642 case VHOST_SET_VRING_CALL:
1643 if (copy_from_user(&f, argp, sizeof f)) {
1647 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
1653 spin_lock(&vq->call_ctx.ctx_lock);
1654 swap(ctx, vq->call_ctx.ctx);
1655 spin_unlock(&vq->call_ctx.ctx_lock);
1657 case VHOST_SET_VRING_ERR:
1658 if (copy_from_user(&f, argp, sizeof f)) {
1662 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
1667 swap(ctx, vq->error_ctx);
1669 case VHOST_SET_VRING_ENDIAN:
1670 r = vhost_set_vring_endian(vq, argp);
1672 case VHOST_GET_VRING_ENDIAN:
1673 r = vhost_get_vring_endian(vq, idx, argp);
1675 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1676 if (copy_from_user(&s, argp, sizeof(s))) {
1680 vq->busyloop_timeout = s.num;
1682 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1684 s.num = vq->busyloop_timeout;
1685 if (copy_to_user(argp, &s, sizeof(s)))
1692 if (pollstop && vq->handle_kick)
1693 vhost_poll_stop(&vq->poll);
1695 if (!IS_ERR_OR_NULL(ctx))
1696 eventfd_ctx_put(ctx);
1700 if (pollstart && vq->handle_kick)
1701 r = vhost_poll_start(&vq->poll, vq->kick);
1703 mutex_unlock(&vq->mutex);
1705 if (pollstop && vq->handle_kick)
1706 vhost_poll_flush(&vq->poll);
1709 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1711 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1713 struct vhost_iotlb *niotlb, *oiotlb;
1716 niotlb = iotlb_alloc();
1723 for (i = 0; i < d->nvqs; ++i) {
1724 struct vhost_virtqueue *vq = d->vqs[i];
1726 mutex_lock(&vq->mutex);
1728 __vhost_vq_meta_reset(vq);
1729 mutex_unlock(&vq->mutex);
1732 vhost_iotlb_free(oiotlb);
1736 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1738 /* Caller must have device mutex */
1739 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1741 struct eventfd_ctx *ctx;
1746 /* If you are not the owner, you can become one */
1747 if (ioctl == VHOST_SET_OWNER) {
1748 r = vhost_dev_set_owner(d);
1752 /* You must be the owner to do anything else */
1753 r = vhost_dev_check_owner(d);
1758 case VHOST_SET_MEM_TABLE:
1759 r = vhost_set_memory(d, argp);
1761 case VHOST_SET_LOG_BASE:
1762 if (copy_from_user(&p, argp, sizeof p)) {
1766 if ((u64)(unsigned long)p != p) {
1770 for (i = 0; i < d->nvqs; ++i) {
1771 struct vhost_virtqueue *vq;
1772 void __user *base = (void __user *)(unsigned long)p;
1774 mutex_lock(&vq->mutex);
1775 /* If ring is inactive, will check when it's enabled. */
1776 if (vq->private_data && !vq_log_access_ok(vq, base))
1779 vq->log_base = base;
1780 mutex_unlock(&vq->mutex);
1783 case VHOST_SET_LOG_FD:
1784 r = get_user(fd, (int __user *)argp);
1787 ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd);
1792 swap(ctx, d->log_ctx);
1793 for (i = 0; i < d->nvqs; ++i) {
1794 mutex_lock(&d->vqs[i]->mutex);
1795 d->vqs[i]->log_ctx = d->log_ctx;
1796 mutex_unlock(&d->vqs[i]->mutex);
1799 eventfd_ctx_put(ctx);
1808 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1810 /* TODO: This is really inefficient. We need something like get_user()
1811 * (instruction directly accesses the data, with an exception table entry
1812 * returning -EFAULT). See Documentation/x86/exception-tables.rst.
1814 static int set_bit_to_user(int nr, void __user *addr)
1816 unsigned long log = (unsigned long)addr;
1819 int bit = nr + (log % PAGE_SIZE) * 8;
1822 r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page);
1826 base = kmap_atomic(page);
1828 kunmap_atomic(base);
1829 unpin_user_pages_dirty_lock(&page, 1, true);
1833 static int log_write(void __user *log_base,
1834 u64 write_address, u64 write_length)
1836 u64 write_page = write_address / VHOST_PAGE_SIZE;
1841 write_length += write_address % VHOST_PAGE_SIZE;
1843 u64 base = (u64)(unsigned long)log_base;
1844 u64 log = base + write_page / 8;
1845 int bit = write_page % 8;
1846 if ((u64)(unsigned long)log != log)
1848 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1851 if (write_length <= VHOST_PAGE_SIZE)
1853 write_length -= VHOST_PAGE_SIZE;
1859 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1861 struct vhost_iotlb *umem = vq->umem;
1862 struct vhost_iotlb_map *u;
1863 u64 start, end, l, min;
1869 /* More than one GPAs can be mapped into a single HVA. So
1870 * iterate all possible umems here to be safe.
1872 list_for_each_entry(u, &umem->list, link) {
1873 if (u->addr > hva - 1 + len ||
1874 u->addr - 1 + u->size < hva)
1876 start = max(u->addr, hva);
1877 end = min(u->addr - 1 + u->size, hva - 1 + len);
1878 l = end - start + 1;
1879 r = log_write(vq->log_base,
1880 u->start + start - u->addr,
1898 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1900 struct iovec iov[64];
1904 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1906 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1907 len, iov, 64, VHOST_ACCESS_WO);
1911 for (i = 0; i < ret; i++) {
1912 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1921 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1922 unsigned int log_num, u64 len, struct iovec *iov, int count)
1926 /* Make sure data written is seen before log. */
1930 for (i = 0; i < count; i++) {
1931 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1939 for (i = 0; i < log_num; ++i) {
1940 u64 l = min(log[i].len, len);
1941 r = log_write(vq->log_base, log[i].addr, l);
1947 eventfd_signal(vq->log_ctx, 1);
1951 /* Length written exceeds what we have stored. This is a bug. */
1955 EXPORT_SYMBOL_GPL(vhost_log_write);
1957 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1960 if (vhost_put_used_flags(vq))
1962 if (unlikely(vq->log_used)) {
1963 /* Make sure the flag is seen before log. */
1965 /* Log used flag write. */
1966 used = &vq->used->flags;
1967 log_used(vq, (used - (void __user *)vq->used),
1968 sizeof vq->used->flags);
1970 eventfd_signal(vq->log_ctx, 1);
1975 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1977 if (vhost_put_avail_event(vq))
1979 if (unlikely(vq->log_used)) {
1981 /* Make sure the event is seen before log. */
1983 /* Log avail event write */
1984 used = vhost_avail_event(vq);
1985 log_used(vq, (used - (void __user *)vq->used),
1986 sizeof *vhost_avail_event(vq));
1988 eventfd_signal(vq->log_ctx, 1);
1993 int vhost_vq_init_access(struct vhost_virtqueue *vq)
1995 __virtio16 last_used_idx;
1997 bool is_le = vq->is_le;
1999 if (!vq->private_data)
2002 vhost_init_is_le(vq);
2004 r = vhost_update_used_flags(vq);
2007 vq->signalled_used_valid = false;
2009 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
2013 r = vhost_get_used_idx(vq, &last_used_idx);
2015 vq_err(vq, "Can't access used idx at %p\n",
2019 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2026 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2028 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2029 struct iovec iov[], int iov_size, int access)
2031 const struct vhost_iotlb_map *map;
2032 struct vhost_dev *dev = vq->dev;
2033 struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
2038 while ((u64)len > s) {
2040 if (unlikely(ret >= iov_size)) {
2045 map = vhost_iotlb_itree_first(umem, addr, addr + len - 1);
2046 if (map == NULL || map->start > addr) {
2047 if (umem != dev->iotlb) {
2053 } else if (!(map->perm & access)) {
2059 size = map->size - addr + map->start;
2060 _iov->iov_len = min((u64)len - s, size);
2061 _iov->iov_base = (void __user *)(unsigned long)
2062 (map->addr + addr - map->start);
2069 vhost_iotlb_miss(vq, addr, access);
2073 /* Each buffer in the virtqueues is actually a chain of descriptors. This
2074 * function returns the next descriptor in the chain,
2075 * or -1U if we're at the end. */
2076 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2080 /* If this descriptor says it doesn't chain, we're done. */
2081 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2084 /* Check they're not leading us off end of descriptors. */
2085 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2089 static int get_indirect(struct vhost_virtqueue *vq,
2090 struct iovec iov[], unsigned int iov_size,
2091 unsigned int *out_num, unsigned int *in_num,
2092 struct vhost_log *log, unsigned int *log_num,
2093 struct vring_desc *indirect)
2095 struct vring_desc desc;
2096 unsigned int i = 0, count, found = 0;
2097 u32 len = vhost32_to_cpu(vq, indirect->len);
2098 struct iov_iter from;
2102 if (unlikely(len % sizeof desc)) {
2103 vq_err(vq, "Invalid length in indirect descriptor: "
2104 "len 0x%llx not multiple of 0x%zx\n",
2105 (unsigned long long)len,
2110 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2111 UIO_MAXIOV, VHOST_ACCESS_RO);
2112 if (unlikely(ret < 0)) {
2114 vq_err(vq, "Translation failure %d in indirect.\n", ret);
2117 iov_iter_init(&from, READ, vq->indirect, ret, len);
2118 count = len / sizeof desc;
2119 /* Buffers are chained via a 16 bit next field, so
2120 * we can have at most 2^16 of these. */
2121 if (unlikely(count > USHRT_MAX + 1)) {
2122 vq_err(vq, "Indirect buffer length too big: %d\n",
2128 unsigned iov_count = *in_num + *out_num;
2129 if (unlikely(++found > count)) {
2130 vq_err(vq, "Loop detected: last one at %u "
2131 "indirect size %u\n",
2135 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2136 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2137 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2140 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2141 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2142 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2146 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2147 access = VHOST_ACCESS_WO;
2149 access = VHOST_ACCESS_RO;
2151 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2152 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2153 iov_size - iov_count, access);
2154 if (unlikely(ret < 0)) {
2156 vq_err(vq, "Translation failure %d indirect idx %d\n",
2160 /* If this is an input descriptor, increment that count. */
2161 if (access == VHOST_ACCESS_WO) {
2163 if (unlikely(log && ret)) {
2164 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2165 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2169 /* If it's an output descriptor, they're all supposed
2170 * to come before any input descriptors. */
2171 if (unlikely(*in_num)) {
2172 vq_err(vq, "Indirect descriptor "
2173 "has out after in: idx %d\n", i);
2178 } while ((i = next_desc(vq, &desc)) != -1);
2182 /* This looks in the virtqueue and for the first available buffer, and converts
2183 * it to an iovec for convenient access. Since descriptors consist of some
2184 * number of output then some number of input descriptors, it's actually two
2185 * iovecs, but we pack them into one and note how many of each there were.
2187 * This function returns the descriptor number found, or vq->num (which is
2188 * never a valid descriptor number) if none was found. A negative code is
2189 * returned on error. */
2190 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2191 struct iovec iov[], unsigned int iov_size,
2192 unsigned int *out_num, unsigned int *in_num,
2193 struct vhost_log *log, unsigned int *log_num)
2195 struct vring_desc desc;
2196 unsigned int i, head, found = 0;
2198 __virtio16 avail_idx;
2199 __virtio16 ring_head;
2202 /* Check it isn't doing very strange things with descriptor numbers. */
2203 last_avail_idx = vq->last_avail_idx;
2205 if (vq->avail_idx == vq->last_avail_idx) {
2206 if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
2207 vq_err(vq, "Failed to access avail idx at %p\n",
2211 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2213 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2214 vq_err(vq, "Guest moved used index from %u to %u",
2215 last_avail_idx, vq->avail_idx);
2219 /* If there's nothing new since last we looked, return
2222 if (vq->avail_idx == last_avail_idx)
2225 /* Only get avail ring entries after they have been
2231 /* Grab the next descriptor number they're advertising, and increment
2232 * the index we've seen. */
2233 if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
2234 vq_err(vq, "Failed to read head: idx %d address %p\n",
2236 &vq->avail->ring[last_avail_idx % vq->num]);
2240 head = vhost16_to_cpu(vq, ring_head);
2242 /* If their number is silly, that's an error. */
2243 if (unlikely(head >= vq->num)) {
2244 vq_err(vq, "Guest says index %u > %u is available",
2249 /* When we start there are none of either input nor output. */
2250 *out_num = *in_num = 0;
2256 unsigned iov_count = *in_num + *out_num;
2257 if (unlikely(i >= vq->num)) {
2258 vq_err(vq, "Desc index is %u > %u, head = %u",
2262 if (unlikely(++found > vq->num)) {
2263 vq_err(vq, "Loop detected: last one at %u "
2264 "vq size %u head %u\n",
2268 ret = vhost_get_desc(vq, &desc, i);
2269 if (unlikely(ret)) {
2270 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2274 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2275 ret = get_indirect(vq, iov, iov_size,
2277 log, log_num, &desc);
2278 if (unlikely(ret < 0)) {
2280 vq_err(vq, "Failure detected "
2281 "in indirect descriptor at idx %d\n", i);
2287 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2288 access = VHOST_ACCESS_WO;
2290 access = VHOST_ACCESS_RO;
2291 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2292 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2293 iov_size - iov_count, access);
2294 if (unlikely(ret < 0)) {
2296 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2300 if (access == VHOST_ACCESS_WO) {
2301 /* If this is an input descriptor,
2302 * increment that count. */
2304 if (unlikely(log && ret)) {
2305 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2306 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2310 /* If it's an output descriptor, they're all supposed
2311 * to come before any input descriptors. */
2312 if (unlikely(*in_num)) {
2313 vq_err(vq, "Descriptor has out after in: "
2319 } while ((i = next_desc(vq, &desc)) != -1);
2321 /* On success, increment avail index. */
2322 vq->last_avail_idx++;
2324 /* Assume notifications from guest are disabled at this point,
2325 * if they aren't we would need to update avail_event index. */
2326 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2329 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2331 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2332 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2334 vq->last_avail_idx -= n;
2336 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2338 /* After we've used one of their buffers, we tell them about it. We'll then
2339 * want to notify the guest, using eventfd. */
2340 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2342 struct vring_used_elem heads = {
2343 cpu_to_vhost32(vq, head),
2344 cpu_to_vhost32(vq, len)
2347 return vhost_add_used_n(vq, &heads, 1);
2349 EXPORT_SYMBOL_GPL(vhost_add_used);
2351 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2352 struct vring_used_elem *heads,
2355 vring_used_elem_t __user *used;
2359 start = vq->last_used_idx & (vq->num - 1);
2360 used = vq->used->ring + start;
2361 if (vhost_put_used(vq, heads, start, count)) {
2362 vq_err(vq, "Failed to write used");
2365 if (unlikely(vq->log_used)) {
2366 /* Make sure data is seen before log. */
2368 /* Log used ring entry write. */
2369 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2370 count * sizeof *used);
2372 old = vq->last_used_idx;
2373 new = (vq->last_used_idx += count);
2374 /* If the driver never bothers to signal in a very long while,
2375 * used index might wrap around. If that happens, invalidate
2376 * signalled_used index we stored. TODO: make sure driver
2377 * signals at least once in 2^16 and remove this. */
2378 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2379 vq->signalled_used_valid = false;
2383 /* After we've used one of their buffers, we tell them about it. We'll then
2384 * want to notify the guest, using eventfd. */
2385 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2390 start = vq->last_used_idx & (vq->num - 1);
2391 n = vq->num - start;
2393 r = __vhost_add_used_n(vq, heads, n);
2399 r = __vhost_add_used_n(vq, heads, count);
2401 /* Make sure buffer is written before we update index. */
2403 if (vhost_put_used_idx(vq)) {
2404 vq_err(vq, "Failed to increment used idx");
2407 if (unlikely(vq->log_used)) {
2408 /* Make sure used idx is seen before log. */
2410 /* Log used index update. */
2411 log_used(vq, offsetof(struct vring_used, idx),
2412 sizeof vq->used->idx);
2414 eventfd_signal(vq->log_ctx, 1);
2418 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2420 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2425 /* Flush out used index updates. This is paired
2426 * with the barrier that the Guest executes when enabling
2430 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2431 unlikely(vq->avail_idx == vq->last_avail_idx))
2434 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2436 if (vhost_get_avail_flags(vq, &flags)) {
2437 vq_err(vq, "Failed to get flags");
2440 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2442 old = vq->signalled_used;
2443 v = vq->signalled_used_valid;
2444 new = vq->signalled_used = vq->last_used_idx;
2445 vq->signalled_used_valid = true;
2450 if (vhost_get_used_event(vq, &event)) {
2451 vq_err(vq, "Failed to get used event idx");
2454 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2457 /* This actually signals the guest, using eventfd. */
2458 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2460 /* Signal the Guest tell them we used something up. */
2461 if (vq->call_ctx.ctx && vhost_notify(dev, vq))
2462 eventfd_signal(vq->call_ctx.ctx, 1);
2464 EXPORT_SYMBOL_GPL(vhost_signal);
2466 /* And here's the combo meal deal. Supersize me! */
2467 void vhost_add_used_and_signal(struct vhost_dev *dev,
2468 struct vhost_virtqueue *vq,
2469 unsigned int head, int len)
2471 vhost_add_used(vq, head, len);
2472 vhost_signal(dev, vq);
2474 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2476 /* multi-buffer version of vhost_add_used_and_signal */
2477 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2478 struct vhost_virtqueue *vq,
2479 struct vring_used_elem *heads, unsigned count)
2481 vhost_add_used_n(vq, heads, count);
2482 vhost_signal(dev, vq);
2484 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2486 /* return true if we're sure that avaiable ring is empty */
2487 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2489 __virtio16 avail_idx;
2492 if (vq->avail_idx != vq->last_avail_idx)
2495 r = vhost_get_avail_idx(vq, &avail_idx);
2498 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2500 return vq->avail_idx == vq->last_avail_idx;
2502 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2504 /* OK, now we need to know about added descriptors. */
2505 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2507 __virtio16 avail_idx;
2510 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2512 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2513 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2514 r = vhost_update_used_flags(vq);
2516 vq_err(vq, "Failed to enable notification at %p: %d\n",
2517 &vq->used->flags, r);
2521 r = vhost_update_avail_event(vq, vq->avail_idx);
2523 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2524 vhost_avail_event(vq), r);
2528 /* They could have slipped one in as we were doing that: make
2529 * sure it's written, then check again. */
2531 r = vhost_get_avail_idx(vq, &avail_idx);
2533 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2534 &vq->avail->idx, r);
2538 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2540 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2542 /* We don't need to be notified again. */
2543 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2547 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2549 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2550 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2551 r = vhost_update_used_flags(vq);
2553 vq_err(vq, "Failed to disable notification at %p: %d\n",
2554 &vq->used->flags, r);
2557 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2559 /* Create a new message. */
2560 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2562 struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2566 /* Make sure all padding within the structure is initialized. */
2567 memset(&node->msg, 0, sizeof node->msg);
2569 node->msg.type = type;
2572 EXPORT_SYMBOL_GPL(vhost_new_msg);
2574 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2575 struct vhost_msg_node *node)
2577 spin_lock(&dev->iotlb_lock);
2578 list_add_tail(&node->node, head);
2579 spin_unlock(&dev->iotlb_lock);
2581 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2583 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2585 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2586 struct list_head *head)
2588 struct vhost_msg_node *node = NULL;
2590 spin_lock(&dev->iotlb_lock);
2591 if (!list_empty(head)) {
2592 node = list_first_entry(head, struct vhost_msg_node,
2594 list_del(&node->node);
2596 spin_unlock(&dev->iotlb_lock);
2600 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2602 void vhost_set_backend_features(struct vhost_dev *dev, u64 features)
2604 struct vhost_virtqueue *vq;
2607 mutex_lock(&dev->mutex);
2608 for (i = 0; i < dev->nvqs; ++i) {
2610 mutex_lock(&vq->mutex);
2611 vq->acked_backend_features = features;
2612 mutex_unlock(&vq->mutex);
2614 mutex_unlock(&dev->mutex);
2616 EXPORT_SYMBOL_GPL(vhost_set_backend_features);
2618 static int __init vhost_init(void)
2623 static void __exit vhost_exit(void)
2627 module_init(vhost_init);
2628 module_exit(vhost_exit);
2630 MODULE_VERSION("0.0.1");
2631 MODULE_LICENSE("GPL v2");
2632 MODULE_AUTHOR("Michael S. Tsirkin");
2633 MODULE_DESCRIPTION("Host kernel accelerator for virtio");