xref: /linux/drivers/vhost/vhost.c (revision d06ce6f1eb5eeffd4ebcfde345dc34a98131d106)
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_objs(*vq->nheads, dev->iov_limit);
533 		if (!vq->indirect || !vq->log || !vq->heads || !vq->nheads)
534 			goto err_nomem;
535 	}
536 	return 0;
537 
538 err_nomem:
539 	for (; i >= 0; --i)
540 		vhost_vq_free_iovecs(dev->vqs[i]);
541 	return -ENOMEM;
542 }
543 
544 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
545 {
546 	int i;
547 
548 	for (i = 0; i < dev->nvqs; ++i)
549 		vhost_vq_free_iovecs(dev->vqs[i]);
550 }
551 
552 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
553 			  int pkts, int total_len)
554 {
555 	struct vhost_dev *dev = vq->dev;
556 
557 	if ((dev->byte_weight && total_len >= dev->byte_weight) ||
558 	    pkts >= dev->weight) {
559 		vhost_poll_queue(&vq->poll);
560 		return true;
561 	}
562 
563 	return false;
564 }
565 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
566 
567 static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
568 				   unsigned int num)
569 {
570 	size_t event __maybe_unused =
571 	       vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
572 
573 	return size_add(struct_size(vq->avail, ring, num), event);
574 }
575 
576 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
577 				  unsigned int num)
578 {
579 	size_t event __maybe_unused =
580 	       vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
581 
582 	return size_add(struct_size(vq->used, ring, num), event);
583 }
584 
585 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
586 				  unsigned int num)
587 {
588 	return sizeof(*vq->desc) * num;
589 }
590 
591 void vhost_dev_init(struct vhost_dev *dev,
592 		    struct vhost_virtqueue **vqs, int nvqs,
593 		    int iov_limit, int weight, int byte_weight,
594 		    bool use_worker,
595 		    int (*msg_handler)(struct vhost_dev *dev, u32 asid,
596 				       struct vhost_iotlb_msg *msg))
597 {
598 	struct vhost_virtqueue *vq;
599 	int i;
600 
601 	dev->vqs = vqs;
602 	dev->nvqs = nvqs;
603 	mutex_init(&dev->mutex);
604 	dev->log_ctx = NULL;
605 	dev->umem = NULL;
606 	dev->iotlb = NULL;
607 	dev->mm = NULL;
608 	dev->iov_limit = iov_limit;
609 	dev->weight = weight;
610 	dev->byte_weight = byte_weight;
611 	dev->use_worker = use_worker;
612 	dev->msg_handler = msg_handler;
613 	dev->fork_owner = fork_from_owner_default;
614 	init_waitqueue_head(&dev->wait);
615 	INIT_LIST_HEAD(&dev->read_list);
616 	INIT_LIST_HEAD(&dev->pending_list);
617 	spin_lock_init(&dev->iotlb_lock);
618 	xa_init_flags(&dev->worker_xa, XA_FLAGS_ALLOC);
619 
620 	for (i = 0; i < dev->nvqs; ++i) {
621 		vq = dev->vqs[i];
622 		vq->log = NULL;
623 		vq->indirect = NULL;
624 		vq->heads = NULL;
625 		vq->nheads = NULL;
626 		vq->dev = dev;
627 		mutex_init(&vq->mutex);
628 		vhost_vq_reset(dev, vq);
629 		if (vq->handle_kick)
630 			vhost_poll_init(&vq->poll, vq->handle_kick,
631 					EPOLLIN, dev, vq);
632 	}
633 }
634 EXPORT_SYMBOL_GPL(vhost_dev_init);
635 
636 /* Caller should have device mutex */
637 long vhost_dev_check_owner(struct vhost_dev *dev)
638 {
639 	/* Are you the owner? If not, I don't think you mean to do that */
640 	return dev->mm == current->mm ? 0 : -EPERM;
641 }
642 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
643 
644 struct vhost_attach_cgroups_struct {
645 	struct vhost_work work;
646 	struct task_struct *owner;
647 	int ret;
648 };
649 
650 static void vhost_attach_cgroups_work(struct vhost_work *work)
651 {
652 	struct vhost_attach_cgroups_struct *s;
653 
654 	s = container_of(work, struct vhost_attach_cgroups_struct, work);
655 	s->ret = cgroup_attach_task_all(s->owner, current);
656 }
657 
658 static int vhost_attach_task_to_cgroups(struct vhost_worker *worker)
659 {
660 	struct vhost_attach_cgroups_struct attach;
661 	int saved_cnt;
662 
663 	attach.owner = current;
664 
665 	vhost_work_init(&attach.work, vhost_attach_cgroups_work);
666 	vhost_worker_queue(worker, &attach.work);
667 
668 	mutex_lock(&worker->mutex);
669 
670 	/*
671 	 * Bypass attachment_cnt check in __vhost_worker_flush:
672 	 * Temporarily change it to INT_MAX to bypass the check
673 	 */
674 	saved_cnt = worker->attachment_cnt;
675 	worker->attachment_cnt = INT_MAX;
676 	__vhost_worker_flush(worker);
677 	worker->attachment_cnt = saved_cnt;
678 
679 	mutex_unlock(&worker->mutex);
680 
681 	return attach.ret;
682 }
683 
684 /* Caller should have device mutex */
685 bool vhost_dev_has_owner(struct vhost_dev *dev)
686 {
687 	return dev->mm;
688 }
689 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
690 
691 static void vhost_attach_mm(struct vhost_dev *dev)
692 {
693 	/* No owner, become one */
694 	if (dev->use_worker) {
695 		dev->mm = get_task_mm(current);
696 	} else {
697 		/* vDPA device does not use worker thread, so there's
698 		 * no need to hold the address space for mm. This helps
699 		 * to avoid deadlock in the case of mmap() which may
700 		 * hold the refcnt of the file and depends on release
701 		 * method to remove vma.
702 		 */
703 		dev->mm = current->mm;
704 		mmgrab(dev->mm);
705 	}
706 }
707 
708 static void vhost_detach_mm(struct vhost_dev *dev)
709 {
710 	if (!dev->mm)
711 		return;
712 
713 	if (dev->use_worker)
714 		mmput(dev->mm);
715 	else
716 		mmdrop(dev->mm);
717 
718 	dev->mm = NULL;
719 }
720 
721 static void vhost_worker_destroy(struct vhost_dev *dev,
722 				 struct vhost_worker *worker)
723 {
724 	if (!worker)
725 		return;
726 
727 	WARN_ON(!llist_empty(&worker->work_list));
728 	xa_erase(&dev->worker_xa, worker->id);
729 	worker->ops->stop(worker);
730 	kfree(worker);
731 }
732 
733 static void vhost_workers_free(struct vhost_dev *dev, bool sync)
734 {
735 	struct vhost_worker *worker;
736 	unsigned long i;
737 
738 	if (!dev->use_worker)
739 		return;
740 
741 	for (i = 0; i < dev->nvqs; i++)
742 		rcu_assign_pointer(dev->vqs[i]->worker, NULL);
743 
744 	/*
745 	 * This path can be reached by lockless work queuers.  In this case
746 	 * vhost_vq_work_queue() reads vq->worker under rcu_read_lock(), so a
747 	 * RCU reader that fetched a worker before we cleared the pointers above
748 	 * may still be queueing work on it.  Wait for those readers to finish,
749 	 * then flush so any work they queued runs (clearing VHOST_WORK_QUEUED)
750 	 * before the workers are freed.  Notably, that is the case for the
751 	 * vsock RESET_OWNER path.
752 	 */
753 	if (sync) {
754 		synchronize_rcu();
755 		vhost_dev_flush(dev);
756 	}
757 
758 	/*
759 	 * Free the default worker we created and cleanup workers userspace
760 	 * created but couldn't clean up (it forgot or crashed).
761 	 */
762 	xa_for_each(&dev->worker_xa, i, worker)
763 		vhost_worker_destroy(dev, worker);
764 	xa_destroy(&dev->worker_xa);
765 }
766 
767 static void vhost_task_wakeup(struct vhost_worker *worker)
768 {
769 	return vhost_task_wake(worker->vtsk);
770 }
771 
772 static void vhost_kthread_wakeup(struct vhost_worker *worker)
773 {
774 	wake_up_process(worker->kthread_task);
775 }
776 
777 static void vhost_task_do_stop(struct vhost_worker *worker)
778 {
779 	return vhost_task_stop(worker->vtsk);
780 }
781 
782 static void vhost_kthread_do_stop(struct vhost_worker *worker)
783 {
784 	kthread_stop(worker->kthread_task);
785 }
786 
787 static int vhost_task_worker_create(struct vhost_worker *worker,
788 				    struct vhost_dev *dev, const char *name)
789 {
790 	struct vhost_task *vtsk;
791 	u32 id;
792 	int ret;
793 
794 	vtsk = vhost_task_create(vhost_run_work_list, vhost_worker_killed,
795 				 worker, name);
796 	if (IS_ERR(vtsk))
797 		return PTR_ERR(vtsk);
798 
799 	worker->vtsk = vtsk;
800 	vhost_task_start(vtsk);
801 	ret = xa_alloc(&dev->worker_xa, &id, worker, xa_limit_32b, GFP_KERNEL);
802 	if (ret < 0) {
803 		vhost_task_do_stop(worker);
804 		return ret;
805 	}
806 	worker->id = id;
807 	return 0;
808 }
809 
810 static int vhost_kthread_worker_create(struct vhost_worker *worker,
811 				       struct vhost_dev *dev, const char *name)
812 {
813 	struct task_struct *task;
814 	u32 id;
815 	int ret;
816 
817 	task = kthread_create(vhost_run_work_kthread_list, worker, "%s", name);
818 	if (IS_ERR(task))
819 		return PTR_ERR(task);
820 
821 	worker->kthread_task = task;
822 	wake_up_process(task);
823 	ret = xa_alloc(&dev->worker_xa, &id, worker, xa_limit_32b, GFP_KERNEL);
824 	if (ret < 0)
825 		goto stop_worker;
826 
827 	ret = vhost_attach_task_to_cgroups(worker);
828 	if (ret)
829 		goto free_id;
830 
831 	worker->id = id;
832 	return 0;
833 
834 free_id:
835 	xa_erase(&dev->worker_xa, id);
836 stop_worker:
837 	vhost_kthread_do_stop(worker);
838 	return ret;
839 }
840 
841 static const struct vhost_worker_ops kthread_ops = {
842 	.create = vhost_kthread_worker_create,
843 	.stop = vhost_kthread_do_stop,
844 	.wakeup = vhost_kthread_wakeup,
845 };
846 
847 static const struct vhost_worker_ops vhost_task_ops = {
848 	.create = vhost_task_worker_create,
849 	.stop = vhost_task_do_stop,
850 	.wakeup = vhost_task_wakeup,
851 };
852 
853 static struct vhost_worker *vhost_worker_create(struct vhost_dev *dev)
854 {
855 	struct vhost_worker *worker;
856 	char name[TASK_COMM_LEN];
857 	int ret;
858 	const struct vhost_worker_ops *ops = dev->fork_owner ? &vhost_task_ops :
859 							       &kthread_ops;
860 
861 	worker = kzalloc_obj(*worker, GFP_KERNEL_ACCOUNT);
862 	if (!worker)
863 		return NULL;
864 
865 	worker->dev = dev;
866 	worker->ops = ops;
867 	snprintf(name, sizeof(name), "vhost-%d", current->pid);
868 
869 	mutex_init(&worker->mutex);
870 	init_llist_head(&worker->work_list);
871 	worker->kcov_handle = kcov_common_handle();
872 	ret = ops->create(worker, dev, name);
873 	if (ret < 0)
874 		goto free_worker;
875 
876 	return worker;
877 
878 free_worker:
879 	kfree(worker);
880 	return NULL;
881 }
882 
883 /* Caller must have device mutex */
884 static void __vhost_vq_attach_worker(struct vhost_virtqueue *vq,
885 				     struct vhost_worker *worker)
886 {
887 	struct vhost_worker *old_worker;
888 
889 	mutex_lock(&worker->mutex);
890 	if (worker->killed) {
891 		mutex_unlock(&worker->mutex);
892 		return;
893 	}
894 
895 	mutex_lock(&vq->mutex);
896 
897 	old_worker = rcu_dereference_check(vq->worker,
898 					   lockdep_is_held(&vq->mutex));
899 	rcu_assign_pointer(vq->worker, worker);
900 	worker->attachment_cnt++;
901 
902 	if (!old_worker) {
903 		mutex_unlock(&vq->mutex);
904 		mutex_unlock(&worker->mutex);
905 		return;
906 	}
907 	mutex_unlock(&vq->mutex);
908 	mutex_unlock(&worker->mutex);
909 
910 	/*
911 	 * Take the worker mutex to make sure we see the work queued from
912 	 * device wide flushes which doesn't use RCU for execution.
913 	 */
914 	mutex_lock(&old_worker->mutex);
915 	if (old_worker->killed) {
916 		mutex_unlock(&old_worker->mutex);
917 		return;
918 	}
919 
920 	/*
921 	 * We don't want to call synchronize_rcu for every vq during setup
922 	 * because it will slow down VM startup. If we haven't done
923 	 * VHOST_SET_VRING_KICK and not done the driver specific
924 	 * SET_ENDPOINT/RUNNING then we can skip the sync since there will
925 	 * not be any works queued for scsi and net.
926 	 */
927 	mutex_lock(&vq->mutex);
928 	if (!vhost_vq_get_backend(vq) && !vq->kick) {
929 		mutex_unlock(&vq->mutex);
930 
931 		old_worker->attachment_cnt--;
932 		mutex_unlock(&old_worker->mutex);
933 		/*
934 		 * vsock can queue anytime after VHOST_VSOCK_SET_GUEST_CID.
935 		 * Warn if it adds support for multiple workers but forgets to
936 		 * handle the early queueing case.
937 		 */
938 		WARN_ON(!old_worker->attachment_cnt &&
939 			!llist_empty(&old_worker->work_list));
940 		return;
941 	}
942 	mutex_unlock(&vq->mutex);
943 
944 	/* Make sure new vq queue/flush/poll calls see the new worker */
945 	synchronize_rcu();
946 	/* Make sure whatever was queued gets run */
947 	__vhost_worker_flush(old_worker);
948 	old_worker->attachment_cnt--;
949 	mutex_unlock(&old_worker->mutex);
950 }
951 
952  /* Caller must have device mutex */
953 static int vhost_vq_attach_worker(struct vhost_virtqueue *vq,
954 				  struct vhost_vring_worker *info)
955 {
956 	unsigned long index = info->worker_id;
957 	struct vhost_dev *dev = vq->dev;
958 	struct vhost_worker *worker;
959 
960 	if (!dev->use_worker)
961 		return -EINVAL;
962 
963 	worker = xa_find(&dev->worker_xa, &index, UINT_MAX, XA_PRESENT);
964 	if (!worker || worker->id != info->worker_id)
965 		return -ENODEV;
966 
967 	__vhost_vq_attach_worker(vq, worker);
968 	return 0;
969 }
970 
971 /* Caller must have device mutex */
972 static int vhost_new_worker(struct vhost_dev *dev,
973 			    struct vhost_worker_state *info)
974 {
975 	struct vhost_worker *worker;
976 
977 	worker = vhost_worker_create(dev);
978 	if (!worker)
979 		return -ENOMEM;
980 
981 	info->worker_id = worker->id;
982 	return 0;
983 }
984 
985 /* Caller must have device mutex */
986 static int vhost_free_worker(struct vhost_dev *dev,
987 			     struct vhost_worker_state *info)
988 {
989 	unsigned long index = info->worker_id;
990 	struct vhost_worker *worker;
991 
992 	worker = xa_find(&dev->worker_xa, &index, UINT_MAX, XA_PRESENT);
993 	if (!worker || worker->id != info->worker_id)
994 		return -ENODEV;
995 
996 	mutex_lock(&worker->mutex);
997 	if (worker->attachment_cnt || worker->killed) {
998 		mutex_unlock(&worker->mutex);
999 		return -EBUSY;
1000 	}
1001 	/*
1002 	 * A flush might have raced and snuck in before attachment_cnt was set
1003 	 * to zero. Make sure flushes are flushed from the queue before
1004 	 * freeing.
1005 	 */
1006 	__vhost_worker_flush(worker);
1007 	mutex_unlock(&worker->mutex);
1008 
1009 	vhost_worker_destroy(dev, worker);
1010 	return 0;
1011 }
1012 
1013 static int vhost_get_vq_from_user(struct vhost_dev *dev, void __user *argp,
1014 				  struct vhost_virtqueue **vq, u32 *id)
1015 {
1016 	u32 __user *idxp = argp;
1017 	u32 idx;
1018 	long r;
1019 
1020 	r = get_user(idx, idxp);
1021 	if (r < 0)
1022 		return r;
1023 
1024 	if (idx >= dev->nvqs)
1025 		return -ENOBUFS;
1026 
1027 	idx = array_index_nospec(idx, dev->nvqs);
1028 
1029 	*vq = dev->vqs[idx];
1030 	*id = idx;
1031 	return 0;
1032 }
1033 
1034 /* Caller must have device mutex */
1035 long vhost_worker_ioctl(struct vhost_dev *dev, unsigned int ioctl,
1036 			void __user *argp)
1037 {
1038 	struct vhost_vring_worker ring_worker;
1039 	struct vhost_worker_state state;
1040 	struct vhost_worker *worker;
1041 	struct vhost_virtqueue *vq;
1042 	long ret;
1043 	u32 idx;
1044 
1045 	if (!dev->use_worker)
1046 		return -EINVAL;
1047 
1048 	if (!vhost_dev_has_owner(dev))
1049 		return -EINVAL;
1050 
1051 	ret = vhost_dev_check_owner(dev);
1052 	if (ret)
1053 		return ret;
1054 
1055 	switch (ioctl) {
1056 	/* dev worker ioctls */
1057 	case VHOST_NEW_WORKER:
1058 		/*
1059 		 * vhost_tasks will account for worker threads under the parent's
1060 		 * NPROC value but kthreads do not. To avoid userspace overflowing
1061 		 * the system with worker threads fork_owner must be true.
1062 		 */
1063 		if (!dev->fork_owner)
1064 			return -EFAULT;
1065 
1066 		ret = vhost_new_worker(dev, &state);
1067 		if (!ret && copy_to_user(argp, &state, sizeof(state)))
1068 			ret = -EFAULT;
1069 		return ret;
1070 	case VHOST_FREE_WORKER:
1071 		if (copy_from_user(&state, argp, sizeof(state)))
1072 			return -EFAULT;
1073 		return vhost_free_worker(dev, &state);
1074 	/* vring worker ioctls */
1075 	case VHOST_ATTACH_VRING_WORKER:
1076 	case VHOST_GET_VRING_WORKER:
1077 		break;
1078 	default:
1079 		return -ENOIOCTLCMD;
1080 	}
1081 
1082 	ret = vhost_get_vq_from_user(dev, argp, &vq, &idx);
1083 	if (ret)
1084 		return ret;
1085 
1086 	switch (ioctl) {
1087 	case VHOST_ATTACH_VRING_WORKER:
1088 		if (copy_from_user(&ring_worker, argp, sizeof(ring_worker))) {
1089 			ret = -EFAULT;
1090 			break;
1091 		}
1092 
1093 		ret = vhost_vq_attach_worker(vq, &ring_worker);
1094 		break;
1095 	case VHOST_GET_VRING_WORKER:
1096 		worker = rcu_dereference_check(vq->worker,
1097 					       lockdep_is_held(&dev->mutex));
1098 		if (!worker) {
1099 			ret = -EINVAL;
1100 			break;
1101 		}
1102 
1103 		ring_worker.index = idx;
1104 		ring_worker.worker_id = worker->id;
1105 
1106 		if (copy_to_user(argp, &ring_worker, sizeof(ring_worker)))
1107 			ret = -EFAULT;
1108 		break;
1109 	default:
1110 		ret = -ENOIOCTLCMD;
1111 		break;
1112 	}
1113 
1114 	return ret;
1115 }
1116 EXPORT_SYMBOL_GPL(vhost_worker_ioctl);
1117 
1118 /* Caller should have device mutex */
1119 long vhost_dev_set_owner(struct vhost_dev *dev)
1120 {
1121 	struct vhost_worker *worker;
1122 	int err, i;
1123 
1124 	/* Is there an owner already? */
1125 	if (vhost_dev_has_owner(dev)) {
1126 		err = -EBUSY;
1127 		goto err_mm;
1128 	}
1129 
1130 	vhost_attach_mm(dev);
1131 
1132 	err = vhost_dev_alloc_iovecs(dev);
1133 	if (err)
1134 		goto err_iovecs;
1135 
1136 	if (dev->use_worker) {
1137 		/*
1138 		 * This should be done last, because vsock can queue work
1139 		 * before VHOST_SET_OWNER so it simplifies the failure path
1140 		 * below since we don't have to worry about vsock queueing
1141 		 * while we free the worker.
1142 		 */
1143 		worker = vhost_worker_create(dev);
1144 		if (!worker) {
1145 			err = -ENOMEM;
1146 			goto err_worker;
1147 		}
1148 
1149 		for (i = 0; i < dev->nvqs; i++)
1150 			__vhost_vq_attach_worker(dev->vqs[i], worker);
1151 	}
1152 
1153 	return 0;
1154 
1155 err_worker:
1156 	vhost_dev_free_iovecs(dev);
1157 err_iovecs:
1158 	vhost_detach_mm(dev);
1159 err_mm:
1160 	return err;
1161 }
1162 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
1163 
1164 static struct vhost_iotlb *iotlb_alloc(void)
1165 {
1166 	if (max_iotlb_entries <= 0)
1167 		return NULL;
1168 
1169 	return vhost_iotlb_alloc(max_iotlb_entries,
1170 				 VHOST_IOTLB_FLAG_RETIRE);
1171 }
1172 
1173 struct vhost_iotlb *vhost_dev_reset_owner_prepare(void)
1174 {
1175 	return iotlb_alloc();
1176 }
1177 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
1178 
1179 /* Caller should have device mutex */
1180 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem,
1181 			   bool sync)
1182 {
1183 	int i;
1184 
1185 	vhost_dev_cleanup(dev, sync);
1186 
1187 	dev->fork_owner = fork_from_owner_default;
1188 	dev->umem = umem;
1189 	/* We don't need VQ locks below since vhost_dev_cleanup makes sure
1190 	 * VQs aren't running.
1191 	 */
1192 	for (i = 0; i < dev->nvqs; ++i)
1193 		dev->vqs[i]->umem = umem;
1194 }
1195 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
1196 
1197 void vhost_dev_stop(struct vhost_dev *dev)
1198 {
1199 	int i;
1200 
1201 	for (i = 0; i < dev->nvqs; ++i) {
1202 		if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick)
1203 			vhost_poll_stop(&dev->vqs[i]->poll);
1204 	}
1205 
1206 	vhost_dev_flush(dev);
1207 }
1208 EXPORT_SYMBOL_GPL(vhost_dev_stop);
1209 
1210 static void vhost_free_msg_locked(struct vhost_msg_node *node)
1211 {
1212 	if (node->vq->iotlb_miss == node)
1213 		node->vq->iotlb_miss = NULL;
1214 	kfree(node);
1215 }
1216 
1217 static void vhost_free_msg(struct vhost_dev *dev,
1218 			   struct vhost_msg_node *node)
1219 {
1220 	spin_lock(&dev->iotlb_lock);
1221 	vhost_free_msg_locked(node);
1222 	spin_unlock(&dev->iotlb_lock);
1223 }
1224 
1225 void vhost_clear_msg(struct vhost_dev *dev)
1226 {
1227 	struct vhost_msg_node *node, *n;
1228 
1229 	spin_lock(&dev->iotlb_lock);
1230 
1231 	list_for_each_entry_safe(node, n, &dev->read_list, node) {
1232 		list_del(&node->node);
1233 		vhost_free_msg_locked(node);
1234 	}
1235 
1236 	list_for_each_entry_safe(node, n, &dev->pending_list, node) {
1237 		list_del(&node->node);
1238 		vhost_free_msg_locked(node);
1239 	}
1240 
1241 	spin_unlock(&dev->iotlb_lock);
1242 }
1243 EXPORT_SYMBOL_GPL(vhost_clear_msg);
1244 
1245 void vhost_dev_cleanup(struct vhost_dev *dev, bool sync)
1246 {
1247 	int i;
1248 
1249 	for (i = 0; i < dev->nvqs; ++i) {
1250 		if (dev->vqs[i]->error_ctx)
1251 			eventfd_ctx_put(dev->vqs[i]->error_ctx);
1252 		if (dev->vqs[i]->kick)
1253 			fput(dev->vqs[i]->kick);
1254 		if (dev->vqs[i]->call_ctx.ctx)
1255 			eventfd_ctx_put(dev->vqs[i]->call_ctx.ctx);
1256 		vhost_vq_reset(dev, dev->vqs[i]);
1257 	}
1258 	vhost_dev_free_iovecs(dev);
1259 	if (dev->log_ctx)
1260 		eventfd_ctx_put(dev->log_ctx);
1261 	dev->log_ctx = NULL;
1262 	/* No one will access memory at this point */
1263 	vhost_iotlb_free(dev->umem);
1264 	dev->umem = NULL;
1265 	vhost_iotlb_free(dev->iotlb);
1266 	dev->iotlb = NULL;
1267 	vhost_clear_msg(dev);
1268 	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
1269 	vhost_workers_free(dev, sync);
1270 	vhost_detach_mm(dev);
1271 }
1272 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
1273 
1274 static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
1275 {
1276 	u64 a = addr / VHOST_PAGE_SIZE / 8;
1277 
1278 	/* Make sure 64 bit math will not overflow. */
1279 	if (a > ULONG_MAX - (unsigned long)log_base ||
1280 	    a + (unsigned long)log_base > ULONG_MAX)
1281 		return false;
1282 
1283 	return access_ok(log_base + a,
1284 			 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
1285 }
1286 
1287 /* Make sure 64 bit math will not overflow. */
1288 static bool vhost_overflow(u64 uaddr, u64 size)
1289 {
1290 	if (uaddr > ULONG_MAX || size > ULONG_MAX)
1291 		return true;
1292 
1293 	if (!size)
1294 		return false;
1295 
1296 	return uaddr > ULONG_MAX - size + 1;
1297 }
1298 
1299 /* Caller should have vq mutex and device mutex. */
1300 static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem,
1301 				int log_all)
1302 {
1303 	struct vhost_iotlb_map *map;
1304 
1305 	if (!umem)
1306 		return false;
1307 
1308 	list_for_each_entry(map, &umem->list, link) {
1309 		unsigned long a = map->addr;
1310 
1311 		if (vhost_overflow(map->addr, map->size))
1312 			return false;
1313 
1314 
1315 		if (!access_ok((void __user *)a, map->size))
1316 			return false;
1317 		else if (log_all && !log_access_ok(log_base,
1318 						   map->start,
1319 						   map->size))
1320 			return false;
1321 	}
1322 	return true;
1323 }
1324 
1325 static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
1326 					       u64 addr, unsigned int size,
1327 					       int type)
1328 {
1329 	const struct vhost_iotlb_map *map = vq->meta_iotlb[type];
1330 
1331 	if (!map)
1332 		return NULL;
1333 
1334 	return (void __user *)(uintptr_t)(map->addr + addr - map->start);
1335 }
1336 
1337 /* Can we switch to this memory table? */
1338 /* Caller should have device mutex but not vq mutex */
1339 static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem,
1340 			     int log_all)
1341 {
1342 	int i;
1343 
1344 	for (i = 0; i < d->nvqs; ++i) {
1345 		bool ok;
1346 		bool log;
1347 
1348 		mutex_lock(&d->vqs[i]->mutex);
1349 		log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
1350 		/* If ring is inactive, will check when it's enabled. */
1351 		if (d->vqs[i]->private_data)
1352 			ok = vq_memory_access_ok(d->vqs[i]->log_base,
1353 						 umem, log);
1354 		else
1355 			ok = true;
1356 		mutex_unlock(&d->vqs[i]->mutex);
1357 		if (!ok)
1358 			return false;
1359 	}
1360 	return true;
1361 }
1362 
1363 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1364 			  struct iovec iov[], int iov_size, int access);
1365 
1366 static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
1367 			      const void *from, unsigned size)
1368 {
1369 	int ret;
1370 
1371 	if (!vq->iotlb)
1372 		return __copy_to_user(to, from, size);
1373 	else {
1374 		/* This function should be called after iotlb
1375 		 * prefetch, which means we're sure that all vq
1376 		 * could be access through iotlb. So -EAGAIN should
1377 		 * not happen in this case.
1378 		 */
1379 		struct iov_iter t;
1380 		void __user *uaddr = vhost_vq_meta_fetch(vq,
1381 				     (u64)(uintptr_t)to, size,
1382 				     VHOST_ADDR_USED);
1383 
1384 		if (uaddr)
1385 			return __copy_to_user(uaddr, from, size);
1386 
1387 		ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
1388 				     ARRAY_SIZE(vq->iotlb_iov),
1389 				     VHOST_ACCESS_WO);
1390 		if (ret < 0)
1391 			goto out;
1392 		iov_iter_init(&t, ITER_DEST, vq->iotlb_iov, ret, size);
1393 		ret = copy_to_iter(from, size, &t);
1394 		if (ret == size)
1395 			ret = 0;
1396 	}
1397 out:
1398 	return ret;
1399 }
1400 
1401 static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
1402 				void __user *from, unsigned size)
1403 {
1404 	int ret;
1405 
1406 	if (!vq->iotlb)
1407 		return __copy_from_user(to, from, size);
1408 	else {
1409 		/* This function should be called after iotlb
1410 		 * prefetch, which means we're sure that vq
1411 		 * could be access through iotlb. So -EAGAIN should
1412 		 * not happen in this case.
1413 		 */
1414 		void __user *uaddr = vhost_vq_meta_fetch(vq,
1415 				     (u64)(uintptr_t)from, size,
1416 				     VHOST_ADDR_DESC);
1417 		struct iov_iter f;
1418 
1419 		if (uaddr)
1420 			return __copy_from_user(to, uaddr, size);
1421 
1422 		ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
1423 				     ARRAY_SIZE(vq->iotlb_iov),
1424 				     VHOST_ACCESS_RO);
1425 		if (ret < 0) {
1426 			vq_err(vq, "IOTLB translation failure: uaddr "
1427 			       "%p size 0x%llx\n", from,
1428 			       (unsigned long long) size);
1429 			goto out;
1430 		}
1431 		iov_iter_init(&f, ITER_SOURCE, vq->iotlb_iov, ret, size);
1432 		ret = copy_from_iter(to, size, &f);
1433 		if (ret == size)
1434 			ret = 0;
1435 	}
1436 
1437 out:
1438 	return ret;
1439 }
1440 
1441 static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
1442 					  void __user *addr, unsigned int size,
1443 					  int type)
1444 {
1445 	int ret;
1446 
1447 	ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
1448 			     ARRAY_SIZE(vq->iotlb_iov),
1449 			     VHOST_ACCESS_RO);
1450 	if (ret < 0) {
1451 		vq_err(vq, "IOTLB translation failure: uaddr "
1452 			"%p size 0x%llx\n", addr,
1453 			(unsigned long long) size);
1454 		return NULL;
1455 	}
1456 
1457 	if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
1458 		vq_err(vq, "Non atomic userspace memory access: uaddr "
1459 			"%p size 0x%llx\n", addr,
1460 			(unsigned long long) size);
1461 		return NULL;
1462 	}
1463 
1464 	return vq->iotlb_iov[0].iov_base;
1465 }
1466 
1467 /* This function should be called after iotlb
1468  * prefetch, which means we're sure that vq
1469  * could be access through iotlb. So -EAGAIN should
1470  * not happen in this case.
1471  */
1472 static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
1473 					    void __user *addr, unsigned int size,
1474 					    int type)
1475 {
1476 	void __user *uaddr = vhost_vq_meta_fetch(vq,
1477 			     (u64)(uintptr_t)addr, size, type);
1478 	if (uaddr)
1479 		return uaddr;
1480 
1481 	return __vhost_get_user_slow(vq, addr, size, type);
1482 }
1483 
1484 #define vhost_put_user(vq, x, ptr)		\
1485 ({ \
1486 	int ret; \
1487 	if (!vq->iotlb) { \
1488 		ret = put_user(x, ptr); \
1489 	} else { \
1490 		__typeof__(ptr) to = \
1491 			(__typeof__(ptr)) __vhost_get_user(vq, ptr,	\
1492 					  sizeof(*ptr), VHOST_ADDR_USED); \
1493 		if (to != NULL) \
1494 			ret = put_user(x, to); \
1495 		else \
1496 			ret = -EFAULT;	\
1497 	} \
1498 	ret; \
1499 })
1500 
1501 static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
1502 {
1503 	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
1504 			      vhost_avail_event(vq));
1505 }
1506 
1507 static inline int vhost_put_used(struct vhost_virtqueue *vq,
1508 				 struct vring_used_elem *head, int idx,
1509 				 int count)
1510 {
1511 	return vhost_copy_to_user(vq, vq->used->ring + idx, head,
1512 				  count * sizeof(*head));
1513 }
1514 
1515 static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
1516 
1517 {
1518 	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
1519 			      &vq->used->flags);
1520 }
1521 
1522 static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
1523 
1524 {
1525 	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
1526 			      &vq->used->idx);
1527 }
1528 
1529 #define vhost_get_user(vq, x, ptr, type)		\
1530 ({ \
1531 	int ret; \
1532 	if (!vq->iotlb) { \
1533 		ret = get_user(x, ptr); \
1534 	} else { \
1535 		__typeof__(ptr) from = \
1536 			(__typeof__(ptr)) __vhost_get_user(vq, ptr, \
1537 							   sizeof(*ptr), \
1538 							   type); \
1539 		if (from != NULL) \
1540 			ret = get_user(x, from); \
1541 		else \
1542 			ret = -EFAULT; \
1543 	} \
1544 	ret; \
1545 })
1546 
1547 #define vhost_get_avail(vq, x, ptr) \
1548 	vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
1549 
1550 #define vhost_get_used(vq, x, ptr) \
1551 	vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
1552 
1553 static void vhost_dev_lock_vqs(struct vhost_dev *d)
1554 {
1555 	int i = 0;
1556 	for (i = 0; i < d->nvqs; ++i)
1557 		mutex_lock_nested(&d->vqs[i]->mutex, i);
1558 }
1559 
1560 static void vhost_dev_unlock_vqs(struct vhost_dev *d)
1561 {
1562 	int i = 0;
1563 	for (i = 0; i < d->nvqs; ++i)
1564 		mutex_unlock(&d->vqs[i]->mutex);
1565 }
1566 
1567 static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq)
1568 {
1569 	__virtio16 idx;
1570 	u16 avail_idx;
1571 	int r;
1572 
1573 	r = vhost_get_avail(vq, idx, &vq->avail->idx);
1574 	if (unlikely(r < 0)) {
1575 		vq_err(vq, "Failed to access available index at %p (%d)\n",
1576 		       &vq->avail->idx, r);
1577 		return r;
1578 	}
1579 
1580 	/* Check it isn't doing very strange thing with available indexes */
1581 	avail_idx = vhost16_to_cpu(vq, idx);
1582 	if (unlikely((u16)(avail_idx - vq->last_avail_idx) > vq->num)) {
1583 		vq_err(vq, "Invalid available index change from %u to %u",
1584 		       vq->last_avail_idx, avail_idx);
1585 		return -EINVAL;
1586 	}
1587 
1588 	/* We're done if there is nothing new */
1589 	if (avail_idx == vq->avail_idx)
1590 		return 0;
1591 
1592 	vq->avail_idx = avail_idx;
1593 
1594 	/*
1595 	 * We updated vq->avail_idx so we need a memory barrier between
1596 	 * the index read above and the caller reading avail ring entries.
1597 	 */
1598 	smp_rmb();
1599 	return 1;
1600 }
1601 
1602 static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
1603 				       __virtio16 *head, int idx)
1604 {
1605 	return vhost_get_avail(vq, *head,
1606 			       &vq->avail->ring[idx & (vq->num - 1)]);
1607 }
1608 
1609 static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1610 					__virtio16 *flags)
1611 {
1612 	return vhost_get_avail(vq, *flags, &vq->avail->flags);
1613 }
1614 
1615 static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1616 				       __virtio16 *event)
1617 {
1618 	return vhost_get_avail(vq, *event, vhost_used_event(vq));
1619 }
1620 
1621 static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1622 				     __virtio16 *idx)
1623 {
1624 	return vhost_get_used(vq, *idx, &vq->used->idx);
1625 }
1626 
1627 static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1628 				 struct vring_desc *desc, int idx)
1629 {
1630 	return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1631 }
1632 
1633 static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1634 				  struct vhost_iotlb_msg *msg)
1635 {
1636 	struct vhost_msg_node *node, *n;
1637 
1638 	spin_lock(&d->iotlb_lock);
1639 
1640 	list_for_each_entry_safe(node, n, &d->pending_list, node) {
1641 		struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1642 		if (msg->iova <= vq_msg->iova &&
1643 		    msg->iova + msg->size - 1 >= vq_msg->iova &&
1644 		    vq_msg->type == VHOST_IOTLB_MISS) {
1645 			vhost_poll_queue(&node->vq->poll);
1646 			list_del(&node->node);
1647 			vhost_free_msg_locked(node);
1648 		}
1649 	}
1650 
1651 	spin_unlock(&d->iotlb_lock);
1652 }
1653 
1654 static bool umem_access_ok(u64 uaddr, u64 size, int access)
1655 {
1656 	unsigned long a = uaddr;
1657 
1658 	/* Make sure 64 bit math will not overflow. */
1659 	if (vhost_overflow(uaddr, size))
1660 		return false;
1661 
1662 	if ((access & VHOST_ACCESS_RO) &&
1663 	    !access_ok((void __user *)a, size))
1664 		return false;
1665 	if ((access & VHOST_ACCESS_WO) &&
1666 	    !access_ok((void __user *)a, size))
1667 		return false;
1668 	return true;
1669 }
1670 
1671 static int vhost_process_iotlb_msg(struct vhost_dev *dev, u32 asid,
1672 				   struct vhost_iotlb_msg *msg)
1673 {
1674 	int ret = 0;
1675 
1676 	if (asid != 0)
1677 		return -EINVAL;
1678 
1679 	mutex_lock(&dev->mutex);
1680 	vhost_dev_lock_vqs(dev);
1681 	switch (msg->type) {
1682 	case VHOST_IOTLB_UPDATE:
1683 		if (!dev->iotlb) {
1684 			ret = -EFAULT;
1685 			break;
1686 		}
1687 		if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
1688 			ret = -EFAULT;
1689 			break;
1690 		}
1691 		vhost_vq_meta_reset(dev);
1692 		if (vhost_iotlb_add_range(dev->iotlb, msg->iova,
1693 					  msg->iova + msg->size - 1,
1694 					  msg->uaddr, msg->perm)) {
1695 			ret = -ENOMEM;
1696 			break;
1697 		}
1698 		vhost_iotlb_notify_vq(dev, msg);
1699 		break;
1700 	case VHOST_IOTLB_INVALIDATE:
1701 		if (!dev->iotlb) {
1702 			ret = -EFAULT;
1703 			break;
1704 		}
1705 		if (!msg->size) {
1706 			ret = -EINVAL;
1707 			break;
1708 		}
1709 		vhost_vq_meta_reset(dev);
1710 		vhost_iotlb_del_range(dev->iotlb, msg->iova,
1711 				      msg->iova + msg->size - 1);
1712 		break;
1713 	default:
1714 		ret = -EINVAL;
1715 		break;
1716 	}
1717 
1718 	vhost_dev_unlock_vqs(dev);
1719 	mutex_unlock(&dev->mutex);
1720 
1721 	return ret;
1722 }
1723 ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1724 			     struct iov_iter *from)
1725 {
1726 	struct vhost_iotlb_msg msg;
1727 	size_t offset;
1728 	int type, ret;
1729 	u32 asid = 0;
1730 
1731 	ret = copy_from_iter(&type, sizeof(type), from);
1732 	if (ret != sizeof(type)) {
1733 		ret = -EINVAL;
1734 		goto done;
1735 	}
1736 
1737 	switch (type) {
1738 	case VHOST_IOTLB_MSG:
1739 		/* There maybe a hole after type for V1 message type,
1740 		 * so skip it here.
1741 		 */
1742 		offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1743 		break;
1744 	case VHOST_IOTLB_MSG_V2:
1745 		if (vhost_backend_has_feature(dev->vqs[0],
1746 					      VHOST_BACKEND_F_IOTLB_ASID)) {
1747 			ret = copy_from_iter(&asid, sizeof(asid), from);
1748 			if (ret != sizeof(asid)) {
1749 				ret = -EINVAL;
1750 				goto done;
1751 			}
1752 			offset = 0;
1753 		} else
1754 			offset = sizeof(__u32);
1755 		break;
1756 	default:
1757 		ret = -EINVAL;
1758 		goto done;
1759 	}
1760 
1761 	iov_iter_advance(from, offset);
1762 	ret = copy_from_iter(&msg, sizeof(msg), from);
1763 	if (ret != sizeof(msg)) {
1764 		ret = -EINVAL;
1765 		goto done;
1766 	}
1767 
1768 	if (msg.type == VHOST_IOTLB_UPDATE &&
1769 	    (!msg.size || !msg.perm || (msg.perm & ~VHOST_ACCESS_RW))) {
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 #ifdef CONFIG_X86
2531 static int set_bit_to_user(int nr, void __user *addr)
2532 {
2533 	return set_bit_user(nr, addr);
2534 }
2535 #else
2536 /* TODO: This is really inefficient.  We need something like get_user()
2537  * (instruction directly accesses the data, with an exception table entry
2538  * returning -EFAULT). See Documentation/arch/x86/exception-tables.rst.
2539  */
2540 static int set_bit_to_user(int nr, void __user *addr)
2541 {
2542 	unsigned long log = (unsigned long)addr;
2543 	struct page *page;
2544 	void *base;
2545 	int bit = nr + (log % PAGE_SIZE) * 8;
2546 	int r;
2547 
2548 	r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page);
2549 	if (r < 0)
2550 		return r;
2551 	BUG_ON(r != 1);
2552 	base = kmap_atomic(page);
2553 	set_bit(bit, base);
2554 	kunmap_atomic(base);
2555 	unpin_user_pages_dirty_lock(&page, 1, true);
2556 	return 0;
2557 }
2558 #endif /* CONFIG_X86 */
2559 
2560 static int log_write(void __user *log_base,
2561 		     u64 write_address, u64 write_length)
2562 {
2563 	u64 write_page = write_address / VHOST_PAGE_SIZE;
2564 	int r;
2565 
2566 	if (!write_length)
2567 		return 0;
2568 	write_length += write_address % VHOST_PAGE_SIZE;
2569 	for (;;) {
2570 		u64 base = (u64)(unsigned long)log_base;
2571 		u64 log = base + write_page / 8;
2572 		int bit = write_page % 8;
2573 		if ((u64)(unsigned long)log != log)
2574 			return -EFAULT;
2575 		r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
2576 		if (r < 0)
2577 			return r;
2578 		if (write_length <= VHOST_PAGE_SIZE)
2579 			break;
2580 		write_length -= VHOST_PAGE_SIZE;
2581 		write_page += 1;
2582 	}
2583 	return r;
2584 }
2585 
2586 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
2587 {
2588 	struct vhost_iotlb *umem = vq->umem;
2589 	struct vhost_iotlb_map *u;
2590 	u64 start, end, l, min;
2591 	int r;
2592 	bool hit = false;
2593 
2594 	while (len) {
2595 		min = len;
2596 		/* More than one GPAs can be mapped into a single HVA. So
2597 		 * iterate all possible umems here to be safe.
2598 		 */
2599 		list_for_each_entry(u, &umem->list, link) {
2600 			if (u->addr > hva - 1 + len ||
2601 			    u->addr - 1 + u->size < hva)
2602 				continue;
2603 			start = max(u->addr, hva);
2604 			end = min(u->addr - 1 + u->size, hva - 1 + len);
2605 			l = end - start + 1;
2606 			r = log_write(vq->log_base,
2607 				      u->start + start - u->addr,
2608 				      l);
2609 			if (r < 0)
2610 				return r;
2611 			hit = true;
2612 			min = min(l, min);
2613 		}
2614 
2615 		if (!hit)
2616 			return -EFAULT;
2617 
2618 		len -= min;
2619 		hva += min;
2620 	}
2621 
2622 	return 0;
2623 }
2624 
2625 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
2626 {
2627 	struct iovec *iov = vq->log_iov;
2628 	int i, ret;
2629 
2630 	if (!vq->iotlb)
2631 		return log_write(vq->log_base, vq->log_addr + used_offset, len);
2632 
2633 	ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
2634 			     len, iov, 64, VHOST_ACCESS_WO);
2635 	if (ret < 0)
2636 		return ret;
2637 
2638 	for (i = 0; i < ret; i++) {
2639 		ret = log_write_hva(vq,	(uintptr_t)iov[i].iov_base,
2640 				    iov[i].iov_len);
2641 		if (ret)
2642 			return ret;
2643 	}
2644 
2645 	return 0;
2646 }
2647 
2648 /*
2649  * vhost_log_write() - Log in dirty page bitmap
2650  * @vq:      vhost virtqueue.
2651  * @log:     Array of dirty memory in GPA.
2652  * @log_num: Size of vhost_log arrary.
2653  * @len:     The total length of memory buffer to log in the dirty bitmap.
2654  *	     Some drivers may only partially use pages shared via the last
2655  *	     vring descriptor (i.e. vhost-net RX buffer).
2656  *	     Use (len == U64_MAX) to indicate the driver would log all
2657  *           pages of vring descriptors.
2658  * @iov:     Array of dirty memory in HVA.
2659  * @count:   Size of iovec array.
2660  */
2661 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
2662 		    unsigned int log_num, u64 len, struct iovec *iov, int count)
2663 {
2664 	int i, r;
2665 
2666 	/* Make sure data written is seen before log. */
2667 	smp_wmb();
2668 
2669 	if (vq->iotlb) {
2670 		for (i = 0; i < count; i++) {
2671 			r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
2672 					  iov[i].iov_len);
2673 			if (r < 0)
2674 				return r;
2675 		}
2676 		return 0;
2677 	}
2678 
2679 	for (i = 0; i < log_num; ++i) {
2680 		u64 l = min(log[i].len, len);
2681 		r = log_write(vq->log_base, log[i].addr, l);
2682 		if (r < 0)
2683 			return r;
2684 
2685 		if (len != U64_MAX)
2686 			len -= l;
2687 	}
2688 
2689 	if (vq->log_ctx)
2690 		eventfd_signal(vq->log_ctx);
2691 
2692 	return 0;
2693 }
2694 EXPORT_SYMBOL_GPL(vhost_log_write);
2695 
2696 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
2697 {
2698 	void __user *used;
2699 	if (vhost_put_used_flags(vq))
2700 		return -EFAULT;
2701 	if (unlikely(vq->log_used)) {
2702 		/* Make sure the flag is seen before log. */
2703 		smp_wmb();
2704 		/* Log used flag write. */
2705 		used = &vq->used->flags;
2706 		log_used(vq, (used - (void __user *)vq->used),
2707 			 sizeof vq->used->flags);
2708 		if (vq->log_ctx)
2709 			eventfd_signal(vq->log_ctx);
2710 	}
2711 	return 0;
2712 }
2713 
2714 static int vhost_update_avail_event(struct vhost_virtqueue *vq)
2715 {
2716 	if (vhost_put_avail_event(vq))
2717 		return -EFAULT;
2718 	if (unlikely(vq->log_used)) {
2719 		void __user *used;
2720 		/* Make sure the event is seen before log. */
2721 		smp_wmb();
2722 		/* Log avail event write */
2723 		used = vhost_avail_event(vq);
2724 		log_used(vq, (used - (void __user *)vq->used),
2725 			 sizeof *vhost_avail_event(vq));
2726 		if (vq->log_ctx)
2727 			eventfd_signal(vq->log_ctx);
2728 	}
2729 	return 0;
2730 }
2731 
2732 int vhost_vq_init_access(struct vhost_virtqueue *vq)
2733 {
2734 	__virtio16 last_used_idx;
2735 	int r;
2736 	bool is_le = vq->is_le;
2737 
2738 	if (!vq->private_data)
2739 		return 0;
2740 
2741 	vhost_init_is_le(vq);
2742 
2743 	r = vhost_update_used_flags(vq);
2744 	if (r)
2745 		goto err;
2746 	vq->signalled_used_valid = false;
2747 	if (!vq->iotlb &&
2748 	    !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
2749 		r = -EFAULT;
2750 		goto err;
2751 	}
2752 	r = vhost_get_used_idx(vq, &last_used_idx);
2753 	if (r) {
2754 		vq_err(vq, "Can't access used idx at %p\n",
2755 		       &vq->used->idx);
2756 		goto err;
2757 	}
2758 	vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2759 	return 0;
2760 
2761 err:
2762 	vq->is_le = is_le;
2763 	return r;
2764 }
2765 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2766 
2767 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2768 			  struct iovec iov[], int iov_size, int access)
2769 {
2770 	const struct vhost_iotlb_map *map;
2771 	struct vhost_dev *dev = vq->dev;
2772 	struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
2773 	struct iovec *_iov;
2774 	u64 s = 0, last = addr + len - 1;
2775 	int ret = 0;
2776 
2777 	while ((u64)len > s) {
2778 		u64 size;
2779 		if (unlikely(ret >= iov_size)) {
2780 			ret = -ENOBUFS;
2781 			break;
2782 		}
2783 
2784 		map = vhost_iotlb_itree_first(umem, addr, last);
2785 		if (map == NULL || map->start > addr) {
2786 			if (umem != dev->iotlb) {
2787 				ret = -EFAULT;
2788 				break;
2789 			}
2790 			ret = -EAGAIN;
2791 			break;
2792 		} else if (!(map->perm & access)) {
2793 			ret = -EPERM;
2794 			break;
2795 		}
2796 
2797 		_iov = iov + ret;
2798 		size = map->size - addr + map->start;
2799 		_iov->iov_len = min((u64)len - s, size);
2800 		_iov->iov_base = (void __user *)(unsigned long)
2801 				 (map->addr + addr - map->start);
2802 		s += size;
2803 		addr += size;
2804 		++ret;
2805 	}
2806 
2807 	if (ret == -EAGAIN)
2808 		vhost_iotlb_miss(vq, addr, access);
2809 	return ret;
2810 }
2811 
2812 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
2813  * function returns the next descriptor in the chain,
2814  * or -1U if we're at the end. */
2815 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2816 {
2817 	unsigned int next;
2818 
2819 	/* If this descriptor says it doesn't chain, we're done. */
2820 	if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2821 		return -1U;
2822 
2823 	/* Check they're not leading us off end of descriptors. */
2824 	next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2825 	return next;
2826 }
2827 
2828 static int get_indirect(struct vhost_virtqueue *vq,
2829 			struct iovec iov[], unsigned int iov_size,
2830 			unsigned int *out_num, unsigned int *in_num,
2831 			struct vhost_log *log, unsigned int *log_num,
2832 			struct vring_desc *indirect)
2833 {
2834 	struct vring_desc desc;
2835 	unsigned int i = 0, count, found = 0;
2836 	u32 len = vhost32_to_cpu(vq, indirect->len);
2837 	struct iov_iter from;
2838 	int ret, access;
2839 
2840 	/* Sanity check */
2841 	if (unlikely(len % sizeof desc)) {
2842 		vq_err(vq, "Invalid length in indirect descriptor: "
2843 		       "len 0x%llx not multiple of 0x%zx\n",
2844 		       (unsigned long long)len,
2845 		       sizeof desc);
2846 		return -EINVAL;
2847 	}
2848 
2849 	ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2850 			     UIO_MAXIOV, VHOST_ACCESS_RO);
2851 	if (unlikely(ret < 0)) {
2852 		if (ret != -EAGAIN)
2853 			vq_err(vq, "Translation failure %d in indirect.\n", ret);
2854 		return ret;
2855 	}
2856 	iov_iter_init(&from, ITER_SOURCE, vq->indirect, ret, len);
2857 	count = len / sizeof desc;
2858 	/* Buffers are chained via a 16 bit next field, so
2859 	 * we can have at most 2^16 of these. */
2860 	if (unlikely(count > USHRT_MAX + 1)) {
2861 		vq_err(vq, "Indirect buffer length too big: %d\n",
2862 		       indirect->len);
2863 		return -E2BIG;
2864 	}
2865 
2866 	do {
2867 		unsigned iov_count = *in_num + *out_num;
2868 		if (unlikely(++found > count)) {
2869 			vq_err(vq, "Loop detected: last one at %u "
2870 			       "indirect size %u\n",
2871 			       i, count);
2872 			return -EINVAL;
2873 		}
2874 		if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2875 			vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2876 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2877 			return -EINVAL;
2878 		}
2879 		if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2880 			vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2881 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2882 			return -EINVAL;
2883 		}
2884 
2885 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2886 			access = VHOST_ACCESS_WO;
2887 		else
2888 			access = VHOST_ACCESS_RO;
2889 
2890 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2891 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
2892 				     iov_size - iov_count, access);
2893 		if (unlikely(ret < 0)) {
2894 			if (ret != -EAGAIN)
2895 				vq_err(vq, "Translation failure %d indirect idx %d\n",
2896 					ret, i);
2897 			return ret;
2898 		}
2899 		/* If this is an input descriptor, increment that count. */
2900 		if (access == VHOST_ACCESS_WO) {
2901 			*in_num += ret;
2902 			if (unlikely(log && ret)) {
2903 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2904 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2905 				++*log_num;
2906 			}
2907 		} else {
2908 			/* If it's an output descriptor, they're all supposed
2909 			 * to come before any input descriptors. */
2910 			if (unlikely(*in_num)) {
2911 				vq_err(vq, "Indirect descriptor "
2912 				       "has out after in: idx %d\n", i);
2913 				return -EINVAL;
2914 			}
2915 			*out_num += ret;
2916 		}
2917 	} while ((i = next_desc(vq, &desc)) != -1);
2918 	return 0;
2919 }
2920 
2921 /**
2922  * vhost_get_vq_desc_n - Fetch the next available descriptor chain and build iovecs
2923  * @vq: target virtqueue
2924  * @iov: array that receives the scatter/gather segments
2925  * @iov_size: capacity of @iov in elements
2926  * @out_num: the number of output segments
2927  * @in_num: the number of input segments
2928  * @log: optional array to record addr/len for each writable segment; NULL if unused
2929  * @log_num: optional output; number of entries written to @log when provided
2930  * @ndesc: optional output; number of descriptors consumed from the available ring
2931  *         (useful for rollback via vhost_discard_vq_desc)
2932  *
2933  * Extracts one available descriptor chain from @vq and translates guest addresses
2934  * into host iovecs.
2935  *
2936  * On success, advances @vq->last_avail_idx by 1 and @vq->next_avail_head by the
2937  * number of descriptors consumed (also stored via @ndesc when non-NULL).
2938  *
2939  * Return:
2940  * - head index in [0, @vq->num) on success;
2941  * - @vq->num if no descriptor is currently available;
2942  * - negative errno on failure
2943  */
2944 int vhost_get_vq_desc_n(struct vhost_virtqueue *vq,
2945 			struct iovec iov[], unsigned int iov_size,
2946 			unsigned int *out_num, unsigned int *in_num,
2947 			struct vhost_log *log, unsigned int *log_num,
2948 			unsigned int *ndesc)
2949 {
2950 	bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER);
2951 	struct vring_desc desc;
2952 	unsigned int i, head, found = 0;
2953 	u16 last_avail_idx = vq->last_avail_idx;
2954 	__virtio16 ring_head;
2955 	int ret, access, c = 0;
2956 
2957 	if (vq->avail_idx == vq->last_avail_idx) {
2958 		ret = vhost_get_avail_idx(vq);
2959 		if (unlikely(ret < 0))
2960 			return ret;
2961 
2962 		if (!ret)
2963 			return vq->num;
2964 	}
2965 
2966 	if (in_order)
2967 		head = vq->next_avail_head & (vq->num - 1);
2968 	else {
2969 		/* Grab the next descriptor number they're
2970 		 * advertising, and increment the index we've seen. */
2971 		if (unlikely(vhost_get_avail_head(vq, &ring_head,
2972 						  last_avail_idx))) {
2973 			vq_err(vq, "Failed to read head: idx %d address %p\n",
2974 				last_avail_idx,
2975 				&vq->avail->ring[last_avail_idx % vq->num]);
2976 			return -EFAULT;
2977 		}
2978 		head = vhost16_to_cpu(vq, ring_head);
2979 	}
2980 
2981 	/* If their number is silly, that's an error. */
2982 	if (unlikely(head >= vq->num)) {
2983 		vq_err(vq, "Guest says index %u > %u is available",
2984 		       head, vq->num);
2985 		return -EINVAL;
2986 	}
2987 
2988 	/* When we start there are none of either input nor output. */
2989 	*out_num = *in_num = 0;
2990 	if (unlikely(log))
2991 		*log_num = 0;
2992 
2993 	i = head;
2994 	do {
2995 		unsigned iov_count = *in_num + *out_num;
2996 		if (unlikely(i >= vq->num)) {
2997 			vq_err(vq, "Desc index is %u > %u, head = %u",
2998 			       i, vq->num, head);
2999 			return -EINVAL;
3000 		}
3001 		if (unlikely(++found > vq->num)) {
3002 			vq_err(vq, "Loop detected: last one at %u "
3003 			       "vq size %u head %u\n",
3004 			       i, vq->num, head);
3005 			return -EINVAL;
3006 		}
3007 		ret = vhost_get_desc(vq, &desc, i);
3008 		if (unlikely(ret)) {
3009 			vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
3010 			       i, vq->desc + i);
3011 			return -EFAULT;
3012 		}
3013 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
3014 			ret = get_indirect(vq, iov, iov_size,
3015 					   out_num, in_num,
3016 					   log, log_num, &desc);
3017 			if (unlikely(ret < 0)) {
3018 				if (ret != -EAGAIN)
3019 					vq_err(vq, "Failure detected "
3020 						"in indirect descriptor at idx %d\n", i);
3021 				return ret;
3022 			}
3023 			++c;
3024 			continue;
3025 		}
3026 
3027 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
3028 			access = VHOST_ACCESS_WO;
3029 		else
3030 			access = VHOST_ACCESS_RO;
3031 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
3032 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
3033 				     iov_size - iov_count, access);
3034 		if (unlikely(ret < 0)) {
3035 			if (ret != -EAGAIN)
3036 				vq_err(vq, "Translation failure %d descriptor idx %d\n",
3037 					ret, i);
3038 			return ret;
3039 		}
3040 		if (access == VHOST_ACCESS_WO) {
3041 			/* If this is an input descriptor,
3042 			 * increment that count. */
3043 			*in_num += ret;
3044 			if (unlikely(log && ret)) {
3045 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
3046 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
3047 				++*log_num;
3048 			}
3049 		} else {
3050 			/* If it's an output descriptor, they're all supposed
3051 			 * to come before any input descriptors. */
3052 			if (unlikely(*in_num)) {
3053 				vq_err(vq, "Descriptor has out after in: "
3054 				       "idx %d\n", i);
3055 				return -EINVAL;
3056 			}
3057 			*out_num += ret;
3058 		}
3059 		++c;
3060 	} while ((i = next_desc(vq, &desc)) != -1);
3061 
3062 	/* On success, increment avail index. */
3063 	vq->last_avail_idx++;
3064 	vq->next_avail_head += c;
3065 
3066 	if (ndesc)
3067 		*ndesc = c;
3068 
3069 	/* Assume notifications from guest are disabled at this point,
3070 	 * if they aren't we would need to update avail_event index. */
3071 	BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
3072 	return head;
3073 }
3074 EXPORT_SYMBOL_GPL(vhost_get_vq_desc_n);
3075 
3076 /* This looks in the virtqueue and for the first available buffer, and converts
3077  * it to an iovec for convenient access.  Since descriptors consist of some
3078  * number of output then some number of input descriptors, it's actually two
3079  * iovecs, but we pack them into one and note how many of each there were.
3080  *
3081  * This function returns the descriptor number found, or vq->num (which is
3082  * never a valid descriptor number) if none was found.  A negative code is
3083  * returned on error.
3084  */
3085 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
3086 		      struct iovec iov[], unsigned int iov_size,
3087 		      unsigned int *out_num, unsigned int *in_num,
3088 		      struct vhost_log *log, unsigned int *log_num)
3089 {
3090 	return vhost_get_vq_desc_n(vq, iov, iov_size, out_num, in_num,
3091 				   log, log_num, NULL);
3092 }
3093 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
3094 
3095 /**
3096  * vhost_discard_vq_desc - Reverse the effect of vhost_get_vq_desc_n()
3097  * @vq: target virtqueue
3098  * @nbufs: number of buffers to roll back
3099  * @ndesc: number of descriptors to roll back
3100  *
3101  * Rewinds the internal consumer cursors after a failed attempt to use buffers
3102  * returned by vhost_get_vq_desc_n().
3103  */
3104 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int nbufs,
3105 			   unsigned int ndesc)
3106 {
3107 	vq->next_avail_head -= ndesc;
3108 	vq->last_avail_idx -= nbufs;
3109 }
3110 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
3111 
3112 /* After we've used one of their buffers, we tell them about it.  We'll then
3113  * want to notify the guest, using eventfd. */
3114 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
3115 {
3116 	struct vring_used_elem heads = {
3117 		cpu_to_vhost32(vq, head),
3118 		cpu_to_vhost32(vq, len)
3119 	};
3120 	u16 nheads = 1;
3121 
3122 	return vhost_add_used_n(vq, &heads, &nheads, 1);
3123 }
3124 EXPORT_SYMBOL_GPL(vhost_add_used);
3125 
3126 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
3127 			    struct vring_used_elem *heads,
3128 			    unsigned count)
3129 {
3130 	vring_used_elem_t __user *used;
3131 	u16 old, new;
3132 	int start;
3133 
3134 	start = vq->last_used_idx & (vq->num - 1);
3135 	used = vq->used->ring + start;
3136 	if (vhost_put_used(vq, heads, start, count)) {
3137 		vq_err(vq, "Failed to write used");
3138 		return -EFAULT;
3139 	}
3140 	if (unlikely(vq->log_used)) {
3141 		/* Make sure data is seen before log. */
3142 		smp_wmb();
3143 		/* Log used ring entry write. */
3144 		log_used(vq, ((void __user *)used - (void __user *)vq->used),
3145 			 count * sizeof *used);
3146 	}
3147 	old = vq->last_used_idx;
3148 	new = (vq->last_used_idx += count);
3149 	/* If the driver never bothers to signal in a very long while,
3150 	 * used index might wrap around. If that happens, invalidate
3151 	 * signalled_used index we stored. TODO: make sure driver
3152 	 * signals at least once in 2^16 and remove this. */
3153 	if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
3154 		vq->signalled_used_valid = false;
3155 	return 0;
3156 }
3157 
3158 static int vhost_add_used_n_ooo(struct vhost_virtqueue *vq,
3159 				struct vring_used_elem *heads,
3160 				unsigned count)
3161 {
3162 	int start, n, r;
3163 
3164 	start = vq->last_used_idx & (vq->num - 1);
3165 	n = vq->num - start;
3166 	if (n < count) {
3167 		r = __vhost_add_used_n(vq, heads, n);
3168 		if (r < 0)
3169 			return r;
3170 		heads += n;
3171 		count -= n;
3172 	}
3173 	return __vhost_add_used_n(vq, heads, count);
3174 }
3175 
3176 static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,
3177 				     struct vring_used_elem *heads,
3178 				     const u16 *nheads,
3179 				     unsigned count)
3180 {
3181 	vring_used_elem_t __user *used;
3182 	u16 old, new = vq->last_used_idx;
3183 	unsigned int total = 0;
3184 	int start, i;
3185 
3186 	if (!nheads)
3187 		return -EINVAL;
3188 
3189 	start = vq->last_used_idx & (vq->num - 1);
3190 
3191 	for (i = 0; i < count; i++) {
3192 		total += nheads[i];
3193 		if (unlikely(total > vq->num)) {
3194 			vq_err(vq, "Added %u > %u used heads\n",
3195 			       total, vq->num);
3196 			return -EINVAL;
3197 		}
3198 		if (vhost_put_used(vq, &heads[i], start, 1)) {
3199 			vq_err(vq, "Failed to write used");
3200 			return -EFAULT;
3201 		}
3202 		start += nheads[i];
3203 		new += nheads[i];
3204 		start &= vq->num - 1;
3205 	}
3206 
3207 	if (unlikely(vq->log_used)) {
3208 		unsigned int log_count = 0;
3209 		int log_start = 0, next;
3210 
3211 		/* Make sure data is seen before log. */
3212 		smp_wmb();
3213 		/* Log contiguous runs of used ring entries that were written. */
3214 		start = vq->last_used_idx & (vq->num - 1);
3215 		for (i = 0; i < count; i++) {
3216 			if (!log_count)
3217 				log_start = start;
3218 			log_count++;
3219 
3220 			next = start + nheads[i];
3221 			if (next >= vq->num)
3222 				next -= vq->num;
3223 			if (i + 1 == count || next != start + 1) {
3224 				used = vq->used->ring + log_start;
3225 				log_used(vq,
3226 					 ((void __user *)used -
3227 					  (void __user *)vq->used),
3228 					 log_count * sizeof(*used));
3229 				log_count = 0;
3230 			}
3231 			start = next;
3232 		}
3233 	}
3234 
3235 	old = vq->last_used_idx;
3236 	vq->last_used_idx = new;
3237 	/* If the driver never bothers to signal in a very long while,
3238 	 * used index might wrap around. If that happens, invalidate
3239 	 * signalled_used index we stored. TODO: make sure driver
3240 	 * signals at least once in 2^16 and remove this. */
3241 	if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
3242 		vq->signalled_used_valid = false;
3243 	return 0;
3244 }
3245 
3246 /* After we've used one of their buffers, we tell them about it.  We'll then
3247  * want to notify the guest, using eventfd. */
3248 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
3249 		     u16 *nheads, unsigned count)
3250 {
3251 	bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER);
3252 	int r;
3253 
3254 	if (unlikely(count > vq->num)) {
3255 		vq_err(vq, "Added %u > %u used entries\n", count, vq->num);
3256 		return -EINVAL;
3257 	}
3258 
3259 	if (!in_order || !nheads)
3260 		r = vhost_add_used_n_ooo(vq, heads, count);
3261 	else
3262 		r = vhost_add_used_n_in_order(vq, heads, nheads, count);
3263 
3264 	if (r < 0)
3265 		return r;
3266 
3267 	/* Make sure buffer is written before we update index. */
3268 	smp_wmb();
3269 	if (vhost_put_used_idx(vq)) {
3270 		vq_err(vq, "Failed to increment used idx");
3271 		return -EFAULT;
3272 	}
3273 	if (unlikely(vq->log_used)) {
3274 		/* Make sure used idx is seen before log. */
3275 		smp_wmb();
3276 		/* Log used index update. */
3277 		log_used(vq, offsetof(struct vring_used, idx),
3278 			 sizeof vq->used->idx);
3279 		if (vq->log_ctx)
3280 			eventfd_signal(vq->log_ctx);
3281 	}
3282 	return r;
3283 }
3284 EXPORT_SYMBOL_GPL(vhost_add_used_n);
3285 
3286 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3287 {
3288 	__u16 old, new;
3289 	__virtio16 event;
3290 	bool v;
3291 	/* Flush out used index updates. This is paired
3292 	 * with the barrier that the Guest executes when enabling
3293 	 * interrupts. */
3294 	smp_mb();
3295 
3296 	if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
3297 	    unlikely(vq->avail_idx == vq->last_avail_idx))
3298 		return true;
3299 
3300 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3301 		__virtio16 flags;
3302 		if (vhost_get_avail_flags(vq, &flags)) {
3303 			vq_err(vq, "Failed to get flags");
3304 			return true;
3305 		}
3306 		return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
3307 	}
3308 	old = vq->signalled_used;
3309 	v = vq->signalled_used_valid;
3310 	new = vq->signalled_used = vq->last_used_idx;
3311 	vq->signalled_used_valid = true;
3312 
3313 	if (unlikely(!v))
3314 		return true;
3315 
3316 	if (vhost_get_used_event(vq, &event)) {
3317 		vq_err(vq, "Failed to get used event idx");
3318 		return true;
3319 	}
3320 	return vring_need_event(vhost16_to_cpu(vq, event), new, old);
3321 }
3322 
3323 /* This actually signals the guest, using eventfd. */
3324 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3325 {
3326 	/* Signal the Guest tell them we used something up. */
3327 	if (vq->call_ctx.ctx && vhost_notify(dev, vq))
3328 		eventfd_signal(vq->call_ctx.ctx);
3329 }
3330 EXPORT_SYMBOL_GPL(vhost_signal);
3331 
3332 /* And here's the combo meal deal.  Supersize me! */
3333 void vhost_add_used_and_signal(struct vhost_dev *dev,
3334 			       struct vhost_virtqueue *vq,
3335 			       unsigned int head, int len)
3336 {
3337 	vhost_add_used(vq, head, len);
3338 	vhost_signal(dev, vq);
3339 }
3340 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
3341 
3342 /* multi-buffer version of vhost_add_used_and_signal */
3343 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
3344 				 struct vhost_virtqueue *vq,
3345 				 struct vring_used_elem *heads,
3346 				 u16 *nheads,
3347 				 unsigned count)
3348 {
3349 	vhost_add_used_n(vq, heads, nheads, count);
3350 	vhost_signal(dev, vq);
3351 }
3352 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
3353 
3354 /* return true if we're sure that available ring is empty */
3355 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3356 {
3357 	int r;
3358 
3359 	if (vq->avail_idx != vq->last_avail_idx)
3360 		return false;
3361 
3362 	r = vhost_get_avail_idx(vq);
3363 
3364 	/* Note: we treat error as non-empty here */
3365 	return r == 0;
3366 }
3367 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
3368 
3369 /* OK, now we need to know about added descriptors. */
3370 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3371 {
3372 	int r;
3373 
3374 	if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
3375 		return false;
3376 	vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
3377 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3378 		r = vhost_update_used_flags(vq);
3379 		if (r) {
3380 			vq_err(vq, "Failed to enable notification at %p: %d\n",
3381 			       &vq->used->flags, r);
3382 			return false;
3383 		}
3384 	} else {
3385 		r = vhost_update_avail_event(vq);
3386 		if (r) {
3387 			vq_err(vq, "Failed to update avail event index at %p: %d\n",
3388 			       vhost_avail_event(vq), r);
3389 			return false;
3390 		}
3391 	}
3392 	/* They could have slipped one in as we were doing that: make
3393 	 * sure it's written, then check again. */
3394 	smp_mb();
3395 
3396 	r = vhost_get_avail_idx(vq);
3397 	/* Note: we treat error as empty here */
3398 	if (unlikely(r < 0))
3399 		return false;
3400 
3401 	return r;
3402 }
3403 EXPORT_SYMBOL_GPL(vhost_enable_notify);
3404 
3405 /* We don't need to be notified again. */
3406 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3407 {
3408 	int r;
3409 
3410 	if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
3411 		return;
3412 	vq->used_flags |= VRING_USED_F_NO_NOTIFY;
3413 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3414 		r = vhost_update_used_flags(vq);
3415 		if (r)
3416 			vq_err(vq, "Failed to disable notification at %p: %d\n",
3417 			       &vq->used->flags, r);
3418 	}
3419 }
3420 EXPORT_SYMBOL_GPL(vhost_disable_notify);
3421 
3422 /* Create a new message. */
3423 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
3424 {
3425 	/* Make sure all padding within the structure is initialized. */
3426 	struct vhost_msg_node *node = kzalloc_obj(*node);
3427 	if (!node)
3428 		return NULL;
3429 
3430 	node->vq = vq;
3431 	node->msg.type = type;
3432 	return node;
3433 }
3434 EXPORT_SYMBOL_GPL(vhost_new_msg);
3435 
3436 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
3437 		       struct vhost_msg_node *node)
3438 {
3439 	spin_lock(&dev->iotlb_lock);
3440 	list_add_tail(&node->node, head);
3441 	spin_unlock(&dev->iotlb_lock);
3442 
3443 	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
3444 }
3445 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
3446 
3447 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
3448 					 struct list_head *head)
3449 {
3450 	struct vhost_msg_node *node = NULL;
3451 
3452 	spin_lock(&dev->iotlb_lock);
3453 	if (!list_empty(head)) {
3454 		node = list_first_entry(head, struct vhost_msg_node,
3455 					node);
3456 		list_del(&node->node);
3457 	}
3458 	spin_unlock(&dev->iotlb_lock);
3459 
3460 	return node;
3461 }
3462 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
3463 
3464 void vhost_set_backend_features(struct vhost_dev *dev, u64 features)
3465 {
3466 	struct vhost_virtqueue *vq;
3467 	int i;
3468 
3469 	mutex_lock(&dev->mutex);
3470 	for (i = 0; i < dev->nvqs; ++i) {
3471 		vq = dev->vqs[i];
3472 		mutex_lock(&vq->mutex);
3473 		vq->acked_backend_features = features;
3474 		mutex_unlock(&vq->mutex);
3475 	}
3476 	mutex_unlock(&dev->mutex);
3477 }
3478 EXPORT_SYMBOL_GPL(vhost_set_backend_features);
3479 
3480 MODULE_VERSION("0.0.1");
3481 MODULE_LICENSE("GPL v2");
3482 MODULE_AUTHOR("Michael S. Tsirkin");
3483 MODULE_DESCRIPTION("Host kernel accelerator for virtio");
3484