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