xref: /linux/drivers/vhost/vhost.c (revision e190bfe56841551b1ad5abb42ebd0c4798cc8c01)
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/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/miscdevice.h>
19 #include <linux/mutex.h>
20 #include <linux/workqueue.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 
27 #include <linux/net.h>
28 #include <linux/if_packet.h>
29 #include <linux/if_arp.h>
30 
31 #include <net/sock.h>
32 
33 #include "vhost.h"
34 
35 enum {
36 	VHOST_MEMORY_MAX_NREGIONS = 64,
37 	VHOST_MEMORY_F_LOG = 0x1,
38 };
39 
40 static struct workqueue_struct *vhost_workqueue;
41 
42 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
43 			    poll_table *pt)
44 {
45 	struct vhost_poll *poll;
46 	poll = container_of(pt, struct vhost_poll, table);
47 
48 	poll->wqh = wqh;
49 	add_wait_queue(wqh, &poll->wait);
50 }
51 
52 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
53 			     void *key)
54 {
55 	struct vhost_poll *poll;
56 	poll = container_of(wait, struct vhost_poll, wait);
57 	if (!((unsigned long)key & poll->mask))
58 		return 0;
59 
60 	queue_work(vhost_workqueue, &poll->work);
61 	return 0;
62 }
63 
64 /* Init poll structure */
65 void vhost_poll_init(struct vhost_poll *poll, work_func_t func,
66 		     unsigned long mask)
67 {
68 	INIT_WORK(&poll->work, func);
69 	init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
70 	init_poll_funcptr(&poll->table, vhost_poll_func);
71 	poll->mask = mask;
72 }
73 
74 /* Start polling a file. We add ourselves to file's wait queue. The caller must
75  * keep a reference to a file until after vhost_poll_stop is called. */
76 void vhost_poll_start(struct vhost_poll *poll, struct file *file)
77 {
78 	unsigned long mask;
79 	mask = file->f_op->poll(file, &poll->table);
80 	if (mask)
81 		vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
82 }
83 
84 /* Stop polling a file. After this function returns, it becomes safe to drop the
85  * file reference. You must also flush afterwards. */
86 void vhost_poll_stop(struct vhost_poll *poll)
87 {
88 	remove_wait_queue(poll->wqh, &poll->wait);
89 }
90 
91 /* Flush any work that has been scheduled. When calling this, don't hold any
92  * locks that are also used by the callback. */
93 void vhost_poll_flush(struct vhost_poll *poll)
94 {
95 	flush_work(&poll->work);
96 }
97 
98 void vhost_poll_queue(struct vhost_poll *poll)
99 {
100 	queue_work(vhost_workqueue, &poll->work);
101 }
102 
103 static void vhost_vq_reset(struct vhost_dev *dev,
104 			   struct vhost_virtqueue *vq)
105 {
106 	vq->num = 1;
107 	vq->desc = NULL;
108 	vq->avail = NULL;
109 	vq->used = NULL;
110 	vq->last_avail_idx = 0;
111 	vq->avail_idx = 0;
112 	vq->last_used_idx = 0;
113 	vq->used_flags = 0;
114 	vq->used_flags = 0;
115 	vq->log_used = false;
116 	vq->log_addr = -1ull;
117 	vq->hdr_size = 0;
118 	vq->private_data = NULL;
119 	vq->log_base = NULL;
120 	vq->error_ctx = NULL;
121 	vq->error = NULL;
122 	vq->kick = NULL;
123 	vq->call_ctx = NULL;
124 	vq->call = NULL;
125 	vq->log_ctx = NULL;
126 }
127 
128 long vhost_dev_init(struct vhost_dev *dev,
129 		    struct vhost_virtqueue *vqs, int nvqs)
130 {
131 	int i;
132 	dev->vqs = vqs;
133 	dev->nvqs = nvqs;
134 	mutex_init(&dev->mutex);
135 	dev->log_ctx = NULL;
136 	dev->log_file = NULL;
137 	dev->memory = NULL;
138 	dev->mm = NULL;
139 
140 	for (i = 0; i < dev->nvqs; ++i) {
141 		dev->vqs[i].dev = dev;
142 		mutex_init(&dev->vqs[i].mutex);
143 		vhost_vq_reset(dev, dev->vqs + i);
144 		if (dev->vqs[i].handle_kick)
145 			vhost_poll_init(&dev->vqs[i].poll,
146 					dev->vqs[i].handle_kick,
147 					POLLIN);
148 	}
149 	return 0;
150 }
151 
152 /* Caller should have device mutex */
153 long vhost_dev_check_owner(struct vhost_dev *dev)
154 {
155 	/* Are you the owner? If not, I don't think you mean to do that */
156 	return dev->mm == current->mm ? 0 : -EPERM;
157 }
158 
159 /* Caller should have device mutex */
160 static long vhost_dev_set_owner(struct vhost_dev *dev)
161 {
162 	/* Is there an owner already? */
163 	if (dev->mm)
164 		return -EBUSY;
165 	/* No owner, become one */
166 	dev->mm = get_task_mm(current);
167 	return 0;
168 }
169 
170 /* Caller should have device mutex */
171 long vhost_dev_reset_owner(struct vhost_dev *dev)
172 {
173 	struct vhost_memory *memory;
174 
175 	/* Restore memory to default empty mapping. */
176 	memory = kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
177 	if (!memory)
178 		return -ENOMEM;
179 
180 	vhost_dev_cleanup(dev);
181 
182 	memory->nregions = 0;
183 	dev->memory = memory;
184 	return 0;
185 }
186 
187 /* Caller should have device mutex */
188 void vhost_dev_cleanup(struct vhost_dev *dev)
189 {
190 	int i;
191 	for (i = 0; i < dev->nvqs; ++i) {
192 		if (dev->vqs[i].kick && dev->vqs[i].handle_kick) {
193 			vhost_poll_stop(&dev->vqs[i].poll);
194 			vhost_poll_flush(&dev->vqs[i].poll);
195 		}
196 		if (dev->vqs[i].error_ctx)
197 			eventfd_ctx_put(dev->vqs[i].error_ctx);
198 		if (dev->vqs[i].error)
199 			fput(dev->vqs[i].error);
200 		if (dev->vqs[i].kick)
201 			fput(dev->vqs[i].kick);
202 		if (dev->vqs[i].call_ctx)
203 			eventfd_ctx_put(dev->vqs[i].call_ctx);
204 		if (dev->vqs[i].call)
205 			fput(dev->vqs[i].call);
206 		vhost_vq_reset(dev, dev->vqs + i);
207 	}
208 	if (dev->log_ctx)
209 		eventfd_ctx_put(dev->log_ctx);
210 	dev->log_ctx = NULL;
211 	if (dev->log_file)
212 		fput(dev->log_file);
213 	dev->log_file = NULL;
214 	/* No one will access memory at this point */
215 	kfree(dev->memory);
216 	dev->memory = NULL;
217 	if (dev->mm)
218 		mmput(dev->mm);
219 	dev->mm = NULL;
220 }
221 
222 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
223 {
224 	u64 a = addr / VHOST_PAGE_SIZE / 8;
225 	/* Make sure 64 bit math will not overflow. */
226 	if (a > ULONG_MAX - (unsigned long)log_base ||
227 	    a + (unsigned long)log_base > ULONG_MAX)
228 		return -EFAULT;
229 
230 	return access_ok(VERIFY_WRITE, log_base + a,
231 			 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
232 }
233 
234 /* Caller should have vq mutex and device mutex. */
235 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
236 			       int log_all)
237 {
238 	int i;
239 
240         if (!mem)
241                 return 0;
242 
243 	for (i = 0; i < mem->nregions; ++i) {
244 		struct vhost_memory_region *m = mem->regions + i;
245 		unsigned long a = m->userspace_addr;
246 		if (m->memory_size > ULONG_MAX)
247 			return 0;
248 		else if (!access_ok(VERIFY_WRITE, (void __user *)a,
249 				    m->memory_size))
250 			return 0;
251 		else if (log_all && !log_access_ok(log_base,
252 						   m->guest_phys_addr,
253 						   m->memory_size))
254 			return 0;
255 	}
256 	return 1;
257 }
258 
259 /* Can we switch to this memory table? */
260 /* Caller should have device mutex but not vq mutex */
261 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
262 			    int log_all)
263 {
264 	int i;
265 	for (i = 0; i < d->nvqs; ++i) {
266 		int ok;
267 		mutex_lock(&d->vqs[i].mutex);
268 		/* If ring is inactive, will check when it's enabled. */
269 		if (d->vqs[i].private_data)
270 			ok = vq_memory_access_ok(d->vqs[i].log_base, mem,
271 						 log_all);
272 		else
273 			ok = 1;
274 		mutex_unlock(&d->vqs[i].mutex);
275 		if (!ok)
276 			return 0;
277 	}
278 	return 1;
279 }
280 
281 static int vq_access_ok(unsigned int num,
282 			struct vring_desc __user *desc,
283 			struct vring_avail __user *avail,
284 			struct vring_used __user *used)
285 {
286 	return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
287 	       access_ok(VERIFY_READ, avail,
288 			 sizeof *avail + num * sizeof *avail->ring) &&
289 	       access_ok(VERIFY_WRITE, used,
290 			sizeof *used + num * sizeof *used->ring);
291 }
292 
293 /* Can we log writes? */
294 /* Caller should have device mutex but not vq mutex */
295 int vhost_log_access_ok(struct vhost_dev *dev)
296 {
297 	return memory_access_ok(dev, dev->memory, 1);
298 }
299 
300 /* Verify access for write logging. */
301 /* Caller should have vq mutex and device mutex */
302 static int vq_log_access_ok(struct vhost_virtqueue *vq, void __user *log_base)
303 {
304 	return vq_memory_access_ok(log_base, vq->dev->memory,
305 			    vhost_has_feature(vq->dev, VHOST_F_LOG_ALL)) &&
306 		(!vq->log_used || log_access_ok(log_base, vq->log_addr,
307 					sizeof *vq->used +
308 					vq->num * sizeof *vq->used->ring));
309 }
310 
311 /* Can we start vq? */
312 /* Caller should have vq mutex and device mutex */
313 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
314 {
315 	return vq_access_ok(vq->num, vq->desc, vq->avail, vq->used) &&
316 		vq_log_access_ok(vq, vq->log_base);
317 }
318 
319 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
320 {
321 	struct vhost_memory mem, *newmem, *oldmem;
322 	unsigned long size = offsetof(struct vhost_memory, regions);
323 	if (copy_from_user(&mem, m, size))
324 		return -EFAULT;
325 	if (mem.padding)
326 		return -EOPNOTSUPP;
327 	if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
328 		return -E2BIG;
329 	newmem = kmalloc(size + mem.nregions * sizeof *m->regions, GFP_KERNEL);
330 	if (!newmem)
331 		return -ENOMEM;
332 
333 	memcpy(newmem, &mem, size);
334 	if (copy_from_user(newmem->regions, m->regions,
335 			   mem.nregions * sizeof *m->regions)) {
336 		kfree(newmem);
337 		return -EFAULT;
338 	}
339 
340 	if (!memory_access_ok(d, newmem, vhost_has_feature(d, VHOST_F_LOG_ALL))) {
341 		kfree(newmem);
342 		return -EFAULT;
343 	}
344 	oldmem = d->memory;
345 	rcu_assign_pointer(d->memory, newmem);
346 	synchronize_rcu();
347 	kfree(oldmem);
348 	return 0;
349 }
350 
351 static int init_used(struct vhost_virtqueue *vq,
352 		     struct vring_used __user *used)
353 {
354 	int r = put_user(vq->used_flags, &used->flags);
355 	if (r)
356 		return r;
357 	return get_user(vq->last_used_idx, &used->idx);
358 }
359 
360 static long vhost_set_vring(struct vhost_dev *d, int ioctl, void __user *argp)
361 {
362 	struct file *eventfp, *filep = NULL,
363 		    *pollstart = NULL, *pollstop = NULL;
364 	struct eventfd_ctx *ctx = NULL;
365 	u32 __user *idxp = argp;
366 	struct vhost_virtqueue *vq;
367 	struct vhost_vring_state s;
368 	struct vhost_vring_file f;
369 	struct vhost_vring_addr a;
370 	u32 idx;
371 	long r;
372 
373 	r = get_user(idx, idxp);
374 	if (r < 0)
375 		return r;
376 	if (idx >= d->nvqs)
377 		return -ENOBUFS;
378 
379 	vq = d->vqs + idx;
380 
381 	mutex_lock(&vq->mutex);
382 
383 	switch (ioctl) {
384 	case VHOST_SET_VRING_NUM:
385 		/* Resizing ring with an active backend?
386 		 * You don't want to do that. */
387 		if (vq->private_data) {
388 			r = -EBUSY;
389 			break;
390 		}
391 		if (copy_from_user(&s, argp, sizeof s)) {
392 			r = -EFAULT;
393 			break;
394 		}
395 		if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
396 			r = -EINVAL;
397 			break;
398 		}
399 		vq->num = s.num;
400 		break;
401 	case VHOST_SET_VRING_BASE:
402 		/* Moving base with an active backend?
403 		 * You don't want to do that. */
404 		if (vq->private_data) {
405 			r = -EBUSY;
406 			break;
407 		}
408 		if (copy_from_user(&s, argp, sizeof s)) {
409 			r = -EFAULT;
410 			break;
411 		}
412 		if (s.num > 0xffff) {
413 			r = -EINVAL;
414 			break;
415 		}
416 		vq->last_avail_idx = s.num;
417 		/* Forget the cached index value. */
418 		vq->avail_idx = vq->last_avail_idx;
419 		break;
420 	case VHOST_GET_VRING_BASE:
421 		s.index = idx;
422 		s.num = vq->last_avail_idx;
423 		if (copy_to_user(argp, &s, sizeof s))
424 			r = -EFAULT;
425 		break;
426 	case VHOST_SET_VRING_ADDR:
427 		if (copy_from_user(&a, argp, sizeof a)) {
428 			r = -EFAULT;
429 			break;
430 		}
431 		if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
432 			r = -EOPNOTSUPP;
433 			break;
434 		}
435 		/* For 32bit, verify that the top 32bits of the user
436 		   data are set to zero. */
437 		if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
438 		    (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
439 		    (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
440 			r = -EFAULT;
441 			break;
442 		}
443 		if ((a.avail_user_addr & (sizeof *vq->avail->ring - 1)) ||
444 		    (a.used_user_addr & (sizeof *vq->used->ring - 1)) ||
445 		    (a.log_guest_addr & (sizeof *vq->used->ring - 1))) {
446 			r = -EINVAL;
447 			break;
448 		}
449 
450 		/* We only verify access here if backend is configured.
451 		 * If it is not, we don't as size might not have been setup.
452 		 * We will verify when backend is configured. */
453 		if (vq->private_data) {
454 			if (!vq_access_ok(vq->num,
455 				(void __user *)(unsigned long)a.desc_user_addr,
456 				(void __user *)(unsigned long)a.avail_user_addr,
457 				(void __user *)(unsigned long)a.used_user_addr)) {
458 				r = -EINVAL;
459 				break;
460 			}
461 
462 			/* Also validate log access for used ring if enabled. */
463 			if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
464 			    !log_access_ok(vq->log_base, a.log_guest_addr,
465 					   sizeof *vq->used +
466 					   vq->num * sizeof *vq->used->ring)) {
467 				r = -EINVAL;
468 				break;
469 			}
470 		}
471 
472 		r = init_used(vq, (struct vring_used __user *)(unsigned long)
473 			      a.used_user_addr);
474 		if (r)
475 			break;
476 		vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
477 		vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
478 		vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
479 		vq->log_addr = a.log_guest_addr;
480 		vq->used = (void __user *)(unsigned long)a.used_user_addr;
481 		break;
482 	case VHOST_SET_VRING_KICK:
483 		if (copy_from_user(&f, argp, sizeof f)) {
484 			r = -EFAULT;
485 			break;
486 		}
487 		eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
488 		if (IS_ERR(eventfp)) {
489 			r = PTR_ERR(eventfp);
490 			break;
491 		}
492 		if (eventfp != vq->kick) {
493 			pollstop = filep = vq->kick;
494 			pollstart = vq->kick = eventfp;
495 		} else
496 			filep = eventfp;
497 		break;
498 	case VHOST_SET_VRING_CALL:
499 		if (copy_from_user(&f, argp, sizeof f)) {
500 			r = -EFAULT;
501 			break;
502 		}
503 		eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
504 		if (IS_ERR(eventfp)) {
505 			r = PTR_ERR(eventfp);
506 			break;
507 		}
508 		if (eventfp != vq->call) {
509 			filep = vq->call;
510 			ctx = vq->call_ctx;
511 			vq->call = eventfp;
512 			vq->call_ctx = eventfp ?
513 				eventfd_ctx_fileget(eventfp) : NULL;
514 		} else
515 			filep = eventfp;
516 		break;
517 	case VHOST_SET_VRING_ERR:
518 		if (copy_from_user(&f, argp, sizeof f)) {
519 			r = -EFAULT;
520 			break;
521 		}
522 		eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
523 		if (IS_ERR(eventfp)) {
524 			r = PTR_ERR(eventfp);
525 			break;
526 		}
527 		if (eventfp != vq->error) {
528 			filep = vq->error;
529 			vq->error = eventfp;
530 			ctx = vq->error_ctx;
531 			vq->error_ctx = eventfp ?
532 				eventfd_ctx_fileget(eventfp) : NULL;
533 		} else
534 			filep = eventfp;
535 		break;
536 	default:
537 		r = -ENOIOCTLCMD;
538 	}
539 
540 	if (pollstop && vq->handle_kick)
541 		vhost_poll_stop(&vq->poll);
542 
543 	if (ctx)
544 		eventfd_ctx_put(ctx);
545 	if (filep)
546 		fput(filep);
547 
548 	if (pollstart && vq->handle_kick)
549 		vhost_poll_start(&vq->poll, vq->kick);
550 
551 	mutex_unlock(&vq->mutex);
552 
553 	if (pollstop && vq->handle_kick)
554 		vhost_poll_flush(&vq->poll);
555 	return r;
556 }
557 
558 /* Caller must have device mutex */
559 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, unsigned long arg)
560 {
561 	void __user *argp = (void __user *)arg;
562 	struct file *eventfp, *filep = NULL;
563 	struct eventfd_ctx *ctx = NULL;
564 	u64 p;
565 	long r;
566 	int i, fd;
567 
568 	/* If you are not the owner, you can become one */
569 	if (ioctl == VHOST_SET_OWNER) {
570 		r = vhost_dev_set_owner(d);
571 		goto done;
572 	}
573 
574 	/* You must be the owner to do anything else */
575 	r = vhost_dev_check_owner(d);
576 	if (r)
577 		goto done;
578 
579 	switch (ioctl) {
580 	case VHOST_SET_MEM_TABLE:
581 		r = vhost_set_memory(d, argp);
582 		break;
583 	case VHOST_SET_LOG_BASE:
584 		if (copy_from_user(&p, argp, sizeof p)) {
585 			r = -EFAULT;
586 			break;
587 		}
588 		if ((u64)(unsigned long)p != p) {
589 			r = -EFAULT;
590 			break;
591 		}
592 		for (i = 0; i < d->nvqs; ++i) {
593 			struct vhost_virtqueue *vq;
594 			void __user *base = (void __user *)(unsigned long)p;
595 			vq = d->vqs + i;
596 			mutex_lock(&vq->mutex);
597 			/* If ring is inactive, will check when it's enabled. */
598 			if (vq->private_data && !vq_log_access_ok(vq, base))
599 				r = -EFAULT;
600 			else
601 				vq->log_base = base;
602 			mutex_unlock(&vq->mutex);
603 		}
604 		break;
605 	case VHOST_SET_LOG_FD:
606 		r = get_user(fd, (int __user *)argp);
607 		if (r < 0)
608 			break;
609 		eventfp = fd == -1 ? NULL : eventfd_fget(fd);
610 		if (IS_ERR(eventfp)) {
611 			r = PTR_ERR(eventfp);
612 			break;
613 		}
614 		if (eventfp != d->log_file) {
615 			filep = d->log_file;
616 			ctx = d->log_ctx;
617 			d->log_ctx = eventfp ?
618 				eventfd_ctx_fileget(eventfp) : NULL;
619 		} else
620 			filep = eventfp;
621 		for (i = 0; i < d->nvqs; ++i) {
622 			mutex_lock(&d->vqs[i].mutex);
623 			d->vqs[i].log_ctx = d->log_ctx;
624 			mutex_unlock(&d->vqs[i].mutex);
625 		}
626 		if (ctx)
627 			eventfd_ctx_put(ctx);
628 		if (filep)
629 			fput(filep);
630 		break;
631 	default:
632 		r = vhost_set_vring(d, ioctl, argp);
633 		break;
634 	}
635 done:
636 	return r;
637 }
638 
639 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
640 						     __u64 addr, __u32 len)
641 {
642 	struct vhost_memory_region *reg;
643 	int i;
644 	/* linear search is not brilliant, but we really have on the order of 6
645 	 * regions in practice */
646 	for (i = 0; i < mem->nregions; ++i) {
647 		reg = mem->regions + i;
648 		if (reg->guest_phys_addr <= addr &&
649 		    reg->guest_phys_addr + reg->memory_size - 1 >= addr)
650 			return reg;
651 	}
652 	return NULL;
653 }
654 
655 /* TODO: This is really inefficient.  We need something like get_user()
656  * (instruction directly accesses the data, with an exception table entry
657  * returning -EFAULT). See Documentation/x86/exception-tables.txt.
658  */
659 static int set_bit_to_user(int nr, void __user *addr)
660 {
661 	unsigned long log = (unsigned long)addr;
662 	struct page *page;
663 	void *base;
664 	int bit = nr + (log % PAGE_SIZE) * 8;
665 	int r;
666 	r = get_user_pages_fast(log, 1, 1, &page);
667 	if (r < 0)
668 		return r;
669 	BUG_ON(r != 1);
670 	base = kmap_atomic(page, KM_USER0);
671 	set_bit(bit, base);
672 	kunmap_atomic(base, KM_USER0);
673 	set_page_dirty_lock(page);
674 	put_page(page);
675 	return 0;
676 }
677 
678 static int log_write(void __user *log_base,
679 		     u64 write_address, u64 write_length)
680 {
681 	int r;
682 	if (!write_length)
683 		return 0;
684 	write_address /= VHOST_PAGE_SIZE;
685 	for (;;) {
686 		u64 base = (u64)(unsigned long)log_base;
687 		u64 log = base + write_address / 8;
688 		int bit = write_address % 8;
689 		if ((u64)(unsigned long)log != log)
690 			return -EFAULT;
691 		r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
692 		if (r < 0)
693 			return r;
694 		if (write_length <= VHOST_PAGE_SIZE)
695 			break;
696 		write_length -= VHOST_PAGE_SIZE;
697 		write_address += VHOST_PAGE_SIZE;
698 	}
699 	return r;
700 }
701 
702 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
703 		    unsigned int log_num, u64 len)
704 {
705 	int i, r;
706 
707 	/* Make sure data written is seen before log. */
708 	smp_wmb();
709 	for (i = 0; i < log_num; ++i) {
710 		u64 l = min(log[i].len, len);
711 		r = log_write(vq->log_base, log[i].addr, l);
712 		if (r < 0)
713 			return r;
714 		len -= l;
715 		if (!len)
716 			return 0;
717 	}
718 	if (vq->log_ctx)
719 		eventfd_signal(vq->log_ctx, 1);
720 	/* Length written exceeds what we have stored. This is a bug. */
721 	BUG();
722 	return 0;
723 }
724 
725 static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len,
726 			  struct iovec iov[], int iov_size)
727 {
728 	const struct vhost_memory_region *reg;
729 	struct vhost_memory *mem;
730 	struct iovec *_iov;
731 	u64 s = 0;
732 	int ret = 0;
733 
734 	rcu_read_lock();
735 
736 	mem = rcu_dereference(dev->memory);
737 	while ((u64)len > s) {
738 		u64 size;
739 		if (ret >= iov_size) {
740 			ret = -ENOBUFS;
741 			break;
742 		}
743 		reg = find_region(mem, addr, len);
744 		if (!reg) {
745 			ret = -EFAULT;
746 			break;
747 		}
748 		_iov = iov + ret;
749 		size = reg->memory_size - addr + reg->guest_phys_addr;
750 		_iov->iov_len = min((u64)len, size);
751 		_iov->iov_base = (void __user *)(unsigned long)
752 			(reg->userspace_addr + addr - reg->guest_phys_addr);
753 		s += size;
754 		addr += size;
755 		++ret;
756 	}
757 
758 	rcu_read_unlock();
759 	return ret;
760 }
761 
762 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
763  * function returns the next descriptor in the chain,
764  * or -1U if we're at the end. */
765 static unsigned next_desc(struct vring_desc *desc)
766 {
767 	unsigned int next;
768 
769 	/* If this descriptor says it doesn't chain, we're done. */
770 	if (!(desc->flags & VRING_DESC_F_NEXT))
771 		return -1U;
772 
773 	/* Check they're not leading us off end of descriptors. */
774 	next = desc->next;
775 	/* Make sure compiler knows to grab that: we don't want it changing! */
776 	/* We will use the result as an index in an array, so most
777 	 * architectures only need a compiler barrier here. */
778 	read_barrier_depends();
779 
780 	return next;
781 }
782 
783 static unsigned get_indirect(struct vhost_dev *dev, struct vhost_virtqueue *vq,
784 			     struct iovec iov[], unsigned int iov_size,
785 			     unsigned int *out_num, unsigned int *in_num,
786 			     struct vhost_log *log, unsigned int *log_num,
787 			     struct vring_desc *indirect)
788 {
789 	struct vring_desc desc;
790 	unsigned int i = 0, count, found = 0;
791 	int ret;
792 
793 	/* Sanity check */
794 	if (indirect->len % sizeof desc) {
795 		vq_err(vq, "Invalid length in indirect descriptor: "
796 		       "len 0x%llx not multiple of 0x%zx\n",
797 		       (unsigned long long)indirect->len,
798 		       sizeof desc);
799 		return -EINVAL;
800 	}
801 
802 	ret = translate_desc(dev, indirect->addr, indirect->len, vq->indirect,
803 			     ARRAY_SIZE(vq->indirect));
804 	if (ret < 0) {
805 		vq_err(vq, "Translation failure %d in indirect.\n", ret);
806 		return ret;
807 	}
808 
809 	/* We will use the result as an address to read from, so most
810 	 * architectures only need a compiler barrier here. */
811 	read_barrier_depends();
812 
813 	count = indirect->len / sizeof desc;
814 	/* Buffers are chained via a 16 bit next field, so
815 	 * we can have at most 2^16 of these. */
816 	if (count > USHRT_MAX + 1) {
817 		vq_err(vq, "Indirect buffer length too big: %d\n",
818 		       indirect->len);
819 		return -E2BIG;
820 	}
821 
822 	do {
823 		unsigned iov_count = *in_num + *out_num;
824 		if (++found > count) {
825 			vq_err(vq, "Loop detected: last one at %u "
826 			       "indirect size %u\n",
827 			       i, count);
828 			return -EINVAL;
829 		}
830 		if (memcpy_fromiovec((unsigned char *)&desc, vq->indirect,
831 				     sizeof desc)) {
832 			vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
833 			       i, (size_t)indirect->addr + i * sizeof desc);
834 			return -EINVAL;
835 		}
836 		if (desc.flags & VRING_DESC_F_INDIRECT) {
837 			vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
838 			       i, (size_t)indirect->addr + i * sizeof desc);
839 			return -EINVAL;
840 		}
841 
842 		ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
843 				     iov_size - iov_count);
844 		if (ret < 0) {
845 			vq_err(vq, "Translation failure %d indirect idx %d\n",
846 			       ret, i);
847 			return ret;
848 		}
849 		/* If this is an input descriptor, increment that count. */
850 		if (desc.flags & VRING_DESC_F_WRITE) {
851 			*in_num += ret;
852 			if (unlikely(log)) {
853 				log[*log_num].addr = desc.addr;
854 				log[*log_num].len = desc.len;
855 				++*log_num;
856 			}
857 		} else {
858 			/* If it's an output descriptor, they're all supposed
859 			 * to come before any input descriptors. */
860 			if (*in_num) {
861 				vq_err(vq, "Indirect descriptor "
862 				       "has out after in: idx %d\n", i);
863 				return -EINVAL;
864 			}
865 			*out_num += ret;
866 		}
867 	} while ((i = next_desc(&desc)) != -1);
868 	return 0;
869 }
870 
871 /* This looks in the virtqueue and for the first available buffer, and converts
872  * it to an iovec for convenient access.  Since descriptors consist of some
873  * number of output then some number of input descriptors, it's actually two
874  * iovecs, but we pack them into one and note how many of each there were.
875  *
876  * This function returns the descriptor number found, or vq->num (which
877  * is never a valid descriptor number) if none was found. */
878 unsigned vhost_get_vq_desc(struct vhost_dev *dev, struct vhost_virtqueue *vq,
879 			   struct iovec iov[], unsigned int iov_size,
880 			   unsigned int *out_num, unsigned int *in_num,
881 			   struct vhost_log *log, unsigned int *log_num)
882 {
883 	struct vring_desc desc;
884 	unsigned int i, head, found = 0;
885 	u16 last_avail_idx;
886 	int ret;
887 
888 	/* Check it isn't doing very strange things with descriptor numbers. */
889 	last_avail_idx = vq->last_avail_idx;
890 	if (get_user(vq->avail_idx, &vq->avail->idx)) {
891 		vq_err(vq, "Failed to access avail idx at %p\n",
892 		       &vq->avail->idx);
893 		return vq->num;
894 	}
895 
896 	if ((u16)(vq->avail_idx - last_avail_idx) > vq->num) {
897 		vq_err(vq, "Guest moved used index from %u to %u",
898 		       last_avail_idx, vq->avail_idx);
899 		return vq->num;
900 	}
901 
902 	/* If there's nothing new since last we looked, return invalid. */
903 	if (vq->avail_idx == last_avail_idx)
904 		return vq->num;
905 
906 	/* Only get avail ring entries after they have been exposed by guest. */
907 	smp_rmb();
908 
909 	/* Grab the next descriptor number they're advertising, and increment
910 	 * the index we've seen. */
911 	if (get_user(head, &vq->avail->ring[last_avail_idx % vq->num])) {
912 		vq_err(vq, "Failed to read head: idx %d address %p\n",
913 		       last_avail_idx,
914 		       &vq->avail->ring[last_avail_idx % vq->num]);
915 		return vq->num;
916 	}
917 
918 	/* If their number is silly, that's an error. */
919 	if (head >= vq->num) {
920 		vq_err(vq, "Guest says index %u > %u is available",
921 		       head, vq->num);
922 		return vq->num;
923 	}
924 
925 	/* When we start there are none of either input nor output. */
926 	*out_num = *in_num = 0;
927 	if (unlikely(log))
928 		*log_num = 0;
929 
930 	i = head;
931 	do {
932 		unsigned iov_count = *in_num + *out_num;
933 		if (i >= vq->num) {
934 			vq_err(vq, "Desc index is %u > %u, head = %u",
935 			       i, vq->num, head);
936 			return vq->num;
937 		}
938 		if (++found > vq->num) {
939 			vq_err(vq, "Loop detected: last one at %u "
940 			       "vq size %u head %u\n",
941 			       i, vq->num, head);
942 			return vq->num;
943 		}
944 		ret = copy_from_user(&desc, vq->desc + i, sizeof desc);
945 		if (ret) {
946 			vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
947 			       i, vq->desc + i);
948 			return vq->num;
949 		}
950 		if (desc.flags & VRING_DESC_F_INDIRECT) {
951 			ret = get_indirect(dev, vq, iov, iov_size,
952 					   out_num, in_num,
953 					   log, log_num, &desc);
954 			if (ret < 0) {
955 				vq_err(vq, "Failure detected "
956 				       "in indirect descriptor at idx %d\n", i);
957 				return vq->num;
958 			}
959 			continue;
960 		}
961 
962 		ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
963 				     iov_size - iov_count);
964 		if (ret < 0) {
965 			vq_err(vq, "Translation failure %d descriptor idx %d\n",
966 			       ret, i);
967 			return vq->num;
968 		}
969 		if (desc.flags & VRING_DESC_F_WRITE) {
970 			/* If this is an input descriptor,
971 			 * increment that count. */
972 			*in_num += ret;
973 			if (unlikely(log)) {
974 				log[*log_num].addr = desc.addr;
975 				log[*log_num].len = desc.len;
976 				++*log_num;
977 			}
978 		} else {
979 			/* If it's an output descriptor, they're all supposed
980 			 * to come before any input descriptors. */
981 			if (*in_num) {
982 				vq_err(vq, "Descriptor has out after in: "
983 				       "idx %d\n", i);
984 				return vq->num;
985 			}
986 			*out_num += ret;
987 		}
988 	} while ((i = next_desc(&desc)) != -1);
989 
990 	/* On success, increment avail index. */
991 	vq->last_avail_idx++;
992 	return head;
993 }
994 
995 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
996 void vhost_discard_vq_desc(struct vhost_virtqueue *vq)
997 {
998 	vq->last_avail_idx--;
999 }
1000 
1001 /* After we've used one of their buffers, we tell them about it.  We'll then
1002  * want to notify the guest, using eventfd. */
1003 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1004 {
1005 	struct vring_used_elem __user *used;
1006 
1007 	/* The virtqueue contains a ring of used buffers.  Get a pointer to the
1008 	 * next entry in that used ring. */
1009 	used = &vq->used->ring[vq->last_used_idx % vq->num];
1010 	if (put_user(head, &used->id)) {
1011 		vq_err(vq, "Failed to write used id");
1012 		return -EFAULT;
1013 	}
1014 	if (put_user(len, &used->len)) {
1015 		vq_err(vq, "Failed to write used len");
1016 		return -EFAULT;
1017 	}
1018 	/* Make sure buffer is written before we update index. */
1019 	smp_wmb();
1020 	if (put_user(vq->last_used_idx + 1, &vq->used->idx)) {
1021 		vq_err(vq, "Failed to increment used idx");
1022 		return -EFAULT;
1023 	}
1024 	if (unlikely(vq->log_used)) {
1025 		/* Make sure data is seen before log. */
1026 		smp_wmb();
1027 		/* Log used ring entry write. */
1028 		log_write(vq->log_base,
1029 			  vq->log_addr +
1030 			   ((void __user *)used - (void __user *)vq->used),
1031 			  sizeof *used);
1032 		/* Log used index update. */
1033 		log_write(vq->log_base,
1034 			  vq->log_addr + offsetof(struct vring_used, idx),
1035 			  sizeof vq->used->idx);
1036 		if (vq->log_ctx)
1037 			eventfd_signal(vq->log_ctx, 1);
1038 	}
1039 	vq->last_used_idx++;
1040 	return 0;
1041 }
1042 
1043 /* This actually signals the guest, using eventfd. */
1044 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1045 {
1046 	__u16 flags;
1047 	/* Flush out used index updates. This is paired
1048 	 * with the barrier that the Guest executes when enabling
1049 	 * interrupts. */
1050 	smp_mb();
1051 
1052 	if (get_user(flags, &vq->avail->flags)) {
1053 		vq_err(vq, "Failed to get flags");
1054 		return;
1055 	}
1056 
1057 	/* If they don't want an interrupt, don't signal, unless empty. */
1058 	if ((flags & VRING_AVAIL_F_NO_INTERRUPT) &&
1059 	    (vq->avail_idx != vq->last_avail_idx ||
1060 	     !vhost_has_feature(dev, VIRTIO_F_NOTIFY_ON_EMPTY)))
1061 		return;
1062 
1063 	/* Signal the Guest tell them we used something up. */
1064 	if (vq->call_ctx)
1065 		eventfd_signal(vq->call_ctx, 1);
1066 }
1067 
1068 /* And here's the combo meal deal.  Supersize me! */
1069 void vhost_add_used_and_signal(struct vhost_dev *dev,
1070 			       struct vhost_virtqueue *vq,
1071 			       unsigned int head, int len)
1072 {
1073 	vhost_add_used(vq, head, len);
1074 	vhost_signal(dev, vq);
1075 }
1076 
1077 /* OK, now we need to know about added descriptors. */
1078 bool vhost_enable_notify(struct vhost_virtqueue *vq)
1079 {
1080 	u16 avail_idx;
1081 	int r;
1082 	if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1083 		return false;
1084 	vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1085 	r = put_user(vq->used_flags, &vq->used->flags);
1086 	if (r) {
1087 		vq_err(vq, "Failed to enable notification at %p: %d\n",
1088 		       &vq->used->flags, r);
1089 		return false;
1090 	}
1091 	/* They could have slipped one in as we were doing that: make
1092 	 * sure it's written, then check again. */
1093 	smp_mb();
1094 	r = get_user(avail_idx, &vq->avail->idx);
1095 	if (r) {
1096 		vq_err(vq, "Failed to check avail idx at %p: %d\n",
1097 		       &vq->avail->idx, r);
1098 		return false;
1099 	}
1100 
1101 	return avail_idx != vq->last_avail_idx;
1102 }
1103 
1104 /* We don't need to be notified again. */
1105 void vhost_disable_notify(struct vhost_virtqueue *vq)
1106 {
1107 	int r;
1108 	if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1109 		return;
1110 	vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1111 	r = put_user(vq->used_flags, &vq->used->flags);
1112 	if (r)
1113 		vq_err(vq, "Failed to enable notification at %p: %d\n",
1114 		       &vq->used->flags, r);
1115 }
1116 
1117 int vhost_init(void)
1118 {
1119 	vhost_workqueue = create_singlethread_workqueue("vhost");
1120 	if (!vhost_workqueue)
1121 		return -ENOMEM;
1122 	return 0;
1123 }
1124 
1125 void vhost_cleanup(void)
1126 {
1127 	destroy_workqueue(vhost_workqueue);
1128 }
1129