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/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>
38 VHOST_MEMORY_MAX_NREGIONS = 64,
39 VHOST_MEMORY_F_LOG = 0x1,
42 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
45 struct vhost_poll *poll;
46 poll = container_of(pt, struct vhost_poll, table);
49 add_wait_queue(wqh, &poll->wait);
52 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
55 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
57 if (!((unsigned long)key & poll->mask))
60 vhost_poll_queue(poll);
64 static void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
66 INIT_LIST_HEAD(&work->node);
68 init_waitqueue_head(&work->done);
70 work->queue_seq = work->done_seq = 0;
73 /* Init poll structure */
74 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
75 unsigned long mask, struct vhost_dev *dev)
77 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
78 init_poll_funcptr(&poll->table, vhost_poll_func);
82 vhost_work_init(&poll->work, fn);
85 /* Start polling a file. We add ourselves to file's wait queue. The caller must
86 * keep a reference to a file until after vhost_poll_stop is called. */
87 void vhost_poll_start(struct vhost_poll *poll, struct file *file)
90 mask = file->f_op->poll(file, &poll->table);
92 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
95 /* Stop polling a file. After this function returns, it becomes safe to drop the
96 * file reference. You must also flush afterwards. */
97 void vhost_poll_stop(struct vhost_poll *poll)
99 remove_wait_queue(poll->wqh, &poll->wait);
102 static void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
108 spin_lock_irq(&dev->work_lock);
109 seq = work->queue_seq;
111 spin_unlock_irq(&dev->work_lock);
112 wait_event(work->done, ({
113 spin_lock_irq(&dev->work_lock);
114 left = seq - work->done_seq <= 0;
115 spin_unlock_irq(&dev->work_lock);
118 spin_lock_irq(&dev->work_lock);
119 flushing = --work->flushing;
120 spin_unlock_irq(&dev->work_lock);
121 BUG_ON(flushing < 0);
124 /* Flush any work that has been scheduled. When calling this, don't hold any
125 * locks that are also used by the callback. */
126 void vhost_poll_flush(struct vhost_poll *poll)
128 vhost_work_flush(poll->dev, &poll->work);
131 static inline void vhost_work_queue(struct vhost_dev *dev,
132 struct vhost_work *work)
136 spin_lock_irqsave(&dev->work_lock, flags);
137 if (list_empty(&work->node)) {
138 list_add_tail(&work->node, &dev->work_list);
140 wake_up_process(dev->worker);
142 spin_unlock_irqrestore(&dev->work_lock, flags);
145 void vhost_poll_queue(struct vhost_poll *poll)
147 vhost_work_queue(poll->dev, &poll->work);
150 static void vhost_vq_reset(struct vhost_dev *dev,
151 struct vhost_virtqueue *vq)
157 vq->last_avail_idx = 0;
159 vq->last_used_idx = 0;
161 vq->log_used = false;
162 vq->log_addr = -1ull;
165 vq->private_data = NULL;
167 vq->error_ctx = NULL;
175 static int vhost_worker(void *data)
177 struct vhost_dev *dev = data;
178 struct vhost_work *work = NULL;
179 unsigned uninitialized_var(seq);
184 /* mb paired w/ kthread_stop */
185 set_current_state(TASK_INTERRUPTIBLE);
187 spin_lock_irq(&dev->work_lock);
189 work->done_seq = seq;
191 wake_up_all(&work->done);
194 if (kthread_should_stop()) {
195 spin_unlock_irq(&dev->work_lock);
196 __set_current_state(TASK_RUNNING);
199 if (!list_empty(&dev->work_list)) {
200 work = list_first_entry(&dev->work_list,
201 struct vhost_work, node);
202 list_del_init(&work->node);
203 seq = work->queue_seq;
206 spin_unlock_irq(&dev->work_lock);
209 __set_current_state(TASK_RUNNING);
219 /* Helper to allocate iovec buffers for all vqs. */
220 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
223 for (i = 0; i < dev->nvqs; ++i) {
224 dev->vqs[i].indirect = kmalloc(sizeof *dev->vqs[i].indirect *
225 UIO_MAXIOV, GFP_KERNEL);
226 dev->vqs[i].log = kmalloc(sizeof *dev->vqs[i].log * UIO_MAXIOV,
228 dev->vqs[i].heads = kmalloc(sizeof *dev->vqs[i].heads *
229 UIO_MAXIOV, GFP_KERNEL);
231 if (!dev->vqs[i].indirect || !dev->vqs[i].log ||
237 for (; i >= 0; --i) {
238 kfree(dev->vqs[i].indirect);
239 kfree(dev->vqs[i].log);
240 kfree(dev->vqs[i].heads);
245 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
248 for (i = 0; i < dev->nvqs; ++i) {
249 kfree(dev->vqs[i].indirect);
250 dev->vqs[i].indirect = NULL;
251 kfree(dev->vqs[i].log);
252 dev->vqs[i].log = NULL;
253 kfree(dev->vqs[i].heads);
254 dev->vqs[i].heads = NULL;
258 long vhost_dev_init(struct vhost_dev *dev,
259 struct vhost_virtqueue *vqs, int nvqs)
265 mutex_init(&dev->mutex);
267 dev->log_file = NULL;
270 spin_lock_init(&dev->work_lock);
271 INIT_LIST_HEAD(&dev->work_list);
274 for (i = 0; i < dev->nvqs; ++i) {
275 dev->vqs[i].log = NULL;
276 dev->vqs[i].indirect = NULL;
277 dev->vqs[i].heads = NULL;
278 dev->vqs[i].dev = dev;
279 mutex_init(&dev->vqs[i].mutex);
280 vhost_vq_reset(dev, dev->vqs + i);
281 if (dev->vqs[i].handle_kick)
282 vhost_poll_init(&dev->vqs[i].poll,
283 dev->vqs[i].handle_kick, POLLIN, dev);
289 /* Caller should have device mutex */
290 long vhost_dev_check_owner(struct vhost_dev *dev)
292 /* Are you the owner? If not, I don't think you mean to do that */
293 return dev->mm == current->mm ? 0 : -EPERM;
296 struct vhost_attach_cgroups_struct {
297 struct vhost_work work;
298 struct task_struct *owner;
302 static void vhost_attach_cgroups_work(struct vhost_work *work)
304 struct vhost_attach_cgroups_struct *s;
305 s = container_of(work, struct vhost_attach_cgroups_struct, work);
306 s->ret = cgroup_attach_task_all(s->owner, current);
309 static int vhost_attach_cgroups(struct vhost_dev *dev)
311 struct vhost_attach_cgroups_struct attach;
312 attach.owner = current;
313 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
314 vhost_work_queue(dev, &attach.work);
315 vhost_work_flush(dev, &attach.work);
319 /* Caller should have device mutex */
320 static long vhost_dev_set_owner(struct vhost_dev *dev)
322 struct task_struct *worker;
324 /* Is there an owner already? */
329 /* No owner, become one */
330 dev->mm = get_task_mm(current);
331 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
332 if (IS_ERR(worker)) {
333 err = PTR_ERR(worker);
337 dev->worker = worker;
338 wake_up_process(worker); /* avoid contributing to loadavg */
340 err = vhost_attach_cgroups(dev);
344 err = vhost_dev_alloc_iovecs(dev);
350 kthread_stop(worker);
360 /* Caller should have device mutex */
361 long vhost_dev_reset_owner(struct vhost_dev *dev)
363 struct vhost_memory *memory;
365 /* Restore memory to default empty mapping. */
366 memory = kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
370 vhost_dev_cleanup(dev);
372 memory->nregions = 0;
373 RCU_INIT_POINTER(dev->memory, memory);
377 /* Caller should have device mutex */
378 void vhost_dev_cleanup(struct vhost_dev *dev)
381 for (i = 0; i < dev->nvqs; ++i) {
382 if (dev->vqs[i].kick && dev->vqs[i].handle_kick) {
383 vhost_poll_stop(&dev->vqs[i].poll);
384 vhost_poll_flush(&dev->vqs[i].poll);
386 if (dev->vqs[i].error_ctx)
387 eventfd_ctx_put(dev->vqs[i].error_ctx);
388 if (dev->vqs[i].error)
389 fput(dev->vqs[i].error);
390 if (dev->vqs[i].kick)
391 fput(dev->vqs[i].kick);
392 if (dev->vqs[i].call_ctx)
393 eventfd_ctx_put(dev->vqs[i].call_ctx);
394 if (dev->vqs[i].call)
395 fput(dev->vqs[i].call);
396 vhost_vq_reset(dev, dev->vqs + i);
398 vhost_dev_free_iovecs(dev);
400 eventfd_ctx_put(dev->log_ctx);
404 dev->log_file = NULL;
405 /* No one will access memory at this point */
406 kfree(rcu_dereference_protected(dev->memory,
407 lockdep_is_held(&dev->mutex)));
408 RCU_INIT_POINTER(dev->memory, NULL);
409 WARN_ON(!list_empty(&dev->work_list));
411 kthread_stop(dev->worker);
419 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
421 u64 a = addr / VHOST_PAGE_SIZE / 8;
422 /* Make sure 64 bit math will not overflow. */
423 if (a > ULONG_MAX - (unsigned long)log_base ||
424 a + (unsigned long)log_base > ULONG_MAX)
427 return access_ok(VERIFY_WRITE, log_base + a,
428 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
431 /* Caller should have vq mutex and device mutex. */
432 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
440 for (i = 0; i < mem->nregions; ++i) {
441 struct vhost_memory_region *m = mem->regions + i;
442 unsigned long a = m->userspace_addr;
443 if (m->memory_size > ULONG_MAX)
445 else if (!access_ok(VERIFY_WRITE, (void __user *)a,
448 else if (log_all && !log_access_ok(log_base,
456 /* Can we switch to this memory table? */
457 /* Caller should have device mutex but not vq mutex */
458 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
462 for (i = 0; i < d->nvqs; ++i) {
464 mutex_lock(&d->vqs[i].mutex);
465 /* If ring is inactive, will check when it's enabled. */
466 if (d->vqs[i].private_data)
467 ok = vq_memory_access_ok(d->vqs[i].log_base, mem,
471 mutex_unlock(&d->vqs[i].mutex);
478 static int vq_access_ok(unsigned int num,
479 struct vring_desc __user *desc,
480 struct vring_avail __user *avail,
481 struct vring_used __user *used)
483 return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
484 access_ok(VERIFY_READ, avail,
485 sizeof *avail + num * sizeof *avail->ring) &&
486 access_ok(VERIFY_WRITE, used,
487 sizeof *used + num * sizeof *used->ring);
490 /* Can we log writes? */
491 /* Caller should have device mutex but not vq mutex */
492 int vhost_log_access_ok(struct vhost_dev *dev)
494 struct vhost_memory *mp;
496 mp = rcu_dereference_protected(dev->memory,
497 lockdep_is_held(&dev->mutex));
498 return memory_access_ok(dev, mp, 1);
501 /* Verify access for write logging. */
502 /* Caller should have vq mutex and device mutex */
503 static int vq_log_access_ok(struct vhost_virtqueue *vq, void __user *log_base)
505 struct vhost_memory *mp;
507 mp = rcu_dereference_protected(vq->dev->memory,
508 lockdep_is_held(&vq->mutex));
509 return vq_memory_access_ok(log_base, mp,
510 vhost_has_feature(vq->dev, VHOST_F_LOG_ALL)) &&
511 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
513 vq->num * sizeof *vq->used->ring));
516 /* Can we start vq? */
517 /* Caller should have vq mutex and device mutex */
518 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
520 return vq_access_ok(vq->num, vq->desc, vq->avail, vq->used) &&
521 vq_log_access_ok(vq, vq->log_base);
524 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
526 struct vhost_memory mem, *newmem, *oldmem;
527 unsigned long size = offsetof(struct vhost_memory, regions);
528 if (copy_from_user(&mem, m, size))
532 if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
534 newmem = kmalloc(size + mem.nregions * sizeof *m->regions, GFP_KERNEL);
538 memcpy(newmem, &mem, size);
539 if (copy_from_user(newmem->regions, m->regions,
540 mem.nregions * sizeof *m->regions)) {
545 if (!memory_access_ok(d, newmem, vhost_has_feature(d, VHOST_F_LOG_ALL))) {
549 oldmem = rcu_dereference_protected(d->memory,
550 lockdep_is_held(&d->mutex));
551 rcu_assign_pointer(d->memory, newmem);
557 static int init_used(struct vhost_virtqueue *vq,
558 struct vring_used __user *used)
560 int r = put_user(vq->used_flags, &used->flags);
563 return get_user(vq->last_used_idx, &used->idx);
566 static long vhost_set_vring(struct vhost_dev *d, int ioctl, void __user *argp)
568 struct file *eventfp, *filep = NULL,
569 *pollstart = NULL, *pollstop = NULL;
570 struct eventfd_ctx *ctx = NULL;
571 u32 __user *idxp = argp;
572 struct vhost_virtqueue *vq;
573 struct vhost_vring_state s;
574 struct vhost_vring_file f;
575 struct vhost_vring_addr a;
579 r = get_user(idx, idxp);
587 mutex_lock(&vq->mutex);
590 case VHOST_SET_VRING_NUM:
591 /* Resizing ring with an active backend?
592 * You don't want to do that. */
593 if (vq->private_data) {
597 if (copy_from_user(&s, argp, sizeof s)) {
601 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
607 case VHOST_SET_VRING_BASE:
608 /* Moving base with an active backend?
609 * You don't want to do that. */
610 if (vq->private_data) {
614 if (copy_from_user(&s, argp, sizeof s)) {
618 if (s.num > 0xffff) {
622 vq->last_avail_idx = s.num;
623 /* Forget the cached index value. */
624 vq->avail_idx = vq->last_avail_idx;
626 case VHOST_GET_VRING_BASE:
628 s.num = vq->last_avail_idx;
629 if (copy_to_user(argp, &s, sizeof s))
632 case VHOST_SET_VRING_ADDR:
633 if (copy_from_user(&a, argp, sizeof a)) {
637 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
641 /* For 32bit, verify that the top 32bits of the user
642 data are set to zero. */
643 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
644 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
645 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
649 if ((a.avail_user_addr & (sizeof *vq->avail->ring - 1)) ||
650 (a.used_user_addr & (sizeof *vq->used->ring - 1)) ||
651 (a.log_guest_addr & (sizeof *vq->used->ring - 1))) {
656 /* We only verify access here if backend is configured.
657 * If it is not, we don't as size might not have been setup.
658 * We will verify when backend is configured. */
659 if (vq->private_data) {
660 if (!vq_access_ok(vq->num,
661 (void __user *)(unsigned long)a.desc_user_addr,
662 (void __user *)(unsigned long)a.avail_user_addr,
663 (void __user *)(unsigned long)a.used_user_addr)) {
668 /* Also validate log access for used ring if enabled. */
669 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
670 !log_access_ok(vq->log_base, a.log_guest_addr,
672 vq->num * sizeof *vq->used->ring)) {
678 r = init_used(vq, (struct vring_used __user *)(unsigned long)
682 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
683 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
684 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
685 vq->log_addr = a.log_guest_addr;
686 vq->used = (void __user *)(unsigned long)a.used_user_addr;
688 case VHOST_SET_VRING_KICK:
689 if (copy_from_user(&f, argp, sizeof f)) {
693 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
694 if (IS_ERR(eventfp)) {
695 r = PTR_ERR(eventfp);
698 if (eventfp != vq->kick) {
699 pollstop = filep = vq->kick;
700 pollstart = vq->kick = eventfp;
704 case VHOST_SET_VRING_CALL:
705 if (copy_from_user(&f, argp, sizeof f)) {
709 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
710 if (IS_ERR(eventfp)) {
711 r = PTR_ERR(eventfp);
714 if (eventfp != vq->call) {
718 vq->call_ctx = eventfp ?
719 eventfd_ctx_fileget(eventfp) : NULL;
723 case VHOST_SET_VRING_ERR:
724 if (copy_from_user(&f, argp, sizeof f)) {
728 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
729 if (IS_ERR(eventfp)) {
730 r = PTR_ERR(eventfp);
733 if (eventfp != vq->error) {
737 vq->error_ctx = eventfp ?
738 eventfd_ctx_fileget(eventfp) : NULL;
746 if (pollstop && vq->handle_kick)
747 vhost_poll_stop(&vq->poll);
750 eventfd_ctx_put(ctx);
754 if (pollstart && vq->handle_kick)
755 vhost_poll_start(&vq->poll, vq->kick);
757 mutex_unlock(&vq->mutex);
759 if (pollstop && vq->handle_kick)
760 vhost_poll_flush(&vq->poll);
764 /* Caller must have device mutex */
765 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, unsigned long arg)
767 void __user *argp = (void __user *)arg;
768 struct file *eventfp, *filep = NULL;
769 struct eventfd_ctx *ctx = NULL;
774 /* If you are not the owner, you can become one */
775 if (ioctl == VHOST_SET_OWNER) {
776 r = vhost_dev_set_owner(d);
780 /* You must be the owner to do anything else */
781 r = vhost_dev_check_owner(d);
786 case VHOST_SET_MEM_TABLE:
787 r = vhost_set_memory(d, argp);
789 case VHOST_SET_LOG_BASE:
790 if (copy_from_user(&p, argp, sizeof p)) {
794 if ((u64)(unsigned long)p != p) {
798 for (i = 0; i < d->nvqs; ++i) {
799 struct vhost_virtqueue *vq;
800 void __user *base = (void __user *)(unsigned long)p;
802 mutex_lock(&vq->mutex);
803 /* If ring is inactive, will check when it's enabled. */
804 if (vq->private_data && !vq_log_access_ok(vq, base))
808 mutex_unlock(&vq->mutex);
811 case VHOST_SET_LOG_FD:
812 r = get_user(fd, (int __user *)argp);
815 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
816 if (IS_ERR(eventfp)) {
817 r = PTR_ERR(eventfp);
820 if (eventfp != d->log_file) {
823 d->log_ctx = eventfp ?
824 eventfd_ctx_fileget(eventfp) : NULL;
827 for (i = 0; i < d->nvqs; ++i) {
828 mutex_lock(&d->vqs[i].mutex);
829 d->vqs[i].log_ctx = d->log_ctx;
830 mutex_unlock(&d->vqs[i].mutex);
833 eventfd_ctx_put(ctx);
838 r = vhost_set_vring(d, ioctl, argp);
845 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
846 __u64 addr, __u32 len)
848 struct vhost_memory_region *reg;
850 /* linear search is not brilliant, but we really have on the order of 6
851 * regions in practice */
852 for (i = 0; i < mem->nregions; ++i) {
853 reg = mem->regions + i;
854 if (reg->guest_phys_addr <= addr &&
855 reg->guest_phys_addr + reg->memory_size - 1 >= addr)
861 /* TODO: This is really inefficient. We need something like get_user()
862 * (instruction directly accesses the data, with an exception table entry
863 * returning -EFAULT). See Documentation/x86/exception-tables.txt.
865 static int set_bit_to_user(int nr, void __user *addr)
867 unsigned long log = (unsigned long)addr;
870 int bit = nr + (log % PAGE_SIZE) * 8;
872 r = get_user_pages_fast(log, 1, 1, &page);
876 base = kmap_atomic(page, KM_USER0);
878 kunmap_atomic(base, KM_USER0);
879 set_page_dirty_lock(page);
884 static int log_write(void __user *log_base,
885 u64 write_address, u64 write_length)
890 write_address /= VHOST_PAGE_SIZE;
892 u64 base = (u64)(unsigned long)log_base;
893 u64 log = base + write_address / 8;
894 int bit = write_address % 8;
895 if ((u64)(unsigned long)log != log)
897 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
900 if (write_length <= VHOST_PAGE_SIZE)
902 write_length -= VHOST_PAGE_SIZE;
903 write_address += VHOST_PAGE_SIZE;
908 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
909 unsigned int log_num, u64 len)
913 /* Make sure data written is seen before log. */
915 for (i = 0; i < log_num; ++i) {
916 u64 l = min(log[i].len, len);
917 r = log_write(vq->log_base, log[i].addr, l);
923 eventfd_signal(vq->log_ctx, 1);
927 /* Length written exceeds what we have stored. This is a bug. */
932 static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len,
933 struct iovec iov[], int iov_size)
935 const struct vhost_memory_region *reg;
936 struct vhost_memory *mem;
943 mem = rcu_dereference(dev->memory);
944 while ((u64)len > s) {
946 if (unlikely(ret >= iov_size)) {
950 reg = find_region(mem, addr, len);
951 if (unlikely(!reg)) {
956 size = reg->memory_size - addr + reg->guest_phys_addr;
957 _iov->iov_len = min((u64)len, size);
958 _iov->iov_base = (void __user *)(unsigned long)
959 (reg->userspace_addr + addr - reg->guest_phys_addr);
969 /* Each buffer in the virtqueues is actually a chain of descriptors. This
970 * function returns the next descriptor in the chain,
971 * or -1U if we're at the end. */
972 static unsigned next_desc(struct vring_desc *desc)
976 /* If this descriptor says it doesn't chain, we're done. */
977 if (!(desc->flags & VRING_DESC_F_NEXT))
980 /* Check they're not leading us off end of descriptors. */
982 /* Make sure compiler knows to grab that: we don't want it changing! */
983 /* We will use the result as an index in an array, so most
984 * architectures only need a compiler barrier here. */
985 read_barrier_depends();
990 static int get_indirect(struct vhost_dev *dev, struct vhost_virtqueue *vq,
991 struct iovec iov[], unsigned int iov_size,
992 unsigned int *out_num, unsigned int *in_num,
993 struct vhost_log *log, unsigned int *log_num,
994 struct vring_desc *indirect)
996 struct vring_desc desc;
997 unsigned int i = 0, count, found = 0;
1001 if (unlikely(indirect->len % sizeof desc)) {
1002 vq_err(vq, "Invalid length in indirect descriptor: "
1003 "len 0x%llx not multiple of 0x%zx\n",
1004 (unsigned long long)indirect->len,
1009 ret = translate_desc(dev, indirect->addr, indirect->len, vq->indirect,
1011 if (unlikely(ret < 0)) {
1012 vq_err(vq, "Translation failure %d in indirect.\n", ret);
1016 /* We will use the result as an address to read from, so most
1017 * architectures only need a compiler barrier here. */
1018 read_barrier_depends();
1020 count = indirect->len / sizeof desc;
1021 /* Buffers are chained via a 16 bit next field, so
1022 * we can have at most 2^16 of these. */
1023 if (unlikely(count > USHRT_MAX + 1)) {
1024 vq_err(vq, "Indirect buffer length too big: %d\n",
1030 unsigned iov_count = *in_num + *out_num;
1031 if (unlikely(++found > count)) {
1032 vq_err(vq, "Loop detected: last one at %u "
1033 "indirect size %u\n",
1037 if (unlikely(memcpy_fromiovec((unsigned char *)&desc, vq->indirect,
1039 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1040 i, (size_t)indirect->addr + i * sizeof desc);
1043 if (unlikely(desc.flags & VRING_DESC_F_INDIRECT)) {
1044 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1045 i, (size_t)indirect->addr + i * sizeof desc);
1049 ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
1050 iov_size - iov_count);
1051 if (unlikely(ret < 0)) {
1052 vq_err(vq, "Translation failure %d indirect idx %d\n",
1056 /* If this is an input descriptor, increment that count. */
1057 if (desc.flags & VRING_DESC_F_WRITE) {
1059 if (unlikely(log)) {
1060 log[*log_num].addr = desc.addr;
1061 log[*log_num].len = desc.len;
1065 /* If it's an output descriptor, they're all supposed
1066 * to come before any input descriptors. */
1067 if (unlikely(*in_num)) {
1068 vq_err(vq, "Indirect descriptor "
1069 "has out after in: idx %d\n", i);
1074 } while ((i = next_desc(&desc)) != -1);
1078 /* This looks in the virtqueue and for the first available buffer, and converts
1079 * it to an iovec for convenient access. Since descriptors consist of some
1080 * number of output then some number of input descriptors, it's actually two
1081 * iovecs, but we pack them into one and note how many of each there were.
1083 * This function returns the descriptor number found, or vq->num (which is
1084 * never a valid descriptor number) if none was found. A negative code is
1085 * returned on error. */
1086 int vhost_get_vq_desc(struct vhost_dev *dev, struct vhost_virtqueue *vq,
1087 struct iovec iov[], unsigned int iov_size,
1088 unsigned int *out_num, unsigned int *in_num,
1089 struct vhost_log *log, unsigned int *log_num)
1091 struct vring_desc desc;
1092 unsigned int i, head, found = 0;
1096 /* Check it isn't doing very strange things with descriptor numbers. */
1097 last_avail_idx = vq->last_avail_idx;
1098 if (unlikely(get_user(vq->avail_idx, &vq->avail->idx))) {
1099 vq_err(vq, "Failed to access avail idx at %p\n",
1104 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1105 vq_err(vq, "Guest moved used index from %u to %u",
1106 last_avail_idx, vq->avail_idx);
1110 /* If there's nothing new since last we looked, return invalid. */
1111 if (vq->avail_idx == last_avail_idx)
1114 /* Only get avail ring entries after they have been exposed by guest. */
1117 /* Grab the next descriptor number they're advertising, and increment
1118 * the index we've seen. */
1119 if (unlikely(get_user(head,
1120 &vq->avail->ring[last_avail_idx % vq->num]))) {
1121 vq_err(vq, "Failed to read head: idx %d address %p\n",
1123 &vq->avail->ring[last_avail_idx % vq->num]);
1127 /* If their number is silly, that's an error. */
1128 if (unlikely(head >= vq->num)) {
1129 vq_err(vq, "Guest says index %u > %u is available",
1134 /* When we start there are none of either input nor output. */
1135 *out_num = *in_num = 0;
1141 unsigned iov_count = *in_num + *out_num;
1142 if (unlikely(i >= vq->num)) {
1143 vq_err(vq, "Desc index is %u > %u, head = %u",
1147 if (unlikely(++found > vq->num)) {
1148 vq_err(vq, "Loop detected: last one at %u "
1149 "vq size %u head %u\n",
1153 ret = copy_from_user(&desc, vq->desc + i, sizeof desc);
1154 if (unlikely(ret)) {
1155 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1159 if (desc.flags & VRING_DESC_F_INDIRECT) {
1160 ret = get_indirect(dev, vq, iov, iov_size,
1162 log, log_num, &desc);
1163 if (unlikely(ret < 0)) {
1164 vq_err(vq, "Failure detected "
1165 "in indirect descriptor at idx %d\n", i);
1171 ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
1172 iov_size - iov_count);
1173 if (unlikely(ret < 0)) {
1174 vq_err(vq, "Translation failure %d descriptor idx %d\n",
1178 if (desc.flags & VRING_DESC_F_WRITE) {
1179 /* If this is an input descriptor,
1180 * increment that count. */
1182 if (unlikely(log)) {
1183 log[*log_num].addr = desc.addr;
1184 log[*log_num].len = desc.len;
1188 /* If it's an output descriptor, they're all supposed
1189 * to come before any input descriptors. */
1190 if (unlikely(*in_num)) {
1191 vq_err(vq, "Descriptor has out after in: "
1197 } while ((i = next_desc(&desc)) != -1);
1199 /* On success, increment avail index. */
1200 vq->last_avail_idx++;
1204 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1205 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1207 vq->last_avail_idx -= n;
1210 /* After we've used one of their buffers, we tell them about it. We'll then
1211 * want to notify the guest, using eventfd. */
1212 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1214 struct vring_used_elem __user *used;
1216 /* The virtqueue contains a ring of used buffers. Get a pointer to the
1217 * next entry in that used ring. */
1218 used = &vq->used->ring[vq->last_used_idx % vq->num];
1219 if (put_user(head, &used->id)) {
1220 vq_err(vq, "Failed to write used id");
1223 if (put_user(len, &used->len)) {
1224 vq_err(vq, "Failed to write used len");
1227 /* Make sure buffer is written before we update index. */
1229 if (put_user(vq->last_used_idx + 1, &vq->used->idx)) {
1230 vq_err(vq, "Failed to increment used idx");
1233 if (unlikely(vq->log_used)) {
1234 /* Make sure data is seen before log. */
1236 /* Log used ring entry write. */
1237 log_write(vq->log_base,
1239 ((void __user *)used - (void __user *)vq->used),
1241 /* Log used index update. */
1242 log_write(vq->log_base,
1243 vq->log_addr + offsetof(struct vring_used, idx),
1244 sizeof vq->used->idx);
1246 eventfd_signal(vq->log_ctx, 1);
1248 vq->last_used_idx++;
1252 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1253 struct vring_used_elem *heads,
1256 struct vring_used_elem __user *used;
1259 start = vq->last_used_idx % vq->num;
1260 used = vq->used->ring + start;
1261 if (__copy_to_user(used, heads, count * sizeof *used)) {
1262 vq_err(vq, "Failed to write used");
1265 if (unlikely(vq->log_used)) {
1266 /* Make sure data is seen before log. */
1268 /* Log used ring entry write. */
1269 log_write(vq->log_base,
1271 ((void __user *)used - (void __user *)vq->used),
1272 count * sizeof *used);
1274 vq->last_used_idx += count;
1278 /* After we've used one of their buffers, we tell them about it. We'll then
1279 * want to notify the guest, using eventfd. */
1280 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1285 start = vq->last_used_idx % vq->num;
1286 n = vq->num - start;
1288 r = __vhost_add_used_n(vq, heads, n);
1294 r = __vhost_add_used_n(vq, heads, count);
1296 /* Make sure buffer is written before we update index. */
1298 if (put_user(vq->last_used_idx, &vq->used->idx)) {
1299 vq_err(vq, "Failed to increment used idx");
1302 if (unlikely(vq->log_used)) {
1303 /* Log used index update. */
1304 log_write(vq->log_base,
1305 vq->log_addr + offsetof(struct vring_used, idx),
1306 sizeof vq->used->idx);
1308 eventfd_signal(vq->log_ctx, 1);
1313 /* This actually signals the guest, using eventfd. */
1314 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1317 /* Flush out used index updates. This is paired
1318 * with the barrier that the Guest executes when enabling
1322 if (get_user(flags, &vq->avail->flags)) {
1323 vq_err(vq, "Failed to get flags");
1327 /* If they don't want an interrupt, don't signal, unless empty. */
1328 if ((flags & VRING_AVAIL_F_NO_INTERRUPT) &&
1329 (vq->avail_idx != vq->last_avail_idx ||
1330 !vhost_has_feature(dev, VIRTIO_F_NOTIFY_ON_EMPTY)))
1333 /* Signal the Guest tell them we used something up. */
1335 eventfd_signal(vq->call_ctx, 1);
1338 /* And here's the combo meal deal. Supersize me! */
1339 void vhost_add_used_and_signal(struct vhost_dev *dev,
1340 struct vhost_virtqueue *vq,
1341 unsigned int head, int len)
1343 vhost_add_used(vq, head, len);
1344 vhost_signal(dev, vq);
1347 /* multi-buffer version of vhost_add_used_and_signal */
1348 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1349 struct vhost_virtqueue *vq,
1350 struct vring_used_elem *heads, unsigned count)
1352 vhost_add_used_n(vq, heads, count);
1353 vhost_signal(dev, vq);
1356 /* OK, now we need to know about added descriptors. */
1357 bool vhost_enable_notify(struct vhost_virtqueue *vq)
1361 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1363 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1364 r = put_user(vq->used_flags, &vq->used->flags);
1366 vq_err(vq, "Failed to enable notification at %p: %d\n",
1367 &vq->used->flags, r);
1370 /* They could have slipped one in as we were doing that: make
1371 * sure it's written, then check again. */
1373 r = get_user(avail_idx, &vq->avail->idx);
1375 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1376 &vq->avail->idx, r);
1380 return avail_idx != vq->avail_idx;
1383 /* We don't need to be notified again. */
1384 void vhost_disable_notify(struct vhost_virtqueue *vq)
1387 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1389 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1390 r = put_user(vq->used_flags, &vq->used->flags);
1392 vq_err(vq, "Failed to enable notification at %p: %d\n",
1393 &vq->used->flags, r);