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