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>
28 #include <linux/sort.h>
33 VHOST_MEMORY_MAX_NREGIONS = 64,
34 VHOST_MEMORY_F_LOG = 0x1,
37 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
38 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
40 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
41 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
43 vq->user_be = !virtio_legacy_is_little_endian();
46 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
48 struct vhost_vring_state s;
53 if (copy_from_user(&s, argp, sizeof(s)))
56 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
57 s.num != VHOST_VRING_BIG_ENDIAN)
65 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
68 struct vhost_vring_state s = {
73 if (copy_to_user(argp, &s, sizeof(s)))
79 static void vhost_init_is_le(struct vhost_virtqueue *vq)
81 /* Note for legacy virtio: user_be is initialized at reset time
82 * according to the host endianness. If userspace does not set an
83 * explicit endianness, the default behavior is native endian, as
84 * expected by legacy virtio.
86 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
89 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
93 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
98 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
104 static void vhost_init_is_le(struct vhost_virtqueue *vq)
106 if (vhost_has_feature(vq, VIRTIO_F_VERSION_1))
109 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
111 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
114 struct vhost_poll *poll;
116 poll = container_of(pt, struct vhost_poll, table);
118 add_wait_queue(wqh, &poll->wait);
121 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
124 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
126 if (!((unsigned long)key & poll->mask))
129 vhost_poll_queue(poll);
133 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
135 INIT_LIST_HEAD(&work->node);
137 init_waitqueue_head(&work->done);
139 work->queue_seq = work->done_seq = 0;
141 EXPORT_SYMBOL_GPL(vhost_work_init);
143 /* Init poll structure */
144 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
145 unsigned long mask, struct vhost_dev *dev)
147 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
148 init_poll_funcptr(&poll->table, vhost_poll_func);
153 vhost_work_init(&poll->work, fn);
155 EXPORT_SYMBOL_GPL(vhost_poll_init);
157 /* Start polling a file. We add ourselves to file's wait queue. The caller must
158 * keep a reference to a file until after vhost_poll_stop is called. */
159 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
167 mask = file->f_op->poll(file, &poll->table);
169 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
170 if (mask & POLLERR) {
172 remove_wait_queue(poll->wqh, &poll->wait);
178 EXPORT_SYMBOL_GPL(vhost_poll_start);
180 /* Stop polling a file. After this function returns, it becomes safe to drop the
181 * file reference. You must also flush afterwards. */
182 void vhost_poll_stop(struct vhost_poll *poll)
185 remove_wait_queue(poll->wqh, &poll->wait);
189 EXPORT_SYMBOL_GPL(vhost_poll_stop);
191 static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
196 spin_lock_irq(&dev->work_lock);
197 left = seq - work->done_seq;
198 spin_unlock_irq(&dev->work_lock);
202 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
207 spin_lock_irq(&dev->work_lock);
208 seq = work->queue_seq;
210 spin_unlock_irq(&dev->work_lock);
211 wait_event(work->done, vhost_work_seq_done(dev, work, seq));
212 spin_lock_irq(&dev->work_lock);
213 flushing = --work->flushing;
214 spin_unlock_irq(&dev->work_lock);
215 BUG_ON(flushing < 0);
217 EXPORT_SYMBOL_GPL(vhost_work_flush);
219 /* Flush any work that has been scheduled. When calling this, don't hold any
220 * locks that are also used by the callback. */
221 void vhost_poll_flush(struct vhost_poll *poll)
223 vhost_work_flush(poll->dev, &poll->work);
225 EXPORT_SYMBOL_GPL(vhost_poll_flush);
227 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
231 spin_lock_irqsave(&dev->work_lock, flags);
232 if (list_empty(&work->node)) {
233 list_add_tail(&work->node, &dev->work_list);
235 spin_unlock_irqrestore(&dev->work_lock, flags);
236 wake_up_process(dev->worker);
238 spin_unlock_irqrestore(&dev->work_lock, flags);
241 EXPORT_SYMBOL_GPL(vhost_work_queue);
243 void vhost_poll_queue(struct vhost_poll *poll)
245 vhost_work_queue(poll->dev, &poll->work);
247 EXPORT_SYMBOL_GPL(vhost_poll_queue);
249 static void vhost_vq_reset(struct vhost_dev *dev,
250 struct vhost_virtqueue *vq)
256 vq->last_avail_idx = 0;
258 vq->last_used_idx = 0;
259 vq->signalled_used = 0;
260 vq->signalled_used_valid = false;
262 vq->log_used = false;
263 vq->log_addr = -1ull;
264 vq->private_data = NULL;
265 vq->acked_features = 0;
267 vq->error_ctx = NULL;
274 vq->is_le = virtio_legacy_is_little_endian();
275 vhost_vq_reset_user_be(vq);
278 static int vhost_worker(void *data)
280 struct vhost_dev *dev = data;
281 struct vhost_work *work = NULL;
282 unsigned uninitialized_var(seq);
283 mm_segment_t oldfs = get_fs();
289 /* mb paired w/ kthread_stop */
290 set_current_state(TASK_INTERRUPTIBLE);
292 spin_lock_irq(&dev->work_lock);
294 work->done_seq = seq;
296 wake_up_all(&work->done);
299 if (kthread_should_stop()) {
300 spin_unlock_irq(&dev->work_lock);
301 __set_current_state(TASK_RUNNING);
304 if (!list_empty(&dev->work_list)) {
305 work = list_first_entry(&dev->work_list,
306 struct vhost_work, node);
307 list_del_init(&work->node);
308 seq = work->queue_seq;
311 spin_unlock_irq(&dev->work_lock);
314 __set_current_state(TASK_RUNNING);
327 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
337 /* Helper to allocate iovec buffers for all vqs. */
338 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
340 struct vhost_virtqueue *vq;
343 for (i = 0; i < dev->nvqs; ++i) {
345 vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
347 vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
348 vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
349 if (!vq->indirect || !vq->log || !vq->heads)
356 vhost_vq_free_iovecs(dev->vqs[i]);
360 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
364 for (i = 0; i < dev->nvqs; ++i)
365 vhost_vq_free_iovecs(dev->vqs[i]);
368 void vhost_dev_init(struct vhost_dev *dev,
369 struct vhost_virtqueue **vqs, int nvqs)
371 struct vhost_virtqueue *vq;
376 mutex_init(&dev->mutex);
378 dev->log_file = NULL;
381 spin_lock_init(&dev->work_lock);
382 INIT_LIST_HEAD(&dev->work_list);
385 for (i = 0; i < dev->nvqs; ++i) {
391 mutex_init(&vq->mutex);
392 vhost_vq_reset(dev, vq);
394 vhost_poll_init(&vq->poll, vq->handle_kick,
398 EXPORT_SYMBOL_GPL(vhost_dev_init);
400 /* Caller should have device mutex */
401 long vhost_dev_check_owner(struct vhost_dev *dev)
403 /* Are you the owner? If not, I don't think you mean to do that */
404 return dev->mm == current->mm ? 0 : -EPERM;
406 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
408 struct vhost_attach_cgroups_struct {
409 struct vhost_work work;
410 struct task_struct *owner;
414 static void vhost_attach_cgroups_work(struct vhost_work *work)
416 struct vhost_attach_cgroups_struct *s;
418 s = container_of(work, struct vhost_attach_cgroups_struct, work);
419 s->ret = cgroup_attach_task_all(s->owner, current);
422 static int vhost_attach_cgroups(struct vhost_dev *dev)
424 struct vhost_attach_cgroups_struct attach;
426 attach.owner = current;
427 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
428 vhost_work_queue(dev, &attach.work);
429 vhost_work_flush(dev, &attach.work);
433 /* Caller should have device mutex */
434 bool vhost_dev_has_owner(struct vhost_dev *dev)
438 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
440 /* Caller should have device mutex */
441 long vhost_dev_set_owner(struct vhost_dev *dev)
443 struct task_struct *worker;
446 /* Is there an owner already? */
447 if (vhost_dev_has_owner(dev)) {
452 /* No owner, become one */
453 dev->mm = get_task_mm(current);
454 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
455 if (IS_ERR(worker)) {
456 err = PTR_ERR(worker);
460 dev->worker = worker;
461 wake_up_process(worker); /* avoid contributing to loadavg */
463 err = vhost_attach_cgroups(dev);
467 err = vhost_dev_alloc_iovecs(dev);
473 kthread_stop(worker);
482 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
484 struct vhost_memory *vhost_dev_reset_owner_prepare(void)
486 return kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
488 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
490 /* Caller should have device mutex */
491 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_memory *memory)
495 vhost_dev_cleanup(dev, true);
497 /* Restore memory to default empty mapping. */
498 memory->nregions = 0;
499 dev->memory = memory;
500 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
501 * VQs aren't running.
503 for (i = 0; i < dev->nvqs; ++i)
504 dev->vqs[i]->memory = memory;
506 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
508 void vhost_dev_stop(struct vhost_dev *dev)
512 for (i = 0; i < dev->nvqs; ++i) {
513 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
514 vhost_poll_stop(&dev->vqs[i]->poll);
515 vhost_poll_flush(&dev->vqs[i]->poll);
519 EXPORT_SYMBOL_GPL(vhost_dev_stop);
521 /* Caller should have device mutex if and only if locked is set */
522 void vhost_dev_cleanup(struct vhost_dev *dev, bool locked)
526 for (i = 0; i < dev->nvqs; ++i) {
527 if (dev->vqs[i]->error_ctx)
528 eventfd_ctx_put(dev->vqs[i]->error_ctx);
529 if (dev->vqs[i]->error)
530 fput(dev->vqs[i]->error);
531 if (dev->vqs[i]->kick)
532 fput(dev->vqs[i]->kick);
533 if (dev->vqs[i]->call_ctx)
534 eventfd_ctx_put(dev->vqs[i]->call_ctx);
535 if (dev->vqs[i]->call)
536 fput(dev->vqs[i]->call);
537 vhost_vq_reset(dev, dev->vqs[i]);
539 vhost_dev_free_iovecs(dev);
541 eventfd_ctx_put(dev->log_ctx);
545 dev->log_file = NULL;
546 /* No one will access memory at this point */
549 WARN_ON(!list_empty(&dev->work_list));
551 kthread_stop(dev->worker);
558 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
560 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
562 u64 a = addr / VHOST_PAGE_SIZE / 8;
564 /* Make sure 64 bit math will not overflow. */
565 if (a > ULONG_MAX - (unsigned long)log_base ||
566 a + (unsigned long)log_base > ULONG_MAX)
569 return access_ok(VERIFY_WRITE, log_base + a,
570 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
573 /* Caller should have vq mutex and device mutex. */
574 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
582 for (i = 0; i < mem->nregions; ++i) {
583 struct vhost_memory_region *m = mem->regions + i;
584 unsigned long a = m->userspace_addr;
585 if (m->memory_size > ULONG_MAX)
587 else if (!access_ok(VERIFY_WRITE, (void __user *)a,
590 else if (log_all && !log_access_ok(log_base,
598 /* Can we switch to this memory table? */
599 /* Caller should have device mutex but not vq mutex */
600 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
605 for (i = 0; i < d->nvqs; ++i) {
609 mutex_lock(&d->vqs[i]->mutex);
610 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
611 /* If ring is inactive, will check when it's enabled. */
612 if (d->vqs[i]->private_data)
613 ok = vq_memory_access_ok(d->vqs[i]->log_base, mem, log);
616 mutex_unlock(&d->vqs[i]->mutex);
623 static int vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
624 struct vring_desc __user *desc,
625 struct vring_avail __user *avail,
626 struct vring_used __user *used)
628 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
629 return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
630 access_ok(VERIFY_READ, avail,
631 sizeof *avail + num * sizeof *avail->ring + s) &&
632 access_ok(VERIFY_WRITE, used,
633 sizeof *used + num * sizeof *used->ring + s);
636 /* Can we log writes? */
637 /* Caller should have device mutex but not vq mutex */
638 int vhost_log_access_ok(struct vhost_dev *dev)
640 return memory_access_ok(dev, dev->memory, 1);
642 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
644 /* Verify access for write logging. */
645 /* Caller should have vq mutex and device mutex */
646 static int vq_log_access_ok(struct vhost_virtqueue *vq,
647 void __user *log_base)
649 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
651 return vq_memory_access_ok(log_base, vq->memory,
652 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
653 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
655 vq->num * sizeof *vq->used->ring + s));
658 /* Can we start vq? */
659 /* Caller should have vq mutex and device mutex */
660 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
662 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used) &&
663 vq_log_access_ok(vq, vq->log_base);
665 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
667 static int vhost_memory_reg_sort_cmp(const void *p1, const void *p2)
669 const struct vhost_memory_region *r1 = p1, *r2 = p2;
670 if (r1->guest_phys_addr < r2->guest_phys_addr)
672 if (r1->guest_phys_addr > r2->guest_phys_addr)
677 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
679 struct vhost_memory mem, *newmem, *oldmem;
680 unsigned long size = offsetof(struct vhost_memory, regions);
683 if (copy_from_user(&mem, m, size))
687 if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
689 newmem = kmalloc(size + mem.nregions * sizeof *m->regions, GFP_KERNEL);
693 memcpy(newmem, &mem, size);
694 if (copy_from_user(newmem->regions, m->regions,
695 mem.nregions * sizeof *m->regions)) {
699 sort(newmem->regions, newmem->nregions, sizeof(*newmem->regions),
700 vhost_memory_reg_sort_cmp, NULL);
702 if (!memory_access_ok(d, newmem, 0)) {
709 /* All memory accesses are done under some VQ mutex. */
710 for (i = 0; i < d->nvqs; ++i) {
711 mutex_lock(&d->vqs[i]->mutex);
712 d->vqs[i]->memory = newmem;
713 mutex_unlock(&d->vqs[i]->mutex);
719 long vhost_vring_ioctl(struct vhost_dev *d, int ioctl, void __user *argp)
721 struct file *eventfp, *filep = NULL;
722 bool pollstart = false, pollstop = false;
723 struct eventfd_ctx *ctx = NULL;
724 u32 __user *idxp = argp;
725 struct vhost_virtqueue *vq;
726 struct vhost_vring_state s;
727 struct vhost_vring_file f;
728 struct vhost_vring_addr a;
732 r = get_user(idx, idxp);
740 mutex_lock(&vq->mutex);
743 case VHOST_SET_VRING_NUM:
744 /* Resizing ring with an active backend?
745 * You don't want to do that. */
746 if (vq->private_data) {
750 if (copy_from_user(&s, argp, sizeof s)) {
754 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
760 case VHOST_SET_VRING_BASE:
761 /* Moving base with an active backend?
762 * You don't want to do that. */
763 if (vq->private_data) {
767 if (copy_from_user(&s, argp, sizeof s)) {
771 if (s.num > 0xffff) {
775 vq->last_avail_idx = s.num;
776 /* Forget the cached index value. */
777 vq->avail_idx = vq->last_avail_idx;
779 case VHOST_GET_VRING_BASE:
781 s.num = vq->last_avail_idx;
782 if (copy_to_user(argp, &s, sizeof s))
785 case VHOST_SET_VRING_ADDR:
786 if (copy_from_user(&a, argp, sizeof a)) {
790 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
794 /* For 32bit, verify that the top 32bits of the user
795 data are set to zero. */
796 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
797 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
798 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
803 /* Make sure it's safe to cast pointers to vring types. */
804 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
805 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
806 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
807 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
808 (a.log_guest_addr & (sizeof(u64) - 1))) {
813 /* We only verify access here if backend is configured.
814 * If it is not, we don't as size might not have been setup.
815 * We will verify when backend is configured. */
816 if (vq->private_data) {
817 if (!vq_access_ok(vq, vq->num,
818 (void __user *)(unsigned long)a.desc_user_addr,
819 (void __user *)(unsigned long)a.avail_user_addr,
820 (void __user *)(unsigned long)a.used_user_addr)) {
825 /* Also validate log access for used ring if enabled. */
826 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
827 !log_access_ok(vq->log_base, a.log_guest_addr,
829 vq->num * sizeof *vq->used->ring)) {
835 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
836 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
837 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
838 vq->log_addr = a.log_guest_addr;
839 vq->used = (void __user *)(unsigned long)a.used_user_addr;
841 case VHOST_SET_VRING_KICK:
842 if (copy_from_user(&f, argp, sizeof f)) {
846 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
847 if (IS_ERR(eventfp)) {
848 r = PTR_ERR(eventfp);
851 if (eventfp != vq->kick) {
852 pollstop = (filep = vq->kick) != NULL;
853 pollstart = (vq->kick = eventfp) != NULL;
857 case VHOST_SET_VRING_CALL:
858 if (copy_from_user(&f, argp, sizeof f)) {
862 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
863 if (IS_ERR(eventfp)) {
864 r = PTR_ERR(eventfp);
867 if (eventfp != vq->call) {
871 vq->call_ctx = eventfp ?
872 eventfd_ctx_fileget(eventfp) : NULL;
876 case VHOST_SET_VRING_ERR:
877 if (copy_from_user(&f, argp, sizeof f)) {
881 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
882 if (IS_ERR(eventfp)) {
883 r = PTR_ERR(eventfp);
886 if (eventfp != vq->error) {
890 vq->error_ctx = eventfp ?
891 eventfd_ctx_fileget(eventfp) : NULL;
895 case VHOST_SET_VRING_ENDIAN:
896 r = vhost_set_vring_endian(vq, argp);
898 case VHOST_GET_VRING_ENDIAN:
899 r = vhost_get_vring_endian(vq, idx, argp);
905 if (pollstop && vq->handle_kick)
906 vhost_poll_stop(&vq->poll);
909 eventfd_ctx_put(ctx);
913 if (pollstart && vq->handle_kick)
914 r = vhost_poll_start(&vq->poll, vq->kick);
916 mutex_unlock(&vq->mutex);
918 if (pollstop && vq->handle_kick)
919 vhost_poll_flush(&vq->poll);
922 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
924 /* Caller must have device mutex */
925 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
927 struct file *eventfp, *filep = NULL;
928 struct eventfd_ctx *ctx = NULL;
933 /* If you are not the owner, you can become one */
934 if (ioctl == VHOST_SET_OWNER) {
935 r = vhost_dev_set_owner(d);
939 /* You must be the owner to do anything else */
940 r = vhost_dev_check_owner(d);
945 case VHOST_SET_MEM_TABLE:
946 r = vhost_set_memory(d, argp);
948 case VHOST_SET_LOG_BASE:
949 if (copy_from_user(&p, argp, sizeof p)) {
953 if ((u64)(unsigned long)p != p) {
957 for (i = 0; i < d->nvqs; ++i) {
958 struct vhost_virtqueue *vq;
959 void __user *base = (void __user *)(unsigned long)p;
961 mutex_lock(&vq->mutex);
962 /* If ring is inactive, will check when it's enabled. */
963 if (vq->private_data && !vq_log_access_ok(vq, base))
967 mutex_unlock(&vq->mutex);
970 case VHOST_SET_LOG_FD:
971 r = get_user(fd, (int __user *)argp);
974 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
975 if (IS_ERR(eventfp)) {
976 r = PTR_ERR(eventfp);
979 if (eventfp != d->log_file) {
982 d->log_ctx = eventfp ?
983 eventfd_ctx_fileget(eventfp) : NULL;
986 for (i = 0; i < d->nvqs; ++i) {
987 mutex_lock(&d->vqs[i]->mutex);
988 d->vqs[i]->log_ctx = d->log_ctx;
989 mutex_unlock(&d->vqs[i]->mutex);
992 eventfd_ctx_put(ctx);
1003 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1005 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
1006 __u64 addr, __u32 len)
1008 const struct vhost_memory_region *reg;
1009 int start = 0, end = mem->nregions;
1011 while (start < end) {
1012 int slot = start + (end - start) / 2;
1013 reg = mem->regions + slot;
1014 if (addr >= reg->guest_phys_addr)
1020 reg = mem->regions + start;
1021 if (addr >= reg->guest_phys_addr &&
1022 reg->guest_phys_addr + reg->memory_size > addr)
1027 /* TODO: This is really inefficient. We need something like get_user()
1028 * (instruction directly accesses the data, with an exception table entry
1029 * returning -EFAULT). See Documentation/x86/exception-tables.txt.
1031 static int set_bit_to_user(int nr, void __user *addr)
1033 unsigned long log = (unsigned long)addr;
1036 int bit = nr + (log % PAGE_SIZE) * 8;
1039 r = get_user_pages_fast(log, 1, 1, &page);
1043 base = kmap_atomic(page);
1045 kunmap_atomic(base);
1046 set_page_dirty_lock(page);
1051 static int log_write(void __user *log_base,
1052 u64 write_address, u64 write_length)
1054 u64 write_page = write_address / VHOST_PAGE_SIZE;
1059 write_length += write_address % VHOST_PAGE_SIZE;
1061 u64 base = (u64)(unsigned long)log_base;
1062 u64 log = base + write_page / 8;
1063 int bit = write_page % 8;
1064 if ((u64)(unsigned long)log != log)
1066 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1069 if (write_length <= VHOST_PAGE_SIZE)
1071 write_length -= VHOST_PAGE_SIZE;
1077 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1078 unsigned int log_num, u64 len)
1082 /* Make sure data written is seen before log. */
1084 for (i = 0; i < log_num; ++i) {
1085 u64 l = min(log[i].len, len);
1086 r = log_write(vq->log_base, log[i].addr, l);
1092 eventfd_signal(vq->log_ctx, 1);
1096 /* Length written exceeds what we have stored. This is a bug. */
1100 EXPORT_SYMBOL_GPL(vhost_log_write);
1102 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1105 if (__put_user(cpu_to_vhost16(vq, vq->used_flags), &vq->used->flags) < 0)
1107 if (unlikely(vq->log_used)) {
1108 /* Make sure the flag is seen before log. */
1110 /* Log used flag write. */
1111 used = &vq->used->flags;
1112 log_write(vq->log_base, vq->log_addr +
1113 (used - (void __user *)vq->used),
1114 sizeof vq->used->flags);
1116 eventfd_signal(vq->log_ctx, 1);
1121 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1123 if (__put_user(cpu_to_vhost16(vq, vq->avail_idx), vhost_avail_event(vq)))
1125 if (unlikely(vq->log_used)) {
1127 /* Make sure the event is seen before log. */
1129 /* Log avail event write */
1130 used = vhost_avail_event(vq);
1131 log_write(vq->log_base, vq->log_addr +
1132 (used - (void __user *)vq->used),
1133 sizeof *vhost_avail_event(vq));
1135 eventfd_signal(vq->log_ctx, 1);
1140 int vhost_init_used(struct vhost_virtqueue *vq)
1142 __virtio16 last_used_idx;
1144 if (!vq->private_data) {
1145 vq->is_le = virtio_legacy_is_little_endian();
1149 vhost_init_is_le(vq);
1151 r = vhost_update_used_flags(vq);
1154 vq->signalled_used_valid = false;
1155 if (!access_ok(VERIFY_READ, &vq->used->idx, sizeof vq->used->idx))
1157 r = __get_user(last_used_idx, &vq->used->idx);
1160 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1163 EXPORT_SYMBOL_GPL(vhost_init_used);
1165 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1166 struct iovec iov[], int iov_size)
1168 const struct vhost_memory_region *reg;
1169 struct vhost_memory *mem;
1175 while ((u64)len > s) {
1177 if (unlikely(ret >= iov_size)) {
1181 reg = find_region(mem, addr, len);
1182 if (unlikely(!reg)) {
1187 size = reg->memory_size - addr + reg->guest_phys_addr;
1188 _iov->iov_len = min((u64)len - s, size);
1189 _iov->iov_base = (void __user *)(unsigned long)
1190 (reg->userspace_addr + addr - reg->guest_phys_addr);
1199 /* Each buffer in the virtqueues is actually a chain of descriptors. This
1200 * function returns the next descriptor in the chain,
1201 * or -1U if we're at the end. */
1202 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1206 /* If this descriptor says it doesn't chain, we're done. */
1207 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1210 /* Check they're not leading us off end of descriptors. */
1211 next = vhost16_to_cpu(vq, desc->next);
1212 /* Make sure compiler knows to grab that: we don't want it changing! */
1213 /* We will use the result as an index in an array, so most
1214 * architectures only need a compiler barrier here. */
1215 read_barrier_depends();
1220 static int get_indirect(struct vhost_virtqueue *vq,
1221 struct iovec iov[], unsigned int iov_size,
1222 unsigned int *out_num, unsigned int *in_num,
1223 struct vhost_log *log, unsigned int *log_num,
1224 struct vring_desc *indirect)
1226 struct vring_desc desc;
1227 unsigned int i = 0, count, found = 0;
1228 u32 len = vhost32_to_cpu(vq, indirect->len);
1229 struct iov_iter from;
1233 if (unlikely(len % sizeof desc)) {
1234 vq_err(vq, "Invalid length in indirect descriptor: "
1235 "len 0x%llx not multiple of 0x%zx\n",
1236 (unsigned long long)len,
1241 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
1243 if (unlikely(ret < 0)) {
1244 vq_err(vq, "Translation failure %d in indirect.\n", ret);
1247 iov_iter_init(&from, READ, vq->indirect, ret, len);
1249 /* We will use the result as an address to read from, so most
1250 * architectures only need a compiler barrier here. */
1251 read_barrier_depends();
1253 count = len / sizeof desc;
1254 /* Buffers are chained via a 16 bit next field, so
1255 * we can have at most 2^16 of these. */
1256 if (unlikely(count > USHRT_MAX + 1)) {
1257 vq_err(vq, "Indirect buffer length too big: %d\n",
1263 unsigned iov_count = *in_num + *out_num;
1264 if (unlikely(++found > count)) {
1265 vq_err(vq, "Loop detected: last one at %u "
1266 "indirect size %u\n",
1270 if (unlikely(copy_from_iter(&desc, sizeof(desc), &from) !=
1272 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1273 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1276 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
1277 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1278 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1282 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1283 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1284 iov_size - iov_count);
1285 if (unlikely(ret < 0)) {
1286 vq_err(vq, "Translation failure %d indirect idx %d\n",
1290 /* If this is an input descriptor, increment that count. */
1291 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1293 if (unlikely(log)) {
1294 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1295 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1299 /* If it's an output descriptor, they're all supposed
1300 * to come before any input descriptors. */
1301 if (unlikely(*in_num)) {
1302 vq_err(vq, "Indirect descriptor "
1303 "has out after in: idx %d\n", i);
1308 } while ((i = next_desc(vq, &desc)) != -1);
1312 /* This looks in the virtqueue and for the first available buffer, and converts
1313 * it to an iovec for convenient access. Since descriptors consist of some
1314 * number of output then some number of input descriptors, it's actually two
1315 * iovecs, but we pack them into one and note how many of each there were.
1317 * This function returns the descriptor number found, or vq->num (which is
1318 * never a valid descriptor number) if none was found. A negative code is
1319 * returned on error. */
1320 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
1321 struct iovec iov[], unsigned int iov_size,
1322 unsigned int *out_num, unsigned int *in_num,
1323 struct vhost_log *log, unsigned int *log_num)
1325 struct vring_desc desc;
1326 unsigned int i, head, found = 0;
1328 __virtio16 avail_idx;
1329 __virtio16 ring_head;
1332 /* Check it isn't doing very strange things with descriptor numbers. */
1333 last_avail_idx = vq->last_avail_idx;
1334 if (unlikely(__get_user(avail_idx, &vq->avail->idx))) {
1335 vq_err(vq, "Failed to access avail idx at %p\n",
1339 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
1341 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1342 vq_err(vq, "Guest moved used index from %u to %u",
1343 last_avail_idx, vq->avail_idx);
1347 /* If there's nothing new since last we looked, return invalid. */
1348 if (vq->avail_idx == last_avail_idx)
1351 /* Only get avail ring entries after they have been exposed by guest. */
1354 /* Grab the next descriptor number they're advertising, and increment
1355 * the index we've seen. */
1356 if (unlikely(__get_user(ring_head,
1357 &vq->avail->ring[last_avail_idx % vq->num]))) {
1358 vq_err(vq, "Failed to read head: idx %d address %p\n",
1360 &vq->avail->ring[last_avail_idx % vq->num]);
1364 head = vhost16_to_cpu(vq, ring_head);
1366 /* If their number is silly, that's an error. */
1367 if (unlikely(head >= vq->num)) {
1368 vq_err(vq, "Guest says index %u > %u is available",
1373 /* When we start there are none of either input nor output. */
1374 *out_num = *in_num = 0;
1380 unsigned iov_count = *in_num + *out_num;
1381 if (unlikely(i >= vq->num)) {
1382 vq_err(vq, "Desc index is %u > %u, head = %u",
1386 if (unlikely(++found > vq->num)) {
1387 vq_err(vq, "Loop detected: last one at %u "
1388 "vq size %u head %u\n",
1392 ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
1393 if (unlikely(ret)) {
1394 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1398 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
1399 ret = get_indirect(vq, iov, iov_size,
1401 log, log_num, &desc);
1402 if (unlikely(ret < 0)) {
1403 vq_err(vq, "Failure detected "
1404 "in indirect descriptor at idx %d\n", i);
1410 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1411 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1412 iov_size - iov_count);
1413 if (unlikely(ret < 0)) {
1414 vq_err(vq, "Translation failure %d descriptor idx %d\n",
1418 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1419 /* If this is an input descriptor,
1420 * increment that count. */
1422 if (unlikely(log)) {
1423 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1424 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1428 /* If it's an output descriptor, they're all supposed
1429 * to come before any input descriptors. */
1430 if (unlikely(*in_num)) {
1431 vq_err(vq, "Descriptor has out after in: "
1437 } while ((i = next_desc(vq, &desc)) != -1);
1439 /* On success, increment avail index. */
1440 vq->last_avail_idx++;
1442 /* Assume notifications from guest are disabled at this point,
1443 * if they aren't we would need to update avail_event index. */
1444 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
1447 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
1449 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1450 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1452 vq->last_avail_idx -= n;
1454 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
1456 /* After we've used one of their buffers, we tell them about it. We'll then
1457 * want to notify the guest, using eventfd. */
1458 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1460 struct vring_used_elem heads = {
1461 cpu_to_vhost32(vq, head),
1462 cpu_to_vhost32(vq, len)
1465 return vhost_add_used_n(vq, &heads, 1);
1467 EXPORT_SYMBOL_GPL(vhost_add_used);
1469 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1470 struct vring_used_elem *heads,
1473 struct vring_used_elem __user *used;
1477 start = vq->last_used_idx % vq->num;
1478 used = vq->used->ring + start;
1480 if (__put_user(heads[0].id, &used->id)) {
1481 vq_err(vq, "Failed to write used id");
1484 if (__put_user(heads[0].len, &used->len)) {
1485 vq_err(vq, "Failed to write used len");
1488 } else if (__copy_to_user(used, heads, count * sizeof *used)) {
1489 vq_err(vq, "Failed to write used");
1492 if (unlikely(vq->log_used)) {
1493 /* Make sure data is seen before log. */
1495 /* Log used ring entry write. */
1496 log_write(vq->log_base,
1498 ((void __user *)used - (void __user *)vq->used),
1499 count * sizeof *used);
1501 old = vq->last_used_idx;
1502 new = (vq->last_used_idx += count);
1503 /* If the driver never bothers to signal in a very long while,
1504 * used index might wrap around. If that happens, invalidate
1505 * signalled_used index we stored. TODO: make sure driver
1506 * signals at least once in 2^16 and remove this. */
1507 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
1508 vq->signalled_used_valid = false;
1512 /* After we've used one of their buffers, we tell them about it. We'll then
1513 * want to notify the guest, using eventfd. */
1514 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1519 start = vq->last_used_idx % vq->num;
1520 n = vq->num - start;
1522 r = __vhost_add_used_n(vq, heads, n);
1528 r = __vhost_add_used_n(vq, heads, count);
1530 /* Make sure buffer is written before we update index. */
1532 if (__put_user(cpu_to_vhost16(vq, vq->last_used_idx), &vq->used->idx)) {
1533 vq_err(vq, "Failed to increment used idx");
1536 if (unlikely(vq->log_used)) {
1537 /* Log used index update. */
1538 log_write(vq->log_base,
1539 vq->log_addr + offsetof(struct vring_used, idx),
1540 sizeof vq->used->idx);
1542 eventfd_signal(vq->log_ctx, 1);
1546 EXPORT_SYMBOL_GPL(vhost_add_used_n);
1548 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1553 /* Flush out used index updates. This is paired
1554 * with the barrier that the Guest executes when enabling
1558 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1559 unlikely(vq->avail_idx == vq->last_avail_idx))
1562 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1564 if (__get_user(flags, &vq->avail->flags)) {
1565 vq_err(vq, "Failed to get flags");
1568 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
1570 old = vq->signalled_used;
1571 v = vq->signalled_used_valid;
1572 new = vq->signalled_used = vq->last_used_idx;
1573 vq->signalled_used_valid = true;
1578 if (__get_user(event, vhost_used_event(vq))) {
1579 vq_err(vq, "Failed to get used event idx");
1582 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
1585 /* This actually signals the guest, using eventfd. */
1586 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1588 /* Signal the Guest tell them we used something up. */
1589 if (vq->call_ctx && vhost_notify(dev, vq))
1590 eventfd_signal(vq->call_ctx, 1);
1592 EXPORT_SYMBOL_GPL(vhost_signal);
1594 /* And here's the combo meal deal. Supersize me! */
1595 void vhost_add_used_and_signal(struct vhost_dev *dev,
1596 struct vhost_virtqueue *vq,
1597 unsigned int head, int len)
1599 vhost_add_used(vq, head, len);
1600 vhost_signal(dev, vq);
1602 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
1604 /* multi-buffer version of vhost_add_used_and_signal */
1605 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1606 struct vhost_virtqueue *vq,
1607 struct vring_used_elem *heads, unsigned count)
1609 vhost_add_used_n(vq, heads, count);
1610 vhost_signal(dev, vq);
1612 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
1614 /* OK, now we need to know about added descriptors. */
1615 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1617 __virtio16 avail_idx;
1620 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1622 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1623 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1624 r = vhost_update_used_flags(vq);
1626 vq_err(vq, "Failed to enable notification at %p: %d\n",
1627 &vq->used->flags, r);
1631 r = vhost_update_avail_event(vq, vq->avail_idx);
1633 vq_err(vq, "Failed to update avail event index at %p: %d\n",
1634 vhost_avail_event(vq), r);
1638 /* They could have slipped one in as we were doing that: make
1639 * sure it's written, then check again. */
1641 r = __get_user(avail_idx, &vq->avail->idx);
1643 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1644 &vq->avail->idx, r);
1648 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
1650 EXPORT_SYMBOL_GPL(vhost_enable_notify);
1652 /* We don't need to be notified again. */
1653 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1657 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1659 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1660 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1661 r = vhost_update_used_flags(vq);
1663 vq_err(vq, "Failed to enable notification at %p: %d\n",
1664 &vq->used->flags, r);
1667 EXPORT_SYMBOL_GPL(vhost_disable_notify);
1669 static int __init vhost_init(void)
1674 static void __exit vhost_exit(void)
1678 module_init(vhost_init);
1679 module_exit(vhost_exit);
1681 MODULE_VERSION("0.0.1");
1682 MODULE_LICENSE("GPL v2");
1683 MODULE_AUTHOR("Michael S. Tsirkin");
1684 MODULE_DESCRIPTION("Host kernel accelerator for virtio");