1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (C) 2009 Red Hat, Inc.
3 * Copyright (C) 2006 Rusty Russell IBM Corporation
5 * Author: Michael S. Tsirkin <mst@redhat.com>
7 * Inspiration, some code, and most witty comments come from
8 * Documentation/virtual/lguest/lguest.c, by Rusty Russell
10 * Generic code for virtio server in host kernel.
13 #include <linux/eventfd.h>
14 #include <linux/vhost.h>
15 #include <linux/uio.h>
17 #include <linux/mmu_context.h>
18 #include <linux/miscdevice.h>
19 #include <linux/mutex.h>
20 #include <linux/poll.h>
21 #include <linux/file.h>
22 #include <linux/highmem.h>
23 #include <linux/slab.h>
24 #include <linux/vmalloc.h>
25 #include <linux/kthread.h>
26 #include <linux/cgroup.h>
27 #include <linux/module.h>
28 #include <linux/sort.h>
29 #include <linux/sched/mm.h>
30 #include <linux/sched/signal.h>
31 #include <linux/interval_tree_generic.h>
32 #include <linux/nospec.h>
33 #include <linux/kcov.h>
37 static ushort max_mem_regions = 64;
38 module_param(max_mem_regions, ushort, 0444);
39 MODULE_PARM_DESC(max_mem_regions,
40 "Maximum number of memory regions in memory map. (default: 64)");
41 static int max_iotlb_entries = 2048;
42 module_param(max_iotlb_entries, int, 0444);
43 MODULE_PARM_DESC(max_iotlb_entries,
44 "Maximum number of iotlb entries. (default: 2048)");
47 VHOST_MEMORY_F_LOG = 0x1,
50 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
51 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
53 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
54 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
56 vq->user_be = !virtio_legacy_is_little_endian();
59 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
64 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
69 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
71 struct vhost_vring_state s;
76 if (copy_from_user(&s, argp, sizeof(s)))
79 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
80 s.num != VHOST_VRING_BIG_ENDIAN)
83 if (s.num == VHOST_VRING_BIG_ENDIAN)
84 vhost_enable_cross_endian_big(vq);
86 vhost_enable_cross_endian_little(vq);
91 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
94 struct vhost_vring_state s = {
99 if (copy_to_user(argp, &s, sizeof(s)))
105 static void vhost_init_is_le(struct vhost_virtqueue *vq)
107 /* Note for legacy virtio: user_be is initialized at reset time
108 * according to the host endianness. If userspace does not set an
109 * explicit endianness, the default behavior is native endian, as
110 * expected by legacy virtio.
112 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
115 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
119 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
124 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
130 static void vhost_init_is_le(struct vhost_virtqueue *vq)
132 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
133 || virtio_legacy_is_little_endian();
135 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
137 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
139 vhost_init_is_le(vq);
142 struct vhost_flush_struct {
143 struct vhost_work work;
144 struct completion wait_event;
147 static void vhost_flush_work(struct vhost_work *work)
149 struct vhost_flush_struct *s;
151 s = container_of(work, struct vhost_flush_struct, work);
152 complete(&s->wait_event);
155 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
158 struct vhost_poll *poll;
160 poll = container_of(pt, struct vhost_poll, table);
162 add_wait_queue(wqh, &poll->wait);
165 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
168 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
169 struct vhost_work *work = &poll->work;
171 if (!(key_to_poll(key) & poll->mask))
174 if (!poll->dev->use_worker)
177 vhost_poll_queue(poll);
182 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
184 clear_bit(VHOST_WORK_QUEUED, &work->flags);
187 EXPORT_SYMBOL_GPL(vhost_work_init);
189 /* Init poll structure */
190 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
191 __poll_t mask, struct vhost_dev *dev)
193 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
194 init_poll_funcptr(&poll->table, vhost_poll_func);
199 vhost_work_init(&poll->work, fn);
201 EXPORT_SYMBOL_GPL(vhost_poll_init);
203 /* Start polling a file. We add ourselves to file's wait queue. The caller must
204 * keep a reference to a file until after vhost_poll_stop is called. */
205 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
212 mask = vfs_poll(file, &poll->table);
214 vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
215 if (mask & EPOLLERR) {
216 vhost_poll_stop(poll);
222 EXPORT_SYMBOL_GPL(vhost_poll_start);
224 /* Stop polling a file. After this function returns, it becomes safe to drop the
225 * file reference. You must also flush afterwards. */
226 void vhost_poll_stop(struct vhost_poll *poll)
229 remove_wait_queue(poll->wqh, &poll->wait);
233 EXPORT_SYMBOL_GPL(vhost_poll_stop);
235 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
237 struct vhost_flush_struct flush;
240 init_completion(&flush.wait_event);
241 vhost_work_init(&flush.work, vhost_flush_work);
243 vhost_work_queue(dev, &flush.work);
244 wait_for_completion(&flush.wait_event);
247 EXPORT_SYMBOL_GPL(vhost_work_flush);
249 /* Flush any work that has been scheduled. When calling this, don't hold any
250 * locks that are also used by the callback. */
251 void vhost_poll_flush(struct vhost_poll *poll)
253 vhost_work_flush(poll->dev, &poll->work);
255 EXPORT_SYMBOL_GPL(vhost_poll_flush);
257 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
262 if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
263 /* We can only add the work to the list after we're
264 * sure it was not in the list.
265 * test_and_set_bit() implies a memory barrier.
267 llist_add(&work->node, &dev->work_list);
268 wake_up_process(dev->worker);
271 EXPORT_SYMBOL_GPL(vhost_work_queue);
273 /* A lockless hint for busy polling code to exit the loop */
274 bool vhost_has_work(struct vhost_dev *dev)
276 return !llist_empty(&dev->work_list);
278 EXPORT_SYMBOL_GPL(vhost_has_work);
280 void vhost_poll_queue(struct vhost_poll *poll)
282 vhost_work_queue(poll->dev, &poll->work);
284 EXPORT_SYMBOL_GPL(vhost_poll_queue);
286 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
290 for (j = 0; j < VHOST_NUM_ADDRS; j++)
291 vq->meta_iotlb[j] = NULL;
294 static void vhost_vq_meta_reset(struct vhost_dev *d)
298 for (i = 0; i < d->nvqs; ++i)
299 __vhost_vq_meta_reset(d->vqs[i]);
302 static void vhost_vq_reset(struct vhost_dev *dev,
303 struct vhost_virtqueue *vq)
309 vq->last_avail_idx = 0;
311 vq->last_used_idx = 0;
312 vq->signalled_used = 0;
313 vq->signalled_used_valid = false;
315 vq->log_used = false;
316 vq->log_addr = -1ull;
317 vq->private_data = NULL;
318 vq->acked_features = 0;
319 vq->acked_backend_features = 0;
321 vq->error_ctx = NULL;
325 vhost_reset_is_le(vq);
326 vhost_disable_cross_endian(vq);
327 vq->busyloop_timeout = 0;
330 __vhost_vq_meta_reset(vq);
333 static int vhost_worker(void *data)
335 struct vhost_dev *dev = data;
336 struct vhost_work *work, *work_next;
337 struct llist_node *node;
338 mm_segment_t oldfs = get_fs();
344 /* mb paired w/ kthread_stop */
345 set_current_state(TASK_INTERRUPTIBLE);
347 if (kthread_should_stop()) {
348 __set_current_state(TASK_RUNNING);
352 node = llist_del_all(&dev->work_list);
356 node = llist_reverse_order(node);
357 /* make sure flag is seen after deletion */
359 llist_for_each_entry_safe(work, work_next, node, node) {
360 clear_bit(VHOST_WORK_QUEUED, &work->flags);
361 __set_current_state(TASK_RUNNING);
362 kcov_remote_start_common(dev->kcov_handle);
374 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
384 /* Helper to allocate iovec buffers for all vqs. */
385 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
387 struct vhost_virtqueue *vq;
390 for (i = 0; i < dev->nvqs; ++i) {
392 vq->indirect = kmalloc_array(UIO_MAXIOV,
393 sizeof(*vq->indirect),
395 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
397 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
399 if (!vq->indirect || !vq->log || !vq->heads)
406 vhost_vq_free_iovecs(dev->vqs[i]);
410 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
414 for (i = 0; i < dev->nvqs; ++i)
415 vhost_vq_free_iovecs(dev->vqs[i]);
418 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
419 int pkts, int total_len)
421 struct vhost_dev *dev = vq->dev;
423 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
424 pkts >= dev->weight) {
425 vhost_poll_queue(&vq->poll);
431 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
433 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
436 size_t event __maybe_unused =
437 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
439 return sizeof(*vq->avail) +
440 sizeof(*vq->avail->ring) * num + event;
443 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
446 size_t event __maybe_unused =
447 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
449 return sizeof(*vq->used) +
450 sizeof(*vq->used->ring) * num + event;
453 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
456 return sizeof(*vq->desc) * num;
459 void vhost_dev_init(struct vhost_dev *dev,
460 struct vhost_virtqueue **vqs, int nvqs,
461 int iov_limit, int weight, int byte_weight,
463 int (*msg_handler)(struct vhost_dev *dev,
464 struct vhost_iotlb_msg *msg))
466 struct vhost_virtqueue *vq;
471 mutex_init(&dev->mutex);
477 dev->iov_limit = iov_limit;
478 dev->weight = weight;
479 dev->byte_weight = byte_weight;
480 dev->use_worker = use_worker;
481 dev->msg_handler = msg_handler;
482 init_llist_head(&dev->work_list);
483 init_waitqueue_head(&dev->wait);
484 INIT_LIST_HEAD(&dev->read_list);
485 INIT_LIST_HEAD(&dev->pending_list);
486 spin_lock_init(&dev->iotlb_lock);
489 for (i = 0; i < dev->nvqs; ++i) {
495 mutex_init(&vq->mutex);
496 vhost_vq_reset(dev, vq);
498 vhost_poll_init(&vq->poll, vq->handle_kick,
502 EXPORT_SYMBOL_GPL(vhost_dev_init);
504 /* Caller should have device mutex */
505 long vhost_dev_check_owner(struct vhost_dev *dev)
507 /* Are you the owner? If not, I don't think you mean to do that */
508 return dev->mm == current->mm ? 0 : -EPERM;
510 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
512 struct vhost_attach_cgroups_struct {
513 struct vhost_work work;
514 struct task_struct *owner;
518 static void vhost_attach_cgroups_work(struct vhost_work *work)
520 struct vhost_attach_cgroups_struct *s;
522 s = container_of(work, struct vhost_attach_cgroups_struct, work);
523 s->ret = cgroup_attach_task_all(s->owner, current);
526 static int vhost_attach_cgroups(struct vhost_dev *dev)
528 struct vhost_attach_cgroups_struct attach;
530 attach.owner = current;
531 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
532 vhost_work_queue(dev, &attach.work);
533 vhost_work_flush(dev, &attach.work);
537 /* Caller should have device mutex */
538 bool vhost_dev_has_owner(struct vhost_dev *dev)
542 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
544 static void vhost_attach_mm(struct vhost_dev *dev)
546 /* No owner, become one */
547 if (dev->use_worker) {
548 dev->mm = get_task_mm(current);
550 /* vDPA device does not use worker thead, so there's
551 * no need to hold the address space for mm. This help
552 * to avoid deadlock in the case of mmap() which may
553 * held the refcnt of the file and depends on release
554 * method to remove vma.
556 dev->mm = current->mm;
561 static void vhost_detach_mm(struct vhost_dev *dev)
574 /* Caller should have device mutex */
575 long vhost_dev_set_owner(struct vhost_dev *dev)
577 struct task_struct *worker;
580 /* Is there an owner already? */
581 if (vhost_dev_has_owner(dev)) {
586 vhost_attach_mm(dev);
588 dev->kcov_handle = kcov_common_handle();
589 if (dev->use_worker) {
590 worker = kthread_create(vhost_worker, dev,
591 "vhost-%d", current->pid);
592 if (IS_ERR(worker)) {
593 err = PTR_ERR(worker);
597 dev->worker = worker;
598 wake_up_process(worker); /* avoid contributing to loadavg */
600 err = vhost_attach_cgroups(dev);
605 err = vhost_dev_alloc_iovecs(dev);
612 kthread_stop(dev->worker);
616 vhost_detach_mm(dev);
617 dev->kcov_handle = 0;
621 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
623 static struct vhost_iotlb *iotlb_alloc(void)
625 return vhost_iotlb_alloc(max_iotlb_entries,
626 VHOST_IOTLB_FLAG_RETIRE);
629 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void)
631 return iotlb_alloc();
633 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
635 /* Caller should have device mutex */
636 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem)
640 vhost_dev_cleanup(dev);
643 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
644 * VQs aren't running.
646 for (i = 0; i < dev->nvqs; ++i)
647 dev->vqs[i]->umem = umem;
649 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
651 void vhost_dev_stop(struct vhost_dev *dev)
655 for (i = 0; i < dev->nvqs; ++i) {
656 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
657 vhost_poll_stop(&dev->vqs[i]->poll);
658 vhost_poll_flush(&dev->vqs[i]->poll);
662 EXPORT_SYMBOL_GPL(vhost_dev_stop);
664 static void vhost_clear_msg(struct vhost_dev *dev)
666 struct vhost_msg_node *node, *n;
668 spin_lock(&dev->iotlb_lock);
670 list_for_each_entry_safe(node, n, &dev->read_list, node) {
671 list_del(&node->node);
675 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
676 list_del(&node->node);
680 spin_unlock(&dev->iotlb_lock);
683 void vhost_dev_cleanup(struct vhost_dev *dev)
687 for (i = 0; i < dev->nvqs; ++i) {
688 if (dev->vqs[i]->error_ctx)
689 eventfd_ctx_put(dev->vqs[i]->error_ctx);
690 if (dev->vqs[i]->kick)
691 fput(dev->vqs[i]->kick);
692 if (dev->vqs[i]->call_ctx)
693 eventfd_ctx_put(dev->vqs[i]->call_ctx);
694 vhost_vq_reset(dev, dev->vqs[i]);
696 vhost_dev_free_iovecs(dev);
698 eventfd_ctx_put(dev->log_ctx);
700 /* No one will access memory at this point */
701 vhost_iotlb_free(dev->umem);
703 vhost_iotlb_free(dev->iotlb);
705 vhost_clear_msg(dev);
706 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
707 WARN_ON(!llist_empty(&dev->work_list));
709 kthread_stop(dev->worker);
711 dev->kcov_handle = 0;
713 vhost_detach_mm(dev);
715 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
717 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
719 u64 a = addr / VHOST_PAGE_SIZE / 8;
721 /* Make sure 64 bit math will not overflow. */
722 if (a > ULONG_MAX - (unsigned long)log_base ||
723 a + (unsigned long)log_base > ULONG_MAX)
726 return access_ok(log_base + a,
727 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
730 static bool vhost_overflow(u64 uaddr, u64 size)
732 /* Make sure 64 bit math will not overflow. */
733 return uaddr > ULONG_MAX || size > ULONG_MAX || uaddr > ULONG_MAX - size;
736 /* Caller should have vq mutex and device mutex. */
737 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem,
740 struct vhost_iotlb_map *map;
745 list_for_each_entry(map, &umem->list, link) {
746 unsigned long a = map->addr;
748 if (vhost_overflow(map->addr, map->size))
752 if (!access_ok((void __user *)a, map->size))
754 else if (log_all && !log_access_ok(log_base,
762 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
763 u64 addr, unsigned int size,
766 const struct vhost_iotlb_map *map = vq->meta_iotlb[type];
771 return (void __user *)(uintptr_t)(map->addr + addr - map->start);
774 /* Can we switch to this memory table? */
775 /* Caller should have device mutex but not vq mutex */
776 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem,
781 for (i = 0; i < d->nvqs; ++i) {
785 mutex_lock(&d->vqs[i]->mutex);
786 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
787 /* If ring is inactive, will check when it's enabled. */
788 if (d->vqs[i]->private_data)
789 ok = vq_memory_access_ok(d->vqs[i]->log_base,
793 mutex_unlock(&d->vqs[i]->mutex);
800 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
801 struct iovec iov[], int iov_size, int access);
803 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
804 const void *from, unsigned size)
809 return __copy_to_user(to, from, size);
811 /* This function should be called after iotlb
812 * prefetch, which means we're sure that all vq
813 * could be access through iotlb. So -EAGAIN should
814 * not happen in this case.
817 void __user *uaddr = vhost_vq_meta_fetch(vq,
818 (u64)(uintptr_t)to, size,
822 return __copy_to_user(uaddr, from, size);
824 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
825 ARRAY_SIZE(vq->iotlb_iov),
829 iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
830 ret = copy_to_iter(from, size, &t);
838 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
839 void __user *from, unsigned size)
844 return __copy_from_user(to, from, size);
846 /* This function should be called after iotlb
847 * prefetch, which means we're sure that vq
848 * could be access through iotlb. So -EAGAIN should
849 * not happen in this case.
851 void __user *uaddr = vhost_vq_meta_fetch(vq,
852 (u64)(uintptr_t)from, size,
857 return __copy_from_user(to, uaddr, size);
859 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
860 ARRAY_SIZE(vq->iotlb_iov),
863 vq_err(vq, "IOTLB translation failure: uaddr "
864 "%p size 0x%llx\n", from,
865 (unsigned long long) size);
868 iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
869 ret = copy_from_iter(to, size, &f);
878 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
879 void __user *addr, unsigned int size,
884 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
885 ARRAY_SIZE(vq->iotlb_iov),
888 vq_err(vq, "IOTLB translation failure: uaddr "
889 "%p size 0x%llx\n", addr,
890 (unsigned long long) size);
894 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
895 vq_err(vq, "Non atomic userspace memory access: uaddr "
896 "%p size 0x%llx\n", addr,
897 (unsigned long long) size);
901 return vq->iotlb_iov[0].iov_base;
904 /* This function should be called after iotlb
905 * prefetch, which means we're sure that vq
906 * could be access through iotlb. So -EAGAIN should
907 * not happen in this case.
909 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
910 void __user *addr, unsigned int size,
913 void __user *uaddr = vhost_vq_meta_fetch(vq,
914 (u64)(uintptr_t)addr, size, type);
918 return __vhost_get_user_slow(vq, addr, size, type);
921 #define vhost_put_user(vq, x, ptr) \
925 ret = __put_user(x, ptr); \
927 __typeof__(ptr) to = \
928 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
929 sizeof(*ptr), VHOST_ADDR_USED); \
931 ret = __put_user(x, to); \
938 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
940 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
941 vhost_avail_event(vq));
944 static inline int vhost_put_used(struct vhost_virtqueue *vq,
945 struct vring_used_elem *head, int idx,
948 return vhost_copy_to_user(vq, vq->used->ring + idx, head,
949 count * sizeof(*head));
952 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
955 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
959 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
962 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
966 #define vhost_get_user(vq, x, ptr, type) \
970 ret = __get_user(x, ptr); \
972 __typeof__(ptr) from = \
973 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
977 ret = __get_user(x, from); \
984 #define vhost_get_avail(vq, x, ptr) \
985 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
987 #define vhost_get_used(vq, x, ptr) \
988 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
990 static void vhost_dev_lock_vqs(struct vhost_dev *d)
993 for (i = 0; i < d->nvqs; ++i)
994 mutex_lock_nested(&d->vqs[i]->mutex, i);
997 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
1000 for (i = 0; i < d->nvqs; ++i)
1001 mutex_unlock(&d->vqs[i]->mutex);
1004 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
1007 return vhost_get_avail(vq, *idx, &vq->avail->idx);
1010 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
1011 __virtio16 *head, int idx)
1013 return vhost_get_avail(vq, *head,
1014 &vq->avail->ring[idx & (vq->num - 1)]);
1017 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1020 return vhost_get_avail(vq, *flags, &vq->avail->flags);
1023 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1026 return vhost_get_avail(vq, *event, vhost_used_event(vq));
1029 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1032 return vhost_get_used(vq, *idx, &vq->used->idx);
1035 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1036 struct vring_desc *desc, int idx)
1038 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1041 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1042 struct vhost_iotlb_msg *msg)
1044 struct vhost_msg_node *node, *n;
1046 spin_lock(&d->iotlb_lock);
1048 list_for_each_entry_safe(node, n, &d->pending_list, node) {
1049 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1050 if (msg->iova <= vq_msg->iova &&
1051 msg->iova + msg->size - 1 >= vq_msg->iova &&
1052 vq_msg->type == VHOST_IOTLB_MISS) {
1053 vhost_poll_queue(&node->vq->poll);
1054 list_del(&node->node);
1059 spin_unlock(&d->iotlb_lock);
1062 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1064 unsigned long a = uaddr;
1066 /* Make sure 64 bit math will not overflow. */
1067 if (vhost_overflow(uaddr, size))
1070 if ((access & VHOST_ACCESS_RO) &&
1071 !access_ok((void __user *)a, size))
1073 if ((access & VHOST_ACCESS_WO) &&
1074 !access_ok((void __user *)a, size))
1079 static int vhost_process_iotlb_msg(struct vhost_dev *dev,
1080 struct vhost_iotlb_msg *msg)
1084 mutex_lock(&dev->mutex);
1085 vhost_dev_lock_vqs(dev);
1086 switch (msg->type) {
1087 case VHOST_IOTLB_UPDATE:
1092 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1096 vhost_vq_meta_reset(dev);
1097 if (vhost_iotlb_add_range(dev->iotlb, msg->iova,
1098 msg->iova + msg->size - 1,
1099 msg->uaddr, msg->perm)) {
1103 vhost_iotlb_notify_vq(dev, msg);
1105 case VHOST_IOTLB_INVALIDATE:
1110 vhost_vq_meta_reset(dev);
1111 vhost_iotlb_del_range(dev->iotlb, msg->iova,
1112 msg->iova + msg->size - 1);
1119 vhost_dev_unlock_vqs(dev);
1120 mutex_unlock(&dev->mutex);
1124 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1125 struct iov_iter *from)
1127 struct vhost_iotlb_msg msg;
1131 ret = copy_from_iter(&type, sizeof(type), from);
1132 if (ret != sizeof(type)) {
1138 case VHOST_IOTLB_MSG:
1139 /* There maybe a hole after type for V1 message type,
1142 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1144 case VHOST_IOTLB_MSG_V2:
1145 offset = sizeof(__u32);
1152 iov_iter_advance(from, offset);
1153 ret = copy_from_iter(&msg, sizeof(msg), from);
1154 if (ret != sizeof(msg)) {
1159 if (dev->msg_handler)
1160 ret = dev->msg_handler(dev, &msg);
1162 ret = vhost_process_iotlb_msg(dev, &msg);
1168 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1169 sizeof(struct vhost_msg_v2);
1173 EXPORT_SYMBOL(vhost_chr_write_iter);
1175 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1180 poll_wait(file, &dev->wait, wait);
1182 if (!list_empty(&dev->read_list))
1183 mask |= EPOLLIN | EPOLLRDNORM;
1187 EXPORT_SYMBOL(vhost_chr_poll);
1189 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1193 struct vhost_msg_node *node;
1195 unsigned size = sizeof(struct vhost_msg);
1197 if (iov_iter_count(to) < size)
1202 prepare_to_wait(&dev->wait, &wait,
1203 TASK_INTERRUPTIBLE);
1205 node = vhost_dequeue_msg(dev, &dev->read_list);
1212 if (signal_pending(current)) {
1225 finish_wait(&dev->wait, &wait);
1228 struct vhost_iotlb_msg *msg;
1229 void *start = &node->msg;
1231 switch (node->msg.type) {
1232 case VHOST_IOTLB_MSG:
1233 size = sizeof(node->msg);
1234 msg = &node->msg.iotlb;
1236 case VHOST_IOTLB_MSG_V2:
1237 size = sizeof(node->msg_v2);
1238 msg = &node->msg_v2.iotlb;
1245 ret = copy_to_iter(start, size, to);
1246 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1250 vhost_enqueue_msg(dev, &dev->pending_list, node);
1255 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1257 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1259 struct vhost_dev *dev = vq->dev;
1260 struct vhost_msg_node *node;
1261 struct vhost_iotlb_msg *msg;
1262 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1264 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1269 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1270 msg = &node->msg_v2.iotlb;
1272 msg = &node->msg.iotlb;
1275 msg->type = VHOST_IOTLB_MISS;
1279 vhost_enqueue_msg(dev, &dev->read_list, node);
1284 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1285 vring_desc_t __user *desc,
1286 vring_avail_t __user *avail,
1287 vring_used_t __user *used)
1290 return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1291 access_ok(avail, vhost_get_avail_size(vq, num)) &&
1292 access_ok(used, vhost_get_used_size(vq, num));
1295 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1296 const struct vhost_iotlb_map *map,
1299 int access = (type == VHOST_ADDR_USED) ?
1300 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1302 if (likely(map->perm & access))
1303 vq->meta_iotlb[type] = map;
1306 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1307 int access, u64 addr, u64 len, int type)
1309 const struct vhost_iotlb_map *map;
1310 struct vhost_iotlb *umem = vq->iotlb;
1311 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1313 if (vhost_vq_meta_fetch(vq, addr, len, type))
1317 map = vhost_iotlb_itree_first(umem, addr, last);
1318 if (map == NULL || map->start > addr) {
1319 vhost_iotlb_miss(vq, addr, access);
1321 } else if (!(map->perm & access)) {
1322 /* Report the possible access violation by
1323 * request another translation from userspace.
1328 size = map->size - addr + map->start;
1330 if (orig_addr == addr && size >= len)
1331 vhost_vq_meta_update(vq, map, type);
1340 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1342 unsigned int num = vq->num;
1347 return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc,
1348 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1349 iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail,
1350 vhost_get_avail_size(vq, num),
1351 VHOST_ADDR_AVAIL) &&
1352 iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used,
1353 vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1355 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1357 /* Can we log writes? */
1358 /* Caller should have device mutex but not vq mutex */
1359 bool vhost_log_access_ok(struct vhost_dev *dev)
1361 return memory_access_ok(dev, dev->umem, 1);
1363 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1365 /* Verify access for write logging. */
1366 /* Caller should have vq mutex and device mutex */
1367 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1368 void __user *log_base)
1370 return vq_memory_access_ok(log_base, vq->umem,
1371 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1372 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
1373 vhost_get_used_size(vq, vq->num)));
1376 /* Can we start vq? */
1377 /* Caller should have vq mutex and device mutex */
1378 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1380 if (!vq_log_access_ok(vq, vq->log_base))
1383 /* Access validation occurs at prefetch time with IOTLB */
1387 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1389 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1391 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1393 struct vhost_memory mem, *newmem;
1394 struct vhost_memory_region *region;
1395 struct vhost_iotlb *newumem, *oldumem;
1396 unsigned long size = offsetof(struct vhost_memory, regions);
1399 if (copy_from_user(&mem, m, size))
1403 if (mem.nregions > max_mem_regions)
1405 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1410 memcpy(newmem, &mem, size);
1411 if (copy_from_user(newmem->regions, m->regions,
1412 mem.nregions * sizeof *m->regions)) {
1417 newumem = iotlb_alloc();
1423 for (region = newmem->regions;
1424 region < newmem->regions + mem.nregions;
1426 if (vhost_iotlb_add_range(newumem,
1427 region->guest_phys_addr,
1428 region->guest_phys_addr +
1429 region->memory_size - 1,
1430 region->userspace_addr,
1435 if (!memory_access_ok(d, newumem, 0))
1441 /* All memory accesses are done under some VQ mutex. */
1442 for (i = 0; i < d->nvqs; ++i) {
1443 mutex_lock(&d->vqs[i]->mutex);
1444 d->vqs[i]->umem = newumem;
1445 mutex_unlock(&d->vqs[i]->mutex);
1449 vhost_iotlb_free(oldumem);
1453 vhost_iotlb_free(newumem);
1458 static long vhost_vring_set_num(struct vhost_dev *d,
1459 struct vhost_virtqueue *vq,
1462 struct vhost_vring_state s;
1464 /* Resizing ring with an active backend?
1465 * You don't want to do that. */
1466 if (vq->private_data)
1469 if (copy_from_user(&s, argp, sizeof s))
1472 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
1479 static long vhost_vring_set_addr(struct vhost_dev *d,
1480 struct vhost_virtqueue *vq,
1483 struct vhost_vring_addr a;
1485 if (copy_from_user(&a, argp, sizeof a))
1487 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
1490 /* For 32bit, verify that the top 32bits of the user
1491 data are set to zero. */
1492 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1493 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1494 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
1497 /* Make sure it's safe to cast pointers to vring types. */
1498 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1499 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1500 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1501 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1502 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
1505 /* We only verify access here if backend is configured.
1506 * If it is not, we don't as size might not have been setup.
1507 * We will verify when backend is configured. */
1508 if (vq->private_data) {
1509 if (!vq_access_ok(vq, vq->num,
1510 (void __user *)(unsigned long)a.desc_user_addr,
1511 (void __user *)(unsigned long)a.avail_user_addr,
1512 (void __user *)(unsigned long)a.used_user_addr))
1515 /* Also validate log access for used ring if enabled. */
1516 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
1517 !log_access_ok(vq->log_base, a.log_guest_addr,
1519 vq->num * sizeof *vq->used->ring))
1523 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1524 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1525 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1526 vq->log_addr = a.log_guest_addr;
1527 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1532 static long vhost_vring_set_num_addr(struct vhost_dev *d,
1533 struct vhost_virtqueue *vq,
1539 mutex_lock(&vq->mutex);
1542 case VHOST_SET_VRING_NUM:
1543 r = vhost_vring_set_num(d, vq, argp);
1545 case VHOST_SET_VRING_ADDR:
1546 r = vhost_vring_set_addr(d, vq, argp);
1552 mutex_unlock(&vq->mutex);
1556 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1558 struct file *eventfp, *filep = NULL;
1559 bool pollstart = false, pollstop = false;
1560 struct eventfd_ctx *ctx = NULL;
1561 u32 __user *idxp = argp;
1562 struct vhost_virtqueue *vq;
1563 struct vhost_vring_state s;
1564 struct vhost_vring_file f;
1568 r = get_user(idx, idxp);
1574 idx = array_index_nospec(idx, d->nvqs);
1577 if (ioctl == VHOST_SET_VRING_NUM ||
1578 ioctl == VHOST_SET_VRING_ADDR) {
1579 return vhost_vring_set_num_addr(d, vq, ioctl, argp);
1582 mutex_lock(&vq->mutex);
1585 case VHOST_SET_VRING_BASE:
1586 /* Moving base with an active backend?
1587 * You don't want to do that. */
1588 if (vq->private_data) {
1592 if (copy_from_user(&s, argp, sizeof s)) {
1596 if (s.num > 0xffff) {
1600 vq->last_avail_idx = s.num;
1601 /* Forget the cached index value. */
1602 vq->avail_idx = vq->last_avail_idx;
1604 case VHOST_GET_VRING_BASE:
1606 s.num = vq->last_avail_idx;
1607 if (copy_to_user(argp, &s, sizeof s))
1610 case VHOST_SET_VRING_KICK:
1611 if (copy_from_user(&f, argp, sizeof f)) {
1615 eventfp = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_fget(f.fd);
1616 if (IS_ERR(eventfp)) {
1617 r = PTR_ERR(eventfp);
1620 if (eventfp != vq->kick) {
1621 pollstop = (filep = vq->kick) != NULL;
1622 pollstart = (vq->kick = eventfp) != NULL;
1626 case VHOST_SET_VRING_CALL:
1627 if (copy_from_user(&f, argp, sizeof f)) {
1631 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
1636 swap(ctx, vq->call_ctx);
1638 case VHOST_SET_VRING_ERR:
1639 if (copy_from_user(&f, argp, sizeof f)) {
1643 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
1648 swap(ctx, vq->error_ctx);
1650 case VHOST_SET_VRING_ENDIAN:
1651 r = vhost_set_vring_endian(vq, argp);
1653 case VHOST_GET_VRING_ENDIAN:
1654 r = vhost_get_vring_endian(vq, idx, argp);
1656 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1657 if (copy_from_user(&s, argp, sizeof(s))) {
1661 vq->busyloop_timeout = s.num;
1663 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1665 s.num = vq->busyloop_timeout;
1666 if (copy_to_user(argp, &s, sizeof(s)))
1673 if (pollstop && vq->handle_kick)
1674 vhost_poll_stop(&vq->poll);
1676 if (!IS_ERR_OR_NULL(ctx))
1677 eventfd_ctx_put(ctx);
1681 if (pollstart && vq->handle_kick)
1682 r = vhost_poll_start(&vq->poll, vq->kick);
1684 mutex_unlock(&vq->mutex);
1686 if (pollstop && vq->handle_kick)
1687 vhost_poll_flush(&vq->poll);
1690 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1692 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1694 struct vhost_iotlb *niotlb, *oiotlb;
1697 niotlb = iotlb_alloc();
1704 for (i = 0; i < d->nvqs; ++i) {
1705 struct vhost_virtqueue *vq = d->vqs[i];
1707 mutex_lock(&vq->mutex);
1709 __vhost_vq_meta_reset(vq);
1710 mutex_unlock(&vq->mutex);
1713 vhost_iotlb_free(oiotlb);
1717 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1719 /* Caller must have device mutex */
1720 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1722 struct eventfd_ctx *ctx;
1727 /* If you are not the owner, you can become one */
1728 if (ioctl == VHOST_SET_OWNER) {
1729 r = vhost_dev_set_owner(d);
1733 /* You must be the owner to do anything else */
1734 r = vhost_dev_check_owner(d);
1739 case VHOST_SET_MEM_TABLE:
1740 r = vhost_set_memory(d, argp);
1742 case VHOST_SET_LOG_BASE:
1743 if (copy_from_user(&p, argp, sizeof p)) {
1747 if ((u64)(unsigned long)p != p) {
1751 for (i = 0; i < d->nvqs; ++i) {
1752 struct vhost_virtqueue *vq;
1753 void __user *base = (void __user *)(unsigned long)p;
1755 mutex_lock(&vq->mutex);
1756 /* If ring is inactive, will check when it's enabled. */
1757 if (vq->private_data && !vq_log_access_ok(vq, base))
1760 vq->log_base = base;
1761 mutex_unlock(&vq->mutex);
1764 case VHOST_SET_LOG_FD:
1765 r = get_user(fd, (int __user *)argp);
1768 ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd);
1773 swap(ctx, d->log_ctx);
1774 for (i = 0; i < d->nvqs; ++i) {
1775 mutex_lock(&d->vqs[i]->mutex);
1776 d->vqs[i]->log_ctx = d->log_ctx;
1777 mutex_unlock(&d->vqs[i]->mutex);
1780 eventfd_ctx_put(ctx);
1789 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1791 /* TODO: This is really inefficient. We need something like get_user()
1792 * (instruction directly accesses the data, with an exception table entry
1793 * returning -EFAULT). See Documentation/x86/exception-tables.rst.
1795 static int set_bit_to_user(int nr, void __user *addr)
1797 unsigned long log = (unsigned long)addr;
1800 int bit = nr + (log % PAGE_SIZE) * 8;
1803 r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page);
1807 base = kmap_atomic(page);
1809 kunmap_atomic(base);
1810 unpin_user_pages_dirty_lock(&page, 1, true);
1814 static int log_write(void __user *log_base,
1815 u64 write_address, u64 write_length)
1817 u64 write_page = write_address / VHOST_PAGE_SIZE;
1822 write_length += write_address % VHOST_PAGE_SIZE;
1824 u64 base = (u64)(unsigned long)log_base;
1825 u64 log = base + write_page / 8;
1826 int bit = write_page % 8;
1827 if ((u64)(unsigned long)log != log)
1829 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1832 if (write_length <= VHOST_PAGE_SIZE)
1834 write_length -= VHOST_PAGE_SIZE;
1840 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1842 struct vhost_iotlb *umem = vq->umem;
1843 struct vhost_iotlb_map *u;
1844 u64 start, end, l, min;
1850 /* More than one GPAs can be mapped into a single HVA. So
1851 * iterate all possible umems here to be safe.
1853 list_for_each_entry(u, &umem->list, link) {
1854 if (u->addr > hva - 1 + len ||
1855 u->addr - 1 + u->size < hva)
1857 start = max(u->addr, hva);
1858 end = min(u->addr - 1 + u->size, hva - 1 + len);
1859 l = end - start + 1;
1860 r = log_write(vq->log_base,
1861 u->start + start - u->addr,
1879 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1881 struct iovec iov[64];
1885 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1887 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1888 len, iov, 64, VHOST_ACCESS_WO);
1892 for (i = 0; i < ret; i++) {
1893 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1902 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1903 unsigned int log_num, u64 len, struct iovec *iov, int count)
1907 /* Make sure data written is seen before log. */
1911 for (i = 0; i < count; i++) {
1912 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1920 for (i = 0; i < log_num; ++i) {
1921 u64 l = min(log[i].len, len);
1922 r = log_write(vq->log_base, log[i].addr, l);
1928 eventfd_signal(vq->log_ctx, 1);
1932 /* Length written exceeds what we have stored. This is a bug. */
1936 EXPORT_SYMBOL_GPL(vhost_log_write);
1938 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1941 if (vhost_put_used_flags(vq))
1943 if (unlikely(vq->log_used)) {
1944 /* Make sure the flag is seen before log. */
1946 /* Log used flag write. */
1947 used = &vq->used->flags;
1948 log_used(vq, (used - (void __user *)vq->used),
1949 sizeof vq->used->flags);
1951 eventfd_signal(vq->log_ctx, 1);
1956 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1958 if (vhost_put_avail_event(vq))
1960 if (unlikely(vq->log_used)) {
1962 /* Make sure the event is seen before log. */
1964 /* Log avail event write */
1965 used = vhost_avail_event(vq);
1966 log_used(vq, (used - (void __user *)vq->used),
1967 sizeof *vhost_avail_event(vq));
1969 eventfd_signal(vq->log_ctx, 1);
1974 int vhost_vq_init_access(struct vhost_virtqueue *vq)
1976 __virtio16 last_used_idx;
1978 bool is_le = vq->is_le;
1980 if (!vq->private_data)
1983 vhost_init_is_le(vq);
1985 r = vhost_update_used_flags(vq);
1988 vq->signalled_used_valid = false;
1990 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
1994 r = vhost_get_used_idx(vq, &last_used_idx);
1996 vq_err(vq, "Can't access used idx at %p\n",
2000 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2007 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2009 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2010 struct iovec iov[], int iov_size, int access)
2012 const struct vhost_iotlb_map *map;
2013 struct vhost_dev *dev = vq->dev;
2014 struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
2019 while ((u64)len > s) {
2021 if (unlikely(ret >= iov_size)) {
2026 map = vhost_iotlb_itree_first(umem, addr, addr + len - 1);
2027 if (map == NULL || map->start > addr) {
2028 if (umem != dev->iotlb) {
2034 } else if (!(map->perm & access)) {
2040 size = map->size - addr + map->start;
2041 _iov->iov_len = min((u64)len - s, size);
2042 _iov->iov_base = (void __user *)(unsigned long)
2043 (map->addr + addr - map->start);
2050 vhost_iotlb_miss(vq, addr, access);
2054 /* Each buffer in the virtqueues is actually a chain of descriptors. This
2055 * function returns the next descriptor in the chain,
2056 * or -1U if we're at the end. */
2057 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2061 /* If this descriptor says it doesn't chain, we're done. */
2062 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2065 /* Check they're not leading us off end of descriptors. */
2066 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2070 static int get_indirect(struct vhost_virtqueue *vq,
2071 struct iovec iov[], unsigned int iov_size,
2072 unsigned int *out_num, unsigned int *in_num,
2073 struct vhost_log *log, unsigned int *log_num,
2074 struct vring_desc *indirect)
2076 struct vring_desc desc;
2077 unsigned int i = 0, count, found = 0;
2078 u32 len = vhost32_to_cpu(vq, indirect->len);
2079 struct iov_iter from;
2083 if (unlikely(len % sizeof desc)) {
2084 vq_err(vq, "Invalid length in indirect descriptor: "
2085 "len 0x%llx not multiple of 0x%zx\n",
2086 (unsigned long long)len,
2091 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2092 UIO_MAXIOV, VHOST_ACCESS_RO);
2093 if (unlikely(ret < 0)) {
2095 vq_err(vq, "Translation failure %d in indirect.\n", ret);
2098 iov_iter_init(&from, READ, vq->indirect, ret, len);
2100 /* We will use the result as an address to read from, so most
2101 * architectures only need a compiler barrier here. */
2102 read_barrier_depends();
2104 count = len / sizeof desc;
2105 /* Buffers are chained via a 16 bit next field, so
2106 * we can have at most 2^16 of these. */
2107 if (unlikely(count > USHRT_MAX + 1)) {
2108 vq_err(vq, "Indirect buffer length too big: %d\n",
2114 unsigned iov_count = *in_num + *out_num;
2115 if (unlikely(++found > count)) {
2116 vq_err(vq, "Loop detected: last one at %u "
2117 "indirect size %u\n",
2121 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2122 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2123 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2126 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2127 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2128 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2132 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2133 access = VHOST_ACCESS_WO;
2135 access = VHOST_ACCESS_RO;
2137 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2138 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2139 iov_size - iov_count, access);
2140 if (unlikely(ret < 0)) {
2142 vq_err(vq, "Translation failure %d indirect idx %d\n",
2146 /* If this is an input descriptor, increment that count. */
2147 if (access == VHOST_ACCESS_WO) {
2149 if (unlikely(log && ret)) {
2150 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2151 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2155 /* If it's an output descriptor, they're all supposed
2156 * to come before any input descriptors. */
2157 if (unlikely(*in_num)) {
2158 vq_err(vq, "Indirect descriptor "
2159 "has out after in: idx %d\n", i);
2164 } while ((i = next_desc(vq, &desc)) != -1);
2168 /* This looks in the virtqueue and for the first available buffer, and converts
2169 * it to an iovec for convenient access. Since descriptors consist of some
2170 * number of output then some number of input descriptors, it's actually two
2171 * iovecs, but we pack them into one and note how many of each there were.
2173 * This function returns the descriptor number found, or vq->num (which is
2174 * never a valid descriptor number) if none was found. A negative code is
2175 * returned on error. */
2176 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2177 struct iovec iov[], unsigned int iov_size,
2178 unsigned int *out_num, unsigned int *in_num,
2179 struct vhost_log *log, unsigned int *log_num)
2181 struct vring_desc desc;
2182 unsigned int i, head, found = 0;
2184 __virtio16 avail_idx;
2185 __virtio16 ring_head;
2188 /* Check it isn't doing very strange things with descriptor numbers. */
2189 last_avail_idx = vq->last_avail_idx;
2191 if (vq->avail_idx == vq->last_avail_idx) {
2192 if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
2193 vq_err(vq, "Failed to access avail idx at %p\n",
2197 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2199 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2200 vq_err(vq, "Guest moved used index from %u to %u",
2201 last_avail_idx, vq->avail_idx);
2205 /* If there's nothing new since last we looked, return
2208 if (vq->avail_idx == last_avail_idx)
2211 /* Only get avail ring entries after they have been
2217 /* Grab the next descriptor number they're advertising, and increment
2218 * the index we've seen. */
2219 if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
2220 vq_err(vq, "Failed to read head: idx %d address %p\n",
2222 &vq->avail->ring[last_avail_idx % vq->num]);
2226 head = vhost16_to_cpu(vq, ring_head);
2228 /* If their number is silly, that's an error. */
2229 if (unlikely(head >= vq->num)) {
2230 vq_err(vq, "Guest says index %u > %u is available",
2235 /* When we start there are none of either input nor output. */
2236 *out_num = *in_num = 0;
2242 unsigned iov_count = *in_num + *out_num;
2243 if (unlikely(i >= vq->num)) {
2244 vq_err(vq, "Desc index is %u > %u, head = %u",
2248 if (unlikely(++found > vq->num)) {
2249 vq_err(vq, "Loop detected: last one at %u "
2250 "vq size %u head %u\n",
2254 ret = vhost_get_desc(vq, &desc, i);
2255 if (unlikely(ret)) {
2256 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2260 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2261 ret = get_indirect(vq, iov, iov_size,
2263 log, log_num, &desc);
2264 if (unlikely(ret < 0)) {
2266 vq_err(vq, "Failure detected "
2267 "in indirect descriptor at idx %d\n", i);
2273 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2274 access = VHOST_ACCESS_WO;
2276 access = VHOST_ACCESS_RO;
2277 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2278 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2279 iov_size - iov_count, access);
2280 if (unlikely(ret < 0)) {
2282 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2286 if (access == VHOST_ACCESS_WO) {
2287 /* If this is an input descriptor,
2288 * increment that count. */
2290 if (unlikely(log && ret)) {
2291 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2292 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2296 /* If it's an output descriptor, they're all supposed
2297 * to come before any input descriptors. */
2298 if (unlikely(*in_num)) {
2299 vq_err(vq, "Descriptor has out after in: "
2305 } while ((i = next_desc(vq, &desc)) != -1);
2307 /* On success, increment avail index. */
2308 vq->last_avail_idx++;
2310 /* Assume notifications from guest are disabled at this point,
2311 * if they aren't we would need to update avail_event index. */
2312 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2315 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2317 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2318 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2320 vq->last_avail_idx -= n;
2322 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2324 /* After we've used one of their buffers, we tell them about it. We'll then
2325 * want to notify the guest, using eventfd. */
2326 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2328 struct vring_used_elem heads = {
2329 cpu_to_vhost32(vq, head),
2330 cpu_to_vhost32(vq, len)
2333 return vhost_add_used_n(vq, &heads, 1);
2335 EXPORT_SYMBOL_GPL(vhost_add_used);
2337 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2338 struct vring_used_elem *heads,
2341 vring_used_elem_t __user *used;
2345 start = vq->last_used_idx & (vq->num - 1);
2346 used = vq->used->ring + start;
2347 if (vhost_put_used(vq, heads, start, count)) {
2348 vq_err(vq, "Failed to write used");
2351 if (unlikely(vq->log_used)) {
2352 /* Make sure data is seen before log. */
2354 /* Log used ring entry write. */
2355 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2356 count * sizeof *used);
2358 old = vq->last_used_idx;
2359 new = (vq->last_used_idx += count);
2360 /* If the driver never bothers to signal in a very long while,
2361 * used index might wrap around. If that happens, invalidate
2362 * signalled_used index we stored. TODO: make sure driver
2363 * signals at least once in 2^16 and remove this. */
2364 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2365 vq->signalled_used_valid = false;
2369 /* After we've used one of their buffers, we tell them about it. We'll then
2370 * want to notify the guest, using eventfd. */
2371 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2376 start = vq->last_used_idx & (vq->num - 1);
2377 n = vq->num - start;
2379 r = __vhost_add_used_n(vq, heads, n);
2385 r = __vhost_add_used_n(vq, heads, count);
2387 /* Make sure buffer is written before we update index. */
2389 if (vhost_put_used_idx(vq)) {
2390 vq_err(vq, "Failed to increment used idx");
2393 if (unlikely(vq->log_used)) {
2394 /* Make sure used idx is seen before log. */
2396 /* Log used index update. */
2397 log_used(vq, offsetof(struct vring_used, idx),
2398 sizeof vq->used->idx);
2400 eventfd_signal(vq->log_ctx, 1);
2404 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2406 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2411 /* Flush out used index updates. This is paired
2412 * with the barrier that the Guest executes when enabling
2416 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2417 unlikely(vq->avail_idx == vq->last_avail_idx))
2420 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2422 if (vhost_get_avail_flags(vq, &flags)) {
2423 vq_err(vq, "Failed to get flags");
2426 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2428 old = vq->signalled_used;
2429 v = vq->signalled_used_valid;
2430 new = vq->signalled_used = vq->last_used_idx;
2431 vq->signalled_used_valid = true;
2436 if (vhost_get_used_event(vq, &event)) {
2437 vq_err(vq, "Failed to get used event idx");
2440 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2443 /* This actually signals the guest, using eventfd. */
2444 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2446 /* Signal the Guest tell them we used something up. */
2447 if (vq->call_ctx && vhost_notify(dev, vq))
2448 eventfd_signal(vq->call_ctx, 1);
2450 EXPORT_SYMBOL_GPL(vhost_signal);
2452 /* And here's the combo meal deal. Supersize me! */
2453 void vhost_add_used_and_signal(struct vhost_dev *dev,
2454 struct vhost_virtqueue *vq,
2455 unsigned int head, int len)
2457 vhost_add_used(vq, head, len);
2458 vhost_signal(dev, vq);
2460 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2462 /* multi-buffer version of vhost_add_used_and_signal */
2463 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2464 struct vhost_virtqueue *vq,
2465 struct vring_used_elem *heads, unsigned count)
2467 vhost_add_used_n(vq, heads, count);
2468 vhost_signal(dev, vq);
2470 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2472 /* return true if we're sure that avaiable ring is empty */
2473 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2475 __virtio16 avail_idx;
2478 if (vq->avail_idx != vq->last_avail_idx)
2481 r = vhost_get_avail_idx(vq, &avail_idx);
2484 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2486 return vq->avail_idx == vq->last_avail_idx;
2488 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2490 /* OK, now we need to know about added descriptors. */
2491 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2493 __virtio16 avail_idx;
2496 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2498 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2499 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2500 r = vhost_update_used_flags(vq);
2502 vq_err(vq, "Failed to enable notification at %p: %d\n",
2503 &vq->used->flags, r);
2507 r = vhost_update_avail_event(vq, vq->avail_idx);
2509 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2510 vhost_avail_event(vq), r);
2514 /* They could have slipped one in as we were doing that: make
2515 * sure it's written, then check again. */
2517 r = vhost_get_avail_idx(vq, &avail_idx);
2519 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2520 &vq->avail->idx, r);
2524 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2526 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2528 /* We don't need to be notified again. */
2529 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2533 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2535 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2536 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2537 r = vhost_update_used_flags(vq);
2539 vq_err(vq, "Failed to enable notification at %p: %d\n",
2540 &vq->used->flags, r);
2543 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2545 /* Create a new message. */
2546 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2548 struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2552 /* Make sure all padding within the structure is initialized. */
2553 memset(&node->msg, 0, sizeof node->msg);
2555 node->msg.type = type;
2558 EXPORT_SYMBOL_GPL(vhost_new_msg);
2560 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2561 struct vhost_msg_node *node)
2563 spin_lock(&dev->iotlb_lock);
2564 list_add_tail(&node->node, head);
2565 spin_unlock(&dev->iotlb_lock);
2567 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2569 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2571 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2572 struct list_head *head)
2574 struct vhost_msg_node *node = NULL;
2576 spin_lock(&dev->iotlb_lock);
2577 if (!list_empty(head)) {
2578 node = list_first_entry(head, struct vhost_msg_node,
2580 list_del(&node->node);
2582 spin_unlock(&dev->iotlb_lock);
2586 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2589 static int __init vhost_init(void)
2594 static void __exit vhost_exit(void)
2598 module_init(vhost_init);
2599 module_exit(vhost_exit);
2601 MODULE_VERSION("0.0.1");
2602 MODULE_LICENSE("GPL v2");
2603 MODULE_AUTHOR("Michael S. Tsirkin");
2604 MODULE_DESCRIPTION("Host kernel accelerator for virtio");