Merge tag 'docs-4.11-fixes' of git://git.lwn.net/linux
[linux-2.6-block.git] / drivers / xen / gntdev.c
1 /******************************************************************************
2  * gntdev.c
3  *
4  * Device for accessing (in user-space) pages that have been granted by other
5  * domains.
6  *
7  * Copyright (c) 2006-2007, D G Murray.
8  *           (c) 2009 Gerd Hoffmann <kraxel@redhat.com>
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #undef DEBUG
21
22 #define pr_fmt(fmt) "xen:" KBUILD_MODNAME ": " fmt
23
24 #include <linux/module.h>
25 #include <linux/kernel.h>
26 #include <linux/init.h>
27 #include <linux/miscdevice.h>
28 #include <linux/fs.h>
29 #include <linux/mm.h>
30 #include <linux/mman.h>
31 #include <linux/mmu_notifier.h>
32 #include <linux/types.h>
33 #include <linux/uaccess.h>
34 #include <linux/sched.h>
35 #include <linux/sched/mm.h>
36 #include <linux/spinlock.h>
37 #include <linux/slab.h>
38 #include <linux/highmem.h>
39
40 #include <xen/xen.h>
41 #include <xen/grant_table.h>
42 #include <xen/balloon.h>
43 #include <xen/gntdev.h>
44 #include <xen/events.h>
45 #include <xen/page.h>
46 #include <asm/xen/hypervisor.h>
47 #include <asm/xen/hypercall.h>
48
49 MODULE_LICENSE("GPL");
50 MODULE_AUTHOR("Derek G. Murray <Derek.Murray@cl.cam.ac.uk>, "
51               "Gerd Hoffmann <kraxel@redhat.com>");
52 MODULE_DESCRIPTION("User-space granted page access driver");
53
54 static int limit = 1024*1024;
55 module_param(limit, int, 0644);
56 MODULE_PARM_DESC(limit, "Maximum number of grants that may be mapped by "
57                 "the gntdev device");
58
59 static atomic_t pages_mapped = ATOMIC_INIT(0);
60
61 static int use_ptemod;
62 #define populate_freeable_maps use_ptemod
63
64 struct gntdev_priv {
65         /* maps with visible offsets in the file descriptor */
66         struct list_head maps;
67         /* maps that are not visible; will be freed on munmap.
68          * Only populated if populate_freeable_maps == 1 */
69         struct list_head freeable_maps;
70         /* lock protects maps and freeable_maps */
71         struct mutex lock;
72         struct mm_struct *mm;
73         struct mmu_notifier mn;
74 };
75
76 struct unmap_notify {
77         int flags;
78         /* Address relative to the start of the grant_map */
79         int addr;
80         int event;
81 };
82
83 struct grant_map {
84         struct list_head next;
85         struct vm_area_struct *vma;
86         int index;
87         int count;
88         int flags;
89         atomic_t users;
90         struct unmap_notify notify;
91         struct ioctl_gntdev_grant_ref *grants;
92         struct gnttab_map_grant_ref   *map_ops;
93         struct gnttab_unmap_grant_ref *unmap_ops;
94         struct gnttab_map_grant_ref   *kmap_ops;
95         struct gnttab_unmap_grant_ref *kunmap_ops;
96         struct page **pages;
97         unsigned long pages_vm_start;
98 };
99
100 static int unmap_grant_pages(struct grant_map *map, int offset, int pages);
101
102 /* ------------------------------------------------------------------ */
103
104 static void gntdev_print_maps(struct gntdev_priv *priv,
105                               char *text, int text_index)
106 {
107 #ifdef DEBUG
108         struct grant_map *map;
109
110         pr_debug("%s: maps list (priv %p)\n", __func__, priv);
111         list_for_each_entry(map, &priv->maps, next)
112                 pr_debug("  index %2d, count %2d %s\n",
113                        map->index, map->count,
114                        map->index == text_index && text ? text : "");
115 #endif
116 }
117
118 static void gntdev_free_map(struct grant_map *map)
119 {
120         if (map == NULL)
121                 return;
122
123         if (map->pages)
124                 gnttab_free_pages(map->count, map->pages);
125         kfree(map->pages);
126         kfree(map->grants);
127         kfree(map->map_ops);
128         kfree(map->unmap_ops);
129         kfree(map->kmap_ops);
130         kfree(map->kunmap_ops);
131         kfree(map);
132 }
133
134 static struct grant_map *gntdev_alloc_map(struct gntdev_priv *priv, int count)
135 {
136         struct grant_map *add;
137         int i;
138
139         add = kzalloc(sizeof(struct grant_map), GFP_KERNEL);
140         if (NULL == add)
141                 return NULL;
142
143         add->grants    = kcalloc(count, sizeof(add->grants[0]), GFP_KERNEL);
144         add->map_ops   = kcalloc(count, sizeof(add->map_ops[0]), GFP_KERNEL);
145         add->unmap_ops = kcalloc(count, sizeof(add->unmap_ops[0]), GFP_KERNEL);
146         add->kmap_ops  = kcalloc(count, sizeof(add->kmap_ops[0]), GFP_KERNEL);
147         add->kunmap_ops = kcalloc(count, sizeof(add->kunmap_ops[0]), GFP_KERNEL);
148         add->pages     = kcalloc(count, sizeof(add->pages[0]), GFP_KERNEL);
149         if (NULL == add->grants    ||
150             NULL == add->map_ops   ||
151             NULL == add->unmap_ops ||
152             NULL == add->kmap_ops  ||
153             NULL == add->kunmap_ops ||
154             NULL == add->pages)
155                 goto err;
156
157         if (gnttab_alloc_pages(count, add->pages))
158                 goto err;
159
160         for (i = 0; i < count; i++) {
161                 add->map_ops[i].handle = -1;
162                 add->unmap_ops[i].handle = -1;
163                 add->kmap_ops[i].handle = -1;
164                 add->kunmap_ops[i].handle = -1;
165         }
166
167         add->index = 0;
168         add->count = count;
169         atomic_set(&add->users, 1);
170
171         return add;
172
173 err:
174         gntdev_free_map(add);
175         return NULL;
176 }
177
178 static void gntdev_add_map(struct gntdev_priv *priv, struct grant_map *add)
179 {
180         struct grant_map *map;
181
182         list_for_each_entry(map, &priv->maps, next) {
183                 if (add->index + add->count < map->index) {
184                         list_add_tail(&add->next, &map->next);
185                         goto done;
186                 }
187                 add->index = map->index + map->count;
188         }
189         list_add_tail(&add->next, &priv->maps);
190
191 done:
192         gntdev_print_maps(priv, "[new]", add->index);
193 }
194
195 static struct grant_map *gntdev_find_map_index(struct gntdev_priv *priv,
196                 int index, int count)
197 {
198         struct grant_map *map;
199
200         list_for_each_entry(map, &priv->maps, next) {
201                 if (map->index != index)
202                         continue;
203                 if (count && map->count != count)
204                         continue;
205                 return map;
206         }
207         return NULL;
208 }
209
210 static void gntdev_put_map(struct gntdev_priv *priv, struct grant_map *map)
211 {
212         if (!map)
213                 return;
214
215         if (!atomic_dec_and_test(&map->users))
216                 return;
217
218         atomic_sub(map->count, &pages_mapped);
219
220         if (map->notify.flags & UNMAP_NOTIFY_SEND_EVENT) {
221                 notify_remote_via_evtchn(map->notify.event);
222                 evtchn_put(map->notify.event);
223         }
224
225         if (populate_freeable_maps && priv) {
226                 mutex_lock(&priv->lock);
227                 list_del(&map->next);
228                 mutex_unlock(&priv->lock);
229         }
230
231         if (map->pages && !use_ptemod)
232                 unmap_grant_pages(map, 0, map->count);
233         gntdev_free_map(map);
234 }
235
236 /* ------------------------------------------------------------------ */
237
238 static int find_grant_ptes(pte_t *pte, pgtable_t token,
239                 unsigned long addr, void *data)
240 {
241         struct grant_map *map = data;
242         unsigned int pgnr = (addr - map->vma->vm_start) >> PAGE_SHIFT;
243         int flags = map->flags | GNTMAP_application_map | GNTMAP_contains_pte;
244         u64 pte_maddr;
245
246         BUG_ON(pgnr >= map->count);
247         pte_maddr = arbitrary_virt_to_machine(pte).maddr;
248
249         /*
250          * Set the PTE as special to force get_user_pages_fast() fall
251          * back to the slow path.  If this is not supported as part of
252          * the grant map, it will be done afterwards.
253          */
254         if (xen_feature(XENFEAT_gnttab_map_avail_bits))
255                 flags |= (1 << _GNTMAP_guest_avail0);
256
257         gnttab_set_map_op(&map->map_ops[pgnr], pte_maddr, flags,
258                           map->grants[pgnr].ref,
259                           map->grants[pgnr].domid);
260         gnttab_set_unmap_op(&map->unmap_ops[pgnr], pte_maddr, flags,
261                             -1 /* handle */);
262         return 0;
263 }
264
265 #ifdef CONFIG_X86
266 static int set_grant_ptes_as_special(pte_t *pte, pgtable_t token,
267                                      unsigned long addr, void *data)
268 {
269         set_pte_at(current->mm, addr, pte, pte_mkspecial(*pte));
270         return 0;
271 }
272 #endif
273
274 static int map_grant_pages(struct grant_map *map)
275 {
276         int i, err = 0;
277
278         if (!use_ptemod) {
279                 /* Note: it could already be mapped */
280                 if (map->map_ops[0].handle != -1)
281                         return 0;
282                 for (i = 0; i < map->count; i++) {
283                         unsigned long addr = (unsigned long)
284                                 pfn_to_kaddr(page_to_pfn(map->pages[i]));
285                         gnttab_set_map_op(&map->map_ops[i], addr, map->flags,
286                                 map->grants[i].ref,
287                                 map->grants[i].domid);
288                         gnttab_set_unmap_op(&map->unmap_ops[i], addr,
289                                 map->flags, -1 /* handle */);
290                 }
291         } else {
292                 /*
293                  * Setup the map_ops corresponding to the pte entries pointing
294                  * to the kernel linear addresses of the struct pages.
295                  * These ptes are completely different from the user ptes dealt
296                  * with find_grant_ptes.
297                  */
298                 for (i = 0; i < map->count; i++) {
299                         unsigned long address = (unsigned long)
300                                 pfn_to_kaddr(page_to_pfn(map->pages[i]));
301                         BUG_ON(PageHighMem(map->pages[i]));
302
303                         gnttab_set_map_op(&map->kmap_ops[i], address,
304                                 map->flags | GNTMAP_host_map,
305                                 map->grants[i].ref,
306                                 map->grants[i].domid);
307                         gnttab_set_unmap_op(&map->kunmap_ops[i], address,
308                                 map->flags | GNTMAP_host_map, -1);
309                 }
310         }
311
312         pr_debug("map %d+%d\n", map->index, map->count);
313         err = gnttab_map_refs(map->map_ops, use_ptemod ? map->kmap_ops : NULL,
314                         map->pages, map->count);
315         if (err)
316                 return err;
317
318         for (i = 0; i < map->count; i++) {
319                 if (map->map_ops[i].status) {
320                         err = -EINVAL;
321                         continue;
322                 }
323
324                 map->unmap_ops[i].handle = map->map_ops[i].handle;
325                 if (use_ptemod)
326                         map->kunmap_ops[i].handle = map->kmap_ops[i].handle;
327         }
328         return err;
329 }
330
331 static int __unmap_grant_pages(struct grant_map *map, int offset, int pages)
332 {
333         int i, err = 0;
334         struct gntab_unmap_queue_data unmap_data;
335
336         if (map->notify.flags & UNMAP_NOTIFY_CLEAR_BYTE) {
337                 int pgno = (map->notify.addr >> PAGE_SHIFT);
338                 if (pgno >= offset && pgno < offset + pages) {
339                         /* No need for kmap, pages are in lowmem */
340                         uint8_t *tmp = pfn_to_kaddr(page_to_pfn(map->pages[pgno]));
341                         tmp[map->notify.addr & (PAGE_SIZE-1)] = 0;
342                         map->notify.flags &= ~UNMAP_NOTIFY_CLEAR_BYTE;
343                 }
344         }
345
346         unmap_data.unmap_ops = map->unmap_ops + offset;
347         unmap_data.kunmap_ops = use_ptemod ? map->kunmap_ops + offset : NULL;
348         unmap_data.pages = map->pages + offset;
349         unmap_data.count = pages;
350
351         err = gnttab_unmap_refs_sync(&unmap_data);
352         if (err)
353                 return err;
354
355         for (i = 0; i < pages; i++) {
356                 if (map->unmap_ops[offset+i].status)
357                         err = -EINVAL;
358                 pr_debug("unmap handle=%d st=%d\n",
359                         map->unmap_ops[offset+i].handle,
360                         map->unmap_ops[offset+i].status);
361                 map->unmap_ops[offset+i].handle = -1;
362         }
363         return err;
364 }
365
366 static int unmap_grant_pages(struct grant_map *map, int offset, int pages)
367 {
368         int range, err = 0;
369
370         pr_debug("unmap %d+%d [%d+%d]\n", map->index, map->count, offset, pages);
371
372         /* It is possible the requested range will have a "hole" where we
373          * already unmapped some of the grants. Only unmap valid ranges.
374          */
375         while (pages && !err) {
376                 while (pages && map->unmap_ops[offset].handle == -1) {
377                         offset++;
378                         pages--;
379                 }
380                 range = 0;
381                 while (range < pages) {
382                         if (map->unmap_ops[offset+range].handle == -1) {
383                                 range--;
384                                 break;
385                         }
386                         range++;
387                 }
388                 err = __unmap_grant_pages(map, offset, range);
389                 offset += range;
390                 pages -= range;
391         }
392
393         return err;
394 }
395
396 /* ------------------------------------------------------------------ */
397
398 static void gntdev_vma_open(struct vm_area_struct *vma)
399 {
400         struct grant_map *map = vma->vm_private_data;
401
402         pr_debug("gntdev_vma_open %p\n", vma);
403         atomic_inc(&map->users);
404 }
405
406 static void gntdev_vma_close(struct vm_area_struct *vma)
407 {
408         struct grant_map *map = vma->vm_private_data;
409         struct file *file = vma->vm_file;
410         struct gntdev_priv *priv = file->private_data;
411
412         pr_debug("gntdev_vma_close %p\n", vma);
413         if (use_ptemod) {
414                 /* It is possible that an mmu notifier could be running
415                  * concurrently, so take priv->lock to ensure that the vma won't
416                  * vanishing during the unmap_grant_pages call, since we will
417                  * spin here until that completes. Such a concurrent call will
418                  * not do any unmapping, since that has been done prior to
419                  * closing the vma, but it may still iterate the unmap_ops list.
420                  */
421                 mutex_lock(&priv->lock);
422                 map->vma = NULL;
423                 mutex_unlock(&priv->lock);
424         }
425         vma->vm_private_data = NULL;
426         gntdev_put_map(priv, map);
427 }
428
429 static struct page *gntdev_vma_find_special_page(struct vm_area_struct *vma,
430                                                  unsigned long addr)
431 {
432         struct grant_map *map = vma->vm_private_data;
433
434         return map->pages[(addr - map->pages_vm_start) >> PAGE_SHIFT];
435 }
436
437 static const struct vm_operations_struct gntdev_vmops = {
438         .open = gntdev_vma_open,
439         .close = gntdev_vma_close,
440         .find_special_page = gntdev_vma_find_special_page,
441 };
442
443 /* ------------------------------------------------------------------ */
444
445 static void unmap_if_in_range(struct grant_map *map,
446                               unsigned long start, unsigned long end)
447 {
448         unsigned long mstart, mend;
449         int err;
450
451         if (!map->vma)
452                 return;
453         if (map->vma->vm_start >= end)
454                 return;
455         if (map->vma->vm_end <= start)
456                 return;
457         mstart = max(start, map->vma->vm_start);
458         mend   = min(end,   map->vma->vm_end);
459         pr_debug("map %d+%d (%lx %lx), range %lx %lx, mrange %lx %lx\n",
460                         map->index, map->count,
461                         map->vma->vm_start, map->vma->vm_end,
462                         start, end, mstart, mend);
463         err = unmap_grant_pages(map,
464                                 (mstart - map->vma->vm_start) >> PAGE_SHIFT,
465                                 (mend - mstart) >> PAGE_SHIFT);
466         WARN_ON(err);
467 }
468
469 static void mn_invl_range_start(struct mmu_notifier *mn,
470                                 struct mm_struct *mm,
471                                 unsigned long start, unsigned long end)
472 {
473         struct gntdev_priv *priv = container_of(mn, struct gntdev_priv, mn);
474         struct grant_map *map;
475
476         mutex_lock(&priv->lock);
477         list_for_each_entry(map, &priv->maps, next) {
478                 unmap_if_in_range(map, start, end);
479         }
480         list_for_each_entry(map, &priv->freeable_maps, next) {
481                 unmap_if_in_range(map, start, end);
482         }
483         mutex_unlock(&priv->lock);
484 }
485
486 static void mn_invl_page(struct mmu_notifier *mn,
487                          struct mm_struct *mm,
488                          unsigned long address)
489 {
490         mn_invl_range_start(mn, mm, address, address + PAGE_SIZE);
491 }
492
493 static void mn_release(struct mmu_notifier *mn,
494                        struct mm_struct *mm)
495 {
496         struct gntdev_priv *priv = container_of(mn, struct gntdev_priv, mn);
497         struct grant_map *map;
498         int err;
499
500         mutex_lock(&priv->lock);
501         list_for_each_entry(map, &priv->maps, next) {
502                 if (!map->vma)
503                         continue;
504                 pr_debug("map %d+%d (%lx %lx)\n",
505                                 map->index, map->count,
506                                 map->vma->vm_start, map->vma->vm_end);
507                 err = unmap_grant_pages(map, /* offset */ 0, map->count);
508                 WARN_ON(err);
509         }
510         list_for_each_entry(map, &priv->freeable_maps, next) {
511                 if (!map->vma)
512                         continue;
513                 pr_debug("map %d+%d (%lx %lx)\n",
514                                 map->index, map->count,
515                                 map->vma->vm_start, map->vma->vm_end);
516                 err = unmap_grant_pages(map, /* offset */ 0, map->count);
517                 WARN_ON(err);
518         }
519         mutex_unlock(&priv->lock);
520 }
521
522 static const struct mmu_notifier_ops gntdev_mmu_ops = {
523         .release                = mn_release,
524         .invalidate_page        = mn_invl_page,
525         .invalidate_range_start = mn_invl_range_start,
526 };
527
528 /* ------------------------------------------------------------------ */
529
530 static int gntdev_open(struct inode *inode, struct file *flip)
531 {
532         struct gntdev_priv *priv;
533         int ret = 0;
534
535         priv = kzalloc(sizeof(*priv), GFP_KERNEL);
536         if (!priv)
537                 return -ENOMEM;
538
539         INIT_LIST_HEAD(&priv->maps);
540         INIT_LIST_HEAD(&priv->freeable_maps);
541         mutex_init(&priv->lock);
542
543         if (use_ptemod) {
544                 priv->mm = get_task_mm(current);
545                 if (!priv->mm) {
546                         kfree(priv);
547                         return -ENOMEM;
548                 }
549                 priv->mn.ops = &gntdev_mmu_ops;
550                 ret = mmu_notifier_register(&priv->mn, priv->mm);
551                 mmput(priv->mm);
552         }
553
554         if (ret) {
555                 kfree(priv);
556                 return ret;
557         }
558
559         flip->private_data = priv;
560         pr_debug("priv %p\n", priv);
561
562         return 0;
563 }
564
565 static int gntdev_release(struct inode *inode, struct file *flip)
566 {
567         struct gntdev_priv *priv = flip->private_data;
568         struct grant_map *map;
569
570         pr_debug("priv %p\n", priv);
571
572         mutex_lock(&priv->lock);
573         while (!list_empty(&priv->maps)) {
574                 map = list_entry(priv->maps.next, struct grant_map, next);
575                 list_del(&map->next);
576                 gntdev_put_map(NULL /* already removed */, map);
577         }
578         WARN_ON(!list_empty(&priv->freeable_maps));
579         mutex_unlock(&priv->lock);
580
581         if (use_ptemod)
582                 mmu_notifier_unregister(&priv->mn, priv->mm);
583         kfree(priv);
584         return 0;
585 }
586
587 static long gntdev_ioctl_map_grant_ref(struct gntdev_priv *priv,
588                                        struct ioctl_gntdev_map_grant_ref __user *u)
589 {
590         struct ioctl_gntdev_map_grant_ref op;
591         struct grant_map *map;
592         int err;
593
594         if (copy_from_user(&op, u, sizeof(op)) != 0)
595                 return -EFAULT;
596         pr_debug("priv %p, add %d\n", priv, op.count);
597         if (unlikely(op.count <= 0))
598                 return -EINVAL;
599
600         err = -ENOMEM;
601         map = gntdev_alloc_map(priv, op.count);
602         if (!map)
603                 return err;
604
605         if (unlikely(atomic_add_return(op.count, &pages_mapped) > limit)) {
606                 pr_debug("can't map: over limit\n");
607                 gntdev_put_map(NULL, map);
608                 return err;
609         }
610
611         if (copy_from_user(map->grants, &u->refs,
612                            sizeof(map->grants[0]) * op.count) != 0) {
613                 gntdev_put_map(NULL, map);
614                 return -EFAULT;
615         }
616
617         mutex_lock(&priv->lock);
618         gntdev_add_map(priv, map);
619         op.index = map->index << PAGE_SHIFT;
620         mutex_unlock(&priv->lock);
621
622         if (copy_to_user(u, &op, sizeof(op)) != 0)
623                 return -EFAULT;
624
625         return 0;
626 }
627
628 static long gntdev_ioctl_unmap_grant_ref(struct gntdev_priv *priv,
629                                          struct ioctl_gntdev_unmap_grant_ref __user *u)
630 {
631         struct ioctl_gntdev_unmap_grant_ref op;
632         struct grant_map *map;
633         int err = -ENOENT;
634
635         if (copy_from_user(&op, u, sizeof(op)) != 0)
636                 return -EFAULT;
637         pr_debug("priv %p, del %d+%d\n", priv, (int)op.index, (int)op.count);
638
639         mutex_lock(&priv->lock);
640         map = gntdev_find_map_index(priv, op.index >> PAGE_SHIFT, op.count);
641         if (map) {
642                 list_del(&map->next);
643                 if (populate_freeable_maps)
644                         list_add_tail(&map->next, &priv->freeable_maps);
645                 err = 0;
646         }
647         mutex_unlock(&priv->lock);
648         if (map)
649                 gntdev_put_map(priv, map);
650         return err;
651 }
652
653 static long gntdev_ioctl_get_offset_for_vaddr(struct gntdev_priv *priv,
654                                               struct ioctl_gntdev_get_offset_for_vaddr __user *u)
655 {
656         struct ioctl_gntdev_get_offset_for_vaddr op;
657         struct vm_area_struct *vma;
658         struct grant_map *map;
659         int rv = -EINVAL;
660
661         if (copy_from_user(&op, u, sizeof(op)) != 0)
662                 return -EFAULT;
663         pr_debug("priv %p, offset for vaddr %lx\n", priv, (unsigned long)op.vaddr);
664
665         down_read(&current->mm->mmap_sem);
666         vma = find_vma(current->mm, op.vaddr);
667         if (!vma || vma->vm_ops != &gntdev_vmops)
668                 goto out_unlock;
669
670         map = vma->vm_private_data;
671         if (!map)
672                 goto out_unlock;
673
674         op.offset = map->index << PAGE_SHIFT;
675         op.count = map->count;
676         rv = 0;
677
678  out_unlock:
679         up_read(&current->mm->mmap_sem);
680
681         if (rv == 0 && copy_to_user(u, &op, sizeof(op)) != 0)
682                 return -EFAULT;
683         return rv;
684 }
685
686 static long gntdev_ioctl_notify(struct gntdev_priv *priv, void __user *u)
687 {
688         struct ioctl_gntdev_unmap_notify op;
689         struct grant_map *map;
690         int rc;
691         int out_flags;
692         unsigned int out_event;
693
694         if (copy_from_user(&op, u, sizeof(op)))
695                 return -EFAULT;
696
697         if (op.action & ~(UNMAP_NOTIFY_CLEAR_BYTE|UNMAP_NOTIFY_SEND_EVENT))
698                 return -EINVAL;
699
700         /* We need to grab a reference to the event channel we are going to use
701          * to send the notify before releasing the reference we may already have
702          * (if someone has called this ioctl twice). This is required so that
703          * it is possible to change the clear_byte part of the notification
704          * without disturbing the event channel part, which may now be the last
705          * reference to that event channel.
706          */
707         if (op.action & UNMAP_NOTIFY_SEND_EVENT) {
708                 if (evtchn_get(op.event_channel_port))
709                         return -EINVAL;
710         }
711
712         out_flags = op.action;
713         out_event = op.event_channel_port;
714
715         mutex_lock(&priv->lock);
716
717         list_for_each_entry(map, &priv->maps, next) {
718                 uint64_t begin = map->index << PAGE_SHIFT;
719                 uint64_t end = (map->index + map->count) << PAGE_SHIFT;
720                 if (op.index >= begin && op.index < end)
721                         goto found;
722         }
723         rc = -ENOENT;
724         goto unlock_out;
725
726  found:
727         if ((op.action & UNMAP_NOTIFY_CLEAR_BYTE) &&
728                         (map->flags & GNTMAP_readonly)) {
729                 rc = -EINVAL;
730                 goto unlock_out;
731         }
732
733         out_flags = map->notify.flags;
734         out_event = map->notify.event;
735
736         map->notify.flags = op.action;
737         map->notify.addr = op.index - (map->index << PAGE_SHIFT);
738         map->notify.event = op.event_channel_port;
739
740         rc = 0;
741
742  unlock_out:
743         mutex_unlock(&priv->lock);
744
745         /* Drop the reference to the event channel we did not save in the map */
746         if (out_flags & UNMAP_NOTIFY_SEND_EVENT)
747                 evtchn_put(out_event);
748
749         return rc;
750 }
751
752 #define GNTDEV_COPY_BATCH 16
753
754 struct gntdev_copy_batch {
755         struct gnttab_copy ops[GNTDEV_COPY_BATCH];
756         struct page *pages[GNTDEV_COPY_BATCH];
757         s16 __user *status[GNTDEV_COPY_BATCH];
758         unsigned int nr_ops;
759         unsigned int nr_pages;
760 };
761
762 static int gntdev_get_page(struct gntdev_copy_batch *batch, void __user *virt,
763                            bool writeable, unsigned long *gfn)
764 {
765         unsigned long addr = (unsigned long)virt;
766         struct page *page;
767         unsigned long xen_pfn;
768         int ret;
769
770         ret = get_user_pages_fast(addr, 1, writeable, &page);
771         if (ret < 0)
772                 return ret;
773
774         batch->pages[batch->nr_pages++] = page;
775
776         xen_pfn = page_to_xen_pfn(page) + XEN_PFN_DOWN(addr & ~PAGE_MASK);
777         *gfn = pfn_to_gfn(xen_pfn);
778
779         return 0;
780 }
781
782 static void gntdev_put_pages(struct gntdev_copy_batch *batch)
783 {
784         unsigned int i;
785
786         for (i = 0; i < batch->nr_pages; i++)
787                 put_page(batch->pages[i]);
788         batch->nr_pages = 0;
789 }
790
791 static int gntdev_copy(struct gntdev_copy_batch *batch)
792 {
793         unsigned int i;
794
795         gnttab_batch_copy(batch->ops, batch->nr_ops);
796         gntdev_put_pages(batch);
797
798         /*
799          * For each completed op, update the status if the op failed
800          * and all previous ops for the segment were successful.
801          */
802         for (i = 0; i < batch->nr_ops; i++) {
803                 s16 status = batch->ops[i].status;
804                 s16 old_status;
805
806                 if (status == GNTST_okay)
807                         continue;
808
809                 if (__get_user(old_status, batch->status[i]))
810                         return -EFAULT;
811
812                 if (old_status != GNTST_okay)
813                         continue;
814
815                 if (__put_user(status, batch->status[i]))
816                         return -EFAULT;
817         }
818
819         batch->nr_ops = 0;
820         return 0;
821 }
822
823 static int gntdev_grant_copy_seg(struct gntdev_copy_batch *batch,
824                                  struct gntdev_grant_copy_segment *seg,
825                                  s16 __user *status)
826 {
827         uint16_t copied = 0;
828
829         /*
830          * Disallow local -> local copies since there is only space in
831          * batch->pages for one page per-op and this would be a very
832          * expensive memcpy().
833          */
834         if (!(seg->flags & (GNTCOPY_source_gref | GNTCOPY_dest_gref)))
835                 return -EINVAL;
836
837         /* Can't cross page if source/dest is a grant ref. */
838         if (seg->flags & GNTCOPY_source_gref) {
839                 if (seg->source.foreign.offset + seg->len > XEN_PAGE_SIZE)
840                         return -EINVAL;
841         }
842         if (seg->flags & GNTCOPY_dest_gref) {
843                 if (seg->dest.foreign.offset + seg->len > XEN_PAGE_SIZE)
844                         return -EINVAL;
845         }
846
847         if (put_user(GNTST_okay, status))
848                 return -EFAULT;
849
850         while (copied < seg->len) {
851                 struct gnttab_copy *op;
852                 void __user *virt;
853                 size_t len, off;
854                 unsigned long gfn;
855                 int ret;
856
857                 if (batch->nr_ops >= GNTDEV_COPY_BATCH) {
858                         ret = gntdev_copy(batch);
859                         if (ret < 0)
860                                 return ret;
861                 }
862
863                 len = seg->len - copied;
864
865                 op = &batch->ops[batch->nr_ops];
866                 op->flags = 0;
867
868                 if (seg->flags & GNTCOPY_source_gref) {
869                         op->source.u.ref = seg->source.foreign.ref;
870                         op->source.domid = seg->source.foreign.domid;
871                         op->source.offset = seg->source.foreign.offset + copied;
872                         op->flags |= GNTCOPY_source_gref;
873                 } else {
874                         virt = seg->source.virt + copied;
875                         off = (unsigned long)virt & ~XEN_PAGE_MASK;
876                         len = min(len, (size_t)XEN_PAGE_SIZE - off);
877
878                         ret = gntdev_get_page(batch, virt, false, &gfn);
879                         if (ret < 0)
880                                 return ret;
881
882                         op->source.u.gmfn = gfn;
883                         op->source.domid = DOMID_SELF;
884                         op->source.offset = off;
885                 }
886
887                 if (seg->flags & GNTCOPY_dest_gref) {
888                         op->dest.u.ref = seg->dest.foreign.ref;
889                         op->dest.domid = seg->dest.foreign.domid;
890                         op->dest.offset = seg->dest.foreign.offset + copied;
891                         op->flags |= GNTCOPY_dest_gref;
892                 } else {
893                         virt = seg->dest.virt + copied;
894                         off = (unsigned long)virt & ~XEN_PAGE_MASK;
895                         len = min(len, (size_t)XEN_PAGE_SIZE - off);
896
897                         ret = gntdev_get_page(batch, virt, true, &gfn);
898                         if (ret < 0)
899                                 return ret;
900
901                         op->dest.u.gmfn = gfn;
902                         op->dest.domid = DOMID_SELF;
903                         op->dest.offset = off;
904                 }
905
906                 op->len = len;
907                 copied += len;
908
909                 batch->status[batch->nr_ops] = status;
910                 batch->nr_ops++;
911         }
912
913         return 0;
914 }
915
916 static long gntdev_ioctl_grant_copy(struct gntdev_priv *priv, void __user *u)
917 {
918         struct ioctl_gntdev_grant_copy copy;
919         struct gntdev_copy_batch batch;
920         unsigned int i;
921         int ret = 0;
922
923         if (copy_from_user(&copy, u, sizeof(copy)))
924                 return -EFAULT;
925
926         batch.nr_ops = 0;
927         batch.nr_pages = 0;
928
929         for (i = 0; i < copy.count; i++) {
930                 struct gntdev_grant_copy_segment seg;
931
932                 if (copy_from_user(&seg, &copy.segments[i], sizeof(seg))) {
933                         ret = -EFAULT;
934                         goto out;
935                 }
936
937                 ret = gntdev_grant_copy_seg(&batch, &seg, &copy.segments[i].status);
938                 if (ret < 0)
939                         goto out;
940
941                 cond_resched();
942         }
943         if (batch.nr_ops)
944                 ret = gntdev_copy(&batch);
945         return ret;
946
947   out:
948         gntdev_put_pages(&batch);
949         return ret;
950 }
951
952 static long gntdev_ioctl(struct file *flip,
953                          unsigned int cmd, unsigned long arg)
954 {
955         struct gntdev_priv *priv = flip->private_data;
956         void __user *ptr = (void __user *)arg;
957
958         switch (cmd) {
959         case IOCTL_GNTDEV_MAP_GRANT_REF:
960                 return gntdev_ioctl_map_grant_ref(priv, ptr);
961
962         case IOCTL_GNTDEV_UNMAP_GRANT_REF:
963                 return gntdev_ioctl_unmap_grant_ref(priv, ptr);
964
965         case IOCTL_GNTDEV_GET_OFFSET_FOR_VADDR:
966                 return gntdev_ioctl_get_offset_for_vaddr(priv, ptr);
967
968         case IOCTL_GNTDEV_SET_UNMAP_NOTIFY:
969                 return gntdev_ioctl_notify(priv, ptr);
970
971         case IOCTL_GNTDEV_GRANT_COPY:
972                 return gntdev_ioctl_grant_copy(priv, ptr);
973
974         default:
975                 pr_debug("priv %p, unknown cmd %x\n", priv, cmd);
976                 return -ENOIOCTLCMD;
977         }
978
979         return 0;
980 }
981
982 static int gntdev_mmap(struct file *flip, struct vm_area_struct *vma)
983 {
984         struct gntdev_priv *priv = flip->private_data;
985         int index = vma->vm_pgoff;
986         int count = vma_pages(vma);
987         struct grant_map *map;
988         int i, err = -EINVAL;
989
990         if ((vma->vm_flags & VM_WRITE) && !(vma->vm_flags & VM_SHARED))
991                 return -EINVAL;
992
993         pr_debug("map %d+%d at %lx (pgoff %lx)\n",
994                         index, count, vma->vm_start, vma->vm_pgoff);
995
996         mutex_lock(&priv->lock);
997         map = gntdev_find_map_index(priv, index, count);
998         if (!map)
999                 goto unlock_out;
1000         if (use_ptemod && map->vma)
1001                 goto unlock_out;
1002         if (use_ptemod && priv->mm != vma->vm_mm) {
1003                 pr_warn("Huh? Other mm?\n");
1004                 goto unlock_out;
1005         }
1006
1007         atomic_inc(&map->users);
1008
1009         vma->vm_ops = &gntdev_vmops;
1010
1011         vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP | VM_MIXEDMAP;
1012
1013         if (use_ptemod)
1014                 vma->vm_flags |= VM_DONTCOPY;
1015
1016         vma->vm_private_data = map;
1017
1018         if (use_ptemod)
1019                 map->vma = vma;
1020
1021         if (map->flags) {
1022                 if ((vma->vm_flags & VM_WRITE) &&
1023                                 (map->flags & GNTMAP_readonly))
1024                         goto out_unlock_put;
1025         } else {
1026                 map->flags = GNTMAP_host_map;
1027                 if (!(vma->vm_flags & VM_WRITE))
1028                         map->flags |= GNTMAP_readonly;
1029         }
1030
1031         mutex_unlock(&priv->lock);
1032
1033         if (use_ptemod) {
1034                 err = apply_to_page_range(vma->vm_mm, vma->vm_start,
1035                                           vma->vm_end - vma->vm_start,
1036                                           find_grant_ptes, map);
1037                 if (err) {
1038                         pr_warn("find_grant_ptes() failure.\n");
1039                         goto out_put_map;
1040                 }
1041         }
1042
1043         err = map_grant_pages(map);
1044         if (err)
1045                 goto out_put_map;
1046
1047         if (!use_ptemod) {
1048                 for (i = 0; i < count; i++) {
1049                         err = vm_insert_page(vma, vma->vm_start + i*PAGE_SIZE,
1050                                 map->pages[i]);
1051                         if (err)
1052                                 goto out_put_map;
1053                 }
1054         } else {
1055 #ifdef CONFIG_X86
1056                 /*
1057                  * If the PTEs were not made special by the grant map
1058                  * hypercall, do so here.
1059                  *
1060                  * This is racy since the mapping is already visible
1061                  * to userspace but userspace should be well-behaved
1062                  * enough to not touch it until the mmap() call
1063                  * returns.
1064                  */
1065                 if (!xen_feature(XENFEAT_gnttab_map_avail_bits)) {
1066                         apply_to_page_range(vma->vm_mm, vma->vm_start,
1067                                             vma->vm_end - vma->vm_start,
1068                                             set_grant_ptes_as_special, NULL);
1069                 }
1070 #endif
1071                 map->pages_vm_start = vma->vm_start;
1072         }
1073
1074         return 0;
1075
1076 unlock_out:
1077         mutex_unlock(&priv->lock);
1078         return err;
1079
1080 out_unlock_put:
1081         mutex_unlock(&priv->lock);
1082 out_put_map:
1083         if (use_ptemod)
1084                 map->vma = NULL;
1085         gntdev_put_map(priv, map);
1086         return err;
1087 }
1088
1089 static const struct file_operations gntdev_fops = {
1090         .owner = THIS_MODULE,
1091         .open = gntdev_open,
1092         .release = gntdev_release,
1093         .mmap = gntdev_mmap,
1094         .unlocked_ioctl = gntdev_ioctl
1095 };
1096
1097 static struct miscdevice gntdev_miscdev = {
1098         .minor        = MISC_DYNAMIC_MINOR,
1099         .name         = "xen/gntdev",
1100         .fops         = &gntdev_fops,
1101 };
1102
1103 /* ------------------------------------------------------------------ */
1104
1105 static int __init gntdev_init(void)
1106 {
1107         int err;
1108
1109         if (!xen_domain())
1110                 return -ENODEV;
1111
1112         use_ptemod = !xen_feature(XENFEAT_auto_translated_physmap);
1113
1114         err = misc_register(&gntdev_miscdev);
1115         if (err != 0) {
1116                 pr_err("Could not register gntdev device\n");
1117                 return err;
1118         }
1119         return 0;
1120 }
1121
1122 static void __exit gntdev_exit(void)
1123 {
1124         misc_deregister(&gntdev_miscdev);
1125 }
1126
1127 module_init(gntdev_init);
1128 module_exit(gntdev_exit);
1129
1130 /* ------------------------------------------------------------------ */