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