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 static unsigned vhost_zcopy_mask __read_mostly;
42 #define vhost_used_event(vq) ((u16 __user *)&vq->avail->ring[vq->num])
43 #define vhost_avail_event(vq) ((u16 __user *)&vq->used->ring[vq->num])
45 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
48 struct vhost_poll *poll;
50 poll = container_of(pt, struct vhost_poll, table);
52 add_wait_queue(wqh, &poll->wait);
55 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
58 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
60 if (!((unsigned long)key & poll->mask))
63 vhost_poll_queue(poll);
67 static void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
69 INIT_LIST_HEAD(&work->node);
71 init_waitqueue_head(&work->done);
73 work->queue_seq = work->done_seq = 0;
76 /* Init poll structure */
77 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
78 unsigned long mask, struct vhost_dev *dev)
80 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
81 init_poll_funcptr(&poll->table, vhost_poll_func);
85 vhost_work_init(&poll->work, fn);
88 /* Start polling a file. We add ourselves to file's wait queue. The caller must
89 * keep a reference to a file until after vhost_poll_stop is called. */
90 void vhost_poll_start(struct vhost_poll *poll, struct file *file)
94 mask = file->f_op->poll(file, &poll->table);
96 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
99 /* Stop polling a file. After this function returns, it becomes safe to drop the
100 * file reference. You must also flush afterwards. */
101 void vhost_poll_stop(struct vhost_poll *poll)
103 remove_wait_queue(poll->wqh, &poll->wait);
106 static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
111 spin_lock_irq(&dev->work_lock);
112 left = seq - work->done_seq;
113 spin_unlock_irq(&dev->work_lock);
117 static void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
122 spin_lock_irq(&dev->work_lock);
123 seq = work->queue_seq;
125 spin_unlock_irq(&dev->work_lock);
126 wait_event(work->done, vhost_work_seq_done(dev, work, seq));
127 spin_lock_irq(&dev->work_lock);
128 flushing = --work->flushing;
129 spin_unlock_irq(&dev->work_lock);
130 BUG_ON(flushing < 0);
133 /* Flush any work that has been scheduled. When calling this, don't hold any
134 * locks that are also used by the callback. */
135 void vhost_poll_flush(struct vhost_poll *poll)
137 vhost_work_flush(poll->dev, &poll->work);
140 static inline void vhost_work_queue(struct vhost_dev *dev,
141 struct vhost_work *work)
145 spin_lock_irqsave(&dev->work_lock, flags);
146 if (list_empty(&work->node)) {
147 list_add_tail(&work->node, &dev->work_list);
149 wake_up_process(dev->worker);
151 spin_unlock_irqrestore(&dev->work_lock, flags);
154 void vhost_poll_queue(struct vhost_poll *poll)
156 vhost_work_queue(poll->dev, &poll->work);
159 static void vhost_vq_reset(struct vhost_dev *dev,
160 struct vhost_virtqueue *vq)
166 vq->last_avail_idx = 0;
168 vq->last_used_idx = 0;
169 vq->signalled_used = 0;
170 vq->signalled_used_valid = false;
172 vq->log_used = false;
173 vq->log_addr = -1ull;
176 vq->private_data = NULL;
178 vq->error_ctx = NULL;
189 static int vhost_worker(void *data)
191 struct vhost_dev *dev = data;
192 struct vhost_work *work = NULL;
193 unsigned uninitialized_var(seq);
194 mm_segment_t oldfs = get_fs();
200 /* mb paired w/ kthread_stop */
201 set_current_state(TASK_INTERRUPTIBLE);
203 spin_lock_irq(&dev->work_lock);
205 work->done_seq = seq;
207 wake_up_all(&work->done);
210 if (kthread_should_stop()) {
211 spin_unlock_irq(&dev->work_lock);
212 __set_current_state(TASK_RUNNING);
215 if (!list_empty(&dev->work_list)) {
216 work = list_first_entry(&dev->work_list,
217 struct vhost_work, node);
218 list_del_init(&work->node);
219 seq = work->queue_seq;
222 spin_unlock_irq(&dev->work_lock);
225 __set_current_state(TASK_RUNNING);
238 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
246 kfree(vq->ubuf_info);
247 vq->ubuf_info = NULL;
250 void vhost_enable_zcopy(int vq)
252 vhost_zcopy_mask |= 0x1 << vq;
255 /* Helper to allocate iovec buffers for all vqs. */
256 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
261 for (i = 0; i < dev->nvqs; ++i) {
262 dev->vqs[i].indirect = kmalloc(sizeof *dev->vqs[i].indirect *
263 UIO_MAXIOV, GFP_KERNEL);
264 dev->vqs[i].log = kmalloc(sizeof *dev->vqs[i].log * UIO_MAXIOV,
266 dev->vqs[i].heads = kmalloc(sizeof *dev->vqs[i].heads *
267 UIO_MAXIOV, GFP_KERNEL);
268 zcopy = vhost_zcopy_mask & (0x1 << i);
270 dev->vqs[i].ubuf_info =
271 kmalloc(sizeof *dev->vqs[i].ubuf_info *
272 UIO_MAXIOV, GFP_KERNEL);
273 if (!dev->vqs[i].indirect || !dev->vqs[i].log ||
274 !dev->vqs[i].heads ||
275 (zcopy && !dev->vqs[i].ubuf_info))
282 vhost_vq_free_iovecs(&dev->vqs[i]);
286 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
290 for (i = 0; i < dev->nvqs; ++i)
291 vhost_vq_free_iovecs(&dev->vqs[i]);
294 long vhost_dev_init(struct vhost_dev *dev,
295 struct vhost_virtqueue *vqs, int nvqs)
301 mutex_init(&dev->mutex);
303 dev->log_file = NULL;
306 spin_lock_init(&dev->work_lock);
307 INIT_LIST_HEAD(&dev->work_list);
310 for (i = 0; i < dev->nvqs; ++i) {
311 dev->vqs[i].log = NULL;
312 dev->vqs[i].indirect = NULL;
313 dev->vqs[i].heads = NULL;
314 dev->vqs[i].ubuf_info = NULL;
315 dev->vqs[i].dev = dev;
316 mutex_init(&dev->vqs[i].mutex);
317 vhost_vq_reset(dev, dev->vqs + i);
318 if (dev->vqs[i].handle_kick)
319 vhost_poll_init(&dev->vqs[i].poll,
320 dev->vqs[i].handle_kick, POLLIN, dev);
326 /* Caller should have device mutex */
327 long vhost_dev_check_owner(struct vhost_dev *dev)
329 /* Are you the owner? If not, I don't think you mean to do that */
330 return dev->mm == current->mm ? 0 : -EPERM;
333 struct vhost_attach_cgroups_struct {
334 struct vhost_work work;
335 struct task_struct *owner;
339 static void vhost_attach_cgroups_work(struct vhost_work *work)
341 struct vhost_attach_cgroups_struct *s;
343 s = container_of(work, struct vhost_attach_cgroups_struct, work);
344 s->ret = cgroup_attach_task_all(s->owner, current);
347 static int vhost_attach_cgroups(struct vhost_dev *dev)
349 struct vhost_attach_cgroups_struct attach;
351 attach.owner = current;
352 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
353 vhost_work_queue(dev, &attach.work);
354 vhost_work_flush(dev, &attach.work);
358 /* Caller should have device mutex */
359 static long vhost_dev_set_owner(struct vhost_dev *dev)
361 struct task_struct *worker;
364 /* Is there an owner already? */
370 /* No owner, become one */
371 dev->mm = get_task_mm(current);
372 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
373 if (IS_ERR(worker)) {
374 err = PTR_ERR(worker);
378 dev->worker = worker;
379 wake_up_process(worker); /* avoid contributing to loadavg */
381 err = vhost_attach_cgroups(dev);
385 err = vhost_dev_alloc_iovecs(dev);
391 kthread_stop(worker);
401 /* Caller should have device mutex */
402 long vhost_dev_reset_owner(struct vhost_dev *dev)
404 struct vhost_memory *memory;
406 /* Restore memory to default empty mapping. */
407 memory = kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
411 vhost_dev_cleanup(dev, true);
413 memory->nregions = 0;
414 RCU_INIT_POINTER(dev->memory, memory);
418 /* In case of DMA done not in order in lower device driver for some reason.
419 * upend_idx is used to track end of used idx, done_idx is used to track head
420 * of used idx. Once lower device DMA done contiguously, we will signal KVM
423 int vhost_zerocopy_signal_used(struct vhost_virtqueue *vq)
428 for (i = vq->done_idx; i != vq->upend_idx; i = (i + 1) % UIO_MAXIOV) {
429 if ((vq->heads[i].len == VHOST_DMA_DONE_LEN)) {
430 vq->heads[i].len = VHOST_DMA_CLEAR_LEN;
431 vhost_add_used_and_signal(vq->dev, vq,
442 /* Caller should have device mutex if and only if locked is set */
443 void vhost_dev_cleanup(struct vhost_dev *dev, bool locked)
447 for (i = 0; i < dev->nvqs; ++i) {
448 if (dev->vqs[i].kick && dev->vqs[i].handle_kick) {
449 vhost_poll_stop(&dev->vqs[i].poll);
450 vhost_poll_flush(&dev->vqs[i].poll);
452 /* Wait for all lower device DMAs done. */
453 if (dev->vqs[i].ubufs)
454 vhost_ubuf_put_and_wait(dev->vqs[i].ubufs);
456 /* Signal guest as appropriate. */
457 vhost_zerocopy_signal_used(&dev->vqs[i]);
459 if (dev->vqs[i].error_ctx)
460 eventfd_ctx_put(dev->vqs[i].error_ctx);
461 if (dev->vqs[i].error)
462 fput(dev->vqs[i].error);
463 if (dev->vqs[i].kick)
464 fput(dev->vqs[i].kick);
465 if (dev->vqs[i].call_ctx)
466 eventfd_ctx_put(dev->vqs[i].call_ctx);
467 if (dev->vqs[i].call)
468 fput(dev->vqs[i].call);
469 vhost_vq_reset(dev, dev->vqs + i);
471 vhost_dev_free_iovecs(dev);
473 eventfd_ctx_put(dev->log_ctx);
477 dev->log_file = NULL;
478 /* No one will access memory at this point */
479 kfree(rcu_dereference_protected(dev->memory,
481 lockdep_is_held(&dev->mutex)));
482 RCU_INIT_POINTER(dev->memory, NULL);
483 WARN_ON(!list_empty(&dev->work_list));
485 kthread_stop(dev->worker);
493 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
495 u64 a = addr / VHOST_PAGE_SIZE / 8;
497 /* Make sure 64 bit math will not overflow. */
498 if (a > ULONG_MAX - (unsigned long)log_base ||
499 a + (unsigned long)log_base > ULONG_MAX)
502 return access_ok(VERIFY_WRITE, log_base + a,
503 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
506 /* Caller should have vq mutex and device mutex. */
507 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
515 for (i = 0; i < mem->nregions; ++i) {
516 struct vhost_memory_region *m = mem->regions + i;
517 unsigned long a = m->userspace_addr;
518 if (m->memory_size > ULONG_MAX)
520 else if (!access_ok(VERIFY_WRITE, (void __user *)a,
523 else if (log_all && !log_access_ok(log_base,
531 /* Can we switch to this memory table? */
532 /* Caller should have device mutex but not vq mutex */
533 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
538 for (i = 0; i < d->nvqs; ++i) {
540 mutex_lock(&d->vqs[i].mutex);
541 /* If ring is inactive, will check when it's enabled. */
542 if (d->vqs[i].private_data)
543 ok = vq_memory_access_ok(d->vqs[i].log_base, mem,
547 mutex_unlock(&d->vqs[i].mutex);
554 static int vq_access_ok(struct vhost_dev *d, unsigned int num,
555 struct vring_desc __user *desc,
556 struct vring_avail __user *avail,
557 struct vring_used __user *used)
559 size_t s = vhost_has_feature(d, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
560 return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
561 access_ok(VERIFY_READ, avail,
562 sizeof *avail + num * sizeof *avail->ring + s) &&
563 access_ok(VERIFY_WRITE, used,
564 sizeof *used + num * sizeof *used->ring + s);
567 /* Can we log writes? */
568 /* Caller should have device mutex but not vq mutex */
569 int vhost_log_access_ok(struct vhost_dev *dev)
571 struct vhost_memory *mp;
573 mp = rcu_dereference_protected(dev->memory,
574 lockdep_is_held(&dev->mutex));
575 return memory_access_ok(dev, mp, 1);
578 /* Verify access for write logging. */
579 /* Caller should have vq mutex and device mutex */
580 static int vq_log_access_ok(struct vhost_dev *d, struct vhost_virtqueue *vq,
581 void __user *log_base)
583 struct vhost_memory *mp;
584 size_t s = vhost_has_feature(d, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
586 mp = rcu_dereference_protected(vq->dev->memory,
587 lockdep_is_held(&vq->mutex));
588 return vq_memory_access_ok(log_base, mp,
589 vhost_has_feature(vq->dev, VHOST_F_LOG_ALL)) &&
590 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
592 vq->num * sizeof *vq->used->ring + s));
595 /* Can we start vq? */
596 /* Caller should have vq mutex and device mutex */
597 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
599 return vq_access_ok(vq->dev, vq->num, vq->desc, vq->avail, vq->used) &&
600 vq_log_access_ok(vq->dev, vq, vq->log_base);
603 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
605 struct vhost_memory mem, *newmem, *oldmem;
606 unsigned long size = offsetof(struct vhost_memory, regions);
608 if (copy_from_user(&mem, m, size))
612 if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
614 newmem = kmalloc(size + mem.nregions * sizeof *m->regions, GFP_KERNEL);
618 memcpy(newmem, &mem, size);
619 if (copy_from_user(newmem->regions, m->regions,
620 mem.nregions * sizeof *m->regions)) {
625 if (!memory_access_ok(d, newmem,
626 vhost_has_feature(d, VHOST_F_LOG_ALL))) {
630 oldmem = rcu_dereference_protected(d->memory,
631 lockdep_is_held(&d->mutex));
632 rcu_assign_pointer(d->memory, newmem);
638 static long vhost_set_vring(struct vhost_dev *d, int ioctl, void __user *argp)
640 struct file *eventfp, *filep = NULL,
641 *pollstart = NULL, *pollstop = NULL;
642 struct eventfd_ctx *ctx = NULL;
643 u32 __user *idxp = argp;
644 struct vhost_virtqueue *vq;
645 struct vhost_vring_state s;
646 struct vhost_vring_file f;
647 struct vhost_vring_addr a;
651 r = get_user(idx, idxp);
659 mutex_lock(&vq->mutex);
662 case VHOST_SET_VRING_NUM:
663 /* Resizing ring with an active backend?
664 * You don't want to do that. */
665 if (vq->private_data) {
669 if (copy_from_user(&s, argp, sizeof s)) {
673 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
679 case VHOST_SET_VRING_BASE:
680 /* Moving base with an active backend?
681 * You don't want to do that. */
682 if (vq->private_data) {
686 if (copy_from_user(&s, argp, sizeof s)) {
690 if (s.num > 0xffff) {
694 vq->last_avail_idx = s.num;
695 /* Forget the cached index value. */
696 vq->avail_idx = vq->last_avail_idx;
698 case VHOST_GET_VRING_BASE:
700 s.num = vq->last_avail_idx;
701 if (copy_to_user(argp, &s, sizeof s))
704 case VHOST_SET_VRING_ADDR:
705 if (copy_from_user(&a, argp, sizeof a)) {
709 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
713 /* For 32bit, verify that the top 32bits of the user
714 data are set to zero. */
715 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
716 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
717 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
721 if ((a.avail_user_addr & (sizeof *vq->avail->ring - 1)) ||
722 (a.used_user_addr & (sizeof *vq->used->ring - 1)) ||
723 (a.log_guest_addr & (sizeof *vq->used->ring - 1))) {
728 /* We only verify access here if backend is configured.
729 * If it is not, we don't as size might not have been setup.
730 * We will verify when backend is configured. */
731 if (vq->private_data) {
732 if (!vq_access_ok(d, vq->num,
733 (void __user *)(unsigned long)a.desc_user_addr,
734 (void __user *)(unsigned long)a.avail_user_addr,
735 (void __user *)(unsigned long)a.used_user_addr)) {
740 /* Also validate log access for used ring if enabled. */
741 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
742 !log_access_ok(vq->log_base, a.log_guest_addr,
744 vq->num * sizeof *vq->used->ring)) {
750 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
751 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
752 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
753 vq->log_addr = a.log_guest_addr;
754 vq->used = (void __user *)(unsigned long)a.used_user_addr;
756 case VHOST_SET_VRING_KICK:
757 if (copy_from_user(&f, argp, sizeof f)) {
761 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
762 if (IS_ERR(eventfp)) {
763 r = PTR_ERR(eventfp);
766 if (eventfp != vq->kick) {
767 pollstop = filep = vq->kick;
768 pollstart = vq->kick = eventfp;
772 case VHOST_SET_VRING_CALL:
773 if (copy_from_user(&f, argp, sizeof f)) {
777 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
778 if (IS_ERR(eventfp)) {
779 r = PTR_ERR(eventfp);
782 if (eventfp != vq->call) {
786 vq->call_ctx = eventfp ?
787 eventfd_ctx_fileget(eventfp) : NULL;
791 case VHOST_SET_VRING_ERR:
792 if (copy_from_user(&f, argp, sizeof f)) {
796 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
797 if (IS_ERR(eventfp)) {
798 r = PTR_ERR(eventfp);
801 if (eventfp != vq->error) {
805 vq->error_ctx = eventfp ?
806 eventfd_ctx_fileget(eventfp) : NULL;
814 if (pollstop && vq->handle_kick)
815 vhost_poll_stop(&vq->poll);
818 eventfd_ctx_put(ctx);
822 if (pollstart && vq->handle_kick)
823 vhost_poll_start(&vq->poll, vq->kick);
825 mutex_unlock(&vq->mutex);
827 if (pollstop && vq->handle_kick)
828 vhost_poll_flush(&vq->poll);
832 /* Caller must have device mutex */
833 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, unsigned long arg)
835 void __user *argp = (void __user *)arg;
836 struct file *eventfp, *filep = NULL;
837 struct eventfd_ctx *ctx = NULL;
842 /* If you are not the owner, you can become one */
843 if (ioctl == VHOST_SET_OWNER) {
844 r = vhost_dev_set_owner(d);
848 /* You must be the owner to do anything else */
849 r = vhost_dev_check_owner(d);
854 case VHOST_SET_MEM_TABLE:
855 r = vhost_set_memory(d, argp);
857 case VHOST_SET_LOG_BASE:
858 if (copy_from_user(&p, argp, sizeof p)) {
862 if ((u64)(unsigned long)p != p) {
866 for (i = 0; i < d->nvqs; ++i) {
867 struct vhost_virtqueue *vq;
868 void __user *base = (void __user *)(unsigned long)p;
870 mutex_lock(&vq->mutex);
871 /* If ring is inactive, will check when it's enabled. */
872 if (vq->private_data && !vq_log_access_ok(d, vq, base))
876 mutex_unlock(&vq->mutex);
879 case VHOST_SET_LOG_FD:
880 r = get_user(fd, (int __user *)argp);
883 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
884 if (IS_ERR(eventfp)) {
885 r = PTR_ERR(eventfp);
888 if (eventfp != d->log_file) {
891 d->log_ctx = eventfp ?
892 eventfd_ctx_fileget(eventfp) : NULL;
895 for (i = 0; i < d->nvqs; ++i) {
896 mutex_lock(&d->vqs[i].mutex);
897 d->vqs[i].log_ctx = d->log_ctx;
898 mutex_unlock(&d->vqs[i].mutex);
901 eventfd_ctx_put(ctx);
906 r = vhost_set_vring(d, ioctl, argp);
913 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
914 __u64 addr, __u32 len)
916 struct vhost_memory_region *reg;
919 /* linear search is not brilliant, but we really have on the order of 6
920 * regions in practice */
921 for (i = 0; i < mem->nregions; ++i) {
922 reg = mem->regions + i;
923 if (reg->guest_phys_addr <= addr &&
924 reg->guest_phys_addr + reg->memory_size - 1 >= addr)
930 /* TODO: This is really inefficient. We need something like get_user()
931 * (instruction directly accesses the data, with an exception table entry
932 * returning -EFAULT). See Documentation/x86/exception-tables.txt.
934 static int set_bit_to_user(int nr, void __user *addr)
936 unsigned long log = (unsigned long)addr;
939 int bit = nr + (log % PAGE_SIZE) * 8;
942 r = get_user_pages_fast(log, 1, 1, &page);
946 base = kmap_atomic(page);
949 set_page_dirty_lock(page);
954 static int log_write(void __user *log_base,
955 u64 write_address, u64 write_length)
957 u64 write_page = write_address / VHOST_PAGE_SIZE;
962 write_length += write_address % VHOST_PAGE_SIZE;
964 u64 base = (u64)(unsigned long)log_base;
965 u64 log = base + write_page / 8;
966 int bit = write_page % 8;
967 if ((u64)(unsigned long)log != log)
969 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
972 if (write_length <= VHOST_PAGE_SIZE)
974 write_length -= VHOST_PAGE_SIZE;
980 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
981 unsigned int log_num, u64 len)
985 /* Make sure data written is seen before log. */
987 for (i = 0; i < log_num; ++i) {
988 u64 l = min(log[i].len, len);
989 r = log_write(vq->log_base, log[i].addr, l);
995 eventfd_signal(vq->log_ctx, 1);
999 /* Length written exceeds what we have stored. This is a bug. */
1004 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1007 if (__put_user(vq->used_flags, &vq->used->flags) < 0)
1009 if (unlikely(vq->log_used)) {
1010 /* Make sure the flag is seen before log. */
1012 /* Log used flag write. */
1013 used = &vq->used->flags;
1014 log_write(vq->log_base, vq->log_addr +
1015 (used - (void __user *)vq->used),
1016 sizeof vq->used->flags);
1018 eventfd_signal(vq->log_ctx, 1);
1023 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1025 if (__put_user(vq->avail_idx, vhost_avail_event(vq)))
1027 if (unlikely(vq->log_used)) {
1029 /* Make sure the event is seen before log. */
1031 /* Log avail event write */
1032 used = vhost_avail_event(vq);
1033 log_write(vq->log_base, vq->log_addr +
1034 (used - (void __user *)vq->used),
1035 sizeof *vhost_avail_event(vq));
1037 eventfd_signal(vq->log_ctx, 1);
1042 int vhost_init_used(struct vhost_virtqueue *vq)
1045 if (!vq->private_data)
1048 r = vhost_update_used_flags(vq);
1051 vq->signalled_used_valid = false;
1052 return get_user(vq->last_used_idx, &vq->used->idx);
1055 static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len,
1056 struct iovec iov[], int iov_size)
1058 const struct vhost_memory_region *reg;
1059 struct vhost_memory *mem;
1066 mem = rcu_dereference(dev->memory);
1067 while ((u64)len > s) {
1069 if (unlikely(ret >= iov_size)) {
1073 reg = find_region(mem, addr, len);
1074 if (unlikely(!reg)) {
1079 size = reg->memory_size - addr + reg->guest_phys_addr;
1080 _iov->iov_len = min((u64)len, size);
1081 _iov->iov_base = (void __user *)(unsigned long)
1082 (reg->userspace_addr + addr - reg->guest_phys_addr);
1092 /* Each buffer in the virtqueues is actually a chain of descriptors. This
1093 * function returns the next descriptor in the chain,
1094 * or -1U if we're at the end. */
1095 static unsigned next_desc(struct vring_desc *desc)
1099 /* If this descriptor says it doesn't chain, we're done. */
1100 if (!(desc->flags & VRING_DESC_F_NEXT))
1103 /* Check they're not leading us off end of descriptors. */
1105 /* Make sure compiler knows to grab that: we don't want it changing! */
1106 /* We will use the result as an index in an array, so most
1107 * architectures only need a compiler barrier here. */
1108 read_barrier_depends();
1113 static int get_indirect(struct vhost_dev *dev, struct vhost_virtqueue *vq,
1114 struct iovec iov[], unsigned int iov_size,
1115 unsigned int *out_num, unsigned int *in_num,
1116 struct vhost_log *log, unsigned int *log_num,
1117 struct vring_desc *indirect)
1119 struct vring_desc desc;
1120 unsigned int i = 0, count, found = 0;
1124 if (unlikely(indirect->len % sizeof desc)) {
1125 vq_err(vq, "Invalid length in indirect descriptor: "
1126 "len 0x%llx not multiple of 0x%zx\n",
1127 (unsigned long long)indirect->len,
1132 ret = translate_desc(dev, indirect->addr, indirect->len, vq->indirect,
1134 if (unlikely(ret < 0)) {
1135 vq_err(vq, "Translation failure %d in indirect.\n", ret);
1139 /* We will use the result as an address to read from, so most
1140 * architectures only need a compiler barrier here. */
1141 read_barrier_depends();
1143 count = indirect->len / sizeof desc;
1144 /* Buffers are chained via a 16 bit next field, so
1145 * we can have at most 2^16 of these. */
1146 if (unlikely(count > USHRT_MAX + 1)) {
1147 vq_err(vq, "Indirect buffer length too big: %d\n",
1153 unsigned iov_count = *in_num + *out_num;
1154 if (unlikely(++found > count)) {
1155 vq_err(vq, "Loop detected: last one at %u "
1156 "indirect size %u\n",
1160 if (unlikely(memcpy_fromiovec((unsigned char *)&desc,
1161 vq->indirect, sizeof desc))) {
1162 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1163 i, (size_t)indirect->addr + i * sizeof desc);
1166 if (unlikely(desc.flags & VRING_DESC_F_INDIRECT)) {
1167 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1168 i, (size_t)indirect->addr + i * sizeof desc);
1172 ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
1173 iov_size - iov_count);
1174 if (unlikely(ret < 0)) {
1175 vq_err(vq, "Translation failure %d indirect idx %d\n",
1179 /* If this is an input descriptor, increment that count. */
1180 if (desc.flags & VRING_DESC_F_WRITE) {
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, "Indirect descriptor "
1192 "has out after in: idx %d\n", i);
1197 } while ((i = next_desc(&desc)) != -1);
1201 /* This looks in the virtqueue and for the first available buffer, and converts
1202 * it to an iovec for convenient access. Since descriptors consist of some
1203 * number of output then some number of input descriptors, it's actually two
1204 * iovecs, but we pack them into one and note how many of each there were.
1206 * This function returns the descriptor number found, or vq->num (which is
1207 * never a valid descriptor number) if none was found. A negative code is
1208 * returned on error. */
1209 int vhost_get_vq_desc(struct vhost_dev *dev, struct vhost_virtqueue *vq,
1210 struct iovec iov[], unsigned int iov_size,
1211 unsigned int *out_num, unsigned int *in_num,
1212 struct vhost_log *log, unsigned int *log_num)
1214 struct vring_desc desc;
1215 unsigned int i, head, found = 0;
1219 /* Check it isn't doing very strange things with descriptor numbers. */
1220 last_avail_idx = vq->last_avail_idx;
1221 if (unlikely(__get_user(vq->avail_idx, &vq->avail->idx))) {
1222 vq_err(vq, "Failed to access avail idx at %p\n",
1227 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1228 vq_err(vq, "Guest moved used index from %u to %u",
1229 last_avail_idx, vq->avail_idx);
1233 /* If there's nothing new since last we looked, return invalid. */
1234 if (vq->avail_idx == last_avail_idx)
1237 /* Only get avail ring entries after they have been exposed by guest. */
1240 /* Grab the next descriptor number they're advertising, and increment
1241 * the index we've seen. */
1242 if (unlikely(__get_user(head,
1243 &vq->avail->ring[last_avail_idx % vq->num]))) {
1244 vq_err(vq, "Failed to read head: idx %d address %p\n",
1246 &vq->avail->ring[last_avail_idx % vq->num]);
1250 /* If their number is silly, that's an error. */
1251 if (unlikely(head >= vq->num)) {
1252 vq_err(vq, "Guest says index %u > %u is available",
1257 /* When we start there are none of either input nor output. */
1258 *out_num = *in_num = 0;
1264 unsigned iov_count = *in_num + *out_num;
1265 if (unlikely(i >= vq->num)) {
1266 vq_err(vq, "Desc index is %u > %u, head = %u",
1270 if (unlikely(++found > vq->num)) {
1271 vq_err(vq, "Loop detected: last one at %u "
1272 "vq size %u head %u\n",
1276 ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
1277 if (unlikely(ret)) {
1278 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1282 if (desc.flags & VRING_DESC_F_INDIRECT) {
1283 ret = get_indirect(dev, vq, iov, iov_size,
1285 log, log_num, &desc);
1286 if (unlikely(ret < 0)) {
1287 vq_err(vq, "Failure detected "
1288 "in indirect descriptor at idx %d\n", i);
1294 ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
1295 iov_size - iov_count);
1296 if (unlikely(ret < 0)) {
1297 vq_err(vq, "Translation failure %d descriptor idx %d\n",
1301 if (desc.flags & VRING_DESC_F_WRITE) {
1302 /* If this is an input descriptor,
1303 * increment that count. */
1305 if (unlikely(log)) {
1306 log[*log_num].addr = desc.addr;
1307 log[*log_num].len = desc.len;
1311 /* If it's an output descriptor, they're all supposed
1312 * to come before any input descriptors. */
1313 if (unlikely(*in_num)) {
1314 vq_err(vq, "Descriptor has out after in: "
1320 } while ((i = next_desc(&desc)) != -1);
1322 /* On success, increment avail index. */
1323 vq->last_avail_idx++;
1325 /* Assume notifications from guest are disabled at this point,
1326 * if they aren't we would need to update avail_event index. */
1327 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
1331 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1332 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1334 vq->last_avail_idx -= n;
1337 /* After we've used one of their buffers, we tell them about it. We'll then
1338 * want to notify the guest, using eventfd. */
1339 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1341 struct vring_used_elem __user *used;
1343 /* The virtqueue contains a ring of used buffers. Get a pointer to the
1344 * next entry in that used ring. */
1345 used = &vq->used->ring[vq->last_used_idx % vq->num];
1346 if (__put_user(head, &used->id)) {
1347 vq_err(vq, "Failed to write used id");
1350 if (__put_user(len, &used->len)) {
1351 vq_err(vq, "Failed to write used len");
1354 /* Make sure buffer is written before we update index. */
1356 if (__put_user(vq->last_used_idx + 1, &vq->used->idx)) {
1357 vq_err(vq, "Failed to increment used idx");
1360 if (unlikely(vq->log_used)) {
1361 /* Make sure data is seen before log. */
1363 /* Log used ring entry write. */
1364 log_write(vq->log_base,
1366 ((void __user *)used - (void __user *)vq->used),
1368 /* Log used index update. */
1369 log_write(vq->log_base,
1370 vq->log_addr + offsetof(struct vring_used, idx),
1371 sizeof vq->used->idx);
1373 eventfd_signal(vq->log_ctx, 1);
1375 vq->last_used_idx++;
1376 /* If the driver never bothers to signal in a very long while,
1377 * used index might wrap around. If that happens, invalidate
1378 * signalled_used index we stored. TODO: make sure driver
1379 * signals at least once in 2^16 and remove this. */
1380 if (unlikely(vq->last_used_idx == vq->signalled_used))
1381 vq->signalled_used_valid = false;
1385 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1386 struct vring_used_elem *heads,
1389 struct vring_used_elem __user *used;
1393 start = vq->last_used_idx % vq->num;
1394 used = vq->used->ring + start;
1395 if (__copy_to_user(used, heads, count * sizeof *used)) {
1396 vq_err(vq, "Failed to write used");
1399 if (unlikely(vq->log_used)) {
1400 /* Make sure data is seen before log. */
1402 /* Log used ring entry write. */
1403 log_write(vq->log_base,
1405 ((void __user *)used - (void __user *)vq->used),
1406 count * sizeof *used);
1408 old = vq->last_used_idx;
1409 new = (vq->last_used_idx += count);
1410 /* If the driver never bothers to signal in a very long while,
1411 * used index might wrap around. If that happens, invalidate
1412 * signalled_used index we stored. TODO: make sure driver
1413 * signals at least once in 2^16 and remove this. */
1414 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
1415 vq->signalled_used_valid = false;
1419 /* After we've used one of their buffers, we tell them about it. We'll then
1420 * want to notify the guest, using eventfd. */
1421 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1426 start = vq->last_used_idx % vq->num;
1427 n = vq->num - start;
1429 r = __vhost_add_used_n(vq, heads, n);
1435 r = __vhost_add_used_n(vq, heads, count);
1437 /* Make sure buffer is written before we update index. */
1439 if (put_user(vq->last_used_idx, &vq->used->idx)) {
1440 vq_err(vq, "Failed to increment used idx");
1443 if (unlikely(vq->log_used)) {
1444 /* Log used index update. */
1445 log_write(vq->log_base,
1446 vq->log_addr + offsetof(struct vring_used, idx),
1447 sizeof vq->used->idx);
1449 eventfd_signal(vq->log_ctx, 1);
1454 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1456 __u16 old, new, event;
1458 /* Flush out used index updates. This is paired
1459 * with the barrier that the Guest executes when enabling
1463 if (vhost_has_feature(dev, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1464 unlikely(vq->avail_idx == vq->last_avail_idx))
1467 if (!vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) {
1469 if (__get_user(flags, &vq->avail->flags)) {
1470 vq_err(vq, "Failed to get flags");
1473 return !(flags & VRING_AVAIL_F_NO_INTERRUPT);
1475 old = vq->signalled_used;
1476 v = vq->signalled_used_valid;
1477 new = vq->signalled_used = vq->last_used_idx;
1478 vq->signalled_used_valid = true;
1483 if (get_user(event, vhost_used_event(vq))) {
1484 vq_err(vq, "Failed to get used event idx");
1487 return vring_need_event(event, new, old);
1490 /* This actually signals the guest, using eventfd. */
1491 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1493 /* Signal the Guest tell them we used something up. */
1494 if (vq->call_ctx && vhost_notify(dev, vq))
1495 eventfd_signal(vq->call_ctx, 1);
1498 /* And here's the combo meal deal. Supersize me! */
1499 void vhost_add_used_and_signal(struct vhost_dev *dev,
1500 struct vhost_virtqueue *vq,
1501 unsigned int head, int len)
1503 vhost_add_used(vq, head, len);
1504 vhost_signal(dev, vq);
1507 /* multi-buffer version of vhost_add_used_and_signal */
1508 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1509 struct vhost_virtqueue *vq,
1510 struct vring_used_elem *heads, unsigned count)
1512 vhost_add_used_n(vq, heads, count);
1513 vhost_signal(dev, vq);
1516 /* OK, now we need to know about added descriptors. */
1517 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1522 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1524 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1525 if (!vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) {
1526 r = vhost_update_used_flags(vq);
1528 vq_err(vq, "Failed to enable notification at %p: %d\n",
1529 &vq->used->flags, r);
1533 r = vhost_update_avail_event(vq, vq->avail_idx);
1535 vq_err(vq, "Failed to update avail event index at %p: %d\n",
1536 vhost_avail_event(vq), r);
1540 /* They could have slipped one in as we were doing that: make
1541 * sure it's written, then check again. */
1543 r = __get_user(avail_idx, &vq->avail->idx);
1545 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1546 &vq->avail->idx, r);
1550 return avail_idx != vq->avail_idx;
1553 /* We don't need to be notified again. */
1554 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1558 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1560 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1561 if (!vhost_has_feature(dev, VIRTIO_RING_F_EVENT_IDX)) {
1562 r = vhost_update_used_flags(vq);
1564 vq_err(vq, "Failed to enable notification at %p: %d\n",
1565 &vq->used->flags, r);
1569 static void vhost_zerocopy_done_signal(struct kref *kref)
1571 struct vhost_ubuf_ref *ubufs = container_of(kref, struct vhost_ubuf_ref,
1573 wake_up(&ubufs->wait);
1576 struct vhost_ubuf_ref *vhost_ubuf_alloc(struct vhost_virtqueue *vq,
1579 struct vhost_ubuf_ref *ubufs;
1580 /* No zero copy backend? Nothing to count. */
1583 ubufs = kmalloc(sizeof *ubufs, GFP_KERNEL);
1585 return ERR_PTR(-ENOMEM);
1586 kref_init(&ubufs->kref);
1587 init_waitqueue_head(&ubufs->wait);
1592 void vhost_ubuf_put(struct vhost_ubuf_ref *ubufs)
1594 kref_put(&ubufs->kref, vhost_zerocopy_done_signal);
1597 void vhost_ubuf_put_and_wait(struct vhost_ubuf_ref *ubufs)
1599 kref_put(&ubufs->kref, vhost_zerocopy_done_signal);
1600 wait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount));
1604 void vhost_zerocopy_callback(struct ubuf_info *ubuf)
1606 struct vhost_ubuf_ref *ubufs = ubuf->ctx;
1607 struct vhost_virtqueue *vq = ubufs->vq;
1609 vhost_poll_queue(&vq->poll);
1610 /* set len = 1 to mark this desc buffers done DMA */
1611 vq->heads[ubuf->desc].len = VHOST_DMA_DONE_LEN;
1612 kref_put(&ubufs->kref, vhost_zerocopy_done_signal);