vhost.c 62.7 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
2
3
4
5
6
7
/* Copyright (C) 2009 Red Hat, Inc.
 * Copyright (C) 2006 Rusty Russell IBM Corporation
 *
 * Author: Michael S. Tsirkin <mst@redhat.com>
 *
 * Inspiration, some code, and most witty comments come from
Rob Landley's avatar
Rob Landley committed
8
 * Documentation/virtual/lguest/lguest.c, by Rusty Russell
9
10
11
12
13
14
 *
 * Generic code for virtio server in host kernel.
 */

#include <linux/eventfd.h>
#include <linux/vhost.h>
15
#include <linux/uio.h>
16
#include <linux/mm.h>
17
#include <linux/mmu_context.h>
18
19
20
21
22
#include <linux/miscdevice.h>
#include <linux/mutex.h>
#include <linux/poll.h>
#include <linux/file.h>
#include <linux/highmem.h>
23
#include <linux/slab.h>
24
#include <linux/vmalloc.h>
25
#include <linux/kthread.h>
26
#include <linux/cgroup.h>
Asias He's avatar
Asias He committed
27
#include <linux/module.h>
28
#include <linux/sort.h>
29
#include <linux/sched/mm.h>
30
#include <linux/sched/signal.h>
31
#include <linux/interval_tree_generic.h>
32
#include <linux/nospec.h>
33
34
35

#include "vhost.h"

36
37
38
39
static ushort max_mem_regions = 64;
module_param(max_mem_regions, ushort, 0444);
MODULE_PARM_DESC(max_mem_regions,
	"Maximum number of memory regions in memory map. (default: 64)");
Jason Wang's avatar
Jason Wang committed
40
41
42
43
static int max_iotlb_entries = 2048;
module_param(max_iotlb_entries, int, 0444);
MODULE_PARM_DESC(max_iotlb_entries,
	"Maximum number of iotlb entries. (default: 2048)");
44

45
46
47
48
enum {
	VHOST_MEMORY_F_LOG = 0x1,
};

49
50
#define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
#define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
51

52
53
INTERVAL_TREE_DEFINE(struct vhost_umem_node,
		     rb, __u64, __subtree_last,
54
		     START, LAST, static inline, vhost_umem_interval_tree);
55

56
#ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
Greg Kurz's avatar
Greg Kurz committed
57
static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
58
59
60
61
{
	vq->user_be = !virtio_legacy_is_little_endian();
}

Greg Kurz's avatar
Greg Kurz committed
62
63
64
65
66
67
68
69
70
71
static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
{
	vq->user_be = true;
}

static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
{
	vq->user_be = false;
}

72
73
74
75
76
77
78
79
80
81
82
83
84
85
static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
{
	struct vhost_vring_state s;

	if (vq->private_data)
		return -EBUSY;

	if (copy_from_user(&s, argp, sizeof(s)))
		return -EFAULT;

	if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
	    s.num != VHOST_VRING_BIG_ENDIAN)
		return -EINVAL;

Greg Kurz's avatar
Greg Kurz committed
86
87
88
89
	if (s.num == VHOST_VRING_BIG_ENDIAN)
		vhost_enable_cross_endian_big(vq);
	else
		vhost_enable_cross_endian_little(vq);
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

	return 0;
}

static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
				   int __user *argp)
{
	struct vhost_vring_state s = {
		.index = idx,
		.num = vq->user_be
	};

	if (copy_to_user(argp, &s, sizeof(s)))
		return -EFAULT;

	return 0;
}

static void vhost_init_is_le(struct vhost_virtqueue *vq)
{
	/* Note for legacy virtio: user_be is initialized at reset time
	 * according to the host endianness. If userspace does not set an
	 * explicit endianness, the default behavior is native endian, as
	 * expected by legacy virtio.
	 */
	vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
}
#else
Greg Kurz's avatar
Greg Kurz committed
118
static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
{
}

static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
{
	return -ENOIOCTLCMD;
}

static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
				   int __user *argp)
{
	return -ENOIOCTLCMD;
}

static void vhost_init_is_le(struct vhost_virtqueue *vq)
{
135
136
	vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
		|| virtio_legacy_is_little_endian();
137
138
139
}
#endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */

Greg Kurz's avatar
Greg Kurz committed
140
141
static void vhost_reset_is_le(struct vhost_virtqueue *vq)
{
142
	vhost_init_is_le(vq);
Greg Kurz's avatar
Greg Kurz committed
143
144
}

Jason Wang's avatar
Jason Wang committed
145
146
147
148
149
150
151
152
153
154
155
156
157
struct vhost_flush_struct {
	struct vhost_work work;
	struct completion wait_event;
};

static void vhost_flush_work(struct vhost_work *work)
{
	struct vhost_flush_struct *s;

	s = container_of(work, struct vhost_flush_struct, work);
	complete(&s->wait_event);
}

158
159
160
161
162
static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
			    poll_table *pt)
{
	struct vhost_poll *poll;

163
	poll = container_of(pt, struct vhost_poll, table);
164
165
166
167
	poll->wqh = wqh;
	add_wait_queue(wqh, &poll->wait);
}

168
static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
169
170
			     void *key)
{
171
172
	struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);

Al Viro's avatar
Al Viro committed
173
	if (!(key_to_poll(key) & poll->mask))
174
175
		return 0;

176
	vhost_poll_queue(poll);
177
178
179
	return 0;
}

180
void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
181
{
Jason Wang's avatar
Jason Wang committed
182
	clear_bit(VHOST_WORK_QUEUED, &work->flags);
183
184
	work->fn = fn;
}
Asias He's avatar
Asias He committed
185
EXPORT_SYMBOL_GPL(vhost_work_init);
186

187
/* Init poll structure */
188
void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
Al Viro's avatar
Al Viro committed
189
		     __poll_t mask, struct vhost_dev *dev)
190
191
192
193
{
	init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
	init_poll_funcptr(&poll->table, vhost_poll_func);
	poll->mask = mask;
194
	poll->dev = dev;
195
	poll->wqh = NULL;
196

197
	vhost_work_init(&poll->work, fn);
198
}
Asias He's avatar
Asias He committed
199
EXPORT_SYMBOL_GPL(vhost_poll_init);
200
201
202

/* Start polling a file. We add ourselves to file's wait queue. The caller must
 * keep a reference to a file until after vhost_poll_stop is called. */
203
int vhost_poll_start(struct vhost_poll *poll, struct file *file)
204
{
205
	__poll_t mask;
206

207
208
209
	if (poll->wqh)
		return 0;

210
	mask = vfs_poll(file, &poll->table);
211
	if (mask)
Al Viro's avatar
Al Viro committed
212
		vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
213
	if (mask & EPOLLERR) {
214
		vhost_poll_stop(poll);
215
		return -EINVAL;
216
217
	}

218
	return 0;
219
}
Asias He's avatar
Asias He committed
220
EXPORT_SYMBOL_GPL(vhost_poll_start);
221
222
223
224
225

/* Stop polling a file. After this function returns, it becomes safe to drop the
 * file reference. You must also flush afterwards. */
void vhost_poll_stop(struct vhost_poll *poll)
{
226
227
228
229
	if (poll->wqh) {
		remove_wait_queue(poll->wqh, &poll->wait);
		poll->wqh = NULL;
	}
230
}
Asias He's avatar
Asias He committed
231
EXPORT_SYMBOL_GPL(vhost_poll_stop);
232

Jason Wang's avatar
Jason Wang committed
233
void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
234
{
Jason Wang's avatar
Jason Wang committed
235
	struct vhost_flush_struct flush;
236

Jason Wang's avatar
Jason Wang committed
237
238
239
	if (dev->worker) {
		init_completion(&flush.wait_event);
		vhost_work_init(&flush.work, vhost_flush_work);
240

Jason Wang's avatar
Jason Wang committed
241
242
243
		vhost_work_queue(dev, &flush.work);
		wait_for_completion(&flush.wait_event);
	}
244
}
Asias He's avatar
Asias He committed
245
EXPORT_SYMBOL_GPL(vhost_work_flush);
246

247
248
249
250
251
252
/* Flush any work that has been scheduled. When calling this, don't hold any
 * locks that are also used by the callback. */
void vhost_poll_flush(struct vhost_poll *poll)
{
	vhost_work_flush(poll->dev, &poll->work);
}
Asias He's avatar
Asias He committed
253
EXPORT_SYMBOL_GPL(vhost_poll_flush);
254

255
void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
256
{
Jason Wang's avatar
Jason Wang committed
257
258
	if (!dev->worker)
		return;
259

Jason Wang's avatar
Jason Wang committed
260
261
262
	if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
		/* We can only add the work to the list after we're
		 * sure it was not in the list.
263
		 * test_and_set_bit() implies a memory barrier.
Jason Wang's avatar
Jason Wang committed
264
265
		 */
		llist_add(&work->node, &dev->work_list);
266
267
		wake_up_process(dev->worker);
	}
268
}
Asias He's avatar
Asias He committed
269
EXPORT_SYMBOL_GPL(vhost_work_queue);
270

Jason Wang's avatar
Jason Wang committed
271
272
273
/* A lockless hint for busy polling code to exit the loop */
bool vhost_has_work(struct vhost_dev *dev)
{
Jason Wang's avatar
Jason Wang committed
274
	return !llist_empty(&dev->work_list);
Jason Wang's avatar
Jason Wang committed
275
276
277
}
EXPORT_SYMBOL_GPL(vhost_has_work);

278
279
280
281
void vhost_poll_queue(struct vhost_poll *poll)
{
	vhost_work_queue(poll->dev, &poll->work);
}
Asias He's avatar
Asias He committed
282
EXPORT_SYMBOL_GPL(vhost_poll_queue);
283

284
285
286
287
288
289
290
291
292
293
294
295
static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
{
	int j;

	for (j = 0; j < VHOST_NUM_ADDRS; j++)
		vq->meta_iotlb[j] = NULL;
}

static void vhost_vq_meta_reset(struct vhost_dev *d)
{
	int i;

296
	for (i = 0; i < d->nvqs; ++i)
297
298
299
		__vhost_vq_meta_reset(d->vqs[i]);
}

300
301
302
303
304
305
306
307
308
309
static void vhost_vq_reset(struct vhost_dev *dev,
			   struct vhost_virtqueue *vq)
{
	vq->num = 1;
	vq->desc = NULL;
	vq->avail = NULL;
	vq->used = NULL;
	vq->last_avail_idx = 0;
	vq->avail_idx = 0;
	vq->last_used_idx = 0;
310
311
	vq->signalled_used = 0;
	vq->signalled_used_valid = false;
312
313
314
315
	vq->used_flags = 0;
	vq->log_used = false;
	vq->log_addr = -1ull;
	vq->private_data = NULL;
316
	vq->acked_features = 0;
317
	vq->acked_backend_features = 0;
318
319
320
321
	vq->log_base = NULL;
	vq->error_ctx = NULL;
	vq->kick = NULL;
	vq->call_ctx = NULL;
322
	vq->log_ctx = NULL;
Greg Kurz's avatar
Greg Kurz committed
323
324
	vhost_reset_is_le(vq);
	vhost_disable_cross_endian(vq);
Jason Wang's avatar
Jason Wang committed
325
	vq->busyloop_timeout = 0;
326
	vq->umem = NULL;
Jason Wang's avatar
Jason Wang committed
327
	vq->iotlb = NULL;
328
	__vhost_vq_meta_reset(vq);
329
330
}

331
332
333
static int vhost_worker(void *data)
{
	struct vhost_dev *dev = data;
Jason Wang's avatar
Jason Wang committed
334
335
	struct vhost_work *work, *work_next;
	struct llist_node *node;
336
	mm_segment_t oldfs = get_fs();
337

338
	set_fs(USER_DS);
339
340
	use_mm(dev->mm);

341
342
343
344
345
346
	for (;;) {
		/* mb paired w/ kthread_stop */
		set_current_state(TASK_INTERRUPTIBLE);

		if (kthread_should_stop()) {
			__set_current_state(TASK_RUNNING);
347
			break;
348
		}
Jason Wang's avatar
Jason Wang committed
349
350
351
352
353
354
355
356
357
358

		node = llist_del_all(&dev->work_list);
		if (!node)
			schedule();

		node = llist_reverse_order(node);
		/* make sure flag is seen after deletion */
		smp_wmb();
		llist_for_each_entry_safe(work, work_next, node, node) {
			clear_bit(VHOST_WORK_QUEUED, &work->flags);
359
360
			__set_current_state(TASK_RUNNING);
			work->fn(work);
361
362
			if (need_resched())
				schedule();
Jason Wang's avatar
Jason Wang committed
363
		}
364
	}
365
	unuse_mm(dev->mm);
366
	set_fs(oldfs);
367
	return 0;
368
369
}

370
371
372
373
374
375
376
377
378
379
static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
{
	kfree(vq->indirect);
	vq->indirect = NULL;
	kfree(vq->log);
	vq->log = NULL;
	kfree(vq->heads);
	vq->heads = NULL;
}

Jason Wang's avatar
Jason Wang committed
380
381
382
/* Helper to allocate iovec buffers for all vqs. */
static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
{
Asias He's avatar
Asias He committed
383
	struct vhost_virtqueue *vq;
Jason Wang's avatar
Jason Wang committed
384
	int i;
385

Jason Wang's avatar
Jason Wang committed
386
	for (i = 0; i < dev->nvqs; ++i) {
Asias He's avatar
Asias He committed
387
		vq = dev->vqs[i];
388
389
390
		vq->indirect = kmalloc_array(UIO_MAXIOV,
					     sizeof(*vq->indirect),
					     GFP_KERNEL);
Jason Wang's avatar
Jason Wang committed
391
		vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
392
					GFP_KERNEL);
Jason Wang's avatar
Jason Wang committed
393
		vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
394
					  GFP_KERNEL);
Asias He's avatar
Asias He committed
395
		if (!vq->indirect || !vq->log || !vq->heads)
Jason Wang's avatar
Jason Wang committed
396
397
398
			goto err_nomem;
	}
	return 0;
399

Jason Wang's avatar
Jason Wang committed
400
err_nomem:
401
	for (; i >= 0; --i)
402
		vhost_vq_free_iovecs(dev->vqs[i]);
Jason Wang's avatar
Jason Wang committed
403
404
405
406
407
408
	return -ENOMEM;
}

static void vhost_dev_free_iovecs(struct vhost_dev *dev)
{
	int i;
409

410
	for (i = 0; i < dev->nvqs; ++i)
411
		vhost_vq_free_iovecs(dev->vqs[i]);
Jason Wang's avatar
Jason Wang committed
412
413
}

414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
			  int pkts, int total_len)
{
	struct vhost_dev *dev = vq->dev;

	if ((dev->byte_weight && total_len >= dev->byte_weight) ||
	    pkts >= dev->weight) {
		vhost_poll_queue(&vq->poll);
		return true;
	}

	return false;
}
EXPORT_SYMBOL_GPL(vhost_exceeds_weight);

429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
				   unsigned int num)
{
	size_t event __maybe_unused =
	       vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;

	return sizeof(*vq->avail) +
	       sizeof(*vq->avail->ring) * num + event;
}

static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
				  unsigned int num)
{
	size_t event __maybe_unused =
	       vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;

	return sizeof(*vq->used) +
	       sizeof(*vq->used->ring) * num + event;
}

static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
				  unsigned int num)
{
	return sizeof(*vq->desc) * num;
}

Zhi Yong Wu's avatar
Zhi Yong Wu committed
455
void vhost_dev_init(struct vhost_dev *dev,
456
457
		    struct vhost_virtqueue **vqs, int nvqs,
		    int iov_limit, int weight, int byte_weight)
458
{
Asias He's avatar
Asias He committed
459
	struct vhost_virtqueue *vq;
460
	int i;
461

462
463
464
465
	dev->vqs = vqs;
	dev->nvqs = nvqs;
	mutex_init(&dev->mutex);
	dev->log_ctx = NULL;
466
	dev->umem = NULL;
Jason Wang's avatar
Jason Wang committed
467
	dev->iotlb = NULL;
468
	dev->mm = NULL;
469
	dev->worker = NULL;
Jason Wang's avatar
Jason Wang committed
470
	dev->iov_limit = iov_limit;
471
472
	dev->weight = weight;
	dev->byte_weight = byte_weight;
Jason Wang's avatar
Jason Wang committed
473
	init_llist_head(&dev->work_list);
Jason Wang's avatar
Jason Wang committed
474
475
476
477
	init_waitqueue_head(&dev->wait);
	INIT_LIST_HEAD(&dev->read_list);
	INIT_LIST_HEAD(&dev->pending_list);
	spin_lock_init(&dev->iotlb_lock);
478

479
480

	for (i = 0; i < dev->nvqs; ++i) {
Asias He's avatar
Asias He committed
481
482
483
484
485
486
487
488
489
		vq = dev->vqs[i];
		vq->log = NULL;
		vq->indirect = NULL;
		vq->heads = NULL;
		vq->dev = dev;
		mutex_init(&vq->mutex);
		vhost_vq_reset(dev, vq);
		if (vq->handle_kick)
			vhost_poll_init(&vq->poll, vq->handle_kick,
490
					EPOLLIN, dev);
491
492
	}
}
Asias He's avatar
Asias He committed
493
EXPORT_SYMBOL_GPL(vhost_dev_init);
494
495
496
497
498
499
500

/* Caller should have device mutex */
long vhost_dev_check_owner(struct vhost_dev *dev)
{
	/* Are you the owner? If not, I don't think you mean to do that */
	return dev->mm == current->mm ? 0 : -EPERM;
}
Asias He's avatar
Asias He committed
501
EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
502

503
struct vhost_attach_cgroups_struct {
504
505
506
	struct vhost_work work;
	struct task_struct *owner;
	int ret;
507
508
509
510
};

static void vhost_attach_cgroups_work(struct vhost_work *work)
{
511
512
513
514
	struct vhost_attach_cgroups_struct *s;

	s = container_of(work, struct vhost_attach_cgroups_struct, work);
	s->ret = cgroup_attach_task_all(s->owner, current);
515
516
517
518
}

static int vhost_attach_cgroups(struct vhost_dev *dev)
{
519
520
521
522
523
524
525
	struct vhost_attach_cgroups_struct attach;

	attach.owner = current;
	vhost_work_init(&attach.work, vhost_attach_cgroups_work);
	vhost_work_queue(dev, &attach.work);
	vhost_work_flush(dev, &attach.work);
	return attach.ret;
526
527
}

528
529
530
531
532
/* Caller should have device mutex */
bool vhost_dev_has_owner(struct vhost_dev *dev)
{
	return dev->mm;
}
Asias He's avatar
Asias He committed
533
EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
534

535
/* Caller should have device mutex */
Asias He's avatar
Asias He committed
536
long vhost_dev_set_owner(struct vhost_dev *dev)
537
{
538
539
	struct task_struct *worker;
	int err;
540

541
	/* Is there an owner already? */
542
	if (vhost_dev_has_owner(dev)) {
543
544
545
		err = -EBUSY;
		goto err_mm;
	}
546

547
548
	/* No owner, become one */
	dev->mm = get_task_mm(current);
549
550
551
552
553
554
555
	worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
	if (IS_ERR(worker)) {
		err = PTR_ERR(worker);
		goto err_worker;
	}

	dev->worker = worker;
556
557
558
	wake_up_process(worker);	/* avoid contributing to loadavg */

	err = vhost_attach_cgroups(dev);
559
560
	if (err)
		goto err_cgroup;
561

Jason Wang's avatar
Jason Wang committed
562
563
564
565
	err = vhost_dev_alloc_iovecs(dev);
	if (err)
		goto err_cgroup;

566
	return 0;
567
568
err_cgroup:
	kthread_stop(worker);
Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
569
	dev->worker = NULL;
570
571
572
573
574
575
err_worker:
	if (dev->mm)
		mmput(dev->mm);
	dev->mm = NULL;
err_mm:
	return err;
576
}
Asias He's avatar
Asias He committed
577
EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
578

579
580
struct vhost_umem *vhost_dev_reset_owner_prepare(void)
{
581
	return kvzalloc(sizeof(struct vhost_umem), GFP_KERNEL);
582
}
Asias He's avatar
Asias He committed
583
EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
584

585
/* Caller should have device mutex */
586
void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_umem *umem)
587
{
588
589
	int i;

590
	vhost_dev_cleanup(dev);
591

592
	/* Restore memory to default empty mapping. */
593
594
	INIT_LIST_HEAD(&umem->umem_list);
	dev->umem = umem;
595
596
597
598
	/* We don't need VQ locks below since vhost_dev_cleanup makes sure
	 * VQs aren't running.
	 */
	for (i = 0; i < dev->nvqs; ++i)
599
		dev->vqs[i]->umem = umem;
600
}
Asias He's avatar
Asias He committed
601
EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
602

603
void vhost_dev_stop(struct vhost_dev *dev)
604
605
{
	int i;
606
607

	for (i = 0; i < dev->nvqs; ++i) {
608
609
610
		if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
			vhost_poll_stop(&dev->vqs[i]->poll);
			vhost_poll_flush(&dev->vqs[i]->poll);
611
		}
612
613
	}
}
Asias He's avatar
Asias He committed
614
EXPORT_SYMBOL_GPL(vhost_dev_stop);
615

Jason Wang's avatar
Jason Wang committed
616
617
618
619
620
621
622
623
624
static void vhost_umem_free(struct vhost_umem *umem,
			    struct vhost_umem_node *node)
{
	vhost_umem_interval_tree_remove(node, &umem->umem_tree);
	list_del(&node->link);
	kfree(node);
	umem->numem--;
}

625
626
627
628
629
630
631
static void vhost_umem_clean(struct vhost_umem *umem)
{
	struct vhost_umem_node *node, *tmp;

	if (!umem)
		return;

Jason Wang's avatar
Jason Wang committed
632
633
634
	list_for_each_entry_safe(node, tmp, &umem->umem_list, link)
		vhost_umem_free(umem, node);

635
636
637
	kvfree(umem);
}

Jason Wang's avatar
Jason Wang committed
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
static void vhost_clear_msg(struct vhost_dev *dev)
{
	struct vhost_msg_node *node, *n;

	spin_lock(&dev->iotlb_lock);

	list_for_each_entry_safe(node, n, &dev->read_list, node) {
		list_del(&node->node);
		kfree(node);
	}

	list_for_each_entry_safe(node, n, &dev->pending_list, node) {
		list_del(&node->node);
		kfree(node);
	}

	spin_unlock(&dev->iotlb_lock);
}

657
void vhost_dev_cleanup(struct vhost_dev *dev)
658
659
{
	int i;
660

661
	for (i = 0; i < dev->nvqs; ++i) {
662
663
664
665
666
667
668
		if (dev->vqs[i]->error_ctx)
			eventfd_ctx_put(dev->vqs[i]->error_ctx);
		if (dev->vqs[i]->kick)
			fput(dev->vqs[i]->kick);
		if (dev->vqs[i]->call_ctx)
			eventfd_ctx_put(dev->vqs[i]->call_ctx);
		vhost_vq_reset(dev, dev->vqs[i]);
669
	}
Jason Wang's avatar
Jason Wang committed
670
	vhost_dev_free_iovecs(dev);
671
672
673
674
	if (dev->log_ctx)
		eventfd_ctx_put(dev->log_ctx);
	dev->log_ctx = NULL;
	/* No one will access memory at this point */
675
676
	vhost_umem_clean(dev->umem);
	dev->umem = NULL;
Jason Wang's avatar
Jason Wang committed
677
678
679
	vhost_umem_clean(dev->iotlb);
	dev->iotlb = NULL;
	vhost_clear_msg(dev);
680
	wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
Jason Wang's avatar
Jason Wang committed
681
	WARN_ON(!llist_empty(&dev->work_list));
682
683
684
685
	if (dev->worker) {
		kthread_stop(dev->worker);
		dev->worker = NULL;
	}
686
	if (dev->mm)
687
688
		mmput(dev->mm);
	dev->mm = NULL;
689
}
Asias He's avatar
Asias He committed
690
EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
691

692
static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
693
694
{
	u64 a = addr / VHOST_PAGE_SIZE / 8;
695

696
697
698
	/* Make sure 64 bit math will not overflow. */
	if (a > ULONG_MAX - (unsigned long)log_base ||
	    a + (unsigned long)log_base > ULONG_MAX)
699
		return false;
700

701
	return access_ok(log_base + a,
702
703
704
			 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
}

705
706
707
708
709
710
static bool vhost_overflow(u64 uaddr, u64 size)
{
	/* Make sure 64 bit math will not overflow. */
	return uaddr > ULONG_MAX || size > ULONG_MAX || uaddr > ULONG_MAX - size;
}

711
/* Caller should have vq mutex and device mutex. */
712
713
static bool vq_memory_access_ok(void __user *log_base, struct vhost_umem *umem,
				int log_all)
714
{
715
	struct vhost_umem_node *node;
716

717
	if (!umem)
718
		return false;
719

720
721
722
	list_for_each_entry(node, &umem->umem_list, link) {
		unsigned long a = node->userspace_addr;

723
		if (vhost_overflow(node->userspace_addr, node->size))
724
			return false;
725
726


727
		if (!access_ok((void __user *)a,
728
				    node->size))
729
			return false;
730
		else if (log_all && !log_access_ok(log_base,
731
732
						   node->start,
						   node->size))
733
			return false;
734
	}
735
	return true;
736
737
}

738
739
740
741
742
743
744
745
746
747
748
749
static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
					       u64 addr, unsigned int size,
					       int type)
{
	const struct vhost_umem_node *node = vq->meta_iotlb[type];

	if (!node)
		return NULL;

	return (void *)(uintptr_t)(node->userspace_addr + addr - node->start);
}

750
751
/* Can we switch to this memory table? */
/* Caller should have device mutex but not vq mutex */
752
753
static bool memory_access_ok(struct vhost_dev *d, struct vhost_umem *umem,
			     int log_all)
754
755
{
	int i;
756

757
	for (i = 0; i < d->nvqs; ++i) {
758
		bool ok;
759
760
		bool log;

761
		mutex_lock(&d->vqs[i]->mutex);
762
		log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
763
		/* If ring is inactive, will check when it's enabled. */
764
		if (d->vqs[i]->private_data)
765
766
			ok = vq_memory_access_ok(d->vqs[i]->log_base,
						 umem, log);
767
		else
768
			ok = true;
769
		mutex_unlock(&d->vqs[i]->mutex);
770
		if (!ok)
771
			return false;
772
	}
773
	return true;
774
775
}

Jason Wang's avatar
Jason Wang committed
776
777
static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
			  struct iovec iov[], int iov_size, int access);
778

779
static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
780
781
			      const void *from, unsigned size)
{
Jason Wang's avatar
Jason Wang committed
782
	int ret;
783

Jason Wang's avatar
Jason Wang committed
784
785
786
787
788
789
790
791
792
	if (!vq->iotlb)
		return __copy_to_user(to, from, size);
	else {
		/* This function should be called after iotlb
		 * prefetch, which means we're sure that all vq
		 * could be access through iotlb. So -EAGAIN should
		 * not happen in this case.
		 */
		struct iov_iter t;
793
794
		void __user *uaddr = vhost_vq_meta_fetch(vq,
				     (u64)(uintptr_t)to, size,
Eric Auger's avatar
Eric Auger committed
795
				     VHOST_ADDR_USED);
796
797
798
799

		if (uaddr)
			return __copy_to_user(uaddr, from, size);

Jason Wang's avatar
Jason Wang committed
800
801
802
803
804
805
806
807
808
809
810
811
812
		ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
				     ARRAY_SIZE(vq->iotlb_iov),
				     VHOST_ACCESS_WO);
		if (ret < 0)
			goto out;
		iov_iter_init(&t, WRITE, vq->iotlb_iov, ret, size);
		ret = copy_to_iter(from, size, &t);
		if (ret == size)
			ret = 0;
	}
out:
	return ret;
}
813
814

static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
815
				void __user *from, unsigned size)
816
{
Jason Wang's avatar
Jason Wang committed
817
818
819
820
821
822
823
824
825
826
	int ret;

	if (!vq->iotlb)
		return __copy_from_user(to, from, size);
	else {
		/* This function should be called after iotlb
		 * prefetch, which means we're sure that vq
		 * could be access through iotlb. So -EAGAIN should
		 * not happen in this case.
		 */
827
828
829
		void __user *uaddr = vhost_vq_meta_fetch(vq,
				     (u64)(uintptr_t)from, size,
				     VHOST_ADDR_DESC);
Jason Wang's avatar
Jason Wang committed
830
		struct iov_iter f;
831
832
833
834

		if (uaddr)
			return __copy_from_user(to, uaddr, size);

Jason Wang's avatar
Jason Wang committed
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
		ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
				     ARRAY_SIZE(vq->iotlb_iov),
				     VHOST_ACCESS_RO);
		if (ret < 0) {
			vq_err(vq, "IOTLB translation failure: uaddr "
			       "%p size 0x%llx\n", from,
			       (unsigned long long) size);
			goto out;
		}
		iov_iter_init(&f, READ, vq->iotlb_iov, ret, size);
		ret = copy_from_iter(to, size, &f);
		if (ret == size)
			ret = 0;
	}

out:
	return ret;
}

854
855
856
static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
					  void __user *addr, unsigned int size,
					  int type)
Jason Wang's avatar
Jason Wang committed
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
{
	int ret;

	ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
			     ARRAY_SIZE(vq->iotlb_iov),
			     VHOST_ACCESS_RO);
	if (ret < 0) {
		vq_err(vq, "IOTLB translation failure: uaddr "
			"%p size 0x%llx\n", addr,
			(unsigned long long) size);
		return NULL;
	}

	if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
		vq_err(vq, "Non atomic userspace memory access: uaddr "
			"%p size 0x%llx\n", addr,
			(unsigned long long) size);
		return NULL;
	}

	return vq->iotlb_iov[0].iov_base;
}

880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
/* This function should be called after iotlb
 * prefetch, which means we're sure that vq
 * could be access through iotlb. So -EAGAIN should
 * not happen in this case.
 */
static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
					    void *addr, unsigned int size,
					    int type)
{
	void __user *uaddr = vhost_vq_meta_fetch(vq,
			     (u64)(uintptr_t)addr, size, type);
	if (uaddr)
		return uaddr;

	return __vhost_get_user_slow(vq, addr, size, type);
}

#define vhost_put_user(vq, x, ptr)		\
Jason Wang's avatar
Jason Wang committed
898
899
900
901
902
903
({ \
	int ret = -EFAULT; \
	if (!vq->iotlb) { \
		ret = __put_user(x, ptr); \
	} else { \
		__typeof__(ptr) to = \
904
905
			(__typeof__(ptr)) __vhost_get_user(vq, ptr,	\
					  sizeof(*ptr), VHOST_ADDR_USED); \
Jason Wang's avatar
Jason Wang committed
906
907
908
909
910
911
912
913
		if (to != NULL) \
			ret = __put_user(x, to); \
		else \
			ret = -EFAULT;	\
	} \
	ret; \
})

914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
{
	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
			      vhost_avail_event(vq));
}

static inline int vhost_put_used(struct vhost_virtqueue *vq,
				 struct vring_used_elem *head, int idx,
				 int count)
{
	return vhost_copy_to_user(vq, vq->used->ring + idx, head,
				  count * sizeof(*head));
}

static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)

{
	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
			      &vq->used->flags);
}

static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)

{
	return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
			      &vq->used->idx);
}

942
#define vhost_get_user(vq, x, ptr, type)		\
Jason Wang's avatar
Jason Wang committed
943
944
945
946
947
948
({ \
	int ret; \
	if (!vq->iotlb) { \
		ret = __get_user(x, ptr); \
	} else { \
		__typeof__(ptr) from = \
949
950
951
			(__typeof__(ptr)) __vhost_get_user(vq, ptr, \
							   sizeof(*ptr), \
							   type); \
Jason Wang's avatar
Jason Wang committed
952
953
954
955
956
957
958
959
		if (from != NULL) \
			ret = __get_user(x, from); \
		else \
			ret = -EFAULT; \
	} \
	ret; \
})

960
961
962
963
964
965
#define vhost_get_avail(vq, x, ptr) \
	vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)

#define vhost_get_used(vq, x, ptr) \
	vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)

966
967
968
969
970
971
972
973
974
975
976
977
978
979
static void vhost_dev_lock_vqs(struct vhost_dev *d)
{
	int i = 0;
	for (i = 0; i < d->nvqs; ++i)
		mutex_lock_nested(&d->vqs[i]->mutex, i);
}

static void vhost_dev_unlock_vqs(struct vhost_dev *d)
{
	int i = 0;
	for (i = 0; i < d->nvqs; ++i)
		mutex_unlock(&d->vqs[i]->mutex);
}

980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
				      __virtio16 *idx)
{
	return vhost_get_avail(vq, *idx, &vq->avail->idx);
}

static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
				       __virtio16 *head, int idx)
{
	return vhost_get_avail(vq, *head,
			       &vq->avail->ring[idx & (vq->num - 1)]);
}

static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
					__virtio16 *flags)
{
	return vhost_get_avail(vq, *flags, &vq->avail->flags);
}

static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
				       __virtio16 *event)
{
	return vhost_get_avail(vq, *event, vhost_used_event(vq));
}

static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
				     __virtio16 *idx)
{
	return vhost_get_used(vq, *idx, &vq->used->idx);
}

static inline int vhost_get_desc(struct vhost_virtqueue *vq,
				 struct vring_desc *desc, int idx)
{
	return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
}

Jason Wang's avatar
Jason Wang committed
1017
1018
1019
1020
static int vhost_new_umem_range(struct vhost_umem *umem,
				u64 start, u64 size, u64 end,
				u64 userspace_addr, int perm)
{
1021
	struct vhost_umem_node *tmp, *node;
Jason Wang's avatar
Jason Wang committed
1022

1023
1024
1025
1026
	if (!size)
		return -EFAULT;

	node = kmalloc(sizeof(*node), GFP_ATOMIC);
Jason Wang's avatar
Jason Wang committed
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
	if (!node)
		return -ENOMEM;

	if (umem->numem == max_iotlb_entries) {
		tmp = list_first_entry(&umem->umem_list, typeof(*tmp), link);
		vhost_umem_free(umem, tmp);
	}

	node->start = start;
	node->size = size;
	node->last = end;
	node->userspace_addr = userspace_addr;
	node->perm = perm;
	INIT_LIST_HEAD(&node->link);
	list_add_tail(&node->link, &umem->umem_list);
	vhost_umem_interval_tree_insert(node, &umem->umem_tree);
	umem->numem++;

	return 0;
}

static void vhost_del_umem_range(struct vhost_umem *umem,
				 u64 start, u64 end)
{
	struct vhost_umem_node *node;

	while ((node = vhost_umem_interval_tree_iter_first(&umem->umem_tree,
							   start, end)))
		vhost_umem_free(umem, node);
}

static void vhost_iotlb_notify_vq(struct vhost_dev *d,
				  struct vhost_iotlb_msg *msg)
{
	struct vhost_msg_node *node, *n;

	spin_lock(&d->iotlb_lock);

	list_for_each_entry_safe(node, n, &d->pending_list, node) {
		struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
		if (msg->iova <= vq_msg->iova &&
1068
		    msg->iova + msg->size - 1 >= vq_msg->iova &&
Jason Wang's avatar
Jason Wang committed
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
		    vq_msg->type == VHOST_IOTLB_MISS) {
			vhost_poll_queue(&node->vq->poll);
			list_del(&node->node);
			kfree(node);
		}
	}

	spin_unlock(&d->iotlb_lock);
}

1079
static bool umem_access_ok(u64 uaddr, u64 size, int access)
Jason Wang's avatar
Jason Wang committed
1080
1081
1082
{
	unsigned long a = uaddr;

1083
1084
	/* Make sure 64 bit math will not overflow. */
	if (vhost_overflow(uaddr, size))
1085
		return false;
1086

Jason Wang's avatar
Jason Wang committed
1087
	if ((access & VHOST_ACCESS_RO) &&
1088
	    !access_ok((void __user *)a, size))
1089
		return false;
Jason Wang's avatar
Jason Wang committed
1090
	if ((access & VHOST_ACCESS_WO) &&
1091
	    !access_ok((void __user *)a, size))
1092
1093
		return false;
	return true;
Jason Wang's avatar
Jason Wang committed
1094
1095
}

1096
1097
static int vhost_process_iotlb_msg(struct vhost_dev *dev,
				   struct vhost_iotlb_msg *msg)
Jason Wang's avatar
Jason Wang committed
1098
1099
1100
{
	int ret = 0;

1101
	mutex_lock(&dev->mutex);
1102
	vhost_dev_lock_vqs(dev);
Jason Wang's avatar
Jason Wang committed
1103
1104
1105
1106
1107
1108
	switch (msg->type) {
	case VHOST_IOTLB_UPDATE:
		if (!dev->iotlb) {
			ret = -EFAULT;
			break;
		}
1109
		if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
Jason Wang's avatar
Jason Wang committed
1110
1111
1112
			ret = -EFAULT;
			break;
		}
1113
		vhost_vq_meta_reset(dev);
Jason Wang's avatar
Jason Wang committed
1114
1115
1116
1117
1118
1119
1120
1121
1122
		if (vhost_new_umem_range(dev->iotlb, msg->iova, msg->size,
					 msg->iova + msg->size - 1,
					 msg->uaddr, msg->perm)) {
			ret = -ENOMEM;
			break;
		}
		vhost_iotlb_notify_vq(dev, msg);
		break;
	case VHOST_IOTLB_INVALIDATE:
1123
1124
1125
1126
		if (!dev->iotlb) {
			ret = -EFAULT;
			break;
		}
1127
		vhost_vq_meta_reset(dev);
Jason Wang's avatar
Jason Wang committed
1128
1129
1130
1131
1132
1133
1134
1135
		vhost_del_umem_range(dev->iotlb, msg->iova,
				     msg->iova + msg->size - 1);
		break;
	default:
		ret = -EINVAL;
		break;
	}

1136
	vhost_dev_unlock_vqs(dev);
1137
1138
	mutex_unlock(&dev->mutex);

Jason Wang's avatar
Jason Wang committed
1139
1140
1141
1142
1143
	return ret;
}
ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
			     struct iov_iter *from)
{
1144
1145
1146
	struct vhost_iotlb_msg msg;
	size_t offset;
	int type, ret;
Jason Wang's avatar
Jason Wang committed
1147

1148
	ret = copy_from_iter(&type, sizeof(type), from);
1149
1150
	if (ret != sizeof(type)) {
		ret = -EINVAL;
Jason Wang's avatar
Jason Wang committed
1151
		goto done;
1152
	}
Jason Wang's avatar
Jason Wang committed
1153

1154
	switch (type) {
Jason Wang's avatar
Jason Wang committed
1155
	case VHOST_IOTLB_MSG:
1156
1157
1158
1159
1160
1161
1162
		/* There maybe a hole after type for V1 message type,
		 * so skip it here.
		 */
		offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
		break;
	case VHOST_IOTLB_MSG_V2:
<