vhost: add helper to parse userspace vring state/file
[linux-block.git] / drivers / vhost / vhost.c
CommitLineData
7a338472 1// SPDX-License-Identifier: GPL-2.0-only
3a4d5c94
MT
2/* Copyright (C) 2009 Red Hat, Inc.
3 * Copyright (C) 2006 Rusty Russell IBM Corporation
4 *
5 * Author: Michael S. Tsirkin <mst@redhat.com>
6 *
7 * Inspiration, some code, and most witty comments come from
61516587 8 * Documentation/virtual/lguest/lguest.c, by Rusty Russell
3a4d5c94 9 *
3a4d5c94
MT
10 * Generic code for virtio server in host kernel.
11 */
12
13#include <linux/eventfd.h>
14#include <linux/vhost.h>
35596b27 15#include <linux/uio.h>
3a4d5c94
MT
16#include <linux/mm.h>
17#include <linux/miscdevice.h>
18#include <linux/mutex.h>
3a4d5c94
MT
19#include <linux/poll.h>
20#include <linux/file.h>
21#include <linux/highmem.h>
5a0e3ad6 22#include <linux/slab.h>
4de7255f 23#include <linux/vmalloc.h>
c23f3445 24#include <linux/kthread.h>
6ac1afbf 25#include <linux/module.h>
bcfeacab 26#include <linux/sort.h>
6e84f315 27#include <linux/sched/mm.h>
174cd4b1 28#include <linux/sched/signal.h>
6e890c5d 29#include <linux/sched/vhost_task.h>
a9709d68 30#include <linux/interval_tree_generic.h>
ff002269 31#include <linux/nospec.h>
8f6a7f96 32#include <linux/kcov.h>
3a4d5c94 33
3a4d5c94
MT
34#include "vhost.h"
35
c9ce42f7
IM
36static ushort max_mem_regions = 64;
37module_param(max_mem_regions, ushort, 0444);
38MODULE_PARM_DESC(max_mem_regions,
39 "Maximum number of memory regions in memory map. (default: 64)");
6b1e6cc7
JW
40static int max_iotlb_entries = 2048;
41module_param(max_iotlb_entries, int, 0444);
42MODULE_PARM_DESC(max_iotlb_entries,
43 "Maximum number of iotlb entries. (default: 2048)");
c9ce42f7 44
3a4d5c94 45enum {
3a4d5c94
MT
46 VHOST_MEMORY_F_LOG = 0x1,
47};
48
3b1bbe89
MT
49#define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
50#define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
8ea8cf89 51
2751c988 52#ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
c5072037 53static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
2751c988
GK
54{
55 vq->user_be = !virtio_legacy_is_little_endian();
56}
57
c5072037
GK
58static void vhost_enable_cross_endian_big(struct vhost_virtqueue *vq)
59{
60 vq->user_be = true;
61}
62
63static void vhost_enable_cross_endian_little(struct vhost_virtqueue *vq)
64{
65 vq->user_be = false;
66}
67
2751c988
GK
68static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
69{
70 struct vhost_vring_state s;
71
72 if (vq->private_data)
73 return -EBUSY;
74
75 if (copy_from_user(&s, argp, sizeof(s)))
76 return -EFAULT;
77
78 if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
79 s.num != VHOST_VRING_BIG_ENDIAN)
80 return -EINVAL;
81
c5072037
GK
82 if (s.num == VHOST_VRING_BIG_ENDIAN)
83 vhost_enable_cross_endian_big(vq);
84 else
85 vhost_enable_cross_endian_little(vq);
2751c988
GK
86
87 return 0;
88}
89
90static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
91 int __user *argp)
92{
93 struct vhost_vring_state s = {
94 .index = idx,
95 .num = vq->user_be
96 };
97
98 if (copy_to_user(argp, &s, sizeof(s)))
99 return -EFAULT;
100
101 return 0;
102}
103
104static void vhost_init_is_le(struct vhost_virtqueue *vq)
105{
106 /* Note for legacy virtio: user_be is initialized at reset time
107 * according to the host endianness. If userspace does not set an
108 * explicit endianness, the default behavior is native endian, as
109 * expected by legacy virtio.
110 */
111 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
112}
113#else
c5072037 114static void vhost_disable_cross_endian(struct vhost_virtqueue *vq)
2751c988
GK
115{
116}
117
118static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
119{
120 return -ENOIOCTLCMD;
121}
122
123static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
124 int __user *argp)
125{
126 return -ENOIOCTLCMD;
127}
128
129static void vhost_init_is_le(struct vhost_virtqueue *vq)
130{
cda8bba0
HP
131 vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1)
132 || virtio_legacy_is_little_endian();
2751c988
GK
133}
134#endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
135
c5072037
GK
136static void vhost_reset_is_le(struct vhost_virtqueue *vq)
137{
cda8bba0 138 vhost_init_is_le(vq);
c5072037
GK
139}
140
7235acdb
JW
141struct vhost_flush_struct {
142 struct vhost_work work;
143 struct completion wait_event;
144};
145
146static void vhost_flush_work(struct vhost_work *work)
147{
148 struct vhost_flush_struct *s;
149
150 s = container_of(work, struct vhost_flush_struct, work);
151 complete(&s->wait_event);
152}
153
3a4d5c94
MT
154static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
155 poll_table *pt)
156{
157 struct vhost_poll *poll;
3a4d5c94 158
d47effe1 159 poll = container_of(pt, struct vhost_poll, table);
3a4d5c94
MT
160 poll->wqh = wqh;
161 add_wait_queue(wqh, &poll->wait);
162}
163
ac6424b9 164static int vhost_poll_wakeup(wait_queue_entry_t *wait, unsigned mode, int sync,
3a4d5c94
MT
165 void *key)
166{
c23f3445 167 struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
01fcb1cb 168 struct vhost_work *work = &poll->work;
c23f3445 169
3ad6f93e 170 if (!(key_to_poll(key) & poll->mask))
3a4d5c94
MT
171 return 0;
172
01fcb1cb
JW
173 if (!poll->dev->use_worker)
174 work->fn(work);
175 else
176 vhost_poll_queue(poll);
177
3a4d5c94
MT
178 return 0;
179}
180
163049ae 181void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
87d6a412 182{
04b96e55 183 clear_bit(VHOST_WORK_QUEUED, &work->flags);
87d6a412 184 work->fn = fn;
87d6a412 185}
6ac1afbf 186EXPORT_SYMBOL_GPL(vhost_work_init);
87d6a412 187
3a4d5c94 188/* Init poll structure */
c23f3445 189void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
493b94bf
MC
190 __poll_t mask, struct vhost_dev *dev,
191 struct vhost_virtqueue *vq)
3a4d5c94 192{
3a4d5c94
MT
193 init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
194 init_poll_funcptr(&poll->table, vhost_poll_func);
195 poll->mask = mask;
c23f3445 196 poll->dev = dev;
2b8b328b 197 poll->wqh = NULL;
493b94bf 198 poll->vq = vq;
c23f3445 199
87d6a412 200 vhost_work_init(&poll->work, fn);
3a4d5c94 201}
6ac1afbf 202EXPORT_SYMBOL_GPL(vhost_poll_init);
3a4d5c94
MT
203
204/* Start polling a file. We add ourselves to file's wait queue. The caller must
205 * keep a reference to a file until after vhost_poll_stop is called. */
2b8b328b 206int vhost_poll_start(struct vhost_poll *poll, struct file *file)
3a4d5c94 207{
e6c8adca 208 __poll_t mask;
d47effe1 209
70181d51
JW
210 if (poll->wqh)
211 return 0;
212
9965ed17 213 mask = vfs_poll(file, &poll->table);
3a4d5c94 214 if (mask)
3ad6f93e 215 vhost_poll_wakeup(&poll->wait, 0, 0, poll_to_key(mask));
a9a08845 216 if (mask & EPOLLERR) {
dc6455a7 217 vhost_poll_stop(poll);
896fc242 218 return -EINVAL;
2b8b328b
JW
219 }
220
896fc242 221 return 0;
3a4d5c94 222}
6ac1afbf 223EXPORT_SYMBOL_GPL(vhost_poll_start);
3a4d5c94
MT
224
225/* Stop polling a file. After this function returns, it becomes safe to drop the
226 * file reference. You must also flush afterwards. */
227void vhost_poll_stop(struct vhost_poll *poll)
228{
2b8b328b
JW
229 if (poll->wqh) {
230 remove_wait_queue(poll->wqh, &poll->wait);
231 poll->wqh = NULL;
232 }
3a4d5c94 233}
6ac1afbf 234EXPORT_SYMBOL_GPL(vhost_poll_stop);
3a4d5c94 235
0921dddc
MC
236static bool vhost_worker_queue(struct vhost_worker *worker,
237 struct vhost_work *work)
3a4d5c94 238{
0921dddc 239 if (!worker)
c011bb66
MC
240 return false;
241 /*
242 * vsock can queue while we do a VHOST_SET_OWNER, so we have a smp_wmb
243 * when setting up the worker. We don't have a smp_rmb here because
244 * test_and_set_bit gives us a mb already.
245 */
04b96e55
JW
246 if (!test_and_set_bit(VHOST_WORK_QUEUED, &work->flags)) {
247 /* We can only add the work to the list after we're
248 * sure it was not in the list.
635abf01 249 * test_and_set_bit() implies a memory barrier.
04b96e55 250 */
0921dddc
MC
251 llist_add(&work->node, &worker->work_list);
252 vhost_task_wake(worker->vtsk);
c23f3445 253 }
c011bb66
MC
254
255 return true;
3a4d5c94 256}
0921dddc 257
0921dddc
MC
258bool vhost_vq_work_queue(struct vhost_virtqueue *vq, struct vhost_work *work)
259{
260 return vhost_worker_queue(vq->worker, work);
261}
262EXPORT_SYMBOL_GPL(vhost_vq_work_queue);
263
a6fc0473 264static void vhost_worker_flush(struct vhost_worker *worker)
0921dddc
MC
265{
266 struct vhost_flush_struct flush;
267
268 init_completion(&flush.wait_event);
269 vhost_work_init(&flush.work, vhost_flush_work);
270
a6fc0473 271 if (vhost_worker_queue(worker, &flush.work))
0921dddc
MC
272 wait_for_completion(&flush.wait_event);
273}
a6fc0473
MC
274
275void vhost_vq_flush(struct vhost_virtqueue *vq)
276{
277 vhost_worker_flush(vq->worker);
278}
279EXPORT_SYMBOL_GPL(vhost_vq_flush);
280
281void vhost_dev_flush(struct vhost_dev *dev)
282{
283 vhost_worker_flush(dev->worker);
284}
0921dddc
MC
285EXPORT_SYMBOL_GPL(vhost_dev_flush);
286
526d3e7f 287/* A lockless hint for busy polling code to exit the loop */
9784df15 288bool vhost_vq_has_work(struct vhost_virtqueue *vq)
526d3e7f 289{
9784df15 290 return !llist_empty(&vq->worker->work_list);
526d3e7f 291}
9784df15 292EXPORT_SYMBOL_GPL(vhost_vq_has_work);
526d3e7f 293
87d6a412
MT
294void vhost_poll_queue(struct vhost_poll *poll)
295{
493b94bf 296 vhost_vq_work_queue(poll->vq, &poll->work);
87d6a412 297}
6ac1afbf 298EXPORT_SYMBOL_GPL(vhost_poll_queue);
87d6a412 299
f8894913
JW
300static void __vhost_vq_meta_reset(struct vhost_virtqueue *vq)
301{
302 int j;
303
304 for (j = 0; j < VHOST_NUM_ADDRS; j++)
305 vq->meta_iotlb[j] = NULL;
306}
307
308static void vhost_vq_meta_reset(struct vhost_dev *d)
309{
310 int i;
311
86a07da3 312 for (i = 0; i < d->nvqs; ++i)
f8894913
JW
313 __vhost_vq_meta_reset(d->vqs[i]);
314}
315
265a0ad8
ZL
316static void vhost_vring_call_reset(struct vhost_vring_call *call_ctx)
317{
318 call_ctx->ctx = NULL;
319 memset(&call_ctx->producer, 0x0, sizeof(struct irq_bypass_producer));
265a0ad8
ZL
320}
321
6bcf3422
MC
322bool vhost_vq_is_setup(struct vhost_virtqueue *vq)
323{
324 return vq->avail && vq->desc && vq->used && vhost_vq_access_ok(vq);
325}
326EXPORT_SYMBOL_GPL(vhost_vq_is_setup);
327
3a4d5c94
MT
328static void vhost_vq_reset(struct vhost_dev *dev,
329 struct vhost_virtqueue *vq)
330{
331 vq->num = 1;
332 vq->desc = NULL;
333 vq->avail = NULL;
334 vq->used = NULL;
335 vq->last_avail_idx = 0;
336 vq->avail_idx = 0;
337 vq->last_used_idx = 0;
8ea8cf89
MT
338 vq->signalled_used = 0;
339 vq->signalled_used_valid = false;
3a4d5c94 340 vq->used_flags = 0;
3a4d5c94
MT
341 vq->log_used = false;
342 vq->log_addr = -1ull;
3a4d5c94 343 vq->private_data = NULL;
ea16c514 344 vq->acked_features = 0;
429711ae 345 vq->acked_backend_features = 0;
3a4d5c94
MT
346 vq->log_base = NULL;
347 vq->error_ctx = NULL;
3a4d5c94 348 vq->kick = NULL;
73a99f08 349 vq->log_ctx = NULL;
c5072037 350 vhost_disable_cross_endian(vq);
beb691e6 351 vhost_reset_is_le(vq);
03088137 352 vq->busyloop_timeout = 0;
a9709d68 353 vq->umem = NULL;
6b1e6cc7 354 vq->iotlb = NULL;
737bdb64 355 vq->worker = NULL;
265a0ad8 356 vhost_vring_call_reset(&vq->call_ctx);
f8894913 357 __vhost_vq_meta_reset(vq);
3a4d5c94
MT
358}
359
f9010dbd 360static bool vhost_worker(void *data)
c23f3445 361{
1a5f8090 362 struct vhost_worker *worker = data;
04b96e55
JW
363 struct vhost_work *work, *work_next;
364 struct llist_node *node;
c23f3445 365
f9010dbd
MC
366 node = llist_del_all(&worker->work_list);
367 if (node) {
4b13cbef
MC
368 __set_current_state(TASK_RUNNING);
369
04b96e55
JW
370 node = llist_reverse_order(node);
371 /* make sure flag is seen after deletion */
372 smp_wmb();
373 llist_for_each_entry_safe(work, work_next, node, node) {
374 clear_bit(VHOST_WORK_QUEUED, &work->flags);
1a5f8090 375 kcov_remote_start_common(worker->kcov_handle);
c23f3445 376 work->fn(work);
8f6a7f96 377 kcov_remote_stop();
05bfb338 378 cond_resched();
04b96e55 379 }
c23f3445 380 }
6e890c5d 381
f9010dbd 382 return !!node;
c23f3445
TH
383}
384
bab632d6
MT
385static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
386{
387 kfree(vq->indirect);
388 vq->indirect = NULL;
389 kfree(vq->log);
390 vq->log = NULL;
391 kfree(vq->heads);
392 vq->heads = NULL;
bab632d6
MT
393}
394
e0e9b406
JW
395/* Helper to allocate iovec buffers for all vqs. */
396static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
397{
6d5e6aa8 398 struct vhost_virtqueue *vq;
e0e9b406 399 int i;
d47effe1 400
e0e9b406 401 for (i = 0; i < dev->nvqs; ++i) {
6d5e6aa8 402 vq = dev->vqs[i];
6da2ec56
KC
403 vq->indirect = kmalloc_array(UIO_MAXIOV,
404 sizeof(*vq->indirect),
405 GFP_KERNEL);
b46a0bf7 406 vq->log = kmalloc_array(dev->iov_limit, sizeof(*vq->log),
6da2ec56 407 GFP_KERNEL);
b46a0bf7 408 vq->heads = kmalloc_array(dev->iov_limit, sizeof(*vq->heads),
6da2ec56 409 GFP_KERNEL);
6d5e6aa8 410 if (!vq->indirect || !vq->log || !vq->heads)
e0e9b406
JW
411 goto err_nomem;
412 }
413 return 0;
d47effe1 414
e0e9b406 415err_nomem:
bab632d6 416 for (; i >= 0; --i)
3ab2e420 417 vhost_vq_free_iovecs(dev->vqs[i]);
e0e9b406
JW
418 return -ENOMEM;
419}
420
421static void vhost_dev_free_iovecs(struct vhost_dev *dev)
422{
423 int i;
d47effe1 424
bab632d6 425 for (i = 0; i < dev->nvqs; ++i)
3ab2e420 426 vhost_vq_free_iovecs(dev->vqs[i]);
e0e9b406
JW
427}
428
e82b9b07
JW
429bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
430 int pkts, int total_len)
431{
432 struct vhost_dev *dev = vq->dev;
433
434 if ((dev->byte_weight && total_len >= dev->byte_weight) ||
435 pkts >= dev->weight) {
436 vhost_poll_queue(&vq->poll);
437 return true;
438 }
439
440 return false;
441}
442EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
443
4942e825
JW
444static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
445 unsigned int num)
446{
447 size_t event __maybe_unused =
448 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
449
e4be66e5 450 return size_add(struct_size(vq->avail, ring, num), event);
4942e825
JW
451}
452
453static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
454 unsigned int num)
455{
456 size_t event __maybe_unused =
457 vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
458
e4be66e5 459 return size_add(struct_size(vq->used, ring, num), event);
4942e825
JW
460}
461
462static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,
463 unsigned int num)
464{
465 return sizeof(*vq->desc) * num;
466}
467
59566b6e 468void vhost_dev_init(struct vhost_dev *dev,
e82b9b07 469 struct vhost_virtqueue **vqs, int nvqs,
792a4f2e 470 int iov_limit, int weight, int byte_weight,
01fcb1cb 471 bool use_worker,
91233ad7 472 int (*msg_handler)(struct vhost_dev *dev, u32 asid,
792a4f2e 473 struct vhost_iotlb_msg *msg))
3a4d5c94 474{
6d5e6aa8 475 struct vhost_virtqueue *vq;
3a4d5c94 476 int i;
c23f3445 477
3a4d5c94
MT
478 dev->vqs = vqs;
479 dev->nvqs = nvqs;
480 mutex_init(&dev->mutex);
481 dev->log_ctx = NULL;
a9709d68 482 dev->umem = NULL;
6b1e6cc7 483 dev->iotlb = NULL;
3a4d5c94 484 dev->mm = NULL;
c011bb66 485 dev->worker = NULL;
b46a0bf7 486 dev->iov_limit = iov_limit;
e82b9b07
JW
487 dev->weight = weight;
488 dev->byte_weight = byte_weight;
01fcb1cb 489 dev->use_worker = use_worker;
792a4f2e 490 dev->msg_handler = msg_handler;
6b1e6cc7
JW
491 init_waitqueue_head(&dev->wait);
492 INIT_LIST_HEAD(&dev->read_list);
493 INIT_LIST_HEAD(&dev->pending_list);
494 spin_lock_init(&dev->iotlb_lock);
3d2c7d37 495
3a4d5c94
MT
496
497 for (i = 0; i < dev->nvqs; ++i) {
6d5e6aa8
AH
498 vq = dev->vqs[i];
499 vq->log = NULL;
500 vq->indirect = NULL;
501 vq->heads = NULL;
502 vq->dev = dev;
503 mutex_init(&vq->mutex);
504 vhost_vq_reset(dev, vq);
505 if (vq->handle_kick)
506 vhost_poll_init(&vq->poll, vq->handle_kick,
493b94bf 507 EPOLLIN, dev, vq);
3a4d5c94 508 }
3a4d5c94 509}
6ac1afbf 510EXPORT_SYMBOL_GPL(vhost_dev_init);
3a4d5c94
MT
511
512/* Caller should have device mutex */
513long vhost_dev_check_owner(struct vhost_dev *dev)
514{
515 /* Are you the owner? If not, I don't think you mean to do that */
516 return dev->mm == current->mm ? 0 : -EPERM;
517}
6ac1afbf 518EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
3a4d5c94 519
05c05351
MT
520/* Caller should have device mutex */
521bool vhost_dev_has_owner(struct vhost_dev *dev)
522{
523 return dev->mm;
524}
6ac1afbf 525EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
05c05351 526
5ce995f3
JW
527static void vhost_attach_mm(struct vhost_dev *dev)
528{
529 /* No owner, become one */
530 if (dev->use_worker) {
531 dev->mm = get_task_mm(current);
532 } else {
533 /* vDPA device does not use worker thead, so there's
534 * no need to hold the address space for mm. This help
535 * to avoid deadlock in the case of mmap() which may
536 * held the refcnt of the file and depends on release
537 * method to remove vma.
538 */
539 dev->mm = current->mm;
540 mmgrab(dev->mm);
541 }
542}
543
544static void vhost_detach_mm(struct vhost_dev *dev)
545{
546 if (!dev->mm)
547 return;
548
549 if (dev->use_worker)
550 mmput(dev->mm);
551 else
552 mmdrop(dev->mm);
553
554 dev->mm = NULL;
555}
556
1a5f8090
MC
557static void vhost_worker_free(struct vhost_dev *dev)
558{
c011bb66 559 if (!dev->worker)
1a5f8090
MC
560 return;
561
c011bb66
MC
562 WARN_ON(!llist_empty(&dev->worker->work_list));
563 vhost_task_stop(dev->worker->vtsk);
564 kfree(dev->worker);
565 dev->worker = NULL;
1a5f8090
MC
566}
567
737bdb64 568static struct vhost_worker *vhost_worker_create(struct vhost_dev *dev)
1a5f8090 569{
c011bb66 570 struct vhost_worker *worker;
6e890c5d
MC
571 struct vhost_task *vtsk;
572 char name[TASK_COMM_LEN];
1a5f8090 573
c011bb66
MC
574 worker = kzalloc(sizeof(*worker), GFP_KERNEL_ACCOUNT);
575 if (!worker)
737bdb64 576 return NULL;
c011bb66 577
6e890c5d 578 snprintf(name, sizeof(name), "vhost-%d", current->pid);
1a5f8090 579
c011bb66 580 vtsk = vhost_task_create(vhost_worker, worker, name);
a284f09e 581 if (!vtsk)
c011bb66
MC
582 goto free_worker;
583
584 init_llist_head(&worker->work_list);
585 worker->kcov_handle = kcov_common_handle();
586 worker->vtsk = vtsk;
587 /*
588 * vsock can already try to queue so make sure llist and vtsk are both
589 * set before vhost_work_queue sees dev->worker is set.
590 */
591 smp_wmb();
592 dev->worker = worker;
1a5f8090 593
6e890c5d 594 vhost_task_start(vtsk);
737bdb64 595 return worker;
c011bb66
MC
596
597free_worker:
598 kfree(worker);
737bdb64 599 return NULL;
1a5f8090
MC
600}
601
cef25866
MC
602static int vhost_get_vq_from_user(struct vhost_dev *dev, void __user *argp,
603 struct vhost_virtqueue **vq, u32 *id)
604{
605 u32 __user *idxp = argp;
606 u32 idx;
607 long r;
608
609 r = get_user(idx, idxp);
610 if (r < 0)
611 return r;
612
613 if (idx >= dev->nvqs)
614 return -ENOBUFS;
615
616 idx = array_index_nospec(idx, dev->nvqs);
617
618 *vq = dev->vqs[idx];
619 *id = idx;
620 return 0;
621}
622
3a4d5c94 623/* Caller should have device mutex */
54db63c2 624long vhost_dev_set_owner(struct vhost_dev *dev)
3a4d5c94 625{
737bdb64
MC
626 struct vhost_worker *worker;
627 int err, i;
d47effe1 628
3a4d5c94 629 /* Is there an owner already? */
05c05351 630 if (vhost_dev_has_owner(dev)) {
c23f3445
TH
631 err = -EBUSY;
632 goto err_mm;
633 }
d47effe1 634
5ce995f3
JW
635 vhost_attach_mm(dev);
636
3e11c6eb
MC
637 err = vhost_dev_alloc_iovecs(dev);
638 if (err)
639 goto err_iovecs;
640
01fcb1cb 641 if (dev->use_worker) {
3e11c6eb
MC
642 /*
643 * This should be done last, because vsock can queue work
644 * before VHOST_SET_OWNER so it simplifies the failure path
645 * below since we don't have to worry about vsock queueing
646 * while we free the worker.
647 */
737bdb64
MC
648 worker = vhost_worker_create(dev);
649 if (!worker) {
650 err = -ENOMEM;
1a5f8090 651 goto err_worker;
737bdb64
MC
652 }
653
654 for (i = 0; i < dev->nvqs; i++)
655 dev->vqs[i]->worker = worker;
01fcb1cb 656 }
c23f3445 657
3a4d5c94 658 return 0;
3e11c6eb 659
c23f3445 660err_worker:
3e11c6eb
MC
661 vhost_dev_free_iovecs(dev);
662err_iovecs:
5ce995f3 663 vhost_detach_mm(dev);
c23f3445
TH
664err_mm:
665 return err;
3a4d5c94 666}
6ac1afbf 667EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
3a4d5c94 668
0bbe3066
JW
669static struct vhost_iotlb *iotlb_alloc(void)
670{
671 return vhost_iotlb_alloc(max_iotlb_entries,
672 VHOST_IOTLB_FLAG_RETIRE);
673}
674
675struct vhost_iotlb *vhost_dev_reset_owner_prepare(void)
a9709d68 676{
0bbe3066 677 return iotlb_alloc();
150b9e51 678}
6ac1afbf 679EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
3a4d5c94 680
150b9e51 681/* Caller should have device mutex */
0bbe3066 682void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_iotlb *umem)
150b9e51 683{
47283bef
MT
684 int i;
685
f6f93f75 686 vhost_dev_cleanup(dev);
3a4d5c94 687
a9709d68 688 dev->umem = umem;
47283bef
MT
689 /* We don't need VQ locks below since vhost_dev_cleanup makes sure
690 * VQs aren't running.
691 */
692 for (i = 0; i < dev->nvqs; ++i)
a9709d68 693 dev->vqs[i]->umem = umem;
3a4d5c94 694}
6ac1afbf 695EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
3a4d5c94 696
b211616d 697void vhost_dev_stop(struct vhost_dev *dev)
bab632d6
MT
698{
699 int i;
b211616d
MT
700
701 for (i = 0; i < dev->nvqs; ++i) {
6ca84326 702 if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick)
3ab2e420 703 vhost_poll_stop(&dev->vqs[i]->poll);
bab632d6 704 }
6ca84326 705
b2ffa407 706 vhost_dev_flush(dev);
bab632d6 707}
6ac1afbf 708EXPORT_SYMBOL_GPL(vhost_dev_stop);
bab632d6 709
9526f9a2 710void vhost_clear_msg(struct vhost_dev *dev)
6b1e6cc7
JW
711{
712 struct vhost_msg_node *node, *n;
713
714 spin_lock(&dev->iotlb_lock);
715
716 list_for_each_entry_safe(node, n, &dev->read_list, node) {
717 list_del(&node->node);
718 kfree(node);
719 }
720
721 list_for_each_entry_safe(node, n, &dev->pending_list, node) {
722 list_del(&node->node);
723 kfree(node);
724 }
725
726 spin_unlock(&dev->iotlb_lock);
727}
9526f9a2 728EXPORT_SYMBOL_GPL(vhost_clear_msg);
6b1e6cc7 729
f6f93f75 730void vhost_dev_cleanup(struct vhost_dev *dev)
3a4d5c94
MT
731{
732 int i;
d47effe1 733
3a4d5c94 734 for (i = 0; i < dev->nvqs; ++i) {
3ab2e420
AH
735 if (dev->vqs[i]->error_ctx)
736 eventfd_ctx_put(dev->vqs[i]->error_ctx);
3ab2e420
AH
737 if (dev->vqs[i]->kick)
738 fput(dev->vqs[i]->kick);
265a0ad8
ZL
739 if (dev->vqs[i]->call_ctx.ctx)
740 eventfd_ctx_put(dev->vqs[i]->call_ctx.ctx);
3ab2e420 741 vhost_vq_reset(dev, dev->vqs[i]);
3a4d5c94 742 }
e0e9b406 743 vhost_dev_free_iovecs(dev);
3a4d5c94
MT
744 if (dev->log_ctx)
745 eventfd_ctx_put(dev->log_ctx);
746 dev->log_ctx = NULL;
3a4d5c94 747 /* No one will access memory at this point */
0bbe3066 748 vhost_iotlb_free(dev->umem);
a9709d68 749 dev->umem = NULL;
0bbe3066 750 vhost_iotlb_free(dev->iotlb);
6b1e6cc7
JW
751 dev->iotlb = NULL;
752 vhost_clear_msg(dev);
a9a08845 753 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
1a5f8090 754 vhost_worker_free(dev);
5ce995f3 755 vhost_detach_mm(dev);
3a4d5c94 756}
6ac1afbf 757EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
3a4d5c94 758
ddd3d408 759static bool log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
3a4d5c94
MT
760{
761 u64 a = addr / VHOST_PAGE_SIZE / 8;
d47effe1 762
3a4d5c94
MT
763 /* Make sure 64 bit math will not overflow. */
764 if (a > ULONG_MAX - (unsigned long)log_base ||
765 a + (unsigned long)log_base > ULONG_MAX)
ddd3d408 766 return false;
3a4d5c94 767
96d4f267 768 return access_ok(log_base + a,
3a4d5c94
MT
769 (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
770}
771
f7ad318e 772/* Make sure 64 bit math will not overflow. */
ec33d031
MT
773static bool vhost_overflow(u64 uaddr, u64 size)
774{
f7ad318e
XY
775 if (uaddr > ULONG_MAX || size > ULONG_MAX)
776 return true;
777
778 if (!size)
779 return false;
780
781 return uaddr > ULONG_MAX - size + 1;
ec33d031
MT
782}
783
3a4d5c94 784/* Caller should have vq mutex and device mutex. */
0bbe3066 785static bool vq_memory_access_ok(void __user *log_base, struct vhost_iotlb *umem,
ddd3d408 786 int log_all)
3a4d5c94 787{
0bbe3066 788 struct vhost_iotlb_map *map;
179b284e 789
a9709d68 790 if (!umem)
ddd3d408 791 return false;
179b284e 792
0bbe3066
JW
793 list_for_each_entry(map, &umem->list, link) {
794 unsigned long a = map->addr;
a9709d68 795
0bbe3066 796 if (vhost_overflow(map->addr, map->size))
ddd3d408 797 return false;
ec33d031
MT
798
799
0bbe3066 800 if (!access_ok((void __user *)a, map->size))
ddd3d408 801 return false;
3a4d5c94 802 else if (log_all && !log_access_ok(log_base,
0bbe3066
JW
803 map->start,
804 map->size))
ddd3d408 805 return false;
3a4d5c94 806 }
ddd3d408 807 return true;
3a4d5c94
MT
808}
809
f8894913
JW
810static inline void __user *vhost_vq_meta_fetch(struct vhost_virtqueue *vq,
811 u64 addr, unsigned int size,
812 int type)
813{
0bbe3066 814 const struct vhost_iotlb_map *map = vq->meta_iotlb[type];
f8894913 815
0bbe3066 816 if (!map)
f8894913
JW
817 return NULL;
818
1b0be99f 819 return (void __user *)(uintptr_t)(map->addr + addr - map->start);
f8894913
JW
820}
821
3a4d5c94
MT
822/* Can we switch to this memory table? */
823/* Caller should have device mutex but not vq mutex */
0bbe3066 824static bool memory_access_ok(struct vhost_dev *d, struct vhost_iotlb *umem,
ddd3d408 825 int log_all)
3a4d5c94
MT
826{
827 int i;
d47effe1 828
3a4d5c94 829 for (i = 0; i < d->nvqs; ++i) {
ddd3d408 830 bool ok;
ea16c514
MT
831 bool log;
832
3ab2e420 833 mutex_lock(&d->vqs[i]->mutex);
ea16c514 834 log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
3a4d5c94 835 /* If ring is inactive, will check when it's enabled. */
3ab2e420 836 if (d->vqs[i]->private_data)
a9709d68
JW
837 ok = vq_memory_access_ok(d->vqs[i]->log_base,
838 umem, log);
3a4d5c94 839 else
ddd3d408 840 ok = true;
3ab2e420 841 mutex_unlock(&d->vqs[i]->mutex);
3a4d5c94 842 if (!ok)
ddd3d408 843 return false;
3a4d5c94 844 }
ddd3d408 845 return true;
3a4d5c94
MT
846}
847
6b1e6cc7
JW
848static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
849 struct iovec iov[], int iov_size, int access);
bfe2bc51 850
72952cc0 851static int vhost_copy_to_user(struct vhost_virtqueue *vq, void __user *to,
bfe2bc51
JW
852 const void *from, unsigned size)
853{
6b1e6cc7 854 int ret;
bfe2bc51 855
6b1e6cc7
JW
856 if (!vq->iotlb)
857 return __copy_to_user(to, from, size);
858 else {
859 /* This function should be called after iotlb
860 * prefetch, which means we're sure that all vq
861 * could be access through iotlb. So -EAGAIN should
862 * not happen in this case.
863 */
6b1e6cc7 864 struct iov_iter t;
f8894913
JW
865 void __user *uaddr = vhost_vq_meta_fetch(vq,
866 (u64)(uintptr_t)to, size,
7ced6c98 867 VHOST_ADDR_USED);
f8894913
JW
868
869 if (uaddr)
870 return __copy_to_user(uaddr, from, size);
871
6b1e6cc7
JW
872 ret = translate_desc(vq, (u64)(uintptr_t)to, size, vq->iotlb_iov,
873 ARRAY_SIZE(vq->iotlb_iov),
874 VHOST_ACCESS_WO);
875 if (ret < 0)
876 goto out;
de4eda9d 877 iov_iter_init(&t, ITER_DEST, vq->iotlb_iov, ret, size);
6b1e6cc7
JW
878 ret = copy_to_iter(from, size, &t);
879 if (ret == size)
880 ret = 0;
881 }
882out:
883 return ret;
884}
bfe2bc51
JW
885
886static int vhost_copy_from_user(struct vhost_virtqueue *vq, void *to,
72952cc0 887 void __user *from, unsigned size)
bfe2bc51 888{
6b1e6cc7
JW
889 int ret;
890
891 if (!vq->iotlb)
892 return __copy_from_user(to, from, size);
893 else {
894 /* This function should be called after iotlb
895 * prefetch, which means we're sure that vq
896 * could be access through iotlb. So -EAGAIN should
897 * not happen in this case.
898 */
f8894913
JW
899 void __user *uaddr = vhost_vq_meta_fetch(vq,
900 (u64)(uintptr_t)from, size,
901 VHOST_ADDR_DESC);
6b1e6cc7 902 struct iov_iter f;
f8894913
JW
903
904 if (uaddr)
905 return __copy_from_user(to, uaddr, size);
906
6b1e6cc7
JW
907 ret = translate_desc(vq, (u64)(uintptr_t)from, size, vq->iotlb_iov,
908 ARRAY_SIZE(vq->iotlb_iov),
909 VHOST_ACCESS_RO);
910 if (ret < 0) {
911 vq_err(vq, "IOTLB translation failure: uaddr "
912 "%p size 0x%llx\n", from,
913 (unsigned long long) size);
914 goto out;
915 }
de4eda9d 916 iov_iter_init(&f, ITER_SOURCE, vq->iotlb_iov, ret, size);
6b1e6cc7
JW
917 ret = copy_from_iter(to, size, &f);
918 if (ret == size)
919 ret = 0;
920 }
921
922out:
923 return ret;
924}
925
f8894913
JW
926static void __user *__vhost_get_user_slow(struct vhost_virtqueue *vq,
927 void __user *addr, unsigned int size,
928 int type)
6b1e6cc7
JW
929{
930 int ret;
931
6b1e6cc7
JW
932 ret = translate_desc(vq, (u64)(uintptr_t)addr, size, vq->iotlb_iov,
933 ARRAY_SIZE(vq->iotlb_iov),
934 VHOST_ACCESS_RO);
935 if (ret < 0) {
936 vq_err(vq, "IOTLB translation failure: uaddr "
937 "%p size 0x%llx\n", addr,
938 (unsigned long long) size);
939 return NULL;
940 }
941
942 if (ret != 1 || vq->iotlb_iov[0].iov_len != size) {
943 vq_err(vq, "Non atomic userspace memory access: uaddr "
944 "%p size 0x%llx\n", addr,
945 (unsigned long long) size);
946 return NULL;
947 }
948
949 return vq->iotlb_iov[0].iov_base;
950}
951
f8894913
JW
952/* This function should be called after iotlb
953 * prefetch, which means we're sure that vq
954 * could be access through iotlb. So -EAGAIN should
955 * not happen in this case.
956 */
957static inline void __user *__vhost_get_user(struct vhost_virtqueue *vq,
1b0be99f 958 void __user *addr, unsigned int size,
f8894913
JW
959 int type)
960{
961 void __user *uaddr = vhost_vq_meta_fetch(vq,
962 (u64)(uintptr_t)addr, size, type);
963 if (uaddr)
964 return uaddr;
965
966 return __vhost_get_user_slow(vq, addr, size, type);
967}
968
969#define vhost_put_user(vq, x, ptr) \
6b1e6cc7 970({ \
002ef18e 971 int ret; \
6b1e6cc7
JW
972 if (!vq->iotlb) { \
973 ret = __put_user(x, ptr); \
974 } else { \
975 __typeof__(ptr) to = \
f8894913
JW
976 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
977 sizeof(*ptr), VHOST_ADDR_USED); \
6b1e6cc7
JW
978 if (to != NULL) \
979 ret = __put_user(x, to); \
980 else \
981 ret = -EFAULT; \
982 } \
983 ret; \
984})
985
7b5d753e
JW
986static inline int vhost_put_avail_event(struct vhost_virtqueue *vq)
987{
988 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->avail_idx),
989 vhost_avail_event(vq));
990}
991
992static inline int vhost_put_used(struct vhost_virtqueue *vq,
993 struct vring_used_elem *head, int idx,
994 int count)
995{
996 return vhost_copy_to_user(vq, vq->used->ring + idx, head,
997 count * sizeof(*head));
998}
999
1000static inline int vhost_put_used_flags(struct vhost_virtqueue *vq)
1001
1002{
1003 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->used_flags),
1004 &vq->used->flags);
1005}
1006
1007static inline int vhost_put_used_idx(struct vhost_virtqueue *vq)
1008
1009{
1010 return vhost_put_user(vq, cpu_to_vhost16(vq, vq->last_used_idx),
1011 &vq->used->idx);
1012}
1013
f8894913 1014#define vhost_get_user(vq, x, ptr, type) \
6b1e6cc7
JW
1015({ \
1016 int ret; \
1017 if (!vq->iotlb) { \
1018 ret = __get_user(x, ptr); \
1019 } else { \
1020 __typeof__(ptr) from = \
f8894913
JW
1021 (__typeof__(ptr)) __vhost_get_user(vq, ptr, \
1022 sizeof(*ptr), \
1023 type); \
6b1e6cc7
JW
1024 if (from != NULL) \
1025 ret = __get_user(x, from); \
1026 else \
1027 ret = -EFAULT; \
1028 } \
1029 ret; \
1030})
1031
f8894913
JW
1032#define vhost_get_avail(vq, x, ptr) \
1033 vhost_get_user(vq, x, ptr, VHOST_ADDR_AVAIL)
1034
1035#define vhost_get_used(vq, x, ptr) \
1036 vhost_get_user(vq, x, ptr, VHOST_ADDR_USED)
1037
86a07da3
JW
1038static void vhost_dev_lock_vqs(struct vhost_dev *d)
1039{
1040 int i = 0;
1041 for (i = 0; i < d->nvqs; ++i)
1042 mutex_lock_nested(&d->vqs[i]->mutex, i);
1043}
1044
1045static void vhost_dev_unlock_vqs(struct vhost_dev *d)
1046{
1047 int i = 0;
1048 for (i = 0; i < d->nvqs; ++i)
1049 mutex_unlock(&d->vqs[i]->mutex);
1050}
1051
7b5d753e
JW
1052static inline int vhost_get_avail_idx(struct vhost_virtqueue *vq,
1053 __virtio16 *idx)
1054{
1055 return vhost_get_avail(vq, *idx, &vq->avail->idx);
1056}
1057
1058static inline int vhost_get_avail_head(struct vhost_virtqueue *vq,
1059 __virtio16 *head, int idx)
1060{
1061 return vhost_get_avail(vq, *head,
1062 &vq->avail->ring[idx & (vq->num - 1)]);
1063}
1064
1065static inline int vhost_get_avail_flags(struct vhost_virtqueue *vq,
1066 __virtio16 *flags)
1067{
1068 return vhost_get_avail(vq, *flags, &vq->avail->flags);
1069}
1070
1071static inline int vhost_get_used_event(struct vhost_virtqueue *vq,
1072 __virtio16 *event)
1073{
1074 return vhost_get_avail(vq, *event, vhost_used_event(vq));
1075}
1076
1077static inline int vhost_get_used_idx(struct vhost_virtqueue *vq,
1078 __virtio16 *idx)
1079{
1080 return vhost_get_used(vq, *idx, &vq->used->idx);
1081}
1082
1083static inline int vhost_get_desc(struct vhost_virtqueue *vq,
1084 struct vring_desc *desc, int idx)
1085{
1086 return vhost_copy_from_user(vq, desc, vq->desc + idx, sizeof(*desc));
1087}
1088
6b1e6cc7
JW
1089static void vhost_iotlb_notify_vq(struct vhost_dev *d,
1090 struct vhost_iotlb_msg *msg)
1091{
1092 struct vhost_msg_node *node, *n;
1093
1094 spin_lock(&d->iotlb_lock);
1095
1096 list_for_each_entry_safe(node, n, &d->pending_list, node) {
1097 struct vhost_iotlb_msg *vq_msg = &node->msg.iotlb;
1098 if (msg->iova <= vq_msg->iova &&
2d66f997 1099 msg->iova + msg->size - 1 >= vq_msg->iova &&
6b1e6cc7
JW
1100 vq_msg->type == VHOST_IOTLB_MISS) {
1101 vhost_poll_queue(&node->vq->poll);
1102 list_del(&node->node);
1103 kfree(node);
1104 }
1105 }
1106
1107 spin_unlock(&d->iotlb_lock);
1108}
1109
ddd3d408 1110static bool umem_access_ok(u64 uaddr, u64 size, int access)
6b1e6cc7
JW
1111{
1112 unsigned long a = uaddr;
1113
ec33d031
MT
1114 /* Make sure 64 bit math will not overflow. */
1115 if (vhost_overflow(uaddr, size))
ddd3d408 1116 return false;
ec33d031 1117
6b1e6cc7 1118 if ((access & VHOST_ACCESS_RO) &&
96d4f267 1119 !access_ok((void __user *)a, size))
ddd3d408 1120 return false;
6b1e6cc7 1121 if ((access & VHOST_ACCESS_WO) &&
96d4f267 1122 !access_ok((void __user *)a, size))
ddd3d408
SH
1123 return false;
1124 return true;
6b1e6cc7
JW
1125}
1126
91233ad7 1127static int vhost_process_iotlb_msg(struct vhost_dev *dev, u32 asid,
72952cc0 1128 struct vhost_iotlb_msg *msg)
6b1e6cc7
JW
1129{
1130 int ret = 0;
1131
91233ad7
GD
1132 if (asid != 0)
1133 return -EINVAL;
1134
1b15ad68 1135 mutex_lock(&dev->mutex);
86a07da3 1136 vhost_dev_lock_vqs(dev);
6b1e6cc7
JW
1137 switch (msg->type) {
1138 case VHOST_IOTLB_UPDATE:
1139 if (!dev->iotlb) {
1140 ret = -EFAULT;
1141 break;
1142 }
ddd3d408 1143 if (!umem_access_ok(msg->uaddr, msg->size, msg->perm)) {
6b1e6cc7
JW
1144 ret = -EFAULT;
1145 break;
1146 }
f8894913 1147 vhost_vq_meta_reset(dev);
0bbe3066
JW
1148 if (vhost_iotlb_add_range(dev->iotlb, msg->iova,
1149 msg->iova + msg->size - 1,
1150 msg->uaddr, msg->perm)) {
6b1e6cc7
JW
1151 ret = -ENOMEM;
1152 break;
1153 }
1154 vhost_iotlb_notify_vq(dev, msg);
1155 break;
1156 case VHOST_IOTLB_INVALIDATE:
6f3180af
JW
1157 if (!dev->iotlb) {
1158 ret = -EFAULT;
1159 break;
1160 }
f8894913 1161 vhost_vq_meta_reset(dev);
0bbe3066
JW
1162 vhost_iotlb_del_range(dev->iotlb, msg->iova,
1163 msg->iova + msg->size - 1);
6b1e6cc7
JW
1164 break;
1165 default:
1166 ret = -EINVAL;
1167 break;
1168 }
1169
86a07da3 1170 vhost_dev_unlock_vqs(dev);
1b15ad68
JW
1171 mutex_unlock(&dev->mutex);
1172
6b1e6cc7
JW
1173 return ret;
1174}
1175ssize_t vhost_chr_write_iter(struct vhost_dev *dev,
1176 struct iov_iter *from)
1177{
429711ae
JW
1178 struct vhost_iotlb_msg msg;
1179 size_t offset;
1180 int type, ret;
91233ad7 1181 u32 asid = 0;
6b1e6cc7 1182
429711ae 1183 ret = copy_from_iter(&type, sizeof(type), from);
74ad7419
PT
1184 if (ret != sizeof(type)) {
1185 ret = -EINVAL;
6b1e6cc7 1186 goto done;
74ad7419 1187 }
6b1e6cc7 1188
429711ae 1189 switch (type) {
6b1e6cc7 1190 case VHOST_IOTLB_MSG:
429711ae
JW
1191 /* There maybe a hole after type for V1 message type,
1192 * so skip it here.
1193 */
1194 offset = offsetof(struct vhost_msg, iotlb) - sizeof(int);
1195 break;
1196 case VHOST_IOTLB_MSG_V2:
91233ad7
GD
1197 if (vhost_backend_has_feature(dev->vqs[0],
1198 VHOST_BACKEND_F_IOTLB_ASID)) {
1199 ret = copy_from_iter(&asid, sizeof(asid), from);
1200 if (ret != sizeof(asid)) {
1201 ret = -EINVAL;
1202 goto done;
1203 }
aaca8373 1204 offset = 0;
91233ad7
GD
1205 } else
1206 offset = sizeof(__u32);
6b1e6cc7
JW
1207 break;
1208 default:
1209 ret = -EINVAL;
429711ae 1210 goto done;
6b1e6cc7
JW
1211 }
1212
429711ae
JW
1213 iov_iter_advance(from, offset);
1214 ret = copy_from_iter(&msg, sizeof(msg), from);
74ad7419
PT
1215 if (ret != sizeof(msg)) {
1216 ret = -EINVAL;
429711ae 1217 goto done;
74ad7419 1218 }
792a4f2e 1219
95932ab2
JW
1220 if ((msg.type == VHOST_IOTLB_UPDATE ||
1221 msg.type == VHOST_IOTLB_INVALIDATE) &&
1222 msg.size == 0) {
e2ae38cf
AR
1223 ret = -EINVAL;
1224 goto done;
1225 }
1226
792a4f2e 1227 if (dev->msg_handler)
91233ad7 1228 ret = dev->msg_handler(dev, asid, &msg);
792a4f2e 1229 else
91233ad7 1230 ret = vhost_process_iotlb_msg(dev, asid, &msg);
792a4f2e 1231 if (ret) {
429711ae
JW
1232 ret = -EFAULT;
1233 goto done;
1234 }
1235
1236 ret = (type == VHOST_IOTLB_MSG) ? sizeof(struct vhost_msg) :
1237 sizeof(struct vhost_msg_v2);
6b1e6cc7
JW
1238done:
1239 return ret;
1240}
1241EXPORT_SYMBOL(vhost_chr_write_iter);
1242
afc9a42b 1243__poll_t vhost_chr_poll(struct file *file, struct vhost_dev *dev,
6b1e6cc7
JW
1244 poll_table *wait)
1245{
afc9a42b 1246 __poll_t mask = 0;
6b1e6cc7
JW
1247
1248 poll_wait(file, &dev->wait, wait);
1249
1250 if (!list_empty(&dev->read_list))
a9a08845 1251 mask |= EPOLLIN | EPOLLRDNORM;
6b1e6cc7
JW
1252
1253 return mask;
1254}
1255EXPORT_SYMBOL(vhost_chr_poll);
1256
1257ssize_t vhost_chr_read_iter(struct vhost_dev *dev, struct iov_iter *to,
1258 int noblock)
1259{
1260 DEFINE_WAIT(wait);
1261 struct vhost_msg_node *node;
1262 ssize_t ret = 0;
1263 unsigned size = sizeof(struct vhost_msg);
1264
1265 if (iov_iter_count(to) < size)
1266 return 0;
1267
1268 while (1) {
1269 if (!noblock)
1270 prepare_to_wait(&dev->wait, &wait,
1271 TASK_INTERRUPTIBLE);
1272
1273 node = vhost_dequeue_msg(dev, &dev->read_list);
1274 if (node)
1275 break;
1276 if (noblock) {
1277 ret = -EAGAIN;
1278 break;
1279 }
1280 if (signal_pending(current)) {
1281 ret = -ERESTARTSYS;
1282 break;
1283 }
1284 if (!dev->iotlb) {
1285 ret = -EBADFD;
1286 break;
1287 }
1288
1289 schedule();
1290 }
1291
1292 if (!noblock)
1293 finish_wait(&dev->wait, &wait);
1294
1295 if (node) {
429711ae
JW
1296 struct vhost_iotlb_msg *msg;
1297 void *start = &node->msg;
6b1e6cc7 1298
429711ae
JW
1299 switch (node->msg.type) {
1300 case VHOST_IOTLB_MSG:
1301 size = sizeof(node->msg);
1302 msg = &node->msg.iotlb;
1303 break;
1304 case VHOST_IOTLB_MSG_V2:
1305 size = sizeof(node->msg_v2);
1306 msg = &node->msg_v2.iotlb;
1307 break;
1308 default:
1309 BUG();
1310 break;
1311 }
1312
1313 ret = copy_to_iter(start, size, to);
1314 if (ret != size || msg->type != VHOST_IOTLB_MISS) {
6b1e6cc7
JW
1315 kfree(node);
1316 return ret;
1317 }
6b1e6cc7
JW
1318 vhost_enqueue_msg(dev, &dev->pending_list, node);
1319 }
1320
1321 return ret;
1322}
1323EXPORT_SYMBOL_GPL(vhost_chr_read_iter);
1324
1325static int vhost_iotlb_miss(struct vhost_virtqueue *vq, u64 iova, int access)
1326{
1327 struct vhost_dev *dev = vq->dev;
1328 struct vhost_msg_node *node;
1329 struct vhost_iotlb_msg *msg;
429711ae 1330 bool v2 = vhost_backend_has_feature(vq, VHOST_BACKEND_F_IOTLB_MSG_V2);
6b1e6cc7 1331
429711ae 1332 node = vhost_new_msg(vq, v2 ? VHOST_IOTLB_MSG_V2 : VHOST_IOTLB_MSG);
6b1e6cc7
JW
1333 if (!node)
1334 return -ENOMEM;
1335
429711ae
JW
1336 if (v2) {
1337 node->msg_v2.type = VHOST_IOTLB_MSG_V2;
1338 msg = &node->msg_v2.iotlb;
1339 } else {
1340 msg = &node->msg.iotlb;
1341 }
1342
6b1e6cc7
JW
1343 msg->type = VHOST_IOTLB_MISS;
1344 msg->iova = iova;
1345 msg->perm = access;
1346
1347 vhost_enqueue_msg(dev, &dev->read_list, node);
1348
1349 return 0;
bfe2bc51
JW
1350}
1351
ddd3d408 1352static bool vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
a865e420
MT
1353 vring_desc_t __user *desc,
1354 vring_avail_t __user *avail,
1355 vring_used_t __user *used)
6b1e6cc7 1356
3a4d5c94 1357{
0210a8db
GK
1358 /* If an IOTLB device is present, the vring addresses are
1359 * GIOVAs. Access validation occurs at prefetch time. */
1360 if (vq->iotlb)
1361 return true;
1362
4942e825
JW
1363 return access_ok(desc, vhost_get_desc_size(vq, num)) &&
1364 access_ok(avail, vhost_get_avail_size(vq, num)) &&
1365 access_ok(used, vhost_get_used_size(vq, num));
3a4d5c94
MT
1366}
1367
f8894913 1368static void vhost_vq_meta_update(struct vhost_virtqueue *vq,
0bbe3066 1369 const struct vhost_iotlb_map *map,
f8894913
JW
1370 int type)
1371{
1372 int access = (type == VHOST_ADDR_USED) ?
1373 VHOST_ACCESS_WO : VHOST_ACCESS_RO;
1374
0bbe3066
JW
1375 if (likely(map->perm & access))
1376 vq->meta_iotlb[type] = map;
f8894913
JW
1377}
1378
ddd3d408
SH
1379static bool iotlb_access_ok(struct vhost_virtqueue *vq,
1380 int access, u64 addr, u64 len, int type)
6b1e6cc7 1381{
0bbe3066
JW
1382 const struct vhost_iotlb_map *map;
1383 struct vhost_iotlb *umem = vq->iotlb;
ca2c5b33 1384 u64 s = 0, size, orig_addr = addr, last = addr + len - 1;
f8894913
JW
1385
1386 if (vhost_vq_meta_fetch(vq, addr, len, type))
1387 return true;
6b1e6cc7
JW
1388
1389 while (len > s) {
0bbe3066
JW
1390 map = vhost_iotlb_itree_first(umem, addr, last);
1391 if (map == NULL || map->start > addr) {
6b1e6cc7
JW
1392 vhost_iotlb_miss(vq, addr, access);
1393 return false;
0bbe3066 1394 } else if (!(map->perm & access)) {
6b1e6cc7
JW
1395 /* Report the possible access violation by
1396 * request another translation from userspace.
1397 */
1398 return false;
1399 }
1400
0bbe3066 1401 size = map->size - addr + map->start;
f8894913
JW
1402
1403 if (orig_addr == addr && size >= len)
0bbe3066 1404 vhost_vq_meta_update(vq, map, type);
f8894913 1405
6b1e6cc7
JW
1406 s += size;
1407 addr += size;
1408 }
1409
1410 return true;
1411}
1412
9b5e830b 1413int vq_meta_prefetch(struct vhost_virtqueue *vq)
6b1e6cc7 1414{
6b1e6cc7
JW
1415 unsigned int num = vq->num;
1416
3d2c7d37 1417 if (!vq->iotlb)
6b1e6cc7
JW
1418 return 1;
1419
0bbe3066 1420 return iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->desc,
4942e825 1421 vhost_get_desc_size(vq, num), VHOST_ADDR_DESC) &&
0bbe3066 1422 iotlb_access_ok(vq, VHOST_MAP_RO, (u64)(uintptr_t)vq->avail,
4942e825 1423 vhost_get_avail_size(vq, num),
f8894913 1424 VHOST_ADDR_AVAIL) &&
0bbe3066 1425 iotlb_access_ok(vq, VHOST_MAP_WO, (u64)(uintptr_t)vq->used,
4942e825 1426 vhost_get_used_size(vq, num), VHOST_ADDR_USED);
6b1e6cc7 1427}
9b5e830b 1428EXPORT_SYMBOL_GPL(vq_meta_prefetch);
6b1e6cc7 1429
3a4d5c94
MT
1430/* Can we log writes? */
1431/* Caller should have device mutex but not vq mutex */
ddd3d408 1432bool vhost_log_access_ok(struct vhost_dev *dev)
3a4d5c94 1433{
a9709d68 1434 return memory_access_ok(dev, dev->umem, 1);
3a4d5c94 1435}
6ac1afbf 1436EXPORT_SYMBOL_GPL(vhost_log_access_ok);
3a4d5c94 1437
ab512251
GK
1438static bool vq_log_used_access_ok(struct vhost_virtqueue *vq,
1439 void __user *log_base,
1440 bool log_used,
1441 u64 log_addr)
1442{
1443 /* If an IOTLB device is present, log_addr is a GIOVA that
1444 * will never be logged by log_used(). */
1445 if (vq->iotlb)
1446 return true;
1447
1448 return !log_used || log_access_ok(log_base, log_addr,
1449 vhost_get_used_size(vq, vq->num));
1450}
1451
3a4d5c94
MT
1452/* Verify access for write logging. */
1453/* Caller should have vq mutex and device mutex */
ddd3d408
SH
1454static bool vq_log_access_ok(struct vhost_virtqueue *vq,
1455 void __user *log_base)
3a4d5c94 1456{
a9709d68 1457 return vq_memory_access_ok(log_base, vq->umem,
ea16c514 1458 vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
ab512251 1459 vq_log_used_access_ok(vq, log_base, vq->log_used, vq->log_addr);
3a4d5c94
MT
1460}
1461
1462/* Can we start vq? */
1463/* Caller should have vq mutex and device mutex */
ddd3d408 1464bool vhost_vq_access_ok(struct vhost_virtqueue *vq)
3a4d5c94 1465{
d14d2b78 1466 if (!vq_log_access_ok(vq, vq->log_base))
ddd3d408 1467 return false;
d65026c6 1468
d65026c6 1469 return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used);
3a4d5c94 1470}
6ac1afbf 1471EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
3a4d5c94
MT
1472
1473static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
1474{
a9709d68
JW
1475 struct vhost_memory mem, *newmem;
1476 struct vhost_memory_region *region;
0bbe3066 1477 struct vhost_iotlb *newumem, *oldumem;
3a4d5c94 1478 unsigned long size = offsetof(struct vhost_memory, regions);
98f9ca0a 1479 int i;
d47effe1 1480
7ad9c9d2
TY
1481 if (copy_from_user(&mem, m, size))
1482 return -EFAULT;
3a4d5c94
MT
1483 if (mem.padding)
1484 return -EOPNOTSUPP;
c9ce42f7 1485 if (mem.nregions > max_mem_regions)
3a4d5c94 1486 return -E2BIG;
b2303d7b
MW
1487 newmem = kvzalloc(struct_size(newmem, regions, mem.nregions),
1488 GFP_KERNEL);
3a4d5c94
MT
1489 if (!newmem)
1490 return -ENOMEM;
1491
1492 memcpy(newmem, &mem, size);
7ad9c9d2 1493 if (copy_from_user(newmem->regions, m->regions,
bf11d71a 1494 flex_array_size(newmem, regions, mem.nregions))) {
bcfeacab 1495 kvfree(newmem);
7ad9c9d2 1496 return -EFAULT;
3a4d5c94
MT
1497 }
1498
0bbe3066 1499 newumem = iotlb_alloc();
a9709d68 1500 if (!newumem) {
4de7255f 1501 kvfree(newmem);
a9709d68
JW
1502 return -ENOMEM;
1503 }
1504
a9709d68
JW
1505 for (region = newmem->regions;
1506 region < newmem->regions + mem.nregions;
1507 region++) {
0bbe3066
JW
1508 if (vhost_iotlb_add_range(newumem,
1509 region->guest_phys_addr,
1510 region->guest_phys_addr +
1511 region->memory_size - 1,
1512 region->userspace_addr,
1513 VHOST_MAP_RW))
a9709d68 1514 goto err;
a02c3789 1515 }
a9709d68
JW
1516
1517 if (!memory_access_ok(d, newumem, 0))
1518 goto err;
1519
1520 oldumem = d->umem;
1521 d->umem = newumem;
98f9ca0a 1522
47283bef 1523 /* All memory accesses are done under some VQ mutex. */
98f9ca0a
MT
1524 for (i = 0; i < d->nvqs; ++i) {
1525 mutex_lock(&d->vqs[i]->mutex);
a9709d68 1526 d->vqs[i]->umem = newumem;
98f9ca0a
MT
1527 mutex_unlock(&d->vqs[i]->mutex);
1528 }
a9709d68
JW
1529
1530 kvfree(newmem);
0bbe3066 1531 vhost_iotlb_free(oldumem);
3a4d5c94 1532 return 0;
a9709d68
JW
1533
1534err:
0bbe3066 1535 vhost_iotlb_free(newumem);
a9709d68
JW
1536 kvfree(newmem);
1537 return -EFAULT;
3a4d5c94
MT
1538}
1539
feebcaea
JW
1540static long vhost_vring_set_num(struct vhost_dev *d,
1541 struct vhost_virtqueue *vq,
1542 void __user *argp)
1543{
1544 struct vhost_vring_state s;
1545
1546 /* Resizing ring with an active backend?
1547 * You don't want to do that. */
1548 if (vq->private_data)
1549 return -EBUSY;
1550
1551 if (copy_from_user(&s, argp, sizeof s))
1552 return -EFAULT;
1553
1554 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1)))
1555 return -EINVAL;
1556 vq->num = s.num;
1557
1558 return 0;
1559}
1560
1561static long vhost_vring_set_addr(struct vhost_dev *d,
1562 struct vhost_virtqueue *vq,
1563 void __user *argp)
1564{
1565 struct vhost_vring_addr a;
1566
1567 if (copy_from_user(&a, argp, sizeof a))
1568 return -EFAULT;
1569 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG))
1570 return -EOPNOTSUPP;
1571
1572 /* For 32bit, verify that the top 32bits of the user
1573 data are set to zero. */
1574 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
1575 (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
1576 (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr)
1577 return -EFAULT;
1578
1579 /* Make sure it's safe to cast pointers to vring types. */
1580 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
1581 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
1582 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
1583 (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
1584 (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1)))
1585 return -EINVAL;
1586
1587 /* We only verify access here if backend is configured.
1588 * If it is not, we don't as size might not have been setup.
1589 * We will verify when backend is configured. */
1590 if (vq->private_data) {
1591 if (!vq_access_ok(vq, vq->num,
1592 (void __user *)(unsigned long)a.desc_user_addr,
1593 (void __user *)(unsigned long)a.avail_user_addr,
1594 (void __user *)(unsigned long)a.used_user_addr))
1595 return -EINVAL;
1596
1597 /* Also validate log access for used ring if enabled. */
ab512251
GK
1598 if (!vq_log_used_access_ok(vq, vq->log_base,
1599 a.flags & (0x1 << VHOST_VRING_F_LOG),
1600 a.log_guest_addr))
feebcaea
JW
1601 return -EINVAL;
1602 }
1603
1604 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
1605 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
1606 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
1607 vq->log_addr = a.log_guest_addr;
1608 vq->used = (void __user *)(unsigned long)a.used_user_addr;
1609
1610 return 0;
1611}
1612
1613static long vhost_vring_set_num_addr(struct vhost_dev *d,
1614 struct vhost_virtqueue *vq,
1615 unsigned int ioctl,
1616 void __user *argp)
1617{
1618 long r;
1619
1620 mutex_lock(&vq->mutex);
1621
1622 switch (ioctl) {
1623 case VHOST_SET_VRING_NUM:
1624 r = vhost_vring_set_num(d, vq, argp);
1625 break;
1626 case VHOST_SET_VRING_ADDR:
1627 r = vhost_vring_set_addr(d, vq, argp);
1628 break;
1629 default:
1630 BUG();
1631 }
1632
1633 mutex_unlock(&vq->mutex);
1634
1635 return r;
1636}
26b36604 1637long vhost_vring_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
3a4d5c94 1638{
cecb46f1
AV
1639 struct file *eventfp, *filep = NULL;
1640 bool pollstart = false, pollstop = false;
3a4d5c94 1641 struct eventfd_ctx *ctx = NULL;
3a4d5c94
MT
1642 struct vhost_virtqueue *vq;
1643 struct vhost_vring_state s;
1644 struct vhost_vring_file f;
3a4d5c94
MT
1645 u32 idx;
1646 long r;
1647
cef25866 1648 r = vhost_get_vq_from_user(d, argp, &vq, &idx);
3a4d5c94
MT
1649 if (r < 0)
1650 return r;
3a4d5c94 1651
feebcaea
JW
1652 if (ioctl == VHOST_SET_VRING_NUM ||
1653 ioctl == VHOST_SET_VRING_ADDR) {
1654 return vhost_vring_set_num_addr(d, vq, ioctl, argp);
1655 }
1656
3a4d5c94
MT
1657 mutex_lock(&vq->mutex);
1658
1659 switch (ioctl) {
3a4d5c94
MT
1660 case VHOST_SET_VRING_BASE:
1661 /* Moving base with an active backend?
1662 * You don't want to do that. */
1663 if (vq->private_data) {
1664 r = -EBUSY;
1665 break;
1666 }
7ad9c9d2
TY
1667 if (copy_from_user(&s, argp, sizeof s)) {
1668 r = -EFAULT;
3a4d5c94 1669 break;
7ad9c9d2 1670 }
55d8122f
SN
1671 if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) {
1672 vq->last_avail_idx = s.num & 0xffff;
1673 vq->last_used_idx = (s.num >> 16) & 0xffff;
1674 } else {
1675 if (s.num > 0xffff) {
1676 r = -EINVAL;
1677 break;
1678 }
1679 vq->last_avail_idx = s.num;
3a4d5c94 1680 }
3a4d5c94
MT
1681 /* Forget the cached index value. */
1682 vq->avail_idx = vq->last_avail_idx;
1683 break;
1684 case VHOST_GET_VRING_BASE:
1685 s.index = idx;
55d8122f
SN
1686 if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED))
1687 s.num = (u32)vq->last_avail_idx | ((u32)vq->last_used_idx << 16);
1688 else
1689 s.num = vq->last_avail_idx;
7ad9c9d2
TY
1690 if (copy_to_user(argp, &s, sizeof s))
1691 r = -EFAULT;
3a4d5c94 1692 break;
3a4d5c94 1693 case VHOST_SET_VRING_KICK:
7ad9c9d2
TY
1694 if (copy_from_user(&f, argp, sizeof f)) {
1695 r = -EFAULT;
3a4d5c94 1696 break;
7ad9c9d2 1697 }
e0136c16 1698 eventfp = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_fget(f.fd);
535297a6
MT
1699 if (IS_ERR(eventfp)) {
1700 r = PTR_ERR(eventfp);
1701 break;
1702 }
3a4d5c94 1703 if (eventfp != vq->kick) {
cecb46f1
AV
1704 pollstop = (filep = vq->kick) != NULL;
1705 pollstart = (vq->kick = eventfp) != NULL;
3a4d5c94
MT
1706 } else
1707 filep = eventfp;
1708 break;
1709 case VHOST_SET_VRING_CALL:
7ad9c9d2
TY
1710 if (copy_from_user(&f, argp, sizeof f)) {
1711 r = -EFAULT;
3a4d5c94 1712 break;
7ad9c9d2 1713 }
e0136c16 1714 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
e050c7d9
EB
1715 if (IS_ERR(ctx)) {
1716 r = PTR_ERR(ctx);
535297a6
MT
1717 break;
1718 }
265a0ad8 1719
265a0ad8 1720 swap(ctx, vq->call_ctx.ctx);
3a4d5c94
MT
1721 break;
1722 case VHOST_SET_VRING_ERR:
7ad9c9d2
TY
1723 if (copy_from_user(&f, argp, sizeof f)) {
1724 r = -EFAULT;
3a4d5c94 1725 break;
7ad9c9d2 1726 }
e0136c16 1727 ctx = f.fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(f.fd);
09f332a5
EB
1728 if (IS_ERR(ctx)) {
1729 r = PTR_ERR(ctx);
535297a6
MT
1730 break;
1731 }
09f332a5 1732 swap(ctx, vq->error_ctx);
3a4d5c94 1733 break;
2751c988
GK
1734 case VHOST_SET_VRING_ENDIAN:
1735 r = vhost_set_vring_endian(vq, argp);
1736 break;
1737 case VHOST_GET_VRING_ENDIAN:
1738 r = vhost_get_vring_endian(vq, idx, argp);
1739 break;
03088137
JW
1740 case VHOST_SET_VRING_BUSYLOOP_TIMEOUT:
1741 if (copy_from_user(&s, argp, sizeof(s))) {
1742 r = -EFAULT;
1743 break;
1744 }
1745 vq->busyloop_timeout = s.num;
1746 break;
1747 case VHOST_GET_VRING_BUSYLOOP_TIMEOUT:
1748 s.index = idx;
1749 s.num = vq->busyloop_timeout;
1750 if (copy_to_user(argp, &s, sizeof(s)))
1751 r = -EFAULT;
1752 break;
3a4d5c94
MT
1753 default:
1754 r = -ENOIOCTLCMD;
1755 }
1756
1757 if (pollstop && vq->handle_kick)
1758 vhost_poll_stop(&vq->poll);
1759
e050c7d9 1760 if (!IS_ERR_OR_NULL(ctx))
3a4d5c94
MT
1761 eventfd_ctx_put(ctx);
1762 if (filep)
1763 fput(filep);
1764
1765 if (pollstart && vq->handle_kick)
2b8b328b 1766 r = vhost_poll_start(&vq->poll, vq->kick);
3a4d5c94
MT
1767
1768 mutex_unlock(&vq->mutex);
1769
1770 if (pollstop && vq->handle_kick)
b2ffa407 1771 vhost_dev_flush(vq->poll.dev);
3a4d5c94
MT
1772 return r;
1773}
6ac1afbf 1774EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
3a4d5c94 1775
759aba1e 1776int vhost_init_device_iotlb(struct vhost_dev *d)
6b1e6cc7 1777{
0bbe3066 1778 struct vhost_iotlb *niotlb, *oiotlb;
6b1e6cc7
JW
1779 int i;
1780
0bbe3066 1781 niotlb = iotlb_alloc();
6b1e6cc7
JW
1782 if (!niotlb)
1783 return -ENOMEM;
1784
1785 oiotlb = d->iotlb;
1786 d->iotlb = niotlb;
1787
1788 for (i = 0; i < d->nvqs; ++i) {
b13f9c63
JW
1789 struct vhost_virtqueue *vq = d->vqs[i];
1790
1791 mutex_lock(&vq->mutex);
1792 vq->iotlb = niotlb;
1793 __vhost_vq_meta_reset(vq);
1794 mutex_unlock(&vq->mutex);
6b1e6cc7
JW
1795 }
1796
0bbe3066 1797 vhost_iotlb_free(oiotlb);
6b1e6cc7
JW
1798
1799 return 0;
1800}
1801EXPORT_SYMBOL_GPL(vhost_init_device_iotlb);
1802
3a4d5c94 1803/* Caller must have device mutex */
935cdee7 1804long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
3a4d5c94 1805{
d25cc43c 1806 struct eventfd_ctx *ctx;
3a4d5c94
MT
1807 u64 p;
1808 long r;
1809 int i, fd;
1810
1811 /* If you are not the owner, you can become one */
1812 if (ioctl == VHOST_SET_OWNER) {
1813 r = vhost_dev_set_owner(d);
1814 goto done;
1815 }
1816
1817 /* You must be the owner to do anything else */
1818 r = vhost_dev_check_owner(d);
1819 if (r)
1820 goto done;
1821
1822 switch (ioctl) {
1823 case VHOST_SET_MEM_TABLE:
1824 r = vhost_set_memory(d, argp);
1825 break;
1826 case VHOST_SET_LOG_BASE:
7ad9c9d2
TY
1827 if (copy_from_user(&p, argp, sizeof p)) {
1828 r = -EFAULT;
3a4d5c94 1829 break;
7ad9c9d2 1830 }
3a4d5c94
MT
1831 if ((u64)(unsigned long)p != p) {
1832 r = -EFAULT;
1833 break;
1834 }
1835 for (i = 0; i < d->nvqs; ++i) {
1836 struct vhost_virtqueue *vq;
1837 void __user *base = (void __user *)(unsigned long)p;
3ab2e420 1838 vq = d->vqs[i];
3a4d5c94
MT
1839 mutex_lock(&vq->mutex);
1840 /* If ring is inactive, will check when it's enabled. */
ea16c514 1841 if (vq->private_data && !vq_log_access_ok(vq, base))
3a4d5c94
MT
1842 r = -EFAULT;
1843 else
1844 vq->log_base = base;
1845 mutex_unlock(&vq->mutex);
1846 }
1847 break;
1848 case VHOST_SET_LOG_FD:
1849 r = get_user(fd, (int __user *)argp);
1850 if (r < 0)
1851 break;
e0136c16 1852 ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd);
d25cc43c
EB
1853 if (IS_ERR(ctx)) {
1854 r = PTR_ERR(ctx);
3a4d5c94
MT
1855 break;
1856 }
d25cc43c 1857 swap(ctx, d->log_ctx);
3a4d5c94 1858 for (i = 0; i < d->nvqs; ++i) {
3ab2e420
AH
1859 mutex_lock(&d->vqs[i]->mutex);
1860 d->vqs[i]->log_ctx = d->log_ctx;
1861 mutex_unlock(&d->vqs[i]->mutex);
3a4d5c94
MT
1862 }
1863 if (ctx)
1864 eventfd_ctx_put(ctx);
3a4d5c94
MT
1865 break;
1866 default:
935cdee7 1867 r = -ENOIOCTLCMD;
3a4d5c94
MT
1868 break;
1869 }
1870done:
1871 return r;
1872}
6ac1afbf 1873EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
3a4d5c94 1874
3a4d5c94
MT
1875/* TODO: This is really inefficient. We need something like get_user()
1876 * (instruction directly accesses the data, with an exception table entry
ff61f079 1877 * returning -EFAULT). See Documentation/arch/x86/exception-tables.rst.
3a4d5c94
MT
1878 */
1879static int set_bit_to_user(int nr, void __user *addr)
1880{
1881 unsigned long log = (unsigned long)addr;
1882 struct page *page;
1883 void *base;
1884 int bit = nr + (log % PAGE_SIZE) * 8;
1885 int r;
d47effe1 1886
690623e1 1887 r = pin_user_pages_fast(log, 1, FOLL_WRITE, &page);
d6db3f5c 1888 if (r < 0)
3a4d5c94 1889 return r;
d6db3f5c 1890 BUG_ON(r != 1);
c6daa7ff 1891 base = kmap_atomic(page);
3a4d5c94 1892 set_bit(bit, base);
c6daa7ff 1893 kunmap_atomic(base);
690623e1 1894 unpin_user_pages_dirty_lock(&page, 1, true);
3a4d5c94
MT
1895 return 0;
1896}
1897
1898static int log_write(void __user *log_base,
1899 u64 write_address, u64 write_length)
1900{
28831ee6 1901 u64 write_page = write_address / VHOST_PAGE_SIZE;
3a4d5c94 1902 int r;
d47effe1 1903
3a4d5c94
MT
1904 if (!write_length)
1905 return 0;
3bf9be40 1906 write_length += write_address % VHOST_PAGE_SIZE;
3a4d5c94
MT
1907 for (;;) {
1908 u64 base = (u64)(unsigned long)log_base;
28831ee6
MT
1909 u64 log = base + write_page / 8;
1910 int bit = write_page % 8;
3a4d5c94
MT
1911 if ((u64)(unsigned long)log != log)
1912 return -EFAULT;
1913 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1914 if (r < 0)
1915 return r;
1916 if (write_length <= VHOST_PAGE_SIZE)
1917 break;
1918 write_length -= VHOST_PAGE_SIZE;
28831ee6 1919 write_page += 1;
3a4d5c94
MT
1920 }
1921 return r;
1922}
1923
cc5e7107
JW
1924static int log_write_hva(struct vhost_virtqueue *vq, u64 hva, u64 len)
1925{
0bbe3066
JW
1926 struct vhost_iotlb *umem = vq->umem;
1927 struct vhost_iotlb_map *u;
cc5e7107
JW
1928 u64 start, end, l, min;
1929 int r;
1930 bool hit = false;
1931
1932 while (len) {
1933 min = len;
1934 /* More than one GPAs can be mapped into a single HVA. So
1935 * iterate all possible umems here to be safe.
1936 */
0bbe3066
JW
1937 list_for_each_entry(u, &umem->list, link) {
1938 if (u->addr > hva - 1 + len ||
1939 u->addr - 1 + u->size < hva)
cc5e7107 1940 continue;
0bbe3066
JW
1941 start = max(u->addr, hva);
1942 end = min(u->addr - 1 + u->size, hva - 1 + len);
cc5e7107
JW
1943 l = end - start + 1;
1944 r = log_write(vq->log_base,
0bbe3066 1945 u->start + start - u->addr,
cc5e7107
JW
1946 l);
1947 if (r < 0)
1948 return r;
1949 hit = true;
1950 min = min(l, min);
1951 }
1952
1953 if (!hit)
1954 return -EFAULT;
1955
1956 len -= min;
1957 hva += min;
1958 }
1959
1960 return 0;
1961}
1962
1963static int log_used(struct vhost_virtqueue *vq, u64 used_offset, u64 len)
1964{
5e5e8736 1965 struct iovec *iov = vq->log_iov;
cc5e7107
JW
1966 int i, ret;
1967
1968 if (!vq->iotlb)
1969 return log_write(vq->log_base, vq->log_addr + used_offset, len);
1970
1971 ret = translate_desc(vq, (uintptr_t)vq->used + used_offset,
1972 len, iov, 64, VHOST_ACCESS_WO);
816db766 1973 if (ret < 0)
cc5e7107
JW
1974 return ret;
1975
1976 for (i = 0; i < ret; i++) {
1977 ret = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1978 iov[i].iov_len);
1979 if (ret)
1980 return ret;
1981 }
1982
1983 return 0;
1984}
1985
3a4d5c94 1986int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
cc5e7107 1987 unsigned int log_num, u64 len, struct iovec *iov, int count)
3a4d5c94
MT
1988{
1989 int i, r;
1990
1991 /* Make sure data written is seen before log. */
5659338c 1992 smp_wmb();
cc5e7107
JW
1993
1994 if (vq->iotlb) {
1995 for (i = 0; i < count; i++) {
1996 r = log_write_hva(vq, (uintptr_t)iov[i].iov_base,
1997 iov[i].iov_len);
1998 if (r < 0)
1999 return r;
2000 }
2001 return 0;
2002 }
2003
3a4d5c94
MT
2004 for (i = 0; i < log_num; ++i) {
2005 u64 l = min(log[i].len, len);
2006 r = log_write(vq->log_base, log[i].addr, l);
2007 if (r < 0)
2008 return r;
2009 len -= l;
5786aee8
MT
2010 if (!len) {
2011 if (vq->log_ctx)
2012 eventfd_signal(vq->log_ctx, 1);
3a4d5c94 2013 return 0;
5786aee8 2014 }
3a4d5c94 2015 }
3a4d5c94
MT
2016 /* Length written exceeds what we have stored. This is a bug. */
2017 BUG();
2018 return 0;
2019}
6ac1afbf 2020EXPORT_SYMBOL_GPL(vhost_log_write);
3a4d5c94 2021
2723feaa
JW
2022static int vhost_update_used_flags(struct vhost_virtqueue *vq)
2023{
2024 void __user *used;
7b5d753e 2025 if (vhost_put_used_flags(vq))
2723feaa
JW
2026 return -EFAULT;
2027 if (unlikely(vq->log_used)) {
2028 /* Make sure the flag is seen before log. */
2029 smp_wmb();
2030 /* Log used flag write. */
2031 used = &vq->used->flags;
cc5e7107
JW
2032 log_used(vq, (used - (void __user *)vq->used),
2033 sizeof vq->used->flags);
2723feaa
JW
2034 if (vq->log_ctx)
2035 eventfd_signal(vq->log_ctx, 1);
2036 }
2037 return 0;
2038}
2039
4c809363 2040static int vhost_update_avail_event(struct vhost_virtqueue *vq)
2723feaa 2041{
7b5d753e 2042 if (vhost_put_avail_event(vq))
2723feaa
JW
2043 return -EFAULT;
2044 if (unlikely(vq->log_used)) {
2045 void __user *used;
2046 /* Make sure the event is seen before log. */
2047 smp_wmb();
2048 /* Log avail event write */
2049 used = vhost_avail_event(vq);
cc5e7107
JW
2050 log_used(vq, (used - (void __user *)vq->used),
2051 sizeof *vhost_avail_event(vq));
2723feaa
JW
2052 if (vq->log_ctx)
2053 eventfd_signal(vq->log_ctx, 1);
2054 }
2055 return 0;
2056}
2057
80f7d030 2058int vhost_vq_init_access(struct vhost_virtqueue *vq)
2723feaa 2059{
3b1bbe89 2060 __virtio16 last_used_idx;
2723feaa 2061 int r;
e1f33be9
GK
2062 bool is_le = vq->is_le;
2063
cda8bba0 2064 if (!vq->private_data)
2723feaa 2065 return 0;
2751c988
GK
2066
2067 vhost_init_is_le(vq);
2723feaa
JW
2068
2069 r = vhost_update_used_flags(vq);
2070 if (r)
e1f33be9 2071 goto err;
2723feaa 2072 vq->signalled_used_valid = false;
6b1e6cc7 2073 if (!vq->iotlb &&
96d4f267 2074 !access_ok(&vq->used->idx, sizeof vq->used->idx)) {
e1f33be9
GK
2075 r = -EFAULT;
2076 goto err;
2077 }
7b5d753e 2078 r = vhost_get_used_idx(vq, &last_used_idx);
6b1e6cc7
JW
2079 if (r) {
2080 vq_err(vq, "Can't access used idx at %p\n",
2081 &vq->used->idx);
e1f33be9 2082 goto err;
6b1e6cc7 2083 }
3b1bbe89 2084 vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
64f7f051 2085 return 0;
6b1e6cc7 2086
e1f33be9
GK
2087err:
2088 vq->is_le = is_le;
2089 return r;
2723feaa 2090}
80f7d030 2091EXPORT_SYMBOL_GPL(vhost_vq_init_access);
2723feaa 2092
47283bef 2093static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
6b1e6cc7 2094 struct iovec iov[], int iov_size, int access)
3a4d5c94 2095{
0bbe3066 2096 const struct vhost_iotlb_map *map;
6b1e6cc7 2097 struct vhost_dev *dev = vq->dev;
0bbe3066 2098 struct vhost_iotlb *umem = dev->iotlb ? dev->iotlb : dev->umem;
3a4d5c94 2099 struct iovec *_iov;
98047313 2100 u64 s = 0, last = addr + len - 1;
3a4d5c94
MT
2101 int ret = 0;
2102
3a4d5c94
MT
2103 while ((u64)len > s) {
2104 u64 size;
7b3384fc 2105 if (unlikely(ret >= iov_size)) {
3a4d5c94
MT
2106 ret = -ENOBUFS;
2107 break;
2108 }
6b1e6cc7 2109
98047313 2110 map = vhost_iotlb_itree_first(umem, addr, last);
0bbe3066 2111 if (map == NULL || map->start > addr) {
6b1e6cc7
JW
2112 if (umem != dev->iotlb) {
2113 ret = -EFAULT;
2114 break;
2115 }
2116 ret = -EAGAIN;
2117 break;
0bbe3066 2118 } else if (!(map->perm & access)) {
6b1e6cc7 2119 ret = -EPERM;
3a4d5c94
MT
2120 break;
2121 }
6b1e6cc7 2122
3a4d5c94 2123 _iov = iov + ret;
0bbe3066 2124 size = map->size - addr + map->start;
bd97120f 2125 _iov->iov_len = min((u64)len - s, size);
0d4a3f2a 2126 _iov->iov_base = (void __user *)(unsigned long)
0bbe3066 2127 (map->addr + addr - map->start);
3a4d5c94
MT
2128 s += size;
2129 addr += size;
2130 ++ret;
2131 }
2132
6b1e6cc7
JW
2133 if (ret == -EAGAIN)
2134 vhost_iotlb_miss(vq, addr, access);
3a4d5c94
MT
2135 return ret;
2136}
2137
2138/* Each buffer in the virtqueues is actually a chain of descriptors. This
2139 * function returns the next descriptor in the chain,
2140 * or -1U if we're at the end. */
3b1bbe89 2141static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
3a4d5c94
MT
2142{
2143 unsigned int next;
2144
2145 /* If this descriptor says it doesn't chain, we're done. */
3b1bbe89 2146 if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
3a4d5c94
MT
2147 return -1U;
2148
2149 /* Check they're not leading us off end of descriptors. */
3a5db0b1 2150 next = vhost16_to_cpu(vq, READ_ONCE(desc->next));
3a4d5c94
MT
2151 return next;
2152}
2153
47283bef 2154static int get_indirect(struct vhost_virtqueue *vq,
7b3384fc
MT
2155 struct iovec iov[], unsigned int iov_size,
2156 unsigned int *out_num, unsigned int *in_num,
2157 struct vhost_log *log, unsigned int *log_num,
2158 struct vring_desc *indirect)
3a4d5c94
MT
2159{
2160 struct vring_desc desc;
2161 unsigned int i = 0, count, found = 0;
3b1bbe89 2162 u32 len = vhost32_to_cpu(vq, indirect->len);
aad9a1ce 2163 struct iov_iter from;
6b1e6cc7 2164 int ret, access;
3a4d5c94
MT
2165
2166 /* Sanity check */
3b1bbe89 2167 if (unlikely(len % sizeof desc)) {
3a4d5c94
MT
2168 vq_err(vq, "Invalid length in indirect descriptor: "
2169 "len 0x%llx not multiple of 0x%zx\n",
3b1bbe89 2170 (unsigned long long)len,
3a4d5c94
MT
2171 sizeof desc);
2172 return -EINVAL;
2173 }
2174
3b1bbe89 2175 ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
6b1e6cc7 2176 UIO_MAXIOV, VHOST_ACCESS_RO);
7b3384fc 2177 if (unlikely(ret < 0)) {
6b1e6cc7
JW
2178 if (ret != -EAGAIN)
2179 vq_err(vq, "Translation failure %d in indirect.\n", ret);
3a4d5c94
MT
2180 return ret;
2181 }
de4eda9d 2182 iov_iter_init(&from, ITER_SOURCE, vq->indirect, ret, len);
3b1bbe89 2183 count = len / sizeof desc;
3a4d5c94
MT
2184 /* Buffers are chained via a 16 bit next field, so
2185 * we can have at most 2^16 of these. */
7b3384fc 2186 if (unlikely(count > USHRT_MAX + 1)) {
3a4d5c94
MT
2187 vq_err(vq, "Indirect buffer length too big: %d\n",
2188 indirect->len);
2189 return -E2BIG;
2190 }
2191
2192 do {
2193 unsigned iov_count = *in_num + *out_num;
7b3384fc 2194 if (unlikely(++found > count)) {
3a4d5c94
MT
2195 vq_err(vq, "Loop detected: last one at %u "
2196 "indirect size %u\n",
2197 i, count);
2198 return -EINVAL;
2199 }
cbbd26b8 2200 if (unlikely(!copy_from_iter_full(&desc, sizeof(desc), &from))) {
3a4d5c94 2201 vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
3b1bbe89 2202 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
3a4d5c94
MT
2203 return -EINVAL;
2204 }
3b1bbe89 2205 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
3a4d5c94 2206 vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
3b1bbe89 2207 i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
3a4d5c94
MT
2208 return -EINVAL;
2209 }
2210
6b1e6cc7
JW
2211 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2212 access = VHOST_ACCESS_WO;
2213 else
2214 access = VHOST_ACCESS_RO;
2215
3b1bbe89
MT
2216 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2217 vhost32_to_cpu(vq, desc.len), iov + iov_count,
6b1e6cc7 2218 iov_size - iov_count, access);
7b3384fc 2219 if (unlikely(ret < 0)) {
6b1e6cc7
JW
2220 if (ret != -EAGAIN)
2221 vq_err(vq, "Translation failure %d indirect idx %d\n",
2222 ret, i);
3a4d5c94
MT
2223 return ret;
2224 }
2225 /* If this is an input descriptor, increment that count. */
6b1e6cc7 2226 if (access == VHOST_ACCESS_WO) {
3a4d5c94 2227 *in_num += ret;
060423bf 2228 if (unlikely(log && ret)) {
3b1bbe89
MT
2229 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2230 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
3a4d5c94
MT
2231 ++*log_num;
2232 }
2233 } else {
2234 /* If it's an output descriptor, they're all supposed
2235 * to come before any input descriptors. */
7b3384fc 2236 if (unlikely(*in_num)) {
3a4d5c94
MT
2237 vq_err(vq, "Indirect descriptor "
2238 "has out after in: idx %d\n", i);
2239 return -EINVAL;
2240 }
2241 *out_num += ret;
2242 }
3b1bbe89 2243 } while ((i = next_desc(vq, &desc)) != -1);
3a4d5c94
MT
2244 return 0;
2245}
2246
2247/* This looks in the virtqueue and for the first available buffer, and converts
2248 * it to an iovec for convenient access. Since descriptors consist of some
2249 * number of output then some number of input descriptors, it's actually two
2250 * iovecs, but we pack them into one and note how many of each there were.
2251 *
d5675bd2
MT
2252 * This function returns the descriptor number found, or vq->num (which is
2253 * never a valid descriptor number) if none was found. A negative code is
2254 * returned on error. */
47283bef 2255int vhost_get_vq_desc(struct vhost_virtqueue *vq,
d5675bd2
MT
2256 struct iovec iov[], unsigned int iov_size,
2257 unsigned int *out_num, unsigned int *in_num,
2258 struct vhost_log *log, unsigned int *log_num)
3a4d5c94
MT
2259{
2260 struct vring_desc desc;
2261 unsigned int i, head, found = 0;
2262 u16 last_avail_idx;
3b1bbe89
MT
2263 __virtio16 avail_idx;
2264 __virtio16 ring_head;
6b1e6cc7 2265 int ret, access;
3a4d5c94
MT
2266
2267 /* Check it isn't doing very strange things with descriptor numbers. */
2268 last_avail_idx = vq->last_avail_idx;
3a4d5c94 2269
e3b56cdd 2270 if (vq->avail_idx == vq->last_avail_idx) {
7b5d753e 2271 if (unlikely(vhost_get_avail_idx(vq, &avail_idx))) {
e3b56cdd
JW
2272 vq_err(vq, "Failed to access avail idx at %p\n",
2273 &vq->avail->idx);
2274 return -EFAULT;
2275 }
2276 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
3a4d5c94 2277
e3b56cdd
JW
2278 if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
2279 vq_err(vq, "Guest moved used index from %u to %u",
2280 last_avail_idx, vq->avail_idx);
2281 return -EFAULT;
2282 }
2283
2284 /* If there's nothing new since last we looked, return
2285 * invalid.
2286 */
2287 if (vq->avail_idx == last_avail_idx)
2288 return vq->num;
3a4d5c94 2289
e3b56cdd
JW
2290 /* Only get avail ring entries after they have been
2291 * exposed by guest.
2292 */
2293 smp_rmb();
2294 }
3a4d5c94
MT
2295
2296 /* Grab the next descriptor number they're advertising, and increment
2297 * the index we've seen. */
7b5d753e 2298 if (unlikely(vhost_get_avail_head(vq, &ring_head, last_avail_idx))) {
3a4d5c94
MT
2299 vq_err(vq, "Failed to read head: idx %d address %p\n",
2300 last_avail_idx,
2301 &vq->avail->ring[last_avail_idx % vq->num]);
d5675bd2 2302 return -EFAULT;
3a4d5c94
MT
2303 }
2304
3b1bbe89
MT
2305 head = vhost16_to_cpu(vq, ring_head);
2306
3a4d5c94 2307 /* If their number is silly, that's an error. */
7b3384fc 2308 if (unlikely(head >= vq->num)) {
3a4d5c94
MT
2309 vq_err(vq, "Guest says index %u > %u is available",
2310 head, vq->num);
d5675bd2 2311 return -EINVAL;
3a4d5c94
MT
2312 }
2313
2314 /* When we start there are none of either input nor output. */
2315 *out_num = *in_num = 0;
2316 if (unlikely(log))
2317 *log_num = 0;
2318
2319 i = head;
2320 do {
2321 unsigned iov_count = *in_num + *out_num;
7b3384fc 2322 if (unlikely(i >= vq->num)) {
3a4d5c94
MT
2323 vq_err(vq, "Desc index is %u > %u, head = %u",
2324 i, vq->num, head);
d5675bd2 2325 return -EINVAL;
3a4d5c94 2326 }
7b3384fc 2327 if (unlikely(++found > vq->num)) {
3a4d5c94
MT
2328 vq_err(vq, "Loop detected: last one at %u "
2329 "vq size %u head %u\n",
2330 i, vq->num, head);
d5675bd2 2331 return -EINVAL;
3a4d5c94 2332 }
7b5d753e 2333 ret = vhost_get_desc(vq, &desc, i);
7b3384fc 2334 if (unlikely(ret)) {
3a4d5c94
MT
2335 vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
2336 i, vq->desc + i);
d5675bd2 2337 return -EFAULT;
3a4d5c94 2338 }
3b1bbe89 2339 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
47283bef 2340 ret = get_indirect(vq, iov, iov_size,
3a4d5c94
MT
2341 out_num, in_num,
2342 log, log_num, &desc);
7b3384fc 2343 if (unlikely(ret < 0)) {
6b1e6cc7
JW
2344 if (ret != -EAGAIN)
2345 vq_err(vq, "Failure detected "
2346 "in indirect descriptor at idx %d\n", i);
d5675bd2 2347 return ret;
3a4d5c94
MT
2348 }
2349 continue;
2350 }
2351
6b1e6cc7
JW
2352 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE))
2353 access = VHOST_ACCESS_WO;
2354 else
2355 access = VHOST_ACCESS_RO;
3b1bbe89
MT
2356 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
2357 vhost32_to_cpu(vq, desc.len), iov + iov_count,
6b1e6cc7 2358 iov_size - iov_count, access);
7b3384fc 2359 if (unlikely(ret < 0)) {
6b1e6cc7
JW
2360 if (ret != -EAGAIN)
2361 vq_err(vq, "Translation failure %d descriptor idx %d\n",
2362 ret, i);
d5675bd2 2363 return ret;
3a4d5c94 2364 }
6b1e6cc7 2365 if (access == VHOST_ACCESS_WO) {
3a4d5c94
MT
2366 /* If this is an input descriptor,
2367 * increment that count. */
2368 *in_num += ret;
060423bf 2369 if (unlikely(log && ret)) {
3b1bbe89
MT
2370 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
2371 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
3a4d5c94
MT
2372 ++*log_num;
2373 }
2374 } else {
2375 /* If it's an output descriptor, they're all supposed
2376 * to come before any input descriptors. */
7b3384fc 2377 if (unlikely(*in_num)) {
3a4d5c94
MT
2378 vq_err(vq, "Descriptor has out after in: "
2379 "idx %d\n", i);
d5675bd2 2380 return -EINVAL;
3a4d5c94
MT
2381 }
2382 *out_num += ret;
2383 }
3b1bbe89 2384 } while ((i = next_desc(vq, &desc)) != -1);
3a4d5c94
MT
2385
2386 /* On success, increment avail index. */
2387 vq->last_avail_idx++;
8ea8cf89
MT
2388
2389 /* Assume notifications from guest are disabled at this point,
2390 * if they aren't we would need to update avail_event index. */
2391 BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
3a4d5c94
MT
2392 return head;
2393}
6ac1afbf 2394EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
3a4d5c94
MT
2395
2396/* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
8dd014ad 2397void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
3a4d5c94 2398{
8dd014ad 2399 vq->last_avail_idx -= n;
3a4d5c94 2400}
6ac1afbf 2401EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
3a4d5c94
MT
2402
2403/* After we've used one of their buffers, we tell them about it. We'll then
2404 * want to notify the guest, using eventfd. */
2405int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
2406{
3b1bbe89
MT
2407 struct vring_used_elem heads = {
2408 cpu_to_vhost32(vq, head),
2409 cpu_to_vhost32(vq, len)
2410 };
3a4d5c94 2411
c49e4e57 2412 return vhost_add_used_n(vq, &heads, 1);
3a4d5c94 2413}
6ac1afbf 2414EXPORT_SYMBOL_GPL(vhost_add_used);
3a4d5c94 2415
8dd014ad
DS
2416static int __vhost_add_used_n(struct vhost_virtqueue *vq,
2417 struct vring_used_elem *heads,
2418 unsigned count)
2419{
a865e420 2420 vring_used_elem_t __user *used;
8ea8cf89 2421 u16 old, new;
8dd014ad
DS
2422 int start;
2423
5fba13b5 2424 start = vq->last_used_idx & (vq->num - 1);
8dd014ad 2425 used = vq->used->ring + start;
7b5d753e 2426 if (vhost_put_used(vq, heads, start, count)) {
8dd014ad
DS
2427 vq_err(vq, "Failed to write used");
2428 return -EFAULT;
2429 }
2430 if (unlikely(vq->log_used)) {
2431 /* Make sure data is seen before log. */
2432 smp_wmb();
2433 /* Log used ring entry write. */
cc5e7107
JW
2434 log_used(vq, ((void __user *)used - (void __user *)vq->used),
2435 count * sizeof *used);
8dd014ad 2436 }
8ea8cf89
MT
2437 old = vq->last_used_idx;
2438 new = (vq->last_used_idx += count);
2439 /* If the driver never bothers to signal in a very long while,
2440 * used index might wrap around. If that happens, invalidate
2441 * signalled_used index we stored. TODO: make sure driver
2442 * signals at least once in 2^16 and remove this. */
2443 if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
2444 vq->signalled_used_valid = false;
8dd014ad
DS
2445 return 0;
2446}
2447
2448/* After we've used one of their buffers, we tell them about it. We'll then
2449 * want to notify the guest, using eventfd. */
2450int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
2451 unsigned count)
2452{
2453 int start, n, r;
2454
5fba13b5 2455 start = vq->last_used_idx & (vq->num - 1);
8dd014ad
DS
2456 n = vq->num - start;
2457 if (n < count) {
2458 r = __vhost_add_used_n(vq, heads, n);
2459 if (r < 0)
2460 return r;
2461 heads += n;
2462 count -= n;
2463 }
2464 r = __vhost_add_used_n(vq, heads, count);
2465
2466 /* Make sure buffer is written before we update index. */
2467 smp_wmb();
7b5d753e 2468 if (vhost_put_used_idx(vq)) {
8dd014ad
DS
2469 vq_err(vq, "Failed to increment used idx");
2470 return -EFAULT;
2471 }
2472 if (unlikely(vq->log_used)) {
841df922
JW
2473 /* Make sure used idx is seen before log. */
2474 smp_wmb();
8dd014ad 2475 /* Log used index update. */
cc5e7107
JW
2476 log_used(vq, offsetof(struct vring_used, idx),
2477 sizeof vq->used->idx);
8dd014ad
DS
2478 if (vq->log_ctx)
2479 eventfd_signal(vq->log_ctx, 1);
2480 }
2481 return r;
2482}
6ac1afbf 2483EXPORT_SYMBOL_GPL(vhost_add_used_n);
8dd014ad 2484
8ea8cf89 2485static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3a4d5c94 2486{
3b1bbe89
MT
2487 __u16 old, new;
2488 __virtio16 event;
8ea8cf89 2489 bool v;
8d65843c
JW
2490 /* Flush out used index updates. This is paired
2491 * with the barrier that the Guest executes when enabling
2492 * interrupts. */
2493 smp_mb();
0d499356 2494
ea16c514 2495 if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
8ea8cf89
MT
2496 unlikely(vq->avail_idx == vq->last_avail_idx))
2497 return true;
2498
ea16c514 2499 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
3b1bbe89 2500 __virtio16 flags;
7b5d753e 2501 if (vhost_get_avail_flags(vq, &flags)) {
8ea8cf89
MT
2502 vq_err(vq, "Failed to get flags");
2503 return true;
2504 }
3b1bbe89 2505 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
3a4d5c94 2506 }
8ea8cf89
MT
2507 old = vq->signalled_used;
2508 v = vq->signalled_used_valid;
2509 new = vq->signalled_used = vq->last_used_idx;
2510 vq->signalled_used_valid = true;
3a4d5c94 2511
8ea8cf89
MT
2512 if (unlikely(!v))
2513 return true;
3a4d5c94 2514
7b5d753e 2515 if (vhost_get_used_event(vq, &event)) {
8ea8cf89
MT
2516 vq_err(vq, "Failed to get used event idx");
2517 return true;
2518 }
8d65843c 2519 return vring_need_event(vhost16_to_cpu(vq, event), new, old);
8ea8cf89
MT
2520}
2521
2522/* This actually signals the guest, using eventfd. */
2523void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2524{
3a4d5c94 2525 /* Signal the Guest tell them we used something up. */
265a0ad8
ZL
2526 if (vq->call_ctx.ctx && vhost_notify(dev, vq))
2527 eventfd_signal(vq->call_ctx.ctx, 1);
3a4d5c94 2528}
6ac1afbf 2529EXPORT_SYMBOL_GPL(vhost_signal);
3a4d5c94
MT
2530
2531/* And here's the combo meal deal. Supersize me! */
2532void vhost_add_used_and_signal(struct vhost_dev *dev,
2533 struct vhost_virtqueue *vq,
2534 unsigned int head, int len)
2535{
2536 vhost_add_used(vq, head, len);
2537 vhost_signal(dev, vq);
2538}
6ac1afbf 2539EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
3a4d5c94 2540
8dd014ad
DS
2541/* multi-buffer version of vhost_add_used_and_signal */
2542void vhost_add_used_and_signal_n(struct vhost_dev *dev,
2543 struct vhost_virtqueue *vq,
2544 struct vring_used_elem *heads, unsigned count)
2545{
2546 vhost_add_used_n(vq, heads, count);
2547 vhost_signal(dev, vq);
2548}
6ac1afbf 2549EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
8dd014ad 2550
d4a60603
JW
2551/* return true if we're sure that avaiable ring is empty */
2552bool vhost_vq_avail_empty(struct vhost_dev *dev, struct vhost_virtqueue *vq)
2553{
2554 __virtio16 avail_idx;
2555 int r;
2556
275bf960
JW
2557 if (vq->avail_idx != vq->last_avail_idx)
2558 return false;
2559
7b5d753e 2560 r = vhost_get_avail_idx(vq, &avail_idx);
275bf960 2561 if (unlikely(r))
d4a60603 2562 return false;
275bf960 2563 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
d4a60603 2564
275bf960 2565 return vq->avail_idx == vq->last_avail_idx;
d4a60603
JW
2566}
2567EXPORT_SYMBOL_GPL(vhost_vq_avail_empty);
2568
3a4d5c94 2569/* OK, now we need to know about added descriptors. */
8ea8cf89 2570bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3a4d5c94 2571{
3b1bbe89 2572 __virtio16 avail_idx;
3a4d5c94 2573 int r;
d47effe1 2574
3a4d5c94
MT
2575 if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
2576 return false;
2577 vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
ea16c514 2578 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2723feaa 2579 r = vhost_update_used_flags(vq);
8ea8cf89
MT
2580 if (r) {
2581 vq_err(vq, "Failed to enable notification at %p: %d\n",
2582 &vq->used->flags, r);
2583 return false;
2584 }
2585 } else {
4c809363 2586 r = vhost_update_avail_event(vq);
8ea8cf89
MT
2587 if (r) {
2588 vq_err(vq, "Failed to update avail event index at %p: %d\n",
2589 vhost_avail_event(vq), r);
2590 return false;
2591 }
2592 }
3a4d5c94
MT
2593 /* They could have slipped one in as we were doing that: make
2594 * sure it's written, then check again. */
5659338c 2595 smp_mb();
7b5d753e 2596 r = vhost_get_avail_idx(vq, &avail_idx);
3a4d5c94
MT
2597 if (r) {
2598 vq_err(vq, "Failed to check avail idx at %p: %d\n",
2599 &vq->avail->idx, r);
2600 return false;
2601 }
d3bb267b 2602 vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
3a4d5c94 2603
d3bb267b 2604 return vq->avail_idx != vq->last_avail_idx;
3a4d5c94 2605}
6ac1afbf 2606EXPORT_SYMBOL_GPL(vhost_enable_notify);
3a4d5c94
MT
2607
2608/* We don't need to be notified again. */
8ea8cf89 2609void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
3a4d5c94
MT
2610{
2611 int r;
d47effe1 2612
3a4d5c94
MT
2613 if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
2614 return;
2615 vq->used_flags |= VRING_USED_F_NO_NOTIFY;
ea16c514 2616 if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
2723feaa 2617 r = vhost_update_used_flags(vq);
8ea8cf89 2618 if (r)
ae6961de 2619 vq_err(vq, "Failed to disable notification at %p: %d\n",
8ea8cf89
MT
2620 &vq->used->flags, r);
2621 }
3a4d5c94 2622}
6ac1afbf
AH
2623EXPORT_SYMBOL_GPL(vhost_disable_notify);
2624
6b1e6cc7
JW
2625/* Create a new message. */
2626struct vhost_msg_node *vhost_new_msg(struct vhost_virtqueue *vq, int type)
2627{
4d8df0f5
PB
2628 /* Make sure all padding within the structure is initialized. */
2629 struct vhost_msg_node *node = kzalloc(sizeof(*node), GFP_KERNEL);
6b1e6cc7
JW
2630 if (!node)
2631 return NULL;
670ae9ca 2632
6b1e6cc7
JW
2633 node->vq = vq;
2634 node->msg.type = type;
2635 return node;
2636}
2637EXPORT_SYMBOL_GPL(vhost_new_msg);
2638
2639void vhost_enqueue_msg(struct vhost_dev *dev, struct list_head *head,
2640 struct vhost_msg_node *node)
2641{
2642 spin_lock(&dev->iotlb_lock);
2643 list_add_tail(&node->node, head);
2644 spin_unlock(&dev->iotlb_lock);
2645
a9a08845 2646 wake_up_interruptible_poll(&dev->wait, EPOLLIN | EPOLLRDNORM);
6b1e6cc7
JW
2647}
2648EXPORT_SYMBOL_GPL(vhost_enqueue_msg);
2649
2650struct vhost_msg_node *vhost_dequeue_msg(struct vhost_dev *dev,
2651 struct list_head *head)
2652{
2653 struct vhost_msg_node *node = NULL;
2654
2655 spin_lock(&dev->iotlb_lock);
2656 if (!list_empty(head)) {
2657 node = list_first_entry(head, struct vhost_msg_node,
2658 node);
2659 list_del(&node->node);
2660 }
2661 spin_unlock(&dev->iotlb_lock);
2662
2663 return node;
2664}
2665EXPORT_SYMBOL_GPL(vhost_dequeue_msg);
2666
460f7ce1
JW
2667void vhost_set_backend_features(struct vhost_dev *dev, u64 features)
2668{
2669 struct vhost_virtqueue *vq;
2670 int i;
2671
2672 mutex_lock(&dev->mutex);
2673 for (i = 0; i < dev->nvqs; ++i) {
2674 vq = dev->vqs[i];
2675 mutex_lock(&vq->mutex);
2676 vq->acked_backend_features = features;
2677 mutex_unlock(&vq->mutex);
2678 }
2679 mutex_unlock(&dev->mutex);
2680}
2681EXPORT_SYMBOL_GPL(vhost_set_backend_features);
6b1e6cc7 2682
6ac1afbf
AH
2683static int __init vhost_init(void)
2684{
2685 return 0;
2686}
2687
2688static void __exit vhost_exit(void)
2689{
2690}
2691
2692module_init(vhost_init);
2693module_exit(vhost_exit);
2694
2695MODULE_VERSION("0.0.1");
2696MODULE_LICENSE("GPL v2");
2697MODULE_AUTHOR("Michael S. Tsirkin");
2698MODULE_DESCRIPTION("Host kernel accelerator for virtio");