ceph: save peer feature bits in connection structure
[linux-2.6.git] / drivers / vhost / vhost.c
blob49fa953aaf6e354be77e47ff708f8677cc58026b
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>
17 #include <linux/mm.h>
18 #include <linux/miscdevice.h>
19 #include <linux/mutex.h>
20 #include <linux/workqueue.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>
27 #include <linux/net.h>
28 #include <linux/if_packet.h>
29 #include <linux/if_arp.h>
31 #include <net/sock.h>
33 #include "vhost.h"
35 enum {
36 VHOST_MEMORY_MAX_NREGIONS = 64,
37 VHOST_MEMORY_F_LOG = 0x1,
40 static struct workqueue_struct *vhost_workqueue;
42 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
43 poll_table *pt)
45 struct vhost_poll *poll;
46 poll = container_of(pt, struct vhost_poll, table);
48 poll->wqh = wqh;
49 add_wait_queue(wqh, &poll->wait);
52 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
53 void *key)
55 struct vhost_poll *poll;
56 poll = container_of(wait, struct vhost_poll, wait);
57 if (!((unsigned long)key & poll->mask))
58 return 0;
60 queue_work(vhost_workqueue, &poll->work);
61 return 0;
64 /* Init poll structure */
65 void vhost_poll_init(struct vhost_poll *poll, work_func_t func,
66 unsigned long mask)
68 INIT_WORK(&poll->work, func);
69 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
70 init_poll_funcptr(&poll->table, vhost_poll_func);
71 poll->mask = mask;
74 /* Start polling a file. We add ourselves to file's wait queue. The caller must
75 * keep a reference to a file until after vhost_poll_stop is called. */
76 void vhost_poll_start(struct vhost_poll *poll, struct file *file)
78 unsigned long mask;
79 mask = file->f_op->poll(file, &poll->table);
80 if (mask)
81 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
84 /* Stop polling a file. After this function returns, it becomes safe to drop the
85 * file reference. You must also flush afterwards. */
86 void vhost_poll_stop(struct vhost_poll *poll)
88 remove_wait_queue(poll->wqh, &poll->wait);
91 /* Flush any work that has been scheduled. When calling this, don't hold any
92 * locks that are also used by the callback. */
93 void vhost_poll_flush(struct vhost_poll *poll)
95 flush_work(&poll->work);
98 void vhost_poll_queue(struct vhost_poll *poll)
100 queue_work(vhost_workqueue, &poll->work);
103 static void vhost_vq_reset(struct vhost_dev *dev,
104 struct vhost_virtqueue *vq)
106 vq->num = 1;
107 vq->desc = NULL;
108 vq->avail = NULL;
109 vq->used = NULL;
110 vq->last_avail_idx = 0;
111 vq->avail_idx = 0;
112 vq->last_used_idx = 0;
113 vq->used_flags = 0;
114 vq->used_flags = 0;
115 vq->log_used = false;
116 vq->log_addr = -1ull;
117 vq->hdr_size = 0;
118 vq->private_data = NULL;
119 vq->log_base = NULL;
120 vq->error_ctx = NULL;
121 vq->error = NULL;
122 vq->kick = NULL;
123 vq->call_ctx = NULL;
124 vq->call = NULL;
125 vq->log_ctx = NULL;
128 long vhost_dev_init(struct vhost_dev *dev,
129 struct vhost_virtqueue *vqs, int nvqs)
131 int i;
132 dev->vqs = vqs;
133 dev->nvqs = nvqs;
134 mutex_init(&dev->mutex);
135 dev->log_ctx = NULL;
136 dev->log_file = NULL;
137 dev->memory = NULL;
138 dev->mm = NULL;
140 for (i = 0; i < dev->nvqs; ++i) {
141 dev->vqs[i].dev = dev;
142 mutex_init(&dev->vqs[i].mutex);
143 vhost_vq_reset(dev, dev->vqs + i);
144 if (dev->vqs[i].handle_kick)
145 vhost_poll_init(&dev->vqs[i].poll,
146 dev->vqs[i].handle_kick,
147 POLLIN);
149 return 0;
152 /* Caller should have device mutex */
153 long vhost_dev_check_owner(struct vhost_dev *dev)
155 /* Are you the owner? If not, I don't think you mean to do that */
156 return dev->mm == current->mm ? 0 : -EPERM;
159 /* Caller should have device mutex */
160 static long vhost_dev_set_owner(struct vhost_dev *dev)
162 /* Is there an owner already? */
163 if (dev->mm)
164 return -EBUSY;
165 /* No owner, become one */
166 dev->mm = get_task_mm(current);
167 return 0;
170 /* Caller should have device mutex */
171 long vhost_dev_reset_owner(struct vhost_dev *dev)
173 struct vhost_memory *memory;
175 /* Restore memory to default empty mapping. */
176 memory = kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
177 if (!memory)
178 return -ENOMEM;
180 vhost_dev_cleanup(dev);
182 memory->nregions = 0;
183 dev->memory = memory;
184 return 0;
187 /* Caller should have device mutex */
188 void vhost_dev_cleanup(struct vhost_dev *dev)
190 int i;
191 for (i = 0; i < dev->nvqs; ++i) {
192 if (dev->vqs[i].kick && dev->vqs[i].handle_kick) {
193 vhost_poll_stop(&dev->vqs[i].poll);
194 vhost_poll_flush(&dev->vqs[i].poll);
196 if (dev->vqs[i].error_ctx)
197 eventfd_ctx_put(dev->vqs[i].error_ctx);
198 if (dev->vqs[i].error)
199 fput(dev->vqs[i].error);
200 if (dev->vqs[i].kick)
201 fput(dev->vqs[i].kick);
202 if (dev->vqs[i].call_ctx)
203 eventfd_ctx_put(dev->vqs[i].call_ctx);
204 if (dev->vqs[i].call)
205 fput(dev->vqs[i].call);
206 vhost_vq_reset(dev, dev->vqs + i);
208 if (dev->log_ctx)
209 eventfd_ctx_put(dev->log_ctx);
210 dev->log_ctx = NULL;
211 if (dev->log_file)
212 fput(dev->log_file);
213 dev->log_file = NULL;
214 /* No one will access memory at this point */
215 kfree(dev->memory);
216 dev->memory = NULL;
217 if (dev->mm)
218 mmput(dev->mm);
219 dev->mm = NULL;
222 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
224 u64 a = addr / VHOST_PAGE_SIZE / 8;
225 /* Make sure 64 bit math will not overflow. */
226 if (a > ULONG_MAX - (unsigned long)log_base ||
227 a + (unsigned long)log_base > ULONG_MAX)
228 return -EFAULT;
230 return access_ok(VERIFY_WRITE, log_base + a,
231 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
234 /* Caller should have vq mutex and device mutex. */
235 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
236 int log_all)
238 int i;
240 if (!mem)
241 return 0;
243 for (i = 0; i < mem->nregions; ++i) {
244 struct vhost_memory_region *m = mem->regions + i;
245 unsigned long a = m->userspace_addr;
246 if (m->memory_size > ULONG_MAX)
247 return 0;
248 else if (!access_ok(VERIFY_WRITE, (void __user *)a,
249 m->memory_size))
250 return 0;
251 else if (log_all && !log_access_ok(log_base,
252 m->guest_phys_addr,
253 m->memory_size))
254 return 0;
256 return 1;
259 /* Can we switch to this memory table? */
260 /* Caller should have device mutex but not vq mutex */
261 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
262 int log_all)
264 int i;
265 for (i = 0; i < d->nvqs; ++i) {
266 int ok;
267 mutex_lock(&d->vqs[i].mutex);
268 /* If ring is inactive, will check when it's enabled. */
269 if (d->vqs[i].private_data)
270 ok = vq_memory_access_ok(d->vqs[i].log_base, mem,
271 log_all);
272 else
273 ok = 1;
274 mutex_unlock(&d->vqs[i].mutex);
275 if (!ok)
276 return 0;
278 return 1;
281 static int vq_access_ok(unsigned int num,
282 struct vring_desc __user *desc,
283 struct vring_avail __user *avail,
284 struct vring_used __user *used)
286 return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
287 access_ok(VERIFY_READ, avail,
288 sizeof *avail + num * sizeof *avail->ring) &&
289 access_ok(VERIFY_WRITE, used,
290 sizeof *used + num * sizeof *used->ring);
293 /* Can we log writes? */
294 /* Caller should have device mutex but not vq mutex */
295 int vhost_log_access_ok(struct vhost_dev *dev)
297 return memory_access_ok(dev, dev->memory, 1);
300 /* Verify access for write logging. */
301 /* Caller should have vq mutex and device mutex */
302 static int vq_log_access_ok(struct vhost_virtqueue *vq, void __user *log_base)
304 return vq_memory_access_ok(log_base, vq->dev->memory,
305 vhost_has_feature(vq->dev, VHOST_F_LOG_ALL)) &&
306 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
307 sizeof *vq->used +
308 vq->num * sizeof *vq->used->ring));
311 /* Can we start vq? */
312 /* Caller should have vq mutex and device mutex */
313 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
315 return vq_access_ok(vq->num, vq->desc, vq->avail, vq->used) &&
316 vq_log_access_ok(vq, vq->log_base);
319 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
321 struct vhost_memory mem, *newmem, *oldmem;
322 unsigned long size = offsetof(struct vhost_memory, regions);
323 long r;
324 r = copy_from_user(&mem, m, size);
325 if (r)
326 return r;
327 if (mem.padding)
328 return -EOPNOTSUPP;
329 if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
330 return -E2BIG;
331 newmem = kmalloc(size + mem.nregions * sizeof *m->regions, GFP_KERNEL);
332 if (!newmem)
333 return -ENOMEM;
335 memcpy(newmem, &mem, size);
336 r = copy_from_user(newmem->regions, m->regions,
337 mem.nregions * sizeof *m->regions);
338 if (r) {
339 kfree(newmem);
340 return r;
343 if (!memory_access_ok(d, newmem, vhost_has_feature(d, VHOST_F_LOG_ALL)))
344 return -EFAULT;
345 oldmem = d->memory;
346 rcu_assign_pointer(d->memory, newmem);
347 synchronize_rcu();
348 kfree(oldmem);
349 return 0;
352 static int init_used(struct vhost_virtqueue *vq,
353 struct vring_used __user *used)
355 int r = put_user(vq->used_flags, &used->flags);
356 if (r)
357 return r;
358 return get_user(vq->last_used_idx, &used->idx);
361 static long vhost_set_vring(struct vhost_dev *d, int ioctl, void __user *argp)
363 struct file *eventfp, *filep = NULL,
364 *pollstart = NULL, *pollstop = NULL;
365 struct eventfd_ctx *ctx = NULL;
366 u32 __user *idxp = argp;
367 struct vhost_virtqueue *vq;
368 struct vhost_vring_state s;
369 struct vhost_vring_file f;
370 struct vhost_vring_addr a;
371 u32 idx;
372 long r;
374 r = get_user(idx, idxp);
375 if (r < 0)
376 return r;
377 if (idx > d->nvqs)
378 return -ENOBUFS;
380 vq = d->vqs + idx;
382 mutex_lock(&vq->mutex);
384 switch (ioctl) {
385 case VHOST_SET_VRING_NUM:
386 /* Resizing ring with an active backend?
387 * You don't want to do that. */
388 if (vq->private_data) {
389 r = -EBUSY;
390 break;
392 r = copy_from_user(&s, argp, sizeof s);
393 if (r < 0)
394 break;
395 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
396 r = -EINVAL;
397 break;
399 vq->num = s.num;
400 break;
401 case VHOST_SET_VRING_BASE:
402 /* Moving base with an active backend?
403 * You don't want to do that. */
404 if (vq->private_data) {
405 r = -EBUSY;
406 break;
408 r = copy_from_user(&s, argp, sizeof s);
409 if (r < 0)
410 break;
411 if (s.num > 0xffff) {
412 r = -EINVAL;
413 break;
415 vq->last_avail_idx = s.num;
416 /* Forget the cached index value. */
417 vq->avail_idx = vq->last_avail_idx;
418 break;
419 case VHOST_GET_VRING_BASE:
420 s.index = idx;
421 s.num = vq->last_avail_idx;
422 r = copy_to_user(argp, &s, sizeof s);
423 break;
424 case VHOST_SET_VRING_ADDR:
425 r = copy_from_user(&a, argp, sizeof a);
426 if (r < 0)
427 break;
428 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
429 r = -EOPNOTSUPP;
430 break;
432 /* For 32bit, verify that the top 32bits of the user
433 data are set to zero. */
434 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
435 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
436 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
437 r = -EFAULT;
438 break;
440 if ((a.avail_user_addr & (sizeof *vq->avail->ring - 1)) ||
441 (a.used_user_addr & (sizeof *vq->used->ring - 1)) ||
442 (a.log_guest_addr & (sizeof *vq->used->ring - 1))) {
443 r = -EINVAL;
444 break;
447 /* We only verify access here if backend is configured.
448 * If it is not, we don't as size might not have been setup.
449 * We will verify when backend is configured. */
450 if (vq->private_data) {
451 if (!vq_access_ok(vq->num,
452 (void __user *)(unsigned long)a.desc_user_addr,
453 (void __user *)(unsigned long)a.avail_user_addr,
454 (void __user *)(unsigned long)a.used_user_addr)) {
455 r = -EINVAL;
456 break;
459 /* Also validate log access for used ring if enabled. */
460 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
461 !log_access_ok(vq->log_base, a.log_guest_addr,
462 sizeof *vq->used +
463 vq->num * sizeof *vq->used->ring)) {
464 r = -EINVAL;
465 break;
469 r = init_used(vq, (struct vring_used __user *)(unsigned long)
470 a.used_user_addr);
471 if (r)
472 break;
473 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
474 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
475 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
476 vq->log_addr = a.log_guest_addr;
477 vq->used = (void __user *)(unsigned long)a.used_user_addr;
478 break;
479 case VHOST_SET_VRING_KICK:
480 r = copy_from_user(&f, argp, sizeof f);
481 if (r < 0)
482 break;
483 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
484 if (IS_ERR(eventfp)) {
485 r = PTR_ERR(eventfp);
486 break;
488 if (eventfp != vq->kick) {
489 pollstop = filep = vq->kick;
490 pollstart = vq->kick = eventfp;
491 } else
492 filep = eventfp;
493 break;
494 case VHOST_SET_VRING_CALL:
495 r = copy_from_user(&f, argp, sizeof f);
496 if (r < 0)
497 break;
498 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
499 if (IS_ERR(eventfp)) {
500 r = PTR_ERR(eventfp);
501 break;
503 if (eventfp != vq->call) {
504 filep = vq->call;
505 ctx = vq->call_ctx;
506 vq->call = eventfp;
507 vq->call_ctx = eventfp ?
508 eventfd_ctx_fileget(eventfp) : NULL;
509 } else
510 filep = eventfp;
511 break;
512 case VHOST_SET_VRING_ERR:
513 r = copy_from_user(&f, argp, sizeof f);
514 if (r < 0)
515 break;
516 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
517 if (IS_ERR(eventfp)) {
518 r = PTR_ERR(eventfp);
519 break;
521 if (eventfp != vq->error) {
522 filep = vq->error;
523 vq->error = eventfp;
524 ctx = vq->error_ctx;
525 vq->error_ctx = eventfp ?
526 eventfd_ctx_fileget(eventfp) : NULL;
527 } else
528 filep = eventfp;
529 break;
530 default:
531 r = -ENOIOCTLCMD;
534 if (pollstop && vq->handle_kick)
535 vhost_poll_stop(&vq->poll);
537 if (ctx)
538 eventfd_ctx_put(ctx);
539 if (filep)
540 fput(filep);
542 if (pollstart && vq->handle_kick)
543 vhost_poll_start(&vq->poll, vq->kick);
545 mutex_unlock(&vq->mutex);
547 if (pollstop && vq->handle_kick)
548 vhost_poll_flush(&vq->poll);
549 return r;
552 /* Caller must have device mutex */
553 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, unsigned long arg)
555 void __user *argp = (void __user *)arg;
556 struct file *eventfp, *filep = NULL;
557 struct eventfd_ctx *ctx = NULL;
558 u64 p;
559 long r;
560 int i, fd;
562 /* If you are not the owner, you can become one */
563 if (ioctl == VHOST_SET_OWNER) {
564 r = vhost_dev_set_owner(d);
565 goto done;
568 /* You must be the owner to do anything else */
569 r = vhost_dev_check_owner(d);
570 if (r)
571 goto done;
573 switch (ioctl) {
574 case VHOST_SET_MEM_TABLE:
575 r = vhost_set_memory(d, argp);
576 break;
577 case VHOST_SET_LOG_BASE:
578 r = copy_from_user(&p, argp, sizeof p);
579 if (r < 0)
580 break;
581 if ((u64)(unsigned long)p != p) {
582 r = -EFAULT;
583 break;
585 for (i = 0; i < d->nvqs; ++i) {
586 struct vhost_virtqueue *vq;
587 void __user *base = (void __user *)(unsigned long)p;
588 vq = d->vqs + i;
589 mutex_lock(&vq->mutex);
590 /* If ring is inactive, will check when it's enabled. */
591 if (vq->private_data && !vq_log_access_ok(vq, base))
592 r = -EFAULT;
593 else
594 vq->log_base = base;
595 mutex_unlock(&vq->mutex);
597 break;
598 case VHOST_SET_LOG_FD:
599 r = get_user(fd, (int __user *)argp);
600 if (r < 0)
601 break;
602 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
603 if (IS_ERR(eventfp)) {
604 r = PTR_ERR(eventfp);
605 break;
607 if (eventfp != d->log_file) {
608 filep = d->log_file;
609 ctx = d->log_ctx;
610 d->log_ctx = eventfp ?
611 eventfd_ctx_fileget(eventfp) : NULL;
612 } else
613 filep = eventfp;
614 for (i = 0; i < d->nvqs; ++i) {
615 mutex_lock(&d->vqs[i].mutex);
616 d->vqs[i].log_ctx = d->log_ctx;
617 mutex_unlock(&d->vqs[i].mutex);
619 if (ctx)
620 eventfd_ctx_put(ctx);
621 if (filep)
622 fput(filep);
623 break;
624 default:
625 r = vhost_set_vring(d, ioctl, argp);
626 break;
628 done:
629 return r;
632 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
633 __u64 addr, __u32 len)
635 struct vhost_memory_region *reg;
636 int i;
637 /* linear search is not brilliant, but we really have on the order of 6
638 * regions in practice */
639 for (i = 0; i < mem->nregions; ++i) {
640 reg = mem->regions + i;
641 if (reg->guest_phys_addr <= addr &&
642 reg->guest_phys_addr + reg->memory_size - 1 >= addr)
643 return reg;
645 return NULL;
648 /* TODO: This is really inefficient. We need something like get_user()
649 * (instruction directly accesses the data, with an exception table entry
650 * returning -EFAULT). See Documentation/x86/exception-tables.txt.
652 static int set_bit_to_user(int nr, void __user *addr)
654 unsigned long log = (unsigned long)addr;
655 struct page *page;
656 void *base;
657 int bit = nr + (log % PAGE_SIZE) * 8;
658 int r;
659 r = get_user_pages_fast(log, 1, 1, &page);
660 if (r < 0)
661 return r;
662 BUG_ON(r != 1);
663 base = kmap_atomic(page, KM_USER0);
664 set_bit(bit, base);
665 kunmap_atomic(base, KM_USER0);
666 set_page_dirty_lock(page);
667 put_page(page);
668 return 0;
671 static int log_write(void __user *log_base,
672 u64 write_address, u64 write_length)
674 int r;
675 if (!write_length)
676 return 0;
677 write_address /= VHOST_PAGE_SIZE;
678 for (;;) {
679 u64 base = (u64)(unsigned long)log_base;
680 u64 log = base + write_address / 8;
681 int bit = write_address % 8;
682 if ((u64)(unsigned long)log != log)
683 return -EFAULT;
684 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
685 if (r < 0)
686 return r;
687 if (write_length <= VHOST_PAGE_SIZE)
688 break;
689 write_length -= VHOST_PAGE_SIZE;
690 write_address += VHOST_PAGE_SIZE;
692 return r;
695 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
696 unsigned int log_num, u64 len)
698 int i, r;
700 /* Make sure data written is seen before log. */
701 smp_wmb();
702 for (i = 0; i < log_num; ++i) {
703 u64 l = min(log[i].len, len);
704 r = log_write(vq->log_base, log[i].addr, l);
705 if (r < 0)
706 return r;
707 len -= l;
708 if (!len)
709 return 0;
711 if (vq->log_ctx)
712 eventfd_signal(vq->log_ctx, 1);
713 /* Length written exceeds what we have stored. This is a bug. */
714 BUG();
715 return 0;
718 int translate_desc(struct vhost_dev *dev, u64 addr, u32 len,
719 struct iovec iov[], int iov_size)
721 const struct vhost_memory_region *reg;
722 struct vhost_memory *mem;
723 struct iovec *_iov;
724 u64 s = 0;
725 int ret = 0;
727 rcu_read_lock();
729 mem = rcu_dereference(dev->memory);
730 while ((u64)len > s) {
731 u64 size;
732 if (ret >= iov_size) {
733 ret = -ENOBUFS;
734 break;
736 reg = find_region(mem, addr, len);
737 if (!reg) {
738 ret = -EFAULT;
739 break;
741 _iov = iov + ret;
742 size = reg->memory_size - addr + reg->guest_phys_addr;
743 _iov->iov_len = min((u64)len, size);
744 _iov->iov_base = (void *)(unsigned long)
745 (reg->userspace_addr + addr - reg->guest_phys_addr);
746 s += size;
747 addr += size;
748 ++ret;
751 rcu_read_unlock();
752 return ret;
755 /* Each buffer in the virtqueues is actually a chain of descriptors. This
756 * function returns the next descriptor in the chain,
757 * or -1U if we're at the end. */
758 static unsigned next_desc(struct vring_desc *desc)
760 unsigned int next;
762 /* If this descriptor says it doesn't chain, we're done. */
763 if (!(desc->flags & VRING_DESC_F_NEXT))
764 return -1U;
766 /* Check they're not leading us off end of descriptors. */
767 next = desc->next;
768 /* Make sure compiler knows to grab that: we don't want it changing! */
769 /* We will use the result as an index in an array, so most
770 * architectures only need a compiler barrier here. */
771 read_barrier_depends();
773 return next;
776 static unsigned get_indirect(struct vhost_dev *dev, struct vhost_virtqueue *vq,
777 struct iovec iov[], unsigned int iov_size,
778 unsigned int *out_num, unsigned int *in_num,
779 struct vhost_log *log, unsigned int *log_num,
780 struct vring_desc *indirect)
782 struct vring_desc desc;
783 unsigned int i = 0, count, found = 0;
784 int ret;
786 /* Sanity check */
787 if (indirect->len % sizeof desc) {
788 vq_err(vq, "Invalid length in indirect descriptor: "
789 "len 0x%llx not multiple of 0x%zx\n",
790 (unsigned long long)indirect->len,
791 sizeof desc);
792 return -EINVAL;
795 ret = translate_desc(dev, indirect->addr, indirect->len, vq->indirect,
796 ARRAY_SIZE(vq->indirect));
797 if (ret < 0) {
798 vq_err(vq, "Translation failure %d in indirect.\n", ret);
799 return ret;
802 /* We will use the result as an address to read from, so most
803 * architectures only need a compiler barrier here. */
804 read_barrier_depends();
806 count = indirect->len / sizeof desc;
807 /* Buffers are chained via a 16 bit next field, so
808 * we can have at most 2^16 of these. */
809 if (count > USHORT_MAX + 1) {
810 vq_err(vq, "Indirect buffer length too big: %d\n",
811 indirect->len);
812 return -E2BIG;
815 do {
816 unsigned iov_count = *in_num + *out_num;
817 if (++found > count) {
818 vq_err(vq, "Loop detected: last one at %u "
819 "indirect size %u\n",
820 i, count);
821 return -EINVAL;
823 if (memcpy_fromiovec((unsigned char *)&desc, vq->indirect,
824 sizeof desc)) {
825 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
826 i, (size_t)indirect->addr + i * sizeof desc);
827 return -EINVAL;
829 if (desc.flags & VRING_DESC_F_INDIRECT) {
830 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
831 i, (size_t)indirect->addr + i * sizeof desc);
832 return -EINVAL;
835 ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
836 iov_size - iov_count);
837 if (ret < 0) {
838 vq_err(vq, "Translation failure %d indirect idx %d\n",
839 ret, i);
840 return ret;
842 /* If this is an input descriptor, increment that count. */
843 if (desc.flags & VRING_DESC_F_WRITE) {
844 *in_num += ret;
845 if (unlikely(log)) {
846 log[*log_num].addr = desc.addr;
847 log[*log_num].len = desc.len;
848 ++*log_num;
850 } else {
851 /* If it's an output descriptor, they're all supposed
852 * to come before any input descriptors. */
853 if (*in_num) {
854 vq_err(vq, "Indirect descriptor "
855 "has out after in: idx %d\n", i);
856 return -EINVAL;
858 *out_num += ret;
860 } while ((i = next_desc(&desc)) != -1);
861 return 0;
864 /* This looks in the virtqueue and for the first available buffer, and converts
865 * it to an iovec for convenient access. Since descriptors consist of some
866 * number of output then some number of input descriptors, it's actually two
867 * iovecs, but we pack them into one and note how many of each there were.
869 * This function returns the descriptor number found, or vq->num (which
870 * is never a valid descriptor number) if none was found. */
871 unsigned vhost_get_vq_desc(struct vhost_dev *dev, struct vhost_virtqueue *vq,
872 struct iovec iov[], unsigned int iov_size,
873 unsigned int *out_num, unsigned int *in_num,
874 struct vhost_log *log, unsigned int *log_num)
876 struct vring_desc desc;
877 unsigned int i, head, found = 0;
878 u16 last_avail_idx;
879 int ret;
881 /* Check it isn't doing very strange things with descriptor numbers. */
882 last_avail_idx = vq->last_avail_idx;
883 if (get_user(vq->avail_idx, &vq->avail->idx)) {
884 vq_err(vq, "Failed to access avail idx at %p\n",
885 &vq->avail->idx);
886 return vq->num;
889 if ((u16)(vq->avail_idx - last_avail_idx) > vq->num) {
890 vq_err(vq, "Guest moved used index from %u to %u",
891 last_avail_idx, vq->avail_idx);
892 return vq->num;
895 /* If there's nothing new since last we looked, return invalid. */
896 if (vq->avail_idx == last_avail_idx)
897 return vq->num;
899 /* Only get avail ring entries after they have been exposed by guest. */
900 smp_rmb();
902 /* Grab the next descriptor number they're advertising, and increment
903 * the index we've seen. */
904 if (get_user(head, &vq->avail->ring[last_avail_idx % vq->num])) {
905 vq_err(vq, "Failed to read head: idx %d address %p\n",
906 last_avail_idx,
907 &vq->avail->ring[last_avail_idx % vq->num]);
908 return vq->num;
911 /* If their number is silly, that's an error. */
912 if (head >= vq->num) {
913 vq_err(vq, "Guest says index %u > %u is available",
914 head, vq->num);
915 return vq->num;
918 /* When we start there are none of either input nor output. */
919 *out_num = *in_num = 0;
920 if (unlikely(log))
921 *log_num = 0;
923 i = head;
924 do {
925 unsigned iov_count = *in_num + *out_num;
926 if (i >= vq->num) {
927 vq_err(vq, "Desc index is %u > %u, head = %u",
928 i, vq->num, head);
929 return vq->num;
931 if (++found > vq->num) {
932 vq_err(vq, "Loop detected: last one at %u "
933 "vq size %u head %u\n",
934 i, vq->num, head);
935 return vq->num;
937 ret = copy_from_user(&desc, vq->desc + i, sizeof desc);
938 if (ret) {
939 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
940 i, vq->desc + i);
941 return vq->num;
943 if (desc.flags & VRING_DESC_F_INDIRECT) {
944 ret = get_indirect(dev, vq, iov, iov_size,
945 out_num, in_num,
946 log, log_num, &desc);
947 if (ret < 0) {
948 vq_err(vq, "Failure detected "
949 "in indirect descriptor at idx %d\n", i);
950 return vq->num;
952 continue;
955 ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
956 iov_size - iov_count);
957 if (ret < 0) {
958 vq_err(vq, "Translation failure %d descriptor idx %d\n",
959 ret, i);
960 return vq->num;
962 if (desc.flags & VRING_DESC_F_WRITE) {
963 /* If this is an input descriptor,
964 * increment that count. */
965 *in_num += ret;
966 if (unlikely(log)) {
967 log[*log_num].addr = desc.addr;
968 log[*log_num].len = desc.len;
969 ++*log_num;
971 } else {
972 /* If it's an output descriptor, they're all supposed
973 * to come before any input descriptors. */
974 if (*in_num) {
975 vq_err(vq, "Descriptor has out after in: "
976 "idx %d\n", i);
977 return vq->num;
979 *out_num += ret;
981 } while ((i = next_desc(&desc)) != -1);
983 /* On success, increment avail index. */
984 vq->last_avail_idx++;
985 return head;
988 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
989 void vhost_discard_vq_desc(struct vhost_virtqueue *vq)
991 vq->last_avail_idx--;
994 /* After we've used one of their buffers, we tell them about it. We'll then
995 * want to notify the guest, using eventfd. */
996 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
998 struct vring_used_elem *used;
1000 /* The virtqueue contains a ring of used buffers. Get a pointer to the
1001 * next entry in that used ring. */
1002 used = &vq->used->ring[vq->last_used_idx % vq->num];
1003 if (put_user(head, &used->id)) {
1004 vq_err(vq, "Failed to write used id");
1005 return -EFAULT;
1007 if (put_user(len, &used->len)) {
1008 vq_err(vq, "Failed to write used len");
1009 return -EFAULT;
1011 /* Make sure buffer is written before we update index. */
1012 smp_wmb();
1013 if (put_user(vq->last_used_idx + 1, &vq->used->idx)) {
1014 vq_err(vq, "Failed to increment used idx");
1015 return -EFAULT;
1017 if (unlikely(vq->log_used)) {
1018 /* Make sure data is seen before log. */
1019 smp_wmb();
1020 /* Log used ring entry write. */
1021 log_write(vq->log_base,
1022 vq->log_addr + ((void *)used - (void *)vq->used),
1023 sizeof *used);
1024 /* Log used index update. */
1025 log_write(vq->log_base,
1026 vq->log_addr + offsetof(struct vring_used, idx),
1027 sizeof vq->used->idx);
1028 if (vq->log_ctx)
1029 eventfd_signal(vq->log_ctx, 1);
1031 vq->last_used_idx++;
1032 return 0;
1035 /* This actually signals the guest, using eventfd. */
1036 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1038 __u16 flags;
1039 /* Flush out used index updates. This is paired
1040 * with the barrier that the Guest executes when enabling
1041 * interrupts. */
1042 smp_mb();
1044 if (get_user(flags, &vq->avail->flags)) {
1045 vq_err(vq, "Failed to get flags");
1046 return;
1049 /* If they don't want an interrupt, don't signal, unless empty. */
1050 if ((flags & VRING_AVAIL_F_NO_INTERRUPT) &&
1051 (vq->avail_idx != vq->last_avail_idx ||
1052 !vhost_has_feature(dev, VIRTIO_F_NOTIFY_ON_EMPTY)))
1053 return;
1055 /* Signal the Guest tell them we used something up. */
1056 if (vq->call_ctx)
1057 eventfd_signal(vq->call_ctx, 1);
1060 /* And here's the combo meal deal. Supersize me! */
1061 void vhost_add_used_and_signal(struct vhost_dev *dev,
1062 struct vhost_virtqueue *vq,
1063 unsigned int head, int len)
1065 vhost_add_used(vq, head, len);
1066 vhost_signal(dev, vq);
1069 /* OK, now we need to know about added descriptors. */
1070 bool vhost_enable_notify(struct vhost_virtqueue *vq)
1072 u16 avail_idx;
1073 int r;
1074 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1075 return false;
1076 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1077 r = put_user(vq->used_flags, &vq->used->flags);
1078 if (r) {
1079 vq_err(vq, "Failed to enable notification at %p: %d\n",
1080 &vq->used->flags, r);
1081 return false;
1083 /* They could have slipped one in as we were doing that: make
1084 * sure it's written, then check again. */
1085 smp_mb();
1086 r = get_user(avail_idx, &vq->avail->idx);
1087 if (r) {
1088 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1089 &vq->avail->idx, r);
1090 return false;
1093 return avail_idx != vq->last_avail_idx;
1096 /* We don't need to be notified again. */
1097 void vhost_disable_notify(struct vhost_virtqueue *vq)
1099 int r;
1100 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1101 return;
1102 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1103 r = put_user(vq->used_flags, &vq->used->flags);
1104 if (r)
1105 vq_err(vq, "Failed to enable notification at %p: %d\n",
1106 &vq->used->flags, r);
1109 int vhost_init(void)
1111 vhost_workqueue = create_singlethread_workqueue("vhost");
1112 if (!vhost_workqueue)
1113 return -ENOMEM;
1114 return 0;
1117 void vhost_cleanup(void)
1119 destroy_workqueue(vhost_workqueue);