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