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