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_vq_reset(struct vhost_dev *dev,
302 struct vhost_virtqueue *vq)
308 vq->last_avail_idx = 0;
310 vq->last_used_idx = 0;
311 vq->signalled_used = 0;
312 vq->signalled_used_valid = false;
314 vq->log_used = false;
315 vq->log_addr = -1ull;
316 vq->private_data = NULL;
317 vq->acked_features = 0;
318 vq->acked_backend_features = 0;
320 vq->error_ctx = NULL;
324 vhost_reset_is_le(vq);
325 vhost_disable_cross_endian(vq);
326 vq->busyloop_timeout = 0;
329 __vhost_vq_meta_reset(vq);
332 static int vhost_worker(void *data)
334 struct vhost_dev *dev = data;
335 struct vhost_work *work, *work_next;
336 struct llist_node *node;
338 kthread_use_mm(dev->mm);
341 /* mb paired w/ kthread_stop */
342 set_current_state(TASK_INTERRUPTIBLE);
344 if (kthread_should_stop()) {
345 __set_current_state(TASK_RUNNING);
349 node = llist_del_all(&dev->work_list);
353 node = llist_reverse_order(node);
354 /* make sure flag is seen after deletion */
356 llist_for_each_entry_safe(work, work_next, node, node) {
357 clear_bit(VHOST_WORK_QUEUED, &work->flags);
358 __set_current_state(TASK_RUNNING);
359 kcov_remote_start_common(dev->kcov_handle);
366 kthread_unuse_mm(dev->mm);
370 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
380 /* Helper to allocate iovec buffers for all vqs. */
381 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
383 struct vhost_virtqueue *vq;
386 for (i = 0; i < dev->nvqs; ++i) {
388 vq->indirect = kmalloc_array(UIO_MAXIOV,
389 sizeof(*vq->indirect),
391 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
393 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
395 if (!vq->indirect || !vq->log || !vq->heads)
402 vhost_vq_free_iovecs(dev->vqs[i]);
406 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
410 for (i = 0; i < dev->nvqs; ++i)
411 vhost_vq_free_iovecs(dev->vqs[i]);
414 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
415 int pkts, int total_len)
417 struct vhost_dev *dev = vq->dev;
419 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
420 pkts >= dev->weight) {
421 vhost_poll_queue(&vq->poll);
427 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
429 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
432 size_t event __maybe_unused =
433 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
435 return sizeof(*vq->avail) +
436 sizeof(*vq->avail->ring) * num + event;
439 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
442 size_t event __maybe_unused =
443 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
445 return sizeof(*vq->used) +
446 sizeof(*vq->used->ring) * num + event;
449 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
452 return sizeof(*vq->desc) * num;
455 void vhost_dev_init(struct vhost_dev *dev,
456 struct vhost_virtqueue **vqs, int nvqs,
457 int iov_limit, int weight, int byte_weight,
459 int (*msg_handler)(struct vhost_dev *dev,
460 struct vhost_iotlb_msg *msg))
462 struct vhost_virtqueue *vq;
467 mutex_init(&dev->mutex);
473 dev->iov_limit = iov_limit;
474 dev->weight = weight;
475 dev->byte_weight = byte_weight;
476 dev->use_worker = use_worker;
477 dev->msg_handler = msg_handler;
478 init_llist_head(&dev->work_list);
479 init_waitqueue_head(&dev->wait);
480 INIT_LIST_HEAD(&dev->read_list);
481 INIT_LIST_HEAD(&dev->pending_list);
482 spin_lock_init(&dev->iotlb_lock);
485 for (i = 0; i < dev->nvqs; ++i) {
491 mutex_init(&vq->mutex);
492 vhost_vq_reset(dev, vq);
494 vhost_poll_init(&vq->poll, vq->handle_kick,
498 EXPORT_SYMBOL_GPL(vhost_dev_init);
500 /* Caller should have device mutex */
501 long vhost_dev_check_owner(struct vhost_dev *dev)
503 /* Are you the owner? If not, I don't think you mean to do that */
504 return dev->mm == current->mm ? 0 : -EPERM;
506 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
508 struct vhost_attach_cgroups_struct {
509 struct vhost_work work;
510 struct task_struct *owner;
514 static void vhost_attach_cgroups_work(struct vhost_work *work)
516 struct vhost_attach_cgroups_struct *s;
518 s = container_of(work, struct vhost_attach_cgroups_struct, work);
519 s->ret = cgroup_attach_task_all(s->owner, current);
522 static int vhost_attach_cgroups(struct vhost_dev *dev)
524 struct vhost_attach_cgroups_struct attach;
526 attach.owner = current;
527 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
528 vhost_work_queue(dev, &attach.work);
529 vhost_work_flush(dev, &attach.work);
533 /* Caller should have device mutex */
534 bool vhost_dev_has_owner(struct vhost_dev *dev)
538 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
540 static void vhost_attach_mm(struct vhost_dev *dev)
542 /* No owner, become one */
543 if (dev->use_worker) {
544 dev->mm = get_task_mm(current);
546 /* vDPA device does not use worker thead, so there's
547 * no need to hold the address space for mm. This help
548 * to avoid deadlock in the case of mmap() which may
549 * held the refcnt of the file and depends on release
550 * method to remove vma.
552 dev->mm = current->mm;
557 static void vhost_detach_mm(struct vhost_dev *dev)
570 /* Caller should have device mutex */
571 long vhost_dev_set_owner(struct vhost_dev *dev)
573 struct task_struct *worker;
576 /* Is there an owner already? */
577 if (vhost_dev_has_owner(dev)) {
582 vhost_attach_mm(dev);
584 dev->kcov_handle = kcov_common_handle();
585 if (dev->use_worker) {
586 worker = kthread_create(vhost_worker, dev,
587 "vhost-%d", current->pid);
588 if (IS_ERR(worker)) {
589 err = PTR_ERR(worker);
593 dev->worker = worker;
594 wake_up_process(worker); /* avoid contributing to loadavg */
596 err = vhost_attach_cgroups(dev);
601 err = vhost_dev_alloc_iovecs(dev);
608 kthread_stop(dev->worker);
612 vhost_detach_mm(dev);
613 dev->kcov_handle = 0;
617 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
619 static struct vhost_iotlb *iotlb_alloc(void)
621 return vhost_iotlb_alloc(max_iotlb_entries,
622 VHOST_IOTLB_FLAG_RETIRE);
625 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void)
627 return iotlb_alloc();
629 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
631 /* Caller should have device mutex */
632 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem)
636 vhost_dev_cleanup(dev);
639 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
640 * VQs aren't running.
642 for (i = 0; i < dev->nvqs; ++i)
643 dev->vqs[i]->umem = umem;
645 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
647 void vhost_dev_stop(struct vhost_dev *dev)
651 for (i = 0; i < dev->nvqs; ++i) {
652 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
653 vhost_poll_stop(&dev->vqs[i]->poll);
654 vhost_poll_flush(&dev->vqs[i]->poll);
658 EXPORT_SYMBOL_GPL(vhost_dev_stop);
660 static void vhost_clear_msg(struct vhost_dev *dev)
662 struct vhost_msg_node *node, *n;
664 spin_lock(&dev->iotlb_lock);
666 list_for_each_entry_safe(node, n, &dev->read_list, node) {
667 list_del(&node->node);
671 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
672 list_del(&node->node);
676 spin_unlock(&dev->iotlb_lock);
679 void vhost_dev_cleanup(struct vhost_dev *dev)
683 for (i = 0; i < dev->nvqs; ++i) {
684 if (dev->vqs[i]->error_ctx)
685 eventfd_ctx_put(dev->vqs[i]->error_ctx);
686 if (dev->vqs[i]->kick)
687 fput(dev->vqs[i]->kick);
688 if (dev->vqs[i]->call_ctx)
689 eventfd_ctx_put(dev->vqs[i]->call_ctx);
690 vhost_vq_reset(dev, dev->vqs[i]);
692 vhost_dev_free_iovecs(dev);
694 eventfd_ctx_put(dev->log_ctx);
696 /* No one will access memory at this point */
697 vhost_iotlb_free(dev->umem);
699 vhost_iotlb_free(dev->iotlb);
701 vhost_clear_msg(dev);
702 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
703 WARN_ON(!llist_empty(&dev->work_list));
705 kthread_stop(dev->worker);
707 dev->kcov_handle = 0;
709 vhost_detach_mm(dev);
711 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
713 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
715 u64 a = addr / VHOST_PAGE_SIZE / 8;
717 /* Make sure 64 bit math will not overflow. */
718 if (a > ULONG_MAX - (unsigned long)log_base ||
719 a + (unsigned long)log_base > ULONG_MAX)
722 return access_ok(log_base + a,
723 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
726 static bool vhost_overflow(u64 uaddr, u64 size)
728 /* Make sure 64 bit math will not overflow. */
729 return uaddr > ULONG_MAX || size > ULONG_MAX || uaddr > ULONG_MAX - size;
732 /* Caller should have vq mutex and device mutex. */
733 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem,
736 struct vhost_iotlb_map *map;
741 list_for_each_entry(map, &umem->list, link) {
742 unsigned long a = map->addr;
744 if (vhost_overflow(map->addr, map->size))
748 if (!access_ok((void __user *)a, map->size))
750 else if (log_all && !log_access_ok(log_base,
758 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
759 u64 addr, unsigned int size,
762 const struct vhost_iotlb_map *map = vq->meta_iotlb[type];
767 return (void __user *)(uintptr_t)(map->addr + addr - map->start);
770 /* Can we switch to this memory table? */
771 /* Caller should have device mutex but not vq mutex */
772 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem,
777 for (i = 0; i < d->nvqs; ++i) {
781 mutex_lock(&d->vqs[i]->mutex);
782 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
783 /* If ring is inactive, will check when it's enabled. */
784 if (d->vqs[i]->private_data)
785 ok = vq_memory_access_ok(d->vqs[i]->log_base,
789 mutex_unlock(&d->vqs[i]->mutex);
796 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
797 struct iovec iov[], int iov_size, int access);
799 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
800 const void *from, unsigned size)
805 return __copy_to_user(to, from, size);
807 /* This function should be called after iotlb
808 * prefetch, which means we're sure that all vq
809 * could be access through iotlb. So -EAGAIN should
810 * not happen in this case.
813 void __user *uaddr = vhost_vq_meta_fetch(vq,
814 (u64)(uintptr_t)to, size,
818 return __copy_to_user(uaddr, from, size);
820 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
821 ARRAY_SIZE(vq->iotlb_iov),
825 iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
826 ret = copy_to_iter(from, size, &t);
834 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
835 void __user *from, unsigned size)
840 return __copy_from_user(to, from, size);
842 /* This function should be called after iotlb
843 * prefetch, which means we're sure that vq
844 * could be access through iotlb. So -EAGAIN should
845 * not happen in this case.
847 void __user *uaddr = vhost_vq_meta_fetch(vq,
848 (u64)(uintptr_t)from, size,
853 return __copy_from_user(to, uaddr, size);
855 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
856 ARRAY_SIZE(vq->iotlb_iov),
859 vq_err(vq, "IOTLB translation failure: uaddr "
860 "%p size 0x%llx\n", from,
861 (unsigned long long) size);
864 iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
865 ret = copy_from_iter(to, size, &f);
874 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
875 void __user *addr, unsigned int size,
880 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
881 ARRAY_SIZE(vq->iotlb_iov),
884 vq_err(vq, "IOTLB translation failure: uaddr "
885 "%p size 0x%llx\n", addr,
886 (unsigned long long) size);
890 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
891 vq_err(vq, "Non atomic userspace memory access: uaddr "
892 "%p size 0x%llx\n", addr,
893 (unsigned long long) size);
897 return vq->iotlb_iov[0].iov_base;
900 /* This function should be called after iotlb
901 * prefetch, which means we're sure that vq
902 * could be access through iotlb. So -EAGAIN should
903 * not happen in this case.
905 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
906 void __user *addr, unsigned int size,
909 void __user *uaddr = vhost_vq_meta_fetch(vq,
910 (u64)(uintptr_t)addr, size, type);
914 return __vhost_get_user_slow(vq, addr, size, type);
917 #define vhost_put_user(vq, x, ptr) \
921 ret = __put_user(x, ptr); \
923 __typeof__(ptr) to = \
924 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
925 sizeof(*ptr), VHOST_ADDR_USED); \
927 ret = __put_user(x, to); \
934 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
936 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
937 vhost_avail_event(vq));
940 static inline int vhost_put_used(struct vhost_virtqueue *vq,
941 struct vring_used_elem *head, int idx,
944 return vhost_copy_to_user(vq, vq->used->ring + idx, head,
945 count * sizeof(*head));
948 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
951 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
955 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
958 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
962 #define vhost_get_user(vq, x, ptr, type) \
966 ret = __get_user(x, ptr); \
968 __typeof__(ptr) from = \
969 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
973 ret = __get_user(x, from); \
980 #define vhost_get_avail(vq, x, ptr) \
981 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
983 #define vhost_get_used(vq, x, ptr) \
984 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
986 static void vhost_dev_lock_vqs(struct vhost_dev *d)
989 for (i = 0; i < d->nvqs; ++i)
990 mutex_lock_nested(&d->vqs[i]->mutex, i);
993 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
996 for (i = 0; i < d->nvqs; ++i)
997 mutex_unlock(&d->vqs[i]->mutex);
1000 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
1003 return vhost_get_avail(vq, *idx, &vq->avail->idx);
1006 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
1007 __virtio16 *head, int idx)
1009 return vhost_get_avail(vq, *head,
1010 &vq->avail->ring[idx & (vq->num - 1)]);
1013 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1016 return vhost_get_avail(vq, *flags, &vq->avail->flags);
1019 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1022 return vhost_get_avail(vq, *event, vhost_used_event(vq));
1025 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1028 return vhost_get_used(vq, *idx, &vq->used->idx);
1031 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1032 struct vring_desc *desc, int idx)
1034 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1037 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1038 struct vhost_iotlb_msg *msg)
1040 struct vhost_msg_node *node, *n;
1042 spin_lock(&d->iotlb_lock);
1044 list_for_each_entry_safe(node, n, &d->pending_list, node) {
1045 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1046 if (msg->iova <= vq_msg->iova &&
1047 msg->iova + msg->size - 1 >= vq_msg->iova &&
1048 vq_msg->type == VHOST_IOTLB_MISS) {
1049 vhost_poll_queue(&node->vq->poll);
1050 list_del(&node->node);
1055 spin_unlock(&d->iotlb_lock);
1058 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1060 unsigned long a = uaddr;
1062 /* Make sure 64 bit math will not overflow. */
1063 if (vhost_overflow(uaddr, size))
1066 if ((access & VHOST_ACCESS_RO) &&
1067 !access_ok((void __user *)a, size))
1069 if ((access & VHOST_ACCESS_WO) &&
1070 !access_ok((void __user *)a, size))
1075 static int vhost_process_iotlb_msg(struct vhost_dev *dev,
1076 struct vhost_iotlb_msg *msg)
1080 mutex_lock(&dev->mutex);
1081 vhost_dev_lock_vqs(dev);
1082 switch (msg->type) {
1083 case VHOST_IOTLB_UPDATE:
1088 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1092 vhost_vq_meta_reset(dev);
1093 if (vhost_iotlb_add_range(dev->iotlb, msg->iova,
1094 msg->iova + msg->size - 1,
1095 msg->uaddr, msg->perm)) {
1099 vhost_iotlb_notify_vq(dev, msg);
1101 case VHOST_IOTLB_INVALIDATE:
1106 vhost_vq_meta_reset(dev);
1107 vhost_iotlb_del_range(dev->iotlb, msg->iova,
1108 msg->iova + msg->size - 1);
1115 vhost_dev_unlock_vqs(dev);
1116 mutex_unlock(&dev->mutex);
1120 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1121 struct iov_iter *from)
1123 struct vhost_iotlb_msg msg;
1127 ret = copy_from_iter(&type, sizeof(type), from);
1128 if (ret != sizeof(type)) {
1134 case VHOST_IOTLB_MSG:
1135 /* There maybe a hole after type for V1 message type,
1138 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1140 case VHOST_IOTLB_MSG_V2:
1141 offset = sizeof(__u32);
1148 iov_iter_advance(from, offset);
1149 ret = copy_from_iter(&msg, sizeof(msg), from);
1150 if (ret != sizeof(msg)) {
1155 if (dev->msg_handler)
1156 ret = dev->msg_handler(dev, &msg);
1158 ret = vhost_process_iotlb_msg(dev, &msg);
1164 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1165 sizeof(struct vhost_msg_v2);
1169 EXPORT_SYMBOL(vhost_chr_write_iter);
1171 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1176 poll_wait(file, &dev->wait, wait);
1178 if (!list_empty(&dev->read_list))
1179 mask |= EPOLLIN | EPOLLRDNORM;
1183 EXPORT_SYMBOL(vhost_chr_poll);
1185 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1189 struct vhost_msg_node *node;
1191 unsigned size = sizeof(struct vhost_msg);
1193 if (iov_iter_count(to) < size)
1198 prepare_to_wait(&dev->wait, &wait,
1199 TASK_INTERRUPTIBLE);
1201 node = vhost_dequeue_msg(dev, &dev->read_list);
1208 if (signal_pending(current)) {
1221 finish_wait(&dev->wait, &wait);
1224 struct vhost_iotlb_msg *msg;
1225 void *start = &node->msg;
1227 switch (node->msg.type) {
1228 case VHOST_IOTLB_MSG:
1229 size = sizeof(node->msg);
1230 msg = &node->msg.iotlb;
1232 case VHOST_IOTLB_MSG_V2:
1233 size = sizeof(node->msg_v2);
1234 msg = &node->msg_v2.iotlb;
1241 ret = copy_to_iter(start, size, to);
1242 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1246 vhost_enqueue_msg(dev, &dev->pending_list, node);
1251 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1253 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1255 struct vhost_dev *dev = vq->dev;
1256 struct vhost_msg_node *node;
1257 struct vhost_iotlb_msg *msg;
1258 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1260 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1265 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1266 msg = &node->msg_v2.iotlb;
1268 msg = &node->msg.iotlb;
1271 msg->type = VHOST_IOTLB_MISS;
1275 vhost_enqueue_msg(dev, &dev->read_list, node);
1280 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1281 vring_desc_t __user *desc,
1282 vring_avail_t __user *avail,
1283 vring_used_t __user *used)
1286 return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1287 access_ok(avail, vhost_get_avail_size(vq, num)) &&
1288 access_ok(used, vhost_get_used_size(vq, num));
1291 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1292 const struct vhost_iotlb_map *map,
1295 int access = (type == VHOST_ADDR_USED) ?
1296 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1298 if (likely(map->perm & access))
1299 vq->meta_iotlb[type] = map;
1302 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1303 int access, u64 addr, u64 len, int type)
1305 const struct vhost_iotlb_map *map;
1306 struct vhost_iotlb *umem = vq->iotlb;
1307 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1309 if (vhost_vq_meta_fetch(vq, addr, len, type))
1313 map = vhost_iotlb_itree_first(umem, addr, last);
1314 if (map == NULL || map->start > addr) {
1315 vhost_iotlb_miss(vq, addr, access);
1317 } else if (!(map->perm & access)) {
1318 /* Report the possible access violation by
1319 * request another translation from userspace.
1324 size = map->size - addr + map->start;
1326 if (orig_addr == addr && size >= len)
1327 vhost_vq_meta_update(vq, map, type);
1336 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1338 unsigned int num = vq->num;
1343 return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc,
1344 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1345 iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail,
1346 vhost_get_avail_size(vq, num),
1347 VHOST_ADDR_AVAIL) &&
1348 iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used,
1349 vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1351 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1353 /* Can we log writes? */
1354 /* Caller should have device mutex but not vq mutex */
1355 bool vhost_log_access_ok(struct vhost_dev *dev)
1357 return memory_access_ok(dev, dev->umem, 1);
1359 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1361 /* Verify access for write logging. */
1362 /* Caller should have vq mutex and device mutex */
1363 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1364 void __user *log_base)
1366 return vq_memory_access_ok(log_base, vq->umem,
1367 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1368 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
1369 vhost_get_used_size(vq, vq->num)));
1372 /* Can we start vq? */
1373 /* Caller should have vq mutex and device mutex */
1374 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1376 if (!vq_log_access_ok(vq, vq->log_base))
1379 /* Access validation occurs at prefetch time with IOTLB */
1383 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1385 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1387 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1389 struct vhost_memory mem, *newmem;
1390 struct vhost_memory_region *region;
1391 struct vhost_iotlb *newumem, *oldumem;
1392 unsigned long size = offsetof(struct vhost_memory, regions);
1395 if (copy_from_user(&mem, m, size))
1399 if (mem.nregions > max_mem_regions)
1401 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1406 memcpy(newmem, &mem, size);
1407 if (copy_from_user(newmem->regions, m->regions,
1408 mem.nregions * sizeof *m->regions)) {
1413 newumem = iotlb_alloc();
1419 for (region = newmem->regions;
1420 region < newmem->regions + mem.nregions;
1422 if (vhost_iotlb_add_range(newumem,
1423 region->guest_phys_addr,
1424 region->guest_phys_addr +
1425 region->memory_size - 1,
1426 region->userspace_addr,
1431 if (!memory_access_ok(d, newumem, 0))
1437 /* All memory accesses are done under some VQ mutex. */
1438 for (i = 0; i < d->nvqs; ++i) {
1439 mutex_lock(&d->vqs[i]->mutex);
1440 d->vqs[i]->umem = newumem;
1441 mutex_unlock(&d->vqs[i]->mutex);
1445 vhost_iotlb_free(oldumem);
1449 vhost_iotlb_free(newumem);
1454 static long vhost_vring_set_num(struct vhost_dev *d,
1455 struct vhost_virtqueue *vq,
1458 struct vhost_vring_state s;
1460 /* Resizing ring with an active backend?
1461 * You don't want to do that. */
1462 if (vq->private_data)
1465 if (copy_from_user(&s, argp, sizeof s))
1468 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
1475 static long vhost_vring_set_addr(struct vhost_dev *d,
1476 struct vhost_virtqueue *vq,
1479 struct vhost_vring_addr a;
1481 if (copy_from_user(&a, argp, sizeof a))
1483 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
1486 /* For 32bit, verify that the top 32bits of the user
1487 data are set to zero. */
1488 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1489 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1490 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
1493 /* Make sure it's safe to cast pointers to vring types. */
1494 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1495 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1496 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1497 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1498 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
1501 /* We only verify access here if backend is configured.
1502 * If it is not, we don't as size might not have been setup.
1503 * We will verify when backend is configured. */
1504 if (vq->private_data) {
1505 if (!vq_access_ok(vq, vq->num,
1506 (void __user *)(unsigned long)a.desc_user_addr,
1507 (void __user *)(unsigned long)a.avail_user_addr,
1508 (void __user *)(unsigned long)a.used_user_addr))
1511 /* Also validate log access for used ring if enabled. */
1512 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
1513 !log_access_ok(vq->log_base, a.log_guest_addr,
1515 vq->num * sizeof *vq->used->ring))
1519 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1520 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1521 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1522 vq->log_addr = a.log_guest_addr;
1523 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1528 static long vhost_vring_set_num_addr(struct vhost_dev *d,
1529 struct vhost_virtqueue *vq,
1535 mutex_lock(&vq->mutex);
1538 case VHOST_SET_VRING_NUM:
1539 r = vhost_vring_set_num(d, vq, argp);
1541 case VHOST_SET_VRING_ADDR:
1542 r = vhost_vring_set_addr(d, vq, argp);
1548 mutex_unlock(&vq->mutex);
1552 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1554 struct file *eventfp, *filep = NULL;
1555 bool pollstart = false, pollstop = false;
1556 struct eventfd_ctx *ctx = NULL;
1557 u32 __user *idxp = argp;
1558 struct vhost_virtqueue *vq;
1559 struct vhost_vring_state s;
1560 struct vhost_vring_file f;
1564 r = get_user(idx, idxp);
1570 idx = array_index_nospec(idx, d->nvqs);
1573 if (ioctl == VHOST_SET_VRING_NUM ||
1574 ioctl == VHOST_SET_VRING_ADDR) {
1575 return vhost_vring_set_num_addr(d, vq, ioctl, argp);
1578 mutex_lock(&vq->mutex);
1581 case VHOST_SET_VRING_BASE:
1582 /* Moving base with an active backend?
1583 * You don't want to do that. */
1584 if (vq->private_data) {
1588 if (copy_from_user(&s, argp, sizeof s)) {
1592 if (s.num > 0xffff) {
1596 vq->last_avail_idx = s.num;
1597 /* Forget the cached index value. */
1598 vq->avail_idx = vq->last_avail_idx;
1600 case VHOST_GET_VRING_BASE:
1602 s.num = vq->last_avail_idx;
1603 if (copy_to_user(argp, &s, sizeof s))
1606 case VHOST_SET_VRING_KICK:
1607 if (copy_from_user(&f, argp, sizeof f)) {
1611 eventfp = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_fget(f.fd);
1612 if (IS_ERR(eventfp)) {
1613 r = PTR_ERR(eventfp);
1616 if (eventfp != vq->kick) {
1617 pollstop = (filep = vq->kick) != NULL;
1618 pollstart = (vq->kick = eventfp) != NULL;
1622 case VHOST_SET_VRING_CALL:
1623 if (copy_from_user(&f, argp, sizeof f)) {
1627 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
1632 swap(ctx, vq->call_ctx);
1634 case VHOST_SET_VRING_ERR:
1635 if (copy_from_user(&f, argp, sizeof f)) {
1639 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
1644 swap(ctx, vq->error_ctx);
1646 case VHOST_SET_VRING_ENDIAN:
1647 r = vhost_set_vring_endian(vq, argp);
1649 case VHOST_GET_VRING_ENDIAN:
1650 r = vhost_get_vring_endian(vq, idx, argp);
1652 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1653 if (copy_from_user(&s, argp, sizeof(s))) {
1657 vq->busyloop_timeout = s.num;
1659 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1661 s.num = vq->busyloop_timeout;
1662 if (copy_to_user(argp, &s, sizeof(s)))
1669 if (pollstop && vq->handle_kick)
1670 vhost_poll_stop(&vq->poll);
1672 if (!IS_ERR_OR_NULL(ctx))
1673 eventfd_ctx_put(ctx);
1677 if (pollstart && vq->handle_kick)
1678 r = vhost_poll_start(&vq->poll, vq->kick);
1680 mutex_unlock(&vq->mutex);
1682 if (pollstop && vq->handle_kick)
1683 vhost_poll_flush(&vq->poll);
1686 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1688 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1690 struct vhost_iotlb *niotlb, *oiotlb;
1693 niotlb = iotlb_alloc();
1700 for (i = 0; i < d->nvqs; ++i) {
1701 struct vhost_virtqueue *vq = d->vqs[i];
1703 mutex_lock(&vq->mutex);
1705 __vhost_vq_meta_reset(vq);
1706 mutex_unlock(&vq->mutex);
1709 vhost_iotlb_free(oiotlb);
1713 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1715 /* Caller must have device mutex */
1716 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1718 struct eventfd_ctx *ctx;
1723 /* If you are not the owner, you can become one */
1724 if (ioctl == VHOST_SET_OWNER) {
1725 r = vhost_dev_set_owner(d);
1729 /* You must be the owner to do anything else */
1730 r = vhost_dev_check_owner(d);
1735 case VHOST_SET_MEM_TABLE:
1736 r = vhost_set_memory(d, argp);
1738 case VHOST_SET_LOG_BASE:
1739 if (copy_from_user(&p, argp, sizeof p)) {
1743 if ((u64)(unsigned long)p != p) {
1747 for (i = 0; i < d->nvqs; ++i) {
1748 struct vhost_virtqueue *vq;
1749 void __user *base = (void __user *)(unsigned long)p;
1751 mutex_lock(&vq->mutex);
1752 /* If ring is inactive, will check when it's enabled. */
1753 if (vq->private_data && !vq_log_access_ok(vq, base))
1756 vq->log_base = base;
1757 mutex_unlock(&vq->mutex);
1760 case VHOST_SET_LOG_FD:
1761 r = get_user(fd, (int __user *)argp);
1764 ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd);
1769 swap(ctx, d->log_ctx);
1770 for (i = 0; i < d->nvqs; ++i) {
1771 mutex_lock(&d->vqs[i]->mutex);
1772 d->vqs[i]->log_ctx = d->log_ctx;
1773 mutex_unlock(&d->vqs[i]->mutex);
1776 eventfd_ctx_put(ctx);
1785 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1787 /* TODO: This is really inefficient. We need something like get_user()
1788 * (instruction directly accesses the data, with an exception table entry
1789 * returning -EFAULT). See Documentation/x86/exception-tables.rst.
1791 static int set_bit_to_user(int nr, void __user *addr)
1793 unsigned long log = (unsigned long)addr;
1796 int bit = nr + (log % PAGE_SIZE) * 8;
1799 r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page);
1803 base = kmap_atomic(page);
1805 kunmap_atomic(base);
1806 unpin_user_pages_dirty_lock(&page, 1, true);
1810 static int log_write(void __user *log_base,
1811 u64 write_address, u64 write_length)
1813 u64 write_page = write_address / VHOST_PAGE_SIZE;
1818 write_length += write_address % VHOST_PAGE_SIZE;
1820 u64 base = (u64)(unsigned long)log_base;
1821 u64 log = base + write_page / 8;
1822 int bit = write_page % 8;
1823 if ((u64)(unsigned long)log != log)
1825 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1828 if (write_length <= VHOST_PAGE_SIZE)
1830 write_length -= VHOST_PAGE_SIZE;
1836 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1838 struct vhost_iotlb *umem = vq->umem;
1839 struct vhost_iotlb_map *u;
1840 u64 start, end, l, min;
1846 /* More than one GPAs can be mapped into a single HVA. So
1847 * iterate all possible umems here to be safe.
1849 list_for_each_entry(u, &umem->list, link) {
1850 if (u->addr > hva - 1 + len ||
1851 u->addr - 1 + u->size < hva)
1853 start = max(u->addr, hva);
1854 end = min(u->addr - 1 + u->size, hva - 1 + len);
1855 l = end - start + 1;
1856 r = log_write(vq->log_base,
1857 u->start + start - u->addr,
1875 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1877 struct iovec iov[64];
1881 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1883 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1884 len, iov, 64, VHOST_ACCESS_WO);
1888 for (i = 0; i < ret; i++) {
1889 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1898 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1899 unsigned int log_num, u64 len, struct iovec *iov, int count)
1903 /* Make sure data written is seen before log. */
1907 for (i = 0; i < count; i++) {
1908 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1916 for (i = 0; i < log_num; ++i) {
1917 u64 l = min(log[i].len, len);
1918 r = log_write(vq->log_base, log[i].addr, l);
1924 eventfd_signal(vq->log_ctx, 1);
1928 /* Length written exceeds what we have stored. This is a bug. */
1932 EXPORT_SYMBOL_GPL(vhost_log_write);
1934 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1937 if (vhost_put_used_flags(vq))
1939 if (unlikely(vq->log_used)) {
1940 /* Make sure the flag is seen before log. */
1942 /* Log used flag write. */
1943 used = &vq->used->flags;
1944 log_used(vq, (used - (void __user *)vq->used),
1945 sizeof vq->used->flags);
1947 eventfd_signal(vq->log_ctx, 1);
1952 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1954 if (vhost_put_avail_event(vq))
1956 if (unlikely(vq->log_used)) {
1958 /* Make sure the event is seen before log. */
1960 /* Log avail event write */
1961 used = vhost_avail_event(vq);
1962 log_used(vq, (used - (void __user *)vq->used),
1963 sizeof *vhost_avail_event(vq));
1965 eventfd_signal(vq->log_ctx, 1);
1970 int vhost_vq_init_access(struct vhost_virtqueue *vq)
1972 __virtio16 last_used_idx;
1974 bool is_le = vq->is_le;
1976 if (!vq->private_data)
1979 vhost_init_is_le(vq);
1981 r = vhost_update_used_flags(vq);
1984 vq->signalled_used_valid = false;
1986 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
1990 r = vhost_get_used_idx(vq, &last_used_idx);
1992 vq_err(vq, "Can't access used idx at %p\n",
1996 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2003 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2005 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2006 struct iovec iov[], int iov_size, int access)
2008 const struct vhost_iotlb_map *map;
2009 struct vhost_dev *dev = vq->dev;
2010 struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
2015 while ((u64)len > s) {
2017 if (unlikely(ret >= iov_size)) {
2022 map = vhost_iotlb_itree_first(umem, addr, addr + len - 1);
2023 if (map == NULL || map->start > addr) {
2024 if (umem != dev->iotlb) {
2030 } else if (!(map->perm & access)) {
2036 size = map->size - addr + map->start;
2037 _iov->iov_len = min((u64)len - s, size);
2038 _iov->iov_base = (void __user *)(unsigned long)
2039 (map->addr + addr - map->start);
2046 vhost_iotlb_miss(vq, addr, access);
2050 /* Each buffer in the virtqueues is actually a chain of descriptors. This
2051 * function returns the next descriptor in the chain,
2052 * or -1U if we're at the end. */
2053 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2057 /* If this descriptor says it doesn't chain, we're done. */
2058 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2061 /* Check they're not leading us off end of descriptors. */
2062 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2066 static int get_indirect(struct vhost_virtqueue *vq,
2067 struct iovec iov[], unsigned int iov_size,
2068 unsigned int *out_num, unsigned int *in_num,
2069 struct vhost_log *log, unsigned int *log_num,
2070 struct vring_desc *indirect)
2072 struct vring_desc desc;
2073 unsigned int i = 0, count, found = 0;
2074 u32 len = vhost32_to_cpu(vq, indirect->len);
2075 struct iov_iter from;
2079 if (unlikely(len % sizeof desc)) {
2080 vq_err(vq, "Invalid length in indirect descriptor: "
2081 "len 0x%llx not multiple of 0x%zx\n",
2082 (unsigned long long)len,
2087 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2088 UIO_MAXIOV, VHOST_ACCESS_RO);
2089 if (unlikely(ret < 0)) {
2091 vq_err(vq, "Translation failure %d in indirect.\n", ret);
2094 iov_iter_init(&from, READ, vq->indirect, ret, len);
2096 /* We will use the result as an address to read from, so most
2097 * architectures only need a compiler barrier here. */
2098 read_barrier_depends();
2100 count = len / sizeof desc;
2101 /* Buffers are chained via a 16 bit next field, so
2102 * we can have at most 2^16 of these. */
2103 if (unlikely(count > USHRT_MAX + 1)) {
2104 vq_err(vq, "Indirect buffer length too big: %d\n",
2110 unsigned iov_count = *in_num + *out_num;
2111 if (unlikely(++found > count)) {
2112 vq_err(vq, "Loop detected: last one at %u "
2113 "indirect size %u\n",
2117 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2118 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2119 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2122 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2123 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2124 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2128 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2129 access = VHOST_ACCESS_WO;
2131 access = VHOST_ACCESS_RO;
2133 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2134 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2135 iov_size - iov_count, access);
2136 if (unlikely(ret < 0)) {
2138 vq_err(vq, "Translation failure %d indirect idx %d\n",
2142 /* If this is an input descriptor, increment that count. */
2143 if (access == VHOST_ACCESS_WO) {
2145 if (unlikely(log && ret)) {
2146 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2147 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2151 /* If it's an output descriptor, they're all supposed
2152 * to come before any input descriptors. */
2153 if (unlikely(*in_num)) {
2154 vq_err(vq, "Indirect descriptor "
2155 "has out after in: idx %d\n", i);
2160 } while ((i = next_desc(vq, &desc)) != -1);
2164 /* This looks in the virtqueue and for the first available buffer, and converts
2165 * it to an iovec for convenient access. Since descriptors consist of some
2166 * number of output then some number of input descriptors, it's actually two
2167 * iovecs, but we pack them into one and note how many of each there were.
2169 * This function returns the descriptor number found, or vq->num (which is
2170 * never a valid descriptor number) if none was found. A negative code is
2171 * returned on error. */
2172 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2173 struct iovec iov[], unsigned int iov_size,
2174 unsigned int *out_num, unsigned int *in_num,
2175 struct vhost_log *log, unsigned int *log_num)
2177 struct vring_desc desc;
2178 unsigned int i, head, found = 0;
2180 __virtio16 avail_idx;
2181 __virtio16 ring_head;
2184 /* Check it isn't doing very strange things with descriptor numbers. */
2185 last_avail_idx = vq->last_avail_idx;
2187 if (vq->avail_idx == vq->last_avail_idx) {
2188 if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
2189 vq_err(vq, "Failed to access avail idx at %p\n",
2193 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2195 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2196 vq_err(vq, "Guest moved used index from %u to %u",
2197 last_avail_idx, vq->avail_idx);
2201 /* If there's nothing new since last we looked, return
2204 if (vq->avail_idx == last_avail_idx)
2207 /* Only get avail ring entries after they have been
2213 /* Grab the next descriptor number they're advertising, and increment
2214 * the index we've seen. */
2215 if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
2216 vq_err(vq, "Failed to read head: idx %d address %p\n",
2218 &vq->avail->ring[last_avail_idx % vq->num]);
2222 head = vhost16_to_cpu(vq, ring_head);
2224 /* If their number is silly, that's an error. */
2225 if (unlikely(head >= vq->num)) {
2226 vq_err(vq, "Guest says index %u > %u is available",
2231 /* When we start there are none of either input nor output. */
2232 *out_num = *in_num = 0;
2238 unsigned iov_count = *in_num + *out_num;
2239 if (unlikely(i >= vq->num)) {
2240 vq_err(vq, "Desc index is %u > %u, head = %u",
2244 if (unlikely(++found > vq->num)) {
2245 vq_err(vq, "Loop detected: last one at %u "
2246 "vq size %u head %u\n",
2250 ret = vhost_get_desc(vq, &desc, i);
2251 if (unlikely(ret)) {
2252 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2256 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2257 ret = get_indirect(vq, iov, iov_size,
2259 log, log_num, &desc);
2260 if (unlikely(ret < 0)) {
2262 vq_err(vq, "Failure detected "
2263 "in indirect descriptor at idx %d\n", i);
2269 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2270 access = VHOST_ACCESS_WO;
2272 access = VHOST_ACCESS_RO;
2273 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2274 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2275 iov_size - iov_count, access);
2276 if (unlikely(ret < 0)) {
2278 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2282 if (access == VHOST_ACCESS_WO) {
2283 /* If this is an input descriptor,
2284 * increment that count. */
2286 if (unlikely(log && ret)) {
2287 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2288 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2292 /* If it's an output descriptor, they're all supposed
2293 * to come before any input descriptors. */
2294 if (unlikely(*in_num)) {
2295 vq_err(vq, "Descriptor has out after in: "
2301 } while ((i = next_desc(vq, &desc)) != -1);
2303 /* On success, increment avail index. */
2304 vq->last_avail_idx++;
2306 /* Assume notifications from guest are disabled at this point,
2307 * if they aren't we would need to update avail_event index. */
2308 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2311 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2313 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2314 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2316 vq->last_avail_idx -= n;
2318 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2320 /* After we've used one of their buffers, we tell them about it. We'll then
2321 * want to notify the guest, using eventfd. */
2322 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2324 struct vring_used_elem heads = {
2325 cpu_to_vhost32(vq, head),
2326 cpu_to_vhost32(vq, len)
2329 return vhost_add_used_n(vq, &heads, 1);
2331 EXPORT_SYMBOL_GPL(vhost_add_used);
2333 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2334 struct vring_used_elem *heads,
2337 vring_used_elem_t __user *used;
2341 start = vq->last_used_idx & (vq->num - 1);
2342 used = vq->used->ring + start;
2343 if (vhost_put_used(vq, heads, start, count)) {
2344 vq_err(vq, "Failed to write used");
2347 if (unlikely(vq->log_used)) {
2348 /* Make sure data is seen before log. */
2350 /* Log used ring entry write. */
2351 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2352 count * sizeof *used);
2354 old = vq->last_used_idx;
2355 new = (vq->last_used_idx += count);
2356 /* If the driver never bothers to signal in a very long while,
2357 * used index might wrap around. If that happens, invalidate
2358 * signalled_used index we stored. TODO: make sure driver
2359 * signals at least once in 2^16 and remove this. */
2360 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2361 vq->signalled_used_valid = false;
2365 /* After we've used one of their buffers, we tell them about it. We'll then
2366 * want to notify the guest, using eventfd. */
2367 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2372 start = vq->last_used_idx & (vq->num - 1);
2373 n = vq->num - start;
2375 r = __vhost_add_used_n(vq, heads, n);
2381 r = __vhost_add_used_n(vq, heads, count);
2383 /* Make sure buffer is written before we update index. */
2385 if (vhost_put_used_idx(vq)) {
2386 vq_err(vq, "Failed to increment used idx");
2389 if (unlikely(vq->log_used)) {
2390 /* Make sure used idx is seen before log. */
2392 /* Log used index update. */
2393 log_used(vq, offsetof(struct vring_used, idx),
2394 sizeof vq->used->idx);
2396 eventfd_signal(vq->log_ctx, 1);
2400 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2402 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2407 /* Flush out used index updates. This is paired
2408 * with the barrier that the Guest executes when enabling
2412 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2413 unlikely(vq->avail_idx == vq->last_avail_idx))
2416 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2418 if (vhost_get_avail_flags(vq, &flags)) {
2419 vq_err(vq, "Failed to get flags");
2422 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2424 old = vq->signalled_used;
2425 v = vq->signalled_used_valid;
2426 new = vq->signalled_used = vq->last_used_idx;
2427 vq->signalled_used_valid = true;
2432 if (vhost_get_used_event(vq, &event)) {
2433 vq_err(vq, "Failed to get used event idx");
2436 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2439 /* This actually signals the guest, using eventfd. */
2440 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2442 /* Signal the Guest tell them we used something up. */
2443 if (vq->call_ctx && vhost_notify(dev, vq))
2444 eventfd_signal(vq->call_ctx, 1);
2446 EXPORT_SYMBOL_GPL(vhost_signal);
2448 /* And here's the combo meal deal. Supersize me! */
2449 void vhost_add_used_and_signal(struct vhost_dev *dev,
2450 struct vhost_virtqueue *vq,
2451 unsigned int head, int len)
2453 vhost_add_used(vq, head, len);
2454 vhost_signal(dev, vq);
2456 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2458 /* multi-buffer version of vhost_add_used_and_signal */
2459 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2460 struct vhost_virtqueue *vq,
2461 struct vring_used_elem *heads, unsigned count)
2463 vhost_add_used_n(vq, heads, count);
2464 vhost_signal(dev, vq);
2466 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2468 /* return true if we're sure that avaiable ring is empty */
2469 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2471 __virtio16 avail_idx;
2474 if (vq->avail_idx != vq->last_avail_idx)
2477 r = vhost_get_avail_idx(vq, &avail_idx);
2480 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2482 return vq->avail_idx == vq->last_avail_idx;
2484 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2486 /* OK, now we need to know about added descriptors. */
2487 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2489 __virtio16 avail_idx;
2492 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2494 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2495 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2496 r = vhost_update_used_flags(vq);
2498 vq_err(vq, "Failed to enable notification at %p: %d\n",
2499 &vq->used->flags, r);
2503 r = vhost_update_avail_event(vq, vq->avail_idx);
2505 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2506 vhost_avail_event(vq), r);
2510 /* They could have slipped one in as we were doing that: make
2511 * sure it's written, then check again. */
2513 r = vhost_get_avail_idx(vq, &avail_idx);
2515 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2516 &vq->avail->idx, r);
2520 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2522 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2524 /* We don't need to be notified again. */
2525 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2529 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2531 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2532 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2533 r = vhost_update_used_flags(vq);
2535 vq_err(vq, "Failed to enable notification at %p: %d\n",
2536 &vq->used->flags, r);
2539 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2541 /* Create a new message. */
2542 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2544 struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2548 /* Make sure all padding within the structure is initialized. */
2549 memset(&node->msg, 0, sizeof node->msg);
2551 node->msg.type = type;
2554 EXPORT_SYMBOL_GPL(vhost_new_msg);
2556 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2557 struct vhost_msg_node *node)
2559 spin_lock(&dev->iotlb_lock);
2560 list_add_tail(&node->node, head);
2561 spin_unlock(&dev->iotlb_lock);
2563 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2565 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2567 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2568 struct list_head *head)
2570 struct vhost_msg_node *node = NULL;
2572 spin_lock(&dev->iotlb_lock);
2573 if (!list_empty(head)) {
2574 node = list_first_entry(head, struct vhost_msg_node,
2576 list_del(&node->node);
2578 spin_unlock(&dev->iotlb_lock);
2582 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2585 static int __init vhost_init(void)
2590 static void __exit vhost_exit(void)
2594 module_init(vhost_init);
2595 module_exit(vhost_exit);
2597 MODULE_VERSION("0.0.1");
2598 MODULE_LICENSE("GPL v2");
2599 MODULE_AUTHOR("Michael S. Tsirkin");
2600 MODULE_DESCRIPTION("Host kernel accelerator for virtio");