1 /* Copyright (C) 2009 Red Hat, Inc.
2 * Copyright (C) 2006 Rusty Russell IBM Corporation
4 * Author: Michael S. Tsirkin <mst@redhat.com>
6 * Inspiration, some code, and most witty comments come from
7 * Documentation/virtual/lguest/lguest.c, by Rusty Russell
9 * This work is licensed under the terms of the GNU GPL, version 2.
11 * Generic code for virtio server in host kernel.
14 #include <linux/eventfd.h>
15 #include <linux/vhost.h>
16 #include <linux/uio.h>
18 #include <linux/mmu_context.h>
19 #include <linux/miscdevice.h>
20 #include <linux/mutex.h>
21 #include <linux/poll.h>
22 #include <linux/file.h>
23 #include <linux/highmem.h>
24 #include <linux/slab.h>
25 #include <linux/kthread.h>
26 #include <linux/cgroup.h>
27 #include <linux/module.h>
32 VHOST_MEMORY_MAX_NREGIONS = 64,
33 VHOST_MEMORY_F_LOG = 0x1,
36 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
37 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
39 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
40 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
42 vq->user_be = !virtio_legacy_is_little_endian();
45 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
47 struct vhost_vring_state s;
52 if (copy_from_user(&s, argp, sizeof(s)))
55 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
56 s.num != VHOST_VRING_BIG_ENDIAN)
64 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
67 struct vhost_vring_state s = {
72 if (copy_to_user(argp, &s, sizeof(s)))
78 static void vhost_init_is_le(struct vhost_virtqueue *vq)
80 /* Note for legacy virtio: user_be is initialized at reset time
81 * according to the host endianness. If userspace does not set an
82 * explicit endianness, the default behavior is native endian, as
83 * expected by legacy virtio.
85 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
88 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
92 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
97 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
103 static void vhost_init_is_le(struct vhost_virtqueue *vq)
105 if (vhost_has_feature(vq, VIRTIO_F_VERSION_1))
108 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
110 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
113 struct vhost_poll *poll;
115 poll = container_of(pt, struct vhost_poll, table);
117 add_wait_queue(wqh, &poll->wait);
120 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
123 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
125 if (!((unsigned long)key & poll->mask))
128 vhost_poll_queue(poll);
132 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
134 INIT_LIST_HEAD(&work->node);
136 init_waitqueue_head(&work->done);
138 work->queue_seq = work->done_seq = 0;
140 EXPORT_SYMBOL_GPL(vhost_work_init);
142 /* Init poll structure */
143 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
144 unsigned long mask, struct vhost_dev *dev)
146 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
147 init_poll_funcptr(&poll->table, vhost_poll_func);
152 vhost_work_init(&poll->work, fn);
154 EXPORT_SYMBOL_GPL(vhost_poll_init);
156 /* Start polling a file. We add ourselves to file's wait queue. The caller must
157 * keep a reference to a file until after vhost_poll_stop is called. */
158 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
166 mask = file->f_op->poll(file, &poll->table);
168 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
169 if (mask & POLLERR) {
171 remove_wait_queue(poll->wqh, &poll->wait);
177 EXPORT_SYMBOL_GPL(vhost_poll_start);
179 /* Stop polling a file. After this function returns, it becomes safe to drop the
180 * file reference. You must also flush afterwards. */
181 void vhost_poll_stop(struct vhost_poll *poll)
184 remove_wait_queue(poll->wqh, &poll->wait);
188 EXPORT_SYMBOL_GPL(vhost_poll_stop);
190 static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
195 spin_lock_irq(&dev->work_lock);
196 left = seq - work->done_seq;
197 spin_unlock_irq(&dev->work_lock);
201 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
206 spin_lock_irq(&dev->work_lock);
207 seq = work->queue_seq;
209 spin_unlock_irq(&dev->work_lock);
210 wait_event(work->done, vhost_work_seq_done(dev, work, seq));
211 spin_lock_irq(&dev->work_lock);
212 flushing = --work->flushing;
213 spin_unlock_irq(&dev->work_lock);
214 BUG_ON(flushing < 0);
216 EXPORT_SYMBOL_GPL(vhost_work_flush);
218 /* Flush any work that has been scheduled. When calling this, don't hold any
219 * locks that are also used by the callback. */
220 void vhost_poll_flush(struct vhost_poll *poll)
222 vhost_work_flush(poll->dev, &poll->work);
224 EXPORT_SYMBOL_GPL(vhost_poll_flush);
226 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
230 spin_lock_irqsave(&dev->work_lock, flags);
231 if (list_empty(&work->node)) {
232 list_add_tail(&work->node, &dev->work_list);
234 spin_unlock_irqrestore(&dev->work_lock, flags);
235 wake_up_process(dev->worker);
237 spin_unlock_irqrestore(&dev->work_lock, flags);
240 EXPORT_SYMBOL_GPL(vhost_work_queue);
242 void vhost_poll_queue(struct vhost_poll *poll)
244 vhost_work_queue(poll->dev, &poll->work);
246 EXPORT_SYMBOL_GPL(vhost_poll_queue);
248 static void vhost_vq_reset(struct vhost_dev *dev,
249 struct vhost_virtqueue *vq)
255 vq->last_avail_idx = 0;
257 vq->last_used_idx = 0;
258 vq->signalled_used = 0;
259 vq->signalled_used_valid = false;
261 vq->log_used = false;
262 vq->log_addr = -1ull;
263 vq->private_data = NULL;
264 vq->acked_features = 0;
266 vq->error_ctx = NULL;
273 vq->is_le = virtio_legacy_is_little_endian();
274 vhost_vq_reset_user_be(vq);
277 static int vhost_worker(void *data)
279 struct vhost_dev *dev = data;
280 struct vhost_work *work = NULL;
281 unsigned uninitialized_var(seq);
282 mm_segment_t oldfs = get_fs();
288 /* mb paired w/ kthread_stop */
289 set_current_state(TASK_INTERRUPTIBLE);
291 spin_lock_irq(&dev->work_lock);
293 work->done_seq = seq;
295 wake_up_all(&work->done);
298 if (kthread_should_stop()) {
299 spin_unlock_irq(&dev->work_lock);
300 __set_current_state(TASK_RUNNING);
303 if (!list_empty(&dev->work_list)) {
304 work = list_first_entry(&dev->work_list,
305 struct vhost_work, node);
306 list_del_init(&work->node);
307 seq = work->queue_seq;
310 spin_unlock_irq(&dev->work_lock);
313 __set_current_state(TASK_RUNNING);
326 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
336 /* Helper to allocate iovec buffers for all vqs. */
337 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
339 struct vhost_virtqueue *vq;
342 for (i = 0; i < dev->nvqs; ++i) {
344 vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
346 vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
347 vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
348 if (!vq->indirect || !vq->log || !vq->heads)
355 vhost_vq_free_iovecs(dev->vqs[i]);
359 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
363 for (i = 0; i < dev->nvqs; ++i)
364 vhost_vq_free_iovecs(dev->vqs[i]);
367 void vhost_dev_init(struct vhost_dev *dev,
368 struct vhost_virtqueue **vqs, int nvqs)
370 struct vhost_virtqueue *vq;
375 mutex_init(&dev->mutex);
377 dev->log_file = NULL;
380 spin_lock_init(&dev->work_lock);
381 INIT_LIST_HEAD(&dev->work_list);
384 for (i = 0; i < dev->nvqs; ++i) {
390 mutex_init(&vq->mutex);
391 vhost_vq_reset(dev, vq);
393 vhost_poll_init(&vq->poll, vq->handle_kick,
397 EXPORT_SYMBOL_GPL(vhost_dev_init);
399 /* Caller should have device mutex */
400 long vhost_dev_check_owner(struct vhost_dev *dev)
402 /* Are you the owner? If not, I don't think you mean to do that */
403 return dev->mm == current->mm ? 0 : -EPERM;
405 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
407 struct vhost_attach_cgroups_struct {
408 struct vhost_work work;
409 struct task_struct *owner;
413 static void vhost_attach_cgroups_work(struct vhost_work *work)
415 struct vhost_attach_cgroups_struct *s;
417 s = container_of(work, struct vhost_attach_cgroups_struct, work);
418 s->ret = cgroup_attach_task_all(s->owner, current);
421 static int vhost_attach_cgroups(struct vhost_dev *dev)
423 struct vhost_attach_cgroups_struct attach;
425 attach.owner = current;
426 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
427 vhost_work_queue(dev, &attach.work);
428 vhost_work_flush(dev, &attach.work);
432 /* Caller should have device mutex */
433 bool vhost_dev_has_owner(struct vhost_dev *dev)
437 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
439 /* Caller should have device mutex */
440 long vhost_dev_set_owner(struct vhost_dev *dev)
442 struct task_struct *worker;
445 /* Is there an owner already? */
446 if (vhost_dev_has_owner(dev)) {
451 /* No owner, become one */
452 dev->mm = get_task_mm(current);
453 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
454 if (IS_ERR(worker)) {
455 err = PTR_ERR(worker);
459 dev->worker = worker;
460 wake_up_process(worker); /* avoid contributing to loadavg */
462 err = vhost_attach_cgroups(dev);
466 err = vhost_dev_alloc_iovecs(dev);
472 kthread_stop(worker);
481 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
483 struct vhost_memory *vhost_dev_reset_owner_prepare(void)
485 return kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
487 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
489 /* Caller should have device mutex */
490 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_memory *memory)
494 vhost_dev_cleanup(dev, true);
496 /* Restore memory to default empty mapping. */
497 memory->nregions = 0;
498 dev->memory = memory;
499 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
500 * VQs aren't running.
502 for (i = 0; i < dev->nvqs; ++i)
503 dev->vqs[i]->memory = memory;
505 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
507 void vhost_dev_stop(struct vhost_dev *dev)
511 for (i = 0; i < dev->nvqs; ++i) {
512 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
513 vhost_poll_stop(&dev->vqs[i]->poll);
514 vhost_poll_flush(&dev->vqs[i]->poll);
518 EXPORT_SYMBOL_GPL(vhost_dev_stop);
520 /* Caller should have device mutex if and only if locked is set */
521 void vhost_dev_cleanup(struct vhost_dev *dev, bool locked)
525 for (i = 0; i < dev->nvqs; ++i) {
526 if (dev->vqs[i]->error_ctx)
527 eventfd_ctx_put(dev->vqs[i]->error_ctx);
528 if (dev->vqs[i]->error)
529 fput(dev->vqs[i]->error);
530 if (dev->vqs[i]->kick)
531 fput(dev->vqs[i]->kick);
532 if (dev->vqs[i]->call_ctx)
533 eventfd_ctx_put(dev->vqs[i]->call_ctx);
534 if (dev->vqs[i]->call)
535 fput(dev->vqs[i]->call);
536 vhost_vq_reset(dev, dev->vqs[i]);
538 vhost_dev_free_iovecs(dev);
540 eventfd_ctx_put(dev->log_ctx);
544 dev->log_file = NULL;
545 /* No one will access memory at this point */
548 WARN_ON(!list_empty(&dev->work_list));
550 kthread_stop(dev->worker);
557 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
559 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
561 u64 a = addr / VHOST_PAGE_SIZE / 8;
563 /* Make sure 64 bit math will not overflow. */
564 if (a > ULONG_MAX - (unsigned long)log_base ||
565 a + (unsigned long)log_base > ULONG_MAX)
568 return access_ok(VERIFY_WRITE, log_base + a,
569 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
572 /* Caller should have vq mutex and device mutex. */
573 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
581 for (i = 0; i < mem->nregions; ++i) {
582 struct vhost_memory_region *m = mem->regions + i;
583 unsigned long a = m->userspace_addr;
584 if (m->memory_size > ULONG_MAX)
586 else if (!access_ok(VERIFY_WRITE, (void __user *)a,
589 else if (log_all && !log_access_ok(log_base,
597 /* Can we switch to this memory table? */
598 /* Caller should have device mutex but not vq mutex */
599 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
604 for (i = 0; i < d->nvqs; ++i) {
608 mutex_lock(&d->vqs[i]->mutex);
609 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
610 /* If ring is inactive, will check when it's enabled. */
611 if (d->vqs[i]->private_data)
612 ok = vq_memory_access_ok(d->vqs[i]->log_base, mem, log);
615 mutex_unlock(&d->vqs[i]->mutex);
622 static int vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
623 struct vring_desc __user *desc,
624 struct vring_avail __user *avail,
625 struct vring_used __user *used)
627 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
628 return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
629 access_ok(VERIFY_READ, avail,
630 sizeof *avail + num * sizeof *avail->ring + s) &&
631 access_ok(VERIFY_WRITE, used,
632 sizeof *used + num * sizeof *used->ring + s);
635 /* Can we log writes? */
636 /* Caller should have device mutex but not vq mutex */
637 int vhost_log_access_ok(struct vhost_dev *dev)
639 return memory_access_ok(dev, dev->memory, 1);
641 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
643 /* Verify access for write logging. */
644 /* Caller should have vq mutex and device mutex */
645 static int vq_log_access_ok(struct vhost_virtqueue *vq,
646 void __user *log_base)
648 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
650 return vq_memory_access_ok(log_base, vq->memory,
651 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
652 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
654 vq->num * sizeof *vq->used->ring + s));
657 /* Can we start vq? */
658 /* Caller should have vq mutex and device mutex */
659 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
661 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used) &&
662 vq_log_access_ok(vq, vq->log_base);
664 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
666 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
668 struct vhost_memory mem, *newmem, *oldmem;
669 unsigned long size = offsetof(struct vhost_memory, regions);
672 if (copy_from_user(&mem, m, size))
676 if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
678 newmem = kmalloc(size + mem.nregions * sizeof *m->regions, GFP_KERNEL);
682 memcpy(newmem, &mem, size);
683 if (copy_from_user(newmem->regions, m->regions,
684 mem.nregions * sizeof *m->regions)) {
689 if (!memory_access_ok(d, newmem, 0)) {
696 /* All memory accesses are done under some VQ mutex. */
697 for (i = 0; i < d->nvqs; ++i) {
698 mutex_lock(&d->vqs[i]->mutex);
699 d->vqs[i]->memory = newmem;
700 mutex_unlock(&d->vqs[i]->mutex);
706 long vhost_vring_ioctl(struct vhost_dev *d, int ioctl, void __user *argp)
708 struct file *eventfp, *filep = NULL;
709 bool pollstart = false, pollstop = false;
710 struct eventfd_ctx *ctx = NULL;
711 u32 __user *idxp = argp;
712 struct vhost_virtqueue *vq;
713 struct vhost_vring_state s;
714 struct vhost_vring_file f;
715 struct vhost_vring_addr a;
719 r = get_user(idx, idxp);
727 mutex_lock(&vq->mutex);
730 case VHOST_SET_VRING_NUM:
731 /* Resizing ring with an active backend?
732 * You don't want to do that. */
733 if (vq->private_data) {
737 if (copy_from_user(&s, argp, sizeof s)) {
741 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
747 case VHOST_SET_VRING_BASE:
748 /* Moving base with an active backend?
749 * You don't want to do that. */
750 if (vq->private_data) {
754 if (copy_from_user(&s, argp, sizeof s)) {
758 if (s.num > 0xffff) {
762 vq->last_avail_idx = s.num;
763 /* Forget the cached index value. */
764 vq->avail_idx = vq->last_avail_idx;
766 case VHOST_GET_VRING_BASE:
768 s.num = vq->last_avail_idx;
769 if (copy_to_user(argp, &s, sizeof s))
772 case VHOST_SET_VRING_ADDR:
773 if (copy_from_user(&a, argp, sizeof a)) {
777 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
781 /* For 32bit, verify that the top 32bits of the user
782 data are set to zero. */
783 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
784 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
785 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
790 /* Make sure it's safe to cast pointers to vring types. */
791 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
792 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
793 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
794 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
795 (a.log_guest_addr & (sizeof(u64) - 1))) {
800 /* We only verify access here if backend is configured.
801 * If it is not, we don't as size might not have been setup.
802 * We will verify when backend is configured. */
803 if (vq->private_data) {
804 if (!vq_access_ok(vq, vq->num,
805 (void __user *)(unsigned long)a.desc_user_addr,
806 (void __user *)(unsigned long)a.avail_user_addr,
807 (void __user *)(unsigned long)a.used_user_addr)) {
812 /* Also validate log access for used ring if enabled. */
813 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
814 !log_access_ok(vq->log_base, a.log_guest_addr,
816 vq->num * sizeof *vq->used->ring)) {
822 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
823 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
824 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
825 vq->log_addr = a.log_guest_addr;
826 vq->used = (void __user *)(unsigned long)a.used_user_addr;
828 case VHOST_SET_VRING_KICK:
829 if (copy_from_user(&f, argp, sizeof f)) {
833 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
834 if (IS_ERR(eventfp)) {
835 r = PTR_ERR(eventfp);
838 if (eventfp != vq->kick) {
839 pollstop = (filep = vq->kick) != NULL;
840 pollstart = (vq->kick = eventfp) != NULL;
844 case VHOST_SET_VRING_CALL:
845 if (copy_from_user(&f, argp, sizeof f)) {
849 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
850 if (IS_ERR(eventfp)) {
851 r = PTR_ERR(eventfp);
854 if (eventfp != vq->call) {
858 vq->call_ctx = eventfp ?
859 eventfd_ctx_fileget(eventfp) : NULL;
863 case VHOST_SET_VRING_ERR:
864 if (copy_from_user(&f, argp, sizeof f)) {
868 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
869 if (IS_ERR(eventfp)) {
870 r = PTR_ERR(eventfp);
873 if (eventfp != vq->error) {
877 vq->error_ctx = eventfp ?
878 eventfd_ctx_fileget(eventfp) : NULL;
882 case VHOST_SET_VRING_ENDIAN:
883 r = vhost_set_vring_endian(vq, argp);
885 case VHOST_GET_VRING_ENDIAN:
886 r = vhost_get_vring_endian(vq, idx, argp);
892 if (pollstop && vq->handle_kick)
893 vhost_poll_stop(&vq->poll);
896 eventfd_ctx_put(ctx);
900 if (pollstart && vq->handle_kick)
901 r = vhost_poll_start(&vq->poll, vq->kick);
903 mutex_unlock(&vq->mutex);
905 if (pollstop && vq->handle_kick)
906 vhost_poll_flush(&vq->poll);
909 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
911 /* Caller must have device mutex */
912 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
914 struct file *eventfp, *filep = NULL;
915 struct eventfd_ctx *ctx = NULL;
920 /* If you are not the owner, you can become one */
921 if (ioctl == VHOST_SET_OWNER) {
922 r = vhost_dev_set_owner(d);
926 /* You must be the owner to do anything else */
927 r = vhost_dev_check_owner(d);
932 case VHOST_SET_MEM_TABLE:
933 r = vhost_set_memory(d, argp);
935 case VHOST_SET_LOG_BASE:
936 if (copy_from_user(&p, argp, sizeof p)) {
940 if ((u64)(unsigned long)p != p) {
944 for (i = 0; i < d->nvqs; ++i) {
945 struct vhost_virtqueue *vq;
946 void __user *base = (void __user *)(unsigned long)p;
948 mutex_lock(&vq->mutex);
949 /* If ring is inactive, will check when it's enabled. */
950 if (vq->private_data && !vq_log_access_ok(vq, base))
954 mutex_unlock(&vq->mutex);
957 case VHOST_SET_LOG_FD:
958 r = get_user(fd, (int __user *)argp);
961 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
962 if (IS_ERR(eventfp)) {
963 r = PTR_ERR(eventfp);
966 if (eventfp != d->log_file) {
969 d->log_ctx = eventfp ?
970 eventfd_ctx_fileget(eventfp) : NULL;
973 for (i = 0; i < d->nvqs; ++i) {
974 mutex_lock(&d->vqs[i]->mutex);
975 d->vqs[i]->log_ctx = d->log_ctx;
976 mutex_unlock(&d->vqs[i]->mutex);
979 eventfd_ctx_put(ctx);
990 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
992 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
993 __u64 addr, __u32 len)
995 struct vhost_memory_region *reg;
998 /* linear search is not brilliant, but we really have on the order of 6
999 * regions in practice */
1000 for (i = 0; i < mem->nregions; ++i) {
1001 reg = mem->regions + i;
1002 if (reg->guest_phys_addr <= addr &&
1003 reg->guest_phys_addr + reg->memory_size - 1 >= addr)
1009 /* TODO: This is really inefficient. We need something like get_user()
1010 * (instruction directly accesses the data, with an exception table entry
1011 * returning -EFAULT). See Documentation/x86/exception-tables.txt.
1013 static int set_bit_to_user(int nr, void __user *addr)
1015 unsigned long log = (unsigned long)addr;
1018 int bit = nr + (log % PAGE_SIZE) * 8;
1021 r = get_user_pages_fast(log, 1, 1, &page);
1025 base = kmap_atomic(page);
1027 kunmap_atomic(base);
1028 set_page_dirty_lock(page);
1033 static int log_write(void __user *log_base,
1034 u64 write_address, u64 write_length)
1036 u64 write_page = write_address / VHOST_PAGE_SIZE;
1041 write_length += write_address % VHOST_PAGE_SIZE;
1043 u64 base = (u64)(unsigned long)log_base;
1044 u64 log = base + write_page / 8;
1045 int bit = write_page % 8;
1046 if ((u64)(unsigned long)log != log)
1048 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1051 if (write_length <= VHOST_PAGE_SIZE)
1053 write_length -= VHOST_PAGE_SIZE;
1059 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1060 unsigned int log_num, u64 len)
1064 /* Make sure data written is seen before log. */
1066 for (i = 0; i < log_num; ++i) {
1067 u64 l = min(log[i].len, len);
1068 r = log_write(vq->log_base, log[i].addr, l);
1074 eventfd_signal(vq->log_ctx, 1);
1078 /* Length written exceeds what we have stored. This is a bug. */
1082 EXPORT_SYMBOL_GPL(vhost_log_write);
1084 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1087 if (__put_user(cpu_to_vhost16(vq, vq->used_flags), &vq->used->flags) < 0)
1089 if (unlikely(vq->log_used)) {
1090 /* Make sure the flag is seen before log. */
1092 /* Log used flag write. */
1093 used = &vq->used->flags;
1094 log_write(vq->log_base, vq->log_addr +
1095 (used - (void __user *)vq->used),
1096 sizeof vq->used->flags);
1098 eventfd_signal(vq->log_ctx, 1);
1103 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1105 if (__put_user(cpu_to_vhost16(vq, vq->avail_idx), vhost_avail_event(vq)))
1107 if (unlikely(vq->log_used)) {
1109 /* Make sure the event is seen before log. */
1111 /* Log avail event write */
1112 used = vhost_avail_event(vq);
1113 log_write(vq->log_base, vq->log_addr +
1114 (used - (void __user *)vq->used),
1115 sizeof *vhost_avail_event(vq));
1117 eventfd_signal(vq->log_ctx, 1);
1122 int vhost_init_used(struct vhost_virtqueue *vq)
1124 __virtio16 last_used_idx;
1126 if (!vq->private_data) {
1127 vq->is_le = virtio_legacy_is_little_endian();
1131 vhost_init_is_le(vq);
1133 r = vhost_update_used_flags(vq);
1136 vq->signalled_used_valid = false;
1137 if (!access_ok(VERIFY_READ, &vq->used->idx, sizeof vq->used->idx))
1139 r = __get_user(last_used_idx, &vq->used->idx);
1142 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1145 EXPORT_SYMBOL_GPL(vhost_init_used);
1147 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1148 struct iovec iov[], int iov_size)
1150 const struct vhost_memory_region *reg;
1151 struct vhost_memory *mem;
1157 while ((u64)len > s) {
1159 if (unlikely(ret >= iov_size)) {
1163 reg = find_region(mem, addr, len);
1164 if (unlikely(!reg)) {
1169 size = reg->memory_size - addr + reg->guest_phys_addr;
1170 _iov->iov_len = min((u64)len - s, size);
1171 _iov->iov_base = (void __user *)(unsigned long)
1172 (reg->userspace_addr + addr - reg->guest_phys_addr);
1181 /* Each buffer in the virtqueues is actually a chain of descriptors. This
1182 * function returns the next descriptor in the chain,
1183 * or -1U if we're at the end. */
1184 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1188 /* If this descriptor says it doesn't chain, we're done. */
1189 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1192 /* Check they're not leading us off end of descriptors. */
1193 next = vhost16_to_cpu(vq, desc->next);
1194 /* Make sure compiler knows to grab that: we don't want it changing! */
1195 /* We will use the result as an index in an array, so most
1196 * architectures only need a compiler barrier here. */
1197 read_barrier_depends();
1202 static int get_indirect(struct vhost_virtqueue *vq,
1203 struct iovec iov[], unsigned int iov_size,
1204 unsigned int *out_num, unsigned int *in_num,
1205 struct vhost_log *log, unsigned int *log_num,
1206 struct vring_desc *indirect)
1208 struct vring_desc desc;
1209 unsigned int i = 0, count, found = 0;
1210 u32 len = vhost32_to_cpu(vq, indirect->len);
1211 struct iov_iter from;
1215 if (unlikely(len % sizeof desc)) {
1216 vq_err(vq, "Invalid length in indirect descriptor: "
1217 "len 0x%llx not multiple of 0x%zx\n",
1218 (unsigned long long)len,
1223 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
1225 if (unlikely(ret < 0)) {
1226 vq_err(vq, "Translation failure %d in indirect.\n", ret);
1229 iov_iter_init(&from, READ, vq->indirect, ret, len);
1231 /* We will use the result as an address to read from, so most
1232 * architectures only need a compiler barrier here. */
1233 read_barrier_depends();
1235 count = len / sizeof desc;
1236 /* Buffers are chained via a 16 bit next field, so
1237 * we can have at most 2^16 of these. */
1238 if (unlikely(count > USHRT_MAX + 1)) {
1239 vq_err(vq, "Indirect buffer length too big: %d\n",
1245 unsigned iov_count = *in_num + *out_num;
1246 if (unlikely(++found > count)) {
1247 vq_err(vq, "Loop detected: last one at %u "
1248 "indirect size %u\n",
1252 if (unlikely(copy_from_iter(&desc, sizeof(desc), &from) !=
1254 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1255 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1258 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
1259 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1260 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1264 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1265 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1266 iov_size - iov_count);
1267 if (unlikely(ret < 0)) {
1268 vq_err(vq, "Translation failure %d indirect idx %d\n",
1272 /* If this is an input descriptor, increment that count. */
1273 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1275 if (unlikely(log)) {
1276 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1277 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1281 /* If it's an output descriptor, they're all supposed
1282 * to come before any input descriptors. */
1283 if (unlikely(*in_num)) {
1284 vq_err(vq, "Indirect descriptor "
1285 "has out after in: idx %d\n", i);
1290 } while ((i = next_desc(vq, &desc)) != -1);
1294 /* This looks in the virtqueue and for the first available buffer, and converts
1295 * it to an iovec for convenient access. Since descriptors consist of some
1296 * number of output then some number of input descriptors, it's actually two
1297 * iovecs, but we pack them into one and note how many of each there were.
1299 * This function returns the descriptor number found, or vq->num (which is
1300 * never a valid descriptor number) if none was found. A negative code is
1301 * returned on error. */
1302 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
1303 struct iovec iov[], unsigned int iov_size,
1304 unsigned int *out_num, unsigned int *in_num,
1305 struct vhost_log *log, unsigned int *log_num)
1307 struct vring_desc desc;
1308 unsigned int i, head, found = 0;
1310 __virtio16 avail_idx;
1311 __virtio16 ring_head;
1314 /* Check it isn't doing very strange things with descriptor numbers. */
1315 last_avail_idx = vq->last_avail_idx;
1316 if (unlikely(__get_user(avail_idx, &vq->avail->idx))) {
1317 vq_err(vq, "Failed to access avail idx at %p\n",
1321 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
1323 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1324 vq_err(vq, "Guest moved used index from %u to %u",
1325 last_avail_idx, vq->avail_idx);
1329 /* If there's nothing new since last we looked, return invalid. */
1330 if (vq->avail_idx == last_avail_idx)
1333 /* Only get avail ring entries after they have been exposed by guest. */
1336 /* Grab the next descriptor number they're advertising, and increment
1337 * the index we've seen. */
1338 if (unlikely(__get_user(ring_head,
1339 &vq->avail->ring[last_avail_idx % vq->num]))) {
1340 vq_err(vq, "Failed to read head: idx %d address %p\n",
1342 &vq->avail->ring[last_avail_idx % vq->num]);
1346 head = vhost16_to_cpu(vq, ring_head);
1348 /* If their number is silly, that's an error. */
1349 if (unlikely(head >= vq->num)) {
1350 vq_err(vq, "Guest says index %u > %u is available",
1355 /* When we start there are none of either input nor output. */
1356 *out_num = *in_num = 0;
1362 unsigned iov_count = *in_num + *out_num;
1363 if (unlikely(i >= vq->num)) {
1364 vq_err(vq, "Desc index is %u > %u, head = %u",
1368 if (unlikely(++found > vq->num)) {
1369 vq_err(vq, "Loop detected: last one at %u "
1370 "vq size %u head %u\n",
1374 ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
1375 if (unlikely(ret)) {
1376 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1380 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
1381 ret = get_indirect(vq, iov, iov_size,
1383 log, log_num, &desc);
1384 if (unlikely(ret < 0)) {
1385 vq_err(vq, "Failure detected "
1386 "in indirect descriptor at idx %d\n", i);
1392 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1393 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1394 iov_size - iov_count);
1395 if (unlikely(ret < 0)) {
1396 vq_err(vq, "Translation failure %d descriptor idx %d\n",
1400 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1401 /* If this is an input descriptor,
1402 * increment that count. */
1404 if (unlikely(log)) {
1405 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1406 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1410 /* If it's an output descriptor, they're all supposed
1411 * to come before any input descriptors. */
1412 if (unlikely(*in_num)) {
1413 vq_err(vq, "Descriptor has out after in: "
1419 } while ((i = next_desc(vq, &desc)) != -1);
1421 /* On success, increment avail index. */
1422 vq->last_avail_idx++;
1424 /* Assume notifications from guest are disabled at this point,
1425 * if they aren't we would need to update avail_event index. */
1426 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
1429 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
1431 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1432 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1434 vq->last_avail_idx -= n;
1436 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
1438 /* After we've used one of their buffers, we tell them about it. We'll then
1439 * want to notify the guest, using eventfd. */
1440 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1442 struct vring_used_elem heads = {
1443 cpu_to_vhost32(vq, head),
1444 cpu_to_vhost32(vq, len)
1447 return vhost_add_used_n(vq, &heads, 1);
1449 EXPORT_SYMBOL_GPL(vhost_add_used);
1451 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1452 struct vring_used_elem *heads,
1455 struct vring_used_elem __user *used;
1459 start = vq->last_used_idx % vq->num;
1460 used = vq->used->ring + start;
1462 if (__put_user(heads[0].id, &used->id)) {
1463 vq_err(vq, "Failed to write used id");
1466 if (__put_user(heads[0].len, &used->len)) {
1467 vq_err(vq, "Failed to write used len");
1470 } else if (__copy_to_user(used, heads, count * sizeof *used)) {
1471 vq_err(vq, "Failed to write used");
1474 if (unlikely(vq->log_used)) {
1475 /* Make sure data is seen before log. */
1477 /* Log used ring entry write. */
1478 log_write(vq->log_base,
1480 ((void __user *)used - (void __user *)vq->used),
1481 count * sizeof *used);
1483 old = vq->last_used_idx;
1484 new = (vq->last_used_idx += count);
1485 /* If the driver never bothers to signal in a very long while,
1486 * used index might wrap around. If that happens, invalidate
1487 * signalled_used index we stored. TODO: make sure driver
1488 * signals at least once in 2^16 and remove this. */
1489 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
1490 vq->signalled_used_valid = false;
1494 /* After we've used one of their buffers, we tell them about it. We'll then
1495 * want to notify the guest, using eventfd. */
1496 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1501 start = vq->last_used_idx % vq->num;
1502 n = vq->num - start;
1504 r = __vhost_add_used_n(vq, heads, n);
1510 r = __vhost_add_used_n(vq, heads, count);
1512 /* Make sure buffer is written before we update index. */
1514 if (__put_user(cpu_to_vhost16(vq, vq->last_used_idx), &vq->used->idx)) {
1515 vq_err(vq, "Failed to increment used idx");
1518 if (unlikely(vq->log_used)) {
1519 /* Log used index update. */
1520 log_write(vq->log_base,
1521 vq->log_addr + offsetof(struct vring_used, idx),
1522 sizeof vq->used->idx);
1524 eventfd_signal(vq->log_ctx, 1);
1528 EXPORT_SYMBOL_GPL(vhost_add_used_n);
1530 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1535 /* Flush out used index updates. This is paired
1536 * with the barrier that the Guest executes when enabling
1540 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1541 unlikely(vq->avail_idx == vq->last_avail_idx))
1544 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1546 if (__get_user(flags, &vq->avail->flags)) {
1547 vq_err(vq, "Failed to get flags");
1550 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
1552 old = vq->signalled_used;
1553 v = vq->signalled_used_valid;
1554 new = vq->signalled_used = vq->last_used_idx;
1555 vq->signalled_used_valid = true;
1560 if (__get_user(event, vhost_used_event(vq))) {
1561 vq_err(vq, "Failed to get used event idx");
1564 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
1567 /* This actually signals the guest, using eventfd. */
1568 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1570 /* Signal the Guest tell them we used something up. */
1571 if (vq->call_ctx && vhost_notify(dev, vq))
1572 eventfd_signal(vq->call_ctx, 1);
1574 EXPORT_SYMBOL_GPL(vhost_signal);
1576 /* And here's the combo meal deal. Supersize me! */
1577 void vhost_add_used_and_signal(struct vhost_dev *dev,
1578 struct vhost_virtqueue *vq,
1579 unsigned int head, int len)
1581 vhost_add_used(vq, head, len);
1582 vhost_signal(dev, vq);
1584 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
1586 /* multi-buffer version of vhost_add_used_and_signal */
1587 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1588 struct vhost_virtqueue *vq,
1589 struct vring_used_elem *heads, unsigned count)
1591 vhost_add_used_n(vq, heads, count);
1592 vhost_signal(dev, vq);
1594 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
1596 /* OK, now we need to know about added descriptors. */
1597 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1599 __virtio16 avail_idx;
1602 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1604 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1605 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1606 r = vhost_update_used_flags(vq);
1608 vq_err(vq, "Failed to enable notification at %p: %d\n",
1609 &vq->used->flags, r);
1613 r = vhost_update_avail_event(vq, vq->avail_idx);
1615 vq_err(vq, "Failed to update avail event index at %p: %d\n",
1616 vhost_avail_event(vq), r);
1620 /* They could have slipped one in as we were doing that: make
1621 * sure it's written, then check again. */
1623 r = __get_user(avail_idx, &vq->avail->idx);
1625 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1626 &vq->avail->idx, r);
1630 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
1632 EXPORT_SYMBOL_GPL(vhost_enable_notify);
1634 /* We don't need to be notified again. */
1635 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1639 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1641 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1642 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1643 r = vhost_update_used_flags(vq);
1645 vq_err(vq, "Failed to enable notification at %p: %d\n",
1646 &vq->used->flags, r);
1649 EXPORT_SYMBOL_GPL(vhost_disable_notify);
1651 static int __init vhost_init(void)
1656 static void __exit vhost_exit(void)
1660 module_init(vhost_init);
1661 module_exit(vhost_exit);
1663 MODULE_VERSION("0.0.1");
1664 MODULE_LICENSE("GPL v2");
1665 MODULE_AUTHOR("Michael S. Tsirkin");
1666 MODULE_DESCRIPTION("Host kernel accelerator for virtio");