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