Merge branch 'core-fixes-for-linus' of git://git.kernel.org/pub/scm/linux/kernel...
[pandora-kernel.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/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/virtio_net.h>
17 #include <linux/mm.h>
18 #include <linux/miscdevice.h>
19 #include <linux/mutex.h>
20 #include <linux/rcupdate.h>
21 #include <linux/poll.h>
22 #include <linux/file.h>
23 #include <linux/highmem.h>
24 #include <linux/slab.h>
25 #include <linux/kthread.h>
26 #include <linux/cgroup.h>
27
28 #include <linux/net.h>
29 #include <linux/if_packet.h>
30 #include <linux/if_arp.h>
31
32 #include <net/sock.h>
33
34 #include "vhost.h"
35
36 enum {
37         VHOST_MEMORY_MAX_NREGIONS = 64,
38         VHOST_MEMORY_F_LOG = 0x1,
39 };
40
41 static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
42                             poll_table *pt)
43 {
44         struct vhost_poll *poll;
45         poll = container_of(pt, struct vhost_poll, table);
46
47         poll->wqh = wqh;
48         add_wait_queue(wqh, &poll->wait);
49 }
50
51 static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
52                              void *key)
53 {
54         struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
55
56         if (!((unsigned long)key & poll->mask))
57                 return 0;
58
59         vhost_poll_queue(poll);
60         return 0;
61 }
62
63 static void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
64 {
65         INIT_LIST_HEAD(&work->node);
66         work->fn = fn;
67         init_waitqueue_head(&work->done);
68         work->flushing = 0;
69         work->queue_seq = work->done_seq = 0;
70 }
71
72 /* Init poll structure */
73 void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
74                      unsigned long mask, struct vhost_dev *dev)
75 {
76         init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
77         init_poll_funcptr(&poll->table, vhost_poll_func);
78         poll->mask = mask;
79         poll->dev = dev;
80
81         vhost_work_init(&poll->work, fn);
82 }
83
84 /* Start polling a file. We add ourselves to file's wait queue. The caller must
85  * keep a reference to a file until after vhost_poll_stop is called. */
86 void vhost_poll_start(struct vhost_poll *poll, struct file *file)
87 {
88         unsigned long mask;
89         mask = file->f_op->poll(file, &poll->table);
90         if (mask)
91                 vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
92 }
93
94 /* Stop polling a file. After this function returns, it becomes safe to drop the
95  * file reference. You must also flush afterwards. */
96 void vhost_poll_stop(struct vhost_poll *poll)
97 {
98         remove_wait_queue(poll->wqh, &poll->wait);
99 }
100
101 static void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
102 {
103         unsigned seq;
104         int left;
105         int flushing;
106
107         spin_lock_irq(&dev->work_lock);
108         seq = work->queue_seq;
109         work->flushing++;
110         spin_unlock_irq(&dev->work_lock);
111         wait_event(work->done, ({
112                    spin_lock_irq(&dev->work_lock);
113                    left = seq - work->done_seq <= 0;
114                    spin_unlock_irq(&dev->work_lock);
115                    left;
116         }));
117         spin_lock_irq(&dev->work_lock);
118         flushing = --work->flushing;
119         spin_unlock_irq(&dev->work_lock);
120         BUG_ON(flushing < 0);
121 }
122
123 /* Flush any work that has been scheduled. When calling this, don't hold any
124  * locks that are also used by the callback. */
125 void vhost_poll_flush(struct vhost_poll *poll)
126 {
127         vhost_work_flush(poll->dev, &poll->work);
128 }
129
130 static inline void vhost_work_queue(struct vhost_dev *dev,
131                                     struct vhost_work *work)
132 {
133         unsigned long flags;
134
135         spin_lock_irqsave(&dev->work_lock, flags);
136         if (list_empty(&work->node)) {
137                 list_add_tail(&work->node, &dev->work_list);
138                 work->queue_seq++;
139                 wake_up_process(dev->worker);
140         }
141         spin_unlock_irqrestore(&dev->work_lock, flags);
142 }
143
144 void vhost_poll_queue(struct vhost_poll *poll)
145 {
146         vhost_work_queue(poll->dev, &poll->work);
147 }
148
149 static void vhost_vq_reset(struct vhost_dev *dev,
150                            struct vhost_virtqueue *vq)
151 {
152         vq->num = 1;
153         vq->desc = NULL;
154         vq->avail = NULL;
155         vq->used = NULL;
156         vq->last_avail_idx = 0;
157         vq->avail_idx = 0;
158         vq->last_used_idx = 0;
159         vq->used_flags = 0;
160         vq->used_flags = 0;
161         vq->log_used = false;
162         vq->log_addr = -1ull;
163         vq->vhost_hlen = 0;
164         vq->sock_hlen = 0;
165         vq->private_data = NULL;
166         vq->log_base = NULL;
167         vq->error_ctx = NULL;
168         vq->error = NULL;
169         vq->kick = NULL;
170         vq->call_ctx = NULL;
171         vq->call = NULL;
172         vq->log_ctx = NULL;
173 }
174
175 static int vhost_worker(void *data)
176 {
177         struct vhost_dev *dev = data;
178         struct vhost_work *work = NULL;
179         unsigned uninitialized_var(seq);
180
181         for (;;) {
182                 /* mb paired w/ kthread_stop */
183                 set_current_state(TASK_INTERRUPTIBLE);
184
185                 spin_lock_irq(&dev->work_lock);
186                 if (work) {
187                         work->done_seq = seq;
188                         if (work->flushing)
189                                 wake_up_all(&work->done);
190                 }
191
192                 if (kthread_should_stop()) {
193                         spin_unlock_irq(&dev->work_lock);
194                         __set_current_state(TASK_RUNNING);
195                         return 0;
196                 }
197                 if (!list_empty(&dev->work_list)) {
198                         work = list_first_entry(&dev->work_list,
199                                                 struct vhost_work, node);
200                         list_del_init(&work->node);
201                         seq = work->queue_seq;
202                 } else
203                         work = NULL;
204                 spin_unlock_irq(&dev->work_lock);
205
206                 if (work) {
207                         __set_current_state(TASK_RUNNING);
208                         work->fn(work);
209                 } else
210                         schedule();
211
212         }
213 }
214
215 long vhost_dev_init(struct vhost_dev *dev,
216                     struct vhost_virtqueue *vqs, int nvqs)
217 {
218         int i;
219
220         dev->vqs = vqs;
221         dev->nvqs = nvqs;
222         mutex_init(&dev->mutex);
223         dev->log_ctx = NULL;
224         dev->log_file = NULL;
225         dev->memory = NULL;
226         dev->mm = NULL;
227         spin_lock_init(&dev->work_lock);
228         INIT_LIST_HEAD(&dev->work_list);
229         dev->worker = NULL;
230
231         for (i = 0; i < dev->nvqs; ++i) {
232                 dev->vqs[i].dev = dev;
233                 mutex_init(&dev->vqs[i].mutex);
234                 vhost_vq_reset(dev, dev->vqs + i);
235                 if (dev->vqs[i].handle_kick)
236                         vhost_poll_init(&dev->vqs[i].poll,
237                                         dev->vqs[i].handle_kick, POLLIN, dev);
238         }
239
240         return 0;
241 }
242
243 /* Caller should have device mutex */
244 long vhost_dev_check_owner(struct vhost_dev *dev)
245 {
246         /* Are you the owner? If not, I don't think you mean to do that */
247         return dev->mm == current->mm ? 0 : -EPERM;
248 }
249
250 struct vhost_attach_cgroups_struct {
251         struct vhost_work work;
252         struct task_struct *owner;
253         int ret;
254 };
255
256 static void vhost_attach_cgroups_work(struct vhost_work *work)
257 {
258         struct vhost_attach_cgroups_struct *s;
259         s = container_of(work, struct vhost_attach_cgroups_struct, work);
260         s->ret = cgroup_attach_task_all(s->owner, current);
261 }
262
263 static int vhost_attach_cgroups(struct vhost_dev *dev)
264 {
265         struct vhost_attach_cgroups_struct attach;
266         attach.owner = current;
267         vhost_work_init(&attach.work, vhost_attach_cgroups_work);
268         vhost_work_queue(dev, &attach.work);
269         vhost_work_flush(dev, &attach.work);
270         return attach.ret;
271 }
272
273 /* Caller should have device mutex */
274 static long vhost_dev_set_owner(struct vhost_dev *dev)
275 {
276         struct task_struct *worker;
277         int err;
278         /* Is there an owner already? */
279         if (dev->mm) {
280                 err = -EBUSY;
281                 goto err_mm;
282         }
283         /* No owner, become one */
284         dev->mm = get_task_mm(current);
285         worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
286         if (IS_ERR(worker)) {
287                 err = PTR_ERR(worker);
288                 goto err_worker;
289         }
290
291         dev->worker = worker;
292         wake_up_process(worker);        /* avoid contributing to loadavg */
293
294         err = vhost_attach_cgroups(dev);
295         if (err)
296                 goto err_cgroup;
297
298         return 0;
299 err_cgroup:
300         kthread_stop(worker);
301         dev->worker = NULL;
302 err_worker:
303         if (dev->mm)
304                 mmput(dev->mm);
305         dev->mm = NULL;
306 err_mm:
307         return err;
308 }
309
310 /* Caller should have device mutex */
311 long vhost_dev_reset_owner(struct vhost_dev *dev)
312 {
313         struct vhost_memory *memory;
314
315         /* Restore memory to default empty mapping. */
316         memory = kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
317         if (!memory)
318                 return -ENOMEM;
319
320         vhost_dev_cleanup(dev);
321
322         memory->nregions = 0;
323         RCU_INIT_POINTER(dev->memory, memory);
324         return 0;
325 }
326
327 /* Caller should have device mutex */
328 void vhost_dev_cleanup(struct vhost_dev *dev)
329 {
330         int i;
331         for (i = 0; i < dev->nvqs; ++i) {
332                 if (dev->vqs[i].kick && dev->vqs[i].handle_kick) {
333                         vhost_poll_stop(&dev->vqs[i].poll);
334                         vhost_poll_flush(&dev->vqs[i].poll);
335                 }
336                 if (dev->vqs[i].error_ctx)
337                         eventfd_ctx_put(dev->vqs[i].error_ctx);
338                 if (dev->vqs[i].error)
339                         fput(dev->vqs[i].error);
340                 if (dev->vqs[i].kick)
341                         fput(dev->vqs[i].kick);
342                 if (dev->vqs[i].call_ctx)
343                         eventfd_ctx_put(dev->vqs[i].call_ctx);
344                 if (dev->vqs[i].call)
345                         fput(dev->vqs[i].call);
346                 vhost_vq_reset(dev, dev->vqs + i);
347         }
348         if (dev->log_ctx)
349                 eventfd_ctx_put(dev->log_ctx);
350         dev->log_ctx = NULL;
351         if (dev->log_file)
352                 fput(dev->log_file);
353         dev->log_file = NULL;
354         /* No one will access memory at this point */
355         kfree(rcu_dereference_protected(dev->memory,
356                                         lockdep_is_held(&dev->mutex)));
357         RCU_INIT_POINTER(dev->memory, NULL);
358         if (dev->mm)
359                 mmput(dev->mm);
360         dev->mm = NULL;
361
362         WARN_ON(!list_empty(&dev->work_list));
363         if (dev->worker) {
364                 kthread_stop(dev->worker);
365                 dev->worker = NULL;
366         }
367 }
368
369 static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
370 {
371         u64 a = addr / VHOST_PAGE_SIZE / 8;
372         /* Make sure 64 bit math will not overflow. */
373         if (a > ULONG_MAX - (unsigned long)log_base ||
374             a + (unsigned long)log_base > ULONG_MAX)
375                 return -EFAULT;
376
377         return access_ok(VERIFY_WRITE, log_base + a,
378                          (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
379 }
380
381 /* Caller should have vq mutex and device mutex. */
382 static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
383                                int log_all)
384 {
385         int i;
386
387         if (!mem)
388                 return 0;
389
390         for (i = 0; i < mem->nregions; ++i) {
391                 struct vhost_memory_region *m = mem->regions + i;
392                 unsigned long a = m->userspace_addr;
393                 if (m->memory_size > ULONG_MAX)
394                         return 0;
395                 else if (!access_ok(VERIFY_WRITE, (void __user *)a,
396                                     m->memory_size))
397                         return 0;
398                 else if (log_all && !log_access_ok(log_base,
399                                                    m->guest_phys_addr,
400                                                    m->memory_size))
401                         return 0;
402         }
403         return 1;
404 }
405
406 /* Can we switch to this memory table? */
407 /* Caller should have device mutex but not vq mutex */
408 static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
409                             int log_all)
410 {
411         int i;
412         for (i = 0; i < d->nvqs; ++i) {
413                 int ok;
414                 mutex_lock(&d->vqs[i].mutex);
415                 /* If ring is inactive, will check when it's enabled. */
416                 if (d->vqs[i].private_data)
417                         ok = vq_memory_access_ok(d->vqs[i].log_base, mem,
418                                                  log_all);
419                 else
420                         ok = 1;
421                 mutex_unlock(&d->vqs[i].mutex);
422                 if (!ok)
423                         return 0;
424         }
425         return 1;
426 }
427
428 static int vq_access_ok(unsigned int num,
429                         struct vring_desc __user *desc,
430                         struct vring_avail __user *avail,
431                         struct vring_used __user *used)
432 {
433         return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
434                access_ok(VERIFY_READ, avail,
435                          sizeof *avail + num * sizeof *avail->ring) &&
436                access_ok(VERIFY_WRITE, used,
437                         sizeof *used + num * sizeof *used->ring);
438 }
439
440 /* Can we log writes? */
441 /* Caller should have device mutex but not vq mutex */
442 int vhost_log_access_ok(struct vhost_dev *dev)
443 {
444         struct vhost_memory *mp;
445
446         mp = rcu_dereference_protected(dev->memory,
447                                        lockdep_is_held(&dev->mutex));
448         return memory_access_ok(dev, mp, 1);
449 }
450
451 /* Verify access for write logging. */
452 /* Caller should have vq mutex and device mutex */
453 static int vq_log_access_ok(struct vhost_virtqueue *vq, void __user *log_base)
454 {
455         struct vhost_memory *mp;
456
457         mp = rcu_dereference_protected(vq->dev->memory,
458                                        lockdep_is_held(&vq->mutex));
459         return vq_memory_access_ok(log_base, mp,
460                             vhost_has_feature(vq->dev, VHOST_F_LOG_ALL)) &&
461                 (!vq->log_used || log_access_ok(log_base, vq->log_addr,
462                                         sizeof *vq->used +
463                                         vq->num * sizeof *vq->used->ring));
464 }
465
466 /* Can we start vq? */
467 /* Caller should have vq mutex and device mutex */
468 int vhost_vq_access_ok(struct vhost_virtqueue *vq)
469 {
470         return vq_access_ok(vq->num, vq->desc, vq->avail, vq->used) &&
471                 vq_log_access_ok(vq, vq->log_base);
472 }
473
474 static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
475 {
476         struct vhost_memory mem, *newmem, *oldmem;
477         unsigned long size = offsetof(struct vhost_memory, regions);
478         if (copy_from_user(&mem, m, size))
479                 return -EFAULT;
480         if (mem.padding)
481                 return -EOPNOTSUPP;
482         if (mem.nregions > VHOST_MEMORY_MAX_NREGIONS)
483                 return -E2BIG;
484         newmem = kmalloc(size + mem.nregions * sizeof *m->regions, GFP_KERNEL);
485         if (!newmem)
486                 return -ENOMEM;
487
488         memcpy(newmem, &mem, size);
489         if (copy_from_user(newmem->regions, m->regions,
490                            mem.nregions * sizeof *m->regions)) {
491                 kfree(newmem);
492                 return -EFAULT;
493         }
494
495         if (!memory_access_ok(d, newmem, vhost_has_feature(d, VHOST_F_LOG_ALL))) {
496                 kfree(newmem);
497                 return -EFAULT;
498         }
499         oldmem = rcu_dereference_protected(d->memory,
500                                            lockdep_is_held(&d->mutex));
501         rcu_assign_pointer(d->memory, newmem);
502         synchronize_rcu();
503         kfree(oldmem);
504         return 0;
505 }
506
507 static int init_used(struct vhost_virtqueue *vq,
508                      struct vring_used __user *used)
509 {
510         int r = put_user(vq->used_flags, &used->flags);
511         if (r)
512                 return r;
513         return get_user(vq->last_used_idx, &used->idx);
514 }
515
516 static long vhost_set_vring(struct vhost_dev *d, int ioctl, void __user *argp)
517 {
518         struct file *eventfp, *filep = NULL,
519                     *pollstart = NULL, *pollstop = NULL;
520         struct eventfd_ctx *ctx = NULL;
521         u32 __user *idxp = argp;
522         struct vhost_virtqueue *vq;
523         struct vhost_vring_state s;
524         struct vhost_vring_file f;
525         struct vhost_vring_addr a;
526         u32 idx;
527         long r;
528
529         r = get_user(idx, idxp);
530         if (r < 0)
531                 return r;
532         if (idx >= d->nvqs)
533                 return -ENOBUFS;
534
535         vq = d->vqs + idx;
536
537         mutex_lock(&vq->mutex);
538
539         switch (ioctl) {
540         case VHOST_SET_VRING_NUM:
541                 /* Resizing ring with an active backend?
542                  * You don't want to do that. */
543                 if (vq->private_data) {
544                         r = -EBUSY;
545                         break;
546                 }
547                 if (copy_from_user(&s, argp, sizeof s)) {
548                         r = -EFAULT;
549                         break;
550                 }
551                 if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
552                         r = -EINVAL;
553                         break;
554                 }
555                 vq->num = s.num;
556                 break;
557         case VHOST_SET_VRING_BASE:
558                 /* Moving base with an active backend?
559                  * You don't want to do that. */
560                 if (vq->private_data) {
561                         r = -EBUSY;
562                         break;
563                 }
564                 if (copy_from_user(&s, argp, sizeof s)) {
565                         r = -EFAULT;
566                         break;
567                 }
568                 if (s.num > 0xffff) {
569                         r = -EINVAL;
570                         break;
571                 }
572                 vq->last_avail_idx = s.num;
573                 /* Forget the cached index value. */
574                 vq->avail_idx = vq->last_avail_idx;
575                 break;
576         case VHOST_GET_VRING_BASE:
577                 s.index = idx;
578                 s.num = vq->last_avail_idx;
579                 if (copy_to_user(argp, &s, sizeof s))
580                         r = -EFAULT;
581                 break;
582         case VHOST_SET_VRING_ADDR:
583                 if (copy_from_user(&a, argp, sizeof a)) {
584                         r = -EFAULT;
585                         break;
586                 }
587                 if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
588                         r = -EOPNOTSUPP;
589                         break;
590                 }
591                 /* For 32bit, verify that the top 32bits of the user
592                    data are set to zero. */
593                 if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
594                     (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
595                     (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
596                         r = -EFAULT;
597                         break;
598                 }
599                 if ((a.avail_user_addr & (sizeof *vq->avail->ring - 1)) ||
600                     (a.used_user_addr & (sizeof *vq->used->ring - 1)) ||
601                     (a.log_guest_addr & (sizeof *vq->used->ring - 1))) {
602                         r = -EINVAL;
603                         break;
604                 }
605
606                 /* We only verify access here if backend is configured.
607                  * If it is not, we don't as size might not have been setup.
608                  * We will verify when backend is configured. */
609                 if (vq->private_data) {
610                         if (!vq_access_ok(vq->num,
611                                 (void __user *)(unsigned long)a.desc_user_addr,
612                                 (void __user *)(unsigned long)a.avail_user_addr,
613                                 (void __user *)(unsigned long)a.used_user_addr)) {
614                                 r = -EINVAL;
615                                 break;
616                         }
617
618                         /* Also validate log access for used ring if enabled. */
619                         if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
620                             !log_access_ok(vq->log_base, a.log_guest_addr,
621                                            sizeof *vq->used +
622                                            vq->num * sizeof *vq->used->ring)) {
623                                 r = -EINVAL;
624                                 break;
625                         }
626                 }
627
628                 r = init_used(vq, (struct vring_used __user *)(unsigned long)
629                               a.used_user_addr);
630                 if (r)
631                         break;
632                 vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
633                 vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
634                 vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
635                 vq->log_addr = a.log_guest_addr;
636                 vq->used = (void __user *)(unsigned long)a.used_user_addr;
637                 break;
638         case VHOST_SET_VRING_KICK:
639                 if (copy_from_user(&f, argp, sizeof f)) {
640                         r = -EFAULT;
641                         break;
642                 }
643                 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
644                 if (IS_ERR(eventfp)) {
645                         r = PTR_ERR(eventfp);
646                         break;
647                 }
648                 if (eventfp != vq->kick) {
649                         pollstop = filep = vq->kick;
650                         pollstart = vq->kick = eventfp;
651                 } else
652                         filep = eventfp;
653                 break;
654         case VHOST_SET_VRING_CALL:
655                 if (copy_from_user(&f, argp, sizeof f)) {
656                         r = -EFAULT;
657                         break;
658                 }
659                 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
660                 if (IS_ERR(eventfp)) {
661                         r = PTR_ERR(eventfp);
662                         break;
663                 }
664                 if (eventfp != vq->call) {
665                         filep = vq->call;
666                         ctx = vq->call_ctx;
667                         vq->call = eventfp;
668                         vq->call_ctx = eventfp ?
669                                 eventfd_ctx_fileget(eventfp) : NULL;
670                 } else
671                         filep = eventfp;
672                 break;
673         case VHOST_SET_VRING_ERR:
674                 if (copy_from_user(&f, argp, sizeof f)) {
675                         r = -EFAULT;
676                         break;
677                 }
678                 eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
679                 if (IS_ERR(eventfp)) {
680                         r = PTR_ERR(eventfp);
681                         break;
682                 }
683                 if (eventfp != vq->error) {
684                         filep = vq->error;
685                         vq->error = eventfp;
686                         ctx = vq->error_ctx;
687                         vq->error_ctx = eventfp ?
688                                 eventfd_ctx_fileget(eventfp) : NULL;
689                 } else
690                         filep = eventfp;
691                 break;
692         default:
693                 r = -ENOIOCTLCMD;
694         }
695
696         if (pollstop && vq->handle_kick)
697                 vhost_poll_stop(&vq->poll);
698
699         if (ctx)
700                 eventfd_ctx_put(ctx);
701         if (filep)
702                 fput(filep);
703
704         if (pollstart && vq->handle_kick)
705                 vhost_poll_start(&vq->poll, vq->kick);
706
707         mutex_unlock(&vq->mutex);
708
709         if (pollstop && vq->handle_kick)
710                 vhost_poll_flush(&vq->poll);
711         return r;
712 }
713
714 /* Caller must have device mutex */
715 long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, unsigned long arg)
716 {
717         void __user *argp = (void __user *)arg;
718         struct file *eventfp, *filep = NULL;
719         struct eventfd_ctx *ctx = NULL;
720         u64 p;
721         long r;
722         int i, fd;
723
724         /* If you are not the owner, you can become one */
725         if (ioctl == VHOST_SET_OWNER) {
726                 r = vhost_dev_set_owner(d);
727                 goto done;
728         }
729
730         /* You must be the owner to do anything else */
731         r = vhost_dev_check_owner(d);
732         if (r)
733                 goto done;
734
735         switch (ioctl) {
736         case VHOST_SET_MEM_TABLE:
737                 r = vhost_set_memory(d, argp);
738                 break;
739         case VHOST_SET_LOG_BASE:
740                 if (copy_from_user(&p, argp, sizeof p)) {
741                         r = -EFAULT;
742                         break;
743                 }
744                 if ((u64)(unsigned long)p != p) {
745                         r = -EFAULT;
746                         break;
747                 }
748                 for (i = 0; i < d->nvqs; ++i) {
749                         struct vhost_virtqueue *vq;
750                         void __user *base = (void __user *)(unsigned long)p;
751                         vq = d->vqs + i;
752                         mutex_lock(&vq->mutex);
753                         /* If ring is inactive, will check when it's enabled. */
754                         if (vq->private_data && !vq_log_access_ok(vq, base))
755                                 r = -EFAULT;
756                         else
757                                 vq->log_base = base;
758                         mutex_unlock(&vq->mutex);
759                 }
760                 break;
761         case VHOST_SET_LOG_FD:
762                 r = get_user(fd, (int __user *)argp);
763                 if (r < 0)
764                         break;
765                 eventfp = fd == -1 ? NULL : eventfd_fget(fd);
766                 if (IS_ERR(eventfp)) {
767                         r = PTR_ERR(eventfp);
768                         break;
769                 }
770                 if (eventfp != d->log_file) {
771                         filep = d->log_file;
772                         ctx = d->log_ctx;
773                         d->log_ctx = eventfp ?
774                                 eventfd_ctx_fileget(eventfp) : NULL;
775                 } else
776                         filep = eventfp;
777                 for (i = 0; i < d->nvqs; ++i) {
778                         mutex_lock(&d->vqs[i].mutex);
779                         d->vqs[i].log_ctx = d->log_ctx;
780                         mutex_unlock(&d->vqs[i].mutex);
781                 }
782                 if (ctx)
783                         eventfd_ctx_put(ctx);
784                 if (filep)
785                         fput(filep);
786                 break;
787         default:
788                 r = vhost_set_vring(d, ioctl, argp);
789                 break;
790         }
791 done:
792         return r;
793 }
794
795 static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
796                                                      __u64 addr, __u32 len)
797 {
798         struct vhost_memory_region *reg;
799         int i;
800         /* linear search is not brilliant, but we really have on the order of 6
801          * regions in practice */
802         for (i = 0; i < mem->nregions; ++i) {
803                 reg = mem->regions + i;
804                 if (reg->guest_phys_addr <= addr &&
805                     reg->guest_phys_addr + reg->memory_size - 1 >= addr)
806                         return reg;
807         }
808         return NULL;
809 }
810
811 /* TODO: This is really inefficient.  We need something like get_user()
812  * (instruction directly accesses the data, with an exception table entry
813  * returning -EFAULT). See Documentation/x86/exception-tables.txt.
814  */
815 static int set_bit_to_user(int nr, void __user *addr)
816 {
817         unsigned long log = (unsigned long)addr;
818         struct page *page;
819         void *base;
820         int bit = nr + (log % PAGE_SIZE) * 8;
821         int r;
822         r = get_user_pages_fast(log, 1, 1, &page);
823         if (r < 0)
824                 return r;
825         BUG_ON(r != 1);
826         base = kmap_atomic(page, KM_USER0);
827         set_bit(bit, base);
828         kunmap_atomic(base, KM_USER0);
829         set_page_dirty_lock(page);
830         put_page(page);
831         return 0;
832 }
833
834 static int log_write(void __user *log_base,
835                      u64 write_address, u64 write_length)
836 {
837         int r;
838         if (!write_length)
839                 return 0;
840         write_address /= VHOST_PAGE_SIZE;
841         for (;;) {
842                 u64 base = (u64)(unsigned long)log_base;
843                 u64 log = base + write_address / 8;
844                 int bit = write_address % 8;
845                 if ((u64)(unsigned long)log != log)
846                         return -EFAULT;
847                 r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
848                 if (r < 0)
849                         return r;
850                 if (write_length <= VHOST_PAGE_SIZE)
851                         break;
852                 write_length -= VHOST_PAGE_SIZE;
853                 write_address += VHOST_PAGE_SIZE;
854         }
855         return r;
856 }
857
858 int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
859                     unsigned int log_num, u64 len)
860 {
861         int i, r;
862
863         /* Make sure data written is seen before log. */
864         smp_wmb();
865         for (i = 0; i < log_num; ++i) {
866                 u64 l = min(log[i].len, len);
867                 r = log_write(vq->log_base, log[i].addr, l);
868                 if (r < 0)
869                         return r;
870                 len -= l;
871                 if (!len) {
872                         if (vq->log_ctx)
873                                 eventfd_signal(vq->log_ctx, 1);
874                         return 0;
875                 }
876         }
877         /* Length written exceeds what we have stored. This is a bug. */
878         BUG();
879         return 0;
880 }
881
882 static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len,
883                           struct iovec iov[], int iov_size)
884 {
885         const struct vhost_memory_region *reg;
886         struct vhost_memory *mem;
887         struct iovec *_iov;
888         u64 s = 0;
889         int ret = 0;
890
891         rcu_read_lock();
892
893         mem = rcu_dereference(dev->memory);
894         while ((u64)len > s) {
895                 u64 size;
896                 if (unlikely(ret >= iov_size)) {
897                         ret = -ENOBUFS;
898                         break;
899                 }
900                 reg = find_region(mem, addr, len);
901                 if (unlikely(!reg)) {
902                         ret = -EFAULT;
903                         break;
904                 }
905                 _iov = iov + ret;
906                 size = reg->memory_size - addr + reg->guest_phys_addr;
907                 _iov->iov_len = min((u64)len, size);
908                 _iov->iov_base = (void __user *)(unsigned long)
909                         (reg->userspace_addr + addr - reg->guest_phys_addr);
910                 s += size;
911                 addr += size;
912                 ++ret;
913         }
914
915         rcu_read_unlock();
916         return ret;
917 }
918
919 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
920  * function returns the next descriptor in the chain,
921  * or -1U if we're at the end. */
922 static unsigned next_desc(struct vring_desc *desc)
923 {
924         unsigned int next;
925
926         /* If this descriptor says it doesn't chain, we're done. */
927         if (!(desc->flags & VRING_DESC_F_NEXT))
928                 return -1U;
929
930         /* Check they're not leading us off end of descriptors. */
931         next = desc->next;
932         /* Make sure compiler knows to grab that: we don't want it changing! */
933         /* We will use the result as an index in an array, so most
934          * architectures only need a compiler barrier here. */
935         read_barrier_depends();
936
937         return next;
938 }
939
940 static int get_indirect(struct vhost_dev *dev, struct vhost_virtqueue *vq,
941                         struct iovec iov[], unsigned int iov_size,
942                         unsigned int *out_num, unsigned int *in_num,
943                         struct vhost_log *log, unsigned int *log_num,
944                         struct vring_desc *indirect)
945 {
946         struct vring_desc desc;
947         unsigned int i = 0, count, found = 0;
948         int ret;
949
950         /* Sanity check */
951         if (unlikely(indirect->len % sizeof desc)) {
952                 vq_err(vq, "Invalid length in indirect descriptor: "
953                        "len 0x%llx not multiple of 0x%zx\n",
954                        (unsigned long long)indirect->len,
955                        sizeof desc);
956                 return -EINVAL;
957         }
958
959         ret = translate_desc(dev, indirect->addr, indirect->len, vq->indirect,
960                              ARRAY_SIZE(vq->indirect));
961         if (unlikely(ret < 0)) {
962                 vq_err(vq, "Translation failure %d in indirect.\n", ret);
963                 return ret;
964         }
965
966         /* We will use the result as an address to read from, so most
967          * architectures only need a compiler barrier here. */
968         read_barrier_depends();
969
970         count = indirect->len / sizeof desc;
971         /* Buffers are chained via a 16 bit next field, so
972          * we can have at most 2^16 of these. */
973         if (unlikely(count > USHRT_MAX + 1)) {
974                 vq_err(vq, "Indirect buffer length too big: %d\n",
975                        indirect->len);
976                 return -E2BIG;
977         }
978
979         do {
980                 unsigned iov_count = *in_num + *out_num;
981                 if (unlikely(++found > count)) {
982                         vq_err(vq, "Loop detected: last one at %u "
983                                "indirect size %u\n",
984                                i, count);
985                         return -EINVAL;
986                 }
987                 if (unlikely(memcpy_fromiovec((unsigned char *)&desc, vq->indirect,
988                                               sizeof desc))) {
989                         vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
990                                i, (size_t)indirect->addr + i * sizeof desc);
991                         return -EINVAL;
992                 }
993                 if (unlikely(desc.flags & VRING_DESC_F_INDIRECT)) {
994                         vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
995                                i, (size_t)indirect->addr + i * sizeof desc);
996                         return -EINVAL;
997                 }
998
999                 ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
1000                                      iov_size - iov_count);
1001                 if (unlikely(ret < 0)) {
1002                         vq_err(vq, "Translation failure %d indirect idx %d\n",
1003                                ret, i);
1004                         return ret;
1005                 }
1006                 /* If this is an input descriptor, increment that count. */
1007                 if (desc.flags & VRING_DESC_F_WRITE) {
1008                         *in_num += ret;
1009                         if (unlikely(log)) {
1010                                 log[*log_num].addr = desc.addr;
1011                                 log[*log_num].len = desc.len;
1012                                 ++*log_num;
1013                         }
1014                 } else {
1015                         /* If it's an output descriptor, they're all supposed
1016                          * to come before any input descriptors. */
1017                         if (unlikely(*in_num)) {
1018                                 vq_err(vq, "Indirect descriptor "
1019                                        "has out after in: idx %d\n", i);
1020                                 return -EINVAL;
1021                         }
1022                         *out_num += ret;
1023                 }
1024         } while ((i = next_desc(&desc)) != -1);
1025         return 0;
1026 }
1027
1028 /* This looks in the virtqueue and for the first available buffer, and converts
1029  * it to an iovec for convenient access.  Since descriptors consist of some
1030  * number of output then some number of input descriptors, it's actually two
1031  * iovecs, but we pack them into one and note how many of each there were.
1032  *
1033  * This function returns the descriptor number found, or vq->num (which is
1034  * never a valid descriptor number) if none was found.  A negative code is
1035  * returned on error. */
1036 int vhost_get_vq_desc(struct vhost_dev *dev, struct vhost_virtqueue *vq,
1037                       struct iovec iov[], unsigned int iov_size,
1038                       unsigned int *out_num, unsigned int *in_num,
1039                       struct vhost_log *log, unsigned int *log_num)
1040 {
1041         struct vring_desc desc;
1042         unsigned int i, head, found = 0;
1043         u16 last_avail_idx;
1044         int ret;
1045
1046         /* Check it isn't doing very strange things with descriptor numbers. */
1047         last_avail_idx = vq->last_avail_idx;
1048         if (unlikely(get_user(vq->avail_idx, &vq->avail->idx))) {
1049                 vq_err(vq, "Failed to access avail idx at %p\n",
1050                        &vq->avail->idx);
1051                 return -EFAULT;
1052         }
1053
1054         if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
1055                 vq_err(vq, "Guest moved used index from %u to %u",
1056                        last_avail_idx, vq->avail_idx);
1057                 return -EFAULT;
1058         }
1059
1060         /* If there's nothing new since last we looked, return invalid. */
1061         if (vq->avail_idx == last_avail_idx)
1062                 return vq->num;
1063
1064         /* Only get avail ring entries after they have been exposed by guest. */
1065         smp_rmb();
1066
1067         /* Grab the next descriptor number they're advertising, and increment
1068          * the index we've seen. */
1069         if (unlikely(get_user(head,
1070                               &vq->avail->ring[last_avail_idx % vq->num]))) {
1071                 vq_err(vq, "Failed to read head: idx %d address %p\n",
1072                        last_avail_idx,
1073                        &vq->avail->ring[last_avail_idx % vq->num]);
1074                 return -EFAULT;
1075         }
1076
1077         /* If their number is silly, that's an error. */
1078         if (unlikely(head >= vq->num)) {
1079                 vq_err(vq, "Guest says index %u > %u is available",
1080                        head, vq->num);
1081                 return -EINVAL;
1082         }
1083
1084         /* When we start there are none of either input nor output. */
1085         *out_num = *in_num = 0;
1086         if (unlikely(log))
1087                 *log_num = 0;
1088
1089         i = head;
1090         do {
1091                 unsigned iov_count = *in_num + *out_num;
1092                 if (unlikely(i >= vq->num)) {
1093                         vq_err(vq, "Desc index is %u > %u, head = %u",
1094                                i, vq->num, head);
1095                         return -EINVAL;
1096                 }
1097                 if (unlikely(++found > vq->num)) {
1098                         vq_err(vq, "Loop detected: last one at %u "
1099                                "vq size %u head %u\n",
1100                                i, vq->num, head);
1101                         return -EINVAL;
1102                 }
1103                 ret = copy_from_user(&desc, vq->desc + i, sizeof desc);
1104                 if (unlikely(ret)) {
1105                         vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
1106                                i, vq->desc + i);
1107                         return -EFAULT;
1108                 }
1109                 if (desc.flags & VRING_DESC_F_INDIRECT) {
1110                         ret = get_indirect(dev, vq, iov, iov_size,
1111                                            out_num, in_num,
1112                                            log, log_num, &desc);
1113                         if (unlikely(ret < 0)) {
1114                                 vq_err(vq, "Failure detected "
1115                                        "in indirect descriptor at idx %d\n", i);
1116                                 return ret;
1117                         }
1118                         continue;
1119                 }
1120
1121                 ret = translate_desc(dev, desc.addr, desc.len, iov + iov_count,
1122                                      iov_size - iov_count);
1123                 if (unlikely(ret < 0)) {
1124                         vq_err(vq, "Translation failure %d descriptor idx %d\n",
1125                                ret, i);
1126                         return ret;
1127                 }
1128                 if (desc.flags & VRING_DESC_F_WRITE) {
1129                         /* If this is an input descriptor,
1130                          * increment that count. */
1131                         *in_num += ret;
1132                         if (unlikely(log)) {
1133                                 log[*log_num].addr = desc.addr;
1134                                 log[*log_num].len = desc.len;
1135                                 ++*log_num;
1136                         }
1137                 } else {
1138                         /* If it's an output descriptor, they're all supposed
1139                          * to come before any input descriptors. */
1140                         if (unlikely(*in_num)) {
1141                                 vq_err(vq, "Descriptor has out after in: "
1142                                        "idx %d\n", i);
1143                                 return -EINVAL;
1144                         }
1145                         *out_num += ret;
1146                 }
1147         } while ((i = next_desc(&desc)) != -1);
1148
1149         /* On success, increment avail index. */
1150         vq->last_avail_idx++;
1151         return head;
1152 }
1153
1154 /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
1155 void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
1156 {
1157         vq->last_avail_idx -= n;
1158 }
1159
1160 /* After we've used one of their buffers, we tell them about it.  We'll then
1161  * want to notify the guest, using eventfd. */
1162 int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
1163 {
1164         struct vring_used_elem __user *used;
1165
1166         /* The virtqueue contains a ring of used buffers.  Get a pointer to the
1167          * next entry in that used ring. */
1168         used = &vq->used->ring[vq->last_used_idx % vq->num];
1169         if (put_user(head, &used->id)) {
1170                 vq_err(vq, "Failed to write used id");
1171                 return -EFAULT;
1172         }
1173         if (put_user(len, &used->len)) {
1174                 vq_err(vq, "Failed to write used len");
1175                 return -EFAULT;
1176         }
1177         /* Make sure buffer is written before we update index. */
1178         smp_wmb();
1179         if (put_user(vq->last_used_idx + 1, &vq->used->idx)) {
1180                 vq_err(vq, "Failed to increment used idx");
1181                 return -EFAULT;
1182         }
1183         if (unlikely(vq->log_used)) {
1184                 /* Make sure data is seen before log. */
1185                 smp_wmb();
1186                 /* Log used ring entry write. */
1187                 log_write(vq->log_base,
1188                           vq->log_addr +
1189                            ((void __user *)used - (void __user *)vq->used),
1190                           sizeof *used);
1191                 /* Log used index update. */
1192                 log_write(vq->log_base,
1193                           vq->log_addr + offsetof(struct vring_used, idx),
1194                           sizeof vq->used->idx);
1195                 if (vq->log_ctx)
1196                         eventfd_signal(vq->log_ctx, 1);
1197         }
1198         vq->last_used_idx++;
1199         return 0;
1200 }
1201
1202 static int __vhost_add_used_n(struct vhost_virtqueue *vq,
1203                             struct vring_used_elem *heads,
1204                             unsigned count)
1205 {
1206         struct vring_used_elem __user *used;
1207         int start;
1208
1209         start = vq->last_used_idx % vq->num;
1210         used = vq->used->ring + start;
1211         if (copy_to_user(used, heads, count * sizeof *used)) {
1212                 vq_err(vq, "Failed to write used");
1213                 return -EFAULT;
1214         }
1215         if (unlikely(vq->log_used)) {
1216                 /* Make sure data is seen before log. */
1217                 smp_wmb();
1218                 /* Log used ring entry write. */
1219                 log_write(vq->log_base,
1220                           vq->log_addr +
1221                            ((void __user *)used - (void __user *)vq->used),
1222                           count * sizeof *used);
1223         }
1224         vq->last_used_idx += count;
1225         return 0;
1226 }
1227
1228 /* After we've used one of their buffers, we tell them about it.  We'll then
1229  * want to notify the guest, using eventfd. */
1230 int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
1231                      unsigned count)
1232 {
1233         int start, n, r;
1234
1235         start = vq->last_used_idx % vq->num;
1236         n = vq->num - start;
1237         if (n < count) {
1238                 r = __vhost_add_used_n(vq, heads, n);
1239                 if (r < 0)
1240                         return r;
1241                 heads += n;
1242                 count -= n;
1243         }
1244         r = __vhost_add_used_n(vq, heads, count);
1245
1246         /* Make sure buffer is written before we update index. */
1247         smp_wmb();
1248         if (put_user(vq->last_used_idx, &vq->used->idx)) {
1249                 vq_err(vq, "Failed to increment used idx");
1250                 return -EFAULT;
1251         }
1252         if (unlikely(vq->log_used)) {
1253                 /* Log used index update. */
1254                 log_write(vq->log_base,
1255                           vq->log_addr + offsetof(struct vring_used, idx),
1256                           sizeof vq->used->idx);
1257                 if (vq->log_ctx)
1258                         eventfd_signal(vq->log_ctx, 1);
1259         }
1260         return r;
1261 }
1262
1263 /* This actually signals the guest, using eventfd. */
1264 void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
1265 {
1266         __u16 flags;
1267         /* Flush out used index updates. This is paired
1268          * with the barrier that the Guest executes when enabling
1269          * interrupts. */
1270         smp_mb();
1271
1272         if (get_user(flags, &vq->avail->flags)) {
1273                 vq_err(vq, "Failed to get flags");
1274                 return;
1275         }
1276
1277         /* If they don't want an interrupt, don't signal, unless empty. */
1278         if ((flags & VRING_AVAIL_F_NO_INTERRUPT) &&
1279             (vq->avail_idx != vq->last_avail_idx ||
1280              !vhost_has_feature(dev, VIRTIO_F_NOTIFY_ON_EMPTY)))
1281                 return;
1282
1283         /* Signal the Guest tell them we used something up. */
1284         if (vq->call_ctx)
1285                 eventfd_signal(vq->call_ctx, 1);
1286 }
1287
1288 /* And here's the combo meal deal.  Supersize me! */
1289 void vhost_add_used_and_signal(struct vhost_dev *dev,
1290                                struct vhost_virtqueue *vq,
1291                                unsigned int head, int len)
1292 {
1293         vhost_add_used(vq, head, len);
1294         vhost_signal(dev, vq);
1295 }
1296
1297 /* multi-buffer version of vhost_add_used_and_signal */
1298 void vhost_add_used_and_signal_n(struct vhost_dev *dev,
1299                                  struct vhost_virtqueue *vq,
1300                                  struct vring_used_elem *heads, unsigned count)
1301 {
1302         vhost_add_used_n(vq, heads, count);
1303         vhost_signal(dev, vq);
1304 }
1305
1306 /* OK, now we need to know about added descriptors. */
1307 bool vhost_enable_notify(struct vhost_virtqueue *vq)
1308 {
1309         u16 avail_idx;
1310         int r;
1311         if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
1312                 return false;
1313         vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
1314         r = put_user(vq->used_flags, &vq->used->flags);
1315         if (r) {
1316                 vq_err(vq, "Failed to enable notification at %p: %d\n",
1317                        &vq->used->flags, r);
1318                 return false;
1319         }
1320         /* They could have slipped one in as we were doing that: make
1321          * sure it's written, then check again. */
1322         smp_mb();
1323         r = get_user(avail_idx, &vq->avail->idx);
1324         if (r) {
1325                 vq_err(vq, "Failed to check avail idx at %p: %d\n",
1326                        &vq->avail->idx, r);
1327                 return false;
1328         }
1329
1330         return avail_idx != vq->avail_idx;
1331 }
1332
1333 /* We don't need to be notified again. */
1334 void vhost_disable_notify(struct vhost_virtqueue *vq)
1335 {
1336         int r;
1337         if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
1338                 return;
1339         vq->used_flags |= VRING_USED_F_NO_NOTIFY;
1340         r = put_user(vq->used_flags, &vq->used->flags);
1341         if (r)
1342                 vq_err(vq, "Failed to enable notification at %p: %d\n",
1343                        &vq->used->flags, r);
1344 }