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