xref: /linux/drivers/vhost/vhost.c (revision 5efd97e6f0c745d5cb34e4e3b709200e23d4d7b7)
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/cgroup.h>
26 #include <linux/module.h>
27 #include <linux/sort.h>
28 #include <linux/sched/mm.h>
29 #include <linux/sched/signal.h>
30 #include <linux/sched/vhost_task.h>
31 #include <linux/interval_tree_generic.h>
32 #include <linux/nospec.h>
33 #include <linux/kcov.h>
34 
35 #include "vhost.h"
36 
37 static ushort max_mem_regions = 64;
38 module_param(max_mem_regions, ushort, 0444);
39 MODULE_PARM_DESC(max_mem_regions,
40 	"Maximum number of memory regions in memory map. (default: 64)");
41 static int max_iotlb_entries = 2048;
42 module_param(max_iotlb_entries, int, 0444);
43 MODULE_PARM_DESC(max_iotlb_entries,
44 	"Maximum number of iotlb entries. (default: 2048)");
45 static bool fork_from_owner_default = VHOST_FORK_OWNER_TASK;
46 
47 #ifdef CONFIG_VHOST_ENABLE_FORK_OWNER_CONTROL
48 module_param(fork_from_owner_default, bool, 0444);
49 MODULE_PARM_DESC(fork_from_owner_default,
50 		 "Set task mode as the default(default: Y)");
51 #endif
52 
53 enum {
54 	VHOST_MEMORY_F_LOG = 0x1,
55 };
56 
57 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
58 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
59 
60 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
61 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
62 {
63 	vq->user_be = !virtio_legacy_is_little_endian();
64 }
65 
66 static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
67 {
68 	vq->user_be = true;
69 }
70 
71 static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
72 {
73 	vq->user_be = false;
74 }
75 
76 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
77 {
78 	struct vhost_vring_state s;
79 
80 	if (vq->private_data)
81 		return -EBUSY;
82 
83 	if (copy_from_user(&s, argp, sizeof(s)))
84 		return -EFAULT;
85 
86 	if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
87 	    s.num != VHOST_VRING_BIG_ENDIAN)
88 		return -EINVAL;
89 
90 	if (s.num == VHOST_VRING_BIG_ENDIAN)
91 		vhost_enable_cross_endian_big(vq);
92 	else
93 		vhost_enable_cross_endian_little(vq);
94 
95 	return 0;
96 }
97 
98 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
99 				   int __user *argp)
100 {
101 	struct vhost_vring_state s = {
102 		.index = idx,
103 		.num = vq->user_be
104 	};
105 
106 	if (copy_to_user(argp, &s, sizeof(s)))
107 		return -EFAULT;
108 
109 	return 0;
110 }
111 
112 static void vhost_init_is_le(struct vhost_virtqueue *vq)
113 {
114 	/* Note for legacy virtio: user_be is initialized at reset time
115 	 * according to the host endianness. If userspace does not set an
116 	 * explicit endianness, the default behavior is native endian, as
117 	 * expected by legacy virtio.
118 	 */
119 	vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
120 }
121 #else
122 static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
123 {
124 }
125 
126 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
127 {
128 	return -ENOIOCTLCMD;
129 }
130 
131 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
132 				   int __user *argp)
133 {
134 	return -ENOIOCTLCMD;
135 }
136 
137 static void vhost_init_is_le(struct vhost_virtqueue *vq)
138 {
139 	vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
140 		|| virtio_legacy_is_little_endian();
141 }
142 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
143 
144 static void vhost_reset_is_le(struct vhost_virtqueue *vq)
145 {
146 	vhost_init_is_le(vq);
147 }
148 
149 struct vhost_flush_struct {
150 	struct vhost_work work;
151 	struct completion wait_event;
152 };
153 
154 static void vhost_flush_work(struct vhost_work *work)
155 {
156 	struct vhost_flush_struct *s;
157 
158 	s = container_of(work, struct vhost_flush_struct, work);
159 	complete(&s->wait_event);
160 }
161 
162 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
163 			    poll_table *pt)
164 {
165 	struct vhost_poll *poll;
166 
167 	poll = container_of(pt, struct vhost_poll, table);
168 	poll->wqh = wqh;
169 	add_wait_queue(wqh, &poll->wait);
170 }
171 
172 static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
173 			     void *key)
174 {
175 	struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
176 	struct vhost_work *work = &poll->work;
177 
178 	if (!(key_to_poll(key) & poll->mask))
179 		return 0;
180 
181 	if (!poll->dev->use_worker)
182 		work->fn(work);
183 	else
184 		vhost_poll_queue(poll);
185 
186 	return 0;
187 }
188 
189 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
190 {
191 	clear_bit(VHOST_WORK_QUEUED, &work->flags);
192 	work->fn = fn;
193 }
194 EXPORT_SYMBOL_GPL(vhost_work_init);
195 
196 /* Init poll structure */
197 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
198 		     __poll_t mask, struct vhost_dev *dev,
199 		     struct vhost_virtqueue *vq)
200 {
201 	init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
202 	init_poll_funcptr(&poll->table, vhost_poll_func);
203 	poll->mask = mask;
204 	poll->dev = dev;
205 	poll->wqh = NULL;
206 	poll->vq = vq;
207 
208 	vhost_work_init(&poll->work, fn);
209 }
210 EXPORT_SYMBOL_GPL(vhost_poll_init);
211 
212 /* Start polling a file. We add ourselves to file's wait queue. The caller must
213  * keep a reference to a file until after vhost_poll_stop is called. */
214 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
215 {
216 	__poll_t mask;
217 
218 	if (poll->wqh)
219 		return 0;
220 
221 	mask = vfs_poll(file, &poll->table);
222 	if (mask)
223 		vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
224 	if (mask & EPOLLERR) {
225 		vhost_poll_stop(poll);
226 		return -EINVAL;
227 	}
228 
229 	return 0;
230 }
231 EXPORT_SYMBOL_GPL(vhost_poll_start);
232 
233 /* Stop polling a file. After this function returns, it becomes safe to drop the
234  * file reference. You must also flush afterwards. */
235 void vhost_poll_stop(struct vhost_poll *poll)
236 {
237 	if (poll->wqh) {
238 		remove_wait_queue(poll->wqh, &poll->wait);
239 		poll->wqh = NULL;
240 	}
241 }
242 EXPORT_SYMBOL_GPL(vhost_poll_stop);
243 
244 static void vhost_worker_queue(struct vhost_worker *worker,
245 			       struct vhost_work *work)
246 {
247 	if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
248 		/* We can only add the work to the list after we're
249 		 * sure it was not in the list.
250 		 * test_and_set_bit() implies a memory barrier.
251 		 */
252 		llist_add(&work->node, &worker->work_list);
253 		worker->ops->wakeup(worker);
254 	}
255 }
256 
257 bool vhost_vq_work_queue(struct vhost_virtqueue *vq, struct vhost_work *work)
258 {
259 	struct vhost_worker *worker;
260 	bool queued = false;
261 
262 	rcu_read_lock();
263 	worker = rcu_dereference(vq->worker);
264 	if (worker) {
265 		queued = true;
266 		vhost_worker_queue(worker, work);
267 	}
268 	rcu_read_unlock();
269 
270 	return queued;
271 }
272 EXPORT_SYMBOL_GPL(vhost_vq_work_queue);
273 
274 /**
275  * __vhost_worker_flush - flush a worker
276  * @worker: worker to flush
277  *
278  * The worker's flush_mutex must be held.
279  */
280 static void __vhost_worker_flush(struct vhost_worker *worker)
281 {
282 	struct vhost_flush_struct flush;
283 
284 	if (!worker->attachment_cnt || worker->killed)
285 		return;
286 
287 	init_completion(&flush.wait_event);
288 	vhost_work_init(&flush.work, vhost_flush_work);
289 
290 	vhost_worker_queue(worker, &flush.work);
291 	/*
292 	 * Drop mutex in case our worker is killed and it needs to take the
293 	 * mutex to force cleanup.
294 	 */
295 	mutex_unlock(&worker->mutex);
296 	wait_for_completion(&flush.wait_event);
297 	mutex_lock(&worker->mutex);
298 }
299 
300 static void vhost_worker_flush(struct vhost_worker *worker)
301 {
302 	mutex_lock(&worker->mutex);
303 	__vhost_worker_flush(worker);
304 	mutex_unlock(&worker->mutex);
305 }
306 
307 void vhost_dev_flush(struct vhost_dev *dev)
308 {
309 	struct vhost_worker *worker;
310 	unsigned long i;
311 
312 	xa_for_each(&dev->worker_xa, i, worker)
313 		vhost_worker_flush(worker);
314 }
315 EXPORT_SYMBOL_GPL(vhost_dev_flush);
316 
317 /* A lockless hint for busy polling code to exit the loop */
318 bool vhost_vq_has_work(struct vhost_virtqueue *vq)
319 {
320 	struct vhost_worker *worker;
321 	bool has_work = false;
322 
323 	rcu_read_lock();
324 	worker = rcu_dereference(vq->worker);
325 	if (worker && !llist_empty(&worker->work_list))
326 		has_work = true;
327 	rcu_read_unlock();
328 
329 	return has_work;
330 }
331 EXPORT_SYMBOL_GPL(vhost_vq_has_work);
332 
333 void vhost_poll_queue(struct vhost_poll *poll)
334 {
335 	vhost_vq_work_queue(poll->vq, &poll->work);
336 }
337 EXPORT_SYMBOL_GPL(vhost_poll_queue);
338 
339 static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
340 {
341 	int j;
342 
343 	for (j = 0; j < VHOST_NUM_ADDRS; j++)
344 		vq->meta_iotlb[j] = NULL;
345 }
346 
347 /* Caller must hold the virtqueue mutex. */
348 static void vhost_vq_invalidate_access(struct vhost_virtqueue *vq)
349 {
350 	vq->desc = NULL;
351 	vq->avail = NULL;
352 	vq->used = NULL;
353 	vq->log_used = false;
354 	vq->log_addr = -1ull;
355 	__vhost_vq_meta_reset(vq);
356 }
357 
358 static void vhost_vq_meta_reset(struct vhost_dev *d)
359 {
360 	int i;
361 
362 	for (i = 0; i < d->nvqs; ++i)
363 		__vhost_vq_meta_reset(d->vqs[i]);
364 }
365 
366 static void vhost_vring_call_reset(struct vhost_vring_call *call_ctx)
367 {
368 	call_ctx->ctx = NULL;
369 	memset(&call_ctx->producer, 0x0, sizeof(struct irq_bypass_producer));
370 }
371 
372 bool vhost_vq_is_setup(struct vhost_virtqueue *vq)
373 {
374 	return vq->avail && vq->desc && vq->used && vhost_vq_access_ok(vq);
375 }
376 EXPORT_SYMBOL_GPL(vhost_vq_is_setup);
377 
378 static void vhost_vq_reset(struct vhost_dev *dev,
379 			   struct vhost_virtqueue *vq)
380 {
381 	vq->num = 1;
382 	vq->desc = NULL;
383 	vq->avail = NULL;
384 	vq->used = NULL;
385 	vq->last_avail_idx = 0;
386 	vq->next_avail_head = 0;
387 	vq->avail_idx = 0;
388 	vq->last_used_idx = 0;
389 	vq->signalled_used = 0;
390 	vq->signalled_used_valid = false;
391 	vq->used_flags = 0;
392 	vq->log_used = false;
393 	vq->log_addr = -1ull;
394 	vq->private_data = NULL;
395 	virtio_features_zero(vq->acked_features_array);
396 	vq->acked_backend_features = 0;
397 	vq->log_base = NULL;
398 	vq->error_ctx = NULL;
399 	vq->kick = NULL;
400 	vq->log_ctx = NULL;
401 	vhost_disable_cross_endian(vq);
402 	vhost_reset_is_le(vq);
403 	vq->busyloop_timeout = 0;
404 	vq->umem = NULL;
405 	vq->iotlb = NULL;
406 	vq->iotlb_miss = NULL;
407 	rcu_assign_pointer(vq->worker, NULL);
408 	vhost_vring_call_reset(&vq->call_ctx);
409 	__vhost_vq_meta_reset(vq);
410 }
411 
412 static int vhost_run_work_kthread_list(void *data)
413 {
414 	struct vhost_worker *worker = data;
415 	struct vhost_work *work, *work_next;
416 	struct vhost_dev *dev = worker->dev;
417 	struct llist_node *node;
418 
419 	kthread_use_mm(dev->mm);
420 
421 	for (;;) {
422 		/* mb paired w/ kthread_stop */
423 		set_current_state(TASK_INTERRUPTIBLE);
424 
425 		if (kthread_should_stop()) {
426 			__set_current_state(TASK_RUNNING);
427 			break;
428 		}
429 		node = llist_del_all(&worker->work_list);
430 		if (!node)
431 			schedule();
432 
433 		node = llist_reverse_order(node);
434 		/* make sure flag is seen after deletion */
435 		smp_wmb();
436 		llist_for_each_entry_safe(work, work_next, node, node) {
437 			clear_bit(VHOST_WORK_QUEUED, &work->flags);
438 			__set_current_state(TASK_RUNNING);
439 			kcov_remote_start_common(worker->kcov_handle);
440 			work->fn(work);
441 			kcov_remote_stop();
442 			cond_resched();
443 		}
444 	}
445 	kthread_unuse_mm(dev->mm);
446 
447 	return 0;
448 }
449 
450 static bool vhost_run_work_list(void *data)
451 {
452 	struct vhost_worker *worker = data;
453 	struct vhost_work *work, *work_next;
454 	struct llist_node *node;
455 
456 	node = llist_del_all(&worker->work_list);
457 	if (node) {
458 		__set_current_state(TASK_RUNNING);
459 
460 		node = llist_reverse_order(node);
461 		/* make sure flag is seen after deletion */
462 		smp_wmb();
463 		llist_for_each_entry_safe(work, work_next, node, node) {
464 			clear_bit(VHOST_WORK_QUEUED, &work->flags);
465 			kcov_remote_start_common(worker->kcov_handle);
466 			work->fn(work);
467 			kcov_remote_stop();
468 			cond_resched();
469 		}
470 	}
471 
472 	return !!node;
473 }
474 
475 static void vhost_worker_killed(void *data)
476 {
477 	struct vhost_worker *worker = data;
478 	struct vhost_dev *dev = worker->dev;
479 	struct vhost_virtqueue *vq;
480 	int i, attach_cnt = 0;
481 
482 	mutex_lock(&worker->mutex);
483 	worker->killed = true;
484 
485 	for (i = 0; i < dev->nvqs; i++) {
486 		vq = dev->vqs[i];
487 
488 		mutex_lock(&vq->mutex);
489 		if (worker ==
490 		    rcu_dereference_check(vq->worker,
491 					  lockdep_is_held(&vq->mutex))) {
492 			rcu_assign_pointer(vq->worker, NULL);
493 			attach_cnt++;
494 		}
495 		mutex_unlock(&vq->mutex);
496 	}
497 
498 	worker->attachment_cnt -= attach_cnt;
499 	if (attach_cnt)
500 		synchronize_rcu();
501 	/*
502 	 * Finish vhost_worker_flush calls and any other works that snuck in
503 	 * before the synchronize_rcu.
504 	 */
505 	vhost_run_work_list(worker);
506 	mutex_unlock(&worker->mutex);
507 }
508 
509 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
510 {
511 	kfree(vq->indirect);
512 	vq->indirect = NULL;
513 	kfree(vq->log);
514 	vq->log = NULL;
515 	kfree(vq->heads);
516 	vq->heads = NULL;
517 	kfree(vq->nheads);
518 	vq->nheads = NULL;
519 }
520 
521 /* Helper to allocate iovec buffers for all vqs. */
522 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
523 {
524 	struct vhost_virtqueue *vq;
525 	int i;
526 
527 	for (i = 0; i < dev->nvqs; ++i) {
528 		vq = dev->vqs[i];
529 		vq->indirect = kmalloc_objs(*vq->indirect, UIO_MAXIOV);
530 		vq->log = kmalloc_objs(*vq->log, dev->iov_limit);
531 		vq->heads = kmalloc_objs(*vq->heads, dev->iov_limit);
532 		vq->nheads = kmalloc_array(dev->iov_limit, sizeof(*vq->nheads),
533 					   GFP_KERNEL);
534 		if (!vq->indirect || !vq->log || !vq->heads || !vq->nheads)
535 			goto err_nomem;
536 	}
537 	return 0;
538 
539 err_nomem:
540 	for (; i >= 0; --i)
541 		vhost_vq_free_iovecs(dev->vqs[i]);
542 	return -ENOMEM;
543 }
544 
545 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
546 {
547 	int i;
548 
549 	for (i = 0; i < dev->nvqs; ++i)
550 		vhost_vq_free_iovecs(dev->vqs[i]);
551 }
552 
553 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
554 			  int pkts, int total_len)
555 {
556 	struct vhost_dev *dev = vq->dev;
557 
558 	if ((dev->byte_weight && total_len >= dev->byte_weight) ||
559 	    pkts >= dev->weight) {
560 		vhost_poll_queue(&vq->poll);
561 		return true;
562 	}
563 
564 	return false;
565 }
566 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
567 
568 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
569 				   unsigned int num)
570 {
571 	size_t event __maybe_unused =
572 	       vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
573 
574 	return size_add(struct_size(vq->avail, ring, num), event);
575 }
576 
577 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
578 				  unsigned int num)
579 {
580 	size_t event __maybe_unused =
581 	       vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
582 
583 	return size_add(struct_size(vq->used, ring, num), event);
584 }
585 
586 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
587 				  unsigned int num)
588 {
589 	return sizeof(*vq->desc) * num;
590 }
591 
592 void vhost_dev_init(struct vhost_dev *dev,
593 		    struct vhost_virtqueue **vqs, int nvqs,
594 		    int iov_limit, int weight, int byte_weight,
595 		    bool use_worker,
596 		    int (*msg_handler)(struct vhost_dev *dev, u32 asid,
597 				       struct vhost_iotlb_msg *msg))
598 {
599 	struct vhost_virtqueue *vq;
600 	int i;
601 
602 	dev->vqs = vqs;
603 	dev->nvqs = nvqs;
604 	mutex_init(&dev->mutex);
605 	dev->log_ctx = NULL;
606 	dev->umem = NULL;
607 	dev->iotlb = NULL;
608 	dev->mm = NULL;
609 	dev->iov_limit = iov_limit;
610 	dev->weight = weight;
611 	dev->byte_weight = byte_weight;
612 	dev->use_worker = use_worker;
613 	dev->msg_handler = msg_handler;
614 	dev->fork_owner = fork_from_owner_default;
615 	init_waitqueue_head(&dev->wait);
616 	INIT_LIST_HEAD(&dev->read_list);
617 	INIT_LIST_HEAD(&dev->pending_list);
618 	spin_lock_init(&dev->iotlb_lock);
619 	xa_init_flags(&dev->worker_xa, XA_FLAGS_ALLOC);
620 
621 	for (i = 0; i < dev->nvqs; ++i) {
622 		vq = dev->vqs[i];
623 		vq->log = NULL;
624 		vq->indirect = NULL;
625 		vq->heads = NULL;
626 		vq->nheads = NULL;
627 		vq->dev = dev;
628 		mutex_init(&vq->mutex);
629 		vhost_vq_reset(dev, vq);
630 		if (vq->handle_kick)
631 			vhost_poll_init(&vq->poll, vq->handle_kick,
632 					EPOLLIN, dev, vq);
633 	}
634 }
635 EXPORT_SYMBOL_GPL(vhost_dev_init);
636 
637 /* Caller should have device mutex */
638 long vhost_dev_check_owner(struct vhost_dev *dev)
639 {
640 	/* Are you the owner? If not, I don't think you mean to do that */
641 	return dev->mm == current->mm ? 0 : -EPERM;
642 }
643 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
644 
645 struct vhost_attach_cgroups_struct {
646 	struct vhost_work work;
647 	struct task_struct *owner;
648 	int ret;
649 };
650 
651 static void vhost_attach_cgroups_work(struct vhost_work *work)
652 {
653 	struct vhost_attach_cgroups_struct *s;
654 
655 	s = container_of(work, struct vhost_attach_cgroups_struct, work);
656 	s->ret = cgroup_attach_task_all(s->owner, current);
657 }
658 
659 static int vhost_attach_task_to_cgroups(struct vhost_worker *worker)
660 {
661 	struct vhost_attach_cgroups_struct attach;
662 	int saved_cnt;
663 
664 	attach.owner = current;
665 
666 	vhost_work_init(&attach.work, vhost_attach_cgroups_work);
667 	vhost_worker_queue(worker, &attach.work);
668 
669 	mutex_lock(&worker->mutex);
670 
671 	/*
672 	 * Bypass attachment_cnt check in __vhost_worker_flush:
673 	 * Temporarily change it to INT_MAX to bypass the check
674 	 */
675 	saved_cnt = worker->attachment_cnt;
676 	worker->attachment_cnt = INT_MAX;
677 	__vhost_worker_flush(worker);
678 	worker->attachment_cnt = saved_cnt;
679 
680 	mutex_unlock(&worker->mutex);
681 
682 	return attach.ret;
683 }
684 
685 /* Caller should have device mutex */
686 bool vhost_dev_has_owner(struct vhost_dev *dev)
687 {
688 	return dev->mm;
689 }
690 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
691 
692 static void vhost_attach_mm(struct vhost_dev *dev)
693 {
694 	/* No owner, become one */
695 	if (dev->use_worker) {
696 		dev->mm = get_task_mm(current);
697 	} else {
698 		/* vDPA device does not use worker thread, so there's
699 		 * no need to hold the address space for mm. This helps
700 		 * to avoid deadlock in the case of mmap() which may
701 		 * hold the refcnt of the file and depends on release
702 		 * method to remove vma.
703 		 */
704 		dev->mm = current->mm;
705 		mmgrab(dev->mm);
706 	}
707 }
708 
709 static void vhost_detach_mm(struct vhost_dev *dev)
710 {
711 	if (!dev->mm)
712 		return;
713 
714 	if (dev->use_worker)
715 		mmput(dev->mm);
716 	else
717 		mmdrop(dev->mm);
718 
719 	dev->mm = NULL;
720 }
721 
722 static void vhost_worker_destroy(struct vhost_dev *dev,
723 				 struct vhost_worker *worker)
724 {
725 	if (!worker)
726 		return;
727 
728 	WARN_ON(!llist_empty(&worker->work_list));
729 	xa_erase(&dev->worker_xa, worker->id);
730 	worker->ops->stop(worker);
731 	kfree(worker);
732 }
733 
734 static void vhost_workers_free(struct vhost_dev *dev, bool sync)
735 {
736 	struct vhost_worker *worker;
737 	unsigned long i;
738 
739 	if (!dev->use_worker)
740 		return;
741 
742 	for (i = 0; i < dev->nvqs; i++)
743 		rcu_assign_pointer(dev->vqs[i]->worker, NULL);
744 
745 	/*
746 	 * This path can be reached by lockless work queuers.  In this case
747 	 * vhost_vq_work_queue() reads vq->worker under rcu_read_lock(), so a
748 	 * RCU reader that fetched a worker before we cleared the pointers above
749 	 * may still be queueing work on it.  Wait for those readers to finish,
750 	 * then flush so any work they queued runs (clearing VHOST_WORK_QUEUED)
751 	 * before the workers are freed.  Notably, that is the case for the
752 	 * vsock RESET_OWNER path.
753 	 */
754 	if (sync) {
755 		synchronize_rcu();
756 		vhost_dev_flush(dev);
757 	}
758 
759 	/*
760 	 * Free the default worker we created and cleanup workers userspace
761 	 * created but couldn't clean up (it forgot or crashed).
762 	 */
763 	xa_for_each(&dev->worker_xa, i, worker)
764 		vhost_worker_destroy(dev, worker);
765 	xa_destroy(&dev->worker_xa);
766 }
767 
768 static void vhost_task_wakeup(struct vhost_worker *worker)
769 {
770 	return vhost_task_wake(worker->vtsk);
771 }
772 
773 static void vhost_kthread_wakeup(struct vhost_worker *worker)
774 {
775 	wake_up_process(worker->kthread_task);
776 }
777 
778 static void vhost_task_do_stop(struct vhost_worker *worker)
779 {
780 	return vhost_task_stop(worker->vtsk);
781 }
782 
783 static void vhost_kthread_do_stop(struct vhost_worker *worker)
784 {
785 	kthread_stop(worker->kthread_task);
786 }
787 
788 static int vhost_task_worker_create(struct vhost_worker *worker,
789 				    struct vhost_dev *dev, const char *name)
790 {
791 	struct vhost_task *vtsk;
792 	u32 id;
793 	int ret;
794 
795 	vtsk = vhost_task_create(vhost_run_work_list, vhost_worker_killed,
796 				 worker, name);
797 	if (IS_ERR(vtsk))
798 		return PTR_ERR(vtsk);
799 
800 	worker->vtsk = vtsk;
801 	vhost_task_start(vtsk);
802 	ret = xa_alloc(&dev->worker_xa, &id, worker, xa_limit_32b, GFP_KERNEL);
803 	if (ret < 0) {
804 		vhost_task_do_stop(worker);
805 		return ret;
806 	}
807 	worker->id = id;
808 	return 0;
809 }
810 
811 static int vhost_kthread_worker_create(struct vhost_worker *worker,
812 				       struct vhost_dev *dev, const char *name)
813 {
814 	struct task_struct *task;
815 	u32 id;
816 	int ret;
817 
818 	task = kthread_create(vhost_run_work_kthread_list, worker, "%s", name);
819 	if (IS_ERR(task))
820 		return PTR_ERR(task);
821 
822 	worker->kthread_task = task;
823 	wake_up_process(task);
824 	ret = xa_alloc(&dev->worker_xa, &id, worker, xa_limit_32b, GFP_KERNEL);
825 	if (ret < 0)
826 		goto stop_worker;
827 
828 	ret = vhost_attach_task_to_cgroups(worker);
829 	if (ret)
830 		goto free_id;
831 
832 	worker->id = id;
833 	return 0;
834 
835 free_id:
836 	xa_erase(&dev->worker_xa, id);
837 stop_worker:
838 	vhost_kthread_do_stop(worker);
839 	return ret;
840 }
841 
842 static const struct vhost_worker_ops kthread_ops = {
843 	.create = vhost_kthread_worker_create,
844 	.stop = vhost_kthread_do_stop,
845 	.wakeup = vhost_kthread_wakeup,
846 };
847 
848 static const struct vhost_worker_ops vhost_task_ops = {
849 	.create = vhost_task_worker_create,
850 	.stop = vhost_task_do_stop,
851 	.wakeup = vhost_task_wakeup,
852 };
853 
854 static struct vhost_worker *vhost_worker_create(struct vhost_dev *dev)
855 {
856 	struct vhost_worker *worker;
857 	char name[TASK_COMM_LEN];
858 	int ret;
859 	const struct vhost_worker_ops *ops = dev->fork_owner ? &vhost_task_ops :
860 							       &kthread_ops;
861 
862 	worker = kzalloc_obj(*worker, GFP_KERNEL_ACCOUNT);
863 	if (!worker)
864 		return NULL;
865 
866 	worker->dev = dev;
867 	worker->ops = ops;
868 	snprintf(name, sizeof(name), "vhost-%d", current->pid);
869 
870 	mutex_init(&worker->mutex);
871 	init_llist_head(&worker->work_list);
872 	worker->kcov_handle = kcov_common_handle();
873 	ret = ops->create(worker, dev, name);
874 	if (ret < 0)
875 		goto free_worker;
876 
877 	return worker;
878 
879 free_worker:
880 	kfree(worker);
881 	return NULL;
882 }
883 
884 /* Caller must have device mutex */
885 static void __vhost_vq_attach_worker(struct vhost_virtqueue *vq,
886 				     struct vhost_worker *worker)
887 {
888 	struct vhost_worker *old_worker;
889 
890 	mutex_lock(&worker->mutex);
891 	if (worker->killed) {
892 		mutex_unlock(&worker->mutex);
893 		return;
894 	}
895 
896 	mutex_lock(&vq->mutex);
897 
898 	old_worker = rcu_dereference_check(vq->worker,
899 					   lockdep_is_held(&vq->mutex));
900 	rcu_assign_pointer(vq->worker, worker);
901 	worker->attachment_cnt++;
902 
903 	if (!old_worker) {
904 		mutex_unlock(&vq->mutex);
905 		mutex_unlock(&worker->mutex);
906 		return;
907 	}
908 	mutex_unlock(&vq->mutex);
909 	mutex_unlock(&worker->mutex);
910 
911 	/*
912 	 * Take the worker mutex to make sure we see the work queued from
913 	 * device wide flushes which doesn't use RCU for execution.
914 	 */
915 	mutex_lock(&old_worker->mutex);
916 	if (old_worker->killed) {
917 		mutex_unlock(&old_worker->mutex);
918 		return;
919 	}
920 
921 	/*
922 	 * We don't want to call synchronize_rcu for every vq during setup
923 	 * because it will slow down VM startup. If we haven't done
924 	 * VHOST_SET_VRING_KICK and not done the driver specific
925 	 * SET_ENDPOINT/RUNNING then we can skip the sync since there will
926 	 * not be any works queued for scsi and net.
927 	 */
928 	mutex_lock(&vq->mutex);
929 	if (!vhost_vq_get_backend(vq) && !vq->kick) {
930 		mutex_unlock(&vq->mutex);
931 
932 		old_worker->attachment_cnt--;
933 		mutex_unlock(&old_worker->mutex);
934 		/*
935 		 * vsock can queue anytime after VHOST_VSOCK_SET_GUEST_CID.
936 		 * Warn if it adds support for multiple workers but forgets to
937 		 * handle the early queueing case.
938 		 */
939 		WARN_ON(!old_worker->attachment_cnt &&
940 			!llist_empty(&old_worker->work_list));
941 		return;
942 	}
943 	mutex_unlock(&vq->mutex);
944 
945 	/* Make sure new vq queue/flush/poll calls see the new worker */
946 	synchronize_rcu();
947 	/* Make sure whatever was queued gets run */
948 	__vhost_worker_flush(old_worker);
949 	old_worker->attachment_cnt--;
950 	mutex_unlock(&old_worker->mutex);
951 }
952 
953  /* Caller must have device mutex */
954 static int vhost_vq_attach_worker(struct vhost_virtqueue *vq,
955 				  struct vhost_vring_worker *info)
956 {
957 	unsigned long index = info->worker_id;
958 	struct vhost_dev *dev = vq->dev;
959 	struct vhost_worker *worker;
960 
961 	if (!dev->use_worker)
962 		return -EINVAL;
963 
964 	worker = xa_find(&dev->worker_xa, &index, UINT_MAX, XA_PRESENT);
965 	if (!worker || worker->id != info->worker_id)
966 		return -ENODEV;
967 
968 	__vhost_vq_attach_worker(vq, worker);
969 	return 0;
970 }
971 
972 /* Caller must have device mutex */
973 static int vhost_new_worker(struct vhost_dev *dev,
974 			    struct vhost_worker_state *info)
975 {
976 	struct vhost_worker *worker;
977 
978 	worker = vhost_worker_create(dev);
979 	if (!worker)
980 		return -ENOMEM;
981 
982 	info->worker_id = worker->id;
983 	return 0;
984 }
985 
986 /* Caller must have device mutex */
987 static int vhost_free_worker(struct vhost_dev *dev,
988 			     struct vhost_worker_state *info)
989 {
990 	unsigned long index = info->worker_id;
991 	struct vhost_worker *worker;
992 
993 	worker = xa_find(&dev->worker_xa, &index, UINT_MAX, XA_PRESENT);
994 	if (!worker || worker->id != info->worker_id)
995 		return -ENODEV;
996 
997 	mutex_lock(&worker->mutex);
998 	if (worker->attachment_cnt || worker->killed) {
999 		mutex_unlock(&worker->mutex);
1000 		return -EBUSY;
1001 	}
1002 	/*
1003 	 * A flush might have raced and snuck in before attachment_cnt was set
1004 	 * to zero. Make sure flushes are flushed from the queue before
1005 	 * freeing.
1006 	 */
1007 	__vhost_worker_flush(worker);
1008 	mutex_unlock(&worker->mutex);
1009 
1010 	vhost_worker_destroy(dev, worker);
1011 	return 0;
1012 }
1013 
1014 static int vhost_get_vq_from_user(struct vhost_dev *dev, void __user *argp,
1015 				  struct vhost_virtqueue **vq, u32 *id)
1016 {
1017 	u32 __user *idxp = argp;
1018 	u32 idx;
1019 	long r;
1020 
1021 	r = get_user(idx, idxp);
1022 	if (r < 0)
1023 		return r;
1024 
1025 	if (idx >= dev->nvqs)
1026 		return -ENOBUFS;
1027 
1028 	idx = array_index_nospec(idx, dev->nvqs);
1029 
1030 	*vq = dev->vqs[idx];
1031 	*id = idx;
1032 	return 0;
1033 }
1034 
1035 /* Caller must have device mutex */
1036 long vhost_worker_ioctl(struct vhost_dev *dev, unsigned int ioctl,
1037 			void __user *argp)
1038 {
1039 	struct vhost_vring_worker ring_worker;
1040 	struct vhost_worker_state state;
1041 	struct vhost_worker *worker;
1042 	struct vhost_virtqueue *vq;
1043 	long ret;
1044 	u32 idx;
1045 
1046 	if (!dev->use_worker)
1047 		return -EINVAL;
1048 
1049 	if (!vhost_dev_has_owner(dev))
1050 		return -EINVAL;
1051 
1052 	ret = vhost_dev_check_owner(dev);
1053 	if (ret)
1054 		return ret;
1055 
1056 	switch (ioctl) {
1057 	/* dev worker ioctls */
1058 	case VHOST_NEW_WORKER:
1059 		/*
1060 		 * vhost_tasks will account for worker threads under the parent's
1061 		 * NPROC value but kthreads do not. To avoid userspace overflowing
1062 		 * the system with worker threads fork_owner must be true.
1063 		 */
1064 		if (!dev->fork_owner)
1065 			return -EFAULT;
1066 
1067 		ret = vhost_new_worker(dev, &state);
1068 		if (!ret && copy_to_user(argp, &state, sizeof(state)))
1069 			ret = -EFAULT;
1070 		return ret;
1071 	case VHOST_FREE_WORKER:
1072 		if (copy_from_user(&state, argp, sizeof(state)))
1073 			return -EFAULT;
1074 		return vhost_free_worker(dev, &state);
1075 	/* vring worker ioctls */
1076 	case VHOST_ATTACH_VRING_WORKER:
1077 	case VHOST_GET_VRING_WORKER:
1078 		break;
1079 	default:
1080 		return -ENOIOCTLCMD;
1081 	}
1082 
1083 	ret = vhost_get_vq_from_user(dev, argp, &vq, &idx);
1084 	if (ret)
1085 		return ret;
1086 
1087 	switch (ioctl) {
1088 	case VHOST_ATTACH_VRING_WORKER:
1089 		if (copy_from_user(&ring_worker, argp, sizeof(ring_worker))) {
1090 			ret = -EFAULT;
1091 			break;
1092 		}
1093 
1094 		ret = vhost_vq_attach_worker(vq, &ring_worker);
1095 		break;
1096 	case VHOST_GET_VRING_WORKER:
1097 		worker = rcu_dereference_check(vq->worker,
1098 					       lockdep_is_held(&dev->mutex));
1099 		if (!worker) {
1100 			ret = -EINVAL;
1101 			break;
1102 		}
1103 
1104 		ring_worker.index = idx;
1105 		ring_worker.worker_id = worker->id;
1106 
1107 		if (copy_to_user(argp, &ring_worker, sizeof(ring_worker)))
1108 			ret = -EFAULT;
1109 		break;
1110 	default:
1111 		ret = -ENOIOCTLCMD;
1112 		break;
1113 	}
1114 
1115 	return ret;
1116 }
1117 EXPORT_SYMBOL_GPL(vhost_worker_ioctl);
1118 
1119 /* Caller should have device mutex */
1120 long vhost_dev_set_owner(struct vhost_dev *dev)
1121 {
1122 	struct vhost_worker *worker;
1123 	int err, i;
1124 
1125 	/* Is there an owner already? */
1126 	if (vhost_dev_has_owner(dev)) {
1127 		err = -EBUSY;
1128 		goto err_mm;
1129 	}
1130 
1131 	vhost_attach_mm(dev);
1132 
1133 	err = vhost_dev_alloc_iovecs(dev);
1134 	if (err)
1135 		goto err_iovecs;
1136 
1137 	if (dev->use_worker) {
1138 		/*
1139 		 * This should be done last, because vsock can queue work
1140 		 * before VHOST_SET_OWNER so it simplifies the failure path
1141 		 * below since we don't have to worry about vsock queueing
1142 		 * while we free the worker.
1143 		 */
1144 		worker = vhost_worker_create(dev);
1145 		if (!worker) {
1146 			err = -ENOMEM;
1147 			goto err_worker;
1148 		}
1149 
1150 		for (i = 0; i < dev->nvqs; i++)
1151 			__vhost_vq_attach_worker(dev->vqs[i], worker);
1152 	}
1153 
1154 	return 0;
1155 
1156 err_worker:
1157 	vhost_dev_free_iovecs(dev);
1158 err_iovecs:
1159 	vhost_detach_mm(dev);
1160 err_mm:
1161 	return err;
1162 }
1163 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
1164 
1165 static struct vhost_iotlb *iotlb_alloc(void)
1166 {
1167 	if (max_iotlb_entries <= 0)
1168 		return NULL;
1169 
1170 	return vhost_iotlb_alloc(max_iotlb_entries,
1171 				 VHOST_IOTLB_FLAG_RETIRE);
1172 }
1173 
1174 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void)
1175 {
1176 	return iotlb_alloc();
1177 }
1178 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
1179 
1180 /* Caller should have device mutex */
1181 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem,
1182 			   bool sync)
1183 {
1184 	int i;
1185 
1186 	vhost_dev_cleanup(dev, sync);
1187 
1188 	dev->fork_owner = fork_from_owner_default;
1189 	dev->umem = umem;
1190 	/* We don't need VQ locks below since vhost_dev_cleanup makes sure
1191 	 * VQs aren't running.
1192 	 */
1193 	for (i = 0; i < dev->nvqs; ++i)
1194 		dev->vqs[i]->umem = umem;
1195 }
1196 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
1197 
1198 void vhost_dev_stop(struct vhost_dev *dev)
1199 {
1200 	int i;
1201 
1202 	for (i = 0; i < dev->nvqs; ++i) {
1203 		if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick)
1204 			vhost_poll_stop(&dev->vqs[i]->poll);
1205 	}
1206 
1207 	vhost_dev_flush(dev);
1208 }
1209 EXPORT_SYMBOL_GPL(vhost_dev_stop);
1210 
1211 static void vhost_free_msg_locked(struct vhost_msg_node *node)
1212 {
1213 	if (node->vq->iotlb_miss == node)
1214 		node->vq->iotlb_miss = NULL;
1215 	kfree(node);
1216 }
1217 
1218 static void vhost_free_msg(struct vhost_dev *dev,
1219 			   struct vhost_msg_node *node)
1220 {
1221 	spin_lock(&dev->iotlb_lock);
1222 	vhost_free_msg_locked(node);
1223 	spin_unlock(&dev->iotlb_lock);
1224 }
1225 
1226 void vhost_clear_msg(struct vhost_dev *dev)
1227 {
1228 	struct vhost_msg_node *node, *n;
1229 
1230 	spin_lock(&dev->iotlb_lock);
1231 
1232 	list_for_each_entry_safe(node, n, &dev->read_list, node) {
1233 		list_del(&node->node);
1234 		vhost_free_msg_locked(node);
1235 	}
1236 
1237 	list_for_each_entry_safe(node, n, &dev->pending_list, node) {
1238 		list_del(&node->node);
1239 		vhost_free_msg_locked(node);
1240 	}
1241 
1242 	spin_unlock(&dev->iotlb_lock);
1243 }
1244 EXPORT_SYMBOL_GPL(vhost_clear_msg);
1245 
1246 void vhost_dev_cleanup(struct vhost_dev *dev, bool sync)
1247 {
1248 	int i;
1249 
1250 	for (i = 0; i < dev->nvqs; ++i) {
1251 		if (dev->vqs[i]->error_ctx)
1252 			eventfd_ctx_put(dev->vqs[i]->error_ctx);
1253 		if (dev->vqs[i]->kick)
1254 			fput(dev->vqs[i]->kick);
1255 		if (dev->vqs[i]->call_ctx.ctx)
1256 			eventfd_ctx_put(dev->vqs[i]->call_ctx.ctx);
1257 		vhost_vq_reset(dev, dev->vqs[i]);
1258 	}
1259 	vhost_dev_free_iovecs(dev);
1260 	if (dev->log_ctx)
1261 		eventfd_ctx_put(dev->log_ctx);
1262 	dev->log_ctx = NULL;
1263 	/* No one will access memory at this point */
1264 	vhost_iotlb_free(dev->umem);
1265 	dev->umem = NULL;
1266 	vhost_iotlb_free(dev->iotlb);
1267 	dev->iotlb = NULL;
1268 	vhost_clear_msg(dev);
1269 	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
1270 	vhost_workers_free(dev, sync);
1271 	vhost_detach_mm(dev);
1272 }
1273 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
1274 
1275 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
1276 {
1277 	u64 a = addr / VHOST_PAGE_SIZE / 8;
1278 
1279 	/* Make sure 64 bit math will not overflow. */
1280 	if (a > ULONG_MAX - (unsigned long)log_base ||
1281 	    a + (unsigned long)log_base > ULONG_MAX)
1282 		return false;
1283 
1284 	return access_ok(log_base + a,
1285 			 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
1286 }
1287 
1288 /* Make sure 64 bit math will not overflow. */
1289 static bool vhost_overflow(u64 uaddr, u64 size)
1290 {
1291 	if (uaddr > ULONG_MAX || size > ULONG_MAX)
1292 		return true;
1293 
1294 	if (!size)
1295 		return false;
1296 
1297 	return uaddr > ULONG_MAX - size + 1;
1298 }
1299 
1300 /* Caller should have vq mutex and device mutex. */
1301 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem,
1302 				int log_all)
1303 {
1304 	struct vhost_iotlb_map *map;
1305 
1306 	if (!umem)
1307 		return false;
1308 
1309 	list_for_each_entry(map, &umem->list, link) {
1310 		unsigned long a = map->addr;
1311 
1312 		if (vhost_overflow(map->addr, map->size))
1313 			return false;
1314 
1315 
1316 		if (!access_ok((void __user *)a, map->size))
1317 			return false;
1318 		else if (log_all && !log_access_ok(log_base,
1319 						   map->start,
1320 						   map->size))
1321 			return false;
1322 	}
1323 	return true;
1324 }
1325 
1326 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
1327 					       u64 addr, unsigned int size,
1328 					       int type)
1329 {
1330 	const struct vhost_iotlb_map *map = vq->meta_iotlb[type];
1331 
1332 	if (!map)
1333 		return NULL;
1334 
1335 	return (void __user *)(uintptr_t)(map->addr + addr - map->start);
1336 }
1337 
1338 /* Can we switch to this memory table? */
1339 /* Caller should have device mutex but not vq mutex */
1340 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem,
1341 			     int log_all)
1342 {
1343 	int i;
1344 
1345 	for (i = 0; i < d->nvqs; ++i) {
1346 		bool ok;
1347 		bool log;
1348 
1349 		mutex_lock(&d->vqs[i]->mutex);
1350 		log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
1351 		/* If ring is inactive, will check when it's enabled. */
1352 		if (d->vqs[i]->private_data)
1353 			ok = vq_memory_access_ok(d->vqs[i]->log_base,
1354 						 umem, log);
1355 		else
1356 			ok = true;
1357 		mutex_unlock(&d->vqs[i]->mutex);
1358 		if (!ok)
1359 			return false;
1360 	}
1361 	return true;
1362 }
1363 
1364 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1365 			  struct iovec iov[], int iov_size, int access);
1366 
1367 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
1368 			      const void *from, unsigned size)
1369 {
1370 	int ret;
1371 
1372 	if (!vq->iotlb)
1373 		return __copy_to_user(to, from, size);
1374 	else {
1375 		/* This function should be called after iotlb
1376 		 * prefetch, which means we're sure that all vq
1377 		 * could be access through iotlb. So -EAGAIN should
1378 		 * not happen in this case.
1379 		 */
1380 		struct iov_iter t;
1381 		void __user *uaddr = vhost_vq_meta_fetch(vq,
1382 				     (u64)(uintptr_t)to, size,
1383 				     VHOST_ADDR_USED);
1384 
1385 		if (uaddr)
1386 			return __copy_to_user(uaddr, from, size);
1387 
1388 		ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
1389 				     ARRAY_SIZE(vq->iotlb_iov),
1390 				     VHOST_ACCESS_WO);
1391 		if (ret < 0)
1392 			goto out;
1393 		iov_iter_init(&t, ITER_DEST, vq->iotlb_iov, ret, size);
1394 		ret = copy_to_iter(from, size, &t);
1395 		if (ret == size)
1396 			ret = 0;
1397 	}
1398 out:
1399 	return ret;
1400 }
1401 
1402 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
1403 				void __user *from, unsigned size)
1404 {
1405 	int ret;
1406 
1407 	if (!vq->iotlb)
1408 		return __copy_from_user(to, from, size);
1409 	else {
1410 		/* This function should be called after iotlb
1411 		 * prefetch, which means we're sure that vq
1412 		 * could be access through iotlb. So -EAGAIN should
1413 		 * not happen in this case.
1414 		 */
1415 		void __user *uaddr = vhost_vq_meta_fetch(vq,
1416 				     (u64)(uintptr_t)from, size,
1417 				     VHOST_ADDR_DESC);
1418 		struct iov_iter f;
1419 
1420 		if (uaddr)
1421 			return __copy_from_user(to, uaddr, size);
1422 
1423 		ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
1424 				     ARRAY_SIZE(vq->iotlb_iov),
1425 				     VHOST_ACCESS_RO);
1426 		if (ret < 0) {
1427 			vq_err(vq, "IOTLB translation failure: uaddr "
1428 			       "%p size 0x%llx\n", from,
1429 			       (unsigned long long) size);
1430 			goto out;
1431 		}
1432 		iov_iter_init(&f, ITER_SOURCE, vq->iotlb_iov, ret, size);
1433 		ret = copy_from_iter(to, size, &f);
1434 		if (ret == size)
1435 			ret = 0;
1436 	}
1437 
1438 out:
1439 	return ret;
1440 }
1441 
1442 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
1443 					  void __user *addr, unsigned int size,
1444 					  int type)
1445 {
1446 	int ret;
1447 
1448 	ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
1449 			     ARRAY_SIZE(vq->iotlb_iov),
1450 			     VHOST_ACCESS_RO);
1451 	if (ret < 0) {
1452 		vq_err(vq, "IOTLB translation failure: uaddr "
1453 			"%p size 0x%llx\n", addr,
1454 			(unsigned long long) size);
1455 		return NULL;
1456 	}
1457 
1458 	if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
1459 		vq_err(vq, "Non atomic userspace memory access: uaddr "
1460 			"%p size 0x%llx\n", addr,
1461 			(unsigned long long) size);
1462 		return NULL;
1463 	}
1464 
1465 	return vq->iotlb_iov[0].iov_base;
1466 }
1467 
1468 /* This function should be called after iotlb
1469  * prefetch, which means we're sure that vq
1470  * could be access through iotlb. So -EAGAIN should
1471  * not happen in this case.
1472  */
1473 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
1474 					    void __user *addr, unsigned int size,
1475 					    int type)
1476 {
1477 	void __user *uaddr = vhost_vq_meta_fetch(vq,
1478 			     (u64)(uintptr_t)addr, size, type);
1479 	if (uaddr)
1480 		return uaddr;
1481 
1482 	return __vhost_get_user_slow(vq, addr, size, type);
1483 }
1484 
1485 #define vhost_put_user(vq, x, ptr)		\
1486 ({ \
1487 	int ret; \
1488 	if (!vq->iotlb) { \
1489 		ret = put_user(x, ptr); \
1490 	} else { \
1491 		__typeof__(ptr) to = \
1492 			(__typeof__(ptr)) __vhost_get_user(vq, ptr,	\
1493 					  sizeof(*ptr), VHOST_ADDR_USED); \
1494 		if (to != NULL) \
1495 			ret = put_user(x, to); \
1496 		else \
1497 			ret = -EFAULT;	\
1498 	} \
1499 	ret; \
1500 })
1501 
1502 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
1503 {
1504 	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
1505 			      vhost_avail_event(vq));
1506 }
1507 
1508 static inline int vhost_put_used(struct vhost_virtqueue *vq,
1509 				 struct vring_used_elem *head, int idx,
1510 				 int count)
1511 {
1512 	return vhost_copy_to_user(vq, vq->used->ring + idx, head,
1513 				  count * sizeof(*head));
1514 }
1515 
1516 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
1517 
1518 {
1519 	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
1520 			      &vq->used->flags);
1521 }
1522 
1523 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
1524 
1525 {
1526 	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
1527 			      &vq->used->idx);
1528 }
1529 
1530 #define vhost_get_user(vq, x, ptr, type)		\
1531 ({ \
1532 	int ret; \
1533 	if (!vq->iotlb) { \
1534 		ret = get_user(x, ptr); \
1535 	} else { \
1536 		__typeof__(ptr) from = \
1537 			(__typeof__(ptr)) __vhost_get_user(vq, ptr, \
1538 							   sizeof(*ptr), \
1539 							   type); \
1540 		if (from != NULL) \
1541 			ret = get_user(x, from); \
1542 		else \
1543 			ret = -EFAULT; \
1544 	} \
1545 	ret; \
1546 })
1547 
1548 #define vhost_get_avail(vq, x, ptr) \
1549 	vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
1550 
1551 #define vhost_get_used(vq, x, ptr) \
1552 	vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
1553 
1554 static void vhost_dev_lock_vqs(struct vhost_dev *d)
1555 {
1556 	int i = 0;
1557 	for (i = 0; i < d->nvqs; ++i)
1558 		mutex_lock_nested(&d->vqs[i]->mutex, i);
1559 }
1560 
1561 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
1562 {
1563 	int i = 0;
1564 	for (i = 0; i < d->nvqs; ++i)
1565 		mutex_unlock(&d->vqs[i]->mutex);
1566 }
1567 
1568 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq)
1569 {
1570 	__virtio16 idx;
1571 	u16 avail_idx;
1572 	int r;
1573 
1574 	r = vhost_get_avail(vq, idx, &vq->avail->idx);
1575 	if (unlikely(r < 0)) {
1576 		vq_err(vq, "Failed to access available index at %p (%d)\n",
1577 		       &vq->avail->idx, r);
1578 		return r;
1579 	}
1580 
1581 	/* Check it isn't doing very strange thing with available indexes */
1582 	avail_idx = vhost16_to_cpu(vq, idx);
1583 	if (unlikely((u16)(avail_idx - vq->last_avail_idx) > vq->num)) {
1584 		vq_err(vq, "Invalid available index change from %u to %u",
1585 		       vq->last_avail_idx, avail_idx);
1586 		return -EINVAL;
1587 	}
1588 
1589 	/* We're done if there is nothing new */
1590 	if (avail_idx == vq->avail_idx)
1591 		return 0;
1592 
1593 	vq->avail_idx = avail_idx;
1594 
1595 	/*
1596 	 * We updated vq->avail_idx so we need a memory barrier between
1597 	 * the index read above and the caller reading avail ring entries.
1598 	 */
1599 	smp_rmb();
1600 	return 1;
1601 }
1602 
1603 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
1604 				       __virtio16 *head, int idx)
1605 {
1606 	return vhost_get_avail(vq, *head,
1607 			       &vq->avail->ring[idx & (vq->num - 1)]);
1608 }
1609 
1610 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1611 					__virtio16 *flags)
1612 {
1613 	return vhost_get_avail(vq, *flags, &vq->avail->flags);
1614 }
1615 
1616 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1617 				       __virtio16 *event)
1618 {
1619 	return vhost_get_avail(vq, *event, vhost_used_event(vq));
1620 }
1621 
1622 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1623 				     __virtio16 *idx)
1624 {
1625 	return vhost_get_used(vq, *idx, &vq->used->idx);
1626 }
1627 
1628 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1629 				 struct vring_desc *desc, int idx)
1630 {
1631 	return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1632 }
1633 
1634 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1635 				  struct vhost_iotlb_msg *msg)
1636 {
1637 	struct vhost_msg_node *node, *n;
1638 
1639 	spin_lock(&d->iotlb_lock);
1640 
1641 	list_for_each_entry_safe(node, n, &d->pending_list, node) {
1642 		struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1643 		if (msg->iova <= vq_msg->iova &&
1644 		    msg->iova + msg->size - 1 >= vq_msg->iova &&
1645 		    vq_msg->type == VHOST_IOTLB_MISS) {
1646 			vhost_poll_queue(&node->vq->poll);
1647 			list_del(&node->node);
1648 			vhost_free_msg_locked(node);
1649 		}
1650 	}
1651 
1652 	spin_unlock(&d->iotlb_lock);
1653 }
1654 
1655 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1656 {
1657 	unsigned long a = uaddr;
1658 
1659 	/* Make sure 64 bit math will not overflow. */
1660 	if (vhost_overflow(uaddr, size))
1661 		return false;
1662 
1663 	if ((access & VHOST_ACCESS_RO) &&
1664 	    !access_ok((void __user *)a, size))
1665 		return false;
1666 	if ((access & VHOST_ACCESS_WO) &&
1667 	    !access_ok((void __user *)a, size))
1668 		return false;
1669 	return true;
1670 }
1671 
1672 static int vhost_process_iotlb_msg(struct vhost_dev *dev, u32 asid,
1673 				   struct vhost_iotlb_msg *msg)
1674 {
1675 	int ret = 0;
1676 
1677 	if (asid != 0)
1678 		return -EINVAL;
1679 
1680 	mutex_lock(&dev->mutex);
1681 	vhost_dev_lock_vqs(dev);
1682 	switch (msg->type) {
1683 	case VHOST_IOTLB_UPDATE:
1684 		if (!dev->iotlb) {
1685 			ret = -EFAULT;
1686 			break;
1687 		}
1688 		if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1689 			ret = -EFAULT;
1690 			break;
1691 		}
1692 		vhost_vq_meta_reset(dev);
1693 		if (vhost_iotlb_add_range(dev->iotlb, msg->iova,
1694 					  msg->iova + msg->size - 1,
1695 					  msg->uaddr, msg->perm)) {
1696 			ret = -ENOMEM;
1697 			break;
1698 		}
1699 		vhost_iotlb_notify_vq(dev, msg);
1700 		break;
1701 	case VHOST_IOTLB_INVALIDATE:
1702 		if (!dev->iotlb) {
1703 			ret = -EFAULT;
1704 			break;
1705 		}
1706 		if (!msg->size) {
1707 			ret = -EINVAL;
1708 			break;
1709 		}
1710 		vhost_vq_meta_reset(dev);
1711 		vhost_iotlb_del_range(dev->iotlb, msg->iova,
1712 				      msg->iova + msg->size - 1);
1713 		break;
1714 	default:
1715 		ret = -EINVAL;
1716 		break;
1717 	}
1718 
1719 	vhost_dev_unlock_vqs(dev);
1720 	mutex_unlock(&dev->mutex);
1721 
1722 	return ret;
1723 }
1724 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1725 			     struct iov_iter *from)
1726 {
1727 	struct vhost_iotlb_msg msg;
1728 	size_t offset;
1729 	int type, ret;
1730 	u32 asid = 0;
1731 
1732 	ret = copy_from_iter(&type, sizeof(type), from);
1733 	if (ret != sizeof(type)) {
1734 		ret = -EINVAL;
1735 		goto done;
1736 	}
1737 
1738 	switch (type) {
1739 	case VHOST_IOTLB_MSG:
1740 		/* There maybe a hole after type for V1 message type,
1741 		 * so skip it here.
1742 		 */
1743 		offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1744 		break;
1745 	case VHOST_IOTLB_MSG_V2:
1746 		if (vhost_backend_has_feature(dev->vqs[0],
1747 					      VHOST_BACKEND_F_IOTLB_ASID)) {
1748 			ret = copy_from_iter(&asid, sizeof(asid), from);
1749 			if (ret != sizeof(asid)) {
1750 				ret = -EINVAL;
1751 				goto done;
1752 			}
1753 			offset = 0;
1754 		} else
1755 			offset = sizeof(__u32);
1756 		break;
1757 	default:
1758 		ret = -EINVAL;
1759 		goto done;
1760 	}
1761 
1762 	iov_iter_advance(from, offset);
1763 	ret = copy_from_iter(&msg, sizeof(msg), from);
1764 	if (ret != sizeof(msg)) {
1765 		ret = -EINVAL;
1766 		goto done;
1767 	}
1768 
1769 	if (msg.type == VHOST_IOTLB_UPDATE && msg.size == 0) {
1770 		ret = -EINVAL;
1771 		goto done;
1772 	}
1773 
1774 	if (dev->msg_handler)
1775 		ret = dev->msg_handler(dev, asid, &msg);
1776 	else
1777 		ret = vhost_process_iotlb_msg(dev, asid, &msg);
1778 	if (ret) {
1779 		ret = -EFAULT;
1780 		goto done;
1781 	}
1782 
1783 	ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1784 	      sizeof(struct vhost_msg_v2);
1785 done:
1786 	return ret;
1787 }
1788 EXPORT_SYMBOL(vhost_chr_write_iter);
1789 
1790 __poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
1791 			    poll_table *wait)
1792 {
1793 	__poll_t mask = 0;
1794 
1795 	poll_wait(file, &dev->wait, wait);
1796 
1797 	if (!list_empty(&dev->read_list))
1798 		mask |= EPOLLIN | EPOLLRDNORM;
1799 
1800 	return mask;
1801 }
1802 EXPORT_SYMBOL(vhost_chr_poll);
1803 
1804 ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1805 			    int noblock)
1806 {
1807 	DEFINE_WAIT(wait);
1808 	struct vhost_msg_node *node;
1809 	ssize_t ret = 0;
1810 	unsigned size = sizeof(struct vhost_msg);
1811 
1812 	if (iov_iter_count(to) < size)
1813 		return 0;
1814 
1815 	while (1) {
1816 		if (!noblock)
1817 			prepare_to_wait(&dev->wait, &wait,
1818 					TASK_INTERRUPTIBLE);
1819 
1820 		node = vhost_dequeue_msg(dev, &dev->read_list);
1821 		if (node)
1822 			break;
1823 		if (noblock) {
1824 			ret = -EAGAIN;
1825 			break;
1826 		}
1827 		if (signal_pending(current)) {
1828 			ret = -ERESTARTSYS;
1829 			break;
1830 		}
1831 		if (!dev->iotlb) {
1832 			ret = -EBADFD;
1833 			break;
1834 		}
1835 
1836 		schedule();
1837 	}
1838 
1839 	if (!noblock)
1840 		finish_wait(&dev->wait, &wait);
1841 
1842 	if (node) {
1843 		struct vhost_iotlb_msg *msg;
1844 		void *start = &node->msg;
1845 
1846 		switch (node->msg.type) {
1847 		case VHOST_IOTLB_MSG:
1848 			size = sizeof(node->msg);
1849 			msg = &node->msg.iotlb;
1850 			break;
1851 		case VHOST_IOTLB_MSG_V2:
1852 			size = sizeof(node->msg_v2);
1853 			msg = &node->msg_v2.iotlb;
1854 			break;
1855 		default:
1856 			BUG();
1857 			break;
1858 		}
1859 
1860 		ret = copy_to_iter(start, size, to);
1861 		if (ret != size || msg->type != VHOST_IOTLB_MISS) {
1862 			vhost_free_msg(dev, node);
1863 			return ret;
1864 		}
1865 		vhost_enqueue_msg(dev, &dev->pending_list, node);
1866 	}
1867 
1868 	return ret;
1869 }
1870 EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1871 
1872 static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1873 {
1874 	struct vhost_dev *dev = vq->dev;
1875 	struct vhost_msg_node *node;
1876 	struct vhost_iotlb_msg *msg;
1877 	bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
1878 
1879 	node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
1880 	if (!node)
1881 		return -ENOMEM;
1882 
1883 	if (v2) {
1884 		node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1885 		msg = &node->msg_v2.iotlb;
1886 	} else {
1887 		msg = &node->msg.iotlb;
1888 	}
1889 
1890 	msg->type = VHOST_IOTLB_MISS;
1891 	msg->iova = iova;
1892 	msg->perm = access;
1893 
1894 	spin_lock(&dev->iotlb_lock);
1895 	/* VQ processing stops at the first miss until userspace resolves it. */
1896 	if (vq->iotlb_miss) {
1897 		spin_unlock(&dev->iotlb_lock);
1898 		kfree(node);
1899 		return 0;
1900 	}
1901 
1902 	vq->iotlb_miss = node;
1903 	list_add_tail(&node->node, &dev->read_list);
1904 	spin_unlock(&dev->iotlb_lock);
1905 
1906 	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
1907 
1908 	return 0;
1909 }
1910 
1911 static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
1912 			 vring_desc_t __user *desc,
1913 			 vring_avail_t __user *avail,
1914 			 vring_used_t __user *used)
1915 
1916 {
1917 	/* If an IOTLB device is present, the vring addresses are
1918 	 * GIOVAs. Access validation occurs at prefetch time. */
1919 	if (vq->iotlb)
1920 		return true;
1921 
1922 	return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1923 	       access_ok(avail, vhost_get_avail_size(vq, num)) &&
1924 	       access_ok(used, vhost_get_used_size(vq, num));
1925 }
1926 
1927 static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
1928 				 const struct vhost_iotlb_map *map,
1929 				 int type)
1930 {
1931 	int access = (type == VHOST_ADDR_USED) ?
1932 		     VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1933 
1934 	if (likely(map->perm & access))
1935 		vq->meta_iotlb[type] = map;
1936 }
1937 
1938 static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1939 			    int access, u64 addr, u64 len, int type)
1940 {
1941 	const struct vhost_iotlb_map *map;
1942 	struct vhost_iotlb *umem = vq->iotlb;
1943 	u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
1944 
1945 	if (vhost_vq_meta_fetch(vq, addr, len, type))
1946 		return true;
1947 
1948 	while (len > s) {
1949 		map = vhost_iotlb_itree_first(umem, addr, last);
1950 		if (map == NULL || map->start > addr) {
1951 			vhost_iotlb_miss(vq, addr, access);
1952 			return false;
1953 		} else if (!(map->perm & access)) {
1954 			/* Report the possible access violation by
1955 			 * request another translation from userspace.
1956 			 */
1957 			return false;
1958 		}
1959 
1960 		size = map->size - addr + map->start;
1961 
1962 		if (orig_addr == addr && size >= len)
1963 			vhost_vq_meta_update(vq, map, type);
1964 
1965 		s += size;
1966 		addr += size;
1967 	}
1968 
1969 	return true;
1970 }
1971 
1972 int vq_meta_prefetch(struct vhost_virtqueue *vq)
1973 {
1974 	unsigned int num = vq->num;
1975 
1976 	/*
1977 	 * vhost_vq_invalidate_access() clears all three addresses together.
1978 	 * A single zero address may be a valid GIOVA in IOTLB mode.
1979 	 */
1980 	if (!vq->desc && !vq->avail && !vq->used)
1981 		return 0;
1982 
1983 	if (!vq->iotlb)
1984 		return 1;
1985 
1986 	return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc,
1987 			       vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
1988 	       iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail,
1989 			       vhost_get_avail_size(vq, num),
1990 			       VHOST_ADDR_AVAIL) &&
1991 	       iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used,
1992 			       vhost_get_used_size(vq, num), VHOST_ADDR_USED);
1993 }
1994 EXPORT_SYMBOL_GPL(vq_meta_prefetch);
1995 
1996 /* Can we log writes? */
1997 /* Caller should have device mutex but not vq mutex */
1998 bool vhost_log_access_ok(struct vhost_dev *dev)
1999 {
2000 	return memory_access_ok(dev, dev->umem, 1);
2001 }
2002 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
2003 
2004 static bool vq_log_used_access_ok(struct vhost_virtqueue *vq,
2005 				  void __user *log_base,
2006 				  bool log_used,
2007 				  u64 log_addr)
2008 {
2009 	/* If an IOTLB device is present, log_addr is a GIOVA that
2010 	 * will never be logged by log_used(). */
2011 	if (vq->iotlb)
2012 		return true;
2013 
2014 	return !log_used || log_access_ok(log_base, log_addr,
2015 					  vhost_get_used_size(vq, vq->num));
2016 }
2017 
2018 /* Verify access for write logging. */
2019 /* Caller should have vq mutex and device mutex */
2020 static bool vq_log_access_ok(struct vhost_virtqueue *vq,
2021 			     void __user *log_base)
2022 {
2023 	return vq_memory_access_ok(log_base, vq->umem,
2024 				   vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
2025 		vq_log_used_access_ok(vq, log_base, vq->log_used, vq->log_addr);
2026 }
2027 
2028 /* Can we start vq? */
2029 /* Caller should have vq mutex and device mutex */
2030 bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
2031 {
2032 	if (!vq_log_access_ok(vq, vq->log_base))
2033 		return false;
2034 
2035 	return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
2036 }
2037 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
2038 
2039 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
2040 {
2041 	struct vhost_memory mem, *newmem;
2042 	struct vhost_memory_region *region;
2043 	struct vhost_iotlb *newumem, *oldumem;
2044 	unsigned long size = offsetof(struct vhost_memory, regions);
2045 	int i;
2046 
2047 	if (copy_from_user(&mem, m, size))
2048 		return -EFAULT;
2049 	if (mem.padding)
2050 		return -EOPNOTSUPP;
2051 	if (mem.nregions > max_mem_regions)
2052 		return -E2BIG;
2053 	if (max_iotlb_entries <= 0)
2054 		return -EINVAL;
2055 	newmem = kvzalloc_flex(*newmem, regions, mem.nregions);
2056 	if (!newmem)
2057 		return -ENOMEM;
2058 
2059 	memcpy(newmem, &mem, size);
2060 	if (copy_from_user(newmem->regions, m->regions,
2061 			   flex_array_size(newmem, regions, mem.nregions))) {
2062 		kvfree(newmem);
2063 		return -EFAULT;
2064 	}
2065 
2066 	newumem = iotlb_alloc();
2067 	if (!newumem) {
2068 		kvfree(newmem);
2069 		return -ENOMEM;
2070 	}
2071 
2072 	for (region = newmem->regions;
2073 	     region < newmem->regions + mem.nregions;
2074 	     region++) {
2075 		if (vhost_iotlb_add_range(newumem,
2076 					  region->guest_phys_addr,
2077 					  region->guest_phys_addr +
2078 					  region->memory_size - 1,
2079 					  region->userspace_addr,
2080 					  VHOST_MAP_RW))
2081 			goto err;
2082 	}
2083 
2084 	if (!memory_access_ok(d, newumem, 0))
2085 		goto err;
2086 
2087 	oldumem = d->umem;
2088 	d->umem = newumem;
2089 
2090 	/* All memory accesses are done under some VQ mutex. */
2091 	for (i = 0; i < d->nvqs; ++i) {
2092 		mutex_lock(&d->vqs[i]->mutex);
2093 		d->vqs[i]->umem = newumem;
2094 		mutex_unlock(&d->vqs[i]->mutex);
2095 	}
2096 
2097 	kvfree(newmem);
2098 	vhost_iotlb_free(oldumem);
2099 	return 0;
2100 
2101 err:
2102 	vhost_iotlb_free(newumem);
2103 	kvfree(newmem);
2104 	return -EFAULT;
2105 }
2106 
2107 static long vhost_vring_set_num(struct vhost_dev *d,
2108 				struct vhost_virtqueue *vq,
2109 				void __user *argp)
2110 {
2111 	struct vhost_vring_state s;
2112 
2113 	/* Resizing ring with an active backend?
2114 	 * You don't want to do that. */
2115 	if (vq->private_data)
2116 		return -EBUSY;
2117 
2118 	if (copy_from_user(&s, argp, sizeof s))
2119 		return -EFAULT;
2120 
2121 	if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
2122 		return -EINVAL;
2123 	vq->num = s.num;
2124 
2125 	return 0;
2126 }
2127 
2128 static long vhost_vring_set_addr(struct vhost_dev *d,
2129 				 struct vhost_virtqueue *vq,
2130 				 void __user *argp)
2131 {
2132 	struct vhost_vring_addr a;
2133 
2134 	if (copy_from_user(&a, argp, sizeof a))
2135 		return -EFAULT;
2136 	if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
2137 		return -EOPNOTSUPP;
2138 
2139 	/* For 32bit, verify that the top 32bits of the user
2140 	   data are set to zero. */
2141 	if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
2142 	    (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
2143 	    (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
2144 		return -EFAULT;
2145 
2146 	/* Make sure it's safe to cast pointers to vring types. */
2147 	BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
2148 	BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
2149 	if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
2150 	    (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
2151 	    (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
2152 		return -EINVAL;
2153 
2154 	/* We only verify access here if backend is configured.
2155 	 * If it is not, we don't as size might not have been setup.
2156 	 * We will verify when backend is configured. */
2157 	if (vq->private_data) {
2158 		if (!vq_access_ok(vq, vq->num,
2159 			(void __user *)(unsigned long)a.desc_user_addr,
2160 			(void __user *)(unsigned long)a.avail_user_addr,
2161 			(void __user *)(unsigned long)a.used_user_addr))
2162 			return -EINVAL;
2163 
2164 		/* Also validate log access for used ring if enabled. */
2165 		if (!vq_log_used_access_ok(vq, vq->log_base,
2166 				a.flags & (0x1 << VHOST_VRING_F_LOG),
2167 				a.log_guest_addr))
2168 			return -EINVAL;
2169 	}
2170 
2171 	vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
2172 	vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
2173 	vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
2174 	vq->log_addr = a.log_guest_addr;
2175 	vq->used = (void __user *)(unsigned long)a.used_user_addr;
2176 
2177 	return 0;
2178 }
2179 
2180 static long vhost_vring_set_num_addr(struct vhost_dev *d,
2181 				     struct vhost_virtqueue *vq,
2182 				     unsigned int ioctl,
2183 				     void __user *argp)
2184 {
2185 	long r;
2186 
2187 	mutex_lock(&vq->mutex);
2188 
2189 	switch (ioctl) {
2190 	case VHOST_SET_VRING_NUM:
2191 		r = vhost_vring_set_num(d, vq, argp);
2192 		break;
2193 	case VHOST_SET_VRING_ADDR:
2194 		r = vhost_vring_set_addr(d, vq, argp);
2195 		break;
2196 	default:
2197 		BUG();
2198 	}
2199 
2200 	/*
2201 	 * The metadata cache holds the IOTLB mapping that backed the previous
2202 	 * desc/avail/used addresses and vring size, both of which are being
2203 	 * replaced here.  iotlb_access_ok() takes a cache hit as proof that the
2204 	 * region was validated, so the stale entries have to go.
2205 	 */
2206 	__vhost_vq_meta_reset(vq);
2207 
2208 	mutex_unlock(&vq->mutex);
2209 
2210 	return r;
2211 }
2212 long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
2213 {
2214 	struct file *eventfp, *filep = NULL;
2215 	bool pollstart = false, pollstop = false;
2216 	struct eventfd_ctx *ctx = NULL;
2217 	struct vhost_virtqueue *vq;
2218 	struct vhost_vring_state s;
2219 	struct vhost_vring_file f;
2220 	u32 idx;
2221 	long r;
2222 
2223 	r = vhost_get_vq_from_user(d, argp, &vq, &idx);
2224 	if (r < 0)
2225 		return r;
2226 
2227 	if (ioctl == VHOST_SET_VRING_NUM ||
2228 	    ioctl == VHOST_SET_VRING_ADDR) {
2229 		return vhost_vring_set_num_addr(d, vq, ioctl, argp);
2230 	}
2231 
2232 	mutex_lock(&vq->mutex);
2233 
2234 	switch (ioctl) {
2235 	case VHOST_SET_VRING_BASE:
2236 		/* Moving base with an active backend?
2237 		 * You don't want to do that. */
2238 		if (vq->private_data) {
2239 			r = -EBUSY;
2240 			break;
2241 		}
2242 		if (copy_from_user(&s, argp, sizeof s)) {
2243 			r = -EFAULT;
2244 			break;
2245 		}
2246 		if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) {
2247 			vq->next_avail_head = vq->last_avail_idx =
2248 					      s.num & 0xffff;
2249 			vq->last_used_idx = (s.num >> 16) & 0xffff;
2250 		} else {
2251 			if (s.num > 0xffff) {
2252 				r = -EINVAL;
2253 				break;
2254 			}
2255 			vq->next_avail_head = vq->last_avail_idx = s.num;
2256 		}
2257 		/* Forget the cached index value. */
2258 		vq->avail_idx = vq->last_avail_idx;
2259 		break;
2260 	case VHOST_GET_VRING_BASE:
2261 		s.index = idx;
2262 		if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED))
2263 			s.num = (u32)vq->last_avail_idx | ((u32)vq->last_used_idx << 16);
2264 		else
2265 			s.num = vq->last_avail_idx;
2266 		if (copy_to_user(argp, &s, sizeof s))
2267 			r = -EFAULT;
2268 		break;
2269 	case VHOST_SET_VRING_KICK:
2270 		if (copy_from_user(&f, argp, sizeof f)) {
2271 			r = -EFAULT;
2272 			break;
2273 		}
2274 		eventfp = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_fget(f.fd);
2275 		if (IS_ERR(eventfp)) {
2276 			r = PTR_ERR(eventfp);
2277 			break;
2278 		}
2279 		if (eventfp != vq->kick) {
2280 			pollstop = (filep = vq->kick) != NULL;
2281 			pollstart = (vq->kick = eventfp) != NULL;
2282 		} else
2283 			filep = eventfp;
2284 		break;
2285 	case VHOST_SET_VRING_CALL:
2286 		if (copy_from_user(&f, argp, sizeof f)) {
2287 			r = -EFAULT;
2288 			break;
2289 		}
2290 		ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
2291 		if (IS_ERR(ctx)) {
2292 			r = PTR_ERR(ctx);
2293 			break;
2294 		}
2295 
2296 		swap(ctx, vq->call_ctx.ctx);
2297 		break;
2298 	case VHOST_SET_VRING_ERR:
2299 		if (copy_from_user(&f, argp, sizeof f)) {
2300 			r = -EFAULT;
2301 			break;
2302 		}
2303 		ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
2304 		if (IS_ERR(ctx)) {
2305 			r = PTR_ERR(ctx);
2306 			break;
2307 		}
2308 		swap(ctx, vq->error_ctx);
2309 		break;
2310 	case VHOST_SET_VRING_ENDIAN:
2311 		r = vhost_set_vring_endian(vq, argp);
2312 		break;
2313 	case VHOST_GET_VRING_ENDIAN:
2314 		r = vhost_get_vring_endian(vq, idx, argp);
2315 		break;
2316 	case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
2317 		if (copy_from_user(&s, argp, sizeof(s))) {
2318 			r = -EFAULT;
2319 			break;
2320 		}
2321 		vq->busyloop_timeout = s.num;
2322 		break;
2323 	case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
2324 		s.index = idx;
2325 		s.num = vq->busyloop_timeout;
2326 		if (copy_to_user(argp, &s, sizeof(s)))
2327 			r = -EFAULT;
2328 		break;
2329 	default:
2330 		r = -ENOIOCTLCMD;
2331 	}
2332 
2333 	if (pollstop && vq->handle_kick)
2334 		vhost_poll_stop(&vq->poll);
2335 
2336 	if (!IS_ERR_OR_NULL(ctx))
2337 		eventfd_ctx_put(ctx);
2338 	if (filep)
2339 		fput(filep);
2340 
2341 	if (pollstart && vq->handle_kick)
2342 		r = vhost_poll_start(&vq->poll, vq->kick);
2343 
2344 	mutex_unlock(&vq->mutex);
2345 
2346 	if (pollstop && vq->handle_kick)
2347 		vhost_dev_flush(vq->poll.dev);
2348 	return r;
2349 }
2350 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
2351 
2352 /* Caller must hold the device mutex. */
2353 void vhost_clear_device_iotlb(struct vhost_dev *d)
2354 {
2355 	struct vhost_iotlb *iotlb;
2356 	int i;
2357 
2358 	iotlb = d->iotlb;
2359 	if (!iotlb)
2360 		return;
2361 
2362 	vhost_dev_lock_vqs(d);
2363 
2364 	/*
2365 	 * vhost_dev_lock_vqs() takes all VQ mutexes in index order.  Drop the
2366 	 * device-wide view while they are held, then clear each per-VQ view
2367 	 * and its cached ring access before releasing the locks.  Workers
2368 	 * cannot observe a mixed address-space state during this handoff.
2369 	 */
2370 	d->iotlb = NULL;
2371 
2372 	for (i = 0; i < d->nvqs; ++i) {
2373 		struct vhost_virtqueue *vq = d->vqs[i];
2374 
2375 		vq->iotlb = NULL;
2376 		vhost_vq_invalidate_access(vq);
2377 	}
2378 
2379 	vhost_dev_unlock_vqs(d);
2380 	vhost_clear_msg(d);
2381 	vhost_iotlb_free(iotlb);
2382 	wake_up_interruptible_poll(&d->wait, EPOLLIN | EPOLLRDNORM);
2383 }
2384 EXPORT_SYMBOL_GPL(vhost_clear_device_iotlb);
2385 
2386 int vhost_init_device_iotlb(struct vhost_dev *d)
2387 {
2388 	struct vhost_iotlb *niotlb, *oiotlb;
2389 	int i;
2390 
2391 	if (max_iotlb_entries <= 0)
2392 		return -EINVAL;
2393 
2394 	niotlb = iotlb_alloc();
2395 	if (!niotlb)
2396 		return -ENOMEM;
2397 
2398 	oiotlb = d->iotlb;
2399 	d->iotlb = niotlb;
2400 
2401 	for (i = 0; i < d->nvqs; ++i) {
2402 		struct vhost_virtqueue *vq = d->vqs[i];
2403 
2404 		mutex_lock(&vq->mutex);
2405 		vq->iotlb = niotlb;
2406 		if (oiotlb)
2407 			__vhost_vq_meta_reset(vq);
2408 		else
2409 			vhost_vq_invalidate_access(vq);
2410 		mutex_unlock(&vq->mutex);
2411 	}
2412 
2413 	vhost_iotlb_free(oiotlb);
2414 
2415 	return 0;
2416 }
2417 EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
2418 
2419 /* Caller must have device mutex */
2420 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
2421 {
2422 	struct eventfd_ctx *ctx;
2423 	u64 p;
2424 	long r;
2425 	int i, fd;
2426 
2427 	/* If you are not the owner, you can become one */
2428 	if (ioctl == VHOST_SET_OWNER) {
2429 		r = vhost_dev_set_owner(d);
2430 		goto done;
2431 	}
2432 
2433 #ifdef CONFIG_VHOST_ENABLE_FORK_OWNER_CONTROL
2434 	if (ioctl == VHOST_SET_FORK_FROM_OWNER) {
2435 		/* Only allow modification before owner is set */
2436 		if (vhost_dev_has_owner(d)) {
2437 			r = -EBUSY;
2438 			goto done;
2439 		}
2440 		u8 fork_owner_val;
2441 
2442 		if (get_user(fork_owner_val, (u8 __user *)argp)) {
2443 			r = -EFAULT;
2444 			goto done;
2445 		}
2446 		if (fork_owner_val != VHOST_FORK_OWNER_TASK &&
2447 		    fork_owner_val != VHOST_FORK_OWNER_KTHREAD) {
2448 			r = -EINVAL;
2449 			goto done;
2450 		}
2451 		d->fork_owner = !!fork_owner_val;
2452 		r = 0;
2453 		goto done;
2454 	}
2455 	if (ioctl == VHOST_GET_FORK_FROM_OWNER) {
2456 		u8 fork_owner_val = d->fork_owner;
2457 
2458 		if (fork_owner_val != VHOST_FORK_OWNER_TASK &&
2459 		    fork_owner_val != VHOST_FORK_OWNER_KTHREAD) {
2460 			r = -EINVAL;
2461 			goto done;
2462 		}
2463 		if (put_user(fork_owner_val, (u8 __user *)argp)) {
2464 			r = -EFAULT;
2465 			goto done;
2466 		}
2467 		r = 0;
2468 		goto done;
2469 	}
2470 #endif
2471 
2472 	/* You must be the owner to do anything else */
2473 	r = vhost_dev_check_owner(d);
2474 	if (r)
2475 		goto done;
2476 
2477 	switch (ioctl) {
2478 	case VHOST_SET_MEM_TABLE:
2479 		r = vhost_set_memory(d, argp);
2480 		break;
2481 	case VHOST_SET_LOG_BASE:
2482 		if (copy_from_user(&p, argp, sizeof p)) {
2483 			r = -EFAULT;
2484 			break;
2485 		}
2486 		if ((u64)(unsigned long)p != p) {
2487 			r = -EFAULT;
2488 			break;
2489 		}
2490 		for (i = 0; i < d->nvqs; ++i) {
2491 			struct vhost_virtqueue *vq;
2492 			void __user *base = (void __user *)(unsigned long)p;
2493 			vq = d->vqs[i];
2494 			mutex_lock(&vq->mutex);
2495 			/* If ring is inactive, will check when it's enabled. */
2496 			if (vq->private_data && !vq_log_access_ok(vq, base))
2497 				r = -EFAULT;
2498 			else
2499 				vq->log_base = base;
2500 			mutex_unlock(&vq->mutex);
2501 		}
2502 		break;
2503 	case VHOST_SET_LOG_FD:
2504 		r = get_user(fd, (int __user *)argp);
2505 		if (r < 0)
2506 			break;
2507 		ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd);
2508 		if (IS_ERR(ctx)) {
2509 			r = PTR_ERR(ctx);
2510 			break;
2511 		}
2512 		swap(ctx, d->log_ctx);
2513 		for (i = 0; i < d->nvqs; ++i) {
2514 			mutex_lock(&d->vqs[i]->mutex);
2515 			d->vqs[i]->log_ctx = d->log_ctx;
2516 			mutex_unlock(&d->vqs[i]->mutex);
2517 		}
2518 		if (ctx)
2519 			eventfd_ctx_put(ctx);
2520 		break;
2521 	default:
2522 		r = -ENOIOCTLCMD;
2523 		break;
2524 	}
2525 done:
2526 	return r;
2527 }
2528 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
2529 
2530 /* TODO: This is really inefficient.  We need something like get_user()
2531  * (instruction directly accesses the data, with an exception table entry
2532  * returning -EFAULT). See Documentation/arch/x86/exception-tables.rst.
2533  */
2534 static int set_bit_to_user(int nr, void __user *addr)
2535 {
2536 	unsigned long log = (unsigned long)addr;
2537 	struct page *page;
2538 	void *base;
2539 	int bit = nr + (log % PAGE_SIZE) * 8;
2540 	int r;
2541 
2542 	r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page);
2543 	if (r < 0)
2544 		return r;
2545 	BUG_ON(r != 1);
2546 	base = kmap_atomic(page);
2547 	set_bit(bit, base);
2548 	kunmap_atomic(base);
2549 	unpin_user_pages_dirty_lock(&page, 1, true);
2550 	return 0;
2551 }
2552 
2553 static int log_write(void __user *log_base,
2554 		     u64 write_address, u64 write_length)
2555 {
2556 	u64 write_page = write_address / VHOST_PAGE_SIZE;
2557 	int r;
2558 
2559 	if (!write_length)
2560 		return 0;
2561 	write_length += write_address % VHOST_PAGE_SIZE;
2562 	for (;;) {
2563 		u64 base = (u64)(unsigned long)log_base;
2564 		u64 log = base + write_page / 8;
2565 		int bit = write_page % 8;
2566 		if ((u64)(unsigned long)log != log)
2567 			return -EFAULT;
2568 		r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
2569 		if (r < 0)
2570 			return r;
2571 		if (write_length <= VHOST_PAGE_SIZE)
2572 			break;
2573 		write_length -= VHOST_PAGE_SIZE;
2574 		write_page += 1;
2575 	}
2576 	return r;
2577 }
2578 
2579 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
2580 {
2581 	struct vhost_iotlb *umem = vq->umem;
2582 	struct vhost_iotlb_map *u;
2583 	u64 start, end, l, min;
2584 	int r;
2585 	bool hit = false;
2586 
2587 	while (len) {
2588 		min = len;
2589 		/* More than one GPAs can be mapped into a single HVA. So
2590 		 * iterate all possible umems here to be safe.
2591 		 */
2592 		list_for_each_entry(u, &umem->list, link) {
2593 			if (u->addr > hva - 1 + len ||
2594 			    u->addr - 1 + u->size < hva)
2595 				continue;
2596 			start = max(u->addr, hva);
2597 			end = min(u->addr - 1 + u->size, hva - 1 + len);
2598 			l = end - start + 1;
2599 			r = log_write(vq->log_base,
2600 				      u->start + start - u->addr,
2601 				      l);
2602 			if (r < 0)
2603 				return r;
2604 			hit = true;
2605 			min = min(l, min);
2606 		}
2607 
2608 		if (!hit)
2609 			return -EFAULT;
2610 
2611 		len -= min;
2612 		hva += min;
2613 	}
2614 
2615 	return 0;
2616 }
2617 
2618 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
2619 {
2620 	struct iovec *iov = vq->log_iov;
2621 	int i, ret;
2622 
2623 	if (!vq->iotlb)
2624 		return log_write(vq->log_base, vq->log_addr + used_offset, len);
2625 
2626 	ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
2627 			     len, iov, 64, VHOST_ACCESS_WO);
2628 	if (ret < 0)
2629 		return ret;
2630 
2631 	for (i = 0; i < ret; i++) {
2632 		ret = log_write_hva(vq,	(uintptr_t)iov[i].iov_base,
2633 				    iov[i].iov_len);
2634 		if (ret)
2635 			return ret;
2636 	}
2637 
2638 	return 0;
2639 }
2640 
2641 /*
2642  * vhost_log_write() - Log in dirty page bitmap
2643  * @vq:      vhost virtqueue.
2644  * @log:     Array of dirty memory in GPA.
2645  * @log_num: Size of vhost_log arrary.
2646  * @len:     The total length of memory buffer to log in the dirty bitmap.
2647  *	     Some drivers may only partially use pages shared via the last
2648  *	     vring descriptor (i.e. vhost-net RX buffer).
2649  *	     Use (len == U64_MAX) to indicate the driver would log all
2650  *           pages of vring descriptors.
2651  * @iov:     Array of dirty memory in HVA.
2652  * @count:   Size of iovec array.
2653  */
2654 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
2655 		    unsigned int log_num, u64 len, struct iovec *iov, int count)
2656 {
2657 	int i, r;
2658 
2659 	/* Make sure data written is seen before log. */
2660 	smp_wmb();
2661 
2662 	if (vq->iotlb) {
2663 		for (i = 0; i < count; i++) {
2664 			r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
2665 					  iov[i].iov_len);
2666 			if (r < 0)
2667 				return r;
2668 		}
2669 		return 0;
2670 	}
2671 
2672 	for (i = 0; i < log_num; ++i) {
2673 		u64 l = min(log[i].len, len);
2674 		r = log_write(vq->log_base, log[i].addr, l);
2675 		if (r < 0)
2676 			return r;
2677 
2678 		if (len != U64_MAX)
2679 			len -= l;
2680 	}
2681 
2682 	if (vq->log_ctx)
2683 		eventfd_signal(vq->log_ctx);
2684 
2685 	return 0;
2686 }
2687 EXPORT_SYMBOL_GPL(vhost_log_write);
2688 
2689 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
2690 {
2691 	void __user *used;
2692 	if (vhost_put_used_flags(vq))
2693 		return -EFAULT;
2694 	if (unlikely(vq->log_used)) {
2695 		/* Make sure the flag is seen before log. */
2696 		smp_wmb();
2697 		/* Log used flag write. */
2698 		used = &vq->used->flags;
2699 		log_used(vq, (used - (void __user *)vq->used),
2700 			 sizeof vq->used->flags);
2701 		if (vq->log_ctx)
2702 			eventfd_signal(vq->log_ctx);
2703 	}
2704 	return 0;
2705 }
2706 
2707 static int vhost_update_avail_event(struct vhost_virtqueue *vq)
2708 {
2709 	if (vhost_put_avail_event(vq))
2710 		return -EFAULT;
2711 	if (unlikely(vq->log_used)) {
2712 		void __user *used;
2713 		/* Make sure the event is seen before log. */
2714 		smp_wmb();
2715 		/* Log avail event write */
2716 		used = vhost_avail_event(vq);
2717 		log_used(vq, (used - (void __user *)vq->used),
2718 			 sizeof *vhost_avail_event(vq));
2719 		if (vq->log_ctx)
2720 			eventfd_signal(vq->log_ctx);
2721 	}
2722 	return 0;
2723 }
2724 
2725 int vhost_vq_init_access(struct vhost_virtqueue *vq)
2726 {
2727 	__virtio16 last_used_idx;
2728 	int r;
2729 	bool is_le = vq->is_le;
2730 
2731 	if (!vq->private_data)
2732 		return 0;
2733 
2734 	vhost_init_is_le(vq);
2735 
2736 	r = vhost_update_used_flags(vq);
2737 	if (r)
2738 		goto err;
2739 	vq->signalled_used_valid = false;
2740 	if (!vq->iotlb &&
2741 	    !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
2742 		r = -EFAULT;
2743 		goto err;
2744 	}
2745 	r = vhost_get_used_idx(vq, &last_used_idx);
2746 	if (r) {
2747 		vq_err(vq, "Can't access used idx at %p\n",
2748 		       &vq->used->idx);
2749 		goto err;
2750 	}
2751 	vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2752 	return 0;
2753 
2754 err:
2755 	vq->is_le = is_le;
2756 	return r;
2757 }
2758 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2759 
2760 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2761 			  struct iovec iov[], int iov_size, int access)
2762 {
2763 	const struct vhost_iotlb_map *map;
2764 	struct vhost_dev *dev = vq->dev;
2765 	struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
2766 	struct iovec *_iov;
2767 	u64 s = 0, last = addr + len - 1;
2768 	int ret = 0;
2769 
2770 	while ((u64)len > s) {
2771 		u64 size;
2772 		if (unlikely(ret >= iov_size)) {
2773 			ret = -ENOBUFS;
2774 			break;
2775 		}
2776 
2777 		map = vhost_iotlb_itree_first(umem, addr, last);
2778 		if (map == NULL || map->start > addr) {
2779 			if (umem != dev->iotlb) {
2780 				ret = -EFAULT;
2781 				break;
2782 			}
2783 			ret = -EAGAIN;
2784 			break;
2785 		} else if (!(map->perm & access)) {
2786 			ret = -EPERM;
2787 			break;
2788 		}
2789 
2790 		_iov = iov + ret;
2791 		size = map->size - addr + map->start;
2792 		_iov->iov_len = min((u64)len - s, size);
2793 		_iov->iov_base = (void __user *)(unsigned long)
2794 				 (map->addr + addr - map->start);
2795 		s += size;
2796 		addr += size;
2797 		++ret;
2798 	}
2799 
2800 	if (ret == -EAGAIN)
2801 		vhost_iotlb_miss(vq, addr, access);
2802 	return ret;
2803 }
2804 
2805 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
2806  * function returns the next descriptor in the chain,
2807  * or -1U if we're at the end. */
2808 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2809 {
2810 	unsigned int next;
2811 
2812 	/* If this descriptor says it doesn't chain, we're done. */
2813 	if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2814 		return -1U;
2815 
2816 	/* Check they're not leading us off end of descriptors. */
2817 	next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2818 	return next;
2819 }
2820 
2821 static int get_indirect(struct vhost_virtqueue *vq,
2822 			struct iovec iov[], unsigned int iov_size,
2823 			unsigned int *out_num, unsigned int *in_num,
2824 			struct vhost_log *log, unsigned int *log_num,
2825 			struct vring_desc *indirect)
2826 {
2827 	struct vring_desc desc;
2828 	unsigned int i = 0, count, found = 0;
2829 	u32 len = vhost32_to_cpu(vq, indirect->len);
2830 	struct iov_iter from;
2831 	int ret, access;
2832 
2833 	/* Sanity check */
2834 	if (unlikely(len % sizeof desc)) {
2835 		vq_err(vq, "Invalid length in indirect descriptor: "
2836 		       "len 0x%llx not multiple of 0x%zx\n",
2837 		       (unsigned long long)len,
2838 		       sizeof desc);
2839 		return -EINVAL;
2840 	}
2841 
2842 	ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2843 			     UIO_MAXIOV, VHOST_ACCESS_RO);
2844 	if (unlikely(ret < 0)) {
2845 		if (ret != -EAGAIN)
2846 			vq_err(vq, "Translation failure %d in indirect.\n", ret);
2847 		return ret;
2848 	}
2849 	iov_iter_init(&from, ITER_SOURCE, vq->indirect, ret, len);
2850 	count = len / sizeof desc;
2851 	/* Buffers are chained via a 16 bit next field, so
2852 	 * we can have at most 2^16 of these. */
2853 	if (unlikely(count > USHRT_MAX + 1)) {
2854 		vq_err(vq, "Indirect buffer length too big: %d\n",
2855 		       indirect->len);
2856 		return -E2BIG;
2857 	}
2858 
2859 	do {
2860 		unsigned iov_count = *in_num + *out_num;
2861 		if (unlikely(++found > count)) {
2862 			vq_err(vq, "Loop detected: last one at %u "
2863 			       "indirect size %u\n",
2864 			       i, count);
2865 			return -EINVAL;
2866 		}
2867 		if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2868 			vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2869 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2870 			return -EINVAL;
2871 		}
2872 		if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2873 			vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2874 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2875 			return -EINVAL;
2876 		}
2877 
2878 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2879 			access = VHOST_ACCESS_WO;
2880 		else
2881 			access = VHOST_ACCESS_RO;
2882 
2883 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2884 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
2885 				     iov_size - iov_count, access);
2886 		if (unlikely(ret < 0)) {
2887 			if (ret != -EAGAIN)
2888 				vq_err(vq, "Translation failure %d indirect idx %d\n",
2889 					ret, i);
2890 			return ret;
2891 		}
2892 		/* If this is an input descriptor, increment that count. */
2893 		if (access == VHOST_ACCESS_WO) {
2894 			*in_num += ret;
2895 			if (unlikely(log && ret)) {
2896 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2897 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2898 				++*log_num;
2899 			}
2900 		} else {
2901 			/* If it's an output descriptor, they're all supposed
2902 			 * to come before any input descriptors. */
2903 			if (unlikely(*in_num)) {
2904 				vq_err(vq, "Indirect descriptor "
2905 				       "has out after in: idx %d\n", i);
2906 				return -EINVAL;
2907 			}
2908 			*out_num += ret;
2909 		}
2910 	} while ((i = next_desc(vq, &desc)) != -1);
2911 	return 0;
2912 }
2913 
2914 /**
2915  * vhost_get_vq_desc_n - Fetch the next available descriptor chain and build iovecs
2916  * @vq: target virtqueue
2917  * @iov: array that receives the scatter/gather segments
2918  * @iov_size: capacity of @iov in elements
2919  * @out_num: the number of output segments
2920  * @in_num: the number of input segments
2921  * @log: optional array to record addr/len for each writable segment; NULL if unused
2922  * @log_num: optional output; number of entries written to @log when provided
2923  * @ndesc: optional output; number of descriptors consumed from the available ring
2924  *         (useful for rollback via vhost_discard_vq_desc)
2925  *
2926  * Extracts one available descriptor chain from @vq and translates guest addresses
2927  * into host iovecs.
2928  *
2929  * On success, advances @vq->last_avail_idx by 1 and @vq->next_avail_head by the
2930  * number of descriptors consumed (also stored via @ndesc when non-NULL).
2931  *
2932  * Return:
2933  * - head index in [0, @vq->num) on success;
2934  * - @vq->num if no descriptor is currently available;
2935  * - negative errno on failure
2936  */
2937 int vhost_get_vq_desc_n(struct vhost_virtqueue *vq,
2938 			struct iovec iov[], unsigned int iov_size,
2939 			unsigned int *out_num, unsigned int *in_num,
2940 			struct vhost_log *log, unsigned int *log_num,
2941 			unsigned int *ndesc)
2942 {
2943 	bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER);
2944 	struct vring_desc desc;
2945 	unsigned int i, head, found = 0;
2946 	u16 last_avail_idx = vq->last_avail_idx;
2947 	__virtio16 ring_head;
2948 	int ret, access, c = 0;
2949 
2950 	if (vq->avail_idx == vq->last_avail_idx) {
2951 		ret = vhost_get_avail_idx(vq);
2952 		if (unlikely(ret < 0))
2953 			return ret;
2954 
2955 		if (!ret)
2956 			return vq->num;
2957 	}
2958 
2959 	if (in_order)
2960 		head = vq->next_avail_head & (vq->num - 1);
2961 	else {
2962 		/* Grab the next descriptor number they're
2963 		 * advertising, and increment the index we've seen. */
2964 		if (unlikely(vhost_get_avail_head(vq, &ring_head,
2965 						  last_avail_idx))) {
2966 			vq_err(vq, "Failed to read head: idx %d address %p\n",
2967 				last_avail_idx,
2968 				&vq->avail->ring[last_avail_idx % vq->num]);
2969 			return -EFAULT;
2970 		}
2971 		head = vhost16_to_cpu(vq, ring_head);
2972 	}
2973 
2974 	/* If their number is silly, that's an error. */
2975 	if (unlikely(head >= vq->num)) {
2976 		vq_err(vq, "Guest says index %u > %u is available",
2977 		       head, vq->num);
2978 		return -EINVAL;
2979 	}
2980 
2981 	/* When we start there are none of either input nor output. */
2982 	*out_num = *in_num = 0;
2983 	if (unlikely(log))
2984 		*log_num = 0;
2985 
2986 	i = head;
2987 	do {
2988 		unsigned iov_count = *in_num + *out_num;
2989 		if (unlikely(i >= vq->num)) {
2990 			vq_err(vq, "Desc index is %u > %u, head = %u",
2991 			       i, vq->num, head);
2992 			return -EINVAL;
2993 		}
2994 		if (unlikely(++found > vq->num)) {
2995 			vq_err(vq, "Loop detected: last one at %u "
2996 			       "vq size %u head %u\n",
2997 			       i, vq->num, head);
2998 			return -EINVAL;
2999 		}
3000 		ret = vhost_get_desc(vq, &desc, i);
3001 		if (unlikely(ret)) {
3002 			vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
3003 			       i, vq->desc + i);
3004 			return -EFAULT;
3005 		}
3006 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
3007 			ret = get_indirect(vq, iov, iov_size,
3008 					   out_num, in_num,
3009 					   log, log_num, &desc);
3010 			if (unlikely(ret < 0)) {
3011 				if (ret != -EAGAIN)
3012 					vq_err(vq, "Failure detected "
3013 						"in indirect descriptor at idx %d\n", i);
3014 				return ret;
3015 			}
3016 			++c;
3017 			continue;
3018 		}
3019 
3020 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
3021 			access = VHOST_ACCESS_WO;
3022 		else
3023 			access = VHOST_ACCESS_RO;
3024 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
3025 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
3026 				     iov_size - iov_count, access);
3027 		if (unlikely(ret < 0)) {
3028 			if (ret != -EAGAIN)
3029 				vq_err(vq, "Translation failure %d descriptor idx %d\n",
3030 					ret, i);
3031 			return ret;
3032 		}
3033 		if (access == VHOST_ACCESS_WO) {
3034 			/* If this is an input descriptor,
3035 			 * increment that count. */
3036 			*in_num += ret;
3037 			if (unlikely(log && ret)) {
3038 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
3039 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
3040 				++*log_num;
3041 			}
3042 		} else {
3043 			/* If it's an output descriptor, they're all supposed
3044 			 * to come before any input descriptors. */
3045 			if (unlikely(*in_num)) {
3046 				vq_err(vq, "Descriptor has out after in: "
3047 				       "idx %d\n", i);
3048 				return -EINVAL;
3049 			}
3050 			*out_num += ret;
3051 		}
3052 		++c;
3053 	} while ((i = next_desc(vq, &desc)) != -1);
3054 
3055 	/* On success, increment avail index. */
3056 	vq->last_avail_idx++;
3057 	vq->next_avail_head += c;
3058 
3059 	if (ndesc)
3060 		*ndesc = c;
3061 
3062 	/* Assume notifications from guest are disabled at this point,
3063 	 * if they aren't we would need to update avail_event index. */
3064 	BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
3065 	return head;
3066 }
3067 EXPORT_SYMBOL_GPL(vhost_get_vq_desc_n);
3068 
3069 /* This looks in the virtqueue and for the first available buffer, and converts
3070  * it to an iovec for convenient access.  Since descriptors consist of some
3071  * number of output then some number of input descriptors, it's actually two
3072  * iovecs, but we pack them into one and note how many of each there were.
3073  *
3074  * This function returns the descriptor number found, or vq->num (which is
3075  * never a valid descriptor number) if none was found.  A negative code is
3076  * returned on error.
3077  */
3078 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
3079 		      struct iovec iov[], unsigned int iov_size,
3080 		      unsigned int *out_num, unsigned int *in_num,
3081 		      struct vhost_log *log, unsigned int *log_num)
3082 {
3083 	return vhost_get_vq_desc_n(vq, iov, iov_size, out_num, in_num,
3084 				   log, log_num, NULL);
3085 }
3086 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
3087 
3088 /**
3089  * vhost_discard_vq_desc - Reverse the effect of vhost_get_vq_desc_n()
3090  * @vq: target virtqueue
3091  * @nbufs: number of buffers to roll back
3092  * @ndesc: number of descriptors to roll back
3093  *
3094  * Rewinds the internal consumer cursors after a failed attempt to use buffers
3095  * returned by vhost_get_vq_desc_n().
3096  */
3097 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int nbufs,
3098 			   unsigned int ndesc)
3099 {
3100 	vq->next_avail_head -= ndesc;
3101 	vq->last_avail_idx -= nbufs;
3102 }
3103 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
3104 
3105 /* After we've used one of their buffers, we tell them about it.  We'll then
3106  * want to notify the guest, using eventfd. */
3107 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
3108 {
3109 	struct vring_used_elem heads = {
3110 		cpu_to_vhost32(vq, head),
3111 		cpu_to_vhost32(vq, len)
3112 	};
3113 	u16 nheads = 1;
3114 
3115 	return vhost_add_used_n(vq, &heads, &nheads, 1);
3116 }
3117 EXPORT_SYMBOL_GPL(vhost_add_used);
3118 
3119 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
3120 			    struct vring_used_elem *heads,
3121 			    unsigned count)
3122 {
3123 	vring_used_elem_t __user *used;
3124 	u16 old, new;
3125 	int start;
3126 
3127 	start = vq->last_used_idx & (vq->num - 1);
3128 	used = vq->used->ring + start;
3129 	if (vhost_put_used(vq, heads, start, count)) {
3130 		vq_err(vq, "Failed to write used");
3131 		return -EFAULT;
3132 	}
3133 	if (unlikely(vq->log_used)) {
3134 		/* Make sure data is seen before log. */
3135 		smp_wmb();
3136 		/* Log used ring entry write. */
3137 		log_used(vq, ((void __user *)used - (void __user *)vq->used),
3138 			 count * sizeof *used);
3139 	}
3140 	old = vq->last_used_idx;
3141 	new = (vq->last_used_idx += count);
3142 	/* If the driver never bothers to signal in a very long while,
3143 	 * used index might wrap around. If that happens, invalidate
3144 	 * signalled_used index we stored. TODO: make sure driver
3145 	 * signals at least once in 2^16 and remove this. */
3146 	if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
3147 		vq->signalled_used_valid = false;
3148 	return 0;
3149 }
3150 
3151 static int vhost_add_used_n_ooo(struct vhost_virtqueue *vq,
3152 				struct vring_used_elem *heads,
3153 				unsigned count)
3154 {
3155 	int start, n, r;
3156 
3157 	start = vq->last_used_idx & (vq->num - 1);
3158 	n = vq->num - start;
3159 	if (n < count) {
3160 		r = __vhost_add_used_n(vq, heads, n);
3161 		if (r < 0)
3162 			return r;
3163 		heads += n;
3164 		count -= n;
3165 	}
3166 	return __vhost_add_used_n(vq, heads, count);
3167 }
3168 
3169 static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,
3170 				     struct vring_used_elem *heads,
3171 				     const u16 *nheads,
3172 				     unsigned count)
3173 {
3174 	vring_used_elem_t __user *used;
3175 	u16 old, new = vq->last_used_idx;
3176 	int start, i;
3177 
3178 	if (!nheads)
3179 		return -EINVAL;
3180 
3181 	start = vq->last_used_idx & (vq->num - 1);
3182 	used = vq->used->ring + start;
3183 
3184 	for (i = 0; i < count; i++) {
3185 		if (vhost_put_used(vq, &heads[i], start, 1)) {
3186 			vq_err(vq, "Failed to write used");
3187 			return -EFAULT;
3188 		}
3189 		start += nheads[i];
3190 		new += nheads[i];
3191 		if (start >= vq->num)
3192 			start -= vq->num;
3193 	}
3194 
3195 	if (unlikely(vq->log_used)) {
3196 		/* Make sure data is seen before log. */
3197 		smp_wmb();
3198 		/* Log used ring entry write. */
3199 		log_used(vq, ((void __user *)used - (void __user *)vq->used),
3200 			 (vq->num - start) * sizeof *used);
3201 		if (start + count > vq->num)
3202 			log_used(vq, 0,
3203 				 (start + count - vq->num) * sizeof *used);
3204 	}
3205 
3206 	old = vq->last_used_idx;
3207 	vq->last_used_idx = new;
3208 	/* If the driver never bothers to signal in a very long while,
3209 	 * used index might wrap around. If that happens, invalidate
3210 	 * signalled_used index we stored. TODO: make sure driver
3211 	 * signals at least once in 2^16 and remove this. */
3212 	if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
3213 		vq->signalled_used_valid = false;
3214 	return 0;
3215 }
3216 
3217 /* After we've used one of their buffers, we tell them about it.  We'll then
3218  * want to notify the guest, using eventfd. */
3219 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
3220 		     u16 *nheads, unsigned count)
3221 {
3222 	bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER);
3223 	int r;
3224 
3225 	if (!in_order || !nheads)
3226 		r = vhost_add_used_n_ooo(vq, heads, count);
3227 	else
3228 		r = vhost_add_used_n_in_order(vq, heads, nheads, count);
3229 
3230 	if (r < 0)
3231 		return r;
3232 
3233 	/* Make sure buffer is written before we update index. */
3234 	smp_wmb();
3235 	if (vhost_put_used_idx(vq)) {
3236 		vq_err(vq, "Failed to increment used idx");
3237 		return -EFAULT;
3238 	}
3239 	if (unlikely(vq->log_used)) {
3240 		/* Make sure used idx is seen before log. */
3241 		smp_wmb();
3242 		/* Log used index update. */
3243 		log_used(vq, offsetof(struct vring_used, idx),
3244 			 sizeof vq->used->idx);
3245 		if (vq->log_ctx)
3246 			eventfd_signal(vq->log_ctx);
3247 	}
3248 	return r;
3249 }
3250 EXPORT_SYMBOL_GPL(vhost_add_used_n);
3251 
3252 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3253 {
3254 	__u16 old, new;
3255 	__virtio16 event;
3256 	bool v;
3257 	/* Flush out used index updates. This is paired
3258 	 * with the barrier that the Guest executes when enabling
3259 	 * interrupts. */
3260 	smp_mb();
3261 
3262 	if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
3263 	    unlikely(vq->avail_idx == vq->last_avail_idx))
3264 		return true;
3265 
3266 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3267 		__virtio16 flags;
3268 		if (vhost_get_avail_flags(vq, &flags)) {
3269 			vq_err(vq, "Failed to get flags");
3270 			return true;
3271 		}
3272 		return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
3273 	}
3274 	old = vq->signalled_used;
3275 	v = vq->signalled_used_valid;
3276 	new = vq->signalled_used = vq->last_used_idx;
3277 	vq->signalled_used_valid = true;
3278 
3279 	if (unlikely(!v))
3280 		return true;
3281 
3282 	if (vhost_get_used_event(vq, &event)) {
3283 		vq_err(vq, "Failed to get used event idx");
3284 		return true;
3285 	}
3286 	return vring_need_event(vhost16_to_cpu(vq, event), new, old);
3287 }
3288 
3289 /* This actually signals the guest, using eventfd. */
3290 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3291 {
3292 	/* Signal the Guest tell them we used something up. */
3293 	if (vq->call_ctx.ctx && vhost_notify(dev, vq))
3294 		eventfd_signal(vq->call_ctx.ctx);
3295 }
3296 EXPORT_SYMBOL_GPL(vhost_signal);
3297 
3298 /* And here's the combo meal deal.  Supersize me! */
3299 void vhost_add_used_and_signal(struct vhost_dev *dev,
3300 			       struct vhost_virtqueue *vq,
3301 			       unsigned int head, int len)
3302 {
3303 	vhost_add_used(vq, head, len);
3304 	vhost_signal(dev, vq);
3305 }
3306 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
3307 
3308 /* multi-buffer version of vhost_add_used_and_signal */
3309 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
3310 				 struct vhost_virtqueue *vq,
3311 				 struct vring_used_elem *heads,
3312 				 u16 *nheads,
3313 				 unsigned count)
3314 {
3315 	vhost_add_used_n(vq, heads, nheads, count);
3316 	vhost_signal(dev, vq);
3317 }
3318 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
3319 
3320 /* return true if we're sure that available ring is empty */
3321 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3322 {
3323 	int r;
3324 
3325 	if (vq->avail_idx != vq->last_avail_idx)
3326 		return false;
3327 
3328 	r = vhost_get_avail_idx(vq);
3329 
3330 	/* Note: we treat error as non-empty here */
3331 	return r == 0;
3332 }
3333 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
3334 
3335 /* OK, now we need to know about added descriptors. */
3336 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3337 {
3338 	int r;
3339 
3340 	if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
3341 		return false;
3342 	vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
3343 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3344 		r = vhost_update_used_flags(vq);
3345 		if (r) {
3346 			vq_err(vq, "Failed to enable notification at %p: %d\n",
3347 			       &vq->used->flags, r);
3348 			return false;
3349 		}
3350 	} else {
3351 		r = vhost_update_avail_event(vq);
3352 		if (r) {
3353 			vq_err(vq, "Failed to update avail event index at %p: %d\n",
3354 			       vhost_avail_event(vq), r);
3355 			return false;
3356 		}
3357 	}
3358 	/* They could have slipped one in as we were doing that: make
3359 	 * sure it's written, then check again. */
3360 	smp_mb();
3361 
3362 	r = vhost_get_avail_idx(vq);
3363 	/* Note: we treat error as empty here */
3364 	if (unlikely(r < 0))
3365 		return false;
3366 
3367 	return r;
3368 }
3369 EXPORT_SYMBOL_GPL(vhost_enable_notify);
3370 
3371 /* We don't need to be notified again. */
3372 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3373 {
3374 	int r;
3375 
3376 	if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
3377 		return;
3378 	vq->used_flags |= VRING_USED_F_NO_NOTIFY;
3379 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3380 		r = vhost_update_used_flags(vq);
3381 		if (r)
3382 			vq_err(vq, "Failed to disable notification at %p: %d\n",
3383 			       &vq->used->flags, r);
3384 	}
3385 }
3386 EXPORT_SYMBOL_GPL(vhost_disable_notify);
3387 
3388 /* Create a new message. */
3389 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
3390 {
3391 	/* Make sure all padding within the structure is initialized. */
3392 	struct vhost_msg_node *node = kzalloc_obj(*node);
3393 	if (!node)
3394 		return NULL;
3395 
3396 	node->vq = vq;
3397 	node->msg.type = type;
3398 	return node;
3399 }
3400 EXPORT_SYMBOL_GPL(vhost_new_msg);
3401 
3402 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
3403 		       struct vhost_msg_node *node)
3404 {
3405 	spin_lock(&dev->iotlb_lock);
3406 	list_add_tail(&node->node, head);
3407 	spin_unlock(&dev->iotlb_lock);
3408 
3409 	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
3410 }
3411 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
3412 
3413 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
3414 					 struct list_head *head)
3415 {
3416 	struct vhost_msg_node *node = NULL;
3417 
3418 	spin_lock(&dev->iotlb_lock);
3419 	if (!list_empty(head)) {
3420 		node = list_first_entry(head, struct vhost_msg_node,
3421 					node);
3422 		list_del(&node->node);
3423 	}
3424 	spin_unlock(&dev->iotlb_lock);
3425 
3426 	return node;
3427 }
3428 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
3429 
3430 void vhost_set_backend_features(struct vhost_dev *dev, u64 features)
3431 {
3432 	struct vhost_virtqueue *vq;
3433 	int i;
3434 
3435 	mutex_lock(&dev->mutex);
3436 	for (i = 0; i < dev->nvqs; ++i) {
3437 		vq = dev->vqs[i];
3438 		mutex_lock(&vq->mutex);
3439 		vq->acked_backend_features = features;
3440 		mutex_unlock(&vq->mutex);
3441 	}
3442 	mutex_unlock(&dev->mutex);
3443 }
3444 EXPORT_SYMBOL_GPL(vhost_set_backend_features);
3445 
3446 MODULE_VERSION("0.0.1");
3447 MODULE_LICENSE("GPL v2");
3448 MODULE_AUTHOR("Michael S. Tsirkin");
3449 MODULE_DESCRIPTION("Host kernel accelerator for virtio");
3450