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