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