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