1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (C) 2009 Red Hat, Inc.
3 * Copyright (C) 2006 Rusty Russell IBM Corporation
7 * Inspiration, some code, and most witty comments come from
8 * Documentation/virtual/lguest/lguest.c, by Rusty Russell
10 * Generic code for virtio server in host kernel.
13 #include <linux/eventfd.h>
14 #include <linux/vhost.h>
15 #include <linux/uio.h>
17 #include <linux/mmu_context.h>
18 #include <linux/miscdevice.h>
19 #include <linux/mutex.h>
20 #include <linux/poll.h>
21 #include <linux/file.h>
22 #include <linux/highmem.h>
23 #include <linux/slab.h>
24 #include <linux/vmalloc.h>
25 #include <linux/kthread.h>
26 #include <linux/cgroup.h>
27 #include <linux/module.h>
28 #include <linux/sort.h>
29 #include <linux/sched/mm.h>
30 #include <linux/sched/signal.h>
31 #include <linux/interval_tree_generic.h>
32 #include <linux/nospec.h>
33 #include <linux/kcov.h>
37 static ushort max_mem_regions = 64;
38 module_param(max_mem_regions, ushort, 0444);
39 MODULE_PARM_DESC(max_mem_regions,
40 "Maximum number of memory regions in memory map. (default: 64)");
41 static int max_iotlb_entries = 2048;
42 module_param(max_iotlb_entries, int, 0444);
43 MODULE_PARM_DESC(max_iotlb_entries,
44 "Maximum number of iotlb entries. (default: 2048)");
47 VHOST_MEMORY_F_LOG = 0x1,
50 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
51 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
53 INTERVAL_TREE_DEFINE(struct vhost_umem_node,
54 rb, __u64, __subtree_last,
55 START, LAST, static inline, vhost_umem_interval_tree);
57 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
58 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
60 vq->user_be = !virtio_legacy_is_little_endian();
63 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
68 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
73 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
75 struct vhost_vring_state s;
80 if (copy_from_user(&s, argp, sizeof(s)))
83 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
84 s.num != VHOST_VRING_BIG_ENDIAN)
87 if (s.num == VHOST_VRING_BIG_ENDIAN)
88 vhost_enable_cross_endian_big(vq);
90 vhost_enable_cross_endian_little(vq);
95 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
98 struct vhost_vring_state s = {
103 if (copy_to_user(argp, &s, sizeof(s)))
109 static void vhost_init_is_le(struct vhost_virtqueue *vq)
111 /* Note for legacy virtio: user_be is initialized at reset time
112 * according to the host endianness. If userspace does not set an
113 * explicit endianness, the default behavior is native endian, as
114 * expected by legacy virtio.
116 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
119 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
123 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
128 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
134 static void vhost_init_is_le(struct vhost_virtqueue *vq)
136 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
137 || virtio_legacy_is_little_endian();
139 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
141 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
143 vhost_init_is_le(vq);
146 struct vhost_flush_struct {
147 struct vhost_work work;
148 struct completion wait_event;
151 static void vhost_flush_work(struct vhost_work *work)
153 struct vhost_flush_struct *s;
155 s = container_of(work, struct vhost_flush_struct, work);
156 complete(&s->wait_event);
159 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
162 struct vhost_poll *poll;
164 poll = container_of(pt, struct vhost_poll, table);
166 add_wait_queue(wqh, &poll->wait);
169 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
172 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
174 if (!(key_to_poll(key) & poll->mask))
177 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;
337 mm_segment_t oldfs = get_fs();
343 /* mb paired w/ kthread_stop */
344 set_current_state(TASK_INTERRUPTIBLE);
346 if (kthread_should_stop()) {
347 __set_current_state(TASK_RUNNING);
351 node = llist_del_all(&dev->work_list);
355 node = llist_reverse_order(node);
356 /* make sure flag is seen after deletion */
358 llist_for_each_entry_safe(work, work_next, node, node) {
359 clear_bit(VHOST_WORK_QUEUED, &work->flags);
360 __set_current_state(TASK_RUNNING);
361 kcov_remote_start_common(dev->kcov_handle);
373 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
383 /* Helper to allocate iovec buffers for all vqs. */
384 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
386 struct vhost_virtqueue *vq;
389 for (i = 0; i < dev->nvqs; ++i) {
391 vq->indirect = kmalloc_array(UIO_MAXIOV,
392 sizeof(*vq->indirect),
394 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
396 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
398 if (!vq->indirect || !vq->log || !vq->heads)
405 vhost_vq_free_iovecs(dev->vqs[i]);
409 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
413 for (i = 0; i < dev->nvqs; ++i)
414 vhost_vq_free_iovecs(dev->vqs[i]);
417 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
418 int pkts, int total_len)
420 struct vhost_dev *dev = vq->dev;
422 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
423 pkts >= dev->weight) {
424 vhost_poll_queue(&vq->poll);
430 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
432 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
435 size_t event __maybe_unused =
436 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
438 return sizeof(*vq->avail) +
439 sizeof(*vq->avail->ring) * num + event;
442 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
445 size_t event __maybe_unused =
446 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
448 return sizeof(*vq->used) +
449 sizeof(*vq->used->ring) * num + event;
452 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
455 return sizeof(*vq->desc) * num;
458 void vhost_dev_init(struct vhost_dev *dev,
459 struct vhost_virtqueue **vqs, int nvqs,
460 int iov_limit, int weight, int byte_weight)
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 init_llist_head(&dev->work_list);
477 init_waitqueue_head(&dev->wait);
478 INIT_LIST_HEAD(&dev->read_list);
479 INIT_LIST_HEAD(&dev->pending_list);
480 spin_lock_init(&dev->iotlb_lock);
483 for (i = 0; i < dev->nvqs; ++i) {
489 mutex_init(&vq->mutex);
490 vhost_vq_reset(dev, vq);
492 vhost_poll_init(&vq->poll, vq->handle_kick,
496 EXPORT_SYMBOL_GPL(vhost_dev_init);
498 /* Caller should have device mutex */
499 long vhost_dev_check_owner(struct vhost_dev *dev)
501 /* Are you the owner? If not, I don't think you mean to do that */
502 return dev->mm == current->mm ? 0 : -EPERM;
504 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
506 struct vhost_attach_cgroups_struct {
507 struct vhost_work work;
508 struct task_struct *owner;
512 static void vhost_attach_cgroups_work(struct vhost_work *work)
514 struct vhost_attach_cgroups_struct *s;
516 s = container_of(work, struct vhost_attach_cgroups_struct, work);
517 s->ret = cgroup_attach_task_all(s->owner, current);
520 static int vhost_attach_cgroups(struct vhost_dev *dev)
522 struct vhost_attach_cgroups_struct attach;
524 attach.owner = current;
525 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
526 vhost_work_queue(dev, &attach.work);
527 vhost_work_flush(dev, &attach.work);
531 /* Caller should have device mutex */
532 bool vhost_dev_has_owner(struct vhost_dev *dev)
536 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
538 /* Caller should have device mutex */
539 long vhost_dev_set_owner(struct vhost_dev *dev)
541 struct task_struct *worker;
544 /* Is there an owner already? */
545 if (vhost_dev_has_owner(dev)) {
550 /* No owner, become one */
551 dev->mm = get_task_mm(current);
552 dev->kcov_handle = kcov_common_handle();
553 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
554 if (IS_ERR(worker)) {
555 err = PTR_ERR(worker);
559 dev->worker = worker;
560 wake_up_process(worker); /* avoid contributing to loadavg */
562 err = vhost_attach_cgroups(dev);
566 err = vhost_dev_alloc_iovecs(dev);
572 kthread_stop(worker);
578 dev->kcov_handle = 0;
582 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
584 struct vhost_umem *vhost_dev_reset_owner_prepare(void)
586 return kvzalloc(sizeof(struct vhost_umem), GFP_KERNEL);
588 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
590 /* Caller should have device mutex */
591 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_umem *umem)
595 vhost_dev_cleanup(dev);
597 /* Restore memory to default empty mapping. */
598 INIT_LIST_HEAD(&umem->umem_list);
600 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
601 * VQs aren't running.
603 for (i = 0; i < dev->nvqs; ++i)
604 dev->vqs[i]->umem = umem;
606 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
608 void vhost_dev_stop(struct vhost_dev *dev)
612 for (i = 0; i < dev->nvqs; ++i) {
613 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
614 vhost_poll_stop(&dev->vqs[i]->poll);
615 vhost_poll_flush(&dev->vqs[i]->poll);
619 EXPORT_SYMBOL_GPL(vhost_dev_stop);
621 static void vhost_umem_free(struct vhost_umem *umem,
622 struct vhost_umem_node *node)
624 vhost_umem_interval_tree_remove(node, &umem->umem_tree);
625 list_del(&node->link);
630 static void vhost_umem_clean(struct vhost_umem *umem)
632 struct vhost_umem_node *node, *tmp;
637 list_for_each_entry_safe(node, tmp, &umem->umem_list, link)
638 vhost_umem_free(umem, node);
643 static void vhost_clear_msg(struct vhost_dev *dev)
645 struct vhost_msg_node *node, *n;
647 spin_lock(&dev->iotlb_lock);
649 list_for_each_entry_safe(node, n, &dev->read_list, node) {
650 list_del(&node->node);
654 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
655 list_del(&node->node);
659 spin_unlock(&dev->iotlb_lock);
662 void vhost_dev_cleanup(struct vhost_dev *dev)
666 for (i = 0; i < dev->nvqs; ++i) {
667 if (dev->vqs[i]->error_ctx)
668 eventfd_ctx_put(dev->vqs[i]->error_ctx);
669 if (dev->vqs[i]->kick)
670 fput(dev->vqs[i]->kick);
671 if (dev->vqs[i]->call_ctx)
672 eventfd_ctx_put(dev->vqs[i]->call_ctx);
673 vhost_vq_reset(dev, dev->vqs[i]);
675 vhost_dev_free_iovecs(dev);
677 eventfd_ctx_put(dev->log_ctx);
679 /* No one will access memory at this point */
680 vhost_umem_clean(dev->umem);
682 vhost_umem_clean(dev->iotlb);
684 vhost_clear_msg(dev);
685 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
686 WARN_ON(!llist_empty(&dev->work_list));
688 kthread_stop(dev->worker);
690 dev->kcov_handle = 0;
696 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
698 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
700 u64 a = addr / VHOST_PAGE_SIZE / 8;
702 /* Make sure 64 bit math will not overflow. */
703 if (a > ULONG_MAX - (unsigned long)log_base ||
704 a + (unsigned long)log_base > ULONG_MAX)
707 return access_ok(log_base + a,
708 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
711 static bool vhost_overflow(u64 uaddr, u64 size)
713 /* Make sure 64 bit math will not overflow. */
714 return uaddr > ULONG_MAX || size > ULONG_MAX || uaddr > ULONG_MAX - size;
717 /* Caller should have vq mutex and device mutex. */
718 static bool vq_memory_access_ok(void __user *log_base, struct vhost_umem *umem,
721 struct vhost_umem_node *node;
726 list_for_each_entry(node, &umem->umem_list, link) {
727 unsigned long a = node->userspace_addr;
729 if (vhost_overflow(node->userspace_addr, node->size))
733 if (!access_ok((void __user *)a,
736 else if (log_all && !log_access_ok(log_base,
744 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
745 u64 addr, unsigned int size,
748 const struct vhost_umem_node *node = vq->meta_iotlb[type];
753 return (void *)(uintptr_t)(node->userspace_addr + addr - node->start);
756 /* Can we switch to this memory table? */
757 /* Caller should have device mutex but not vq mutex */
758 static bool memory_access_ok(struct vhost_dev *d, struct vhost_umem *umem,
763 for (i = 0; i < d->nvqs; ++i) {
767 mutex_lock(&d->vqs[i]->mutex);
768 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
769 /* If ring is inactive, will check when it's enabled. */
770 if (d->vqs[i]->private_data)
771 ok = vq_memory_access_ok(d->vqs[i]->log_base,
775 mutex_unlock(&d->vqs[i]->mutex);
782 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
783 struct iovec iov[], int iov_size, int access);
785 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
786 const void *from, unsigned size)
791 return __copy_to_user(to, from, size);
793 /* This function should be called after iotlb
794 * prefetch, which means we're sure that all vq
795 * could be access through iotlb. So -EAGAIN should
796 * not happen in this case.
799 void __user *uaddr = vhost_vq_meta_fetch(vq,
800 (u64)(uintptr_t)to, size,
804 return __copy_to_user(uaddr, from, size);
806 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
807 ARRAY_SIZE(vq->iotlb_iov),
811 iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
812 ret = copy_to_iter(from, size, &t);
820 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
821 void __user *from, unsigned size)
826 return __copy_from_user(to, from, size);
828 /* This function should be called after iotlb
829 * prefetch, which means we're sure that vq
830 * could be access through iotlb. So -EAGAIN should
831 * not happen in this case.
833 void __user *uaddr = vhost_vq_meta_fetch(vq,
834 (u64)(uintptr_t)from, size,
839 return __copy_from_user(to, uaddr, size);
841 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
842 ARRAY_SIZE(vq->iotlb_iov),
845 vq_err(vq, "IOTLB translation failure: uaddr "
846 "%p size 0x%llx\n", from,
847 (unsigned long long) size);
850 iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
851 ret = copy_from_iter(to, size, &f);
860 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
861 void __user *addr, unsigned int size,
866 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
867 ARRAY_SIZE(vq->iotlb_iov),
870 vq_err(vq, "IOTLB translation failure: uaddr "
871 "%p size 0x%llx\n", addr,
872 (unsigned long long) size);
876 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
877 vq_err(vq, "Non atomic userspace memory access: uaddr "
878 "%p size 0x%llx\n", addr,
879 (unsigned long long) size);
883 return vq->iotlb_iov[0].iov_base;
886 /* This function should be called after iotlb
887 * prefetch, which means we're sure that vq
888 * could be access through iotlb. So -EAGAIN should
889 * not happen in this case.
891 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
892 void *addr, unsigned int size,
895 void __user *uaddr = vhost_vq_meta_fetch(vq,
896 (u64)(uintptr_t)addr, size, type);
900 return __vhost_get_user_slow(vq, addr, size, type);
903 #define vhost_put_user(vq, x, ptr) \
907 ret = __put_user(x, ptr); \
909 __typeof__(ptr) to = \
910 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
911 sizeof(*ptr), VHOST_ADDR_USED); \
913 ret = __put_user(x, to); \
920 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
922 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
923 vhost_avail_event(vq));
926 static inline int vhost_put_used(struct vhost_virtqueue *vq,
927 struct vring_used_elem *head, int idx,
930 return vhost_copy_to_user(vq, vq->used->ring + idx, head,
931 count * sizeof(*head));
934 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
937 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
941 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
944 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
948 #define vhost_get_user(vq, x, ptr, type) \
952 ret = __get_user(x, ptr); \
954 __typeof__(ptr) from = \
955 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
959 ret = __get_user(x, from); \
966 #define vhost_get_avail(vq, x, ptr) \
967 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
969 #define vhost_get_used(vq, x, ptr) \
970 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
972 static void vhost_dev_lock_vqs(struct vhost_dev *d)
975 for (i = 0; i < d->nvqs; ++i)
976 mutex_lock_nested(&d->vqs[i]->mutex, i);
979 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
982 for (i = 0; i < d->nvqs; ++i)
983 mutex_unlock(&d->vqs[i]->mutex);
986 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
989 return vhost_get_avail(vq, *idx, &vq->avail->idx);
992 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
993 __virtio16 *head, int idx)
995 return vhost_get_avail(vq, *head,
996 &vq->avail->ring[idx & (vq->num - 1)]);
999 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1002 return vhost_get_avail(vq, *flags, &vq->avail->flags);
1005 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1008 return vhost_get_avail(vq, *event, vhost_used_event(vq));
1011 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1014 return vhost_get_used(vq, *idx, &vq->used->idx);
1017 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1018 struct vring_desc *desc, int idx)
1020 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1023 static int vhost_new_umem_range(struct vhost_umem *umem,
1024 u64 start, u64 size, u64 end,
1025 u64 userspace_addr, int perm)
1027 struct vhost_umem_node *tmp, *node;
1032 node = kmalloc(sizeof(*node), GFP_ATOMIC);
1036 if (umem->numem == max_iotlb_entries) {
1037 tmp = list_first_entry(&umem->umem_list, typeof(*tmp), link);
1038 vhost_umem_free(umem, tmp);
1041 node->start = start;
1044 node->userspace_addr = userspace_addr;
1046 INIT_LIST_HEAD(&node->link);
1047 list_add_tail(&node->link, &umem->umem_list);
1048 vhost_umem_interval_tree_insert(node, &umem->umem_tree);
1054 static void vhost_del_umem_range(struct vhost_umem *umem,
1057 struct vhost_umem_node *node;
1059 while ((node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1061 vhost_umem_free(umem, node);
1064 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1065 struct vhost_iotlb_msg *msg)
1067 struct vhost_msg_node *node, *n;
1069 spin_lock(&d->iotlb_lock);
1071 list_for_each_entry_safe(node, n, &d->pending_list, node) {
1072 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1073 if (msg->iova <= vq_msg->iova &&
1074 msg->iova + msg->size - 1 >= vq_msg->iova &&
1075 vq_msg->type == VHOST_IOTLB_MISS) {
1076 vhost_poll_queue(&node->vq->poll);
1077 list_del(&node->node);
1082 spin_unlock(&d->iotlb_lock);
1085 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1087 unsigned long a = uaddr;
1089 /* Make sure 64 bit math will not overflow. */
1090 if (vhost_overflow(uaddr, size))
1093 if ((access & VHOST_ACCESS_RO) &&
1094 !access_ok((void __user *)a, size))
1096 if ((access & VHOST_ACCESS_WO) &&
1097 !access_ok((void __user *)a, size))
1102 static int vhost_process_iotlb_msg(struct vhost_dev *dev,
1103 struct vhost_iotlb_msg *msg)
1107 mutex_lock(&dev->mutex);
1108 vhost_dev_lock_vqs(dev);
1109 switch (msg->type) {
1110 case VHOST_IOTLB_UPDATE:
1115 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1119 vhost_vq_meta_reset(dev);
1120 if (vhost_new_umem_range(dev->iotlb, msg->iova, msg->size,
1121 msg->iova + msg->size - 1,
1122 msg->uaddr, msg->perm)) {
1126 vhost_iotlb_notify_vq(dev, msg);
1128 case VHOST_IOTLB_INVALIDATE:
1133 vhost_vq_meta_reset(dev);
1134 vhost_del_umem_range(dev->iotlb, msg->iova,
1135 msg->iova + msg->size - 1);
1142 vhost_dev_unlock_vqs(dev);
1143 mutex_unlock(&dev->mutex);
1147 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1148 struct iov_iter *from)
1150 struct vhost_iotlb_msg msg;
1154 ret = copy_from_iter(&type, sizeof(type), from);
1155 if (ret != sizeof(type)) {
1161 case VHOST_IOTLB_MSG:
1162 /* There maybe a hole after type for V1 message type,
1165 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1167 case VHOST_IOTLB_MSG_V2:
1168 offset = sizeof(__u32);
1175 iov_iter_advance(from, offset);
1176 ret = copy_from_iter(&msg, sizeof(msg), from);
1177 if (ret != sizeof(msg)) {
1181 if (vhost_process_iotlb_msg(dev, &msg)) {
1186 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1187 sizeof(struct vhost_msg_v2);
1191 EXPORT_SYMBOL(vhost_chr_write_iter);
1193 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1198 poll_wait(file, &dev->wait, wait);
1200 if (!list_empty(&dev->read_list))
1201 mask |= EPOLLIN | EPOLLRDNORM;
1205 EXPORT_SYMBOL(vhost_chr_poll);
1207 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1211 struct vhost_msg_node *node;
1213 unsigned size = sizeof(struct vhost_msg);
1215 if (iov_iter_count(to) < size)
1220 prepare_to_wait(&dev->wait, &wait,
1221 TASK_INTERRUPTIBLE);
1223 node = vhost_dequeue_msg(dev, &dev->read_list);
1230 if (signal_pending(current)) {
1243 finish_wait(&dev->wait, &wait);
1246 struct vhost_iotlb_msg *msg;
1247 void *start = &node->msg;
1249 switch (node->msg.type) {
1250 case VHOST_IOTLB_MSG:
1251 size = sizeof(node->msg);
1252 msg = &node->msg.iotlb;
1254 case VHOST_IOTLB_MSG_V2:
1255 size = sizeof(node->msg_v2);
1256 msg = &node->msg_v2.iotlb;
1263 ret = copy_to_iter(start, size, to);
1264 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1268 vhost_enqueue_msg(dev, &dev->pending_list, node);
1273 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1275 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1277 struct vhost_dev *dev = vq->dev;
1278 struct vhost_msg_node *node;
1279 struct vhost_iotlb_msg *msg;
1280 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1282 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1287 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1288 msg = &node->msg_v2.iotlb;
1290 msg = &node->msg.iotlb;
1293 msg->type = VHOST_IOTLB_MISS;
1297 vhost_enqueue_msg(dev, &dev->read_list, node);
1302 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1303 struct vring_desc __user *desc,
1304 struct vring_avail __user *avail,
1305 struct vring_used __user *used)
1308 return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1309 access_ok(avail, vhost_get_avail_size(vq, num)) &&
1310 access_ok(used, vhost_get_used_size(vq, num));
1313 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1314 const struct vhost_umem_node *node,
1317 int access = (type == VHOST_ADDR_USED) ?
1318 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1320 if (likely(node->perm & access))
1321 vq->meta_iotlb[type] = node;
1324 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1325 int access, u64 addr, u64 len, int type)
1327 const struct vhost_umem_node *node;
1328 struct vhost_umem *umem = vq->iotlb;
1329 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1331 if (vhost_vq_meta_fetch(vq, addr, len, type))
1335 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1338 if (node == NULL || node->start > addr) {
1339 vhost_iotlb_miss(vq, addr, access);
1341 } else if (!(node->perm & access)) {
1342 /* Report the possible access violation by
1343 * request another translation from userspace.
1348 size = node->size - addr + node->start;
1350 if (orig_addr == addr && size >= len)
1351 vhost_vq_meta_update(vq, node, type);
1360 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1362 unsigned int num = vq->num;
1367 return iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->desc,
1368 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1369 iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->avail,
1370 vhost_get_avail_size(vq, num),
1371 VHOST_ADDR_AVAIL) &&
1372 iotlb_access_ok(vq, VHOST_ACCESS_WO, (u64)(uintptr_t)vq->used,
1373 vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1375 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1377 /* Can we log writes? */
1378 /* Caller should have device mutex but not vq mutex */
1379 bool vhost_log_access_ok(struct vhost_dev *dev)
1381 return memory_access_ok(dev, dev->umem, 1);
1383 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1385 /* Verify access for write logging. */
1386 /* Caller should have vq mutex and device mutex */
1387 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1388 void __user *log_base)
1390 return vq_memory_access_ok(log_base, vq->umem,
1391 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1392 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
1393 vhost_get_used_size(vq, vq->num)));
1396 /* Can we start vq? */
1397 /* Caller should have vq mutex and device mutex */
1398 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1400 if (!vq_log_access_ok(vq, vq->log_base))
1403 /* Access validation occurs at prefetch time with IOTLB */
1407 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1409 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1411 static struct vhost_umem *vhost_umem_alloc(void)
1413 struct vhost_umem *umem = kvzalloc(sizeof(*umem), GFP_KERNEL);
1418 umem->umem_tree = RB_ROOT_CACHED;
1420 INIT_LIST_HEAD(&umem->umem_list);
1425 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1427 struct vhost_memory mem, *newmem;
1428 struct vhost_memory_region *region;
1429 struct vhost_umem *newumem, *oldumem;
1430 unsigned long size = offsetof(struct vhost_memory, regions);
1433 if (copy_from_user(&mem, m, size))
1437 if (mem.nregions > max_mem_regions)
1439 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1444 memcpy(newmem, &mem, size);
1445 if (copy_from_user(newmem->regions, m->regions,
1446 mem.nregions * sizeof *m->regions)) {
1451 newumem = vhost_umem_alloc();
1457 for (region = newmem->regions;
1458 region < newmem->regions + mem.nregions;
1460 if (vhost_new_umem_range(newumem,
1461 region->guest_phys_addr,
1462 region->memory_size,
1463 region->guest_phys_addr +
1464 region->memory_size - 1,
1465 region->userspace_addr,
1470 if (!memory_access_ok(d, newumem, 0))
1476 /* All memory accesses are done under some VQ mutex. */
1477 for (i = 0; i < d->nvqs; ++i) {
1478 mutex_lock(&d->vqs[i]->mutex);
1479 d->vqs[i]->umem = newumem;
1480 mutex_unlock(&d->vqs[i]->mutex);
1484 vhost_umem_clean(oldumem);
1488 vhost_umem_clean(newumem);
1493 static long vhost_vring_set_num(struct vhost_dev *d,
1494 struct vhost_virtqueue *vq,
1497 struct vhost_vring_state s;
1499 /* Resizing ring with an active backend?
1500 * You don't want to do that. */
1501 if (vq->private_data)
1504 if (copy_from_user(&s, argp, sizeof s))
1507 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
1514 static long vhost_vring_set_addr(struct vhost_dev *d,
1515 struct vhost_virtqueue *vq,
1518 struct vhost_vring_addr a;
1520 if (copy_from_user(&a, argp, sizeof a))
1522 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
1525 /* For 32bit, verify that the top 32bits of the user
1526 data are set to zero. */
1527 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1528 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1529 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
1532 /* Make sure it's safe to cast pointers to vring types. */
1533 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1534 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1535 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1536 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1537 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
1540 /* We only verify access here if backend is configured.
1541 * If it is not, we don't as size might not have been setup.
1542 * We will verify when backend is configured. */
1543 if (vq->private_data) {
1544 if (!vq_access_ok(vq, vq->num,
1545 (void __user *)(unsigned long)a.desc_user_addr,
1546 (void __user *)(unsigned long)a.avail_user_addr,
1547 (void __user *)(unsigned long)a.used_user_addr))
1550 /* Also validate log access for used ring if enabled. */
1551 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
1552 !log_access_ok(vq->log_base, a.log_guest_addr,
1554 vq->num * sizeof *vq->used->ring))
1558 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1559 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1560 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1561 vq->log_addr = a.log_guest_addr;
1562 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1567 static long vhost_vring_set_num_addr(struct vhost_dev *d,
1568 struct vhost_virtqueue *vq,
1574 mutex_lock(&vq->mutex);
1577 case VHOST_SET_VRING_NUM:
1578 r = vhost_vring_set_num(d, vq, argp);
1580 case VHOST_SET_VRING_ADDR:
1581 r = vhost_vring_set_addr(d, vq, argp);
1587 mutex_unlock(&vq->mutex);
1591 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1593 struct file *eventfp, *filep = NULL;
1594 bool pollstart = false, pollstop = false;
1595 struct eventfd_ctx *ctx = NULL;
1596 u32 __user *idxp = argp;
1597 struct vhost_virtqueue *vq;
1598 struct vhost_vring_state s;
1599 struct vhost_vring_file f;
1603 r = get_user(idx, idxp);
1609 idx = array_index_nospec(idx, d->nvqs);
1612 if (ioctl == VHOST_SET_VRING_NUM ||
1613 ioctl == VHOST_SET_VRING_ADDR) {
1614 return vhost_vring_set_num_addr(d, vq, ioctl, argp);
1617 mutex_lock(&vq->mutex);
1620 case VHOST_SET_VRING_BASE:
1621 /* Moving base with an active backend?
1622 * You don't want to do that. */
1623 if (vq->private_data) {
1627 if (copy_from_user(&s, argp, sizeof s)) {
1631 if (s.num > 0xffff) {
1635 vq->last_avail_idx = s.num;
1636 /* Forget the cached index value. */
1637 vq->avail_idx = vq->last_avail_idx;
1639 case VHOST_GET_VRING_BASE:
1641 s.num = vq->last_avail_idx;
1642 if (copy_to_user(argp, &s, sizeof s))
1645 case VHOST_SET_VRING_KICK:
1646 if (copy_from_user(&f, argp, sizeof f)) {
1650 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1651 if (IS_ERR(eventfp)) {
1652 r = PTR_ERR(eventfp);
1655 if (eventfp != vq->kick) {
1656 pollstop = (filep = vq->kick) != NULL;
1657 pollstart = (vq->kick = eventfp) != NULL;
1661 case VHOST_SET_VRING_CALL:
1662 if (copy_from_user(&f, argp, sizeof f)) {
1666 ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1671 swap(ctx, vq->call_ctx);
1673 case VHOST_SET_VRING_ERR:
1674 if (copy_from_user(&f, argp, sizeof f)) {
1678 ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1683 swap(ctx, vq->error_ctx);
1685 case VHOST_SET_VRING_ENDIAN:
1686 r = vhost_set_vring_endian(vq, argp);
1688 case VHOST_GET_VRING_ENDIAN:
1689 r = vhost_get_vring_endian(vq, idx, argp);
1691 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1692 if (copy_from_user(&s, argp, sizeof(s))) {
1696 vq->busyloop_timeout = s.num;
1698 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1700 s.num = vq->busyloop_timeout;
1701 if (copy_to_user(argp, &s, sizeof(s)))
1708 if (pollstop && vq->handle_kick)
1709 vhost_poll_stop(&vq->poll);
1711 if (!IS_ERR_OR_NULL(ctx))
1712 eventfd_ctx_put(ctx);
1716 if (pollstart && vq->handle_kick)
1717 r = vhost_poll_start(&vq->poll, vq->kick);
1719 mutex_unlock(&vq->mutex);
1721 if (pollstop && vq->handle_kick)
1722 vhost_poll_flush(&vq->poll);
1725 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1727 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1729 struct vhost_umem *niotlb, *oiotlb;
1732 niotlb = vhost_umem_alloc();
1739 for (i = 0; i < d->nvqs; ++i) {
1740 struct vhost_virtqueue *vq = d->vqs[i];
1742 mutex_lock(&vq->mutex);
1744 __vhost_vq_meta_reset(vq);
1745 mutex_unlock(&vq->mutex);
1748 vhost_umem_clean(oiotlb);
1752 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1754 /* Caller must have device mutex */
1755 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1757 struct eventfd_ctx *ctx;
1762 /* If you are not the owner, you can become one */
1763 if (ioctl == VHOST_SET_OWNER) {
1764 r = vhost_dev_set_owner(d);
1768 /* You must be the owner to do anything else */
1769 r = vhost_dev_check_owner(d);
1774 case VHOST_SET_MEM_TABLE:
1775 r = vhost_set_memory(d, argp);
1777 case VHOST_SET_LOG_BASE:
1778 if (copy_from_user(&p, argp, sizeof p)) {
1782 if ((u64)(unsigned long)p != p) {
1786 for (i = 0; i < d->nvqs; ++i) {
1787 struct vhost_virtqueue *vq;
1788 void __user *base = (void __user *)(unsigned long)p;
1790 mutex_lock(&vq->mutex);
1791 /* If ring is inactive, will check when it's enabled. */
1792 if (vq->private_data && !vq_log_access_ok(vq, base))
1795 vq->log_base = base;
1796 mutex_unlock(&vq->mutex);
1799 case VHOST_SET_LOG_FD:
1800 r = get_user(fd, (int __user *)argp);
1803 ctx = fd == -1 ? NULL : eventfd_ctx_fdget(fd);
1808 swap(ctx, d->log_ctx);
1809 for (i = 0; i < d->nvqs; ++i) {
1810 mutex_lock(&d->vqs[i]->mutex);
1811 d->vqs[i]->log_ctx = d->log_ctx;
1812 mutex_unlock(&d->vqs[i]->mutex);
1815 eventfd_ctx_put(ctx);
1824 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1826 /* TODO: This is really inefficient. We need something like get_user()
1827 * (instruction directly accesses the data, with an exception table entry
1828 * returning -EFAULT). See Documentation/x86/exception-tables.rst.
1830 static int set_bit_to_user(int nr, void __user *addr)
1832 unsigned long log = (unsigned long)addr;
1835 int bit = nr + (log % PAGE_SIZE) * 8;
1838 r = get_user_pages_fast(log, 1, FOLL_WRITE, &page);
1842 base = kmap_atomic(page);
1844 kunmap_atomic(base);
1845 set_page_dirty_lock(page);
1850 static int log_write(void __user *log_base,
1851 u64 write_address, u64 write_length)
1853 u64 write_page = write_address / VHOST_PAGE_SIZE;
1858 write_length += write_address % VHOST_PAGE_SIZE;
1860 u64 base = (u64)(unsigned long)log_base;
1861 u64 log = base + write_page / 8;
1862 int bit = write_page % 8;
1863 if ((u64)(unsigned long)log != log)
1865 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1868 if (write_length <= VHOST_PAGE_SIZE)
1870 write_length -= VHOST_PAGE_SIZE;
1876 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1878 struct vhost_umem *umem = vq->umem;
1879 struct vhost_umem_node *u;
1880 u64 start, end, l, min;
1886 /* More than one GPAs can be mapped into a single HVA. So
1887 * iterate all possible umems here to be safe.
1889 list_for_each_entry(u, &umem->umem_list, link) {
1890 if (u->userspace_addr > hva - 1 + len ||
1891 u->userspace_addr - 1 + u->size < hva)
1893 start = max(u->userspace_addr, hva);
1894 end = min(u->userspace_addr - 1 + u->size,
1896 l = end - start + 1;
1897 r = log_write(vq->log_base,
1898 u->start + start - u->userspace_addr,
1916 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1918 struct iovec iov[64];
1922 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1924 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1925 len, iov, 64, VHOST_ACCESS_WO);
1929 for (i = 0; i < ret; i++) {
1930 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1939 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1940 unsigned int log_num, u64 len, struct iovec *iov, int count)
1944 /* Make sure data written is seen before log. */
1948 for (i = 0; i < count; i++) {
1949 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1957 for (i = 0; i < log_num; ++i) {
1958 u64 l = min(log[i].len, len);
1959 r = log_write(vq->log_base, log[i].addr, l);
1965 eventfd_signal(vq->log_ctx, 1);
1969 /* Length written exceeds what we have stored. This is a bug. */
1973 EXPORT_SYMBOL_GPL(vhost_log_write);
1975 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1978 if (vhost_put_used_flags(vq))
1980 if (unlikely(vq->log_used)) {
1981 /* Make sure the flag is seen before log. */
1983 /* Log used flag write. */
1984 used = &vq->used->flags;
1985 log_used(vq, (used - (void __user *)vq->used),
1986 sizeof vq->used->flags);
1988 eventfd_signal(vq->log_ctx, 1);
1993 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1995 if (vhost_put_avail_event(vq))
1997 if (unlikely(vq->log_used)) {
1999 /* Make sure the event is seen before log. */
2001 /* Log avail event write */
2002 used = vhost_avail_event(vq);
2003 log_used(vq, (used - (void __user *)vq->used),
2004 sizeof *vhost_avail_event(vq));
2006 eventfd_signal(vq->log_ctx, 1);
2011 int vhost_vq_init_access(struct vhost_virtqueue *vq)
2013 __virtio16 last_used_idx;
2015 bool is_le = vq->is_le;
2017 if (!vq->private_data)
2020 vhost_init_is_le(vq);
2022 r = vhost_update_used_flags(vq);
2025 vq->signalled_used_valid = false;
2027 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
2031 r = vhost_get_used_idx(vq, &last_used_idx);
2033 vq_err(vq, "Can't access used idx at %p\n",
2037 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2044 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2046 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2047 struct iovec iov[], int iov_size, int access)
2049 const struct vhost_umem_node *node;
2050 struct vhost_dev *dev = vq->dev;
2051 struct vhost_umem *umem = dev->iotlb ? dev->iotlb : dev->umem;
2056 while ((u64)len > s) {
2058 if (unlikely(ret >= iov_size)) {
2063 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
2064 addr, addr + len - 1);
2065 if (node == NULL || node->start > addr) {
2066 if (umem != dev->iotlb) {
2072 } else if (!(node->perm & access)) {
2078 size = node->size - addr + node->start;
2079 _iov->iov_len = min((u64)len - s, size);
2080 _iov->iov_base = (void __user *)(unsigned long)
2081 (node->userspace_addr + addr - node->start);
2088 vhost_iotlb_miss(vq, addr, access);
2092 /* Each buffer in the virtqueues is actually a chain of descriptors. This
2093 * function returns the next descriptor in the chain,
2094 * or -1U if we're at the end. */
2095 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2099 /* If this descriptor says it doesn't chain, we're done. */
2100 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2103 /* Check they're not leading us off end of descriptors. */
2104 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2108 static int get_indirect(struct vhost_virtqueue *vq,
2109 struct iovec iov[], unsigned int iov_size,
2110 unsigned int *out_num, unsigned int *in_num,
2111 struct vhost_log *log, unsigned int *log_num,
2112 struct vring_desc *indirect)
2114 struct vring_desc desc;
2115 unsigned int i = 0, count, found = 0;
2116 u32 len = vhost32_to_cpu(vq, indirect->len);
2117 struct iov_iter from;
2121 if (unlikely(len % sizeof desc)) {
2122 vq_err(vq, "Invalid length in indirect descriptor: "
2123 "len 0x%llx not multiple of 0x%zx\n",
2124 (unsigned long long)len,
2129 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2130 UIO_MAXIOV, VHOST_ACCESS_RO);
2131 if (unlikely(ret < 0)) {
2133 vq_err(vq, "Translation failure %d in indirect.\n", ret);
2136 iov_iter_init(&from, READ, vq->indirect, ret, len);
2138 /* We will use the result as an address to read from, so most
2139 * architectures only need a compiler barrier here. */
2140 read_barrier_depends();
2142 count = len / sizeof desc;
2143 /* Buffers are chained via a 16 bit next field, so
2144 * we can have at most 2^16 of these. */
2145 if (unlikely(count > USHRT_MAX + 1)) {
2146 vq_err(vq, "Indirect buffer length too big: %d\n",
2152 unsigned iov_count = *in_num + *out_num;
2153 if (unlikely(++found > count)) {
2154 vq_err(vq, "Loop detected: last one at %u "
2155 "indirect size %u\n",
2159 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2160 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2161 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2164 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2165 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2166 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2170 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2171 access = VHOST_ACCESS_WO;
2173 access = VHOST_ACCESS_RO;
2175 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2176 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2177 iov_size - iov_count, access);
2178 if (unlikely(ret < 0)) {
2180 vq_err(vq, "Translation failure %d indirect idx %d\n",
2184 /* If this is an input descriptor, increment that count. */
2185 if (access == VHOST_ACCESS_WO) {
2187 if (unlikely(log && ret)) {
2188 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2189 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2193 /* If it's an output descriptor, they're all supposed
2194 * to come before any input descriptors. */
2195 if (unlikely(*in_num)) {
2196 vq_err(vq, "Indirect descriptor "
2197 "has out after in: idx %d\n", i);
2202 } while ((i = next_desc(vq, &desc)) != -1);
2206 /* This looks in the virtqueue and for the first available buffer, and converts
2207 * it to an iovec for convenient access. Since descriptors consist of some
2208 * number of output then some number of input descriptors, it's actually two
2209 * iovecs, but we pack them into one and note how many of each there were.
2211 * This function returns the descriptor number found, or vq->num (which is
2212 * never a valid descriptor number) if none was found. A negative code is
2213 * returned on error. */
2214 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2215 struct iovec iov[], unsigned int iov_size,
2216 unsigned int *out_num, unsigned int *in_num,
2217 struct vhost_log *log, unsigned int *log_num)
2219 struct vring_desc desc;
2220 unsigned int i, head, found = 0;
2222 __virtio16 avail_idx;
2223 __virtio16 ring_head;
2226 /* Check it isn't doing very strange things with descriptor numbers. */
2227 last_avail_idx = vq->last_avail_idx;
2229 if (vq->avail_idx == vq->last_avail_idx) {
2230 if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
2231 vq_err(vq, "Failed to access avail idx at %p\n",
2235 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2237 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2238 vq_err(vq, "Guest moved used index from %u to %u",
2239 last_avail_idx, vq->avail_idx);
2243 /* If there's nothing new since last we looked, return
2246 if (vq->avail_idx == last_avail_idx)
2249 /* Only get avail ring entries after they have been
2255 /* Grab the next descriptor number they're advertising, and increment
2256 * the index we've seen. */
2257 if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
2258 vq_err(vq, "Failed to read head: idx %d address %p\n",
2260 &vq->avail->ring[last_avail_idx % vq->num]);
2264 head = vhost16_to_cpu(vq, ring_head);
2266 /* If their number is silly, that's an error. */
2267 if (unlikely(head >= vq->num)) {
2268 vq_err(vq, "Guest says index %u > %u is available",
2273 /* When we start there are none of either input nor output. */
2274 *out_num = *in_num = 0;
2280 unsigned iov_count = *in_num + *out_num;
2281 if (unlikely(i >= vq->num)) {
2282 vq_err(vq, "Desc index is %u > %u, head = %u",
2286 if (unlikely(++found > vq->num)) {
2287 vq_err(vq, "Loop detected: last one at %u "
2288 "vq size %u head %u\n",
2292 ret = vhost_get_desc(vq, &desc, i);
2293 if (unlikely(ret)) {
2294 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2298 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2299 ret = get_indirect(vq, iov, iov_size,
2301 log, log_num, &desc);
2302 if (unlikely(ret < 0)) {
2304 vq_err(vq, "Failure detected "
2305 "in indirect descriptor at idx %d\n", i);
2311 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2312 access = VHOST_ACCESS_WO;
2314 access = VHOST_ACCESS_RO;
2315 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2316 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2317 iov_size - iov_count, access);
2318 if (unlikely(ret < 0)) {
2320 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2324 if (access == VHOST_ACCESS_WO) {
2325 /* If this is an input descriptor,
2326 * increment that count. */
2328 if (unlikely(log && ret)) {
2329 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2330 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2334 /* If it's an output descriptor, they're all supposed
2335 * to come before any input descriptors. */
2336 if (unlikely(*in_num)) {
2337 vq_err(vq, "Descriptor has out after in: "
2343 } while ((i = next_desc(vq, &desc)) != -1);
2345 /* On success, increment avail index. */
2346 vq->last_avail_idx++;
2348 /* Assume notifications from guest are disabled at this point,
2349 * if they aren't we would need to update avail_event index. */
2350 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2353 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2355 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2356 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2358 vq->last_avail_idx -= n;
2360 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2362 /* After we've used one of their buffers, we tell them about it. We'll then
2363 * want to notify the guest, using eventfd. */
2364 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2366 struct vring_used_elem heads = {
2367 cpu_to_vhost32(vq, head),
2368 cpu_to_vhost32(vq, len)
2371 return vhost_add_used_n(vq, &heads, 1);
2373 EXPORT_SYMBOL_GPL(vhost_add_used);
2375 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2376 struct vring_used_elem *heads,
2379 struct vring_used_elem __user *used;
2383 start = vq->last_used_idx & (vq->num - 1);
2384 used = vq->used->ring + start;
2385 if (vhost_put_used(vq, heads, start, count)) {
2386 vq_err(vq, "Failed to write used");
2389 if (unlikely(vq->log_used)) {
2390 /* Make sure data is seen before log. */
2392 /* Log used ring entry write. */
2393 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2394 count * sizeof *used);
2396 old = vq->last_used_idx;
2397 new = (vq->last_used_idx += count);
2398 /* If the driver never bothers to signal in a very long while,
2399 * used index might wrap around. If that happens, invalidate
2400 * signalled_used index we stored. TODO: make sure driver
2401 * signals at least once in 2^16 and remove this. */
2402 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2403 vq->signalled_used_valid = false;
2407 /* After we've used one of their buffers, we tell them about it. We'll then
2408 * want to notify the guest, using eventfd. */
2409 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2414 start = vq->last_used_idx & (vq->num - 1);
2415 n = vq->num - start;
2417 r = __vhost_add_used_n(vq, heads, n);
2423 r = __vhost_add_used_n(vq, heads, count);
2425 /* Make sure buffer is written before we update index. */
2427 if (vhost_put_used_idx(vq)) {
2428 vq_err(vq, "Failed to increment used idx");
2431 if (unlikely(vq->log_used)) {
2432 /* Make sure used idx is seen before log. */
2434 /* Log used index update. */
2435 log_used(vq, offsetof(struct vring_used, idx),
2436 sizeof vq->used->idx);
2438 eventfd_signal(vq->log_ctx, 1);
2442 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2444 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2449 /* Flush out used index updates. This is paired
2450 * with the barrier that the Guest executes when enabling
2454 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2455 unlikely(vq->avail_idx == vq->last_avail_idx))
2458 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2460 if (vhost_get_avail_flags(vq, &flags)) {
2461 vq_err(vq, "Failed to get flags");
2464 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2466 old = vq->signalled_used;
2467 v = vq->signalled_used_valid;
2468 new = vq->signalled_used = vq->last_used_idx;
2469 vq->signalled_used_valid = true;
2474 if (vhost_get_used_event(vq, &event)) {
2475 vq_err(vq, "Failed to get used event idx");
2478 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2481 /* This actually signals the guest, using eventfd. */
2482 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2484 /* Signal the Guest tell them we used something up. */
2485 if (vq->call_ctx && vhost_notify(dev, vq))
2486 eventfd_signal(vq->call_ctx, 1);
2488 EXPORT_SYMBOL_GPL(vhost_signal);
2490 /* And here's the combo meal deal. Supersize me! */
2491 void vhost_add_used_and_signal(struct vhost_dev *dev,
2492 struct vhost_virtqueue *vq,
2493 unsigned int head, int len)
2495 vhost_add_used(vq, head, len);
2496 vhost_signal(dev, vq);
2498 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2500 /* multi-buffer version of vhost_add_used_and_signal */
2501 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2502 struct vhost_virtqueue *vq,
2503 struct vring_used_elem *heads, unsigned count)
2505 vhost_add_used_n(vq, heads, count);
2506 vhost_signal(dev, vq);
2508 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2510 /* return true if we're sure that avaiable ring is empty */
2511 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2513 __virtio16 avail_idx;
2516 if (vq->avail_idx != vq->last_avail_idx)
2519 r = vhost_get_avail_idx(vq, &avail_idx);
2522 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2524 return vq->avail_idx == vq->last_avail_idx;
2526 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2528 /* OK, now we need to know about added descriptors. */
2529 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2531 __virtio16 avail_idx;
2534 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2536 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2537 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2538 r = vhost_update_used_flags(vq);
2540 vq_err(vq, "Failed to enable notification at %p: %d\n",
2541 &vq->used->flags, r);
2545 r = vhost_update_avail_event(vq, vq->avail_idx);
2547 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2548 vhost_avail_event(vq), r);
2552 /* They could have slipped one in as we were doing that: make
2553 * sure it's written, then check again. */
2555 r = vhost_get_avail_idx(vq, &avail_idx);
2557 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2558 &vq->avail->idx, r);
2562 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2564 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2566 /* We don't need to be notified again. */
2567 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2571 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2573 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2574 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2575 r = vhost_update_used_flags(vq);
2577 vq_err(vq, "Failed to enable notification at %p: %d\n",
2578 &vq->used->flags, r);
2581 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2583 /* Create a new message. */
2584 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2586 struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2590 /* Make sure all padding within the structure is initialized. */
2591 memset(&node->msg, 0, sizeof node->msg);
2593 node->msg.type = type;
2596 EXPORT_SYMBOL_GPL(vhost_new_msg);
2598 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2599 struct vhost_msg_node *node)
2601 spin_lock(&dev->iotlb_lock);
2602 list_add_tail(&node->node, head);
2603 spin_unlock(&dev->iotlb_lock);
2605 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2607 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2609 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2610 struct list_head *head)
2612 struct vhost_msg_node *node = NULL;
2614 spin_lock(&dev->iotlb_lock);
2615 if (!list_empty(head)) {
2616 node = list_first_entry(head, struct vhost_msg_node,
2618 list_del(&node->node);
2620 spin_unlock(&dev->iotlb_lock);
2624 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2627 static int __init vhost_init(void)
2632 static void __exit vhost_exit(void)
2636 module_init(vhost_init);
2637 module_exit(vhost_exit);
2639 MODULE_VERSION("0.0.1");
2640 MODULE_LICENSE("GPL v2");
2641 MODULE_AUTHOR("Michael S. Tsirkin");
2642 MODULE_DESCRIPTION("Host kernel accelerator for virtio");