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