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