1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (C) 2009 Red Hat, Inc.
3 * Copyright (C) 2006 Rusty Russell IBM Corporation
5 * Author: Michael S. Tsirkin <mst@redhat.com>
7 * Inspiration, some code, and most witty comments come from
8 * Documentation/virtual/lguest/lguest.c, by Rusty Russell
10 * Generic code for virtio server in host kernel.
13 #include <linux/eventfd.h>
14 #include <linux/vhost.h>
15 #include <linux/uio.h>
17 #include <linux/miscdevice.h>
18 #include <linux/mutex.h>
19 #include <linux/poll.h>
20 #include <linux/file.h>
21 #include <linux/highmem.h>
22 #include <linux/slab.h>
23 #include <linux/vmalloc.h>
24 #include <linux/kthread.h>
25 #include <linux/module.h>
26 #include <linux/sort.h>
27 #include <linux/sched/mm.h>
28 #include <linux/sched/signal.h>
29 #include <linux/sched/vhost_task.h>
30 #include <linux/interval_tree_generic.h>
31 #include <linux/nospec.h>
32 #include <linux/kcov.h>
36 static ushort max_mem_regions = 64;
37 module_param(max_mem_regions, ushort, 0444);
38 MODULE_PARM_DESC(max_mem_regions,
39 "Maximum number of memory regions in memory map. (default: 64)");
40 static int max_iotlb_entries = 2048;
41 module_param(max_iotlb_entries, int, 0444);
42 MODULE_PARM_DESC(max_iotlb_entries,
43 "Maximum number of iotlb entries. (default: 2048)");
46 VHOST_MEMORY_F_LOG = 0x1,
49 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
50 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
52 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
53 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
55 vq->user_be = !virtio_legacy_is_little_endian();
58 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
63 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
68 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
70 struct vhost_vring_state s;
75 if (copy_from_user(&s, argp, sizeof(s)))
78 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
79 s.num != VHOST_VRING_BIG_ENDIAN)
82 if (s.num == VHOST_VRING_BIG_ENDIAN)
83 vhost_enable_cross_endian_big(vq);
85 vhost_enable_cross_endian_little(vq);
90 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
93 struct vhost_vring_state s = {
98 if (copy_to_user(argp, &s, sizeof(s)))
104 static void vhost_init_is_le(struct vhost_virtqueue *vq)
106 /* Note for legacy virtio: user_be is initialized at reset time
107 * according to the host endianness. If userspace does not set an
108 * explicit endianness, the default behavior is native endian, as
109 * expected by legacy virtio.
111 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
114 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
118 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
123 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
129 static void vhost_init_is_le(struct vhost_virtqueue *vq)
131 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
132 || virtio_legacy_is_little_endian();
134 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
136 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
138 vhost_init_is_le(vq);
141 struct vhost_flush_struct {
142 struct vhost_work work;
143 struct completion wait_event;
146 static void vhost_flush_work(struct vhost_work *work)
148 struct vhost_flush_struct *s;
150 s = container_of(work, struct vhost_flush_struct, work);
151 complete(&s->wait_event);
154 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
157 struct vhost_poll *poll;
159 poll = container_of(pt, struct vhost_poll, table);
161 add_wait_queue(wqh, &poll->wait);
164 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
167 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
168 struct vhost_work *work = &poll->work;
170 if (!(key_to_poll(key) & poll->mask))
173 if (!poll->dev->use_worker)
176 vhost_poll_queue(poll);
181 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
183 clear_bit(VHOST_WORK_QUEUED, &work->flags);
186 EXPORT_SYMBOL_GPL(vhost_work_init);
188 /* Init poll structure */
189 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
190 __poll_t mask, struct vhost_dev *dev)
192 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
193 init_poll_funcptr(&poll->table, vhost_poll_func);
198 vhost_work_init(&poll->work, fn);
200 EXPORT_SYMBOL_GPL(vhost_poll_init);
202 /* Start polling a file. We add ourselves to file's wait queue. The caller must
203 * keep a reference to a file until after vhost_poll_stop is called. */
204 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
211 mask = vfs_poll(file, &poll->table);
213 vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
214 if (mask & EPOLLERR) {
215 vhost_poll_stop(poll);
221 EXPORT_SYMBOL_GPL(vhost_poll_start);
223 /* Stop polling a file. After this function returns, it becomes safe to drop the
224 * file reference. You must also flush afterwards. */
225 void vhost_poll_stop(struct vhost_poll *poll)
228 remove_wait_queue(poll->wqh, &poll->wait);
232 EXPORT_SYMBOL_GPL(vhost_poll_stop);
234 void vhost_dev_flush(struct vhost_dev *dev)
236 struct vhost_flush_struct flush;
238 init_completion(&flush.wait_event);
239 vhost_work_init(&flush.work, vhost_flush_work);
241 if (vhost_work_queue(dev, &flush.work))
242 wait_for_completion(&flush.wait_event);
244 EXPORT_SYMBOL_GPL(vhost_dev_flush);
246 bool vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
251 * vsock can queue while we do a VHOST_SET_OWNER, so we have a smp_wmb
252 * when setting up the worker. We don't have a smp_rmb here because
253 * test_and_set_bit gives us a mb already.
255 if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
256 /* We can only add the work to the list after we're
257 * sure it was not in the list.
258 * test_and_set_bit() implies a memory barrier.
260 llist_add(&work->node, &dev->worker->work_list);
261 vhost_task_wake(dev->worker->vtsk);
266 EXPORT_SYMBOL_GPL(vhost_work_queue);
268 /* A lockless hint for busy polling code to exit the loop */
269 bool vhost_vq_has_work(struct vhost_virtqueue *vq)
271 return !llist_empty(&vq->worker->work_list);
273 EXPORT_SYMBOL_GPL(vhost_vq_has_work);
275 void vhost_poll_queue(struct vhost_poll *poll)
277 vhost_work_queue(poll->dev, &poll->work);
279 EXPORT_SYMBOL_GPL(vhost_poll_queue);
281 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
285 for (j = 0; j < VHOST_NUM_ADDRS; j++)
286 vq->meta_iotlb[j] = NULL;
289 static void vhost_vq_meta_reset(struct vhost_dev *d)
293 for (i = 0; i < d->nvqs; ++i)
294 __vhost_vq_meta_reset(d->vqs[i]);
297 static void vhost_vring_call_reset(struct vhost_vring_call *call_ctx)
299 call_ctx->ctx = NULL;
300 memset(&call_ctx->producer, 0x0, sizeof(struct irq_bypass_producer));
303 bool vhost_vq_is_setup(struct vhost_virtqueue *vq)
305 return vq->avail && vq->desc && vq->used && vhost_vq_access_ok(vq);
307 EXPORT_SYMBOL_GPL(vhost_vq_is_setup);
309 static void vhost_vq_reset(struct vhost_dev *dev,
310 struct vhost_virtqueue *vq)
316 vq->last_avail_idx = 0;
318 vq->last_used_idx = 0;
319 vq->signalled_used = 0;
320 vq->signalled_used_valid = false;
322 vq->log_used = false;
323 vq->log_addr = -1ull;
324 vq->private_data = NULL;
325 vq->acked_features = 0;
326 vq->acked_backend_features = 0;
328 vq->error_ctx = NULL;
331 vhost_disable_cross_endian(vq);
332 vhost_reset_is_le(vq);
333 vq->busyloop_timeout = 0;
337 vhost_vring_call_reset(&vq->call_ctx);
338 __vhost_vq_meta_reset(vq);
341 static bool vhost_worker(void *data)
343 struct vhost_worker *worker = data;
344 struct vhost_work *work, *work_next;
345 struct llist_node *node;
347 node = llist_del_all(&worker->work_list);
349 __set_current_state(TASK_RUNNING);
351 node = llist_reverse_order(node);
352 /* make sure flag is seen after deletion */
354 llist_for_each_entry_safe(work, work_next, node, node) {
355 clear_bit(VHOST_WORK_QUEUED, &work->flags);
356 kcov_remote_start_common(worker->kcov_handle);
366 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
376 /* Helper to allocate iovec buffers for all vqs. */
377 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
379 struct vhost_virtqueue *vq;
382 for (i = 0; i < dev->nvqs; ++i) {
384 vq->indirect = kmalloc_array(UIO_MAXIOV,
385 sizeof(*vq->indirect),
387 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
389 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
391 if (!vq->indirect || !vq->log || !vq->heads)
398 vhost_vq_free_iovecs(dev->vqs[i]);
402 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
406 for (i = 0; i < dev->nvqs; ++i)
407 vhost_vq_free_iovecs(dev->vqs[i]);
410 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
411 int pkts, int total_len)
413 struct vhost_dev *dev = vq->dev;
415 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
416 pkts >= dev->weight) {
417 vhost_poll_queue(&vq->poll);
423 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
425 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
428 size_t event __maybe_unused =
429 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
431 return size_add(struct_size(vq->avail, ring, num), event);
434 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
437 size_t event __maybe_unused =
438 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
440 return size_add(struct_size(vq->used, ring, num), event);
443 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
446 return sizeof(*vq->desc) * num;
449 void vhost_dev_init(struct vhost_dev *dev,
450 struct vhost_virtqueue **vqs, int nvqs,
451 int iov_limit, int weight, int byte_weight,
453 int (*msg_handler)(struct vhost_dev *dev, u32 asid,
454 struct vhost_iotlb_msg *msg))
456 struct vhost_virtqueue *vq;
461 mutex_init(&dev->mutex);
467 dev->iov_limit = iov_limit;
468 dev->weight = weight;
469 dev->byte_weight = byte_weight;
470 dev->use_worker = use_worker;
471 dev->msg_handler = msg_handler;
472 init_waitqueue_head(&dev->wait);
473 INIT_LIST_HEAD(&dev->read_list);
474 INIT_LIST_HEAD(&dev->pending_list);
475 spin_lock_init(&dev->iotlb_lock);
478 for (i = 0; i < dev->nvqs; ++i) {
484 mutex_init(&vq->mutex);
485 vhost_vq_reset(dev, vq);
487 vhost_poll_init(&vq->poll, vq->handle_kick,
491 EXPORT_SYMBOL_GPL(vhost_dev_init);
493 /* Caller should have device mutex */
494 long vhost_dev_check_owner(struct vhost_dev *dev)
496 /* Are you the owner? If not, I don't think you mean to do that */
497 return dev->mm == current->mm ? 0 : -EPERM;
499 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
501 /* Caller should have device mutex */
502 bool vhost_dev_has_owner(struct vhost_dev *dev)
506 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
508 static void vhost_attach_mm(struct vhost_dev *dev)
510 /* No owner, become one */
511 if (dev->use_worker) {
512 dev->mm = get_task_mm(current);
514 /* vDPA device does not use worker thead, so there's
515 * no need to hold the address space for mm. This help
516 * to avoid deadlock in the case of mmap() which may
517 * held the refcnt of the file and depends on release
518 * method to remove vma.
520 dev->mm = current->mm;
525 static void vhost_detach_mm(struct vhost_dev *dev)
538 static void vhost_worker_free(struct vhost_dev *dev)
543 WARN_ON(!llist_empty(&dev->worker->work_list));
544 vhost_task_stop(dev->worker->vtsk);
549 static struct vhost_worker *vhost_worker_create(struct vhost_dev *dev)
551 struct vhost_worker *worker;
552 struct vhost_task *vtsk;
553 char name[TASK_COMM_LEN];
555 worker = kzalloc(sizeof(*worker), GFP_KERNEL_ACCOUNT);
559 snprintf(name, sizeof(name), "vhost-%d", current->pid);
561 vtsk = vhost_task_create(vhost_worker, worker, name);
565 init_llist_head(&worker->work_list);
566 worker->kcov_handle = kcov_common_handle();
569 * vsock can already try to queue so make sure llist and vtsk are both
570 * set before vhost_work_queue sees dev->worker is set.
573 dev->worker = worker;
575 vhost_task_start(vtsk);
583 /* Caller should have device mutex */
584 long vhost_dev_set_owner(struct vhost_dev *dev)
586 struct vhost_worker *worker;
589 /* Is there an owner already? */
590 if (vhost_dev_has_owner(dev)) {
595 vhost_attach_mm(dev);
597 err = vhost_dev_alloc_iovecs(dev);
601 if (dev->use_worker) {
603 * This should be done last, because vsock can queue work
604 * before VHOST_SET_OWNER so it simplifies the failure path
605 * below since we don't have to worry about vsock queueing
606 * while we free the worker.
608 worker = vhost_worker_create(dev);
614 for (i = 0; i < dev->nvqs; i++)
615 dev->vqs[i]->worker = worker;
621 vhost_dev_free_iovecs(dev);
623 vhost_detach_mm(dev);
627 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
629 static struct vhost_iotlb *iotlb_alloc(void)
631 return vhost_iotlb_alloc(max_iotlb_entries,
632 VHOST_IOTLB_FLAG_RETIRE);
635 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void)
637 return iotlb_alloc();
639 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
641 /* Caller should have device mutex */
642 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem)
646 vhost_dev_cleanup(dev);
649 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
650 * VQs aren't running.
652 for (i = 0; i < dev->nvqs; ++i)
653 dev->vqs[i]->umem = umem;
655 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
657 void vhost_dev_stop(struct vhost_dev *dev)
661 for (i = 0; i < dev->nvqs; ++i) {
662 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick)
663 vhost_poll_stop(&dev->vqs[i]->poll);
666 vhost_dev_flush(dev);
668 EXPORT_SYMBOL_GPL(vhost_dev_stop);
670 void vhost_clear_msg(struct vhost_dev *dev)
672 struct vhost_msg_node *node, *n;
674 spin_lock(&dev->iotlb_lock);
676 list_for_each_entry_safe(node, n, &dev->read_list, node) {
677 list_del(&node->node);
681 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
682 list_del(&node->node);
686 spin_unlock(&dev->iotlb_lock);
688 EXPORT_SYMBOL_GPL(vhost_clear_msg);
690 void vhost_dev_cleanup(struct vhost_dev *dev)
694 for (i = 0; i < dev->nvqs; ++i) {
695 if (dev->vqs[i]->error_ctx)
696 eventfd_ctx_put(dev->vqs[i]->error_ctx);
697 if (dev->vqs[i]->kick)
698 fput(dev->vqs[i]->kick);
699 if (dev->vqs[i]->call_ctx.ctx)
700 eventfd_ctx_put(dev->vqs[i]->call_ctx.ctx);
701 vhost_vq_reset(dev, dev->vqs[i]);
703 vhost_dev_free_iovecs(dev);
705 eventfd_ctx_put(dev->log_ctx);
707 /* No one will access memory at this point */
708 vhost_iotlb_free(dev->umem);
710 vhost_iotlb_free(dev->iotlb);
712 vhost_clear_msg(dev);
713 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
714 vhost_worker_free(dev);
715 vhost_detach_mm(dev);
717 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
719 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
721 u64 a = addr / VHOST_PAGE_SIZE / 8;
723 /* Make sure 64 bit math will not overflow. */
724 if (a > ULONG_MAX - (unsigned long)log_base ||
725 a + (unsigned long)log_base > ULONG_MAX)
728 return access_ok(log_base + a,
729 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
732 /* Make sure 64 bit math will not overflow. */
733 static bool vhost_overflow(u64 uaddr, u64 size)
735 if (uaddr > ULONG_MAX || size > ULONG_MAX)
741 return uaddr > ULONG_MAX - size + 1;
744 /* Caller should have vq mutex and device mutex. */
745 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem,
748 struct vhost_iotlb_map *map;
753 list_for_each_entry(map, &umem->list, link) {
754 unsigned long a = map->addr;
756 if (vhost_overflow(map->addr, map->size))
760 if (!access_ok((void __user *)a, map->size))
762 else if (log_all && !log_access_ok(log_base,
770 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
771 u64 addr, unsigned int size,
774 const struct vhost_iotlb_map *map = vq->meta_iotlb[type];
779 return (void __user *)(uintptr_t)(map->addr + addr - map->start);
782 /* Can we switch to this memory table? */
783 /* Caller should have device mutex but not vq mutex */
784 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem,
789 for (i = 0; i < d->nvqs; ++i) {
793 mutex_lock(&d->vqs[i]->mutex);
794 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
795 /* If ring is inactive, will check when it's enabled. */
796 if (d->vqs[i]->private_data)
797 ok = vq_memory_access_ok(d->vqs[i]->log_base,
801 mutex_unlock(&d->vqs[i]->mutex);
808 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
809 struct iovec iov[], int iov_size, int access);
811 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
812 const void *from, unsigned size)
817 return __copy_to_user(to, from, size);
819 /* This function should be called after iotlb
820 * prefetch, which means we're sure that all vq
821 * could be access through iotlb. So -EAGAIN should
822 * not happen in this case.
825 void __user *uaddr = vhost_vq_meta_fetch(vq,
826 (u64)(uintptr_t)to, size,
830 return __copy_to_user(uaddr, from, size);
832 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
833 ARRAY_SIZE(vq->iotlb_iov),
837 iov_iter_init(&t, ITER_DEST, vq->iotlb_iov, ret, size);
838 ret = copy_to_iter(from, size, &t);
846 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
847 void __user *from, unsigned size)
852 return __copy_from_user(to, from, size);
854 /* This function should be called after iotlb
855 * prefetch, which means we're sure that vq
856 * could be access through iotlb. So -EAGAIN should
857 * not happen in this case.
859 void __user *uaddr = vhost_vq_meta_fetch(vq,
860 (u64)(uintptr_t)from, size,
865 return __copy_from_user(to, uaddr, size);
867 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
868 ARRAY_SIZE(vq->iotlb_iov),
871 vq_err(vq, "IOTLB translation failure: uaddr "
872 "%p size 0x%llx\n", from,
873 (unsigned long long) size);
876 iov_iter_init(&f, ITER_SOURCE, vq->iotlb_iov, ret, size);
877 ret = copy_from_iter(to, size, &f);
886 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
887 void __user *addr, unsigned int size,
892 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
893 ARRAY_SIZE(vq->iotlb_iov),
896 vq_err(vq, "IOTLB translation failure: uaddr "
897 "%p size 0x%llx\n", addr,
898 (unsigned long long) size);
902 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
903 vq_err(vq, "Non atomic userspace memory access: uaddr "
904 "%p size 0x%llx\n", addr,
905 (unsigned long long) size);
909 return vq->iotlb_iov[0].iov_base;
912 /* This function should be called after iotlb
913 * prefetch, which means we're sure that vq
914 * could be access through iotlb. So -EAGAIN should
915 * not happen in this case.
917 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
918 void __user *addr, unsigned int size,
921 void __user *uaddr = vhost_vq_meta_fetch(vq,
922 (u64)(uintptr_t)addr, size, type);
926 return __vhost_get_user_slow(vq, addr, size, type);
929 #define vhost_put_user(vq, x, ptr) \
933 ret = __put_user(x, ptr); \
935 __typeof__(ptr) to = \
936 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
937 sizeof(*ptr), VHOST_ADDR_USED); \
939 ret = __put_user(x, to); \
946 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
948 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
949 vhost_avail_event(vq));
952 static inline int vhost_put_used(struct vhost_virtqueue *vq,
953 struct vring_used_elem *head, int idx,
956 return vhost_copy_to_user(vq, vq->used->ring + idx, head,
957 count * sizeof(*head));
960 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
963 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
967 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
970 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
974 #define vhost_get_user(vq, x, ptr, type) \
978 ret = __get_user(x, ptr); \
980 __typeof__(ptr) from = \
981 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
985 ret = __get_user(x, from); \
992 #define vhost_get_avail(vq, x, ptr) \
993 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
995 #define vhost_get_used(vq, x, ptr) \
996 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
998 static void vhost_dev_lock_vqs(struct vhost_dev *d)
1001 for (i = 0; i < d->nvqs; ++i)
1002 mutex_lock_nested(&d->vqs[i]->mutex, i);
1005 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
1008 for (i = 0; i < d->nvqs; ++i)
1009 mutex_unlock(&d->vqs[i]->mutex);
1012 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
1015 return vhost_get_avail(vq, *idx, &vq->avail->idx);
1018 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
1019 __virtio16 *head, int idx)
1021 return vhost_get_avail(vq, *head,
1022 &vq->avail->ring[idx & (vq->num - 1)]);
1025 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1028 return vhost_get_avail(vq, *flags, &vq->avail->flags);
1031 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1034 return vhost_get_avail(vq, *event, vhost_used_event(vq));
1037 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1040 return vhost_get_used(vq, *idx, &vq->used->idx);
1043 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1044 struct vring_desc *desc, int idx)
1046 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1049 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1050 struct vhost_iotlb_msg *msg)
1052 struct vhost_msg_node *node, *n;
1054 spin_lock(&d->iotlb_lock);
1056 list_for_each_entry_safe(node, n, &d->pending_list, node) {
1057 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1058 if (msg->iova <= vq_msg->iova &&
1059 msg->iova + msg->size - 1 >= vq_msg->iova &&
1060 vq_msg->type == VHOST_IOTLB_MISS) {
1061 vhost_poll_queue(&node->vq->poll);
1062 list_del(&node->node);
1067 spin_unlock(&d->iotlb_lock);
1070 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1072 unsigned long a = uaddr;
1074 /* Make sure 64 bit math will not overflow. */
1075 if (vhost_overflow(uaddr, size))
1078 if ((access & VHOST_ACCESS_RO) &&
1079 !access_ok((void __user *)a, size))
1081 if ((access & VHOST_ACCESS_WO) &&
1082 !access_ok((void __user *)a, size))
1087 static int vhost_process_iotlb_msg(struct vhost_dev *dev, u32 asid,
1088 struct vhost_iotlb_msg *msg)
1095 mutex_lock(&dev->mutex);
1096 vhost_dev_lock_vqs(dev);
1097 switch (msg->type) {
1098 case VHOST_IOTLB_UPDATE:
1103 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1107 vhost_vq_meta_reset(dev);
1108 if (vhost_iotlb_add_range(dev->iotlb, msg->iova,
1109 msg->iova + msg->size - 1,
1110 msg->uaddr, msg->perm)) {
1114 vhost_iotlb_notify_vq(dev, msg);
1116 case VHOST_IOTLB_INVALIDATE:
1121 vhost_vq_meta_reset(dev);
1122 vhost_iotlb_del_range(dev->iotlb, msg->iova,
1123 msg->iova + msg->size - 1);
1130 vhost_dev_unlock_vqs(dev);
1131 mutex_unlock(&dev->mutex);
1135 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1136 struct iov_iter *from)
1138 struct vhost_iotlb_msg msg;
1143 ret = copy_from_iter(&type, sizeof(type), from);
1144 if (ret != sizeof(type)) {
1150 case VHOST_IOTLB_MSG:
1151 /* There maybe a hole after type for V1 message type,
1154 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1156 case VHOST_IOTLB_MSG_V2:
1157 if (vhost_backend_has_feature(dev->vqs[0],
1158 VHOST_BACKEND_F_IOTLB_ASID)) {
1159 ret = copy_from_iter(&asid, sizeof(asid), from);
1160 if (ret != sizeof(asid)) {
1166 offset = sizeof(__u32);
1173 iov_iter_advance(from, offset);
1174 ret = copy_from_iter(&msg, sizeof(msg), from);
1175 if (ret != sizeof(msg)) {
1180 if ((msg.type == VHOST_IOTLB_UPDATE ||
1181 msg.type == VHOST_IOTLB_INVALIDATE) &&
1187 if (dev->msg_handler)
1188 ret = dev->msg_handler(dev, asid, &msg);
1190 ret = vhost_process_iotlb_msg(dev, asid, &msg);
1196 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1197 sizeof(struct vhost_msg_v2);
1201 EXPORT_SYMBOL(vhost_chr_write_iter);
1203 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1208 poll_wait(file, &dev->wait, wait);
1210 if (!list_empty(&dev->read_list))
1211 mask |= EPOLLIN | EPOLLRDNORM;
1215 EXPORT_SYMBOL(vhost_chr_poll);
1217 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1221 struct vhost_msg_node *node;
1223 unsigned size = sizeof(struct vhost_msg);
1225 if (iov_iter_count(to) < size)
1230 prepare_to_wait(&dev->wait, &wait,
1231 TASK_INTERRUPTIBLE);
1233 node = vhost_dequeue_msg(dev, &dev->read_list);
1240 if (signal_pending(current)) {
1253 finish_wait(&dev->wait, &wait);
1256 struct vhost_iotlb_msg *msg;
1257 void *start = &node->msg;
1259 switch (node->msg.type) {
1260 case VHOST_IOTLB_MSG:
1261 size = sizeof(node->msg);
1262 msg = &node->msg.iotlb;
1264 case VHOST_IOTLB_MSG_V2:
1265 size = sizeof(node->msg_v2);
1266 msg = &node->msg_v2.iotlb;
1273 ret = copy_to_iter(start, size, to);
1274 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1278 vhost_enqueue_msg(dev, &dev->pending_list, node);
1283 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1285 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1287 struct vhost_dev *dev = vq->dev;
1288 struct vhost_msg_node *node;
1289 struct vhost_iotlb_msg *msg;
1290 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1292 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1297 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1298 msg = &node->msg_v2.iotlb;
1300 msg = &node->msg.iotlb;
1303 msg->type = VHOST_IOTLB_MISS;
1307 vhost_enqueue_msg(dev, &dev->read_list, node);
1312 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1313 vring_desc_t __user *desc,
1314 vring_avail_t __user *avail,
1315 vring_used_t __user *used)
1318 /* If an IOTLB device is present, the vring addresses are
1319 * GIOVAs. Access validation occurs at prefetch time. */
1323 return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1324 access_ok(avail, vhost_get_avail_size(vq, num)) &&
1325 access_ok(used, vhost_get_used_size(vq, num));
1328 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1329 const struct vhost_iotlb_map *map,
1332 int access = (type == VHOST_ADDR_USED) ?
1333 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1335 if (likely(map->perm & access))
1336 vq->meta_iotlb[type] = map;
1339 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1340 int access, u64 addr, u64 len, int type)
1342 const struct vhost_iotlb_map *map;
1343 struct vhost_iotlb *umem = vq->iotlb;
1344 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1346 if (vhost_vq_meta_fetch(vq, addr, len, type))
1350 map = vhost_iotlb_itree_first(umem, addr, last);
1351 if (map == NULL || map->start > addr) {
1352 vhost_iotlb_miss(vq, addr, access);
1354 } else if (!(map->perm & access)) {
1355 /* Report the possible access violation by
1356 * request another translation from userspace.
1361 size = map->size - addr + map->start;
1363 if (orig_addr == addr && size >= len)
1364 vhost_vq_meta_update(vq, map, type);
1373 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1375 unsigned int num = vq->num;
1380 return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc,
1381 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1382 iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail,
1383 vhost_get_avail_size(vq, num),
1384 VHOST_ADDR_AVAIL) &&
1385 iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used,
1386 vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1388 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1390 /* Can we log writes? */
1391 /* Caller should have device mutex but not vq mutex */
1392 bool vhost_log_access_ok(struct vhost_dev *dev)
1394 return memory_access_ok(dev, dev->umem, 1);
1396 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1398 static bool vq_log_used_access_ok(struct vhost_virtqueue *vq,
1399 void __user *log_base,
1403 /* If an IOTLB device is present, log_addr is a GIOVA that
1404 * will never be logged by log_used(). */
1408 return !log_used || log_access_ok(log_base, log_addr,
1409 vhost_get_used_size(vq, vq->num));
1412 /* Verify access for write logging. */
1413 /* Caller should have vq mutex and device mutex */
1414 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1415 void __user *log_base)
1417 return vq_memory_access_ok(log_base, vq->umem,
1418 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1419 vq_log_used_access_ok(vq, log_base, vq->log_used, vq->log_addr);
1422 /* Can we start vq? */
1423 /* Caller should have vq mutex and device mutex */
1424 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1426 if (!vq_log_access_ok(vq, vq->log_base))
1429 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1431 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1433 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1435 struct vhost_memory mem, *newmem;
1436 struct vhost_memory_region *region;
1437 struct vhost_iotlb *newumem, *oldumem;
1438 unsigned long size = offsetof(struct vhost_memory, regions);
1441 if (copy_from_user(&mem, m, size))
1445 if (mem.nregions > max_mem_regions)
1447 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1452 memcpy(newmem, &mem, size);
1453 if (copy_from_user(newmem->regions, m->regions,
1454 flex_array_size(newmem, regions, mem.nregions))) {
1459 newumem = iotlb_alloc();
1465 for (region = newmem->regions;
1466 region < newmem->regions + mem.nregions;
1468 if (vhost_iotlb_add_range(newumem,
1469 region->guest_phys_addr,
1470 region->guest_phys_addr +
1471 region->memory_size - 1,
1472 region->userspace_addr,
1477 if (!memory_access_ok(d, newumem, 0))
1483 /* All memory accesses are done under some VQ mutex. */
1484 for (i = 0; i < d->nvqs; ++i) {
1485 mutex_lock(&d->vqs[i]->mutex);
1486 d->vqs[i]->umem = newumem;
1487 mutex_unlock(&d->vqs[i]->mutex);
1491 vhost_iotlb_free(oldumem);
1495 vhost_iotlb_free(newumem);
1500 static long vhost_vring_set_num(struct vhost_dev *d,
1501 struct vhost_virtqueue *vq,
1504 struct vhost_vring_state s;
1506 /* Resizing ring with an active backend?
1507 * You don't want to do that. */
1508 if (vq->private_data)
1511 if (copy_from_user(&s, argp, sizeof s))
1514 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
1521 static long vhost_vring_set_addr(struct vhost_dev *d,
1522 struct vhost_virtqueue *vq,
1525 struct vhost_vring_addr a;
1527 if (copy_from_user(&a, argp, sizeof a))
1529 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
1532 /* For 32bit, verify that the top 32bits of the user
1533 data are set to zero. */
1534 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1535 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1536 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
1539 /* Make sure it's safe to cast pointers to vring types. */
1540 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1541 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1542 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1543 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1544 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
1547 /* We only verify access here if backend is configured.
1548 * If it is not, we don't as size might not have been setup.
1549 * We will verify when backend is configured. */
1550 if (vq->private_data) {
1551 if (!vq_access_ok(vq, vq->num,
1552 (void __user *)(unsigned long)a.desc_user_addr,
1553 (void __user *)(unsigned long)a.avail_user_addr,
1554 (void __user *)(unsigned long)a.used_user_addr))
1557 /* Also validate log access for used ring if enabled. */
1558 if (!vq_log_used_access_ok(vq, vq->log_base,
1559 a.flags & (0x1 << VHOST_VRING_F_LOG),
1564 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1565 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1566 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1567 vq->log_addr = a.log_guest_addr;
1568 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1573 static long vhost_vring_set_num_addr(struct vhost_dev *d,
1574 struct vhost_virtqueue *vq,
1580 mutex_lock(&vq->mutex);
1583 case VHOST_SET_VRING_NUM:
1584 r = vhost_vring_set_num(d, vq, argp);
1586 case VHOST_SET_VRING_ADDR:
1587 r = vhost_vring_set_addr(d, vq, argp);
1593 mutex_unlock(&vq->mutex);
1597 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1599 struct file *eventfp, *filep = NULL;
1600 bool pollstart = false, pollstop = false;
1601 struct eventfd_ctx *ctx = NULL;
1602 u32 __user *idxp = argp;
1603 struct vhost_virtqueue *vq;
1604 struct vhost_vring_state s;
1605 struct vhost_vring_file f;
1609 r = get_user(idx, idxp);
1615 idx = array_index_nospec(idx, d->nvqs);
1618 if (ioctl == VHOST_SET_VRING_NUM ||
1619 ioctl == VHOST_SET_VRING_ADDR) {
1620 return vhost_vring_set_num_addr(d, vq, ioctl, argp);
1623 mutex_lock(&vq->mutex);
1626 case VHOST_SET_VRING_BASE:
1627 /* Moving base with an active backend?
1628 * You don't want to do that. */
1629 if (vq->private_data) {
1633 if (copy_from_user(&s, argp, sizeof s)) {
1637 if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) {
1638 vq->last_avail_idx = s.num & 0xffff;
1639 vq->last_used_idx = (s.num >> 16) & 0xffff;
1641 if (s.num > 0xffff) {
1645 vq->last_avail_idx = s.num;
1647 /* Forget the cached index value. */
1648 vq->avail_idx = vq->last_avail_idx;
1650 case VHOST_GET_VRING_BASE:
1652 if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED))
1653 s.num = (u32)vq->last_avail_idx | ((u32)vq->last_used_idx << 16);
1655 s.num = vq->last_avail_idx;
1656 if (copy_to_user(argp, &s, sizeof s))
1659 case VHOST_SET_VRING_KICK:
1660 if (copy_from_user(&f, argp, sizeof f)) {
1664 eventfp = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_fget(f.fd);
1665 if (IS_ERR(eventfp)) {
1666 r = PTR_ERR(eventfp);
1669 if (eventfp != vq->kick) {
1670 pollstop = (filep = vq->kick) != NULL;
1671 pollstart = (vq->kick = eventfp) != NULL;
1675 case VHOST_SET_VRING_CALL:
1676 if (copy_from_user(&f, argp, sizeof f)) {
1680 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
1686 swap(ctx, vq->call_ctx.ctx);
1688 case VHOST_SET_VRING_ERR:
1689 if (copy_from_user(&f, argp, sizeof f)) {
1693 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
1698 swap(ctx, vq->error_ctx);
1700 case VHOST_SET_VRING_ENDIAN:
1701 r = vhost_set_vring_endian(vq, argp);
1703 case VHOST_GET_VRING_ENDIAN:
1704 r = vhost_get_vring_endian(vq, idx, argp);
1706 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1707 if (copy_from_user(&s, argp, sizeof(s))) {
1711 vq->busyloop_timeout = s.num;
1713 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1715 s.num = vq->busyloop_timeout;
1716 if (copy_to_user(argp, &s, sizeof(s)))
1723 if (pollstop && vq->handle_kick)
1724 vhost_poll_stop(&vq->poll);
1726 if (!IS_ERR_OR_NULL(ctx))
1727 eventfd_ctx_put(ctx);
1731 if (pollstart && vq->handle_kick)
1732 r = vhost_poll_start(&vq->poll, vq->kick);
1734 mutex_unlock(&vq->mutex);
1736 if (pollstop && vq->handle_kick)
1737 vhost_dev_flush(vq->poll.dev);
1740 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1742 int vhost_init_device_iotlb(struct vhost_dev *d)
1744 struct vhost_iotlb *niotlb, *oiotlb;
1747 niotlb = iotlb_alloc();
1754 for (i = 0; i < d->nvqs; ++i) {
1755 struct vhost_virtqueue *vq = d->vqs[i];
1757 mutex_lock(&vq->mutex);
1759 __vhost_vq_meta_reset(vq);
1760 mutex_unlock(&vq->mutex);
1763 vhost_iotlb_free(oiotlb);
1767 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1769 /* Caller must have device mutex */
1770 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1772 struct eventfd_ctx *ctx;
1777 /* If you are not the owner, you can become one */
1778 if (ioctl == VHOST_SET_OWNER) {
1779 r = vhost_dev_set_owner(d);
1783 /* You must be the owner to do anything else */
1784 r = vhost_dev_check_owner(d);
1789 case VHOST_SET_MEM_TABLE:
1790 r = vhost_set_memory(d, argp);
1792 case VHOST_SET_LOG_BASE:
1793 if (copy_from_user(&p, argp, sizeof p)) {
1797 if ((u64)(unsigned long)p != p) {
1801 for (i = 0; i < d->nvqs; ++i) {
1802 struct vhost_virtqueue *vq;
1803 void __user *base = (void __user *)(unsigned long)p;
1805 mutex_lock(&vq->mutex);
1806 /* If ring is inactive, will check when it's enabled. */
1807 if (vq->private_data && !vq_log_access_ok(vq, base))
1810 vq->log_base = base;
1811 mutex_unlock(&vq->mutex);
1814 case VHOST_SET_LOG_FD:
1815 r = get_user(fd, (int __user *)argp);
1818 ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd);
1823 swap(ctx, d->log_ctx);
1824 for (i = 0; i < d->nvqs; ++i) {
1825 mutex_lock(&d->vqs[i]->mutex);
1826 d->vqs[i]->log_ctx = d->log_ctx;
1827 mutex_unlock(&d->vqs[i]->mutex);
1830 eventfd_ctx_put(ctx);
1839 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1841 /* TODO: This is really inefficient. We need something like get_user()
1842 * (instruction directly accesses the data, with an exception table entry
1843 * returning -EFAULT). See Documentation/arch/x86/exception-tables.rst.
1845 static int set_bit_to_user(int nr, void __user *addr)
1847 unsigned long log = (unsigned long)addr;
1850 int bit = nr + (log % PAGE_SIZE) * 8;
1853 r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page);
1857 base = kmap_atomic(page);
1859 kunmap_atomic(base);
1860 unpin_user_pages_dirty_lock(&page, 1, true);
1864 static int log_write(void __user *log_base,
1865 u64 write_address, u64 write_length)
1867 u64 write_page = write_address / VHOST_PAGE_SIZE;
1872 write_length += write_address % VHOST_PAGE_SIZE;
1874 u64 base = (u64)(unsigned long)log_base;
1875 u64 log = base + write_page / 8;
1876 int bit = write_page % 8;
1877 if ((u64)(unsigned long)log != log)
1879 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1882 if (write_length <= VHOST_PAGE_SIZE)
1884 write_length -= VHOST_PAGE_SIZE;
1890 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1892 struct vhost_iotlb *umem = vq->umem;
1893 struct vhost_iotlb_map *u;
1894 u64 start, end, l, min;
1900 /* More than one GPAs can be mapped into a single HVA. So
1901 * iterate all possible umems here to be safe.
1903 list_for_each_entry(u, &umem->list, link) {
1904 if (u->addr > hva - 1 + len ||
1905 u->addr - 1 + u->size < hva)
1907 start = max(u->addr, hva);
1908 end = min(u->addr - 1 + u->size, hva - 1 + len);
1909 l = end - start + 1;
1910 r = log_write(vq->log_base,
1911 u->start + start - u->addr,
1929 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1931 struct iovec *iov = vq->log_iov;
1935 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1937 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1938 len, iov, 64, VHOST_ACCESS_WO);
1942 for (i = 0; i < ret; i++) {
1943 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1952 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1953 unsigned int log_num, u64 len, struct iovec *iov, int count)
1957 /* Make sure data written is seen before log. */
1961 for (i = 0; i < count; i++) {
1962 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1970 for (i = 0; i < log_num; ++i) {
1971 u64 l = min(log[i].len, len);
1972 r = log_write(vq->log_base, log[i].addr, l);
1978 eventfd_signal(vq->log_ctx, 1);
1982 /* Length written exceeds what we have stored. This is a bug. */
1986 EXPORT_SYMBOL_GPL(vhost_log_write);
1988 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1991 if (vhost_put_used_flags(vq))
1993 if (unlikely(vq->log_used)) {
1994 /* Make sure the flag is seen before log. */
1996 /* Log used flag write. */
1997 used = &vq->used->flags;
1998 log_used(vq, (used - (void __user *)vq->used),
1999 sizeof vq->used->flags);
2001 eventfd_signal(vq->log_ctx, 1);
2006 static int vhost_update_avail_event(struct vhost_virtqueue *vq)
2008 if (vhost_put_avail_event(vq))
2010 if (unlikely(vq->log_used)) {
2012 /* Make sure the event is seen before log. */
2014 /* Log avail event write */
2015 used = vhost_avail_event(vq);
2016 log_used(vq, (used - (void __user *)vq->used),
2017 sizeof *vhost_avail_event(vq));
2019 eventfd_signal(vq->log_ctx, 1);
2024 int vhost_vq_init_access(struct vhost_virtqueue *vq)
2026 __virtio16 last_used_idx;
2028 bool is_le = vq->is_le;
2030 if (!vq->private_data)
2033 vhost_init_is_le(vq);
2035 r = vhost_update_used_flags(vq);
2038 vq->signalled_used_valid = false;
2040 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
2044 r = vhost_get_used_idx(vq, &last_used_idx);
2046 vq_err(vq, "Can't access used idx at %p\n",
2050 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2057 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2059 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2060 struct iovec iov[], int iov_size, int access)
2062 const struct vhost_iotlb_map *map;
2063 struct vhost_dev *dev = vq->dev;
2064 struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
2066 u64 s = 0, last = addr + len - 1;
2069 while ((u64)len > s) {
2071 if (unlikely(ret >= iov_size)) {
2076 map = vhost_iotlb_itree_first(umem, addr, last);
2077 if (map == NULL || map->start > addr) {
2078 if (umem != dev->iotlb) {
2084 } else if (!(map->perm & access)) {
2090 size = map->size - addr + map->start;
2091 _iov->iov_len = min((u64)len - s, size);
2092 _iov->iov_base = (void __user *)(unsigned long)
2093 (map->addr + addr - map->start);
2100 vhost_iotlb_miss(vq, addr, access);
2104 /* Each buffer in the virtqueues is actually a chain of descriptors. This
2105 * function returns the next descriptor in the chain,
2106 * or -1U if we're at the end. */
2107 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2111 /* If this descriptor says it doesn't chain, we're done. */
2112 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2115 /* Check they're not leading us off end of descriptors. */
2116 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2120 static int get_indirect(struct vhost_virtqueue *vq,
2121 struct iovec iov[], unsigned int iov_size,
2122 unsigned int *out_num, unsigned int *in_num,
2123 struct vhost_log *log, unsigned int *log_num,
2124 struct vring_desc *indirect)
2126 struct vring_desc desc;
2127 unsigned int i = 0, count, found = 0;
2128 u32 len = vhost32_to_cpu(vq, indirect->len);
2129 struct iov_iter from;
2133 if (unlikely(len % sizeof desc)) {
2134 vq_err(vq, "Invalid length in indirect descriptor: "
2135 "len 0x%llx not multiple of 0x%zx\n",
2136 (unsigned long long)len,
2141 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2142 UIO_MAXIOV, VHOST_ACCESS_RO);
2143 if (unlikely(ret < 0)) {
2145 vq_err(vq, "Translation failure %d in indirect.\n", ret);
2148 iov_iter_init(&from, ITER_SOURCE, vq->indirect, ret, len);
2149 count = len / sizeof desc;
2150 /* Buffers are chained via a 16 bit next field, so
2151 * we can have at most 2^16 of these. */
2152 if (unlikely(count > USHRT_MAX + 1)) {
2153 vq_err(vq, "Indirect buffer length too big: %d\n",
2159 unsigned iov_count = *in_num + *out_num;
2160 if (unlikely(++found > count)) {
2161 vq_err(vq, "Loop detected: last one at %u "
2162 "indirect size %u\n",
2166 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2167 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2168 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2171 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2172 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2173 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2177 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2178 access = VHOST_ACCESS_WO;
2180 access = VHOST_ACCESS_RO;
2182 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2183 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2184 iov_size - iov_count, access);
2185 if (unlikely(ret < 0)) {
2187 vq_err(vq, "Translation failure %d indirect idx %d\n",
2191 /* If this is an input descriptor, increment that count. */
2192 if (access == VHOST_ACCESS_WO) {
2194 if (unlikely(log && ret)) {
2195 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2196 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2200 /* If it's an output descriptor, they're all supposed
2201 * to come before any input descriptors. */
2202 if (unlikely(*in_num)) {
2203 vq_err(vq, "Indirect descriptor "
2204 "has out after in: idx %d\n", i);
2209 } while ((i = next_desc(vq, &desc)) != -1);
2213 /* This looks in the virtqueue and for the first available buffer, and converts
2214 * it to an iovec for convenient access. Since descriptors consist of some
2215 * number of output then some number of input descriptors, it's actually two
2216 * iovecs, but we pack them into one and note how many of each there were.
2218 * This function returns the descriptor number found, or vq->num (which is
2219 * never a valid descriptor number) if none was found. A negative code is
2220 * returned on error. */
2221 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2222 struct iovec iov[], unsigned int iov_size,
2223 unsigned int *out_num, unsigned int *in_num,
2224 struct vhost_log *log, unsigned int *log_num)
2226 struct vring_desc desc;
2227 unsigned int i, head, found = 0;
2229 __virtio16 avail_idx;
2230 __virtio16 ring_head;
2233 /* Check it isn't doing very strange things with descriptor numbers. */
2234 last_avail_idx = vq->last_avail_idx;
2236 if (vq->avail_idx == vq->last_avail_idx) {
2237 if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
2238 vq_err(vq, "Failed to access avail idx at %p\n",
2242 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2244 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2245 vq_err(vq, "Guest moved used index from %u to %u",
2246 last_avail_idx, vq->avail_idx);
2250 /* If there's nothing new since last we looked, return
2253 if (vq->avail_idx == last_avail_idx)
2256 /* Only get avail ring entries after they have been
2262 /* Grab the next descriptor number they're advertising, and increment
2263 * the index we've seen. */
2264 if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
2265 vq_err(vq, "Failed to read head: idx %d address %p\n",
2267 &vq->avail->ring[last_avail_idx % vq->num]);
2271 head = vhost16_to_cpu(vq, ring_head);
2273 /* If their number is silly, that's an error. */
2274 if (unlikely(head >= vq->num)) {
2275 vq_err(vq, "Guest says index %u > %u is available",
2280 /* When we start there are none of either input nor output. */
2281 *out_num = *in_num = 0;
2287 unsigned iov_count = *in_num + *out_num;
2288 if (unlikely(i >= vq->num)) {
2289 vq_err(vq, "Desc index is %u > %u, head = %u",
2293 if (unlikely(++found > vq->num)) {
2294 vq_err(vq, "Loop detected: last one at %u "
2295 "vq size %u head %u\n",
2299 ret = vhost_get_desc(vq, &desc, i);
2300 if (unlikely(ret)) {
2301 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2305 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2306 ret = get_indirect(vq, iov, iov_size,
2308 log, log_num, &desc);
2309 if (unlikely(ret < 0)) {
2311 vq_err(vq, "Failure detected "
2312 "in indirect descriptor at idx %d\n", i);
2318 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2319 access = VHOST_ACCESS_WO;
2321 access = VHOST_ACCESS_RO;
2322 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2323 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2324 iov_size - iov_count, access);
2325 if (unlikely(ret < 0)) {
2327 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2331 if (access == VHOST_ACCESS_WO) {
2332 /* If this is an input descriptor,
2333 * increment that count. */
2335 if (unlikely(log && ret)) {
2336 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2337 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2341 /* If it's an output descriptor, they're all supposed
2342 * to come before any input descriptors. */
2343 if (unlikely(*in_num)) {
2344 vq_err(vq, "Descriptor has out after in: "
2350 } while ((i = next_desc(vq, &desc)) != -1);
2352 /* On success, increment avail index. */
2353 vq->last_avail_idx++;
2355 /* Assume notifications from guest are disabled at this point,
2356 * if they aren't we would need to update avail_event index. */
2357 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2360 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2362 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2363 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2365 vq->last_avail_idx -= n;
2367 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
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(struct vhost_virtqueue *vq, unsigned int head, int len)
2373 struct vring_used_elem heads = {
2374 cpu_to_vhost32(vq, head),
2375 cpu_to_vhost32(vq, len)
2378 return vhost_add_used_n(vq, &heads, 1);
2380 EXPORT_SYMBOL_GPL(vhost_add_used);
2382 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2383 struct vring_used_elem *heads,
2386 vring_used_elem_t __user *used;
2390 start = vq->last_used_idx & (vq->num - 1);
2391 used = vq->used->ring + start;
2392 if (vhost_put_used(vq, heads, start, count)) {
2393 vq_err(vq, "Failed to write used");
2396 if (unlikely(vq->log_used)) {
2397 /* Make sure data is seen before log. */
2399 /* Log used ring entry write. */
2400 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2401 count * sizeof *used);
2403 old = vq->last_used_idx;
2404 new = (vq->last_used_idx += count);
2405 /* If the driver never bothers to signal in a very long while,
2406 * used index might wrap around. If that happens, invalidate
2407 * signalled_used index we stored. TODO: make sure driver
2408 * signals at least once in 2^16 and remove this. */
2409 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2410 vq->signalled_used_valid = false;
2414 /* After we've used one of their buffers, we tell them about it. We'll then
2415 * want to notify the guest, using eventfd. */
2416 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2421 start = vq->last_used_idx & (vq->num - 1);
2422 n = vq->num - start;
2424 r = __vhost_add_used_n(vq, heads, n);
2430 r = __vhost_add_used_n(vq, heads, count);
2432 /* Make sure buffer is written before we update index. */
2434 if (vhost_put_used_idx(vq)) {
2435 vq_err(vq, "Failed to increment used idx");
2438 if (unlikely(vq->log_used)) {
2439 /* Make sure used idx is seen before log. */
2441 /* Log used index update. */
2442 log_used(vq, offsetof(struct vring_used, idx),
2443 sizeof vq->used->idx);
2445 eventfd_signal(vq->log_ctx, 1);
2449 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2451 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2456 /* Flush out used index updates. This is paired
2457 * with the barrier that the Guest executes when enabling
2461 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2462 unlikely(vq->avail_idx == vq->last_avail_idx))
2465 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2467 if (vhost_get_avail_flags(vq, &flags)) {
2468 vq_err(vq, "Failed to get flags");
2471 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2473 old = vq->signalled_used;
2474 v = vq->signalled_used_valid;
2475 new = vq->signalled_used = vq->last_used_idx;
2476 vq->signalled_used_valid = true;
2481 if (vhost_get_used_event(vq, &event)) {
2482 vq_err(vq, "Failed to get used event idx");
2485 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2488 /* This actually signals the guest, using eventfd. */
2489 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2491 /* Signal the Guest tell them we used something up. */
2492 if (vq->call_ctx.ctx && vhost_notify(dev, vq))
2493 eventfd_signal(vq->call_ctx.ctx, 1);
2495 EXPORT_SYMBOL_GPL(vhost_signal);
2497 /* And here's the combo meal deal. Supersize me! */
2498 void vhost_add_used_and_signal(struct vhost_dev *dev,
2499 struct vhost_virtqueue *vq,
2500 unsigned int head, int len)
2502 vhost_add_used(vq, head, len);
2503 vhost_signal(dev, vq);
2505 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2507 /* multi-buffer version of vhost_add_used_and_signal */
2508 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2509 struct vhost_virtqueue *vq,
2510 struct vring_used_elem *heads, unsigned count)
2512 vhost_add_used_n(vq, heads, count);
2513 vhost_signal(dev, vq);
2515 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2517 /* return true if we're sure that avaiable ring is empty */
2518 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2520 __virtio16 avail_idx;
2523 if (vq->avail_idx != vq->last_avail_idx)
2526 r = vhost_get_avail_idx(vq, &avail_idx);
2529 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2531 return vq->avail_idx == vq->last_avail_idx;
2533 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2535 /* OK, now we need to know about added descriptors. */
2536 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2538 __virtio16 avail_idx;
2541 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2543 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2544 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2545 r = vhost_update_used_flags(vq);
2547 vq_err(vq, "Failed to enable notification at %p: %d\n",
2548 &vq->used->flags, r);
2552 r = vhost_update_avail_event(vq);
2554 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2555 vhost_avail_event(vq), r);
2559 /* They could have slipped one in as we were doing that: make
2560 * sure it's written, then check again. */
2562 r = vhost_get_avail_idx(vq, &avail_idx);
2564 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2565 &vq->avail->idx, r);
2568 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2570 return vq->avail_idx != vq->last_avail_idx;
2572 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2574 /* We don't need to be notified again. */
2575 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2579 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2581 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2582 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2583 r = vhost_update_used_flags(vq);
2585 vq_err(vq, "Failed to disable notification at %p: %d\n",
2586 &vq->used->flags, r);
2589 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2591 /* Create a new message. */
2592 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2594 /* Make sure all padding within the structure is initialized. */
2595 struct vhost_msg_node *node = kzalloc(sizeof(*node), GFP_KERNEL);
2600 node->msg.type = type;
2603 EXPORT_SYMBOL_GPL(vhost_new_msg);
2605 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2606 struct vhost_msg_node *node)
2608 spin_lock(&dev->iotlb_lock);
2609 list_add_tail(&node->node, head);
2610 spin_unlock(&dev->iotlb_lock);
2612 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2614 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2616 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2617 struct list_head *head)
2619 struct vhost_msg_node *node = NULL;
2621 spin_lock(&dev->iotlb_lock);
2622 if (!list_empty(head)) {
2623 node = list_first_entry(head, struct vhost_msg_node,
2625 list_del(&node->node);
2627 spin_unlock(&dev->iotlb_lock);
2631 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2633 void vhost_set_backend_features(struct vhost_dev *dev, u64 features)
2635 struct vhost_virtqueue *vq;
2638 mutex_lock(&dev->mutex);
2639 for (i = 0; i < dev->nvqs; ++i) {
2641 mutex_lock(&vq->mutex);
2642 vq->acked_backend_features = features;
2643 mutex_unlock(&vq->mutex);
2645 mutex_unlock(&dev->mutex);
2647 EXPORT_SYMBOL_GPL(vhost_set_backend_features);
2649 static int __init vhost_init(void)
2654 static void __exit vhost_exit(void)
2658 module_init(vhost_init);
2659 module_exit(vhost_exit);
2661 MODULE_VERSION("0.0.1");
2662 MODULE_LICENSE("GPL v2");
2663 MODULE_AUTHOR("Michael S. Tsirkin");
2664 MODULE_DESCRIPTION("Host kernel accelerator for virtio");