1 /* Copyright (C) 2009 Red Hat, Inc.
2 * Copyright (C) 2006 Rusty Russell IBM Corporation
4 * Author: Michael S. Tsirkin <mst@redhat.com>
6 * Inspiration, some code, and most witty comments come from
7 * Documentation/virtual/lguest/lguest.c, by Rusty Russell
9 * This work is licensed under the terms of the GNU GPL, version 2.
11 * Generic code for virtio server in host kernel.
14 #include <linux/eventfd.h>
15 #include <linux/vhost.h>
16 #include <linux/uio.h>
18 #include <linux/mmu_context.h>
19 #include <linux/miscdevice.h>
20 #include <linux/mutex.h>
21 #include <linux/poll.h>
22 #include <linux/file.h>
23 #include <linux/highmem.h>
24 #include <linux/slab.h>
25 #include <linux/vmalloc.h>
26 #include <linux/kthread.h>
27 #include <linux/cgroup.h>
28 #include <linux/module.h>
29 #include <linux/sort.h>
30 #include <linux/nospec.h>
34 static ushort max_mem_regions = 64;
35 module_param(max_mem_regions, ushort, 0444);
36 MODULE_PARM_DESC(max_mem_regions,
37 "Maximum number of memory regions in memory map. (default: 64)");
40 VHOST_MEMORY_F_LOG = 0x1,
43 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
44 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
46 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
47 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
49 vq->user_be = !virtio_legacy_is_little_endian();
52 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
54 struct vhost_vring_state s;
59 if (copy_from_user(&s, argp, sizeof(s)))
62 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
63 s.num != VHOST_VRING_BIG_ENDIAN)
71 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
74 struct vhost_vring_state s = {
79 if (copy_to_user(argp, &s, sizeof(s)))
85 static void vhost_init_is_le(struct vhost_virtqueue *vq)
87 /* Note for legacy virtio: user_be is initialized at reset time
88 * according to the host endianness. If userspace does not set an
89 * explicit endianness, the default behavior is native endian, as
90 * expected by legacy virtio.
92 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
95 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
99 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
104 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
110 static void vhost_init_is_le(struct vhost_virtqueue *vq)
112 if (vhost_has_feature(vq, VIRTIO_F_VERSION_1))
115 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
117 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
120 struct vhost_poll *poll;
122 poll = container_of(pt, struct vhost_poll, table);
124 add_wait_queue(wqh, &poll->wait);
127 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
130 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
132 if (!((unsigned long)key & poll->mask))
135 vhost_poll_queue(poll);
139 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
141 INIT_LIST_HEAD(&work->node);
143 init_waitqueue_head(&work->done);
145 work->queue_seq = work->done_seq = 0;
147 EXPORT_SYMBOL_GPL(vhost_work_init);
149 /* Init poll structure */
150 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
151 unsigned long mask, struct vhost_dev *dev)
153 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
154 init_poll_funcptr(&poll->table, vhost_poll_func);
159 vhost_work_init(&poll->work, fn);
161 EXPORT_SYMBOL_GPL(vhost_poll_init);
163 /* Start polling a file. We add ourselves to file's wait queue. The caller must
164 * keep a reference to a file until after vhost_poll_stop is called. */
165 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
173 mask = file->f_op->poll(file, &poll->table);
175 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
176 if (mask & POLLERR) {
177 vhost_poll_stop(poll);
183 EXPORT_SYMBOL_GPL(vhost_poll_start);
185 /* Stop polling a file. After this function returns, it becomes safe to drop the
186 * file reference. You must also flush afterwards. */
187 void vhost_poll_stop(struct vhost_poll *poll)
190 remove_wait_queue(poll->wqh, &poll->wait);
194 EXPORT_SYMBOL_GPL(vhost_poll_stop);
196 static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
201 spin_lock_irq(&dev->work_lock);
202 left = seq - work->done_seq;
203 spin_unlock_irq(&dev->work_lock);
207 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
212 spin_lock_irq(&dev->work_lock);
213 seq = work->queue_seq;
215 spin_unlock_irq(&dev->work_lock);
216 wait_event(work->done, vhost_work_seq_done(dev, work, seq));
217 spin_lock_irq(&dev->work_lock);
218 flushing = --work->flushing;
219 spin_unlock_irq(&dev->work_lock);
220 BUG_ON(flushing < 0);
222 EXPORT_SYMBOL_GPL(vhost_work_flush);
224 /* Flush any work that has been scheduled. When calling this, don't hold any
225 * locks that are also used by the callback. */
226 void vhost_poll_flush(struct vhost_poll *poll)
228 vhost_work_flush(poll->dev, &poll->work);
230 EXPORT_SYMBOL_GPL(vhost_poll_flush);
232 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
236 spin_lock_irqsave(&dev->work_lock, flags);
237 if (list_empty(&work->node)) {
238 list_add_tail(&work->node, &dev->work_list);
240 spin_unlock_irqrestore(&dev->work_lock, flags);
241 wake_up_process(dev->worker);
243 spin_unlock_irqrestore(&dev->work_lock, flags);
246 EXPORT_SYMBOL_GPL(vhost_work_queue);
248 void vhost_poll_queue(struct vhost_poll *poll)
250 vhost_work_queue(poll->dev, &poll->work);
252 EXPORT_SYMBOL_GPL(vhost_poll_queue);
254 static void vhost_vq_reset(struct vhost_dev *dev,
255 struct vhost_virtqueue *vq)
261 vq->last_avail_idx = 0;
263 vq->last_used_idx = 0;
264 vq->signalled_used = 0;
265 vq->signalled_used_valid = false;
267 vq->log_used = false;
268 vq->log_addr = -1ull;
269 vq->private_data = NULL;
270 vq->acked_features = 0;
272 vq->error_ctx = NULL;
279 vq->is_le = virtio_legacy_is_little_endian();
280 vhost_vq_reset_user_be(vq);
283 static int vhost_worker(void *data)
285 struct vhost_dev *dev = data;
286 struct vhost_work *work = NULL;
287 unsigned uninitialized_var(seq);
288 mm_segment_t oldfs = get_fs();
294 /* mb paired w/ kthread_stop */
295 set_current_state(TASK_INTERRUPTIBLE);
297 spin_lock_irq(&dev->work_lock);
299 work->done_seq = seq;
301 wake_up_all(&work->done);
304 if (kthread_should_stop()) {
305 spin_unlock_irq(&dev->work_lock);
306 __set_current_state(TASK_RUNNING);
309 if (!list_empty(&dev->work_list)) {
310 work = list_first_entry(&dev->work_list,
311 struct vhost_work, node);
312 list_del_init(&work->node);
313 seq = work->queue_seq;
316 spin_unlock_irq(&dev->work_lock);
319 __set_current_state(TASK_RUNNING);
332 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
342 /* Helper to allocate iovec buffers for all vqs. */
343 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
345 struct vhost_virtqueue *vq;
348 for (i = 0; i < dev->nvqs; ++i) {
350 vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
352 vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
353 vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
354 if (!vq->indirect || !vq->log || !vq->heads)
361 vhost_vq_free_iovecs(dev->vqs[i]);
365 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
369 for (i = 0; i < dev->nvqs; ++i)
370 vhost_vq_free_iovecs(dev->vqs[i]);
373 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
374 int pkts, int total_len)
376 struct vhost_dev *dev = vq->dev;
378 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
379 pkts >= dev->weight) {
380 vhost_poll_queue(&vq->poll);
386 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
388 void vhost_dev_init(struct vhost_dev *dev,
389 struct vhost_virtqueue **vqs, int nvqs,
390 int weight, int byte_weight)
392 struct vhost_virtqueue *vq;
397 mutex_init(&dev->mutex);
399 dev->log_file = NULL;
402 spin_lock_init(&dev->work_lock);
403 INIT_LIST_HEAD(&dev->work_list);
405 dev->weight = weight;
406 dev->byte_weight = byte_weight;
408 for (i = 0; i < dev->nvqs; ++i) {
414 mutex_init(&vq->mutex);
415 vhost_vq_reset(dev, vq);
417 vhost_poll_init(&vq->poll, vq->handle_kick,
421 EXPORT_SYMBOL_GPL(vhost_dev_init);
423 /* Caller should have device mutex */
424 long vhost_dev_check_owner(struct vhost_dev *dev)
426 /* Are you the owner? If not, I don't think you mean to do that */
427 return dev->mm == current->mm ? 0 : -EPERM;
429 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
431 struct vhost_attach_cgroups_struct {
432 struct vhost_work work;
433 struct task_struct *owner;
437 static void vhost_attach_cgroups_work(struct vhost_work *work)
439 struct vhost_attach_cgroups_struct *s;
441 s = container_of(work, struct vhost_attach_cgroups_struct, work);
442 s->ret = cgroup_attach_task_all(s->owner, current);
445 static int vhost_attach_cgroups(struct vhost_dev *dev)
447 struct vhost_attach_cgroups_struct attach;
449 attach.owner = current;
450 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
451 vhost_work_queue(dev, &attach.work);
452 vhost_work_flush(dev, &attach.work);
456 /* Caller should have device mutex */
457 bool vhost_dev_has_owner(struct vhost_dev *dev)
461 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
463 /* Caller should have device mutex */
464 long vhost_dev_set_owner(struct vhost_dev *dev)
466 struct task_struct *worker;
469 /* Is there an owner already? */
470 if (vhost_dev_has_owner(dev)) {
475 /* No owner, become one */
476 dev->mm = get_task_mm(current);
477 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
478 if (IS_ERR(worker)) {
479 err = PTR_ERR(worker);
483 dev->worker = worker;
484 wake_up_process(worker); /* avoid contributing to loadavg */
486 err = vhost_attach_cgroups(dev);
490 err = vhost_dev_alloc_iovecs(dev);
496 kthread_stop(worker);
505 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
507 struct vhost_memory *vhost_dev_reset_owner_prepare(void)
509 return kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
511 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
513 /* Caller should have device mutex */
514 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_memory *memory)
518 vhost_dev_cleanup(dev, true);
520 /* Restore memory to default empty mapping. */
521 memory->nregions = 0;
522 dev->memory = memory;
523 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
524 * VQs aren't running.
526 for (i = 0; i < dev->nvqs; ++i)
527 dev->vqs[i]->memory = memory;
529 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
531 void vhost_dev_stop(struct vhost_dev *dev)
535 for (i = 0; i < dev->nvqs; ++i) {
536 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
537 vhost_poll_stop(&dev->vqs[i]->poll);
538 vhost_poll_flush(&dev->vqs[i]->poll);
542 EXPORT_SYMBOL_GPL(vhost_dev_stop);
544 /* Caller should have device mutex if and only if locked is set */
545 void vhost_dev_cleanup(struct vhost_dev *dev, bool locked)
549 for (i = 0; i < dev->nvqs; ++i) {
550 if (dev->vqs[i]->error_ctx)
551 eventfd_ctx_put(dev->vqs[i]->error_ctx);
552 if (dev->vqs[i]->error)
553 fput(dev->vqs[i]->error);
554 if (dev->vqs[i]->kick)
555 fput(dev->vqs[i]->kick);
556 if (dev->vqs[i]->call_ctx)
557 eventfd_ctx_put(dev->vqs[i]->call_ctx);
558 if (dev->vqs[i]->call)
559 fput(dev->vqs[i]->call);
560 vhost_vq_reset(dev, dev->vqs[i]);
562 vhost_dev_free_iovecs(dev);
564 eventfd_ctx_put(dev->log_ctx);
568 dev->log_file = NULL;
569 /* No one will access memory at this point */
572 WARN_ON(!list_empty(&dev->work_list));
574 kthread_stop(dev->worker);
581 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
583 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
585 u64 a = addr / VHOST_PAGE_SIZE / 8;
587 /* Make sure 64 bit math will not overflow. */
588 if (a > ULONG_MAX - (unsigned long)log_base ||
589 a + (unsigned long)log_base > ULONG_MAX)
592 return access_ok(VERIFY_WRITE, log_base + a,
593 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
596 /* Caller should have vq mutex and device mutex. */
597 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
605 for (i = 0; i < mem->nregions; ++i) {
606 struct vhost_memory_region *m = mem->regions + i;
607 unsigned long a = m->userspace_addr;
608 if (m->memory_size > ULONG_MAX)
610 else if (!access_ok(VERIFY_WRITE, (void __user *)a,
613 else if (log_all && !log_access_ok(log_base,
621 /* Can we switch to this memory table? */
622 /* Caller should have device mutex but not vq mutex */
623 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
628 for (i = 0; i < d->nvqs; ++i) {
632 mutex_lock(&d->vqs[i]->mutex);
633 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
634 /* If ring is inactive, will check when it's enabled. */
635 if (d->vqs[i]->private_data)
636 ok = vq_memory_access_ok(d->vqs[i]->log_base, mem, log);
639 mutex_unlock(&d->vqs[i]->mutex);
646 static int vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
647 struct vring_desc __user *desc,
648 struct vring_avail __user *avail,
649 struct vring_used __user *used)
651 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
652 return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
653 access_ok(VERIFY_READ, avail,
654 sizeof *avail + num * sizeof *avail->ring + s) &&
655 access_ok(VERIFY_WRITE, used,
656 sizeof *used + num * sizeof *used->ring + s);
659 /* Can we log writes? */
660 /* Caller should have device mutex but not vq mutex */
661 int vhost_log_access_ok(struct vhost_dev *dev)
663 return memory_access_ok(dev, dev->memory, 1);
665 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
667 /* Verify access for write logging. */
668 /* Caller should have vq mutex and device mutex */
669 static int vq_log_access_ok(struct vhost_virtqueue *vq,
670 void __user *log_base)
672 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
674 return vq_memory_access_ok(log_base, vq->memory,
675 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
676 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
678 vq->num * sizeof *vq->used->ring + s));
681 /* Can we start vq? */
682 /* Caller should have vq mutex and device mutex */
683 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
685 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used) &&
686 vq_log_access_ok(vq, vq->log_base);
688 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
690 static int vhost_memory_reg_sort_cmp(const void *p1, const void *p2)
692 const struct vhost_memory_region *r1 = p1, *r2 = p2;
693 if (r1->guest_phys_addr < r2->guest_phys_addr)
695 if (r1->guest_phys_addr > r2->guest_phys_addr)
700 static void *vhost_kvzalloc(unsigned long size)
702 void *n = kzalloc(size, GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
709 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
711 struct vhost_memory mem, *newmem, *oldmem;
712 unsigned long size = offsetof(struct vhost_memory, regions);
715 if (copy_from_user(&mem, m, size))
719 if (mem.nregions > max_mem_regions)
721 newmem = vhost_kvzalloc(size + mem.nregions * sizeof(*m->regions));
725 memcpy(newmem, &mem, size);
726 if (copy_from_user(newmem->regions, m->regions,
727 mem.nregions * sizeof *m->regions)) {
731 sort(newmem->regions, newmem->nregions, sizeof(*newmem->regions),
732 vhost_memory_reg_sort_cmp, NULL);
734 if (!memory_access_ok(d, newmem, 0)) {
741 /* All memory accesses are done under some VQ mutex. */
742 for (i = 0; i < d->nvqs; ++i) {
743 mutex_lock(&d->vqs[i]->mutex);
744 d->vqs[i]->memory = newmem;
745 mutex_unlock(&d->vqs[i]->mutex);
751 long vhost_vring_ioctl(struct vhost_dev *d, int ioctl, void __user *argp)
753 struct file *eventfp, *filep = NULL;
754 bool pollstart = false, pollstop = false;
755 struct eventfd_ctx *ctx = NULL;
756 u32 __user *idxp = argp;
757 struct vhost_virtqueue *vq;
758 struct vhost_vring_state s;
759 struct vhost_vring_file f;
760 struct vhost_vring_addr a;
764 r = get_user(idx, idxp);
770 idx = array_index_nospec(idx, d->nvqs);
773 mutex_lock(&vq->mutex);
776 case VHOST_SET_VRING_NUM:
777 /* Resizing ring with an active backend?
778 * You don't want to do that. */
779 if (vq->private_data) {
783 if (copy_from_user(&s, argp, sizeof s)) {
787 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
793 case VHOST_SET_VRING_BASE:
794 /* Moving base with an active backend?
795 * You don't want to do that. */
796 if (vq->private_data) {
800 if (copy_from_user(&s, argp, sizeof s)) {
804 if (s.num > 0xffff) {
808 vq->last_avail_idx = s.num;
809 /* Forget the cached index value. */
810 vq->avail_idx = vq->last_avail_idx;
812 case VHOST_GET_VRING_BASE:
814 s.num = vq->last_avail_idx;
815 if (copy_to_user(argp, &s, sizeof s))
818 case VHOST_SET_VRING_ADDR:
819 if (copy_from_user(&a, argp, sizeof a)) {
823 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
827 /* For 32bit, verify that the top 32bits of the user
828 data are set to zero. */
829 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
830 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
831 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
836 /* Make sure it's safe to cast pointers to vring types. */
837 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
838 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
839 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
840 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
841 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1))) {
846 /* We only verify access here if backend is configured.
847 * If it is not, we don't as size might not have been setup.
848 * We will verify when backend is configured. */
849 if (vq->private_data) {
850 if (!vq_access_ok(vq, vq->num,
851 (void __user *)(unsigned long)a.desc_user_addr,
852 (void __user *)(unsigned long)a.avail_user_addr,
853 (void __user *)(unsigned long)a.used_user_addr)) {
858 /* Also validate log access for used ring if enabled. */
859 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
860 !log_access_ok(vq->log_base, a.log_guest_addr,
862 vq->num * sizeof *vq->used->ring)) {
868 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
869 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
870 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
871 vq->log_addr = a.log_guest_addr;
872 vq->used = (void __user *)(unsigned long)a.used_user_addr;
874 case VHOST_SET_VRING_KICK:
875 if (copy_from_user(&f, argp, sizeof f)) {
879 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
880 if (IS_ERR(eventfp)) {
881 r = PTR_ERR(eventfp);
884 if (eventfp != vq->kick) {
885 pollstop = (filep = vq->kick) != NULL;
886 pollstart = (vq->kick = eventfp) != NULL;
890 case VHOST_SET_VRING_CALL:
891 if (copy_from_user(&f, argp, sizeof f)) {
895 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
896 if (IS_ERR(eventfp)) {
897 r = PTR_ERR(eventfp);
900 if (eventfp != vq->call) {
904 vq->call_ctx = eventfp ?
905 eventfd_ctx_fileget(eventfp) : NULL;
909 case VHOST_SET_VRING_ERR:
910 if (copy_from_user(&f, argp, sizeof f)) {
914 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
915 if (IS_ERR(eventfp)) {
916 r = PTR_ERR(eventfp);
919 if (eventfp != vq->error) {
923 vq->error_ctx = eventfp ?
924 eventfd_ctx_fileget(eventfp) : NULL;
928 case VHOST_SET_VRING_ENDIAN:
929 r = vhost_set_vring_endian(vq, argp);
931 case VHOST_GET_VRING_ENDIAN:
932 r = vhost_get_vring_endian(vq, idx, argp);
938 if (pollstop && vq->handle_kick)
939 vhost_poll_stop(&vq->poll);
942 eventfd_ctx_put(ctx);
946 if (pollstart && vq->handle_kick)
947 r = vhost_poll_start(&vq->poll, vq->kick);
949 mutex_unlock(&vq->mutex);
951 if (pollstop && vq->handle_kick)
952 vhost_poll_flush(&vq->poll);
955 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
957 /* Caller must have device mutex */
958 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
960 struct file *eventfp, *filep = NULL;
961 struct eventfd_ctx *ctx = NULL;
966 /* If you are not the owner, you can become one */
967 if (ioctl == VHOST_SET_OWNER) {
968 r = vhost_dev_set_owner(d);
972 /* You must be the owner to do anything else */
973 r = vhost_dev_check_owner(d);
978 case VHOST_SET_MEM_TABLE:
979 r = vhost_set_memory(d, argp);
981 case VHOST_SET_LOG_BASE:
982 if (copy_from_user(&p, argp, sizeof p)) {
986 if ((u64)(unsigned long)p != p) {
990 for (i = 0; i < d->nvqs; ++i) {
991 struct vhost_virtqueue *vq;
992 void __user *base = (void __user *)(unsigned long)p;
994 mutex_lock(&vq->mutex);
995 /* If ring is inactive, will check when it's enabled. */
996 if (vq->private_data && !vq_log_access_ok(vq, base))
1000 mutex_unlock(&vq->mutex);
1003 case VHOST_SET_LOG_FD:
1004 r = get_user(fd, (int __user *)argp);
1007 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
1008 if (IS_ERR(eventfp)) {
1009 r = PTR_ERR(eventfp);
1012 if (eventfp != d->log_file) {
1013 filep = d->log_file;
1014 d->log_file = eventfp;
1016 d->log_ctx = eventfp ?
1017 eventfd_ctx_fileget(eventfp) : NULL;
1020 for (i = 0; i < d->nvqs; ++i) {
1021 mutex_lock(&d->vqs[i]->mutex);
1022 d->vqs[i]->log_ctx = d->log_ctx;
1023 mutex_unlock(&d->vqs[i]->mutex);
1026 eventfd_ctx_put(ctx);
1037 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1039 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
1040 __u64 addr, __u32 len)
1042 const struct vhost_memory_region *reg;
1043 int start = 0, end = mem->nregions;
1045 while (start < end) {
1046 int slot = start + (end - start) / 2;
1047 reg = mem->regions + slot;
1048 if (addr >= reg->guest_phys_addr)
1054 reg = mem->regions + start;
1055 if (addr >= reg->guest_phys_addr &&
1056 reg->guest_phys_addr + reg->memory_size > addr)
1061 /* TODO: This is really inefficient. We need something like get_user()
1062 * (instruction directly accesses the data, with an exception table entry
1063 * returning -EFAULT). See Documentation/x86/exception-tables.txt.
1065 static int set_bit_to_user(int nr, void __user *addr)
1067 unsigned long log = (unsigned long)addr;
1070 int bit = nr + (log % PAGE_SIZE) * 8;
1073 r = get_user_pages_fast(log, 1, 1, &page);
1077 base = kmap_atomic(page);
1079 kunmap_atomic(base);
1080 set_page_dirty_lock(page);
1085 static int log_write(void __user *log_base,
1086 u64 write_address, u64 write_length)
1088 u64 write_page = write_address / VHOST_PAGE_SIZE;
1093 write_length += write_address % VHOST_PAGE_SIZE;
1095 u64 base = (u64)(unsigned long)log_base;
1096 u64 log = base + write_page / 8;
1097 int bit = write_page % 8;
1098 if ((u64)(unsigned long)log != log)
1100 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1103 if (write_length <= VHOST_PAGE_SIZE)
1105 write_length -= VHOST_PAGE_SIZE;
1111 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1112 unsigned int log_num, u64 len)
1116 /* Make sure data written is seen before log. */
1118 for (i = 0; i < log_num; ++i) {
1119 u64 l = min(log[i].len, len);
1120 r = log_write(vq->log_base, log[i].addr, l);
1126 eventfd_signal(vq->log_ctx, 1);
1130 /* Length written exceeds what we have stored. This is a bug. */
1134 EXPORT_SYMBOL_GPL(vhost_log_write);
1136 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1139 if (__put_user(cpu_to_vhost16(vq, vq->used_flags), &vq->used->flags) < 0)
1141 if (unlikely(vq->log_used)) {
1142 /* Make sure the flag is seen before log. */
1144 /* Log used flag write. */
1145 used = &vq->used->flags;
1146 log_write(vq->log_base, vq->log_addr +
1147 (used - (void __user *)vq->used),
1148 sizeof vq->used->flags);
1150 eventfd_signal(vq->log_ctx, 1);
1155 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1157 if (__put_user(cpu_to_vhost16(vq, vq->avail_idx), vhost_avail_event(vq)))
1159 if (unlikely(vq->log_used)) {
1161 /* Make sure the event is seen before log. */
1163 /* Log avail event write */
1164 used = vhost_avail_event(vq);
1165 log_write(vq->log_base, vq->log_addr +
1166 (used - (void __user *)vq->used),
1167 sizeof *vhost_avail_event(vq));
1169 eventfd_signal(vq->log_ctx, 1);
1174 int vhost_init_used(struct vhost_virtqueue *vq)
1176 __virtio16 last_used_idx;
1178 if (!vq->private_data) {
1179 vq->is_le = virtio_legacy_is_little_endian();
1183 vhost_init_is_le(vq);
1185 r = vhost_update_used_flags(vq);
1188 vq->signalled_used_valid = false;
1189 if (!access_ok(VERIFY_READ, &vq->used->idx, sizeof vq->used->idx))
1191 r = __get_user(last_used_idx, &vq->used->idx);
1194 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1197 EXPORT_SYMBOL_GPL(vhost_init_used);
1199 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1200 struct iovec iov[], int iov_size)
1202 const struct vhost_memory_region *reg;
1203 struct vhost_memory *mem;
1209 while ((u64)len > s) {
1211 if (unlikely(ret >= iov_size)) {
1215 reg = find_region(mem, addr, len);
1216 if (unlikely(!reg)) {
1221 size = reg->memory_size - addr + reg->guest_phys_addr;
1222 _iov->iov_len = min((u64)len - s, size);
1223 _iov->iov_base = (void __user *)(unsigned long)
1224 (reg->userspace_addr + addr - reg->guest_phys_addr);
1233 /* Each buffer in the virtqueues is actually a chain of descriptors. This
1234 * function returns the next descriptor in the chain,
1235 * or -1U if we're at the end. */
1236 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1240 /* If this descriptor says it doesn't chain, we're done. */
1241 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1244 /* Check they're not leading us off end of descriptors. */
1245 next = vhost16_to_cpu(vq, desc->next);
1246 /* Make sure compiler knows to grab that: we don't want it changing! */
1247 /* We will use the result as an index in an array, so most
1248 * architectures only need a compiler barrier here. */
1249 read_barrier_depends();
1254 static int get_indirect(struct vhost_virtqueue *vq,
1255 struct iovec iov[], unsigned int iov_size,
1256 unsigned int *out_num, unsigned int *in_num,
1257 struct vhost_log *log, unsigned int *log_num,
1258 struct vring_desc *indirect)
1260 struct vring_desc desc;
1261 unsigned int i = 0, count, found = 0;
1262 u32 len = vhost32_to_cpu(vq, indirect->len);
1263 struct iov_iter from;
1267 if (unlikely(len % sizeof desc)) {
1268 vq_err(vq, "Invalid length in indirect descriptor: "
1269 "len 0x%llx not multiple of 0x%zx\n",
1270 (unsigned long long)len,
1275 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
1277 if (unlikely(ret < 0)) {
1278 vq_err(vq, "Translation failure %d in indirect.\n", ret);
1281 iov_iter_init(&from, READ, vq->indirect, ret, len);
1283 /* We will use the result as an address to read from, so most
1284 * architectures only need a compiler barrier here. */
1285 read_barrier_depends();
1287 count = len / sizeof desc;
1288 /* Buffers are chained via a 16 bit next field, so
1289 * we can have at most 2^16 of these. */
1290 if (unlikely(count > USHRT_MAX + 1)) {
1291 vq_err(vq, "Indirect buffer length too big: %d\n",
1297 unsigned iov_count = *in_num + *out_num;
1298 if (unlikely(++found > count)) {
1299 vq_err(vq, "Loop detected: last one at %u "
1300 "indirect size %u\n",
1304 if (unlikely(copy_from_iter(&desc, sizeof(desc), &from) !=
1306 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1307 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1310 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
1311 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1312 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1316 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1317 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1318 iov_size - iov_count);
1319 if (unlikely(ret < 0)) {
1320 vq_err(vq, "Translation failure %d indirect idx %d\n",
1324 /* If this is an input descriptor, increment that count. */
1325 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1327 if (unlikely(log && ret)) {
1328 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1329 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1333 /* If it's an output descriptor, they're all supposed
1334 * to come before any input descriptors. */
1335 if (unlikely(*in_num)) {
1336 vq_err(vq, "Indirect descriptor "
1337 "has out after in: idx %d\n", i);
1342 } while ((i = next_desc(vq, &desc)) != -1);
1346 /* This looks in the virtqueue and for the first available buffer, and converts
1347 * it to an iovec for convenient access. Since descriptors consist of some
1348 * number of output then some number of input descriptors, it's actually two
1349 * iovecs, but we pack them into one and note how many of each there were.
1351 * This function returns the descriptor number found, or vq->num (which is
1352 * never a valid descriptor number) if none was found. A negative code is
1353 * returned on error. */
1354 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
1355 struct iovec iov[], unsigned int iov_size,
1356 unsigned int *out_num, unsigned int *in_num,
1357 struct vhost_log *log, unsigned int *log_num)
1359 struct vring_desc desc;
1360 unsigned int i, head, found = 0;
1362 __virtio16 avail_idx;
1363 __virtio16 ring_head;
1366 /* Check it isn't doing very strange things with descriptor numbers. */
1367 last_avail_idx = vq->last_avail_idx;
1368 if (unlikely(__get_user(avail_idx, &vq->avail->idx))) {
1369 vq_err(vq, "Failed to access avail idx at %p\n",
1373 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
1375 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1376 vq_err(vq, "Guest moved used index from %u to %u",
1377 last_avail_idx, vq->avail_idx);
1381 /* If there's nothing new since last we looked, return invalid. */
1382 if (vq->avail_idx == last_avail_idx)
1385 /* Only get avail ring entries after they have been exposed by guest. */
1388 /* Grab the next descriptor number they're advertising, and increment
1389 * the index we've seen. */
1390 if (unlikely(__get_user(ring_head,
1391 &vq->avail->ring[last_avail_idx & (vq->num - 1)]))) {
1392 vq_err(vq, "Failed to read head: idx %d address %p\n",
1394 &vq->avail->ring[last_avail_idx % vq->num]);
1398 head = vhost16_to_cpu(vq, ring_head);
1400 /* If their number is silly, that's an error. */
1401 if (unlikely(head >= vq->num)) {
1402 vq_err(vq, "Guest says index %u > %u is available",
1407 /* When we start there are none of either input nor output. */
1408 *out_num = *in_num = 0;
1414 unsigned iov_count = *in_num + *out_num;
1415 if (unlikely(i >= vq->num)) {
1416 vq_err(vq, "Desc index is %u > %u, head = %u",
1420 if (unlikely(++found > vq->num)) {
1421 vq_err(vq, "Loop detected: last one at %u "
1422 "vq size %u head %u\n",
1426 ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
1427 if (unlikely(ret)) {
1428 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1432 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
1433 ret = get_indirect(vq, iov, iov_size,
1435 log, log_num, &desc);
1436 if (unlikely(ret < 0)) {
1437 vq_err(vq, "Failure detected "
1438 "in indirect descriptor at idx %d\n", i);
1444 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1445 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1446 iov_size - iov_count);
1447 if (unlikely(ret < 0)) {
1448 vq_err(vq, "Translation failure %d descriptor idx %d\n",
1452 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1453 /* If this is an input descriptor,
1454 * increment that count. */
1456 if (unlikely(log && ret)) {
1457 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1458 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1462 /* If it's an output descriptor, they're all supposed
1463 * to come before any input descriptors. */
1464 if (unlikely(*in_num)) {
1465 vq_err(vq, "Descriptor has out after in: "
1471 } while ((i = next_desc(vq, &desc)) != -1);
1473 /* On success, increment avail index. */
1474 vq->last_avail_idx++;
1476 /* Assume notifications from guest are disabled at this point,
1477 * if they aren't we would need to update avail_event index. */
1478 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
1481 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
1483 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1484 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1486 vq->last_avail_idx -= n;
1488 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
1490 /* After we've used one of their buffers, we tell them about it. We'll then
1491 * want to notify the guest, using eventfd. */
1492 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1494 struct vring_used_elem heads = {
1495 cpu_to_vhost32(vq, head),
1496 cpu_to_vhost32(vq, len)
1499 return vhost_add_used_n(vq, &heads, 1);
1501 EXPORT_SYMBOL_GPL(vhost_add_used);
1503 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1504 struct vring_used_elem *heads,
1507 struct vring_used_elem __user *used;
1511 start = vq->last_used_idx & (vq->num - 1);
1512 used = vq->used->ring + start;
1514 if (__put_user(heads[0].id, &used->id)) {
1515 vq_err(vq, "Failed to write used id");
1518 if (__put_user(heads[0].len, &used->len)) {
1519 vq_err(vq, "Failed to write used len");
1522 } else if (__copy_to_user(used, heads, count * sizeof *used)) {
1523 vq_err(vq, "Failed to write used");
1526 if (unlikely(vq->log_used)) {
1527 /* Make sure data is seen before log. */
1529 /* Log used ring entry write. */
1530 log_write(vq->log_base,
1532 ((void __user *)used - (void __user *)vq->used),
1533 count * sizeof *used);
1535 old = vq->last_used_idx;
1536 new = (vq->last_used_idx += count);
1537 /* If the driver never bothers to signal in a very long while,
1538 * used index might wrap around. If that happens, invalidate
1539 * signalled_used index we stored. TODO: make sure driver
1540 * signals at least once in 2^16 and remove this. */
1541 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
1542 vq->signalled_used_valid = false;
1546 /* After we've used one of their buffers, we tell them about it. We'll then
1547 * want to notify the guest, using eventfd. */
1548 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1553 start = vq->last_used_idx & (vq->num - 1);
1554 n = vq->num - start;
1556 r = __vhost_add_used_n(vq, heads, n);
1562 r = __vhost_add_used_n(vq, heads, count);
1564 /* Make sure buffer is written before we update index. */
1566 if (__put_user(cpu_to_vhost16(vq, vq->last_used_idx), &vq->used->idx)) {
1567 vq_err(vq, "Failed to increment used idx");
1570 if (unlikely(vq->log_used)) {
1571 /* Make sure used idx is seen before log. */
1573 /* Log used index update. */
1574 log_write(vq->log_base,
1575 vq->log_addr + offsetof(struct vring_used, idx),
1576 sizeof vq->used->idx);
1578 eventfd_signal(vq->log_ctx, 1);
1582 EXPORT_SYMBOL_GPL(vhost_add_used_n);
1584 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1589 /* Flush out used index updates. This is paired
1590 * with the barrier that the Guest executes when enabling
1594 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1595 unlikely(vq->avail_idx == vq->last_avail_idx))
1598 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1600 if (__get_user(flags, &vq->avail->flags)) {
1601 vq_err(vq, "Failed to get flags");
1604 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
1606 old = vq->signalled_used;
1607 v = vq->signalled_used_valid;
1608 new = vq->signalled_used = vq->last_used_idx;
1609 vq->signalled_used_valid = true;
1614 if (__get_user(event, vhost_used_event(vq))) {
1615 vq_err(vq, "Failed to get used event idx");
1618 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
1621 /* This actually signals the guest, using eventfd. */
1622 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1624 /* Signal the Guest tell them we used something up. */
1625 if (vq->call_ctx && vhost_notify(dev, vq))
1626 eventfd_signal(vq->call_ctx, 1);
1628 EXPORT_SYMBOL_GPL(vhost_signal);
1630 /* And here's the combo meal deal. Supersize me! */
1631 void vhost_add_used_and_signal(struct vhost_dev *dev,
1632 struct vhost_virtqueue *vq,
1633 unsigned int head, int len)
1635 vhost_add_used(vq, head, len);
1636 vhost_signal(dev, vq);
1638 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
1640 /* multi-buffer version of vhost_add_used_and_signal */
1641 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1642 struct vhost_virtqueue *vq,
1643 struct vring_used_elem *heads, unsigned count)
1645 vhost_add_used_n(vq, heads, count);
1646 vhost_signal(dev, vq);
1648 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
1650 /* OK, now we need to know about added descriptors. */
1651 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1653 __virtio16 avail_idx;
1656 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1658 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1659 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1660 r = vhost_update_used_flags(vq);
1662 vq_err(vq, "Failed to enable notification at %p: %d\n",
1663 &vq->used->flags, r);
1667 r = vhost_update_avail_event(vq, vq->avail_idx);
1669 vq_err(vq, "Failed to update avail event index at %p: %d\n",
1670 vhost_avail_event(vq), r);
1674 /* They could have slipped one in as we were doing that: make
1675 * sure it's written, then check again. */
1677 r = __get_user(avail_idx, &vq->avail->idx);
1679 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1680 &vq->avail->idx, r);
1684 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
1686 EXPORT_SYMBOL_GPL(vhost_enable_notify);
1688 /* We don't need to be notified again. */
1689 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1693 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1695 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1696 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1697 r = vhost_update_used_flags(vq);
1699 vq_err(vq, "Failed to enable notification at %p: %d\n",
1700 &vq->used->flags, r);
1703 EXPORT_SYMBOL_GPL(vhost_disable_notify);
1705 static int __init vhost_init(void)
1710 static void __exit vhost_exit(void)
1714 module_init(vhost_init);
1715 module_exit(vhost_exit);
1717 MODULE_VERSION("0.0.1");
1718 MODULE_LICENSE("GPL v2");
1719 MODULE_AUTHOR("Michael S. Tsirkin");
1720 MODULE_DESCRIPTION("Host kernel accelerator for virtio");