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