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