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