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