Back to home page

OSCL-LXR

 
 

    


0001 /******************************************************************************
0002  * gntdev.c
0003  *
0004  * Device for accessing (in user-space) pages that have been granted by other
0005  * domains.
0006  *
0007  * Copyright (c) 2006-2007, D G Murray.
0008  *           (c) 2009 Gerd Hoffmann <kraxel@redhat.com>
0009  *           (c) 2018 Oleksandr Andrushchenko, EPAM Systems Inc.
0010  *
0011  * This program is distributed in the hope that it will be useful,
0012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
0013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0014  * GNU General Public License for more details.
0015  *
0016  * You should have received a copy of the GNU General Public License
0017  * along with this program; if not, write to the Free Software
0018  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
0019  */
0020 
0021 #undef DEBUG
0022 
0023 #define pr_fmt(fmt) "xen:" KBUILD_MODNAME ": " fmt
0024 
0025 #include <linux/dma-mapping.h>
0026 #include <linux/module.h>
0027 #include <linux/kernel.h>
0028 #include <linux/init.h>
0029 #include <linux/miscdevice.h>
0030 #include <linux/fs.h>
0031 #include <linux/uaccess.h>
0032 #include <linux/sched.h>
0033 #include <linux/sched/mm.h>
0034 #include <linux/spinlock.h>
0035 #include <linux/slab.h>
0036 #include <linux/highmem.h>
0037 #include <linux/refcount.h>
0038 #include <linux/workqueue.h>
0039 
0040 #include <xen/xen.h>
0041 #include <xen/grant_table.h>
0042 #include <xen/balloon.h>
0043 #include <xen/gntdev.h>
0044 #include <xen/events.h>
0045 #include <xen/page.h>
0046 #include <asm/xen/hypervisor.h>
0047 #include <asm/xen/hypercall.h>
0048 
0049 #include "gntdev-common.h"
0050 #ifdef CONFIG_XEN_GNTDEV_DMABUF
0051 #include "gntdev-dmabuf.h"
0052 #endif
0053 
0054 MODULE_LICENSE("GPL");
0055 MODULE_AUTHOR("Derek G. Murray <Derek.Murray@cl.cam.ac.uk>, "
0056           "Gerd Hoffmann <kraxel@redhat.com>");
0057 MODULE_DESCRIPTION("User-space granted page access driver");
0058 
0059 static unsigned int limit = 64*1024;
0060 module_param(limit, uint, 0644);
0061 MODULE_PARM_DESC(limit,
0062     "Maximum number of grants that may be mapped by one mapping request");
0063 
0064 /* True in PV mode, false otherwise */
0065 static int use_ptemod;
0066 
0067 static void unmap_grant_pages(struct gntdev_grant_map *map,
0068                   int offset, int pages);
0069 
0070 static struct miscdevice gntdev_miscdev;
0071 
0072 /* ------------------------------------------------------------------ */
0073 
0074 bool gntdev_test_page_count(unsigned int count)
0075 {
0076     return !count || count > limit;
0077 }
0078 
0079 static void gntdev_print_maps(struct gntdev_priv *priv,
0080                   char *text, int text_index)
0081 {
0082 #ifdef DEBUG
0083     struct gntdev_grant_map *map;
0084 
0085     pr_debug("%s: maps list (priv %p)\n", __func__, priv);
0086     list_for_each_entry(map, &priv->maps, next)
0087         pr_debug("  index %2d, count %2d %s\n",
0088                map->index, map->count,
0089                map->index == text_index && text ? text : "");
0090 #endif
0091 }
0092 
0093 static void gntdev_free_map(struct gntdev_grant_map *map)
0094 {
0095     if (map == NULL)
0096         return;
0097 
0098 #ifdef CONFIG_XEN_GRANT_DMA_ALLOC
0099     if (map->dma_vaddr) {
0100         struct gnttab_dma_alloc_args args;
0101 
0102         args.dev = map->dma_dev;
0103         args.coherent = !!(map->dma_flags & GNTDEV_DMA_FLAG_COHERENT);
0104         args.nr_pages = map->count;
0105         args.pages = map->pages;
0106         args.frames = map->frames;
0107         args.vaddr = map->dma_vaddr;
0108         args.dev_bus_addr = map->dma_bus_addr;
0109 
0110         gnttab_dma_free_pages(&args);
0111     } else
0112 #endif
0113     if (map->pages)
0114         gnttab_free_pages(map->count, map->pages);
0115 
0116 #ifdef CONFIG_XEN_GRANT_DMA_ALLOC
0117     kvfree(map->frames);
0118 #endif
0119     kvfree(map->pages);
0120     kvfree(map->grants);
0121     kvfree(map->map_ops);
0122     kvfree(map->unmap_ops);
0123     kvfree(map->kmap_ops);
0124     kvfree(map->kunmap_ops);
0125     kvfree(map->being_removed);
0126     kfree(map);
0127 }
0128 
0129 struct gntdev_grant_map *gntdev_alloc_map(struct gntdev_priv *priv, int count,
0130                       int dma_flags)
0131 {
0132     struct gntdev_grant_map *add;
0133     int i;
0134 
0135     add = kzalloc(sizeof(*add), GFP_KERNEL);
0136     if (NULL == add)
0137         return NULL;
0138 
0139     add->grants    = kvmalloc_array(count, sizeof(add->grants[0]),
0140                     GFP_KERNEL);
0141     add->map_ops   = kvmalloc_array(count, sizeof(add->map_ops[0]),
0142                     GFP_KERNEL);
0143     add->unmap_ops = kvmalloc_array(count, sizeof(add->unmap_ops[0]),
0144                     GFP_KERNEL);
0145     add->pages     = kvcalloc(count, sizeof(add->pages[0]), GFP_KERNEL);
0146     add->being_removed =
0147         kvcalloc(count, sizeof(add->being_removed[0]), GFP_KERNEL);
0148     if (NULL == add->grants    ||
0149         NULL == add->map_ops   ||
0150         NULL == add->unmap_ops ||
0151         NULL == add->pages     ||
0152         NULL == add->being_removed)
0153         goto err;
0154     if (use_ptemod) {
0155         add->kmap_ops   = kvmalloc_array(count, sizeof(add->kmap_ops[0]),
0156                          GFP_KERNEL);
0157         add->kunmap_ops = kvmalloc_array(count, sizeof(add->kunmap_ops[0]),
0158                          GFP_KERNEL);
0159         if (NULL == add->kmap_ops || NULL == add->kunmap_ops)
0160             goto err;
0161     }
0162 
0163 #ifdef CONFIG_XEN_GRANT_DMA_ALLOC
0164     add->dma_flags = dma_flags;
0165 
0166     /*
0167      * Check if this mapping is requested to be backed
0168      * by a DMA buffer.
0169      */
0170     if (dma_flags & (GNTDEV_DMA_FLAG_WC | GNTDEV_DMA_FLAG_COHERENT)) {
0171         struct gnttab_dma_alloc_args args;
0172 
0173         add->frames = kvcalloc(count, sizeof(add->frames[0]),
0174                        GFP_KERNEL);
0175         if (!add->frames)
0176             goto err;
0177 
0178         /* Remember the device, so we can free DMA memory. */
0179         add->dma_dev = priv->dma_dev;
0180 
0181         args.dev = priv->dma_dev;
0182         args.coherent = !!(dma_flags & GNTDEV_DMA_FLAG_COHERENT);
0183         args.nr_pages = count;
0184         args.pages = add->pages;
0185         args.frames = add->frames;
0186 
0187         if (gnttab_dma_alloc_pages(&args))
0188             goto err;
0189 
0190         add->dma_vaddr = args.vaddr;
0191         add->dma_bus_addr = args.dev_bus_addr;
0192     } else
0193 #endif
0194     if (gnttab_alloc_pages(count, add->pages))
0195         goto err;
0196 
0197     for (i = 0; i < count; i++) {
0198         add->grants[i].domid = DOMID_INVALID;
0199         add->grants[i].ref = INVALID_GRANT_REF;
0200         add->map_ops[i].handle = INVALID_GRANT_HANDLE;
0201         add->unmap_ops[i].handle = INVALID_GRANT_HANDLE;
0202         if (use_ptemod) {
0203             add->kmap_ops[i].handle = INVALID_GRANT_HANDLE;
0204             add->kunmap_ops[i].handle = INVALID_GRANT_HANDLE;
0205         }
0206     }
0207 
0208     add->index = 0;
0209     add->count = count;
0210     refcount_set(&add->users, 1);
0211 
0212     return add;
0213 
0214 err:
0215     gntdev_free_map(add);
0216     return NULL;
0217 }
0218 
0219 void gntdev_add_map(struct gntdev_priv *priv, struct gntdev_grant_map *add)
0220 {
0221     struct gntdev_grant_map *map;
0222 
0223     list_for_each_entry(map, &priv->maps, next) {
0224         if (add->index + add->count < map->index) {
0225             list_add_tail(&add->next, &map->next);
0226             goto done;
0227         }
0228         add->index = map->index + map->count;
0229     }
0230     list_add_tail(&add->next, &priv->maps);
0231 
0232 done:
0233     gntdev_print_maps(priv, "[new]", add->index);
0234 }
0235 
0236 static struct gntdev_grant_map *gntdev_find_map_index(struct gntdev_priv *priv,
0237                               int index, int count)
0238 {
0239     struct gntdev_grant_map *map;
0240 
0241     list_for_each_entry(map, &priv->maps, next) {
0242         if (map->index != index)
0243             continue;
0244         if (count && map->count != count)
0245             continue;
0246         return map;
0247     }
0248     return NULL;
0249 }
0250 
0251 void gntdev_put_map(struct gntdev_priv *priv, struct gntdev_grant_map *map)
0252 {
0253     if (!map)
0254         return;
0255 
0256     if (!refcount_dec_and_test(&map->users))
0257         return;
0258 
0259     if (map->pages && !use_ptemod) {
0260         /*
0261          * Increment the reference count.  This ensures that the
0262          * subsequent call to unmap_grant_pages() will not wind up
0263          * re-entering itself.  It *can* wind up calling
0264          * gntdev_put_map() recursively, but such calls will be with a
0265          * reference count greater than 1, so they will return before
0266          * this code is reached.  The recursion depth is thus limited to
0267          * 1.  Do NOT use refcount_inc() here, as it will detect that
0268          * the reference count is zero and WARN().
0269          */
0270         refcount_set(&map->users, 1);
0271 
0272         /*
0273          * Unmap the grants.  This may or may not be asynchronous, so it
0274          * is possible that the reference count is 1 on return, but it
0275          * could also be greater than 1.
0276          */
0277         unmap_grant_pages(map, 0, map->count);
0278 
0279         /* Check if the memory now needs to be freed */
0280         if (!refcount_dec_and_test(&map->users))
0281             return;
0282 
0283         /*
0284          * All pages have been returned to the hypervisor, so free the
0285          * map.
0286          */
0287     }
0288 
0289     if (map->notify.flags & UNMAP_NOTIFY_SEND_EVENT) {
0290         notify_remote_via_evtchn(map->notify.event);
0291         evtchn_put(map->notify.event);
0292     }
0293     gntdev_free_map(map);
0294 }
0295 
0296 /* ------------------------------------------------------------------ */
0297 
0298 static int find_grant_ptes(pte_t *pte, unsigned long addr, void *data)
0299 {
0300     struct gntdev_grant_map *map = data;
0301     unsigned int pgnr = (addr - map->vma->vm_start) >> PAGE_SHIFT;
0302     int flags = map->flags | GNTMAP_application_map | GNTMAP_contains_pte |
0303             (1 << _GNTMAP_guest_avail0);
0304     u64 pte_maddr;
0305 
0306     BUG_ON(pgnr >= map->count);
0307     pte_maddr = arbitrary_virt_to_machine(pte).maddr;
0308 
0309     gnttab_set_map_op(&map->map_ops[pgnr], pte_maddr, flags,
0310               map->grants[pgnr].ref,
0311               map->grants[pgnr].domid);
0312     gnttab_set_unmap_op(&map->unmap_ops[pgnr], pte_maddr, flags,
0313                 INVALID_GRANT_HANDLE);
0314     return 0;
0315 }
0316 
0317 int gntdev_map_grant_pages(struct gntdev_grant_map *map)
0318 {
0319     size_t alloced = 0;
0320     int i, err = 0;
0321 
0322     if (!use_ptemod) {
0323         /* Note: it could already be mapped */
0324         if (map->map_ops[0].handle != INVALID_GRANT_HANDLE)
0325             return 0;
0326         for (i = 0; i < map->count; i++) {
0327             unsigned long addr = (unsigned long)
0328                 pfn_to_kaddr(page_to_pfn(map->pages[i]));
0329             gnttab_set_map_op(&map->map_ops[i], addr, map->flags,
0330                 map->grants[i].ref,
0331                 map->grants[i].domid);
0332             gnttab_set_unmap_op(&map->unmap_ops[i], addr,
0333                 map->flags, INVALID_GRANT_HANDLE);
0334         }
0335     } else {
0336         /*
0337          * Setup the map_ops corresponding to the pte entries pointing
0338          * to the kernel linear addresses of the struct pages.
0339          * These ptes are completely different from the user ptes dealt
0340          * with find_grant_ptes.
0341          * Note that GNTMAP_device_map isn't needed here: The
0342          * dev_bus_addr output field gets consumed only from ->map_ops,
0343          * and by not requesting it when mapping we also avoid needing
0344          * to mirror dev_bus_addr into ->unmap_ops (and holding an extra
0345          * reference to the page in the hypervisor).
0346          */
0347         unsigned int flags = (map->flags & ~GNTMAP_device_map) |
0348                      GNTMAP_host_map;
0349 
0350         for (i = 0; i < map->count; i++) {
0351             unsigned long address = (unsigned long)
0352                 pfn_to_kaddr(page_to_pfn(map->pages[i]));
0353             BUG_ON(PageHighMem(map->pages[i]));
0354 
0355             gnttab_set_map_op(&map->kmap_ops[i], address, flags,
0356                 map->grants[i].ref,
0357                 map->grants[i].domid);
0358             gnttab_set_unmap_op(&map->kunmap_ops[i], address,
0359                 flags, INVALID_GRANT_HANDLE);
0360         }
0361     }
0362 
0363     pr_debug("map %d+%d\n", map->index, map->count);
0364     err = gnttab_map_refs(map->map_ops, map->kmap_ops, map->pages,
0365             map->count);
0366 
0367     for (i = 0; i < map->count; i++) {
0368         if (map->map_ops[i].status == GNTST_okay) {
0369             map->unmap_ops[i].handle = map->map_ops[i].handle;
0370             if (!use_ptemod)
0371                 alloced++;
0372         } else if (!err)
0373             err = -EINVAL;
0374 
0375         if (map->flags & GNTMAP_device_map)
0376             map->unmap_ops[i].dev_bus_addr = map->map_ops[i].dev_bus_addr;
0377 
0378         if (use_ptemod) {
0379             if (map->kmap_ops[i].status == GNTST_okay) {
0380                 if (map->map_ops[i].status == GNTST_okay)
0381                     alloced++;
0382                 map->kunmap_ops[i].handle = map->kmap_ops[i].handle;
0383             } else if (!err)
0384                 err = -EINVAL;
0385         }
0386     }
0387     atomic_add(alloced, &map->live_grants);
0388     return err;
0389 }
0390 
0391 static void __unmap_grant_pages_done(int result,
0392         struct gntab_unmap_queue_data *data)
0393 {
0394     unsigned int i;
0395     struct gntdev_grant_map *map = data->data;
0396     unsigned int offset = data->unmap_ops - map->unmap_ops;
0397 
0398     for (i = 0; i < data->count; i++) {
0399         WARN_ON(map->unmap_ops[offset + i].status != GNTST_okay &&
0400             map->unmap_ops[offset + i].handle != INVALID_GRANT_HANDLE);
0401         pr_debug("unmap handle=%d st=%d\n",
0402             map->unmap_ops[offset+i].handle,
0403             map->unmap_ops[offset+i].status);
0404         map->unmap_ops[offset+i].handle = INVALID_GRANT_HANDLE;
0405         if (use_ptemod) {
0406             WARN_ON(map->kunmap_ops[offset + i].status != GNTST_okay &&
0407                 map->kunmap_ops[offset + i].handle != INVALID_GRANT_HANDLE);
0408             pr_debug("kunmap handle=%u st=%d\n",
0409                  map->kunmap_ops[offset+i].handle,
0410                  map->kunmap_ops[offset+i].status);
0411             map->kunmap_ops[offset+i].handle = INVALID_GRANT_HANDLE;
0412         }
0413     }
0414     /*
0415      * Decrease the live-grant counter.  This must happen after the loop to
0416      * prevent premature reuse of the grants by gnttab_mmap().
0417      */
0418     atomic_sub(data->count, &map->live_grants);
0419 
0420     /* Release reference taken by __unmap_grant_pages */
0421     gntdev_put_map(NULL, map);
0422 }
0423 
0424 static void __unmap_grant_pages(struct gntdev_grant_map *map, int offset,
0425                    int pages)
0426 {
0427     if (map->notify.flags & UNMAP_NOTIFY_CLEAR_BYTE) {
0428         int pgno = (map->notify.addr >> PAGE_SHIFT);
0429 
0430         if (pgno >= offset && pgno < offset + pages) {
0431             /* No need for kmap, pages are in lowmem */
0432             uint8_t *tmp = pfn_to_kaddr(page_to_pfn(map->pages[pgno]));
0433 
0434             tmp[map->notify.addr & (PAGE_SIZE-1)] = 0;
0435             map->notify.flags &= ~UNMAP_NOTIFY_CLEAR_BYTE;
0436         }
0437     }
0438 
0439     map->unmap_data.unmap_ops = map->unmap_ops + offset;
0440     map->unmap_data.kunmap_ops = use_ptemod ? map->kunmap_ops + offset : NULL;
0441     map->unmap_data.pages = map->pages + offset;
0442     map->unmap_data.count = pages;
0443     map->unmap_data.done = __unmap_grant_pages_done;
0444     map->unmap_data.data = map;
0445     refcount_inc(&map->users); /* to keep map alive during async call below */
0446 
0447     gnttab_unmap_refs_async(&map->unmap_data);
0448 }
0449 
0450 static void unmap_grant_pages(struct gntdev_grant_map *map, int offset,
0451                   int pages)
0452 {
0453     int range;
0454 
0455     if (atomic_read(&map->live_grants) == 0)
0456         return; /* Nothing to do */
0457 
0458     pr_debug("unmap %d+%d [%d+%d]\n", map->index, map->count, offset, pages);
0459 
0460     /* It is possible the requested range will have a "hole" where we
0461      * already unmapped some of the grants. Only unmap valid ranges.
0462      */
0463     while (pages) {
0464         while (pages && map->being_removed[offset]) {
0465             offset++;
0466             pages--;
0467         }
0468         range = 0;
0469         while (range < pages) {
0470             if (map->being_removed[offset + range])
0471                 break;
0472             map->being_removed[offset + range] = true;
0473             range++;
0474         }
0475         if (range)
0476             __unmap_grant_pages(map, offset, range);
0477         offset += range;
0478         pages -= range;
0479     }
0480 }
0481 
0482 /* ------------------------------------------------------------------ */
0483 
0484 static void gntdev_vma_open(struct vm_area_struct *vma)
0485 {
0486     struct gntdev_grant_map *map = vma->vm_private_data;
0487 
0488     pr_debug("gntdev_vma_open %p\n", vma);
0489     refcount_inc(&map->users);
0490 }
0491 
0492 static void gntdev_vma_close(struct vm_area_struct *vma)
0493 {
0494     struct gntdev_grant_map *map = vma->vm_private_data;
0495     struct file *file = vma->vm_file;
0496     struct gntdev_priv *priv = file->private_data;
0497 
0498     pr_debug("gntdev_vma_close %p\n", vma);
0499     if (use_ptemod) {
0500         WARN_ON(map->vma != vma);
0501         mmu_interval_notifier_remove(&map->notifier);
0502         map->vma = NULL;
0503     }
0504     vma->vm_private_data = NULL;
0505     gntdev_put_map(priv, map);
0506 }
0507 
0508 static struct page *gntdev_vma_find_special_page(struct vm_area_struct *vma,
0509                          unsigned long addr)
0510 {
0511     struct gntdev_grant_map *map = vma->vm_private_data;
0512 
0513     return map->pages[(addr - map->pages_vm_start) >> PAGE_SHIFT];
0514 }
0515 
0516 static const struct vm_operations_struct gntdev_vmops = {
0517     .open = gntdev_vma_open,
0518     .close = gntdev_vma_close,
0519     .find_special_page = gntdev_vma_find_special_page,
0520 };
0521 
0522 /* ------------------------------------------------------------------ */
0523 
0524 static bool gntdev_invalidate(struct mmu_interval_notifier *mn,
0525                   const struct mmu_notifier_range *range,
0526                   unsigned long cur_seq)
0527 {
0528     struct gntdev_grant_map *map =
0529         container_of(mn, struct gntdev_grant_map, notifier);
0530     unsigned long mstart, mend;
0531 
0532     if (!mmu_notifier_range_blockable(range))
0533         return false;
0534 
0535     /*
0536      * If the VMA is split or otherwise changed the notifier is not
0537      * updated, but we don't want to process VA's outside the modified
0538      * VMA. FIXME: It would be much more understandable to just prevent
0539      * modifying the VMA in the first place.
0540      */
0541     if (map->vma->vm_start >= range->end ||
0542         map->vma->vm_end <= range->start)
0543         return true;
0544 
0545     mstart = max(range->start, map->vma->vm_start);
0546     mend = min(range->end, map->vma->vm_end);
0547     pr_debug("map %d+%d (%lx %lx), range %lx %lx, mrange %lx %lx\n",
0548             map->index, map->count,
0549             map->vma->vm_start, map->vma->vm_end,
0550             range->start, range->end, mstart, mend);
0551     unmap_grant_pages(map,
0552                 (mstart - map->vma->vm_start) >> PAGE_SHIFT,
0553                 (mend - mstart) >> PAGE_SHIFT);
0554 
0555     return true;
0556 }
0557 
0558 static const struct mmu_interval_notifier_ops gntdev_mmu_ops = {
0559     .invalidate = gntdev_invalidate,
0560 };
0561 
0562 /* ------------------------------------------------------------------ */
0563 
0564 static int gntdev_open(struct inode *inode, struct file *flip)
0565 {
0566     struct gntdev_priv *priv;
0567 
0568     priv = kzalloc(sizeof(*priv), GFP_KERNEL);
0569     if (!priv)
0570         return -ENOMEM;
0571 
0572     INIT_LIST_HEAD(&priv->maps);
0573     mutex_init(&priv->lock);
0574 
0575 #ifdef CONFIG_XEN_GNTDEV_DMABUF
0576     priv->dmabuf_priv = gntdev_dmabuf_init(flip);
0577     if (IS_ERR(priv->dmabuf_priv)) {
0578         int ret = PTR_ERR(priv->dmabuf_priv);
0579 
0580         kfree(priv);
0581         return ret;
0582     }
0583 #endif
0584 
0585     flip->private_data = priv;
0586 #ifdef CONFIG_XEN_GRANT_DMA_ALLOC
0587     priv->dma_dev = gntdev_miscdev.this_device;
0588     dma_coerce_mask_and_coherent(priv->dma_dev, DMA_BIT_MASK(64));
0589 #endif
0590     pr_debug("priv %p\n", priv);
0591 
0592     return 0;
0593 }
0594 
0595 static int gntdev_release(struct inode *inode, struct file *flip)
0596 {
0597     struct gntdev_priv *priv = flip->private_data;
0598     struct gntdev_grant_map *map;
0599 
0600     pr_debug("priv %p\n", priv);
0601 
0602     mutex_lock(&priv->lock);
0603     while (!list_empty(&priv->maps)) {
0604         map = list_entry(priv->maps.next,
0605                  struct gntdev_grant_map, next);
0606         list_del(&map->next);
0607         gntdev_put_map(NULL /* already removed */, map);
0608     }
0609     mutex_unlock(&priv->lock);
0610 
0611 #ifdef CONFIG_XEN_GNTDEV_DMABUF
0612     gntdev_dmabuf_fini(priv->dmabuf_priv);
0613 #endif
0614 
0615     kfree(priv);
0616     return 0;
0617 }
0618 
0619 static long gntdev_ioctl_map_grant_ref(struct gntdev_priv *priv,
0620                        struct ioctl_gntdev_map_grant_ref __user *u)
0621 {
0622     struct ioctl_gntdev_map_grant_ref op;
0623     struct gntdev_grant_map *map;
0624     int err;
0625 
0626     if (copy_from_user(&op, u, sizeof(op)) != 0)
0627         return -EFAULT;
0628     pr_debug("priv %p, add %d\n", priv, op.count);
0629     if (unlikely(gntdev_test_page_count(op.count)))
0630         return -EINVAL;
0631 
0632     err = -ENOMEM;
0633     map = gntdev_alloc_map(priv, op.count, 0 /* This is not a dma-buf. */);
0634     if (!map)
0635         return err;
0636 
0637     if (copy_from_user(map->grants, &u->refs,
0638                sizeof(map->grants[0]) * op.count) != 0) {
0639         gntdev_put_map(NULL, map);
0640         return -EFAULT;
0641     }
0642 
0643     mutex_lock(&priv->lock);
0644     gntdev_add_map(priv, map);
0645     op.index = map->index << PAGE_SHIFT;
0646     mutex_unlock(&priv->lock);
0647 
0648     if (copy_to_user(u, &op, sizeof(op)) != 0)
0649         return -EFAULT;
0650 
0651     return 0;
0652 }
0653 
0654 static long gntdev_ioctl_unmap_grant_ref(struct gntdev_priv *priv,
0655                      struct ioctl_gntdev_unmap_grant_ref __user *u)
0656 {
0657     struct ioctl_gntdev_unmap_grant_ref op;
0658     struct gntdev_grant_map *map;
0659     int err = -ENOENT;
0660 
0661     if (copy_from_user(&op, u, sizeof(op)) != 0)
0662         return -EFAULT;
0663     pr_debug("priv %p, del %d+%d\n", priv, (int)op.index, (int)op.count);
0664 
0665     mutex_lock(&priv->lock);
0666     map = gntdev_find_map_index(priv, op.index >> PAGE_SHIFT, op.count);
0667     if (map) {
0668         list_del(&map->next);
0669         err = 0;
0670     }
0671     mutex_unlock(&priv->lock);
0672     if (map)
0673         gntdev_put_map(priv, map);
0674     return err;
0675 }
0676 
0677 static long gntdev_ioctl_get_offset_for_vaddr(struct gntdev_priv *priv,
0678                           struct ioctl_gntdev_get_offset_for_vaddr __user *u)
0679 {
0680     struct ioctl_gntdev_get_offset_for_vaddr op;
0681     struct vm_area_struct *vma;
0682     struct gntdev_grant_map *map;
0683     int rv = -EINVAL;
0684 
0685     if (copy_from_user(&op, u, sizeof(op)) != 0)
0686         return -EFAULT;
0687     pr_debug("priv %p, offset for vaddr %lx\n", priv, (unsigned long)op.vaddr);
0688 
0689     mmap_read_lock(current->mm);
0690     vma = find_vma(current->mm, op.vaddr);
0691     if (!vma || vma->vm_ops != &gntdev_vmops)
0692         goto out_unlock;
0693 
0694     map = vma->vm_private_data;
0695     if (!map)
0696         goto out_unlock;
0697 
0698     op.offset = map->index << PAGE_SHIFT;
0699     op.count = map->count;
0700     rv = 0;
0701 
0702  out_unlock:
0703     mmap_read_unlock(current->mm);
0704 
0705     if (rv == 0 && copy_to_user(u, &op, sizeof(op)) != 0)
0706         return -EFAULT;
0707     return rv;
0708 }
0709 
0710 static long gntdev_ioctl_notify(struct gntdev_priv *priv, void __user *u)
0711 {
0712     struct ioctl_gntdev_unmap_notify op;
0713     struct gntdev_grant_map *map;
0714     int rc;
0715     int out_flags;
0716     evtchn_port_t out_event;
0717 
0718     if (copy_from_user(&op, u, sizeof(op)))
0719         return -EFAULT;
0720 
0721     if (op.action & ~(UNMAP_NOTIFY_CLEAR_BYTE|UNMAP_NOTIFY_SEND_EVENT))
0722         return -EINVAL;
0723 
0724     /* We need to grab a reference to the event channel we are going to use
0725      * to send the notify before releasing the reference we may already have
0726      * (if someone has called this ioctl twice). This is required so that
0727      * it is possible to change the clear_byte part of the notification
0728      * without disturbing the event channel part, which may now be the last
0729      * reference to that event channel.
0730      */
0731     if (op.action & UNMAP_NOTIFY_SEND_EVENT) {
0732         if (evtchn_get(op.event_channel_port))
0733             return -EINVAL;
0734     }
0735 
0736     out_flags = op.action;
0737     out_event = op.event_channel_port;
0738 
0739     mutex_lock(&priv->lock);
0740 
0741     list_for_each_entry(map, &priv->maps, next) {
0742         uint64_t begin = map->index << PAGE_SHIFT;
0743         uint64_t end = (map->index + map->count) << PAGE_SHIFT;
0744         if (op.index >= begin && op.index < end)
0745             goto found;
0746     }
0747     rc = -ENOENT;
0748     goto unlock_out;
0749 
0750  found:
0751     if ((op.action & UNMAP_NOTIFY_CLEAR_BYTE) &&
0752             (map->flags & GNTMAP_readonly)) {
0753         rc = -EINVAL;
0754         goto unlock_out;
0755     }
0756 
0757     out_flags = map->notify.flags;
0758     out_event = map->notify.event;
0759 
0760     map->notify.flags = op.action;
0761     map->notify.addr = op.index - (map->index << PAGE_SHIFT);
0762     map->notify.event = op.event_channel_port;
0763 
0764     rc = 0;
0765 
0766  unlock_out:
0767     mutex_unlock(&priv->lock);
0768 
0769     /* Drop the reference to the event channel we did not save in the map */
0770     if (out_flags & UNMAP_NOTIFY_SEND_EVENT)
0771         evtchn_put(out_event);
0772 
0773     return rc;
0774 }
0775 
0776 #define GNTDEV_COPY_BATCH 16
0777 
0778 struct gntdev_copy_batch {
0779     struct gnttab_copy ops[GNTDEV_COPY_BATCH];
0780     struct page *pages[GNTDEV_COPY_BATCH];
0781     s16 __user *status[GNTDEV_COPY_BATCH];
0782     unsigned int nr_ops;
0783     unsigned int nr_pages;
0784     bool writeable;
0785 };
0786 
0787 static int gntdev_get_page(struct gntdev_copy_batch *batch, void __user *virt,
0788                 unsigned long *gfn)
0789 {
0790     unsigned long addr = (unsigned long)virt;
0791     struct page *page;
0792     unsigned long xen_pfn;
0793     int ret;
0794 
0795     ret = pin_user_pages_fast(addr, 1, batch->writeable ? FOLL_WRITE : 0, &page);
0796     if (ret < 0)
0797         return ret;
0798 
0799     batch->pages[batch->nr_pages++] = page;
0800 
0801     xen_pfn = page_to_xen_pfn(page) + XEN_PFN_DOWN(addr & ~PAGE_MASK);
0802     *gfn = pfn_to_gfn(xen_pfn);
0803 
0804     return 0;
0805 }
0806 
0807 static void gntdev_put_pages(struct gntdev_copy_batch *batch)
0808 {
0809     unpin_user_pages_dirty_lock(batch->pages, batch->nr_pages, batch->writeable);
0810     batch->nr_pages = 0;
0811     batch->writeable = false;
0812 }
0813 
0814 static int gntdev_copy(struct gntdev_copy_batch *batch)
0815 {
0816     unsigned int i;
0817 
0818     gnttab_batch_copy(batch->ops, batch->nr_ops);
0819     gntdev_put_pages(batch);
0820 
0821     /*
0822      * For each completed op, update the status if the op failed
0823      * and all previous ops for the segment were successful.
0824      */
0825     for (i = 0; i < batch->nr_ops; i++) {
0826         s16 status = batch->ops[i].status;
0827         s16 old_status;
0828 
0829         if (status == GNTST_okay)
0830             continue;
0831 
0832         if (__get_user(old_status, batch->status[i]))
0833             return -EFAULT;
0834 
0835         if (old_status != GNTST_okay)
0836             continue;
0837 
0838         if (__put_user(status, batch->status[i]))
0839             return -EFAULT;
0840     }
0841 
0842     batch->nr_ops = 0;
0843     return 0;
0844 }
0845 
0846 static int gntdev_grant_copy_seg(struct gntdev_copy_batch *batch,
0847                  struct gntdev_grant_copy_segment *seg,
0848                  s16 __user *status)
0849 {
0850     uint16_t copied = 0;
0851 
0852     /*
0853      * Disallow local -> local copies since there is only space in
0854      * batch->pages for one page per-op and this would be a very
0855      * expensive memcpy().
0856      */
0857     if (!(seg->flags & (GNTCOPY_source_gref | GNTCOPY_dest_gref)))
0858         return -EINVAL;
0859 
0860     /* Can't cross page if source/dest is a grant ref. */
0861     if (seg->flags & GNTCOPY_source_gref) {
0862         if (seg->source.foreign.offset + seg->len > XEN_PAGE_SIZE)
0863             return -EINVAL;
0864     }
0865     if (seg->flags & GNTCOPY_dest_gref) {
0866         if (seg->dest.foreign.offset + seg->len > XEN_PAGE_SIZE)
0867             return -EINVAL;
0868     }
0869 
0870     if (put_user(GNTST_okay, status))
0871         return -EFAULT;
0872 
0873     while (copied < seg->len) {
0874         struct gnttab_copy *op;
0875         void __user *virt;
0876         size_t len, off;
0877         unsigned long gfn;
0878         int ret;
0879 
0880         if (batch->nr_ops >= GNTDEV_COPY_BATCH) {
0881             ret = gntdev_copy(batch);
0882             if (ret < 0)
0883                 return ret;
0884         }
0885 
0886         len = seg->len - copied;
0887 
0888         op = &batch->ops[batch->nr_ops];
0889         op->flags = 0;
0890 
0891         if (seg->flags & GNTCOPY_source_gref) {
0892             op->source.u.ref = seg->source.foreign.ref;
0893             op->source.domid = seg->source.foreign.domid;
0894             op->source.offset = seg->source.foreign.offset + copied;
0895             op->flags |= GNTCOPY_source_gref;
0896         } else {
0897             virt = seg->source.virt + copied;
0898             off = (unsigned long)virt & ~XEN_PAGE_MASK;
0899             len = min(len, (size_t)XEN_PAGE_SIZE - off);
0900             batch->writeable = false;
0901 
0902             ret = gntdev_get_page(batch, virt, &gfn);
0903             if (ret < 0)
0904                 return ret;
0905 
0906             op->source.u.gmfn = gfn;
0907             op->source.domid = DOMID_SELF;
0908             op->source.offset = off;
0909         }
0910 
0911         if (seg->flags & GNTCOPY_dest_gref) {
0912             op->dest.u.ref = seg->dest.foreign.ref;
0913             op->dest.domid = seg->dest.foreign.domid;
0914             op->dest.offset = seg->dest.foreign.offset + copied;
0915             op->flags |= GNTCOPY_dest_gref;
0916         } else {
0917             virt = seg->dest.virt + copied;
0918             off = (unsigned long)virt & ~XEN_PAGE_MASK;
0919             len = min(len, (size_t)XEN_PAGE_SIZE - off);
0920             batch->writeable = true;
0921 
0922             ret = gntdev_get_page(batch, virt, &gfn);
0923             if (ret < 0)
0924                 return ret;
0925 
0926             op->dest.u.gmfn = gfn;
0927             op->dest.domid = DOMID_SELF;
0928             op->dest.offset = off;
0929         }
0930 
0931         op->len = len;
0932         copied += len;
0933 
0934         batch->status[batch->nr_ops] = status;
0935         batch->nr_ops++;
0936     }
0937 
0938     return 0;
0939 }
0940 
0941 static long gntdev_ioctl_grant_copy(struct gntdev_priv *priv, void __user *u)
0942 {
0943     struct ioctl_gntdev_grant_copy copy;
0944     struct gntdev_copy_batch batch;
0945     unsigned int i;
0946     int ret = 0;
0947 
0948     if (copy_from_user(&copy, u, sizeof(copy)))
0949         return -EFAULT;
0950 
0951     batch.nr_ops = 0;
0952     batch.nr_pages = 0;
0953 
0954     for (i = 0; i < copy.count; i++) {
0955         struct gntdev_grant_copy_segment seg;
0956 
0957         if (copy_from_user(&seg, &copy.segments[i], sizeof(seg))) {
0958             ret = -EFAULT;
0959             goto out;
0960         }
0961 
0962         ret = gntdev_grant_copy_seg(&batch, &seg, &copy.segments[i].status);
0963         if (ret < 0)
0964             goto out;
0965 
0966         cond_resched();
0967     }
0968     if (batch.nr_ops)
0969         ret = gntdev_copy(&batch);
0970     return ret;
0971 
0972   out:
0973     gntdev_put_pages(&batch);
0974     return ret;
0975 }
0976 
0977 static long gntdev_ioctl(struct file *flip,
0978              unsigned int cmd, unsigned long arg)
0979 {
0980     struct gntdev_priv *priv = flip->private_data;
0981     void __user *ptr = (void __user *)arg;
0982 
0983     switch (cmd) {
0984     case IOCTL_GNTDEV_MAP_GRANT_REF:
0985         return gntdev_ioctl_map_grant_ref(priv, ptr);
0986 
0987     case IOCTL_GNTDEV_UNMAP_GRANT_REF:
0988         return gntdev_ioctl_unmap_grant_ref(priv, ptr);
0989 
0990     case IOCTL_GNTDEV_GET_OFFSET_FOR_VADDR:
0991         return gntdev_ioctl_get_offset_for_vaddr(priv, ptr);
0992 
0993     case IOCTL_GNTDEV_SET_UNMAP_NOTIFY:
0994         return gntdev_ioctl_notify(priv, ptr);
0995 
0996     case IOCTL_GNTDEV_GRANT_COPY:
0997         return gntdev_ioctl_grant_copy(priv, ptr);
0998 
0999 #ifdef CONFIG_XEN_GNTDEV_DMABUF
1000     case IOCTL_GNTDEV_DMABUF_EXP_FROM_REFS:
1001         return gntdev_ioctl_dmabuf_exp_from_refs(priv, use_ptemod, ptr);
1002 
1003     case IOCTL_GNTDEV_DMABUF_EXP_WAIT_RELEASED:
1004         return gntdev_ioctl_dmabuf_exp_wait_released(priv, ptr);
1005 
1006     case IOCTL_GNTDEV_DMABUF_IMP_TO_REFS:
1007         return gntdev_ioctl_dmabuf_imp_to_refs(priv, ptr);
1008 
1009     case IOCTL_GNTDEV_DMABUF_IMP_RELEASE:
1010         return gntdev_ioctl_dmabuf_imp_release(priv, ptr);
1011 #endif
1012 
1013     default:
1014         pr_debug("priv %p, unknown cmd %x\n", priv, cmd);
1015         return -ENOIOCTLCMD;
1016     }
1017 
1018     return 0;
1019 }
1020 
1021 static int gntdev_mmap(struct file *flip, struct vm_area_struct *vma)
1022 {
1023     struct gntdev_priv *priv = flip->private_data;
1024     int index = vma->vm_pgoff;
1025     int count = vma_pages(vma);
1026     struct gntdev_grant_map *map;
1027     int err = -EINVAL;
1028 
1029     if ((vma->vm_flags & VM_WRITE) && !(vma->vm_flags & VM_SHARED))
1030         return -EINVAL;
1031 
1032     pr_debug("map %d+%d at %lx (pgoff %lx)\n",
1033             index, count, vma->vm_start, vma->vm_pgoff);
1034 
1035     mutex_lock(&priv->lock);
1036     map = gntdev_find_map_index(priv, index, count);
1037     if (!map)
1038         goto unlock_out;
1039     if (use_ptemod && map->vma)
1040         goto unlock_out;
1041     if (atomic_read(&map->live_grants)) {
1042         err = -EAGAIN;
1043         goto unlock_out;
1044     }
1045     refcount_inc(&map->users);
1046 
1047     vma->vm_ops = &gntdev_vmops;
1048 
1049     vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP | VM_MIXEDMAP;
1050 
1051     if (use_ptemod)
1052         vma->vm_flags |= VM_DONTCOPY;
1053 
1054     vma->vm_private_data = map;
1055     if (map->flags) {
1056         if ((vma->vm_flags & VM_WRITE) &&
1057                 (map->flags & GNTMAP_readonly))
1058             goto out_unlock_put;
1059     } else {
1060         map->flags = GNTMAP_host_map;
1061         if (!(vma->vm_flags & VM_WRITE))
1062             map->flags |= GNTMAP_readonly;
1063     }
1064 
1065     if (use_ptemod) {
1066         map->vma = vma;
1067         err = mmu_interval_notifier_insert_locked(
1068             &map->notifier, vma->vm_mm, vma->vm_start,
1069             vma->vm_end - vma->vm_start, &gntdev_mmu_ops);
1070         if (err) {
1071             map->vma = NULL;
1072             goto out_unlock_put;
1073         }
1074     }
1075     mutex_unlock(&priv->lock);
1076 
1077     if (use_ptemod) {
1078         /*
1079          * gntdev takes the address of the PTE in find_grant_ptes() and
1080          * passes it to the hypervisor in gntdev_map_grant_pages(). The
1081          * purpose of the notifier is to prevent the hypervisor pointer
1082          * to the PTE from going stale.
1083          *
1084          * Since this vma's mappings can't be touched without the
1085          * mmap_lock, and we are holding it now, there is no need for
1086          * the notifier_range locking pattern.
1087          */
1088         mmu_interval_read_begin(&map->notifier);
1089 
1090         map->pages_vm_start = vma->vm_start;
1091         err = apply_to_page_range(vma->vm_mm, vma->vm_start,
1092                       vma->vm_end - vma->vm_start,
1093                       find_grant_ptes, map);
1094         if (err) {
1095             pr_warn("find_grant_ptes() failure.\n");
1096             goto out_put_map;
1097         }
1098     }
1099 
1100     err = gntdev_map_grant_pages(map);
1101     if (err)
1102         goto out_put_map;
1103 
1104     if (!use_ptemod) {
1105         err = vm_map_pages_zero(vma, map->pages, map->count);
1106         if (err)
1107             goto out_put_map;
1108     }
1109 
1110     return 0;
1111 
1112 unlock_out:
1113     mutex_unlock(&priv->lock);
1114     return err;
1115 
1116 out_unlock_put:
1117     mutex_unlock(&priv->lock);
1118 out_put_map:
1119     if (use_ptemod) {
1120         unmap_grant_pages(map, 0, map->count);
1121         if (map->vma) {
1122             mmu_interval_notifier_remove(&map->notifier);
1123             map->vma = NULL;
1124         }
1125     }
1126     gntdev_put_map(priv, map);
1127     return err;
1128 }
1129 
1130 static const struct file_operations gntdev_fops = {
1131     .owner = THIS_MODULE,
1132     .open = gntdev_open,
1133     .release = gntdev_release,
1134     .mmap = gntdev_mmap,
1135     .unlocked_ioctl = gntdev_ioctl
1136 };
1137 
1138 static struct miscdevice gntdev_miscdev = {
1139     .minor        = MISC_DYNAMIC_MINOR,
1140     .name         = "xen/gntdev",
1141     .fops         = &gntdev_fops,
1142 };
1143 
1144 /* ------------------------------------------------------------------ */
1145 
1146 static int __init gntdev_init(void)
1147 {
1148     int err;
1149 
1150     if (!xen_domain())
1151         return -ENODEV;
1152 
1153     use_ptemod = !xen_feature(XENFEAT_auto_translated_physmap);
1154 
1155     err = misc_register(&gntdev_miscdev);
1156     if (err != 0) {
1157         pr_err("Could not register gntdev device\n");
1158         return err;
1159     }
1160     return 0;
1161 }
1162 
1163 static void __exit gntdev_exit(void)
1164 {
1165     misc_deregister(&gntdev_miscdev);
1166 }
1167 
1168 module_init(gntdev_init);
1169 module_exit(gntdev_exit);
1170 
1171 /* ------------------------------------------------------------------ */