xref: /linux/drivers/vhost/vhost.c (revision 005438a8eef063495ac059d128eea71b58de50e5)
1 /* Copyright (C) 2009 Red Hat, Inc.
2  * Copyright (C) 2006 Rusty Russell IBM Corporation
3  *
4  * Author: Michael S. Tsirkin <mst@redhat.com>
5  *
6  * Inspiration, some code, and most witty comments come from
7  * Documentation/virtual/lguest/lguest.c, by Rusty Russell
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.
10  *
11  * Generic code for virtio server in host kernel.
12  */
13 
14 #include <linux/eventfd.h>
15 #include <linux/vhost.h>
16 #include <linux/uio.h>
17 #include <linux/mm.h>
18 #include <linux/mmu_context.h>
19 #include <linux/miscdevice.h>
20 #include <linux/mutex.h>
21 #include <linux/poll.h>
22 #include <linux/file.h>
23 #include <linux/highmem.h>
24 #include <linux/slab.h>
25 #include <linux/kthread.h>
26 #include <linux/cgroup.h>
27 #include <linux/module.h>
28 
29 #include "vhost.h"
30 
31 enum {
32 	VHOST_MEMORY_MAX_NREGIONS = 64,
33 	VHOST_MEMORY_F_LOG = 0x1,
34 };
35 
36 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
37 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
38 
39 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
40 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
41 {
42 	vq->user_be = !virtio_legacy_is_little_endian();
43 }
44 
45 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
46 {
47 	struct vhost_vring_state s;
48 
49 	if (vq->private_data)
50 		return -EBUSY;
51 
52 	if (copy_from_user(&s, argp, sizeof(s)))
53 		return -EFAULT;
54 
55 	if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
56 	    s.num != VHOST_VRING_BIG_ENDIAN)
57 		return -EINVAL;
58 
59 	vq->user_be = s.num;
60 
61 	return 0;
62 }
63 
64 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
65 				   int __user *argp)
66 {
67 	struct vhost_vring_state s = {
68 		.index = idx,
69 		.num = vq->user_be
70 	};
71 
72 	if (copy_to_user(argp, &s, sizeof(s)))
73 		return -EFAULT;
74 
75 	return 0;
76 }
77 
78 static void vhost_init_is_le(struct vhost_virtqueue *vq)
79 {
80 	/* Note for legacy virtio: user_be is initialized at reset time
81 	 * according to the host endianness. If userspace does not set an
82 	 * explicit endianness, the default behavior is native endian, as
83 	 * expected by legacy virtio.
84 	 */
85 	vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
86 }
87 #else
88 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
89 {
90 }
91 
92 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
93 {
94 	return -ENOIOCTLCMD;
95 }
96 
97 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
98 				   int __user *argp)
99 {
100 	return -ENOIOCTLCMD;
101 }
102 
103 static void vhost_init_is_le(struct vhost_virtqueue *vq)
104 {
105 	if (vhost_has_feature(vq, VIRTIO_F_VERSION_1))
106 		vq->is_le = true;
107 }
108 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
109 
110 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
111 			    poll_table *pt)
112 {
113 	struct vhost_poll *poll;
114 
115 	poll = container_of(pt, struct vhost_poll, table);
116 	poll->wqh = wqh;
117 	add_wait_queue(wqh, &poll->wait);
118 }
119 
120 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
121 			     void *key)
122 {
123 	struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
124 
125 	if (!((unsigned long)key & poll->mask))
126 		return 0;
127 
128 	vhost_poll_queue(poll);
129 	return 0;
130 }
131 
132 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
133 {
134 	INIT_LIST_HEAD(&work->node);
135 	work->fn = fn;
136 	init_waitqueue_head(&work->done);
137 	work->flushing = 0;
138 	work->queue_seq = work->done_seq = 0;
139 }
140 EXPORT_SYMBOL_GPL(vhost_work_init);
141 
142 /* Init poll structure */
143 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
144 		     unsigned long mask, struct vhost_dev *dev)
145 {
146 	init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
147 	init_poll_funcptr(&poll->table, vhost_poll_func);
148 	poll->mask = mask;
149 	poll->dev = dev;
150 	poll->wqh = NULL;
151 
152 	vhost_work_init(&poll->work, fn);
153 }
154 EXPORT_SYMBOL_GPL(vhost_poll_init);
155 
156 /* Start polling a file. We add ourselves to file's wait queue. The caller must
157  * keep a reference to a file until after vhost_poll_stop is called. */
158 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
159 {
160 	unsigned long mask;
161 	int ret = 0;
162 
163 	if (poll->wqh)
164 		return 0;
165 
166 	mask = file->f_op->poll(file, &poll->table);
167 	if (mask)
168 		vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
169 	if (mask & POLLERR) {
170 		if (poll->wqh)
171 			remove_wait_queue(poll->wqh, &poll->wait);
172 		ret = -EINVAL;
173 	}
174 
175 	return ret;
176 }
177 EXPORT_SYMBOL_GPL(vhost_poll_start);
178 
179 /* Stop polling a file. After this function returns, it becomes safe to drop the
180  * file reference. You must also flush afterwards. */
181 void vhost_poll_stop(struct vhost_poll *poll)
182 {
183 	if (poll->wqh) {
184 		remove_wait_queue(poll->wqh, &poll->wait);
185 		poll->wqh = NULL;
186 	}
187 }
188 EXPORT_SYMBOL_GPL(vhost_poll_stop);
189 
190 static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
191 				unsigned seq)
192 {
193 	int left;
194 
195 	spin_lock_irq(&dev->work_lock);
196 	left = seq - work->done_seq;
197 	spin_unlock_irq(&dev->work_lock);
198 	return left <= 0;
199 }
200 
201 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
202 {
203 	unsigned seq;
204 	int flushing;
205 
206 	spin_lock_irq(&dev->work_lock);
207 	seq = work->queue_seq;
208 	work->flushing++;
209 	spin_unlock_irq(&dev->work_lock);
210 	wait_event(work->done, vhost_work_seq_done(dev, work, seq));
211 	spin_lock_irq(&dev->work_lock);
212 	flushing = --work->flushing;
213 	spin_unlock_irq(&dev->work_lock);
214 	BUG_ON(flushing < 0);
215 }
216 EXPORT_SYMBOL_GPL(vhost_work_flush);
217 
218 /* Flush any work that has been scheduled. When calling this, don't hold any
219  * locks that are also used by the callback. */
220 void vhost_poll_flush(struct vhost_poll *poll)
221 {
222 	vhost_work_flush(poll->dev, &poll->work);
223 }
224 EXPORT_SYMBOL_GPL(vhost_poll_flush);
225 
226 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
227 {
228 	unsigned long flags;
229 
230 	spin_lock_irqsave(&dev->work_lock, flags);
231 	if (list_empty(&work->node)) {
232 		list_add_tail(&work->node, &dev->work_list);
233 		work->queue_seq++;
234 		spin_unlock_irqrestore(&dev->work_lock, flags);
235 		wake_up_process(dev->worker);
236 	} else {
237 		spin_unlock_irqrestore(&dev->work_lock, flags);
238 	}
239 }
240 EXPORT_SYMBOL_GPL(vhost_work_queue);
241 
242 void vhost_poll_queue(struct vhost_poll *poll)
243 {
244 	vhost_work_queue(poll->dev, &poll->work);
245 }
246 EXPORT_SYMBOL_GPL(vhost_poll_queue);
247 
248 static void vhost_vq_reset(struct vhost_dev *dev,
249 			   struct vhost_virtqueue *vq)
250 {
251 	vq->num = 1;
252 	vq->desc = NULL;
253 	vq->avail = NULL;
254 	vq->used = NULL;
255 	vq->last_avail_idx = 0;
256 	vq->avail_idx = 0;
257 	vq->last_used_idx = 0;
258 	vq->signalled_used = 0;
259 	vq->signalled_used_valid = false;
260 	vq->used_flags = 0;
261 	vq->log_used = false;
262 	vq->log_addr = -1ull;
263 	vq->private_data = NULL;
264 	vq->acked_features = 0;
265 	vq->log_base = NULL;
266 	vq->error_ctx = NULL;
267 	vq->error = NULL;
268 	vq->kick = NULL;
269 	vq->call_ctx = NULL;
270 	vq->call = NULL;
271 	vq->log_ctx = NULL;
272 	vq->memory = NULL;
273 	vq->is_le = virtio_legacy_is_little_endian();
274 	vhost_vq_reset_user_be(vq);
275 }
276 
277 static int vhost_worker(void *data)
278 {
279 	struct vhost_dev *dev = data;
280 	struct vhost_work *work = NULL;
281 	unsigned uninitialized_var(seq);
282 	mm_segment_t oldfs = get_fs();
283 
284 	set_fs(USER_DS);
285 	use_mm(dev->mm);
286 
287 	for (;;) {
288 		/* mb paired w/ kthread_stop */
289 		set_current_state(TASK_INTERRUPTIBLE);
290 
291 		spin_lock_irq(&dev->work_lock);
292 		if (work) {
293 			work->done_seq = seq;
294 			if (work->flushing)
295 				wake_up_all(&work->done);
296 		}
297 
298 		if (kthread_should_stop()) {
299 			spin_unlock_irq(&dev->work_lock);
300 			__set_current_state(TASK_RUNNING);
301 			break;
302 		}
303 		if (!list_empty(&dev->work_list)) {
304 			work = list_first_entry(&dev->work_list,
305 						struct vhost_work, node);
306 			list_del_init(&work->node);
307 			seq = work->queue_seq;
308 		} else
309 			work = NULL;
310 		spin_unlock_irq(&dev->work_lock);
311 
312 		if (work) {
313 			__set_current_state(TASK_RUNNING);
314 			work->fn(work);
315 			if (need_resched())
316 				schedule();
317 		} else
318 			schedule();
319 
320 	}
321 	unuse_mm(dev->mm);
322 	set_fs(oldfs);
323 	return 0;
324 }
325 
326 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
327 {
328 	kfree(vq->indirect);
329 	vq->indirect = NULL;
330 	kfree(vq->log);
331 	vq->log = NULL;
332 	kfree(vq->heads);
333 	vq->heads = NULL;
334 }
335 
336 /* Helper to allocate iovec buffers for all vqs. */
337 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
338 {
339 	struct vhost_virtqueue *vq;
340 	int i;
341 
342 	for (i = 0; i < dev->nvqs; ++i) {
343 		vq = dev->vqs[i];
344 		vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
345 				       GFP_KERNEL);
346 		vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
347 		vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
348 		if (!vq->indirect || !vq->log || !vq->heads)
349 			goto err_nomem;
350 	}
351 	return 0;
352 
353 err_nomem:
354 	for (; i >= 0; --i)
355 		vhost_vq_free_iovecs(dev->vqs[i]);
356 	return -ENOMEM;
357 }
358 
359 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
360 {
361 	int i;
362 
363 	for (i = 0; i < dev->nvqs; ++i)
364 		vhost_vq_free_iovecs(dev->vqs[i]);
365 }
366 
367 void vhost_dev_init(struct vhost_dev *dev,
368 		    struct vhost_virtqueue **vqs, int nvqs)
369 {
370 	struct vhost_virtqueue *vq;
371 	int i;
372 
373 	dev->vqs = vqs;
374 	dev->nvqs = nvqs;
375 	mutex_init(&dev->mutex);
376 	dev->log_ctx = NULL;
377 	dev->log_file = NULL;
378 	dev->memory = NULL;
379 	dev->mm = NULL;
380 	spin_lock_init(&dev->work_lock);
381 	INIT_LIST_HEAD(&dev->work_list);
382 	dev->worker = NULL;
383 
384 	for (i = 0; i < dev->nvqs; ++i) {
385 		vq = dev->vqs[i];
386 		vq->log = NULL;
387 		vq->indirect = NULL;
388 		vq->heads = NULL;
389 		vq->dev = dev;
390 		mutex_init(&vq->mutex);
391 		vhost_vq_reset(dev, vq);
392 		if (vq->handle_kick)
393 			vhost_poll_init(&vq->poll, vq->handle_kick,
394 					POLLIN, dev);
395 	}
396 }
397 EXPORT_SYMBOL_GPL(vhost_dev_init);
398 
399 /* Caller should have device mutex */
400 long vhost_dev_check_owner(struct vhost_dev *dev)
401 {
402 	/* Are you the owner? If not, I don't think you mean to do that */
403 	return dev->mm == current->mm ? 0 : -EPERM;
404 }
405 EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
406 
407 struct vhost_attach_cgroups_struct {
408 	struct vhost_work work;
409 	struct task_struct *owner;
410 	int ret;
411 };
412 
413 static void vhost_attach_cgroups_work(struct vhost_work *work)
414 {
415 	struct vhost_attach_cgroups_struct *s;
416 
417 	s = container_of(work, struct vhost_attach_cgroups_struct, work);
418 	s->ret = cgroup_attach_task_all(s->owner, current);
419 }
420 
421 static int vhost_attach_cgroups(struct vhost_dev *dev)
422 {
423 	struct vhost_attach_cgroups_struct attach;
424 
425 	attach.owner = current;
426 	vhost_work_init(&attach.work, vhost_attach_cgroups_work);
427 	vhost_work_queue(dev, &attach.work);
428 	vhost_work_flush(dev, &attach.work);
429 	return attach.ret;
430 }
431 
432 /* Caller should have device mutex */
433 bool vhost_dev_has_owner(struct vhost_dev *dev)
434 {
435 	return dev->mm;
436 }
437 EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
438 
439 /* Caller should have device mutex */
440 long vhost_dev_set_owner(struct vhost_dev *dev)
441 {
442 	struct task_struct *worker;
443 	int err;
444 
445 	/* Is there an owner already? */
446 	if (vhost_dev_has_owner(dev)) {
447 		err = -EBUSY;
448 		goto err_mm;
449 	}
450 
451 	/* No owner, become one */
452 	dev->mm = get_task_mm(current);
453 	worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
454 	if (IS_ERR(worker)) {
455 		err = PTR_ERR(worker);
456 		goto err_worker;
457 	}
458 
459 	dev->worker = worker;
460 	wake_up_process(worker);	/* avoid contributing to loadavg */
461 
462 	err = vhost_attach_cgroups(dev);
463 	if (err)
464 		goto err_cgroup;
465 
466 	err = vhost_dev_alloc_iovecs(dev);
467 	if (err)
468 		goto err_cgroup;
469 
470 	return 0;
471 err_cgroup:
472 	kthread_stop(worker);
473 	dev->worker = NULL;
474 err_worker:
475 	if (dev->mm)
476 		mmput(dev->mm);
477 	dev->mm = NULL;
478 err_mm:
479 	return err;
480 }
481 EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
482 
483 struct vhost_memory *vhost_dev_reset_owner_prepare(void)
484 {
485 	return kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
486 }
487 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
488 
489 /* Caller should have device mutex */
490 void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_memory *memory)
491 {
492 	int i;
493 
494 	vhost_dev_cleanup(dev, true);
495 
496 	/* Restore memory to default empty mapping. */
497 	memory->nregions = 0;
498 	dev->memory = memory;
499 	/* We don't need VQ locks below since vhost_dev_cleanup makes sure
500 	 * VQs aren't running.
501 	 */
502 	for (i = 0; i < dev->nvqs; ++i)
503 		dev->vqs[i]->memory = memory;
504 }
505 EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
506 
507 void vhost_dev_stop(struct vhost_dev *dev)
508 {
509 	int i;
510 
511 	for (i = 0; i < dev->nvqs; ++i) {
512 		if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
513 			vhost_poll_stop(&dev->vqs[i]->poll);
514 			vhost_poll_flush(&dev->vqs[i]->poll);
515 		}
516 	}
517 }
518 EXPORT_SYMBOL_GPL(vhost_dev_stop);
519 
520 /* Caller should have device mutex if and only if locked is set */
521 void vhost_dev_cleanup(struct vhost_dev *dev, bool locked)
522 {
523 	int i;
524 
525 	for (i = 0; i < dev->nvqs; ++i) {
526 		if (dev->vqs[i]->error_ctx)
527 			eventfd_ctx_put(dev->vqs[i]->error_ctx);
528 		if (dev->vqs[i]->error)
529 			fput(dev->vqs[i]->error);
530 		if (dev->vqs[i]->kick)
531 			fput(dev->vqs[i]->kick);
532 		if (dev->vqs[i]->call_ctx)
533 			eventfd_ctx_put(dev->vqs[i]->call_ctx);
534 		if (dev->vqs[i]->call)
535 			fput(dev->vqs[i]->call);
536 		vhost_vq_reset(dev, dev->vqs[i]);
537 	}
538 	vhost_dev_free_iovecs(dev);
539 	if (dev->log_ctx)
540 		eventfd_ctx_put(dev->log_ctx);
541 	dev->log_ctx = NULL;
542 	if (dev->log_file)
543 		fput(dev->log_file);
544 	dev->log_file = NULL;
545 	/* No one will access memory at this point */
546 	kfree(dev->memory);
547 	dev->memory = NULL;
548 	WARN_ON(!list_empty(&dev->work_list));
549 	if (dev->worker) {
550 		kthread_stop(dev->worker);
551 		dev->worker = NULL;
552 	}
553 	if (dev->mm)
554 		mmput(dev->mm);
555 	dev->mm = NULL;
556 }
557 EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
558 
559 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
560 {
561 	u64 a = addr / VHOST_PAGE_SIZE / 8;
562 
563 	/* Make sure 64 bit math will not overflow. */
564 	if (a > ULONG_MAX - (unsigned long)log_base ||
565 	    a + (unsigned long)log_base > ULONG_MAX)
566 		return 0;
567 
568 	return access_ok(VERIFY_WRITE, log_base + a,
569 			 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
570 }
571 
572 /* Caller should have vq mutex and device mutex. */
573 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
574 			       int log_all)
575 {
576 	int i;
577 
578 	if (!mem)
579 		return 0;
580 
581 	for (i = 0; i < mem->nregions; ++i) {
582 		struct vhost_memory_region *m = mem->regions + i;
583 		unsigned long a = m->userspace_addr;
584 		if (m->memory_size > ULONG_MAX)
585 			return 0;
586 		else if (!access_ok(VERIFY_WRITE, (void __user *)a,
587 				    m->memory_size))
588 			return 0;
589 		else if (log_all && !log_access_ok(log_base,
590 						   m->guest_phys_addr,
591 						   m->memory_size))
592 			return 0;
593 	}
594 	return 1;
595 }
596 
597 /* Can we switch to this memory table? */
598 /* Caller should have device mutex but not vq mutex */
599 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
600 			    int log_all)
601 {
602 	int i;
603 
604 	for (i = 0; i < d->nvqs; ++i) {
605 		int ok;
606 		bool log;
607 
608 		mutex_lock(&d->vqs[i]->mutex);
609 		log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
610 		/* If ring is inactive, will check when it's enabled. */
611 		if (d->vqs[i]->private_data)
612 			ok = vq_memory_access_ok(d->vqs[i]->log_base, mem, log);
613 		else
614 			ok = 1;
615 		mutex_unlock(&d->vqs[i]->mutex);
616 		if (!ok)
617 			return 0;
618 	}
619 	return 1;
620 }
621 
622 static int vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
623 			struct vring_desc __user *desc,
624 			struct vring_avail __user *avail,
625 			struct vring_used __user *used)
626 {
627 	size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
628 	return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
629 	       access_ok(VERIFY_READ, avail,
630 			 sizeof *avail + num * sizeof *avail->ring + s) &&
631 	       access_ok(VERIFY_WRITE, used,
632 			sizeof *used + num * sizeof *used->ring + s);
633 }
634 
635 /* Can we log writes? */
636 /* Caller should have device mutex but not vq mutex */
637 int vhost_log_access_ok(struct vhost_dev *dev)
638 {
639 	return memory_access_ok(dev, dev->memory, 1);
640 }
641 EXPORT_SYMBOL_GPL(vhost_log_access_ok);
642 
643 /* Verify access for write logging. */
644 /* Caller should have vq mutex and device mutex */
645 static int vq_log_access_ok(struct vhost_virtqueue *vq,
646 			    void __user *log_base)
647 {
648 	size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
649 
650 	return vq_memory_access_ok(log_base, vq->memory,
651 				   vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
652 		(!vq->log_used || log_access_ok(log_base, vq->log_addr,
653 					sizeof *vq->used +
654 					vq->num * sizeof *vq->used->ring + s));
655 }
656 
657 /* Can we start vq? */
658 /* Caller should have vq mutex and device mutex */
659 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
660 {
661 	return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used) &&
662 		vq_log_access_ok(vq, vq->log_base);
663 }
664 EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
665 
666 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
667 {
668 	struct vhost_memory mem, *newmem, *oldmem;
669 	unsigned long size = offsetof(struct vhost_memory, regions);
670 	int i;
671 
672 	if (copy_from_user(&mem, m, size))
673 		return -EFAULT;
674 	if (mem.padding)
675 		return -EOPNOTSUPP;
676 	if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
677 		return -E2BIG;
678 	newmem = kmalloc(size + mem.nregions * sizeof *m->regions, GFP_KERNEL);
679 	if (!newmem)
680 		return -ENOMEM;
681 
682 	memcpy(newmem, &mem, size);
683 	if (copy_from_user(newmem->regions, m->regions,
684 			   mem.nregions * sizeof *m->regions)) {
685 		kfree(newmem);
686 		return -EFAULT;
687 	}
688 
689 	if (!memory_access_ok(d, newmem, 0)) {
690 		kfree(newmem);
691 		return -EFAULT;
692 	}
693 	oldmem = d->memory;
694 	d->memory = newmem;
695 
696 	/* All memory accesses are done under some VQ mutex. */
697 	for (i = 0; i < d->nvqs; ++i) {
698 		mutex_lock(&d->vqs[i]->mutex);
699 		d->vqs[i]->memory = newmem;
700 		mutex_unlock(&d->vqs[i]->mutex);
701 	}
702 	kfree(oldmem);
703 	return 0;
704 }
705 
706 long vhost_vring_ioctl(struct vhost_dev *d, int ioctl, void __user *argp)
707 {
708 	struct file *eventfp, *filep = NULL;
709 	bool pollstart = false, pollstop = false;
710 	struct eventfd_ctx *ctx = NULL;
711 	u32 __user *idxp = argp;
712 	struct vhost_virtqueue *vq;
713 	struct vhost_vring_state s;
714 	struct vhost_vring_file f;
715 	struct vhost_vring_addr a;
716 	u32 idx;
717 	long r;
718 
719 	r = get_user(idx, idxp);
720 	if (r < 0)
721 		return r;
722 	if (idx >= d->nvqs)
723 		return -ENOBUFS;
724 
725 	vq = d->vqs[idx];
726 
727 	mutex_lock(&vq->mutex);
728 
729 	switch (ioctl) {
730 	case VHOST_SET_VRING_NUM:
731 		/* Resizing ring with an active backend?
732 		 * You don't want to do that. */
733 		if (vq->private_data) {
734 			r = -EBUSY;
735 			break;
736 		}
737 		if (copy_from_user(&s, argp, sizeof s)) {
738 			r = -EFAULT;
739 			break;
740 		}
741 		if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
742 			r = -EINVAL;
743 			break;
744 		}
745 		vq->num = s.num;
746 		break;
747 	case VHOST_SET_VRING_BASE:
748 		/* Moving base with an active backend?
749 		 * You don't want to do that. */
750 		if (vq->private_data) {
751 			r = -EBUSY;
752 			break;
753 		}
754 		if (copy_from_user(&s, argp, sizeof s)) {
755 			r = -EFAULT;
756 			break;
757 		}
758 		if (s.num > 0xffff) {
759 			r = -EINVAL;
760 			break;
761 		}
762 		vq->last_avail_idx = s.num;
763 		/* Forget the cached index value. */
764 		vq->avail_idx = vq->last_avail_idx;
765 		break;
766 	case VHOST_GET_VRING_BASE:
767 		s.index = idx;
768 		s.num = vq->last_avail_idx;
769 		if (copy_to_user(argp, &s, sizeof s))
770 			r = -EFAULT;
771 		break;
772 	case VHOST_SET_VRING_ADDR:
773 		if (copy_from_user(&a, argp, sizeof a)) {
774 			r = -EFAULT;
775 			break;
776 		}
777 		if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
778 			r = -EOPNOTSUPP;
779 			break;
780 		}
781 		/* For 32bit, verify that the top 32bits of the user
782 		   data are set to zero. */
783 		if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
784 		    (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
785 		    (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
786 			r = -EFAULT;
787 			break;
788 		}
789 
790 		/* Make sure it's safe to cast pointers to vring types. */
791 		BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
792 		BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
793 		if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
794 		    (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
795 		    (a.log_guest_addr & (sizeof(u64) - 1))) {
796 			r = -EINVAL;
797 			break;
798 		}
799 
800 		/* We only verify access here if backend is configured.
801 		 * If it is not, we don't as size might not have been setup.
802 		 * We will verify when backend is configured. */
803 		if (vq->private_data) {
804 			if (!vq_access_ok(vq, vq->num,
805 				(void __user *)(unsigned long)a.desc_user_addr,
806 				(void __user *)(unsigned long)a.avail_user_addr,
807 				(void __user *)(unsigned long)a.used_user_addr)) {
808 				r = -EINVAL;
809 				break;
810 			}
811 
812 			/* Also validate log access for used ring if enabled. */
813 			if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
814 			    !log_access_ok(vq->log_base, a.log_guest_addr,
815 					   sizeof *vq->used +
816 					   vq->num * sizeof *vq->used->ring)) {
817 				r = -EINVAL;
818 				break;
819 			}
820 		}
821 
822 		vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
823 		vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
824 		vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
825 		vq->log_addr = a.log_guest_addr;
826 		vq->used = (void __user *)(unsigned long)a.used_user_addr;
827 		break;
828 	case VHOST_SET_VRING_KICK:
829 		if (copy_from_user(&f, argp, sizeof f)) {
830 			r = -EFAULT;
831 			break;
832 		}
833 		eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
834 		if (IS_ERR(eventfp)) {
835 			r = PTR_ERR(eventfp);
836 			break;
837 		}
838 		if (eventfp != vq->kick) {
839 			pollstop = (filep = vq->kick) != NULL;
840 			pollstart = (vq->kick = eventfp) != NULL;
841 		} else
842 			filep = eventfp;
843 		break;
844 	case VHOST_SET_VRING_CALL:
845 		if (copy_from_user(&f, argp, sizeof f)) {
846 			r = -EFAULT;
847 			break;
848 		}
849 		eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
850 		if (IS_ERR(eventfp)) {
851 			r = PTR_ERR(eventfp);
852 			break;
853 		}
854 		if (eventfp != vq->call) {
855 			filep = vq->call;
856 			ctx = vq->call_ctx;
857 			vq->call = eventfp;
858 			vq->call_ctx = eventfp ?
859 				eventfd_ctx_fileget(eventfp) : NULL;
860 		} else
861 			filep = eventfp;
862 		break;
863 	case VHOST_SET_VRING_ERR:
864 		if (copy_from_user(&f, argp, sizeof f)) {
865 			r = -EFAULT;
866 			break;
867 		}
868 		eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
869 		if (IS_ERR(eventfp)) {
870 			r = PTR_ERR(eventfp);
871 			break;
872 		}
873 		if (eventfp != vq->error) {
874 			filep = vq->error;
875 			vq->error = eventfp;
876 			ctx = vq->error_ctx;
877 			vq->error_ctx = eventfp ?
878 				eventfd_ctx_fileget(eventfp) : NULL;
879 		} else
880 			filep = eventfp;
881 		break;
882 	case VHOST_SET_VRING_ENDIAN:
883 		r = vhost_set_vring_endian(vq, argp);
884 		break;
885 	case VHOST_GET_VRING_ENDIAN:
886 		r = vhost_get_vring_endian(vq, idx, argp);
887 		break;
888 	default:
889 		r = -ENOIOCTLCMD;
890 	}
891 
892 	if (pollstop && vq->handle_kick)
893 		vhost_poll_stop(&vq->poll);
894 
895 	if (ctx)
896 		eventfd_ctx_put(ctx);
897 	if (filep)
898 		fput(filep);
899 
900 	if (pollstart && vq->handle_kick)
901 		r = vhost_poll_start(&vq->poll, vq->kick);
902 
903 	mutex_unlock(&vq->mutex);
904 
905 	if (pollstop && vq->handle_kick)
906 		vhost_poll_flush(&vq->poll);
907 	return r;
908 }
909 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
910 
911 /* Caller must have device mutex */
912 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
913 {
914 	struct file *eventfp, *filep = NULL;
915 	struct eventfd_ctx *ctx = NULL;
916 	u64 p;
917 	long r;
918 	int i, fd;
919 
920 	/* If you are not the owner, you can become one */
921 	if (ioctl == VHOST_SET_OWNER) {
922 		r = vhost_dev_set_owner(d);
923 		goto done;
924 	}
925 
926 	/* You must be the owner to do anything else */
927 	r = vhost_dev_check_owner(d);
928 	if (r)
929 		goto done;
930 
931 	switch (ioctl) {
932 	case VHOST_SET_MEM_TABLE:
933 		r = vhost_set_memory(d, argp);
934 		break;
935 	case VHOST_SET_LOG_BASE:
936 		if (copy_from_user(&p, argp, sizeof p)) {
937 			r = -EFAULT;
938 			break;
939 		}
940 		if ((u64)(unsigned long)p != p) {
941 			r = -EFAULT;
942 			break;
943 		}
944 		for (i = 0; i < d->nvqs; ++i) {
945 			struct vhost_virtqueue *vq;
946 			void __user *base = (void __user *)(unsigned long)p;
947 			vq = d->vqs[i];
948 			mutex_lock(&vq->mutex);
949 			/* If ring is inactive, will check when it's enabled. */
950 			if (vq->private_data && !vq_log_access_ok(vq, base))
951 				r = -EFAULT;
952 			else
953 				vq->log_base = base;
954 			mutex_unlock(&vq->mutex);
955 		}
956 		break;
957 	case VHOST_SET_LOG_FD:
958 		r = get_user(fd, (int __user *)argp);
959 		if (r < 0)
960 			break;
961 		eventfp = fd == -1 ? NULL : eventfd_fget(fd);
962 		if (IS_ERR(eventfp)) {
963 			r = PTR_ERR(eventfp);
964 			break;
965 		}
966 		if (eventfp != d->log_file) {
967 			filep = d->log_file;
968 			ctx = d->log_ctx;
969 			d->log_ctx = eventfp ?
970 				eventfd_ctx_fileget(eventfp) : NULL;
971 		} else
972 			filep = eventfp;
973 		for (i = 0; i < d->nvqs; ++i) {
974 			mutex_lock(&d->vqs[i]->mutex);
975 			d->vqs[i]->log_ctx = d->log_ctx;
976 			mutex_unlock(&d->vqs[i]->mutex);
977 		}
978 		if (ctx)
979 			eventfd_ctx_put(ctx);
980 		if (filep)
981 			fput(filep);
982 		break;
983 	default:
984 		r = -ENOIOCTLCMD;
985 		break;
986 	}
987 done:
988 	return r;
989 }
990 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
991 
992 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
993 						     __u64 addr, __u32 len)
994 {
995 	struct vhost_memory_region *reg;
996 	int i;
997 
998 	/* linear search is not brilliant, but we really have on the order of 6
999 	 * regions in practice */
1000 	for (i = 0; i < mem->nregions; ++i) {
1001 		reg = mem->regions + i;
1002 		if (reg->guest_phys_addr <= addr &&
1003 		    reg->guest_phys_addr + reg->memory_size - 1 >= addr)
1004 			return reg;
1005 	}
1006 	return NULL;
1007 }
1008 
1009 /* TODO: This is really inefficient.  We need something like get_user()
1010  * (instruction directly accesses the data, with an exception table entry
1011  * returning -EFAULT). See Documentation/x86/exception-tables.txt.
1012  */
1013 static int set_bit_to_user(int nr, void __user *addr)
1014 {
1015 	unsigned long log = (unsigned long)addr;
1016 	struct page *page;
1017 	void *base;
1018 	int bit = nr + (log % PAGE_SIZE) * 8;
1019 	int r;
1020 
1021 	r = get_user_pages_fast(log, 1, 1, &page);
1022 	if (r < 0)
1023 		return r;
1024 	BUG_ON(r != 1);
1025 	base = kmap_atomic(page);
1026 	set_bit(bit, base);
1027 	kunmap_atomic(base);
1028 	set_page_dirty_lock(page);
1029 	put_page(page);
1030 	return 0;
1031 }
1032 
1033 static int log_write(void __user *log_base,
1034 		     u64 write_address, u64 write_length)
1035 {
1036 	u64 write_page = write_address / VHOST_PAGE_SIZE;
1037 	int r;
1038 
1039 	if (!write_length)
1040 		return 0;
1041 	write_length += write_address % VHOST_PAGE_SIZE;
1042 	for (;;) {
1043 		u64 base = (u64)(unsigned long)log_base;
1044 		u64 log = base + write_page / 8;
1045 		int bit = write_page % 8;
1046 		if ((u64)(unsigned long)log != log)
1047 			return -EFAULT;
1048 		r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1049 		if (r < 0)
1050 			return r;
1051 		if (write_length <= VHOST_PAGE_SIZE)
1052 			break;
1053 		write_length -= VHOST_PAGE_SIZE;
1054 		write_page += 1;
1055 	}
1056 	return r;
1057 }
1058 
1059 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1060 		    unsigned int log_num, u64 len)
1061 {
1062 	int i, r;
1063 
1064 	/* Make sure data written is seen before log. */
1065 	smp_wmb();
1066 	for (i = 0; i < log_num; ++i) {
1067 		u64 l = min(log[i].len, len);
1068 		r = log_write(vq->log_base, log[i].addr, l);
1069 		if (r < 0)
1070 			return r;
1071 		len -= l;
1072 		if (!len) {
1073 			if (vq->log_ctx)
1074 				eventfd_signal(vq->log_ctx, 1);
1075 			return 0;
1076 		}
1077 	}
1078 	/* Length written exceeds what we have stored. This is a bug. */
1079 	BUG();
1080 	return 0;
1081 }
1082 EXPORT_SYMBOL_GPL(vhost_log_write);
1083 
1084 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1085 {
1086 	void __user *used;
1087 	if (__put_user(cpu_to_vhost16(vq, vq->used_flags), &vq->used->flags) < 0)
1088 		return -EFAULT;
1089 	if (unlikely(vq->log_used)) {
1090 		/* Make sure the flag is seen before log. */
1091 		smp_wmb();
1092 		/* Log used flag write. */
1093 		used = &vq->used->flags;
1094 		log_write(vq->log_base, vq->log_addr +
1095 			  (used - (void __user *)vq->used),
1096 			  sizeof vq->used->flags);
1097 		if (vq->log_ctx)
1098 			eventfd_signal(vq->log_ctx, 1);
1099 	}
1100 	return 0;
1101 }
1102 
1103 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1104 {
1105 	if (__put_user(cpu_to_vhost16(vq, vq->avail_idx), vhost_avail_event(vq)))
1106 		return -EFAULT;
1107 	if (unlikely(vq->log_used)) {
1108 		void __user *used;
1109 		/* Make sure the event is seen before log. */
1110 		smp_wmb();
1111 		/* Log avail event write */
1112 		used = vhost_avail_event(vq);
1113 		log_write(vq->log_base, vq->log_addr +
1114 			  (used - (void __user *)vq->used),
1115 			  sizeof *vhost_avail_event(vq));
1116 		if (vq->log_ctx)
1117 			eventfd_signal(vq->log_ctx, 1);
1118 	}
1119 	return 0;
1120 }
1121 
1122 int vhost_init_used(struct vhost_virtqueue *vq)
1123 {
1124 	__virtio16 last_used_idx;
1125 	int r;
1126 	if (!vq->private_data) {
1127 		vq->is_le = virtio_legacy_is_little_endian();
1128 		return 0;
1129 	}
1130 
1131 	vhost_init_is_le(vq);
1132 
1133 	r = vhost_update_used_flags(vq);
1134 	if (r)
1135 		return r;
1136 	vq->signalled_used_valid = false;
1137 	if (!access_ok(VERIFY_READ, &vq->used->idx, sizeof vq->used->idx))
1138 		return -EFAULT;
1139 	r = __get_user(last_used_idx, &vq->used->idx);
1140 	if (r)
1141 		return r;
1142 	vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1143 	return 0;
1144 }
1145 EXPORT_SYMBOL_GPL(vhost_init_used);
1146 
1147 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1148 			  struct iovec iov[], int iov_size)
1149 {
1150 	const struct vhost_memory_region *reg;
1151 	struct vhost_memory *mem;
1152 	struct iovec *_iov;
1153 	u64 s = 0;
1154 	int ret = 0;
1155 
1156 	mem = vq->memory;
1157 	while ((u64)len > s) {
1158 		u64 size;
1159 		if (unlikely(ret >= iov_size)) {
1160 			ret = -ENOBUFS;
1161 			break;
1162 		}
1163 		reg = find_region(mem, addr, len);
1164 		if (unlikely(!reg)) {
1165 			ret = -EFAULT;
1166 			break;
1167 		}
1168 		_iov = iov + ret;
1169 		size = reg->memory_size - addr + reg->guest_phys_addr;
1170 		_iov->iov_len = min((u64)len - s, size);
1171 		_iov->iov_base = (void __user *)(unsigned long)
1172 			(reg->userspace_addr + addr - reg->guest_phys_addr);
1173 		s += size;
1174 		addr += size;
1175 		++ret;
1176 	}
1177 
1178 	return ret;
1179 }
1180 
1181 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
1182  * function returns the next descriptor in the chain,
1183  * or -1U if we're at the end. */
1184 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1185 {
1186 	unsigned int next;
1187 
1188 	/* If this descriptor says it doesn't chain, we're done. */
1189 	if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1190 		return -1U;
1191 
1192 	/* Check they're not leading us off end of descriptors. */
1193 	next = vhost16_to_cpu(vq, desc->next);
1194 	/* Make sure compiler knows to grab that: we don't want it changing! */
1195 	/* We will use the result as an index in an array, so most
1196 	 * architectures only need a compiler barrier here. */
1197 	read_barrier_depends();
1198 
1199 	return next;
1200 }
1201 
1202 static int get_indirect(struct vhost_virtqueue *vq,
1203 			struct iovec iov[], unsigned int iov_size,
1204 			unsigned int *out_num, unsigned int *in_num,
1205 			struct vhost_log *log, unsigned int *log_num,
1206 			struct vring_desc *indirect)
1207 {
1208 	struct vring_desc desc;
1209 	unsigned int i = 0, count, found = 0;
1210 	u32 len = vhost32_to_cpu(vq, indirect->len);
1211 	struct iov_iter from;
1212 	int ret;
1213 
1214 	/* Sanity check */
1215 	if (unlikely(len % sizeof desc)) {
1216 		vq_err(vq, "Invalid length in indirect descriptor: "
1217 		       "len 0x%llx not multiple of 0x%zx\n",
1218 		       (unsigned long long)len,
1219 		       sizeof desc);
1220 		return -EINVAL;
1221 	}
1222 
1223 	ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
1224 			     UIO_MAXIOV);
1225 	if (unlikely(ret < 0)) {
1226 		vq_err(vq, "Translation failure %d in indirect.\n", ret);
1227 		return ret;
1228 	}
1229 	iov_iter_init(&from, READ, vq->indirect, ret, len);
1230 
1231 	/* We will use the result as an address to read from, so most
1232 	 * architectures only need a compiler barrier here. */
1233 	read_barrier_depends();
1234 
1235 	count = len / sizeof desc;
1236 	/* Buffers are chained via a 16 bit next field, so
1237 	 * we can have at most 2^16 of these. */
1238 	if (unlikely(count > USHRT_MAX + 1)) {
1239 		vq_err(vq, "Indirect buffer length too big: %d\n",
1240 		       indirect->len);
1241 		return -E2BIG;
1242 	}
1243 
1244 	do {
1245 		unsigned iov_count = *in_num + *out_num;
1246 		if (unlikely(++found > count)) {
1247 			vq_err(vq, "Loop detected: last one at %u "
1248 			       "indirect size %u\n",
1249 			       i, count);
1250 			return -EINVAL;
1251 		}
1252 		if (unlikely(copy_from_iter(&desc, sizeof(desc), &from) !=
1253 			     sizeof(desc))) {
1254 			vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1255 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1256 			return -EINVAL;
1257 		}
1258 		if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
1259 			vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1260 			       i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1261 			return -EINVAL;
1262 		}
1263 
1264 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1265 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
1266 				     iov_size - iov_count);
1267 		if (unlikely(ret < 0)) {
1268 			vq_err(vq, "Translation failure %d indirect idx %d\n",
1269 			       ret, i);
1270 			return ret;
1271 		}
1272 		/* If this is an input descriptor, increment that count. */
1273 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1274 			*in_num += ret;
1275 			if (unlikely(log)) {
1276 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1277 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1278 				++*log_num;
1279 			}
1280 		} else {
1281 			/* If it's an output descriptor, they're all supposed
1282 			 * to come before any input descriptors. */
1283 			if (unlikely(*in_num)) {
1284 				vq_err(vq, "Indirect descriptor "
1285 				       "has out after in: idx %d\n", i);
1286 				return -EINVAL;
1287 			}
1288 			*out_num += ret;
1289 		}
1290 	} while ((i = next_desc(vq, &desc)) != -1);
1291 	return 0;
1292 }
1293 
1294 /* This looks in the virtqueue and for the first available buffer, and converts
1295  * it to an iovec for convenient access.  Since descriptors consist of some
1296  * number of output then some number of input descriptors, it's actually two
1297  * iovecs, but we pack them into one and note how many of each there were.
1298  *
1299  * This function returns the descriptor number found, or vq->num (which is
1300  * never a valid descriptor number) if none was found.  A negative code is
1301  * returned on error. */
1302 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
1303 		      struct iovec iov[], unsigned int iov_size,
1304 		      unsigned int *out_num, unsigned int *in_num,
1305 		      struct vhost_log *log, unsigned int *log_num)
1306 {
1307 	struct vring_desc desc;
1308 	unsigned int i, head, found = 0;
1309 	u16 last_avail_idx;
1310 	__virtio16 avail_idx;
1311 	__virtio16 ring_head;
1312 	int ret;
1313 
1314 	/* Check it isn't doing very strange things with descriptor numbers. */
1315 	last_avail_idx = vq->last_avail_idx;
1316 	if (unlikely(__get_user(avail_idx, &vq->avail->idx))) {
1317 		vq_err(vq, "Failed to access avail idx at %p\n",
1318 		       &vq->avail->idx);
1319 		return -EFAULT;
1320 	}
1321 	vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
1322 
1323 	if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1324 		vq_err(vq, "Guest moved used index from %u to %u",
1325 		       last_avail_idx, vq->avail_idx);
1326 		return -EFAULT;
1327 	}
1328 
1329 	/* If there's nothing new since last we looked, return invalid. */
1330 	if (vq->avail_idx == last_avail_idx)
1331 		return vq->num;
1332 
1333 	/* Only get avail ring entries after they have been exposed by guest. */
1334 	smp_rmb();
1335 
1336 	/* Grab the next descriptor number they're advertising, and increment
1337 	 * the index we've seen. */
1338 	if (unlikely(__get_user(ring_head,
1339 				&vq->avail->ring[last_avail_idx % vq->num]))) {
1340 		vq_err(vq, "Failed to read head: idx %d address %p\n",
1341 		       last_avail_idx,
1342 		       &vq->avail->ring[last_avail_idx % vq->num]);
1343 		return -EFAULT;
1344 	}
1345 
1346 	head = vhost16_to_cpu(vq, ring_head);
1347 
1348 	/* If their number is silly, that's an error. */
1349 	if (unlikely(head >= vq->num)) {
1350 		vq_err(vq, "Guest says index %u > %u is available",
1351 		       head, vq->num);
1352 		return -EINVAL;
1353 	}
1354 
1355 	/* When we start there are none of either input nor output. */
1356 	*out_num = *in_num = 0;
1357 	if (unlikely(log))
1358 		*log_num = 0;
1359 
1360 	i = head;
1361 	do {
1362 		unsigned iov_count = *in_num + *out_num;
1363 		if (unlikely(i >= vq->num)) {
1364 			vq_err(vq, "Desc index is %u > %u, head = %u",
1365 			       i, vq->num, head);
1366 			return -EINVAL;
1367 		}
1368 		if (unlikely(++found > vq->num)) {
1369 			vq_err(vq, "Loop detected: last one at %u "
1370 			       "vq size %u head %u\n",
1371 			       i, vq->num, head);
1372 			return -EINVAL;
1373 		}
1374 		ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
1375 		if (unlikely(ret)) {
1376 			vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1377 			       i, vq->desc + i);
1378 			return -EFAULT;
1379 		}
1380 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
1381 			ret = get_indirect(vq, iov, iov_size,
1382 					   out_num, in_num,
1383 					   log, log_num, &desc);
1384 			if (unlikely(ret < 0)) {
1385 				vq_err(vq, "Failure detected "
1386 				       "in indirect descriptor at idx %d\n", i);
1387 				return ret;
1388 			}
1389 			continue;
1390 		}
1391 
1392 		ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1393 				     vhost32_to_cpu(vq, desc.len), iov + iov_count,
1394 				     iov_size - iov_count);
1395 		if (unlikely(ret < 0)) {
1396 			vq_err(vq, "Translation failure %d descriptor idx %d\n",
1397 			       ret, i);
1398 			return ret;
1399 		}
1400 		if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1401 			/* If this is an input descriptor,
1402 			 * increment that count. */
1403 			*in_num += ret;
1404 			if (unlikely(log)) {
1405 				log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1406 				log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1407 				++*log_num;
1408 			}
1409 		} else {
1410 			/* If it's an output descriptor, they're all supposed
1411 			 * to come before any input descriptors. */
1412 			if (unlikely(*in_num)) {
1413 				vq_err(vq, "Descriptor has out after in: "
1414 				       "idx %d\n", i);
1415 				return -EINVAL;
1416 			}
1417 			*out_num += ret;
1418 		}
1419 	} while ((i = next_desc(vq, &desc)) != -1);
1420 
1421 	/* On success, increment avail index. */
1422 	vq->last_avail_idx++;
1423 
1424 	/* Assume notifications from guest are disabled at this point,
1425 	 * if they aren't we would need to update avail_event index. */
1426 	BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
1427 	return head;
1428 }
1429 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
1430 
1431 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1432 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1433 {
1434 	vq->last_avail_idx -= n;
1435 }
1436 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
1437 
1438 /* After we've used one of their buffers, we tell them about it.  We'll then
1439  * want to notify the guest, using eventfd. */
1440 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1441 {
1442 	struct vring_used_elem heads = {
1443 		cpu_to_vhost32(vq, head),
1444 		cpu_to_vhost32(vq, len)
1445 	};
1446 
1447 	return vhost_add_used_n(vq, &heads, 1);
1448 }
1449 EXPORT_SYMBOL_GPL(vhost_add_used);
1450 
1451 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1452 			    struct vring_used_elem *heads,
1453 			    unsigned count)
1454 {
1455 	struct vring_used_elem __user *used;
1456 	u16 old, new;
1457 	int start;
1458 
1459 	start = vq->last_used_idx % vq->num;
1460 	used = vq->used->ring + start;
1461 	if (count == 1) {
1462 		if (__put_user(heads[0].id, &used->id)) {
1463 			vq_err(vq, "Failed to write used id");
1464 			return -EFAULT;
1465 		}
1466 		if (__put_user(heads[0].len, &used->len)) {
1467 			vq_err(vq, "Failed to write used len");
1468 			return -EFAULT;
1469 		}
1470 	} else if (__copy_to_user(used, heads, count * sizeof *used)) {
1471 		vq_err(vq, "Failed to write used");
1472 		return -EFAULT;
1473 	}
1474 	if (unlikely(vq->log_used)) {
1475 		/* Make sure data is seen before log. */
1476 		smp_wmb();
1477 		/* Log used ring entry write. */
1478 		log_write(vq->log_base,
1479 			  vq->log_addr +
1480 			   ((void __user *)used - (void __user *)vq->used),
1481 			  count * sizeof *used);
1482 	}
1483 	old = vq->last_used_idx;
1484 	new = (vq->last_used_idx += count);
1485 	/* If the driver never bothers to signal in a very long while,
1486 	 * used index might wrap around. If that happens, invalidate
1487 	 * signalled_used index we stored. TODO: make sure driver
1488 	 * signals at least once in 2^16 and remove this. */
1489 	if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
1490 		vq->signalled_used_valid = false;
1491 	return 0;
1492 }
1493 
1494 /* After we've used one of their buffers, we tell them about it.  We'll then
1495  * want to notify the guest, using eventfd. */
1496 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1497 		     unsigned count)
1498 {
1499 	int start, n, r;
1500 
1501 	start = vq->last_used_idx % vq->num;
1502 	n = vq->num - start;
1503 	if (n < count) {
1504 		r = __vhost_add_used_n(vq, heads, n);
1505 		if (r < 0)
1506 			return r;
1507 		heads += n;
1508 		count -= n;
1509 	}
1510 	r = __vhost_add_used_n(vq, heads, count);
1511 
1512 	/* Make sure buffer is written before we update index. */
1513 	smp_wmb();
1514 	if (__put_user(cpu_to_vhost16(vq, vq->last_used_idx), &vq->used->idx)) {
1515 		vq_err(vq, "Failed to increment used idx");
1516 		return -EFAULT;
1517 	}
1518 	if (unlikely(vq->log_used)) {
1519 		/* Log used index update. */
1520 		log_write(vq->log_base,
1521 			  vq->log_addr + offsetof(struct vring_used, idx),
1522 			  sizeof vq->used->idx);
1523 		if (vq->log_ctx)
1524 			eventfd_signal(vq->log_ctx, 1);
1525 	}
1526 	return r;
1527 }
1528 EXPORT_SYMBOL_GPL(vhost_add_used_n);
1529 
1530 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1531 {
1532 	__u16 old, new;
1533 	__virtio16 event;
1534 	bool v;
1535 	/* Flush out used index updates. This is paired
1536 	 * with the barrier that the Guest executes when enabling
1537 	 * interrupts. */
1538 	smp_mb();
1539 
1540 	if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1541 	    unlikely(vq->avail_idx == vq->last_avail_idx))
1542 		return true;
1543 
1544 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1545 		__virtio16 flags;
1546 		if (__get_user(flags, &vq->avail->flags)) {
1547 			vq_err(vq, "Failed to get flags");
1548 			return true;
1549 		}
1550 		return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
1551 	}
1552 	old = vq->signalled_used;
1553 	v = vq->signalled_used_valid;
1554 	new = vq->signalled_used = vq->last_used_idx;
1555 	vq->signalled_used_valid = true;
1556 
1557 	if (unlikely(!v))
1558 		return true;
1559 
1560 	if (__get_user(event, vhost_used_event(vq))) {
1561 		vq_err(vq, "Failed to get used event idx");
1562 		return true;
1563 	}
1564 	return vring_need_event(vhost16_to_cpu(vq, event), new, old);
1565 }
1566 
1567 /* This actually signals the guest, using eventfd. */
1568 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1569 {
1570 	/* Signal the Guest tell them we used something up. */
1571 	if (vq->call_ctx && vhost_notify(dev, vq))
1572 		eventfd_signal(vq->call_ctx, 1);
1573 }
1574 EXPORT_SYMBOL_GPL(vhost_signal);
1575 
1576 /* And here's the combo meal deal.  Supersize me! */
1577 void vhost_add_used_and_signal(struct vhost_dev *dev,
1578 			       struct vhost_virtqueue *vq,
1579 			       unsigned int head, int len)
1580 {
1581 	vhost_add_used(vq, head, len);
1582 	vhost_signal(dev, vq);
1583 }
1584 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
1585 
1586 /* multi-buffer version of vhost_add_used_and_signal */
1587 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1588 				 struct vhost_virtqueue *vq,
1589 				 struct vring_used_elem *heads, unsigned count)
1590 {
1591 	vhost_add_used_n(vq, heads, count);
1592 	vhost_signal(dev, vq);
1593 }
1594 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
1595 
1596 /* OK, now we need to know about added descriptors. */
1597 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1598 {
1599 	__virtio16 avail_idx;
1600 	int r;
1601 
1602 	if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1603 		return false;
1604 	vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1605 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1606 		r = vhost_update_used_flags(vq);
1607 		if (r) {
1608 			vq_err(vq, "Failed to enable notification at %p: %d\n",
1609 			       &vq->used->flags, r);
1610 			return false;
1611 		}
1612 	} else {
1613 		r = vhost_update_avail_event(vq, vq->avail_idx);
1614 		if (r) {
1615 			vq_err(vq, "Failed to update avail event index at %p: %d\n",
1616 			       vhost_avail_event(vq), r);
1617 			return false;
1618 		}
1619 	}
1620 	/* They could have slipped one in as we were doing that: make
1621 	 * sure it's written, then check again. */
1622 	smp_mb();
1623 	r = __get_user(avail_idx, &vq->avail->idx);
1624 	if (r) {
1625 		vq_err(vq, "Failed to check avail idx at %p: %d\n",
1626 		       &vq->avail->idx, r);
1627 		return false;
1628 	}
1629 
1630 	return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
1631 }
1632 EXPORT_SYMBOL_GPL(vhost_enable_notify);
1633 
1634 /* We don't need to be notified again. */
1635 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1636 {
1637 	int r;
1638 
1639 	if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1640 		return;
1641 	vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1642 	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1643 		r = vhost_update_used_flags(vq);
1644 		if (r)
1645 			vq_err(vq, "Failed to enable notification at %p: %d\n",
1646 			       &vq->used->flags, r);
1647 	}
1648 }
1649 EXPORT_SYMBOL_GPL(vhost_disable_notify);
1650 
1651 static int __init vhost_init(void)
1652 {
1653 	return 0;
1654 }
1655 
1656 static void __exit vhost_exit(void)
1657 {
1658 }
1659 
1660 module_init(vhost_init);
1661 module_exit(vhost_exit);
1662 
1663 MODULE_VERSION("0.0.1");
1664 MODULE_LICENSE("GPL v2");
1665 MODULE_AUTHOR("Michael S. Tsirkin");
1666 MODULE_DESCRIPTION("Host kernel accelerator for virtio");
1667