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