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