Linux-libre 4.4.228-gnu
[librecmc/linux-libre.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 #include <linux/nospec.h>
31
32 #include "vhost.h"
33
34 static ushort max_mem_regions = 64;
35 module_param(max_mem_regions, ushort, 0444);
36 MODULE_PARM_DESC(max_mem_regions,
37         "Maximum number of memory regions in memory map. (default: 64)");
38
39 enum {
40         VHOST_MEMORY_F_LOG = 0x1,
41 };
42
43 #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
44 #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
45
46 #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
47 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
48 {
49         vq->user_be = !virtio_legacy_is_little_endian();
50 }
51
52 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
53 {
54         struct vhost_vring_state s;
55
56         if (vq->private_data)
57                 return -EBUSY;
58
59         if (copy_from_user(&s, argp, sizeof(s)))
60                 return -EFAULT;
61
62         if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
63             s.num != VHOST_VRING_BIG_ENDIAN)
64                 return -EINVAL;
65
66         vq->user_be = s.num;
67
68         return 0;
69 }
70
71 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
72                                    int __user *argp)
73 {
74         struct vhost_vring_state s = {
75                 .index = idx,
76                 .num = vq->user_be
77         };
78
79         if (copy_to_user(argp, &s, sizeof(s)))
80                 return -EFAULT;
81
82         return 0;
83 }
84
85 static void vhost_init_is_le(struct vhost_virtqueue *vq)
86 {
87         /* Note for legacy virtio: user_be is initialized at reset time
88          * according to the host endianness. If userspace does not set an
89          * explicit endianness, the default behavior is native endian, as
90          * expected by legacy virtio.
91          */
92         vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
93 }
94 #else
95 static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
96 {
97 }
98
99 static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
100 {
101         return -ENOIOCTLCMD;
102 }
103
104 static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
105                                    int __user *argp)
106 {
107         return -ENOIOCTLCMD;
108 }
109
110 static void vhost_init_is_le(struct vhost_virtqueue *vq)
111 {
112         if (vhost_has_feature(vq, VIRTIO_F_VERSION_1))
113                 vq->is_le = true;
114 }
115 #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
116
117 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
118                             poll_table *pt)
119 {
120         struct vhost_poll *poll;
121
122         poll = container_of(pt, struct vhost_poll, table);
123         poll->wqh = wqh;
124         add_wait_queue(wqh, &poll->wait);
125 }
126
127 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
128                              void *key)
129 {
130         struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
131
132         if (!((unsigned long)key & poll->mask))
133                 return 0;
134
135         vhost_poll_queue(poll);
136         return 0;
137 }
138
139 void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
140 {
141         INIT_LIST_HEAD(&work->node);
142         work->fn = fn;
143         init_waitqueue_head(&work->done);
144         work->flushing = 0;
145         work->queue_seq = work->done_seq = 0;
146 }
147 EXPORT_SYMBOL_GPL(vhost_work_init);
148
149 /* Init poll structure */
150 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
151                      unsigned long mask, struct vhost_dev *dev)
152 {
153         init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
154         init_poll_funcptr(&poll->table, vhost_poll_func);
155         poll->mask = mask;
156         poll->dev = dev;
157         poll->wqh = NULL;
158
159         vhost_work_init(&poll->work, fn);
160 }
161 EXPORT_SYMBOL_GPL(vhost_poll_init);
162
163 /* Start polling a file. We add ourselves to file's wait queue. The caller must
164  * keep a reference to a file until after vhost_poll_stop is called. */
165 int vhost_poll_start(struct vhost_poll *poll, struct file *file)
166 {
167         unsigned long mask;
168         int ret = 0;
169
170         if (poll->wqh)
171                 return 0;
172
173         mask = file->f_op->poll(file, &poll->table);
174         if (mask)
175                 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
176         if (mask & POLLERR) {
177                 vhost_poll_stop(poll);
178                 ret = -EINVAL;
179         }
180
181         return ret;
182 }
183 EXPORT_SYMBOL_GPL(vhost_poll_start);
184
185 /* Stop polling a file. After this function returns, it becomes safe to drop the
186  * file reference. You must also flush afterwards. */
187 void vhost_poll_stop(struct vhost_poll *poll)
188 {
189         if (poll->wqh) {
190                 remove_wait_queue(poll->wqh, &poll->wait);
191                 poll->wqh = NULL;
192         }
193 }
194 EXPORT_SYMBOL_GPL(vhost_poll_stop);
195
196 static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
197                                 unsigned seq)
198 {
199         int left;
200
201         spin_lock_irq(&dev->work_lock);
202         left = seq - work->done_seq;
203         spin_unlock_irq(&dev->work_lock);
204         return left <= 0;
205 }
206
207 void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
208 {
209         unsigned seq;
210         int flushing;
211
212         spin_lock_irq(&dev->work_lock);
213         seq = work->queue_seq;
214         work->flushing++;
215         spin_unlock_irq(&dev->work_lock);
216         wait_event(work->done, vhost_work_seq_done(dev, work, seq));
217         spin_lock_irq(&dev->work_lock);
218         flushing = --work->flushing;
219         spin_unlock_irq(&dev->work_lock);
220         BUG_ON(flushing < 0);
221 }
222 EXPORT_SYMBOL_GPL(vhost_work_flush);
223
224 /* Flush any work that has been scheduled. When calling this, don't hold any
225  * locks that are also used by the callback. */
226 void vhost_poll_flush(struct vhost_poll *poll)
227 {
228         vhost_work_flush(poll->dev, &poll->work);
229 }
230 EXPORT_SYMBOL_GPL(vhost_poll_flush);
231
232 void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
233 {
234         unsigned long flags;
235
236         spin_lock_irqsave(&dev->work_lock, flags);
237         if (list_empty(&work->node)) {
238                 list_add_tail(&work->node, &dev->work_list);
239                 work->queue_seq++;
240                 spin_unlock_irqrestore(&dev->work_lock, flags);
241                 wake_up_process(dev->worker);
242         } else {
243                 spin_unlock_irqrestore(&dev->work_lock, flags);
244         }
245 }
246 EXPORT_SYMBOL_GPL(vhost_work_queue);
247
248 void vhost_poll_queue(struct vhost_poll *poll)
249 {
250         vhost_work_queue(poll->dev, &poll->work);
251 }
252 EXPORT_SYMBOL_GPL(vhost_poll_queue);
253
254 static void vhost_vq_reset(struct vhost_dev *dev,
255                            struct vhost_virtqueue *vq)
256 {
257         vq->num = 1;
258         vq->desc = NULL;
259         vq->avail = NULL;
260         vq->used = NULL;
261         vq->last_avail_idx = 0;
262         vq->avail_idx = 0;
263         vq->last_used_idx = 0;
264         vq->signalled_used = 0;
265         vq->signalled_used_valid = false;
266         vq->used_flags = 0;
267         vq->log_used = false;
268         vq->log_addr = -1ull;
269         vq->private_data = NULL;
270         vq->acked_features = 0;
271         vq->log_base = NULL;
272         vq->error_ctx = NULL;
273         vq->error = NULL;
274         vq->kick = NULL;
275         vq->call_ctx = NULL;
276         vq->call = NULL;
277         vq->log_ctx = NULL;
278         vq->memory = NULL;
279         vq->is_le = virtio_legacy_is_little_endian();
280         vhost_vq_reset_user_be(vq);
281 }
282
283 static int vhost_worker(void *data)
284 {
285         struct vhost_dev *dev = data;
286         struct vhost_work *work = NULL;
287         unsigned uninitialized_var(seq);
288         mm_segment_t oldfs = get_fs();
289
290         set_fs(USER_DS);
291         use_mm(dev->mm);
292
293         for (;;) {
294                 /* mb paired w/ kthread_stop */
295                 set_current_state(TASK_INTERRUPTIBLE);
296
297                 spin_lock_irq(&dev->work_lock);
298                 if (work) {
299                         work->done_seq = seq;
300                         if (work->flushing)
301                                 wake_up_all(&work->done);
302                 }
303
304                 if (kthread_should_stop()) {
305                         spin_unlock_irq(&dev->work_lock);
306                         __set_current_state(TASK_RUNNING);
307                         break;
308                 }
309                 if (!list_empty(&dev->work_list)) {
310                         work = list_first_entry(&dev->work_list,
311                                                 struct vhost_work, node);
312                         list_del_init(&work->node);
313                         seq = work->queue_seq;
314                 } else
315                         work = NULL;
316                 spin_unlock_irq(&dev->work_lock);
317
318                 if (work) {
319                         __set_current_state(TASK_RUNNING);
320                         work->fn(work);
321                         if (need_resched())
322                                 schedule();
323                 } else
324                         schedule();
325
326         }
327         unuse_mm(dev->mm);
328         set_fs(oldfs);
329         return 0;
330 }
331
332 static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
333 {
334         kfree(vq->indirect);
335         vq->indirect = NULL;
336         kfree(vq->log);
337         vq->log = NULL;
338         kfree(vq->heads);
339         vq->heads = NULL;
340 }
341
342 /* Helper to allocate iovec buffers for all vqs. */
343 static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
344 {
345         struct vhost_virtqueue *vq;
346         int i;
347
348         for (i = 0; i < dev->nvqs; ++i) {
349                 vq = dev->vqs[i];
350                 vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
351                                        GFP_KERNEL);
352                 vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
353                 vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
354                 if (!vq->indirect || !vq->log || !vq->heads)
355                         goto err_nomem;
356         }
357         return 0;
358
359 err_nomem:
360         for (; i >= 0; --i)
361                 vhost_vq_free_iovecs(dev->vqs[i]);
362         return -ENOMEM;
363 }
364
365 static void vhost_dev_free_iovecs(struct vhost_dev *dev)
366 {
367         int i;
368
369         for (i = 0; i < dev->nvqs; ++i)
370                 vhost_vq_free_iovecs(dev->vqs[i]);
371 }
372
373 bool vhost_exceeds_weight(struct vhost_virtqueue *vq,
374                           int pkts, int total_len)
375 {
376         struct vhost_dev *dev = vq->dev;
377
378         if ((dev->byte_weight && total_len >= dev->byte_weight) ||
379             pkts >= dev->weight) {
380                 vhost_poll_queue(&vq->poll);
381                 return true;
382         }
383
384         return false;
385 }
386 EXPORT_SYMBOL_GPL(vhost_exceeds_weight);
387
388 void vhost_dev_init(struct vhost_dev *dev,
389                     struct vhost_virtqueue **vqs, int nvqs,
390                     int weight, int byte_weight)
391 {
392         struct vhost_virtqueue *vq;
393         int i;
394
395         dev->vqs = vqs;
396         dev->nvqs = nvqs;
397         mutex_init(&dev->mutex);
398         dev->log_ctx = NULL;
399         dev->log_file = NULL;
400         dev->memory = NULL;
401         dev->mm = NULL;
402         spin_lock_init(&dev->work_lock);
403         INIT_LIST_HEAD(&dev->work_list);
404         dev->worker = NULL;
405         dev->weight = weight;
406         dev->byte_weight = byte_weight;
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         idx = array_index_nospec(idx, d->nvqs);
771         vq = d->vqs[idx];
772
773         mutex_lock(&vq->mutex);
774
775         switch (ioctl) {
776         case VHOST_SET_VRING_NUM:
777                 /* Resizing ring with an active backend?
778                  * You don't want to do that. */
779                 if (vq->private_data) {
780                         r = -EBUSY;
781                         break;
782                 }
783                 if (copy_from_user(&s, argp, sizeof s)) {
784                         r = -EFAULT;
785                         break;
786                 }
787                 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
788                         r = -EINVAL;
789                         break;
790                 }
791                 vq->num = s.num;
792                 break;
793         case VHOST_SET_VRING_BASE:
794                 /* Moving base with an active backend?
795                  * You don't want to do that. */
796                 if (vq->private_data) {
797                         r = -EBUSY;
798                         break;
799                 }
800                 if (copy_from_user(&s, argp, sizeof s)) {
801                         r = -EFAULT;
802                         break;
803                 }
804                 if (s.num > 0xffff) {
805                         r = -EINVAL;
806                         break;
807                 }
808                 vq->last_avail_idx = s.num;
809                 /* Forget the cached index value. */
810                 vq->avail_idx = vq->last_avail_idx;
811                 break;
812         case VHOST_GET_VRING_BASE:
813                 s.index = idx;
814                 s.num = vq->last_avail_idx;
815                 if (copy_to_user(argp, &s, sizeof s))
816                         r = -EFAULT;
817                 break;
818         case VHOST_SET_VRING_ADDR:
819                 if (copy_from_user(&a, argp, sizeof a)) {
820                         r = -EFAULT;
821                         break;
822                 }
823                 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
824                         r = -EOPNOTSUPP;
825                         break;
826                 }
827                 /* For 32bit, verify that the top 32bits of the user
828                    data are set to zero. */
829                 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
830                     (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
831                     (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
832                         r = -EFAULT;
833                         break;
834                 }
835
836                 /* Make sure it's safe to cast pointers to vring types. */
837                 BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
838                 BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
839                 if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
840                     (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
841                     (a.log_guest_addr & (VRING_USED_ALIGN_SIZE - 1))) {
842                         r = -EINVAL;
843                         break;
844                 }
845
846                 /* We only verify access here if backend is configured.
847                  * If it is not, we don't as size might not have been setup.
848                  * We will verify when backend is configured. */
849                 if (vq->private_data) {
850                         if (!vq_access_ok(vq, vq->num,
851                                 (void __user *)(unsigned long)a.desc_user_addr,
852                                 (void __user *)(unsigned long)a.avail_user_addr,
853                                 (void __user *)(unsigned long)a.used_user_addr)) {
854                                 r = -EINVAL;
855                                 break;
856                         }
857
858                         /* Also validate log access for used ring if enabled. */
859                         if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
860                             !log_access_ok(vq->log_base, a.log_guest_addr,
861                                            sizeof *vq->used +
862                                            vq->num * sizeof *vq->used->ring)) {
863                                 r = -EINVAL;
864                                 break;
865                         }
866                 }
867
868                 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
869                 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
870                 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
871                 vq->log_addr = a.log_guest_addr;
872                 vq->used = (void __user *)(unsigned long)a.used_user_addr;
873                 break;
874         case VHOST_SET_VRING_KICK:
875                 if (copy_from_user(&f, argp, sizeof f)) {
876                         r = -EFAULT;
877                         break;
878                 }
879                 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
880                 if (IS_ERR(eventfp)) {
881                         r = PTR_ERR(eventfp);
882                         break;
883                 }
884                 if (eventfp != vq->kick) {
885                         pollstop = (filep = vq->kick) != NULL;
886                         pollstart = (vq->kick = eventfp) != NULL;
887                 } else
888                         filep = eventfp;
889                 break;
890         case VHOST_SET_VRING_CALL:
891                 if (copy_from_user(&f, argp, sizeof f)) {
892                         r = -EFAULT;
893                         break;
894                 }
895                 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
896                 if (IS_ERR(eventfp)) {
897                         r = PTR_ERR(eventfp);
898                         break;
899                 }
900                 if (eventfp != vq->call) {
901                         filep = vq->call;
902                         ctx = vq->call_ctx;
903                         vq->call = eventfp;
904                         vq->call_ctx = eventfp ?
905                                 eventfd_ctx_fileget(eventfp) : NULL;
906                 } else
907                         filep = eventfp;
908                 break;
909         case VHOST_SET_VRING_ERR:
910                 if (copy_from_user(&f, argp, sizeof f)) {
911                         r = -EFAULT;
912                         break;
913                 }
914                 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
915                 if (IS_ERR(eventfp)) {
916                         r = PTR_ERR(eventfp);
917                         break;
918                 }
919                 if (eventfp != vq->error) {
920                         filep = vq->error;
921                         vq->error = eventfp;
922                         ctx = vq->error_ctx;
923                         vq->error_ctx = eventfp ?
924                                 eventfd_ctx_fileget(eventfp) : NULL;
925                 } else
926                         filep = eventfp;
927                 break;
928         case VHOST_SET_VRING_ENDIAN:
929                 r = vhost_set_vring_endian(vq, argp);
930                 break;
931         case VHOST_GET_VRING_ENDIAN:
932                 r = vhost_get_vring_endian(vq, idx, argp);
933                 break;
934         default:
935                 r = -ENOIOCTLCMD;
936         }
937
938         if (pollstop && vq->handle_kick)
939                 vhost_poll_stop(&vq->poll);
940
941         if (ctx)
942                 eventfd_ctx_put(ctx);
943         if (filep)
944                 fput(filep);
945
946         if (pollstart && vq->handle_kick)
947                 r = vhost_poll_start(&vq->poll, vq->kick);
948
949         mutex_unlock(&vq->mutex);
950
951         if (pollstop && vq->handle_kick)
952                 vhost_poll_flush(&vq->poll);
953         return r;
954 }
955 EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
956
957 /* Caller must have device mutex */
958 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
959 {
960         struct file *eventfp, *filep = NULL;
961         struct eventfd_ctx *ctx = NULL;
962         u64 p;
963         long r;
964         int i, fd;
965
966         /* If you are not the owner, you can become one */
967         if (ioctl == VHOST_SET_OWNER) {
968                 r = vhost_dev_set_owner(d);
969                 goto done;
970         }
971
972         /* You must be the owner to do anything else */
973         r = vhost_dev_check_owner(d);
974         if (r)
975                 goto done;
976
977         switch (ioctl) {
978         case VHOST_SET_MEM_TABLE:
979                 r = vhost_set_memory(d, argp);
980                 break;
981         case VHOST_SET_LOG_BASE:
982                 if (copy_from_user(&p, argp, sizeof p)) {
983                         r = -EFAULT;
984                         break;
985                 }
986                 if ((u64)(unsigned long)p != p) {
987                         r = -EFAULT;
988                         break;
989                 }
990                 for (i = 0; i < d->nvqs; ++i) {
991                         struct vhost_virtqueue *vq;
992                         void __user *base = (void __user *)(unsigned long)p;
993                         vq = d->vqs[i];
994                         mutex_lock(&vq->mutex);
995                         /* If ring is inactive, will check when it's enabled. */
996                         if (vq->private_data && !vq_log_access_ok(vq, base))
997                                 r = -EFAULT;
998                         else
999                                 vq->log_base = base;
1000                         mutex_unlock(&vq->mutex);
1001                 }
1002                 break;
1003         case VHOST_SET_LOG_FD:
1004                 r = get_user(fd, (int __user *)argp);
1005                 if (r < 0)
1006                         break;
1007                 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
1008                 if (IS_ERR(eventfp)) {
1009                         r = PTR_ERR(eventfp);
1010                         break;
1011                 }
1012                 if (eventfp != d->log_file) {
1013                         filep = d->log_file;
1014                         d->log_file = eventfp;
1015                         ctx = d->log_ctx;
1016                         d->log_ctx = eventfp ?
1017                                 eventfd_ctx_fileget(eventfp) : NULL;
1018                 } else
1019                         filep = eventfp;
1020                 for (i = 0; i < d->nvqs; ++i) {
1021                         mutex_lock(&d->vqs[i]->mutex);
1022                         d->vqs[i]->log_ctx = d->log_ctx;
1023                         mutex_unlock(&d->vqs[i]->mutex);
1024                 }
1025                 if (ctx)
1026                         eventfd_ctx_put(ctx);
1027                 if (filep)
1028                         fput(filep);
1029                 break;
1030         default:
1031                 r = -ENOIOCTLCMD;
1032                 break;
1033         }
1034 done:
1035         return r;
1036 }
1037 EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
1038
1039 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
1040                                                      __u64 addr, __u32 len)
1041 {
1042         const struct vhost_memory_region *reg;
1043         int start = 0, end = mem->nregions;
1044
1045         while (start < end) {
1046                 int slot = start + (end - start) / 2;
1047                 reg = mem->regions + slot;
1048                 if (addr >= reg->guest_phys_addr)
1049                         end = slot;
1050                 else
1051                         start = slot + 1;
1052         }
1053
1054         reg = mem->regions + start;
1055         if (addr >= reg->guest_phys_addr &&
1056                 reg->guest_phys_addr + reg->memory_size > addr)
1057                 return reg;
1058         return NULL;
1059 }
1060
1061 /* TODO: This is really inefficient.  We need something like get_user()
1062  * (instruction directly accesses the data, with an exception table entry
1063  * returning -EFAULT). See Documentation/x86/exception-tables.txt.
1064  */
1065 static int set_bit_to_user(int nr, void __user *addr)
1066 {
1067         unsigned long log = (unsigned long)addr;
1068         struct page *page;
1069         void *base;
1070         int bit = nr + (log % PAGE_SIZE) * 8;
1071         int r;
1072
1073         r = get_user_pages_fast(log, 1, 1, &page);
1074         if (r < 0)
1075                 return r;
1076         BUG_ON(r != 1);
1077         base = kmap_atomic(page);
1078         set_bit(bit, base);
1079         kunmap_atomic(base);
1080         set_page_dirty_lock(page);
1081         put_page(page);
1082         return 0;
1083 }
1084
1085 static int log_write(void __user *log_base,
1086                      u64 write_address, u64 write_length)
1087 {
1088         u64 write_page = write_address / VHOST_PAGE_SIZE;
1089         int r;
1090
1091         if (!write_length)
1092                 return 0;
1093         write_length += write_address % VHOST_PAGE_SIZE;
1094         for (;;) {
1095                 u64 base = (u64)(unsigned long)log_base;
1096                 u64 log = base + write_page / 8;
1097                 int bit = write_page % 8;
1098                 if ((u64)(unsigned long)log != log)
1099                         return -EFAULT;
1100                 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
1101                 if (r < 0)
1102                         return r;
1103                 if (write_length <= VHOST_PAGE_SIZE)
1104                         break;
1105                 write_length -= VHOST_PAGE_SIZE;
1106                 write_page += 1;
1107         }
1108         return r;
1109 }
1110
1111 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
1112                     unsigned int log_num, u64 len)
1113 {
1114         int i, r;
1115
1116         /* Make sure data written is seen before log. */
1117         smp_wmb();
1118         for (i = 0; i < log_num; ++i) {
1119                 u64 l = min(log[i].len, len);
1120                 r = log_write(vq->log_base, log[i].addr, l);
1121                 if (r < 0)
1122                         return r;
1123                 len -= l;
1124                 if (!len) {
1125                         if (vq->log_ctx)
1126                                 eventfd_signal(vq->log_ctx, 1);
1127                         return 0;
1128                 }
1129         }
1130         /* Length written exceeds what we have stored. This is a bug. */
1131         BUG();
1132         return 0;
1133 }
1134 EXPORT_SYMBOL_GPL(vhost_log_write);
1135
1136 static int vhost_update_used_flags(struct vhost_virtqueue *vq)
1137 {
1138         void __user *used;
1139         if (__put_user(cpu_to_vhost16(vq, vq->used_flags), &vq->used->flags) < 0)
1140                 return -EFAULT;
1141         if (unlikely(vq->log_used)) {
1142                 /* Make sure the flag is seen before log. */
1143                 smp_wmb();
1144                 /* Log used flag write. */
1145                 used = &vq->used->flags;
1146                 log_write(vq->log_base, vq->log_addr +
1147                           (used - (void __user *)vq->used),
1148                           sizeof vq->used->flags);
1149                 if (vq->log_ctx)
1150                         eventfd_signal(vq->log_ctx, 1);
1151         }
1152         return 0;
1153 }
1154
1155 static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
1156 {
1157         if (__put_user(cpu_to_vhost16(vq, vq->avail_idx), vhost_avail_event(vq)))
1158                 return -EFAULT;
1159         if (unlikely(vq->log_used)) {
1160                 void __user *used;
1161                 /* Make sure the event is seen before log. */
1162                 smp_wmb();
1163                 /* Log avail event write */
1164                 used = vhost_avail_event(vq);
1165                 log_write(vq->log_base, vq->log_addr +
1166                           (used - (void __user *)vq->used),
1167                           sizeof *vhost_avail_event(vq));
1168                 if (vq->log_ctx)
1169                         eventfd_signal(vq->log_ctx, 1);
1170         }
1171         return 0;
1172 }
1173
1174 int vhost_init_used(struct vhost_virtqueue *vq)
1175 {
1176         __virtio16 last_used_idx;
1177         int r;
1178         if (!vq->private_data) {
1179                 vq->is_le = virtio_legacy_is_little_endian();
1180                 return 0;
1181         }
1182
1183         vhost_init_is_le(vq);
1184
1185         r = vhost_update_used_flags(vq);
1186         if (r)
1187                 return r;
1188         vq->signalled_used_valid = false;
1189         if (!access_ok(VERIFY_READ, &vq->used->idx, sizeof vq->used->idx))
1190                 return -EFAULT;
1191         r = __get_user(last_used_idx, &vq->used->idx);
1192         if (r)
1193                 return r;
1194         vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
1195         return 0;
1196 }
1197 EXPORT_SYMBOL_GPL(vhost_init_used);
1198
1199 static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
1200                           struct iovec iov[], int iov_size)
1201 {
1202         const struct vhost_memory_region *reg;
1203         struct vhost_memory *mem;
1204         struct iovec *_iov;
1205         u64 s = 0;
1206         int ret = 0;
1207
1208         mem = vq->memory;
1209         while ((u64)len > s) {
1210                 u64 size;
1211                 if (unlikely(ret >= iov_size)) {
1212                         ret = -ENOBUFS;
1213                         break;
1214                 }
1215                 reg = find_region(mem, addr, len);
1216                 if (unlikely(!reg)) {
1217                         ret = -EFAULT;
1218                         break;
1219                 }
1220                 _iov = iov + ret;
1221                 size = reg->memory_size - addr + reg->guest_phys_addr;
1222                 _iov->iov_len = min((u64)len - s, size);
1223                 _iov->iov_base = (void __user *)(unsigned long)
1224                         (reg->userspace_addr + addr - reg->guest_phys_addr);
1225                 s += size;
1226                 addr += size;
1227                 ++ret;
1228         }
1229
1230         return ret;
1231 }
1232
1233 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
1234  * function returns the next descriptor in the chain,
1235  * or -1U if we're at the end. */
1236 static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
1237 {
1238         unsigned int next;
1239
1240         /* If this descriptor says it doesn't chain, we're done. */
1241         if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
1242                 return -1U;
1243
1244         /* Check they're not leading us off end of descriptors. */
1245         next = vhost16_to_cpu(vq, desc->next);
1246         /* Make sure compiler knows to grab that: we don't want it changing! */
1247         /* We will use the result as an index in an array, so most
1248          * architectures only need a compiler barrier here. */
1249         read_barrier_depends();
1250
1251         return next;
1252 }
1253
1254 static int get_indirect(struct vhost_virtqueue *vq,
1255                         struct iovec iov[], unsigned int iov_size,
1256                         unsigned int *out_num, unsigned int *in_num,
1257                         struct vhost_log *log, unsigned int *log_num,
1258                         struct vring_desc *indirect)
1259 {
1260         struct vring_desc desc;
1261         unsigned int i = 0, count, found = 0;
1262         u32 len = vhost32_to_cpu(vq, indirect->len);
1263         struct iov_iter from;
1264         int ret;
1265
1266         /* Sanity check */
1267         if (unlikely(len % sizeof desc)) {
1268                 vq_err(vq, "Invalid length in indirect descriptor: "
1269                        "len 0x%llx not multiple of 0x%zx\n",
1270                        (unsigned long long)len,
1271                        sizeof desc);
1272                 return -EINVAL;
1273         }
1274
1275         ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
1276                              UIO_MAXIOV);
1277         if (unlikely(ret < 0)) {
1278                 vq_err(vq, "Translation failure %d in indirect.\n", ret);
1279                 return ret;
1280         }
1281         iov_iter_init(&from, READ, vq->indirect, ret, len);
1282
1283         /* We will use the result as an address to read from, so most
1284          * architectures only need a compiler barrier here. */
1285         read_barrier_depends();
1286
1287         count = len / sizeof desc;
1288         /* Buffers are chained via a 16 bit next field, so
1289          * we can have at most 2^16 of these. */
1290         if (unlikely(count > USHRT_MAX + 1)) {
1291                 vq_err(vq, "Indirect buffer length too big: %d\n",
1292                        indirect->len);
1293                 return -E2BIG;
1294         }
1295
1296         do {
1297                 unsigned iov_count = *in_num + *out_num;
1298                 if (unlikely(++found > count)) {
1299                         vq_err(vq, "Loop detected: last one at %u "
1300                                "indirect size %u\n",
1301                                i, count);
1302                         return -EINVAL;
1303                 }
1304                 if (unlikely(copy_from_iter(&desc, sizeof(desc), &from) !=
1305                              sizeof(desc))) {
1306                         vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
1307                                i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1308                         return -EINVAL;
1309                 }
1310                 if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
1311                         vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
1312                                i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
1313                         return -EINVAL;
1314                 }
1315
1316                 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1317                                      vhost32_to_cpu(vq, desc.len), iov + iov_count,
1318                                      iov_size - iov_count);
1319                 if (unlikely(ret < 0)) {
1320                         vq_err(vq, "Translation failure %d indirect idx %d\n",
1321                                ret, i);
1322                         return ret;
1323                 }
1324                 /* If this is an input descriptor, increment that count. */
1325                 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1326                         *in_num += ret;
1327                         if (unlikely(log && ret)) {
1328                                 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1329                                 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1330                                 ++*log_num;
1331                         }
1332                 } else {
1333                         /* If it's an output descriptor, they're all supposed
1334                          * to come before any input descriptors. */
1335                         if (unlikely(*in_num)) {
1336                                 vq_err(vq, "Indirect descriptor "
1337                                        "has out after in: idx %d\n", i);
1338                                 return -EINVAL;
1339                         }
1340                         *out_num += ret;
1341                 }
1342         } while ((i = next_desc(vq, &desc)) != -1);
1343         return 0;
1344 }
1345
1346 /* This looks in the virtqueue and for the first available buffer, and converts
1347  * it to an iovec for convenient access.  Since descriptors consist of some
1348  * number of output then some number of input descriptors, it's actually two
1349  * iovecs, but we pack them into one and note how many of each there were.
1350  *
1351  * This function returns the descriptor number found, or vq->num (which is
1352  * never a valid descriptor number) if none was found.  A negative code is
1353  * returned on error. */
1354 int vhost_get_vq_desc(struct vhost_virtqueue *vq,
1355                       struct iovec iov[], unsigned int iov_size,
1356                       unsigned int *out_num, unsigned int *in_num,
1357                       struct vhost_log *log, unsigned int *log_num)
1358 {
1359         struct vring_desc desc;
1360         unsigned int i, head, found = 0;
1361         u16 last_avail_idx;
1362         __virtio16 avail_idx;
1363         __virtio16 ring_head;
1364         int ret;
1365
1366         /* Check it isn't doing very strange things with descriptor numbers. */
1367         last_avail_idx = vq->last_avail_idx;
1368         if (unlikely(__get_user(avail_idx, &vq->avail->idx))) {
1369                 vq_err(vq, "Failed to access avail idx at %p\n",
1370                        &vq->avail->idx);
1371                 return -EFAULT;
1372         }
1373         vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
1374
1375         if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1376                 vq_err(vq, "Guest moved used index from %u to %u",
1377                        last_avail_idx, vq->avail_idx);
1378                 return -EFAULT;
1379         }
1380
1381         /* If there's nothing new since last we looked, return invalid. */
1382         if (vq->avail_idx == last_avail_idx)
1383                 return vq->num;
1384
1385         /* Only get avail ring entries after they have been exposed by guest. */
1386         smp_rmb();
1387
1388         /* Grab the next descriptor number they're advertising, and increment
1389          * the index we've seen. */
1390         if (unlikely(__get_user(ring_head,
1391                                 &vq->avail->ring[last_avail_idx & (vq->num - 1)]))) {
1392                 vq_err(vq, "Failed to read head: idx %d address %p\n",
1393                        last_avail_idx,
1394                        &vq->avail->ring[last_avail_idx % vq->num]);
1395                 return -EFAULT;
1396         }
1397
1398         head = vhost16_to_cpu(vq, ring_head);
1399
1400         /* If their number is silly, that's an error. */
1401         if (unlikely(head >= vq->num)) {
1402                 vq_err(vq, "Guest says index %u > %u is available",
1403                        head, vq->num);
1404                 return -EINVAL;
1405         }
1406
1407         /* When we start there are none of either input nor output. */
1408         *out_num = *in_num = 0;
1409         if (unlikely(log))
1410                 *log_num = 0;
1411
1412         i = head;
1413         do {
1414                 unsigned iov_count = *in_num + *out_num;
1415                 if (unlikely(i >= vq->num)) {
1416                         vq_err(vq, "Desc index is %u > %u, head = %u",
1417                                i, vq->num, head);
1418                         return -EINVAL;
1419                 }
1420                 if (unlikely(++found > vq->num)) {
1421                         vq_err(vq, "Loop detected: last one at %u "
1422                                "vq size %u head %u\n",
1423                                i, vq->num, head);
1424                         return -EINVAL;
1425                 }
1426                 ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
1427                 if (unlikely(ret)) {
1428                         vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1429                                i, vq->desc + i);
1430                         return -EFAULT;
1431                 }
1432                 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
1433                         ret = get_indirect(vq, iov, iov_size,
1434                                            out_num, in_num,
1435                                            log, log_num, &desc);
1436                         if (unlikely(ret < 0)) {
1437                                 vq_err(vq, "Failure detected "
1438                                        "in indirect descriptor at idx %d\n", i);
1439                                 return ret;
1440                         }
1441                         continue;
1442                 }
1443
1444                 ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
1445                                      vhost32_to_cpu(vq, desc.len), iov + iov_count,
1446                                      iov_size - iov_count);
1447                 if (unlikely(ret < 0)) {
1448                         vq_err(vq, "Translation failure %d descriptor idx %d\n",
1449                                ret, i);
1450                         return ret;
1451                 }
1452                 if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
1453                         /* If this is an input descriptor,
1454                          * increment that count. */
1455                         *in_num += ret;
1456                         if (unlikely(log && ret)) {
1457                                 log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
1458                                 log[*log_num].len = vhost32_to_cpu(vq, desc.len);
1459                                 ++*log_num;
1460                         }
1461                 } else {
1462                         /* If it's an output descriptor, they're all supposed
1463                          * to come before any input descriptors. */
1464                         if (unlikely(*in_num)) {
1465                                 vq_err(vq, "Descriptor has out after in: "
1466                                        "idx %d\n", i);
1467                                 return -EINVAL;
1468                         }
1469                         *out_num += ret;
1470                 }
1471         } while ((i = next_desc(vq, &desc)) != -1);
1472
1473         /* On success, increment avail index. */
1474         vq->last_avail_idx++;
1475
1476         /* Assume notifications from guest are disabled at this point,
1477          * if they aren't we would need to update avail_event index. */
1478         BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
1479         return head;
1480 }
1481 EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
1482
1483 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1484 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1485 {
1486         vq->last_avail_idx -= n;
1487 }
1488 EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
1489
1490 /* After we've used one of their buffers, we tell them about it.  We'll then
1491  * want to notify the guest, using eventfd. */
1492 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1493 {
1494         struct vring_used_elem heads = {
1495                 cpu_to_vhost32(vq, head),
1496                 cpu_to_vhost32(vq, len)
1497         };
1498
1499         return vhost_add_used_n(vq, &heads, 1);
1500 }
1501 EXPORT_SYMBOL_GPL(vhost_add_used);
1502
1503 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1504                             struct vring_used_elem *heads,
1505                             unsigned count)
1506 {
1507         struct vring_used_elem __user *used;
1508         u16 old, new;
1509         int start;
1510
1511         start = vq->last_used_idx & (vq->num - 1);
1512         used = vq->used->ring + start;
1513         if (count == 1) {
1514                 if (__put_user(heads[0].id, &used->id)) {
1515                         vq_err(vq, "Failed to write used id");
1516                         return -EFAULT;
1517                 }
1518                 if (__put_user(heads[0].len, &used->len)) {
1519                         vq_err(vq, "Failed to write used len");
1520                         return -EFAULT;
1521                 }
1522         } else if (__copy_to_user(used, heads, count * sizeof *used)) {
1523                 vq_err(vq, "Failed to write used");
1524                 return -EFAULT;
1525         }
1526         if (unlikely(vq->log_used)) {
1527                 /* Make sure data is seen before log. */
1528                 smp_wmb();
1529                 /* Log used ring entry write. */
1530                 log_write(vq->log_base,
1531                           vq->log_addr +
1532                            ((void __user *)used - (void __user *)vq->used),
1533                           count * sizeof *used);
1534         }
1535         old = vq->last_used_idx;
1536         new = (vq->last_used_idx += count);
1537         /* If the driver never bothers to signal in a very long while,
1538          * used index might wrap around. If that happens, invalidate
1539          * signalled_used index we stored. TODO: make sure driver
1540          * signals at least once in 2^16 and remove this. */
1541         if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
1542                 vq->signalled_used_valid = false;
1543         return 0;
1544 }
1545
1546 /* After we've used one of their buffers, we tell them about it.  We'll then
1547  * want to notify the guest, using eventfd. */
1548 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1549                      unsigned count)
1550 {
1551         int start, n, r;
1552
1553         start = vq->last_used_idx & (vq->num - 1);
1554         n = vq->num - start;
1555         if (n < count) {
1556                 r = __vhost_add_used_n(vq, heads, n);
1557                 if (r < 0)
1558                         return r;
1559                 heads += n;
1560                 count -= n;
1561         }
1562         r = __vhost_add_used_n(vq, heads, count);
1563
1564         /* Make sure buffer is written before we update index. */
1565         smp_wmb();
1566         if (__put_user(cpu_to_vhost16(vq, vq->last_used_idx), &vq->used->idx)) {
1567                 vq_err(vq, "Failed to increment used idx");
1568                 return -EFAULT;
1569         }
1570         if (unlikely(vq->log_used)) {
1571                 /* Make sure used idx is seen before log. */
1572                 smp_wmb();
1573                 /* Log used index update. */
1574                 log_write(vq->log_base,
1575                           vq->log_addr + offsetof(struct vring_used, idx),
1576                           sizeof vq->used->idx);
1577                 if (vq->log_ctx)
1578                         eventfd_signal(vq->log_ctx, 1);
1579         }
1580         return r;
1581 }
1582 EXPORT_SYMBOL_GPL(vhost_add_used_n);
1583
1584 static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1585 {
1586         __u16 old, new;
1587         __virtio16 event;
1588         bool v;
1589         /* Flush out used index updates. This is paired
1590          * with the barrier that the Guest executes when enabling
1591          * interrupts. */
1592         smp_mb();
1593
1594         if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1595             unlikely(vq->avail_idx == vq->last_avail_idx))
1596                 return true;
1597
1598         if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1599                 __virtio16 flags;
1600                 if (__get_user(flags, &vq->avail->flags)) {
1601                         vq_err(vq, "Failed to get flags");
1602                         return true;
1603                 }
1604                 return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
1605         }
1606         old = vq->signalled_used;
1607         v = vq->signalled_used_valid;
1608         new = vq->signalled_used = vq->last_used_idx;
1609         vq->signalled_used_valid = true;
1610
1611         if (unlikely(!v))
1612                 return true;
1613
1614         if (__get_user(event, vhost_used_event(vq))) {
1615                 vq_err(vq, "Failed to get used event idx");
1616                 return true;
1617         }
1618         return vring_need_event(vhost16_to_cpu(vq, event), new, old);
1619 }
1620
1621 /* This actually signals the guest, using eventfd. */
1622 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1623 {
1624         /* Signal the Guest tell them we used something up. */
1625         if (vq->call_ctx && vhost_notify(dev, vq))
1626                 eventfd_signal(vq->call_ctx, 1);
1627 }
1628 EXPORT_SYMBOL_GPL(vhost_signal);
1629
1630 /* And here's the combo meal deal.  Supersize me! */
1631 void vhost_add_used_and_signal(struct vhost_dev *dev,
1632                                struct vhost_virtqueue *vq,
1633                                unsigned int head, int len)
1634 {
1635         vhost_add_used(vq, head, len);
1636         vhost_signal(dev, vq);
1637 }
1638 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
1639
1640 /* multi-buffer version of vhost_add_used_and_signal */
1641 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1642                                  struct vhost_virtqueue *vq,
1643                                  struct vring_used_elem *heads, unsigned count)
1644 {
1645         vhost_add_used_n(vq, heads, count);
1646         vhost_signal(dev, vq);
1647 }
1648 EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
1649
1650 /* OK, now we need to know about added descriptors. */
1651 bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1652 {
1653         __virtio16 avail_idx;
1654         int r;
1655
1656         if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1657                 return false;
1658         vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1659         if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1660                 r = vhost_update_used_flags(vq);
1661                 if (r) {
1662                         vq_err(vq, "Failed to enable notification at %p: %d\n",
1663                                &vq->used->flags, r);
1664                         return false;
1665                 }
1666         } else {
1667                 r = vhost_update_avail_event(vq, vq->avail_idx);
1668                 if (r) {
1669                         vq_err(vq, "Failed to update avail event index at %p: %d\n",
1670                                vhost_avail_event(vq), r);
1671                         return false;
1672                 }
1673         }
1674         /* They could have slipped one in as we were doing that: make
1675          * sure it's written, then check again. */
1676         smp_mb();
1677         r = __get_user(avail_idx, &vq->avail->idx);
1678         if (r) {
1679                 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1680                        &vq->avail->idx, r);
1681                 return false;
1682         }
1683
1684         return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
1685 }
1686 EXPORT_SYMBOL_GPL(vhost_enable_notify);
1687
1688 /* We don't need to be notified again. */
1689 void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1690 {
1691         int r;
1692
1693         if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1694                 return;
1695         vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1696         if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
1697                 r = vhost_update_used_flags(vq);
1698                 if (r)
1699                         vq_err(vq, "Failed to enable notification at %p: %d\n",
1700                                &vq->used->flags, r);
1701         }
1702 }
1703 EXPORT_SYMBOL_GPL(vhost_disable_notify);
1704
1705 static int __init vhost_init(void)
1706 {
1707         return 0;
1708 }
1709
1710 static void __exit vhost_exit(void)
1711 {
1712 }
1713
1714 module_init(vhost_init);
1715 module_exit(vhost_exit);
1716
1717 MODULE_VERSION("0.0.1");
1718 MODULE_LICENSE("GPL v2");
1719 MODULE_AUTHOR("Michael S. Tsirkin");
1720 MODULE_DESCRIPTION("Host kernel accelerator for virtio");