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