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