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