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/virtio_net.h>
18 #include <linux/mmu_context.h>
19 #include <linux/miscdevice.h>
20 #include <linux/mutex.h>
21 #include <linux/rcupdate.h>
22 #include <linux/poll.h>
23 #include <linux/file.h>
24 #include <linux/highmem.h>
25 #include <linux/slab.h>
26 #include <linux/kthread.h>
27 #include <linux/cgroup.h>
29 #include <linux/net.h>
30 #include <linux/if_packet.h>
31 #include <linux/if_arp.h>
36 VHOST_MEMORY_MAX_NREGIONS = 64,
37 VHOST_MEMORY_F_LOG = 0x1,
40 #define vhost_used_event(vq) ((u16 __user *)&vq->avail->ring[vq->num])
41 #define vhost_avail_event(vq) ((u16 __user *)&vq->used->ring[vq->num])
43 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
46 struct vhost_poll *poll;
48 poll = container_of(pt, struct vhost_poll, table);
50 add_wait_queue(wqh, &poll->wait);
53 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
56 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
58 if (!((unsigned long)key & poll->mask))
61 vhost_poll_queue(poll);
65 static void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
67 INIT_LIST_HEAD(&work->node);
69 init_waitqueue_head(&work->done);
71 work->queue_seq = work->done_seq = 0;
74 /* Init poll structure */
75 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
76 unsigned long mask, struct vhost_dev *dev)
78 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
79 init_poll_funcptr(&poll->table, vhost_poll_func);
83 vhost_work_init(&poll->work, fn);
86 /* Start polling a file. We add ourselves to file's wait queue. The caller must
87 * keep a reference to a file until after vhost_poll_stop is called. */
88 void vhost_poll_start(struct vhost_poll *poll, struct file *file)
92 mask = file->f_op->poll(file, &poll->table);
94 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
97 /* Stop polling a file. After this function returns, it becomes safe to drop the
98 * file reference. You must also flush afterwards. */
99 void vhost_poll_stop(struct vhost_poll *poll)
101 remove_wait_queue(poll->wqh, &poll->wait);
104 static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
109 spin_lock_irq(&dev->work_lock);
110 left = seq - work->done_seq;
111 spin_unlock_irq(&dev->work_lock);
115 static void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
120 spin_lock_irq(&dev->work_lock);
121 seq = work->queue_seq;
123 spin_unlock_irq(&dev->work_lock);
124 wait_event(work->done, vhost_work_seq_done(dev, work, seq));
125 spin_lock_irq(&dev->work_lock);
126 flushing = --work->flushing;
127 spin_unlock_irq(&dev->work_lock);
128 BUG_ON(flushing < 0);
131 /* Flush any work that has been scheduled. When calling this, don't hold any
132 * locks that are also used by the callback. */
133 void vhost_poll_flush(struct vhost_poll *poll)
135 vhost_work_flush(poll->dev, &poll->work);
138 static inline void vhost_work_queue(struct vhost_dev *dev,
139 struct vhost_work *work)
143 spin_lock_irqsave(&dev->work_lock, flags);
144 if (list_empty(&work->node)) {
145 list_add_tail(&work->node, &dev->work_list);
147 wake_up_process(dev->worker);
149 spin_unlock_irqrestore(&dev->work_lock, flags);
152 void vhost_poll_queue(struct vhost_poll *poll)
154 vhost_work_queue(poll->dev, &poll->work);
157 static void vhost_vq_reset(struct vhost_dev *dev,
158 struct vhost_virtqueue *vq)
164 vq->last_avail_idx = 0;
166 vq->last_used_idx = 0;
167 vq->signalled_used = 0;
168 vq->signalled_used_valid = false;
170 vq->log_used = false;
171 vq->log_addr = -1ull;
174 vq->private_data = NULL;
176 vq->error_ctx = NULL;
184 static int vhost_worker(void *data)
186 struct vhost_dev *dev = data;
187 struct vhost_work *work = NULL;
188 unsigned uninitialized_var(seq);
193 /* mb paired w/ kthread_stop */
194 set_current_state(TASK_INTERRUPTIBLE);
196 spin_lock_irq(&dev->work_lock);
198 work->done_seq = seq;
200 wake_up_all(&work->done);
203 if (kthread_should_stop()) {
204 spin_unlock_irq(&dev->work_lock);
205 __set_current_state(TASK_RUNNING);
208 if (!list_empty(&dev->work_list)) {
209 work = list_first_entry(&dev->work_list,
210 struct vhost_work, node);
211 list_del_init(&work->node);
212 seq = work->queue_seq;
215 spin_unlock_irq(&dev->work_lock);
218 __set_current_state(TASK_RUNNING);
228 /* Helper to allocate iovec buffers for all vqs. */
229 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
233 for (i = 0; i < dev->nvqs; ++i) {
234 dev->vqs[i].indirect = kmalloc(sizeof *dev->vqs[i].indirect *
235 UIO_MAXIOV, GFP_KERNEL);
236 dev->vqs[i].log = kmalloc(sizeof *dev->vqs[i].log * UIO_MAXIOV,
238 dev->vqs[i].heads = kmalloc(sizeof *dev->vqs[i].heads *
239 UIO_MAXIOV, GFP_KERNEL);
241 if (!dev->vqs[i].indirect || !dev->vqs[i].log ||
248 for (; i >= 0; --i) {
249 kfree(dev->vqs[i].indirect);
250 kfree(dev->vqs[i].log);
251 kfree(dev->vqs[i].heads);
256 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
260 for (i = 0; i < dev->nvqs; ++i) {
261 kfree(dev->vqs[i].indirect);
262 dev->vqs[i].indirect = NULL;
263 kfree(dev->vqs[i].log);
264 dev->vqs[i].log = NULL;
265 kfree(dev->vqs[i].heads);
266 dev->vqs[i].heads = NULL;
270 long vhost_dev_init(struct vhost_dev *dev,
271 struct vhost_virtqueue *vqs, int nvqs)
277 mutex_init(&dev->mutex);
279 dev->log_file = NULL;
282 spin_lock_init(&dev->work_lock);
283 INIT_LIST_HEAD(&dev->work_list);
286 for (i = 0; i < dev->nvqs; ++i) {
287 dev->vqs[i].log = NULL;
288 dev->vqs[i].indirect = NULL;
289 dev->vqs[i].heads = NULL;
290 dev->vqs[i].dev = dev;
291 mutex_init(&dev->vqs[i].mutex);
292 vhost_vq_reset(dev, dev->vqs + i);
293 if (dev->vqs[i].handle_kick)
294 vhost_poll_init(&dev->vqs[i].poll,
295 dev->vqs[i].handle_kick, POLLIN, dev);
301 /* Caller should have device mutex */
302 long vhost_dev_check_owner(struct vhost_dev *dev)
304 /* Are you the owner? If not, I don't think you mean to do that */
305 return dev->mm == current->mm ? 0 : -EPERM;
308 struct vhost_attach_cgroups_struct {
309 struct vhost_work work;
310 struct task_struct *owner;
314 static void vhost_attach_cgroups_work(struct vhost_work *work)
316 struct vhost_attach_cgroups_struct *s;
318 s = container_of(work, struct vhost_attach_cgroups_struct, work);
319 s->ret = cgroup_attach_task_all(s->owner, current);
322 static int vhost_attach_cgroups(struct vhost_dev *dev)
324 struct vhost_attach_cgroups_struct attach;
326 attach.owner = current;
327 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
328 vhost_work_queue(dev, &attach.work);
329 vhost_work_flush(dev, &attach.work);
333 /* Caller should have device mutex */
334 static long vhost_dev_set_owner(struct vhost_dev *dev)
336 struct task_struct *worker;
339 /* Is there an owner already? */
345 /* No owner, become one */
346 dev->mm = get_task_mm(current);
347 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
348 if (IS_ERR(worker)) {
349 err = PTR_ERR(worker);
353 dev->worker = worker;
354 wake_up_process(worker); /* avoid contributing to loadavg */
356 err = vhost_attach_cgroups(dev);
360 err = vhost_dev_alloc_iovecs(dev);
366 kthread_stop(worker);
376 /* Caller should have device mutex */
377 long vhost_dev_reset_owner(struct vhost_dev *dev)
379 struct vhost_memory *memory;
381 /* Restore memory to default empty mapping. */
382 memory = kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
386 vhost_dev_cleanup(dev);
388 memory->nregions = 0;
389 RCU_INIT_POINTER(dev->memory, memory);
393 /* Caller should have device mutex */
394 void vhost_dev_cleanup(struct vhost_dev *dev)
398 for (i = 0; i < dev->nvqs; ++i) {
399 if (dev->vqs[i].kick && dev->vqs[i].handle_kick) {
400 vhost_poll_stop(&dev->vqs[i].poll);
401 vhost_poll_flush(&dev->vqs[i].poll);
403 if (dev->vqs[i].error_ctx)
404 eventfd_ctx_put(dev->vqs[i].error_ctx);
405 if (dev->vqs[i].error)
406 fput(dev->vqs[i].error);
407 if (dev->vqs[i].kick)
408 fput(dev->vqs[i].kick);
409 if (dev->vqs[i].call_ctx)
410 eventfd_ctx_put(dev->vqs[i].call_ctx);
411 if (dev->vqs[i].call)
412 fput(dev->vqs[i].call);
413 vhost_vq_reset(dev, dev->vqs + i);
415 vhost_dev_free_iovecs(dev);
417 eventfd_ctx_put(dev->log_ctx);
421 dev->log_file = NULL;
422 /* No one will access memory at this point */
423 kfree(rcu_dereference_protected(dev->memory,
424 lockdep_is_held(&dev->mutex)));
425 RCU_INIT_POINTER(dev->memory, NULL);
426 WARN_ON(!list_empty(&dev->work_list));
428 kthread_stop(dev->worker);
436 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
438 u64 a = addr / VHOST_PAGE_SIZE / 8;
440 /* Make sure 64 bit math will not overflow. */
441 if (a > ULONG_MAX - (unsigned long)log_base ||
442 a + (unsigned long)log_base > ULONG_MAX)
445 return access_ok(VERIFY_WRITE, log_base + a,
446 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
449 /* Caller should have vq mutex and device mutex. */
450 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
458 for (i = 0; i < mem->nregions; ++i) {
459 struct vhost_memory_region *m = mem->regions + i;
460 unsigned long a = m->userspace_addr;
461 if (m->memory_size > ULONG_MAX)
463 else if (!access_ok(VERIFY_WRITE, (void __user *)a,
466 else if (log_all && !log_access_ok(log_base,
474 /* Can we switch to this memory table? */
475 /* Caller should have device mutex but not vq mutex */
476 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
481 for (i = 0; i < d->nvqs; ++i) {
483 mutex_lock(&d->vqs[i].mutex);
484 /* If ring is inactive, will check when it's enabled. */
485 if (d->vqs[i].private_data)
486 ok = vq_memory_access_ok(d->vqs[i].log_base, mem,
490 mutex_unlock(&d->vqs[i].mutex);
497 static int vq_access_ok(struct vhost_dev *d, unsigned int num,
498 struct vring_desc __user *desc,
499 struct vring_avail __user *avail,
500 struct vring_used __user *used)
502 size_t s = vhost_has_feature(d, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
503 return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
504 access_ok(VERIFY_READ, avail,
505 sizeof *avail + num * sizeof *avail->ring + s) &&
506 access_ok(VERIFY_WRITE, used,
507 sizeof *used + num * sizeof *used->ring + s);
510 /* Can we log writes? */
511 /* Caller should have device mutex but not vq mutex */
512 int vhost_log_access_ok(struct vhost_dev *dev)
514 struct vhost_memory *mp;
516 mp = rcu_dereference_protected(dev->memory,
517 lockdep_is_held(&dev->mutex));
518 return memory_access_ok(dev, mp, 1);
521 /* Verify access for write logging. */
522 /* Caller should have vq mutex and device mutex */
523 static int vq_log_access_ok(struct vhost_dev *d, struct vhost_virtqueue *vq,
524 void __user *log_base)
526 struct vhost_memory *mp;
527 size_t s = vhost_has_feature(d, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
529 mp = rcu_dereference_protected(vq->dev->memory,
530 lockdep_is_held(&vq->mutex));
531 return vq_memory_access_ok(log_base, mp,
532 vhost_has_feature(vq->dev, VHOST_F_LOG_ALL)) &&
533 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
535 vq->num * sizeof *vq->used->ring + s));
538 /* Can we start vq? */
539 /* Caller should have vq mutex and device mutex */
540 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
542 return vq_access_ok(vq->dev, vq->num, vq->desc, vq->avail, vq->used) &&
543 vq_log_access_ok(vq->dev, vq, vq->log_base);
546 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
548 struct vhost_memory mem, *newmem, *oldmem;
549 unsigned long size = offsetof(struct vhost_memory, regions);
551 if (copy_from_user(&mem, m, size))
555 if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
557 newmem = kmalloc(size + mem.nregions * sizeof *m->regions, GFP_KERNEL);
561 memcpy(newmem, &mem, size);
562 if (copy_from_user(newmem->regions, m->regions,
563 mem.nregions * sizeof *m->regions)) {
568 if (!memory_access_ok(d, newmem,
569 vhost_has_feature(d, VHOST_F_LOG_ALL))) {
573 oldmem = rcu_dereference_protected(d->memory,
574 lockdep_is_held(&d->mutex));
575 rcu_assign_pointer(d->memory, newmem);
581 static int init_used(struct vhost_virtqueue *vq,
582 struct vring_used __user *used)
584 int r = put_user(vq->used_flags, &used->flags);
588 vq->signalled_used_valid = false;
589 return get_user(vq->last_used_idx, &used->idx);
592 static long vhost_set_vring(struct vhost_dev *d, int ioctl, void __user *argp)
594 struct file *eventfp, *filep = NULL,
595 *pollstart = NULL, *pollstop = NULL;
596 struct eventfd_ctx *ctx = NULL;
597 u32 __user *idxp = argp;
598 struct vhost_virtqueue *vq;
599 struct vhost_vring_state s;
600 struct vhost_vring_file f;
601 struct vhost_vring_addr a;
605 r = get_user(idx, idxp);
613 mutex_lock(&vq->mutex);
616 case VHOST_SET_VRING_NUM:
617 /* Resizing ring with an active backend?
618 * You don't want to do that. */
619 if (vq->private_data) {
623 if (copy_from_user(&s, argp, sizeof s)) {
627 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
633 case VHOST_SET_VRING_BASE:
634 /* Moving base with an active backend?
635 * You don't want to do that. */
636 if (vq->private_data) {
640 if (copy_from_user(&s, argp, sizeof s)) {
644 if (s.num > 0xffff) {
648 vq->last_avail_idx = s.num;
649 /* Forget the cached index value. */
650 vq->avail_idx = vq->last_avail_idx;
652 case VHOST_GET_VRING_BASE:
654 s.num = vq->last_avail_idx;
655 if (copy_to_user(argp, &s, sizeof s))
658 case VHOST_SET_VRING_ADDR:
659 if (copy_from_user(&a, argp, sizeof a)) {
663 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
667 /* For 32bit, verify that the top 32bits of the user
668 data are set to zero. */
669 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
670 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
671 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
675 if ((a.avail_user_addr & (sizeof *vq->avail->ring - 1)) ||
676 (a.used_user_addr & (sizeof *vq->used->ring - 1)) ||
677 (a.log_guest_addr & (sizeof *vq->used->ring - 1))) {
682 /* We only verify access here if backend is configured.
683 * If it is not, we don't as size might not have been setup.
684 * We will verify when backend is configured. */
685 if (vq->private_data) {
686 if (!vq_access_ok(d, vq->num,
687 (void __user *)(unsigned long)a.desc_user_addr,
688 (void __user *)(unsigned long)a.avail_user_addr,
689 (void __user *)(unsigned long)a.used_user_addr)) {
694 /* Also validate log access for used ring if enabled. */
695 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
696 !log_access_ok(vq->log_base, a.log_guest_addr,
698 vq->num * sizeof *vq->used->ring)) {
704 r = init_used(vq, (struct vring_used __user *)(unsigned long)
708 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
709 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
710 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
711 vq->log_addr = a.log_guest_addr;
712 vq->used = (void __user *)(unsigned long)a.used_user_addr;
714 case VHOST_SET_VRING_KICK:
715 if (copy_from_user(&f, argp, sizeof f)) {
719 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
720 if (IS_ERR(eventfp)) {
721 r = PTR_ERR(eventfp);
724 if (eventfp != vq->kick) {
725 pollstop = filep = vq->kick;
726 pollstart = vq->kick = eventfp;
730 case VHOST_SET_VRING_CALL:
731 if (copy_from_user(&f, argp, sizeof f)) {
735 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
736 if (IS_ERR(eventfp)) {
737 r = PTR_ERR(eventfp);
740 if (eventfp != vq->call) {
744 vq->call_ctx = eventfp ?
745 eventfd_ctx_fileget(eventfp) : NULL;
749 case VHOST_SET_VRING_ERR:
750 if (copy_from_user(&f, argp, sizeof f)) {
754 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
755 if (IS_ERR(eventfp)) {
756 r = PTR_ERR(eventfp);
759 if (eventfp != vq->error) {
763 vq->error_ctx = eventfp ?
764 eventfd_ctx_fileget(eventfp) : NULL;
772 if (pollstop && vq->handle_kick)
773 vhost_poll_stop(&vq->poll);
776 eventfd_ctx_put(ctx);
780 if (pollstart && vq->handle_kick)
781 vhost_poll_start(&vq->poll, vq->kick);
783 mutex_unlock(&vq->mutex);
785 if (pollstop && vq->handle_kick)
786 vhost_poll_flush(&vq->poll);
790 /* Caller must have device mutex */
791 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, unsigned long arg)
793 void __user *argp = (void __user *)arg;
794 struct file *eventfp, *filep = NULL;
795 struct eventfd_ctx *ctx = NULL;
800 /* If you are not the owner, you can become one */
801 if (ioctl == VHOST_SET_OWNER) {
802 r = vhost_dev_set_owner(d);
806 /* You must be the owner to do anything else */
807 r = vhost_dev_check_owner(d);
812 case VHOST_SET_MEM_TABLE:
813 r = vhost_set_memory(d, argp);
815 case VHOST_SET_LOG_BASE:
816 if (copy_from_user(&p, argp, sizeof p)) {
820 if ((u64)(unsigned long)p != p) {
824 for (i = 0; i < d->nvqs; ++i) {
825 struct vhost_virtqueue *vq;
826 void __user *base = (void __user *)(unsigned long)p;
828 mutex_lock(&vq->mutex);
829 /* If ring is inactive, will check when it's enabled. */
830 if (vq->private_data && !vq_log_access_ok(d, vq, base))
834 mutex_unlock(&vq->mutex);
837 case VHOST_SET_LOG_FD:
838 r = get_user(fd, (int __user *)argp);
841 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
842 if (IS_ERR(eventfp)) {
843 r = PTR_ERR(eventfp);
846 if (eventfp != d->log_file) {
849 d->log_ctx = eventfp ?
850 eventfd_ctx_fileget(eventfp) : NULL;
853 for (i = 0; i < d->nvqs; ++i) {
854 mutex_lock(&d->vqs[i].mutex);
855 d->vqs[i].log_ctx = d->log_ctx;
856 mutex_unlock(&d->vqs[i].mutex);
859 eventfd_ctx_put(ctx);
864 r = vhost_set_vring(d, ioctl, argp);
871 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
872 __u64 addr, __u32 len)
874 struct vhost_memory_region *reg;
877 /* linear search is not brilliant, but we really have on the order of 6
878 * regions in practice */
879 for (i = 0; i < mem->nregions; ++i) {
880 reg = mem->regions + i;
881 if (reg->guest_phys_addr <= addr &&
882 reg->guest_phys_addr + reg->memory_size - 1 >= addr)
888 /* TODO: This is really inefficient. We need something like get_user()
889 * (instruction directly accesses the data, with an exception table entry
890 * returning -EFAULT). See Documentation/x86/exception-tables.txt.
892 static int set_bit_to_user(int nr, void __user *addr)
894 unsigned long log = (unsigned long)addr;
897 int bit = nr + (log % PAGE_SIZE) * 8;
900 r = get_user_pages_fast(log, 1, 1, &page);
904 base = kmap_atomic(page, KM_USER0);
906 kunmap_atomic(base, KM_USER0);
907 set_page_dirty_lock(page);
912 static int log_write(void __user *log_base,
913 u64 write_address, u64 write_length)
915 u64 write_page = write_address / VHOST_PAGE_SIZE;
920 write_length += write_address % VHOST_PAGE_SIZE;
922 u64 base = (u64)(unsigned long)log_base;
923 u64 log = base + write_page / 8;
924 int bit = write_page % 8;
925 if ((u64)(unsigned long)log != log)
927 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
930 if (write_length <= VHOST_PAGE_SIZE)
932 write_length -= VHOST_PAGE_SIZE;
938 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
939 unsigned int log_num, u64 len)
943 /* Make sure data written is seen before log. */
945 for (i = 0; i < log_num; ++i) {
946 u64 l = min(log[i].len, len);
947 r = log_write(vq->log_base, log[i].addr, l);
953 eventfd_signal(vq->log_ctx, 1);
957 /* Length written exceeds what we have stored. This is a bug. */
962 static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len,
963 struct iovec iov[], int iov_size)
965 const struct vhost_memory_region *reg;
966 struct vhost_memory *mem;
973 mem = rcu_dereference(dev->memory);
974 while ((u64)len > s) {
976 if (unlikely(ret >= iov_size)) {
980 reg = find_region(mem, addr, len);
981 if (unlikely(!reg)) {
986 size = reg->memory_size - addr + reg->guest_phys_addr;
987 _iov->iov_len = min((u64)len, size);
988 _iov->iov_base = (void __user *)(unsigned long)
989 (reg->userspace_addr + addr - reg->guest_phys_addr);
999 /* Each buffer in the virtqueues is actually a chain of descriptors. This
1000 * function returns the next descriptor in the chain,
1001 * or -1U if we're at the end. */
1002 static unsigned next_desc(struct vring_desc *desc)
1006 /* If this descriptor says it doesn't chain, we're done. */
1007 if (!(desc->flags & VRING_DESC_F_NEXT))
1010 /* Check they're not leading us off end of descriptors. */
1012 /* Make sure compiler knows to grab that: we don't want it changing! */
1013 /* We will use the result as an index in an array, so most
1014 * architectures only need a compiler barrier here. */
1015 read_barrier_depends();
1020 static int get_indirect(struct vhost_dev *dev, struct vhost_virtqueue *vq,
1021 struct iovec iov[], unsigned int iov_size,
1022 unsigned int *out_num, unsigned int *in_num,
1023 struct vhost_log *log, unsigned int *log_num,
1024 struct vring_desc *indirect)
1026 struct vring_desc desc;
1027 unsigned int i = 0, count, found = 0;
1031 if (unlikely(indirect->len % sizeof desc)) {
1032 vq_err(vq, "Invalid length in indirect descriptor: "
1033 "len 0x%llx not multiple of 0x%zx\n",
1034 (unsigned long long)indirect->len,
1039 ret = translate_desc(dev, indirect->addr, indirect->len, vq->indirect,
1041 if (unlikely(ret < 0)) {
1042 vq_err(vq, "Translation failure %d in indirect.\n", ret);
1046 /* We will use the result as an address to read from, so most
1047 * architectures only need a compiler barrier here. */
1048 read_barrier_depends();
1050 count = indirect->len / sizeof desc;
1051 /* Buffers are chained via a 16 bit next field, so
1052 * we can have at most 2^16 of these. */
1053 if (unlikely(count > USHRT_MAX + 1)) {
1054 vq_err(vq, "Indirect buffer length too big: %d\n",
1060 unsigned iov_count = *in_num + *out_num;
1061 if (unlikely(++found > count)) {
1062 vq_err(vq, "Loop detected: last one at %u "
1063 "indirect size %u\n",
1067 if (unlikely(memcpy_fromiovec((unsigned char *)&desc,
1068 vq->indirect, sizeof desc))) {
1069 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1070 i, (size_t)indirect->addr + i * sizeof desc);
1073 if (unlikely(desc.flags & VRING_DESC_F_INDIRECT)) {
1074 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1075 i, (size_t)indirect->addr + i * sizeof desc);
1079 ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
1080 iov_size - iov_count);
1081 if (unlikely(ret < 0)) {
1082 vq_err(vq, "Translation failure %d indirect idx %d\n",
1086 /* If this is an input descriptor, increment that count. */
1087 if (desc.flags & VRING_DESC_F_WRITE) {
1089 if (unlikely(log)) {
1090 log[*log_num].addr = desc.addr;
1091 log[*log_num].len = desc.len;
1095 /* If it's an output descriptor, they're all supposed
1096 * to come before any input descriptors. */
1097 if (unlikely(*in_num)) {
1098 vq_err(vq, "Indirect descriptor "
1099 "has out after in: idx %d\n", i);
1104 } while ((i = next_desc(&desc)) != -1);
1108 /* This looks in the virtqueue and for the first available buffer, and converts
1109 * it to an iovec for convenient access. Since descriptors consist of some
1110 * number of output then some number of input descriptors, it's actually two
1111 * iovecs, but we pack them into one and note how many of each there were.
1113 * This function returns the descriptor number found, or vq->num (which is
1114 * never a valid descriptor number) if none was found. A negative code is
1115 * returned on error. */
1116 int vhost_get_vq_desc(struct vhost_dev *dev, struct vhost_virtqueue *vq,
1117 struct iovec iov[], unsigned int iov_size,
1118 unsigned int *out_num, unsigned int *in_num,
1119 struct vhost_log *log, unsigned int *log_num)
1121 struct vring_desc desc;
1122 unsigned int i, head, found = 0;
1126 /* Check it isn't doing very strange things with descriptor numbers. */
1127 last_avail_idx = vq->last_avail_idx;
1128 if (unlikely(__get_user(vq->avail_idx, &vq->avail->idx))) {
1129 vq_err(vq, "Failed to access avail idx at %p\n",
1134 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1135 vq_err(vq, "Guest moved used index from %u to %u",
1136 last_avail_idx, vq->avail_idx);
1140 /* If there's nothing new since last we looked, return invalid. */
1141 if (vq->avail_idx == last_avail_idx)
1144 /* Only get avail ring entries after they have been exposed by guest. */
1147 /* Grab the next descriptor number they're advertising, and increment
1148 * the index we've seen. */
1149 if (unlikely(__get_user(head,
1150 &vq->avail->ring[last_avail_idx % vq->num]))) {
1151 vq_err(vq, "Failed to read head: idx %d address %p\n",
1153 &vq->avail->ring[last_avail_idx % vq->num]);
1157 /* If their number is silly, that's an error. */
1158 if (unlikely(head >= vq->num)) {
1159 vq_err(vq, "Guest says index %u > %u is available",
1164 /* When we start there are none of either input nor output. */
1165 *out_num = *in_num = 0;
1171 unsigned iov_count = *in_num + *out_num;
1172 if (unlikely(i >= vq->num)) {
1173 vq_err(vq, "Desc index is %u > %u, head = %u",
1177 if (unlikely(++found > vq->num)) {
1178 vq_err(vq, "Loop detected: last one at %u "
1179 "vq size %u head %u\n",
1183 ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
1184 if (unlikely(ret)) {
1185 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1189 if (desc.flags & VRING_DESC_F_INDIRECT) {
1190 ret = get_indirect(dev, vq, iov, iov_size,
1192 log, log_num, &desc);
1193 if (unlikely(ret < 0)) {
1194 vq_err(vq, "Failure detected "
1195 "in indirect descriptor at idx %d\n", i);
1201 ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
1202 iov_size - iov_count);
1203 if (unlikely(ret < 0)) {
1204 vq_err(vq, "Translation failure %d descriptor idx %d\n",
1208 if (desc.flags & VRING_DESC_F_WRITE) {
1209 /* If this is an input descriptor,
1210 * increment that count. */
1212 if (unlikely(log)) {
1213 log[*log_num].addr = desc.addr;
1214 log[*log_num].len = desc.len;
1218 /* If it's an output descriptor, they're all supposed
1219 * to come before any input descriptors. */
1220 if (unlikely(*in_num)) {
1221 vq_err(vq, "Descriptor has out after in: "
1227 } while ((i = next_desc(&desc)) != -1);
1229 /* On success, increment avail index. */
1230 vq->last_avail_idx++;
1232 /* Assume notifications from guest are disabled at this point,
1233 * if they aren't we would need to update avail_event index. */
1234 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
1238 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1239 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1241 vq->last_avail_idx -= n;
1244 /* After we've used one of their buffers, we tell them about it. We'll then
1245 * want to notify the guest, using eventfd. */
1246 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1248 struct vring_used_elem __user *used;
1250 /* The virtqueue contains a ring of used buffers. Get a pointer to the
1251 * next entry in that used ring. */
1252 used = &vq->used->ring[vq->last_used_idx % vq->num];
1253 if (__put_user(head, &used->id)) {
1254 vq_err(vq, "Failed to write used id");
1257 if (__put_user(len, &used->len)) {
1258 vq_err(vq, "Failed to write used len");
1261 /* Make sure buffer is written before we update index. */
1263 if (__put_user(vq->last_used_idx + 1, &vq->used->idx)) {
1264 vq_err(vq, "Failed to increment used idx");
1267 if (unlikely(vq->log_used)) {
1268 /* Make sure data is seen before log. */
1270 /* Log used ring entry write. */
1271 log_write(vq->log_base,
1273 ((void __user *)used - (void __user *)vq->used),
1275 /* Log used index update. */
1276 log_write(vq->log_base,
1277 vq->log_addr + offsetof(struct vring_used, idx),
1278 sizeof vq->used->idx);
1280 eventfd_signal(vq->log_ctx, 1);
1282 vq->last_used_idx++;
1283 /* If the driver never bothers to signal in a very long while,
1284 * used index might wrap around. If that happens, invalidate
1285 * signalled_used index we stored. TODO: make sure driver
1286 * signals at least once in 2^16 and remove this. */
1287 if (unlikely(vq->last_used_idx == vq->signalled_used))
1288 vq->signalled_used_valid = false;
1292 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1293 struct vring_used_elem *heads,
1296 struct vring_used_elem __user *used;
1300 start = vq->last_used_idx % vq->num;
1301 used = vq->used->ring + start;
1302 if (__copy_to_user(used, heads, count * sizeof *used)) {
1303 vq_err(vq, "Failed to write used");
1306 if (unlikely(vq->log_used)) {
1307 /* Make sure data is seen before log. */
1309 /* Log used ring entry write. */
1310 log_write(vq->log_base,
1312 ((void __user *)used - (void __user *)vq->used),
1313 count * sizeof *used);
1315 old = vq->last_used_idx;
1316 new = (vq->last_used_idx += count);
1317 /* If the driver never bothers to signal in a very long while,
1318 * used index might wrap around. If that happens, invalidate
1319 * signalled_used index we stored. TODO: make sure driver
1320 * signals at least once in 2^16 and remove this. */
1321 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
1322 vq->signalled_used_valid = false;
1326 /* After we've used one of their buffers, we tell them about it. We'll then
1327 * want to notify the guest, using eventfd. */
1328 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1333 start = vq->last_used_idx % vq->num;
1334 n = vq->num - start;
1336 r = __vhost_add_used_n(vq, heads, n);
1342 r = __vhost_add_used_n(vq, heads, count);
1344 /* Make sure buffer is written before we update index. */
1346 if (put_user(vq->last_used_idx, &vq->used->idx)) {
1347 vq_err(vq, "Failed to increment used idx");
1350 if (unlikely(vq->log_used)) {
1351 /* Log used index update. */
1352 log_write(vq->log_base,
1353 vq->log_addr + offsetof(struct vring_used, idx),
1354 sizeof vq->used->idx);
1356 eventfd_signal(vq->log_ctx, 1);
1361 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1363 __u16 old, new, event;
1365 /* Flush out used index updates. This is paired
1366 * with the barrier that the Guest executes when enabling
1370 if (vhost_has_feature(dev, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1371 unlikely(vq->avail_idx == vq->last_avail_idx))
1374 if (!vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) {
1376 if (__get_user(flags, &vq->avail->flags)) {
1377 vq_err(vq, "Failed to get flags");
1380 return !(flags & VRING_AVAIL_F_NO_INTERRUPT);
1382 old = vq->signalled_used;
1383 v = vq->signalled_used_valid;
1384 new = vq->signalled_used = vq->last_used_idx;
1385 vq->signalled_used_valid = true;
1390 if (get_user(event, vhost_used_event(vq))) {
1391 vq_err(vq, "Failed to get used event idx");
1394 return vring_need_event(event, new, old);
1397 /* This actually signals the guest, using eventfd. */
1398 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1400 /* Signal the Guest tell them we used something up. */
1401 if (vq->call_ctx && vhost_notify(dev, vq))
1402 eventfd_signal(vq->call_ctx, 1);
1405 /* And here's the combo meal deal. Supersize me! */
1406 void vhost_add_used_and_signal(struct vhost_dev *dev,
1407 struct vhost_virtqueue *vq,
1408 unsigned int head, int len)
1410 vhost_add_used(vq, head, len);
1411 vhost_signal(dev, vq);
1414 /* multi-buffer version of vhost_add_used_and_signal */
1415 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1416 struct vhost_virtqueue *vq,
1417 struct vring_used_elem *heads, unsigned count)
1419 vhost_add_used_n(vq, heads, count);
1420 vhost_signal(dev, vq);
1423 /* OK, now we need to know about added descriptors. */
1424 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1429 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1431 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1432 if (!vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) {
1433 r = put_user(vq->used_flags, &vq->used->flags);
1435 vq_err(vq, "Failed to enable notification at %p: %d\n",
1436 &vq->used->flags, r);
1440 r = put_user(vq->avail_idx, vhost_avail_event(vq));
1442 vq_err(vq, "Failed to update avail event index at %p: %d\n",
1443 vhost_avail_event(vq), r);
1447 if (unlikely(vq->log_used)) {
1449 /* Make sure data is seen before log. */
1451 used = vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX) ?
1452 &vq->used->flags : vhost_avail_event(vq);
1453 /* Log used flags or event index entry write. Both are 16 bit
1455 log_write(vq->log_base, vq->log_addr +
1456 (used - (void __user *)vq->used),
1459 eventfd_signal(vq->log_ctx, 1);
1461 /* They could have slipped one in as we were doing that: make
1462 * sure it's written, then check again. */
1464 r = __get_user(avail_idx, &vq->avail->idx);
1466 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1467 &vq->avail->idx, r);
1471 return avail_idx != vq->avail_idx;
1474 /* We don't need to be notified again. */
1475 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1479 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1481 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1482 if (!vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) {
1483 r = put_user(vq->used_flags, &vq->used->flags);
1485 vq_err(vq, "Failed to enable notification at %p: %d\n",
1486 &vq->used->flags, r);