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,
191 struct vhost_virtqueue *vq)
193 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
194 init_poll_funcptr(&poll->table, vhost_poll_func);
200 vhost_work_init(&poll->work, fn);
202 EXPORT_SYMBOL_GPL(vhost_poll_init);
204 /* Start polling a file. We add ourselves to file's wait queue. The caller must
205 * keep a reference to a file until after vhost_poll_stop is called. */
206 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
213 mask = vfs_poll(file, &poll->table);
215 vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
216 if (mask & EPOLLERR) {
217 vhost_poll_stop(poll);
223 EXPORT_SYMBOL_GPL(vhost_poll_start);
225 /* Stop polling a file. After this function returns, it becomes safe to drop the
226 * file reference. You must also flush afterwards. */
227 void vhost_poll_stop(struct vhost_poll *poll)
230 remove_wait_queue(poll->wqh, &poll->wait);
234 EXPORT_SYMBOL_GPL(vhost_poll_stop);
236 static bool vhost_worker_queue(struct vhost_worker *worker,
237 struct vhost_work *work)
242 * vsock can queue while we do a VHOST_SET_OWNER, so we have a smp_wmb
243 * when setting up the worker. We don't have a smp_rmb here because
244 * test_and_set_bit gives us a mb already.
246 if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
247 /* We can only add the work to the list after we're
248 * sure it was not in the list.
249 * test_and_set_bit() implies a memory barrier.
251 llist_add(&work->node, &worker->work_list);
252 vhost_task_wake(worker->vtsk);
258 bool vhost_vq_work_queue(struct vhost_virtqueue *vq, struct vhost_work *work)
260 return vhost_worker_queue(vq->worker, work);
262 EXPORT_SYMBOL_GPL(vhost_vq_work_queue);
264 static void vhost_worker_flush(struct vhost_worker *worker)
266 struct vhost_flush_struct flush;
268 init_completion(&flush.wait_event);
269 vhost_work_init(&flush.work, vhost_flush_work);
271 if (vhost_worker_queue(worker, &flush.work))
272 wait_for_completion(&flush.wait_event);
275 void vhost_vq_flush(struct vhost_virtqueue *vq)
277 vhost_worker_flush(vq->worker);
279 EXPORT_SYMBOL_GPL(vhost_vq_flush);
281 void vhost_dev_flush(struct vhost_dev *dev)
283 vhost_worker_flush(dev->worker);
285 EXPORT_SYMBOL_GPL(vhost_dev_flush);
287 /* A lockless hint for busy polling code to exit the loop */
288 bool vhost_vq_has_work(struct vhost_virtqueue *vq)
290 return !llist_empty(&vq->worker->work_list);
292 EXPORT_SYMBOL_GPL(vhost_vq_has_work);
294 void vhost_poll_queue(struct vhost_poll *poll)
296 vhost_vq_work_queue(poll->vq, &poll->work);
298 EXPORT_SYMBOL_GPL(vhost_poll_queue);
300 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
304 for (j = 0; j < VHOST_NUM_ADDRS; j++)
305 vq->meta_iotlb[j] = NULL;
308 static void vhost_vq_meta_reset(struct vhost_dev *d)
312 for (i = 0; i < d->nvqs; ++i)
313 __vhost_vq_meta_reset(d->vqs[i]);
316 static void vhost_vring_call_reset(struct vhost_vring_call *call_ctx)
318 call_ctx->ctx = NULL;
319 memset(&call_ctx->producer, 0x0, sizeof(struct irq_bypass_producer));
322 bool vhost_vq_is_setup(struct vhost_virtqueue *vq)
324 return vq->avail && vq->desc && vq->used && vhost_vq_access_ok(vq);
326 EXPORT_SYMBOL_GPL(vhost_vq_is_setup);
328 static void vhost_vq_reset(struct vhost_dev *dev,
329 struct vhost_virtqueue *vq)
335 vq->last_avail_idx = 0;
337 vq->last_used_idx = 0;
338 vq->signalled_used = 0;
339 vq->signalled_used_valid = false;
341 vq->log_used = false;
342 vq->log_addr = -1ull;
343 vq->private_data = NULL;
344 vq->acked_features = 0;
345 vq->acked_backend_features = 0;
347 vq->error_ctx = NULL;
350 vhost_disable_cross_endian(vq);
351 vhost_reset_is_le(vq);
352 vq->busyloop_timeout = 0;
356 vhost_vring_call_reset(&vq->call_ctx);
357 __vhost_vq_meta_reset(vq);
360 static bool vhost_worker(void *data)
362 struct vhost_worker *worker = data;
363 struct vhost_work *work, *work_next;
364 struct llist_node *node;
366 node = llist_del_all(&worker->work_list);
368 __set_current_state(TASK_RUNNING);
370 node = llist_reverse_order(node);
371 /* make sure flag is seen after deletion */
373 llist_for_each_entry_safe(work, work_next, node, node) {
374 clear_bit(VHOST_WORK_QUEUED, &work->flags);
375 kcov_remote_start_common(worker->kcov_handle);
385 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
395 /* Helper to allocate iovec buffers for all vqs. */
396 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
398 struct vhost_virtqueue *vq;
401 for (i = 0; i < dev->nvqs; ++i) {
403 vq->indirect = kmalloc_array(UIO_MAXIOV,
404 sizeof(*vq->indirect),
406 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
408 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
410 if (!vq->indirect || !vq->log || !vq->heads)
417 vhost_vq_free_iovecs(dev->vqs[i]);
421 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
425 for (i = 0; i < dev->nvqs; ++i)
426 vhost_vq_free_iovecs(dev->vqs[i]);
429 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
430 int pkts, int total_len)
432 struct vhost_dev *dev = vq->dev;
434 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
435 pkts >= dev->weight) {
436 vhost_poll_queue(&vq->poll);
442 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
444 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
447 size_t event __maybe_unused =
448 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
450 return size_add(struct_size(vq->avail, ring, num), event);
453 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
456 size_t event __maybe_unused =
457 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
459 return size_add(struct_size(vq->used, ring, num), event);
462 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
465 return sizeof(*vq->desc) * num;
468 void vhost_dev_init(struct vhost_dev *dev,
469 struct vhost_virtqueue **vqs, int nvqs,
470 int iov_limit, int weight, int byte_weight,
472 int (*msg_handler)(struct vhost_dev *dev, u32 asid,
473 struct vhost_iotlb_msg *msg))
475 struct vhost_virtqueue *vq;
480 mutex_init(&dev->mutex);
486 dev->iov_limit = iov_limit;
487 dev->weight = weight;
488 dev->byte_weight = byte_weight;
489 dev->use_worker = use_worker;
490 dev->msg_handler = msg_handler;
491 init_waitqueue_head(&dev->wait);
492 INIT_LIST_HEAD(&dev->read_list);
493 INIT_LIST_HEAD(&dev->pending_list);
494 spin_lock_init(&dev->iotlb_lock);
497 for (i = 0; i < dev->nvqs; ++i) {
503 mutex_init(&vq->mutex);
504 vhost_vq_reset(dev, vq);
506 vhost_poll_init(&vq->poll, vq->handle_kick,
510 EXPORT_SYMBOL_GPL(vhost_dev_init);
512 /* Caller should have device mutex */
513 long vhost_dev_check_owner(struct vhost_dev *dev)
515 /* Are you the owner? If not, I don't think you mean to do that */
516 return dev->mm == current->mm ? 0 : -EPERM;
518 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
520 /* Caller should have device mutex */
521 bool vhost_dev_has_owner(struct vhost_dev *dev)
525 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
527 static void vhost_attach_mm(struct vhost_dev *dev)
529 /* No owner, become one */
530 if (dev->use_worker) {
531 dev->mm = get_task_mm(current);
533 /* vDPA device does not use worker thead, so there's
534 * no need to hold the address space for mm. This help
535 * to avoid deadlock in the case of mmap() which may
536 * held the refcnt of the file and depends on release
537 * method to remove vma.
539 dev->mm = current->mm;
544 static void vhost_detach_mm(struct vhost_dev *dev)
557 static void vhost_worker_free(struct vhost_dev *dev)
562 WARN_ON(!llist_empty(&dev->worker->work_list));
563 vhost_task_stop(dev->worker->vtsk);
568 static struct vhost_worker *vhost_worker_create(struct vhost_dev *dev)
570 struct vhost_worker *worker;
571 struct vhost_task *vtsk;
572 char name[TASK_COMM_LEN];
574 worker = kzalloc(sizeof(*worker), GFP_KERNEL_ACCOUNT);
578 snprintf(name, sizeof(name), "vhost-%d", current->pid);
580 vtsk = vhost_task_create(vhost_worker, worker, name);
584 init_llist_head(&worker->work_list);
585 worker->kcov_handle = kcov_common_handle();
588 * vsock can already try to queue so make sure llist and vtsk are both
589 * set before vhost_work_queue sees dev->worker is set.
592 dev->worker = worker;
594 vhost_task_start(vtsk);
602 static int vhost_get_vq_from_user(struct vhost_dev *dev, void __user *argp,
603 struct vhost_virtqueue **vq, u32 *id)
605 u32 __user *idxp = argp;
609 r = get_user(idx, idxp);
613 if (idx >= dev->nvqs)
616 idx = array_index_nospec(idx, dev->nvqs);
623 /* Caller should have device mutex */
624 long vhost_dev_set_owner(struct vhost_dev *dev)
626 struct vhost_worker *worker;
629 /* Is there an owner already? */
630 if (vhost_dev_has_owner(dev)) {
635 vhost_attach_mm(dev);
637 err = vhost_dev_alloc_iovecs(dev);
641 if (dev->use_worker) {
643 * This should be done last, because vsock can queue work
644 * before VHOST_SET_OWNER so it simplifies the failure path
645 * below since we don't have to worry about vsock queueing
646 * while we free the worker.
648 worker = vhost_worker_create(dev);
654 for (i = 0; i < dev->nvqs; i++)
655 dev->vqs[i]->worker = worker;
661 vhost_dev_free_iovecs(dev);
663 vhost_detach_mm(dev);
667 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
669 static struct vhost_iotlb *iotlb_alloc(void)
671 return vhost_iotlb_alloc(max_iotlb_entries,
672 VHOST_IOTLB_FLAG_RETIRE);
675 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void)
677 return iotlb_alloc();
679 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
681 /* Caller should have device mutex */
682 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem)
686 vhost_dev_cleanup(dev);
689 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
690 * VQs aren't running.
692 for (i = 0; i < dev->nvqs; ++i)
693 dev->vqs[i]->umem = umem;
695 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
697 void vhost_dev_stop(struct vhost_dev *dev)
701 for (i = 0; i < dev->nvqs; ++i) {
702 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick)
703 vhost_poll_stop(&dev->vqs[i]->poll);
706 vhost_dev_flush(dev);
708 EXPORT_SYMBOL_GPL(vhost_dev_stop);
710 void vhost_clear_msg(struct vhost_dev *dev)
712 struct vhost_msg_node *node, *n;
714 spin_lock(&dev->iotlb_lock);
716 list_for_each_entry_safe(node, n, &dev->read_list, node) {
717 list_del(&node->node);
721 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
722 list_del(&node->node);
726 spin_unlock(&dev->iotlb_lock);
728 EXPORT_SYMBOL_GPL(vhost_clear_msg);
730 void vhost_dev_cleanup(struct vhost_dev *dev)
734 for (i = 0; i < dev->nvqs; ++i) {
735 if (dev->vqs[i]->error_ctx)
736 eventfd_ctx_put(dev->vqs[i]->error_ctx);
737 if (dev->vqs[i]->kick)
738 fput(dev->vqs[i]->kick);
739 if (dev->vqs[i]->call_ctx.ctx)
740 eventfd_ctx_put(dev->vqs[i]->call_ctx.ctx);
741 vhost_vq_reset(dev, dev->vqs[i]);
743 vhost_dev_free_iovecs(dev);
745 eventfd_ctx_put(dev->log_ctx);
747 /* No one will access memory at this point */
748 vhost_iotlb_free(dev->umem);
750 vhost_iotlb_free(dev->iotlb);
752 vhost_clear_msg(dev);
753 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
754 vhost_worker_free(dev);
755 vhost_detach_mm(dev);
757 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
759 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
761 u64 a = addr / VHOST_PAGE_SIZE / 8;
763 /* Make sure 64 bit math will not overflow. */
764 if (a > ULONG_MAX - (unsigned long)log_base ||
765 a + (unsigned long)log_base > ULONG_MAX)
768 return access_ok(log_base + a,
769 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
772 /* Make sure 64 bit math will not overflow. */
773 static bool vhost_overflow(u64 uaddr, u64 size)
775 if (uaddr > ULONG_MAX || size > ULONG_MAX)
781 return uaddr > ULONG_MAX - size + 1;
784 /* Caller should have vq mutex and device mutex. */
785 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem,
788 struct vhost_iotlb_map *map;
793 list_for_each_entry(map, &umem->list, link) {
794 unsigned long a = map->addr;
796 if (vhost_overflow(map->addr, map->size))
800 if (!access_ok((void __user *)a, map->size))
802 else if (log_all && !log_access_ok(log_base,
810 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
811 u64 addr, unsigned int size,
814 const struct vhost_iotlb_map *map = vq->meta_iotlb[type];
819 return (void __user *)(uintptr_t)(map->addr + addr - map->start);
822 /* Can we switch to this memory table? */
823 /* Caller should have device mutex but not vq mutex */
824 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem,
829 for (i = 0; i < d->nvqs; ++i) {
833 mutex_lock(&d->vqs[i]->mutex);
834 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
835 /* If ring is inactive, will check when it's enabled. */
836 if (d->vqs[i]->private_data)
837 ok = vq_memory_access_ok(d->vqs[i]->log_base,
841 mutex_unlock(&d->vqs[i]->mutex);
848 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
849 struct iovec iov[], int iov_size, int access);
851 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
852 const void *from, unsigned size)
857 return __copy_to_user(to, from, size);
859 /* This function should be called after iotlb
860 * prefetch, which means we're sure that all vq
861 * could be access through iotlb. So -EAGAIN should
862 * not happen in this case.
865 void __user *uaddr = vhost_vq_meta_fetch(vq,
866 (u64)(uintptr_t)to, size,
870 return __copy_to_user(uaddr, from, size);
872 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
873 ARRAY_SIZE(vq->iotlb_iov),
877 iov_iter_init(&t, ITER_DEST, vq->iotlb_iov, ret, size);
878 ret = copy_to_iter(from, size, &t);
886 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
887 void __user *from, unsigned size)
892 return __copy_from_user(to, from, size);
894 /* This function should be called after iotlb
895 * prefetch, which means we're sure that vq
896 * could be access through iotlb. So -EAGAIN should
897 * not happen in this case.
899 void __user *uaddr = vhost_vq_meta_fetch(vq,
900 (u64)(uintptr_t)from, size,
905 return __copy_from_user(to, uaddr, size);
907 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
908 ARRAY_SIZE(vq->iotlb_iov),
911 vq_err(vq, "IOTLB translation failure: uaddr "
912 "%p size 0x%llx\n", from,
913 (unsigned long long) size);
916 iov_iter_init(&f, ITER_SOURCE, vq->iotlb_iov, ret, size);
917 ret = copy_from_iter(to, size, &f);
926 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
927 void __user *addr, unsigned int size,
932 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
933 ARRAY_SIZE(vq->iotlb_iov),
936 vq_err(vq, "IOTLB translation failure: uaddr "
937 "%p size 0x%llx\n", addr,
938 (unsigned long long) size);
942 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
943 vq_err(vq, "Non atomic userspace memory access: uaddr "
944 "%p size 0x%llx\n", addr,
945 (unsigned long long) size);
949 return vq->iotlb_iov[0].iov_base;
952 /* This function should be called after iotlb
953 * prefetch, which means we're sure that vq
954 * could be access through iotlb. So -EAGAIN should
955 * not happen in this case.
957 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
958 void __user *addr, unsigned int size,
961 void __user *uaddr = vhost_vq_meta_fetch(vq,
962 (u64)(uintptr_t)addr, size, type);
966 return __vhost_get_user_slow(vq, addr, size, type);
969 #define vhost_put_user(vq, x, ptr) \
973 ret = __put_user(x, ptr); \
975 __typeof__(ptr) to = \
976 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
977 sizeof(*ptr), VHOST_ADDR_USED); \
979 ret = __put_user(x, to); \
986 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
988 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
989 vhost_avail_event(vq));
992 static inline int vhost_put_used(struct vhost_virtqueue *vq,
993 struct vring_used_elem *head, int idx,
996 return vhost_copy_to_user(vq, vq->used->ring + idx, head,
997 count * sizeof(*head));
1000 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
1003 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
1007 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
1010 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
1014 #define vhost_get_user(vq, x, ptr, type) \
1018 ret = __get_user(x, ptr); \
1020 __typeof__(ptr) from = \
1021 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
1025 ret = __get_user(x, from); \
1032 #define vhost_get_avail(vq, x, ptr) \
1033 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
1035 #define vhost_get_used(vq, x, ptr) \
1036 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
1038 static void vhost_dev_lock_vqs(struct vhost_dev *d)
1041 for (i = 0; i < d->nvqs; ++i)
1042 mutex_lock_nested(&d->vqs[i]->mutex, i);
1045 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
1048 for (i = 0; i < d->nvqs; ++i)
1049 mutex_unlock(&d->vqs[i]->mutex);
1052 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
1055 return vhost_get_avail(vq, *idx, &vq->avail->idx);
1058 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
1059 __virtio16 *head, int idx)
1061 return vhost_get_avail(vq, *head,
1062 &vq->avail->ring[idx & (vq->num - 1)]);
1065 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1068 return vhost_get_avail(vq, *flags, &vq->avail->flags);
1071 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1074 return vhost_get_avail(vq, *event, vhost_used_event(vq));
1077 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1080 return vhost_get_used(vq, *idx, &vq->used->idx);
1083 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1084 struct vring_desc *desc, int idx)
1086 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1089 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1090 struct vhost_iotlb_msg *msg)
1092 struct vhost_msg_node *node, *n;
1094 spin_lock(&d->iotlb_lock);
1096 list_for_each_entry_safe(node, n, &d->pending_list, node) {
1097 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1098 if (msg->iova <= vq_msg->iova &&
1099 msg->iova + msg->size - 1 >= vq_msg->iova &&
1100 vq_msg->type == VHOST_IOTLB_MISS) {
1101 vhost_poll_queue(&node->vq->poll);
1102 list_del(&node->node);
1107 spin_unlock(&d->iotlb_lock);
1110 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1112 unsigned long a = uaddr;
1114 /* Make sure 64 bit math will not overflow. */
1115 if (vhost_overflow(uaddr, size))
1118 if ((access & VHOST_ACCESS_RO) &&
1119 !access_ok((void __user *)a, size))
1121 if ((access & VHOST_ACCESS_WO) &&
1122 !access_ok((void __user *)a, size))
1127 static int vhost_process_iotlb_msg(struct vhost_dev *dev, u32 asid,
1128 struct vhost_iotlb_msg *msg)
1135 mutex_lock(&dev->mutex);
1136 vhost_dev_lock_vqs(dev);
1137 switch (msg->type) {
1138 case VHOST_IOTLB_UPDATE:
1143 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1147 vhost_vq_meta_reset(dev);
1148 if (vhost_iotlb_add_range(dev->iotlb, msg->iova,
1149 msg->iova + msg->size - 1,
1150 msg->uaddr, msg->perm)) {
1154 vhost_iotlb_notify_vq(dev, msg);
1156 case VHOST_IOTLB_INVALIDATE:
1161 vhost_vq_meta_reset(dev);
1162 vhost_iotlb_del_range(dev->iotlb, msg->iova,
1163 msg->iova + msg->size - 1);
1170 vhost_dev_unlock_vqs(dev);
1171 mutex_unlock(&dev->mutex);
1175 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1176 struct iov_iter *from)
1178 struct vhost_iotlb_msg msg;
1183 ret = copy_from_iter(&type, sizeof(type), from);
1184 if (ret != sizeof(type)) {
1190 case VHOST_IOTLB_MSG:
1191 /* There maybe a hole after type for V1 message type,
1194 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1196 case VHOST_IOTLB_MSG_V2:
1197 if (vhost_backend_has_feature(dev->vqs[0],
1198 VHOST_BACKEND_F_IOTLB_ASID)) {
1199 ret = copy_from_iter(&asid, sizeof(asid), from);
1200 if (ret != sizeof(asid)) {
1206 offset = sizeof(__u32);
1213 iov_iter_advance(from, offset);
1214 ret = copy_from_iter(&msg, sizeof(msg), from);
1215 if (ret != sizeof(msg)) {
1220 if ((msg.type == VHOST_IOTLB_UPDATE ||
1221 msg.type == VHOST_IOTLB_INVALIDATE) &&
1227 if (dev->msg_handler)
1228 ret = dev->msg_handler(dev, asid, &msg);
1230 ret = vhost_process_iotlb_msg(dev, asid, &msg);
1236 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1237 sizeof(struct vhost_msg_v2);
1241 EXPORT_SYMBOL(vhost_chr_write_iter);
1243 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1248 poll_wait(file, &dev->wait, wait);
1250 if (!list_empty(&dev->read_list))
1251 mask |= EPOLLIN | EPOLLRDNORM;
1255 EXPORT_SYMBOL(vhost_chr_poll);
1257 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1261 struct vhost_msg_node *node;
1263 unsigned size = sizeof(struct vhost_msg);
1265 if (iov_iter_count(to) < size)
1270 prepare_to_wait(&dev->wait, &wait,
1271 TASK_INTERRUPTIBLE);
1273 node = vhost_dequeue_msg(dev, &dev->read_list);
1280 if (signal_pending(current)) {
1293 finish_wait(&dev->wait, &wait);
1296 struct vhost_iotlb_msg *msg;
1297 void *start = &node->msg;
1299 switch (node->msg.type) {
1300 case VHOST_IOTLB_MSG:
1301 size = sizeof(node->msg);
1302 msg = &node->msg.iotlb;
1304 case VHOST_IOTLB_MSG_V2:
1305 size = sizeof(node->msg_v2);
1306 msg = &node->msg_v2.iotlb;
1313 ret = copy_to_iter(start, size, to);
1314 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1318 vhost_enqueue_msg(dev, &dev->pending_list, node);
1323 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1325 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1327 struct vhost_dev *dev = vq->dev;
1328 struct vhost_msg_node *node;
1329 struct vhost_iotlb_msg *msg;
1330 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1332 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1337 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1338 msg = &node->msg_v2.iotlb;
1340 msg = &node->msg.iotlb;
1343 msg->type = VHOST_IOTLB_MISS;
1347 vhost_enqueue_msg(dev, &dev->read_list, node);
1352 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1353 vring_desc_t __user *desc,
1354 vring_avail_t __user *avail,
1355 vring_used_t __user *used)
1358 /* If an IOTLB device is present, the vring addresses are
1359 * GIOVAs. Access validation occurs at prefetch time. */
1363 return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1364 access_ok(avail, vhost_get_avail_size(vq, num)) &&
1365 access_ok(used, vhost_get_used_size(vq, num));
1368 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1369 const struct vhost_iotlb_map *map,
1372 int access = (type == VHOST_ADDR_USED) ?
1373 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1375 if (likely(map->perm & access))
1376 vq->meta_iotlb[type] = map;
1379 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1380 int access, u64 addr, u64 len, int type)
1382 const struct vhost_iotlb_map *map;
1383 struct vhost_iotlb *umem = vq->iotlb;
1384 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1386 if (vhost_vq_meta_fetch(vq, addr, len, type))
1390 map = vhost_iotlb_itree_first(umem, addr, last);
1391 if (map == NULL || map->start > addr) {
1392 vhost_iotlb_miss(vq, addr, access);
1394 } else if (!(map->perm & access)) {
1395 /* Report the possible access violation by
1396 * request another translation from userspace.
1401 size = map->size - addr + map->start;
1403 if (orig_addr == addr && size >= len)
1404 vhost_vq_meta_update(vq, map, type);
1413 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1415 unsigned int num = vq->num;
1420 return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc,
1421 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1422 iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail,
1423 vhost_get_avail_size(vq, num),
1424 VHOST_ADDR_AVAIL) &&
1425 iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used,
1426 vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1428 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1430 /* Can we log writes? */
1431 /* Caller should have device mutex but not vq mutex */
1432 bool vhost_log_access_ok(struct vhost_dev *dev)
1434 return memory_access_ok(dev, dev->umem, 1);
1436 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1438 static bool vq_log_used_access_ok(struct vhost_virtqueue *vq,
1439 void __user *log_base,
1443 /* If an IOTLB device is present, log_addr is a GIOVA that
1444 * will never be logged by log_used(). */
1448 return !log_used || log_access_ok(log_base, log_addr,
1449 vhost_get_used_size(vq, vq->num));
1452 /* Verify access for write logging. */
1453 /* Caller should have vq mutex and device mutex */
1454 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1455 void __user *log_base)
1457 return vq_memory_access_ok(log_base, vq->umem,
1458 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1459 vq_log_used_access_ok(vq, log_base, vq->log_used, vq->log_addr);
1462 /* Can we start vq? */
1463 /* Caller should have vq mutex and device mutex */
1464 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1466 if (!vq_log_access_ok(vq, vq->log_base))
1469 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1471 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1473 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1475 struct vhost_memory mem, *newmem;
1476 struct vhost_memory_region *region;
1477 struct vhost_iotlb *newumem, *oldumem;
1478 unsigned long size = offsetof(struct vhost_memory, regions);
1481 if (copy_from_user(&mem, m, size))
1485 if (mem.nregions > max_mem_regions)
1487 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1492 memcpy(newmem, &mem, size);
1493 if (copy_from_user(newmem->regions, m->regions,
1494 flex_array_size(newmem, regions, mem.nregions))) {
1499 newumem = iotlb_alloc();
1505 for (region = newmem->regions;
1506 region < newmem->regions + mem.nregions;
1508 if (vhost_iotlb_add_range(newumem,
1509 region->guest_phys_addr,
1510 region->guest_phys_addr +
1511 region->memory_size - 1,
1512 region->userspace_addr,
1517 if (!memory_access_ok(d, newumem, 0))
1523 /* All memory accesses are done under some VQ mutex. */
1524 for (i = 0; i < d->nvqs; ++i) {
1525 mutex_lock(&d->vqs[i]->mutex);
1526 d->vqs[i]->umem = newumem;
1527 mutex_unlock(&d->vqs[i]->mutex);
1531 vhost_iotlb_free(oldumem);
1535 vhost_iotlb_free(newumem);
1540 static long vhost_vring_set_num(struct vhost_dev *d,
1541 struct vhost_virtqueue *vq,
1544 struct vhost_vring_state s;
1546 /* Resizing ring with an active backend?
1547 * You don't want to do that. */
1548 if (vq->private_data)
1551 if (copy_from_user(&s, argp, sizeof s))
1554 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
1561 static long vhost_vring_set_addr(struct vhost_dev *d,
1562 struct vhost_virtqueue *vq,
1565 struct vhost_vring_addr a;
1567 if (copy_from_user(&a, argp, sizeof a))
1569 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
1572 /* For 32bit, verify that the top 32bits of the user
1573 data are set to zero. */
1574 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1575 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1576 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
1579 /* Make sure it's safe to cast pointers to vring types. */
1580 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1581 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1582 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1583 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1584 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
1587 /* We only verify access here if backend is configured.
1588 * If it is not, we don't as size might not have been setup.
1589 * We will verify when backend is configured. */
1590 if (vq->private_data) {
1591 if (!vq_access_ok(vq, vq->num,
1592 (void __user *)(unsigned long)a.desc_user_addr,
1593 (void __user *)(unsigned long)a.avail_user_addr,
1594 (void __user *)(unsigned long)a.used_user_addr))
1597 /* Also validate log access for used ring if enabled. */
1598 if (!vq_log_used_access_ok(vq, vq->log_base,
1599 a.flags & (0x1 << VHOST_VRING_F_LOG),
1604 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1605 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1606 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1607 vq->log_addr = a.log_guest_addr;
1608 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1613 static long vhost_vring_set_num_addr(struct vhost_dev *d,
1614 struct vhost_virtqueue *vq,
1620 mutex_lock(&vq->mutex);
1623 case VHOST_SET_VRING_NUM:
1624 r = vhost_vring_set_num(d, vq, argp);
1626 case VHOST_SET_VRING_ADDR:
1627 r = vhost_vring_set_addr(d, vq, argp);
1633 mutex_unlock(&vq->mutex);
1637 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1639 struct file *eventfp, *filep = NULL;
1640 bool pollstart = false, pollstop = false;
1641 struct eventfd_ctx *ctx = NULL;
1642 struct vhost_virtqueue *vq;
1643 struct vhost_vring_state s;
1644 struct vhost_vring_file f;
1648 r = vhost_get_vq_from_user(d, argp, &vq, &idx);
1652 if (ioctl == VHOST_SET_VRING_NUM ||
1653 ioctl == VHOST_SET_VRING_ADDR) {
1654 return vhost_vring_set_num_addr(d, vq, ioctl, argp);
1657 mutex_lock(&vq->mutex);
1660 case VHOST_SET_VRING_BASE:
1661 /* Moving base with an active backend?
1662 * You don't want to do that. */
1663 if (vq->private_data) {
1667 if (copy_from_user(&s, argp, sizeof s)) {
1671 if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) {
1672 vq->last_avail_idx = s.num & 0xffff;
1673 vq->last_used_idx = (s.num >> 16) & 0xffff;
1675 if (s.num > 0xffff) {
1679 vq->last_avail_idx = s.num;
1681 /* Forget the cached index value. */
1682 vq->avail_idx = vq->last_avail_idx;
1684 case VHOST_GET_VRING_BASE:
1686 if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED))
1687 s.num = (u32)vq->last_avail_idx | ((u32)vq->last_used_idx << 16);
1689 s.num = vq->last_avail_idx;
1690 if (copy_to_user(argp, &s, sizeof s))
1693 case VHOST_SET_VRING_KICK:
1694 if (copy_from_user(&f, argp, sizeof f)) {
1698 eventfp = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_fget(f.fd);
1699 if (IS_ERR(eventfp)) {
1700 r = PTR_ERR(eventfp);
1703 if (eventfp != vq->kick) {
1704 pollstop = (filep = vq->kick) != NULL;
1705 pollstart = (vq->kick = eventfp) != NULL;
1709 case VHOST_SET_VRING_CALL:
1710 if (copy_from_user(&f, argp, sizeof f)) {
1714 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
1720 swap(ctx, vq->call_ctx.ctx);
1722 case VHOST_SET_VRING_ERR:
1723 if (copy_from_user(&f, argp, sizeof f)) {
1727 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
1732 swap(ctx, vq->error_ctx);
1734 case VHOST_SET_VRING_ENDIAN:
1735 r = vhost_set_vring_endian(vq, argp);
1737 case VHOST_GET_VRING_ENDIAN:
1738 r = vhost_get_vring_endian(vq, idx, argp);
1740 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1741 if (copy_from_user(&s, argp, sizeof(s))) {
1745 vq->busyloop_timeout = s.num;
1747 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1749 s.num = vq->busyloop_timeout;
1750 if (copy_to_user(argp, &s, sizeof(s)))
1757 if (pollstop && vq->handle_kick)
1758 vhost_poll_stop(&vq->poll);
1760 if (!IS_ERR_OR_NULL(ctx))
1761 eventfd_ctx_put(ctx);
1765 if (pollstart && vq->handle_kick)
1766 r = vhost_poll_start(&vq->poll, vq->kick);
1768 mutex_unlock(&vq->mutex);
1770 if (pollstop && vq->handle_kick)
1771 vhost_dev_flush(vq->poll.dev);
1774 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1776 int vhost_init_device_iotlb(struct vhost_dev *d)
1778 struct vhost_iotlb *niotlb, *oiotlb;
1781 niotlb = iotlb_alloc();
1788 for (i = 0; i < d->nvqs; ++i) {
1789 struct vhost_virtqueue *vq = d->vqs[i];
1791 mutex_lock(&vq->mutex);
1793 __vhost_vq_meta_reset(vq);
1794 mutex_unlock(&vq->mutex);
1797 vhost_iotlb_free(oiotlb);
1801 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1803 /* Caller must have device mutex */
1804 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1806 struct eventfd_ctx *ctx;
1811 /* If you are not the owner, you can become one */
1812 if (ioctl == VHOST_SET_OWNER) {
1813 r = vhost_dev_set_owner(d);
1817 /* You must be the owner to do anything else */
1818 r = vhost_dev_check_owner(d);
1823 case VHOST_SET_MEM_TABLE:
1824 r = vhost_set_memory(d, argp);
1826 case VHOST_SET_LOG_BASE:
1827 if (copy_from_user(&p, argp, sizeof p)) {
1831 if ((u64)(unsigned long)p != p) {
1835 for (i = 0; i < d->nvqs; ++i) {
1836 struct vhost_virtqueue *vq;
1837 void __user *base = (void __user *)(unsigned long)p;
1839 mutex_lock(&vq->mutex);
1840 /* If ring is inactive, will check when it's enabled. */
1841 if (vq->private_data && !vq_log_access_ok(vq, base))
1844 vq->log_base = base;
1845 mutex_unlock(&vq->mutex);
1848 case VHOST_SET_LOG_FD:
1849 r = get_user(fd, (int __user *)argp);
1852 ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd);
1857 swap(ctx, d->log_ctx);
1858 for (i = 0; i < d->nvqs; ++i) {
1859 mutex_lock(&d->vqs[i]->mutex);
1860 d->vqs[i]->log_ctx = d->log_ctx;
1861 mutex_unlock(&d->vqs[i]->mutex);
1864 eventfd_ctx_put(ctx);
1873 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1875 /* TODO: This is really inefficient. We need something like get_user()
1876 * (instruction directly accesses the data, with an exception table entry
1877 * returning -EFAULT). See Documentation/arch/x86/exception-tables.rst.
1879 static int set_bit_to_user(int nr, void __user *addr)
1881 unsigned long log = (unsigned long)addr;
1884 int bit = nr + (log % PAGE_SIZE) * 8;
1887 r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page);
1891 base = kmap_atomic(page);
1893 kunmap_atomic(base);
1894 unpin_user_pages_dirty_lock(&page, 1, true);
1898 static int log_write(void __user *log_base,
1899 u64 write_address, u64 write_length)
1901 u64 write_page = write_address / VHOST_PAGE_SIZE;
1906 write_length += write_address % VHOST_PAGE_SIZE;
1908 u64 base = (u64)(unsigned long)log_base;
1909 u64 log = base + write_page / 8;
1910 int bit = write_page % 8;
1911 if ((u64)(unsigned long)log != log)
1913 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1916 if (write_length <= VHOST_PAGE_SIZE)
1918 write_length -= VHOST_PAGE_SIZE;
1924 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1926 struct vhost_iotlb *umem = vq->umem;
1927 struct vhost_iotlb_map *u;
1928 u64 start, end, l, min;
1934 /* More than one GPAs can be mapped into a single HVA. So
1935 * iterate all possible umems here to be safe.
1937 list_for_each_entry(u, &umem->list, link) {
1938 if (u->addr > hva - 1 + len ||
1939 u->addr - 1 + u->size < hva)
1941 start = max(u->addr, hva);
1942 end = min(u->addr - 1 + u->size, hva - 1 + len);
1943 l = end - start + 1;
1944 r = log_write(vq->log_base,
1945 u->start + start - u->addr,
1963 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1965 struct iovec *iov = vq->log_iov;
1969 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1971 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1972 len, iov, 64, VHOST_ACCESS_WO);
1976 for (i = 0; i < ret; i++) {
1977 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1986 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1987 unsigned int log_num, u64 len, struct iovec *iov, int count)
1991 /* Make sure data written is seen before log. */
1995 for (i = 0; i < count; i++) {
1996 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
2004 for (i = 0; i < log_num; ++i) {
2005 u64 l = min(log[i].len, len);
2006 r = log_write(vq->log_base, log[i].addr, l);
2012 eventfd_signal(vq->log_ctx, 1);
2016 /* Length written exceeds what we have stored. This is a bug. */
2020 EXPORT_SYMBOL_GPL(vhost_log_write);
2022 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
2025 if (vhost_put_used_flags(vq))
2027 if (unlikely(vq->log_used)) {
2028 /* Make sure the flag is seen before log. */
2030 /* Log used flag write. */
2031 used = &vq->used->flags;
2032 log_used(vq, (used - (void __user *)vq->used),
2033 sizeof vq->used->flags);
2035 eventfd_signal(vq->log_ctx, 1);
2040 static int vhost_update_avail_event(struct vhost_virtqueue *vq)
2042 if (vhost_put_avail_event(vq))
2044 if (unlikely(vq->log_used)) {
2046 /* Make sure the event is seen before log. */
2048 /* Log avail event write */
2049 used = vhost_avail_event(vq);
2050 log_used(vq, (used - (void __user *)vq->used),
2051 sizeof *vhost_avail_event(vq));
2053 eventfd_signal(vq->log_ctx, 1);
2058 int vhost_vq_init_access(struct vhost_virtqueue *vq)
2060 __virtio16 last_used_idx;
2062 bool is_le = vq->is_le;
2064 if (!vq->private_data)
2067 vhost_init_is_le(vq);
2069 r = vhost_update_used_flags(vq);
2072 vq->signalled_used_valid = false;
2074 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
2078 r = vhost_get_used_idx(vq, &last_used_idx);
2080 vq_err(vq, "Can't access used idx at %p\n",
2084 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2091 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2093 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2094 struct iovec iov[], int iov_size, int access)
2096 const struct vhost_iotlb_map *map;
2097 struct vhost_dev *dev = vq->dev;
2098 struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
2100 u64 s = 0, last = addr + len - 1;
2103 while ((u64)len > s) {
2105 if (unlikely(ret >= iov_size)) {
2110 map = vhost_iotlb_itree_first(umem, addr, last);
2111 if (map == NULL || map->start > addr) {
2112 if (umem != dev->iotlb) {
2118 } else if (!(map->perm & access)) {
2124 size = map->size - addr + map->start;
2125 _iov->iov_len = min((u64)len - s, size);
2126 _iov->iov_base = (void __user *)(unsigned long)
2127 (map->addr + addr - map->start);
2134 vhost_iotlb_miss(vq, addr, access);
2138 /* Each buffer in the virtqueues is actually a chain of descriptors. This
2139 * function returns the next descriptor in the chain,
2140 * or -1U if we're at the end. */
2141 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2145 /* If this descriptor says it doesn't chain, we're done. */
2146 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2149 /* Check they're not leading us off end of descriptors. */
2150 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2154 static int get_indirect(struct vhost_virtqueue *vq,
2155 struct iovec iov[], unsigned int iov_size,
2156 unsigned int *out_num, unsigned int *in_num,
2157 struct vhost_log *log, unsigned int *log_num,
2158 struct vring_desc *indirect)
2160 struct vring_desc desc;
2161 unsigned int i = 0, count, found = 0;
2162 u32 len = vhost32_to_cpu(vq, indirect->len);
2163 struct iov_iter from;
2167 if (unlikely(len % sizeof desc)) {
2168 vq_err(vq, "Invalid length in indirect descriptor: "
2169 "len 0x%llx not multiple of 0x%zx\n",
2170 (unsigned long long)len,
2175 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2176 UIO_MAXIOV, VHOST_ACCESS_RO);
2177 if (unlikely(ret < 0)) {
2179 vq_err(vq, "Translation failure %d in indirect.\n", ret);
2182 iov_iter_init(&from, ITER_SOURCE, vq->indirect, ret, len);
2183 count = len / sizeof desc;
2184 /* Buffers are chained via a 16 bit next field, so
2185 * we can have at most 2^16 of these. */
2186 if (unlikely(count > USHRT_MAX + 1)) {
2187 vq_err(vq, "Indirect buffer length too big: %d\n",
2193 unsigned iov_count = *in_num + *out_num;
2194 if (unlikely(++found > count)) {
2195 vq_err(vq, "Loop detected: last one at %u "
2196 "indirect size %u\n",
2200 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2201 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2202 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2205 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2206 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2207 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2211 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2212 access = VHOST_ACCESS_WO;
2214 access = VHOST_ACCESS_RO;
2216 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2217 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2218 iov_size - iov_count, access);
2219 if (unlikely(ret < 0)) {
2221 vq_err(vq, "Translation failure %d indirect idx %d\n",
2225 /* If this is an input descriptor, increment that count. */
2226 if (access == VHOST_ACCESS_WO) {
2228 if (unlikely(log && ret)) {
2229 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2230 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2234 /* If it's an output descriptor, they're all supposed
2235 * to come before any input descriptors. */
2236 if (unlikely(*in_num)) {
2237 vq_err(vq, "Indirect descriptor "
2238 "has out after in: idx %d\n", i);
2243 } while ((i = next_desc(vq, &desc)) != -1);
2247 /* This looks in the virtqueue and for the first available buffer, and converts
2248 * it to an iovec for convenient access. Since descriptors consist of some
2249 * number of output then some number of input descriptors, it's actually two
2250 * iovecs, but we pack them into one and note how many of each there were.
2252 * This function returns the descriptor number found, or vq->num (which is
2253 * never a valid descriptor number) if none was found. A negative code is
2254 * returned on error. */
2255 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2256 struct iovec iov[], unsigned int iov_size,
2257 unsigned int *out_num, unsigned int *in_num,
2258 struct vhost_log *log, unsigned int *log_num)
2260 struct vring_desc desc;
2261 unsigned int i, head, found = 0;
2263 __virtio16 avail_idx;
2264 __virtio16 ring_head;
2267 /* Check it isn't doing very strange things with descriptor numbers. */
2268 last_avail_idx = vq->last_avail_idx;
2270 if (vq->avail_idx == vq->last_avail_idx) {
2271 if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
2272 vq_err(vq, "Failed to access avail idx at %p\n",
2276 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2278 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2279 vq_err(vq, "Guest moved used index from %u to %u",
2280 last_avail_idx, vq->avail_idx);
2284 /* If there's nothing new since last we looked, return
2287 if (vq->avail_idx == last_avail_idx)
2290 /* Only get avail ring entries after they have been
2296 /* Grab the next descriptor number they're advertising, and increment
2297 * the index we've seen. */
2298 if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
2299 vq_err(vq, "Failed to read head: idx %d address %p\n",
2301 &vq->avail->ring[last_avail_idx % vq->num]);
2305 head = vhost16_to_cpu(vq, ring_head);
2307 /* If their number is silly, that's an error. */
2308 if (unlikely(head >= vq->num)) {
2309 vq_err(vq, "Guest says index %u > %u is available",
2314 /* When we start there are none of either input nor output. */
2315 *out_num = *in_num = 0;
2321 unsigned iov_count = *in_num + *out_num;
2322 if (unlikely(i >= vq->num)) {
2323 vq_err(vq, "Desc index is %u > %u, head = %u",
2327 if (unlikely(++found > vq->num)) {
2328 vq_err(vq, "Loop detected: last one at %u "
2329 "vq size %u head %u\n",
2333 ret = vhost_get_desc(vq, &desc, i);
2334 if (unlikely(ret)) {
2335 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2339 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2340 ret = get_indirect(vq, iov, iov_size,
2342 log, log_num, &desc);
2343 if (unlikely(ret < 0)) {
2345 vq_err(vq, "Failure detected "
2346 "in indirect descriptor at idx %d\n", i);
2352 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2353 access = VHOST_ACCESS_WO;
2355 access = VHOST_ACCESS_RO;
2356 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2357 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2358 iov_size - iov_count, access);
2359 if (unlikely(ret < 0)) {
2361 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2365 if (access == VHOST_ACCESS_WO) {
2366 /* If this is an input descriptor,
2367 * increment that count. */
2369 if (unlikely(log && ret)) {
2370 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2371 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2375 /* If it's an output descriptor, they're all supposed
2376 * to come before any input descriptors. */
2377 if (unlikely(*in_num)) {
2378 vq_err(vq, "Descriptor has out after in: "
2384 } while ((i = next_desc(vq, &desc)) != -1);
2386 /* On success, increment avail index. */
2387 vq->last_avail_idx++;
2389 /* Assume notifications from guest are disabled at this point,
2390 * if they aren't we would need to update avail_event index. */
2391 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2394 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2396 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2397 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2399 vq->last_avail_idx -= n;
2401 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2403 /* After we've used one of their buffers, we tell them about it. We'll then
2404 * want to notify the guest, using eventfd. */
2405 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2407 struct vring_used_elem heads = {
2408 cpu_to_vhost32(vq, head),
2409 cpu_to_vhost32(vq, len)
2412 return vhost_add_used_n(vq, &heads, 1);
2414 EXPORT_SYMBOL_GPL(vhost_add_used);
2416 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2417 struct vring_used_elem *heads,
2420 vring_used_elem_t __user *used;
2424 start = vq->last_used_idx & (vq->num - 1);
2425 used = vq->used->ring + start;
2426 if (vhost_put_used(vq, heads, start, count)) {
2427 vq_err(vq, "Failed to write used");
2430 if (unlikely(vq->log_used)) {
2431 /* Make sure data is seen before log. */
2433 /* Log used ring entry write. */
2434 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2435 count * sizeof *used);
2437 old = vq->last_used_idx;
2438 new = (vq->last_used_idx += count);
2439 /* If the driver never bothers to signal in a very long while,
2440 * used index might wrap around. If that happens, invalidate
2441 * signalled_used index we stored. TODO: make sure driver
2442 * signals at least once in 2^16 and remove this. */
2443 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2444 vq->signalled_used_valid = false;
2448 /* After we've used one of their buffers, we tell them about it. We'll then
2449 * want to notify the guest, using eventfd. */
2450 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2455 start = vq->last_used_idx & (vq->num - 1);
2456 n = vq->num - start;
2458 r = __vhost_add_used_n(vq, heads, n);
2464 r = __vhost_add_used_n(vq, heads, count);
2466 /* Make sure buffer is written before we update index. */
2468 if (vhost_put_used_idx(vq)) {
2469 vq_err(vq, "Failed to increment used idx");
2472 if (unlikely(vq->log_used)) {
2473 /* Make sure used idx is seen before log. */
2475 /* Log used index update. */
2476 log_used(vq, offsetof(struct vring_used, idx),
2477 sizeof vq->used->idx);
2479 eventfd_signal(vq->log_ctx, 1);
2483 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2485 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2490 /* Flush out used index updates. This is paired
2491 * with the barrier that the Guest executes when enabling
2495 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2496 unlikely(vq->avail_idx == vq->last_avail_idx))
2499 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2501 if (vhost_get_avail_flags(vq, &flags)) {
2502 vq_err(vq, "Failed to get flags");
2505 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2507 old = vq->signalled_used;
2508 v = vq->signalled_used_valid;
2509 new = vq->signalled_used = vq->last_used_idx;
2510 vq->signalled_used_valid = true;
2515 if (vhost_get_used_event(vq, &event)) {
2516 vq_err(vq, "Failed to get used event idx");
2519 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2522 /* This actually signals the guest, using eventfd. */
2523 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2525 /* Signal the Guest tell them we used something up. */
2526 if (vq->call_ctx.ctx && vhost_notify(dev, vq))
2527 eventfd_signal(vq->call_ctx.ctx, 1);
2529 EXPORT_SYMBOL_GPL(vhost_signal);
2531 /* And here's the combo meal deal. Supersize me! */
2532 void vhost_add_used_and_signal(struct vhost_dev *dev,
2533 struct vhost_virtqueue *vq,
2534 unsigned int head, int len)
2536 vhost_add_used(vq, head, len);
2537 vhost_signal(dev, vq);
2539 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2541 /* multi-buffer version of vhost_add_used_and_signal */
2542 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2543 struct vhost_virtqueue *vq,
2544 struct vring_used_elem *heads, unsigned count)
2546 vhost_add_used_n(vq, heads, count);
2547 vhost_signal(dev, vq);
2549 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2551 /* return true if we're sure that avaiable ring is empty */
2552 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2554 __virtio16 avail_idx;
2557 if (vq->avail_idx != vq->last_avail_idx)
2560 r = vhost_get_avail_idx(vq, &avail_idx);
2563 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2565 return vq->avail_idx == vq->last_avail_idx;
2567 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2569 /* OK, now we need to know about added descriptors. */
2570 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2572 __virtio16 avail_idx;
2575 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2577 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2578 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2579 r = vhost_update_used_flags(vq);
2581 vq_err(vq, "Failed to enable notification at %p: %d\n",
2582 &vq->used->flags, r);
2586 r = vhost_update_avail_event(vq);
2588 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2589 vhost_avail_event(vq), r);
2593 /* They could have slipped one in as we were doing that: make
2594 * sure it's written, then check again. */
2596 r = vhost_get_avail_idx(vq, &avail_idx);
2598 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2599 &vq->avail->idx, r);
2602 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2604 return vq->avail_idx != vq->last_avail_idx;
2606 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2608 /* We don't need to be notified again. */
2609 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2613 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2615 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2616 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2617 r = vhost_update_used_flags(vq);
2619 vq_err(vq, "Failed to disable notification at %p: %d\n",
2620 &vq->used->flags, r);
2623 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2625 /* Create a new message. */
2626 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2628 /* Make sure all padding within the structure is initialized. */
2629 struct vhost_msg_node *node = kzalloc(sizeof(*node), GFP_KERNEL);
2634 node->msg.type = type;
2637 EXPORT_SYMBOL_GPL(vhost_new_msg);
2639 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2640 struct vhost_msg_node *node)
2642 spin_lock(&dev->iotlb_lock);
2643 list_add_tail(&node->node, head);
2644 spin_unlock(&dev->iotlb_lock);
2646 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2648 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2650 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2651 struct list_head *head)
2653 struct vhost_msg_node *node = NULL;
2655 spin_lock(&dev->iotlb_lock);
2656 if (!list_empty(head)) {
2657 node = list_first_entry(head, struct vhost_msg_node,
2659 list_del(&node->node);
2661 spin_unlock(&dev->iotlb_lock);
2665 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2667 void vhost_set_backend_features(struct vhost_dev *dev, u64 features)
2669 struct vhost_virtqueue *vq;
2672 mutex_lock(&dev->mutex);
2673 for (i = 0; i < dev->nvqs; ++i) {
2675 mutex_lock(&vq->mutex);
2676 vq->acked_backend_features = features;
2677 mutex_unlock(&vq->mutex);
2679 mutex_unlock(&dev->mutex);
2681 EXPORT_SYMBOL_GPL(vhost_set_backend_features);
2683 static int __init vhost_init(void)
2688 static void __exit vhost_exit(void)
2692 module_init(vhost_init);
2693 module_exit(vhost_exit);
2695 MODULE_VERSION("0.0.1");
2696 MODULE_LICENSE("GPL v2");
2697 MODULE_AUTHOR("Michael S. Tsirkin");
2698 MODULE_DESCRIPTION("Host kernel accelerator for virtio");