GNU Linux-libre 4.14.290-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                         if (!use_ptemod)
368                                 alloced++;
369                 } else if (!err)
370                         err = -EINVAL;
371
372                 if (map->flags & GNTMAP_device_map)
373                         map->unmap_ops[i].dev_bus_addr = map->map_ops[i].dev_bus_addr;
374
375                 if (use_ptemod) {
376                         if (map->kmap_ops[i].status == GNTST_okay) {
377                                 if (map->map_ops[i].status == GNTST_okay)
378                                         alloced++;
379                                 map->kunmap_ops[i].handle = map->kmap_ops[i].handle;
380                         } else if (!err)
381                                 err = -EINVAL;
382                 }
383         }
384         atomic_add(alloced, &map->live_grants);
385         return err;
386 }
387
388 static void __unmap_grant_pages_done(int result,
389                 struct gntab_unmap_queue_data *data)
390 {
391         unsigned int i;
392         struct grant_map *map = data->data;
393         unsigned int offset = data->unmap_ops - map->unmap_ops;
394
395         for (i = 0; i < data->count; i++) {
396                 WARN_ON(map->unmap_ops[offset+i].status &&
397                         map->unmap_ops[offset+i].handle != -1);
398                 pr_debug("unmap handle=%d st=%d\n",
399                         map->unmap_ops[offset+i].handle,
400                         map->unmap_ops[offset+i].status);
401                 map->unmap_ops[offset+i].handle = -1;
402         }
403         /*
404          * Decrease the live-grant counter.  This must happen after the loop to
405          * prevent premature reuse of the grants by gnttab_mmap().
406          */
407         atomic_sub(data->count, &map->live_grants);
408
409         /* Release reference taken by unmap_grant_pages */
410         gntdev_put_map(NULL, map);
411 }
412
413 static void __unmap_grant_pages(struct grant_map *map, int offset, int pages)
414 {
415         if (map->notify.flags & UNMAP_NOTIFY_CLEAR_BYTE) {
416                 int pgno = (map->notify.addr >> PAGE_SHIFT);
417
418                 if (pgno >= offset && pgno < offset + pages) {
419                         /* No need for kmap, pages are in lowmem */
420                         uint8_t *tmp = pfn_to_kaddr(page_to_pfn(map->pages[pgno]));
421
422                         tmp[map->notify.addr & (PAGE_SIZE-1)] = 0;
423                         map->notify.flags &= ~UNMAP_NOTIFY_CLEAR_BYTE;
424                 }
425         }
426
427         map->unmap_data.unmap_ops = map->unmap_ops + offset;
428         map->unmap_data.kunmap_ops = use_ptemod ? map->kunmap_ops + offset : NULL;
429         map->unmap_data.pages = map->pages + offset;
430         map->unmap_data.count = pages;
431         map->unmap_data.done = __unmap_grant_pages_done;
432         map->unmap_data.data = map;
433         refcount_inc(&map->users); /* to keep map alive during async call below */
434
435         gnttab_unmap_refs_async(&map->unmap_data);
436 }
437
438 static void unmap_grant_pages(struct grant_map *map, int offset, int pages)
439 {
440         int range;
441
442         if (atomic_read(&map->live_grants) == 0)
443                 return; /* Nothing to do */
444
445         pr_debug("unmap %d+%d [%d+%d]\n", map->index, map->count, offset, pages);
446
447         /* It is possible the requested range will have a "hole" where we
448          * already unmapped some of the grants. Only unmap valid ranges.
449          */
450         while (pages) {
451                 while (pages && map->being_removed[offset]) {
452                         offset++;
453                         pages--;
454                 }
455                 range = 0;
456                 while (range < pages) {
457                         if (map->being_removed[offset + range])
458                                 break;
459                         map->being_removed[offset + range] = true;
460                         range++;
461                 }
462                 if (range)
463                         __unmap_grant_pages(map, offset, range);
464                 offset += range;
465                 pages -= range;
466         }
467 }
468
469 /* ------------------------------------------------------------------ */
470
471 static void gntdev_vma_open(struct vm_area_struct *vma)
472 {
473         struct grant_map *map = vma->vm_private_data;
474
475         pr_debug("gntdev_vma_open %p\n", vma);
476         refcount_inc(&map->users);
477 }
478
479 static void gntdev_vma_close(struct vm_area_struct *vma)
480 {
481         struct grant_map *map = vma->vm_private_data;
482         struct file *file = vma->vm_file;
483         struct gntdev_priv *priv = file->private_data;
484
485         pr_debug("gntdev_vma_close %p\n", vma);
486         if (use_ptemod) {
487                 /* It is possible that an mmu notifier could be running
488                  * concurrently, so take priv->lock to ensure that the vma won't
489                  * vanishing during the unmap_grant_pages call, since we will
490                  * spin here until that completes. Such a concurrent call will
491                  * not do any unmapping, since that has been done prior to
492                  * closing the vma, but it may still iterate the unmap_ops list.
493                  */
494                 mutex_lock(&priv->lock);
495                 map->vma = NULL;
496                 mutex_unlock(&priv->lock);
497         }
498         vma->vm_private_data = NULL;
499         gntdev_put_map(priv, map);
500 }
501
502 static struct page *gntdev_vma_find_special_page(struct vm_area_struct *vma,
503                                                  unsigned long addr)
504 {
505         struct grant_map *map = vma->vm_private_data;
506
507         return map->pages[(addr - map->pages_vm_start) >> PAGE_SHIFT];
508 }
509
510 static const struct vm_operations_struct gntdev_vmops = {
511         .open = gntdev_vma_open,
512         .close = gntdev_vma_close,
513         .find_special_page = gntdev_vma_find_special_page,
514 };
515
516 /* ------------------------------------------------------------------ */
517
518 static void unmap_if_in_range(struct grant_map *map,
519                               unsigned long start, unsigned long end)
520 {
521         unsigned long mstart, mend;
522
523         if (!map->vma)
524                 return;
525         if (map->vma->vm_start >= end)
526                 return;
527         if (map->vma->vm_end <= start)
528                 return;
529         mstart = max(start, map->vma->vm_start);
530         mend   = min(end,   map->vma->vm_end);
531         pr_debug("map %d+%d (%lx %lx), range %lx %lx, mrange %lx %lx\n",
532                         map->index, map->count,
533                         map->vma->vm_start, map->vma->vm_end,
534                         start, end, mstart, mend);
535         unmap_grant_pages(map,
536                                 (mstart - map->vma->vm_start) >> PAGE_SHIFT,
537                                 (mend - mstart) >> PAGE_SHIFT);
538 }
539
540 static void mn_invl_range_start(struct mmu_notifier *mn,
541                                 struct mm_struct *mm,
542                                 unsigned long start, unsigned long end)
543 {
544         struct gntdev_priv *priv = container_of(mn, struct gntdev_priv, mn);
545         struct grant_map *map;
546
547         mutex_lock(&priv->lock);
548         list_for_each_entry(map, &priv->maps, next) {
549                 unmap_if_in_range(map, start, end);
550         }
551         list_for_each_entry(map, &priv->freeable_maps, next) {
552                 unmap_if_in_range(map, start, end);
553         }
554         mutex_unlock(&priv->lock);
555 }
556
557 static void mn_release(struct mmu_notifier *mn,
558                        struct mm_struct *mm)
559 {
560         struct gntdev_priv *priv = container_of(mn, struct gntdev_priv, mn);
561         struct grant_map *map;
562
563         mutex_lock(&priv->lock);
564         list_for_each_entry(map, &priv->maps, next) {
565                 if (!map->vma)
566                         continue;
567                 pr_debug("map %d+%d (%lx %lx)\n",
568                                 map->index, map->count,
569                                 map->vma->vm_start, map->vma->vm_end);
570                 unmap_grant_pages(map, /* offset */ 0, map->count);
571         }
572         list_for_each_entry(map, &priv->freeable_maps, next) {
573                 if (!map->vma)
574                         continue;
575                 pr_debug("map %d+%d (%lx %lx)\n",
576                                 map->index, map->count,
577                                 map->vma->vm_start, map->vma->vm_end);
578                 unmap_grant_pages(map, /* offset */ 0, map->count);
579         }
580         mutex_unlock(&priv->lock);
581 }
582
583 static const struct mmu_notifier_ops gntdev_mmu_ops = {
584         .release                = mn_release,
585         .invalidate_range_start = mn_invl_range_start,
586 };
587
588 /* ------------------------------------------------------------------ */
589
590 static int gntdev_open(struct inode *inode, struct file *flip)
591 {
592         struct gntdev_priv *priv;
593         int ret = 0;
594
595         priv = kzalloc(sizeof(*priv), GFP_KERNEL);
596         if (!priv)
597                 return -ENOMEM;
598
599         INIT_LIST_HEAD(&priv->maps);
600         INIT_LIST_HEAD(&priv->freeable_maps);
601         mutex_init(&priv->lock);
602
603         if (use_ptemod) {
604                 priv->mm = get_task_mm(current);
605                 if (!priv->mm) {
606                         kfree(priv);
607                         return -ENOMEM;
608                 }
609                 priv->mn.ops = &gntdev_mmu_ops;
610                 ret = mmu_notifier_register(&priv->mn, priv->mm);
611                 mmput(priv->mm);
612         }
613
614         if (ret) {
615                 kfree(priv);
616                 return ret;
617         }
618
619         flip->private_data = priv;
620         pr_debug("priv %p\n", priv);
621
622         return 0;
623 }
624
625 static int gntdev_release(struct inode *inode, struct file *flip)
626 {
627         struct gntdev_priv *priv = flip->private_data;
628         struct grant_map *map;
629
630         pr_debug("priv %p\n", priv);
631
632         mutex_lock(&priv->lock);
633         while (!list_empty(&priv->maps)) {
634                 map = list_entry(priv->maps.next, struct grant_map, next);
635                 list_del(&map->next);
636                 gntdev_put_map(NULL /* already removed */, map);
637         }
638         WARN_ON(!list_empty(&priv->freeable_maps));
639         mutex_unlock(&priv->lock);
640
641         if (use_ptemod)
642                 mmu_notifier_unregister(&priv->mn, priv->mm);
643         kfree(priv);
644         return 0;
645 }
646
647 static long gntdev_ioctl_map_grant_ref(struct gntdev_priv *priv,
648                                        struct ioctl_gntdev_map_grant_ref __user *u)
649 {
650         struct ioctl_gntdev_map_grant_ref op;
651         struct grant_map *map;
652         int err;
653
654         if (copy_from_user(&op, u, sizeof(op)) != 0)
655                 return -EFAULT;
656         pr_debug("priv %p, add %d\n", priv, op.count);
657         if (unlikely(op.count <= 0))
658                 return -EINVAL;
659
660         err = -ENOMEM;
661         map = gntdev_alloc_map(priv, op.count);
662         if (!map)
663                 return err;
664
665         if (unlikely(atomic_add_return(op.count, &pages_mapped) > limit)) {
666                 pr_debug("can't map: over limit\n");
667                 gntdev_put_map(NULL, map);
668                 return err;
669         }
670
671         if (copy_from_user(map->grants, &u->refs,
672                            sizeof(map->grants[0]) * op.count) != 0) {
673                 gntdev_put_map(NULL, map);
674                 return -EFAULT;
675         }
676
677         mutex_lock(&priv->lock);
678         gntdev_add_map(priv, map);
679         op.index = map->index << PAGE_SHIFT;
680         mutex_unlock(&priv->lock);
681
682         if (copy_to_user(u, &op, sizeof(op)) != 0)
683                 return -EFAULT;
684
685         return 0;
686 }
687
688 static long gntdev_ioctl_unmap_grant_ref(struct gntdev_priv *priv,
689                                          struct ioctl_gntdev_unmap_grant_ref __user *u)
690 {
691         struct ioctl_gntdev_unmap_grant_ref op;
692         struct grant_map *map;
693         int err = -ENOENT;
694
695         if (copy_from_user(&op, u, sizeof(op)) != 0)
696                 return -EFAULT;
697         pr_debug("priv %p, del %d+%d\n", priv, (int)op.index, (int)op.count);
698
699         mutex_lock(&priv->lock);
700         map = gntdev_find_map_index(priv, op.index >> PAGE_SHIFT, op.count);
701         if (map) {
702                 list_del(&map->next);
703                 if (populate_freeable_maps)
704                         list_add_tail(&map->next, &priv->freeable_maps);
705                 err = 0;
706         }
707         mutex_unlock(&priv->lock);
708         if (map)
709                 gntdev_put_map(priv, map);
710         return err;
711 }
712
713 static long gntdev_ioctl_get_offset_for_vaddr(struct gntdev_priv *priv,
714                                               struct ioctl_gntdev_get_offset_for_vaddr __user *u)
715 {
716         struct ioctl_gntdev_get_offset_for_vaddr op;
717         struct vm_area_struct *vma;
718         struct grant_map *map;
719         int rv = -EINVAL;
720
721         if (copy_from_user(&op, u, sizeof(op)) != 0)
722                 return -EFAULT;
723         pr_debug("priv %p, offset for vaddr %lx\n", priv, (unsigned long)op.vaddr);
724
725         down_read(&current->mm->mmap_sem);
726         vma = find_vma(current->mm, op.vaddr);
727         if (!vma || vma->vm_ops != &gntdev_vmops)
728                 goto out_unlock;
729
730         map = vma->vm_private_data;
731         if (!map)
732                 goto out_unlock;
733
734         op.offset = map->index << PAGE_SHIFT;
735         op.count = map->count;
736         rv = 0;
737
738  out_unlock:
739         up_read(&current->mm->mmap_sem);
740
741         if (rv == 0 && copy_to_user(u, &op, sizeof(op)) != 0)
742                 return -EFAULT;
743         return rv;
744 }
745
746 static long gntdev_ioctl_notify(struct gntdev_priv *priv, void __user *u)
747 {
748         struct ioctl_gntdev_unmap_notify op;
749         struct grant_map *map;
750         int rc;
751         int out_flags;
752         unsigned int out_event;
753
754         if (copy_from_user(&op, u, sizeof(op)))
755                 return -EFAULT;
756
757         if (op.action & ~(UNMAP_NOTIFY_CLEAR_BYTE|UNMAP_NOTIFY_SEND_EVENT))
758                 return -EINVAL;
759
760         /* We need to grab a reference to the event channel we are going to use
761          * to send the notify before releasing the reference we may already have
762          * (if someone has called this ioctl twice). This is required so that
763          * it is possible to change the clear_byte part of the notification
764          * without disturbing the event channel part, which may now be the last
765          * reference to that event channel.
766          */
767         if (op.action & UNMAP_NOTIFY_SEND_EVENT) {
768                 if (evtchn_get(op.event_channel_port))
769                         return -EINVAL;
770         }
771
772         out_flags = op.action;
773         out_event = op.event_channel_port;
774
775         mutex_lock(&priv->lock);
776
777         list_for_each_entry(map, &priv->maps, next) {
778                 uint64_t begin = map->index << PAGE_SHIFT;
779                 uint64_t end = (map->index + map->count) << PAGE_SHIFT;
780                 if (op.index >= begin && op.index < end)
781                         goto found;
782         }
783         rc = -ENOENT;
784         goto unlock_out;
785
786  found:
787         if ((op.action & UNMAP_NOTIFY_CLEAR_BYTE) &&
788                         (map->flags & GNTMAP_readonly)) {
789                 rc = -EINVAL;
790                 goto unlock_out;
791         }
792
793         out_flags = map->notify.flags;
794         out_event = map->notify.event;
795
796         map->notify.flags = op.action;
797         map->notify.addr = op.index - (map->index << PAGE_SHIFT);
798         map->notify.event = op.event_channel_port;
799
800         rc = 0;
801
802  unlock_out:
803         mutex_unlock(&priv->lock);
804
805         /* Drop the reference to the event channel we did not save in the map */
806         if (out_flags & UNMAP_NOTIFY_SEND_EVENT)
807                 evtchn_put(out_event);
808
809         return rc;
810 }
811
812 #define GNTDEV_COPY_BATCH 16
813
814 struct gntdev_copy_batch {
815         struct gnttab_copy ops[GNTDEV_COPY_BATCH];
816         struct page *pages[GNTDEV_COPY_BATCH];
817         s16 __user *status[GNTDEV_COPY_BATCH];
818         unsigned int nr_ops;
819         unsigned int nr_pages;
820 };
821
822 static int gntdev_get_page(struct gntdev_copy_batch *batch, void __user *virt,
823                            bool writeable, unsigned long *gfn)
824 {
825         unsigned long addr = (unsigned long)virt;
826         struct page *page;
827         unsigned long xen_pfn;
828         int ret;
829
830         ret = get_user_pages_fast(addr, 1, writeable, &page);
831         if (ret < 0)
832                 return ret;
833
834         batch->pages[batch->nr_pages++] = page;
835
836         xen_pfn = page_to_xen_pfn(page) + XEN_PFN_DOWN(addr & ~PAGE_MASK);
837         *gfn = pfn_to_gfn(xen_pfn);
838
839         return 0;
840 }
841
842 static void gntdev_put_pages(struct gntdev_copy_batch *batch)
843 {
844         unsigned int i;
845
846         for (i = 0; i < batch->nr_pages; i++)
847                 put_page(batch->pages[i]);
848         batch->nr_pages = 0;
849 }
850
851 static int gntdev_copy(struct gntdev_copy_batch *batch)
852 {
853         unsigned int i;
854
855         gnttab_batch_copy(batch->ops, batch->nr_ops);
856         gntdev_put_pages(batch);
857
858         /*
859          * For each completed op, update the status if the op failed
860          * and all previous ops for the segment were successful.
861          */
862         for (i = 0; i < batch->nr_ops; i++) {
863                 s16 status = batch->ops[i].status;
864                 s16 old_status;
865
866                 if (status == GNTST_okay)
867                         continue;
868
869                 if (__get_user(old_status, batch->status[i]))
870                         return -EFAULT;
871
872                 if (old_status != GNTST_okay)
873                         continue;
874
875                 if (__put_user(status, batch->status[i]))
876                         return -EFAULT;
877         }
878
879         batch->nr_ops = 0;
880         return 0;
881 }
882
883 static int gntdev_grant_copy_seg(struct gntdev_copy_batch *batch,
884                                  struct gntdev_grant_copy_segment *seg,
885                                  s16 __user *status)
886 {
887         uint16_t copied = 0;
888
889         /*
890          * Disallow local -> local copies since there is only space in
891          * batch->pages for one page per-op and this would be a very
892          * expensive memcpy().
893          */
894         if (!(seg->flags & (GNTCOPY_source_gref | GNTCOPY_dest_gref)))
895                 return -EINVAL;
896
897         /* Can't cross page if source/dest is a grant ref. */
898         if (seg->flags & GNTCOPY_source_gref) {
899                 if (seg->source.foreign.offset + seg->len > XEN_PAGE_SIZE)
900                         return -EINVAL;
901         }
902         if (seg->flags & GNTCOPY_dest_gref) {
903                 if (seg->dest.foreign.offset + seg->len > XEN_PAGE_SIZE)
904                         return -EINVAL;
905         }
906
907         if (put_user(GNTST_okay, status))
908                 return -EFAULT;
909
910         while (copied < seg->len) {
911                 struct gnttab_copy *op;
912                 void __user *virt;
913                 size_t len, off;
914                 unsigned long gfn;
915                 int ret;
916
917                 if (batch->nr_ops >= GNTDEV_COPY_BATCH) {
918                         ret = gntdev_copy(batch);
919                         if (ret < 0)
920                                 return ret;
921                 }
922
923                 len = seg->len - copied;
924
925                 op = &batch->ops[batch->nr_ops];
926                 op->flags = 0;
927
928                 if (seg->flags & GNTCOPY_source_gref) {
929                         op->source.u.ref = seg->source.foreign.ref;
930                         op->source.domid = seg->source.foreign.domid;
931                         op->source.offset = seg->source.foreign.offset + copied;
932                         op->flags |= GNTCOPY_source_gref;
933                 } else {
934                         virt = seg->source.virt + copied;
935                         off = (unsigned long)virt & ~XEN_PAGE_MASK;
936                         len = min(len, (size_t)XEN_PAGE_SIZE - off);
937
938                         ret = gntdev_get_page(batch, virt, false, &gfn);
939                         if (ret < 0)
940                                 return ret;
941
942                         op->source.u.gmfn = gfn;
943                         op->source.domid = DOMID_SELF;
944                         op->source.offset = off;
945                 }
946
947                 if (seg->flags & GNTCOPY_dest_gref) {
948                         op->dest.u.ref = seg->dest.foreign.ref;
949                         op->dest.domid = seg->dest.foreign.domid;
950                         op->dest.offset = seg->dest.foreign.offset + copied;
951                         op->flags |= GNTCOPY_dest_gref;
952                 } else {
953                         virt = seg->dest.virt + copied;
954                         off = (unsigned long)virt & ~XEN_PAGE_MASK;
955                         len = min(len, (size_t)XEN_PAGE_SIZE - off);
956
957                         ret = gntdev_get_page(batch, virt, true, &gfn);
958                         if (ret < 0)
959                                 return ret;
960
961                         op->dest.u.gmfn = gfn;
962                         op->dest.domid = DOMID_SELF;
963                         op->dest.offset = off;
964                 }
965
966                 op->len = len;
967                 copied += len;
968
969                 batch->status[batch->nr_ops] = status;
970                 batch->nr_ops++;
971         }
972
973         return 0;
974 }
975
976 static long gntdev_ioctl_grant_copy(struct gntdev_priv *priv, void __user *u)
977 {
978         struct ioctl_gntdev_grant_copy copy;
979         struct gntdev_copy_batch batch;
980         unsigned int i;
981         int ret = 0;
982
983         if (copy_from_user(&copy, u, sizeof(copy)))
984                 return -EFAULT;
985
986         batch.nr_ops = 0;
987         batch.nr_pages = 0;
988
989         for (i = 0; i < copy.count; i++) {
990                 struct gntdev_grant_copy_segment seg;
991
992                 if (copy_from_user(&seg, &copy.segments[i], sizeof(seg))) {
993                         ret = -EFAULT;
994                         goto out;
995                 }
996
997                 ret = gntdev_grant_copy_seg(&batch, &seg, &copy.segments[i].status);
998                 if (ret < 0)
999                         goto out;
1000
1001                 cond_resched();
1002         }
1003         if (batch.nr_ops)
1004                 ret = gntdev_copy(&batch);
1005         return ret;
1006
1007   out:
1008         gntdev_put_pages(&batch);
1009         return ret;
1010 }
1011
1012 static long gntdev_ioctl(struct file *flip,
1013                          unsigned int cmd, unsigned long arg)
1014 {
1015         struct gntdev_priv *priv = flip->private_data;
1016         void __user *ptr = (void __user *)arg;
1017
1018         switch (cmd) {
1019         case IOCTL_GNTDEV_MAP_GRANT_REF:
1020                 return gntdev_ioctl_map_grant_ref(priv, ptr);
1021
1022         case IOCTL_GNTDEV_UNMAP_GRANT_REF:
1023                 return gntdev_ioctl_unmap_grant_ref(priv, ptr);
1024
1025         case IOCTL_GNTDEV_GET_OFFSET_FOR_VADDR:
1026                 return gntdev_ioctl_get_offset_for_vaddr(priv, ptr);
1027
1028         case IOCTL_GNTDEV_SET_UNMAP_NOTIFY:
1029                 return gntdev_ioctl_notify(priv, ptr);
1030
1031         case IOCTL_GNTDEV_GRANT_COPY:
1032                 return gntdev_ioctl_grant_copy(priv, ptr);
1033
1034         default:
1035                 pr_debug("priv %p, unknown cmd %x\n", priv, cmd);
1036                 return -ENOIOCTLCMD;
1037         }
1038
1039         return 0;
1040 }
1041
1042 static int gntdev_mmap(struct file *flip, struct vm_area_struct *vma)
1043 {
1044         struct gntdev_priv *priv = flip->private_data;
1045         int index = vma->vm_pgoff;
1046         int count = vma_pages(vma);
1047         struct grant_map *map;
1048         int i, err = -EINVAL;
1049
1050         if ((vma->vm_flags & VM_WRITE) && !(vma->vm_flags & VM_SHARED))
1051                 return -EINVAL;
1052
1053         pr_debug("map %d+%d at %lx (pgoff %lx)\n",
1054                         index, count, vma->vm_start, vma->vm_pgoff);
1055
1056         mutex_lock(&priv->lock);
1057         map = gntdev_find_map_index(priv, index, count);
1058         if (!map)
1059                 goto unlock_out;
1060         if (use_ptemod && map->vma)
1061                 goto unlock_out;
1062         if (use_ptemod && priv->mm != vma->vm_mm) {
1063                 pr_warn("Huh? Other mm?\n");
1064                 goto unlock_out;
1065         }
1066
1067         if (atomic_read(&map->live_grants)) {
1068                 err = -EAGAIN;
1069                 goto unlock_out;
1070         }
1071         refcount_inc(&map->users);
1072
1073         vma->vm_ops = &gntdev_vmops;
1074
1075         vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP | VM_MIXEDMAP;
1076
1077         if (use_ptemod)
1078                 vma->vm_flags |= VM_DONTCOPY;
1079
1080         vma->vm_private_data = map;
1081
1082         if (use_ptemod)
1083                 map->vma = vma;
1084
1085         if (map->flags) {
1086                 if ((vma->vm_flags & VM_WRITE) &&
1087                                 (map->flags & GNTMAP_readonly))
1088                         goto out_unlock_put;
1089         } else {
1090                 map->flags = GNTMAP_host_map;
1091                 if (!(vma->vm_flags & VM_WRITE))
1092                         map->flags |= GNTMAP_readonly;
1093         }
1094
1095         mutex_unlock(&priv->lock);
1096
1097         if (use_ptemod) {
1098                 map->pages_vm_start = vma->vm_start;
1099                 err = apply_to_page_range(vma->vm_mm, vma->vm_start,
1100                                           vma->vm_end - vma->vm_start,
1101                                           find_grant_ptes, map);
1102                 if (err) {
1103                         pr_warn("find_grant_ptes() failure.\n");
1104                         goto out_put_map;
1105                 }
1106         }
1107
1108         err = map_grant_pages(map);
1109         if (err)
1110                 goto out_put_map;
1111
1112         if (!use_ptemod) {
1113                 for (i = 0; i < count; i++) {
1114                         err = vm_insert_page(vma, vma->vm_start + i*PAGE_SIZE,
1115                                 map->pages[i]);
1116                         if (err)
1117                                 goto out_put_map;
1118                 }
1119         } else {
1120 #ifdef CONFIG_X86
1121                 /*
1122                  * If the PTEs were not made special by the grant map
1123                  * hypercall, do so here.
1124                  *
1125                  * This is racy since the mapping is already visible
1126                  * to userspace but userspace should be well-behaved
1127                  * enough to not touch it until the mmap() call
1128                  * returns.
1129                  */
1130                 if (!xen_feature(XENFEAT_gnttab_map_avail_bits)) {
1131                         apply_to_page_range(vma->vm_mm, vma->vm_start,
1132                                             vma->vm_end - vma->vm_start,
1133                                             set_grant_ptes_as_special, NULL);
1134                 }
1135 #endif
1136         }
1137
1138         return 0;
1139
1140 unlock_out:
1141         mutex_unlock(&priv->lock);
1142         return err;
1143
1144 out_unlock_put:
1145         mutex_unlock(&priv->lock);
1146 out_put_map:
1147         if (use_ptemod) {
1148                 map->vma = NULL;
1149                 unmap_grant_pages(map, 0, map->count);
1150         }
1151         gntdev_put_map(priv, map);
1152         return err;
1153 }
1154
1155 static const struct file_operations gntdev_fops = {
1156         .owner = THIS_MODULE,
1157         .open = gntdev_open,
1158         .release = gntdev_release,
1159         .mmap = gntdev_mmap,
1160         .unlocked_ioctl = gntdev_ioctl
1161 };
1162
1163 static struct miscdevice gntdev_miscdev = {
1164         .minor        = MISC_DYNAMIC_MINOR,
1165         .name         = "xen/gntdev",
1166         .fops         = &gntdev_fops,
1167 };
1168
1169 /* ------------------------------------------------------------------ */
1170
1171 static int __init gntdev_init(void)
1172 {
1173         int err;
1174
1175         if (!xen_domain())
1176                 return -ENODEV;
1177
1178         use_ptemod = !xen_feature(XENFEAT_auto_translated_physmap);
1179
1180         err = misc_register(&gntdev_miscdev);
1181         if (err != 0) {
1182                 pr_err("Could not register gntdev device\n");
1183                 return err;
1184         }
1185         return 0;
1186 }
1187
1188 static void __exit gntdev_exit(void)
1189 {
1190         misc_deregister(&gntdev_miscdev);
1191 }
1192
1193 module_init(gntdev_init);
1194 module_exit(gntdev_exit);
1195
1196 /* ------------------------------------------------------------------ */