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