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