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