]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - drivers/vhost/vhost.c
vhost: introduce vhost_vq_avail_empty()
[mirror_ubuntu-bionic-kernel.git] / drivers / vhost / vhost.c
1 /* Copyright (C) 2009 Red Hat, Inc.
2 * Copyright (C) 2006 Rusty Russell IBM Corporation
3 *
4 * Author: Michael S. Tsirkin <mst@redhat.com>
5 *
6 * Inspiration, some code, and most witty comments come from
7 * Documentation/virtual/lguest/lguest.c, by Rusty Russell
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2.
10 *
11 * Generic code for virtio server in host kernel.
12 */
13
14 #include <linux/eventfd.h>
15 #include <linux/vhost.h>
16 #include <linux/uio.h>
17 #include <linux/mm.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
31 #include "vhost.h"
32
33 static ushort max_mem_regions = 64;
34 module_param(max_mem_regions, ushort, 0444);
35 MODULE_PARM_DESC(max_mem_regions,
36 "Maximum number of memory regions in memory map. (default: 64)");
37
38 enum {
39 VHOST_MEMORY_F_LOG = 0x1,
40 };
41
42 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
43 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
44
45 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
46 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
47 {
48 vq->user_be = !virtio_legacy_is_little_endian();
49 }
50
51 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
52 {
53 vq->user_be = true;
54 }
55
56 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
57 {
58 vq->user_be = false;
59 }
60
61 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
62 {
63 struct vhost_vring_state s;
64
65 if (vq->private_data)
66 return -EBUSY;
67
68 if (copy_from_user(&s, argp, sizeof(s)))
69 return -EFAULT;
70
71 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
72 s.num != VHOST_VRING_BIG_ENDIAN)
73 return -EINVAL;
74
75 if (s.num == VHOST_VRING_BIG_ENDIAN)
76 vhost_enable_cross_endian_big(vq);
77 else
78 vhost_enable_cross_endian_little(vq);
79
80 return 0;
81 }
82
83 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
84 int __user *argp)
85 {
86 struct vhost_vring_state s = {
87 .index = idx,
88 .num = vq->user_be
89 };
90
91 if (copy_to_user(argp, &s, sizeof(s)))
92 return -EFAULT;
93
94 return 0;
95 }
96
97 static void vhost_init_is_le(struct vhost_virtqueue *vq)
98 {
99 /* Note for legacy virtio: user_be is initialized at reset time
100 * according to the host endianness. If userspace does not set an
101 * explicit endianness, the default behavior is native endian, as
102 * expected by legacy virtio.
103 */
104 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
105 }
106 #else
107 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
108 {
109 }
110
111 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
112 {
113 return -ENOIOCTLCMD;
114 }
115
116 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
117 int __user *argp)
118 {
119 return -ENOIOCTLCMD;
120 }
121
122 static void vhost_init_is_le(struct vhost_virtqueue *vq)
123 {
124 if (vhost_has_feature(vq, VIRTIO_F_VERSION_1))
125 vq->is_le = true;
126 }
127 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
128
129 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
130 {
131 vq->is_le = virtio_legacy_is_little_endian();
132 }
133
134 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
135 poll_table *pt)
136 {
137 struct vhost_poll *poll;
138
139 poll = container_of(pt, struct vhost_poll, table);
140 poll->wqh = wqh;
141 add_wait_queue(wqh, &poll->wait);
142 }
143
144 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
145 void *key)
146 {
147 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
148
149 if (!((unsigned long)key & poll->mask))
150 return 0;
151
152 vhost_poll_queue(poll);
153 return 0;
154 }
155
156 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
157 {
158 INIT_LIST_HEAD(&work->node);
159 work->fn = fn;
160 init_waitqueue_head(&work->done);
161 work->flushing = 0;
162 work->queue_seq = work->done_seq = 0;
163 }
164 EXPORT_SYMBOL_GPL(vhost_work_init);
165
166 /* Init poll structure */
167 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
168 unsigned long mask, struct vhost_dev *dev)
169 {
170 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
171 init_poll_funcptr(&poll->table, vhost_poll_func);
172 poll->mask = mask;
173 poll->dev = dev;
174 poll->wqh = NULL;
175
176 vhost_work_init(&poll->work, fn);
177 }
178 EXPORT_SYMBOL_GPL(vhost_poll_init);
179
180 /* Start polling a file. We add ourselves to file's wait queue. The caller must
181 * keep a reference to a file until after vhost_poll_stop is called. */
182 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
183 {
184 unsigned long mask;
185 int ret = 0;
186
187 if (poll->wqh)
188 return 0;
189
190 mask = file->f_op->poll(file, &poll->table);
191 if (mask)
192 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
193 if (mask & POLLERR) {
194 if (poll->wqh)
195 remove_wait_queue(poll->wqh, &poll->wait);
196 ret = -EINVAL;
197 }
198
199 return ret;
200 }
201 EXPORT_SYMBOL_GPL(vhost_poll_start);
202
203 /* Stop polling a file. After this function returns, it becomes safe to drop the
204 * file reference. You must also flush afterwards. */
205 void vhost_poll_stop(struct vhost_poll *poll)
206 {
207 if (poll->wqh) {
208 remove_wait_queue(poll->wqh, &poll->wait);
209 poll->wqh = NULL;
210 }
211 }
212 EXPORT_SYMBOL_GPL(vhost_poll_stop);
213
214 static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
215 unsigned seq)
216 {
217 int left;
218
219 spin_lock_irq(&dev->work_lock);
220 left = seq - work->done_seq;
221 spin_unlock_irq(&dev->work_lock);
222 return left <= 0;
223 }
224
225 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
226 {
227 unsigned seq;
228 int flushing;
229
230 spin_lock_irq(&dev->work_lock);
231 seq = work->queue_seq;
232 work->flushing++;
233 spin_unlock_irq(&dev->work_lock);
234 wait_event(work->done, vhost_work_seq_done(dev, work, seq));
235 spin_lock_irq(&dev->work_lock);
236 flushing = --work->flushing;
237 spin_unlock_irq(&dev->work_lock);
238 BUG_ON(flushing < 0);
239 }
240 EXPORT_SYMBOL_GPL(vhost_work_flush);
241
242 /* Flush any work that has been scheduled. When calling this, don't hold any
243 * locks that are also used by the callback. */
244 void vhost_poll_flush(struct vhost_poll *poll)
245 {
246 vhost_work_flush(poll->dev, &poll->work);
247 }
248 EXPORT_SYMBOL_GPL(vhost_poll_flush);
249
250 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
251 {
252 unsigned long flags;
253
254 spin_lock_irqsave(&dev->work_lock, flags);
255 if (list_empty(&work->node)) {
256 list_add_tail(&work->node, &dev->work_list);
257 work->queue_seq++;
258 spin_unlock_irqrestore(&dev->work_lock, flags);
259 wake_up_process(dev->worker);
260 } else {
261 spin_unlock_irqrestore(&dev->work_lock, flags);
262 }
263 }
264 EXPORT_SYMBOL_GPL(vhost_work_queue);
265
266 /* A lockless hint for busy polling code to exit the loop */
267 bool vhost_has_work(struct vhost_dev *dev)
268 {
269 return !list_empty(&dev->work_list);
270 }
271 EXPORT_SYMBOL_GPL(vhost_has_work);
272
273 void vhost_poll_queue(struct vhost_poll *poll)
274 {
275 vhost_work_queue(poll->dev, &poll->work);
276 }
277 EXPORT_SYMBOL_GPL(vhost_poll_queue);
278
279 static void vhost_vq_reset(struct vhost_dev *dev,
280 struct vhost_virtqueue *vq)
281 {
282 vq->num = 1;
283 vq->desc = NULL;
284 vq->avail = NULL;
285 vq->used = NULL;
286 vq->last_avail_idx = 0;
287 vq->avail_idx = 0;
288 vq->last_used_idx = 0;
289 vq->signalled_used = 0;
290 vq->signalled_used_valid = false;
291 vq->used_flags = 0;
292 vq->log_used = false;
293 vq->log_addr = -1ull;
294 vq->private_data = NULL;
295 vq->acked_features = 0;
296 vq->log_base = NULL;
297 vq->error_ctx = NULL;
298 vq->error = NULL;
299 vq->kick = NULL;
300 vq->call_ctx = NULL;
301 vq->call = NULL;
302 vq->log_ctx = NULL;
303 vq->memory = NULL;
304 vhost_reset_is_le(vq);
305 vhost_disable_cross_endian(vq);
306 }
307
308 static int vhost_worker(void *data)
309 {
310 struct vhost_dev *dev = data;
311 struct vhost_work *work = NULL;
312 unsigned uninitialized_var(seq);
313 mm_segment_t oldfs = get_fs();
314
315 set_fs(USER_DS);
316 use_mm(dev->mm);
317
318 for (;;) {
319 /* mb paired w/ kthread_stop */
320 set_current_state(TASK_INTERRUPTIBLE);
321
322 spin_lock_irq(&dev->work_lock);
323 if (work) {
324 work->done_seq = seq;
325 if (work->flushing)
326 wake_up_all(&work->done);
327 }
328
329 if (kthread_should_stop()) {
330 spin_unlock_irq(&dev->work_lock);
331 __set_current_state(TASK_RUNNING);
332 break;
333 }
334 if (!list_empty(&dev->work_list)) {
335 work = list_first_entry(&dev->work_list,
336 struct vhost_work, node);
337 list_del_init(&work->node);
338 seq = work->queue_seq;
339 } else
340 work = NULL;
341 spin_unlock_irq(&dev->work_lock);
342
343 if (work) {
344 __set_current_state(TASK_RUNNING);
345 work->fn(work);
346 if (need_resched())
347 schedule();
348 } else
349 schedule();
350
351 }
352 unuse_mm(dev->mm);
353 set_fs(oldfs);
354 return 0;
355 }
356
357 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
358 {
359 kfree(vq->indirect);
360 vq->indirect = NULL;
361 kfree(vq->log);
362 vq->log = NULL;
363 kfree(vq->heads);
364 vq->heads = NULL;
365 }
366
367 /* Helper to allocate iovec buffers for all vqs. */
368 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
369 {
370 struct vhost_virtqueue *vq;
371 int i;
372
373 for (i = 0; i < dev->nvqs; ++i) {
374 vq = dev->vqs[i];
375 vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
376 GFP_KERNEL);
377 vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
378 vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
379 if (!vq->indirect || !vq->log || !vq->heads)
380 goto err_nomem;
381 }
382 return 0;
383
384 err_nomem:
385 for (; i >= 0; --i)
386 vhost_vq_free_iovecs(dev->vqs[i]);
387 return -ENOMEM;
388 }
389
390 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
391 {
392 int i;
393
394 for (i = 0; i < dev->nvqs; ++i)
395 vhost_vq_free_iovecs(dev->vqs[i]);
396 }
397
398 void vhost_dev_init(struct vhost_dev *dev,
399 struct vhost_virtqueue **vqs, int nvqs)
400 {
401 struct vhost_virtqueue *vq;
402 int i;
403
404 dev->vqs = vqs;
405 dev->nvqs = nvqs;
406 mutex_init(&dev->mutex);
407 dev->log_ctx = NULL;
408 dev->log_file = NULL;
409 dev->memory = NULL;
410 dev->mm = NULL;
411 spin_lock_init(&dev->work_lock);
412 INIT_LIST_HEAD(&dev->work_list);
413 dev->worker = NULL;
414
415 for (i = 0; i < dev->nvqs; ++i) {
416 vq = dev->vqs[i];
417 vq->log = NULL;
418 vq->indirect = NULL;
419 vq->heads = NULL;
420 vq->dev = dev;
421 mutex_init(&vq->mutex);
422 vhost_vq_reset(dev, vq);
423 if (vq->handle_kick)
424 vhost_poll_init(&vq->poll, vq->handle_kick,
425 POLLIN, dev);
426 }
427 }
428 EXPORT_SYMBOL_GPL(vhost_dev_init);
429
430 /* Caller should have device mutex */
431 long vhost_dev_check_owner(struct vhost_dev *dev)
432 {
433 /* Are you the owner? If not, I don't think you mean to do that */
434 return dev->mm == current->mm ? 0 : -EPERM;
435 }
436 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
437
438 struct vhost_attach_cgroups_struct {
439 struct vhost_work work;
440 struct task_struct *owner;
441 int ret;
442 };
443
444 static void vhost_attach_cgroups_work(struct vhost_work *work)
445 {
446 struct vhost_attach_cgroups_struct *s;
447
448 s = container_of(work, struct vhost_attach_cgroups_struct, work);
449 s->ret = cgroup_attach_task_all(s->owner, current);
450 }
451
452 static int vhost_attach_cgroups(struct vhost_dev *dev)
453 {
454 struct vhost_attach_cgroups_struct attach;
455
456 attach.owner = current;
457 vhost_work_init(&attach.work, vhost_attach_cgroups_work);
458 vhost_work_queue(dev, &attach.work);
459 vhost_work_flush(dev, &attach.work);
460 return attach.ret;
461 }
462
463 /* Caller should have device mutex */
464 bool vhost_dev_has_owner(struct vhost_dev *dev)
465 {
466 return dev->mm;
467 }
468 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
469
470 /* Caller should have device mutex */
471 long vhost_dev_set_owner(struct vhost_dev *dev)
472 {
473 struct task_struct *worker;
474 int err;
475
476 /* Is there an owner already? */
477 if (vhost_dev_has_owner(dev)) {
478 err = -EBUSY;
479 goto err_mm;
480 }
481
482 /* No owner, become one */
483 dev->mm = get_task_mm(current);
484 worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
485 if (IS_ERR(worker)) {
486 err = PTR_ERR(worker);
487 goto err_worker;
488 }
489
490 dev->worker = worker;
491 wake_up_process(worker); /* avoid contributing to loadavg */
492
493 err = vhost_attach_cgroups(dev);
494 if (err)
495 goto err_cgroup;
496
497 err = vhost_dev_alloc_iovecs(dev);
498 if (err)
499 goto err_cgroup;
500
501 return 0;
502 err_cgroup:
503 kthread_stop(worker);
504 dev->worker = NULL;
505 err_worker:
506 if (dev->mm)
507 mmput(dev->mm);
508 dev->mm = NULL;
509 err_mm:
510 return err;
511 }
512 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
513
514 struct vhost_memory *vhost_dev_reset_owner_prepare(void)
515 {
516 return kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
517 }
518 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
519
520 /* Caller should have device mutex */
521 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_memory *memory)
522 {
523 int i;
524
525 vhost_dev_cleanup(dev, true);
526
527 /* Restore memory to default empty mapping. */
528 memory->nregions = 0;
529 dev->memory = memory;
530 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
531 * VQs aren't running.
532 */
533 for (i = 0; i < dev->nvqs; ++i)
534 dev->vqs[i]->memory = memory;
535 }
536 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
537
538 void vhost_dev_stop(struct vhost_dev *dev)
539 {
540 int i;
541
542 for (i = 0; i < dev->nvqs; ++i) {
543 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
544 vhost_poll_stop(&dev->vqs[i]->poll);
545 vhost_poll_flush(&dev->vqs[i]->poll);
546 }
547 }
548 }
549 EXPORT_SYMBOL_GPL(vhost_dev_stop);
550
551 /* Caller should have device mutex if and only if locked is set */
552 void vhost_dev_cleanup(struct vhost_dev *dev, bool locked)
553 {
554 int i;
555
556 for (i = 0; i < dev->nvqs; ++i) {
557 if (dev->vqs[i]->error_ctx)
558 eventfd_ctx_put(dev->vqs[i]->error_ctx);
559 if (dev->vqs[i]->error)
560 fput(dev->vqs[i]->error);
561 if (dev->vqs[i]->kick)
562 fput(dev->vqs[i]->kick);
563 if (dev->vqs[i]->call_ctx)
564 eventfd_ctx_put(dev->vqs[i]->call_ctx);
565 if (dev->vqs[i]->call)
566 fput(dev->vqs[i]->call);
567 vhost_vq_reset(dev, dev->vqs[i]);
568 }
569 vhost_dev_free_iovecs(dev);
570 if (dev->log_ctx)
571 eventfd_ctx_put(dev->log_ctx);
572 dev->log_ctx = NULL;
573 if (dev->log_file)
574 fput(dev->log_file);
575 dev->log_file = NULL;
576 /* No one will access memory at this point */
577 kvfree(dev->memory);
578 dev->memory = NULL;
579 WARN_ON(!list_empty(&dev->work_list));
580 if (dev->worker) {
581 kthread_stop(dev->worker);
582 dev->worker = NULL;
583 }
584 if (dev->mm)
585 mmput(dev->mm);
586 dev->mm = NULL;
587 }
588 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
589
590 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
591 {
592 u64 a = addr / VHOST_PAGE_SIZE / 8;
593
594 /* Make sure 64 bit math will not overflow. */
595 if (a > ULONG_MAX - (unsigned long)log_base ||
596 a + (unsigned long)log_base > ULONG_MAX)
597 return 0;
598
599 return access_ok(VERIFY_WRITE, log_base + a,
600 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
601 }
602
603 /* Caller should have vq mutex and device mutex. */
604 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
605 int log_all)
606 {
607 int i;
608
609 if (!mem)
610 return 0;
611
612 for (i = 0; i < mem->nregions; ++i) {
613 struct vhost_memory_region *m = mem->regions + i;
614 unsigned long a = m->userspace_addr;
615 if (m->memory_size > ULONG_MAX)
616 return 0;
617 else if (!access_ok(VERIFY_WRITE, (void __user *)a,
618 m->memory_size))
619 return 0;
620 else if (log_all && !log_access_ok(log_base,
621 m->guest_phys_addr,
622 m->memory_size))
623 return 0;
624 }
625 return 1;
626 }
627
628 /* Can we switch to this memory table? */
629 /* Caller should have device mutex but not vq mutex */
630 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
631 int log_all)
632 {
633 int i;
634
635 for (i = 0; i < d->nvqs; ++i) {
636 int ok;
637 bool log;
638
639 mutex_lock(&d->vqs[i]->mutex);
640 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
641 /* If ring is inactive, will check when it's enabled. */
642 if (d->vqs[i]->private_data)
643 ok = vq_memory_access_ok(d->vqs[i]->log_base, mem, log);
644 else
645 ok = 1;
646 mutex_unlock(&d->vqs[i]->mutex);
647 if (!ok)
648 return 0;
649 }
650 return 1;
651 }
652
653 static int vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
654 struct vring_desc __user *desc,
655 struct vring_avail __user *avail,
656 struct vring_used __user *used)
657 {
658 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
659 return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
660 access_ok(VERIFY_READ, avail,
661 sizeof *avail + num * sizeof *avail->ring + s) &&
662 access_ok(VERIFY_WRITE, used,
663 sizeof *used + num * sizeof *used->ring + s);
664 }
665
666 /* Can we log writes? */
667 /* Caller should have device mutex but not vq mutex */
668 int vhost_log_access_ok(struct vhost_dev *dev)
669 {
670 return memory_access_ok(dev, dev->memory, 1);
671 }
672 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
673
674 /* Verify access for write logging. */
675 /* Caller should have vq mutex and device mutex */
676 static int vq_log_access_ok(struct vhost_virtqueue *vq,
677 void __user *log_base)
678 {
679 size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
680
681 return vq_memory_access_ok(log_base, vq->memory,
682 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
683 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
684 sizeof *vq->used +
685 vq->num * sizeof *vq->used->ring + s));
686 }
687
688 /* Can we start vq? */
689 /* Caller should have vq mutex and device mutex */
690 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
691 {
692 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used) &&
693 vq_log_access_ok(vq, vq->log_base);
694 }
695 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
696
697 static int vhost_memory_reg_sort_cmp(const void *p1, const void *p2)
698 {
699 const struct vhost_memory_region *r1 = p1, *r2 = p2;
700 if (r1->guest_phys_addr < r2->guest_phys_addr)
701 return 1;
702 if (r1->guest_phys_addr > r2->guest_phys_addr)
703 return -1;
704 return 0;
705 }
706
707 static void *vhost_kvzalloc(unsigned long size)
708 {
709 void *n = kzalloc(size, GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
710
711 if (!n)
712 n = vzalloc(size);
713 return n;
714 }
715
716 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
717 {
718 struct vhost_memory mem, *newmem, *oldmem;
719 unsigned long size = offsetof(struct vhost_memory, regions);
720 int i;
721
722 if (copy_from_user(&mem, m, size))
723 return -EFAULT;
724 if (mem.padding)
725 return -EOPNOTSUPP;
726 if (mem.nregions > max_mem_regions)
727 return -E2BIG;
728 newmem = vhost_kvzalloc(size + mem.nregions * sizeof(*m->regions));
729 if (!newmem)
730 return -ENOMEM;
731
732 memcpy(newmem, &mem, size);
733 if (copy_from_user(newmem->regions, m->regions,
734 mem.nregions * sizeof *m->regions)) {
735 kvfree(newmem);
736 return -EFAULT;
737 }
738 sort(newmem->regions, newmem->nregions, sizeof(*newmem->regions),
739 vhost_memory_reg_sort_cmp, NULL);
740
741 if (!memory_access_ok(d, newmem, 0)) {
742 kvfree(newmem);
743 return -EFAULT;
744 }
745 oldmem = d->memory;
746 d->memory = newmem;
747
748 /* All memory accesses are done under some VQ mutex. */
749 for (i = 0; i < d->nvqs; ++i) {
750 mutex_lock(&d->vqs[i]->mutex);
751 d->vqs[i]->memory = newmem;
752 mutex_unlock(&d->vqs[i]->mutex);
753 }
754 kvfree(oldmem);
755 return 0;
756 }
757
758 long vhost_vring_ioctl(struct vhost_dev *d, int ioctl, void __user *argp)
759 {
760 struct file *eventfp, *filep = NULL;
761 bool pollstart = false, pollstop = false;
762 struct eventfd_ctx *ctx = NULL;
763 u32 __user *idxp = argp;
764 struct vhost_virtqueue *vq;
765 struct vhost_vring_state s;
766 struct vhost_vring_file f;
767 struct vhost_vring_addr a;
768 u32 idx;
769 long r;
770
771 r = get_user(idx, idxp);
772 if (r < 0)
773 return r;
774 if (idx >= d->nvqs)
775 return -ENOBUFS;
776
777 vq = d->vqs[idx];
778
779 mutex_lock(&vq->mutex);
780
781 switch (ioctl) {
782 case VHOST_SET_VRING_NUM:
783 /* Resizing ring with an active backend?
784 * You don't want to do that. */
785 if (vq->private_data) {
786 r = -EBUSY;
787 break;
788 }
789 if (copy_from_user(&s, argp, sizeof s)) {
790 r = -EFAULT;
791 break;
792 }
793 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
794 r = -EINVAL;
795 break;
796 }
797 vq->num = s.num;
798 break;
799 case VHOST_SET_VRING_BASE:
800 /* Moving base with an active backend?
801 * You don't want to do that. */
802 if (vq->private_data) {
803 r = -EBUSY;
804 break;
805 }
806 if (copy_from_user(&s, argp, sizeof s)) {
807 r = -EFAULT;
808 break;
809 }
810 if (s.num > 0xffff) {
811 r = -EINVAL;
812 break;
813 }
814 vq->last_avail_idx = s.num;
815 /* Forget the cached index value. */
816 vq->avail_idx = vq->last_avail_idx;
817 break;
818 case VHOST_GET_VRING_BASE:
819 s.index = idx;
820 s.num = vq->last_avail_idx;
821 if (copy_to_user(argp, &s, sizeof s))
822 r = -EFAULT;
823 break;
824 case VHOST_SET_VRING_ADDR:
825 if (copy_from_user(&a, argp, sizeof a)) {
826 r = -EFAULT;
827 break;
828 }
829 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
830 r = -EOPNOTSUPP;
831 break;
832 }
833 /* For 32bit, verify that the top 32bits of the user
834 data are set to zero. */
835 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
836 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
837 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
838 r = -EFAULT;
839 break;
840 }
841
842 /* Make sure it's safe to cast pointers to vring types. */
843 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
844 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
845 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
846 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
847 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1))) {
848 r = -EINVAL;
849 break;
850 }
851
852 /* We only verify access here if backend is configured.
853 * If it is not, we don't as size might not have been setup.
854 * We will verify when backend is configured. */
855 if (vq->private_data) {
856 if (!vq_access_ok(vq, vq->num,
857 (void __user *)(unsigned long)a.desc_user_addr,
858 (void __user *)(unsigned long)a.avail_user_addr,
859 (void __user *)(unsigned long)a.used_user_addr)) {
860 r = -EINVAL;
861 break;
862 }
863
864 /* Also validate log access for used ring if enabled. */
865 if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
866 !log_access_ok(vq->log_base, a.log_guest_addr,
867 sizeof *vq->used +
868 vq->num * sizeof *vq->used->ring)) {
869 r = -EINVAL;
870 break;
871 }
872 }
873
874 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
875 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
876 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
877 vq->log_addr = a.log_guest_addr;
878 vq->used = (void __user *)(unsigned long)a.used_user_addr;
879 break;
880 case VHOST_SET_VRING_KICK:
881 if (copy_from_user(&f, argp, sizeof f)) {
882 r = -EFAULT;
883 break;
884 }
885 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
886 if (IS_ERR(eventfp)) {
887 r = PTR_ERR(eventfp);
888 break;
889 }
890 if (eventfp != vq->kick) {
891 pollstop = (filep = vq->kick) != NULL;
892 pollstart = (vq->kick = eventfp) != NULL;
893 } else
894 filep = eventfp;
895 break;
896 case VHOST_SET_VRING_CALL:
897 if (copy_from_user(&f, argp, sizeof f)) {
898 r = -EFAULT;
899 break;
900 }
901 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
902 if (IS_ERR(eventfp)) {
903 r = PTR_ERR(eventfp);
904 break;
905 }
906 if (eventfp != vq->call) {
907 filep = vq->call;
908 ctx = vq->call_ctx;
909 vq->call = eventfp;
910 vq->call_ctx = eventfp ?
911 eventfd_ctx_fileget(eventfp) : NULL;
912 } else
913 filep = eventfp;
914 break;
915 case VHOST_SET_VRING_ERR:
916 if (copy_from_user(&f, argp, sizeof f)) {
917 r = -EFAULT;
918 break;
919 }
920 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
921 if (IS_ERR(eventfp)) {
922 r = PTR_ERR(eventfp);
923 break;
924 }
925 if (eventfp != vq->error) {
926 filep = vq->error;
927 vq->error = eventfp;
928 ctx = vq->error_ctx;
929 vq->error_ctx = eventfp ?
930 eventfd_ctx_fileget(eventfp) : NULL;
931 } else
932 filep = eventfp;
933 break;
934 case VHOST_SET_VRING_ENDIAN:
935 r = vhost_set_vring_endian(vq, argp);
936 break;
937 case VHOST_GET_VRING_ENDIAN:
938 r = vhost_get_vring_endian(vq, idx, argp);
939 break;
940 default:
941 r = -ENOIOCTLCMD;
942 }
943
944 if (pollstop && vq->handle_kick)
945 vhost_poll_stop(&vq->poll);
946
947 if (ctx)
948 eventfd_ctx_put(ctx);
949 if (filep)
950 fput(filep);
951
952 if (pollstart && vq->handle_kick)
953 r = vhost_poll_start(&vq->poll, vq->kick);
954
955 mutex_unlock(&vq->mutex);
956
957 if (pollstop && vq->handle_kick)
958 vhost_poll_flush(&vq->poll);
959 return r;
960 }
961 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
962
963 /* Caller must have device mutex */
964 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
965 {
966 struct file *eventfp, *filep = NULL;
967 struct eventfd_ctx *ctx = NULL;
968 u64 p;
969 long r;
970 int i, fd;
971
972 /* If you are not the owner, you can become one */
973 if (ioctl == VHOST_SET_OWNER) {
974 r = vhost_dev_set_owner(d);
975 goto done;
976 }
977
978 /* You must be the owner to do anything else */
979 r = vhost_dev_check_owner(d);
980 if (r)
981 goto done;
982
983 switch (ioctl) {
984 case VHOST_SET_MEM_TABLE:
985 r = vhost_set_memory(d, argp);
986 break;
987 case VHOST_SET_LOG_BASE:
988 if (copy_from_user(&p, argp, sizeof p)) {
989 r = -EFAULT;
990 break;
991 }
992 if ((u64)(unsigned long)p != p) {
993 r = -EFAULT;
994 break;
995 }
996 for (i = 0; i < d->nvqs; ++i) {
997 struct vhost_virtqueue *vq;
998 void __user *base = (void __user *)(unsigned long)p;
999 vq = d->vqs[i];
1000 mutex_lock(&vq->mutex);
1001 /* If ring is inactive, will check when it's enabled. */
1002 if (vq->private_data && !vq_log_access_ok(vq, base))
1003 r = -EFAULT;
1004 else
1005 vq->log_base = base;
1006 mutex_unlock(&vq->mutex);
1007 }
1008 break;
1009 case VHOST_SET_LOG_FD:
1010 r = get_user(fd, (int __user *)argp);
1011 if (r < 0)
1012 break;
1013 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
1014 if (IS_ERR(eventfp)) {
1015 r = PTR_ERR(eventfp);
1016 break;
1017 }
1018 if (eventfp != d->log_file) {
1019 filep = d->log_file;
1020 d->log_file = eventfp;
1021 ctx = d->log_ctx;
1022 d->log_ctx = eventfp ?
1023 eventfd_ctx_fileget(eventfp) : NULL;
1024 } else
1025 filep = eventfp;
1026 for (i = 0; i < d->nvqs; ++i) {
1027 mutex_lock(&d->vqs[i]->mutex);
1028 d->vqs[i]->log_ctx = d->log_ctx;
1029 mutex_unlock(&d->vqs[i]->mutex);
1030 }
1031 if (ctx)
1032 eventfd_ctx_put(ctx);
1033 if (filep)
1034 fput(filep);
1035 break;
1036 default:
1037 r = -ENOIOCTLCMD;
1038 break;
1039 }
1040 done:
1041 return r;
1042 }
1043 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1044
1045 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
1046 __u64 addr, __u32 len)
1047 {
1048 const struct vhost_memory_region *reg;
1049 int start = 0, end = mem->nregions;
1050
1051 while (start < end) {
1052 int slot = start + (end - start) / 2;
1053 reg = mem->regions + slot;
1054 if (addr >= reg->guest_phys_addr)
1055 end = slot;
1056 else
1057 start = slot + 1;
1058 }
1059
1060 reg = mem->regions + start;
1061 if (addr >= reg->guest_phys_addr &&
1062 reg->guest_phys_addr + reg->memory_size > addr)
1063 return reg;
1064 return NULL;
1065 }
1066
1067 /* TODO: This is really inefficient. We need something like get_user()
1068 * (instruction directly accesses the data, with an exception table entry
1069 * returning -EFAULT). See Documentation/x86/exception-tables.txt.
1070 */
1071 static int set_bit_to_user(int nr, void __user *addr)
1072 {
1073 unsigned long log = (unsigned long)addr;
1074 struct page *page;
1075 void *base;
1076 int bit = nr + (log % PAGE_SIZE) * 8;
1077 int r;
1078
1079 r = get_user_pages_fast(log, 1, 1, &page);
1080 if (r < 0)
1081 return r;
1082 BUG_ON(r != 1);
1083 base = kmap_atomic(page);
1084 set_bit(bit, base);
1085 kunmap_atomic(base);
1086 set_page_dirty_lock(page);
1087 put_page(page);
1088 return 0;
1089 }
1090
1091 static int log_write(void __user *log_base,
1092 u64 write_address, u64 write_length)
1093 {
1094 u64 write_page = write_address / VHOST_PAGE_SIZE;
1095 int r;
1096
1097 if (!write_length)
1098 return 0;
1099 write_length += write_address % VHOST_PAGE_SIZE;
1100 for (;;) {
1101 u64 base = (u64)(unsigned long)log_base;
1102 u64 log = base + write_page / 8;
1103 int bit = write_page % 8;
1104 if ((u64)(unsigned long)log != log)
1105 return -EFAULT;
1106 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1107 if (r < 0)
1108 return r;
1109 if (write_length <= VHOST_PAGE_SIZE)
1110 break;
1111 write_length -= VHOST_PAGE_SIZE;
1112 write_page += 1;
1113 }
1114 return r;
1115 }
1116
1117 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1118 unsigned int log_num, u64 len)
1119 {
1120 int i, r;
1121
1122 /* Make sure data written is seen before log. */
1123 smp_wmb();
1124 for (i = 0; i < log_num; ++i) {
1125 u64 l = min(log[i].len, len);
1126 r = log_write(vq->log_base, log[i].addr, l);
1127 if (r < 0)
1128 return r;
1129 len -= l;
1130 if (!len) {
1131 if (vq->log_ctx)
1132 eventfd_signal(vq->log_ctx, 1);
1133 return 0;
1134 }
1135 }
1136 /* Length written exceeds what we have stored. This is a bug. */
1137 BUG();
1138 return 0;
1139 }
1140 EXPORT_SYMBOL_GPL(vhost_log_write);
1141
1142 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1143 {
1144 void __user *used;
1145 if (__put_user(cpu_to_vhost16(vq, vq->used_flags), &vq->used->flags) < 0)
1146 return -EFAULT;
1147 if (unlikely(vq->log_used)) {
1148 /* Make sure the flag is seen before log. */
1149 smp_wmb();
1150 /* Log used flag write. */
1151 used = &vq->used->flags;
1152 log_write(vq->log_base, vq->log_addr +
1153 (used - (void __user *)vq->used),
1154 sizeof vq->used->flags);
1155 if (vq->log_ctx)
1156 eventfd_signal(vq->log_ctx, 1);
1157 }
1158 return 0;
1159 }
1160
1161 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1162 {
1163 if (__put_user(cpu_to_vhost16(vq, vq->avail_idx), vhost_avail_event(vq)))
1164 return -EFAULT;
1165 if (unlikely(vq->log_used)) {
1166 void __user *used;
1167 /* Make sure the event is seen before log. */
1168 smp_wmb();
1169 /* Log avail event write */
1170 used = vhost_avail_event(vq);
1171 log_write(vq->log_base, vq->log_addr +
1172 (used - (void __user *)vq->used),
1173 sizeof *vhost_avail_event(vq));
1174 if (vq->log_ctx)
1175 eventfd_signal(vq->log_ctx, 1);
1176 }
1177 return 0;
1178 }
1179
1180 int vhost_vq_init_access(struct vhost_virtqueue *vq)
1181 {
1182 __virtio16 last_used_idx;
1183 int r;
1184 bool is_le = vq->is_le;
1185
1186 if (!vq->private_data) {
1187 vhost_reset_is_le(vq);
1188 return 0;
1189 }
1190
1191 vhost_init_is_le(vq);
1192
1193 r = vhost_update_used_flags(vq);
1194 if (r)
1195 goto err;
1196 vq->signalled_used_valid = false;
1197 if (!access_ok(VERIFY_READ, &vq->used->idx, sizeof vq->used->idx)) {
1198 r = -EFAULT;
1199 goto err;
1200 }
1201 r = __get_user(last_used_idx, &vq->used->idx);
1202 if (r)
1203 goto err;
1204 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1205 return 0;
1206 err:
1207 vq->is_le = is_le;
1208 return r;
1209 }
1210 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
1211
1212 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1213 struct iovec iov[], int iov_size)
1214 {
1215 const struct vhost_memory_region *reg;
1216 struct vhost_memory *mem;
1217 struct iovec *_iov;
1218 u64 s = 0;
1219 int ret = 0;
1220
1221 mem = vq->memory;
1222 while ((u64)len > s) {
1223 u64 size;
1224 if (unlikely(ret >= iov_size)) {
1225 ret = -ENOBUFS;
1226 break;
1227 }
1228 reg = find_region(mem, addr, len);
1229 if (unlikely(!reg)) {
1230 ret = -EFAULT;
1231 break;
1232 }
1233 _iov = iov + ret;
1234 size = reg->memory_size - addr + reg->guest_phys_addr;
1235 _iov->iov_len = min((u64)len - s, size);
1236 _iov->iov_base = (void __user *)(unsigned long)
1237 (reg->userspace_addr + addr - reg->guest_phys_addr);
1238 s += size;
1239 addr += size;
1240 ++ret;
1241 }
1242
1243 return ret;
1244 }
1245
1246 /* Each buffer in the virtqueues is actually a chain of descriptors. This
1247 * function returns the next descriptor in the chain,
1248 * or -1U if we're at the end. */
1249 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1250 {
1251 unsigned int next;
1252
1253 /* If this descriptor says it doesn't chain, we're done. */
1254 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1255 return -1U;
1256
1257 /* Check they're not leading us off end of descriptors. */
1258 next = vhost16_to_cpu(vq, desc->next);
1259 /* Make sure compiler knows to grab that: we don't want it changing! */
1260 /* We will use the result as an index in an array, so most
1261 * architectures only need a compiler barrier here. */
1262 read_barrier_depends();
1263
1264 return next;
1265 }
1266
1267 static int get_indirect(struct vhost_virtqueue *vq,
1268 struct iovec iov[], unsigned int iov_size,
1269 unsigned int *out_num, unsigned int *in_num,
1270 struct vhost_log *log, unsigned int *log_num,
1271 struct vring_desc *indirect)
1272 {
1273 struct vring_desc desc;
1274 unsigned int i = 0, count, found = 0;
1275 u32 len = vhost32_to_cpu(vq, indirect->len);
1276 struct iov_iter from;
1277 int ret;
1278
1279 /* Sanity check */
1280 if (unlikely(len % sizeof desc)) {
1281 vq_err(vq, "Invalid length in indirect descriptor: "
1282 "len 0x%llx not multiple of 0x%zx\n",
1283 (unsigned long long)len,
1284 sizeof desc);
1285 return -EINVAL;
1286 }
1287
1288 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
1289 UIO_MAXIOV);
1290 if (unlikely(ret < 0)) {
1291 vq_err(vq, "Translation failure %d in indirect.\n", ret);
1292 return ret;
1293 }
1294 iov_iter_init(&from, READ, vq->indirect, ret, len);
1295
1296 /* We will use the result as an address to read from, so most
1297 * architectures only need a compiler barrier here. */
1298 read_barrier_depends();
1299
1300 count = len / sizeof desc;
1301 /* Buffers are chained via a 16 bit next field, so
1302 * we can have at most 2^16 of these. */
1303 if (unlikely(count > USHRT_MAX + 1)) {
1304 vq_err(vq, "Indirect buffer length too big: %d\n",
1305 indirect->len);
1306 return -E2BIG;
1307 }
1308
1309 do {
1310 unsigned iov_count = *in_num + *out_num;
1311 if (unlikely(++found > count)) {
1312 vq_err(vq, "Loop detected: last one at %u "
1313 "indirect size %u\n",
1314 i, count);
1315 return -EINVAL;
1316 }
1317 if (unlikely(copy_from_iter(&desc, sizeof(desc), &from) !=
1318 sizeof(desc))) {
1319 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1320 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1321 return -EINVAL;
1322 }
1323 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
1324 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1325 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1326 return -EINVAL;
1327 }
1328
1329 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1330 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1331 iov_size - iov_count);
1332 if (unlikely(ret < 0)) {
1333 vq_err(vq, "Translation failure %d indirect idx %d\n",
1334 ret, i);
1335 return ret;
1336 }
1337 /* If this is an input descriptor, increment that count. */
1338 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1339 *in_num += ret;
1340 if (unlikely(log)) {
1341 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1342 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1343 ++*log_num;
1344 }
1345 } else {
1346 /* If it's an output descriptor, they're all supposed
1347 * to come before any input descriptors. */
1348 if (unlikely(*in_num)) {
1349 vq_err(vq, "Indirect descriptor "
1350 "has out after in: idx %d\n", i);
1351 return -EINVAL;
1352 }
1353 *out_num += ret;
1354 }
1355 } while ((i = next_desc(vq, &desc)) != -1);
1356 return 0;
1357 }
1358
1359 /* This looks in the virtqueue and for the first available buffer, and converts
1360 * it to an iovec for convenient access. Since descriptors consist of some
1361 * number of output then some number of input descriptors, it's actually two
1362 * iovecs, but we pack them into one and note how many of each there were.
1363 *
1364 * This function returns the descriptor number found, or vq->num (which is
1365 * never a valid descriptor number) if none was found. A negative code is
1366 * returned on error. */
1367 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
1368 struct iovec iov[], unsigned int iov_size,
1369 unsigned int *out_num, unsigned int *in_num,
1370 struct vhost_log *log, unsigned int *log_num)
1371 {
1372 struct vring_desc desc;
1373 unsigned int i, head, found = 0;
1374 u16 last_avail_idx;
1375 __virtio16 avail_idx;
1376 __virtio16 ring_head;
1377 int ret;
1378
1379 /* Check it isn't doing very strange things with descriptor numbers. */
1380 last_avail_idx = vq->last_avail_idx;
1381 if (unlikely(__get_user(avail_idx, &vq->avail->idx))) {
1382 vq_err(vq, "Failed to access avail idx at %p\n",
1383 &vq->avail->idx);
1384 return -EFAULT;
1385 }
1386 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
1387
1388 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1389 vq_err(vq, "Guest moved used index from %u to %u",
1390 last_avail_idx, vq->avail_idx);
1391 return -EFAULT;
1392 }
1393
1394 /* If there's nothing new since last we looked, return invalid. */
1395 if (vq->avail_idx == last_avail_idx)
1396 return vq->num;
1397
1398 /* Only get avail ring entries after they have been exposed by guest. */
1399 smp_rmb();
1400
1401 /* Grab the next descriptor number they're advertising, and increment
1402 * the index we've seen. */
1403 if (unlikely(__get_user(ring_head,
1404 &vq->avail->ring[last_avail_idx & (vq->num - 1)]))) {
1405 vq_err(vq, "Failed to read head: idx %d address %p\n",
1406 last_avail_idx,
1407 &vq->avail->ring[last_avail_idx % vq->num]);
1408 return -EFAULT;
1409 }
1410
1411 head = vhost16_to_cpu(vq, ring_head);
1412
1413 /* If their number is silly, that's an error. */
1414 if (unlikely(head >= vq->num)) {
1415 vq_err(vq, "Guest says index %u > %u is available",
1416 head, vq->num);
1417 return -EINVAL;
1418 }
1419
1420 /* When we start there are none of either input nor output. */
1421 *out_num = *in_num = 0;
1422 if (unlikely(log))
1423 *log_num = 0;
1424
1425 i = head;
1426 do {
1427 unsigned iov_count = *in_num + *out_num;
1428 if (unlikely(i >= vq->num)) {
1429 vq_err(vq, "Desc index is %u > %u, head = %u",
1430 i, vq->num, head);
1431 return -EINVAL;
1432 }
1433 if (unlikely(++found > vq->num)) {
1434 vq_err(vq, "Loop detected: last one at %u "
1435 "vq size %u head %u\n",
1436 i, vq->num, head);
1437 return -EINVAL;
1438 }
1439 ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
1440 if (unlikely(ret)) {
1441 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1442 i, vq->desc + i);
1443 return -EFAULT;
1444 }
1445 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
1446 ret = get_indirect(vq, iov, iov_size,
1447 out_num, in_num,
1448 log, log_num, &desc);
1449 if (unlikely(ret < 0)) {
1450 vq_err(vq, "Failure detected "
1451 "in indirect descriptor at idx %d\n", i);
1452 return ret;
1453 }
1454 continue;
1455 }
1456
1457 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1458 vhost32_to_cpu(vq, desc.len), iov + iov_count,
1459 iov_size - iov_count);
1460 if (unlikely(ret < 0)) {
1461 vq_err(vq, "Translation failure %d descriptor idx %d\n",
1462 ret, i);
1463 return ret;
1464 }
1465 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1466 /* If this is an input descriptor,
1467 * increment that count. */
1468 *in_num += ret;
1469 if (unlikely(log)) {
1470 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1471 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1472 ++*log_num;
1473 }
1474 } else {
1475 /* If it's an output descriptor, they're all supposed
1476 * to come before any input descriptors. */
1477 if (unlikely(*in_num)) {
1478 vq_err(vq, "Descriptor has out after in: "
1479 "idx %d\n", i);
1480 return -EINVAL;
1481 }
1482 *out_num += ret;
1483 }
1484 } while ((i = next_desc(vq, &desc)) != -1);
1485
1486 /* On success, increment avail index. */
1487 vq->last_avail_idx++;
1488
1489 /* Assume notifications from guest are disabled at this point,
1490 * if they aren't we would need to update avail_event index. */
1491 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
1492 return head;
1493 }
1494 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
1495
1496 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1497 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1498 {
1499 vq->last_avail_idx -= n;
1500 }
1501 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
1502
1503 /* After we've used one of their buffers, we tell them about it. We'll then
1504 * want to notify the guest, using eventfd. */
1505 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1506 {
1507 struct vring_used_elem heads = {
1508 cpu_to_vhost32(vq, head),
1509 cpu_to_vhost32(vq, len)
1510 };
1511
1512 return vhost_add_used_n(vq, &heads, 1);
1513 }
1514 EXPORT_SYMBOL_GPL(vhost_add_used);
1515
1516 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1517 struct vring_used_elem *heads,
1518 unsigned count)
1519 {
1520 struct vring_used_elem __user *used;
1521 u16 old, new;
1522 int start;
1523
1524 start = vq->last_used_idx & (vq->num - 1);
1525 used = vq->used->ring + start;
1526 if (count == 1) {
1527 if (__put_user(heads[0].id, &used->id)) {
1528 vq_err(vq, "Failed to write used id");
1529 return -EFAULT;
1530 }
1531 if (__put_user(heads[0].len, &used->len)) {
1532 vq_err(vq, "Failed to write used len");
1533 return -EFAULT;
1534 }
1535 } else if (__copy_to_user(used, heads, count * sizeof *used)) {
1536 vq_err(vq, "Failed to write used");
1537 return -EFAULT;
1538 }
1539 if (unlikely(vq->log_used)) {
1540 /* Make sure data is seen before log. */
1541 smp_wmb();
1542 /* Log used ring entry write. */
1543 log_write(vq->log_base,
1544 vq->log_addr +
1545 ((void __user *)used - (void __user *)vq->used),
1546 count * sizeof *used);
1547 }
1548 old = vq->last_used_idx;
1549 new = (vq->last_used_idx += count);
1550 /* If the driver never bothers to signal in a very long while,
1551 * used index might wrap around. If that happens, invalidate
1552 * signalled_used index we stored. TODO: make sure driver
1553 * signals at least once in 2^16 and remove this. */
1554 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
1555 vq->signalled_used_valid = false;
1556 return 0;
1557 }
1558
1559 /* After we've used one of their buffers, we tell them about it. We'll then
1560 * want to notify the guest, using eventfd. */
1561 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1562 unsigned count)
1563 {
1564 int start, n, r;
1565
1566 start = vq->last_used_idx & (vq->num - 1);
1567 n = vq->num - start;
1568 if (n < count) {
1569 r = __vhost_add_used_n(vq, heads, n);
1570 if (r < 0)
1571 return r;
1572 heads += n;
1573 count -= n;
1574 }
1575 r = __vhost_add_used_n(vq, heads, count);
1576
1577 /* Make sure buffer is written before we update index. */
1578 smp_wmb();
1579 if (__put_user(cpu_to_vhost16(vq, vq->last_used_idx), &vq->used->idx)) {
1580 vq_err(vq, "Failed to increment used idx");
1581 return -EFAULT;
1582 }
1583 if (unlikely(vq->log_used)) {
1584 /* Log used index update. */
1585 log_write(vq->log_base,
1586 vq->log_addr + offsetof(struct vring_used, idx),
1587 sizeof vq->used->idx);
1588 if (vq->log_ctx)
1589 eventfd_signal(vq->log_ctx, 1);
1590 }
1591 return r;
1592 }
1593 EXPORT_SYMBOL_GPL(vhost_add_used_n);
1594
1595 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1596 {
1597 __u16 old, new;
1598 __virtio16 event;
1599 bool v;
1600 /* Flush out used index updates. This is paired
1601 * with the barrier that the Guest executes when enabling
1602 * interrupts. */
1603 smp_mb();
1604
1605 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1606 unlikely(vq->avail_idx == vq->last_avail_idx))
1607 return true;
1608
1609 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1610 __virtio16 flags;
1611 if (__get_user(flags, &vq->avail->flags)) {
1612 vq_err(vq, "Failed to get flags");
1613 return true;
1614 }
1615 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
1616 }
1617 old = vq->signalled_used;
1618 v = vq->signalled_used_valid;
1619 new = vq->signalled_used = vq->last_used_idx;
1620 vq->signalled_used_valid = true;
1621
1622 if (unlikely(!v))
1623 return true;
1624
1625 if (__get_user(event, vhost_used_event(vq))) {
1626 vq_err(vq, "Failed to get used event idx");
1627 return true;
1628 }
1629 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
1630 }
1631
1632 /* This actually signals the guest, using eventfd. */
1633 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1634 {
1635 /* Signal the Guest tell them we used something up. */
1636 if (vq->call_ctx && vhost_notify(dev, vq))
1637 eventfd_signal(vq->call_ctx, 1);
1638 }
1639 EXPORT_SYMBOL_GPL(vhost_signal);
1640
1641 /* And here's the combo meal deal. Supersize me! */
1642 void vhost_add_used_and_signal(struct vhost_dev *dev,
1643 struct vhost_virtqueue *vq,
1644 unsigned int head, int len)
1645 {
1646 vhost_add_used(vq, head, len);
1647 vhost_signal(dev, vq);
1648 }
1649 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
1650
1651 /* multi-buffer version of vhost_add_used_and_signal */
1652 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1653 struct vhost_virtqueue *vq,
1654 struct vring_used_elem *heads, unsigned count)
1655 {
1656 vhost_add_used_n(vq, heads, count);
1657 vhost_signal(dev, vq);
1658 }
1659 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
1660
1661 /* return true if we're sure that avaiable ring is empty */
1662 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1663 {
1664 __virtio16 avail_idx;
1665 int r;
1666
1667 r = __get_user(avail_idx, &vq->avail->idx);
1668 if (r)
1669 return false;
1670
1671 return vhost16_to_cpu(vq, avail_idx) == vq->avail_idx;
1672 }
1673 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
1674
1675 /* OK, now we need to know about added descriptors. */
1676 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1677 {
1678 __virtio16 avail_idx;
1679 int r;
1680
1681 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1682 return false;
1683 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1684 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1685 r = vhost_update_used_flags(vq);
1686 if (r) {
1687 vq_err(vq, "Failed to enable notification at %p: %d\n",
1688 &vq->used->flags, r);
1689 return false;
1690 }
1691 } else {
1692 r = vhost_update_avail_event(vq, vq->avail_idx);
1693 if (r) {
1694 vq_err(vq, "Failed to update avail event index at %p: %d\n",
1695 vhost_avail_event(vq), r);
1696 return false;
1697 }
1698 }
1699 /* They could have slipped one in as we were doing that: make
1700 * sure it's written, then check again. */
1701 smp_mb();
1702 r = __get_user(avail_idx, &vq->avail->idx);
1703 if (r) {
1704 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1705 &vq->avail->idx, r);
1706 return false;
1707 }
1708
1709 return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
1710 }
1711 EXPORT_SYMBOL_GPL(vhost_enable_notify);
1712
1713 /* We don't need to be notified again. */
1714 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1715 {
1716 int r;
1717
1718 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1719 return;
1720 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1721 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1722 r = vhost_update_used_flags(vq);
1723 if (r)
1724 vq_err(vq, "Failed to enable notification at %p: %d\n",
1725 &vq->used->flags, r);
1726 }
1727 }
1728 EXPORT_SYMBOL_GPL(vhost_disable_notify);
1729
1730 static int __init vhost_init(void)
1731 {
1732 return 0;
1733 }
1734
1735 static void __exit vhost_exit(void)
1736 {
1737 }
1738
1739 module_init(vhost_init);
1740 module_exit(vhost_exit);
1741
1742 MODULE_VERSION("0.0.1");
1743 MODULE_LICENSE("GPL v2");
1744 MODULE_AUTHOR("Michael S. Tsirkin");
1745 MODULE_DESCRIPTION("Host kernel accelerator for virtio");