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