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