media: stv06xx: add missing descriptor sanity checks
[linux/fpc-iii.git] / drivers / vhost / vhost.c
blobf44340b41494e5a20ed4a7948d9c5e17addcce11
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>
16 #include <linux/mm.h>
17 #include <linux/mmu_context.h>
18 #include <linux/miscdevice.h>
19 #include <linux/mutex.h>
20 #include <linux/poll.h>
21 #include <linux/file.h>
22 #include <linux/highmem.h>
23 #include <linux/slab.h>
24 #include <linux/vmalloc.h>
25 #include <linux/kthread.h>
26 #include <linux/cgroup.h>
27 #include <linux/module.h>
28 #include <linux/sort.h>
29 #include <linux/sched/mm.h>
30 #include <linux/sched/signal.h>
31 #include <linux/interval_tree_generic.h>
32 #include <linux/nospec.h>
33 #include <linux/kcov.h>
35 #include "vhost.h"
37 static ushort max_mem_regions = 64;
38 module_param(max_mem_regions, ushort, 0444);
39 MODULE_PARM_DESC(max_mem_regions,
40 "Maximum number of memory regions in memory map. (default: 64)");
41 static int max_iotlb_entries = 2048;
42 module_param(max_iotlb_entries, int, 0444);
43 MODULE_PARM_DESC(max_iotlb_entries,
44 "Maximum number of iotlb entries. (default: 2048)");
46 enum {
47 VHOST_MEMORY_F_LOG = 0x1,
50 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
51 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
53 INTERVAL_TREE_DEFINE(struct vhost_umem_node,
54 rb, __u64, __subtree_last,
55 START, LAST, static inline, vhost_umem_interval_tree);
57 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
58 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
60 vq->user_be = !virtio_legacy_is_little_endian();
63 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
65 vq->user_be = true;
68 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
70 vq->user_be = false;
73 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
75 struct vhost_vring_state s;
77 if (vq->private_data)
78 return -EBUSY;
80 if (copy_from_user(&s, argp, sizeof(s)))
81 return -EFAULT;
83 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
84 s.num != VHOST_VRING_BIG_ENDIAN)
85 return -EINVAL;
87 if (s.num == VHOST_VRING_BIG_ENDIAN)
88 vhost_enable_cross_endian_big(vq);
89 else
90 vhost_enable_cross_endian_little(vq);
92 return 0;
95 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
96 int __user *argp)
98 struct vhost_vring_state s = {
99 .index = idx,
100 .num = vq->user_be
103 if (copy_to_user(argp, &s, sizeof(s)))
104 return -EFAULT;
106 return 0;
109 static void vhost_init_is_le(struct vhost_virtqueue *vq)
111 /* Note for legacy virtio: user_be is initialized at reset time
112 * according to the host endianness. If userspace does not set an
113 * explicit endianness, the default behavior is native endian, as
114 * expected by legacy virtio.
116 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
118 #else
119 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
123 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
125 return -ENOIOCTLCMD;
128 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
129 int __user *argp)
131 return -ENOIOCTLCMD;
134 static void vhost_init_is_le(struct vhost_virtqueue *vq)
136 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
137 || virtio_legacy_is_little_endian();
139 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
141 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
143 vhost_init_is_le(vq);
146 struct vhost_flush_struct {
147 struct vhost_work work;
148 struct completion wait_event;
151 static void vhost_flush_work(struct vhost_work *work)
153 struct vhost_flush_struct *s;
155 s = container_of(work, struct vhost_flush_struct, work);
156 complete(&s->wait_event);
159 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
160 poll_table *pt)
162 struct vhost_poll *poll;
164 poll = container_of(pt, struct vhost_poll, table);
165 poll->wqh = wqh;
166 add_wait_queue(wqh, &poll->wait);
169 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
170 void *key)
172 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
174 if (!(key_to_poll(key) & poll->mask))
175 return 0;
177 vhost_poll_queue(poll);
178 return 0;
181 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
183 clear_bit(VHOST_WORK_QUEUED, &work->flags);
184 work->fn = fn;
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);
194 poll->mask = mask;
195 poll->dev = dev;
196 poll->wqh = NULL;
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)
206 __poll_t mask;
208 if (poll->wqh)
209 return 0;
211 mask = vfs_poll(file, &poll->table);
212 if (mask)
213 vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
214 if (mask & EPOLLERR) {
215 vhost_poll_stop(poll);
216 return -EINVAL;
219 return 0;
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)
227 if (poll->wqh) {
228 remove_wait_queue(poll->wqh, &poll->wait);
229 poll->wqh = NULL;
232 EXPORT_SYMBOL_GPL(vhost_poll_stop);
234 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
236 struct vhost_flush_struct flush;
238 if (dev->worker) {
239 init_completion(&flush.wait_event);
240 vhost_work_init(&flush.work, vhost_flush_work);
242 vhost_work_queue(dev, &flush.work);
243 wait_for_completion(&flush.wait_event);
246 EXPORT_SYMBOL_GPL(vhost_work_flush);
248 /* Flush any work that has been scheduled. When calling this, don't hold any
249 * locks that are also used by the callback. */
250 void vhost_poll_flush(struct vhost_poll *poll)
252 vhost_work_flush(poll->dev, &poll->work);
254 EXPORT_SYMBOL_GPL(vhost_poll_flush);
256 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
258 if (!dev->worker)
259 return;
261 if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
262 /* We can only add the work to the list after we're
263 * sure it was not in the list.
264 * test_and_set_bit() implies a memory barrier.
266 llist_add(&work->node, &dev->work_list);
267 wake_up_process(dev->worker);
270 EXPORT_SYMBOL_GPL(vhost_work_queue);
272 /* A lockless hint for busy polling code to exit the loop */
273 bool vhost_has_work(struct vhost_dev *dev)
275 return !llist_empty(&dev->work_list);
277 EXPORT_SYMBOL_GPL(vhost_has_work);
279 void vhost_poll_queue(struct vhost_poll *poll)
281 vhost_work_queue(poll->dev, &poll->work);
283 EXPORT_SYMBOL_GPL(vhost_poll_queue);
285 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
287 int j;
289 for (j = 0; j < VHOST_NUM_ADDRS; j++)
290 vq->meta_iotlb[j] = NULL;
293 static void vhost_vq_meta_reset(struct vhost_dev *d)
295 int i;
297 for (i = 0; i < d->nvqs; ++i)
298 __vhost_vq_meta_reset(d->vqs[i]);
301 static void vhost_vq_reset(struct vhost_dev *dev,
302 struct vhost_virtqueue *vq)
304 vq->num = 1;
305 vq->desc = NULL;
306 vq->avail = NULL;
307 vq->used = NULL;
308 vq->last_avail_idx = 0;
309 vq->avail_idx = 0;
310 vq->last_used_idx = 0;
311 vq->signalled_used = 0;
312 vq->signalled_used_valid = false;
313 vq->used_flags = 0;
314 vq->log_used = false;
315 vq->log_addr = -1ull;
316 vq->private_data = NULL;
317 vq->acked_features = 0;
318 vq->acked_backend_features = 0;
319 vq->log_base = NULL;
320 vq->error_ctx = NULL;
321 vq->kick = NULL;
322 vq->call_ctx = NULL;
323 vq->log_ctx = NULL;
324 vhost_reset_is_le(vq);
325 vhost_disable_cross_endian(vq);
326 vq->busyloop_timeout = 0;
327 vq->umem = NULL;
328 vq->iotlb = NULL;
329 __vhost_vq_meta_reset(vq);
332 static int vhost_worker(void *data)
334 struct vhost_dev *dev = data;
335 struct vhost_work *work, *work_next;
336 struct llist_node *node;
337 mm_segment_t oldfs = get_fs();
339 set_fs(USER_DS);
340 use_mm(dev->mm);
342 for (;;) {
343 /* mb paired w/ kthread_stop */
344 set_current_state(TASK_INTERRUPTIBLE);
346 if (kthread_should_stop()) {
347 __set_current_state(TASK_RUNNING);
348 break;
351 node = llist_del_all(&dev->work_list);
352 if (!node)
353 schedule();
355 node = llist_reverse_order(node);
356 /* make sure flag is seen after deletion */
357 smp_wmb();
358 llist_for_each_entry_safe(work, work_next, node, node) {
359 clear_bit(VHOST_WORK_QUEUED, &work->flags);
360 __set_current_state(TASK_RUNNING);
361 kcov_remote_start_common(dev->kcov_handle);
362 work->fn(work);
363 kcov_remote_stop();
364 if (need_resched())
365 schedule();
368 unuse_mm(dev->mm);
369 set_fs(oldfs);
370 return 0;
373 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
375 kfree(vq->indirect);
376 vq->indirect = NULL;
377 kfree(vq->log);
378 vq->log = NULL;
379 kfree(vq->heads);
380 vq->heads = NULL;
383 /* Helper to allocate iovec buffers for all vqs. */
384 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
386 struct vhost_virtqueue *vq;
387 int i;
389 for (i = 0; i < dev->nvqs; ++i) {
390 vq = dev->vqs[i];
391 vq->indirect = kmalloc_array(UIO_MAXIOV,
392 sizeof(*vq->indirect),
393 GFP_KERNEL);
394 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
395 GFP_KERNEL);
396 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
397 GFP_KERNEL);
398 if (!vq->indirect || !vq->log || !vq->heads)
399 goto err_nomem;
401 return 0;
403 err_nomem:
404 for (; i >= 0; --i)
405 vhost_vq_free_iovecs(dev->vqs[i]);
406 return -ENOMEM;
409 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
411 int i;
413 for (i = 0; i < dev->nvqs; ++i)
414 vhost_vq_free_iovecs(dev->vqs[i]);
417 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
418 int pkts, int total_len)
420 struct vhost_dev *dev = vq->dev;
422 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
423 pkts >= dev->weight) {
424 vhost_poll_queue(&vq->poll);
425 return true;
428 return false;
430 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
432 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
433 unsigned int num)
435 size_t event __maybe_unused =
436 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
438 return sizeof(*vq->avail) +
439 sizeof(*vq->avail->ring) * num + event;
442 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
443 unsigned int num)
445 size_t event __maybe_unused =
446 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
448 return sizeof(*vq->used) +
449 sizeof(*vq->used->ring) * num + event;
452 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
453 unsigned int num)
455 return sizeof(*vq->desc) * num;
458 void vhost_dev_init(struct vhost_dev *dev,
459 struct vhost_virtqueue **vqs, int nvqs,
460 int iov_limit, int weight, int byte_weight)
462 struct vhost_virtqueue *vq;
463 int i;
465 dev->vqs = vqs;
466 dev->nvqs = nvqs;
467 mutex_init(&dev->mutex);
468 dev->log_ctx = NULL;
469 dev->umem = NULL;
470 dev->iotlb = NULL;
471 dev->mm = NULL;
472 dev->worker = NULL;
473 dev->iov_limit = iov_limit;
474 dev->weight = weight;
475 dev->byte_weight = byte_weight;
476 init_llist_head(&dev->work_list);
477 init_waitqueue_head(&dev->wait);
478 INIT_LIST_HEAD(&dev->read_list);
479 INIT_LIST_HEAD(&dev->pending_list);
480 spin_lock_init(&dev->iotlb_lock);
483 for (i = 0; i < dev->nvqs; ++i) {
484 vq = dev->vqs[i];
485 vq->log = NULL;
486 vq->indirect = NULL;
487 vq->heads = NULL;
488 vq->dev = dev;
489 mutex_init(&vq->mutex);
490 vhost_vq_reset(dev, vq);
491 if (vq->handle_kick)
492 vhost_poll_init(&vq->poll, vq->handle_kick,
493 EPOLLIN, dev);
496 EXPORT_SYMBOL_GPL(vhost_dev_init);
498 /* Caller should have device mutex */
499 long vhost_dev_check_owner(struct vhost_dev *dev)
501 /* Are you the owner? If not, I don't think you mean to do that */
502 return dev->mm == current->mm ? 0 : -EPERM;
504 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
506 struct vhost_attach_cgroups_struct {
507 struct vhost_work work;
508 struct task_struct *owner;
509 int ret;
512 static void vhost_attach_cgroups_work(struct vhost_work *work)
514 struct vhost_attach_cgroups_struct *s;
516 s = container_of(work, struct vhost_attach_cgroups_struct, work);
517 s->ret = cgroup_attach_task_all(s->owner, current);
520 static int vhost_attach_cgroups(struct vhost_dev *dev)
522 struct vhost_attach_cgroups_struct attach;
524 attach.owner = current;
525 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
526 vhost_work_queue(dev, &attach.work);
527 vhost_work_flush(dev, &attach.work);
528 return attach.ret;
531 /* Caller should have device mutex */
532 bool vhost_dev_has_owner(struct vhost_dev *dev)
534 return dev->mm;
536 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
538 /* Caller should have device mutex */
539 long vhost_dev_set_owner(struct vhost_dev *dev)
541 struct task_struct *worker;
542 int err;
544 /* Is there an owner already? */
545 if (vhost_dev_has_owner(dev)) {
546 err = -EBUSY;
547 goto err_mm;
550 /* No owner, become one */
551 dev->mm = get_task_mm(current);
552 dev->kcov_handle = kcov_common_handle();
553 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
554 if (IS_ERR(worker)) {
555 err = PTR_ERR(worker);
556 goto err_worker;
559 dev->worker = worker;
560 wake_up_process(worker); /* avoid contributing to loadavg */
562 err = vhost_attach_cgroups(dev);
563 if (err)
564 goto err_cgroup;
566 err = vhost_dev_alloc_iovecs(dev);
567 if (err)
568 goto err_cgroup;
570 return 0;
571 err_cgroup:
572 kthread_stop(worker);
573 dev->worker = NULL;
574 err_worker:
575 if (dev->mm)
576 mmput(dev->mm);
577 dev->mm = NULL;
578 dev->kcov_handle = 0;
579 err_mm:
580 return err;
582 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
584 struct vhost_umem *vhost_dev_reset_owner_prepare(void)
586 return kvzalloc(sizeof(struct vhost_umem), GFP_KERNEL);
588 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
590 /* Caller should have device mutex */
591 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_umem *umem)
593 int i;
595 vhost_dev_cleanup(dev);
597 /* Restore memory to default empty mapping. */
598 INIT_LIST_HEAD(&umem->umem_list);
599 dev->umem = umem;
600 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
601 * VQs aren't running.
603 for (i = 0; i < dev->nvqs; ++i)
604 dev->vqs[i]->umem = umem;
606 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
608 void vhost_dev_stop(struct vhost_dev *dev)
610 int i;
612 for (i = 0; i < dev->nvqs; ++i) {
613 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
614 vhost_poll_stop(&dev->vqs[i]->poll);
615 vhost_poll_flush(&dev->vqs[i]->poll);
619 EXPORT_SYMBOL_GPL(vhost_dev_stop);
621 static void vhost_umem_free(struct vhost_umem *umem,
622 struct vhost_umem_node *node)
624 vhost_umem_interval_tree_remove(node, &umem->umem_tree);
625 list_del(&node->link);
626 kfree(node);
627 umem->numem--;
630 static void vhost_umem_clean(struct vhost_umem *umem)
632 struct vhost_umem_node *node, *tmp;
634 if (!umem)
635 return;
637 list_for_each_entry_safe(node, tmp, &umem->umem_list, link)
638 vhost_umem_free(umem, node);
640 kvfree(umem);
643 static void vhost_clear_msg(struct vhost_dev *dev)
645 struct vhost_msg_node *node, *n;
647 spin_lock(&dev->iotlb_lock);
649 list_for_each_entry_safe(node, n, &dev->read_list, node) {
650 list_del(&node->node);
651 kfree(node);
654 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
655 list_del(&node->node);
656 kfree(node);
659 spin_unlock(&dev->iotlb_lock);
662 void vhost_dev_cleanup(struct vhost_dev *dev)
664 int i;
666 for (i = 0; i < dev->nvqs; ++i) {
667 if (dev->vqs[i]->error_ctx)
668 eventfd_ctx_put(dev->vqs[i]->error_ctx);
669 if (dev->vqs[i]->kick)
670 fput(dev->vqs[i]->kick);
671 if (dev->vqs[i]->call_ctx)
672 eventfd_ctx_put(dev->vqs[i]->call_ctx);
673 vhost_vq_reset(dev, dev->vqs[i]);
675 vhost_dev_free_iovecs(dev);
676 if (dev->log_ctx)
677 eventfd_ctx_put(dev->log_ctx);
678 dev->log_ctx = NULL;
679 /* No one will access memory at this point */
680 vhost_umem_clean(dev->umem);
681 dev->umem = NULL;
682 vhost_umem_clean(dev->iotlb);
683 dev->iotlb = NULL;
684 vhost_clear_msg(dev);
685 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
686 WARN_ON(!llist_empty(&dev->work_list));
687 if (dev->worker) {
688 kthread_stop(dev->worker);
689 dev->worker = NULL;
690 dev->kcov_handle = 0;
692 if (dev->mm)
693 mmput(dev->mm);
694 dev->mm = NULL;
696 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
698 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
700 u64 a = addr / VHOST_PAGE_SIZE / 8;
702 /* Make sure 64 bit math will not overflow. */
703 if (a > ULONG_MAX - (unsigned long)log_base ||
704 a + (unsigned long)log_base > ULONG_MAX)
705 return false;
707 return access_ok(log_base + a,
708 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
711 static bool vhost_overflow(u64 uaddr, u64 size)
713 /* Make sure 64 bit math will not overflow. */
714 return uaddr > ULONG_MAX || size > ULONG_MAX || uaddr > ULONG_MAX - size;
717 /* Caller should have vq mutex and device mutex. */
718 static bool vq_memory_access_ok(void __user *log_base, struct vhost_umem *umem,
719 int log_all)
721 struct vhost_umem_node *node;
723 if (!umem)
724 return false;
726 list_for_each_entry(node, &umem->umem_list, link) {
727 unsigned long a = node->userspace_addr;
729 if (vhost_overflow(node->userspace_addr, node->size))
730 return false;
733 if (!access_ok((void __user *)a,
734 node->size))
735 return false;
736 else if (log_all && !log_access_ok(log_base,
737 node->start,
738 node->size))
739 return false;
741 return true;
744 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
745 u64 addr, unsigned int size,
746 int type)
748 const struct vhost_umem_node *node = vq->meta_iotlb[type];
750 if (!node)
751 return NULL;
753 return (void *)(uintptr_t)(node->userspace_addr + addr - node->start);
756 /* Can we switch to this memory table? */
757 /* Caller should have device mutex but not vq mutex */
758 static bool memory_access_ok(struct vhost_dev *d, struct vhost_umem *umem,
759 int log_all)
761 int i;
763 for (i = 0; i < d->nvqs; ++i) {
764 bool ok;
765 bool log;
767 mutex_lock(&d->vqs[i]->mutex);
768 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
769 /* If ring is inactive, will check when it's enabled. */
770 if (d->vqs[i]->private_data)
771 ok = vq_memory_access_ok(d->vqs[i]->log_base,
772 umem, log);
773 else
774 ok = true;
775 mutex_unlock(&d->vqs[i]->mutex);
776 if (!ok)
777 return false;
779 return true;
782 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
783 struct iovec iov[], int iov_size, int access);
785 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
786 const void *from, unsigned size)
788 int ret;
790 if (!vq->iotlb)
791 return __copy_to_user(to, from, size);
792 else {
793 /* This function should be called after iotlb
794 * prefetch, which means we're sure that all vq
795 * could be access through iotlb. So -EAGAIN should
796 * not happen in this case.
798 struct iov_iter t;
799 void __user *uaddr = vhost_vq_meta_fetch(vq,
800 (u64)(uintptr_t)to, size,
801 VHOST_ADDR_USED);
803 if (uaddr)
804 return __copy_to_user(uaddr, from, size);
806 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
807 ARRAY_SIZE(vq->iotlb_iov),
808 VHOST_ACCESS_WO);
809 if (ret < 0)
810 goto out;
811 iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
812 ret = copy_to_iter(from, size, &t);
813 if (ret == size)
814 ret = 0;
816 out:
817 return ret;
820 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
821 void __user *from, unsigned size)
823 int ret;
825 if (!vq->iotlb)
826 return __copy_from_user(to, from, size);
827 else {
828 /* This function should be called after iotlb
829 * prefetch, which means we're sure that vq
830 * could be access through iotlb. So -EAGAIN should
831 * not happen in this case.
833 void __user *uaddr = vhost_vq_meta_fetch(vq,
834 (u64)(uintptr_t)from, size,
835 VHOST_ADDR_DESC);
836 struct iov_iter f;
838 if (uaddr)
839 return __copy_from_user(to, uaddr, size);
841 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
842 ARRAY_SIZE(vq->iotlb_iov),
843 VHOST_ACCESS_RO);
844 if (ret < 0) {
845 vq_err(vq, "IOTLB translation failure: uaddr "
846 "%p size 0x%llx\n", from,
847 (unsigned long long) size);
848 goto out;
850 iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
851 ret = copy_from_iter(to, size, &f);
852 if (ret == size)
853 ret = 0;
856 out:
857 return ret;
860 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
861 void __user *addr, unsigned int size,
862 int type)
864 int ret;
866 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
867 ARRAY_SIZE(vq->iotlb_iov),
868 VHOST_ACCESS_RO);
869 if (ret < 0) {
870 vq_err(vq, "IOTLB translation failure: uaddr "
871 "%p size 0x%llx\n", addr,
872 (unsigned long long) size);
873 return NULL;
876 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
877 vq_err(vq, "Non atomic userspace memory access: uaddr "
878 "%p size 0x%llx\n", addr,
879 (unsigned long long) size);
880 return NULL;
883 return vq->iotlb_iov[0].iov_base;
886 /* This function should be called after iotlb
887 * prefetch, which means we're sure that vq
888 * could be access through iotlb. So -EAGAIN should
889 * not happen in this case.
891 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
892 void *addr, unsigned int size,
893 int type)
895 void __user *uaddr = vhost_vq_meta_fetch(vq,
896 (u64)(uintptr_t)addr, size, type);
897 if (uaddr)
898 return uaddr;
900 return __vhost_get_user_slow(vq, addr, size, type);
903 #define vhost_put_user(vq, x, ptr) \
904 ({ \
905 int ret = -EFAULT; \
906 if (!vq->iotlb) { \
907 ret = __put_user(x, ptr); \
908 } else { \
909 __typeof__(ptr) to = \
910 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
911 sizeof(*ptr), VHOST_ADDR_USED); \
912 if (to != NULL) \
913 ret = __put_user(x, to); \
914 else \
915 ret = -EFAULT; \
917 ret; \
920 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
922 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
923 vhost_avail_event(vq));
926 static inline int vhost_put_used(struct vhost_virtqueue *vq,
927 struct vring_used_elem *head, int idx,
928 int count)
930 return vhost_copy_to_user(vq, vq->used->ring + idx, head,
931 count * sizeof(*head));
934 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
937 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
938 &vq->used->flags);
941 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
944 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
945 &vq->used->idx);
948 #define vhost_get_user(vq, x, ptr, type) \
949 ({ \
950 int ret; \
951 if (!vq->iotlb) { \
952 ret = __get_user(x, ptr); \
953 } else { \
954 __typeof__(ptr) from = \
955 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
956 sizeof(*ptr), \
957 type); \
958 if (from != NULL) \
959 ret = __get_user(x, from); \
960 else \
961 ret = -EFAULT; \
963 ret; \
966 #define vhost_get_avail(vq, x, ptr) \
967 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
969 #define vhost_get_used(vq, x, ptr) \
970 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
972 static void vhost_dev_lock_vqs(struct vhost_dev *d)
974 int i = 0;
975 for (i = 0; i < d->nvqs; ++i)
976 mutex_lock_nested(&d->vqs[i]->mutex, i);
979 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
981 int i = 0;
982 for (i = 0; i < d->nvqs; ++i)
983 mutex_unlock(&d->vqs[i]->mutex);
986 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
987 __virtio16 *idx)
989 return vhost_get_avail(vq, *idx, &vq->avail->idx);
992 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
993 __virtio16 *head, int idx)
995 return vhost_get_avail(vq, *head,
996 &vq->avail->ring[idx & (vq->num - 1)]);
999 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1000 __virtio16 *flags)
1002 return vhost_get_avail(vq, *flags, &vq->avail->flags);
1005 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1006 __virtio16 *event)
1008 return vhost_get_avail(vq, *event, vhost_used_event(vq));
1011 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1012 __virtio16 *idx)
1014 return vhost_get_used(vq, *idx, &vq->used->idx);
1017 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1018 struct vring_desc *desc, int idx)
1020 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1023 static int vhost_new_umem_range(struct vhost_umem *umem,
1024 u64 start, u64 size, u64 end,
1025 u64 userspace_addr, int perm)
1027 struct vhost_umem_node *tmp, *node;
1029 if (!size)
1030 return -EFAULT;
1032 node = kmalloc(sizeof(*node), GFP_ATOMIC);
1033 if (!node)
1034 return -ENOMEM;
1036 if (umem->numem == max_iotlb_entries) {
1037 tmp = list_first_entry(&umem->umem_list, typeof(*tmp), link);
1038 vhost_umem_free(umem, tmp);
1041 node->start = start;
1042 node->size = size;
1043 node->last = end;
1044 node->userspace_addr = userspace_addr;
1045 node->perm = perm;
1046 INIT_LIST_HEAD(&node->link);
1047 list_add_tail(&node->link, &umem->umem_list);
1048 vhost_umem_interval_tree_insert(node, &umem->umem_tree);
1049 umem->numem++;
1051 return 0;
1054 static void vhost_del_umem_range(struct vhost_umem *umem,
1055 u64 start, u64 end)
1057 struct vhost_umem_node *node;
1059 while ((node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1060 start, end)))
1061 vhost_umem_free(umem, node);
1064 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1065 struct vhost_iotlb_msg *msg)
1067 struct vhost_msg_node *node, *n;
1069 spin_lock(&d->iotlb_lock);
1071 list_for_each_entry_safe(node, n, &d->pending_list, node) {
1072 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1073 if (msg->iova <= vq_msg->iova &&
1074 msg->iova + msg->size - 1 >= vq_msg->iova &&
1075 vq_msg->type == VHOST_IOTLB_MISS) {
1076 vhost_poll_queue(&node->vq->poll);
1077 list_del(&node->node);
1078 kfree(node);
1082 spin_unlock(&d->iotlb_lock);
1085 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1087 unsigned long a = uaddr;
1089 /* Make sure 64 bit math will not overflow. */
1090 if (vhost_overflow(uaddr, size))
1091 return false;
1093 if ((access & VHOST_ACCESS_RO) &&
1094 !access_ok((void __user *)a, size))
1095 return false;
1096 if ((access & VHOST_ACCESS_WO) &&
1097 !access_ok((void __user *)a, size))
1098 return false;
1099 return true;
1102 static int vhost_process_iotlb_msg(struct vhost_dev *dev,
1103 struct vhost_iotlb_msg *msg)
1105 int ret = 0;
1107 mutex_lock(&dev->mutex);
1108 vhost_dev_lock_vqs(dev);
1109 switch (msg->type) {
1110 case VHOST_IOTLB_UPDATE:
1111 if (!dev->iotlb) {
1112 ret = -EFAULT;
1113 break;
1115 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1116 ret = -EFAULT;
1117 break;
1119 vhost_vq_meta_reset(dev);
1120 if (vhost_new_umem_range(dev->iotlb, msg->iova, msg->size,
1121 msg->iova + msg->size - 1,
1122 msg->uaddr, msg->perm)) {
1123 ret = -ENOMEM;
1124 break;
1126 vhost_iotlb_notify_vq(dev, msg);
1127 break;
1128 case VHOST_IOTLB_INVALIDATE:
1129 if (!dev->iotlb) {
1130 ret = -EFAULT;
1131 break;
1133 vhost_vq_meta_reset(dev);
1134 vhost_del_umem_range(dev->iotlb, msg->iova,
1135 msg->iova + msg->size - 1);
1136 break;
1137 default:
1138 ret = -EINVAL;
1139 break;
1142 vhost_dev_unlock_vqs(dev);
1143 mutex_unlock(&dev->mutex);
1145 return ret;
1147 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1148 struct iov_iter *from)
1150 struct vhost_iotlb_msg msg;
1151 size_t offset;
1152 int type, ret;
1154 ret = copy_from_iter(&type, sizeof(type), from);
1155 if (ret != sizeof(type)) {
1156 ret = -EINVAL;
1157 goto done;
1160 switch (type) {
1161 case VHOST_IOTLB_MSG:
1162 /* There maybe a hole after type for V1 message type,
1163 * so skip it here.
1165 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1166 break;
1167 case VHOST_IOTLB_MSG_V2:
1168 offset = sizeof(__u32);
1169 break;
1170 default:
1171 ret = -EINVAL;
1172 goto done;
1175 iov_iter_advance(from, offset);
1176 ret = copy_from_iter(&msg, sizeof(msg), from);
1177 if (ret != sizeof(msg)) {
1178 ret = -EINVAL;
1179 goto done;
1181 if (vhost_process_iotlb_msg(dev, &msg)) {
1182 ret = -EFAULT;
1183 goto done;
1186 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1187 sizeof(struct vhost_msg_v2);
1188 done:
1189 return ret;
1191 EXPORT_SYMBOL(vhost_chr_write_iter);
1193 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1194 poll_table *wait)
1196 __poll_t mask = 0;
1198 poll_wait(file, &dev->wait, wait);
1200 if (!list_empty(&dev->read_list))
1201 mask |= EPOLLIN | EPOLLRDNORM;
1203 return mask;
1205 EXPORT_SYMBOL(vhost_chr_poll);
1207 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1208 int noblock)
1210 DEFINE_WAIT(wait);
1211 struct vhost_msg_node *node;
1212 ssize_t ret = 0;
1213 unsigned size = sizeof(struct vhost_msg);
1215 if (iov_iter_count(to) < size)
1216 return 0;
1218 while (1) {
1219 if (!noblock)
1220 prepare_to_wait(&dev->wait, &wait,
1221 TASK_INTERRUPTIBLE);
1223 node = vhost_dequeue_msg(dev, &dev->read_list);
1224 if (node)
1225 break;
1226 if (noblock) {
1227 ret = -EAGAIN;
1228 break;
1230 if (signal_pending(current)) {
1231 ret = -ERESTARTSYS;
1232 break;
1234 if (!dev->iotlb) {
1235 ret = -EBADFD;
1236 break;
1239 schedule();
1242 if (!noblock)
1243 finish_wait(&dev->wait, &wait);
1245 if (node) {
1246 struct vhost_iotlb_msg *msg;
1247 void *start = &node->msg;
1249 switch (node->msg.type) {
1250 case VHOST_IOTLB_MSG:
1251 size = sizeof(node->msg);
1252 msg = &node->msg.iotlb;
1253 break;
1254 case VHOST_IOTLB_MSG_V2:
1255 size = sizeof(node->msg_v2);
1256 msg = &node->msg_v2.iotlb;
1257 break;
1258 default:
1259 BUG();
1260 break;
1263 ret = copy_to_iter(start, size, to);
1264 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1265 kfree(node);
1266 return ret;
1268 vhost_enqueue_msg(dev, &dev->pending_list, node);
1271 return ret;
1273 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1275 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1277 struct vhost_dev *dev = vq->dev;
1278 struct vhost_msg_node *node;
1279 struct vhost_iotlb_msg *msg;
1280 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1282 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1283 if (!node)
1284 return -ENOMEM;
1286 if (v2) {
1287 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1288 msg = &node->msg_v2.iotlb;
1289 } else {
1290 msg = &node->msg.iotlb;
1293 msg->type = VHOST_IOTLB_MISS;
1294 msg->iova = iova;
1295 msg->perm = access;
1297 vhost_enqueue_msg(dev, &dev->read_list, node);
1299 return 0;
1302 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1303 struct vring_desc __user *desc,
1304 struct vring_avail __user *avail,
1305 struct vring_used __user *used)
1308 return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1309 access_ok(avail, vhost_get_avail_size(vq, num)) &&
1310 access_ok(used, vhost_get_used_size(vq, num));
1313 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1314 const struct vhost_umem_node *node,
1315 int type)
1317 int access = (type == VHOST_ADDR_USED) ?
1318 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1320 if (likely(node->perm & access))
1321 vq->meta_iotlb[type] = node;
1324 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1325 int access, u64 addr, u64 len, int type)
1327 const struct vhost_umem_node *node;
1328 struct vhost_umem *umem = vq->iotlb;
1329 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1331 if (vhost_vq_meta_fetch(vq, addr, len, type))
1332 return true;
1334 while (len > s) {
1335 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1336 addr,
1337 last);
1338 if (node == NULL || node->start > addr) {
1339 vhost_iotlb_miss(vq, addr, access);
1340 return false;
1341 } else if (!(node->perm & access)) {
1342 /* Report the possible access violation by
1343 * request another translation from userspace.
1345 return false;
1348 size = node->size - addr + node->start;
1350 if (orig_addr == addr && size >= len)
1351 vhost_vq_meta_update(vq, node, type);
1353 s += size;
1354 addr += size;
1357 return true;
1360 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1362 unsigned int num = vq->num;
1364 if (!vq->iotlb)
1365 return 1;
1367 return iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->desc,
1368 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1369 iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->avail,
1370 vhost_get_avail_size(vq, num),
1371 VHOST_ADDR_AVAIL) &&
1372 iotlb_access_ok(vq, VHOST_ACCESS_WO, (u64)(uintptr_t)vq->used,
1373 vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1375 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1377 /* Can we log writes? */
1378 /* Caller should have device mutex but not vq mutex */
1379 bool vhost_log_access_ok(struct vhost_dev *dev)
1381 return memory_access_ok(dev, dev->umem, 1);
1383 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1385 /* Verify access for write logging. */
1386 /* Caller should have vq mutex and device mutex */
1387 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1388 void __user *log_base)
1390 return vq_memory_access_ok(log_base, vq->umem,
1391 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1392 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
1393 vhost_get_used_size(vq, vq->num)));
1396 /* Can we start vq? */
1397 /* Caller should have vq mutex and device mutex */
1398 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
1400 if (!vq_log_access_ok(vq, vq->log_base))
1401 return false;
1403 /* Access validation occurs at prefetch time with IOTLB */
1404 if (vq->iotlb)
1405 return true;
1407 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1409 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1411 static struct vhost_umem *vhost_umem_alloc(void)
1413 struct vhost_umem *umem = kvzalloc(sizeof(*umem), GFP_KERNEL);
1415 if (!umem)
1416 return NULL;
1418 umem->umem_tree = RB_ROOT_CACHED;
1419 umem->numem = 0;
1420 INIT_LIST_HEAD(&umem->umem_list);
1422 return umem;
1425 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1427 struct vhost_memory mem, *newmem;
1428 struct vhost_memory_region *region;
1429 struct vhost_umem *newumem, *oldumem;
1430 unsigned long size = offsetof(struct vhost_memory, regions);
1431 int i;
1433 if (copy_from_user(&mem, m, size))
1434 return -EFAULT;
1435 if (mem.padding)
1436 return -EOPNOTSUPP;
1437 if (mem.nregions > max_mem_regions)
1438 return -E2BIG;
1439 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1440 GFP_KERNEL);
1441 if (!newmem)
1442 return -ENOMEM;
1444 memcpy(newmem, &mem, size);
1445 if (copy_from_user(newmem->regions, m->regions,
1446 mem.nregions * sizeof *m->regions)) {
1447 kvfree(newmem);
1448 return -EFAULT;
1451 newumem = vhost_umem_alloc();
1452 if (!newumem) {
1453 kvfree(newmem);
1454 return -ENOMEM;
1457 for (region = newmem->regions;
1458 region < newmem->regions + mem.nregions;
1459 region++) {
1460 if (vhost_new_umem_range(newumem,
1461 region->guest_phys_addr,
1462 region->memory_size,
1463 region->guest_phys_addr +
1464 region->memory_size - 1,
1465 region->userspace_addr,
1466 VHOST_ACCESS_RW))
1467 goto err;
1470 if (!memory_access_ok(d, newumem, 0))
1471 goto err;
1473 oldumem = d->umem;
1474 d->umem = newumem;
1476 /* All memory accesses are done under some VQ mutex. */
1477 for (i = 0; i < d->nvqs; ++i) {
1478 mutex_lock(&d->vqs[i]->mutex);
1479 d->vqs[i]->umem = newumem;
1480 mutex_unlock(&d->vqs[i]->mutex);
1483 kvfree(newmem);
1484 vhost_umem_clean(oldumem);
1485 return 0;
1487 err:
1488 vhost_umem_clean(newumem);
1489 kvfree(newmem);
1490 return -EFAULT;
1493 static long vhost_vring_set_num(struct vhost_dev *d,
1494 struct vhost_virtqueue *vq,
1495 void __user *argp)
1497 struct vhost_vring_state s;
1499 /* Resizing ring with an active backend?
1500 * You don't want to do that. */
1501 if (vq->private_data)
1502 return -EBUSY;
1504 if (copy_from_user(&s, argp, sizeof s))
1505 return -EFAULT;
1507 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
1508 return -EINVAL;
1509 vq->num = s.num;
1511 return 0;
1514 static long vhost_vring_set_addr(struct vhost_dev *d,
1515 struct vhost_virtqueue *vq,
1516 void __user *argp)
1518 struct vhost_vring_addr a;
1520 if (copy_from_user(&a, argp, sizeof a))
1521 return -EFAULT;
1522 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
1523 return -EOPNOTSUPP;
1525 /* For 32bit, verify that the top 32bits of the user
1526 data are set to zero. */
1527 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1528 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1529 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
1530 return -EFAULT;
1532 /* Make sure it's safe to cast pointers to vring types. */
1533 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1534 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1535 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1536 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1537 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
1538 return -EINVAL;
1540 /* We only verify access here if backend is configured.
1541 * If it is not, we don't as size might not have been setup.
1542 * We will verify when backend is configured. */
1543 if (vq->private_data) {
1544 if (!vq_access_ok(vq, vq->num,
1545 (void __user *)(unsigned long)a.desc_user_addr,
1546 (void __user *)(unsigned long)a.avail_user_addr,
1547 (void __user *)(unsigned long)a.used_user_addr))
1548 return -EINVAL;
1550 /* Also validate log access for used ring if enabled. */
1551 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
1552 !log_access_ok(vq->log_base, a.log_guest_addr,
1553 sizeof *vq->used +
1554 vq->num * sizeof *vq->used->ring))
1555 return -EINVAL;
1558 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1559 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1560 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1561 vq->log_addr = a.log_guest_addr;
1562 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1564 return 0;
1567 static long vhost_vring_set_num_addr(struct vhost_dev *d,
1568 struct vhost_virtqueue *vq,
1569 unsigned int ioctl,
1570 void __user *argp)
1572 long r;
1574 mutex_lock(&vq->mutex);
1576 switch (ioctl) {
1577 case VHOST_SET_VRING_NUM:
1578 r = vhost_vring_set_num(d, vq, argp);
1579 break;
1580 case VHOST_SET_VRING_ADDR:
1581 r = vhost_vring_set_addr(d, vq, argp);
1582 break;
1583 default:
1584 BUG();
1587 mutex_unlock(&vq->mutex);
1589 return r;
1591 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1593 struct file *eventfp, *filep = NULL;
1594 bool pollstart = false, pollstop = false;
1595 struct eventfd_ctx *ctx = NULL;
1596 u32 __user *idxp = argp;
1597 struct vhost_virtqueue *vq;
1598 struct vhost_vring_state s;
1599 struct vhost_vring_file f;
1600 u32 idx;
1601 long r;
1603 r = get_user(idx, idxp);
1604 if (r < 0)
1605 return r;
1606 if (idx >= d->nvqs)
1607 return -ENOBUFS;
1609 idx = array_index_nospec(idx, d->nvqs);
1610 vq = d->vqs[idx];
1612 if (ioctl == VHOST_SET_VRING_NUM ||
1613 ioctl == VHOST_SET_VRING_ADDR) {
1614 return vhost_vring_set_num_addr(d, vq, ioctl, argp);
1617 mutex_lock(&vq->mutex);
1619 switch (ioctl) {
1620 case VHOST_SET_VRING_BASE:
1621 /* Moving base with an active backend?
1622 * You don't want to do that. */
1623 if (vq->private_data) {
1624 r = -EBUSY;
1625 break;
1627 if (copy_from_user(&s, argp, sizeof s)) {
1628 r = -EFAULT;
1629 break;
1631 if (s.num > 0xffff) {
1632 r = -EINVAL;
1633 break;
1635 vq->last_avail_idx = s.num;
1636 /* Forget the cached index value. */
1637 vq->avail_idx = vq->last_avail_idx;
1638 break;
1639 case VHOST_GET_VRING_BASE:
1640 s.index = idx;
1641 s.num = vq->last_avail_idx;
1642 if (copy_to_user(argp, &s, sizeof s))
1643 r = -EFAULT;
1644 break;
1645 case VHOST_SET_VRING_KICK:
1646 if (copy_from_user(&f, argp, sizeof f)) {
1647 r = -EFAULT;
1648 break;
1650 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1651 if (IS_ERR(eventfp)) {
1652 r = PTR_ERR(eventfp);
1653 break;
1655 if (eventfp != vq->kick) {
1656 pollstop = (filep = vq->kick) != NULL;
1657 pollstart = (vq->kick = eventfp) != NULL;
1658 } else
1659 filep = eventfp;
1660 break;
1661 case VHOST_SET_VRING_CALL:
1662 if (copy_from_user(&f, argp, sizeof f)) {
1663 r = -EFAULT;
1664 break;
1666 ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1667 if (IS_ERR(ctx)) {
1668 r = PTR_ERR(ctx);
1669 break;
1671 swap(ctx, vq->call_ctx);
1672 break;
1673 case VHOST_SET_VRING_ERR:
1674 if (copy_from_user(&f, argp, sizeof f)) {
1675 r = -EFAULT;
1676 break;
1678 ctx = f.fd == -1 ? NULL : eventfd_ctx_fdget(f.fd);
1679 if (IS_ERR(ctx)) {
1680 r = PTR_ERR(ctx);
1681 break;
1683 swap(ctx, vq->error_ctx);
1684 break;
1685 case VHOST_SET_VRING_ENDIAN:
1686 r = vhost_set_vring_endian(vq, argp);
1687 break;
1688 case VHOST_GET_VRING_ENDIAN:
1689 r = vhost_get_vring_endian(vq, idx, argp);
1690 break;
1691 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1692 if (copy_from_user(&s, argp, sizeof(s))) {
1693 r = -EFAULT;
1694 break;
1696 vq->busyloop_timeout = s.num;
1697 break;
1698 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1699 s.index = idx;
1700 s.num = vq->busyloop_timeout;
1701 if (copy_to_user(argp, &s, sizeof(s)))
1702 r = -EFAULT;
1703 break;
1704 default:
1705 r = -ENOIOCTLCMD;
1708 if (pollstop && vq->handle_kick)
1709 vhost_poll_stop(&vq->poll);
1711 if (!IS_ERR_OR_NULL(ctx))
1712 eventfd_ctx_put(ctx);
1713 if (filep)
1714 fput(filep);
1716 if (pollstart && vq->handle_kick)
1717 r = vhost_poll_start(&vq->poll, vq->kick);
1719 mutex_unlock(&vq->mutex);
1721 if (pollstop && vq->handle_kick)
1722 vhost_poll_flush(&vq->poll);
1723 return r;
1725 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1727 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1729 struct vhost_umem *niotlb, *oiotlb;
1730 int i;
1732 niotlb = vhost_umem_alloc();
1733 if (!niotlb)
1734 return -ENOMEM;
1736 oiotlb = d->iotlb;
1737 d->iotlb = niotlb;
1739 for (i = 0; i < d->nvqs; ++i) {
1740 struct vhost_virtqueue *vq = d->vqs[i];
1742 mutex_lock(&vq->mutex);
1743 vq->iotlb = niotlb;
1744 __vhost_vq_meta_reset(vq);
1745 mutex_unlock(&vq->mutex);
1748 vhost_umem_clean(oiotlb);
1750 return 0;
1752 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1754 /* Caller must have device mutex */
1755 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1757 struct eventfd_ctx *ctx;
1758 u64 p;
1759 long r;
1760 int i, fd;
1762 /* If you are not the owner, you can become one */
1763 if (ioctl == VHOST_SET_OWNER) {
1764 r = vhost_dev_set_owner(d);
1765 goto done;
1768 /* You must be the owner to do anything else */
1769 r = vhost_dev_check_owner(d);
1770 if (r)
1771 goto done;
1773 switch (ioctl) {
1774 case VHOST_SET_MEM_TABLE:
1775 r = vhost_set_memory(d, argp);
1776 break;
1777 case VHOST_SET_LOG_BASE:
1778 if (copy_from_user(&p, argp, sizeof p)) {
1779 r = -EFAULT;
1780 break;
1782 if ((u64)(unsigned long)p != p) {
1783 r = -EFAULT;
1784 break;
1786 for (i = 0; i < d->nvqs; ++i) {
1787 struct vhost_virtqueue *vq;
1788 void __user *base = (void __user *)(unsigned long)p;
1789 vq = d->vqs[i];
1790 mutex_lock(&vq->mutex);
1791 /* If ring is inactive, will check when it's enabled. */
1792 if (vq->private_data && !vq_log_access_ok(vq, base))
1793 r = -EFAULT;
1794 else
1795 vq->log_base = base;
1796 mutex_unlock(&vq->mutex);
1798 break;
1799 case VHOST_SET_LOG_FD:
1800 r = get_user(fd, (int __user *)argp);
1801 if (r < 0)
1802 break;
1803 ctx = fd == -1 ? NULL : eventfd_ctx_fdget(fd);
1804 if (IS_ERR(ctx)) {
1805 r = PTR_ERR(ctx);
1806 break;
1808 swap(ctx, d->log_ctx);
1809 for (i = 0; i < d->nvqs; ++i) {
1810 mutex_lock(&d->vqs[i]->mutex);
1811 d->vqs[i]->log_ctx = d->log_ctx;
1812 mutex_unlock(&d->vqs[i]->mutex);
1814 if (ctx)
1815 eventfd_ctx_put(ctx);
1816 break;
1817 default:
1818 r = -ENOIOCTLCMD;
1819 break;
1821 done:
1822 return r;
1824 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1826 /* TODO: This is really inefficient. We need something like get_user()
1827 * (instruction directly accesses the data, with an exception table entry
1828 * returning -EFAULT). See Documentation/x86/exception-tables.rst.
1830 static int set_bit_to_user(int nr, void __user *addr)
1832 unsigned long log = (unsigned long)addr;
1833 struct page *page;
1834 void *base;
1835 int bit = nr + (log % PAGE_SIZE) * 8;
1836 int r;
1838 r = get_user_pages_fast(log, 1, FOLL_WRITE, &page);
1839 if (r < 0)
1840 return r;
1841 BUG_ON(r != 1);
1842 base = kmap_atomic(page);
1843 set_bit(bit, base);
1844 kunmap_atomic(base);
1845 set_page_dirty_lock(page);
1846 put_page(page);
1847 return 0;
1850 static int log_write(void __user *log_base,
1851 u64 write_address, u64 write_length)
1853 u64 write_page = write_address / VHOST_PAGE_SIZE;
1854 int r;
1856 if (!write_length)
1857 return 0;
1858 write_length += write_address % VHOST_PAGE_SIZE;
1859 for (;;) {
1860 u64 base = (u64)(unsigned long)log_base;
1861 u64 log = base + write_page / 8;
1862 int bit = write_page % 8;
1863 if ((u64)(unsigned long)log != log)
1864 return -EFAULT;
1865 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1866 if (r < 0)
1867 return r;
1868 if (write_length <= VHOST_PAGE_SIZE)
1869 break;
1870 write_length -= VHOST_PAGE_SIZE;
1871 write_page += 1;
1873 return r;
1876 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1878 struct vhost_umem *umem = vq->umem;
1879 struct vhost_umem_node *u;
1880 u64 start, end, l, min;
1881 int r;
1882 bool hit = false;
1884 while (len) {
1885 min = len;
1886 /* More than one GPAs can be mapped into a single HVA. So
1887 * iterate all possible umems here to be safe.
1889 list_for_each_entry(u, &umem->umem_list, link) {
1890 if (u->userspace_addr > hva - 1 + len ||
1891 u->userspace_addr - 1 + u->size < hva)
1892 continue;
1893 start = max(u->userspace_addr, hva);
1894 end = min(u->userspace_addr - 1 + u->size,
1895 hva - 1 + len);
1896 l = end - start + 1;
1897 r = log_write(vq->log_base,
1898 u->start + start - u->userspace_addr,
1900 if (r < 0)
1901 return r;
1902 hit = true;
1903 min = min(l, min);
1906 if (!hit)
1907 return -EFAULT;
1909 len -= min;
1910 hva += min;
1913 return 0;
1916 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1918 struct iovec iov[64];
1919 int i, ret;
1921 if (!vq->iotlb)
1922 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1924 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1925 len, iov, 64, VHOST_ACCESS_WO);
1926 if (ret < 0)
1927 return ret;
1929 for (i = 0; i < ret; i++) {
1930 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1931 iov[i].iov_len);
1932 if (ret)
1933 return ret;
1936 return 0;
1939 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1940 unsigned int log_num, u64 len, struct iovec *iov, int count)
1942 int i, r;
1944 /* Make sure data written is seen before log. */
1945 smp_wmb();
1947 if (vq->iotlb) {
1948 for (i = 0; i < count; i++) {
1949 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1950 iov[i].iov_len);
1951 if (r < 0)
1952 return r;
1954 return 0;
1957 for (i = 0; i < log_num; ++i) {
1958 u64 l = min(log[i].len, len);
1959 r = log_write(vq->log_base, log[i].addr, l);
1960 if (r < 0)
1961 return r;
1962 len -= l;
1963 if (!len) {
1964 if (vq->log_ctx)
1965 eventfd_signal(vq->log_ctx, 1);
1966 return 0;
1969 /* Length written exceeds what we have stored. This is a bug. */
1970 BUG();
1971 return 0;
1973 EXPORT_SYMBOL_GPL(vhost_log_write);
1975 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1977 void __user *used;
1978 if (vhost_put_used_flags(vq))
1979 return -EFAULT;
1980 if (unlikely(vq->log_used)) {
1981 /* Make sure the flag is seen before log. */
1982 smp_wmb();
1983 /* Log used flag write. */
1984 used = &vq->used->flags;
1985 log_used(vq, (used - (void __user *)vq->used),
1986 sizeof vq->used->flags);
1987 if (vq->log_ctx)
1988 eventfd_signal(vq->log_ctx, 1);
1990 return 0;
1993 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1995 if (vhost_put_avail_event(vq))
1996 return -EFAULT;
1997 if (unlikely(vq->log_used)) {
1998 void __user *used;
1999 /* Make sure the event is seen before log. */
2000 smp_wmb();
2001 /* Log avail event write */
2002 used = vhost_avail_event(vq);
2003 log_used(vq, (used - (void __user *)vq->used),
2004 sizeof *vhost_avail_event(vq));
2005 if (vq->log_ctx)
2006 eventfd_signal(vq->log_ctx, 1);
2008 return 0;
2011 int vhost_vq_init_access(struct vhost_virtqueue *vq)
2013 __virtio16 last_used_idx;
2014 int r;
2015 bool is_le = vq->is_le;
2017 if (!vq->private_data)
2018 return 0;
2020 vhost_init_is_le(vq);
2022 r = vhost_update_used_flags(vq);
2023 if (r)
2024 goto err;
2025 vq->signalled_used_valid = false;
2026 if (!vq->iotlb &&
2027 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
2028 r = -EFAULT;
2029 goto err;
2031 r = vhost_get_used_idx(vq, &last_used_idx);
2032 if (r) {
2033 vq_err(vq, "Can't access used idx at %p\n",
2034 &vq->used->idx);
2035 goto err;
2037 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2038 return 0;
2040 err:
2041 vq->is_le = is_le;
2042 return r;
2044 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2046 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2047 struct iovec iov[], int iov_size, int access)
2049 const struct vhost_umem_node *node;
2050 struct vhost_dev *dev = vq->dev;
2051 struct vhost_umem *umem = dev->iotlb ? dev->iotlb : dev->umem;
2052 struct iovec *_iov;
2053 u64 s = 0;
2054 int ret = 0;
2056 while ((u64)len > s) {
2057 u64 size;
2058 if (unlikely(ret >= iov_size)) {
2059 ret = -ENOBUFS;
2060 break;
2063 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
2064 addr, addr + len - 1);
2065 if (node == NULL || node->start > addr) {
2066 if (umem != dev->iotlb) {
2067 ret = -EFAULT;
2068 break;
2070 ret = -EAGAIN;
2071 break;
2072 } else if (!(node->perm & access)) {
2073 ret = -EPERM;
2074 break;
2077 _iov = iov + ret;
2078 size = node->size - addr + node->start;
2079 _iov->iov_len = min((u64)len - s, size);
2080 _iov->iov_base = (void __user *)(unsigned long)
2081 (node->userspace_addr + addr - node->start);
2082 s += size;
2083 addr += size;
2084 ++ret;
2087 if (ret == -EAGAIN)
2088 vhost_iotlb_miss(vq, addr, access);
2089 return ret;
2092 /* Each buffer in the virtqueues is actually a chain of descriptors. This
2093 * function returns the next descriptor in the chain,
2094 * or -1U if we're at the end. */
2095 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2097 unsigned int next;
2099 /* If this descriptor says it doesn't chain, we're done. */
2100 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2101 return -1U;
2103 /* Check they're not leading us off end of descriptors. */
2104 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2105 return next;
2108 static int get_indirect(struct vhost_virtqueue *vq,
2109 struct iovec iov[], unsigned int iov_size,
2110 unsigned int *out_num, unsigned int *in_num,
2111 struct vhost_log *log, unsigned int *log_num,
2112 struct vring_desc *indirect)
2114 struct vring_desc desc;
2115 unsigned int i = 0, count, found = 0;
2116 u32 len = vhost32_to_cpu(vq, indirect->len);
2117 struct iov_iter from;
2118 int ret, access;
2120 /* Sanity check */
2121 if (unlikely(len % sizeof desc)) {
2122 vq_err(vq, "Invalid length in indirect descriptor: "
2123 "len 0x%llx not multiple of 0x%zx\n",
2124 (unsigned long long)len,
2125 sizeof desc);
2126 return -EINVAL;
2129 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2130 UIO_MAXIOV, VHOST_ACCESS_RO);
2131 if (unlikely(ret < 0)) {
2132 if (ret != -EAGAIN)
2133 vq_err(vq, "Translation failure %d in indirect.\n", ret);
2134 return ret;
2136 iov_iter_init(&from, READ, vq->indirect, ret, len);
2138 /* We will use the result as an address to read from, so most
2139 * architectures only need a compiler barrier here. */
2140 read_barrier_depends();
2142 count = len / sizeof desc;
2143 /* Buffers are chained via a 16 bit next field, so
2144 * we can have at most 2^16 of these. */
2145 if (unlikely(count > USHRT_MAX + 1)) {
2146 vq_err(vq, "Indirect buffer length too big: %d\n",
2147 indirect->len);
2148 return -E2BIG;
2151 do {
2152 unsigned iov_count = *in_num + *out_num;
2153 if (unlikely(++found > count)) {
2154 vq_err(vq, "Loop detected: last one at %u "
2155 "indirect size %u\n",
2156 i, count);
2157 return -EINVAL;
2159 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2160 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2161 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2162 return -EINVAL;
2164 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2165 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2166 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2167 return -EINVAL;
2170 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2171 access = VHOST_ACCESS_WO;
2172 else
2173 access = VHOST_ACCESS_RO;
2175 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2176 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2177 iov_size - iov_count, access);
2178 if (unlikely(ret < 0)) {
2179 if (ret != -EAGAIN)
2180 vq_err(vq, "Translation failure %d indirect idx %d\n",
2181 ret, i);
2182 return ret;
2184 /* If this is an input descriptor, increment that count. */
2185 if (access == VHOST_ACCESS_WO) {
2186 *in_num += ret;
2187 if (unlikely(log && ret)) {
2188 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2189 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2190 ++*log_num;
2192 } else {
2193 /* If it's an output descriptor, they're all supposed
2194 * to come before any input descriptors. */
2195 if (unlikely(*in_num)) {
2196 vq_err(vq, "Indirect descriptor "
2197 "has out after in: idx %d\n", i);
2198 return -EINVAL;
2200 *out_num += ret;
2202 } while ((i = next_desc(vq, &desc)) != -1);
2203 return 0;
2206 /* This looks in the virtqueue and for the first available buffer, and converts
2207 * it to an iovec for convenient access. Since descriptors consist of some
2208 * number of output then some number of input descriptors, it's actually two
2209 * iovecs, but we pack them into one and note how many of each there were.
2211 * This function returns the descriptor number found, or vq->num (which is
2212 * never a valid descriptor number) if none was found. A negative code is
2213 * returned on error. */
2214 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2215 struct iovec iov[], unsigned int iov_size,
2216 unsigned int *out_num, unsigned int *in_num,
2217 struct vhost_log *log, unsigned int *log_num)
2219 struct vring_desc desc;
2220 unsigned int i, head, found = 0;
2221 u16 last_avail_idx;
2222 __virtio16 avail_idx;
2223 __virtio16 ring_head;
2224 int ret, access;
2226 /* Check it isn't doing very strange things with descriptor numbers. */
2227 last_avail_idx = vq->last_avail_idx;
2229 if (vq->avail_idx == vq->last_avail_idx) {
2230 if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
2231 vq_err(vq, "Failed to access avail idx at %p\n",
2232 &vq->avail->idx);
2233 return -EFAULT;
2235 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2237 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2238 vq_err(vq, "Guest moved used index from %u to %u",
2239 last_avail_idx, vq->avail_idx);
2240 return -EFAULT;
2243 /* If there's nothing new since last we looked, return
2244 * invalid.
2246 if (vq->avail_idx == last_avail_idx)
2247 return vq->num;
2249 /* Only get avail ring entries after they have been
2250 * exposed by guest.
2252 smp_rmb();
2255 /* Grab the next descriptor number they're advertising, and increment
2256 * the index we've seen. */
2257 if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
2258 vq_err(vq, "Failed to read head: idx %d address %p\n",
2259 last_avail_idx,
2260 &vq->avail->ring[last_avail_idx % vq->num]);
2261 return -EFAULT;
2264 head = vhost16_to_cpu(vq, ring_head);
2266 /* If their number is silly, that's an error. */
2267 if (unlikely(head >= vq->num)) {
2268 vq_err(vq, "Guest says index %u > %u is available",
2269 head, vq->num);
2270 return -EINVAL;
2273 /* When we start there are none of either input nor output. */
2274 *out_num = *in_num = 0;
2275 if (unlikely(log))
2276 *log_num = 0;
2278 i = head;
2279 do {
2280 unsigned iov_count = *in_num + *out_num;
2281 if (unlikely(i >= vq->num)) {
2282 vq_err(vq, "Desc index is %u > %u, head = %u",
2283 i, vq->num, head);
2284 return -EINVAL;
2286 if (unlikely(++found > vq->num)) {
2287 vq_err(vq, "Loop detected: last one at %u "
2288 "vq size %u head %u\n",
2289 i, vq->num, head);
2290 return -EINVAL;
2292 ret = vhost_get_desc(vq, &desc, i);
2293 if (unlikely(ret)) {
2294 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2295 i, vq->desc + i);
2296 return -EFAULT;
2298 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2299 ret = get_indirect(vq, iov, iov_size,
2300 out_num, in_num,
2301 log, log_num, &desc);
2302 if (unlikely(ret < 0)) {
2303 if (ret != -EAGAIN)
2304 vq_err(vq, "Failure detected "
2305 "in indirect descriptor at idx %d\n", i);
2306 return ret;
2308 continue;
2311 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2312 access = VHOST_ACCESS_WO;
2313 else
2314 access = VHOST_ACCESS_RO;
2315 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2316 vhost32_to_cpu(vq, desc.len), iov + iov_count,
2317 iov_size - iov_count, access);
2318 if (unlikely(ret < 0)) {
2319 if (ret != -EAGAIN)
2320 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2321 ret, i);
2322 return ret;
2324 if (access == VHOST_ACCESS_WO) {
2325 /* If this is an input descriptor,
2326 * increment that count. */
2327 *in_num += ret;
2328 if (unlikely(log && ret)) {
2329 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2330 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2331 ++*log_num;
2333 } else {
2334 /* If it's an output descriptor, they're all supposed
2335 * to come before any input descriptors. */
2336 if (unlikely(*in_num)) {
2337 vq_err(vq, "Descriptor has out after in: "
2338 "idx %d\n", i);
2339 return -EINVAL;
2341 *out_num += ret;
2343 } while ((i = next_desc(vq, &desc)) != -1);
2345 /* On success, increment avail index. */
2346 vq->last_avail_idx++;
2348 /* Assume notifications from guest are disabled at this point,
2349 * if they aren't we would need to update avail_event index. */
2350 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2351 return head;
2353 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2355 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2356 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2358 vq->last_avail_idx -= n;
2360 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2362 /* After we've used one of their buffers, we tell them about it. We'll then
2363 * want to notify the guest, using eventfd. */
2364 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2366 struct vring_used_elem heads = {
2367 cpu_to_vhost32(vq, head),
2368 cpu_to_vhost32(vq, len)
2371 return vhost_add_used_n(vq, &heads, 1);
2373 EXPORT_SYMBOL_GPL(vhost_add_used);
2375 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2376 struct vring_used_elem *heads,
2377 unsigned count)
2379 struct vring_used_elem __user *used;
2380 u16 old, new;
2381 int start;
2383 start = vq->last_used_idx & (vq->num - 1);
2384 used = vq->used->ring + start;
2385 if (vhost_put_used(vq, heads, start, count)) {
2386 vq_err(vq, "Failed to write used");
2387 return -EFAULT;
2389 if (unlikely(vq->log_used)) {
2390 /* Make sure data is seen before log. */
2391 smp_wmb();
2392 /* Log used ring entry write. */
2393 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2394 count * sizeof *used);
2396 old = vq->last_used_idx;
2397 new = (vq->last_used_idx += count);
2398 /* If the driver never bothers to signal in a very long while,
2399 * used index might wrap around. If that happens, invalidate
2400 * signalled_used index we stored. TODO: make sure driver
2401 * signals at least once in 2^16 and remove this. */
2402 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2403 vq->signalled_used_valid = false;
2404 return 0;
2407 /* After we've used one of their buffers, we tell them about it. We'll then
2408 * want to notify the guest, using eventfd. */
2409 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2410 unsigned count)
2412 int start, n, r;
2414 start = vq->last_used_idx & (vq->num - 1);
2415 n = vq->num - start;
2416 if (n < count) {
2417 r = __vhost_add_used_n(vq, heads, n);
2418 if (r < 0)
2419 return r;
2420 heads += n;
2421 count -= n;
2423 r = __vhost_add_used_n(vq, heads, count);
2425 /* Make sure buffer is written before we update index. */
2426 smp_wmb();
2427 if (vhost_put_used_idx(vq)) {
2428 vq_err(vq, "Failed to increment used idx");
2429 return -EFAULT;
2431 if (unlikely(vq->log_used)) {
2432 /* Make sure used idx is seen before log. */
2433 smp_wmb();
2434 /* Log used index update. */
2435 log_used(vq, offsetof(struct vring_used, idx),
2436 sizeof vq->used->idx);
2437 if (vq->log_ctx)
2438 eventfd_signal(vq->log_ctx, 1);
2440 return r;
2442 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2444 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2446 __u16 old, new;
2447 __virtio16 event;
2448 bool v;
2449 /* Flush out used index updates. This is paired
2450 * with the barrier that the Guest executes when enabling
2451 * interrupts. */
2452 smp_mb();
2454 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2455 unlikely(vq->avail_idx == vq->last_avail_idx))
2456 return true;
2458 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2459 __virtio16 flags;
2460 if (vhost_get_avail_flags(vq, &flags)) {
2461 vq_err(vq, "Failed to get flags");
2462 return true;
2464 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2466 old = vq->signalled_used;
2467 v = vq->signalled_used_valid;
2468 new = vq->signalled_used = vq->last_used_idx;
2469 vq->signalled_used_valid = true;
2471 if (unlikely(!v))
2472 return true;
2474 if (vhost_get_used_event(vq, &event)) {
2475 vq_err(vq, "Failed to get used event idx");
2476 return true;
2478 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2481 /* This actually signals the guest, using eventfd. */
2482 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2484 /* Signal the Guest tell them we used something up. */
2485 if (vq->call_ctx && vhost_notify(dev, vq))
2486 eventfd_signal(vq->call_ctx, 1);
2488 EXPORT_SYMBOL_GPL(vhost_signal);
2490 /* And here's the combo meal deal. Supersize me! */
2491 void vhost_add_used_and_signal(struct vhost_dev *dev,
2492 struct vhost_virtqueue *vq,
2493 unsigned int head, int len)
2495 vhost_add_used(vq, head, len);
2496 vhost_signal(dev, vq);
2498 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2500 /* multi-buffer version of vhost_add_used_and_signal */
2501 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2502 struct vhost_virtqueue *vq,
2503 struct vring_used_elem *heads, unsigned count)
2505 vhost_add_used_n(vq, heads, count);
2506 vhost_signal(dev, vq);
2508 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2510 /* return true if we're sure that avaiable ring is empty */
2511 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2513 __virtio16 avail_idx;
2514 int r;
2516 if (vq->avail_idx != vq->last_avail_idx)
2517 return false;
2519 r = vhost_get_avail_idx(vq, &avail_idx);
2520 if (unlikely(r))
2521 return false;
2522 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2524 return vq->avail_idx == vq->last_avail_idx;
2526 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2528 /* OK, now we need to know about added descriptors. */
2529 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2531 __virtio16 avail_idx;
2532 int r;
2534 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2535 return false;
2536 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2537 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2538 r = vhost_update_used_flags(vq);
2539 if (r) {
2540 vq_err(vq, "Failed to enable notification at %p: %d\n",
2541 &vq->used->flags, r);
2542 return false;
2544 } else {
2545 r = vhost_update_avail_event(vq, vq->avail_idx);
2546 if (r) {
2547 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2548 vhost_avail_event(vq), r);
2549 return false;
2552 /* They could have slipped one in as we were doing that: make
2553 * sure it's written, then check again. */
2554 smp_mb();
2555 r = vhost_get_avail_idx(vq, &avail_idx);
2556 if (r) {
2557 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2558 &vq->avail->idx, r);
2559 return false;
2562 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2564 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2566 /* We don't need to be notified again. */
2567 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2569 int r;
2571 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2572 return;
2573 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2574 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2575 r = vhost_update_used_flags(vq);
2576 if (r)
2577 vq_err(vq, "Failed to enable notification at %p: %d\n",
2578 &vq->used->flags, r);
2581 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2583 /* Create a new message. */
2584 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2586 struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2587 if (!node)
2588 return NULL;
2590 /* Make sure all padding within the structure is initialized. */
2591 memset(&node->msg, 0, sizeof node->msg);
2592 node->vq = vq;
2593 node->msg.type = type;
2594 return node;
2596 EXPORT_SYMBOL_GPL(vhost_new_msg);
2598 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2599 struct vhost_msg_node *node)
2601 spin_lock(&dev->iotlb_lock);
2602 list_add_tail(&node->node, head);
2603 spin_unlock(&dev->iotlb_lock);
2605 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
2607 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2609 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2610 struct list_head *head)
2612 struct vhost_msg_node *node = NULL;
2614 spin_lock(&dev->iotlb_lock);
2615 if (!list_empty(head)) {
2616 node = list_first_entry(head, struct vhost_msg_node,
2617 node);
2618 list_del(&node->node);
2620 spin_unlock(&dev->iotlb_lock);
2622 return node;
2624 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2627 static int __init vhost_init(void)
2629 return 0;
2632 static void __exit vhost_exit(void)
2636 module_init(vhost_init);
2637 module_exit(vhost_exit);
2639 MODULE_VERSION("0.0.1");
2640 MODULE_LICENSE("GPL v2");
2641 MODULE_AUTHOR("Michael S. Tsirkin");
2642 MODULE_DESCRIPTION("Host kernel accelerator for virtio");