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/vmalloc.h>
26 #include <linux/kthread.h>
27 #include <linux/cgroup.h>
28 #include <linux/module.h>
29 #include <linux/sort.h>
34 VHOST_MEMORY_MAX_NREGIONS = 64,
35 VHOST_MEMORY_F_LOG = 0x1,
38 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
39 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
41 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
42 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
44 vq->user_be = !virtio_legacy_is_little_endian();
47 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
49 struct vhost_vring_state s;
54 if (copy_from_user(&s, argp, sizeof(s)))
57 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
58 s.num != VHOST_VRING_BIG_ENDIAN)
66 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
69 struct vhost_vring_state s = {
74 if (copy_to_user(argp, &s, sizeof(s)))
80 static void vhost_init_is_le(struct vhost_virtqueue *vq)
82 /* Note for legacy virtio: user_be is initialized at reset time
83 * according to the host endianness. If userspace does not set an
84 * explicit endianness, the default behavior is native endian, as
85 * expected by legacy virtio.
87 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
90 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
94 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
99 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
105 static void vhost_init_is_le(struct vhost_virtqueue *vq)
107 if (vhost_has_feature(vq, VIRTIO_F_VERSION_1))
110 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
112 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
115 struct vhost_poll *poll;
117 poll = container_of(pt, struct vhost_poll, table);
119 add_wait_queue(wqh, &poll->wait);
122 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
125 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
127 if (!((unsigned long)key & poll->mask))
130 vhost_poll_queue(poll);
134 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
136 INIT_LIST_HEAD(&work->node);
138 init_waitqueue_head(&work->done);
140 work->queue_seq = work->done_seq = 0;
142 EXPORT_SYMBOL_GPL(vhost_work_init);
144 /* Init poll structure */
145 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
146 unsigned long mask, struct vhost_dev *dev)
148 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
149 init_poll_funcptr(&poll->table, vhost_poll_func);
154 vhost_work_init(&poll->work, fn);
156 EXPORT_SYMBOL_GPL(vhost_poll_init);
158 /* Start polling a file. We add ourselves to file's wait queue. The caller must
159 * keep a reference to a file until after vhost_poll_stop is called. */
160 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
168 mask = file->f_op->poll(file, &poll->table);
170 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
171 if (mask & POLLERR) {
173 remove_wait_queue(poll->wqh, &poll->wait);
179 EXPORT_SYMBOL_GPL(vhost_poll_start);
181 /* Stop polling a file. After this function returns, it becomes safe to drop the
182 * file reference. You must also flush afterwards. */
183 void vhost_poll_stop(struct vhost_poll *poll)
186 remove_wait_queue(poll->wqh, &poll->wait);
190 EXPORT_SYMBOL_GPL(vhost_poll_stop);
192 static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
197 spin_lock_irq(&dev->work_lock);
198 left = seq - work->done_seq;
199 spin_unlock_irq(&dev->work_lock);
203 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
208 spin_lock_irq(&dev->work_lock);
209 seq = work->queue_seq;
211 spin_unlock_irq(&dev->work_lock);
212 wait_event(work->done, vhost_work_seq_done(dev, work, seq));
213 spin_lock_irq(&dev->work_lock);
214 flushing = --work->flushing;
215 spin_unlock_irq(&dev->work_lock);
216 BUG_ON(flushing < 0);
218 EXPORT_SYMBOL_GPL(vhost_work_flush);
220 /* Flush any work that has been scheduled. When calling this, don't hold any
221 * locks that are also used by the callback. */
222 void vhost_poll_flush(struct vhost_poll *poll)
224 vhost_work_flush(poll->dev, &poll->work);
226 EXPORT_SYMBOL_GPL(vhost_poll_flush);
228 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
232 spin_lock_irqsave(&dev->work_lock, flags);
233 if (list_empty(&work->node)) {
234 list_add_tail(&work->node, &dev->work_list);
236 spin_unlock_irqrestore(&dev->work_lock, flags);
237 wake_up_process(dev->worker);
239 spin_unlock_irqrestore(&dev->work_lock, flags);
242 EXPORT_SYMBOL_GPL(vhost_work_queue);
244 void vhost_poll_queue(struct vhost_poll *poll)
246 vhost_work_queue(poll->dev, &poll->work);
248 EXPORT_SYMBOL_GPL(vhost_poll_queue);
250 static void vhost_vq_reset(struct vhost_dev *dev,
251 struct vhost_virtqueue *vq)
257 vq->last_avail_idx = 0;
259 vq->last_used_idx = 0;
260 vq->signalled_used = 0;
261 vq->signalled_used_valid = false;
263 vq->log_used = false;
264 vq->log_addr = -1ull;
265 vq->private_data = NULL;
266 vq->acked_features = 0;
268 vq->error_ctx = NULL;
275 vq->is_le = virtio_legacy_is_little_endian();
276 vhost_vq_reset_user_be(vq);
279 static int vhost_worker(void *data)
281 struct vhost_dev *dev = data;
282 struct vhost_work *work = NULL;
283 unsigned uninitialized_var(seq);
284 mm_segment_t oldfs = get_fs();
290 /* mb paired w/ kthread_stop */
291 set_current_state(TASK_INTERRUPTIBLE);
293 spin_lock_irq(&dev->work_lock);
295 work->done_seq = seq;
297 wake_up_all(&work->done);
300 if (kthread_should_stop()) {
301 spin_unlock_irq(&dev->work_lock);
302 __set_current_state(TASK_RUNNING);
305 if (!list_empty(&dev->work_list)) {
306 work = list_first_entry(&dev->work_list,
307 struct vhost_work, node);
308 list_del_init(&work->node);
309 seq = work->queue_seq;
312 spin_unlock_irq(&dev->work_lock);
315 __set_current_state(TASK_RUNNING);
328 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
338 /* Helper to allocate iovec buffers for all vqs. */
339 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
341 struct vhost_virtqueue *vq;
344 for (i = 0; i < dev->nvqs; ++i) {
346 vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
348 vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
349 vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
350 if (!vq->indirect || !vq->log || !vq->heads)
357 vhost_vq_free_iovecs(dev->vqs[i]);
361 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
365 for (i = 0; i < dev->nvqs; ++i)
366 vhost_vq_free_iovecs(dev->vqs[i]);
369 void vhost_dev_init(struct vhost_dev *dev,
370 struct vhost_virtqueue **vqs, int nvqs)
372 struct vhost_virtqueue *vq;
377 mutex_init(&dev->mutex);
379 dev->log_file = NULL;
382 spin_lock_init(&dev->work_lock);
383 INIT_LIST_HEAD(&dev->work_list);
386 for (i = 0; i < dev->nvqs; ++i) {
392 mutex_init(&vq->mutex);
393 vhost_vq_reset(dev, vq);
395 vhost_poll_init(&vq->poll, vq->handle_kick,
399 EXPORT_SYMBOL_GPL(vhost_dev_init);
401 /* Caller should have device mutex */
402 long vhost_dev_check_owner(struct vhost_dev *dev)
404 /* Are you the owner? If not, I don't think you mean to do that */
405 return dev->mm == current->mm ? 0 : -EPERM;
407 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
409 struct vhost_attach_cgroups_struct {
410 struct vhost_work work;
411 struct task_struct *owner;
415 static void vhost_attach_cgroups_work(struct vhost_work *work)
417 struct vhost_attach_cgroups_struct *s;
419 s = container_of(work, struct vhost_attach_cgroups_struct, work);
420 s->ret = cgroup_attach_task_all(s->owner, current);
423 static int vhost_attach_cgroups(struct vhost_dev *dev)
425 struct vhost_attach_cgroups_struct attach;
427 attach.owner = current;
428 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
429 vhost_work_queue(dev, &attach.work);
430 vhost_work_flush(dev, &attach.work);
434 /* Caller should have device mutex */
435 bool vhost_dev_has_owner(struct vhost_dev *dev)
439 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
441 /* Caller should have device mutex */
442 long vhost_dev_set_owner(struct vhost_dev *dev)
444 struct task_struct *worker;
447 /* Is there an owner already? */
448 if (vhost_dev_has_owner(dev)) {
453 /* No owner, become one */
454 dev->mm = get_task_mm(current);
455 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
456 if (IS_ERR(worker)) {
457 err = PTR_ERR(worker);
461 dev->worker = worker;
462 wake_up_process(worker); /* avoid contributing to loadavg */
464 err = vhost_attach_cgroups(dev);
468 err = vhost_dev_alloc_iovecs(dev);
474 kthread_stop(worker);
483 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
485 struct vhost_memory *vhost_dev_reset_owner_prepare(void)
487 return kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
489 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
491 /* Caller should have device mutex */
492 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_memory *memory)
496 vhost_dev_cleanup(dev, true);
498 /* Restore memory to default empty mapping. */
499 memory->nregions = 0;
500 dev->memory = memory;
501 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
502 * VQs aren't running.
504 for (i = 0; i < dev->nvqs; ++i)
505 dev->vqs[i]->memory = memory;
507 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
509 void vhost_dev_stop(struct vhost_dev *dev)
513 for (i = 0; i < dev->nvqs; ++i) {
514 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
515 vhost_poll_stop(&dev->vqs[i]->poll);
516 vhost_poll_flush(&dev->vqs[i]->poll);
520 EXPORT_SYMBOL_GPL(vhost_dev_stop);
522 /* Caller should have device mutex if and only if locked is set */
523 void vhost_dev_cleanup(struct vhost_dev *dev, bool locked)
527 for (i = 0; i < dev->nvqs; ++i) {
528 if (dev->vqs[i]->error_ctx)
529 eventfd_ctx_put(dev->vqs[i]->error_ctx);
530 if (dev->vqs[i]->error)
531 fput(dev->vqs[i]->error);
532 if (dev->vqs[i]->kick)
533 fput(dev->vqs[i]->kick);
534 if (dev->vqs[i]->call_ctx)
535 eventfd_ctx_put(dev->vqs[i]->call_ctx);
536 if (dev->vqs[i]->call)
537 fput(dev->vqs[i]->call);
538 vhost_vq_reset(dev, dev->vqs[i]);
540 vhost_dev_free_iovecs(dev);
542 eventfd_ctx_put(dev->log_ctx);
546 dev->log_file = NULL;
547 /* No one will access memory at this point */
550 WARN_ON(!list_empty(&dev->work_list));
552 kthread_stop(dev->worker);
559 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
561 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
563 u64 a = addr / VHOST_PAGE_SIZE / 8;
565 /* Make sure 64 bit math will not overflow. */
566 if (a > ULONG_MAX - (unsigned long)log_base ||
567 a + (unsigned long)log_base > ULONG_MAX)
570 return access_ok(VERIFY_WRITE, log_base + a,
571 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
574 /* Caller should have vq mutex and device mutex. */
575 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
583 for (i = 0; i < mem->nregions; ++i) {
584 struct vhost_memory_region *m = mem->regions + i;
585 unsigned long a = m->userspace_addr;
586 if (m->memory_size > ULONG_MAX)
588 else if (!access_ok(VERIFY_WRITE, (void __user *)a,
591 else if (log_all && !log_access_ok(log_base,
599 /* Can we switch to this memory table? */
600 /* Caller should have device mutex but not vq mutex */
601 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
606 for (i = 0; i < d->nvqs; ++i) {
610 mutex_lock(&d->vqs[i]->mutex);
611 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
612 /* If ring is inactive, will check when it's enabled. */
613 if (d->vqs[i]->private_data)
614 ok = vq_memory_access_ok(d->vqs[i]->log_base, mem, log);
617 mutex_unlock(&d->vqs[i]->mutex);
624 static int vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
625 struct vring_desc __user *desc,
626 struct vring_avail __user *avail,
627 struct vring_used __user *used)
629 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
630 return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
631 access_ok(VERIFY_READ, avail,
632 sizeof *avail + num * sizeof *avail->ring + s) &&
633 access_ok(VERIFY_WRITE, used,
634 sizeof *used + num * sizeof *used->ring + s);
637 /* Can we log writes? */
638 /* Caller should have device mutex but not vq mutex */
639 int vhost_log_access_ok(struct vhost_dev *dev)
641 return memory_access_ok(dev, dev->memory, 1);
643 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
645 /* Verify access for write logging. */
646 /* Caller should have vq mutex and device mutex */
647 static int vq_log_access_ok(struct vhost_virtqueue *vq,
648 void __user *log_base)
650 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
652 return vq_memory_access_ok(log_base, vq->memory,
653 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
654 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
656 vq->num * sizeof *vq->used->ring + s));
659 /* Can we start vq? */
660 /* Caller should have vq mutex and device mutex */
661 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
663 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used) &&
664 vq_log_access_ok(vq, vq->log_base);
666 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
668 static int vhost_memory_reg_sort_cmp(const void *p1, const void *p2)
670 const struct vhost_memory_region *r1 = p1, *r2 = p2;
671 if (r1->guest_phys_addr < r2->guest_phys_addr)
673 if (r1->guest_phys_addr > r2->guest_phys_addr)
678 static void *vhost_kvzalloc(unsigned long size)
680 void *n = kzalloc(size, GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
685 return ERR_PTR(-ENOMEM);
690 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
692 struct vhost_memory mem, *newmem, *oldmem;
693 unsigned long size = offsetof(struct vhost_memory, regions);
696 if (copy_from_user(&mem, m, size))
700 if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
702 newmem = vhost_kvzalloc(size + mem.nregions * sizeof(*m->regions));
706 memcpy(newmem, &mem, size);
707 if (copy_from_user(newmem->regions, m->regions,
708 mem.nregions * sizeof *m->regions)) {
712 sort(newmem->regions, newmem->nregions, sizeof(*newmem->regions),
713 vhost_memory_reg_sort_cmp, NULL);
715 if (!memory_access_ok(d, newmem, 0)) {
722 /* All memory accesses are done under some VQ mutex. */
723 for (i = 0; i < d->nvqs; ++i) {
724 mutex_lock(&d->vqs[i]->mutex);
725 d->vqs[i]->memory = newmem;
726 mutex_unlock(&d->vqs[i]->mutex);
732 long vhost_vring_ioctl(struct vhost_dev *d, int ioctl, void __user *argp)
734 struct file *eventfp, *filep = NULL;
735 bool pollstart = false, pollstop = false;
736 struct eventfd_ctx *ctx = NULL;
737 u32 __user *idxp = argp;
738 struct vhost_virtqueue *vq;
739 struct vhost_vring_state s;
740 struct vhost_vring_file f;
741 struct vhost_vring_addr a;
745 r = get_user(idx, idxp);
753 mutex_lock(&vq->mutex);
756 case VHOST_SET_VRING_NUM:
757 /* Resizing ring with an active backend?
758 * You don't want to do that. */
759 if (vq->private_data) {
763 if (copy_from_user(&s, argp, sizeof s)) {
767 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
773 case VHOST_SET_VRING_BASE:
774 /* Moving base with an active backend?
775 * You don't want to do that. */
776 if (vq->private_data) {
780 if (copy_from_user(&s, argp, sizeof s)) {
784 if (s.num > 0xffff) {
788 vq->last_avail_idx = s.num;
789 /* Forget the cached index value. */
790 vq->avail_idx = vq->last_avail_idx;
792 case VHOST_GET_VRING_BASE:
794 s.num = vq->last_avail_idx;
795 if (copy_to_user(argp, &s, sizeof s))
798 case VHOST_SET_VRING_ADDR:
799 if (copy_from_user(&a, argp, sizeof a)) {
803 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
807 /* For 32bit, verify that the top 32bits of the user
808 data are set to zero. */
809 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
810 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
811 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
816 /* Make sure it's safe to cast pointers to vring types. */
817 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
818 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
819 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
820 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
821 (a.log_guest_addr & (sizeof(u64) - 1))) {
826 /* We only verify access here if backend is configured.
827 * If it is not, we don't as size might not have been setup.
828 * We will verify when backend is configured. */
829 if (vq->private_data) {
830 if (!vq_access_ok(vq, vq->num,
831 (void __user *)(unsigned long)a.desc_user_addr,
832 (void __user *)(unsigned long)a.avail_user_addr,
833 (void __user *)(unsigned long)a.used_user_addr)) {
838 /* Also validate log access for used ring if enabled. */
839 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
840 !log_access_ok(vq->log_base, a.log_guest_addr,
842 vq->num * sizeof *vq->used->ring)) {
848 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
849 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
850 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
851 vq->log_addr = a.log_guest_addr;
852 vq->used = (void __user *)(unsigned long)a.used_user_addr;
854 case VHOST_SET_VRING_KICK:
855 if (copy_from_user(&f, argp, sizeof f)) {
859 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
860 if (IS_ERR(eventfp)) {
861 r = PTR_ERR(eventfp);
864 if (eventfp != vq->kick) {
865 pollstop = (filep = vq->kick) != NULL;
866 pollstart = (vq->kick = eventfp) != NULL;
870 case VHOST_SET_VRING_CALL:
871 if (copy_from_user(&f, argp, sizeof f)) {
875 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
876 if (IS_ERR(eventfp)) {
877 r = PTR_ERR(eventfp);
880 if (eventfp != vq->call) {
884 vq->call_ctx = eventfp ?
885 eventfd_ctx_fileget(eventfp) : NULL;
889 case VHOST_SET_VRING_ERR:
890 if (copy_from_user(&f, argp, sizeof f)) {
894 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
895 if (IS_ERR(eventfp)) {
896 r = PTR_ERR(eventfp);
899 if (eventfp != vq->error) {
903 vq->error_ctx = eventfp ?
904 eventfd_ctx_fileget(eventfp) : NULL;
908 case VHOST_SET_VRING_ENDIAN:
909 r = vhost_set_vring_endian(vq, argp);
911 case VHOST_GET_VRING_ENDIAN:
912 r = vhost_get_vring_endian(vq, idx, argp);
918 if (pollstop && vq->handle_kick)
919 vhost_poll_stop(&vq->poll);
922 eventfd_ctx_put(ctx);
926 if (pollstart && vq->handle_kick)
927 r = vhost_poll_start(&vq->poll, vq->kick);
929 mutex_unlock(&vq->mutex);
931 if (pollstop && vq->handle_kick)
932 vhost_poll_flush(&vq->poll);
935 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
937 /* Caller must have device mutex */
938 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
940 struct file *eventfp, *filep = NULL;
941 struct eventfd_ctx *ctx = NULL;
946 /* If you are not the owner, you can become one */
947 if (ioctl == VHOST_SET_OWNER) {
948 r = vhost_dev_set_owner(d);
952 /* You must be the owner to do anything else */
953 r = vhost_dev_check_owner(d);
958 case VHOST_SET_MEM_TABLE:
959 r = vhost_set_memory(d, argp);
961 case VHOST_SET_LOG_BASE:
962 if (copy_from_user(&p, argp, sizeof p)) {
966 if ((u64)(unsigned long)p != p) {
970 for (i = 0; i < d->nvqs; ++i) {
971 struct vhost_virtqueue *vq;
972 void __user *base = (void __user *)(unsigned long)p;
974 mutex_lock(&vq->mutex);
975 /* If ring is inactive, will check when it's enabled. */
976 if (vq->private_data && !vq_log_access_ok(vq, base))
980 mutex_unlock(&vq->mutex);
983 case VHOST_SET_LOG_FD:
984 r = get_user(fd, (int __user *)argp);
987 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
988 if (IS_ERR(eventfp)) {
989 r = PTR_ERR(eventfp);
992 if (eventfp != d->log_file) {
995 d->log_ctx = eventfp ?
996 eventfd_ctx_fileget(eventfp) : NULL;
999 for (i = 0; i < d->nvqs; ++i) {
1000 mutex_lock(&d->vqs[i]->mutex);
1001 d->vqs[i]->log_ctx = d->log_ctx;
1002 mutex_unlock(&d->vqs[i]->mutex);
1005 eventfd_ctx_put(ctx);
1016 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1018 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
1019 __u64 addr, __u32 len)
1021 const struct vhost_memory_region *reg;
1022 int start = 0, end = mem->nregions;
1024 while (start < end) {
1025 int slot = start + (end - start) / 2;
1026 reg = mem->regions + slot;
1027 if (addr >= reg->guest_phys_addr)
1033 reg = mem->regions + start;
1034 if (addr >= reg->guest_phys_addr &&
1035 reg->guest_phys_addr + reg->memory_size > addr)
1040 /* TODO: This is really inefficient. We need something like get_user()
1041 * (instruction directly accesses the data, with an exception table entry
1042 * returning -EFAULT). See Documentation/x86/exception-tables.txt.
1044 static int set_bit_to_user(int nr, void __user *addr)
1046 unsigned long log = (unsigned long)addr;
1049 int bit = nr + (log % PAGE_SIZE) * 8;
1052 r = get_user_pages_fast(log, 1, 1, &page);
1056 base = kmap_atomic(page);
1058 kunmap_atomic(base);
1059 set_page_dirty_lock(page);
1064 static int log_write(void __user *log_base,
1065 u64 write_address, u64 write_length)
1067 u64 write_page = write_address / VHOST_PAGE_SIZE;
1072 write_length += write_address % VHOST_PAGE_SIZE;
1074 u64 base = (u64)(unsigned long)log_base;
1075 u64 log = base + write_page / 8;
1076 int bit = write_page % 8;
1077 if ((u64)(unsigned long)log != log)
1079 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1082 if (write_length <= VHOST_PAGE_SIZE)
1084 write_length -= VHOST_PAGE_SIZE;
1090 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1091 unsigned int log_num, u64 len)
1095 /* Make sure data written is seen before log. */
1097 for (i = 0; i < log_num; ++i) {
1098 u64 l = min(log[i].len, len);
1099 r = log_write(vq->log_base, log[i].addr, l);
1105 eventfd_signal(vq->log_ctx, 1);
1109 /* Length written exceeds what we have stored. This is a bug. */
1113 EXPORT_SYMBOL_GPL(vhost_log_write);
1115 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1118 if (__put_user(cpu_to_vhost16(vq, vq->used_flags), &vq->used->flags) < 0)
1120 if (unlikely(vq->log_used)) {
1121 /* Make sure the flag is seen before log. */
1123 /* Log used flag write. */
1124 used = &vq->used->flags;
1125 log_write(vq->log_base, vq->log_addr +
1126 (used - (void __user *)vq->used),
1127 sizeof vq->used->flags);
1129 eventfd_signal(vq->log_ctx, 1);
1134 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1136 if (__put_user(cpu_to_vhost16(vq, vq->avail_idx), vhost_avail_event(vq)))
1138 if (unlikely(vq->log_used)) {
1140 /* Make sure the event is seen before log. */
1142 /* Log avail event write */
1143 used = vhost_avail_event(vq);
1144 log_write(vq->log_base, vq->log_addr +
1145 (used - (void __user *)vq->used),
1146 sizeof *vhost_avail_event(vq));
1148 eventfd_signal(vq->log_ctx, 1);
1153 int vhost_init_used(struct vhost_virtqueue *vq)
1155 __virtio16 last_used_idx;
1157 if (!vq->private_data) {
1158 vq->is_le = virtio_legacy_is_little_endian();
1162 vhost_init_is_le(vq);
1164 r = vhost_update_used_flags(vq);
1167 vq->signalled_used_valid = false;
1168 if (!access_ok(VERIFY_READ, &vq->used->idx, sizeof vq->used->idx))
1170 r = __get_user(last_used_idx, &vq->used->idx);
1173 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1176 EXPORT_SYMBOL_GPL(vhost_init_used);
1178 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1179 struct iovec iov[], int iov_size)
1181 const struct vhost_memory_region *reg;
1182 struct vhost_memory *mem;
1188 while ((u64)len > s) {
1190 if (unlikely(ret >= iov_size)) {
1194 reg = find_region(mem, addr, len);
1195 if (unlikely(!reg)) {
1200 size = reg->memory_size - addr + reg->guest_phys_addr;
1201 _iov->iov_len = min((u64)len - s, size);
1202 _iov->iov_base = (void __user *)(unsigned long)
1203 (reg->userspace_addr + addr - reg->guest_phys_addr);
1212 /* Each buffer in the virtqueues is actually a chain of descriptors. This
1213 * function returns the next descriptor in the chain,
1214 * or -1U if we're at the end. */
1215 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1219 /* If this descriptor says it doesn't chain, we're done. */
1220 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1223 /* Check they're not leading us off end of descriptors. */
1224 next = vhost16_to_cpu(vq, desc->next);
1225 /* Make sure compiler knows to grab that: we don't want it changing! */
1226 /* We will use the result as an index in an array, so most
1227 * architectures only need a compiler barrier here. */
1228 read_barrier_depends();
1233 static int get_indirect(struct vhost_virtqueue *vq,
1234 struct iovec iov[], unsigned int iov_size,
1235 unsigned int *out_num, unsigned int *in_num,
1236 struct vhost_log *log, unsigned int *log_num,
1237 struct vring_desc *indirect)
1239 struct vring_desc desc;
1240 unsigned int i = 0, count, found = 0;
1241 u32 len = vhost32_to_cpu(vq, indirect->len);
1242 struct iov_iter from;
1246 if (unlikely(len % sizeof desc)) {
1247 vq_err(vq, "Invalid length in indirect descriptor: "
1248 "len 0x%llx not multiple of 0x%zx\n",
1249 (unsigned long long)len,
1254 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
1256 if (unlikely(ret < 0)) {
1257 vq_err(vq, "Translation failure %d in indirect.\n", ret);
1260 iov_iter_init(&from, READ, vq->indirect, ret, len);
1262 /* We will use the result as an address to read from, so most
1263 * architectures only need a compiler barrier here. */
1264 read_barrier_depends();
1266 count = len / sizeof desc;
1267 /* Buffers are chained via a 16 bit next field, so
1268 * we can have at most 2^16 of these. */
1269 if (unlikely(count > USHRT_MAX + 1)) {
1270 vq_err(vq, "Indirect buffer length too big: %d\n",
1276 unsigned iov_count = *in_num + *out_num;
1277 if (unlikely(++found > count)) {
1278 vq_err(vq, "Loop detected: last one at %u "
1279 "indirect size %u\n",
1283 if (unlikely(copy_from_iter(&desc, sizeof(desc), &from) !=
1285 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1286 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1289 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
1290 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1291 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1295 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1296 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1297 iov_size - iov_count);
1298 if (unlikely(ret < 0)) {
1299 vq_err(vq, "Translation failure %d indirect idx %d\n",
1303 /* If this is an input descriptor, increment that count. */
1304 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1306 if (unlikely(log)) {
1307 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1308 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1312 /* If it's an output descriptor, they're all supposed
1313 * to come before any input descriptors. */
1314 if (unlikely(*in_num)) {
1315 vq_err(vq, "Indirect descriptor "
1316 "has out after in: idx %d\n", i);
1321 } while ((i = next_desc(vq, &desc)) != -1);
1325 /* This looks in the virtqueue and for the first available buffer, and converts
1326 * it to an iovec for convenient access. Since descriptors consist of some
1327 * number of output then some number of input descriptors, it's actually two
1328 * iovecs, but we pack them into one and note how many of each there were.
1330 * This function returns the descriptor number found, or vq->num (which is
1331 * never a valid descriptor number) if none was found. A negative code is
1332 * returned on error. */
1333 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
1334 struct iovec iov[], unsigned int iov_size,
1335 unsigned int *out_num, unsigned int *in_num,
1336 struct vhost_log *log, unsigned int *log_num)
1338 struct vring_desc desc;
1339 unsigned int i, head, found = 0;
1341 __virtio16 avail_idx;
1342 __virtio16 ring_head;
1345 /* Check it isn't doing very strange things with descriptor numbers. */
1346 last_avail_idx = vq->last_avail_idx;
1347 if (unlikely(__get_user(avail_idx, &vq->avail->idx))) {
1348 vq_err(vq, "Failed to access avail idx at %p\n",
1352 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
1354 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1355 vq_err(vq, "Guest moved used index from %u to %u",
1356 last_avail_idx, vq->avail_idx);
1360 /* If there's nothing new since last we looked, return invalid. */
1361 if (vq->avail_idx == last_avail_idx)
1364 /* Only get avail ring entries after they have been exposed by guest. */
1367 /* Grab the next descriptor number they're advertising, and increment
1368 * the index we've seen. */
1369 if (unlikely(__get_user(ring_head,
1370 &vq->avail->ring[last_avail_idx % vq->num]))) {
1371 vq_err(vq, "Failed to read head: idx %d address %p\n",
1373 &vq->avail->ring[last_avail_idx % vq->num]);
1377 head = vhost16_to_cpu(vq, ring_head);
1379 /* If their number is silly, that's an error. */
1380 if (unlikely(head >= vq->num)) {
1381 vq_err(vq, "Guest says index %u > %u is available",
1386 /* When we start there are none of either input nor output. */
1387 *out_num = *in_num = 0;
1393 unsigned iov_count = *in_num + *out_num;
1394 if (unlikely(i >= vq->num)) {
1395 vq_err(vq, "Desc index is %u > %u, head = %u",
1399 if (unlikely(++found > vq->num)) {
1400 vq_err(vq, "Loop detected: last one at %u "
1401 "vq size %u head %u\n",
1405 ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
1406 if (unlikely(ret)) {
1407 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1411 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
1412 ret = get_indirect(vq, iov, iov_size,
1414 log, log_num, &desc);
1415 if (unlikely(ret < 0)) {
1416 vq_err(vq, "Failure detected "
1417 "in indirect descriptor at idx %d\n", i);
1423 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1424 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1425 iov_size - iov_count);
1426 if (unlikely(ret < 0)) {
1427 vq_err(vq, "Translation failure %d descriptor idx %d\n",
1431 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1432 /* If this is an input descriptor,
1433 * increment that count. */
1435 if (unlikely(log)) {
1436 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1437 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1441 /* If it's an output descriptor, they're all supposed
1442 * to come before any input descriptors. */
1443 if (unlikely(*in_num)) {
1444 vq_err(vq, "Descriptor has out after in: "
1450 } while ((i = next_desc(vq, &desc)) != -1);
1452 /* On success, increment avail index. */
1453 vq->last_avail_idx++;
1455 /* Assume notifications from guest are disabled at this point,
1456 * if they aren't we would need to update avail_event index. */
1457 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
1460 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
1462 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1463 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1465 vq->last_avail_idx -= n;
1467 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
1469 /* After we've used one of their buffers, we tell them about it. We'll then
1470 * want to notify the guest, using eventfd. */
1471 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1473 struct vring_used_elem heads = {
1474 cpu_to_vhost32(vq, head),
1475 cpu_to_vhost32(vq, len)
1478 return vhost_add_used_n(vq, &heads, 1);
1480 EXPORT_SYMBOL_GPL(vhost_add_used);
1482 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1483 struct vring_used_elem *heads,
1486 struct vring_used_elem __user *used;
1490 start = vq->last_used_idx % vq->num;
1491 used = vq->used->ring + start;
1493 if (__put_user(heads[0].id, &used->id)) {
1494 vq_err(vq, "Failed to write used id");
1497 if (__put_user(heads[0].len, &used->len)) {
1498 vq_err(vq, "Failed to write used len");
1501 } else if (__copy_to_user(used, heads, count * sizeof *used)) {
1502 vq_err(vq, "Failed to write used");
1505 if (unlikely(vq->log_used)) {
1506 /* Make sure data is seen before log. */
1508 /* Log used ring entry write. */
1509 log_write(vq->log_base,
1511 ((void __user *)used - (void __user *)vq->used),
1512 count * sizeof *used);
1514 old = vq->last_used_idx;
1515 new = (vq->last_used_idx += count);
1516 /* If the driver never bothers to signal in a very long while,
1517 * used index might wrap around. If that happens, invalidate
1518 * signalled_used index we stored. TODO: make sure driver
1519 * signals at least once in 2^16 and remove this. */
1520 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
1521 vq->signalled_used_valid = false;
1525 /* After we've used one of their buffers, we tell them about it. We'll then
1526 * want to notify the guest, using eventfd. */
1527 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1532 start = vq->last_used_idx % vq->num;
1533 n = vq->num - start;
1535 r = __vhost_add_used_n(vq, heads, n);
1541 r = __vhost_add_used_n(vq, heads, count);
1543 /* Make sure buffer is written before we update index. */
1545 if (__put_user(cpu_to_vhost16(vq, vq->last_used_idx), &vq->used->idx)) {
1546 vq_err(vq, "Failed to increment used idx");
1549 if (unlikely(vq->log_used)) {
1550 /* Log used index update. */
1551 log_write(vq->log_base,
1552 vq->log_addr + offsetof(struct vring_used, idx),
1553 sizeof vq->used->idx);
1555 eventfd_signal(vq->log_ctx, 1);
1559 EXPORT_SYMBOL_GPL(vhost_add_used_n);
1561 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1566 /* Flush out used index updates. This is paired
1567 * with the barrier that the Guest executes when enabling
1571 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1572 unlikely(vq->avail_idx == vq->last_avail_idx))
1575 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1577 if (__get_user(flags, &vq->avail->flags)) {
1578 vq_err(vq, "Failed to get flags");
1581 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
1583 old = vq->signalled_used;
1584 v = vq->signalled_used_valid;
1585 new = vq->signalled_used = vq->last_used_idx;
1586 vq->signalled_used_valid = true;
1591 if (__get_user(event, vhost_used_event(vq))) {
1592 vq_err(vq, "Failed to get used event idx");
1595 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
1598 /* This actually signals the guest, using eventfd. */
1599 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1601 /* Signal the Guest tell them we used something up. */
1602 if (vq->call_ctx && vhost_notify(dev, vq))
1603 eventfd_signal(vq->call_ctx, 1);
1605 EXPORT_SYMBOL_GPL(vhost_signal);
1607 /* And here's the combo meal deal. Supersize me! */
1608 void vhost_add_used_and_signal(struct vhost_dev *dev,
1609 struct vhost_virtqueue *vq,
1610 unsigned int head, int len)
1612 vhost_add_used(vq, head, len);
1613 vhost_signal(dev, vq);
1615 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
1617 /* multi-buffer version of vhost_add_used_and_signal */
1618 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1619 struct vhost_virtqueue *vq,
1620 struct vring_used_elem *heads, unsigned count)
1622 vhost_add_used_n(vq, heads, count);
1623 vhost_signal(dev, vq);
1625 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
1627 /* OK, now we need to know about added descriptors. */
1628 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1630 __virtio16 avail_idx;
1633 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1635 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1636 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1637 r = vhost_update_used_flags(vq);
1639 vq_err(vq, "Failed to enable notification at %p: %d\n",
1640 &vq->used->flags, r);
1644 r = vhost_update_avail_event(vq, vq->avail_idx);
1646 vq_err(vq, "Failed to update avail event index at %p: %d\n",
1647 vhost_avail_event(vq), r);
1651 /* They could have slipped one in as we were doing that: make
1652 * sure it's written, then check again. */
1654 r = __get_user(avail_idx, &vq->avail->idx);
1656 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1657 &vq->avail->idx, r);
1661 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
1663 EXPORT_SYMBOL_GPL(vhost_enable_notify);
1665 /* We don't need to be notified again. */
1666 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1670 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1672 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1673 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1674 r = vhost_update_used_flags(vq);
1676 vq_err(vq, "Failed to enable notification at %p: %d\n",
1677 &vq->used->flags, r);
1680 EXPORT_SYMBOL_GPL(vhost_disable_notify);
1682 static int __init vhost_init(void)
1687 static void __exit vhost_exit(void)
1691 module_init(vhost_init);
1692 module_exit(vhost_exit);
1694 MODULE_VERSION("0.0.1");
1695 MODULE_LICENSE("GPL v2");
1696 MODULE_AUTHOR("Michael S. Tsirkin");
1697 MODULE_DESCRIPTION("Host kernel accelerator for virtio");