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