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