GNU Linux-libre 4.9.337-gnu1
[releases.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 #include <linux/interval_tree_generic.h>
31 #include <linux/nospec.h>
32
33 #include "vhost.h"
34
35 static ushort max_mem_regions = 64;
36 module_param(max_mem_regions, ushort, 0444);
37 MODULE_PARM_DESC(max_mem_regions,
38         "Maximum number of memory regions in memory map. (default: 64)");
39 static int max_iotlb_entries = 2048;
40 module_param(max_iotlb_entries, int, 0444);
41 MODULE_PARM_DESC(max_iotlb_entries,
42         "Maximum number of iotlb entries. (default: 2048)");
43
44 enum {
45         VHOST_MEMORY_F_LOG = 0x1,
46 };
47
48 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
49 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
50
51 INTERVAL_TREE_DEFINE(struct vhost_umem_node,
52                      rb, __u64, __subtree_last,
53                      START, LAST, , vhost_umem_interval_tree);
54
55 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
56 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
57 {
58         vq->user_be = !virtio_legacy_is_little_endian();
59 }
60
61 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
62 {
63         vq->user_be = true;
64 }
65
66 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
67 {
68         vq->user_be = false;
69 }
70
71 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
72 {
73         struct vhost_vring_state s;
74
75         if (vq->private_data)
76                 return -EBUSY;
77
78         if (copy_from_user(&s, argp, sizeof(s)))
79                 return -EFAULT;
80
81         if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
82             s.num != VHOST_VRING_BIG_ENDIAN)
83                 return -EINVAL;
84
85         if (s.num == VHOST_VRING_BIG_ENDIAN)
86                 vhost_enable_cross_endian_big(vq);
87         else
88                 vhost_enable_cross_endian_little(vq);
89
90         return 0;
91 }
92
93 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
94                                    int __user *argp)
95 {
96         struct vhost_vring_state s = {
97                 .index = idx,
98                 .num = vq->user_be
99         };
100
101         if (copy_to_user(argp, &s, sizeof(s)))
102                 return -EFAULT;
103
104         return 0;
105 }
106
107 static void vhost_init_is_le(struct vhost_virtqueue *vq)
108 {
109         /* Note for legacy virtio: user_be is initialized at reset time
110          * according to the host endianness. If userspace does not set an
111          * explicit endianness, the default behavior is native endian, as
112          * expected by legacy virtio.
113          */
114         vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
115 }
116 #else
117 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
118 {
119 }
120
121 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
122 {
123         return -ENOIOCTLCMD;
124 }
125
126 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
127                                    int __user *argp)
128 {
129         return -ENOIOCTLCMD;
130 }
131
132 static void vhost_init_is_le(struct vhost_virtqueue *vq)
133 {
134         vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
135                 || virtio_legacy_is_little_endian();
136 }
137 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
138
139 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
140 {
141         vhost_init_is_le(vq);
142 }
143
144 struct vhost_flush_struct {
145         struct vhost_work work;
146         struct completion wait_event;
147 };
148
149 static void vhost_flush_work(struct vhost_work *work)
150 {
151         struct vhost_flush_struct *s;
152
153         s = container_of(work, struct vhost_flush_struct, work);
154         complete(&s->wait_event);
155 }
156
157 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
158                             poll_table *pt)
159 {
160         struct vhost_poll *poll;
161
162         poll = container_of(pt, struct vhost_poll, table);
163         poll->wqh = wqh;
164         add_wait_queue(wqh, &poll->wait);
165 }
166
167 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
168                              void *key)
169 {
170         struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
171
172         if (!((unsigned long)key & poll->mask))
173                 return 0;
174
175         vhost_poll_queue(poll);
176         return 0;
177 }
178
179 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
180 {
181         clear_bit(VHOST_WORK_QUEUED, &work->flags);
182         work->fn = fn;
183         init_waitqueue_head(&work->done);
184 }
185 EXPORT_SYMBOL_GPL(vhost_work_init);
186
187 /* Init poll structure */
188 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
189                      unsigned long mask, struct vhost_dev *dev)
190 {
191         init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
192         init_poll_funcptr(&poll->table, vhost_poll_func);
193         poll->mask = mask;
194         poll->dev = dev;
195         poll->wqh = NULL;
196
197         vhost_work_init(&poll->work, fn);
198 }
199 EXPORT_SYMBOL_GPL(vhost_poll_init);
200
201 /* Start polling a file. We add ourselves to file's wait queue. The caller must
202  * keep a reference to a file until after vhost_poll_stop is called. */
203 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
204 {
205         unsigned long mask;
206         int ret = 0;
207
208         if (poll->wqh)
209                 return 0;
210
211         mask = file->f_op->poll(file, &poll->table);
212         if (mask)
213                 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
214         if (mask & POLLERR) {
215                 vhost_poll_stop(poll);
216                 ret = -EINVAL;
217         }
218
219         return ret;
220 }
221 EXPORT_SYMBOL_GPL(vhost_poll_start);
222
223 /* Stop polling a file. After this function returns, it becomes safe to drop the
224  * file reference. You must also flush afterwards. */
225 void vhost_poll_stop(struct vhost_poll *poll)
226 {
227         if (poll->wqh) {
228                 remove_wait_queue(poll->wqh, &poll->wait);
229                 poll->wqh = NULL;
230         }
231 }
232 EXPORT_SYMBOL_GPL(vhost_poll_stop);
233
234 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
235 {
236         struct vhost_flush_struct flush;
237
238         if (dev->worker) {
239                 init_completion(&flush.wait_event);
240                 vhost_work_init(&flush.work, vhost_flush_work);
241
242                 vhost_work_queue(dev, &flush.work);
243                 wait_for_completion(&flush.wait_event);
244         }
245 }
246 EXPORT_SYMBOL_GPL(vhost_work_flush);
247
248 /* Flush any work that has been scheduled. When calling this, don't hold any
249  * locks that are also used by the callback. */
250 void vhost_poll_flush(struct vhost_poll *poll)
251 {
252         vhost_work_flush(poll->dev, &poll->work);
253 }
254 EXPORT_SYMBOL_GPL(vhost_poll_flush);
255
256 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
257 {
258         if (!dev->worker)
259                 return;
260
261         if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
262                 /* We can only add the work to the list after we're
263                  * sure it was not in the list.
264                  */
265                 smp_mb();
266                 llist_add(&work->node, &dev->work_list);
267                 wake_up_process(dev->worker);
268         }
269 }
270 EXPORT_SYMBOL_GPL(vhost_work_queue);
271
272 /* A lockless hint for busy polling code to exit the loop */
273 bool vhost_has_work(struct vhost_dev *dev)
274 {
275         return !llist_empty(&dev->work_list);
276 }
277 EXPORT_SYMBOL_GPL(vhost_has_work);
278
279 void vhost_poll_queue(struct vhost_poll *poll)
280 {
281         vhost_work_queue(poll->dev, &poll->work);
282 }
283 EXPORT_SYMBOL_GPL(vhost_poll_queue);
284
285 static void vhost_vq_reset(struct vhost_dev *dev,
286                            struct vhost_virtqueue *vq)
287 {
288         vq->num = 1;
289         vq->desc = NULL;
290         vq->avail = NULL;
291         vq->used = NULL;
292         vq->last_avail_idx = 0;
293         vq->avail_idx = 0;
294         vq->last_used_idx = 0;
295         vq->signalled_used = 0;
296         vq->signalled_used_valid = false;
297         vq->used_flags = 0;
298         vq->log_used = false;
299         vq->log_addr = -1ull;
300         vq->private_data = NULL;
301         vq->acked_features = 0;
302         vq->log_base = NULL;
303         vq->error_ctx = NULL;
304         vq->error = NULL;
305         vq->kick = NULL;
306         vq->call_ctx = NULL;
307         vq->call = NULL;
308         vq->log_ctx = NULL;
309         vhost_disable_cross_endian(vq);
310         vhost_reset_is_le(vq);
311         vq->busyloop_timeout = 0;
312         vq->umem = NULL;
313         vq->iotlb = NULL;
314 }
315
316 static int vhost_worker(void *data)
317 {
318         struct vhost_dev *dev = data;
319         struct vhost_work *work, *work_next;
320         struct llist_node *node;
321         mm_segment_t oldfs = get_fs();
322
323         set_fs(USER_DS);
324         use_mm(dev->mm);
325
326         for (;;) {
327                 /* mb paired w/ kthread_stop */
328                 set_current_state(TASK_INTERRUPTIBLE);
329
330                 if (kthread_should_stop()) {
331                         __set_current_state(TASK_RUNNING);
332                         break;
333                 }
334
335                 node = llist_del_all(&dev->work_list);
336                 if (!node)
337                         schedule();
338
339                 node = llist_reverse_order(node);
340                 /* make sure flag is seen after deletion */
341                 smp_wmb();
342                 llist_for_each_entry_safe(work, work_next, node, node) {
343                         clear_bit(VHOST_WORK_QUEUED, &work->flags);
344                         __set_current_state(TASK_RUNNING);
345                         work->fn(work);
346                         if (need_resched())
347                                 schedule();
348                 }
349         }
350         unuse_mm(dev->mm);
351         set_fs(oldfs);
352         return 0;
353 }
354
355 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
356 {
357         kfree(vq->indirect);
358         vq->indirect = NULL;
359         kfree(vq->log);
360         vq->log = NULL;
361         kfree(vq->heads);
362         vq->heads = NULL;
363 }
364
365 /* Helper to allocate iovec buffers for all vqs. */
366 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
367 {
368         struct vhost_virtqueue *vq;
369         int i;
370
371         for (i = 0; i < dev->nvqs; ++i) {
372                 vq = dev->vqs[i];
373                 vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
374                                        GFP_KERNEL);
375                 vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
376                 vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
377                 if (!vq->indirect || !vq->log || !vq->heads)
378                         goto err_nomem;
379         }
380         return 0;
381
382 err_nomem:
383         for (; i >= 0; --i)
384                 vhost_vq_free_iovecs(dev->vqs[i]);
385         return -ENOMEM;
386 }
387
388 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
389 {
390         int i;
391
392         for (i = 0; i < dev->nvqs; ++i)
393                 vhost_vq_free_iovecs(dev->vqs[i]);
394 }
395
396 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
397                           int pkts, int total_len)
398 {
399         struct vhost_dev *dev = vq->dev;
400
401         if ((dev->byte_weight && total_len >= dev->byte_weight) ||
402             pkts >= dev->weight) {
403                 vhost_poll_queue(&vq->poll);
404                 return true;
405         }
406
407         return false;
408 }
409 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
410
411 void vhost_dev_init(struct vhost_dev *dev,
412                     struct vhost_virtqueue **vqs, int nvqs,
413                     int weight, int byte_weight)
414 {
415         struct vhost_virtqueue *vq;
416         int i;
417
418         dev->vqs = vqs;
419         dev->nvqs = nvqs;
420         mutex_init(&dev->mutex);
421         dev->log_ctx = NULL;
422         dev->log_file = NULL;
423         dev->umem = NULL;
424         dev->iotlb = NULL;
425         dev->mm = NULL;
426         dev->worker = NULL;
427         dev->weight = weight;
428         dev->byte_weight = byte_weight;
429         init_llist_head(&dev->work_list);
430         init_waitqueue_head(&dev->wait);
431         INIT_LIST_HEAD(&dev->read_list);
432         INIT_LIST_HEAD(&dev->pending_list);
433         spin_lock_init(&dev->iotlb_lock);
434
435
436         for (i = 0; i < dev->nvqs; ++i) {
437                 vq = dev->vqs[i];
438                 vq->log = NULL;
439                 vq->indirect = NULL;
440                 vq->heads = NULL;
441                 vq->dev = dev;
442                 mutex_init(&vq->mutex);
443                 vhost_vq_reset(dev, vq);
444                 if (vq->handle_kick)
445                         vhost_poll_init(&vq->poll, vq->handle_kick,
446                                         POLLIN, dev);
447         }
448 }
449 EXPORT_SYMBOL_GPL(vhost_dev_init);
450
451 /* Caller should have device mutex */
452 long vhost_dev_check_owner(struct vhost_dev *dev)
453 {
454         /* Are you the owner? If not, I don't think you mean to do that */
455         return dev->mm == current->mm ? 0 : -EPERM;
456 }
457 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
458
459 struct vhost_attach_cgroups_struct {
460         struct vhost_work work;
461         struct task_struct *owner;
462         int ret;
463 };
464
465 static void vhost_attach_cgroups_work(struct vhost_work *work)
466 {
467         struct vhost_attach_cgroups_struct *s;
468
469         s = container_of(work, struct vhost_attach_cgroups_struct, work);
470         s->ret = cgroup_attach_task_all(s->owner, current);
471 }
472
473 static int vhost_attach_cgroups(struct vhost_dev *dev)
474 {
475         struct vhost_attach_cgroups_struct attach;
476
477         attach.owner = current;
478         vhost_work_init(&attach.work, vhost_attach_cgroups_work);
479         vhost_work_queue(dev, &attach.work);
480         vhost_work_flush(dev, &attach.work);
481         return attach.ret;
482 }
483
484 /* Caller should have device mutex */
485 bool vhost_dev_has_owner(struct vhost_dev *dev)
486 {
487         return dev->mm;
488 }
489 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
490
491 /* Caller should have device mutex */
492 long vhost_dev_set_owner(struct vhost_dev *dev)
493 {
494         struct task_struct *worker;
495         int err;
496
497         /* Is there an owner already? */
498         if (vhost_dev_has_owner(dev)) {
499                 err = -EBUSY;
500                 goto err_mm;
501         }
502
503         /* No owner, become one */
504         dev->mm = get_task_mm(current);
505         worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
506         if (IS_ERR(worker)) {
507                 err = PTR_ERR(worker);
508                 goto err_worker;
509         }
510
511         dev->worker = worker;
512         wake_up_process(worker);        /* avoid contributing to loadavg */
513
514         err = vhost_attach_cgroups(dev);
515         if (err)
516                 goto err_cgroup;
517
518         err = vhost_dev_alloc_iovecs(dev);
519         if (err)
520                 goto err_cgroup;
521
522         return 0;
523 err_cgroup:
524         kthread_stop(worker);
525         dev->worker = NULL;
526 err_worker:
527         if (dev->mm)
528                 mmput(dev->mm);
529         dev->mm = NULL;
530 err_mm:
531         return err;
532 }
533 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
534
535 static void *vhost_kvzalloc(unsigned long size)
536 {
537         void *n = kzalloc(size, GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
538
539         if (!n)
540                 n = vzalloc(size);
541         return n;
542 }
543
544 struct vhost_umem *vhost_dev_reset_owner_prepare(void)
545 {
546         return vhost_kvzalloc(sizeof(struct vhost_umem));
547 }
548 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
549
550 /* Caller should have device mutex */
551 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_umem *umem)
552 {
553         int i;
554
555         vhost_dev_cleanup(dev, true);
556
557         /* Restore memory to default empty mapping. */
558         INIT_LIST_HEAD(&umem->umem_list);
559         dev->umem = umem;
560         /* We don't need VQ locks below since vhost_dev_cleanup makes sure
561          * VQs aren't running.
562          */
563         for (i = 0; i < dev->nvqs; ++i)
564                 dev->vqs[i]->umem = umem;
565 }
566 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
567
568 void vhost_dev_stop(struct vhost_dev *dev)
569 {
570         int i;
571
572         for (i = 0; i < dev->nvqs; ++i) {
573                 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
574                         vhost_poll_stop(&dev->vqs[i]->poll);
575                         vhost_poll_flush(&dev->vqs[i]->poll);
576                 }
577         }
578 }
579 EXPORT_SYMBOL_GPL(vhost_dev_stop);
580
581 static void vhost_umem_free(struct vhost_umem *umem,
582                             struct vhost_umem_node *node)
583 {
584         vhost_umem_interval_tree_remove(node, &umem->umem_tree);
585         list_del(&node->link);
586         kfree(node);
587         umem->numem--;
588 }
589
590 static void vhost_umem_clean(struct vhost_umem *umem)
591 {
592         struct vhost_umem_node *node, *tmp;
593
594         if (!umem)
595                 return;
596
597         list_for_each_entry_safe(node, tmp, &umem->umem_list, link)
598                 vhost_umem_free(umem, node);
599
600         kvfree(umem);
601 }
602
603 static void vhost_clear_msg(struct vhost_dev *dev)
604 {
605         struct vhost_msg_node *node, *n;
606
607         spin_lock(&dev->iotlb_lock);
608
609         list_for_each_entry_safe(node, n, &dev->read_list, node) {
610                 list_del(&node->node);
611                 kfree(node);
612         }
613
614         list_for_each_entry_safe(node, n, &dev->pending_list, node) {
615                 list_del(&node->node);
616                 kfree(node);
617         }
618
619         spin_unlock(&dev->iotlb_lock);
620 }
621
622 /* Caller should have device mutex if and only if locked is set */
623 void vhost_dev_cleanup(struct vhost_dev *dev, bool locked)
624 {
625         int i;
626
627         for (i = 0; i < dev->nvqs; ++i) {
628                 if (dev->vqs[i]->error_ctx)
629                         eventfd_ctx_put(dev->vqs[i]->error_ctx);
630                 if (dev->vqs[i]->error)
631                         fput(dev->vqs[i]->error);
632                 if (dev->vqs[i]->kick)
633                         fput(dev->vqs[i]->kick);
634                 if (dev->vqs[i]->call_ctx)
635                         eventfd_ctx_put(dev->vqs[i]->call_ctx);
636                 if (dev->vqs[i]->call)
637                         fput(dev->vqs[i]->call);
638                 vhost_vq_reset(dev, dev->vqs[i]);
639         }
640         vhost_dev_free_iovecs(dev);
641         if (dev->log_ctx)
642                 eventfd_ctx_put(dev->log_ctx);
643         dev->log_ctx = NULL;
644         if (dev->log_file)
645                 fput(dev->log_file);
646         dev->log_file = NULL;
647         /* No one will access memory at this point */
648         vhost_umem_clean(dev->umem);
649         dev->umem = NULL;
650         vhost_umem_clean(dev->iotlb);
651         dev->iotlb = NULL;
652         vhost_clear_msg(dev);
653         wake_up_interruptible_poll(&dev->wait, POLLIN | POLLRDNORM);
654         WARN_ON(!llist_empty(&dev->work_list));
655         if (dev->worker) {
656                 kthread_stop(dev->worker);
657                 dev->worker = NULL;
658         }
659         if (dev->mm)
660                 mmput(dev->mm);
661         dev->mm = NULL;
662 }
663 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
664
665 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
666 {
667         u64 a = addr / VHOST_PAGE_SIZE / 8;
668
669         /* Make sure 64 bit math will not overflow. */
670         if (a > ULONG_MAX - (unsigned long)log_base ||
671             a + (unsigned long)log_base > ULONG_MAX)
672                 return 0;
673
674         return access_ok(VERIFY_WRITE, log_base + a,
675                          (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
676 }
677
678 /* Make sure 64 bit math will not overflow. */
679 static bool vhost_overflow(u64 uaddr, u64 size)
680 {
681         if (uaddr > ULONG_MAX || size > ULONG_MAX)
682                 return true;
683
684         if (!size)
685                 return false;
686
687         return uaddr > ULONG_MAX - size + 1;
688 }
689
690 /* Caller should have vq mutex and device mutex. */
691 static int vq_memory_access_ok(void __user *log_base, struct vhost_umem *umem,
692                                int log_all)
693 {
694         struct vhost_umem_node *node;
695
696         if (!umem)
697                 return 0;
698
699         list_for_each_entry(node, &umem->umem_list, link) {
700                 unsigned long a = node->userspace_addr;
701
702                 if (vhost_overflow(node->userspace_addr, node->size))
703                         return 0;
704
705
706                 if (!access_ok(VERIFY_WRITE, (void __user *)a,
707                                     node->size))
708                         return 0;
709                 else if (log_all && !log_access_ok(log_base,
710                                                    node->start,
711                                                    node->size))
712                         return 0;
713         }
714         return 1;
715 }
716
717 /* Can we switch to this memory table? */
718 /* Caller should have device mutex but not vq mutex */
719 static int memory_access_ok(struct vhost_dev *d, struct vhost_umem *umem,
720                             int log_all)
721 {
722         int i;
723
724         for (i = 0; i < d->nvqs; ++i) {
725                 int ok;
726                 bool log;
727
728                 mutex_lock(&d->vqs[i]->mutex);
729                 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
730                 /* If ring is inactive, will check when it's enabled. */
731                 if (d->vqs[i]->private_data)
732                         ok = vq_memory_access_ok(d->vqs[i]->log_base,
733                                                  umem, log);
734                 else
735                         ok = 1;
736                 mutex_unlock(&d->vqs[i]->mutex);
737                 if (!ok)
738                         return 0;
739         }
740         return 1;
741 }
742
743 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
744                           struct iovec iov[], int iov_size, int access);
745
746 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void *to,
747                               const void *from, unsigned size)
748 {
749         int ret;
750
751         if (!vq->iotlb)
752                 return __copy_to_user(to, from, size);
753         else {
754                 /* This function should be called after iotlb
755                  * prefetch, which means we're sure that all vq
756                  * could be access through iotlb. So -EAGAIN should
757                  * not happen in this case.
758                  */
759                 /* TODO: more fast path */
760                 struct iov_iter t;
761                 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
762                                      ARRAY_SIZE(vq->iotlb_iov),
763                                      VHOST_ACCESS_WO);
764                 if (ret < 0)
765                         goto out;
766                 iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
767                 ret = copy_to_iter(from, size, &t);
768                 if (ret == size)
769                         ret = 0;
770         }
771 out:
772         return ret;
773 }
774
775 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
776                                 void *from, unsigned size)
777 {
778         int ret;
779
780         if (!vq->iotlb)
781                 return __copy_from_user(to, from, size);
782         else {
783                 /* This function should be called after iotlb
784                  * prefetch, which means we're sure that vq
785                  * could be access through iotlb. So -EAGAIN should
786                  * not happen in this case.
787                  */
788                 /* TODO: more fast path */
789                 struct iov_iter f;
790                 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
791                                      ARRAY_SIZE(vq->iotlb_iov),
792                                      VHOST_ACCESS_RO);
793                 if (ret < 0) {
794                         vq_err(vq, "IOTLB translation failure: uaddr "
795                                "%p size 0x%llx\n", from,
796                                (unsigned long long) size);
797                         goto out;
798                 }
799                 iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
800                 ret = copy_from_iter(to, size, &f);
801                 if (ret == size)
802                         ret = 0;
803         }
804
805 out:
806         return ret;
807 }
808
809 static void __user *__vhost_get_user(struct vhost_virtqueue *vq,
810                                      void *addr, unsigned size)
811 {
812         int ret;
813
814         /* This function should be called after iotlb
815          * prefetch, which means we're sure that vq
816          * could be access through iotlb. So -EAGAIN should
817          * not happen in this case.
818          */
819         /* TODO: more fast path */
820         ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
821                              ARRAY_SIZE(vq->iotlb_iov),
822                              VHOST_ACCESS_RO);
823         if (ret < 0) {
824                 vq_err(vq, "IOTLB translation failure: uaddr "
825                         "%p size 0x%llx\n", addr,
826                         (unsigned long long) size);
827                 return NULL;
828         }
829
830         if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
831                 vq_err(vq, "Non atomic userspace memory access: uaddr "
832                         "%p size 0x%llx\n", addr,
833                         (unsigned long long) size);
834                 return NULL;
835         }
836
837         return vq->iotlb_iov[0].iov_base;
838 }
839
840 #define vhost_put_user(vq, x, ptr) \
841 ({ \
842         int ret = -EFAULT; \
843         if (!vq->iotlb) { \
844                 ret = __put_user(x, ptr); \
845         } else { \
846                 __typeof__(ptr) to = \
847                         (__typeof__(ptr)) __vhost_get_user(vq, ptr, sizeof(*ptr)); \
848                 if (to != NULL) \
849                         ret = __put_user(x, to); \
850                 else \
851                         ret = -EFAULT;  \
852         } \
853         ret; \
854 })
855
856 #define vhost_get_user(vq, x, ptr) \
857 ({ \
858         int ret; \
859         if (!vq->iotlb) { \
860                 ret = __get_user(x, ptr); \
861         } else { \
862                 __typeof__(ptr) from = \
863                         (__typeof__(ptr)) __vhost_get_user(vq, ptr, sizeof(*ptr)); \
864                 if (from != NULL) \
865                         ret = __get_user(x, from); \
866                 else \
867                         ret = -EFAULT; \
868         } \
869         ret; \
870 })
871
872 static void vhost_dev_lock_vqs(struct vhost_dev *d)
873 {
874         int i = 0;
875         for (i = 0; i < d->nvqs; ++i)
876                 mutex_lock_nested(&d->vqs[i]->mutex, i);
877 }
878
879 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
880 {
881         int i = 0;
882         for (i = 0; i < d->nvqs; ++i)
883                 mutex_unlock(&d->vqs[i]->mutex);
884 }
885
886 static int vhost_new_umem_range(struct vhost_umem *umem,
887                                 u64 start, u64 size, u64 end,
888                                 u64 userspace_addr, int perm)
889 {
890         struct vhost_umem_node *tmp, *node;
891
892         if (!size)
893                 return -EFAULT;
894
895         node = kmalloc(sizeof(*node), GFP_ATOMIC);
896         if (!node)
897                 return -ENOMEM;
898
899         if (umem->numem == max_iotlb_entries) {
900                 tmp = list_first_entry(&umem->umem_list, typeof(*tmp), link);
901                 vhost_umem_free(umem, tmp);
902         }
903
904         node->start = start;
905         node->size = size;
906         node->last = end;
907         node->userspace_addr = userspace_addr;
908         node->perm = perm;
909         INIT_LIST_HEAD(&node->link);
910         list_add_tail(&node->link, &umem->umem_list);
911         vhost_umem_interval_tree_insert(node, &umem->umem_tree);
912         umem->numem++;
913
914         return 0;
915 }
916
917 static void vhost_del_umem_range(struct vhost_umem *umem,
918                                  u64 start, u64 end)
919 {
920         struct vhost_umem_node *node;
921
922         while ((node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
923                                                            start, end)))
924                 vhost_umem_free(umem, node);
925 }
926
927 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
928                                   struct vhost_iotlb_msg *msg)
929 {
930         struct vhost_msg_node *node, *n;
931
932         spin_lock(&d->iotlb_lock);
933
934         list_for_each_entry_safe(node, n, &d->pending_list, node) {
935                 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
936                 if (msg->iova <= vq_msg->iova &&
937                     msg->iova + msg->size - 1 >= vq_msg->iova &&
938                     vq_msg->type == VHOST_IOTLB_MISS) {
939                         vhost_poll_queue(&node->vq->poll);
940                         list_del(&node->node);
941                         kfree(node);
942                 }
943         }
944
945         spin_unlock(&d->iotlb_lock);
946 }
947
948 static int umem_access_ok(u64 uaddr, u64 size, int access)
949 {
950         unsigned long a = uaddr;
951
952         /* Make sure 64 bit math will not overflow. */
953         if (vhost_overflow(uaddr, size))
954                 return -EFAULT;
955
956         if ((access & VHOST_ACCESS_RO) &&
957             !access_ok(VERIFY_READ, (void __user *)a, size))
958                 return -EFAULT;
959         if ((access & VHOST_ACCESS_WO) &&
960             !access_ok(VERIFY_WRITE, (void __user *)a, size))
961                 return -EFAULT;
962         return 0;
963 }
964
965 int vhost_process_iotlb_msg(struct vhost_dev *dev,
966                             struct vhost_iotlb_msg *msg)
967 {
968         int ret = 0;
969
970         mutex_lock(&dev->mutex);
971         vhost_dev_lock_vqs(dev);
972         switch (msg->type) {
973         case VHOST_IOTLB_UPDATE:
974                 if (!dev->iotlb) {
975                         ret = -EFAULT;
976                         break;
977                 }
978                 if (umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
979                         ret = -EFAULT;
980                         break;
981                 }
982                 if (vhost_new_umem_range(dev->iotlb, msg->iova, msg->size,
983                                          msg->iova + msg->size - 1,
984                                          msg->uaddr, msg->perm)) {
985                         ret = -ENOMEM;
986                         break;
987                 }
988                 vhost_iotlb_notify_vq(dev, msg);
989                 break;
990         case VHOST_IOTLB_INVALIDATE:
991                 vhost_del_umem_range(dev->iotlb, msg->iova,
992                                      msg->iova + msg->size - 1);
993                 break;
994         default:
995                 ret = -EINVAL;
996                 break;
997         }
998
999         vhost_dev_unlock_vqs(dev);
1000         mutex_unlock(&dev->mutex);
1001
1002         return ret;
1003 }
1004 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1005                              struct iov_iter *from)
1006 {
1007         struct vhost_msg_node node;
1008         unsigned size = sizeof(struct vhost_msg);
1009         size_t ret;
1010         int err;
1011
1012         if (iov_iter_count(from) < size)
1013                 return 0;
1014         ret = copy_from_iter(&node.msg, size, from);
1015         if (ret != size)
1016                 goto done;
1017
1018         switch (node.msg.type) {
1019         case VHOST_IOTLB_MSG:
1020                 err = vhost_process_iotlb_msg(dev, &node.msg.iotlb);
1021                 if (err)
1022                         ret = err;
1023                 break;
1024         default:
1025                 ret = -EINVAL;
1026                 break;
1027         }
1028
1029 done:
1030         return ret;
1031 }
1032 EXPORT_SYMBOL(vhost_chr_write_iter);
1033
1034 unsigned int vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1035                             poll_table *wait)
1036 {
1037         unsigned int mask = 0;
1038
1039         poll_wait(file, &dev->wait, wait);
1040
1041         if (!list_empty(&dev->read_list))
1042                 mask |= POLLIN | POLLRDNORM;
1043
1044         return mask;
1045 }
1046 EXPORT_SYMBOL(vhost_chr_poll);
1047
1048 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1049                             int noblock)
1050 {
1051         DEFINE_WAIT(wait);
1052         struct vhost_msg_node *node;
1053         ssize_t ret = 0;
1054         unsigned size = sizeof(struct vhost_msg);
1055
1056         if (iov_iter_count(to) < size)
1057                 return 0;
1058
1059         while (1) {
1060                 if (!noblock)
1061                         prepare_to_wait(&dev->wait, &wait,
1062                                         TASK_INTERRUPTIBLE);
1063
1064                 node = vhost_dequeue_msg(dev, &dev->read_list);
1065                 if (node)
1066                         break;
1067                 if (noblock) {
1068                         ret = -EAGAIN;
1069                         break;
1070                 }
1071                 if (signal_pending(current)) {
1072                         ret = -ERESTARTSYS;
1073                         break;
1074                 }
1075                 if (!dev->iotlb) {
1076                         ret = -EBADFD;
1077                         break;
1078                 }
1079
1080                 schedule();
1081         }
1082
1083         if (!noblock)
1084                 finish_wait(&dev->wait, &wait);
1085
1086         if (node) {
1087                 ret = copy_to_iter(&node->msg, size, to);
1088
1089                 if (ret != size || node->msg.type != VHOST_IOTLB_MISS) {
1090                         kfree(node);
1091                         return ret;
1092                 }
1093
1094                 vhost_enqueue_msg(dev, &dev->pending_list, node);
1095         }
1096
1097         return ret;
1098 }
1099 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1100
1101 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1102 {
1103         struct vhost_dev *dev = vq->dev;
1104         struct vhost_msg_node *node;
1105         struct vhost_iotlb_msg *msg;
1106
1107         node = vhost_new_msg(vq, VHOST_IOTLB_MISS);
1108         if (!node)
1109                 return -ENOMEM;
1110
1111         msg = &node->msg.iotlb;
1112         msg->type = VHOST_IOTLB_MISS;
1113         msg->iova = iova;
1114         msg->perm = access;
1115
1116         vhost_enqueue_msg(dev, &dev->read_list, node);
1117
1118         return 0;
1119 }
1120
1121 static int vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1122                         struct vring_desc __user *desc,
1123                         struct vring_avail __user *avail,
1124                         struct vring_used __user *used)
1125
1126 {
1127         size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1128
1129         return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
1130                access_ok(VERIFY_READ, avail,
1131                          sizeof *avail + num * sizeof *avail->ring + s) &&
1132                access_ok(VERIFY_WRITE, used,
1133                         sizeof *used + num * sizeof *used->ring + s);
1134 }
1135
1136 static int iotlb_access_ok(struct vhost_virtqueue *vq,
1137                            int access, u64 addr, u64 len)
1138 {
1139         const struct vhost_umem_node *node;
1140         struct vhost_umem *umem = vq->iotlb;
1141         u64 s = 0, size;
1142
1143         while (len > s) {
1144                 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1145                                                            addr,
1146                                                            addr + len - 1);
1147                 if (node == NULL || node->start > addr) {
1148                         vhost_iotlb_miss(vq, addr, access);
1149                         return false;
1150                 } else if (!(node->perm & access)) {
1151                         /* Report the possible access violation by
1152                          * request another translation from userspace.
1153                          */
1154                         return false;
1155                 }
1156
1157                 size = node->size - addr + node->start;
1158                 s += size;
1159                 addr += size;
1160         }
1161
1162         return true;
1163 }
1164
1165 int vq_iotlb_prefetch(struct vhost_virtqueue *vq)
1166 {
1167         size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1168         unsigned int num = vq->num;
1169
1170         if (!vq->iotlb)
1171                 return 1;
1172
1173         return iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->desc,
1174                                num * sizeof *vq->desc) &&
1175                iotlb_access_ok(vq, VHOST_ACCESS_RO, (u64)(uintptr_t)vq->avail,
1176                                sizeof *vq->avail +
1177                                num * sizeof *vq->avail->ring + s) &&
1178                iotlb_access_ok(vq, VHOST_ACCESS_WO, (u64)(uintptr_t)vq->used,
1179                                sizeof *vq->used +
1180                                num * sizeof *vq->used->ring + s);
1181 }
1182 EXPORT_SYMBOL_GPL(vq_iotlb_prefetch);
1183
1184 /* Can we log writes? */
1185 /* Caller should have device mutex but not vq mutex */
1186 int vhost_log_access_ok(struct vhost_dev *dev)
1187 {
1188         return memory_access_ok(dev, dev->umem, 1);
1189 }
1190 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
1191
1192 /* Verify access for write logging. */
1193 /* Caller should have vq mutex and device mutex */
1194 static int vq_log_access_ok(struct vhost_virtqueue *vq,
1195                             void __user *log_base)
1196 {
1197         size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
1198
1199         return vq_memory_access_ok(log_base, vq->umem,
1200                                    vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
1201                 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
1202                                         sizeof *vq->used +
1203                                         vq->num * sizeof *vq->used->ring + s));
1204 }
1205
1206 /* Can we start vq? */
1207 /* Caller should have vq mutex and device mutex */
1208 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
1209 {
1210         if (!vq_log_access_ok(vq, vq->log_base))
1211                 return 0;
1212
1213         /* Access validation occurs at prefetch time with IOTLB */
1214         if (vq->iotlb)
1215                 return 1;
1216
1217         return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
1218 }
1219 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
1220
1221 static struct vhost_umem *vhost_umem_alloc(void)
1222 {
1223         struct vhost_umem *umem = vhost_kvzalloc(sizeof(*umem));
1224
1225         if (!umem)
1226                 return NULL;
1227
1228         umem->umem_tree = RB_ROOT;
1229         umem->numem = 0;
1230         INIT_LIST_HEAD(&umem->umem_list);
1231
1232         return umem;
1233 }
1234
1235 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1236 {
1237         struct vhost_memory mem, *newmem;
1238         struct vhost_memory_region *region;
1239         struct vhost_umem *newumem, *oldumem;
1240         unsigned long size = offsetof(struct vhost_memory, regions);
1241         int i;
1242
1243         if (copy_from_user(&mem, m, size))
1244                 return -EFAULT;
1245         if (mem.padding)
1246                 return -EOPNOTSUPP;
1247         if (mem.nregions > max_mem_regions)
1248                 return -E2BIG;
1249         newmem = vhost_kvzalloc(size + mem.nregions * sizeof(*m->regions));
1250         if (!newmem)
1251                 return -ENOMEM;
1252
1253         memcpy(newmem, &mem, size);
1254         if (copy_from_user(newmem->regions, m->regions,
1255                            mem.nregions * sizeof *m->regions)) {
1256                 kvfree(newmem);
1257                 return -EFAULT;
1258         }
1259
1260         newumem = vhost_umem_alloc();
1261         if (!newumem) {
1262                 kvfree(newmem);
1263                 return -ENOMEM;
1264         }
1265
1266         for (region = newmem->regions;
1267              region < newmem->regions + mem.nregions;
1268              region++) {
1269                 if (vhost_new_umem_range(newumem,
1270                                          region->guest_phys_addr,
1271                                          region->memory_size,
1272                                          region->guest_phys_addr +
1273                                          region->memory_size - 1,
1274                                          region->userspace_addr,
1275                                          VHOST_ACCESS_RW))
1276                         goto err;
1277         }
1278
1279         if (!memory_access_ok(d, newumem, 0))
1280                 goto err;
1281
1282         oldumem = d->umem;
1283         d->umem = newumem;
1284
1285         /* All memory accesses are done under some VQ mutex. */
1286         for (i = 0; i < d->nvqs; ++i) {
1287                 mutex_lock(&d->vqs[i]->mutex);
1288                 d->vqs[i]->umem = newumem;
1289                 mutex_unlock(&d->vqs[i]->mutex);
1290         }
1291
1292         kvfree(newmem);
1293         vhost_umem_clean(oldumem);
1294         return 0;
1295
1296 err:
1297         vhost_umem_clean(newumem);
1298         kvfree(newmem);
1299         return -EFAULT;
1300 }
1301
1302 long vhost_vring_ioctl(struct vhost_dev *d, int ioctl, void __user *argp)
1303 {
1304         struct file *eventfp, *filep = NULL;
1305         bool pollstart = false, pollstop = false;
1306         struct eventfd_ctx *ctx = NULL;
1307         u32 __user *idxp = argp;
1308         struct vhost_virtqueue *vq;
1309         struct vhost_vring_state s;
1310         struct vhost_vring_file f;
1311         struct vhost_vring_addr a;
1312         u32 idx;
1313         long r;
1314
1315         r = get_user(idx, idxp);
1316         if (r < 0)
1317                 return r;
1318         if (idx >= d->nvqs)
1319                 return -ENOBUFS;
1320
1321         idx = array_index_nospec(idx, d->nvqs);
1322         vq = d->vqs[idx];
1323
1324         mutex_lock(&vq->mutex);
1325
1326         switch (ioctl) {
1327         case VHOST_SET_VRING_NUM:
1328                 /* Resizing ring with an active backend?
1329                  * You don't want to do that. */
1330                 if (vq->private_data) {
1331                         r = -EBUSY;
1332                         break;
1333                 }
1334                 if (copy_from_user(&s, argp, sizeof s)) {
1335                         r = -EFAULT;
1336                         break;
1337                 }
1338                 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
1339                         r = -EINVAL;
1340                         break;
1341                 }
1342                 vq->num = s.num;
1343                 break;
1344         case VHOST_SET_VRING_BASE:
1345                 /* Moving base with an active backend?
1346                  * You don't want to do that. */
1347                 if (vq->private_data) {
1348                         r = -EBUSY;
1349                         break;
1350                 }
1351                 if (copy_from_user(&s, argp, sizeof s)) {
1352                         r = -EFAULT;
1353                         break;
1354                 }
1355                 if (s.num > 0xffff) {
1356                         r = -EINVAL;
1357                         break;
1358                 }
1359                 vq->last_avail_idx = s.num;
1360                 /* Forget the cached index value. */
1361                 vq->avail_idx = vq->last_avail_idx;
1362                 break;
1363         case VHOST_GET_VRING_BASE:
1364                 s.index = idx;
1365                 s.num = vq->last_avail_idx;
1366                 if (copy_to_user(argp, &s, sizeof s))
1367                         r = -EFAULT;
1368                 break;
1369         case VHOST_SET_VRING_ADDR:
1370                 if (copy_from_user(&a, argp, sizeof a)) {
1371                         r = -EFAULT;
1372                         break;
1373                 }
1374                 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
1375                         r = -EOPNOTSUPP;
1376                         break;
1377                 }
1378                 /* For 32bit, verify that the top 32bits of the user
1379                    data are set to zero. */
1380                 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1381                     (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1382                     (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
1383                         r = -EFAULT;
1384                         break;
1385                 }
1386
1387                 /* Make sure it's safe to cast pointers to vring types. */
1388                 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1389                 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1390                 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1391                     (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1392                     (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1))) {
1393                         r = -EINVAL;
1394                         break;
1395                 }
1396
1397                 /* We only verify access here if backend is configured.
1398                  * If it is not, we don't as size might not have been setup.
1399                  * We will verify when backend is configured. */
1400                 if (vq->private_data) {
1401                         if (!vq_access_ok(vq, vq->num,
1402                                 (void __user *)(unsigned long)a.desc_user_addr,
1403                                 (void __user *)(unsigned long)a.avail_user_addr,
1404                                 (void __user *)(unsigned long)a.used_user_addr)) {
1405                                 r = -EINVAL;
1406                                 break;
1407                         }
1408
1409                         /* Also validate log access for used ring if enabled. */
1410                         if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
1411                             !log_access_ok(vq->log_base, a.log_guest_addr,
1412                                            sizeof *vq->used +
1413                                            vq->num * sizeof *vq->used->ring)) {
1414                                 r = -EINVAL;
1415                                 break;
1416                         }
1417                 }
1418
1419                 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1420                 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1421                 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1422                 vq->log_addr = a.log_guest_addr;
1423                 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1424                 break;
1425         case VHOST_SET_VRING_KICK:
1426                 if (copy_from_user(&f, argp, sizeof f)) {
1427                         r = -EFAULT;
1428                         break;
1429                 }
1430                 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1431                 if (IS_ERR(eventfp)) {
1432                         r = PTR_ERR(eventfp);
1433                         break;
1434                 }
1435                 if (eventfp != vq->kick) {
1436                         pollstop = (filep = vq->kick) != NULL;
1437                         pollstart = (vq->kick = eventfp) != NULL;
1438                 } else
1439                         filep = eventfp;
1440                 break;
1441         case VHOST_SET_VRING_CALL:
1442                 if (copy_from_user(&f, argp, sizeof f)) {
1443                         r = -EFAULT;
1444                         break;
1445                 }
1446                 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1447                 if (IS_ERR(eventfp)) {
1448                         r = PTR_ERR(eventfp);
1449                         break;
1450                 }
1451                 if (eventfp != vq->call) {
1452                         filep = vq->call;
1453                         ctx = vq->call_ctx;
1454                         vq->call = eventfp;
1455                         vq->call_ctx = eventfp ?
1456                                 eventfd_ctx_fileget(eventfp) : NULL;
1457                 } else
1458                         filep = eventfp;
1459                 break;
1460         case VHOST_SET_VRING_ERR:
1461                 if (copy_from_user(&f, argp, sizeof f)) {
1462                         r = -EFAULT;
1463                         break;
1464                 }
1465                 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
1466                 if (IS_ERR(eventfp)) {
1467                         r = PTR_ERR(eventfp);
1468                         break;
1469                 }
1470                 if (eventfp != vq->error) {
1471                         filep = vq->error;
1472                         vq->error = eventfp;
1473                         ctx = vq->error_ctx;
1474                         vq->error_ctx = eventfp ?
1475                                 eventfd_ctx_fileget(eventfp) : NULL;
1476                 } else
1477                         filep = eventfp;
1478                 break;
1479         case VHOST_SET_VRING_ENDIAN:
1480                 r = vhost_set_vring_endian(vq, argp);
1481                 break;
1482         case VHOST_GET_VRING_ENDIAN:
1483                 r = vhost_get_vring_endian(vq, idx, argp);
1484                 break;
1485         case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1486                 if (copy_from_user(&s, argp, sizeof(s))) {
1487                         r = -EFAULT;
1488                         break;
1489                 }
1490                 vq->busyloop_timeout = s.num;
1491                 break;
1492         case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1493                 s.index = idx;
1494                 s.num = vq->busyloop_timeout;
1495                 if (copy_to_user(argp, &s, sizeof(s)))
1496                         r = -EFAULT;
1497                 break;
1498         default:
1499                 r = -ENOIOCTLCMD;
1500         }
1501
1502         if (pollstop && vq->handle_kick)
1503                 vhost_poll_stop(&vq->poll);
1504
1505         if (ctx)
1506                 eventfd_ctx_put(ctx);
1507         if (filep)
1508                 fput(filep);
1509
1510         if (pollstart && vq->handle_kick)
1511                 r = vhost_poll_start(&vq->poll, vq->kick);
1512
1513         mutex_unlock(&vq->mutex);
1514
1515         if (pollstop && vq->handle_kick)
1516                 vhost_poll_flush(&vq->poll);
1517         return r;
1518 }
1519 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
1520
1521 int vhost_init_device_iotlb(struct vhost_dev *d, bool enabled)
1522 {
1523         struct vhost_umem *niotlb, *oiotlb;
1524         int i;
1525
1526         niotlb = vhost_umem_alloc();
1527         if (!niotlb)
1528                 return -ENOMEM;
1529
1530         oiotlb = d->iotlb;
1531         d->iotlb = niotlb;
1532
1533         for (i = 0; i < d->nvqs; ++i) {
1534                 mutex_lock(&d->vqs[i]->mutex);
1535                 d->vqs[i]->iotlb = niotlb;
1536                 mutex_unlock(&d->vqs[i]->mutex);
1537         }
1538
1539         vhost_umem_clean(oiotlb);
1540
1541         return 0;
1542 }
1543 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1544
1545 /* Caller must have device mutex */
1546 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
1547 {
1548         struct file *eventfp, *filep = NULL;
1549         struct eventfd_ctx *ctx = NULL;
1550         u64 p;
1551         long r;
1552         int i, fd;
1553
1554         /* If you are not the owner, you can become one */
1555         if (ioctl == VHOST_SET_OWNER) {
1556                 r = vhost_dev_set_owner(d);
1557                 goto done;
1558         }
1559
1560         /* You must be the owner to do anything else */
1561         r = vhost_dev_check_owner(d);
1562         if (r)
1563                 goto done;
1564
1565         switch (ioctl) {
1566         case VHOST_SET_MEM_TABLE:
1567                 r = vhost_set_memory(d, argp);
1568                 break;
1569         case VHOST_SET_LOG_BASE:
1570                 if (copy_from_user(&p, argp, sizeof p)) {
1571                         r = -EFAULT;
1572                         break;
1573                 }
1574                 if ((u64)(unsigned long)p != p) {
1575                         r = -EFAULT;
1576                         break;
1577                 }
1578                 for (i = 0; i < d->nvqs; ++i) {
1579                         struct vhost_virtqueue *vq;
1580                         void __user *base = (void __user *)(unsigned long)p;
1581                         vq = d->vqs[i];
1582                         mutex_lock(&vq->mutex);
1583                         /* If ring is inactive, will check when it's enabled. */
1584                         if (vq->private_data && !vq_log_access_ok(vq, base))
1585                                 r = -EFAULT;
1586                         else
1587                                 vq->log_base = base;
1588                         mutex_unlock(&vq->mutex);
1589                 }
1590                 break;
1591         case VHOST_SET_LOG_FD:
1592                 r = get_user(fd, (int __user *)argp);
1593                 if (r < 0)
1594                         break;
1595                 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
1596                 if (IS_ERR(eventfp)) {
1597                         r = PTR_ERR(eventfp);
1598                         break;
1599                 }
1600                 if (eventfp != d->log_file) {
1601                         filep = d->log_file;
1602                         d->log_file = eventfp;
1603                         ctx = d->log_ctx;
1604                         d->log_ctx = eventfp ?
1605                                 eventfd_ctx_fileget(eventfp) : NULL;
1606                 } else
1607                         filep = eventfp;
1608                 for (i = 0; i < d->nvqs; ++i) {
1609                         mutex_lock(&d->vqs[i]->mutex);
1610                         d->vqs[i]->log_ctx = d->log_ctx;
1611                         mutex_unlock(&d->vqs[i]->mutex);
1612                 }
1613                 if (ctx)
1614                         eventfd_ctx_put(ctx);
1615                 if (filep)
1616                         fput(filep);
1617                 break;
1618         default:
1619                 r = -ENOIOCTLCMD;
1620                 break;
1621         }
1622 done:
1623         return r;
1624 }
1625 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1626
1627 /* TODO: This is really inefficient.  We need something like get_user()
1628  * (instruction directly accesses the data, with an exception table entry
1629  * returning -EFAULT). See Documentation/x86/exception-tables.txt.
1630  */
1631 static int set_bit_to_user(int nr, void __user *addr)
1632 {
1633         unsigned long log = (unsigned long)addr;
1634         struct page *page;
1635         void *base;
1636         int bit = nr + (log % PAGE_SIZE) * 8;
1637         int r;
1638
1639         r = get_user_pages_fast(log, 1, 1, &page);
1640         if (r < 0)
1641                 return r;
1642         BUG_ON(r != 1);
1643         base = kmap_atomic(page);
1644         set_bit(bit, base);
1645         kunmap_atomic(base);
1646         set_page_dirty_lock(page);
1647         put_page(page);
1648         return 0;
1649 }
1650
1651 static int log_write(void __user *log_base,
1652                      u64 write_address, u64 write_length)
1653 {
1654         u64 write_page = write_address / VHOST_PAGE_SIZE;
1655         int r;
1656
1657         if (!write_length)
1658                 return 0;
1659         write_length += write_address % VHOST_PAGE_SIZE;
1660         for (;;) {
1661                 u64 base = (u64)(unsigned long)log_base;
1662                 u64 log = base + write_page / 8;
1663                 int bit = write_page % 8;
1664                 if ((u64)(unsigned long)log != log)
1665                         return -EFAULT;
1666                 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1667                 if (r < 0)
1668                         return r;
1669                 if (write_length <= VHOST_PAGE_SIZE)
1670                         break;
1671                 write_length -= VHOST_PAGE_SIZE;
1672                 write_page += 1;
1673         }
1674         return r;
1675 }
1676
1677 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1678 {
1679         struct vhost_umem *umem = vq->umem;
1680         struct vhost_umem_node *u;
1681         u64 start, end, l, min;
1682         int r;
1683         bool hit = false;
1684
1685         while (len) {
1686                 min = len;
1687                 /* More than one GPAs can be mapped into a single HVA. So
1688                  * iterate all possible umems here to be safe.
1689                  */
1690                 list_for_each_entry(u, &umem->umem_list, link) {
1691                         if (u->userspace_addr > hva - 1 + len ||
1692                             u->userspace_addr - 1 + u->size < hva)
1693                                 continue;
1694                         start = max(u->userspace_addr, hva);
1695                         end = min(u->userspace_addr - 1 + u->size,
1696                                   hva - 1 + len);
1697                         l = end - start + 1;
1698                         r = log_write(vq->log_base,
1699                                       u->start + start - u->userspace_addr,
1700                                       l);
1701                         if (r < 0)
1702                                 return r;
1703                         hit = true;
1704                         min = min(l, min);
1705                 }
1706
1707                 if (!hit)
1708                         return -EFAULT;
1709
1710                 len -= min;
1711                 hva += min;
1712         }
1713
1714         return 0;
1715 }
1716
1717 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1718 {
1719         struct iovec iov[64];
1720         int i, ret;
1721
1722         if (!vq->iotlb)
1723                 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1724
1725         ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1726                              len, iov, 64, VHOST_ACCESS_WO);
1727         if (ret < 0)
1728                 return ret;
1729
1730         for (i = 0; i < ret; i++) {
1731                 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1732                                     iov[i].iov_len);
1733                 if (ret)
1734                         return ret;
1735         }
1736
1737         return 0;
1738 }
1739
1740 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1741                     unsigned int log_num, u64 len, struct iovec *iov, int count)
1742 {
1743         int i, r;
1744
1745         /* Make sure data written is seen before log. */
1746         smp_wmb();
1747
1748         if (vq->iotlb) {
1749                 for (i = 0; i < count; i++) {
1750                         r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1751                                           iov[i].iov_len);
1752                         if (r < 0)
1753                                 return r;
1754                 }
1755                 return 0;
1756         }
1757
1758         for (i = 0; i < log_num; ++i) {
1759                 u64 l = min(log[i].len, len);
1760                 r = log_write(vq->log_base, log[i].addr, l);
1761                 if (r < 0)
1762                         return r;
1763                 len -= l;
1764                 if (!len) {
1765                         if (vq->log_ctx)
1766                                 eventfd_signal(vq->log_ctx, 1);
1767                         return 0;
1768                 }
1769         }
1770         /* Length written exceeds what we have stored. This is a bug. */
1771         BUG();
1772         return 0;
1773 }
1774 EXPORT_SYMBOL_GPL(vhost_log_write);
1775
1776 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1777 {
1778         void __user *used;
1779         if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
1780                            &vq->used->flags) < 0)
1781                 return -EFAULT;
1782         if (unlikely(vq->log_used)) {
1783                 /* Make sure the flag is seen before log. */
1784                 smp_wmb();
1785                 /* Log used flag write. */
1786                 used = &vq->used->flags;
1787                 log_used(vq, (used - (void __user *)vq->used),
1788                          sizeof vq->used->flags);
1789                 if (vq->log_ctx)
1790                         eventfd_signal(vq->log_ctx, 1);
1791         }
1792         return 0;
1793 }
1794
1795 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1796 {
1797         if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
1798                            vhost_avail_event(vq)))
1799                 return -EFAULT;
1800         if (unlikely(vq->log_used)) {
1801                 void __user *used;
1802                 /* Make sure the event is seen before log. */
1803                 smp_wmb();
1804                 /* Log avail event write */
1805                 used = vhost_avail_event(vq);
1806                 log_used(vq, (used - (void __user *)vq->used),
1807                          sizeof *vhost_avail_event(vq));
1808                 if (vq->log_ctx)
1809                         eventfd_signal(vq->log_ctx, 1);
1810         }
1811         return 0;
1812 }
1813
1814 int vhost_vq_init_access(struct vhost_virtqueue *vq)
1815 {
1816         __virtio16 last_used_idx;
1817         int r;
1818         bool is_le = vq->is_le;
1819
1820         if (!vq->private_data)
1821                 return 0;
1822
1823         vhost_init_is_le(vq);
1824
1825         r = vhost_update_used_flags(vq);
1826         if (r)
1827                 goto err;
1828         vq->signalled_used_valid = false;
1829         if (!vq->iotlb &&
1830             !access_ok(VERIFY_READ, &vq->used->idx, sizeof vq->used->idx)) {
1831                 r = -EFAULT;
1832                 goto err;
1833         }
1834         r = vhost_get_user(vq, last_used_idx, &vq->used->idx);
1835         if (r) {
1836                 vq_err(vq, "Can't access used idx at %p\n",
1837                        &vq->used->idx);
1838                 goto err;
1839         }
1840         vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1841         return 0;
1842
1843 err:
1844         vq->is_le = is_le;
1845         return r;
1846 }
1847 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
1848
1849 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1850                           struct iovec iov[], int iov_size, int access)
1851 {
1852         const struct vhost_umem_node *node;
1853         struct vhost_dev *dev = vq->dev;
1854         struct vhost_umem *umem = dev->iotlb ? dev->iotlb : dev->umem;
1855         struct iovec *_iov;
1856         u64 s = 0;
1857         int ret = 0;
1858
1859         while ((u64)len > s) {
1860                 u64 size;
1861                 if (unlikely(ret >= iov_size)) {
1862                         ret = -ENOBUFS;
1863                         break;
1864                 }
1865
1866                 node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
1867                                                         addr, addr + len - 1);
1868                 if (node == NULL || node->start > addr) {
1869                         if (umem != dev->iotlb) {
1870                                 ret = -EFAULT;
1871                                 break;
1872                         }
1873                         ret = -EAGAIN;
1874                         break;
1875                 } else if (!(node->perm & access)) {
1876                         ret = -EPERM;
1877                         break;
1878                 }
1879
1880                 _iov = iov + ret;
1881                 size = node->size - addr + node->start;
1882                 _iov->iov_len = min((u64)len - s, size);
1883                 _iov->iov_base = (void __user *)(unsigned long)
1884                         (node->userspace_addr + addr - node->start);
1885                 s += size;
1886                 addr += size;
1887                 ++ret;
1888         }
1889
1890         if (ret == -EAGAIN)
1891                 vhost_iotlb_miss(vq, addr, access);
1892         return ret;
1893 }
1894
1895 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
1896  * function returns the next descriptor in the chain,
1897  * or -1U if we're at the end. */
1898 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1899 {
1900         unsigned int next;
1901
1902         /* If this descriptor says it doesn't chain, we're done. */
1903         if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1904                 return -1U;
1905
1906         /* Check they're not leading us off end of descriptors. */
1907         next = vhost16_to_cpu(vq, desc->next);
1908         /* Make sure compiler knows to grab that: we don't want it changing! */
1909         /* We will use the result as an index in an array, so most
1910          * architectures only need a compiler barrier here. */
1911         read_barrier_depends();
1912
1913         return next;
1914 }
1915
1916 static int get_indirect(struct vhost_virtqueue *vq,
1917                         struct iovec iov[], unsigned int iov_size,
1918                         unsigned int *out_num, unsigned int *in_num,
1919                         struct vhost_log *log, unsigned int *log_num,
1920                         struct vring_desc *indirect)
1921 {
1922         struct vring_desc desc;
1923         unsigned int i = 0, count, found = 0;
1924         u32 len = vhost32_to_cpu(vq, indirect->len);
1925         struct iov_iter from;
1926         int ret, access;
1927
1928         /* Sanity check */
1929         if (unlikely(len % sizeof desc)) {
1930                 vq_err(vq, "Invalid length in indirect descriptor: "
1931                        "len 0x%llx not multiple of 0x%zx\n",
1932                        (unsigned long long)len,
1933                        sizeof desc);
1934                 return -EINVAL;
1935         }
1936
1937         ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
1938                              UIO_MAXIOV, VHOST_ACCESS_RO);
1939         if (unlikely(ret < 0)) {
1940                 if (ret != -EAGAIN)
1941                         vq_err(vq, "Translation failure %d in indirect.\n", ret);
1942                 return ret;
1943         }
1944         iov_iter_init(&from, READ, vq->indirect, ret, len);
1945
1946         /* We will use the result as an address to read from, so most
1947          * architectures only need a compiler barrier here. */
1948         read_barrier_depends();
1949
1950         count = len / sizeof desc;
1951         /* Buffers are chained via a 16 bit next field, so
1952          * we can have at most 2^16 of these. */
1953         if (unlikely(count > USHRT_MAX + 1)) {
1954                 vq_err(vq, "Indirect buffer length too big: %d\n",
1955                        indirect->len);
1956                 return -E2BIG;
1957         }
1958
1959         do {
1960                 unsigned iov_count = *in_num + *out_num;
1961                 if (unlikely(++found > count)) {
1962                         vq_err(vq, "Loop detected: last one at %u "
1963                                "indirect size %u\n",
1964                                i, count);
1965                         return -EINVAL;
1966                 }
1967                 if (unlikely(copy_from_iter(&desc, sizeof(desc), &from) !=
1968                              sizeof(desc))) {
1969                         vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1970                                i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1971                         return -EINVAL;
1972                 }
1973                 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
1974                         vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1975                                i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1976                         return -EINVAL;
1977                 }
1978
1979                 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
1980                         access = VHOST_ACCESS_WO;
1981                 else
1982                         access = VHOST_ACCESS_RO;
1983
1984                 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1985                                      vhost32_to_cpu(vq, desc.len), iov + iov_count,
1986                                      iov_size - iov_count, access);
1987                 if (unlikely(ret < 0)) {
1988                         if (ret != -EAGAIN)
1989                                 vq_err(vq, "Translation failure %d indirect idx %d\n",
1990                                         ret, i);
1991                         return ret;
1992                 }
1993                 /* If this is an input descriptor, increment that count. */
1994                 if (access == VHOST_ACCESS_WO) {
1995                         *in_num += ret;
1996                         if (unlikely(log && ret)) {
1997                                 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1998                                 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1999                                 ++*log_num;
2000                         }
2001                 } else {
2002                         /* If it's an output descriptor, they're all supposed
2003                          * to come before any input descriptors. */
2004                         if (unlikely(*in_num)) {
2005                                 vq_err(vq, "Indirect descriptor "
2006                                        "has out after in: idx %d\n", i);
2007                                 return -EINVAL;
2008                         }
2009                         *out_num += ret;
2010                 }
2011         } while ((i = next_desc(vq, &desc)) != -1);
2012         return 0;
2013 }
2014
2015 /* This looks in the virtqueue and for the first available buffer, and converts
2016  * it to an iovec for convenient access.  Since descriptors consist of some
2017  * number of output then some number of input descriptors, it's actually two
2018  * iovecs, but we pack them into one and note how many of each there were.
2019  *
2020  * This function returns the descriptor number found, or vq->num (which is
2021  * never a valid descriptor number) if none was found.  A negative code is
2022  * returned on error. */
2023 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
2024                       struct iovec iov[], unsigned int iov_size,
2025                       unsigned int *out_num, unsigned int *in_num,
2026                       struct vhost_log *log, unsigned int *log_num)
2027 {
2028         struct vring_desc desc;
2029         unsigned int i, head, found = 0;
2030         u16 last_avail_idx;
2031         __virtio16 avail_idx;
2032         __virtio16 ring_head;
2033         int ret, access;
2034
2035         /* Check it isn't doing very strange things with descriptor numbers. */
2036         last_avail_idx = vq->last_avail_idx;
2037         if (unlikely(vhost_get_user(vq, avail_idx, &vq->avail->idx))) {
2038                 vq_err(vq, "Failed to access avail idx at %p\n",
2039                        &vq->avail->idx);
2040                 return -EFAULT;
2041         }
2042         vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
2043
2044         if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2045                 vq_err(vq, "Guest moved used index from %u to %u",
2046                        last_avail_idx, vq->avail_idx);
2047                 return -EFAULT;
2048         }
2049
2050         /* If there's nothing new since last we looked, return invalid. */
2051         if (vq->avail_idx == last_avail_idx)
2052                 return vq->num;
2053
2054         /* Only get avail ring entries after they have been exposed by guest. */
2055         smp_rmb();
2056
2057         /* Grab the next descriptor number they're advertising, and increment
2058          * the index we've seen. */
2059         if (unlikely(vhost_get_user(vq, ring_head,
2060                      &vq->avail->ring[last_avail_idx & (vq->num - 1)]))) {
2061                 vq_err(vq, "Failed to read head: idx %d address %p\n",
2062                        last_avail_idx,
2063                        &vq->avail->ring[last_avail_idx % vq->num]);
2064                 return -EFAULT;
2065         }
2066
2067         head = vhost16_to_cpu(vq, ring_head);
2068
2069         /* If their number is silly, that's an error. */
2070         if (unlikely(head >= vq->num)) {
2071                 vq_err(vq, "Guest says index %u > %u is available",
2072                        head, vq->num);
2073                 return -EINVAL;
2074         }
2075
2076         /* When we start there are none of either input nor output. */
2077         *out_num = *in_num = 0;
2078         if (unlikely(log))
2079                 *log_num = 0;
2080
2081         i = head;
2082         do {
2083                 unsigned iov_count = *in_num + *out_num;
2084                 if (unlikely(i >= vq->num)) {
2085                         vq_err(vq, "Desc index is %u > %u, head = %u",
2086                                i, vq->num, head);
2087                         return -EINVAL;
2088                 }
2089                 if (unlikely(++found > vq->num)) {
2090                         vq_err(vq, "Loop detected: last one at %u "
2091                                "vq size %u head %u\n",
2092                                i, vq->num, head);
2093                         return -EINVAL;
2094                 }
2095                 ret = vhost_copy_from_user(vq, &desc, vq->desc + i,
2096                                            sizeof desc);
2097                 if (unlikely(ret)) {
2098                         vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2099                                i, vq->desc + i);
2100                         return -EFAULT;
2101                 }
2102                 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
2103                         ret = get_indirect(vq, iov, iov_size,
2104                                            out_num, in_num,
2105                                            log, log_num, &desc);
2106                         if (unlikely(ret < 0)) {
2107                                 if (ret != -EAGAIN)
2108                                         vq_err(vq, "Failure detected "
2109                                                 "in indirect descriptor at idx %d\n", i);
2110                                 return ret;
2111                         }
2112                         continue;
2113                 }
2114
2115                 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2116                         access = VHOST_ACCESS_WO;
2117                 else
2118                         access = VHOST_ACCESS_RO;
2119                 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2120                                      vhost32_to_cpu(vq, desc.len), iov + iov_count,
2121                                      iov_size - iov_count, access);
2122                 if (unlikely(ret < 0)) {
2123                         if (ret != -EAGAIN)
2124                                 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2125                                         ret, i);
2126                         return ret;
2127                 }
2128                 if (access == VHOST_ACCESS_WO) {
2129                         /* If this is an input descriptor,
2130                          * increment that count. */
2131                         *in_num += ret;
2132                         if (unlikely(log && ret)) {
2133                                 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2134                                 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2135                                 ++*log_num;
2136                         }
2137                 } else {
2138                         /* If it's an output descriptor, they're all supposed
2139                          * to come before any input descriptors. */
2140                         if (unlikely(*in_num)) {
2141                                 vq_err(vq, "Descriptor has out after in: "
2142                                        "idx %d\n", i);
2143                                 return -EINVAL;
2144                         }
2145                         *out_num += ret;
2146                 }
2147         } while ((i = next_desc(vq, &desc)) != -1);
2148
2149         /* On success, increment avail index. */
2150         vq->last_avail_idx++;
2151
2152         /* Assume notifications from guest are disabled at this point,
2153          * if they aren't we would need to update avail_event index. */
2154         BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
2155         return head;
2156 }
2157 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
2158
2159 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
2160 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
2161 {
2162         vq->last_avail_idx -= n;
2163 }
2164 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
2165
2166 /* After we've used one of their buffers, we tell them about it.  We'll then
2167  * want to notify the guest, using eventfd. */
2168 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2169 {
2170         struct vring_used_elem heads = {
2171                 cpu_to_vhost32(vq, head),
2172                 cpu_to_vhost32(vq, len)
2173         };
2174
2175         return vhost_add_used_n(vq, &heads, 1);
2176 }
2177 EXPORT_SYMBOL_GPL(vhost_add_used);
2178
2179 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2180                             struct vring_used_elem *heads,
2181                             unsigned count)
2182 {
2183         struct vring_used_elem __user *used;
2184         u16 old, new;
2185         int start;
2186
2187         start = vq->last_used_idx & (vq->num - 1);
2188         used = vq->used->ring + start;
2189         if (count == 1) {
2190                 if (vhost_put_user(vq, heads[0].id, &used->id)) {
2191                         vq_err(vq, "Failed to write used id");
2192                         return -EFAULT;
2193                 }
2194                 if (vhost_put_user(vq, heads[0].len, &used->len)) {
2195                         vq_err(vq, "Failed to write used len");
2196                         return -EFAULT;
2197                 }
2198         } else if (vhost_copy_to_user(vq, used, heads, count * sizeof *used)) {
2199                 vq_err(vq, "Failed to write used");
2200                 return -EFAULT;
2201         }
2202         if (unlikely(vq->log_used)) {
2203                 /* Make sure data is seen before log. */
2204                 smp_wmb();
2205                 /* Log used ring entry write. */
2206                 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2207                          count * sizeof *used);
2208         }
2209         old = vq->last_used_idx;
2210         new = (vq->last_used_idx += count);
2211         /* If the driver never bothers to signal in a very long while,
2212          * used index might wrap around. If that happens, invalidate
2213          * signalled_used index we stored. TODO: make sure driver
2214          * signals at least once in 2^16 and remove this. */
2215         if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2216                 vq->signalled_used_valid = false;
2217         return 0;
2218 }
2219
2220 /* After we've used one of their buffers, we tell them about it.  We'll then
2221  * want to notify the guest, using eventfd. */
2222 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2223                      unsigned count)
2224 {
2225         int start, n, r;
2226
2227         start = vq->last_used_idx & (vq->num - 1);
2228         n = vq->num - start;
2229         if (n < count) {
2230                 r = __vhost_add_used_n(vq, heads, n);
2231                 if (r < 0)
2232                         return r;
2233                 heads += n;
2234                 count -= n;
2235         }
2236         r = __vhost_add_used_n(vq, heads, count);
2237
2238         /* Make sure buffer is written before we update index. */
2239         smp_wmb();
2240         if (vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
2241                            &vq->used->idx)) {
2242                 vq_err(vq, "Failed to increment used idx");
2243                 return -EFAULT;
2244         }
2245         if (unlikely(vq->log_used)) {
2246                 /* Make sure used idx is seen before log. */
2247                 smp_wmb();
2248                 /* Log used index update. */
2249                 log_used(vq, offsetof(struct vring_used, idx),
2250                          sizeof vq->used->idx);
2251                 if (vq->log_ctx)
2252                         eventfd_signal(vq->log_ctx, 1);
2253         }
2254         return r;
2255 }
2256 EXPORT_SYMBOL_GPL(vhost_add_used_n);
2257
2258 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2259 {
2260         __u16 old, new;
2261         __virtio16 event;
2262         bool v;
2263         /* Flush out used index updates. This is paired
2264          * with the barrier that the Guest executes when enabling
2265          * interrupts. */
2266         smp_mb();
2267
2268         if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
2269             unlikely(vq->avail_idx == vq->last_avail_idx))
2270                 return true;
2271
2272         if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2273                 __virtio16 flags;
2274                 if (vhost_get_user(vq, flags, &vq->avail->flags)) {
2275                         vq_err(vq, "Failed to get flags");
2276                         return true;
2277                 }
2278                 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
2279         }
2280         old = vq->signalled_used;
2281         v = vq->signalled_used_valid;
2282         new = vq->signalled_used = vq->last_used_idx;
2283         vq->signalled_used_valid = true;
2284
2285         if (unlikely(!v))
2286                 return true;
2287
2288         if (vhost_get_user(vq, event, vhost_used_event(vq))) {
2289                 vq_err(vq, "Failed to get used event idx");
2290                 return true;
2291         }
2292         return vring_need_event(vhost16_to_cpu(vq, event), new, old);
2293 }
2294
2295 /* This actually signals the guest, using eventfd. */
2296 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2297 {
2298         /* Signal the Guest tell them we used something up. */
2299         if (vq->call_ctx && vhost_notify(dev, vq))
2300                 eventfd_signal(vq->call_ctx, 1);
2301 }
2302 EXPORT_SYMBOL_GPL(vhost_signal);
2303
2304 /* And here's the combo meal deal.  Supersize me! */
2305 void vhost_add_used_and_signal(struct vhost_dev *dev,
2306                                struct vhost_virtqueue *vq,
2307                                unsigned int head, int len)
2308 {
2309         vhost_add_used(vq, head, len);
2310         vhost_signal(dev, vq);
2311 }
2312 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
2313
2314 /* multi-buffer version of vhost_add_used_and_signal */
2315 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2316                                  struct vhost_virtqueue *vq,
2317                                  struct vring_used_elem *heads, unsigned count)
2318 {
2319         vhost_add_used_n(vq, heads, count);
2320         vhost_signal(dev, vq);
2321 }
2322 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
2323
2324 /* return true if we're sure that avaiable ring is empty */
2325 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2326 {
2327         __virtio16 avail_idx;
2328         int r;
2329
2330         r = vhost_get_user(vq, avail_idx, &vq->avail->idx);
2331         if (r)
2332                 return false;
2333
2334         return vhost16_to_cpu(vq, avail_idx) == vq->avail_idx;
2335 }
2336 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2337
2338 /* OK, now we need to know about added descriptors. */
2339 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2340 {
2341         __virtio16 avail_idx;
2342         int r;
2343
2344         if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2345                 return false;
2346         vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
2347         if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2348                 r = vhost_update_used_flags(vq);
2349                 if (r) {
2350                         vq_err(vq, "Failed to enable notification at %p: %d\n",
2351                                &vq->used->flags, r);
2352                         return false;
2353                 }
2354         } else {
2355                 r = vhost_update_avail_event(vq, vq->avail_idx);
2356                 if (r) {
2357                         vq_err(vq, "Failed to update avail event index at %p: %d\n",
2358                                vhost_avail_event(vq), r);
2359                         return false;
2360                 }
2361         }
2362         /* They could have slipped one in as we were doing that: make
2363          * sure it's written, then check again. */
2364         smp_mb();
2365         r = vhost_get_user(vq, avail_idx, &vq->avail->idx);
2366         if (r) {
2367                 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2368                        &vq->avail->idx, r);
2369                 return false;
2370         }
2371
2372         return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
2373 }
2374 EXPORT_SYMBOL_GPL(vhost_enable_notify);
2375
2376 /* We don't need to be notified again. */
2377 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2378 {
2379         int r;
2380
2381         if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2382                 return;
2383         vq->used_flags |= VRING_USED_F_NO_NOTIFY;
2384         if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2385                 r = vhost_update_used_flags(vq);
2386                 if (r)
2387                         vq_err(vq, "Failed to enable notification at %p: %d\n",
2388                                &vq->used->flags, r);
2389         }
2390 }
2391 EXPORT_SYMBOL_GPL(vhost_disable_notify);
2392
2393 /* Create a new message. */
2394 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2395 {
2396         struct vhost_msg_node *node = kmalloc(sizeof *node, GFP_KERNEL);
2397         if (!node)
2398                 return NULL;
2399
2400         /* Make sure all padding within the structure is initialized. */
2401         memset(&node->msg, 0, sizeof node->msg);
2402         node->vq = vq;
2403         node->msg.type = type;
2404         return node;
2405 }
2406 EXPORT_SYMBOL_GPL(vhost_new_msg);
2407
2408 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2409                        struct vhost_msg_node *node)
2410 {
2411         spin_lock(&dev->iotlb_lock);
2412         list_add_tail(&node->node, head);
2413         spin_unlock(&dev->iotlb_lock);
2414
2415         wake_up_interruptible_poll(&dev->wait, POLLIN | POLLRDNORM);
2416 }
2417 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2418
2419 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2420                                          struct list_head *head)
2421 {
2422         struct vhost_msg_node *node = NULL;
2423
2424         spin_lock(&dev->iotlb_lock);
2425         if (!list_empty(head)) {
2426                 node = list_first_entry(head, struct vhost_msg_node,
2427                                         node);
2428                 list_del(&node->node);
2429         }
2430         spin_unlock(&dev->iotlb_lock);
2431
2432         return node;
2433 }
2434 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2435
2436
2437 static int __init vhost_init(void)
2438 {
2439         return 0;
2440 }
2441
2442 static void __exit vhost_exit(void)
2443 {
2444 }
2445
2446 module_init(vhost_init);
2447 module_exit(vhost_exit);
2448
2449 MODULE_VERSION("0.0.1");
2450 MODULE_LICENSE("GPL v2");
2451 MODULE_AUTHOR("Michael S. Tsirkin");
2452 MODULE_DESCRIPTION("Host kernel accelerator for virtio");