xref: /linux/drivers/vhost/vhost.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
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 /* TODO: This is really inefficient.  We need something like get_user()
2531  * (instruction directly accesses the data, with an exception table entry
2532  * returning -EFAULT). See Documentation/arch/x86/exception-tables.rst.
2533  */
2534 static int set_bit_to_user(int nr, void __user *addr)
2535 {
2536 	unsigned long log = (unsigned long)addr;
2537 	struct page *page;
2538 	void *base;
2539 	int bit = nr + (log % PAGE_SIZE) * 8;
2540 	int r;
2541 
2542 	r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page);
2543 	if (r < 0)
2544 		return r;
2545 	BUG_ON(r != 1);
2546 	base = kmap_atomic(page);
2547 	set_bit(bit, base);
2548 	kunmap_atomic(base);
2549 	unpin_user_pages_dirty_lock(&page, 1, true);
2550 	return 0;
2551 }
2552 
2553 static int log_write(void __user *log_base,
2554 		     u64 write_address, u64 write_length)
2555 {
2556 	u64 write_page = write_address / VHOST_PAGE_SIZE;
2557 	int r;
2558 
2559 	if (!write_length)
2560 		return 0;
2561 	write_length += write_address % VHOST_PAGE_SIZE;
2562 	for (;;) {
2563 		u64 base = (u64)(unsigned long)log_base;
2564 		u64 log = base + write_page / 8;
2565 		int bit = write_page % 8;
2566 		if ((u64)(unsigned long)log != log)
2567 			return -EFAULT;
2568 		r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
2569 		if (r < 0)
2570 			return r;
2571 		if (write_length <= VHOST_PAGE_SIZE)
2572 			break;
2573 		write_length -= VHOST_PAGE_SIZE;
2574 		write_page += 1;
2575 	}
2576 	return r;
2577 }
2578 
2579 static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
2580 {
2581 	struct vhost_iotlb *umem = vq->umem;
2582 	struct vhost_iotlb_map *u;
2583 	u64 start, end, l, min;
2584 	int r;
2585 	bool hit = false;
2586 
2587 	while (len) {
2588 		min = len;
2589 		/* More than one GPAs can be mapped into a single HVA. So
2590 		 * iterate all possible umems here to be safe.
2591 		 */
2592 		list_for_each_entry(u, &umem->list, link) {
2593 			if (u->addr > hva - 1 + len ||
2594 			    u->addr - 1 + u->size < hva)
2595 				continue;
2596 			start = max(u->addr, hva);
2597 			end = min(u->addr - 1 + u->size, hva - 1 + len);
2598 			l = end - start + 1;
2599 			r = log_write(vq->log_base,
2600 				      u->start + start - u->addr,
2601 				      l);
2602 			if (r < 0)
2603 				return r;
2604 			hit = true;
2605 			min = min(l, min);
2606 		}
2607 
2608 		if (!hit)
2609 			return -EFAULT;
2610 
2611 		len -= min;
2612 		hva += min;
2613 	}
2614 
2615 	return 0;
2616 }
2617 
2618 static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
2619 {
2620 	struct iovec *iov = vq->log_iov;
2621 	int i, ret;
2622 
2623 	if (!vq->iotlb)
2624 		return log_write(vq->log_base, vq->log_addr + used_offset, len);
2625 
2626 	ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
2627 			     len, iov, 64, VHOST_ACCESS_WO);
2628 	if (ret < 0)
2629 		return ret;
2630 
2631 	for (i = 0; i < ret; i++) {
2632 		ret = log_write_hva(vq,	(uintptr_t)iov[i].iov_base,
2633 				    iov[i].iov_len);
2634 		if (ret)
2635 			return ret;
2636 	}
2637 
2638 	return 0;
2639 }
2640 
2641 /*
2642  * vhost_log_write() - Log in dirty page bitmap
2643  * @vq:      vhost virtqueue.
2644  * @log:     Array of dirty memory in GPA.
2645  * @log_num: Size of vhost_log arrary.
2646  * @len:     The total length of memory buffer to log in the dirty bitmap.
2647  *	     Some drivers may only partially use pages shared via the last
2648  *	     vring descriptor (i.e. vhost-net RX buffer).
2649  *	     Use (len == U64_MAX) to indicate the driver would log all
2650  *           pages of vring descriptors.
2651  * @iov:     Array of dirty memory in HVA.
2652  * @count:   Size of iovec array.
2653  */
2654 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
2655 		    unsigned int log_num, u64 len, struct iovec *iov, int count)
2656 {
2657 	int i, r;
2658 
2659 	/* Make sure data written is seen before log. */
2660 	smp_wmb();
2661 
2662 	if (vq->iotlb) {
2663 		for (i = 0; i < count; i++) {
2664 			r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
2665 					  iov[i].iov_len);
2666 			if (r < 0)
2667 				return r;
2668 		}
2669 		return 0;
2670 	}
2671 
2672 	for (i = 0; i < log_num; ++i) {
2673 		u64 l = min(log[i].len, len);
2674 		r = log_write(vq->log_base, log[i].addr, l);
2675 		if (r < 0)
2676 			return r;
2677 
2678 		if (len != U64_MAX)
2679 			len -= l;
2680 	}
2681 
2682 	if (vq->log_ctx)
2683 		eventfd_signal(vq->log_ctx);
2684 
2685 	return 0;
2686 }
2687 EXPORT_SYMBOL_GPL(vhost_log_write);
2688 
2689 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
2690 {
2691 	void __user *used;
2692 	if (vhost_put_used_flags(vq))
2693 		return -EFAULT;
2694 	if (unlikely(vq->log_used)) {
2695 		/* Make sure the flag is seen before log. */
2696 		smp_wmb();
2697 		/* Log used flag write. */
2698 		used = &vq->used->flags;
2699 		log_used(vq, (used - (void __user *)vq->used),
2700 			 sizeof vq->used->flags);
2701 		if (vq->log_ctx)
2702 			eventfd_signal(vq->log_ctx);
2703 	}
2704 	return 0;
2705 }
2706 
2707 static int vhost_update_avail_event(struct vhost_virtqueue *vq)
2708 {
2709 	if (vhost_put_avail_event(vq))
2710 		return -EFAULT;
2711 	if (unlikely(vq->log_used)) {
2712 		void __user *used;
2713 		/* Make sure the event is seen before log. */
2714 		smp_wmb();
2715 		/* Log avail event write */
2716 		used = vhost_avail_event(vq);
2717 		log_used(vq, (used - (void __user *)vq->used),
2718 			 sizeof *vhost_avail_event(vq));
2719 		if (vq->log_ctx)
2720 			eventfd_signal(vq->log_ctx);
2721 	}
2722 	return 0;
2723 }
2724 
2725 int vhost_vq_init_access(struct vhost_virtqueue *vq)
2726 {
2727 	__virtio16 last_used_idx;
2728 	int r;
2729 	bool is_le = vq->is_le;
2730 
2731 	if (!vq->private_data)
2732 		return 0;
2733 
2734 	vhost_init_is_le(vq);
2735 
2736 	r = vhost_update_used_flags(vq);
2737 	if (r)
2738 		goto err;
2739 	vq->signalled_used_valid = false;
2740 	if (!vq->iotlb &&
2741 	    !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
2742 		r = -EFAULT;
2743 		goto err;
2744 	}
2745 	r = vhost_get_used_idx(vq, &last_used_idx);
2746 	if (r) {
2747 		vq_err(vq, "Can't access used idx at %p\n",
2748 		       &vq->used->idx);
2749 		goto err;
2750 	}
2751 	vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
2752 	return 0;
2753 
2754 err:
2755 	vq->is_le = is_le;
2756 	return r;
2757 }
2758 EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2759 
2760 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
2761 			  struct iovec iov[], int iov_size, int access)
2762 {
2763 	const struct vhost_iotlb_map *map;
2764 	struct vhost_dev *dev = vq->dev;
2765 	struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
2766 	struct iovec *_iov;
2767 	u64 s = 0, last = addr + len - 1;
2768 	int ret = 0;
2769 
2770 	while ((u64)len > s) {
2771 		u64 size;
2772 		if (unlikely(ret >= iov_size)) {
2773 			ret = -ENOBUFS;
2774 			break;
2775 		}
2776 
2777 		map = vhost_iotlb_itree_first(umem, addr, last);
2778 		if (map == NULL || map->start > addr) {
2779 			if (umem != dev->iotlb) {
2780 				ret = -EFAULT;
2781 				break;
2782 			}
2783 			ret = -EAGAIN;
2784 			break;
2785 		} else if (!(map->perm & access)) {
2786 			ret = -EPERM;
2787 			break;
2788 		}
2789 
2790 		_iov = iov + ret;
2791 		size = map->size - addr + map->start;
2792 		_iov->iov_len = min((u64)len - s, size);
2793 		_iov->iov_base = (void __user *)(unsigned long)
2794 				 (map->addr + addr - map->start);
2795 		s += size;
2796 		addr += size;
2797 		++ret;
2798 	}
2799 
2800 	if (ret == -EAGAIN)
2801 		vhost_iotlb_miss(vq, addr, access);
2802 	return ret;
2803 }
2804 
2805 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
2806  * function returns the next descriptor in the chain,
2807  * or -1U if we're at the end. */
2808 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
2809 {
2810 	unsigned int next;
2811 
2812 	/* If this descriptor says it doesn't chain, we're done. */
2813 	if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
2814 		return -1U;
2815 
2816 	/* Check they're not leading us off end of descriptors. */
2817 	next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
2818 	return next;
2819 }
2820 
2821 static int get_indirect(struct vhost_virtqueue *vq,
2822 			struct iovec iov[], unsigned int iov_size,
2823 			unsigned int *out_num, unsigned int *in_num,
2824 			struct vhost_log *log, unsigned int *log_num,
2825 			struct vring_desc *indirect)
2826 {
2827 	struct vring_desc desc;
2828 	unsigned int i = 0, count, found = 0;
2829 	u32 len = vhost32_to_cpu(vq, indirect->len);
2830 	struct iov_iter from;
2831 	int ret, access;
2832 
2833 	/* Sanity check */
2834 	if (unlikely(len % sizeof desc)) {
2835 		vq_err(vq, "Invalid length in indirect descriptor: "
2836 		       "len 0x%llx not multiple of 0x%zx\n",
2837 		       (unsigned long long)len,
2838 		       sizeof desc);
2839 		return -EINVAL;
2840 	}
2841 
2842 	ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
2843 			     UIO_MAXIOV, VHOST_ACCESS_RO);
2844 	if (unlikely(ret < 0)) {
2845 		if (ret != -EAGAIN)
2846 			vq_err(vq, "Translation failure %d in indirect.\n", ret);
2847 		return ret;
2848 	}
2849 	iov_iter_init(&from, ITER_SOURCE, vq->indirect, ret, len);
2850 	count = len / sizeof desc;
2851 	/* Buffers are chained via a 16 bit next field, so
2852 	 * we can have at most 2^16 of these. */
2853 	if (unlikely(count > USHRT_MAX + 1)) {
2854 		vq_err(vq, "Indirect buffer length too big: %d\n",
2855 		       indirect->len);
2856 		return -E2BIG;
2857 	}
2858 
2859 	do {
2860 		unsigned iov_count = *in_num + *out_num;
2861 		if (unlikely(++found > count)) {
2862 			vq_err(vq, "Loop detected: last one at %u "
2863 			       "indirect size %u\n",
2864 			       i, count);
2865 			return -EINVAL;
2866 		}
2867 		if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
2868 			vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
2869 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2870 			return -EINVAL;
2871 		}
2872 		if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
2873 			vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
2874 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
2875 			return -EINVAL;
2876 		}
2877 
2878 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2879 			access = VHOST_ACCESS_WO;
2880 		else
2881 			access = VHOST_ACCESS_RO;
2882 
2883 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2884 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
2885 				     iov_size - iov_count, access);
2886 		if (unlikely(ret < 0)) {
2887 			if (ret != -EAGAIN)
2888 				vq_err(vq, "Translation failure %d indirect idx %d\n",
2889 					ret, i);
2890 			return ret;
2891 		}
2892 		/* If this is an input descriptor, increment that count. */
2893 		if (access == VHOST_ACCESS_WO) {
2894 			*in_num += ret;
2895 			if (unlikely(log && ret)) {
2896 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2897 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
2898 				++*log_num;
2899 			}
2900 		} else {
2901 			/* If it's an output descriptor, they're all supposed
2902 			 * to come before any input descriptors. */
2903 			if (unlikely(*in_num)) {
2904 				vq_err(vq, "Indirect descriptor "
2905 				       "has out after in: idx %d\n", i);
2906 				return -EINVAL;
2907 			}
2908 			*out_num += ret;
2909 		}
2910 	} while ((i = next_desc(vq, &desc)) != -1);
2911 	return 0;
2912 }
2913 
2914 /**
2915  * vhost_get_vq_desc_n - Fetch the next available descriptor chain and build iovecs
2916  * @vq: target virtqueue
2917  * @iov: array that receives the scatter/gather segments
2918  * @iov_size: capacity of @iov in elements
2919  * @out_num: the number of output segments
2920  * @in_num: the number of input segments
2921  * @log: optional array to record addr/len for each writable segment; NULL if unused
2922  * @log_num: optional output; number of entries written to @log when provided
2923  * @ndesc: optional output; number of descriptors consumed from the available ring
2924  *         (useful for rollback via vhost_discard_vq_desc)
2925  *
2926  * Extracts one available descriptor chain from @vq and translates guest addresses
2927  * into host iovecs.
2928  *
2929  * On success, advances @vq->last_avail_idx by 1 and @vq->next_avail_head by the
2930  * number of descriptors consumed (also stored via @ndesc when non-NULL).
2931  *
2932  * Return:
2933  * - head index in [0, @vq->num) on success;
2934  * - @vq->num if no descriptor is currently available;
2935  * - negative errno on failure
2936  */
2937 int vhost_get_vq_desc_n(struct vhost_virtqueue *vq,
2938 			struct iovec iov[], unsigned int iov_size,
2939 			unsigned int *out_num, unsigned int *in_num,
2940 			struct vhost_log *log, unsigned int *log_num,
2941 			unsigned int *ndesc)
2942 {
2943 	bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER);
2944 	struct vring_desc desc;
2945 	unsigned int i, head, found = 0;
2946 	u16 last_avail_idx = vq->last_avail_idx;
2947 	__virtio16 ring_head;
2948 	int ret, access, c = 0;
2949 
2950 	if (vq->avail_idx == vq->last_avail_idx) {
2951 		ret = vhost_get_avail_idx(vq);
2952 		if (unlikely(ret < 0))
2953 			return ret;
2954 
2955 		if (!ret)
2956 			return vq->num;
2957 	}
2958 
2959 	if (in_order)
2960 		head = vq->next_avail_head & (vq->num - 1);
2961 	else {
2962 		/* Grab the next descriptor number they're
2963 		 * advertising, and increment the index we've seen. */
2964 		if (unlikely(vhost_get_avail_head(vq, &ring_head,
2965 						  last_avail_idx))) {
2966 			vq_err(vq, "Failed to read head: idx %d address %p\n",
2967 				last_avail_idx,
2968 				&vq->avail->ring[last_avail_idx % vq->num]);
2969 			return -EFAULT;
2970 		}
2971 		head = vhost16_to_cpu(vq, ring_head);
2972 	}
2973 
2974 	/* If their number is silly, that's an error. */
2975 	if (unlikely(head >= vq->num)) {
2976 		vq_err(vq, "Guest says index %u > %u is available",
2977 		       head, vq->num);
2978 		return -EINVAL;
2979 	}
2980 
2981 	/* When we start there are none of either input nor output. */
2982 	*out_num = *in_num = 0;
2983 	if (unlikely(log))
2984 		*log_num = 0;
2985 
2986 	i = head;
2987 	do {
2988 		unsigned iov_count = *in_num + *out_num;
2989 		if (unlikely(i >= vq->num)) {
2990 			vq_err(vq, "Desc index is %u > %u, head = %u",
2991 			       i, vq->num, head);
2992 			return -EINVAL;
2993 		}
2994 		if (unlikely(++found > vq->num)) {
2995 			vq_err(vq, "Loop detected: last one at %u "
2996 			       "vq size %u head %u\n",
2997 			       i, vq->num, head);
2998 			return -EINVAL;
2999 		}
3000 		ret = vhost_get_desc(vq, &desc, i);
3001 		if (unlikely(ret)) {
3002 			vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
3003 			       i, vq->desc + i);
3004 			return -EFAULT;
3005 		}
3006 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
3007 			ret = get_indirect(vq, iov, iov_size,
3008 					   out_num, in_num,
3009 					   log, log_num, &desc);
3010 			if (unlikely(ret < 0)) {
3011 				if (ret != -EAGAIN)
3012 					vq_err(vq, "Failure detected "
3013 						"in indirect descriptor at idx %d\n", i);
3014 				return ret;
3015 			}
3016 			++c;
3017 			continue;
3018 		}
3019 
3020 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
3021 			access = VHOST_ACCESS_WO;
3022 		else
3023 			access = VHOST_ACCESS_RO;
3024 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
3025 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
3026 				     iov_size - iov_count, access);
3027 		if (unlikely(ret < 0)) {
3028 			if (ret != -EAGAIN)
3029 				vq_err(vq, "Translation failure %d descriptor idx %d\n",
3030 					ret, i);
3031 			return ret;
3032 		}
3033 		if (access == VHOST_ACCESS_WO) {
3034 			/* If this is an input descriptor,
3035 			 * increment that count. */
3036 			*in_num += ret;
3037 			if (unlikely(log && ret)) {
3038 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
3039 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
3040 				++*log_num;
3041 			}
3042 		} else {
3043 			/* If it's an output descriptor, they're all supposed
3044 			 * to come before any input descriptors. */
3045 			if (unlikely(*in_num)) {
3046 				vq_err(vq, "Descriptor has out after in: "
3047 				       "idx %d\n", i);
3048 				return -EINVAL;
3049 			}
3050 			*out_num += ret;
3051 		}
3052 		++c;
3053 	} while ((i = next_desc(vq, &desc)) != -1);
3054 
3055 	/* On success, increment avail index. */
3056 	vq->last_avail_idx++;
3057 	vq->next_avail_head += c;
3058 
3059 	if (ndesc)
3060 		*ndesc = c;
3061 
3062 	/* Assume notifications from guest are disabled at this point,
3063 	 * if they aren't we would need to update avail_event index. */
3064 	BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
3065 	return head;
3066 }
3067 EXPORT_SYMBOL_GPL(vhost_get_vq_desc_n);
3068 
3069 /* This looks in the virtqueue and for the first available buffer, and converts
3070  * it to an iovec for convenient access.  Since descriptors consist of some
3071  * number of output then some number of input descriptors, it's actually two
3072  * iovecs, but we pack them into one and note how many of each there were.
3073  *
3074  * This function returns the descriptor number found, or vq->num (which is
3075  * never a valid descriptor number) if none was found.  A negative code is
3076  * returned on error.
3077  */
3078 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
3079 		      struct iovec iov[], unsigned int iov_size,
3080 		      unsigned int *out_num, unsigned int *in_num,
3081 		      struct vhost_log *log, unsigned int *log_num)
3082 {
3083 	return vhost_get_vq_desc_n(vq, iov, iov_size, out_num, in_num,
3084 				   log, log_num, NULL);
3085 }
3086 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
3087 
3088 /**
3089  * vhost_discard_vq_desc - Reverse the effect of vhost_get_vq_desc_n()
3090  * @vq: target virtqueue
3091  * @nbufs: number of buffers to roll back
3092  * @ndesc: number of descriptors to roll back
3093  *
3094  * Rewinds the internal consumer cursors after a failed attempt to use buffers
3095  * returned by vhost_get_vq_desc_n().
3096  */
3097 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int nbufs,
3098 			   unsigned int ndesc)
3099 {
3100 	vq->next_avail_head -= ndesc;
3101 	vq->last_avail_idx -= nbufs;
3102 }
3103 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
3104 
3105 /* After we've used one of their buffers, we tell them about it.  We'll then
3106  * want to notify the guest, using eventfd. */
3107 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
3108 {
3109 	struct vring_used_elem heads = {
3110 		cpu_to_vhost32(vq, head),
3111 		cpu_to_vhost32(vq, len)
3112 	};
3113 	u16 nheads = 1;
3114 
3115 	return vhost_add_used_n(vq, &heads, &nheads, 1);
3116 }
3117 EXPORT_SYMBOL_GPL(vhost_add_used);
3118 
3119 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
3120 			    struct vring_used_elem *heads,
3121 			    unsigned count)
3122 {
3123 	vring_used_elem_t __user *used;
3124 	u16 old, new;
3125 	int start;
3126 
3127 	start = vq->last_used_idx & (vq->num - 1);
3128 	used = vq->used->ring + start;
3129 	if (vhost_put_used(vq, heads, start, count)) {
3130 		vq_err(vq, "Failed to write used");
3131 		return -EFAULT;
3132 	}
3133 	if (unlikely(vq->log_used)) {
3134 		/* Make sure data is seen before log. */
3135 		smp_wmb();
3136 		/* Log used ring entry write. */
3137 		log_used(vq, ((void __user *)used - (void __user *)vq->used),
3138 			 count * sizeof *used);
3139 	}
3140 	old = vq->last_used_idx;
3141 	new = (vq->last_used_idx += count);
3142 	/* If the driver never bothers to signal in a very long while,
3143 	 * used index might wrap around. If that happens, invalidate
3144 	 * signalled_used index we stored. TODO: make sure driver
3145 	 * signals at least once in 2^16 and remove this. */
3146 	if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
3147 		vq->signalled_used_valid = false;
3148 	return 0;
3149 }
3150 
3151 static int vhost_add_used_n_ooo(struct vhost_virtqueue *vq,
3152 				struct vring_used_elem *heads,
3153 				unsigned count)
3154 {
3155 	int start, n, r;
3156 
3157 	start = vq->last_used_idx & (vq->num - 1);
3158 	n = vq->num - start;
3159 	if (n < count) {
3160 		r = __vhost_add_used_n(vq, heads, n);
3161 		if (r < 0)
3162 			return r;
3163 		heads += n;
3164 		count -= n;
3165 	}
3166 	return __vhost_add_used_n(vq, heads, count);
3167 }
3168 
3169 static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,
3170 				     struct vring_used_elem *heads,
3171 				     const u16 *nheads,
3172 				     unsigned count)
3173 {
3174 	vring_used_elem_t __user *used;
3175 	u16 old, new = vq->last_used_idx;
3176 	int start, i;
3177 
3178 	if (!nheads)
3179 		return -EINVAL;
3180 
3181 	start = vq->last_used_idx & (vq->num - 1);
3182 
3183 	for (i = 0; i < count; i++) {
3184 		if (vhost_put_used(vq, &heads[i], start, 1)) {
3185 			vq_err(vq, "Failed to write used");
3186 			return -EFAULT;
3187 		}
3188 		start += nheads[i];
3189 		new += nheads[i];
3190 		start &= vq->num - 1;
3191 	}
3192 
3193 	if (unlikely(vq->log_used)) {
3194 		unsigned int log_count = 0;
3195 		int log_start = 0, next;
3196 
3197 		/* Make sure data is seen before log. */
3198 		smp_wmb();
3199 		/* Log contiguous runs of used ring entries that were written. */
3200 		start = vq->last_used_idx & (vq->num - 1);
3201 		for (i = 0; i < count; i++) {
3202 			if (!log_count)
3203 				log_start = start;
3204 			log_count++;
3205 
3206 			next = start + nheads[i];
3207 			if (next >= vq->num)
3208 				next -= vq->num;
3209 			if (i + 1 == count || next != start + 1) {
3210 				used = vq->used->ring + log_start;
3211 				log_used(vq,
3212 					 ((void __user *)used -
3213 					  (void __user *)vq->used),
3214 					 log_count * sizeof(*used));
3215 				log_count = 0;
3216 			}
3217 			start = next;
3218 		}
3219 	}
3220 
3221 	old = vq->last_used_idx;
3222 	vq->last_used_idx = new;
3223 	/* If the driver never bothers to signal in a very long while,
3224 	 * used index might wrap around. If that happens, invalidate
3225 	 * signalled_used index we stored. TODO: make sure driver
3226 	 * signals at least once in 2^16 and remove this. */
3227 	if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
3228 		vq->signalled_used_valid = false;
3229 	return 0;
3230 }
3231 
3232 /* After we've used one of their buffers, we tell them about it.  We'll then
3233  * want to notify the guest, using eventfd. */
3234 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
3235 		     u16 *nheads, unsigned count)
3236 {
3237 	bool in_order = vhost_has_feature(vq, VIRTIO_F_IN_ORDER);
3238 	int r;
3239 
3240 	if (!in_order || !nheads)
3241 		r = vhost_add_used_n_ooo(vq, heads, count);
3242 	else
3243 		r = vhost_add_used_n_in_order(vq, heads, nheads, count);
3244 
3245 	if (r < 0)
3246 		return r;
3247 
3248 	/* Make sure buffer is written before we update index. */
3249 	smp_wmb();
3250 	if (vhost_put_used_idx(vq)) {
3251 		vq_err(vq, "Failed to increment used idx");
3252 		return -EFAULT;
3253 	}
3254 	if (unlikely(vq->log_used)) {
3255 		/* Make sure used idx is seen before log. */
3256 		smp_wmb();
3257 		/* Log used index update. */
3258 		log_used(vq, offsetof(struct vring_used, idx),
3259 			 sizeof vq->used->idx);
3260 		if (vq->log_ctx)
3261 			eventfd_signal(vq->log_ctx);
3262 	}
3263 	return r;
3264 }
3265 EXPORT_SYMBOL_GPL(vhost_add_used_n);
3266 
3267 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3268 {
3269 	__u16 old, new;
3270 	__virtio16 event;
3271 	bool v;
3272 	/* Flush out used index updates. This is paired
3273 	 * with the barrier that the Guest executes when enabling
3274 	 * interrupts. */
3275 	smp_mb();
3276 
3277 	if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
3278 	    unlikely(vq->avail_idx == vq->last_avail_idx))
3279 		return true;
3280 
3281 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3282 		__virtio16 flags;
3283 		if (vhost_get_avail_flags(vq, &flags)) {
3284 			vq_err(vq, "Failed to get flags");
3285 			return true;
3286 		}
3287 		return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
3288 	}
3289 	old = vq->signalled_used;
3290 	v = vq->signalled_used_valid;
3291 	new = vq->signalled_used = vq->last_used_idx;
3292 	vq->signalled_used_valid = true;
3293 
3294 	if (unlikely(!v))
3295 		return true;
3296 
3297 	if (vhost_get_used_event(vq, &event)) {
3298 		vq_err(vq, "Failed to get used event idx");
3299 		return true;
3300 	}
3301 	return vring_need_event(vhost16_to_cpu(vq, event), new, old);
3302 }
3303 
3304 /* This actually signals the guest, using eventfd. */
3305 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3306 {
3307 	/* Signal the Guest tell them we used something up. */
3308 	if (vq->call_ctx.ctx && vhost_notify(dev, vq))
3309 		eventfd_signal(vq->call_ctx.ctx);
3310 }
3311 EXPORT_SYMBOL_GPL(vhost_signal);
3312 
3313 /* And here's the combo meal deal.  Supersize me! */
3314 void vhost_add_used_and_signal(struct vhost_dev *dev,
3315 			       struct vhost_virtqueue *vq,
3316 			       unsigned int head, int len)
3317 {
3318 	vhost_add_used(vq, head, len);
3319 	vhost_signal(dev, vq);
3320 }
3321 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
3322 
3323 /* multi-buffer version of vhost_add_used_and_signal */
3324 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
3325 				 struct vhost_virtqueue *vq,
3326 				 struct vring_used_elem *heads,
3327 				 u16 *nheads,
3328 				 unsigned count)
3329 {
3330 	vhost_add_used_n(vq, heads, nheads, count);
3331 	vhost_signal(dev, vq);
3332 }
3333 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
3334 
3335 /* return true if we're sure that available ring is empty */
3336 bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3337 {
3338 	int r;
3339 
3340 	if (vq->avail_idx != vq->last_avail_idx)
3341 		return false;
3342 
3343 	r = vhost_get_avail_idx(vq);
3344 
3345 	/* Note: we treat error as non-empty here */
3346 	return r == 0;
3347 }
3348 EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
3349 
3350 /* OK, now we need to know about added descriptors. */
3351 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3352 {
3353 	int r;
3354 
3355 	if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
3356 		return false;
3357 	vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
3358 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3359 		r = vhost_update_used_flags(vq);
3360 		if (r) {
3361 			vq_err(vq, "Failed to enable notification at %p: %d\n",
3362 			       &vq->used->flags, r);
3363 			return false;
3364 		}
3365 	} else {
3366 		r = vhost_update_avail_event(vq);
3367 		if (r) {
3368 			vq_err(vq, "Failed to update avail event index at %p: %d\n",
3369 			       vhost_avail_event(vq), r);
3370 			return false;
3371 		}
3372 	}
3373 	/* They could have slipped one in as we were doing that: make
3374 	 * sure it's written, then check again. */
3375 	smp_mb();
3376 
3377 	r = vhost_get_avail_idx(vq);
3378 	/* Note: we treat error as empty here */
3379 	if (unlikely(r < 0))
3380 		return false;
3381 
3382 	return r;
3383 }
3384 EXPORT_SYMBOL_GPL(vhost_enable_notify);
3385 
3386 /* We don't need to be notified again. */
3387 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3388 {
3389 	int r;
3390 
3391 	if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
3392 		return;
3393 	vq->used_flags |= VRING_USED_F_NO_NOTIFY;
3394 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3395 		r = vhost_update_used_flags(vq);
3396 		if (r)
3397 			vq_err(vq, "Failed to disable notification at %p: %d\n",
3398 			       &vq->used->flags, r);
3399 	}
3400 }
3401 EXPORT_SYMBOL_GPL(vhost_disable_notify);
3402 
3403 /* Create a new message. */
3404 struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
3405 {
3406 	/* Make sure all padding within the structure is initialized. */
3407 	struct vhost_msg_node *node = kzalloc_obj(*node);
3408 	if (!node)
3409 		return NULL;
3410 
3411 	node->vq = vq;
3412 	node->msg.type = type;
3413 	return node;
3414 }
3415 EXPORT_SYMBOL_GPL(vhost_new_msg);
3416 
3417 void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
3418 		       struct vhost_msg_node *node)
3419 {
3420 	spin_lock(&dev->iotlb_lock);
3421 	list_add_tail(&node->node, head);
3422 	spin_unlock(&dev->iotlb_lock);
3423 
3424 	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
3425 }
3426 EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
3427 
3428 struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
3429 					 struct list_head *head)
3430 {
3431 	struct vhost_msg_node *node = NULL;
3432 
3433 	spin_lock(&dev->iotlb_lock);
3434 	if (!list_empty(head)) {
3435 		node = list_first_entry(head, struct vhost_msg_node,
3436 					node);
3437 		list_del(&node->node);
3438 	}
3439 	spin_unlock(&dev->iotlb_lock);
3440 
3441 	return node;
3442 }
3443 EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
3444 
3445 void vhost_set_backend_features(struct vhost_dev *dev, u64 features)
3446 {
3447 	struct vhost_virtqueue *vq;
3448 	int i;
3449 
3450 	mutex_lock(&dev->mutex);
3451 	for (i = 0; i < dev->nvqs; ++i) {
3452 		vq = dev->vqs[i];
3453 		mutex_lock(&vq->mutex);
3454 		vq->acked_backend_features = features;
3455 		mutex_unlock(&vq->mutex);
3456 	}
3457 	mutex_unlock(&dev->mutex);
3458 }
3459 EXPORT_SYMBOL_GPL(vhost_set_backend_features);
3460 
3461 MODULE_VERSION("0.0.1");
3462 MODULE_LICENSE("GPL v2");
3463 MODULE_AUTHOR("Michael S. Tsirkin");
3464 MODULE_DESCRIPTION("Host kernel accelerator for virtio");
3465