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