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