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