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