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